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/Basic/OpenMPKinds.h"
26 #include "clang/Sema/Initialization.h"
27 #include "clang/Sema/Lookup.h"
28 #include "clang/Sema/Scope.h"
29 #include "clang/Sema/ScopeInfo.h"
30 #include "clang/Sema/SemaInternal.h"
31 #include "llvm/ADT/PointerEmbeddedInt.h"
32 using namespace clang;
33 
34 //===----------------------------------------------------------------------===//
35 // Stack of data-sharing attributes for variables
36 //===----------------------------------------------------------------------===//
37 
38 static Expr *CheckMapClauseExpressionBase(
39     Sema &SemaRef, Expr *E,
40     OMPClauseMappableExprCommon::MappableExprComponentList &CurComponents,
41     OpenMPClauseKind CKind, bool NoDiagnose);
42 
43 namespace {
44 /// \brief Default data sharing attributes, which can be applied to directive.
45 enum DefaultDataSharingAttributes {
46   DSA_unspecified = 0, /// \brief Data sharing attribute not specified.
47   DSA_none = 1 << 0,   /// \brief Default data sharing attribute 'none'.
48   DSA_shared = 1 << 1, /// \brief Default data sharing attribute 'shared'.
49 };
50 
51 /// Attributes of the defaultmap clause.
52 enum DefaultMapAttributes {
53   DMA_unspecified,   /// Default mapping is not specified.
54   DMA_tofrom_scalar, /// Default mapping is 'tofrom:scalar'.
55 };
56 
57 /// \brief Stack for tracking declarations used in OpenMP directives and
58 /// clauses and their data-sharing attributes.
59 class DSAStackTy final {
60 public:
61   struct DSAVarData final {
62     OpenMPDirectiveKind DKind = OMPD_unknown;
63     OpenMPClauseKind CKind = OMPC_unknown;
64     Expr *RefExpr = nullptr;
65     DeclRefExpr *PrivateCopy = nullptr;
66     SourceLocation ImplicitDSALoc;
67     DSAVarData() = default;
68     DSAVarData(OpenMPDirectiveKind DKind, OpenMPClauseKind CKind, Expr *RefExpr,
69                DeclRefExpr *PrivateCopy, SourceLocation ImplicitDSALoc)
70         : DKind(DKind), CKind(CKind), RefExpr(RefExpr),
71           PrivateCopy(PrivateCopy), ImplicitDSALoc(ImplicitDSALoc) {}
72   };
73   typedef llvm::SmallVector<std::pair<Expr *, OverloadedOperatorKind>, 4>
74       OperatorOffsetTy;
75 
76 private:
77   struct DSAInfo final {
78     OpenMPClauseKind Attributes = OMPC_unknown;
79     /// Pointer to a reference expression and a flag which shows that the
80     /// variable is marked as lastprivate(true) or not (false).
81     llvm::PointerIntPair<Expr *, 1, bool> RefExpr;
82     DeclRefExpr *PrivateCopy = nullptr;
83   };
84   typedef llvm::DenseMap<ValueDecl *, DSAInfo> DeclSAMapTy;
85   typedef llvm::DenseMap<ValueDecl *, Expr *> AlignedMapTy;
86   typedef std::pair<unsigned, VarDecl *> LCDeclInfo;
87   typedef llvm::DenseMap<ValueDecl *, LCDeclInfo> LoopControlVariablesMapTy;
88   /// Struct that associates a component with the clause kind where they are
89   /// found.
90   struct MappedExprComponentTy {
91     OMPClauseMappableExprCommon::MappableExprComponentLists Components;
92     OpenMPClauseKind Kind = OMPC_unknown;
93   };
94   typedef llvm::DenseMap<ValueDecl *, MappedExprComponentTy>
95       MappedExprComponentsTy;
96   typedef llvm::StringMap<std::pair<OMPCriticalDirective *, llvm::APSInt>>
97       CriticalsWithHintsTy;
98   typedef llvm::DenseMap<OMPDependClause *, OperatorOffsetTy>
99       DoacrossDependMapTy;
100   struct ReductionData {
101     typedef llvm::PointerEmbeddedInt<BinaryOperatorKind, 16> BOKPtrType;
102     SourceRange ReductionRange;
103     llvm::PointerUnion<const Expr *, BOKPtrType> ReductionOp;
104     ReductionData() = default;
105     void set(BinaryOperatorKind BO, SourceRange RR) {
106       ReductionRange = RR;
107       ReductionOp = BO;
108     }
109     void set(const Expr *RefExpr, SourceRange RR) {
110       ReductionRange = RR;
111       ReductionOp = RefExpr;
112     }
113   };
114   typedef llvm::DenseMap<ValueDecl *, ReductionData> DeclReductionMapTy;
115 
116   struct SharingMapTy final {
117     DeclSAMapTy SharingMap;
118     DeclReductionMapTy ReductionMap;
119     AlignedMapTy AlignedMap;
120     MappedExprComponentsTy MappedExprComponents;
121     LoopControlVariablesMapTy LCVMap;
122     DefaultDataSharingAttributes DefaultAttr = DSA_unspecified;
123     SourceLocation DefaultAttrLoc;
124     DefaultMapAttributes DefaultMapAttr = DMA_unspecified;
125     SourceLocation DefaultMapAttrLoc;
126     OpenMPDirectiveKind Directive = OMPD_unknown;
127     DeclarationNameInfo DirectiveName;
128     Scope *CurScope = nullptr;
129     SourceLocation ConstructLoc;
130     /// Set of 'depend' clauses with 'sink|source' dependence kind. Required to
131     /// get the data (loop counters etc.) about enclosing loop-based construct.
132     /// This data is required during codegen.
133     DoacrossDependMapTy DoacrossDepends;
134     /// \brief first argument (Expr *) contains optional argument of the
135     /// 'ordered' clause, the second one is true if the regions has 'ordered'
136     /// clause, false otherwise.
137     llvm::PointerIntPair<Expr *, 1, bool> OrderedRegion;
138     bool NowaitRegion = false;
139     bool CancelRegion = false;
140     unsigned AssociatedLoops = 1;
141     SourceLocation InnerTeamsRegionLoc;
142     /// Reference to the taskgroup task_reduction reference expression.
143     Expr *TaskgroupReductionRef = nullptr;
144     SharingMapTy(OpenMPDirectiveKind DKind, DeclarationNameInfo Name,
145                  Scope *CurScope, SourceLocation Loc)
146         : Directive(DKind), DirectiveName(Name), CurScope(CurScope),
147           ConstructLoc(Loc) {}
148     SharingMapTy() = default;
149   };
150 
151   typedef SmallVector<SharingMapTy, 4> StackTy;
152 
153   /// \brief Stack of used declaration and their data-sharing attributes.
154   DeclSAMapTy Threadprivates;
155   const FunctionScopeInfo *CurrentNonCapturingFunctionScope = nullptr;
156   SmallVector<std::pair<StackTy, const FunctionScopeInfo *>, 4> Stack;
157   /// \brief true, if check for DSA must be from parent directive, false, if
158   /// from current directive.
159   OpenMPClauseKind ClauseKindMode = OMPC_unknown;
160   Sema &SemaRef;
161   bool ForceCapturing = false;
162   CriticalsWithHintsTy Criticals;
163 
164   typedef SmallVector<SharingMapTy, 8>::reverse_iterator reverse_iterator;
165 
166   DSAVarData getDSA(StackTy::reverse_iterator &Iter, ValueDecl *D);
167 
168   /// \brief Checks if the variable is a local for OpenMP region.
169   bool isOpenMPLocal(VarDecl *D, StackTy::reverse_iterator Iter);
170 
171   bool isStackEmpty() const {
172     return Stack.empty() ||
173            Stack.back().second != CurrentNonCapturingFunctionScope ||
174            Stack.back().first.empty();
175   }
176 
177 public:
178   explicit DSAStackTy(Sema &S) : SemaRef(S) {}
179 
180   bool isClauseParsingMode() const { return ClauseKindMode != OMPC_unknown; }
181   OpenMPClauseKind getClauseParsingMode() const {
182     assert(isClauseParsingMode() && "Must be in clause parsing mode.");
183     return ClauseKindMode;
184   }
185   void setClauseParsingMode(OpenMPClauseKind K) { ClauseKindMode = K; }
186 
187   bool isForceVarCapturing() const { return ForceCapturing; }
188   void setForceVarCapturing(bool V) { ForceCapturing = V; }
189 
190   void push(OpenMPDirectiveKind DKind, const DeclarationNameInfo &DirName,
191             Scope *CurScope, SourceLocation Loc) {
192     if (Stack.empty() ||
193         Stack.back().second != CurrentNonCapturingFunctionScope)
194       Stack.emplace_back(StackTy(), CurrentNonCapturingFunctionScope);
195     Stack.back().first.emplace_back(DKind, DirName, CurScope, Loc);
196     Stack.back().first.back().DefaultAttrLoc = Loc;
197   }
198 
199   void pop() {
200     assert(!Stack.back().first.empty() &&
201            "Data-sharing attributes stack is empty!");
202     Stack.back().first.pop_back();
203   }
204 
205   /// Start new OpenMP region stack in new non-capturing function.
206   void pushFunction() {
207     const FunctionScopeInfo *CurFnScope = SemaRef.getCurFunction();
208     assert(!isa<CapturingScopeInfo>(CurFnScope));
209     CurrentNonCapturingFunctionScope = CurFnScope;
210   }
211   /// Pop region stack for non-capturing function.
212   void popFunction(const FunctionScopeInfo *OldFSI) {
213     if (!Stack.empty() && Stack.back().second == OldFSI) {
214       assert(Stack.back().first.empty());
215       Stack.pop_back();
216     }
217     CurrentNonCapturingFunctionScope = nullptr;
218     for (const FunctionScopeInfo *FSI : llvm::reverse(SemaRef.FunctionScopes)) {
219       if (!isa<CapturingScopeInfo>(FSI)) {
220         CurrentNonCapturingFunctionScope = FSI;
221         break;
222       }
223     }
224   }
225 
226   void addCriticalWithHint(OMPCriticalDirective *D, llvm::APSInt Hint) {
227     Criticals[D->getDirectiveName().getAsString()] = std::make_pair(D, Hint);
228   }
229   const std::pair<OMPCriticalDirective *, llvm::APSInt>
230   getCriticalWithHint(const DeclarationNameInfo &Name) const {
231     auto I = Criticals.find(Name.getAsString());
232     if (I != Criticals.end())
233       return I->second;
234     return std::make_pair(nullptr, llvm::APSInt());
235   }
236   /// \brief If 'aligned' declaration for given variable \a D was not seen yet,
237   /// add it and return NULL; otherwise return previous occurrence's expression
238   /// for diagnostics.
239   Expr *addUniqueAligned(ValueDecl *D, Expr *NewDE);
240 
241   /// \brief Register specified variable as loop control variable.
242   void addLoopControlVariable(ValueDecl *D, VarDecl *Capture);
243   /// \brief Check if the specified variable is a loop control variable for
244   /// current region.
245   /// \return The index of the loop control variable in the list of associated
246   /// for-loops (from outer to inner).
247   LCDeclInfo isLoopControlVariable(ValueDecl *D);
248   /// \brief Check if the specified variable is a loop control variable for
249   /// parent region.
250   /// \return The index of the loop control variable in the list of associated
251   /// for-loops (from outer to inner).
252   LCDeclInfo isParentLoopControlVariable(ValueDecl *D);
253   /// \brief Get the loop control variable for the I-th loop (or nullptr) in
254   /// parent directive.
255   ValueDecl *getParentLoopControlVariable(unsigned I);
256 
257   /// \brief Adds explicit data sharing attribute to the specified declaration.
258   void addDSA(ValueDecl *D, Expr *E, OpenMPClauseKind A,
259               DeclRefExpr *PrivateCopy = nullptr);
260 
261   /// Adds additional information for the reduction items with the reduction id
262   /// represented as an operator.
263   void addTaskgroupReductionData(ValueDecl *D, SourceRange SR,
264                                  BinaryOperatorKind BOK);
265   /// Adds additional information for the reduction items with the reduction id
266   /// represented as reduction identifier.
267   void addTaskgroupReductionData(ValueDecl *D, SourceRange SR,
268                                  const Expr *ReductionRef);
269   /// Returns the location and reduction operation from the innermost parent
270   /// region for the given \p D.
271   DSAVarData getTopMostTaskgroupReductionData(ValueDecl *D, SourceRange &SR,
272                                               BinaryOperatorKind &BOK,
273                                               Expr *&TaskgroupDescriptor);
274   /// Returns the location and reduction operation from the innermost parent
275   /// region for the given \p D.
276   DSAVarData getTopMostTaskgroupReductionData(ValueDecl *D, SourceRange &SR,
277                                               const Expr *&ReductionRef,
278                                               Expr *&TaskgroupDescriptor);
279   /// Return reduction reference expression for the current taskgroup.
280   Expr *getTaskgroupReductionRef() const {
281     assert(Stack.back().first.back().Directive == OMPD_taskgroup &&
282            "taskgroup reference expression requested for non taskgroup "
283            "directive.");
284     return Stack.back().first.back().TaskgroupReductionRef;
285   }
286   /// Checks if the given \p VD declaration is actually a taskgroup reduction
287   /// descriptor variable at the \p Level of OpenMP regions.
288   bool isTaskgroupReductionRef(ValueDecl *VD, unsigned Level) const {
289     return Stack.back().first[Level].TaskgroupReductionRef &&
290            cast<DeclRefExpr>(Stack.back().first[Level].TaskgroupReductionRef)
291                    ->getDecl() == VD;
292   }
293 
294   /// \brief Returns data sharing attributes from top of the stack for the
295   /// specified declaration.
296   DSAVarData getTopDSA(ValueDecl *D, bool FromParent);
297   /// \brief Returns data-sharing attributes for the specified declaration.
298   DSAVarData getImplicitDSA(ValueDecl *D, bool FromParent);
299   /// \brief Checks if the specified variables has data-sharing attributes which
300   /// match specified \a CPred predicate in any directive which matches \a DPred
301   /// predicate.
302   DSAVarData hasDSA(ValueDecl *D,
303                     const llvm::function_ref<bool(OpenMPClauseKind)> &CPred,
304                     const llvm::function_ref<bool(OpenMPDirectiveKind)> &DPred,
305                     bool FromParent);
306   /// \brief Checks if the specified variables has data-sharing attributes which
307   /// match specified \a CPred predicate in any innermost directive which
308   /// matches \a DPred predicate.
309   DSAVarData
310   hasInnermostDSA(ValueDecl *D,
311                   const llvm::function_ref<bool(OpenMPClauseKind)> &CPred,
312                   const llvm::function_ref<bool(OpenMPDirectiveKind)> &DPred,
313                   bool FromParent);
314   /// \brief Checks if the specified variables has explicit data-sharing
315   /// attributes which match specified \a CPred predicate at the specified
316   /// OpenMP region.
317   bool hasExplicitDSA(ValueDecl *D,
318                       const llvm::function_ref<bool(OpenMPClauseKind)> &CPred,
319                       unsigned Level, bool NotLastprivate = false);
320 
321   /// \brief Returns true if the directive at level \Level matches in the
322   /// specified \a DPred predicate.
323   bool hasExplicitDirective(
324       const llvm::function_ref<bool(OpenMPDirectiveKind)> &DPred,
325       unsigned Level);
326 
327   /// \brief Finds a directive which matches specified \a DPred predicate.
328   bool hasDirective(const llvm::function_ref<bool(OpenMPDirectiveKind,
329                                                   const DeclarationNameInfo &,
330                                                   SourceLocation)> &DPred,
331                     bool FromParent);
332 
333   /// \brief Returns currently analyzed directive.
334   OpenMPDirectiveKind getCurrentDirective() const {
335     return isStackEmpty() ? OMPD_unknown : Stack.back().first.back().Directive;
336   }
337   /// \brief Returns directive kind at specified level.
338   OpenMPDirectiveKind getDirective(unsigned Level) const {
339     assert(!isStackEmpty() && "No directive at specified level.");
340     return Stack.back().first[Level].Directive;
341   }
342   /// \brief Returns parent directive.
343   OpenMPDirectiveKind getParentDirective() const {
344     if (isStackEmpty() || Stack.back().first.size() == 1)
345       return OMPD_unknown;
346     return std::next(Stack.back().first.rbegin())->Directive;
347   }
348 
349   /// \brief Set default data sharing attribute to none.
350   void setDefaultDSANone(SourceLocation Loc) {
351     assert(!isStackEmpty());
352     Stack.back().first.back().DefaultAttr = DSA_none;
353     Stack.back().first.back().DefaultAttrLoc = Loc;
354   }
355   /// \brief Set default data sharing attribute to shared.
356   void setDefaultDSAShared(SourceLocation Loc) {
357     assert(!isStackEmpty());
358     Stack.back().first.back().DefaultAttr = DSA_shared;
359     Stack.back().first.back().DefaultAttrLoc = Loc;
360   }
361   /// Set default data mapping attribute to 'tofrom:scalar'.
362   void setDefaultDMAToFromScalar(SourceLocation Loc) {
363     assert(!isStackEmpty());
364     Stack.back().first.back().DefaultMapAttr = DMA_tofrom_scalar;
365     Stack.back().first.back().DefaultMapAttrLoc = Loc;
366   }
367 
368   DefaultDataSharingAttributes getDefaultDSA() const {
369     return isStackEmpty() ? DSA_unspecified
370                           : Stack.back().first.back().DefaultAttr;
371   }
372   SourceLocation getDefaultDSALocation() const {
373     return isStackEmpty() ? SourceLocation()
374                           : Stack.back().first.back().DefaultAttrLoc;
375   }
376   DefaultMapAttributes getDefaultDMA() const {
377     return isStackEmpty() ? DMA_unspecified
378                           : Stack.back().first.back().DefaultMapAttr;
379   }
380   DefaultMapAttributes getDefaultDMAAtLevel(unsigned Level) const {
381     return Stack.back().first[Level].DefaultMapAttr;
382   }
383   SourceLocation getDefaultDMALocation() const {
384     return isStackEmpty() ? SourceLocation()
385                           : Stack.back().first.back().DefaultMapAttrLoc;
386   }
387 
388   /// \brief Checks if the specified variable is a threadprivate.
389   bool isThreadPrivate(VarDecl *D) {
390     DSAVarData DVar = getTopDSA(D, false);
391     return isOpenMPThreadPrivate(DVar.CKind);
392   }
393 
394   /// \brief Marks current region as ordered (it has an 'ordered' clause).
395   void setOrderedRegion(bool IsOrdered, Expr *Param) {
396     assert(!isStackEmpty());
397     Stack.back().first.back().OrderedRegion.setInt(IsOrdered);
398     Stack.back().first.back().OrderedRegion.setPointer(Param);
399   }
400   /// \brief Returns true, if parent region is ordered (has associated
401   /// 'ordered' clause), false - otherwise.
402   bool isParentOrderedRegion() const {
403     if (isStackEmpty() || Stack.back().first.size() == 1)
404       return false;
405     return std::next(Stack.back().first.rbegin())->OrderedRegion.getInt();
406   }
407   /// \brief Returns optional parameter for the ordered region.
408   Expr *getParentOrderedRegionParam() const {
409     if (isStackEmpty() || Stack.back().first.size() == 1)
410       return nullptr;
411     return std::next(Stack.back().first.rbegin())->OrderedRegion.getPointer();
412   }
413   /// \brief Marks current region as nowait (it has a 'nowait' clause).
414   void setNowaitRegion(bool IsNowait = true) {
415     assert(!isStackEmpty());
416     Stack.back().first.back().NowaitRegion = IsNowait;
417   }
418   /// \brief Returns true, if parent region is nowait (has associated
419   /// 'nowait' clause), false - otherwise.
420   bool isParentNowaitRegion() const {
421     if (isStackEmpty() || Stack.back().first.size() == 1)
422       return false;
423     return std::next(Stack.back().first.rbegin())->NowaitRegion;
424   }
425   /// \brief Marks parent region as cancel region.
426   void setParentCancelRegion(bool Cancel = true) {
427     if (!isStackEmpty() && Stack.back().first.size() > 1) {
428       auto &StackElemRef = *std::next(Stack.back().first.rbegin());
429       StackElemRef.CancelRegion |= StackElemRef.CancelRegion || Cancel;
430     }
431   }
432   /// \brief Return true if current region has inner cancel construct.
433   bool isCancelRegion() const {
434     return isStackEmpty() ? false : Stack.back().first.back().CancelRegion;
435   }
436 
437   /// \brief Set collapse value for the region.
438   void setAssociatedLoops(unsigned Val) {
439     assert(!isStackEmpty());
440     Stack.back().first.back().AssociatedLoops = Val;
441   }
442   /// \brief Return collapse value for region.
443   unsigned getAssociatedLoops() const {
444     return isStackEmpty() ? 0 : Stack.back().first.back().AssociatedLoops;
445   }
446 
447   /// \brief Marks current target region as one with closely nested teams
448   /// region.
449   void setParentTeamsRegionLoc(SourceLocation TeamsRegionLoc) {
450     if (!isStackEmpty() && Stack.back().first.size() > 1) {
451       std::next(Stack.back().first.rbegin())->InnerTeamsRegionLoc =
452           TeamsRegionLoc;
453     }
454   }
455   /// \brief Returns true, if current region has closely nested teams region.
456   bool hasInnerTeamsRegion() const {
457     return getInnerTeamsRegionLoc().isValid();
458   }
459   /// \brief Returns location of the nested teams region (if any).
460   SourceLocation getInnerTeamsRegionLoc() const {
461     return isStackEmpty() ? SourceLocation()
462                           : Stack.back().first.back().InnerTeamsRegionLoc;
463   }
464 
465   Scope *getCurScope() const {
466     return isStackEmpty() ? nullptr : Stack.back().first.back().CurScope;
467   }
468   Scope *getCurScope() {
469     return isStackEmpty() ? nullptr : Stack.back().first.back().CurScope;
470   }
471   SourceLocation getConstructLoc() {
472     return isStackEmpty() ? SourceLocation()
473                           : Stack.back().first.back().ConstructLoc;
474   }
475 
476   /// Do the check specified in \a Check to all component lists and return true
477   /// if any issue is found.
478   bool checkMappableExprComponentListsForDecl(
479       ValueDecl *VD, bool CurrentRegionOnly,
480       const llvm::function_ref<
481           bool(OMPClauseMappableExprCommon::MappableExprComponentListRef,
482                OpenMPClauseKind)> &Check) {
483     if (isStackEmpty())
484       return false;
485     auto SI = Stack.back().first.rbegin();
486     auto SE = Stack.back().first.rend();
487 
488     if (SI == SE)
489       return false;
490 
491     if (CurrentRegionOnly) {
492       SE = std::next(SI);
493     } else {
494       ++SI;
495     }
496 
497     for (; SI != SE; ++SI) {
498       auto MI = SI->MappedExprComponents.find(VD);
499       if (MI != SI->MappedExprComponents.end())
500         for (auto &L : MI->second.Components)
501           if (Check(L, MI->second.Kind))
502             return true;
503     }
504     return false;
505   }
506 
507   /// Do the check specified in \a Check to all component lists at a given level
508   /// and return true if any issue is found.
509   bool checkMappableExprComponentListsForDeclAtLevel(
510       ValueDecl *VD, unsigned Level,
511       const llvm::function_ref<
512           bool(OMPClauseMappableExprCommon::MappableExprComponentListRef,
513                OpenMPClauseKind)> &Check) {
514     if (isStackEmpty())
515       return false;
516 
517     auto StartI = Stack.back().first.begin();
518     auto EndI = Stack.back().first.end();
519     if (std::distance(StartI, EndI) <= (int)Level)
520       return false;
521     std::advance(StartI, Level);
522 
523     auto MI = StartI->MappedExprComponents.find(VD);
524     if (MI != StartI->MappedExprComponents.end())
525       for (auto &L : MI->second.Components)
526         if (Check(L, MI->second.Kind))
527           return true;
528     return false;
529   }
530 
531   /// Create a new mappable expression component list associated with a given
532   /// declaration and initialize it with the provided list of components.
533   void addMappableExpressionComponents(
534       ValueDecl *VD,
535       OMPClauseMappableExprCommon::MappableExprComponentListRef Components,
536       OpenMPClauseKind WhereFoundClauseKind) {
537     assert(!isStackEmpty() &&
538            "Not expecting to retrieve components from a empty stack!");
539     auto &MEC = Stack.back().first.back().MappedExprComponents[VD];
540     // Create new entry and append the new components there.
541     MEC.Components.resize(MEC.Components.size() + 1);
542     MEC.Components.back().append(Components.begin(), Components.end());
543     MEC.Kind = WhereFoundClauseKind;
544   }
545 
546   unsigned getNestingLevel() const {
547     assert(!isStackEmpty());
548     return Stack.back().first.size() - 1;
549   }
550   void addDoacrossDependClause(OMPDependClause *C, OperatorOffsetTy &OpsOffs) {
551     assert(!isStackEmpty() && Stack.back().first.size() > 1);
552     auto &StackElem = *std::next(Stack.back().first.rbegin());
553     assert(isOpenMPWorksharingDirective(StackElem.Directive));
554     StackElem.DoacrossDepends.insert({C, OpsOffs});
555   }
556   llvm::iterator_range<DoacrossDependMapTy::const_iterator>
557   getDoacrossDependClauses() const {
558     assert(!isStackEmpty());
559     auto &StackElem = Stack.back().first.back();
560     if (isOpenMPWorksharingDirective(StackElem.Directive)) {
561       auto &Ref = StackElem.DoacrossDepends;
562       return llvm::make_range(Ref.begin(), Ref.end());
563     }
564     return llvm::make_range(StackElem.DoacrossDepends.end(),
565                             StackElem.DoacrossDepends.end());
566   }
567 };
568 bool isParallelOrTaskRegion(OpenMPDirectiveKind DKind) {
569   return isOpenMPParallelDirective(DKind) || isOpenMPTaskingDirective(DKind) ||
570          isOpenMPTeamsDirective(DKind) || DKind == OMPD_unknown;
571 }
572 } // namespace
573 
574 static Expr *getExprAsWritten(Expr *E) {
575   if (auto *ExprTemp = dyn_cast<ExprWithCleanups>(E))
576     E = ExprTemp->getSubExpr();
577 
578   if (auto *MTE = dyn_cast<MaterializeTemporaryExpr>(E))
579     E = MTE->GetTemporaryExpr();
580 
581   while (auto *Binder = dyn_cast<CXXBindTemporaryExpr>(E))
582     E = Binder->getSubExpr();
583 
584   if (auto *ICE = dyn_cast<ImplicitCastExpr>(E))
585     E = ICE->getSubExprAsWritten();
586   return E->IgnoreParens();
587 }
588 
589 static ValueDecl *getCanonicalDecl(ValueDecl *D) {
590   if (auto *CED = dyn_cast<OMPCapturedExprDecl>(D))
591     if (auto *ME = dyn_cast<MemberExpr>(getExprAsWritten(CED->getInit())))
592       D = ME->getMemberDecl();
593   auto *VD = dyn_cast<VarDecl>(D);
594   auto *FD = dyn_cast<FieldDecl>(D);
595   if (VD != nullptr) {
596     VD = VD->getCanonicalDecl();
597     D = VD;
598   } else {
599     assert(FD);
600     FD = FD->getCanonicalDecl();
601     D = FD;
602   }
603   return D;
604 }
605 
606 DSAStackTy::DSAVarData DSAStackTy::getDSA(StackTy::reverse_iterator &Iter,
607                                           ValueDecl *D) {
608   D = getCanonicalDecl(D);
609   auto *VD = dyn_cast<VarDecl>(D);
610   auto *FD = dyn_cast<FieldDecl>(D);
611   DSAVarData DVar;
612   if (isStackEmpty() || Iter == Stack.back().first.rend()) {
613     // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
614     // in a region but not in construct]
615     //  File-scope or namespace-scope variables referenced in called routines
616     //  in the region are shared unless they appear in a threadprivate
617     //  directive.
618     if (VD && !VD->isFunctionOrMethodVarDecl() && !isa<ParmVarDecl>(D))
619       DVar.CKind = OMPC_shared;
620 
621     // OpenMP [2.9.1.2, Data-sharing Attribute Rules for Variables Referenced
622     // in a region but not in construct]
623     //  Variables with static storage duration that are declared in called
624     //  routines in the region are shared.
625     if (VD && VD->hasGlobalStorage())
626       DVar.CKind = OMPC_shared;
627 
628     // Non-static data members are shared by default.
629     if (FD)
630       DVar.CKind = OMPC_shared;
631 
632     return DVar;
633   }
634 
635   // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
636   // in a Construct, C/C++, predetermined, p.1]
637   // Variables with automatic storage duration that are declared in a scope
638   // inside the construct are private.
639   if (VD && isOpenMPLocal(VD, Iter) && VD->isLocalVarDecl() &&
640       (VD->getStorageClass() == SC_Auto || VD->getStorageClass() == SC_None)) {
641     DVar.CKind = OMPC_private;
642     return DVar;
643   }
644 
645   DVar.DKind = Iter->Directive;
646   // Explicitly specified attributes and local variables with predetermined
647   // attributes.
648   if (Iter->SharingMap.count(D)) {
649     DVar.RefExpr = Iter->SharingMap[D].RefExpr.getPointer();
650     DVar.PrivateCopy = Iter->SharingMap[D].PrivateCopy;
651     DVar.CKind = Iter->SharingMap[D].Attributes;
652     DVar.ImplicitDSALoc = Iter->DefaultAttrLoc;
653     return DVar;
654   }
655 
656   // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
657   // in a Construct, C/C++, implicitly determined, p.1]
658   //  In a parallel or task construct, the data-sharing attributes of these
659   //  variables are determined by the default clause, if present.
660   switch (Iter->DefaultAttr) {
661   case DSA_shared:
662     DVar.CKind = OMPC_shared;
663     DVar.ImplicitDSALoc = Iter->DefaultAttrLoc;
664     return DVar;
665   case DSA_none:
666     return DVar;
667   case DSA_unspecified:
668     // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
669     // in a Construct, implicitly determined, p.2]
670     //  In a parallel construct, if no default clause is present, these
671     //  variables are shared.
672     DVar.ImplicitDSALoc = Iter->DefaultAttrLoc;
673     if (isOpenMPParallelDirective(DVar.DKind) ||
674         isOpenMPTeamsDirective(DVar.DKind)) {
675       DVar.CKind = OMPC_shared;
676       return DVar;
677     }
678 
679     // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
680     // in a Construct, implicitly determined, p.4]
681     //  In a task construct, if no default clause is present, a variable that in
682     //  the enclosing context is determined to be shared by all implicit tasks
683     //  bound to the current team is shared.
684     if (isOpenMPTaskingDirective(DVar.DKind)) {
685       DSAVarData DVarTemp;
686       auto I = Iter, E = Stack.back().first.rend();
687       do {
688         ++I;
689         // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables
690         // Referenced in a Construct, implicitly determined, p.6]
691         //  In a task construct, if no default clause is present, a variable
692         //  whose data-sharing attribute is not determined by the rules above is
693         //  firstprivate.
694         DVarTemp = getDSA(I, D);
695         if (DVarTemp.CKind != OMPC_shared) {
696           DVar.RefExpr = nullptr;
697           DVar.CKind = OMPC_firstprivate;
698           return DVar;
699         }
700       } while (I != E && !isParallelOrTaskRegion(I->Directive));
701       DVar.CKind =
702           (DVarTemp.CKind == OMPC_unknown) ? OMPC_firstprivate : OMPC_shared;
703       return DVar;
704     }
705   }
706   // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
707   // in a Construct, implicitly determined, p.3]
708   //  For constructs other than task, if no default clause is present, these
709   //  variables inherit their data-sharing attributes from the enclosing
710   //  context.
711   return getDSA(++Iter, D);
712 }
713 
714 Expr *DSAStackTy::addUniqueAligned(ValueDecl *D, Expr *NewDE) {
715   assert(!isStackEmpty() && "Data sharing attributes stack is empty");
716   D = getCanonicalDecl(D);
717   auto &StackElem = Stack.back().first.back();
718   auto It = StackElem.AlignedMap.find(D);
719   if (It == StackElem.AlignedMap.end()) {
720     assert(NewDE && "Unexpected nullptr expr to be added into aligned map");
721     StackElem.AlignedMap[D] = NewDE;
722     return nullptr;
723   } else {
724     assert(It->second && "Unexpected nullptr expr in the aligned map");
725     return It->second;
726   }
727   return nullptr;
728 }
729 
730 void DSAStackTy::addLoopControlVariable(ValueDecl *D, VarDecl *Capture) {
731   assert(!isStackEmpty() && "Data-sharing attributes stack is empty");
732   D = getCanonicalDecl(D);
733   auto &StackElem = Stack.back().first.back();
734   StackElem.LCVMap.insert(
735       {D, LCDeclInfo(StackElem.LCVMap.size() + 1, Capture)});
736 }
737 
738 DSAStackTy::LCDeclInfo DSAStackTy::isLoopControlVariable(ValueDecl *D) {
739   assert(!isStackEmpty() && "Data-sharing attributes stack is empty");
740   D = getCanonicalDecl(D);
741   auto &StackElem = Stack.back().first.back();
742   auto It = StackElem.LCVMap.find(D);
743   if (It != StackElem.LCVMap.end())
744     return It->second;
745   return {0, nullptr};
746 }
747 
748 DSAStackTy::LCDeclInfo DSAStackTy::isParentLoopControlVariable(ValueDecl *D) {
749   assert(!isStackEmpty() && Stack.back().first.size() > 1 &&
750          "Data-sharing attributes stack is empty");
751   D = getCanonicalDecl(D);
752   auto &StackElem = *std::next(Stack.back().first.rbegin());
753   auto It = StackElem.LCVMap.find(D);
754   if (It != StackElem.LCVMap.end())
755     return It->second;
756   return {0, nullptr};
757 }
758 
759 ValueDecl *DSAStackTy::getParentLoopControlVariable(unsigned I) {
760   assert(!isStackEmpty() && Stack.back().first.size() > 1 &&
761          "Data-sharing attributes stack is empty");
762   auto &StackElem = *std::next(Stack.back().first.rbegin());
763   if (StackElem.LCVMap.size() < I)
764     return nullptr;
765   for (auto &Pair : StackElem.LCVMap)
766     if (Pair.second.first == I)
767       return Pair.first;
768   return nullptr;
769 }
770 
771 void DSAStackTy::addDSA(ValueDecl *D, Expr *E, OpenMPClauseKind A,
772                         DeclRefExpr *PrivateCopy) {
773   D = getCanonicalDecl(D);
774   if (A == OMPC_threadprivate) {
775     auto &Data = Threadprivates[D];
776     Data.Attributes = A;
777     Data.RefExpr.setPointer(E);
778     Data.PrivateCopy = nullptr;
779   } else {
780     assert(!isStackEmpty() && "Data-sharing attributes stack is empty");
781     auto &Data = Stack.back().first.back().SharingMap[D];
782     assert(Data.Attributes == OMPC_unknown || (A == Data.Attributes) ||
783            (A == OMPC_firstprivate && Data.Attributes == OMPC_lastprivate) ||
784            (A == OMPC_lastprivate && Data.Attributes == OMPC_firstprivate) ||
785            (isLoopControlVariable(D).first && A == OMPC_private));
786     if (A == OMPC_lastprivate && Data.Attributes == OMPC_firstprivate) {
787       Data.RefExpr.setInt(/*IntVal=*/true);
788       return;
789     }
790     const bool IsLastprivate =
791         A == OMPC_lastprivate || Data.Attributes == OMPC_lastprivate;
792     Data.Attributes = A;
793     Data.RefExpr.setPointerAndInt(E, IsLastprivate);
794     Data.PrivateCopy = PrivateCopy;
795     if (PrivateCopy) {
796       auto &Data = Stack.back().first.back().SharingMap[PrivateCopy->getDecl()];
797       Data.Attributes = A;
798       Data.RefExpr.setPointerAndInt(PrivateCopy, IsLastprivate);
799       Data.PrivateCopy = nullptr;
800     }
801   }
802 }
803 
804 /// \brief Build a variable declaration for OpenMP loop iteration variable.
805 static VarDecl *buildVarDecl(Sema &SemaRef, SourceLocation Loc, QualType Type,
806                              StringRef Name, const AttrVec *Attrs = nullptr) {
807   DeclContext *DC = SemaRef.CurContext;
808   IdentifierInfo *II = &SemaRef.PP.getIdentifierTable().get(Name);
809   TypeSourceInfo *TInfo = SemaRef.Context.getTrivialTypeSourceInfo(Type, Loc);
810   VarDecl *Decl =
811       VarDecl::Create(SemaRef.Context, DC, Loc, Loc, II, Type, TInfo, SC_None);
812   if (Attrs) {
813     for (specific_attr_iterator<AlignedAttr> I(Attrs->begin()), E(Attrs->end());
814          I != E; ++I)
815       Decl->addAttr(*I);
816   }
817   Decl->setImplicit();
818   return Decl;
819 }
820 
821 static DeclRefExpr *buildDeclRefExpr(Sema &S, VarDecl *D, QualType Ty,
822                                      SourceLocation Loc,
823                                      bool RefersToCapture = false) {
824   D->setReferenced();
825   D->markUsed(S.Context);
826   return DeclRefExpr::Create(S.getASTContext(), NestedNameSpecifierLoc(),
827                              SourceLocation(), D, RefersToCapture, Loc, Ty,
828                              VK_LValue);
829 }
830 
831 void DSAStackTy::addTaskgroupReductionData(ValueDecl *D, SourceRange SR,
832                                            BinaryOperatorKind BOK) {
833   D = getCanonicalDecl(D);
834   assert(!isStackEmpty() && "Data-sharing attributes stack is empty");
835   assert(
836       Stack.back().first.back().SharingMap[D].Attributes == OMPC_reduction &&
837       "Additional reduction info may be specified only for reduction items.");
838   auto &ReductionData = Stack.back().first.back().ReductionMap[D];
839   assert(ReductionData.ReductionRange.isInvalid() &&
840          Stack.back().first.back().Directive == OMPD_taskgroup &&
841          "Additional reduction info may be specified only once for reduction "
842          "items.");
843   ReductionData.set(BOK, SR);
844   Expr *&TaskgroupReductionRef =
845       Stack.back().first.back().TaskgroupReductionRef;
846   if (!TaskgroupReductionRef) {
847     auto *VD = buildVarDecl(SemaRef, SR.getBegin(),
848                             SemaRef.Context.VoidPtrTy, ".task_red.");
849     TaskgroupReductionRef =
850         buildDeclRefExpr(SemaRef, VD, SemaRef.Context.VoidPtrTy, SR.getBegin());
851   }
852 }
853 
854 void DSAStackTy::addTaskgroupReductionData(ValueDecl *D, SourceRange SR,
855                                            const Expr *ReductionRef) {
856   D = getCanonicalDecl(D);
857   assert(!isStackEmpty() && "Data-sharing attributes stack is empty");
858   assert(
859       Stack.back().first.back().SharingMap[D].Attributes == OMPC_reduction &&
860       "Additional reduction info may be specified only for reduction items.");
861   auto &ReductionData = Stack.back().first.back().ReductionMap[D];
862   assert(ReductionData.ReductionRange.isInvalid() &&
863          Stack.back().first.back().Directive == OMPD_taskgroup &&
864          "Additional reduction info may be specified only once for reduction "
865          "items.");
866   ReductionData.set(ReductionRef, SR);
867   Expr *&TaskgroupReductionRef =
868       Stack.back().first.back().TaskgroupReductionRef;
869   if (!TaskgroupReductionRef) {
870     auto *VD = buildVarDecl(SemaRef, SR.getBegin(), SemaRef.Context.VoidPtrTy,
871                             ".task_red.");
872     TaskgroupReductionRef =
873         buildDeclRefExpr(SemaRef, VD, SemaRef.Context.VoidPtrTy, SR.getBegin());
874   }
875 }
876 
877 DSAStackTy::DSAVarData
878 DSAStackTy::getTopMostTaskgroupReductionData(ValueDecl *D, SourceRange &SR,
879                                              BinaryOperatorKind &BOK,
880                                              Expr *&TaskgroupDescriptor) {
881   D = getCanonicalDecl(D);
882   assert(!isStackEmpty() && "Data-sharing attributes stack is empty.");
883   if (Stack.back().first.empty())
884       return DSAVarData();
885   for (auto I = std::next(Stack.back().first.rbegin(), 1),
886             E = Stack.back().first.rend();
887        I != E; std::advance(I, 1)) {
888     auto &Data = I->SharingMap[D];
889     if (Data.Attributes != OMPC_reduction || I->Directive != OMPD_taskgroup)
890       continue;
891     auto &ReductionData = I->ReductionMap[D];
892     if (!ReductionData.ReductionOp ||
893         ReductionData.ReductionOp.is<const Expr *>())
894       return DSAVarData();
895     SR = ReductionData.ReductionRange;
896     BOK = ReductionData.ReductionOp.get<ReductionData::BOKPtrType>();
897     assert(I->TaskgroupReductionRef && "taskgroup reduction reference "
898                                        "expression for the descriptor is not "
899                                        "set.");
900     TaskgroupDescriptor = I->TaskgroupReductionRef;
901     return DSAVarData(OMPD_taskgroup, OMPC_reduction, Data.RefExpr.getPointer(),
902                       Data.PrivateCopy, I->DefaultAttrLoc);
903   }
904   return DSAVarData();
905 }
906 
907 DSAStackTy::DSAVarData
908 DSAStackTy::getTopMostTaskgroupReductionData(ValueDecl *D, SourceRange &SR,
909                                              const Expr *&ReductionRef,
910                                              Expr *&TaskgroupDescriptor) {
911   D = getCanonicalDecl(D);
912   assert(!isStackEmpty() && "Data-sharing attributes stack is empty.");
913   if (Stack.back().first.empty())
914       return DSAVarData();
915   for (auto I = std::next(Stack.back().first.rbegin(), 1),
916             E = Stack.back().first.rend();
917        I != E; std::advance(I, 1)) {
918     auto &Data = I->SharingMap[D];
919     if (Data.Attributes != OMPC_reduction || I->Directive != OMPD_taskgroup)
920       continue;
921     auto &ReductionData = I->ReductionMap[D];
922     if (!ReductionData.ReductionOp ||
923         !ReductionData.ReductionOp.is<const Expr *>())
924       return DSAVarData();
925     SR = ReductionData.ReductionRange;
926     ReductionRef = ReductionData.ReductionOp.get<const Expr *>();
927     assert(I->TaskgroupReductionRef && "taskgroup reduction reference "
928                                        "expression for the descriptor is not "
929                                        "set.");
930     TaskgroupDescriptor = I->TaskgroupReductionRef;
931     return DSAVarData(OMPD_taskgroup, OMPC_reduction, Data.RefExpr.getPointer(),
932                       Data.PrivateCopy, I->DefaultAttrLoc);
933   }
934   return DSAVarData();
935 }
936 
937 bool DSAStackTy::isOpenMPLocal(VarDecl *D, StackTy::reverse_iterator Iter) {
938   D = D->getCanonicalDecl();
939   if (!isStackEmpty() && Stack.back().first.size() > 1) {
940     reverse_iterator I = Iter, E = Stack.back().first.rend();
941     Scope *TopScope = nullptr;
942     while (I != E && !isParallelOrTaskRegion(I->Directive))
943       ++I;
944     if (I == E)
945       return false;
946     TopScope = I->CurScope ? I->CurScope->getParent() : nullptr;
947     Scope *CurScope = getCurScope();
948     while (CurScope != TopScope && !CurScope->isDeclScope(D))
949       CurScope = CurScope->getParent();
950     return CurScope != TopScope;
951   }
952   return false;
953 }
954 
955 DSAStackTy::DSAVarData DSAStackTy::getTopDSA(ValueDecl *D, bool FromParent) {
956   D = getCanonicalDecl(D);
957   DSAVarData DVar;
958 
959   // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
960   // in a Construct, C/C++, predetermined, p.1]
961   //  Variables appearing in threadprivate directives are threadprivate.
962   auto *VD = dyn_cast<VarDecl>(D);
963   if ((VD && VD->getTLSKind() != VarDecl::TLS_None &&
964        !(VD->hasAttr<OMPThreadPrivateDeclAttr>() &&
965          SemaRef.getLangOpts().OpenMPUseTLS &&
966          SemaRef.getASTContext().getTargetInfo().isTLSSupported())) ||
967       (VD && VD->getStorageClass() == SC_Register &&
968        VD->hasAttr<AsmLabelAttr>() && !VD->isLocalVarDecl())) {
969     addDSA(D, buildDeclRefExpr(SemaRef, VD, D->getType().getNonReferenceType(),
970                                D->getLocation()),
971            OMPC_threadprivate);
972   }
973   auto TI = Threadprivates.find(D);
974   if (TI != Threadprivates.end()) {
975     DVar.RefExpr = TI->getSecond().RefExpr.getPointer();
976     DVar.CKind = OMPC_threadprivate;
977     return DVar;
978   } else if (VD && VD->hasAttr<OMPThreadPrivateDeclAttr>()) {
979     DVar.RefExpr = buildDeclRefExpr(
980         SemaRef, VD, D->getType().getNonReferenceType(),
981         VD->getAttr<OMPThreadPrivateDeclAttr>()->getLocation());
982     DVar.CKind = OMPC_threadprivate;
983     addDSA(D, DVar.RefExpr, OMPC_threadprivate);
984   }
985 
986   if (isStackEmpty())
987     // Not in OpenMP execution region and top scope was already checked.
988     return DVar;
989 
990   // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
991   // in a Construct, C/C++, predetermined, p.4]
992   //  Static data members are shared.
993   // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
994   // in a Construct, C/C++, predetermined, p.7]
995   //  Variables with static storage duration that are declared in a scope
996   //  inside the construct are shared.
997   auto &&MatchesAlways = [](OpenMPDirectiveKind) -> bool { return true; };
998   if (VD && VD->isStaticDataMember()) {
999     DSAVarData DVarTemp = hasDSA(D, isOpenMPPrivate, MatchesAlways, FromParent);
1000     if (DVarTemp.CKind != OMPC_unknown && DVarTemp.RefExpr)
1001       return DVar;
1002 
1003     DVar.CKind = OMPC_shared;
1004     return DVar;
1005   }
1006 
1007   QualType Type = D->getType().getNonReferenceType().getCanonicalType();
1008   bool IsConstant = Type.isConstant(SemaRef.getASTContext());
1009   Type = SemaRef.getASTContext().getBaseElementType(Type);
1010   // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
1011   // in a Construct, C/C++, predetermined, p.6]
1012   //  Variables with const qualified type having no mutable member are
1013   //  shared.
1014   CXXRecordDecl *RD =
1015       SemaRef.getLangOpts().CPlusPlus ? Type->getAsCXXRecordDecl() : nullptr;
1016   if (auto *CTSD = dyn_cast_or_null<ClassTemplateSpecializationDecl>(RD))
1017     if (auto *CTD = CTSD->getSpecializedTemplate())
1018       RD = CTD->getTemplatedDecl();
1019   if (IsConstant &&
1020       !(SemaRef.getLangOpts().CPlusPlus && RD && RD->hasDefinition() &&
1021         RD->hasMutableFields())) {
1022     // Variables with const-qualified type having no mutable member may be
1023     // listed in a firstprivate clause, even if they are static data members.
1024     DSAVarData DVarTemp = hasDSA(
1025         D, [](OpenMPClauseKind C) -> bool { return C == OMPC_firstprivate; },
1026         MatchesAlways, FromParent);
1027     if (DVarTemp.CKind == OMPC_firstprivate && DVarTemp.RefExpr)
1028       return DVar;
1029 
1030     DVar.CKind = OMPC_shared;
1031     return DVar;
1032   }
1033 
1034   // Explicitly specified attributes and local variables with predetermined
1035   // attributes.
1036   auto I = Stack.back().first.rbegin();
1037   auto EndI = Stack.back().first.rend();
1038   if (FromParent && I != EndI)
1039     std::advance(I, 1);
1040   if (I->SharingMap.count(D)) {
1041     DVar.RefExpr = I->SharingMap[D].RefExpr.getPointer();
1042     DVar.PrivateCopy = I->SharingMap[D].PrivateCopy;
1043     DVar.CKind = I->SharingMap[D].Attributes;
1044     DVar.ImplicitDSALoc = I->DefaultAttrLoc;
1045     DVar.DKind = I->Directive;
1046   }
1047 
1048   return DVar;
1049 }
1050 
1051 DSAStackTy::DSAVarData DSAStackTy::getImplicitDSA(ValueDecl *D,
1052                                                   bool FromParent) {
1053   if (isStackEmpty()) {
1054     StackTy::reverse_iterator I;
1055     return getDSA(I, D);
1056   }
1057   D = getCanonicalDecl(D);
1058   auto StartI = Stack.back().first.rbegin();
1059   auto EndI = Stack.back().first.rend();
1060   if (FromParent && StartI != EndI)
1061     std::advance(StartI, 1);
1062   return getDSA(StartI, D);
1063 }
1064 
1065 DSAStackTy::DSAVarData
1066 DSAStackTy::hasDSA(ValueDecl *D,
1067                    const llvm::function_ref<bool(OpenMPClauseKind)> &CPred,
1068                    const llvm::function_ref<bool(OpenMPDirectiveKind)> &DPred,
1069                    bool FromParent) {
1070   if (isStackEmpty())
1071     return {};
1072   D = getCanonicalDecl(D);
1073   auto I = Stack.back().first.rbegin();
1074   auto EndI = Stack.back().first.rend();
1075   if (FromParent && I != EndI)
1076     std::advance(I, 1);
1077   for (; I != EndI; std::advance(I, 1)) {
1078     if (!DPred(I->Directive) && !isParallelOrTaskRegion(I->Directive))
1079       continue;
1080     auto NewI = I;
1081     DSAVarData DVar = getDSA(NewI, D);
1082     if (I == NewI && CPred(DVar.CKind))
1083       return DVar;
1084   }
1085   return {};
1086 }
1087 
1088 DSAStackTy::DSAVarData DSAStackTy::hasInnermostDSA(
1089     ValueDecl *D, const llvm::function_ref<bool(OpenMPClauseKind)> &CPred,
1090     const llvm::function_ref<bool(OpenMPDirectiveKind)> &DPred,
1091     bool FromParent) {
1092   if (isStackEmpty())
1093     return {};
1094   D = getCanonicalDecl(D);
1095   auto StartI = Stack.back().first.rbegin();
1096   auto EndI = Stack.back().first.rend();
1097   if (FromParent && StartI != EndI)
1098     std::advance(StartI, 1);
1099   if (StartI == EndI || !DPred(StartI->Directive))
1100     return {};
1101   auto NewI = StartI;
1102   DSAVarData DVar = getDSA(NewI, D);
1103   return (NewI == StartI && CPred(DVar.CKind)) ? DVar : DSAVarData();
1104 }
1105 
1106 bool DSAStackTy::hasExplicitDSA(
1107     ValueDecl *D, const llvm::function_ref<bool(OpenMPClauseKind)> &CPred,
1108     unsigned Level, bool NotLastprivate) {
1109   if (isStackEmpty())
1110     return false;
1111   D = getCanonicalDecl(D);
1112   auto StartI = Stack.back().first.begin();
1113   auto EndI = Stack.back().first.end();
1114   if (std::distance(StartI, EndI) <= (int)Level)
1115     return false;
1116   std::advance(StartI, Level);
1117   return (StartI->SharingMap.count(D) > 0) &&
1118          StartI->SharingMap[D].RefExpr.getPointer() &&
1119          CPred(StartI->SharingMap[D].Attributes) &&
1120          (!NotLastprivate || !StartI->SharingMap[D].RefExpr.getInt());
1121 }
1122 
1123 bool DSAStackTy::hasExplicitDirective(
1124     const llvm::function_ref<bool(OpenMPDirectiveKind)> &DPred,
1125     unsigned Level) {
1126   if (isStackEmpty())
1127     return false;
1128   auto StartI = Stack.back().first.begin();
1129   auto EndI = Stack.back().first.end();
1130   if (std::distance(StartI, EndI) <= (int)Level)
1131     return false;
1132   std::advance(StartI, Level);
1133   return DPred(StartI->Directive);
1134 }
1135 
1136 bool DSAStackTy::hasDirective(
1137     const llvm::function_ref<bool(OpenMPDirectiveKind,
1138                                   const DeclarationNameInfo &, SourceLocation)>
1139         &DPred,
1140     bool FromParent) {
1141   // We look only in the enclosing region.
1142   if (isStackEmpty())
1143     return false;
1144   auto StartI = std::next(Stack.back().first.rbegin());
1145   auto EndI = Stack.back().first.rend();
1146   if (FromParent && StartI != EndI)
1147     StartI = std::next(StartI);
1148   for (auto I = StartI, EE = EndI; I != EE; ++I) {
1149     if (DPred(I->Directive, I->DirectiveName, I->ConstructLoc))
1150       return true;
1151   }
1152   return false;
1153 }
1154 
1155 void Sema::InitDataSharingAttributesStack() {
1156   VarDataSharingAttributesStack = new DSAStackTy(*this);
1157 }
1158 
1159 #define DSAStack static_cast<DSAStackTy *>(VarDataSharingAttributesStack)
1160 
1161 void Sema::pushOpenMPFunctionRegion() {
1162   DSAStack->pushFunction();
1163 }
1164 
1165 void Sema::popOpenMPFunctionRegion(const FunctionScopeInfo *OldFSI) {
1166   DSAStack->popFunction(OldFSI);
1167 }
1168 
1169 bool Sema::IsOpenMPCapturedByRef(ValueDecl *D, unsigned Level) {
1170   assert(LangOpts.OpenMP && "OpenMP is not allowed");
1171 
1172   auto &Ctx = getASTContext();
1173   bool IsByRef = true;
1174 
1175   // Find the directive that is associated with the provided scope.
1176   D = cast<ValueDecl>(D->getCanonicalDecl());
1177   auto Ty = D->getType();
1178 
1179   if (DSAStack->hasExplicitDirective(isOpenMPTargetExecutionDirective, Level)) {
1180     // This table summarizes how a given variable should be passed to the device
1181     // given its type and the clauses where it appears. This table is based on
1182     // the description in OpenMP 4.5 [2.10.4, target Construct] and
1183     // OpenMP 4.5 [2.15.5, Data-mapping Attribute Rules and Clauses].
1184     //
1185     // =========================================================================
1186     // | type |  defaultmap   | pvt | first | is_device_ptr |    map   | res.  |
1187     // |      |(tofrom:scalar)|     |  pvt  |               |          |       |
1188     // =========================================================================
1189     // | scl  |               |     |       |       -       |          | bycopy|
1190     // | scl  |               |  -  |   x   |       -       |     -    | bycopy|
1191     // | scl  |               |  x  |   -   |       -       |     -    | null  |
1192     // | scl  |       x       |     |       |       -       |          | byref |
1193     // | scl  |       x       |  -  |   x   |       -       |     -    | bycopy|
1194     // | scl  |       x       |  x  |   -   |       -       |     -    | null  |
1195     // | scl  |               |  -  |   -   |       -       |     x    | byref |
1196     // | scl  |       x       |  -  |   -   |       -       |     x    | byref |
1197     //
1198     // | agg  |      n.a.     |     |       |       -       |          | byref |
1199     // | agg  |      n.a.     |  -  |   x   |       -       |     -    | byref |
1200     // | agg  |      n.a.     |  x  |   -   |       -       |     -    | null  |
1201     // | agg  |      n.a.     |  -  |   -   |       -       |     x    | byref |
1202     // | agg  |      n.a.     |  -  |   -   |       -       |    x[]   | byref |
1203     //
1204     // | ptr  |      n.a.     |     |       |       -       |          | bycopy|
1205     // | ptr  |      n.a.     |  -  |   x   |       -       |     -    | bycopy|
1206     // | ptr  |      n.a.     |  x  |   -   |       -       |     -    | null  |
1207     // | ptr  |      n.a.     |  -  |   -   |       -       |     x    | byref |
1208     // | ptr  |      n.a.     |  -  |   -   |       -       |    x[]   | bycopy|
1209     // | ptr  |      n.a.     |  -  |   -   |       x       |          | bycopy|
1210     // | ptr  |      n.a.     |  -  |   -   |       x       |     x    | bycopy|
1211     // | ptr  |      n.a.     |  -  |   -   |       x       |    x[]   | bycopy|
1212     // =========================================================================
1213     // Legend:
1214     //  scl - scalar
1215     //  ptr - pointer
1216     //  agg - aggregate
1217     //  x - applies
1218     //  - - invalid in this combination
1219     //  [] - mapped with an array section
1220     //  byref - should be mapped by reference
1221     //  byval - should be mapped by value
1222     //  null - initialize a local variable to null on the device
1223     //
1224     // Observations:
1225     //  - All scalar declarations that show up in a map clause have to be passed
1226     //    by reference, because they may have been mapped in the enclosing data
1227     //    environment.
1228     //  - If the scalar value does not fit the size of uintptr, it has to be
1229     //    passed by reference, regardless the result in the table above.
1230     //  - For pointers mapped by value that have either an implicit map or an
1231     //    array section, the runtime library may pass the NULL value to the
1232     //    device instead of the value passed to it by the compiler.
1233 
1234     if (Ty->isReferenceType())
1235       Ty = Ty->castAs<ReferenceType>()->getPointeeType();
1236 
1237     // Locate map clauses and see if the variable being captured is referred to
1238     // in any of those clauses. Here we only care about variables, not fields,
1239     // because fields are part of aggregates.
1240     bool IsVariableUsedInMapClause = false;
1241     bool IsVariableAssociatedWithSection = false;
1242 
1243     DSAStack->checkMappableExprComponentListsForDeclAtLevel(
1244         D, Level, [&](OMPClauseMappableExprCommon::MappableExprComponentListRef
1245                 MapExprComponents,
1246             OpenMPClauseKind WhereFoundClauseKind) {
1247           // Only the map clause information influences how a variable is
1248           // captured. E.g. is_device_ptr does not require changing the default
1249           // behavior.
1250           if (WhereFoundClauseKind != OMPC_map)
1251             return false;
1252 
1253           auto EI = MapExprComponents.rbegin();
1254           auto EE = MapExprComponents.rend();
1255 
1256           assert(EI != EE && "Invalid map expression!");
1257 
1258           if (isa<DeclRefExpr>(EI->getAssociatedExpression()))
1259             IsVariableUsedInMapClause |= EI->getAssociatedDeclaration() == D;
1260 
1261           ++EI;
1262           if (EI == EE)
1263             return false;
1264 
1265           if (isa<ArraySubscriptExpr>(EI->getAssociatedExpression()) ||
1266               isa<OMPArraySectionExpr>(EI->getAssociatedExpression()) ||
1267               isa<MemberExpr>(EI->getAssociatedExpression())) {
1268             IsVariableAssociatedWithSection = true;
1269             // There is nothing more we need to know about this variable.
1270             return true;
1271           }
1272 
1273           // Keep looking for more map info.
1274           return false;
1275         });
1276 
1277     if (IsVariableUsedInMapClause) {
1278       // If variable is identified in a map clause it is always captured by
1279       // reference except if it is a pointer that is dereferenced somehow.
1280       IsByRef = !(Ty->isPointerType() && IsVariableAssociatedWithSection);
1281     } else {
1282       // By default, all the data that has a scalar type is mapped by copy
1283       // (except for reduction variables).
1284       IsByRef =
1285           !Ty->isScalarType() ||
1286           DSAStack->getDefaultDMAAtLevel(Level) == DMA_tofrom_scalar ||
1287           DSAStack->hasExplicitDSA(
1288               D, [](OpenMPClauseKind K) { return K == OMPC_reduction; }, Level);
1289     }
1290   }
1291 
1292   if (IsByRef && Ty.getNonReferenceType()->isScalarType()) {
1293     IsByRef =
1294         !DSAStack->hasExplicitDSA(
1295             D,
1296             [](OpenMPClauseKind K) -> bool { return K == OMPC_firstprivate; },
1297             Level, /*NotLastprivate=*/true) &&
1298         // If the variable is artificial and must be captured by value - try to
1299         // capture by value.
1300         !(isa<OMPCapturedExprDecl>(D) && !D->hasAttr<OMPCaptureNoInitAttr>() &&
1301           !cast<OMPCapturedExprDecl>(D)->getInit()->isGLValue());
1302   }
1303 
1304   // When passing data by copy, we need to make sure it fits the uintptr size
1305   // and alignment, because the runtime library only deals with uintptr types.
1306   // If it does not fit the uintptr size, we need to pass the data by reference
1307   // instead.
1308   if (!IsByRef &&
1309       (Ctx.getTypeSizeInChars(Ty) >
1310            Ctx.getTypeSizeInChars(Ctx.getUIntPtrType()) ||
1311        Ctx.getDeclAlign(D) > Ctx.getTypeAlignInChars(Ctx.getUIntPtrType()))) {
1312     IsByRef = true;
1313   }
1314 
1315   return IsByRef;
1316 }
1317 
1318 unsigned Sema::getOpenMPNestingLevel() const {
1319   assert(getLangOpts().OpenMP);
1320   return DSAStack->getNestingLevel();
1321 }
1322 
1323 bool Sema::isInOpenMPTargetExecutionDirective() const {
1324   return (isOpenMPTargetExecutionDirective(DSAStack->getCurrentDirective()) &&
1325           !DSAStack->isClauseParsingMode()) ||
1326          DSAStack->hasDirective(
1327              [](OpenMPDirectiveKind K, const DeclarationNameInfo &,
1328                 SourceLocation) -> bool {
1329                return isOpenMPTargetExecutionDirective(K);
1330              },
1331              false);
1332 }
1333 
1334 VarDecl *Sema::IsOpenMPCapturedDecl(ValueDecl *D) {
1335   assert(LangOpts.OpenMP && "OpenMP is not allowed");
1336   D = getCanonicalDecl(D);
1337 
1338   // If we are attempting to capture a global variable in a directive with
1339   // 'target' we return true so that this global is also mapped to the device.
1340   //
1341   // FIXME: If the declaration is enclosed in a 'declare target' directive,
1342   // then it should not be captured. Therefore, an extra check has to be
1343   // inserted here once support for 'declare target' is added.
1344   //
1345   auto *VD = dyn_cast<VarDecl>(D);
1346   if (VD && !VD->hasLocalStorage() && isInOpenMPTargetExecutionDirective())
1347     return VD;
1348 
1349   if (DSAStack->getCurrentDirective() != OMPD_unknown &&
1350       (!DSAStack->isClauseParsingMode() ||
1351        DSAStack->getParentDirective() != OMPD_unknown)) {
1352     auto &&Info = DSAStack->isLoopControlVariable(D);
1353     if (Info.first ||
1354         (VD && VD->hasLocalStorage() &&
1355          isParallelOrTaskRegion(DSAStack->getCurrentDirective())) ||
1356         (VD && DSAStack->isForceVarCapturing()))
1357       return VD ? VD : Info.second;
1358     auto DVarPrivate = DSAStack->getTopDSA(D, DSAStack->isClauseParsingMode());
1359     if (DVarPrivate.CKind != OMPC_unknown && isOpenMPPrivate(DVarPrivate.CKind))
1360       return VD ? VD : cast<VarDecl>(DVarPrivate.PrivateCopy->getDecl());
1361     DVarPrivate = DSAStack->hasDSA(
1362         D, isOpenMPPrivate, [](OpenMPDirectiveKind) -> bool { return true; },
1363         DSAStack->isClauseParsingMode());
1364     if (DVarPrivate.CKind != OMPC_unknown)
1365       return VD ? VD : cast<VarDecl>(DVarPrivate.PrivateCopy->getDecl());
1366   }
1367   return nullptr;
1368 }
1369 
1370 void Sema::adjustOpenMPTargetScopeIndex(unsigned &FunctionScopesIndex,
1371                                         unsigned Level) const {
1372   SmallVector<OpenMPDirectiveKind, 4> Regions;
1373   getOpenMPCaptureRegions(Regions, DSAStack->getDirective(Level));
1374   FunctionScopesIndex -= Regions.size();
1375 }
1376 
1377 bool Sema::isOpenMPPrivateDecl(ValueDecl *D, unsigned Level) {
1378   assert(LangOpts.OpenMP && "OpenMP is not allowed");
1379   return DSAStack->hasExplicitDSA(
1380              D, [](OpenMPClauseKind K) -> bool { return K == OMPC_private; },
1381              Level) ||
1382          (DSAStack->isClauseParsingMode() &&
1383           DSAStack->getClauseParsingMode() == OMPC_private) ||
1384          // Consider taskgroup reduction descriptor variable a private to avoid
1385          // possible capture in the region.
1386          (DSAStack->hasExplicitDirective(
1387               [](OpenMPDirectiveKind K) { return K == OMPD_taskgroup; },
1388               Level) &&
1389           DSAStack->isTaskgroupReductionRef(D, Level));
1390 }
1391 
1392 void Sema::setOpenMPCaptureKind(FieldDecl *FD, ValueDecl *D, unsigned Level) {
1393   assert(LangOpts.OpenMP && "OpenMP is not allowed");
1394   D = getCanonicalDecl(D);
1395   OpenMPClauseKind OMPC = OMPC_unknown;
1396   for (unsigned I = DSAStack->getNestingLevel() + 1; I > Level; --I) {
1397     const unsigned NewLevel = I - 1;
1398     if (DSAStack->hasExplicitDSA(D,
1399                                  [&OMPC](const OpenMPClauseKind K) {
1400                                    if (isOpenMPPrivate(K)) {
1401                                      OMPC = K;
1402                                      return true;
1403                                    }
1404                                    return false;
1405                                  },
1406                                  NewLevel))
1407       break;
1408     if (DSAStack->checkMappableExprComponentListsForDeclAtLevel(
1409             D, NewLevel,
1410             [](OMPClauseMappableExprCommon::MappableExprComponentListRef,
1411                OpenMPClauseKind) { return true; })) {
1412       OMPC = OMPC_map;
1413       break;
1414     }
1415     if (DSAStack->hasExplicitDirective(isOpenMPTargetExecutionDirective,
1416                                        NewLevel)) {
1417       OMPC = OMPC_firstprivate;
1418       break;
1419     }
1420   }
1421   if (OMPC != OMPC_unknown)
1422     FD->addAttr(OMPCaptureKindAttr::CreateImplicit(Context, OMPC));
1423 }
1424 
1425 bool Sema::isOpenMPTargetCapturedDecl(ValueDecl *D, unsigned Level) {
1426   assert(LangOpts.OpenMP && "OpenMP is not allowed");
1427   // Return true if the current level is no longer enclosed in a target region.
1428 
1429   auto *VD = dyn_cast<VarDecl>(D);
1430   return VD && !VD->hasLocalStorage() &&
1431          DSAStack->hasExplicitDirective(isOpenMPTargetExecutionDirective,
1432                                         Level);
1433 }
1434 
1435 void Sema::DestroyDataSharingAttributesStack() { delete DSAStack; }
1436 
1437 void Sema::StartOpenMPDSABlock(OpenMPDirectiveKind DKind,
1438                                const DeclarationNameInfo &DirName,
1439                                Scope *CurScope, SourceLocation Loc) {
1440   DSAStack->push(DKind, DirName, CurScope, Loc);
1441   PushExpressionEvaluationContext(
1442       ExpressionEvaluationContext::PotentiallyEvaluated);
1443 }
1444 
1445 void Sema::StartOpenMPClause(OpenMPClauseKind K) {
1446   DSAStack->setClauseParsingMode(K);
1447 }
1448 
1449 void Sema::EndOpenMPClause() {
1450   DSAStack->setClauseParsingMode(/*K=*/OMPC_unknown);
1451 }
1452 
1453 void Sema::EndOpenMPDSABlock(Stmt *CurDirective) {
1454   // OpenMP [2.14.3.5, Restrictions, C/C++, p.1]
1455   //  A variable of class type (or array thereof) that appears in a lastprivate
1456   //  clause requires an accessible, unambiguous default constructor for the
1457   //  class type, unless the list item is also specified in a firstprivate
1458   //  clause.
1459   if (auto *D = dyn_cast_or_null<OMPExecutableDirective>(CurDirective)) {
1460     for (auto *C : D->clauses()) {
1461       if (auto *Clause = dyn_cast<OMPLastprivateClause>(C)) {
1462         SmallVector<Expr *, 8> PrivateCopies;
1463         for (auto *DE : Clause->varlists()) {
1464           if (DE->isValueDependent() || DE->isTypeDependent()) {
1465             PrivateCopies.push_back(nullptr);
1466             continue;
1467           }
1468           auto *DRE = cast<DeclRefExpr>(DE->IgnoreParens());
1469           VarDecl *VD = cast<VarDecl>(DRE->getDecl());
1470           QualType Type = VD->getType().getNonReferenceType();
1471           auto DVar = DSAStack->getTopDSA(VD, false);
1472           if (DVar.CKind == OMPC_lastprivate) {
1473             // Generate helper private variable and initialize it with the
1474             // default value. The address of the original variable is replaced
1475             // by the address of the new private variable in CodeGen. This new
1476             // variable is not added to IdResolver, so the code in the OpenMP
1477             // region uses original variable for proper diagnostics.
1478             auto *VDPrivate = buildVarDecl(
1479                 *this, DE->getExprLoc(), Type.getUnqualifiedType(),
1480                 VD->getName(), VD->hasAttrs() ? &VD->getAttrs() : nullptr);
1481             ActOnUninitializedDecl(VDPrivate);
1482             if (VDPrivate->isInvalidDecl())
1483               continue;
1484             PrivateCopies.push_back(buildDeclRefExpr(
1485                 *this, VDPrivate, DE->getType(), DE->getExprLoc()));
1486           } else {
1487             // The variable is also a firstprivate, so initialization sequence
1488             // for private copy is generated already.
1489             PrivateCopies.push_back(nullptr);
1490           }
1491         }
1492         // Set initializers to private copies if no errors were found.
1493         if (PrivateCopies.size() == Clause->varlist_size())
1494           Clause->setPrivateCopies(PrivateCopies);
1495       }
1496     }
1497   }
1498 
1499   DSAStack->pop();
1500   DiscardCleanupsInEvaluationContext();
1501   PopExpressionEvaluationContext();
1502 }
1503 
1504 static bool FinishOpenMPLinearClause(OMPLinearClause &Clause, DeclRefExpr *IV,
1505                                      Expr *NumIterations, Sema &SemaRef,
1506                                      Scope *S, DSAStackTy *Stack);
1507 
1508 namespace {
1509 
1510 class VarDeclFilterCCC : public CorrectionCandidateCallback {
1511 private:
1512   Sema &SemaRef;
1513 
1514 public:
1515   explicit VarDeclFilterCCC(Sema &S) : SemaRef(S) {}
1516   bool ValidateCandidate(const TypoCorrection &Candidate) override {
1517     NamedDecl *ND = Candidate.getCorrectionDecl();
1518     if (auto *VD = dyn_cast_or_null<VarDecl>(ND)) {
1519       return VD->hasGlobalStorage() &&
1520              SemaRef.isDeclInScope(ND, SemaRef.getCurLexicalContext(),
1521                                    SemaRef.getCurScope());
1522     }
1523     return false;
1524   }
1525 };
1526 
1527 class VarOrFuncDeclFilterCCC : public CorrectionCandidateCallback {
1528 private:
1529   Sema &SemaRef;
1530 
1531 public:
1532   explicit VarOrFuncDeclFilterCCC(Sema &S) : SemaRef(S) {}
1533   bool ValidateCandidate(const TypoCorrection &Candidate) override {
1534     NamedDecl *ND = Candidate.getCorrectionDecl();
1535     if (ND && (isa<VarDecl>(ND) || isa<FunctionDecl>(ND))) {
1536       return SemaRef.isDeclInScope(ND, SemaRef.getCurLexicalContext(),
1537                                    SemaRef.getCurScope());
1538     }
1539     return false;
1540   }
1541 };
1542 
1543 } // namespace
1544 
1545 ExprResult Sema::ActOnOpenMPIdExpression(Scope *CurScope,
1546                                          CXXScopeSpec &ScopeSpec,
1547                                          const DeclarationNameInfo &Id) {
1548   LookupResult Lookup(*this, Id, LookupOrdinaryName);
1549   LookupParsedName(Lookup, CurScope, &ScopeSpec, true);
1550 
1551   if (Lookup.isAmbiguous())
1552     return ExprError();
1553 
1554   VarDecl *VD;
1555   if (!Lookup.isSingleResult()) {
1556     if (TypoCorrection Corrected = CorrectTypo(
1557             Id, LookupOrdinaryName, CurScope, nullptr,
1558             llvm::make_unique<VarDeclFilterCCC>(*this), CTK_ErrorRecovery)) {
1559       diagnoseTypo(Corrected,
1560                    PDiag(Lookup.empty()
1561                              ? diag::err_undeclared_var_use_suggest
1562                              : diag::err_omp_expected_var_arg_suggest)
1563                        << Id.getName());
1564       VD = Corrected.getCorrectionDeclAs<VarDecl>();
1565     } else {
1566       Diag(Id.getLoc(), Lookup.empty() ? diag::err_undeclared_var_use
1567                                        : diag::err_omp_expected_var_arg)
1568           << Id.getName();
1569       return ExprError();
1570     }
1571   } else {
1572     if (!(VD = Lookup.getAsSingle<VarDecl>())) {
1573       Diag(Id.getLoc(), diag::err_omp_expected_var_arg) << Id.getName();
1574       Diag(Lookup.getFoundDecl()->getLocation(), diag::note_declared_at);
1575       return ExprError();
1576     }
1577   }
1578   Lookup.suppressDiagnostics();
1579 
1580   // OpenMP [2.9.2, Syntax, C/C++]
1581   //   Variables must be file-scope, namespace-scope, or static block-scope.
1582   if (!VD->hasGlobalStorage()) {
1583     Diag(Id.getLoc(), diag::err_omp_global_var_arg)
1584         << getOpenMPDirectiveName(OMPD_threadprivate) << !VD->isStaticLocal();
1585     bool IsDecl =
1586         VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
1587     Diag(VD->getLocation(),
1588          IsDecl ? diag::note_previous_decl : diag::note_defined_here)
1589         << VD;
1590     return ExprError();
1591   }
1592 
1593   VarDecl *CanonicalVD = VD->getCanonicalDecl();
1594   NamedDecl *ND = cast<NamedDecl>(CanonicalVD);
1595   // OpenMP [2.9.2, Restrictions, C/C++, p.2]
1596   //   A threadprivate directive for file-scope variables must appear outside
1597   //   any definition or declaration.
1598   if (CanonicalVD->getDeclContext()->isTranslationUnit() &&
1599       !getCurLexicalContext()->isTranslationUnit()) {
1600     Diag(Id.getLoc(), diag::err_omp_var_scope)
1601         << getOpenMPDirectiveName(OMPD_threadprivate) << VD;
1602     bool IsDecl =
1603         VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
1604     Diag(VD->getLocation(),
1605          IsDecl ? diag::note_previous_decl : diag::note_defined_here)
1606         << VD;
1607     return ExprError();
1608   }
1609   // OpenMP [2.9.2, Restrictions, C/C++, p.3]
1610   //   A threadprivate directive for static class member variables must appear
1611   //   in the class definition, in the same scope in which the member
1612   //   variables are declared.
1613   if (CanonicalVD->isStaticDataMember() &&
1614       !CanonicalVD->getDeclContext()->Equals(getCurLexicalContext())) {
1615     Diag(Id.getLoc(), diag::err_omp_var_scope)
1616         << getOpenMPDirectiveName(OMPD_threadprivate) << VD;
1617     bool IsDecl =
1618         VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
1619     Diag(VD->getLocation(),
1620          IsDecl ? diag::note_previous_decl : diag::note_defined_here)
1621         << VD;
1622     return ExprError();
1623   }
1624   // OpenMP [2.9.2, Restrictions, C/C++, p.4]
1625   //   A threadprivate directive for namespace-scope variables must appear
1626   //   outside any definition or declaration other than the namespace
1627   //   definition itself.
1628   if (CanonicalVD->getDeclContext()->isNamespace() &&
1629       (!getCurLexicalContext()->isFileContext() ||
1630        !getCurLexicalContext()->Encloses(CanonicalVD->getDeclContext()))) {
1631     Diag(Id.getLoc(), diag::err_omp_var_scope)
1632         << getOpenMPDirectiveName(OMPD_threadprivate) << VD;
1633     bool IsDecl =
1634         VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
1635     Diag(VD->getLocation(),
1636          IsDecl ? diag::note_previous_decl : diag::note_defined_here)
1637         << VD;
1638     return ExprError();
1639   }
1640   // OpenMP [2.9.2, Restrictions, C/C++, p.6]
1641   //   A threadprivate directive for static block-scope variables must appear
1642   //   in the scope of the variable and not in a nested scope.
1643   if (CanonicalVD->isStaticLocal() && CurScope &&
1644       !isDeclInScope(ND, getCurLexicalContext(), CurScope)) {
1645     Diag(Id.getLoc(), diag::err_omp_var_scope)
1646         << getOpenMPDirectiveName(OMPD_threadprivate) << VD;
1647     bool IsDecl =
1648         VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
1649     Diag(VD->getLocation(),
1650          IsDecl ? diag::note_previous_decl : diag::note_defined_here)
1651         << VD;
1652     return ExprError();
1653   }
1654 
1655   // OpenMP [2.9.2, Restrictions, C/C++, p.2-6]
1656   //   A threadprivate directive must lexically precede all references to any
1657   //   of the variables in its list.
1658   if (VD->isUsed() && !DSAStack->isThreadPrivate(VD)) {
1659     Diag(Id.getLoc(), diag::err_omp_var_used)
1660         << getOpenMPDirectiveName(OMPD_threadprivate) << VD;
1661     return ExprError();
1662   }
1663 
1664   QualType ExprType = VD->getType().getNonReferenceType();
1665   return DeclRefExpr::Create(Context, NestedNameSpecifierLoc(),
1666                              SourceLocation(), VD,
1667                              /*RefersToEnclosingVariableOrCapture=*/false,
1668                              Id.getLoc(), ExprType, VK_LValue);
1669 }
1670 
1671 Sema::DeclGroupPtrTy
1672 Sema::ActOnOpenMPThreadprivateDirective(SourceLocation Loc,
1673                                         ArrayRef<Expr *> VarList) {
1674   if (OMPThreadPrivateDecl *D = CheckOMPThreadPrivateDecl(Loc, VarList)) {
1675     CurContext->addDecl(D);
1676     return DeclGroupPtrTy::make(DeclGroupRef(D));
1677   }
1678   return nullptr;
1679 }
1680 
1681 namespace {
1682 class LocalVarRefChecker : public ConstStmtVisitor<LocalVarRefChecker, bool> {
1683   Sema &SemaRef;
1684 
1685 public:
1686   bool VisitDeclRefExpr(const DeclRefExpr *E) {
1687     if (auto *VD = dyn_cast<VarDecl>(E->getDecl())) {
1688       if (VD->hasLocalStorage()) {
1689         SemaRef.Diag(E->getLocStart(),
1690                      diag::err_omp_local_var_in_threadprivate_init)
1691             << E->getSourceRange();
1692         SemaRef.Diag(VD->getLocation(), diag::note_defined_here)
1693             << VD << VD->getSourceRange();
1694         return true;
1695       }
1696     }
1697     return false;
1698   }
1699   bool VisitStmt(const Stmt *S) {
1700     for (auto Child : S->children()) {
1701       if (Child && Visit(Child))
1702         return true;
1703     }
1704     return false;
1705   }
1706   explicit LocalVarRefChecker(Sema &SemaRef) : SemaRef(SemaRef) {}
1707 };
1708 } // namespace
1709 
1710 OMPThreadPrivateDecl *
1711 Sema::CheckOMPThreadPrivateDecl(SourceLocation Loc, ArrayRef<Expr *> VarList) {
1712   SmallVector<Expr *, 8> Vars;
1713   for (auto &RefExpr : VarList) {
1714     DeclRefExpr *DE = cast<DeclRefExpr>(RefExpr);
1715     VarDecl *VD = cast<VarDecl>(DE->getDecl());
1716     SourceLocation ILoc = DE->getExprLoc();
1717 
1718     // Mark variable as used.
1719     VD->setReferenced();
1720     VD->markUsed(Context);
1721 
1722     QualType QType = VD->getType();
1723     if (QType->isDependentType() || QType->isInstantiationDependentType()) {
1724       // It will be analyzed later.
1725       Vars.push_back(DE);
1726       continue;
1727     }
1728 
1729     // OpenMP [2.9.2, Restrictions, C/C++, p.10]
1730     //   A threadprivate variable must not have an incomplete type.
1731     if (RequireCompleteType(ILoc, VD->getType(),
1732                             diag::err_omp_threadprivate_incomplete_type)) {
1733       continue;
1734     }
1735 
1736     // OpenMP [2.9.2, Restrictions, C/C++, p.10]
1737     //   A threadprivate variable must not have a reference type.
1738     if (VD->getType()->isReferenceType()) {
1739       Diag(ILoc, diag::err_omp_ref_type_arg)
1740           << getOpenMPDirectiveName(OMPD_threadprivate) << VD->getType();
1741       bool IsDecl =
1742           VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
1743       Diag(VD->getLocation(),
1744            IsDecl ? diag::note_previous_decl : diag::note_defined_here)
1745           << VD;
1746       continue;
1747     }
1748 
1749     // Check if this is a TLS variable. If TLS is not being supported, produce
1750     // the corresponding diagnostic.
1751     if ((VD->getTLSKind() != VarDecl::TLS_None &&
1752          !(VD->hasAttr<OMPThreadPrivateDeclAttr>() &&
1753            getLangOpts().OpenMPUseTLS &&
1754            getASTContext().getTargetInfo().isTLSSupported())) ||
1755         (VD->getStorageClass() == SC_Register && VD->hasAttr<AsmLabelAttr>() &&
1756          !VD->isLocalVarDecl())) {
1757       Diag(ILoc, diag::err_omp_var_thread_local)
1758           << VD << ((VD->getTLSKind() != VarDecl::TLS_None) ? 0 : 1);
1759       bool IsDecl =
1760           VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
1761       Diag(VD->getLocation(),
1762            IsDecl ? diag::note_previous_decl : diag::note_defined_here)
1763           << VD;
1764       continue;
1765     }
1766 
1767     // Check if initial value of threadprivate variable reference variable with
1768     // local storage (it is not supported by runtime).
1769     if (auto Init = VD->getAnyInitializer()) {
1770       LocalVarRefChecker Checker(*this);
1771       if (Checker.Visit(Init))
1772         continue;
1773     }
1774 
1775     Vars.push_back(RefExpr);
1776     DSAStack->addDSA(VD, DE, OMPC_threadprivate);
1777     VD->addAttr(OMPThreadPrivateDeclAttr::CreateImplicit(
1778         Context, SourceRange(Loc, Loc)));
1779     if (auto *ML = Context.getASTMutationListener())
1780       ML->DeclarationMarkedOpenMPThreadPrivate(VD);
1781   }
1782   OMPThreadPrivateDecl *D = nullptr;
1783   if (!Vars.empty()) {
1784     D = OMPThreadPrivateDecl::Create(Context, getCurLexicalContext(), Loc,
1785                                      Vars);
1786     D->setAccess(AS_public);
1787   }
1788   return D;
1789 }
1790 
1791 static void ReportOriginalDSA(Sema &SemaRef, DSAStackTy *Stack,
1792                               const ValueDecl *D, DSAStackTy::DSAVarData DVar,
1793                               bool IsLoopIterVar = false) {
1794   if (DVar.RefExpr) {
1795     SemaRef.Diag(DVar.RefExpr->getExprLoc(), diag::note_omp_explicit_dsa)
1796         << getOpenMPClauseName(DVar.CKind);
1797     return;
1798   }
1799   enum {
1800     PDSA_StaticMemberShared,
1801     PDSA_StaticLocalVarShared,
1802     PDSA_LoopIterVarPrivate,
1803     PDSA_LoopIterVarLinear,
1804     PDSA_LoopIterVarLastprivate,
1805     PDSA_ConstVarShared,
1806     PDSA_GlobalVarShared,
1807     PDSA_TaskVarFirstprivate,
1808     PDSA_LocalVarPrivate,
1809     PDSA_Implicit
1810   } Reason = PDSA_Implicit;
1811   bool ReportHint = false;
1812   auto ReportLoc = D->getLocation();
1813   auto *VD = dyn_cast<VarDecl>(D);
1814   if (IsLoopIterVar) {
1815     if (DVar.CKind == OMPC_private)
1816       Reason = PDSA_LoopIterVarPrivate;
1817     else if (DVar.CKind == OMPC_lastprivate)
1818       Reason = PDSA_LoopIterVarLastprivate;
1819     else
1820       Reason = PDSA_LoopIterVarLinear;
1821   } else if (isOpenMPTaskingDirective(DVar.DKind) &&
1822              DVar.CKind == OMPC_firstprivate) {
1823     Reason = PDSA_TaskVarFirstprivate;
1824     ReportLoc = DVar.ImplicitDSALoc;
1825   } else if (VD && VD->isStaticLocal())
1826     Reason = PDSA_StaticLocalVarShared;
1827   else if (VD && VD->isStaticDataMember())
1828     Reason = PDSA_StaticMemberShared;
1829   else if (VD && VD->isFileVarDecl())
1830     Reason = PDSA_GlobalVarShared;
1831   else if (D->getType().isConstant(SemaRef.getASTContext()))
1832     Reason = PDSA_ConstVarShared;
1833   else if (VD && VD->isLocalVarDecl() && DVar.CKind == OMPC_private) {
1834     ReportHint = true;
1835     Reason = PDSA_LocalVarPrivate;
1836   }
1837   if (Reason != PDSA_Implicit) {
1838     SemaRef.Diag(ReportLoc, diag::note_omp_predetermined_dsa)
1839         << Reason << ReportHint
1840         << getOpenMPDirectiveName(Stack->getCurrentDirective());
1841   } else if (DVar.ImplicitDSALoc.isValid()) {
1842     SemaRef.Diag(DVar.ImplicitDSALoc, diag::note_omp_implicit_dsa)
1843         << getOpenMPClauseName(DVar.CKind);
1844   }
1845 }
1846 
1847 namespace {
1848 class DSAAttrChecker : public StmtVisitor<DSAAttrChecker, void> {
1849   DSAStackTy *Stack;
1850   Sema &SemaRef;
1851   bool ErrorFound;
1852   CapturedStmt *CS;
1853   llvm::SmallVector<Expr *, 8> ImplicitFirstprivate;
1854   llvm::SmallVector<Expr *, 8> ImplicitMap;
1855   llvm::DenseMap<ValueDecl *, Expr *> VarsWithInheritedDSA;
1856   llvm::DenseSet<ValueDecl *> ImplicitDeclarations;
1857 
1858 public:
1859   void VisitDeclRefExpr(DeclRefExpr *E) {
1860     if (E->isTypeDependent() || E->isValueDependent() ||
1861         E->containsUnexpandedParameterPack() || E->isInstantiationDependent())
1862       return;
1863     if (auto *VD = dyn_cast<VarDecl>(E->getDecl())) {
1864       VD = VD->getCanonicalDecl();
1865       // Skip internally declared variables.
1866       if (VD->hasLocalStorage() && !CS->capturesVariable(VD))
1867         return;
1868 
1869       auto DVar = Stack->getTopDSA(VD, false);
1870       // Check if the variable has explicit DSA set and stop analysis if it so.
1871       if (DVar.RefExpr || !ImplicitDeclarations.insert(VD).second)
1872         return;
1873 
1874       // Skip internally declared static variables.
1875       if (VD->hasGlobalStorage() && !CS->capturesVariable(VD))
1876         return;
1877 
1878       auto ELoc = E->getExprLoc();
1879       auto DKind = Stack->getCurrentDirective();
1880       // The default(none) clause requires that each variable that is referenced
1881       // in the construct, and does not have a predetermined data-sharing
1882       // attribute, must have its data-sharing attribute explicitly determined
1883       // by being listed in a data-sharing attribute clause.
1884       if (DVar.CKind == OMPC_unknown && Stack->getDefaultDSA() == DSA_none &&
1885           isParallelOrTaskRegion(DKind) &&
1886           VarsWithInheritedDSA.count(VD) == 0) {
1887         VarsWithInheritedDSA[VD] = E;
1888         return;
1889       }
1890 
1891       if (isOpenMPTargetExecutionDirective(DKind) &&
1892           !Stack->isLoopControlVariable(VD).first) {
1893         if (!Stack->checkMappableExprComponentListsForDecl(
1894                 VD, /*CurrentRegionOnly=*/true,
1895                 [](OMPClauseMappableExprCommon::MappableExprComponentListRef
1896                        StackComponents,
1897                    OpenMPClauseKind) {
1898                   // Variable is used if it has been marked as an array, array
1899                   // section or the variable iself.
1900                   return StackComponents.size() == 1 ||
1901                          std::all_of(
1902                              std::next(StackComponents.rbegin()),
1903                              StackComponents.rend(),
1904                              [](const OMPClauseMappableExprCommon::
1905                                     MappableComponent &MC) {
1906                                return MC.getAssociatedDeclaration() ==
1907                                           nullptr &&
1908                                       (isa<OMPArraySectionExpr>(
1909                                            MC.getAssociatedExpression()) ||
1910                                        isa<ArraySubscriptExpr>(
1911                                            MC.getAssociatedExpression()));
1912                              });
1913                 })) {
1914           bool IsFirstprivate = false;
1915           // By default lambdas are captured as firstprivates.
1916           if (const auto *RD =
1917                   VD->getType().getNonReferenceType()->getAsCXXRecordDecl())
1918             IsFirstprivate = RD->isLambda();
1919           IsFirstprivate =
1920               IsFirstprivate ||
1921               (VD->getType().getNonReferenceType()->isScalarType() &&
1922                Stack->getDefaultDMA() != DMA_tofrom_scalar);
1923           if (IsFirstprivate)
1924             ImplicitFirstprivate.emplace_back(E);
1925           else
1926             ImplicitMap.emplace_back(E);
1927           return;
1928         }
1929       }
1930 
1931       // OpenMP [2.9.3.6, Restrictions, p.2]
1932       //  A list item that appears in a reduction clause of the innermost
1933       //  enclosing worksharing or parallel construct may not be accessed in an
1934       //  explicit task.
1935       DVar = Stack->hasInnermostDSA(
1936           VD, [](OpenMPClauseKind C) -> bool { return C == OMPC_reduction; },
1937           [](OpenMPDirectiveKind K) -> bool {
1938             return isOpenMPParallelDirective(K) ||
1939                    isOpenMPWorksharingDirective(K) || isOpenMPTeamsDirective(K);
1940           },
1941           /*FromParent=*/true);
1942       if (isOpenMPTaskingDirective(DKind) && DVar.CKind == OMPC_reduction) {
1943         ErrorFound = true;
1944         SemaRef.Diag(ELoc, diag::err_omp_reduction_in_task);
1945         ReportOriginalDSA(SemaRef, Stack, VD, DVar);
1946         return;
1947       }
1948 
1949       // Define implicit data-sharing attributes for task.
1950       DVar = Stack->getImplicitDSA(VD, false);
1951       if (isOpenMPTaskingDirective(DKind) && DVar.CKind != OMPC_shared &&
1952           !Stack->isLoopControlVariable(VD).first)
1953         ImplicitFirstprivate.push_back(E);
1954     }
1955   }
1956   void VisitMemberExpr(MemberExpr *E) {
1957     if (E->isTypeDependent() || E->isValueDependent() ||
1958         E->containsUnexpandedParameterPack() || E->isInstantiationDependent())
1959       return;
1960     auto *FD = dyn_cast<FieldDecl>(E->getMemberDecl());
1961     OpenMPDirectiveKind DKind = Stack->getCurrentDirective();
1962     if (isa<CXXThisExpr>(E->getBase()->IgnoreParens())) {
1963       if (!FD)
1964         return;
1965       auto DVar = Stack->getTopDSA(FD, false);
1966       // Check if the variable has explicit DSA set and stop analysis if it
1967       // so.
1968       if (DVar.RefExpr || !ImplicitDeclarations.insert(FD).second)
1969         return;
1970 
1971       if (isOpenMPTargetExecutionDirective(DKind) &&
1972           !Stack->isLoopControlVariable(FD).first &&
1973           !Stack->checkMappableExprComponentListsForDecl(
1974               FD, /*CurrentRegionOnly=*/true,
1975               [](OMPClauseMappableExprCommon::MappableExprComponentListRef
1976                      StackComponents,
1977                  OpenMPClauseKind) {
1978                 return isa<CXXThisExpr>(
1979                     cast<MemberExpr>(
1980                         StackComponents.back().getAssociatedExpression())
1981                         ->getBase()
1982                         ->IgnoreParens());
1983               })) {
1984         // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C/C++, p.3]
1985         //  A bit-field cannot appear in a map clause.
1986         //
1987         if (FD->isBitField())
1988           return;
1989         ImplicitMap.emplace_back(E);
1990         return;
1991       }
1992 
1993       auto ELoc = E->getExprLoc();
1994       // OpenMP [2.9.3.6, Restrictions, p.2]
1995       //  A list item that appears in a reduction clause of the innermost
1996       //  enclosing worksharing or parallel construct may not be accessed in
1997       //  an  explicit task.
1998       DVar = Stack->hasInnermostDSA(
1999           FD, [](OpenMPClauseKind C) -> bool { return C == OMPC_reduction; },
2000           [](OpenMPDirectiveKind K) -> bool {
2001             return isOpenMPParallelDirective(K) ||
2002                    isOpenMPWorksharingDirective(K) || isOpenMPTeamsDirective(K);
2003           },
2004           /*FromParent=*/true);
2005       if (isOpenMPTaskingDirective(DKind) && DVar.CKind == OMPC_reduction) {
2006         ErrorFound = true;
2007         SemaRef.Diag(ELoc, diag::err_omp_reduction_in_task);
2008         ReportOriginalDSA(SemaRef, Stack, FD, DVar);
2009         return;
2010       }
2011 
2012       // Define implicit data-sharing attributes for task.
2013       DVar = Stack->getImplicitDSA(FD, false);
2014       if (isOpenMPTaskingDirective(DKind) && DVar.CKind != OMPC_shared &&
2015           !Stack->isLoopControlVariable(FD).first)
2016         ImplicitFirstprivate.push_back(E);
2017       return;
2018     }
2019     if (isOpenMPTargetExecutionDirective(DKind)) {
2020       OMPClauseMappableExprCommon::MappableExprComponentList CurComponents;
2021       if (!CheckMapClauseExpressionBase(SemaRef, E, CurComponents, OMPC_map,
2022                                         /*NoDiagnose=*/true))
2023         return;
2024       auto *VD = cast<ValueDecl>(
2025           CurComponents.back().getAssociatedDeclaration()->getCanonicalDecl());
2026       if (!Stack->checkMappableExprComponentListsForDecl(
2027               VD, /*CurrentRegionOnly=*/true,
2028               [&CurComponents](
2029                   OMPClauseMappableExprCommon::MappableExprComponentListRef
2030                       StackComponents,
2031                   OpenMPClauseKind) {
2032                 auto CCI = CurComponents.rbegin();
2033                 auto CCE = CurComponents.rend();
2034                 for (const auto &SC : llvm::reverse(StackComponents)) {
2035                   // Do both expressions have the same kind?
2036                   if (CCI->getAssociatedExpression()->getStmtClass() !=
2037                       SC.getAssociatedExpression()->getStmtClass())
2038                     if (!(isa<OMPArraySectionExpr>(
2039                               SC.getAssociatedExpression()) &&
2040                           isa<ArraySubscriptExpr>(
2041                               CCI->getAssociatedExpression())))
2042                       return false;
2043 
2044                   Decl *CCD = CCI->getAssociatedDeclaration();
2045                   Decl *SCD = SC.getAssociatedDeclaration();
2046                   CCD = CCD ? CCD->getCanonicalDecl() : nullptr;
2047                   SCD = SCD ? SCD->getCanonicalDecl() : nullptr;
2048                   if (SCD != CCD)
2049                     return false;
2050                   std::advance(CCI, 1);
2051                   if (CCI == CCE)
2052                     break;
2053                 }
2054                 return true;
2055               })) {
2056         Visit(E->getBase());
2057       }
2058     } else
2059       Visit(E->getBase());
2060   }
2061   void VisitOMPExecutableDirective(OMPExecutableDirective *S) {
2062     for (auto *C : S->clauses()) {
2063       // Skip analysis of arguments of implicitly defined firstprivate clause
2064       // for task|target directives.
2065       // Skip analysis of arguments of implicitly defined map clause for target
2066       // directives.
2067       if (C && !((isa<OMPFirstprivateClause>(C) || isa<OMPMapClause>(C)) &&
2068                  C->isImplicit())) {
2069         for (auto *CC : C->children()) {
2070           if (CC)
2071             Visit(CC);
2072         }
2073       }
2074     }
2075   }
2076   void VisitStmt(Stmt *S) {
2077     for (auto *C : S->children()) {
2078       if (C && !isa<OMPExecutableDirective>(C))
2079         Visit(C);
2080     }
2081   }
2082 
2083   bool isErrorFound() { return ErrorFound; }
2084   ArrayRef<Expr *> getImplicitFirstprivate() const {
2085     return ImplicitFirstprivate;
2086   }
2087   ArrayRef<Expr *> getImplicitMap() const { return ImplicitMap; }
2088   llvm::DenseMap<ValueDecl *, Expr *> &getVarsWithInheritedDSA() {
2089     return VarsWithInheritedDSA;
2090   }
2091 
2092   DSAAttrChecker(DSAStackTy *S, Sema &SemaRef, CapturedStmt *CS)
2093       : Stack(S), SemaRef(SemaRef), ErrorFound(false), CS(CS) {}
2094 };
2095 } // namespace
2096 
2097 void Sema::ActOnOpenMPRegionStart(OpenMPDirectiveKind DKind, Scope *CurScope) {
2098   switch (DKind) {
2099   case OMPD_parallel:
2100   case OMPD_parallel_for:
2101   case OMPD_parallel_for_simd:
2102   case OMPD_parallel_sections:
2103   case OMPD_teams:
2104   case OMPD_teams_distribute:
2105   case OMPD_teams_distribute_simd: {
2106     QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1);
2107     QualType KmpInt32PtrTy =
2108         Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
2109     Sema::CapturedParamNameType Params[] = {
2110         std::make_pair(".global_tid.", KmpInt32PtrTy),
2111         std::make_pair(".bound_tid.", KmpInt32PtrTy),
2112         std::make_pair(StringRef(), QualType()) // __context with shared vars
2113     };
2114     ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
2115                              Params);
2116     break;
2117   }
2118   case OMPD_target_teams:
2119   case OMPD_target_parallel:
2120   case OMPD_target_parallel_for:
2121   case OMPD_target_parallel_for_simd:
2122   case OMPD_target_teams_distribute:
2123   case OMPD_target_teams_distribute_simd: {
2124     QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1);
2125     QualType Args[] = {Context.VoidPtrTy.withConst().withRestrict()};
2126     FunctionProtoType::ExtProtoInfo EPI;
2127     EPI.Variadic = true;
2128     QualType CopyFnType = Context.getFunctionType(Context.VoidTy, Args, EPI);
2129     Sema::CapturedParamNameType Params[] = {
2130         std::make_pair(".global_tid.", KmpInt32Ty),
2131         std::make_pair(".part_id.", Context.getPointerType(KmpInt32Ty)),
2132         std::make_pair(".privates.", Context.VoidPtrTy.withConst()),
2133         std::make_pair(".copy_fn.",
2134                        Context.getPointerType(CopyFnType).withConst()),
2135         std::make_pair(".task_t.", Context.VoidPtrTy.withConst()),
2136         std::make_pair(StringRef(), QualType()) // __context with shared vars
2137     };
2138     ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
2139                              Params);
2140     Sema::CapturedParamNameType ParamsTarget[] = {
2141         std::make_pair(StringRef(), QualType()) // __context with shared vars
2142     };
2143     // Start a captured region for 'target' with no implicit parameters.
2144     ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
2145                              ParamsTarget);
2146     QualType KmpInt32PtrTy =
2147         Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
2148     Sema::CapturedParamNameType ParamsTeamsOrParallel[] = {
2149         std::make_pair(".global_tid.", KmpInt32PtrTy),
2150         std::make_pair(".bound_tid.", KmpInt32PtrTy),
2151         std::make_pair(StringRef(), QualType()) // __context with shared vars
2152     };
2153     // Start a captured region for 'teams' or 'parallel'.  Both regions have
2154     // the same implicit parameters.
2155     ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
2156                              ParamsTeamsOrParallel);
2157     break;
2158   }
2159   case OMPD_target:
2160   case OMPD_target_simd: {
2161     QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1);
2162     QualType Args[] = {Context.VoidPtrTy.withConst().withRestrict()};
2163     FunctionProtoType::ExtProtoInfo EPI;
2164     EPI.Variadic = true;
2165     QualType CopyFnType = Context.getFunctionType(Context.VoidTy, Args, EPI);
2166     Sema::CapturedParamNameType Params[] = {
2167         std::make_pair(".global_tid.", KmpInt32Ty),
2168         std::make_pair(".part_id.", Context.getPointerType(KmpInt32Ty)),
2169         std::make_pair(".privates.", Context.VoidPtrTy.withConst()),
2170         std::make_pair(".copy_fn.",
2171                        Context.getPointerType(CopyFnType).withConst()),
2172         std::make_pair(".task_t.", Context.VoidPtrTy.withConst()),
2173         std::make_pair(StringRef(), QualType()) // __context with shared vars
2174     };
2175     ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
2176                              Params);
2177     // Mark this captured region as inlined, because we don't use outlined
2178     // function directly.
2179     getCurCapturedRegion()->TheCapturedDecl->addAttr(
2180         AlwaysInlineAttr::CreateImplicit(
2181             Context, AlwaysInlineAttr::Keyword_forceinline, SourceRange()));
2182     ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
2183                              std::make_pair(StringRef(), QualType()));
2184     break;
2185   }
2186   case OMPD_simd:
2187   case OMPD_for:
2188   case OMPD_for_simd:
2189   case OMPD_sections:
2190   case OMPD_section:
2191   case OMPD_single:
2192   case OMPD_master:
2193   case OMPD_critical:
2194   case OMPD_taskgroup:
2195   case OMPD_distribute:
2196   case OMPD_distribute_simd:
2197   case OMPD_ordered:
2198   case OMPD_atomic:
2199   case OMPD_target_data: {
2200     Sema::CapturedParamNameType Params[] = {
2201         std::make_pair(StringRef(), QualType()) // __context with shared vars
2202     };
2203     ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
2204                              Params);
2205     break;
2206   }
2207   case OMPD_task: {
2208     QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1);
2209     QualType Args[] = {Context.VoidPtrTy.withConst().withRestrict()};
2210     FunctionProtoType::ExtProtoInfo EPI;
2211     EPI.Variadic = true;
2212     QualType CopyFnType = Context.getFunctionType(Context.VoidTy, Args, EPI);
2213     Sema::CapturedParamNameType Params[] = {
2214         std::make_pair(".global_tid.", KmpInt32Ty),
2215         std::make_pair(".part_id.", Context.getPointerType(KmpInt32Ty)),
2216         std::make_pair(".privates.", Context.VoidPtrTy.withConst()),
2217         std::make_pair(".copy_fn.",
2218                        Context.getPointerType(CopyFnType).withConst()),
2219         std::make_pair(".task_t.", Context.VoidPtrTy.withConst()),
2220         std::make_pair(StringRef(), QualType()) // __context with shared vars
2221     };
2222     ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
2223                              Params);
2224     // Mark this captured region as inlined, because we don't use outlined
2225     // function directly.
2226     getCurCapturedRegion()->TheCapturedDecl->addAttr(
2227         AlwaysInlineAttr::CreateImplicit(
2228             Context, AlwaysInlineAttr::Keyword_forceinline, SourceRange()));
2229     break;
2230   }
2231   case OMPD_taskloop:
2232   case OMPD_taskloop_simd: {
2233     QualType KmpInt32Ty =
2234         Context.getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/1);
2235     QualType KmpUInt64Ty =
2236         Context.getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/0);
2237     QualType KmpInt64Ty =
2238         Context.getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/1);
2239     QualType Args[] = {Context.VoidPtrTy.withConst().withRestrict()};
2240     FunctionProtoType::ExtProtoInfo EPI;
2241     EPI.Variadic = true;
2242     QualType CopyFnType = Context.getFunctionType(Context.VoidTy, Args, EPI);
2243     Sema::CapturedParamNameType Params[] = {
2244         std::make_pair(".global_tid.", KmpInt32Ty),
2245         std::make_pair(".part_id.", Context.getPointerType(KmpInt32Ty)),
2246         std::make_pair(".privates.",
2247                        Context.VoidPtrTy.withConst().withRestrict()),
2248         std::make_pair(
2249             ".copy_fn.",
2250             Context.getPointerType(CopyFnType).withConst().withRestrict()),
2251         std::make_pair(".task_t.", Context.VoidPtrTy.withConst()),
2252         std::make_pair(".lb.", KmpUInt64Ty),
2253         std::make_pair(".ub.", KmpUInt64Ty), std::make_pair(".st.", KmpInt64Ty),
2254         std::make_pair(".liter.", KmpInt32Ty),
2255         std::make_pair(".reductions.",
2256                        Context.VoidPtrTy.withConst().withRestrict()),
2257         std::make_pair(StringRef(), QualType()) // __context with shared vars
2258     };
2259     ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
2260                              Params);
2261     // Mark this captured region as inlined, because we don't use outlined
2262     // function directly.
2263     getCurCapturedRegion()->TheCapturedDecl->addAttr(
2264         AlwaysInlineAttr::CreateImplicit(
2265             Context, AlwaysInlineAttr::Keyword_forceinline, SourceRange()));
2266     break;
2267   }
2268   case OMPD_distribute_parallel_for_simd:
2269   case OMPD_distribute_parallel_for:
2270   case OMPD_target_teams_distribute_parallel_for_simd: {
2271     QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1);
2272     QualType KmpInt32PtrTy =
2273         Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
2274     Sema::CapturedParamNameType Params[] = {
2275         std::make_pair(".global_tid.", KmpInt32PtrTy),
2276         std::make_pair(".bound_tid.", KmpInt32PtrTy),
2277         std::make_pair(".previous.lb.", Context.getSizeType()),
2278         std::make_pair(".previous.ub.", Context.getSizeType()),
2279         std::make_pair(StringRef(), QualType()) // __context with shared vars
2280     };
2281     ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
2282                              Params);
2283     break;
2284   }
2285   case OMPD_target_teams_distribute_parallel_for: {
2286     QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1);
2287     QualType KmpInt32PtrTy =
2288         Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
2289 
2290     QualType Args[] = {Context.VoidPtrTy.withConst().withRestrict()};
2291     FunctionProtoType::ExtProtoInfo EPI;
2292     EPI.Variadic = true;
2293     QualType CopyFnType = Context.getFunctionType(Context.VoidTy, Args, EPI);
2294     Sema::CapturedParamNameType Params[] = {
2295         std::make_pair(".global_tid.", KmpInt32Ty),
2296         std::make_pair(".part_id.", Context.getPointerType(KmpInt32Ty)),
2297         std::make_pair(".privates.", Context.VoidPtrTy.withConst()),
2298         std::make_pair(".copy_fn.",
2299                        Context.getPointerType(CopyFnType).withConst()),
2300         std::make_pair(".task_t.", Context.VoidPtrTy.withConst()),
2301         std::make_pair(StringRef(), QualType()) // __context with shared vars
2302     };
2303     ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
2304                              Params);
2305     Sema::CapturedParamNameType ParamsTarget[] = {
2306         std::make_pair(StringRef(), QualType()) // __context with shared vars
2307     };
2308     // Start a captured region for 'target' with no implicit parameters.
2309     ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
2310                              ParamsTarget);
2311 
2312     Sema::CapturedParamNameType ParamsTeams[] = {
2313         std::make_pair(".global_tid.", KmpInt32PtrTy),
2314         std::make_pair(".bound_tid.", KmpInt32PtrTy),
2315         std::make_pair(StringRef(), QualType()) // __context with shared vars
2316     };
2317     // Start a captured region for 'target' with no implicit parameters.
2318     ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
2319                              ParamsTeams);
2320 
2321     Sema::CapturedParamNameType ParamsParallel[] = {
2322         std::make_pair(".global_tid.", KmpInt32PtrTy),
2323         std::make_pair(".bound_tid.", KmpInt32PtrTy),
2324         std::make_pair(".previous.lb.", Context.getSizeType()),
2325         std::make_pair(".previous.ub.", Context.getSizeType()),
2326         std::make_pair(StringRef(), QualType()) // __context with shared vars
2327     };
2328     // Start a captured region for 'teams' or 'parallel'.  Both regions have
2329     // the same implicit parameters.
2330     ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
2331                              ParamsParallel);
2332     break;
2333   }
2334 
2335   case OMPD_teams_distribute_parallel_for:
2336   case OMPD_teams_distribute_parallel_for_simd: {
2337     QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1);
2338     QualType KmpInt32PtrTy =
2339         Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
2340 
2341     Sema::CapturedParamNameType ParamsTeams[] = {
2342         std::make_pair(".global_tid.", KmpInt32PtrTy),
2343         std::make_pair(".bound_tid.", KmpInt32PtrTy),
2344         std::make_pair(StringRef(), QualType()) // __context with shared vars
2345     };
2346     // Start a captured region for 'target' with no implicit parameters.
2347     ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
2348                              ParamsTeams);
2349 
2350     Sema::CapturedParamNameType ParamsParallel[] = {
2351         std::make_pair(".global_tid.", KmpInt32PtrTy),
2352         std::make_pair(".bound_tid.", KmpInt32PtrTy),
2353         std::make_pair(".previous.lb.", Context.getSizeType()),
2354         std::make_pair(".previous.ub.", Context.getSizeType()),
2355         std::make_pair(StringRef(), QualType()) // __context with shared vars
2356     };
2357     // Start a captured region for 'teams' or 'parallel'.  Both regions have
2358     // the same implicit parameters.
2359     ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
2360                              ParamsParallel);
2361     break;
2362   }
2363   case OMPD_target_update:
2364   case OMPD_target_enter_data:
2365   case OMPD_target_exit_data: {
2366     QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1);
2367     QualType Args[] = {Context.VoidPtrTy.withConst().withRestrict()};
2368     FunctionProtoType::ExtProtoInfo EPI;
2369     EPI.Variadic = true;
2370     QualType CopyFnType = Context.getFunctionType(Context.VoidTy, Args, EPI);
2371     Sema::CapturedParamNameType Params[] = {
2372         std::make_pair(".global_tid.", KmpInt32Ty),
2373         std::make_pair(".part_id.", Context.getPointerType(KmpInt32Ty)),
2374         std::make_pair(".privates.", Context.VoidPtrTy.withConst()),
2375         std::make_pair(".copy_fn.",
2376                        Context.getPointerType(CopyFnType).withConst()),
2377         std::make_pair(".task_t.", Context.VoidPtrTy.withConst()),
2378         std::make_pair(StringRef(), QualType()) // __context with shared vars
2379     };
2380     ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
2381                              Params);
2382     // Mark this captured region as inlined, because we don't use outlined
2383     // function directly.
2384     getCurCapturedRegion()->TheCapturedDecl->addAttr(
2385         AlwaysInlineAttr::CreateImplicit(
2386             Context, AlwaysInlineAttr::Keyword_forceinline, SourceRange()));
2387     break;
2388   }
2389   case OMPD_threadprivate:
2390   case OMPD_taskyield:
2391   case OMPD_barrier:
2392   case OMPD_taskwait:
2393   case OMPD_cancellation_point:
2394   case OMPD_cancel:
2395   case OMPD_flush:
2396   case OMPD_declare_reduction:
2397   case OMPD_declare_simd:
2398   case OMPD_declare_target:
2399   case OMPD_end_declare_target:
2400     llvm_unreachable("OpenMP Directive is not allowed");
2401   case OMPD_unknown:
2402     llvm_unreachable("Unknown OpenMP directive");
2403   }
2404 }
2405 
2406 int Sema::getOpenMPCaptureLevels(OpenMPDirectiveKind DKind) {
2407   SmallVector<OpenMPDirectiveKind, 4> CaptureRegions;
2408   getOpenMPCaptureRegions(CaptureRegions, DKind);
2409   return CaptureRegions.size();
2410 }
2411 
2412 static OMPCapturedExprDecl *buildCaptureDecl(Sema &S, IdentifierInfo *Id,
2413                                              Expr *CaptureExpr, bool WithInit,
2414                                              bool AsExpression) {
2415   assert(CaptureExpr);
2416   ASTContext &C = S.getASTContext();
2417   Expr *Init = AsExpression ? CaptureExpr : CaptureExpr->IgnoreImpCasts();
2418   QualType Ty = Init->getType();
2419   if (CaptureExpr->getObjectKind() == OK_Ordinary && CaptureExpr->isGLValue()) {
2420     if (S.getLangOpts().CPlusPlus) {
2421       Ty = C.getLValueReferenceType(Ty);
2422     } else {
2423       Ty = C.getPointerType(Ty);
2424       ExprResult Res =
2425           S.CreateBuiltinUnaryOp(CaptureExpr->getExprLoc(), UO_AddrOf, Init);
2426       if (!Res.isUsable())
2427         return nullptr;
2428       Init = Res.get();
2429     }
2430     WithInit = true;
2431   }
2432   auto *CED = OMPCapturedExprDecl::Create(C, S.CurContext, Id, Ty,
2433                                           CaptureExpr->getLocStart());
2434   if (!WithInit)
2435     CED->addAttr(OMPCaptureNoInitAttr::CreateImplicit(C, SourceRange()));
2436   S.CurContext->addHiddenDecl(CED);
2437   S.AddInitializerToDecl(CED, Init, /*DirectInit=*/false);
2438   return CED;
2439 }
2440 
2441 static DeclRefExpr *buildCapture(Sema &S, ValueDecl *D, Expr *CaptureExpr,
2442                                  bool WithInit) {
2443   OMPCapturedExprDecl *CD;
2444   if (auto *VD = S.IsOpenMPCapturedDecl(D)) {
2445     CD = cast<OMPCapturedExprDecl>(VD);
2446   } else {
2447     CD = buildCaptureDecl(S, D->getIdentifier(), CaptureExpr, WithInit,
2448                           /*AsExpression=*/false);
2449   }
2450   return buildDeclRefExpr(S, CD, CD->getType().getNonReferenceType(),
2451                           CaptureExpr->getExprLoc());
2452 }
2453 
2454 static ExprResult buildCapture(Sema &S, Expr *CaptureExpr, DeclRefExpr *&Ref) {
2455   CaptureExpr = S.DefaultLvalueConversion(CaptureExpr).get();
2456   if (!Ref) {
2457     OMPCapturedExprDecl *CD = buildCaptureDecl(
2458         S, &S.getASTContext().Idents.get(".capture_expr."), CaptureExpr,
2459         /*WithInit=*/true, /*AsExpression=*/true);
2460     Ref = buildDeclRefExpr(S, CD, CD->getType().getNonReferenceType(),
2461                            CaptureExpr->getExprLoc());
2462   }
2463   ExprResult Res = Ref;
2464   if (!S.getLangOpts().CPlusPlus &&
2465       CaptureExpr->getObjectKind() == OK_Ordinary && CaptureExpr->isGLValue() &&
2466       Ref->getType()->isPointerType()) {
2467     Res = S.CreateBuiltinUnaryOp(CaptureExpr->getExprLoc(), UO_Deref, Ref);
2468     if (!Res.isUsable())
2469       return ExprError();
2470   }
2471   return S.DefaultLvalueConversion(Res.get());
2472 }
2473 
2474 namespace {
2475 // OpenMP directives parsed in this section are represented as a
2476 // CapturedStatement with an associated statement.  If a syntax error
2477 // is detected during the parsing of the associated statement, the
2478 // compiler must abort processing and close the CapturedStatement.
2479 //
2480 // Combined directives such as 'target parallel' have more than one
2481 // nested CapturedStatements.  This RAII ensures that we unwind out
2482 // of all the nested CapturedStatements when an error is found.
2483 class CaptureRegionUnwinderRAII {
2484 private:
2485   Sema &S;
2486   bool &ErrorFound;
2487   OpenMPDirectiveKind DKind;
2488 
2489 public:
2490   CaptureRegionUnwinderRAII(Sema &S, bool &ErrorFound,
2491                             OpenMPDirectiveKind DKind)
2492       : S(S), ErrorFound(ErrorFound), DKind(DKind) {}
2493   ~CaptureRegionUnwinderRAII() {
2494     if (ErrorFound) {
2495       int ThisCaptureLevel = S.getOpenMPCaptureLevels(DKind);
2496       while (--ThisCaptureLevel >= 0)
2497         S.ActOnCapturedRegionError();
2498     }
2499   }
2500 };
2501 } // namespace
2502 
2503 StmtResult Sema::ActOnOpenMPRegionEnd(StmtResult S,
2504                                       ArrayRef<OMPClause *> Clauses) {
2505   bool ErrorFound = false;
2506   CaptureRegionUnwinderRAII CaptureRegionUnwinder(
2507       *this, ErrorFound, DSAStack->getCurrentDirective());
2508   if (!S.isUsable()) {
2509     ErrorFound = true;
2510     return StmtError();
2511   }
2512 
2513   SmallVector<OpenMPDirectiveKind, 4> CaptureRegions;
2514   getOpenMPCaptureRegions(CaptureRegions, DSAStack->getCurrentDirective());
2515   OMPOrderedClause *OC = nullptr;
2516   OMPScheduleClause *SC = nullptr;
2517   SmallVector<OMPLinearClause *, 4> LCs;
2518   SmallVector<OMPClauseWithPreInit *, 8> PICs;
2519   // This is required for proper codegen.
2520   for (auto *Clause : Clauses) {
2521     if (isOpenMPTaskingDirective(DSAStack->getCurrentDirective()) &&
2522         Clause->getClauseKind() == OMPC_in_reduction) {
2523       // Capture taskgroup task_reduction descriptors inside the tasking regions
2524       // with the corresponding in_reduction items.
2525       auto *IRC = cast<OMPInReductionClause>(Clause);
2526       for (auto *E : IRC->taskgroup_descriptors())
2527         if (E)
2528           MarkDeclarationsReferencedInExpr(E);
2529     }
2530     if (isOpenMPPrivate(Clause->getClauseKind()) ||
2531         Clause->getClauseKind() == OMPC_copyprivate ||
2532         (getLangOpts().OpenMPUseTLS &&
2533          getASTContext().getTargetInfo().isTLSSupported() &&
2534          Clause->getClauseKind() == OMPC_copyin)) {
2535       DSAStack->setForceVarCapturing(Clause->getClauseKind() == OMPC_copyin);
2536       // Mark all variables in private list clauses as used in inner region.
2537       for (auto *VarRef : Clause->children()) {
2538         if (auto *E = cast_or_null<Expr>(VarRef)) {
2539           MarkDeclarationsReferencedInExpr(E);
2540         }
2541       }
2542       DSAStack->setForceVarCapturing(/*V=*/false);
2543     } else if (CaptureRegions.size() > 1 ||
2544                CaptureRegions.back() != OMPD_unknown) {
2545       if (auto *C = OMPClauseWithPreInit::get(Clause))
2546         PICs.push_back(C);
2547       if (auto *C = OMPClauseWithPostUpdate::get(Clause)) {
2548         if (auto *E = C->getPostUpdateExpr())
2549           MarkDeclarationsReferencedInExpr(E);
2550       }
2551     }
2552     if (Clause->getClauseKind() == OMPC_schedule)
2553       SC = cast<OMPScheduleClause>(Clause);
2554     else if (Clause->getClauseKind() == OMPC_ordered)
2555       OC = cast<OMPOrderedClause>(Clause);
2556     else if (Clause->getClauseKind() == OMPC_linear)
2557       LCs.push_back(cast<OMPLinearClause>(Clause));
2558   }
2559   // OpenMP, 2.7.1 Loop Construct, Restrictions
2560   // The nonmonotonic modifier cannot be specified if an ordered clause is
2561   // specified.
2562   if (SC &&
2563       (SC->getFirstScheduleModifier() == OMPC_SCHEDULE_MODIFIER_nonmonotonic ||
2564        SC->getSecondScheduleModifier() ==
2565            OMPC_SCHEDULE_MODIFIER_nonmonotonic) &&
2566       OC) {
2567     Diag(SC->getFirstScheduleModifier() == OMPC_SCHEDULE_MODIFIER_nonmonotonic
2568              ? SC->getFirstScheduleModifierLoc()
2569              : SC->getSecondScheduleModifierLoc(),
2570          diag::err_omp_schedule_nonmonotonic_ordered)
2571         << SourceRange(OC->getLocStart(), OC->getLocEnd());
2572     ErrorFound = true;
2573   }
2574   if (!LCs.empty() && OC && OC->getNumForLoops()) {
2575     for (auto *C : LCs) {
2576       Diag(C->getLocStart(), diag::err_omp_linear_ordered)
2577           << SourceRange(OC->getLocStart(), OC->getLocEnd());
2578     }
2579     ErrorFound = true;
2580   }
2581   if (isOpenMPWorksharingDirective(DSAStack->getCurrentDirective()) &&
2582       isOpenMPSimdDirective(DSAStack->getCurrentDirective()) && OC &&
2583       OC->getNumForLoops()) {
2584     Diag(OC->getLocStart(), diag::err_omp_ordered_simd)
2585         << getOpenMPDirectiveName(DSAStack->getCurrentDirective());
2586     ErrorFound = true;
2587   }
2588   if (ErrorFound) {
2589     return StmtError();
2590   }
2591   StmtResult SR = S;
2592   for (OpenMPDirectiveKind ThisCaptureRegion : llvm::reverse(CaptureRegions)) {
2593     // Mark all variables in private list clauses as used in inner region.
2594     // Required for proper codegen of combined directives.
2595     // TODO: add processing for other clauses.
2596     if (ThisCaptureRegion != OMPD_unknown) {
2597       for (auto *C : PICs) {
2598         OpenMPDirectiveKind CaptureRegion = C->getCaptureRegion();
2599         // Find the particular capture region for the clause if the
2600         // directive is a combined one with multiple capture regions.
2601         // If the directive is not a combined one, the capture region
2602         // associated with the clause is OMPD_unknown and is generated
2603         // only once.
2604         if (CaptureRegion == ThisCaptureRegion ||
2605             CaptureRegion == OMPD_unknown) {
2606           if (auto *DS = cast_or_null<DeclStmt>(C->getPreInitStmt())) {
2607             for (auto *D : DS->decls())
2608               MarkVariableReferenced(D->getLocation(), cast<VarDecl>(D));
2609           }
2610         }
2611       }
2612     }
2613     SR = ActOnCapturedRegionEnd(SR.get());
2614   }
2615   return SR;
2616 }
2617 
2618 static bool checkCancelRegion(Sema &SemaRef, OpenMPDirectiveKind CurrentRegion,
2619                               OpenMPDirectiveKind CancelRegion,
2620                               SourceLocation StartLoc) {
2621   // CancelRegion is only needed for cancel and cancellation_point.
2622   if (CurrentRegion != OMPD_cancel && CurrentRegion != OMPD_cancellation_point)
2623     return false;
2624 
2625   if (CancelRegion == OMPD_parallel || CancelRegion == OMPD_for ||
2626       CancelRegion == OMPD_sections || CancelRegion == OMPD_taskgroup)
2627     return false;
2628 
2629   SemaRef.Diag(StartLoc, diag::err_omp_wrong_cancel_region)
2630       << getOpenMPDirectiveName(CancelRegion);
2631   return true;
2632 }
2633 
2634 static bool checkNestingOfRegions(Sema &SemaRef, DSAStackTy *Stack,
2635                                   OpenMPDirectiveKind CurrentRegion,
2636                                   const DeclarationNameInfo &CurrentName,
2637                                   OpenMPDirectiveKind CancelRegion,
2638                                   SourceLocation StartLoc) {
2639   if (Stack->getCurScope()) {
2640     auto ParentRegion = Stack->getParentDirective();
2641     auto OffendingRegion = ParentRegion;
2642     bool NestingProhibited = false;
2643     bool CloseNesting = true;
2644     bool OrphanSeen = false;
2645     enum {
2646       NoRecommend,
2647       ShouldBeInParallelRegion,
2648       ShouldBeInOrderedRegion,
2649       ShouldBeInTargetRegion,
2650       ShouldBeInTeamsRegion
2651     } Recommend = NoRecommend;
2652     if (isOpenMPSimdDirective(ParentRegion) && CurrentRegion != OMPD_ordered) {
2653       // OpenMP [2.16, Nesting of Regions]
2654       // OpenMP constructs may not be nested inside a simd region.
2655       // OpenMP [2.8.1,simd Construct, Restrictions]
2656       // An ordered construct with the simd clause is the only OpenMP
2657       // construct that can appear in the simd region.
2658       // Allowing a SIMD construct nested in another SIMD construct is an
2659       // extension. The OpenMP 4.5 spec does not allow it. Issue a warning
2660       // message.
2661       SemaRef.Diag(StartLoc, (CurrentRegion != OMPD_simd)
2662                                  ? diag::err_omp_prohibited_region_simd
2663                                  : diag::warn_omp_nesting_simd);
2664       return CurrentRegion != OMPD_simd;
2665     }
2666     if (ParentRegion == OMPD_atomic) {
2667       // OpenMP [2.16, Nesting of Regions]
2668       // OpenMP constructs may not be nested inside an atomic region.
2669       SemaRef.Diag(StartLoc, diag::err_omp_prohibited_region_atomic);
2670       return true;
2671     }
2672     if (CurrentRegion == OMPD_section) {
2673       // OpenMP [2.7.2, sections Construct, Restrictions]
2674       // Orphaned section directives are prohibited. That is, the section
2675       // directives must appear within the sections construct and must not be
2676       // encountered elsewhere in the sections region.
2677       if (ParentRegion != OMPD_sections &&
2678           ParentRegion != OMPD_parallel_sections) {
2679         SemaRef.Diag(StartLoc, diag::err_omp_orphaned_section_directive)
2680             << (ParentRegion != OMPD_unknown)
2681             << getOpenMPDirectiveName(ParentRegion);
2682         return true;
2683       }
2684       return false;
2685     }
2686     // Allow some constructs (except teams) to be orphaned (they could be
2687     // used in functions, called from OpenMP regions with the required
2688     // preconditions).
2689     if (ParentRegion == OMPD_unknown &&
2690         !isOpenMPNestingTeamsDirective(CurrentRegion))
2691       return false;
2692     if (CurrentRegion == OMPD_cancellation_point ||
2693         CurrentRegion == OMPD_cancel) {
2694       // OpenMP [2.16, Nesting of Regions]
2695       // A cancellation point construct for which construct-type-clause is
2696       // taskgroup must be nested inside a task construct. A cancellation
2697       // point construct for which construct-type-clause is not taskgroup must
2698       // be closely nested inside an OpenMP construct that matches the type
2699       // specified in construct-type-clause.
2700       // A cancel construct for which construct-type-clause is taskgroup must be
2701       // nested inside a task construct. A cancel construct for which
2702       // construct-type-clause is not taskgroup must be closely nested inside an
2703       // OpenMP construct that matches the type specified in
2704       // construct-type-clause.
2705       NestingProhibited =
2706           !((CancelRegion == OMPD_parallel &&
2707              (ParentRegion == OMPD_parallel ||
2708               ParentRegion == OMPD_target_parallel)) ||
2709             (CancelRegion == OMPD_for &&
2710              (ParentRegion == OMPD_for || ParentRegion == OMPD_parallel_for ||
2711               ParentRegion == OMPD_target_parallel_for ||
2712               ParentRegion == OMPD_distribute_parallel_for ||
2713               ParentRegion == OMPD_teams_distribute_parallel_for ||
2714               ParentRegion == OMPD_target_teams_distribute_parallel_for)) ||
2715             (CancelRegion == OMPD_taskgroup && ParentRegion == OMPD_task) ||
2716             (CancelRegion == OMPD_sections &&
2717              (ParentRegion == OMPD_section || ParentRegion == OMPD_sections ||
2718               ParentRegion == OMPD_parallel_sections)));
2719     } else if (CurrentRegion == OMPD_master) {
2720       // OpenMP [2.16, Nesting of Regions]
2721       // A master region may not be closely nested inside a worksharing,
2722       // atomic, or explicit task region.
2723       NestingProhibited = isOpenMPWorksharingDirective(ParentRegion) ||
2724                           isOpenMPTaskingDirective(ParentRegion);
2725     } else if (CurrentRegion == OMPD_critical && CurrentName.getName()) {
2726       // OpenMP [2.16, Nesting of Regions]
2727       // A critical region may not be nested (closely or otherwise) inside a
2728       // critical region with the same name. Note that this restriction is not
2729       // sufficient to prevent deadlock.
2730       SourceLocation PreviousCriticalLoc;
2731       bool DeadLock = Stack->hasDirective(
2732           [CurrentName, &PreviousCriticalLoc](OpenMPDirectiveKind K,
2733                                               const DeclarationNameInfo &DNI,
2734                                               SourceLocation Loc) -> bool {
2735             if (K == OMPD_critical && DNI.getName() == CurrentName.getName()) {
2736               PreviousCriticalLoc = Loc;
2737               return true;
2738             } else
2739               return false;
2740           },
2741           false /* skip top directive */);
2742       if (DeadLock) {
2743         SemaRef.Diag(StartLoc,
2744                      diag::err_omp_prohibited_region_critical_same_name)
2745             << CurrentName.getName();
2746         if (PreviousCriticalLoc.isValid())
2747           SemaRef.Diag(PreviousCriticalLoc,
2748                        diag::note_omp_previous_critical_region);
2749         return true;
2750       }
2751     } else if (CurrentRegion == OMPD_barrier) {
2752       // OpenMP [2.16, Nesting of Regions]
2753       // A barrier region may not be closely nested inside a worksharing,
2754       // explicit task, critical, ordered, atomic, or master region.
2755       NestingProhibited = isOpenMPWorksharingDirective(ParentRegion) ||
2756                           isOpenMPTaskingDirective(ParentRegion) ||
2757                           ParentRegion == OMPD_master ||
2758                           ParentRegion == OMPD_critical ||
2759                           ParentRegion == OMPD_ordered;
2760     } else if (isOpenMPWorksharingDirective(CurrentRegion) &&
2761                !isOpenMPParallelDirective(CurrentRegion) &&
2762                !isOpenMPTeamsDirective(CurrentRegion)) {
2763       // OpenMP [2.16, Nesting of Regions]
2764       // A worksharing region may not be closely nested inside a worksharing,
2765       // explicit task, critical, ordered, atomic, or master region.
2766       NestingProhibited = isOpenMPWorksharingDirective(ParentRegion) ||
2767                           isOpenMPTaskingDirective(ParentRegion) ||
2768                           ParentRegion == OMPD_master ||
2769                           ParentRegion == OMPD_critical ||
2770                           ParentRegion == OMPD_ordered;
2771       Recommend = ShouldBeInParallelRegion;
2772     } else if (CurrentRegion == OMPD_ordered) {
2773       // OpenMP [2.16, Nesting of Regions]
2774       // An ordered region may not be closely nested inside a critical,
2775       // atomic, or explicit task region.
2776       // An ordered region must be closely nested inside a loop region (or
2777       // parallel loop region) with an ordered clause.
2778       // OpenMP [2.8.1,simd Construct, Restrictions]
2779       // An ordered construct with the simd clause is the only OpenMP construct
2780       // that can appear in the simd region.
2781       NestingProhibited = ParentRegion == OMPD_critical ||
2782                           isOpenMPTaskingDirective(ParentRegion) ||
2783                           !(isOpenMPSimdDirective(ParentRegion) ||
2784                             Stack->isParentOrderedRegion());
2785       Recommend = ShouldBeInOrderedRegion;
2786     } else if (isOpenMPNestingTeamsDirective(CurrentRegion)) {
2787       // OpenMP [2.16, Nesting of Regions]
2788       // If specified, a teams construct must be contained within a target
2789       // construct.
2790       NestingProhibited = ParentRegion != OMPD_target;
2791       OrphanSeen = ParentRegion == OMPD_unknown;
2792       Recommend = ShouldBeInTargetRegion;
2793     }
2794     if (!NestingProhibited &&
2795         !isOpenMPTargetExecutionDirective(CurrentRegion) &&
2796         !isOpenMPTargetDataManagementDirective(CurrentRegion) &&
2797         (ParentRegion == OMPD_teams || ParentRegion == OMPD_target_teams)) {
2798       // OpenMP [2.16, Nesting of Regions]
2799       // distribute, parallel, parallel sections, parallel workshare, and the
2800       // parallel loop and parallel loop SIMD constructs are the only OpenMP
2801       // constructs that can be closely nested in the teams region.
2802       NestingProhibited = !isOpenMPParallelDirective(CurrentRegion) &&
2803                           !isOpenMPDistributeDirective(CurrentRegion);
2804       Recommend = ShouldBeInParallelRegion;
2805     }
2806     if (!NestingProhibited &&
2807         isOpenMPNestingDistributeDirective(CurrentRegion)) {
2808       // OpenMP 4.5 [2.17 Nesting of Regions]
2809       // The region associated with the distribute construct must be strictly
2810       // nested inside a teams region
2811       NestingProhibited =
2812           (ParentRegion != OMPD_teams && ParentRegion != OMPD_target_teams);
2813       Recommend = ShouldBeInTeamsRegion;
2814     }
2815     if (!NestingProhibited &&
2816         (isOpenMPTargetExecutionDirective(CurrentRegion) ||
2817          isOpenMPTargetDataManagementDirective(CurrentRegion))) {
2818       // OpenMP 4.5 [2.17 Nesting of Regions]
2819       // If a target, target update, target data, target enter data, or
2820       // target exit data construct is encountered during execution of a
2821       // target region, the behavior is unspecified.
2822       NestingProhibited = Stack->hasDirective(
2823           [&OffendingRegion](OpenMPDirectiveKind K, const DeclarationNameInfo &,
2824                              SourceLocation) -> bool {
2825             if (isOpenMPTargetExecutionDirective(K)) {
2826               OffendingRegion = K;
2827               return true;
2828             } else
2829               return false;
2830           },
2831           false /* don't skip top directive */);
2832       CloseNesting = false;
2833     }
2834     if (NestingProhibited) {
2835       if (OrphanSeen) {
2836         SemaRef.Diag(StartLoc, diag::err_omp_orphaned_device_directive)
2837             << getOpenMPDirectiveName(CurrentRegion) << Recommend;
2838       } else {
2839         SemaRef.Diag(StartLoc, diag::err_omp_prohibited_region)
2840             << CloseNesting << getOpenMPDirectiveName(OffendingRegion)
2841             << Recommend << getOpenMPDirectiveName(CurrentRegion);
2842       }
2843       return true;
2844     }
2845   }
2846   return false;
2847 }
2848 
2849 static bool checkIfClauses(Sema &S, OpenMPDirectiveKind Kind,
2850                            ArrayRef<OMPClause *> Clauses,
2851                            ArrayRef<OpenMPDirectiveKind> AllowedNameModifiers) {
2852   bool ErrorFound = false;
2853   unsigned NamedModifiersNumber = 0;
2854   SmallVector<const OMPIfClause *, OMPC_unknown + 1> FoundNameModifiers(
2855       OMPD_unknown + 1);
2856   SmallVector<SourceLocation, 4> NameModifierLoc;
2857   for (const auto *C : Clauses) {
2858     if (const auto *IC = dyn_cast_or_null<OMPIfClause>(C)) {
2859       // At most one if clause without a directive-name-modifier can appear on
2860       // the directive.
2861       OpenMPDirectiveKind CurNM = IC->getNameModifier();
2862       if (FoundNameModifiers[CurNM]) {
2863         S.Diag(C->getLocStart(), diag::err_omp_more_one_clause)
2864             << getOpenMPDirectiveName(Kind) << getOpenMPClauseName(OMPC_if)
2865             << (CurNM != OMPD_unknown) << getOpenMPDirectiveName(CurNM);
2866         ErrorFound = true;
2867       } else if (CurNM != OMPD_unknown) {
2868         NameModifierLoc.push_back(IC->getNameModifierLoc());
2869         ++NamedModifiersNumber;
2870       }
2871       FoundNameModifiers[CurNM] = IC;
2872       if (CurNM == OMPD_unknown)
2873         continue;
2874       // Check if the specified name modifier is allowed for the current
2875       // directive.
2876       // At most one if clause with the particular directive-name-modifier can
2877       // appear on the directive.
2878       bool MatchFound = false;
2879       for (auto NM : AllowedNameModifiers) {
2880         if (CurNM == NM) {
2881           MatchFound = true;
2882           break;
2883         }
2884       }
2885       if (!MatchFound) {
2886         S.Diag(IC->getNameModifierLoc(),
2887                diag::err_omp_wrong_if_directive_name_modifier)
2888             << getOpenMPDirectiveName(CurNM) << getOpenMPDirectiveName(Kind);
2889         ErrorFound = true;
2890       }
2891     }
2892   }
2893   // If any if clause on the directive includes a directive-name-modifier then
2894   // all if clauses on the directive must include a directive-name-modifier.
2895   if (FoundNameModifiers[OMPD_unknown] && NamedModifiersNumber > 0) {
2896     if (NamedModifiersNumber == AllowedNameModifiers.size()) {
2897       S.Diag(FoundNameModifiers[OMPD_unknown]->getLocStart(),
2898              diag::err_omp_no_more_if_clause);
2899     } else {
2900       std::string Values;
2901       std::string Sep(", ");
2902       unsigned AllowedCnt = 0;
2903       unsigned TotalAllowedNum =
2904           AllowedNameModifiers.size() - NamedModifiersNumber;
2905       for (unsigned Cnt = 0, End = AllowedNameModifiers.size(); Cnt < End;
2906            ++Cnt) {
2907         OpenMPDirectiveKind NM = AllowedNameModifiers[Cnt];
2908         if (!FoundNameModifiers[NM]) {
2909           Values += "'";
2910           Values += getOpenMPDirectiveName(NM);
2911           Values += "'";
2912           if (AllowedCnt + 2 == TotalAllowedNum)
2913             Values += " or ";
2914           else if (AllowedCnt + 1 != TotalAllowedNum)
2915             Values += Sep;
2916           ++AllowedCnt;
2917         }
2918       }
2919       S.Diag(FoundNameModifiers[OMPD_unknown]->getCondition()->getLocStart(),
2920              diag::err_omp_unnamed_if_clause)
2921           << (TotalAllowedNum > 1) << Values;
2922     }
2923     for (auto Loc : NameModifierLoc) {
2924       S.Diag(Loc, diag::note_omp_previous_named_if_clause);
2925     }
2926     ErrorFound = true;
2927   }
2928   return ErrorFound;
2929 }
2930 
2931 StmtResult Sema::ActOnOpenMPExecutableDirective(
2932     OpenMPDirectiveKind Kind, const DeclarationNameInfo &DirName,
2933     OpenMPDirectiveKind CancelRegion, ArrayRef<OMPClause *> Clauses,
2934     Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc) {
2935   StmtResult Res = StmtError();
2936   // First check CancelRegion which is then used in checkNestingOfRegions.
2937   if (checkCancelRegion(*this, Kind, CancelRegion, StartLoc) ||
2938       checkNestingOfRegions(*this, DSAStack, Kind, DirName, CancelRegion,
2939                             StartLoc))
2940     return StmtError();
2941 
2942   llvm::SmallVector<OMPClause *, 8> ClausesWithImplicit;
2943   llvm::DenseMap<ValueDecl *, Expr *> VarsWithInheritedDSA;
2944   bool ErrorFound = false;
2945   ClausesWithImplicit.append(Clauses.begin(), Clauses.end());
2946   if (AStmt && !CurContext->isDependentContext()) {
2947     assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
2948 
2949     // Check default data sharing attributes for referenced variables.
2950     DSAAttrChecker DSAChecker(DSAStack, *this, cast<CapturedStmt>(AStmt));
2951     int ThisCaptureLevel = getOpenMPCaptureLevels(Kind);
2952     Stmt *S = AStmt;
2953     while (--ThisCaptureLevel >= 0)
2954       S = cast<CapturedStmt>(S)->getCapturedStmt();
2955     DSAChecker.Visit(S);
2956     if (DSAChecker.isErrorFound())
2957       return StmtError();
2958     // Generate list of implicitly defined firstprivate variables.
2959     VarsWithInheritedDSA = DSAChecker.getVarsWithInheritedDSA();
2960 
2961     SmallVector<Expr *, 4> ImplicitFirstprivates(
2962         DSAChecker.getImplicitFirstprivate().begin(),
2963         DSAChecker.getImplicitFirstprivate().end());
2964     SmallVector<Expr *, 4> ImplicitMaps(DSAChecker.getImplicitMap().begin(),
2965                                         DSAChecker.getImplicitMap().end());
2966     // Mark taskgroup task_reduction descriptors as implicitly firstprivate.
2967     for (auto *C : Clauses) {
2968       if (auto *IRC = dyn_cast<OMPInReductionClause>(C)) {
2969         for (auto *E : IRC->taskgroup_descriptors())
2970           if (E)
2971             ImplicitFirstprivates.emplace_back(E);
2972       }
2973     }
2974     if (!ImplicitFirstprivates.empty()) {
2975       if (OMPClause *Implicit = ActOnOpenMPFirstprivateClause(
2976               ImplicitFirstprivates, SourceLocation(), SourceLocation(),
2977               SourceLocation())) {
2978         ClausesWithImplicit.push_back(Implicit);
2979         ErrorFound = cast<OMPFirstprivateClause>(Implicit)->varlist_size() !=
2980                      ImplicitFirstprivates.size();
2981       } else
2982         ErrorFound = true;
2983     }
2984     if (!ImplicitMaps.empty()) {
2985       if (OMPClause *Implicit = ActOnOpenMPMapClause(
2986               OMPC_MAP_unknown, OMPC_MAP_tofrom, /*IsMapTypeImplicit=*/true,
2987               SourceLocation(), SourceLocation(), ImplicitMaps,
2988               SourceLocation(), SourceLocation(), SourceLocation())) {
2989         ClausesWithImplicit.emplace_back(Implicit);
2990         ErrorFound |=
2991             cast<OMPMapClause>(Implicit)->varlist_size() != ImplicitMaps.size();
2992       } else
2993         ErrorFound = true;
2994     }
2995   }
2996 
2997   llvm::SmallVector<OpenMPDirectiveKind, 4> AllowedNameModifiers;
2998   switch (Kind) {
2999   case OMPD_parallel:
3000     Res = ActOnOpenMPParallelDirective(ClausesWithImplicit, AStmt, StartLoc,
3001                                        EndLoc);
3002     AllowedNameModifiers.push_back(OMPD_parallel);
3003     break;
3004   case OMPD_simd:
3005     Res = ActOnOpenMPSimdDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc,
3006                                    VarsWithInheritedDSA);
3007     break;
3008   case OMPD_for:
3009     Res = ActOnOpenMPForDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc,
3010                                   VarsWithInheritedDSA);
3011     break;
3012   case OMPD_for_simd:
3013     Res = ActOnOpenMPForSimdDirective(ClausesWithImplicit, AStmt, StartLoc,
3014                                       EndLoc, VarsWithInheritedDSA);
3015     break;
3016   case OMPD_sections:
3017     Res = ActOnOpenMPSectionsDirective(ClausesWithImplicit, AStmt, StartLoc,
3018                                        EndLoc);
3019     break;
3020   case OMPD_section:
3021     assert(ClausesWithImplicit.empty() &&
3022            "No clauses are allowed for 'omp section' directive");
3023     Res = ActOnOpenMPSectionDirective(AStmt, StartLoc, EndLoc);
3024     break;
3025   case OMPD_single:
3026     Res = ActOnOpenMPSingleDirective(ClausesWithImplicit, AStmt, StartLoc,
3027                                      EndLoc);
3028     break;
3029   case OMPD_master:
3030     assert(ClausesWithImplicit.empty() &&
3031            "No clauses are allowed for 'omp master' directive");
3032     Res = ActOnOpenMPMasterDirective(AStmt, StartLoc, EndLoc);
3033     break;
3034   case OMPD_critical:
3035     Res = ActOnOpenMPCriticalDirective(DirName, ClausesWithImplicit, AStmt,
3036                                        StartLoc, EndLoc);
3037     break;
3038   case OMPD_parallel_for:
3039     Res = ActOnOpenMPParallelForDirective(ClausesWithImplicit, AStmt, StartLoc,
3040                                           EndLoc, VarsWithInheritedDSA);
3041     AllowedNameModifiers.push_back(OMPD_parallel);
3042     break;
3043   case OMPD_parallel_for_simd:
3044     Res = ActOnOpenMPParallelForSimdDirective(
3045         ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
3046     AllowedNameModifiers.push_back(OMPD_parallel);
3047     break;
3048   case OMPD_parallel_sections:
3049     Res = ActOnOpenMPParallelSectionsDirective(ClausesWithImplicit, AStmt,
3050                                                StartLoc, EndLoc);
3051     AllowedNameModifiers.push_back(OMPD_parallel);
3052     break;
3053   case OMPD_task:
3054     Res =
3055         ActOnOpenMPTaskDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc);
3056     AllowedNameModifiers.push_back(OMPD_task);
3057     break;
3058   case OMPD_taskyield:
3059     assert(ClausesWithImplicit.empty() &&
3060            "No clauses are allowed for 'omp taskyield' directive");
3061     assert(AStmt == nullptr &&
3062            "No associated statement allowed for 'omp taskyield' directive");
3063     Res = ActOnOpenMPTaskyieldDirective(StartLoc, EndLoc);
3064     break;
3065   case OMPD_barrier:
3066     assert(ClausesWithImplicit.empty() &&
3067            "No clauses are allowed for 'omp barrier' directive");
3068     assert(AStmt == nullptr &&
3069            "No associated statement allowed for 'omp barrier' directive");
3070     Res = ActOnOpenMPBarrierDirective(StartLoc, EndLoc);
3071     break;
3072   case OMPD_taskwait:
3073     assert(ClausesWithImplicit.empty() &&
3074            "No clauses are allowed for 'omp taskwait' directive");
3075     assert(AStmt == nullptr &&
3076            "No associated statement allowed for 'omp taskwait' directive");
3077     Res = ActOnOpenMPTaskwaitDirective(StartLoc, EndLoc);
3078     break;
3079   case OMPD_taskgroup:
3080     Res = ActOnOpenMPTaskgroupDirective(ClausesWithImplicit, AStmt, StartLoc,
3081                                         EndLoc);
3082     break;
3083   case OMPD_flush:
3084     assert(AStmt == nullptr &&
3085            "No associated statement allowed for 'omp flush' directive");
3086     Res = ActOnOpenMPFlushDirective(ClausesWithImplicit, StartLoc, EndLoc);
3087     break;
3088   case OMPD_ordered:
3089     Res = ActOnOpenMPOrderedDirective(ClausesWithImplicit, AStmt, StartLoc,
3090                                       EndLoc);
3091     break;
3092   case OMPD_atomic:
3093     Res = ActOnOpenMPAtomicDirective(ClausesWithImplicit, AStmt, StartLoc,
3094                                      EndLoc);
3095     break;
3096   case OMPD_teams:
3097     Res =
3098         ActOnOpenMPTeamsDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc);
3099     break;
3100   case OMPD_target:
3101     Res = ActOnOpenMPTargetDirective(ClausesWithImplicit, AStmt, StartLoc,
3102                                      EndLoc);
3103     AllowedNameModifiers.push_back(OMPD_target);
3104     break;
3105   case OMPD_target_parallel:
3106     Res = ActOnOpenMPTargetParallelDirective(ClausesWithImplicit, AStmt,
3107                                              StartLoc, EndLoc);
3108     AllowedNameModifiers.push_back(OMPD_target);
3109     AllowedNameModifiers.push_back(OMPD_parallel);
3110     break;
3111   case OMPD_target_parallel_for:
3112     Res = ActOnOpenMPTargetParallelForDirective(
3113         ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
3114     AllowedNameModifiers.push_back(OMPD_target);
3115     AllowedNameModifiers.push_back(OMPD_parallel);
3116     break;
3117   case OMPD_cancellation_point:
3118     assert(ClausesWithImplicit.empty() &&
3119            "No clauses are allowed for 'omp cancellation point' directive");
3120     assert(AStmt == nullptr && "No associated statement allowed for 'omp "
3121                                "cancellation point' directive");
3122     Res = ActOnOpenMPCancellationPointDirective(StartLoc, EndLoc, CancelRegion);
3123     break;
3124   case OMPD_cancel:
3125     assert(AStmt == nullptr &&
3126            "No associated statement allowed for 'omp cancel' directive");
3127     Res = ActOnOpenMPCancelDirective(ClausesWithImplicit, StartLoc, EndLoc,
3128                                      CancelRegion);
3129     AllowedNameModifiers.push_back(OMPD_cancel);
3130     break;
3131   case OMPD_target_data:
3132     Res = ActOnOpenMPTargetDataDirective(ClausesWithImplicit, AStmt, StartLoc,
3133                                          EndLoc);
3134     AllowedNameModifiers.push_back(OMPD_target_data);
3135     break;
3136   case OMPD_target_enter_data:
3137     Res = ActOnOpenMPTargetEnterDataDirective(ClausesWithImplicit, StartLoc,
3138                                               EndLoc, AStmt);
3139     AllowedNameModifiers.push_back(OMPD_target_enter_data);
3140     break;
3141   case OMPD_target_exit_data:
3142     Res = ActOnOpenMPTargetExitDataDirective(ClausesWithImplicit, StartLoc,
3143                                              EndLoc, AStmt);
3144     AllowedNameModifiers.push_back(OMPD_target_exit_data);
3145     break;
3146   case OMPD_taskloop:
3147     Res = ActOnOpenMPTaskLoopDirective(ClausesWithImplicit, AStmt, StartLoc,
3148                                        EndLoc, VarsWithInheritedDSA);
3149     AllowedNameModifiers.push_back(OMPD_taskloop);
3150     break;
3151   case OMPD_taskloop_simd:
3152     Res = ActOnOpenMPTaskLoopSimdDirective(ClausesWithImplicit, AStmt, StartLoc,
3153                                            EndLoc, VarsWithInheritedDSA);
3154     AllowedNameModifiers.push_back(OMPD_taskloop);
3155     break;
3156   case OMPD_distribute:
3157     Res = ActOnOpenMPDistributeDirective(ClausesWithImplicit, AStmt, StartLoc,
3158                                          EndLoc, VarsWithInheritedDSA);
3159     break;
3160   case OMPD_target_update:
3161     Res = ActOnOpenMPTargetUpdateDirective(ClausesWithImplicit, StartLoc,
3162                                            EndLoc, AStmt);
3163     AllowedNameModifiers.push_back(OMPD_target_update);
3164     break;
3165   case OMPD_distribute_parallel_for:
3166     Res = ActOnOpenMPDistributeParallelForDirective(
3167         ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
3168     AllowedNameModifiers.push_back(OMPD_parallel);
3169     break;
3170   case OMPD_distribute_parallel_for_simd:
3171     Res = ActOnOpenMPDistributeParallelForSimdDirective(
3172         ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
3173     AllowedNameModifiers.push_back(OMPD_parallel);
3174     break;
3175   case OMPD_distribute_simd:
3176     Res = ActOnOpenMPDistributeSimdDirective(
3177         ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
3178     break;
3179   case OMPD_target_parallel_for_simd:
3180     Res = ActOnOpenMPTargetParallelForSimdDirective(
3181         ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
3182     AllowedNameModifiers.push_back(OMPD_target);
3183     AllowedNameModifiers.push_back(OMPD_parallel);
3184     break;
3185   case OMPD_target_simd:
3186     Res = ActOnOpenMPTargetSimdDirective(ClausesWithImplicit, AStmt, StartLoc,
3187                                          EndLoc, VarsWithInheritedDSA);
3188     AllowedNameModifiers.push_back(OMPD_target);
3189     break;
3190   case OMPD_teams_distribute:
3191     Res = ActOnOpenMPTeamsDistributeDirective(
3192         ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
3193     break;
3194   case OMPD_teams_distribute_simd:
3195     Res = ActOnOpenMPTeamsDistributeSimdDirective(
3196         ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
3197     break;
3198   case OMPD_teams_distribute_parallel_for_simd:
3199     Res = ActOnOpenMPTeamsDistributeParallelForSimdDirective(
3200         ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
3201     AllowedNameModifiers.push_back(OMPD_parallel);
3202     break;
3203   case OMPD_teams_distribute_parallel_for:
3204     Res = ActOnOpenMPTeamsDistributeParallelForDirective(
3205         ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
3206     AllowedNameModifiers.push_back(OMPD_parallel);
3207     break;
3208   case OMPD_target_teams:
3209     Res = ActOnOpenMPTargetTeamsDirective(ClausesWithImplicit, AStmt, StartLoc,
3210                                           EndLoc);
3211     AllowedNameModifiers.push_back(OMPD_target);
3212     break;
3213   case OMPD_target_teams_distribute:
3214     Res = ActOnOpenMPTargetTeamsDistributeDirective(
3215         ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
3216     AllowedNameModifiers.push_back(OMPD_target);
3217     break;
3218   case OMPD_target_teams_distribute_parallel_for:
3219     Res = ActOnOpenMPTargetTeamsDistributeParallelForDirective(
3220         ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
3221     AllowedNameModifiers.push_back(OMPD_target);
3222     AllowedNameModifiers.push_back(OMPD_parallel);
3223     break;
3224   case OMPD_target_teams_distribute_parallel_for_simd:
3225     Res = ActOnOpenMPTargetTeamsDistributeParallelForSimdDirective(
3226         ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
3227     AllowedNameModifiers.push_back(OMPD_target);
3228     AllowedNameModifiers.push_back(OMPD_parallel);
3229     break;
3230   case OMPD_target_teams_distribute_simd:
3231     Res = ActOnOpenMPTargetTeamsDistributeSimdDirective(
3232         ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
3233     AllowedNameModifiers.push_back(OMPD_target);
3234     break;
3235   case OMPD_declare_target:
3236   case OMPD_end_declare_target:
3237   case OMPD_threadprivate:
3238   case OMPD_declare_reduction:
3239   case OMPD_declare_simd:
3240     llvm_unreachable("OpenMP Directive is not allowed");
3241   case OMPD_unknown:
3242     llvm_unreachable("Unknown OpenMP directive");
3243   }
3244 
3245   for (auto P : VarsWithInheritedDSA) {
3246     Diag(P.second->getExprLoc(), diag::err_omp_no_dsa_for_variable)
3247         << P.first << P.second->getSourceRange();
3248   }
3249   ErrorFound = !VarsWithInheritedDSA.empty() || ErrorFound;
3250 
3251   if (!AllowedNameModifiers.empty())
3252     ErrorFound = checkIfClauses(*this, Kind, Clauses, AllowedNameModifiers) ||
3253                  ErrorFound;
3254 
3255   if (ErrorFound)
3256     return StmtError();
3257   return Res;
3258 }
3259 
3260 Sema::DeclGroupPtrTy Sema::ActOnOpenMPDeclareSimdDirective(
3261     DeclGroupPtrTy DG, OMPDeclareSimdDeclAttr::BranchStateTy BS, Expr *Simdlen,
3262     ArrayRef<Expr *> Uniforms, ArrayRef<Expr *> Aligneds,
3263     ArrayRef<Expr *> Alignments, ArrayRef<Expr *> Linears,
3264     ArrayRef<unsigned> LinModifiers, ArrayRef<Expr *> Steps, SourceRange SR) {
3265   assert(Aligneds.size() == Alignments.size());
3266   assert(Linears.size() == LinModifiers.size());
3267   assert(Linears.size() == Steps.size());
3268   if (!DG || DG.get().isNull())
3269     return DeclGroupPtrTy();
3270 
3271   if (!DG.get().isSingleDecl()) {
3272     Diag(SR.getBegin(), diag::err_omp_single_decl_in_declare_simd);
3273     return DG;
3274   }
3275   auto *ADecl = DG.get().getSingleDecl();
3276   if (auto *FTD = dyn_cast<FunctionTemplateDecl>(ADecl))
3277     ADecl = FTD->getTemplatedDecl();
3278 
3279   auto *FD = dyn_cast<FunctionDecl>(ADecl);
3280   if (!FD) {
3281     Diag(ADecl->getLocation(), diag::err_omp_function_expected);
3282     return DeclGroupPtrTy();
3283   }
3284 
3285   // OpenMP [2.8.2, declare simd construct, Description]
3286   // The parameter of the simdlen clause must be a constant positive integer
3287   // expression.
3288   ExprResult SL;
3289   if (Simdlen)
3290     SL = VerifyPositiveIntegerConstantInClause(Simdlen, OMPC_simdlen);
3291   // OpenMP [2.8.2, declare simd construct, Description]
3292   // The special this pointer can be used as if was one of the arguments to the
3293   // function in any of the linear, aligned, or uniform clauses.
3294   // The uniform clause declares one or more arguments to have an invariant
3295   // value for all concurrent invocations of the function in the execution of a
3296   // single SIMD loop.
3297   llvm::DenseMap<Decl *, Expr *> UniformedArgs;
3298   Expr *UniformedLinearThis = nullptr;
3299   for (auto *E : Uniforms) {
3300     E = E->IgnoreParenImpCasts();
3301     if (auto *DRE = dyn_cast<DeclRefExpr>(E))
3302       if (auto *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl()))
3303         if (FD->getNumParams() > PVD->getFunctionScopeIndex() &&
3304             FD->getParamDecl(PVD->getFunctionScopeIndex())
3305                     ->getCanonicalDecl() == PVD->getCanonicalDecl()) {
3306           UniformedArgs.insert(std::make_pair(PVD->getCanonicalDecl(), E));
3307           continue;
3308         }
3309     if (isa<CXXThisExpr>(E)) {
3310       UniformedLinearThis = E;
3311       continue;
3312     }
3313     Diag(E->getExprLoc(), diag::err_omp_param_or_this_in_clause)
3314         << FD->getDeclName() << (isa<CXXMethodDecl>(ADecl) ? 1 : 0);
3315   }
3316   // OpenMP [2.8.2, declare simd construct, Description]
3317   // The aligned clause declares that the object to which each list item points
3318   // is aligned to the number of bytes expressed in the optional parameter of
3319   // the aligned clause.
3320   // The special this pointer can be used as if was one of the arguments to the
3321   // function in any of the linear, aligned, or uniform clauses.
3322   // The type of list items appearing in the aligned clause must be array,
3323   // pointer, reference to array, or reference to pointer.
3324   llvm::DenseMap<Decl *, Expr *> AlignedArgs;
3325   Expr *AlignedThis = nullptr;
3326   for (auto *E : Aligneds) {
3327     E = E->IgnoreParenImpCasts();
3328     if (auto *DRE = dyn_cast<DeclRefExpr>(E))
3329       if (auto *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl())) {
3330         auto *CanonPVD = PVD->getCanonicalDecl();
3331         if (FD->getNumParams() > PVD->getFunctionScopeIndex() &&
3332             FD->getParamDecl(PVD->getFunctionScopeIndex())
3333                     ->getCanonicalDecl() == CanonPVD) {
3334           // OpenMP  [2.8.1, simd construct, Restrictions]
3335           // A list-item cannot appear in more than one aligned clause.
3336           if (AlignedArgs.count(CanonPVD) > 0) {
3337             Diag(E->getExprLoc(), diag::err_omp_aligned_twice)
3338                 << 1 << E->getSourceRange();
3339             Diag(AlignedArgs[CanonPVD]->getExprLoc(),
3340                  diag::note_omp_explicit_dsa)
3341                 << getOpenMPClauseName(OMPC_aligned);
3342             continue;
3343           }
3344           AlignedArgs[CanonPVD] = E;
3345           QualType QTy = PVD->getType()
3346                              .getNonReferenceType()
3347                              .getUnqualifiedType()
3348                              .getCanonicalType();
3349           const Type *Ty = QTy.getTypePtrOrNull();
3350           if (!Ty || (!Ty->isArrayType() && !Ty->isPointerType())) {
3351             Diag(E->getExprLoc(), diag::err_omp_aligned_expected_array_or_ptr)
3352                 << QTy << getLangOpts().CPlusPlus << E->getSourceRange();
3353             Diag(PVD->getLocation(), diag::note_previous_decl) << PVD;
3354           }
3355           continue;
3356         }
3357       }
3358     if (isa<CXXThisExpr>(E)) {
3359       if (AlignedThis) {
3360         Diag(E->getExprLoc(), diag::err_omp_aligned_twice)
3361             << 2 << E->getSourceRange();
3362         Diag(AlignedThis->getExprLoc(), diag::note_omp_explicit_dsa)
3363             << getOpenMPClauseName(OMPC_aligned);
3364       }
3365       AlignedThis = E;
3366       continue;
3367     }
3368     Diag(E->getExprLoc(), diag::err_omp_param_or_this_in_clause)
3369         << FD->getDeclName() << (isa<CXXMethodDecl>(ADecl) ? 1 : 0);
3370   }
3371   // The optional parameter of the aligned clause, alignment, must be a constant
3372   // positive integer expression. If no optional parameter is specified,
3373   // implementation-defined default alignments for SIMD instructions on the
3374   // target platforms are assumed.
3375   SmallVector<Expr *, 4> NewAligns;
3376   for (auto *E : Alignments) {
3377     ExprResult Align;
3378     if (E)
3379       Align = VerifyPositiveIntegerConstantInClause(E, OMPC_aligned);
3380     NewAligns.push_back(Align.get());
3381   }
3382   // OpenMP [2.8.2, declare simd construct, Description]
3383   // The linear clause declares one or more list items to be private to a SIMD
3384   // lane and to have a linear relationship with respect to the iteration space
3385   // of a loop.
3386   // The special this pointer can be used as if was one of the arguments to the
3387   // function in any of the linear, aligned, or uniform clauses.
3388   // When a linear-step expression is specified in a linear clause it must be
3389   // either a constant integer expression or an integer-typed parameter that is
3390   // specified in a uniform clause on the directive.
3391   llvm::DenseMap<Decl *, Expr *> LinearArgs;
3392   const bool IsUniformedThis = UniformedLinearThis != nullptr;
3393   auto MI = LinModifiers.begin();
3394   for (auto *E : Linears) {
3395     auto LinKind = static_cast<OpenMPLinearClauseKind>(*MI);
3396     ++MI;
3397     E = E->IgnoreParenImpCasts();
3398     if (auto *DRE = dyn_cast<DeclRefExpr>(E))
3399       if (auto *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl())) {
3400         auto *CanonPVD = PVD->getCanonicalDecl();
3401         if (FD->getNumParams() > PVD->getFunctionScopeIndex() &&
3402             FD->getParamDecl(PVD->getFunctionScopeIndex())
3403                     ->getCanonicalDecl() == CanonPVD) {
3404           // OpenMP  [2.15.3.7, linear Clause, Restrictions]
3405           // A list-item cannot appear in more than one linear clause.
3406           if (LinearArgs.count(CanonPVD) > 0) {
3407             Diag(E->getExprLoc(), diag::err_omp_wrong_dsa)
3408                 << getOpenMPClauseName(OMPC_linear)
3409                 << getOpenMPClauseName(OMPC_linear) << E->getSourceRange();
3410             Diag(LinearArgs[CanonPVD]->getExprLoc(),
3411                  diag::note_omp_explicit_dsa)
3412                 << getOpenMPClauseName(OMPC_linear);
3413             continue;
3414           }
3415           // Each argument can appear in at most one uniform or linear clause.
3416           if (UniformedArgs.count(CanonPVD) > 0) {
3417             Diag(E->getExprLoc(), diag::err_omp_wrong_dsa)
3418                 << getOpenMPClauseName(OMPC_linear)
3419                 << getOpenMPClauseName(OMPC_uniform) << E->getSourceRange();
3420             Diag(UniformedArgs[CanonPVD]->getExprLoc(),
3421                  diag::note_omp_explicit_dsa)
3422                 << getOpenMPClauseName(OMPC_uniform);
3423             continue;
3424           }
3425           LinearArgs[CanonPVD] = E;
3426           if (E->isValueDependent() || E->isTypeDependent() ||
3427               E->isInstantiationDependent() ||
3428               E->containsUnexpandedParameterPack())
3429             continue;
3430           (void)CheckOpenMPLinearDecl(CanonPVD, E->getExprLoc(), LinKind,
3431                                       PVD->getOriginalType());
3432           continue;
3433         }
3434       }
3435     if (isa<CXXThisExpr>(E)) {
3436       if (UniformedLinearThis) {
3437         Diag(E->getExprLoc(), diag::err_omp_wrong_dsa)
3438             << getOpenMPClauseName(OMPC_linear)
3439             << getOpenMPClauseName(IsUniformedThis ? OMPC_uniform : OMPC_linear)
3440             << E->getSourceRange();
3441         Diag(UniformedLinearThis->getExprLoc(), diag::note_omp_explicit_dsa)
3442             << getOpenMPClauseName(IsUniformedThis ? OMPC_uniform
3443                                                    : OMPC_linear);
3444         continue;
3445       }
3446       UniformedLinearThis = E;
3447       if (E->isValueDependent() || E->isTypeDependent() ||
3448           E->isInstantiationDependent() || E->containsUnexpandedParameterPack())
3449         continue;
3450       (void)CheckOpenMPLinearDecl(/*D=*/nullptr, E->getExprLoc(), LinKind,
3451                                   E->getType());
3452       continue;
3453     }
3454     Diag(E->getExprLoc(), diag::err_omp_param_or_this_in_clause)
3455         << FD->getDeclName() << (isa<CXXMethodDecl>(ADecl) ? 1 : 0);
3456   }
3457   Expr *Step = nullptr;
3458   Expr *NewStep = nullptr;
3459   SmallVector<Expr *, 4> NewSteps;
3460   for (auto *E : Steps) {
3461     // Skip the same step expression, it was checked already.
3462     if (Step == E || !E) {
3463       NewSteps.push_back(E ? NewStep : nullptr);
3464       continue;
3465     }
3466     Step = E;
3467     if (auto *DRE = dyn_cast<DeclRefExpr>(Step))
3468       if (auto *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl())) {
3469         auto *CanonPVD = PVD->getCanonicalDecl();
3470         if (UniformedArgs.count(CanonPVD) == 0) {
3471           Diag(Step->getExprLoc(), diag::err_omp_expected_uniform_param)
3472               << Step->getSourceRange();
3473         } else if (E->isValueDependent() || E->isTypeDependent() ||
3474                    E->isInstantiationDependent() ||
3475                    E->containsUnexpandedParameterPack() ||
3476                    CanonPVD->getType()->hasIntegerRepresentation())
3477           NewSteps.push_back(Step);
3478         else {
3479           Diag(Step->getExprLoc(), diag::err_omp_expected_int_param)
3480               << Step->getSourceRange();
3481         }
3482         continue;
3483       }
3484     NewStep = Step;
3485     if (Step && !Step->isValueDependent() && !Step->isTypeDependent() &&
3486         !Step->isInstantiationDependent() &&
3487         !Step->containsUnexpandedParameterPack()) {
3488       NewStep = PerformOpenMPImplicitIntegerConversion(Step->getExprLoc(), Step)
3489                     .get();
3490       if (NewStep)
3491         NewStep = VerifyIntegerConstantExpression(NewStep).get();
3492     }
3493     NewSteps.push_back(NewStep);
3494   }
3495   auto *NewAttr = OMPDeclareSimdDeclAttr::CreateImplicit(
3496       Context, BS, SL.get(), const_cast<Expr **>(Uniforms.data()),
3497       Uniforms.size(), const_cast<Expr **>(Aligneds.data()), Aligneds.size(),
3498       const_cast<Expr **>(NewAligns.data()), NewAligns.size(),
3499       const_cast<Expr **>(Linears.data()), Linears.size(),
3500       const_cast<unsigned *>(LinModifiers.data()), LinModifiers.size(),
3501       NewSteps.data(), NewSteps.size(), SR);
3502   ADecl->addAttr(NewAttr);
3503   return ConvertDeclToDeclGroup(ADecl);
3504 }
3505 
3506 StmtResult Sema::ActOnOpenMPParallelDirective(ArrayRef<OMPClause *> Clauses,
3507                                               Stmt *AStmt,
3508                                               SourceLocation StartLoc,
3509                                               SourceLocation EndLoc) {
3510   if (!AStmt)
3511     return StmtError();
3512 
3513   CapturedStmt *CS = cast<CapturedStmt>(AStmt);
3514   // 1.2.2 OpenMP Language Terminology
3515   // Structured block - An executable statement with a single entry at the
3516   // top and a single exit at the bottom.
3517   // The point of exit cannot be a branch out of the structured block.
3518   // longjmp() and throw() must not violate the entry/exit criteria.
3519   CS->getCapturedDecl()->setNothrow();
3520 
3521   getCurFunction()->setHasBranchProtectedScope();
3522 
3523   return OMPParallelDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt,
3524                                       DSAStack->isCancelRegion());
3525 }
3526 
3527 namespace {
3528 /// \brief Helper class for checking canonical form of the OpenMP loops and
3529 /// extracting iteration space of each loop in the loop nest, that will be used
3530 /// for IR generation.
3531 class OpenMPIterationSpaceChecker {
3532   /// \brief Reference to Sema.
3533   Sema &SemaRef;
3534   /// \brief A location for diagnostics (when there is no some better location).
3535   SourceLocation DefaultLoc;
3536   /// \brief A location for diagnostics (when increment is not compatible).
3537   SourceLocation ConditionLoc;
3538   /// \brief A source location for referring to loop init later.
3539   SourceRange InitSrcRange;
3540   /// \brief A source location for referring to condition later.
3541   SourceRange ConditionSrcRange;
3542   /// \brief A source location for referring to increment later.
3543   SourceRange IncrementSrcRange;
3544   /// \brief Loop variable.
3545   ValueDecl *LCDecl = nullptr;
3546   /// \brief Reference to loop variable.
3547   Expr *LCRef = nullptr;
3548   /// \brief Lower bound (initializer for the var).
3549   Expr *LB = nullptr;
3550   /// \brief Upper bound.
3551   Expr *UB = nullptr;
3552   /// \brief Loop step (increment).
3553   Expr *Step = nullptr;
3554   /// \brief This flag is true when condition is one of:
3555   ///   Var <  UB
3556   ///   Var <= UB
3557   ///   UB  >  Var
3558   ///   UB  >= Var
3559   bool TestIsLessOp = false;
3560   /// \brief This flag is true when condition is strict ( < or > ).
3561   bool TestIsStrictOp = false;
3562   /// \brief This flag is true when step is subtracted on each iteration.
3563   bool SubtractStep = false;
3564 
3565 public:
3566   OpenMPIterationSpaceChecker(Sema &SemaRef, SourceLocation DefaultLoc)
3567       : SemaRef(SemaRef), DefaultLoc(DefaultLoc), ConditionLoc(DefaultLoc) {}
3568   /// \brief Check init-expr for canonical loop form and save loop counter
3569   /// variable - #Var and its initialization value - #LB.
3570   bool CheckInit(Stmt *S, bool EmitDiags = true);
3571   /// \brief Check test-expr for canonical form, save upper-bound (#UB), flags
3572   /// for less/greater and for strict/non-strict comparison.
3573   bool CheckCond(Expr *S);
3574   /// \brief Check incr-expr for canonical loop form and return true if it
3575   /// does not conform, otherwise save loop step (#Step).
3576   bool CheckInc(Expr *S);
3577   /// \brief Return the loop counter variable.
3578   ValueDecl *GetLoopDecl() const { return LCDecl; }
3579   /// \brief Return the reference expression to loop counter variable.
3580   Expr *GetLoopDeclRefExpr() const { return LCRef; }
3581   /// \brief Source range of the loop init.
3582   SourceRange GetInitSrcRange() const { return InitSrcRange; }
3583   /// \brief Source range of the loop condition.
3584   SourceRange GetConditionSrcRange() const { return ConditionSrcRange; }
3585   /// \brief Source range of the loop increment.
3586   SourceRange GetIncrementSrcRange() const { return IncrementSrcRange; }
3587   /// \brief True if the step should be subtracted.
3588   bool ShouldSubtractStep() const { return SubtractStep; }
3589   /// \brief Build the expression to calculate the number of iterations.
3590   Expr *
3591   BuildNumIterations(Scope *S, const bool LimitedType,
3592                      llvm::MapVector<Expr *, DeclRefExpr *> &Captures) const;
3593   /// \brief Build the precondition expression for the loops.
3594   Expr *BuildPreCond(Scope *S, Expr *Cond,
3595                      llvm::MapVector<Expr *, DeclRefExpr *> &Captures) const;
3596   /// \brief Build reference expression to the counter be used for codegen.
3597   DeclRefExpr *BuildCounterVar(llvm::MapVector<Expr *, DeclRefExpr *> &Captures,
3598                                DSAStackTy &DSA) const;
3599   /// \brief Build reference expression to the private counter be used for
3600   /// codegen.
3601   Expr *BuildPrivateCounterVar() const;
3602   /// \brief Build initialization of the counter be used for codegen.
3603   Expr *BuildCounterInit() const;
3604   /// \brief Build step of the counter be used for codegen.
3605   Expr *BuildCounterStep() const;
3606   /// \brief Return true if any expression is dependent.
3607   bool Dependent() const;
3608 
3609 private:
3610   /// \brief Check the right-hand side of an assignment in the increment
3611   /// expression.
3612   bool CheckIncRHS(Expr *RHS);
3613   /// \brief Helper to set loop counter variable and its initializer.
3614   bool SetLCDeclAndLB(ValueDecl *NewLCDecl, Expr *NewDeclRefExpr, Expr *NewLB);
3615   /// \brief Helper to set upper bound.
3616   bool SetUB(Expr *NewUB, bool LessOp, bool StrictOp, SourceRange SR,
3617              SourceLocation SL);
3618   /// \brief Helper to set loop increment.
3619   bool SetStep(Expr *NewStep, bool Subtract);
3620 };
3621 
3622 bool OpenMPIterationSpaceChecker::Dependent() const {
3623   if (!LCDecl) {
3624     assert(!LB && !UB && !Step);
3625     return false;
3626   }
3627   return LCDecl->getType()->isDependentType() ||
3628          (LB && LB->isValueDependent()) || (UB && UB->isValueDependent()) ||
3629          (Step && Step->isValueDependent());
3630 }
3631 
3632 bool OpenMPIterationSpaceChecker::SetLCDeclAndLB(ValueDecl *NewLCDecl,
3633                                                  Expr *NewLCRefExpr,
3634                                                  Expr *NewLB) {
3635   // State consistency checking to ensure correct usage.
3636   assert(LCDecl == nullptr && LB == nullptr && LCRef == nullptr &&
3637          UB == nullptr && Step == nullptr && !TestIsLessOp && !TestIsStrictOp);
3638   if (!NewLCDecl || !NewLB)
3639     return true;
3640   LCDecl = getCanonicalDecl(NewLCDecl);
3641   LCRef = NewLCRefExpr;
3642   if (auto *CE = dyn_cast_or_null<CXXConstructExpr>(NewLB))
3643     if (const CXXConstructorDecl *Ctor = CE->getConstructor())
3644       if ((Ctor->isCopyOrMoveConstructor() ||
3645            Ctor->isConvertingConstructor(/*AllowExplicit=*/false)) &&
3646           CE->getNumArgs() > 0 && CE->getArg(0) != nullptr)
3647         NewLB = CE->getArg(0)->IgnoreParenImpCasts();
3648   LB = NewLB;
3649   return false;
3650 }
3651 
3652 bool OpenMPIterationSpaceChecker::SetUB(Expr *NewUB, bool LessOp, bool StrictOp,
3653                                         SourceRange SR, SourceLocation SL) {
3654   // State consistency checking to ensure correct usage.
3655   assert(LCDecl != nullptr && LB != nullptr && UB == nullptr &&
3656          Step == nullptr && !TestIsLessOp && !TestIsStrictOp);
3657   if (!NewUB)
3658     return true;
3659   UB = NewUB;
3660   TestIsLessOp = LessOp;
3661   TestIsStrictOp = StrictOp;
3662   ConditionSrcRange = SR;
3663   ConditionLoc = SL;
3664   return false;
3665 }
3666 
3667 bool OpenMPIterationSpaceChecker::SetStep(Expr *NewStep, bool Subtract) {
3668   // State consistency checking to ensure correct usage.
3669   assert(LCDecl != nullptr && LB != nullptr && Step == nullptr);
3670   if (!NewStep)
3671     return true;
3672   if (!NewStep->isValueDependent()) {
3673     // Check that the step is integer expression.
3674     SourceLocation StepLoc = NewStep->getLocStart();
3675     ExprResult Val = SemaRef.PerformOpenMPImplicitIntegerConversion(
3676         StepLoc, getExprAsWritten(NewStep));
3677     if (Val.isInvalid())
3678       return true;
3679     NewStep = Val.get();
3680 
3681     // OpenMP [2.6, Canonical Loop Form, Restrictions]
3682     //  If test-expr is of form var relational-op b and relational-op is < or
3683     //  <= then incr-expr must cause var to increase on each iteration of the
3684     //  loop. If test-expr is of form var relational-op b and relational-op is
3685     //  > or >= then incr-expr must cause var to decrease on each iteration of
3686     //  the loop.
3687     //  If test-expr is of form b relational-op var and relational-op is < or
3688     //  <= then incr-expr must cause var to decrease on each iteration of the
3689     //  loop. If test-expr is of form b relational-op var and relational-op is
3690     //  > or >= then incr-expr must cause var to increase on each iteration of
3691     //  the loop.
3692     llvm::APSInt Result;
3693     bool IsConstant = NewStep->isIntegerConstantExpr(Result, SemaRef.Context);
3694     bool IsUnsigned = !NewStep->getType()->hasSignedIntegerRepresentation();
3695     bool IsConstNeg =
3696         IsConstant && Result.isSigned() && (Subtract != Result.isNegative());
3697     bool IsConstPos =
3698         IsConstant && Result.isSigned() && (Subtract == Result.isNegative());
3699     bool IsConstZero = IsConstant && !Result.getBoolValue();
3700     if (UB && (IsConstZero ||
3701                (TestIsLessOp ? (IsConstNeg || (IsUnsigned && Subtract))
3702                              : (IsConstPos || (IsUnsigned && !Subtract))))) {
3703       SemaRef.Diag(NewStep->getExprLoc(),
3704                    diag::err_omp_loop_incr_not_compatible)
3705           << LCDecl << TestIsLessOp << NewStep->getSourceRange();
3706       SemaRef.Diag(ConditionLoc,
3707                    diag::note_omp_loop_cond_requres_compatible_incr)
3708           << TestIsLessOp << ConditionSrcRange;
3709       return true;
3710     }
3711     if (TestIsLessOp == Subtract) {
3712       NewStep =
3713           SemaRef.CreateBuiltinUnaryOp(NewStep->getExprLoc(), UO_Minus, NewStep)
3714               .get();
3715       Subtract = !Subtract;
3716     }
3717   }
3718 
3719   Step = NewStep;
3720   SubtractStep = Subtract;
3721   return false;
3722 }
3723 
3724 bool OpenMPIterationSpaceChecker::CheckInit(Stmt *S, bool EmitDiags) {
3725   // Check init-expr for canonical loop form and save loop counter
3726   // variable - #Var and its initialization value - #LB.
3727   // OpenMP [2.6] Canonical loop form. init-expr may be one of the following:
3728   //   var = lb
3729   //   integer-type var = lb
3730   //   random-access-iterator-type var = lb
3731   //   pointer-type var = lb
3732   //
3733   if (!S) {
3734     if (EmitDiags) {
3735       SemaRef.Diag(DefaultLoc, diag::err_omp_loop_not_canonical_init);
3736     }
3737     return true;
3738   }
3739   if (auto *ExprTemp = dyn_cast<ExprWithCleanups>(S))
3740     if (!ExprTemp->cleanupsHaveSideEffects())
3741       S = ExprTemp->getSubExpr();
3742 
3743   InitSrcRange = S->getSourceRange();
3744   if (Expr *E = dyn_cast<Expr>(S))
3745     S = E->IgnoreParens();
3746   if (auto *BO = dyn_cast<BinaryOperator>(S)) {
3747     if (BO->getOpcode() == BO_Assign) {
3748       auto *LHS = BO->getLHS()->IgnoreParens();
3749       if (auto *DRE = dyn_cast<DeclRefExpr>(LHS)) {
3750         if (auto *CED = dyn_cast<OMPCapturedExprDecl>(DRE->getDecl()))
3751           if (auto *ME = dyn_cast<MemberExpr>(getExprAsWritten(CED->getInit())))
3752             return SetLCDeclAndLB(ME->getMemberDecl(), ME, BO->getRHS());
3753         return SetLCDeclAndLB(DRE->getDecl(), DRE, BO->getRHS());
3754       }
3755       if (auto *ME = dyn_cast<MemberExpr>(LHS)) {
3756         if (ME->isArrow() &&
3757             isa<CXXThisExpr>(ME->getBase()->IgnoreParenImpCasts()))
3758           return SetLCDeclAndLB(ME->getMemberDecl(), ME, BO->getRHS());
3759       }
3760     }
3761   } else if (auto *DS = dyn_cast<DeclStmt>(S)) {
3762     if (DS->isSingleDecl()) {
3763       if (auto *Var = dyn_cast_or_null<VarDecl>(DS->getSingleDecl())) {
3764         if (Var->hasInit() && !Var->getType()->isReferenceType()) {
3765           // Accept non-canonical init form here but emit ext. warning.
3766           if (Var->getInitStyle() != VarDecl::CInit && EmitDiags)
3767             SemaRef.Diag(S->getLocStart(),
3768                          diag::ext_omp_loop_not_canonical_init)
3769                 << S->getSourceRange();
3770           return SetLCDeclAndLB(Var, nullptr, Var->getInit());
3771         }
3772       }
3773     }
3774   } else if (auto *CE = dyn_cast<CXXOperatorCallExpr>(S)) {
3775     if (CE->getOperator() == OO_Equal) {
3776       auto *LHS = CE->getArg(0);
3777       if (auto *DRE = dyn_cast<DeclRefExpr>(LHS)) {
3778         if (auto *CED = dyn_cast<OMPCapturedExprDecl>(DRE->getDecl()))
3779           if (auto *ME = dyn_cast<MemberExpr>(getExprAsWritten(CED->getInit())))
3780             return SetLCDeclAndLB(ME->getMemberDecl(), ME, BO->getRHS());
3781         return SetLCDeclAndLB(DRE->getDecl(), DRE, CE->getArg(1));
3782       }
3783       if (auto *ME = dyn_cast<MemberExpr>(LHS)) {
3784         if (ME->isArrow() &&
3785             isa<CXXThisExpr>(ME->getBase()->IgnoreParenImpCasts()))
3786           return SetLCDeclAndLB(ME->getMemberDecl(), ME, BO->getRHS());
3787       }
3788     }
3789   }
3790 
3791   if (Dependent() || SemaRef.CurContext->isDependentContext())
3792     return false;
3793   if (EmitDiags) {
3794     SemaRef.Diag(S->getLocStart(), diag::err_omp_loop_not_canonical_init)
3795         << S->getSourceRange();
3796   }
3797   return true;
3798 }
3799 
3800 /// \brief Ignore parenthesizes, implicit casts, copy constructor and return the
3801 /// variable (which may be the loop variable) if possible.
3802 static const ValueDecl *GetInitLCDecl(Expr *E) {
3803   if (!E)
3804     return nullptr;
3805   E = getExprAsWritten(E);
3806   if (auto *CE = dyn_cast_or_null<CXXConstructExpr>(E))
3807     if (const CXXConstructorDecl *Ctor = CE->getConstructor())
3808       if ((Ctor->isCopyOrMoveConstructor() ||
3809            Ctor->isConvertingConstructor(/*AllowExplicit=*/false)) &&
3810           CE->getNumArgs() > 0 && CE->getArg(0) != nullptr)
3811         E = CE->getArg(0)->IgnoreParenImpCasts();
3812   if (auto *DRE = dyn_cast_or_null<DeclRefExpr>(E)) {
3813     if (auto *VD = dyn_cast<VarDecl>(DRE->getDecl()))
3814       return getCanonicalDecl(VD);
3815   }
3816   if (auto *ME = dyn_cast_or_null<MemberExpr>(E))
3817     if (ME->isArrow() && isa<CXXThisExpr>(ME->getBase()->IgnoreParenImpCasts()))
3818       return getCanonicalDecl(ME->getMemberDecl());
3819   return nullptr;
3820 }
3821 
3822 bool OpenMPIterationSpaceChecker::CheckCond(Expr *S) {
3823   // Check test-expr for canonical form, save upper-bound UB, flags for
3824   // less/greater and for strict/non-strict comparison.
3825   // OpenMP [2.6] Canonical loop form. Test-expr may be one of the following:
3826   //   var relational-op b
3827   //   b relational-op var
3828   //
3829   if (!S) {
3830     SemaRef.Diag(DefaultLoc, diag::err_omp_loop_not_canonical_cond) << LCDecl;
3831     return true;
3832   }
3833   S = getExprAsWritten(S);
3834   SourceLocation CondLoc = S->getLocStart();
3835   if (auto *BO = dyn_cast<BinaryOperator>(S)) {
3836     if (BO->isRelationalOp()) {
3837       if (GetInitLCDecl(BO->getLHS()) == LCDecl)
3838         return SetUB(BO->getRHS(),
3839                      (BO->getOpcode() == BO_LT || BO->getOpcode() == BO_LE),
3840                      (BO->getOpcode() == BO_LT || BO->getOpcode() == BO_GT),
3841                      BO->getSourceRange(), BO->getOperatorLoc());
3842       if (GetInitLCDecl(BO->getRHS()) == LCDecl)
3843         return SetUB(BO->getLHS(),
3844                      (BO->getOpcode() == BO_GT || BO->getOpcode() == BO_GE),
3845                      (BO->getOpcode() == BO_LT || BO->getOpcode() == BO_GT),
3846                      BO->getSourceRange(), BO->getOperatorLoc());
3847     }
3848   } else if (auto *CE = dyn_cast<CXXOperatorCallExpr>(S)) {
3849     if (CE->getNumArgs() == 2) {
3850       auto Op = CE->getOperator();
3851       switch (Op) {
3852       case OO_Greater:
3853       case OO_GreaterEqual:
3854       case OO_Less:
3855       case OO_LessEqual:
3856         if (GetInitLCDecl(CE->getArg(0)) == LCDecl)
3857           return SetUB(CE->getArg(1), Op == OO_Less || Op == OO_LessEqual,
3858                        Op == OO_Less || Op == OO_Greater, CE->getSourceRange(),
3859                        CE->getOperatorLoc());
3860         if (GetInitLCDecl(CE->getArg(1)) == LCDecl)
3861           return SetUB(CE->getArg(0), Op == OO_Greater || Op == OO_GreaterEqual,
3862                        Op == OO_Less || Op == OO_Greater, CE->getSourceRange(),
3863                        CE->getOperatorLoc());
3864         break;
3865       default:
3866         break;
3867       }
3868     }
3869   }
3870   if (Dependent() || SemaRef.CurContext->isDependentContext())
3871     return false;
3872   SemaRef.Diag(CondLoc, diag::err_omp_loop_not_canonical_cond)
3873       << S->getSourceRange() << LCDecl;
3874   return true;
3875 }
3876 
3877 bool OpenMPIterationSpaceChecker::CheckIncRHS(Expr *RHS) {
3878   // RHS of canonical loop form increment can be:
3879   //   var + incr
3880   //   incr + var
3881   //   var - incr
3882   //
3883   RHS = RHS->IgnoreParenImpCasts();
3884   if (auto *BO = dyn_cast<BinaryOperator>(RHS)) {
3885     if (BO->isAdditiveOp()) {
3886       bool IsAdd = BO->getOpcode() == BO_Add;
3887       if (GetInitLCDecl(BO->getLHS()) == LCDecl)
3888         return SetStep(BO->getRHS(), !IsAdd);
3889       if (IsAdd && GetInitLCDecl(BO->getRHS()) == LCDecl)
3890         return SetStep(BO->getLHS(), false);
3891     }
3892   } else if (auto *CE = dyn_cast<CXXOperatorCallExpr>(RHS)) {
3893     bool IsAdd = CE->getOperator() == OO_Plus;
3894     if ((IsAdd || CE->getOperator() == OO_Minus) && CE->getNumArgs() == 2) {
3895       if (GetInitLCDecl(CE->getArg(0)) == LCDecl)
3896         return SetStep(CE->getArg(1), !IsAdd);
3897       if (IsAdd && GetInitLCDecl(CE->getArg(1)) == LCDecl)
3898         return SetStep(CE->getArg(0), false);
3899     }
3900   }
3901   if (Dependent() || SemaRef.CurContext->isDependentContext())
3902     return false;
3903   SemaRef.Diag(RHS->getLocStart(), diag::err_omp_loop_not_canonical_incr)
3904       << RHS->getSourceRange() << LCDecl;
3905   return true;
3906 }
3907 
3908 bool OpenMPIterationSpaceChecker::CheckInc(Expr *S) {
3909   // Check incr-expr for canonical loop form and return true if it
3910   // does not conform.
3911   // OpenMP [2.6] Canonical loop form. Test-expr may be one of the following:
3912   //   ++var
3913   //   var++
3914   //   --var
3915   //   var--
3916   //   var += incr
3917   //   var -= incr
3918   //   var = var + incr
3919   //   var = incr + var
3920   //   var = var - incr
3921   //
3922   if (!S) {
3923     SemaRef.Diag(DefaultLoc, diag::err_omp_loop_not_canonical_incr) << LCDecl;
3924     return true;
3925   }
3926   if (auto *ExprTemp = dyn_cast<ExprWithCleanups>(S))
3927     if (!ExprTemp->cleanupsHaveSideEffects())
3928       S = ExprTemp->getSubExpr();
3929 
3930   IncrementSrcRange = S->getSourceRange();
3931   S = S->IgnoreParens();
3932   if (auto *UO = dyn_cast<UnaryOperator>(S)) {
3933     if (UO->isIncrementDecrementOp() &&
3934         GetInitLCDecl(UO->getSubExpr()) == LCDecl)
3935       return SetStep(SemaRef
3936                          .ActOnIntegerConstant(UO->getLocStart(),
3937                                                (UO->isDecrementOp() ? -1 : 1))
3938                          .get(),
3939                      false);
3940   } else if (auto *BO = dyn_cast<BinaryOperator>(S)) {
3941     switch (BO->getOpcode()) {
3942     case BO_AddAssign:
3943     case BO_SubAssign:
3944       if (GetInitLCDecl(BO->getLHS()) == LCDecl)
3945         return SetStep(BO->getRHS(), BO->getOpcode() == BO_SubAssign);
3946       break;
3947     case BO_Assign:
3948       if (GetInitLCDecl(BO->getLHS()) == LCDecl)
3949         return CheckIncRHS(BO->getRHS());
3950       break;
3951     default:
3952       break;
3953     }
3954   } else if (auto *CE = dyn_cast<CXXOperatorCallExpr>(S)) {
3955     switch (CE->getOperator()) {
3956     case OO_PlusPlus:
3957     case OO_MinusMinus:
3958       if (GetInitLCDecl(CE->getArg(0)) == LCDecl)
3959         return SetStep(SemaRef
3960                            .ActOnIntegerConstant(
3961                                CE->getLocStart(),
3962                                ((CE->getOperator() == OO_MinusMinus) ? -1 : 1))
3963                            .get(),
3964                        false);
3965       break;
3966     case OO_PlusEqual:
3967     case OO_MinusEqual:
3968       if (GetInitLCDecl(CE->getArg(0)) == LCDecl)
3969         return SetStep(CE->getArg(1), CE->getOperator() == OO_MinusEqual);
3970       break;
3971     case OO_Equal:
3972       if (GetInitLCDecl(CE->getArg(0)) == LCDecl)
3973         return CheckIncRHS(CE->getArg(1));
3974       break;
3975     default:
3976       break;
3977     }
3978   }
3979   if (Dependent() || SemaRef.CurContext->isDependentContext())
3980     return false;
3981   SemaRef.Diag(S->getLocStart(), diag::err_omp_loop_not_canonical_incr)
3982       << S->getSourceRange() << LCDecl;
3983   return true;
3984 }
3985 
3986 static ExprResult
3987 tryBuildCapture(Sema &SemaRef, Expr *Capture,
3988                 llvm::MapVector<Expr *, DeclRefExpr *> &Captures) {
3989   if (SemaRef.CurContext->isDependentContext())
3990     return ExprResult(Capture);
3991   if (Capture->isEvaluatable(SemaRef.Context, Expr::SE_AllowSideEffects))
3992     return SemaRef.PerformImplicitConversion(
3993         Capture->IgnoreImpCasts(), Capture->getType(), Sema::AA_Converting,
3994         /*AllowExplicit=*/true);
3995   auto I = Captures.find(Capture);
3996   if (I != Captures.end())
3997     return buildCapture(SemaRef, Capture, I->second);
3998   DeclRefExpr *Ref = nullptr;
3999   ExprResult Res = buildCapture(SemaRef, Capture, Ref);
4000   Captures[Capture] = Ref;
4001   return Res;
4002 }
4003 
4004 /// \brief Build the expression to calculate the number of iterations.
4005 Expr *OpenMPIterationSpaceChecker::BuildNumIterations(
4006     Scope *S, const bool LimitedType,
4007     llvm::MapVector<Expr *, DeclRefExpr *> &Captures) const {
4008   ExprResult Diff;
4009   auto VarType = LCDecl->getType().getNonReferenceType();
4010   if (VarType->isIntegerType() || VarType->isPointerType() ||
4011       SemaRef.getLangOpts().CPlusPlus) {
4012     // Upper - Lower
4013     auto *UBExpr = TestIsLessOp ? UB : LB;
4014     auto *LBExpr = TestIsLessOp ? LB : UB;
4015     Expr *Upper = tryBuildCapture(SemaRef, UBExpr, Captures).get();
4016     Expr *Lower = tryBuildCapture(SemaRef, LBExpr, Captures).get();
4017     if (!Upper || !Lower)
4018       return nullptr;
4019 
4020     Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Sub, Upper, Lower);
4021 
4022     if (!Diff.isUsable() && VarType->getAsCXXRecordDecl()) {
4023       // BuildBinOp already emitted error, this one is to point user to upper
4024       // and lower bound, and to tell what is passed to 'operator-'.
4025       SemaRef.Diag(Upper->getLocStart(), diag::err_omp_loop_diff_cxx)
4026           << Upper->getSourceRange() << Lower->getSourceRange();
4027       return nullptr;
4028     }
4029   }
4030 
4031   if (!Diff.isUsable())
4032     return nullptr;
4033 
4034   // Upper - Lower [- 1]
4035   if (TestIsStrictOp)
4036     Diff = SemaRef.BuildBinOp(
4037         S, DefaultLoc, BO_Sub, Diff.get(),
4038         SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get());
4039   if (!Diff.isUsable())
4040     return nullptr;
4041 
4042   // Upper - Lower [- 1] + Step
4043   auto NewStep = tryBuildCapture(SemaRef, Step, Captures);
4044   if (!NewStep.isUsable())
4045     return nullptr;
4046   Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Add, Diff.get(), NewStep.get());
4047   if (!Diff.isUsable())
4048     return nullptr;
4049 
4050   // Parentheses (for dumping/debugging purposes only).
4051   Diff = SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, Diff.get());
4052   if (!Diff.isUsable())
4053     return nullptr;
4054 
4055   // (Upper - Lower [- 1] + Step) / Step
4056   Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Div, Diff.get(), NewStep.get());
4057   if (!Diff.isUsable())
4058     return nullptr;
4059 
4060   // OpenMP runtime requires 32-bit or 64-bit loop variables.
4061   QualType Type = Diff.get()->getType();
4062   auto &C = SemaRef.Context;
4063   bool UseVarType = VarType->hasIntegerRepresentation() &&
4064                     C.getTypeSize(Type) > C.getTypeSize(VarType);
4065   if (!Type->isIntegerType() || UseVarType) {
4066     unsigned NewSize =
4067         UseVarType ? C.getTypeSize(VarType) : C.getTypeSize(Type);
4068     bool IsSigned = UseVarType ? VarType->hasSignedIntegerRepresentation()
4069                                : Type->hasSignedIntegerRepresentation();
4070     Type = C.getIntTypeForBitwidth(NewSize, IsSigned);
4071     if (!SemaRef.Context.hasSameType(Diff.get()->getType(), Type)) {
4072       Diff = SemaRef.PerformImplicitConversion(
4073           Diff.get(), Type, Sema::AA_Converting, /*AllowExplicit=*/true);
4074       if (!Diff.isUsable())
4075         return nullptr;
4076     }
4077   }
4078   if (LimitedType) {
4079     unsigned NewSize = (C.getTypeSize(Type) > 32) ? 64 : 32;
4080     if (NewSize != C.getTypeSize(Type)) {
4081       if (NewSize < C.getTypeSize(Type)) {
4082         assert(NewSize == 64 && "incorrect loop var size");
4083         SemaRef.Diag(DefaultLoc, diag::warn_omp_loop_64_bit_var)
4084             << InitSrcRange << ConditionSrcRange;
4085       }
4086       QualType NewType = C.getIntTypeForBitwidth(
4087           NewSize, Type->hasSignedIntegerRepresentation() ||
4088                        C.getTypeSize(Type) < NewSize);
4089       if (!SemaRef.Context.hasSameType(Diff.get()->getType(), NewType)) {
4090         Diff = SemaRef.PerformImplicitConversion(Diff.get(), NewType,
4091                                                  Sema::AA_Converting, true);
4092         if (!Diff.isUsable())
4093           return nullptr;
4094       }
4095     }
4096   }
4097 
4098   return Diff.get();
4099 }
4100 
4101 Expr *OpenMPIterationSpaceChecker::BuildPreCond(
4102     Scope *S, Expr *Cond,
4103     llvm::MapVector<Expr *, DeclRefExpr *> &Captures) const {
4104   // Try to build LB <op> UB, where <op> is <, >, <=, or >=.
4105   bool Suppress = SemaRef.getDiagnostics().getSuppressAllDiagnostics();
4106   SemaRef.getDiagnostics().setSuppressAllDiagnostics(/*Val=*/true);
4107 
4108   auto NewLB = tryBuildCapture(SemaRef, LB, Captures);
4109   auto NewUB = tryBuildCapture(SemaRef, UB, Captures);
4110   if (!NewLB.isUsable() || !NewUB.isUsable())
4111     return nullptr;
4112 
4113   auto CondExpr = SemaRef.BuildBinOp(
4114       S, DefaultLoc, TestIsLessOp ? (TestIsStrictOp ? BO_LT : BO_LE)
4115                                   : (TestIsStrictOp ? BO_GT : BO_GE),
4116       NewLB.get(), NewUB.get());
4117   if (CondExpr.isUsable()) {
4118     if (!SemaRef.Context.hasSameUnqualifiedType(CondExpr.get()->getType(),
4119                                                 SemaRef.Context.BoolTy))
4120       CondExpr = SemaRef.PerformImplicitConversion(
4121           CondExpr.get(), SemaRef.Context.BoolTy, /*Action=*/Sema::AA_Casting,
4122           /*AllowExplicit=*/true);
4123   }
4124   SemaRef.getDiagnostics().setSuppressAllDiagnostics(Suppress);
4125   // Otherwise use original loop conditon and evaluate it in runtime.
4126   return CondExpr.isUsable() ? CondExpr.get() : Cond;
4127 }
4128 
4129 /// \brief Build reference expression to the counter be used for codegen.
4130 DeclRefExpr *OpenMPIterationSpaceChecker::BuildCounterVar(
4131     llvm::MapVector<Expr *, DeclRefExpr *> &Captures, DSAStackTy &DSA) const {
4132   auto *VD = dyn_cast<VarDecl>(LCDecl);
4133   if (!VD) {
4134     VD = SemaRef.IsOpenMPCapturedDecl(LCDecl);
4135     auto *Ref = buildDeclRefExpr(
4136         SemaRef, VD, VD->getType().getNonReferenceType(), DefaultLoc);
4137     DSAStackTy::DSAVarData Data = DSA.getTopDSA(LCDecl, /*FromParent=*/false);
4138     // If the loop control decl is explicitly marked as private, do not mark it
4139     // as captured again.
4140     if (!isOpenMPPrivate(Data.CKind) || !Data.RefExpr)
4141       Captures.insert(std::make_pair(LCRef, Ref));
4142     return Ref;
4143   }
4144   return buildDeclRefExpr(SemaRef, VD, VD->getType().getNonReferenceType(),
4145                           DefaultLoc);
4146 }
4147 
4148 Expr *OpenMPIterationSpaceChecker::BuildPrivateCounterVar() const {
4149   if (LCDecl && !LCDecl->isInvalidDecl()) {
4150     auto Type = LCDecl->getType().getNonReferenceType();
4151     auto *PrivateVar =
4152         buildVarDecl(SemaRef, DefaultLoc, Type, LCDecl->getName(),
4153                      LCDecl->hasAttrs() ? &LCDecl->getAttrs() : nullptr);
4154     if (PrivateVar->isInvalidDecl())
4155       return nullptr;
4156     return buildDeclRefExpr(SemaRef, PrivateVar, Type, DefaultLoc);
4157   }
4158   return nullptr;
4159 }
4160 
4161 /// \brief Build initialization of the counter to be used for codegen.
4162 Expr *OpenMPIterationSpaceChecker::BuildCounterInit() const { return LB; }
4163 
4164 /// \brief Build step of the counter be used for codegen.
4165 Expr *OpenMPIterationSpaceChecker::BuildCounterStep() const { return Step; }
4166 
4167 /// \brief Iteration space of a single for loop.
4168 struct LoopIterationSpace final {
4169   /// \brief Condition of the loop.
4170   Expr *PreCond = nullptr;
4171   /// \brief This expression calculates the number of iterations in the loop.
4172   /// It is always possible to calculate it before starting the loop.
4173   Expr *NumIterations = nullptr;
4174   /// \brief The loop counter variable.
4175   Expr *CounterVar = nullptr;
4176   /// \brief Private loop counter variable.
4177   Expr *PrivateCounterVar = nullptr;
4178   /// \brief This is initializer for the initial value of #CounterVar.
4179   Expr *CounterInit = nullptr;
4180   /// \brief This is step for the #CounterVar used to generate its update:
4181   /// #CounterVar = #CounterInit + #CounterStep * CurrentIteration.
4182   Expr *CounterStep = nullptr;
4183   /// \brief Should step be subtracted?
4184   bool Subtract = false;
4185   /// \brief Source range of the loop init.
4186   SourceRange InitSrcRange;
4187   /// \brief Source range of the loop condition.
4188   SourceRange CondSrcRange;
4189   /// \brief Source range of the loop increment.
4190   SourceRange IncSrcRange;
4191 };
4192 
4193 } // namespace
4194 
4195 void Sema::ActOnOpenMPLoopInitialization(SourceLocation ForLoc, Stmt *Init) {
4196   assert(getLangOpts().OpenMP && "OpenMP is not active.");
4197   assert(Init && "Expected loop in canonical form.");
4198   unsigned AssociatedLoops = DSAStack->getAssociatedLoops();
4199   if (AssociatedLoops > 0 &&
4200       isOpenMPLoopDirective(DSAStack->getCurrentDirective())) {
4201     OpenMPIterationSpaceChecker ISC(*this, ForLoc);
4202     if (!ISC.CheckInit(Init, /*EmitDiags=*/false)) {
4203       if (auto *D = ISC.GetLoopDecl()) {
4204         auto *VD = dyn_cast<VarDecl>(D);
4205         if (!VD) {
4206           if (auto *Private = IsOpenMPCapturedDecl(D))
4207             VD = Private;
4208           else {
4209             auto *Ref = buildCapture(*this, D, ISC.GetLoopDeclRefExpr(),
4210                                      /*WithInit=*/false);
4211             VD = cast<VarDecl>(Ref->getDecl());
4212           }
4213         }
4214         DSAStack->addLoopControlVariable(D, VD);
4215       }
4216     }
4217     DSAStack->setAssociatedLoops(AssociatedLoops - 1);
4218   }
4219 }
4220 
4221 /// \brief Called on a for stmt to check and extract its iteration space
4222 /// for further processing (such as collapsing).
4223 static bool CheckOpenMPIterationSpace(
4224     OpenMPDirectiveKind DKind, Stmt *S, Sema &SemaRef, DSAStackTy &DSA,
4225     unsigned CurrentNestedLoopCount, unsigned NestedLoopCount,
4226     Expr *CollapseLoopCountExpr, Expr *OrderedLoopCountExpr,
4227     llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA,
4228     LoopIterationSpace &ResultIterSpace,
4229     llvm::MapVector<Expr *, DeclRefExpr *> &Captures) {
4230   // OpenMP [2.6, Canonical Loop Form]
4231   //   for (init-expr; test-expr; incr-expr) structured-block
4232   auto *For = dyn_cast_or_null<ForStmt>(S);
4233   if (!For) {
4234     SemaRef.Diag(S->getLocStart(), diag::err_omp_not_for)
4235         << (CollapseLoopCountExpr != nullptr || OrderedLoopCountExpr != nullptr)
4236         << getOpenMPDirectiveName(DKind) << NestedLoopCount
4237         << (CurrentNestedLoopCount > 0) << CurrentNestedLoopCount;
4238     if (NestedLoopCount > 1) {
4239       if (CollapseLoopCountExpr && OrderedLoopCountExpr)
4240         SemaRef.Diag(DSA.getConstructLoc(),
4241                      diag::note_omp_collapse_ordered_expr)
4242             << 2 << CollapseLoopCountExpr->getSourceRange()
4243             << OrderedLoopCountExpr->getSourceRange();
4244       else if (CollapseLoopCountExpr)
4245         SemaRef.Diag(CollapseLoopCountExpr->getExprLoc(),
4246                      diag::note_omp_collapse_ordered_expr)
4247             << 0 << CollapseLoopCountExpr->getSourceRange();
4248       else
4249         SemaRef.Diag(OrderedLoopCountExpr->getExprLoc(),
4250                      diag::note_omp_collapse_ordered_expr)
4251             << 1 << OrderedLoopCountExpr->getSourceRange();
4252     }
4253     return true;
4254   }
4255   assert(For->getBody());
4256 
4257   OpenMPIterationSpaceChecker ISC(SemaRef, For->getForLoc());
4258 
4259   // Check init.
4260   auto Init = For->getInit();
4261   if (ISC.CheckInit(Init))
4262     return true;
4263 
4264   bool HasErrors = false;
4265 
4266   // Check loop variable's type.
4267   if (auto *LCDecl = ISC.GetLoopDecl()) {
4268     auto *LoopDeclRefExpr = ISC.GetLoopDeclRefExpr();
4269 
4270     // OpenMP [2.6, Canonical Loop Form]
4271     // Var is one of the following:
4272     //   A variable of signed or unsigned integer type.
4273     //   For C++, a variable of a random access iterator type.
4274     //   For C, a variable of a pointer type.
4275     auto VarType = LCDecl->getType().getNonReferenceType();
4276     if (!VarType->isDependentType() && !VarType->isIntegerType() &&
4277         !VarType->isPointerType() &&
4278         !(SemaRef.getLangOpts().CPlusPlus && VarType->isOverloadableType())) {
4279       SemaRef.Diag(Init->getLocStart(), diag::err_omp_loop_variable_type)
4280           << SemaRef.getLangOpts().CPlusPlus;
4281       HasErrors = true;
4282     }
4283 
4284     // OpenMP, 2.14.1.1 Data-sharing Attribute Rules for Variables Referenced in
4285     // a Construct
4286     // The loop iteration variable(s) in the associated for-loop(s) of a for or
4287     // parallel for construct is (are) private.
4288     // The loop iteration variable in the associated for-loop of a simd
4289     // construct with just one associated for-loop is linear with a
4290     // constant-linear-step that is the increment of the associated for-loop.
4291     // Exclude loop var from the list of variables with implicitly defined data
4292     // sharing attributes.
4293     VarsWithImplicitDSA.erase(LCDecl);
4294 
4295     // OpenMP [2.14.1.1, Data-sharing Attribute Rules for Variables Referenced
4296     // in a Construct, C/C++].
4297     // The loop iteration variable in the associated for-loop of a simd
4298     // construct with just one associated for-loop may be listed in a linear
4299     // clause with a constant-linear-step that is the increment of the
4300     // associated for-loop.
4301     // The loop iteration variable(s) in the associated for-loop(s) of a for or
4302     // parallel for construct may be listed in a private or lastprivate clause.
4303     DSAStackTy::DSAVarData DVar = DSA.getTopDSA(LCDecl, false);
4304     // If LoopVarRefExpr is nullptr it means the corresponding loop variable is
4305     // declared in the loop and it is predetermined as a private.
4306     auto PredeterminedCKind =
4307         isOpenMPSimdDirective(DKind)
4308             ? ((NestedLoopCount == 1) ? OMPC_linear : OMPC_lastprivate)
4309             : OMPC_private;
4310     if (((isOpenMPSimdDirective(DKind) && DVar.CKind != OMPC_unknown &&
4311           DVar.CKind != PredeterminedCKind) ||
4312          ((isOpenMPWorksharingDirective(DKind) || DKind == OMPD_taskloop ||
4313            isOpenMPDistributeDirective(DKind)) &&
4314           !isOpenMPSimdDirective(DKind) && DVar.CKind != OMPC_unknown &&
4315           DVar.CKind != OMPC_private && DVar.CKind != OMPC_lastprivate)) &&
4316         (DVar.CKind != OMPC_private || DVar.RefExpr != nullptr)) {
4317       SemaRef.Diag(Init->getLocStart(), diag::err_omp_loop_var_dsa)
4318           << getOpenMPClauseName(DVar.CKind) << getOpenMPDirectiveName(DKind)
4319           << getOpenMPClauseName(PredeterminedCKind);
4320       if (DVar.RefExpr == nullptr)
4321         DVar.CKind = PredeterminedCKind;
4322       ReportOriginalDSA(SemaRef, &DSA, LCDecl, DVar, /*IsLoopIterVar=*/true);
4323       HasErrors = true;
4324     } else if (LoopDeclRefExpr != nullptr) {
4325       // Make the loop iteration variable private (for worksharing constructs),
4326       // linear (for simd directives with the only one associated loop) or
4327       // lastprivate (for simd directives with several collapsed or ordered
4328       // loops).
4329       if (DVar.CKind == OMPC_unknown)
4330         DVar = DSA.hasDSA(LCDecl, isOpenMPPrivate,
4331                           [](OpenMPDirectiveKind) -> bool { return true; },
4332                           /*FromParent=*/false);
4333       DSA.addDSA(LCDecl, LoopDeclRefExpr, PredeterminedCKind);
4334     }
4335 
4336     assert(isOpenMPLoopDirective(DKind) && "DSA for non-loop vars");
4337 
4338     // Check test-expr.
4339     HasErrors |= ISC.CheckCond(For->getCond());
4340 
4341     // Check incr-expr.
4342     HasErrors |= ISC.CheckInc(For->getInc());
4343   }
4344 
4345   if (ISC.Dependent() || SemaRef.CurContext->isDependentContext() || HasErrors)
4346     return HasErrors;
4347 
4348   // Build the loop's iteration space representation.
4349   ResultIterSpace.PreCond =
4350       ISC.BuildPreCond(DSA.getCurScope(), For->getCond(), Captures);
4351   ResultIterSpace.NumIterations = ISC.BuildNumIterations(
4352       DSA.getCurScope(),
4353       (isOpenMPWorksharingDirective(DKind) ||
4354        isOpenMPTaskLoopDirective(DKind) || isOpenMPDistributeDirective(DKind)),
4355       Captures);
4356   ResultIterSpace.CounterVar = ISC.BuildCounterVar(Captures, DSA);
4357   ResultIterSpace.PrivateCounterVar = ISC.BuildPrivateCounterVar();
4358   ResultIterSpace.CounterInit = ISC.BuildCounterInit();
4359   ResultIterSpace.CounterStep = ISC.BuildCounterStep();
4360   ResultIterSpace.InitSrcRange = ISC.GetInitSrcRange();
4361   ResultIterSpace.CondSrcRange = ISC.GetConditionSrcRange();
4362   ResultIterSpace.IncSrcRange = ISC.GetIncrementSrcRange();
4363   ResultIterSpace.Subtract = ISC.ShouldSubtractStep();
4364 
4365   HasErrors |= (ResultIterSpace.PreCond == nullptr ||
4366                 ResultIterSpace.NumIterations == nullptr ||
4367                 ResultIterSpace.CounterVar == nullptr ||
4368                 ResultIterSpace.PrivateCounterVar == nullptr ||
4369                 ResultIterSpace.CounterInit == nullptr ||
4370                 ResultIterSpace.CounterStep == nullptr);
4371 
4372   return HasErrors;
4373 }
4374 
4375 /// \brief Build 'VarRef = Start.
4376 static ExprResult
4377 BuildCounterInit(Sema &SemaRef, Scope *S, SourceLocation Loc, ExprResult VarRef,
4378                  ExprResult Start,
4379                  llvm::MapVector<Expr *, DeclRefExpr *> &Captures) {
4380   // Build 'VarRef = Start.
4381   auto NewStart = tryBuildCapture(SemaRef, Start.get(), Captures);
4382   if (!NewStart.isUsable())
4383     return ExprError();
4384   if (!SemaRef.Context.hasSameType(NewStart.get()->getType(),
4385                                    VarRef.get()->getType())) {
4386     NewStart = SemaRef.PerformImplicitConversion(
4387         NewStart.get(), VarRef.get()->getType(), Sema::AA_Converting,
4388         /*AllowExplicit=*/true);
4389     if (!NewStart.isUsable())
4390       return ExprError();
4391   }
4392 
4393   auto Init =
4394       SemaRef.BuildBinOp(S, Loc, BO_Assign, VarRef.get(), NewStart.get());
4395   return Init;
4396 }
4397 
4398 /// \brief Build 'VarRef = Start + Iter * Step'.
4399 static ExprResult
4400 BuildCounterUpdate(Sema &SemaRef, Scope *S, SourceLocation Loc,
4401                    ExprResult VarRef, ExprResult Start, ExprResult Iter,
4402                    ExprResult Step, bool Subtract,
4403                    llvm::MapVector<Expr *, DeclRefExpr *> *Captures = nullptr) {
4404   // Add parentheses (for debugging purposes only).
4405   Iter = SemaRef.ActOnParenExpr(Loc, Loc, Iter.get());
4406   if (!VarRef.isUsable() || !Start.isUsable() || !Iter.isUsable() ||
4407       !Step.isUsable())
4408     return ExprError();
4409 
4410   ExprResult NewStep = Step;
4411   if (Captures)
4412     NewStep = tryBuildCapture(SemaRef, Step.get(), *Captures);
4413   if (NewStep.isInvalid())
4414     return ExprError();
4415   ExprResult Update =
4416       SemaRef.BuildBinOp(S, Loc, BO_Mul, Iter.get(), NewStep.get());
4417   if (!Update.isUsable())
4418     return ExprError();
4419 
4420   // Try to build 'VarRef = Start, VarRef (+|-)= Iter * Step' or
4421   // 'VarRef = Start (+|-) Iter * Step'.
4422   ExprResult NewStart = Start;
4423   if (Captures)
4424     NewStart = tryBuildCapture(SemaRef, Start.get(), *Captures);
4425   if (NewStart.isInvalid())
4426     return ExprError();
4427 
4428   // First attempt: try to build 'VarRef = Start, VarRef += Iter * Step'.
4429   ExprResult SavedUpdate = Update;
4430   ExprResult UpdateVal;
4431   if (VarRef.get()->getType()->isOverloadableType() ||
4432       NewStart.get()->getType()->isOverloadableType() ||
4433       Update.get()->getType()->isOverloadableType()) {
4434     bool Suppress = SemaRef.getDiagnostics().getSuppressAllDiagnostics();
4435     SemaRef.getDiagnostics().setSuppressAllDiagnostics(/*Val=*/true);
4436     Update =
4437         SemaRef.BuildBinOp(S, Loc, BO_Assign, VarRef.get(), NewStart.get());
4438     if (Update.isUsable()) {
4439       UpdateVal =
4440           SemaRef.BuildBinOp(S, Loc, Subtract ? BO_SubAssign : BO_AddAssign,
4441                              VarRef.get(), SavedUpdate.get());
4442       if (UpdateVal.isUsable()) {
4443         Update = SemaRef.CreateBuiltinBinOp(Loc, BO_Comma, Update.get(),
4444                                             UpdateVal.get());
4445       }
4446     }
4447     SemaRef.getDiagnostics().setSuppressAllDiagnostics(Suppress);
4448   }
4449 
4450   // Second attempt: try to build 'VarRef = Start (+|-) Iter * Step'.
4451   if (!Update.isUsable() || !UpdateVal.isUsable()) {
4452     Update = SemaRef.BuildBinOp(S, Loc, Subtract ? BO_Sub : BO_Add,
4453                                 NewStart.get(), SavedUpdate.get());
4454     if (!Update.isUsable())
4455       return ExprError();
4456 
4457     if (!SemaRef.Context.hasSameType(Update.get()->getType(),
4458                                      VarRef.get()->getType())) {
4459       Update = SemaRef.PerformImplicitConversion(
4460           Update.get(), VarRef.get()->getType(), Sema::AA_Converting, true);
4461       if (!Update.isUsable())
4462         return ExprError();
4463     }
4464 
4465     Update = SemaRef.BuildBinOp(S, Loc, BO_Assign, VarRef.get(), Update.get());
4466   }
4467   return Update;
4468 }
4469 
4470 /// \brief Convert integer expression \a E to make it have at least \a Bits
4471 /// bits.
4472 static ExprResult WidenIterationCount(unsigned Bits, Expr *E, Sema &SemaRef) {
4473   if (E == nullptr)
4474     return ExprError();
4475   auto &C = SemaRef.Context;
4476   QualType OldType = E->getType();
4477   unsigned HasBits = C.getTypeSize(OldType);
4478   if (HasBits >= Bits)
4479     return ExprResult(E);
4480   // OK to convert to signed, because new type has more bits than old.
4481   QualType NewType = C.getIntTypeForBitwidth(Bits, /* Signed */ true);
4482   return SemaRef.PerformImplicitConversion(E, NewType, Sema::AA_Converting,
4483                                            true);
4484 }
4485 
4486 /// \brief Check if the given expression \a E is a constant integer that fits
4487 /// into \a Bits bits.
4488 static bool FitsInto(unsigned Bits, bool Signed, Expr *E, Sema &SemaRef) {
4489   if (E == nullptr)
4490     return false;
4491   llvm::APSInt Result;
4492   if (E->isIntegerConstantExpr(Result, SemaRef.Context))
4493     return Signed ? Result.isSignedIntN(Bits) : Result.isIntN(Bits);
4494   return false;
4495 }
4496 
4497 /// Build preinits statement for the given declarations.
4498 static Stmt *buildPreInits(ASTContext &Context,
4499                            MutableArrayRef<Decl *> PreInits) {
4500   if (!PreInits.empty()) {
4501     return new (Context) DeclStmt(
4502         DeclGroupRef::Create(Context, PreInits.begin(), PreInits.size()),
4503         SourceLocation(), SourceLocation());
4504   }
4505   return nullptr;
4506 }
4507 
4508 /// Build preinits statement for the given declarations.
4509 static Stmt *
4510 buildPreInits(ASTContext &Context,
4511               const llvm::MapVector<Expr *, DeclRefExpr *> &Captures) {
4512   if (!Captures.empty()) {
4513     SmallVector<Decl *, 16> PreInits;
4514     for (auto &Pair : Captures)
4515       PreInits.push_back(Pair.second->getDecl());
4516     return buildPreInits(Context, PreInits);
4517   }
4518   return nullptr;
4519 }
4520 
4521 /// Build postupdate expression for the given list of postupdates expressions.
4522 static Expr *buildPostUpdate(Sema &S, ArrayRef<Expr *> PostUpdates) {
4523   Expr *PostUpdate = nullptr;
4524   if (!PostUpdates.empty()) {
4525     for (auto *E : PostUpdates) {
4526       Expr *ConvE = S.BuildCStyleCastExpr(
4527                          E->getExprLoc(),
4528                          S.Context.getTrivialTypeSourceInfo(S.Context.VoidTy),
4529                          E->getExprLoc(), E)
4530                         .get();
4531       PostUpdate = PostUpdate
4532                        ? S.CreateBuiltinBinOp(ConvE->getExprLoc(), BO_Comma,
4533                                               PostUpdate, ConvE)
4534                              .get()
4535                        : ConvE;
4536     }
4537   }
4538   return PostUpdate;
4539 }
4540 
4541 /// \brief Called on a for stmt to check itself and nested loops (if any).
4542 /// \return Returns 0 if one of the collapsed stmts is not canonical for loop,
4543 /// number of collapsed loops otherwise.
4544 static unsigned
4545 CheckOpenMPLoop(OpenMPDirectiveKind DKind, Expr *CollapseLoopCountExpr,
4546                 Expr *OrderedLoopCountExpr, Stmt *AStmt, Sema &SemaRef,
4547                 DSAStackTy &DSA,
4548                 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA,
4549                 OMPLoopDirective::HelperExprs &Built) {
4550   unsigned NestedLoopCount = 1;
4551   if (CollapseLoopCountExpr) {
4552     // Found 'collapse' clause - calculate collapse number.
4553     llvm::APSInt Result;
4554     if (CollapseLoopCountExpr->EvaluateAsInt(Result, SemaRef.getASTContext()))
4555       NestedLoopCount = Result.getLimitedValue();
4556   }
4557   if (OrderedLoopCountExpr) {
4558     // Found 'ordered' clause - calculate collapse number.
4559     llvm::APSInt Result;
4560     if (OrderedLoopCountExpr->EvaluateAsInt(Result, SemaRef.getASTContext())) {
4561       if (Result.getLimitedValue() < NestedLoopCount) {
4562         SemaRef.Diag(OrderedLoopCountExpr->getExprLoc(),
4563                      diag::err_omp_wrong_ordered_loop_count)
4564             << OrderedLoopCountExpr->getSourceRange();
4565         SemaRef.Diag(CollapseLoopCountExpr->getExprLoc(),
4566                      diag::note_collapse_loop_count)
4567             << CollapseLoopCountExpr->getSourceRange();
4568       }
4569       NestedLoopCount = Result.getLimitedValue();
4570     }
4571   }
4572   // This is helper routine for loop directives (e.g., 'for', 'simd',
4573   // 'for simd', etc.).
4574   llvm::MapVector<Expr *, DeclRefExpr *> Captures;
4575   SmallVector<LoopIterationSpace, 4> IterSpaces;
4576   IterSpaces.resize(NestedLoopCount);
4577   Stmt *CurStmt = AStmt->IgnoreContainers(/* IgnoreCaptured */ true);
4578   for (unsigned Cnt = 0; Cnt < NestedLoopCount; ++Cnt) {
4579     if (CheckOpenMPIterationSpace(DKind, CurStmt, SemaRef, DSA, Cnt,
4580                                   NestedLoopCount, CollapseLoopCountExpr,
4581                                   OrderedLoopCountExpr, VarsWithImplicitDSA,
4582                                   IterSpaces[Cnt], Captures))
4583       return 0;
4584     // Move on to the next nested for loop, or to the loop body.
4585     // OpenMP [2.8.1, simd construct, Restrictions]
4586     // All loops associated with the construct must be perfectly nested; that
4587     // is, there must be no intervening code nor any OpenMP directive between
4588     // any two loops.
4589     CurStmt = cast<ForStmt>(CurStmt)->getBody()->IgnoreContainers();
4590   }
4591 
4592   Built.clear(/* size */ NestedLoopCount);
4593 
4594   if (SemaRef.CurContext->isDependentContext())
4595     return NestedLoopCount;
4596 
4597   // An example of what is generated for the following code:
4598   //
4599   //   #pragma omp simd collapse(2) ordered(2)
4600   //   for (i = 0; i < NI; ++i)
4601   //     for (k = 0; k < NK; ++k)
4602   //       for (j = J0; j < NJ; j+=2) {
4603   //         <loop body>
4604   //       }
4605   //
4606   // We generate the code below.
4607   // Note: the loop body may be outlined in CodeGen.
4608   // Note: some counters may be C++ classes, operator- is used to find number of
4609   // iterations and operator+= to calculate counter value.
4610   // Note: decltype(NumIterations) must be integer type (in 'omp for', only i32
4611   // or i64 is currently supported).
4612   //
4613   //   #define NumIterations (NI * ((NJ - J0 - 1 + 2) / 2))
4614   //   for (int[32|64]_t IV = 0; IV < NumIterations; ++IV ) {
4615   //     .local.i = IV / ((NJ - J0 - 1 + 2) / 2);
4616   //     .local.j = J0 + (IV % ((NJ - J0 - 1 + 2) / 2)) * 2;
4617   //     // similar updates for vars in clauses (e.g. 'linear')
4618   //     <loop body (using local i and j)>
4619   //   }
4620   //   i = NI; // assign final values of counters
4621   //   j = NJ;
4622   //
4623 
4624   // Last iteration number is (I1 * I2 * ... In) - 1, where I1, I2 ... In are
4625   // the iteration counts of the collapsed for loops.
4626   // Precondition tests if there is at least one iteration (all conditions are
4627   // true).
4628   auto PreCond = ExprResult(IterSpaces[0].PreCond);
4629   auto N0 = IterSpaces[0].NumIterations;
4630   ExprResult LastIteration32 = WidenIterationCount(
4631       32 /* Bits */, SemaRef
4632                          .PerformImplicitConversion(
4633                              N0->IgnoreImpCasts(), N0->getType(),
4634                              Sema::AA_Converting, /*AllowExplicit=*/true)
4635                          .get(),
4636       SemaRef);
4637   ExprResult LastIteration64 = WidenIterationCount(
4638       64 /* Bits */, SemaRef
4639                          .PerformImplicitConversion(
4640                              N0->IgnoreImpCasts(), N0->getType(),
4641                              Sema::AA_Converting, /*AllowExplicit=*/true)
4642                          .get(),
4643       SemaRef);
4644 
4645   if (!LastIteration32.isUsable() || !LastIteration64.isUsable())
4646     return NestedLoopCount;
4647 
4648   auto &C = SemaRef.Context;
4649   bool AllCountsNeedLessThan32Bits = C.getTypeSize(N0->getType()) < 32;
4650 
4651   Scope *CurScope = DSA.getCurScope();
4652   for (unsigned Cnt = 1; Cnt < NestedLoopCount; ++Cnt) {
4653     if (PreCond.isUsable()) {
4654       PreCond =
4655           SemaRef.BuildBinOp(CurScope, PreCond.get()->getExprLoc(), BO_LAnd,
4656                              PreCond.get(), IterSpaces[Cnt].PreCond);
4657     }
4658     auto N = IterSpaces[Cnt].NumIterations;
4659     SourceLocation Loc = N->getExprLoc();
4660     AllCountsNeedLessThan32Bits &= C.getTypeSize(N->getType()) < 32;
4661     if (LastIteration32.isUsable())
4662       LastIteration32 = SemaRef.BuildBinOp(
4663           CurScope, Loc, BO_Mul, LastIteration32.get(),
4664           SemaRef
4665               .PerformImplicitConversion(N->IgnoreImpCasts(), N->getType(),
4666                                          Sema::AA_Converting,
4667                                          /*AllowExplicit=*/true)
4668               .get());
4669     if (LastIteration64.isUsable())
4670       LastIteration64 = SemaRef.BuildBinOp(
4671           CurScope, Loc, BO_Mul, LastIteration64.get(),
4672           SemaRef
4673               .PerformImplicitConversion(N->IgnoreImpCasts(), N->getType(),
4674                                          Sema::AA_Converting,
4675                                          /*AllowExplicit=*/true)
4676               .get());
4677   }
4678 
4679   // Choose either the 32-bit or 64-bit version.
4680   ExprResult LastIteration = LastIteration64;
4681   if (LastIteration32.isUsable() &&
4682       C.getTypeSize(LastIteration32.get()->getType()) == 32 &&
4683       (AllCountsNeedLessThan32Bits || NestedLoopCount == 1 ||
4684        FitsInto(
4685            32 /* Bits */,
4686            LastIteration32.get()->getType()->hasSignedIntegerRepresentation(),
4687            LastIteration64.get(), SemaRef)))
4688     LastIteration = LastIteration32;
4689   QualType VType = LastIteration.get()->getType();
4690   QualType RealVType = VType;
4691   QualType StrideVType = VType;
4692   if (isOpenMPTaskLoopDirective(DKind)) {
4693     VType =
4694         SemaRef.Context.getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/0);
4695     StrideVType =
4696         SemaRef.Context.getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/1);
4697   }
4698 
4699   if (!LastIteration.isUsable())
4700     return 0;
4701 
4702   // Save the number of iterations.
4703   ExprResult NumIterations = LastIteration;
4704   {
4705     LastIteration = SemaRef.BuildBinOp(
4706         CurScope, LastIteration.get()->getExprLoc(), BO_Sub,
4707         LastIteration.get(),
4708         SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get());
4709     if (!LastIteration.isUsable())
4710       return 0;
4711   }
4712 
4713   // Calculate the last iteration number beforehand instead of doing this on
4714   // each iteration. Do not do this if the number of iterations may be kfold-ed.
4715   llvm::APSInt Result;
4716   bool IsConstant =
4717       LastIteration.get()->isIntegerConstantExpr(Result, SemaRef.Context);
4718   ExprResult CalcLastIteration;
4719   if (!IsConstant) {
4720     ExprResult SaveRef =
4721         tryBuildCapture(SemaRef, LastIteration.get(), Captures);
4722     LastIteration = SaveRef;
4723 
4724     // Prepare SaveRef + 1.
4725     NumIterations = SemaRef.BuildBinOp(
4726         CurScope, SaveRef.get()->getExprLoc(), BO_Add, SaveRef.get(),
4727         SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get());
4728     if (!NumIterations.isUsable())
4729       return 0;
4730   }
4731 
4732   SourceLocation InitLoc = IterSpaces[0].InitSrcRange.getBegin();
4733 
4734   // Build variables passed into runtime, necessary for worksharing directives.
4735   ExprResult LB, UB, IL, ST, EUB, CombLB, CombUB, PrevLB, PrevUB, CombEUB;
4736   if (isOpenMPWorksharingDirective(DKind) || isOpenMPTaskLoopDirective(DKind) ||
4737       isOpenMPDistributeDirective(DKind)) {
4738     // Lower bound variable, initialized with zero.
4739     VarDecl *LBDecl = buildVarDecl(SemaRef, InitLoc, VType, ".omp.lb");
4740     LB = buildDeclRefExpr(SemaRef, LBDecl, VType, InitLoc);
4741     SemaRef.AddInitializerToDecl(LBDecl,
4742                                  SemaRef.ActOnIntegerConstant(InitLoc, 0).get(),
4743                                  /*DirectInit*/ false);
4744 
4745     // Upper bound variable, initialized with last iteration number.
4746     VarDecl *UBDecl = buildVarDecl(SemaRef, InitLoc, VType, ".omp.ub");
4747     UB = buildDeclRefExpr(SemaRef, UBDecl, VType, InitLoc);
4748     SemaRef.AddInitializerToDecl(UBDecl, LastIteration.get(),
4749                                  /*DirectInit*/ false);
4750 
4751     // A 32-bit variable-flag where runtime returns 1 for the last iteration.
4752     // This will be used to implement clause 'lastprivate'.
4753     QualType Int32Ty = SemaRef.Context.getIntTypeForBitwidth(32, true);
4754     VarDecl *ILDecl = buildVarDecl(SemaRef, InitLoc, Int32Ty, ".omp.is_last");
4755     IL = buildDeclRefExpr(SemaRef, ILDecl, Int32Ty, InitLoc);
4756     SemaRef.AddInitializerToDecl(ILDecl,
4757                                  SemaRef.ActOnIntegerConstant(InitLoc, 0).get(),
4758                                  /*DirectInit*/ false);
4759 
4760     // Stride variable returned by runtime (we initialize it to 1 by default).
4761     VarDecl *STDecl =
4762         buildVarDecl(SemaRef, InitLoc, StrideVType, ".omp.stride");
4763     ST = buildDeclRefExpr(SemaRef, STDecl, StrideVType, InitLoc);
4764     SemaRef.AddInitializerToDecl(STDecl,
4765                                  SemaRef.ActOnIntegerConstant(InitLoc, 1).get(),
4766                                  /*DirectInit*/ false);
4767 
4768     // Build expression: UB = min(UB, LastIteration)
4769     // It is necessary for CodeGen of directives with static scheduling.
4770     ExprResult IsUBGreater = SemaRef.BuildBinOp(CurScope, InitLoc, BO_GT,
4771                                                 UB.get(), LastIteration.get());
4772     ExprResult CondOp = SemaRef.ActOnConditionalOp(
4773         InitLoc, InitLoc, IsUBGreater.get(), LastIteration.get(), UB.get());
4774     EUB = SemaRef.BuildBinOp(CurScope, InitLoc, BO_Assign, UB.get(),
4775                              CondOp.get());
4776     EUB = SemaRef.ActOnFinishFullExpr(EUB.get());
4777 
4778     // If we have a combined directive that combines 'distribute', 'for' or
4779     // 'simd' we need to be able to access the bounds of the schedule of the
4780     // enclosing region. E.g. in 'distribute parallel for' the bounds obtained
4781     // by scheduling 'distribute' have to be passed to the schedule of 'for'.
4782     if (isOpenMPLoopBoundSharingDirective(DKind)) {
4783 
4784       // Lower bound variable, initialized with zero.
4785       VarDecl *CombLBDecl =
4786           buildVarDecl(SemaRef, InitLoc, VType, ".omp.comb.lb");
4787       CombLB = buildDeclRefExpr(SemaRef, CombLBDecl, VType, InitLoc);
4788       SemaRef.AddInitializerToDecl(
4789           CombLBDecl, SemaRef.ActOnIntegerConstant(InitLoc, 0).get(),
4790           /*DirectInit*/ false);
4791 
4792       // Upper bound variable, initialized with last iteration number.
4793       VarDecl *CombUBDecl =
4794           buildVarDecl(SemaRef, InitLoc, VType, ".omp.comb.ub");
4795       CombUB = buildDeclRefExpr(SemaRef, CombUBDecl, VType, InitLoc);
4796       SemaRef.AddInitializerToDecl(CombUBDecl, LastIteration.get(),
4797                                    /*DirectInit*/ false);
4798 
4799       ExprResult CombIsUBGreater = SemaRef.BuildBinOp(
4800           CurScope, InitLoc, BO_GT, CombUB.get(), LastIteration.get());
4801       ExprResult CombCondOp =
4802           SemaRef.ActOnConditionalOp(InitLoc, InitLoc, CombIsUBGreater.get(),
4803                                      LastIteration.get(), CombUB.get());
4804       CombEUB = SemaRef.BuildBinOp(CurScope, InitLoc, BO_Assign, CombUB.get(),
4805                                    CombCondOp.get());
4806       CombEUB = SemaRef.ActOnFinishFullExpr(CombEUB.get());
4807 
4808       auto *CD = cast<CapturedStmt>(AStmt)->getCapturedDecl();
4809       // We expect to have at least 2 more parameters than the 'parallel'
4810       // directive does - the lower and upper bounds of the previous schedule.
4811       assert(CD->getNumParams() >= 4 &&
4812              "Unexpected number of parameters in loop combined directive");
4813 
4814       // Set the proper type for the bounds given what we learned from the
4815       // enclosed loops.
4816       auto *PrevLBDecl = CD->getParam(/*PrevLB=*/2);
4817       auto *PrevUBDecl = CD->getParam(/*PrevUB=*/3);
4818 
4819       // Previous lower and upper bounds are obtained from the region
4820       // parameters.
4821       PrevLB =
4822           buildDeclRefExpr(SemaRef, PrevLBDecl, PrevLBDecl->getType(), InitLoc);
4823       PrevUB =
4824           buildDeclRefExpr(SemaRef, PrevUBDecl, PrevUBDecl->getType(), InitLoc);
4825     }
4826   }
4827 
4828   // Build the iteration variable and its initialization before loop.
4829   ExprResult IV;
4830   ExprResult Init, CombInit;
4831   {
4832     VarDecl *IVDecl = buildVarDecl(SemaRef, InitLoc, RealVType, ".omp.iv");
4833     IV = buildDeclRefExpr(SemaRef, IVDecl, RealVType, InitLoc);
4834     Expr *RHS =
4835         (isOpenMPWorksharingDirective(DKind) ||
4836          isOpenMPTaskLoopDirective(DKind) || isOpenMPDistributeDirective(DKind))
4837             ? LB.get()
4838             : SemaRef.ActOnIntegerConstant(SourceLocation(), 0).get();
4839     Init = SemaRef.BuildBinOp(CurScope, InitLoc, BO_Assign, IV.get(), RHS);
4840     Init = SemaRef.ActOnFinishFullExpr(Init.get());
4841 
4842     if (isOpenMPLoopBoundSharingDirective(DKind)) {
4843       Expr *CombRHS =
4844           (isOpenMPWorksharingDirective(DKind) ||
4845            isOpenMPTaskLoopDirective(DKind) ||
4846            isOpenMPDistributeDirective(DKind))
4847               ? CombLB.get()
4848               : SemaRef.ActOnIntegerConstant(SourceLocation(), 0).get();
4849       CombInit =
4850           SemaRef.BuildBinOp(CurScope, InitLoc, BO_Assign, IV.get(), CombRHS);
4851       CombInit = SemaRef.ActOnFinishFullExpr(CombInit.get());
4852     }
4853   }
4854 
4855   // Loop condition (IV < NumIterations) or (IV <= UB) for worksharing loops.
4856   SourceLocation CondLoc;
4857   ExprResult Cond =
4858       (isOpenMPWorksharingDirective(DKind) ||
4859        isOpenMPTaskLoopDirective(DKind) || isOpenMPDistributeDirective(DKind))
4860           ? SemaRef.BuildBinOp(CurScope, CondLoc, BO_LE, IV.get(), UB.get())
4861           : SemaRef.BuildBinOp(CurScope, CondLoc, BO_LT, IV.get(),
4862                                NumIterations.get());
4863   ExprResult CombCond;
4864   if (isOpenMPLoopBoundSharingDirective(DKind)) {
4865     CombCond =
4866         SemaRef.BuildBinOp(CurScope, CondLoc, BO_LE, IV.get(), CombUB.get());
4867   }
4868   // Loop increment (IV = IV + 1)
4869   SourceLocation IncLoc;
4870   ExprResult Inc =
4871       SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, IV.get(),
4872                          SemaRef.ActOnIntegerConstant(IncLoc, 1).get());
4873   if (!Inc.isUsable())
4874     return 0;
4875   Inc = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, IV.get(), Inc.get());
4876   Inc = SemaRef.ActOnFinishFullExpr(Inc.get());
4877   if (!Inc.isUsable())
4878     return 0;
4879 
4880   // Increments for worksharing loops (LB = LB + ST; UB = UB + ST).
4881   // Used for directives with static scheduling.
4882   // In combined construct, add combined version that use CombLB and CombUB
4883   // base variables for the update
4884   ExprResult NextLB, NextUB, CombNextLB, CombNextUB;
4885   if (isOpenMPWorksharingDirective(DKind) || isOpenMPTaskLoopDirective(DKind) ||
4886       isOpenMPDistributeDirective(DKind)) {
4887     // LB + ST
4888     NextLB = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, LB.get(), ST.get());
4889     if (!NextLB.isUsable())
4890       return 0;
4891     // LB = LB + ST
4892     NextLB =
4893         SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, LB.get(), NextLB.get());
4894     NextLB = SemaRef.ActOnFinishFullExpr(NextLB.get());
4895     if (!NextLB.isUsable())
4896       return 0;
4897     // UB + ST
4898     NextUB = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, UB.get(), ST.get());
4899     if (!NextUB.isUsable())
4900       return 0;
4901     // UB = UB + ST
4902     NextUB =
4903         SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, UB.get(), NextUB.get());
4904     NextUB = SemaRef.ActOnFinishFullExpr(NextUB.get());
4905     if (!NextUB.isUsable())
4906       return 0;
4907     if (isOpenMPLoopBoundSharingDirective(DKind)) {
4908       CombNextLB =
4909           SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, CombLB.get(), ST.get());
4910       if (!NextLB.isUsable())
4911         return 0;
4912       // LB = LB + ST
4913       CombNextLB = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, CombLB.get(),
4914                                       CombNextLB.get());
4915       CombNextLB = SemaRef.ActOnFinishFullExpr(CombNextLB.get());
4916       if (!CombNextLB.isUsable())
4917         return 0;
4918       // UB + ST
4919       CombNextUB =
4920           SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, CombUB.get(), ST.get());
4921       if (!CombNextUB.isUsable())
4922         return 0;
4923       // UB = UB + ST
4924       CombNextUB = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, CombUB.get(),
4925                                       CombNextUB.get());
4926       CombNextUB = SemaRef.ActOnFinishFullExpr(CombNextUB.get());
4927       if (!CombNextUB.isUsable())
4928         return 0;
4929     }
4930   }
4931 
4932   // Create increment expression for distribute loop when combined in a same
4933   // directive with for as IV = IV + ST; ensure upper bound expression based
4934   // on PrevUB instead of NumIterations - used to implement 'for' when found
4935   // in combination with 'distribute', like in 'distribute parallel for'
4936   SourceLocation DistIncLoc;
4937   ExprResult DistCond, DistInc, PrevEUB;
4938   if (isOpenMPLoopBoundSharingDirective(DKind)) {
4939     DistCond = SemaRef.BuildBinOp(CurScope, CondLoc, BO_LE, IV.get(), UB.get());
4940     assert(DistCond.isUsable() && "distribute cond expr was not built");
4941 
4942     DistInc =
4943         SemaRef.BuildBinOp(CurScope, DistIncLoc, BO_Add, IV.get(), ST.get());
4944     assert(DistInc.isUsable() && "distribute inc expr was not built");
4945     DistInc = SemaRef.BuildBinOp(CurScope, DistIncLoc, BO_Assign, IV.get(),
4946                                  DistInc.get());
4947     DistInc = SemaRef.ActOnFinishFullExpr(DistInc.get());
4948     assert(DistInc.isUsable() && "distribute inc expr was not built");
4949 
4950     // Build expression: UB = min(UB, prevUB) for #for in composite or combined
4951     // construct
4952     SourceLocation DistEUBLoc;
4953     ExprResult IsUBGreater =
4954         SemaRef.BuildBinOp(CurScope, DistEUBLoc, BO_GT, UB.get(), PrevUB.get());
4955     ExprResult CondOp = SemaRef.ActOnConditionalOp(
4956         DistEUBLoc, DistEUBLoc, IsUBGreater.get(), PrevUB.get(), UB.get());
4957     PrevEUB = SemaRef.BuildBinOp(CurScope, DistIncLoc, BO_Assign, UB.get(),
4958                                  CondOp.get());
4959     PrevEUB = SemaRef.ActOnFinishFullExpr(PrevEUB.get());
4960   }
4961 
4962   // Build updates and final values of the loop counters.
4963   bool HasErrors = false;
4964   Built.Counters.resize(NestedLoopCount);
4965   Built.Inits.resize(NestedLoopCount);
4966   Built.Updates.resize(NestedLoopCount);
4967   Built.Finals.resize(NestedLoopCount);
4968   SmallVector<Expr *, 4> LoopMultipliers;
4969   {
4970     ExprResult Div;
4971     // Go from inner nested loop to outer.
4972     for (int Cnt = NestedLoopCount - 1; Cnt >= 0; --Cnt) {
4973       LoopIterationSpace &IS = IterSpaces[Cnt];
4974       SourceLocation UpdLoc = IS.IncSrcRange.getBegin();
4975       // Build: Iter = (IV / Div) % IS.NumIters
4976       // where Div is product of previous iterations' IS.NumIters.
4977       ExprResult Iter;
4978       if (Div.isUsable()) {
4979         Iter =
4980             SemaRef.BuildBinOp(CurScope, UpdLoc, BO_Div, IV.get(), Div.get());
4981       } else {
4982         Iter = IV;
4983         assert((Cnt == (int)NestedLoopCount - 1) &&
4984                "unusable div expected on first iteration only");
4985       }
4986 
4987       if (Cnt != 0 && Iter.isUsable())
4988         Iter = SemaRef.BuildBinOp(CurScope, UpdLoc, BO_Rem, Iter.get(),
4989                                   IS.NumIterations);
4990       if (!Iter.isUsable()) {
4991         HasErrors = true;
4992         break;
4993       }
4994 
4995       // Build update: IS.CounterVar(Private) = IS.Start + Iter * IS.Step
4996       auto *VD = cast<VarDecl>(cast<DeclRefExpr>(IS.CounterVar)->getDecl());
4997       auto *CounterVar = buildDeclRefExpr(SemaRef, VD, IS.CounterVar->getType(),
4998                                           IS.CounterVar->getExprLoc(),
4999                                           /*RefersToCapture=*/true);
5000       ExprResult Init = BuildCounterInit(SemaRef, CurScope, UpdLoc, CounterVar,
5001                                          IS.CounterInit, Captures);
5002       if (!Init.isUsable()) {
5003         HasErrors = true;
5004         break;
5005       }
5006       ExprResult Update = BuildCounterUpdate(
5007           SemaRef, CurScope, UpdLoc, CounterVar, IS.CounterInit, Iter,
5008           IS.CounterStep, IS.Subtract, &Captures);
5009       if (!Update.isUsable()) {
5010         HasErrors = true;
5011         break;
5012       }
5013 
5014       // Build final: IS.CounterVar = IS.Start + IS.NumIters * IS.Step
5015       ExprResult Final = BuildCounterUpdate(
5016           SemaRef, CurScope, UpdLoc, CounterVar, IS.CounterInit,
5017           IS.NumIterations, IS.CounterStep, IS.Subtract, &Captures);
5018       if (!Final.isUsable()) {
5019         HasErrors = true;
5020         break;
5021       }
5022 
5023       // Build Div for the next iteration: Div <- Div * IS.NumIters
5024       if (Cnt != 0) {
5025         if (Div.isUnset())
5026           Div = IS.NumIterations;
5027         else
5028           Div = SemaRef.BuildBinOp(CurScope, UpdLoc, BO_Mul, Div.get(),
5029                                    IS.NumIterations);
5030 
5031         // Add parentheses (for debugging purposes only).
5032         if (Div.isUsable())
5033           Div = tryBuildCapture(SemaRef, Div.get(), Captures);
5034         if (!Div.isUsable()) {
5035           HasErrors = true;
5036           break;
5037         }
5038         LoopMultipliers.push_back(Div.get());
5039       }
5040       if (!Update.isUsable() || !Final.isUsable()) {
5041         HasErrors = true;
5042         break;
5043       }
5044       // Save results
5045       Built.Counters[Cnt] = IS.CounterVar;
5046       Built.PrivateCounters[Cnt] = IS.PrivateCounterVar;
5047       Built.Inits[Cnt] = Init.get();
5048       Built.Updates[Cnt] = Update.get();
5049       Built.Finals[Cnt] = Final.get();
5050     }
5051   }
5052 
5053   if (HasErrors)
5054     return 0;
5055 
5056   // Save results
5057   Built.IterationVarRef = IV.get();
5058   Built.LastIteration = LastIteration.get();
5059   Built.NumIterations = NumIterations.get();
5060   Built.CalcLastIteration =
5061       SemaRef.ActOnFinishFullExpr(CalcLastIteration.get()).get();
5062   Built.PreCond = PreCond.get();
5063   Built.PreInits = buildPreInits(C, Captures);
5064   Built.Cond = Cond.get();
5065   Built.Init = Init.get();
5066   Built.Inc = Inc.get();
5067   Built.LB = LB.get();
5068   Built.UB = UB.get();
5069   Built.IL = IL.get();
5070   Built.ST = ST.get();
5071   Built.EUB = EUB.get();
5072   Built.NLB = NextLB.get();
5073   Built.NUB = NextUB.get();
5074   Built.PrevLB = PrevLB.get();
5075   Built.PrevUB = PrevUB.get();
5076   Built.DistInc = DistInc.get();
5077   Built.PrevEUB = PrevEUB.get();
5078   Built.DistCombinedFields.LB = CombLB.get();
5079   Built.DistCombinedFields.UB = CombUB.get();
5080   Built.DistCombinedFields.EUB = CombEUB.get();
5081   Built.DistCombinedFields.Init = CombInit.get();
5082   Built.DistCombinedFields.Cond = CombCond.get();
5083   Built.DistCombinedFields.NLB = CombNextLB.get();
5084   Built.DistCombinedFields.NUB = CombNextUB.get();
5085 
5086   Expr *CounterVal = SemaRef.DefaultLvalueConversion(IV.get()).get();
5087   // Fill data for doacross depend clauses.
5088   for (auto Pair : DSA.getDoacrossDependClauses()) {
5089     if (Pair.first->getDependencyKind() == OMPC_DEPEND_source)
5090       Pair.first->setCounterValue(CounterVal);
5091     else {
5092       if (NestedLoopCount != Pair.second.size() ||
5093           NestedLoopCount != LoopMultipliers.size() + 1) {
5094         // Erroneous case - clause has some problems.
5095         Pair.first->setCounterValue(CounterVal);
5096         continue;
5097       }
5098       assert(Pair.first->getDependencyKind() == OMPC_DEPEND_sink);
5099       auto I = Pair.second.rbegin();
5100       auto IS = IterSpaces.rbegin();
5101       auto ILM = LoopMultipliers.rbegin();
5102       Expr *UpCounterVal = CounterVal;
5103       Expr *Multiplier = nullptr;
5104       for (int Cnt = NestedLoopCount - 1; Cnt >= 0; --Cnt) {
5105         if (I->first) {
5106           assert(IS->CounterStep);
5107           Expr *NormalizedOffset =
5108               SemaRef
5109                   .BuildBinOp(CurScope, I->first->getExprLoc(), BO_Div,
5110                               I->first, IS->CounterStep)
5111                   .get();
5112           if (Multiplier) {
5113             NormalizedOffset =
5114                 SemaRef
5115                     .BuildBinOp(CurScope, I->first->getExprLoc(), BO_Mul,
5116                                 NormalizedOffset, Multiplier)
5117                     .get();
5118           }
5119           assert(I->second == OO_Plus || I->second == OO_Minus);
5120           BinaryOperatorKind BOK = (I->second == OO_Plus) ? BO_Add : BO_Sub;
5121           UpCounterVal = SemaRef
5122                              .BuildBinOp(CurScope, I->first->getExprLoc(), BOK,
5123                                          UpCounterVal, NormalizedOffset)
5124                              .get();
5125         }
5126         Multiplier = *ILM;
5127         ++I;
5128         ++IS;
5129         ++ILM;
5130       }
5131       Pair.first->setCounterValue(UpCounterVal);
5132     }
5133   }
5134 
5135   return NestedLoopCount;
5136 }
5137 
5138 static Expr *getCollapseNumberExpr(ArrayRef<OMPClause *> Clauses) {
5139   auto CollapseClauses =
5140       OMPExecutableDirective::getClausesOfKind<OMPCollapseClause>(Clauses);
5141   if (CollapseClauses.begin() != CollapseClauses.end())
5142     return (*CollapseClauses.begin())->getNumForLoops();
5143   return nullptr;
5144 }
5145 
5146 static Expr *getOrderedNumberExpr(ArrayRef<OMPClause *> Clauses) {
5147   auto OrderedClauses =
5148       OMPExecutableDirective::getClausesOfKind<OMPOrderedClause>(Clauses);
5149   if (OrderedClauses.begin() != OrderedClauses.end())
5150     return (*OrderedClauses.begin())->getNumForLoops();
5151   return nullptr;
5152 }
5153 
5154 static bool checkSimdlenSafelenSpecified(Sema &S,
5155                                          const ArrayRef<OMPClause *> Clauses) {
5156   OMPSafelenClause *Safelen = nullptr;
5157   OMPSimdlenClause *Simdlen = nullptr;
5158 
5159   for (auto *Clause : Clauses) {
5160     if (Clause->getClauseKind() == OMPC_safelen)
5161       Safelen = cast<OMPSafelenClause>(Clause);
5162     else if (Clause->getClauseKind() == OMPC_simdlen)
5163       Simdlen = cast<OMPSimdlenClause>(Clause);
5164     if (Safelen && Simdlen)
5165       break;
5166   }
5167 
5168   if (Simdlen && Safelen) {
5169     llvm::APSInt SimdlenRes, SafelenRes;
5170     auto SimdlenLength = Simdlen->getSimdlen();
5171     auto SafelenLength = Safelen->getSafelen();
5172     if (SimdlenLength->isValueDependent() || SimdlenLength->isTypeDependent() ||
5173         SimdlenLength->isInstantiationDependent() ||
5174         SimdlenLength->containsUnexpandedParameterPack())
5175       return false;
5176     if (SafelenLength->isValueDependent() || SafelenLength->isTypeDependent() ||
5177         SafelenLength->isInstantiationDependent() ||
5178         SafelenLength->containsUnexpandedParameterPack())
5179       return false;
5180     SimdlenLength->EvaluateAsInt(SimdlenRes, S.Context);
5181     SafelenLength->EvaluateAsInt(SafelenRes, S.Context);
5182     // OpenMP 4.5 [2.8.1, simd Construct, Restrictions]
5183     // If both simdlen and safelen clauses are specified, the value of the
5184     // simdlen parameter must be less than or equal to the value of the safelen
5185     // parameter.
5186     if (SimdlenRes > SafelenRes) {
5187       S.Diag(SimdlenLength->getExprLoc(),
5188              diag::err_omp_wrong_simdlen_safelen_values)
5189           << SimdlenLength->getSourceRange() << SafelenLength->getSourceRange();
5190       return true;
5191     }
5192   }
5193   return false;
5194 }
5195 
5196 StmtResult Sema::ActOnOpenMPSimdDirective(
5197     ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
5198     SourceLocation EndLoc,
5199     llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
5200   if (!AStmt)
5201     return StmtError();
5202 
5203   assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
5204   OMPLoopDirective::HelperExprs B;
5205   // In presence of clause 'collapse' or 'ordered' with number of loops, it will
5206   // define the nested loops number.
5207   unsigned NestedLoopCount = CheckOpenMPLoop(
5208       OMPD_simd, getCollapseNumberExpr(Clauses), getOrderedNumberExpr(Clauses),
5209       AStmt, *this, *DSAStack, VarsWithImplicitDSA, B);
5210   if (NestedLoopCount == 0)
5211     return StmtError();
5212 
5213   assert((CurContext->isDependentContext() || B.builtAll()) &&
5214          "omp simd loop exprs were not built");
5215 
5216   if (!CurContext->isDependentContext()) {
5217     // Finalize the clauses that need pre-built expressions for CodeGen.
5218     for (auto C : Clauses) {
5219       if (auto *LC = dyn_cast<OMPLinearClause>(C))
5220         if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
5221                                      B.NumIterations, *this, CurScope,
5222                                      DSAStack))
5223           return StmtError();
5224     }
5225   }
5226 
5227   if (checkSimdlenSafelenSpecified(*this, Clauses))
5228     return StmtError();
5229 
5230   getCurFunction()->setHasBranchProtectedScope();
5231   return OMPSimdDirective::Create(Context, StartLoc, EndLoc, NestedLoopCount,
5232                                   Clauses, AStmt, B);
5233 }
5234 
5235 StmtResult Sema::ActOnOpenMPForDirective(
5236     ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
5237     SourceLocation EndLoc,
5238     llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
5239   if (!AStmt)
5240     return StmtError();
5241 
5242   assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
5243   OMPLoopDirective::HelperExprs B;
5244   // In presence of clause 'collapse' or 'ordered' with number of loops, it will
5245   // define the nested loops number.
5246   unsigned NestedLoopCount = CheckOpenMPLoop(
5247       OMPD_for, getCollapseNumberExpr(Clauses), getOrderedNumberExpr(Clauses),
5248       AStmt, *this, *DSAStack, VarsWithImplicitDSA, B);
5249   if (NestedLoopCount == 0)
5250     return StmtError();
5251 
5252   assert((CurContext->isDependentContext() || B.builtAll()) &&
5253          "omp for loop exprs were not built");
5254 
5255   if (!CurContext->isDependentContext()) {
5256     // Finalize the clauses that need pre-built expressions for CodeGen.
5257     for (auto C : Clauses) {
5258       if (auto *LC = dyn_cast<OMPLinearClause>(C))
5259         if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
5260                                      B.NumIterations, *this, CurScope,
5261                                      DSAStack))
5262           return StmtError();
5263     }
5264   }
5265 
5266   getCurFunction()->setHasBranchProtectedScope();
5267   return OMPForDirective::Create(Context, StartLoc, EndLoc, NestedLoopCount,
5268                                  Clauses, AStmt, B, DSAStack->isCancelRegion());
5269 }
5270 
5271 StmtResult Sema::ActOnOpenMPForSimdDirective(
5272     ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
5273     SourceLocation EndLoc,
5274     llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
5275   if (!AStmt)
5276     return StmtError();
5277 
5278   assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
5279   OMPLoopDirective::HelperExprs B;
5280   // In presence of clause 'collapse' or 'ordered' with number of loops, it will
5281   // define the nested loops number.
5282   unsigned NestedLoopCount =
5283       CheckOpenMPLoop(OMPD_for_simd, getCollapseNumberExpr(Clauses),
5284                       getOrderedNumberExpr(Clauses), AStmt, *this, *DSAStack,
5285                       VarsWithImplicitDSA, B);
5286   if (NestedLoopCount == 0)
5287     return StmtError();
5288 
5289   assert((CurContext->isDependentContext() || B.builtAll()) &&
5290          "omp for simd loop exprs were not built");
5291 
5292   if (!CurContext->isDependentContext()) {
5293     // Finalize the clauses that need pre-built expressions for CodeGen.
5294     for (auto C : Clauses) {
5295       if (auto *LC = dyn_cast<OMPLinearClause>(C))
5296         if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
5297                                      B.NumIterations, *this, CurScope,
5298                                      DSAStack))
5299           return StmtError();
5300     }
5301   }
5302 
5303   if (checkSimdlenSafelenSpecified(*this, Clauses))
5304     return StmtError();
5305 
5306   getCurFunction()->setHasBranchProtectedScope();
5307   return OMPForSimdDirective::Create(Context, StartLoc, EndLoc, NestedLoopCount,
5308                                      Clauses, AStmt, B);
5309 }
5310 
5311 StmtResult Sema::ActOnOpenMPSectionsDirective(ArrayRef<OMPClause *> Clauses,
5312                                               Stmt *AStmt,
5313                                               SourceLocation StartLoc,
5314                                               SourceLocation EndLoc) {
5315   if (!AStmt)
5316     return StmtError();
5317 
5318   assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
5319   auto BaseStmt = AStmt;
5320   while (auto *CS = dyn_cast_or_null<CapturedStmt>(BaseStmt))
5321     BaseStmt = CS->getCapturedStmt();
5322   if (auto *C = dyn_cast_or_null<CompoundStmt>(BaseStmt)) {
5323     auto S = C->children();
5324     if (S.begin() == S.end())
5325       return StmtError();
5326     // All associated statements must be '#pragma omp section' except for
5327     // the first one.
5328     for (Stmt *SectionStmt : llvm::make_range(std::next(S.begin()), S.end())) {
5329       if (!SectionStmt || !isa<OMPSectionDirective>(SectionStmt)) {
5330         if (SectionStmt)
5331           Diag(SectionStmt->getLocStart(),
5332                diag::err_omp_sections_substmt_not_section);
5333         return StmtError();
5334       }
5335       cast<OMPSectionDirective>(SectionStmt)
5336           ->setHasCancel(DSAStack->isCancelRegion());
5337     }
5338   } else {
5339     Diag(AStmt->getLocStart(), diag::err_omp_sections_not_compound_stmt);
5340     return StmtError();
5341   }
5342 
5343   getCurFunction()->setHasBranchProtectedScope();
5344 
5345   return OMPSectionsDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt,
5346                                       DSAStack->isCancelRegion());
5347 }
5348 
5349 StmtResult Sema::ActOnOpenMPSectionDirective(Stmt *AStmt,
5350                                              SourceLocation StartLoc,
5351                                              SourceLocation EndLoc) {
5352   if (!AStmt)
5353     return StmtError();
5354 
5355   assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
5356 
5357   getCurFunction()->setHasBranchProtectedScope();
5358   DSAStack->setParentCancelRegion(DSAStack->isCancelRegion());
5359 
5360   return OMPSectionDirective::Create(Context, StartLoc, EndLoc, AStmt,
5361                                      DSAStack->isCancelRegion());
5362 }
5363 
5364 StmtResult Sema::ActOnOpenMPSingleDirective(ArrayRef<OMPClause *> Clauses,
5365                                             Stmt *AStmt,
5366                                             SourceLocation StartLoc,
5367                                             SourceLocation EndLoc) {
5368   if (!AStmt)
5369     return StmtError();
5370 
5371   assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
5372 
5373   getCurFunction()->setHasBranchProtectedScope();
5374 
5375   // OpenMP [2.7.3, single Construct, Restrictions]
5376   // The copyprivate clause must not be used with the nowait clause.
5377   OMPClause *Nowait = nullptr;
5378   OMPClause *Copyprivate = nullptr;
5379   for (auto *Clause : Clauses) {
5380     if (Clause->getClauseKind() == OMPC_nowait)
5381       Nowait = Clause;
5382     else if (Clause->getClauseKind() == OMPC_copyprivate)
5383       Copyprivate = Clause;
5384     if (Copyprivate && Nowait) {
5385       Diag(Copyprivate->getLocStart(),
5386            diag::err_omp_single_copyprivate_with_nowait);
5387       Diag(Nowait->getLocStart(), diag::note_omp_nowait_clause_here);
5388       return StmtError();
5389     }
5390   }
5391 
5392   return OMPSingleDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt);
5393 }
5394 
5395 StmtResult Sema::ActOnOpenMPMasterDirective(Stmt *AStmt,
5396                                             SourceLocation StartLoc,
5397                                             SourceLocation EndLoc) {
5398   if (!AStmt)
5399     return StmtError();
5400 
5401   assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
5402 
5403   getCurFunction()->setHasBranchProtectedScope();
5404 
5405   return OMPMasterDirective::Create(Context, StartLoc, EndLoc, AStmt);
5406 }
5407 
5408 StmtResult Sema::ActOnOpenMPCriticalDirective(
5409     const DeclarationNameInfo &DirName, ArrayRef<OMPClause *> Clauses,
5410     Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc) {
5411   if (!AStmt)
5412     return StmtError();
5413 
5414   assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
5415 
5416   bool ErrorFound = false;
5417   llvm::APSInt Hint;
5418   SourceLocation HintLoc;
5419   bool DependentHint = false;
5420   for (auto *C : Clauses) {
5421     if (C->getClauseKind() == OMPC_hint) {
5422       if (!DirName.getName()) {
5423         Diag(C->getLocStart(), diag::err_omp_hint_clause_no_name);
5424         ErrorFound = true;
5425       }
5426       Expr *E = cast<OMPHintClause>(C)->getHint();
5427       if (E->isTypeDependent() || E->isValueDependent() ||
5428           E->isInstantiationDependent())
5429         DependentHint = true;
5430       else {
5431         Hint = E->EvaluateKnownConstInt(Context);
5432         HintLoc = C->getLocStart();
5433       }
5434     }
5435   }
5436   if (ErrorFound)
5437     return StmtError();
5438   auto Pair = DSAStack->getCriticalWithHint(DirName);
5439   if (Pair.first && DirName.getName() && !DependentHint) {
5440     if (llvm::APSInt::compareValues(Hint, Pair.second) != 0) {
5441       Diag(StartLoc, diag::err_omp_critical_with_hint);
5442       if (HintLoc.isValid()) {
5443         Diag(HintLoc, diag::note_omp_critical_hint_here)
5444             << 0 << Hint.toString(/*Radix=*/10, /*Signed=*/false);
5445       } else
5446         Diag(StartLoc, diag::note_omp_critical_no_hint) << 0;
5447       if (auto *C = Pair.first->getSingleClause<OMPHintClause>()) {
5448         Diag(C->getLocStart(), diag::note_omp_critical_hint_here)
5449             << 1
5450             << C->getHint()->EvaluateKnownConstInt(Context).toString(
5451                    /*Radix=*/10, /*Signed=*/false);
5452       } else
5453         Diag(Pair.first->getLocStart(), diag::note_omp_critical_no_hint) << 1;
5454     }
5455   }
5456 
5457   getCurFunction()->setHasBranchProtectedScope();
5458 
5459   auto *Dir = OMPCriticalDirective::Create(Context, DirName, StartLoc, EndLoc,
5460                                            Clauses, AStmt);
5461   if (!Pair.first && DirName.getName() && !DependentHint)
5462     DSAStack->addCriticalWithHint(Dir, Hint);
5463   return Dir;
5464 }
5465 
5466 StmtResult Sema::ActOnOpenMPParallelForDirective(
5467     ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
5468     SourceLocation EndLoc,
5469     llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
5470   if (!AStmt)
5471     return StmtError();
5472 
5473   CapturedStmt *CS = cast<CapturedStmt>(AStmt);
5474   // 1.2.2 OpenMP Language Terminology
5475   // Structured block - An executable statement with a single entry at the
5476   // top and a single exit at the bottom.
5477   // The point of exit cannot be a branch out of the structured block.
5478   // longjmp() and throw() must not violate the entry/exit criteria.
5479   CS->getCapturedDecl()->setNothrow();
5480 
5481   OMPLoopDirective::HelperExprs B;
5482   // In presence of clause 'collapse' or 'ordered' with number of loops, it will
5483   // define the nested loops number.
5484   unsigned NestedLoopCount =
5485       CheckOpenMPLoop(OMPD_parallel_for, getCollapseNumberExpr(Clauses),
5486                       getOrderedNumberExpr(Clauses), AStmt, *this, *DSAStack,
5487                       VarsWithImplicitDSA, B);
5488   if (NestedLoopCount == 0)
5489     return StmtError();
5490 
5491   assert((CurContext->isDependentContext() || B.builtAll()) &&
5492          "omp parallel for loop exprs were not built");
5493 
5494   if (!CurContext->isDependentContext()) {
5495     // Finalize the clauses that need pre-built expressions for CodeGen.
5496     for (auto C : Clauses) {
5497       if (auto *LC = dyn_cast<OMPLinearClause>(C))
5498         if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
5499                                      B.NumIterations, *this, CurScope,
5500                                      DSAStack))
5501           return StmtError();
5502     }
5503   }
5504 
5505   getCurFunction()->setHasBranchProtectedScope();
5506   return OMPParallelForDirective::Create(Context, StartLoc, EndLoc,
5507                                          NestedLoopCount, Clauses, AStmt, B,
5508                                          DSAStack->isCancelRegion());
5509 }
5510 
5511 StmtResult Sema::ActOnOpenMPParallelForSimdDirective(
5512     ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
5513     SourceLocation EndLoc,
5514     llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
5515   if (!AStmt)
5516     return StmtError();
5517 
5518   CapturedStmt *CS = cast<CapturedStmt>(AStmt);
5519   // 1.2.2 OpenMP Language Terminology
5520   // Structured block - An executable statement with a single entry at the
5521   // top and a single exit at the bottom.
5522   // The point of exit cannot be a branch out of the structured block.
5523   // longjmp() and throw() must not violate the entry/exit criteria.
5524   CS->getCapturedDecl()->setNothrow();
5525 
5526   OMPLoopDirective::HelperExprs B;
5527   // In presence of clause 'collapse' or 'ordered' with number of loops, it will
5528   // define the nested loops number.
5529   unsigned NestedLoopCount =
5530       CheckOpenMPLoop(OMPD_parallel_for_simd, getCollapseNumberExpr(Clauses),
5531                       getOrderedNumberExpr(Clauses), AStmt, *this, *DSAStack,
5532                       VarsWithImplicitDSA, B);
5533   if (NestedLoopCount == 0)
5534     return StmtError();
5535 
5536   if (!CurContext->isDependentContext()) {
5537     // Finalize the clauses that need pre-built expressions for CodeGen.
5538     for (auto C : Clauses) {
5539       if (auto *LC = dyn_cast<OMPLinearClause>(C))
5540         if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
5541                                      B.NumIterations, *this, CurScope,
5542                                      DSAStack))
5543           return StmtError();
5544     }
5545   }
5546 
5547   if (checkSimdlenSafelenSpecified(*this, Clauses))
5548     return StmtError();
5549 
5550   getCurFunction()->setHasBranchProtectedScope();
5551   return OMPParallelForSimdDirective::Create(
5552       Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
5553 }
5554 
5555 StmtResult
5556 Sema::ActOnOpenMPParallelSectionsDirective(ArrayRef<OMPClause *> Clauses,
5557                                            Stmt *AStmt, SourceLocation StartLoc,
5558                                            SourceLocation EndLoc) {
5559   if (!AStmt)
5560     return StmtError();
5561 
5562   assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
5563   auto BaseStmt = AStmt;
5564   while (auto *CS = dyn_cast_or_null<CapturedStmt>(BaseStmt))
5565     BaseStmt = CS->getCapturedStmt();
5566   if (auto *C = dyn_cast_or_null<CompoundStmt>(BaseStmt)) {
5567     auto S = C->children();
5568     if (S.begin() == S.end())
5569       return StmtError();
5570     // All associated statements must be '#pragma omp section' except for
5571     // the first one.
5572     for (Stmt *SectionStmt : llvm::make_range(std::next(S.begin()), S.end())) {
5573       if (!SectionStmt || !isa<OMPSectionDirective>(SectionStmt)) {
5574         if (SectionStmt)
5575           Diag(SectionStmt->getLocStart(),
5576                diag::err_omp_parallel_sections_substmt_not_section);
5577         return StmtError();
5578       }
5579       cast<OMPSectionDirective>(SectionStmt)
5580           ->setHasCancel(DSAStack->isCancelRegion());
5581     }
5582   } else {
5583     Diag(AStmt->getLocStart(),
5584          diag::err_omp_parallel_sections_not_compound_stmt);
5585     return StmtError();
5586   }
5587 
5588   getCurFunction()->setHasBranchProtectedScope();
5589 
5590   return OMPParallelSectionsDirective::Create(
5591       Context, StartLoc, EndLoc, Clauses, AStmt, DSAStack->isCancelRegion());
5592 }
5593 
5594 StmtResult Sema::ActOnOpenMPTaskDirective(ArrayRef<OMPClause *> Clauses,
5595                                           Stmt *AStmt, SourceLocation StartLoc,
5596                                           SourceLocation EndLoc) {
5597   if (!AStmt)
5598     return StmtError();
5599 
5600   auto *CS = cast<CapturedStmt>(AStmt);
5601   // 1.2.2 OpenMP Language Terminology
5602   // Structured block - An executable statement with a single entry at the
5603   // top and a single exit at the bottom.
5604   // The point of exit cannot be a branch out of the structured block.
5605   // longjmp() and throw() must not violate the entry/exit criteria.
5606   CS->getCapturedDecl()->setNothrow();
5607 
5608   getCurFunction()->setHasBranchProtectedScope();
5609 
5610   return OMPTaskDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt,
5611                                   DSAStack->isCancelRegion());
5612 }
5613 
5614 StmtResult Sema::ActOnOpenMPTaskyieldDirective(SourceLocation StartLoc,
5615                                                SourceLocation EndLoc) {
5616   return OMPTaskyieldDirective::Create(Context, StartLoc, EndLoc);
5617 }
5618 
5619 StmtResult Sema::ActOnOpenMPBarrierDirective(SourceLocation StartLoc,
5620                                              SourceLocation EndLoc) {
5621   return OMPBarrierDirective::Create(Context, StartLoc, EndLoc);
5622 }
5623 
5624 StmtResult Sema::ActOnOpenMPTaskwaitDirective(SourceLocation StartLoc,
5625                                               SourceLocation EndLoc) {
5626   return OMPTaskwaitDirective::Create(Context, StartLoc, EndLoc);
5627 }
5628 
5629 StmtResult Sema::ActOnOpenMPTaskgroupDirective(ArrayRef<OMPClause *> Clauses,
5630                                                Stmt *AStmt,
5631                                                SourceLocation StartLoc,
5632                                                SourceLocation EndLoc) {
5633   if (!AStmt)
5634     return StmtError();
5635 
5636   assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
5637 
5638   getCurFunction()->setHasBranchProtectedScope();
5639 
5640   return OMPTaskgroupDirective::Create(Context, StartLoc, EndLoc, Clauses,
5641                                        AStmt,
5642                                        DSAStack->getTaskgroupReductionRef());
5643 }
5644 
5645 StmtResult Sema::ActOnOpenMPFlushDirective(ArrayRef<OMPClause *> Clauses,
5646                                            SourceLocation StartLoc,
5647                                            SourceLocation EndLoc) {
5648   assert(Clauses.size() <= 1 && "Extra clauses in flush directive");
5649   return OMPFlushDirective::Create(Context, StartLoc, EndLoc, Clauses);
5650 }
5651 
5652 StmtResult Sema::ActOnOpenMPOrderedDirective(ArrayRef<OMPClause *> Clauses,
5653                                              Stmt *AStmt,
5654                                              SourceLocation StartLoc,
5655                                              SourceLocation EndLoc) {
5656   OMPClause *DependFound = nullptr;
5657   OMPClause *DependSourceClause = nullptr;
5658   OMPClause *DependSinkClause = nullptr;
5659   bool ErrorFound = false;
5660   OMPThreadsClause *TC = nullptr;
5661   OMPSIMDClause *SC = nullptr;
5662   for (auto *C : Clauses) {
5663     if (auto *DC = dyn_cast<OMPDependClause>(C)) {
5664       DependFound = C;
5665       if (DC->getDependencyKind() == OMPC_DEPEND_source) {
5666         if (DependSourceClause) {
5667           Diag(C->getLocStart(), diag::err_omp_more_one_clause)
5668               << getOpenMPDirectiveName(OMPD_ordered)
5669               << getOpenMPClauseName(OMPC_depend) << 2;
5670           ErrorFound = true;
5671         } else
5672           DependSourceClause = C;
5673         if (DependSinkClause) {
5674           Diag(C->getLocStart(), diag::err_omp_depend_sink_source_not_allowed)
5675               << 0;
5676           ErrorFound = true;
5677         }
5678       } else if (DC->getDependencyKind() == OMPC_DEPEND_sink) {
5679         if (DependSourceClause) {
5680           Diag(C->getLocStart(), diag::err_omp_depend_sink_source_not_allowed)
5681               << 1;
5682           ErrorFound = true;
5683         }
5684         DependSinkClause = C;
5685       }
5686     } else if (C->getClauseKind() == OMPC_threads)
5687       TC = cast<OMPThreadsClause>(C);
5688     else if (C->getClauseKind() == OMPC_simd)
5689       SC = cast<OMPSIMDClause>(C);
5690   }
5691   if (!ErrorFound && !SC &&
5692       isOpenMPSimdDirective(DSAStack->getParentDirective())) {
5693     // OpenMP [2.8.1,simd Construct, Restrictions]
5694     // An ordered construct with the simd clause is the only OpenMP construct
5695     // that can appear in the simd region.
5696     Diag(StartLoc, diag::err_omp_prohibited_region_simd);
5697     ErrorFound = true;
5698   } else if (DependFound && (TC || SC)) {
5699     Diag(DependFound->getLocStart(), diag::err_omp_depend_clause_thread_simd)
5700         << getOpenMPClauseName(TC ? TC->getClauseKind() : SC->getClauseKind());
5701     ErrorFound = true;
5702   } else if (DependFound && !DSAStack->getParentOrderedRegionParam()) {
5703     Diag(DependFound->getLocStart(),
5704          diag::err_omp_ordered_directive_without_param);
5705     ErrorFound = true;
5706   } else if (TC || Clauses.empty()) {
5707     if (auto *Param = DSAStack->getParentOrderedRegionParam()) {
5708       SourceLocation ErrLoc = TC ? TC->getLocStart() : StartLoc;
5709       Diag(ErrLoc, diag::err_omp_ordered_directive_with_param)
5710           << (TC != nullptr);
5711       Diag(Param->getLocStart(), diag::note_omp_ordered_param);
5712       ErrorFound = true;
5713     }
5714   }
5715   if ((!AStmt && !DependFound) || ErrorFound)
5716     return StmtError();
5717 
5718   if (AStmt) {
5719     assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
5720 
5721     getCurFunction()->setHasBranchProtectedScope();
5722   }
5723 
5724   return OMPOrderedDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt);
5725 }
5726 
5727 namespace {
5728 /// \brief Helper class for checking expression in 'omp atomic [update]'
5729 /// construct.
5730 class OpenMPAtomicUpdateChecker {
5731   /// \brief Error results for atomic update expressions.
5732   enum ExprAnalysisErrorCode {
5733     /// \brief A statement is not an expression statement.
5734     NotAnExpression,
5735     /// \brief Expression is not builtin binary or unary operation.
5736     NotABinaryOrUnaryExpression,
5737     /// \brief Unary operation is not post-/pre- increment/decrement operation.
5738     NotAnUnaryIncDecExpression,
5739     /// \brief An expression is not of scalar type.
5740     NotAScalarType,
5741     /// \brief A binary operation is not an assignment operation.
5742     NotAnAssignmentOp,
5743     /// \brief RHS part of the binary operation is not a binary expression.
5744     NotABinaryExpression,
5745     /// \brief RHS part is not additive/multiplicative/shift/biwise binary
5746     /// expression.
5747     NotABinaryOperator,
5748     /// \brief RHS binary operation does not have reference to the updated LHS
5749     /// part.
5750     NotAnUpdateExpression,
5751     /// \brief No errors is found.
5752     NoError
5753   };
5754   /// \brief Reference to Sema.
5755   Sema &SemaRef;
5756   /// \brief A location for note diagnostics (when error is found).
5757   SourceLocation NoteLoc;
5758   /// \brief 'x' lvalue part of the source atomic expression.
5759   Expr *X;
5760   /// \brief 'expr' rvalue part of the source atomic expression.
5761   Expr *E;
5762   /// \brief Helper expression of the form
5763   /// 'OpaqueValueExpr(x) binop OpaqueValueExpr(expr)' or
5764   /// 'OpaqueValueExpr(expr) binop OpaqueValueExpr(x)'.
5765   Expr *UpdateExpr;
5766   /// \brief Is 'x' a LHS in a RHS part of full update expression. It is
5767   /// important for non-associative operations.
5768   bool IsXLHSInRHSPart;
5769   BinaryOperatorKind Op;
5770   SourceLocation OpLoc;
5771   /// \brief true if the source expression is a postfix unary operation, false
5772   /// if it is a prefix unary operation.
5773   bool IsPostfixUpdate;
5774 
5775 public:
5776   OpenMPAtomicUpdateChecker(Sema &SemaRef)
5777       : SemaRef(SemaRef), X(nullptr), E(nullptr), UpdateExpr(nullptr),
5778         IsXLHSInRHSPart(false), Op(BO_PtrMemD), IsPostfixUpdate(false) {}
5779   /// \brief Check specified statement that it is suitable for 'atomic update'
5780   /// constructs and extract 'x', 'expr' and Operation from the original
5781   /// expression. If DiagId and NoteId == 0, then only check is performed
5782   /// without error notification.
5783   /// \param DiagId Diagnostic which should be emitted if error is found.
5784   /// \param NoteId Diagnostic note for the main error message.
5785   /// \return true if statement is not an update expression, false otherwise.
5786   bool checkStatement(Stmt *S, unsigned DiagId = 0, unsigned NoteId = 0);
5787   /// \brief Return the 'x' lvalue part of the source atomic expression.
5788   Expr *getX() const { return X; }
5789   /// \brief Return the 'expr' rvalue part of the source atomic expression.
5790   Expr *getExpr() const { return E; }
5791   /// \brief Return the update expression used in calculation of the updated
5792   /// value. Always has form 'OpaqueValueExpr(x) binop OpaqueValueExpr(expr)' or
5793   /// 'OpaqueValueExpr(expr) binop OpaqueValueExpr(x)'.
5794   Expr *getUpdateExpr() const { return UpdateExpr; }
5795   /// \brief Return true if 'x' is LHS in RHS part of full update expression,
5796   /// false otherwise.
5797   bool isXLHSInRHSPart() const { return IsXLHSInRHSPart; }
5798 
5799   /// \brief true if the source expression is a postfix unary operation, false
5800   /// if it is a prefix unary operation.
5801   bool isPostfixUpdate() const { return IsPostfixUpdate; }
5802 
5803 private:
5804   bool checkBinaryOperation(BinaryOperator *AtomicBinOp, unsigned DiagId = 0,
5805                             unsigned NoteId = 0);
5806 };
5807 } // namespace
5808 
5809 bool OpenMPAtomicUpdateChecker::checkBinaryOperation(
5810     BinaryOperator *AtomicBinOp, unsigned DiagId, unsigned NoteId) {
5811   ExprAnalysisErrorCode ErrorFound = NoError;
5812   SourceLocation ErrorLoc, NoteLoc;
5813   SourceRange ErrorRange, NoteRange;
5814   // Allowed constructs are:
5815   //  x = x binop expr;
5816   //  x = expr binop x;
5817   if (AtomicBinOp->getOpcode() == BO_Assign) {
5818     X = AtomicBinOp->getLHS();
5819     if (auto *AtomicInnerBinOp = dyn_cast<BinaryOperator>(
5820             AtomicBinOp->getRHS()->IgnoreParenImpCasts())) {
5821       if (AtomicInnerBinOp->isMultiplicativeOp() ||
5822           AtomicInnerBinOp->isAdditiveOp() || AtomicInnerBinOp->isShiftOp() ||
5823           AtomicInnerBinOp->isBitwiseOp()) {
5824         Op = AtomicInnerBinOp->getOpcode();
5825         OpLoc = AtomicInnerBinOp->getOperatorLoc();
5826         auto *LHS = AtomicInnerBinOp->getLHS();
5827         auto *RHS = AtomicInnerBinOp->getRHS();
5828         llvm::FoldingSetNodeID XId, LHSId, RHSId;
5829         X->IgnoreParenImpCasts()->Profile(XId, SemaRef.getASTContext(),
5830                                           /*Canonical=*/true);
5831         LHS->IgnoreParenImpCasts()->Profile(LHSId, SemaRef.getASTContext(),
5832                                             /*Canonical=*/true);
5833         RHS->IgnoreParenImpCasts()->Profile(RHSId, SemaRef.getASTContext(),
5834                                             /*Canonical=*/true);
5835         if (XId == LHSId) {
5836           E = RHS;
5837           IsXLHSInRHSPart = true;
5838         } else if (XId == RHSId) {
5839           E = LHS;
5840           IsXLHSInRHSPart = false;
5841         } else {
5842           ErrorLoc = AtomicInnerBinOp->getExprLoc();
5843           ErrorRange = AtomicInnerBinOp->getSourceRange();
5844           NoteLoc = X->getExprLoc();
5845           NoteRange = X->getSourceRange();
5846           ErrorFound = NotAnUpdateExpression;
5847         }
5848       } else {
5849         ErrorLoc = AtomicInnerBinOp->getExprLoc();
5850         ErrorRange = AtomicInnerBinOp->getSourceRange();
5851         NoteLoc = AtomicInnerBinOp->getOperatorLoc();
5852         NoteRange = SourceRange(NoteLoc, NoteLoc);
5853         ErrorFound = NotABinaryOperator;
5854       }
5855     } else {
5856       NoteLoc = ErrorLoc = AtomicBinOp->getRHS()->getExprLoc();
5857       NoteRange = ErrorRange = AtomicBinOp->getRHS()->getSourceRange();
5858       ErrorFound = NotABinaryExpression;
5859     }
5860   } else {
5861     ErrorLoc = AtomicBinOp->getExprLoc();
5862     ErrorRange = AtomicBinOp->getSourceRange();
5863     NoteLoc = AtomicBinOp->getOperatorLoc();
5864     NoteRange = SourceRange(NoteLoc, NoteLoc);
5865     ErrorFound = NotAnAssignmentOp;
5866   }
5867   if (ErrorFound != NoError && DiagId != 0 && NoteId != 0) {
5868     SemaRef.Diag(ErrorLoc, DiagId) << ErrorRange;
5869     SemaRef.Diag(NoteLoc, NoteId) << ErrorFound << NoteRange;
5870     return true;
5871   } else if (SemaRef.CurContext->isDependentContext())
5872     E = X = UpdateExpr = nullptr;
5873   return ErrorFound != NoError;
5874 }
5875 
5876 bool OpenMPAtomicUpdateChecker::checkStatement(Stmt *S, unsigned DiagId,
5877                                                unsigned NoteId) {
5878   ExprAnalysisErrorCode ErrorFound = NoError;
5879   SourceLocation ErrorLoc, NoteLoc;
5880   SourceRange ErrorRange, NoteRange;
5881   // Allowed constructs are:
5882   //  x++;
5883   //  x--;
5884   //  ++x;
5885   //  --x;
5886   //  x binop= expr;
5887   //  x = x binop expr;
5888   //  x = expr binop x;
5889   if (auto *AtomicBody = dyn_cast<Expr>(S)) {
5890     AtomicBody = AtomicBody->IgnoreParenImpCasts();
5891     if (AtomicBody->getType()->isScalarType() ||
5892         AtomicBody->isInstantiationDependent()) {
5893       if (auto *AtomicCompAssignOp = dyn_cast<CompoundAssignOperator>(
5894               AtomicBody->IgnoreParenImpCasts())) {
5895         // Check for Compound Assignment Operation
5896         Op = BinaryOperator::getOpForCompoundAssignment(
5897             AtomicCompAssignOp->getOpcode());
5898         OpLoc = AtomicCompAssignOp->getOperatorLoc();
5899         E = AtomicCompAssignOp->getRHS();
5900         X = AtomicCompAssignOp->getLHS()->IgnoreParens();
5901         IsXLHSInRHSPart = true;
5902       } else if (auto *AtomicBinOp = dyn_cast<BinaryOperator>(
5903                      AtomicBody->IgnoreParenImpCasts())) {
5904         // Check for Binary Operation
5905         if (checkBinaryOperation(AtomicBinOp, DiagId, NoteId))
5906           return true;
5907       } else if (auto *AtomicUnaryOp = dyn_cast<UnaryOperator>(
5908                      AtomicBody->IgnoreParenImpCasts())) {
5909         // Check for Unary Operation
5910         if (AtomicUnaryOp->isIncrementDecrementOp()) {
5911           IsPostfixUpdate = AtomicUnaryOp->isPostfix();
5912           Op = AtomicUnaryOp->isIncrementOp() ? BO_Add : BO_Sub;
5913           OpLoc = AtomicUnaryOp->getOperatorLoc();
5914           X = AtomicUnaryOp->getSubExpr()->IgnoreParens();
5915           E = SemaRef.ActOnIntegerConstant(OpLoc, /*uint64_t Val=*/1).get();
5916           IsXLHSInRHSPart = true;
5917         } else {
5918           ErrorFound = NotAnUnaryIncDecExpression;
5919           ErrorLoc = AtomicUnaryOp->getExprLoc();
5920           ErrorRange = AtomicUnaryOp->getSourceRange();
5921           NoteLoc = AtomicUnaryOp->getOperatorLoc();
5922           NoteRange = SourceRange(NoteLoc, NoteLoc);
5923         }
5924       } else if (!AtomicBody->isInstantiationDependent()) {
5925         ErrorFound = NotABinaryOrUnaryExpression;
5926         NoteLoc = ErrorLoc = AtomicBody->getExprLoc();
5927         NoteRange = ErrorRange = AtomicBody->getSourceRange();
5928       }
5929     } else {
5930       ErrorFound = NotAScalarType;
5931       NoteLoc = ErrorLoc = AtomicBody->getLocStart();
5932       NoteRange = ErrorRange = SourceRange(NoteLoc, NoteLoc);
5933     }
5934   } else {
5935     ErrorFound = NotAnExpression;
5936     NoteLoc = ErrorLoc = S->getLocStart();
5937     NoteRange = ErrorRange = SourceRange(NoteLoc, NoteLoc);
5938   }
5939   if (ErrorFound != NoError && DiagId != 0 && NoteId != 0) {
5940     SemaRef.Diag(ErrorLoc, DiagId) << ErrorRange;
5941     SemaRef.Diag(NoteLoc, NoteId) << ErrorFound << NoteRange;
5942     return true;
5943   } else if (SemaRef.CurContext->isDependentContext())
5944     E = X = UpdateExpr = nullptr;
5945   if (ErrorFound == NoError && E && X) {
5946     // Build an update expression of form 'OpaqueValueExpr(x) binop
5947     // OpaqueValueExpr(expr)' or 'OpaqueValueExpr(expr) binop
5948     // OpaqueValueExpr(x)' and then cast it to the type of the 'x' expression.
5949     auto *OVEX = new (SemaRef.getASTContext())
5950         OpaqueValueExpr(X->getExprLoc(), X->getType(), VK_RValue);
5951     auto *OVEExpr = new (SemaRef.getASTContext())
5952         OpaqueValueExpr(E->getExprLoc(), E->getType(), VK_RValue);
5953     auto Update =
5954         SemaRef.CreateBuiltinBinOp(OpLoc, Op, IsXLHSInRHSPart ? OVEX : OVEExpr,
5955                                    IsXLHSInRHSPart ? OVEExpr : OVEX);
5956     if (Update.isInvalid())
5957       return true;
5958     Update = SemaRef.PerformImplicitConversion(Update.get(), X->getType(),
5959                                                Sema::AA_Casting);
5960     if (Update.isInvalid())
5961       return true;
5962     UpdateExpr = Update.get();
5963   }
5964   return ErrorFound != NoError;
5965 }
5966 
5967 StmtResult Sema::ActOnOpenMPAtomicDirective(ArrayRef<OMPClause *> Clauses,
5968                                             Stmt *AStmt,
5969                                             SourceLocation StartLoc,
5970                                             SourceLocation EndLoc) {
5971   if (!AStmt)
5972     return StmtError();
5973 
5974   auto *CS = cast<CapturedStmt>(AStmt);
5975   // 1.2.2 OpenMP Language Terminology
5976   // Structured block - An executable statement with a single entry at the
5977   // top and a single exit at the bottom.
5978   // The point of exit cannot be a branch out of the structured block.
5979   // longjmp() and throw() must not violate the entry/exit criteria.
5980   OpenMPClauseKind AtomicKind = OMPC_unknown;
5981   SourceLocation AtomicKindLoc;
5982   for (auto *C : Clauses) {
5983     if (C->getClauseKind() == OMPC_read || C->getClauseKind() == OMPC_write ||
5984         C->getClauseKind() == OMPC_update ||
5985         C->getClauseKind() == OMPC_capture) {
5986       if (AtomicKind != OMPC_unknown) {
5987         Diag(C->getLocStart(), diag::err_omp_atomic_several_clauses)
5988             << SourceRange(C->getLocStart(), C->getLocEnd());
5989         Diag(AtomicKindLoc, diag::note_omp_atomic_previous_clause)
5990             << getOpenMPClauseName(AtomicKind);
5991       } else {
5992         AtomicKind = C->getClauseKind();
5993         AtomicKindLoc = C->getLocStart();
5994       }
5995     }
5996   }
5997 
5998   auto Body = CS->getCapturedStmt();
5999   if (auto *EWC = dyn_cast<ExprWithCleanups>(Body))
6000     Body = EWC->getSubExpr();
6001 
6002   Expr *X = nullptr;
6003   Expr *V = nullptr;
6004   Expr *E = nullptr;
6005   Expr *UE = nullptr;
6006   bool IsXLHSInRHSPart = false;
6007   bool IsPostfixUpdate = false;
6008   // OpenMP [2.12.6, atomic Construct]
6009   // In the next expressions:
6010   // * x and v (as applicable) are both l-value expressions with scalar type.
6011   // * During the execution of an atomic region, multiple syntactic
6012   // occurrences of x must designate the same storage location.
6013   // * Neither of v and expr (as applicable) may access the storage location
6014   // designated by x.
6015   // * Neither of x and expr (as applicable) may access the storage location
6016   // designated by v.
6017   // * expr is an expression with scalar type.
6018   // * binop is one of +, *, -, /, &, ^, |, <<, or >>.
6019   // * binop, binop=, ++, and -- are not overloaded operators.
6020   // * The expression x binop expr must be numerically equivalent to x binop
6021   // (expr). This requirement is satisfied if the operators in expr have
6022   // precedence greater than binop, or by using parentheses around expr or
6023   // subexpressions of expr.
6024   // * The expression expr binop x must be numerically equivalent to (expr)
6025   // binop x. This requirement is satisfied if the operators in expr have
6026   // precedence equal to or greater than binop, or by using parentheses around
6027   // expr or subexpressions of expr.
6028   // * For forms that allow multiple occurrences of x, the number of times
6029   // that x is evaluated is unspecified.
6030   if (AtomicKind == OMPC_read) {
6031     enum {
6032       NotAnExpression,
6033       NotAnAssignmentOp,
6034       NotAScalarType,
6035       NotAnLValue,
6036       NoError
6037     } ErrorFound = NoError;
6038     SourceLocation ErrorLoc, NoteLoc;
6039     SourceRange ErrorRange, NoteRange;
6040     // If clause is read:
6041     //  v = x;
6042     if (auto *AtomicBody = dyn_cast<Expr>(Body)) {
6043       auto *AtomicBinOp =
6044           dyn_cast<BinaryOperator>(AtomicBody->IgnoreParenImpCasts());
6045       if (AtomicBinOp && AtomicBinOp->getOpcode() == BO_Assign) {
6046         X = AtomicBinOp->getRHS()->IgnoreParenImpCasts();
6047         V = AtomicBinOp->getLHS()->IgnoreParenImpCasts();
6048         if ((X->isInstantiationDependent() || X->getType()->isScalarType()) &&
6049             (V->isInstantiationDependent() || V->getType()->isScalarType())) {
6050           if (!X->isLValue() || !V->isLValue()) {
6051             auto NotLValueExpr = X->isLValue() ? V : X;
6052             ErrorFound = NotAnLValue;
6053             ErrorLoc = AtomicBinOp->getExprLoc();
6054             ErrorRange = AtomicBinOp->getSourceRange();
6055             NoteLoc = NotLValueExpr->getExprLoc();
6056             NoteRange = NotLValueExpr->getSourceRange();
6057           }
6058         } else if (!X->isInstantiationDependent() ||
6059                    !V->isInstantiationDependent()) {
6060           auto NotScalarExpr =
6061               (X->isInstantiationDependent() || X->getType()->isScalarType())
6062                   ? V
6063                   : X;
6064           ErrorFound = NotAScalarType;
6065           ErrorLoc = AtomicBinOp->getExprLoc();
6066           ErrorRange = AtomicBinOp->getSourceRange();
6067           NoteLoc = NotScalarExpr->getExprLoc();
6068           NoteRange = NotScalarExpr->getSourceRange();
6069         }
6070       } else if (!AtomicBody->isInstantiationDependent()) {
6071         ErrorFound = NotAnAssignmentOp;
6072         ErrorLoc = AtomicBody->getExprLoc();
6073         ErrorRange = AtomicBody->getSourceRange();
6074         NoteLoc = AtomicBinOp ? AtomicBinOp->getOperatorLoc()
6075                               : AtomicBody->getExprLoc();
6076         NoteRange = AtomicBinOp ? AtomicBinOp->getSourceRange()
6077                                 : AtomicBody->getSourceRange();
6078       }
6079     } else {
6080       ErrorFound = NotAnExpression;
6081       NoteLoc = ErrorLoc = Body->getLocStart();
6082       NoteRange = ErrorRange = SourceRange(NoteLoc, NoteLoc);
6083     }
6084     if (ErrorFound != NoError) {
6085       Diag(ErrorLoc, diag::err_omp_atomic_read_not_expression_statement)
6086           << ErrorRange;
6087       Diag(NoteLoc, diag::note_omp_atomic_read_write) << ErrorFound
6088                                                       << NoteRange;
6089       return StmtError();
6090     } else if (CurContext->isDependentContext())
6091       V = X = nullptr;
6092   } else if (AtomicKind == OMPC_write) {
6093     enum {
6094       NotAnExpression,
6095       NotAnAssignmentOp,
6096       NotAScalarType,
6097       NotAnLValue,
6098       NoError
6099     } ErrorFound = NoError;
6100     SourceLocation ErrorLoc, NoteLoc;
6101     SourceRange ErrorRange, NoteRange;
6102     // If clause is write:
6103     //  x = expr;
6104     if (auto *AtomicBody = dyn_cast<Expr>(Body)) {
6105       auto *AtomicBinOp =
6106           dyn_cast<BinaryOperator>(AtomicBody->IgnoreParenImpCasts());
6107       if (AtomicBinOp && AtomicBinOp->getOpcode() == BO_Assign) {
6108         X = AtomicBinOp->getLHS();
6109         E = AtomicBinOp->getRHS();
6110         if ((X->isInstantiationDependent() || X->getType()->isScalarType()) &&
6111             (E->isInstantiationDependent() || E->getType()->isScalarType())) {
6112           if (!X->isLValue()) {
6113             ErrorFound = NotAnLValue;
6114             ErrorLoc = AtomicBinOp->getExprLoc();
6115             ErrorRange = AtomicBinOp->getSourceRange();
6116             NoteLoc = X->getExprLoc();
6117             NoteRange = X->getSourceRange();
6118           }
6119         } else if (!X->isInstantiationDependent() ||
6120                    !E->isInstantiationDependent()) {
6121           auto NotScalarExpr =
6122               (X->isInstantiationDependent() || X->getType()->isScalarType())
6123                   ? E
6124                   : X;
6125           ErrorFound = NotAScalarType;
6126           ErrorLoc = AtomicBinOp->getExprLoc();
6127           ErrorRange = AtomicBinOp->getSourceRange();
6128           NoteLoc = NotScalarExpr->getExprLoc();
6129           NoteRange = NotScalarExpr->getSourceRange();
6130         }
6131       } else if (!AtomicBody->isInstantiationDependent()) {
6132         ErrorFound = NotAnAssignmentOp;
6133         ErrorLoc = AtomicBody->getExprLoc();
6134         ErrorRange = AtomicBody->getSourceRange();
6135         NoteLoc = AtomicBinOp ? AtomicBinOp->getOperatorLoc()
6136                               : AtomicBody->getExprLoc();
6137         NoteRange = AtomicBinOp ? AtomicBinOp->getSourceRange()
6138                                 : AtomicBody->getSourceRange();
6139       }
6140     } else {
6141       ErrorFound = NotAnExpression;
6142       NoteLoc = ErrorLoc = Body->getLocStart();
6143       NoteRange = ErrorRange = SourceRange(NoteLoc, NoteLoc);
6144     }
6145     if (ErrorFound != NoError) {
6146       Diag(ErrorLoc, diag::err_omp_atomic_write_not_expression_statement)
6147           << ErrorRange;
6148       Diag(NoteLoc, diag::note_omp_atomic_read_write) << ErrorFound
6149                                                       << NoteRange;
6150       return StmtError();
6151     } else if (CurContext->isDependentContext())
6152       E = X = nullptr;
6153   } else if (AtomicKind == OMPC_update || AtomicKind == OMPC_unknown) {
6154     // If clause is update:
6155     //  x++;
6156     //  x--;
6157     //  ++x;
6158     //  --x;
6159     //  x binop= expr;
6160     //  x = x binop expr;
6161     //  x = expr binop x;
6162     OpenMPAtomicUpdateChecker Checker(*this);
6163     if (Checker.checkStatement(
6164             Body, (AtomicKind == OMPC_update)
6165                       ? diag::err_omp_atomic_update_not_expression_statement
6166                       : diag::err_omp_atomic_not_expression_statement,
6167             diag::note_omp_atomic_update))
6168       return StmtError();
6169     if (!CurContext->isDependentContext()) {
6170       E = Checker.getExpr();
6171       X = Checker.getX();
6172       UE = Checker.getUpdateExpr();
6173       IsXLHSInRHSPart = Checker.isXLHSInRHSPart();
6174     }
6175   } else if (AtomicKind == OMPC_capture) {
6176     enum {
6177       NotAnAssignmentOp,
6178       NotACompoundStatement,
6179       NotTwoSubstatements,
6180       NotASpecificExpression,
6181       NoError
6182     } ErrorFound = NoError;
6183     SourceLocation ErrorLoc, NoteLoc;
6184     SourceRange ErrorRange, NoteRange;
6185     if (auto *AtomicBody = dyn_cast<Expr>(Body)) {
6186       // If clause is a capture:
6187       //  v = x++;
6188       //  v = x--;
6189       //  v = ++x;
6190       //  v = --x;
6191       //  v = x binop= expr;
6192       //  v = x = x binop expr;
6193       //  v = x = expr binop x;
6194       auto *AtomicBinOp =
6195           dyn_cast<BinaryOperator>(AtomicBody->IgnoreParenImpCasts());
6196       if (AtomicBinOp && AtomicBinOp->getOpcode() == BO_Assign) {
6197         V = AtomicBinOp->getLHS();
6198         Body = AtomicBinOp->getRHS()->IgnoreParenImpCasts();
6199         OpenMPAtomicUpdateChecker Checker(*this);
6200         if (Checker.checkStatement(
6201                 Body, diag::err_omp_atomic_capture_not_expression_statement,
6202                 diag::note_omp_atomic_update))
6203           return StmtError();
6204         E = Checker.getExpr();
6205         X = Checker.getX();
6206         UE = Checker.getUpdateExpr();
6207         IsXLHSInRHSPart = Checker.isXLHSInRHSPart();
6208         IsPostfixUpdate = Checker.isPostfixUpdate();
6209       } else if (!AtomicBody->isInstantiationDependent()) {
6210         ErrorLoc = AtomicBody->getExprLoc();
6211         ErrorRange = AtomicBody->getSourceRange();
6212         NoteLoc = AtomicBinOp ? AtomicBinOp->getOperatorLoc()
6213                               : AtomicBody->getExprLoc();
6214         NoteRange = AtomicBinOp ? AtomicBinOp->getSourceRange()
6215                                 : AtomicBody->getSourceRange();
6216         ErrorFound = NotAnAssignmentOp;
6217       }
6218       if (ErrorFound != NoError) {
6219         Diag(ErrorLoc, diag::err_omp_atomic_capture_not_expression_statement)
6220             << ErrorRange;
6221         Diag(NoteLoc, diag::note_omp_atomic_capture) << ErrorFound << NoteRange;
6222         return StmtError();
6223       } else if (CurContext->isDependentContext()) {
6224         UE = V = E = X = nullptr;
6225       }
6226     } else {
6227       // If clause is a capture:
6228       //  { v = x; x = expr; }
6229       //  { v = x; x++; }
6230       //  { v = x; x--; }
6231       //  { v = x; ++x; }
6232       //  { v = x; --x; }
6233       //  { v = x; x binop= expr; }
6234       //  { v = x; x = x binop expr; }
6235       //  { v = x; x = expr binop x; }
6236       //  { x++; v = x; }
6237       //  { x--; v = x; }
6238       //  { ++x; v = x; }
6239       //  { --x; v = x; }
6240       //  { x binop= expr; v = x; }
6241       //  { x = x binop expr; v = x; }
6242       //  { x = expr binop x; v = x; }
6243       if (auto *CS = dyn_cast<CompoundStmt>(Body)) {
6244         // Check that this is { expr1; expr2; }
6245         if (CS->size() == 2) {
6246           auto *First = CS->body_front();
6247           auto *Second = CS->body_back();
6248           if (auto *EWC = dyn_cast<ExprWithCleanups>(First))
6249             First = EWC->getSubExpr()->IgnoreParenImpCasts();
6250           if (auto *EWC = dyn_cast<ExprWithCleanups>(Second))
6251             Second = EWC->getSubExpr()->IgnoreParenImpCasts();
6252           // Need to find what subexpression is 'v' and what is 'x'.
6253           OpenMPAtomicUpdateChecker Checker(*this);
6254           bool IsUpdateExprFound = !Checker.checkStatement(Second);
6255           BinaryOperator *BinOp = nullptr;
6256           if (IsUpdateExprFound) {
6257             BinOp = dyn_cast<BinaryOperator>(First);
6258             IsUpdateExprFound = BinOp && BinOp->getOpcode() == BO_Assign;
6259           }
6260           if (IsUpdateExprFound && !CurContext->isDependentContext()) {
6261             //  { v = x; x++; }
6262             //  { v = x; x--; }
6263             //  { v = x; ++x; }
6264             //  { v = x; --x; }
6265             //  { v = x; x binop= expr; }
6266             //  { v = x; x = x binop expr; }
6267             //  { v = x; x = expr binop x; }
6268             // Check that the first expression has form v = x.
6269             auto *PossibleX = BinOp->getRHS()->IgnoreParenImpCasts();
6270             llvm::FoldingSetNodeID XId, PossibleXId;
6271             Checker.getX()->Profile(XId, Context, /*Canonical=*/true);
6272             PossibleX->Profile(PossibleXId, Context, /*Canonical=*/true);
6273             IsUpdateExprFound = XId == PossibleXId;
6274             if (IsUpdateExprFound) {
6275               V = BinOp->getLHS();
6276               X = Checker.getX();
6277               E = Checker.getExpr();
6278               UE = Checker.getUpdateExpr();
6279               IsXLHSInRHSPart = Checker.isXLHSInRHSPart();
6280               IsPostfixUpdate = true;
6281             }
6282           }
6283           if (!IsUpdateExprFound) {
6284             IsUpdateExprFound = !Checker.checkStatement(First);
6285             BinOp = nullptr;
6286             if (IsUpdateExprFound) {
6287               BinOp = dyn_cast<BinaryOperator>(Second);
6288               IsUpdateExprFound = BinOp && BinOp->getOpcode() == BO_Assign;
6289             }
6290             if (IsUpdateExprFound && !CurContext->isDependentContext()) {
6291               //  { x++; v = x; }
6292               //  { x--; v = x; }
6293               //  { ++x; v = x; }
6294               //  { --x; v = x; }
6295               //  { x binop= expr; v = x; }
6296               //  { x = x binop expr; v = x; }
6297               //  { x = expr binop x; v = x; }
6298               // Check that the second expression has form v = x.
6299               auto *PossibleX = BinOp->getRHS()->IgnoreParenImpCasts();
6300               llvm::FoldingSetNodeID XId, PossibleXId;
6301               Checker.getX()->Profile(XId, Context, /*Canonical=*/true);
6302               PossibleX->Profile(PossibleXId, Context, /*Canonical=*/true);
6303               IsUpdateExprFound = XId == PossibleXId;
6304               if (IsUpdateExprFound) {
6305                 V = BinOp->getLHS();
6306                 X = Checker.getX();
6307                 E = Checker.getExpr();
6308                 UE = Checker.getUpdateExpr();
6309                 IsXLHSInRHSPart = Checker.isXLHSInRHSPart();
6310                 IsPostfixUpdate = false;
6311               }
6312             }
6313           }
6314           if (!IsUpdateExprFound) {
6315             //  { v = x; x = expr; }
6316             auto *FirstExpr = dyn_cast<Expr>(First);
6317             auto *SecondExpr = dyn_cast<Expr>(Second);
6318             if (!FirstExpr || !SecondExpr ||
6319                 !(FirstExpr->isInstantiationDependent() ||
6320                   SecondExpr->isInstantiationDependent())) {
6321               auto *FirstBinOp = dyn_cast<BinaryOperator>(First);
6322               if (!FirstBinOp || FirstBinOp->getOpcode() != BO_Assign) {
6323                 ErrorFound = NotAnAssignmentOp;
6324                 NoteLoc = ErrorLoc = FirstBinOp ? FirstBinOp->getOperatorLoc()
6325                                                 : First->getLocStart();
6326                 NoteRange = ErrorRange = FirstBinOp
6327                                              ? FirstBinOp->getSourceRange()
6328                                              : SourceRange(ErrorLoc, ErrorLoc);
6329               } else {
6330                 auto *SecondBinOp = dyn_cast<BinaryOperator>(Second);
6331                 if (!SecondBinOp || SecondBinOp->getOpcode() != BO_Assign) {
6332                   ErrorFound = NotAnAssignmentOp;
6333                   NoteLoc = ErrorLoc = SecondBinOp
6334                                            ? SecondBinOp->getOperatorLoc()
6335                                            : Second->getLocStart();
6336                   NoteRange = ErrorRange =
6337                       SecondBinOp ? SecondBinOp->getSourceRange()
6338                                   : SourceRange(ErrorLoc, ErrorLoc);
6339                 } else {
6340                   auto *PossibleXRHSInFirst =
6341                       FirstBinOp->getRHS()->IgnoreParenImpCasts();
6342                   auto *PossibleXLHSInSecond =
6343                       SecondBinOp->getLHS()->IgnoreParenImpCasts();
6344                   llvm::FoldingSetNodeID X1Id, X2Id;
6345                   PossibleXRHSInFirst->Profile(X1Id, Context,
6346                                                /*Canonical=*/true);
6347                   PossibleXLHSInSecond->Profile(X2Id, Context,
6348                                                 /*Canonical=*/true);
6349                   IsUpdateExprFound = X1Id == X2Id;
6350                   if (IsUpdateExprFound) {
6351                     V = FirstBinOp->getLHS();
6352                     X = SecondBinOp->getLHS();
6353                     E = SecondBinOp->getRHS();
6354                     UE = nullptr;
6355                     IsXLHSInRHSPart = false;
6356                     IsPostfixUpdate = true;
6357                   } else {
6358                     ErrorFound = NotASpecificExpression;
6359                     ErrorLoc = FirstBinOp->getExprLoc();
6360                     ErrorRange = FirstBinOp->getSourceRange();
6361                     NoteLoc = SecondBinOp->getLHS()->getExprLoc();
6362                     NoteRange = SecondBinOp->getRHS()->getSourceRange();
6363                   }
6364                 }
6365               }
6366             }
6367           }
6368         } else {
6369           NoteLoc = ErrorLoc = Body->getLocStart();
6370           NoteRange = ErrorRange =
6371               SourceRange(Body->getLocStart(), Body->getLocStart());
6372           ErrorFound = NotTwoSubstatements;
6373         }
6374       } else {
6375         NoteLoc = ErrorLoc = Body->getLocStart();
6376         NoteRange = ErrorRange =
6377             SourceRange(Body->getLocStart(), Body->getLocStart());
6378         ErrorFound = NotACompoundStatement;
6379       }
6380       if (ErrorFound != NoError) {
6381         Diag(ErrorLoc, diag::err_omp_atomic_capture_not_compound_statement)
6382             << ErrorRange;
6383         Diag(NoteLoc, diag::note_omp_atomic_capture) << ErrorFound << NoteRange;
6384         return StmtError();
6385       } else if (CurContext->isDependentContext()) {
6386         UE = V = E = X = nullptr;
6387       }
6388     }
6389   }
6390 
6391   getCurFunction()->setHasBranchProtectedScope();
6392 
6393   return OMPAtomicDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt,
6394                                     X, V, E, UE, IsXLHSInRHSPart,
6395                                     IsPostfixUpdate);
6396 }
6397 
6398 StmtResult Sema::ActOnOpenMPTargetDirective(ArrayRef<OMPClause *> Clauses,
6399                                             Stmt *AStmt,
6400                                             SourceLocation StartLoc,
6401                                             SourceLocation EndLoc) {
6402   if (!AStmt)
6403     return StmtError();
6404 
6405   CapturedStmt *CS = cast<CapturedStmt>(AStmt);
6406   // 1.2.2 OpenMP Language Terminology
6407   // Structured block - An executable statement with a single entry at the
6408   // top and a single exit at the bottom.
6409   // The point of exit cannot be a branch out of the structured block.
6410   // longjmp() and throw() must not violate the entry/exit criteria.
6411   CS->getCapturedDecl()->setNothrow();
6412   for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target);
6413        ThisCaptureLevel > 1; --ThisCaptureLevel) {
6414     CS = cast<CapturedStmt>(CS->getCapturedStmt());
6415     // 1.2.2 OpenMP Language Terminology
6416     // Structured block - An executable statement with a single entry at the
6417     // top and a single exit at the bottom.
6418     // The point of exit cannot be a branch out of the structured block.
6419     // longjmp() and throw() must not violate the entry/exit criteria.
6420     CS->getCapturedDecl()->setNothrow();
6421   }
6422 
6423   // OpenMP [2.16, Nesting of Regions]
6424   // If specified, a teams construct must be contained within a target
6425   // construct. That target construct must contain no statements or directives
6426   // outside of the teams construct.
6427   if (DSAStack->hasInnerTeamsRegion()) {
6428     Stmt *S = CS->IgnoreContainers(/*IgnoreCaptured=*/true);
6429     bool OMPTeamsFound = true;
6430     if (auto *CS = dyn_cast<CompoundStmt>(S)) {
6431       auto I = CS->body_begin();
6432       while (I != CS->body_end()) {
6433         auto *OED = dyn_cast<OMPExecutableDirective>(*I);
6434         if (!OED || !isOpenMPTeamsDirective(OED->getDirectiveKind())) {
6435           OMPTeamsFound = false;
6436           break;
6437         }
6438         ++I;
6439       }
6440       assert(I != CS->body_end() && "Not found statement");
6441       S = *I;
6442     } else {
6443       auto *OED = dyn_cast<OMPExecutableDirective>(S);
6444       OMPTeamsFound = OED && isOpenMPTeamsDirective(OED->getDirectiveKind());
6445     }
6446     if (!OMPTeamsFound) {
6447       Diag(StartLoc, diag::err_omp_target_contains_not_only_teams);
6448       Diag(DSAStack->getInnerTeamsRegionLoc(),
6449            diag::note_omp_nested_teams_construct_here);
6450       Diag(S->getLocStart(), diag::note_omp_nested_statement_here)
6451           << isa<OMPExecutableDirective>(S);
6452       return StmtError();
6453     }
6454   }
6455 
6456   getCurFunction()->setHasBranchProtectedScope();
6457 
6458   return OMPTargetDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt);
6459 }
6460 
6461 StmtResult
6462 Sema::ActOnOpenMPTargetParallelDirective(ArrayRef<OMPClause *> Clauses,
6463                                          Stmt *AStmt, SourceLocation StartLoc,
6464                                          SourceLocation EndLoc) {
6465   if (!AStmt)
6466     return StmtError();
6467 
6468   CapturedStmt *CS = cast<CapturedStmt>(AStmt);
6469   // 1.2.2 OpenMP Language Terminology
6470   // Structured block - An executable statement with a single entry at the
6471   // top and a single exit at the bottom.
6472   // The point of exit cannot be a branch out of the structured block.
6473   // longjmp() and throw() must not violate the entry/exit criteria.
6474   CS->getCapturedDecl()->setNothrow();
6475   for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_parallel);
6476        ThisCaptureLevel > 1; --ThisCaptureLevel) {
6477     CS = cast<CapturedStmt>(CS->getCapturedStmt());
6478     // 1.2.2 OpenMP Language Terminology
6479     // Structured block - An executable statement with a single entry at the
6480     // top and a single exit at the bottom.
6481     // The point of exit cannot be a branch out of the structured block.
6482     // longjmp() and throw() must not violate the entry/exit criteria.
6483     CS->getCapturedDecl()->setNothrow();
6484   }
6485 
6486   getCurFunction()->setHasBranchProtectedScope();
6487 
6488   return OMPTargetParallelDirective::Create(Context, StartLoc, EndLoc, Clauses,
6489                                             AStmt);
6490 }
6491 
6492 StmtResult Sema::ActOnOpenMPTargetParallelForDirective(
6493     ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
6494     SourceLocation EndLoc,
6495     llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
6496   if (!AStmt)
6497     return StmtError();
6498 
6499   CapturedStmt *CS = cast<CapturedStmt>(AStmt);
6500   // 1.2.2 OpenMP Language Terminology
6501   // Structured block - An executable statement with a single entry at the
6502   // top and a single exit at the bottom.
6503   // The point of exit cannot be a branch out of the structured block.
6504   // longjmp() and throw() must not violate the entry/exit criteria.
6505   CS->getCapturedDecl()->setNothrow();
6506   for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_parallel_for);
6507        ThisCaptureLevel > 1; --ThisCaptureLevel) {
6508     CS = cast<CapturedStmt>(CS->getCapturedStmt());
6509     // 1.2.2 OpenMP Language Terminology
6510     // Structured block - An executable statement with a single entry at the
6511     // top and a single exit at the bottom.
6512     // The point of exit cannot be a branch out of the structured block.
6513     // longjmp() and throw() must not violate the entry/exit criteria.
6514     CS->getCapturedDecl()->setNothrow();
6515   }
6516 
6517   OMPLoopDirective::HelperExprs B;
6518   // In presence of clause 'collapse' or 'ordered' with number of loops, it will
6519   // define the nested loops number.
6520   unsigned NestedLoopCount =
6521       CheckOpenMPLoop(OMPD_target_parallel_for, getCollapseNumberExpr(Clauses),
6522                       getOrderedNumberExpr(Clauses), CS, *this, *DSAStack,
6523                       VarsWithImplicitDSA, B);
6524   if (NestedLoopCount == 0)
6525     return StmtError();
6526 
6527   assert((CurContext->isDependentContext() || B.builtAll()) &&
6528          "omp target parallel for loop exprs were not built");
6529 
6530   if (!CurContext->isDependentContext()) {
6531     // Finalize the clauses that need pre-built expressions for CodeGen.
6532     for (auto C : Clauses) {
6533       if (auto *LC = dyn_cast<OMPLinearClause>(C))
6534         if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
6535                                      B.NumIterations, *this, CurScope,
6536                                      DSAStack))
6537           return StmtError();
6538     }
6539   }
6540 
6541   getCurFunction()->setHasBranchProtectedScope();
6542   return OMPTargetParallelForDirective::Create(Context, StartLoc, EndLoc,
6543                                                NestedLoopCount, Clauses, AStmt,
6544                                                B, DSAStack->isCancelRegion());
6545 }
6546 
6547 /// Check for existence of a map clause in the list of clauses.
6548 static bool hasClauses(ArrayRef<OMPClause *> Clauses,
6549                        const OpenMPClauseKind K) {
6550   return llvm::any_of(
6551       Clauses, [K](const OMPClause *C) { return C->getClauseKind() == K; });
6552 }
6553 
6554 template <typename... Params>
6555 static bool hasClauses(ArrayRef<OMPClause *> Clauses, const OpenMPClauseKind K,
6556                        const Params... ClauseTypes) {
6557   return hasClauses(Clauses, K) || hasClauses(Clauses, ClauseTypes...);
6558 }
6559 
6560 StmtResult Sema::ActOnOpenMPTargetDataDirective(ArrayRef<OMPClause *> Clauses,
6561                                                 Stmt *AStmt,
6562                                                 SourceLocation StartLoc,
6563                                                 SourceLocation EndLoc) {
6564   if (!AStmt)
6565     return StmtError();
6566 
6567   assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
6568 
6569   // OpenMP [2.10.1, Restrictions, p. 97]
6570   // At least one map clause must appear on the directive.
6571   if (!hasClauses(Clauses, OMPC_map, OMPC_use_device_ptr)) {
6572     Diag(StartLoc, diag::err_omp_no_clause_for_directive)
6573         << "'map' or 'use_device_ptr'"
6574         << getOpenMPDirectiveName(OMPD_target_data);
6575     return StmtError();
6576   }
6577 
6578   getCurFunction()->setHasBranchProtectedScope();
6579 
6580   return OMPTargetDataDirective::Create(Context, StartLoc, EndLoc, Clauses,
6581                                         AStmt);
6582 }
6583 
6584 StmtResult
6585 Sema::ActOnOpenMPTargetEnterDataDirective(ArrayRef<OMPClause *> Clauses,
6586                                           SourceLocation StartLoc,
6587                                           SourceLocation EndLoc, Stmt *AStmt) {
6588   if (!AStmt)
6589     return StmtError();
6590 
6591   CapturedStmt *CS = cast<CapturedStmt>(AStmt);
6592   // 1.2.2 OpenMP Language Terminology
6593   // Structured block - An executable statement with a single entry at the
6594   // top and a single exit at the bottom.
6595   // The point of exit cannot be a branch out of the structured block.
6596   // longjmp() and throw() must not violate the entry/exit criteria.
6597   CS->getCapturedDecl()->setNothrow();
6598   for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_enter_data);
6599        ThisCaptureLevel > 1; --ThisCaptureLevel) {
6600     CS = cast<CapturedStmt>(CS->getCapturedStmt());
6601     // 1.2.2 OpenMP Language Terminology
6602     // Structured block - An executable statement with a single entry at the
6603     // top and a single exit at the bottom.
6604     // The point of exit cannot be a branch out of the structured block.
6605     // longjmp() and throw() must not violate the entry/exit criteria.
6606     CS->getCapturedDecl()->setNothrow();
6607   }
6608 
6609   // OpenMP [2.10.2, Restrictions, p. 99]
6610   // At least one map clause must appear on the directive.
6611   if (!hasClauses(Clauses, OMPC_map)) {
6612     Diag(StartLoc, diag::err_omp_no_clause_for_directive)
6613         << "'map'" << getOpenMPDirectiveName(OMPD_target_enter_data);
6614     return StmtError();
6615   }
6616 
6617   return OMPTargetEnterDataDirective::Create(Context, StartLoc, EndLoc, Clauses,
6618                                              AStmt);
6619 }
6620 
6621 StmtResult
6622 Sema::ActOnOpenMPTargetExitDataDirective(ArrayRef<OMPClause *> Clauses,
6623                                          SourceLocation StartLoc,
6624                                          SourceLocation EndLoc, Stmt *AStmt) {
6625   if (!AStmt)
6626     return StmtError();
6627 
6628   CapturedStmt *CS = cast<CapturedStmt>(AStmt);
6629   // 1.2.2 OpenMP Language Terminology
6630   // Structured block - An executable statement with a single entry at the
6631   // top and a single exit at the bottom.
6632   // The point of exit cannot be a branch out of the structured block.
6633   // longjmp() and throw() must not violate the entry/exit criteria.
6634   CS->getCapturedDecl()->setNothrow();
6635   for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_exit_data);
6636        ThisCaptureLevel > 1; --ThisCaptureLevel) {
6637     CS = cast<CapturedStmt>(CS->getCapturedStmt());
6638     // 1.2.2 OpenMP Language Terminology
6639     // Structured block - An executable statement with a single entry at the
6640     // top and a single exit at the bottom.
6641     // The point of exit cannot be a branch out of the structured block.
6642     // longjmp() and throw() must not violate the entry/exit criteria.
6643     CS->getCapturedDecl()->setNothrow();
6644   }
6645 
6646   // OpenMP [2.10.3, Restrictions, p. 102]
6647   // At least one map clause must appear on the directive.
6648   if (!hasClauses(Clauses, OMPC_map)) {
6649     Diag(StartLoc, diag::err_omp_no_clause_for_directive)
6650         << "'map'" << getOpenMPDirectiveName(OMPD_target_exit_data);
6651     return StmtError();
6652   }
6653 
6654   return OMPTargetExitDataDirective::Create(Context, StartLoc, EndLoc, Clauses,
6655                                             AStmt);
6656 }
6657 
6658 StmtResult Sema::ActOnOpenMPTargetUpdateDirective(ArrayRef<OMPClause *> Clauses,
6659                                                   SourceLocation StartLoc,
6660                                                   SourceLocation EndLoc,
6661                                                   Stmt *AStmt) {
6662   if (!AStmt)
6663     return StmtError();
6664 
6665   CapturedStmt *CS = cast<CapturedStmt>(AStmt);
6666   // 1.2.2 OpenMP Language Terminology
6667   // Structured block - An executable statement with a single entry at the
6668   // top and a single exit at the bottom.
6669   // The point of exit cannot be a branch out of the structured block.
6670   // longjmp() and throw() must not violate the entry/exit criteria.
6671   CS->getCapturedDecl()->setNothrow();
6672   for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_update);
6673        ThisCaptureLevel > 1; --ThisCaptureLevel) {
6674     CS = cast<CapturedStmt>(CS->getCapturedStmt());
6675     // 1.2.2 OpenMP Language Terminology
6676     // Structured block - An executable statement with a single entry at the
6677     // top and a single exit at the bottom.
6678     // The point of exit cannot be a branch out of the structured block.
6679     // longjmp() and throw() must not violate the entry/exit criteria.
6680     CS->getCapturedDecl()->setNothrow();
6681   }
6682 
6683   if (!hasClauses(Clauses, OMPC_to, OMPC_from)) {
6684     Diag(StartLoc, diag::err_omp_at_least_one_motion_clause_required);
6685     return StmtError();
6686   }
6687   return OMPTargetUpdateDirective::Create(Context, StartLoc, EndLoc, Clauses,
6688                                           AStmt);
6689 }
6690 
6691 StmtResult Sema::ActOnOpenMPTeamsDirective(ArrayRef<OMPClause *> Clauses,
6692                                            Stmt *AStmt, SourceLocation StartLoc,
6693                                            SourceLocation EndLoc) {
6694   if (!AStmt)
6695     return StmtError();
6696 
6697   CapturedStmt *CS = cast<CapturedStmt>(AStmt);
6698   // 1.2.2 OpenMP Language Terminology
6699   // Structured block - An executable statement with a single entry at the
6700   // top and a single exit at the bottom.
6701   // The point of exit cannot be a branch out of the structured block.
6702   // longjmp() and throw() must not violate the entry/exit criteria.
6703   CS->getCapturedDecl()->setNothrow();
6704 
6705   getCurFunction()->setHasBranchProtectedScope();
6706 
6707   DSAStack->setParentTeamsRegionLoc(StartLoc);
6708 
6709   return OMPTeamsDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt);
6710 }
6711 
6712 StmtResult
6713 Sema::ActOnOpenMPCancellationPointDirective(SourceLocation StartLoc,
6714                                             SourceLocation EndLoc,
6715                                             OpenMPDirectiveKind CancelRegion) {
6716   if (DSAStack->isParentNowaitRegion()) {
6717     Diag(StartLoc, diag::err_omp_parent_cancel_region_nowait) << 0;
6718     return StmtError();
6719   }
6720   if (DSAStack->isParentOrderedRegion()) {
6721     Diag(StartLoc, diag::err_omp_parent_cancel_region_ordered) << 0;
6722     return StmtError();
6723   }
6724   return OMPCancellationPointDirective::Create(Context, StartLoc, EndLoc,
6725                                                CancelRegion);
6726 }
6727 
6728 StmtResult Sema::ActOnOpenMPCancelDirective(ArrayRef<OMPClause *> Clauses,
6729                                             SourceLocation StartLoc,
6730                                             SourceLocation EndLoc,
6731                                             OpenMPDirectiveKind CancelRegion) {
6732   if (DSAStack->isParentNowaitRegion()) {
6733     Diag(StartLoc, diag::err_omp_parent_cancel_region_nowait) << 1;
6734     return StmtError();
6735   }
6736   if (DSAStack->isParentOrderedRegion()) {
6737     Diag(StartLoc, diag::err_omp_parent_cancel_region_ordered) << 1;
6738     return StmtError();
6739   }
6740   DSAStack->setParentCancelRegion(/*Cancel=*/true);
6741   return OMPCancelDirective::Create(Context, StartLoc, EndLoc, Clauses,
6742                                     CancelRegion);
6743 }
6744 
6745 static bool checkGrainsizeNumTasksClauses(Sema &S,
6746                                           ArrayRef<OMPClause *> Clauses) {
6747   OMPClause *PrevClause = nullptr;
6748   bool ErrorFound = false;
6749   for (auto *C : Clauses) {
6750     if (C->getClauseKind() == OMPC_grainsize ||
6751         C->getClauseKind() == OMPC_num_tasks) {
6752       if (!PrevClause)
6753         PrevClause = C;
6754       else if (PrevClause->getClauseKind() != C->getClauseKind()) {
6755         S.Diag(C->getLocStart(),
6756                diag::err_omp_grainsize_num_tasks_mutually_exclusive)
6757             << getOpenMPClauseName(C->getClauseKind())
6758             << getOpenMPClauseName(PrevClause->getClauseKind());
6759         S.Diag(PrevClause->getLocStart(),
6760                diag::note_omp_previous_grainsize_num_tasks)
6761             << getOpenMPClauseName(PrevClause->getClauseKind());
6762         ErrorFound = true;
6763       }
6764     }
6765   }
6766   return ErrorFound;
6767 }
6768 
6769 static bool checkReductionClauseWithNogroup(Sema &S,
6770                                             ArrayRef<OMPClause *> Clauses) {
6771   OMPClause *ReductionClause = nullptr;
6772   OMPClause *NogroupClause = nullptr;
6773   for (auto *C : Clauses) {
6774     if (C->getClauseKind() == OMPC_reduction) {
6775       ReductionClause = C;
6776       if (NogroupClause)
6777         break;
6778       continue;
6779     }
6780     if (C->getClauseKind() == OMPC_nogroup) {
6781       NogroupClause = C;
6782       if (ReductionClause)
6783         break;
6784       continue;
6785     }
6786   }
6787   if (ReductionClause && NogroupClause) {
6788     S.Diag(ReductionClause->getLocStart(), diag::err_omp_reduction_with_nogroup)
6789         << SourceRange(NogroupClause->getLocStart(),
6790                        NogroupClause->getLocEnd());
6791     return true;
6792   }
6793   return false;
6794 }
6795 
6796 StmtResult Sema::ActOnOpenMPTaskLoopDirective(
6797     ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
6798     SourceLocation EndLoc,
6799     llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
6800   if (!AStmt)
6801     return StmtError();
6802 
6803   assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
6804   OMPLoopDirective::HelperExprs B;
6805   // In presence of clause 'collapse' or 'ordered' with number of loops, it will
6806   // define the nested loops number.
6807   unsigned NestedLoopCount =
6808       CheckOpenMPLoop(OMPD_taskloop, getCollapseNumberExpr(Clauses),
6809                       /*OrderedLoopCountExpr=*/nullptr, AStmt, *this, *DSAStack,
6810                       VarsWithImplicitDSA, B);
6811   if (NestedLoopCount == 0)
6812     return StmtError();
6813 
6814   assert((CurContext->isDependentContext() || B.builtAll()) &&
6815          "omp for loop exprs were not built");
6816 
6817   // OpenMP, [2.9.2 taskloop Construct, Restrictions]
6818   // The grainsize clause and num_tasks clause are mutually exclusive and may
6819   // not appear on the same taskloop directive.
6820   if (checkGrainsizeNumTasksClauses(*this, Clauses))
6821     return StmtError();
6822   // OpenMP, [2.9.2 taskloop Construct, Restrictions]
6823   // If a reduction clause is present on the taskloop directive, the nogroup
6824   // clause must not be specified.
6825   if (checkReductionClauseWithNogroup(*this, Clauses))
6826     return StmtError();
6827 
6828   getCurFunction()->setHasBranchProtectedScope();
6829   return OMPTaskLoopDirective::Create(Context, StartLoc, EndLoc,
6830                                       NestedLoopCount, Clauses, AStmt, B);
6831 }
6832 
6833 StmtResult Sema::ActOnOpenMPTaskLoopSimdDirective(
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   assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
6841   OMPLoopDirective::HelperExprs B;
6842   // In presence of clause 'collapse' or 'ordered' with number of loops, it will
6843   // define the nested loops number.
6844   unsigned NestedLoopCount =
6845       CheckOpenMPLoop(OMPD_taskloop_simd, getCollapseNumberExpr(Clauses),
6846                       /*OrderedLoopCountExpr=*/nullptr, AStmt, *this, *DSAStack,
6847                       VarsWithImplicitDSA, B);
6848   if (NestedLoopCount == 0)
6849     return StmtError();
6850 
6851   assert((CurContext->isDependentContext() || B.builtAll()) &&
6852          "omp for loop exprs were not built");
6853 
6854   if (!CurContext->isDependentContext()) {
6855     // Finalize the clauses that need pre-built expressions for CodeGen.
6856     for (auto C : Clauses) {
6857       if (auto *LC = dyn_cast<OMPLinearClause>(C))
6858         if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
6859                                      B.NumIterations, *this, CurScope,
6860                                      DSAStack))
6861           return StmtError();
6862     }
6863   }
6864 
6865   // OpenMP, [2.9.2 taskloop Construct, Restrictions]
6866   // The grainsize clause and num_tasks clause are mutually exclusive and may
6867   // not appear on the same taskloop directive.
6868   if (checkGrainsizeNumTasksClauses(*this, Clauses))
6869     return StmtError();
6870   // OpenMP, [2.9.2 taskloop Construct, Restrictions]
6871   // If a reduction clause is present on the taskloop directive, the nogroup
6872   // clause must not be specified.
6873   if (checkReductionClauseWithNogroup(*this, Clauses))
6874     return StmtError();
6875   if (checkSimdlenSafelenSpecified(*this, Clauses))
6876     return StmtError();
6877 
6878   getCurFunction()->setHasBranchProtectedScope();
6879   return OMPTaskLoopSimdDirective::Create(Context, StartLoc, EndLoc,
6880                                           NestedLoopCount, Clauses, AStmt, B);
6881 }
6882 
6883 StmtResult Sema::ActOnOpenMPDistributeDirective(
6884     ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
6885     SourceLocation EndLoc,
6886     llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
6887   if (!AStmt)
6888     return StmtError();
6889 
6890   assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
6891   OMPLoopDirective::HelperExprs B;
6892   // In presence of clause 'collapse' with number of loops, it will
6893   // define the nested loops number.
6894   unsigned NestedLoopCount =
6895       CheckOpenMPLoop(OMPD_distribute, getCollapseNumberExpr(Clauses),
6896                       nullptr /*ordered not a clause on distribute*/, AStmt,
6897                       *this, *DSAStack, VarsWithImplicitDSA, B);
6898   if (NestedLoopCount == 0)
6899     return StmtError();
6900 
6901   assert((CurContext->isDependentContext() || B.builtAll()) &&
6902          "omp for loop exprs were not built");
6903 
6904   getCurFunction()->setHasBranchProtectedScope();
6905   return OMPDistributeDirective::Create(Context, StartLoc, EndLoc,
6906                                         NestedLoopCount, Clauses, AStmt, B);
6907 }
6908 
6909 StmtResult Sema::ActOnOpenMPDistributeParallelForDirective(
6910     ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
6911     SourceLocation EndLoc,
6912     llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
6913   if (!AStmt)
6914     return StmtError();
6915 
6916   CapturedStmt *CS = cast<CapturedStmt>(AStmt);
6917   // 1.2.2 OpenMP Language Terminology
6918   // Structured block - An executable statement with a single entry at the
6919   // top and a single exit at the bottom.
6920   // The point of exit cannot be a branch out of the structured block.
6921   // longjmp() and throw() must not violate the entry/exit criteria.
6922   CS->getCapturedDecl()->setNothrow();
6923   for (int ThisCaptureLevel =
6924            getOpenMPCaptureLevels(OMPD_distribute_parallel_for);
6925        ThisCaptureLevel > 1; --ThisCaptureLevel) {
6926     CS = cast<CapturedStmt>(CS->getCapturedStmt());
6927     // 1.2.2 OpenMP Language Terminology
6928     // Structured block - An executable statement with a single entry at the
6929     // top and a single exit at the bottom.
6930     // The point of exit cannot be a branch out of the structured block.
6931     // longjmp() and throw() must not violate the entry/exit criteria.
6932     CS->getCapturedDecl()->setNothrow();
6933   }
6934 
6935   OMPLoopDirective::HelperExprs B;
6936   // In presence of clause 'collapse' with number of loops, it will
6937   // define the nested loops number.
6938   unsigned NestedLoopCount = CheckOpenMPLoop(
6939       OMPD_distribute_parallel_for, getCollapseNumberExpr(Clauses),
6940       nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStack,
6941       VarsWithImplicitDSA, B);
6942   if (NestedLoopCount == 0)
6943     return StmtError();
6944 
6945   assert((CurContext->isDependentContext() || B.builtAll()) &&
6946          "omp for loop exprs were not built");
6947 
6948   getCurFunction()->setHasBranchProtectedScope();
6949   return OMPDistributeParallelForDirective::Create(
6950       Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B,
6951       DSAStack->isCancelRegion());
6952 }
6953 
6954 StmtResult Sema::ActOnOpenMPDistributeParallelForSimdDirective(
6955     ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
6956     SourceLocation EndLoc,
6957     llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
6958   if (!AStmt)
6959     return StmtError();
6960 
6961   CapturedStmt *CS = cast<CapturedStmt>(AStmt);
6962   // 1.2.2 OpenMP Language Terminology
6963   // Structured block - An executable statement with a single entry at the
6964   // top and a single exit at the bottom.
6965   // The point of exit cannot be a branch out of the structured block.
6966   // longjmp() and throw() must not violate the entry/exit criteria.
6967   CS->getCapturedDecl()->setNothrow();
6968   for (int ThisCaptureLevel =
6969            getOpenMPCaptureLevels(OMPD_distribute_parallel_for_simd);
6970        ThisCaptureLevel > 1; --ThisCaptureLevel) {
6971     CS = cast<CapturedStmt>(CS->getCapturedStmt());
6972     // 1.2.2 OpenMP Language Terminology
6973     // Structured block - An executable statement with a single entry at the
6974     // top and a single exit at the bottom.
6975     // The point of exit cannot be a branch out of the structured block.
6976     // longjmp() and throw() must not violate the entry/exit criteria.
6977     CS->getCapturedDecl()->setNothrow();
6978   }
6979 
6980   OMPLoopDirective::HelperExprs B;
6981   // In presence of clause 'collapse' with number of loops, it will
6982   // define the nested loops number.
6983   unsigned NestedLoopCount = CheckOpenMPLoop(
6984       OMPD_distribute_parallel_for_simd, getCollapseNumberExpr(Clauses),
6985       nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStack,
6986       VarsWithImplicitDSA, B);
6987   if (NestedLoopCount == 0)
6988     return StmtError();
6989 
6990   assert((CurContext->isDependentContext() || B.builtAll()) &&
6991          "omp for loop exprs were not built");
6992 
6993   if (!CurContext->isDependentContext()) {
6994     // Finalize the clauses that need pre-built expressions for CodeGen.
6995     for (auto C : Clauses) {
6996       if (auto *LC = dyn_cast<OMPLinearClause>(C))
6997         if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
6998                                      B.NumIterations, *this, CurScope,
6999                                      DSAStack))
7000           return StmtError();
7001     }
7002   }
7003 
7004   if (checkSimdlenSafelenSpecified(*this, Clauses))
7005     return StmtError();
7006 
7007   getCurFunction()->setHasBranchProtectedScope();
7008   return OMPDistributeParallelForSimdDirective::Create(
7009       Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
7010 }
7011 
7012 StmtResult Sema::ActOnOpenMPDistributeSimdDirective(
7013     ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
7014     SourceLocation EndLoc,
7015     llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
7016   if (!AStmt)
7017     return StmtError();
7018 
7019   CapturedStmt *CS = cast<CapturedStmt>(AStmt);
7020   // 1.2.2 OpenMP Language Terminology
7021   // Structured block - An executable statement with a single entry at the
7022   // top and a single exit at the bottom.
7023   // The point of exit cannot be a branch out of the structured block.
7024   // longjmp() and throw() must not violate the entry/exit criteria.
7025   CS->getCapturedDecl()->setNothrow();
7026   for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_distribute_simd);
7027        ThisCaptureLevel > 1; --ThisCaptureLevel) {
7028     CS = cast<CapturedStmt>(CS->getCapturedStmt());
7029     // 1.2.2 OpenMP Language Terminology
7030     // Structured block - An executable statement with a single entry at the
7031     // top and a single exit at the bottom.
7032     // The point of exit cannot be a branch out of the structured block.
7033     // longjmp() and throw() must not violate the entry/exit criteria.
7034     CS->getCapturedDecl()->setNothrow();
7035   }
7036 
7037   OMPLoopDirective::HelperExprs B;
7038   // In presence of clause 'collapse' with number of loops, it will
7039   // define the nested loops number.
7040   unsigned NestedLoopCount =
7041       CheckOpenMPLoop(OMPD_distribute_simd, getCollapseNumberExpr(Clauses),
7042                       nullptr /*ordered not a clause on distribute*/, CS, *this,
7043                       *DSAStack, VarsWithImplicitDSA, B);
7044   if (NestedLoopCount == 0)
7045     return StmtError();
7046 
7047   assert((CurContext->isDependentContext() || B.builtAll()) &&
7048          "omp for loop exprs were not built");
7049 
7050   if (!CurContext->isDependentContext()) {
7051     // Finalize the clauses that need pre-built expressions for CodeGen.
7052     for (auto C : Clauses) {
7053       if (auto *LC = dyn_cast<OMPLinearClause>(C))
7054         if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
7055                                      B.NumIterations, *this, CurScope,
7056                                      DSAStack))
7057           return StmtError();
7058     }
7059   }
7060 
7061   if (checkSimdlenSafelenSpecified(*this, Clauses))
7062     return StmtError();
7063 
7064   getCurFunction()->setHasBranchProtectedScope();
7065   return OMPDistributeSimdDirective::Create(Context, StartLoc, EndLoc,
7066                                             NestedLoopCount, Clauses, AStmt, B);
7067 }
7068 
7069 StmtResult Sema::ActOnOpenMPTargetParallelForSimdDirective(
7070     ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
7071     SourceLocation EndLoc,
7072     llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
7073   if (!AStmt)
7074     return StmtError();
7075 
7076   CapturedStmt *CS = cast<CapturedStmt>(AStmt);
7077   // 1.2.2 OpenMP Language Terminology
7078   // Structured block - An executable statement with a single entry at the
7079   // top and a single exit at the bottom.
7080   // The point of exit cannot be a branch out of the structured block.
7081   // longjmp() and throw() must not violate the entry/exit criteria.
7082   CS->getCapturedDecl()->setNothrow();
7083   for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_parallel_for);
7084        ThisCaptureLevel > 1; --ThisCaptureLevel) {
7085     CS = cast<CapturedStmt>(CS->getCapturedStmt());
7086     // 1.2.2 OpenMP Language Terminology
7087     // Structured block - An executable statement with a single entry at the
7088     // top and a single exit at the bottom.
7089     // The point of exit cannot be a branch out of the structured block.
7090     // longjmp() and throw() must not violate the entry/exit criteria.
7091     CS->getCapturedDecl()->setNothrow();
7092   }
7093 
7094   OMPLoopDirective::HelperExprs B;
7095   // In presence of clause 'collapse' or 'ordered' with number of loops, it will
7096   // define the nested loops number.
7097   unsigned NestedLoopCount = CheckOpenMPLoop(
7098       OMPD_target_parallel_for_simd, getCollapseNumberExpr(Clauses),
7099       getOrderedNumberExpr(Clauses), CS, *this, *DSAStack,
7100       VarsWithImplicitDSA, B);
7101   if (NestedLoopCount == 0)
7102     return StmtError();
7103 
7104   assert((CurContext->isDependentContext() || B.builtAll()) &&
7105          "omp target parallel for simd loop exprs were not built");
7106 
7107   if (!CurContext->isDependentContext()) {
7108     // Finalize the clauses that need pre-built expressions for CodeGen.
7109     for (auto C : Clauses) {
7110       if (auto *LC = dyn_cast<OMPLinearClause>(C))
7111         if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
7112                                      B.NumIterations, *this, CurScope,
7113                                      DSAStack))
7114           return StmtError();
7115     }
7116   }
7117   if (checkSimdlenSafelenSpecified(*this, Clauses))
7118     return StmtError();
7119 
7120   getCurFunction()->setHasBranchProtectedScope();
7121   return OMPTargetParallelForSimdDirective::Create(
7122       Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
7123 }
7124 
7125 StmtResult Sema::ActOnOpenMPTargetSimdDirective(
7126     ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
7127     SourceLocation EndLoc,
7128     llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
7129   if (!AStmt)
7130     return StmtError();
7131 
7132   CapturedStmt *CS = cast<CapturedStmt>(AStmt);
7133   // 1.2.2 OpenMP Language Terminology
7134   // Structured block - An executable statement with a single entry at the
7135   // top and a single exit at the bottom.
7136   // The point of exit cannot be a branch out of the structured block.
7137   // longjmp() and throw() must not violate the entry/exit criteria.
7138   CS->getCapturedDecl()->setNothrow();
7139   for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_simd);
7140        ThisCaptureLevel > 1; --ThisCaptureLevel) {
7141     CS = cast<CapturedStmt>(CS->getCapturedStmt());
7142     // 1.2.2 OpenMP Language Terminology
7143     // Structured block - An executable statement with a single entry at the
7144     // top and a single exit at the bottom.
7145     // The point of exit cannot be a branch out of the structured block.
7146     // longjmp() and throw() must not violate the entry/exit criteria.
7147     CS->getCapturedDecl()->setNothrow();
7148   }
7149 
7150   OMPLoopDirective::HelperExprs B;
7151   // In presence of clause 'collapse' with number of loops, it will define the
7152   // nested loops number.
7153   unsigned NestedLoopCount =
7154       CheckOpenMPLoop(OMPD_target_simd, getCollapseNumberExpr(Clauses),
7155                       getOrderedNumberExpr(Clauses), CS, *this, *DSAStack,
7156                       VarsWithImplicitDSA, B);
7157   if (NestedLoopCount == 0)
7158     return StmtError();
7159 
7160   assert((CurContext->isDependentContext() || B.builtAll()) &&
7161          "omp target simd loop exprs were not built");
7162 
7163   if (!CurContext->isDependentContext()) {
7164     // Finalize the clauses that need pre-built expressions for CodeGen.
7165     for (auto C : Clauses) {
7166       if (auto *LC = dyn_cast<OMPLinearClause>(C))
7167         if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
7168                                      B.NumIterations, *this, CurScope,
7169                                      DSAStack))
7170           return StmtError();
7171     }
7172   }
7173 
7174   if (checkSimdlenSafelenSpecified(*this, Clauses))
7175     return StmtError();
7176 
7177   getCurFunction()->setHasBranchProtectedScope();
7178   return OMPTargetSimdDirective::Create(Context, StartLoc, EndLoc,
7179                                         NestedLoopCount, Clauses, AStmt, B);
7180 }
7181 
7182 StmtResult Sema::ActOnOpenMPTeamsDistributeDirective(
7183     ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
7184     SourceLocation EndLoc,
7185     llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
7186   if (!AStmt)
7187     return StmtError();
7188 
7189   CapturedStmt *CS = cast<CapturedStmt>(AStmt);
7190   // 1.2.2 OpenMP Language Terminology
7191   // Structured block - An executable statement with a single entry at the
7192   // top and a single exit at the bottom.
7193   // The point of exit cannot be a branch out of the structured block.
7194   // longjmp() and throw() must not violate the entry/exit criteria.
7195   CS->getCapturedDecl()->setNothrow();
7196   for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_teams_distribute);
7197        ThisCaptureLevel > 1; --ThisCaptureLevel) {
7198     CS = cast<CapturedStmt>(CS->getCapturedStmt());
7199     // 1.2.2 OpenMP Language Terminology
7200     // Structured block - An executable statement with a single entry at the
7201     // top and a single exit at the bottom.
7202     // The point of exit cannot be a branch out of the structured block.
7203     // longjmp() and throw() must not violate the entry/exit criteria.
7204     CS->getCapturedDecl()->setNothrow();
7205   }
7206 
7207   OMPLoopDirective::HelperExprs B;
7208   // In presence of clause 'collapse' with number of loops, it will
7209   // define the nested loops number.
7210   unsigned NestedLoopCount =
7211       CheckOpenMPLoop(OMPD_teams_distribute, getCollapseNumberExpr(Clauses),
7212                       nullptr /*ordered not a clause on distribute*/, CS, *this,
7213                       *DSAStack, VarsWithImplicitDSA, B);
7214   if (NestedLoopCount == 0)
7215     return StmtError();
7216 
7217   assert((CurContext->isDependentContext() || B.builtAll()) &&
7218          "omp teams distribute loop exprs were not built");
7219 
7220   getCurFunction()->setHasBranchProtectedScope();
7221 
7222   DSAStack->setParentTeamsRegionLoc(StartLoc);
7223 
7224   return OMPTeamsDistributeDirective::Create(
7225       Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
7226 }
7227 
7228 StmtResult Sema::ActOnOpenMPTeamsDistributeSimdDirective(
7229     ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
7230     SourceLocation EndLoc,
7231     llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
7232   if (!AStmt)
7233     return StmtError();
7234 
7235   CapturedStmt *CS = cast<CapturedStmt>(AStmt);
7236   // 1.2.2 OpenMP Language Terminology
7237   // Structured block - An executable statement with a single entry at the
7238   // top and a single exit at the bottom.
7239   // The point of exit cannot be a branch out of the structured block.
7240   // longjmp() and throw() must not violate the entry/exit criteria.
7241   CS->getCapturedDecl()->setNothrow();
7242   for (int ThisCaptureLevel =
7243            getOpenMPCaptureLevels(OMPD_teams_distribute_simd);
7244        ThisCaptureLevel > 1; --ThisCaptureLevel) {
7245     CS = cast<CapturedStmt>(CS->getCapturedStmt());
7246     // 1.2.2 OpenMP Language Terminology
7247     // Structured block - An executable statement with a single entry at the
7248     // top and a single exit at the bottom.
7249     // The point of exit cannot be a branch out of the structured block.
7250     // longjmp() and throw() must not violate the entry/exit criteria.
7251     CS->getCapturedDecl()->setNothrow();
7252   }
7253 
7254 
7255   OMPLoopDirective::HelperExprs B;
7256   // In presence of clause 'collapse' with number of loops, it will
7257   // define the nested loops number.
7258   unsigned NestedLoopCount = CheckOpenMPLoop(
7259       OMPD_teams_distribute_simd, getCollapseNumberExpr(Clauses),
7260       nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStack,
7261       VarsWithImplicitDSA, B);
7262 
7263   if (NestedLoopCount == 0)
7264     return StmtError();
7265 
7266   assert((CurContext->isDependentContext() || B.builtAll()) &&
7267          "omp teams distribute simd loop exprs were not built");
7268 
7269   if (!CurContext->isDependentContext()) {
7270     // Finalize the clauses that need pre-built expressions for CodeGen.
7271     for (auto C : Clauses) {
7272       if (auto *LC = dyn_cast<OMPLinearClause>(C))
7273         if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
7274                                      B.NumIterations, *this, CurScope,
7275                                      DSAStack))
7276           return StmtError();
7277     }
7278   }
7279 
7280   if (checkSimdlenSafelenSpecified(*this, Clauses))
7281     return StmtError();
7282 
7283   getCurFunction()->setHasBranchProtectedScope();
7284 
7285   DSAStack->setParentTeamsRegionLoc(StartLoc);
7286 
7287   return OMPTeamsDistributeSimdDirective::Create(
7288       Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
7289 }
7290 
7291 StmtResult Sema::ActOnOpenMPTeamsDistributeParallelForSimdDirective(
7292     ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
7293     SourceLocation EndLoc,
7294     llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
7295   if (!AStmt)
7296     return StmtError();
7297 
7298   CapturedStmt *CS = cast<CapturedStmt>(AStmt);
7299   // 1.2.2 OpenMP Language Terminology
7300   // Structured block - An executable statement with a single entry at the
7301   // top and a single exit at the bottom.
7302   // The point of exit cannot be a branch out of the structured block.
7303   // longjmp() and throw() must not violate the entry/exit criteria.
7304   CS->getCapturedDecl()->setNothrow();
7305 
7306   for (int ThisCaptureLevel =
7307            getOpenMPCaptureLevels(OMPD_teams_distribute_parallel_for_simd);
7308        ThisCaptureLevel > 1; --ThisCaptureLevel) {
7309     CS = cast<CapturedStmt>(CS->getCapturedStmt());
7310     // 1.2.2 OpenMP Language Terminology
7311     // Structured block - An executable statement with a single entry at the
7312     // top and a single exit at the bottom.
7313     // The point of exit cannot be a branch out of the structured block.
7314     // longjmp() and throw() must not violate the entry/exit criteria.
7315     CS->getCapturedDecl()->setNothrow();
7316   }
7317 
7318   OMPLoopDirective::HelperExprs B;
7319   // In presence of clause 'collapse' with number of loops, it will
7320   // define the nested loops number.
7321   auto NestedLoopCount = CheckOpenMPLoop(
7322       OMPD_teams_distribute_parallel_for_simd, getCollapseNumberExpr(Clauses),
7323       nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStack,
7324       VarsWithImplicitDSA, B);
7325 
7326   if (NestedLoopCount == 0)
7327     return StmtError();
7328 
7329   assert((CurContext->isDependentContext() || B.builtAll()) &&
7330          "omp for loop exprs were not built");
7331 
7332   if (!CurContext->isDependentContext()) {
7333     // Finalize the clauses that need pre-built expressions for CodeGen.
7334     for (auto C : Clauses) {
7335       if (auto *LC = dyn_cast<OMPLinearClause>(C))
7336         if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
7337                                      B.NumIterations, *this, CurScope,
7338                                      DSAStack))
7339           return StmtError();
7340     }
7341   }
7342 
7343   if (checkSimdlenSafelenSpecified(*this, Clauses))
7344     return StmtError();
7345 
7346   getCurFunction()->setHasBranchProtectedScope();
7347 
7348   DSAStack->setParentTeamsRegionLoc(StartLoc);
7349 
7350   return OMPTeamsDistributeParallelForSimdDirective::Create(
7351       Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
7352 }
7353 
7354 StmtResult Sema::ActOnOpenMPTeamsDistributeParallelForDirective(
7355     ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
7356     SourceLocation EndLoc,
7357     llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
7358   if (!AStmt)
7359     return StmtError();
7360 
7361   CapturedStmt *CS = cast<CapturedStmt>(AStmt);
7362   // 1.2.2 OpenMP Language Terminology
7363   // Structured block - An executable statement with a single entry at the
7364   // top and a single exit at the bottom.
7365   // The point of exit cannot be a branch out of the structured block.
7366   // longjmp() and throw() must not violate the entry/exit criteria.
7367   CS->getCapturedDecl()->setNothrow();
7368 
7369   for (int ThisCaptureLevel =
7370            getOpenMPCaptureLevels(OMPD_teams_distribute_parallel_for);
7371        ThisCaptureLevel > 1; --ThisCaptureLevel) {
7372     CS = cast<CapturedStmt>(CS->getCapturedStmt());
7373     // 1.2.2 OpenMP Language Terminology
7374     // Structured block - An executable statement with a single entry at the
7375     // top and a single exit at the bottom.
7376     // The point of exit cannot be a branch out of the structured block.
7377     // longjmp() and throw() must not violate the entry/exit criteria.
7378     CS->getCapturedDecl()->setNothrow();
7379   }
7380 
7381   OMPLoopDirective::HelperExprs B;
7382   // In presence of clause 'collapse' with number of loops, it will
7383   // define the nested loops number.
7384   unsigned NestedLoopCount = CheckOpenMPLoop(
7385       OMPD_teams_distribute_parallel_for, getCollapseNumberExpr(Clauses),
7386       nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStack,
7387       VarsWithImplicitDSA, B);
7388 
7389   if (NestedLoopCount == 0)
7390     return StmtError();
7391 
7392   assert((CurContext->isDependentContext() || B.builtAll()) &&
7393          "omp for loop exprs were not built");
7394 
7395   getCurFunction()->setHasBranchProtectedScope();
7396 
7397   DSAStack->setParentTeamsRegionLoc(StartLoc);
7398 
7399   return OMPTeamsDistributeParallelForDirective::Create(
7400       Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B,
7401       DSAStack->isCancelRegion());
7402 }
7403 
7404 StmtResult Sema::ActOnOpenMPTargetTeamsDirective(ArrayRef<OMPClause *> Clauses,
7405                                                  Stmt *AStmt,
7406                                                  SourceLocation StartLoc,
7407                                                  SourceLocation EndLoc) {
7408   if (!AStmt)
7409     return StmtError();
7410 
7411   CapturedStmt *CS = cast<CapturedStmt>(AStmt);
7412   // 1.2.2 OpenMP Language Terminology
7413   // Structured block - An executable statement with a single entry at the
7414   // top and a single exit at the bottom.
7415   // The point of exit cannot be a branch out of the structured block.
7416   // longjmp() and throw() must not violate the entry/exit criteria.
7417   CS->getCapturedDecl()->setNothrow();
7418 
7419   for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_teams);
7420        ThisCaptureLevel > 1; --ThisCaptureLevel) {
7421     CS = cast<CapturedStmt>(CS->getCapturedStmt());
7422     // 1.2.2 OpenMP Language Terminology
7423     // Structured block - An executable statement with a single entry at the
7424     // top and a single exit at the bottom.
7425     // The point of exit cannot be a branch out of the structured block.
7426     // longjmp() and throw() must not violate the entry/exit criteria.
7427     CS->getCapturedDecl()->setNothrow();
7428   }
7429   getCurFunction()->setHasBranchProtectedScope();
7430 
7431   return OMPTargetTeamsDirective::Create(Context, StartLoc, EndLoc, Clauses,
7432                                          AStmt);
7433 }
7434 
7435 StmtResult Sema::ActOnOpenMPTargetTeamsDistributeDirective(
7436     ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
7437     SourceLocation EndLoc,
7438     llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
7439   if (!AStmt)
7440     return StmtError();
7441 
7442   CapturedStmt *CS = cast<CapturedStmt>(AStmt);
7443   // 1.2.2 OpenMP Language Terminology
7444   // Structured block - An executable statement with a single entry at the
7445   // top and a single exit at the bottom.
7446   // The point of exit cannot be a branch out of the structured block.
7447   // longjmp() and throw() must not violate the entry/exit criteria.
7448   CS->getCapturedDecl()->setNothrow();
7449   for (int ThisCaptureLevel =
7450            getOpenMPCaptureLevels(OMPD_target_teams_distribute);
7451        ThisCaptureLevel > 1; --ThisCaptureLevel) {
7452     CS = cast<CapturedStmt>(CS->getCapturedStmt());
7453     // 1.2.2 OpenMP Language Terminology
7454     // Structured block - An executable statement with a single entry at the
7455     // top and a single exit at the bottom.
7456     // The point of exit cannot be a branch out of the structured block.
7457     // longjmp() and throw() must not violate the entry/exit criteria.
7458     CS->getCapturedDecl()->setNothrow();
7459   }
7460 
7461   OMPLoopDirective::HelperExprs B;
7462   // In presence of clause 'collapse' with number of loops, it will
7463   // define the nested loops number.
7464   auto NestedLoopCount = CheckOpenMPLoop(
7465       OMPD_target_teams_distribute, getCollapseNumberExpr(Clauses),
7466       nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStack,
7467       VarsWithImplicitDSA, B);
7468   if (NestedLoopCount == 0)
7469     return StmtError();
7470 
7471   assert((CurContext->isDependentContext() || B.builtAll()) &&
7472          "omp target teams distribute loop exprs were not built");
7473 
7474   getCurFunction()->setHasBranchProtectedScope();
7475   return OMPTargetTeamsDistributeDirective::Create(
7476       Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
7477 }
7478 
7479 StmtResult Sema::ActOnOpenMPTargetTeamsDistributeParallelForDirective(
7480     ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
7481     SourceLocation EndLoc,
7482     llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
7483   if (!AStmt)
7484     return StmtError();
7485 
7486   CapturedStmt *CS = cast<CapturedStmt>(AStmt);
7487   // 1.2.2 OpenMP Language Terminology
7488   // Structured block - An executable statement with a single entry at the
7489   // top and a single exit at the bottom.
7490   // The point of exit cannot be a branch out of the structured block.
7491   // longjmp() and throw() must not violate the entry/exit criteria.
7492   CS->getCapturedDecl()->setNothrow();
7493 
7494   for (int ThisCaptureLevel =
7495            getOpenMPCaptureLevels(OMPD_target_teams_distribute_parallel_for);
7496        ThisCaptureLevel > 1; --ThisCaptureLevel) {
7497     CS = cast<CapturedStmt>(CS->getCapturedStmt());
7498     // 1.2.2 OpenMP Language Terminology
7499     // Structured block - An executable statement with a single entry at the
7500     // top and a single exit at the bottom.
7501     // The point of exit cannot be a branch out of the structured block.
7502     // longjmp() and throw() must not violate the entry/exit criteria.
7503     CS->getCapturedDecl()->setNothrow();
7504   }
7505 
7506   OMPLoopDirective::HelperExprs B;
7507   // In presence of clause 'collapse' with number of loops, it will
7508   // define the nested loops number.
7509   auto NestedLoopCount = CheckOpenMPLoop(
7510       OMPD_target_teams_distribute_parallel_for, getCollapseNumberExpr(Clauses),
7511       nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStack,
7512       VarsWithImplicitDSA, B);
7513   if (NestedLoopCount == 0)
7514     return StmtError();
7515 
7516   assert((CurContext->isDependentContext() || B.builtAll()) &&
7517          "omp target teams distribute parallel for loop exprs were not built");
7518 
7519   getCurFunction()->setHasBranchProtectedScope();
7520   return OMPTargetTeamsDistributeParallelForDirective::Create(
7521       Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B,
7522       DSAStack->isCancelRegion());
7523 }
7524 
7525 StmtResult Sema::ActOnOpenMPTargetTeamsDistributeParallelForSimdDirective(
7526     ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
7527     SourceLocation EndLoc,
7528     llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
7529   if (!AStmt)
7530     return StmtError();
7531 
7532   CapturedStmt *CS = cast<CapturedStmt>(AStmt);
7533   // 1.2.2 OpenMP Language Terminology
7534   // Structured block - An executable statement with a single entry at the
7535   // top and a single exit at the bottom.
7536   // The point of exit cannot be a branch out of the structured block.
7537   // longjmp() and throw() must not violate the entry/exit criteria.
7538   CS->getCapturedDecl()->setNothrow();
7539 
7540   OMPLoopDirective::HelperExprs B;
7541   // In presence of clause 'collapse' with number of loops, it will
7542   // define the nested loops number.
7543   auto NestedLoopCount = CheckOpenMPLoop(
7544       OMPD_target_teams_distribute_parallel_for_simd,
7545       getCollapseNumberExpr(Clauses),
7546       nullptr /*ordered not a clause on distribute*/, AStmt, *this, *DSAStack,
7547       VarsWithImplicitDSA, B);
7548   if (NestedLoopCount == 0)
7549     return StmtError();
7550 
7551   assert((CurContext->isDependentContext() || B.builtAll()) &&
7552          "omp target teams distribute parallel for simd loop exprs were not "
7553          "built");
7554 
7555   if (!CurContext->isDependentContext()) {
7556     // Finalize the clauses that need pre-built expressions for CodeGen.
7557     for (auto C : Clauses) {
7558       if (auto *LC = dyn_cast<OMPLinearClause>(C))
7559         if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
7560                                      B.NumIterations, *this, CurScope,
7561                                      DSAStack))
7562           return StmtError();
7563     }
7564   }
7565 
7566   if (checkSimdlenSafelenSpecified(*this, Clauses))
7567     return StmtError();
7568 
7569   getCurFunction()->setHasBranchProtectedScope();
7570   return OMPTargetTeamsDistributeParallelForSimdDirective::Create(
7571       Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
7572 }
7573 
7574 StmtResult Sema::ActOnOpenMPTargetTeamsDistributeSimdDirective(
7575     ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
7576     SourceLocation EndLoc,
7577     llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
7578   if (!AStmt)
7579     return StmtError();
7580 
7581   auto *CS = cast<CapturedStmt>(AStmt);
7582   // 1.2.2 OpenMP Language Terminology
7583   // Structured block - An executable statement with a single entry at the
7584   // top and a single exit at the bottom.
7585   // The point of exit cannot be a branch out of the structured block.
7586   // longjmp() and throw() must not violate the entry/exit criteria.
7587   CS->getCapturedDecl()->setNothrow();
7588   for (int ThisCaptureLevel =
7589            getOpenMPCaptureLevels(OMPD_target_teams_distribute_simd);
7590        ThisCaptureLevel > 1; --ThisCaptureLevel) {
7591     CS = cast<CapturedStmt>(CS->getCapturedStmt());
7592     // 1.2.2 OpenMP Language Terminology
7593     // Structured block - An executable statement with a single entry at the
7594     // top and a single exit at the bottom.
7595     // The point of exit cannot be a branch out of the structured block.
7596     // longjmp() and throw() must not violate the entry/exit criteria.
7597     CS->getCapturedDecl()->setNothrow();
7598   }
7599 
7600   OMPLoopDirective::HelperExprs B;
7601   // In presence of clause 'collapse' with number of loops, it will
7602   // define the nested loops number.
7603   auto NestedLoopCount = CheckOpenMPLoop(
7604       OMPD_target_teams_distribute_simd, getCollapseNumberExpr(Clauses),
7605       nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStack,
7606       VarsWithImplicitDSA, B);
7607   if (NestedLoopCount == 0)
7608     return StmtError();
7609 
7610   assert((CurContext->isDependentContext() || B.builtAll()) &&
7611          "omp target teams distribute simd loop exprs were not built");
7612 
7613   if (!CurContext->isDependentContext()) {
7614     // Finalize the clauses that need pre-built expressions for CodeGen.
7615     for (auto C : Clauses) {
7616       if (auto *LC = dyn_cast<OMPLinearClause>(C))
7617         if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
7618                                      B.NumIterations, *this, CurScope,
7619                                      DSAStack))
7620           return StmtError();
7621     }
7622   }
7623 
7624   if (checkSimdlenSafelenSpecified(*this, Clauses))
7625     return StmtError();
7626 
7627   getCurFunction()->setHasBranchProtectedScope();
7628   return OMPTargetTeamsDistributeSimdDirective::Create(
7629       Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
7630 }
7631 
7632 OMPClause *Sema::ActOnOpenMPSingleExprClause(OpenMPClauseKind Kind, Expr *Expr,
7633                                              SourceLocation StartLoc,
7634                                              SourceLocation LParenLoc,
7635                                              SourceLocation EndLoc) {
7636   OMPClause *Res = nullptr;
7637   switch (Kind) {
7638   case OMPC_final:
7639     Res = ActOnOpenMPFinalClause(Expr, StartLoc, LParenLoc, EndLoc);
7640     break;
7641   case OMPC_num_threads:
7642     Res = ActOnOpenMPNumThreadsClause(Expr, StartLoc, LParenLoc, EndLoc);
7643     break;
7644   case OMPC_safelen:
7645     Res = ActOnOpenMPSafelenClause(Expr, StartLoc, LParenLoc, EndLoc);
7646     break;
7647   case OMPC_simdlen:
7648     Res = ActOnOpenMPSimdlenClause(Expr, StartLoc, LParenLoc, EndLoc);
7649     break;
7650   case OMPC_collapse:
7651     Res = ActOnOpenMPCollapseClause(Expr, StartLoc, LParenLoc, EndLoc);
7652     break;
7653   case OMPC_ordered:
7654     Res = ActOnOpenMPOrderedClause(StartLoc, EndLoc, LParenLoc, Expr);
7655     break;
7656   case OMPC_device:
7657     Res = ActOnOpenMPDeviceClause(Expr, StartLoc, LParenLoc, EndLoc);
7658     break;
7659   case OMPC_num_teams:
7660     Res = ActOnOpenMPNumTeamsClause(Expr, StartLoc, LParenLoc, EndLoc);
7661     break;
7662   case OMPC_thread_limit:
7663     Res = ActOnOpenMPThreadLimitClause(Expr, StartLoc, LParenLoc, EndLoc);
7664     break;
7665   case OMPC_priority:
7666     Res = ActOnOpenMPPriorityClause(Expr, StartLoc, LParenLoc, EndLoc);
7667     break;
7668   case OMPC_grainsize:
7669     Res = ActOnOpenMPGrainsizeClause(Expr, StartLoc, LParenLoc, EndLoc);
7670     break;
7671   case OMPC_num_tasks:
7672     Res = ActOnOpenMPNumTasksClause(Expr, StartLoc, LParenLoc, EndLoc);
7673     break;
7674   case OMPC_hint:
7675     Res = ActOnOpenMPHintClause(Expr, StartLoc, LParenLoc, EndLoc);
7676     break;
7677   case OMPC_if:
7678   case OMPC_default:
7679   case OMPC_proc_bind:
7680   case OMPC_schedule:
7681   case OMPC_private:
7682   case OMPC_firstprivate:
7683   case OMPC_lastprivate:
7684   case OMPC_shared:
7685   case OMPC_reduction:
7686   case OMPC_task_reduction:
7687   case OMPC_in_reduction:
7688   case OMPC_linear:
7689   case OMPC_aligned:
7690   case OMPC_copyin:
7691   case OMPC_copyprivate:
7692   case OMPC_nowait:
7693   case OMPC_untied:
7694   case OMPC_mergeable:
7695   case OMPC_threadprivate:
7696   case OMPC_flush:
7697   case OMPC_read:
7698   case OMPC_write:
7699   case OMPC_update:
7700   case OMPC_capture:
7701   case OMPC_seq_cst:
7702   case OMPC_depend:
7703   case OMPC_threads:
7704   case OMPC_simd:
7705   case OMPC_map:
7706   case OMPC_nogroup:
7707   case OMPC_dist_schedule:
7708   case OMPC_defaultmap:
7709   case OMPC_unknown:
7710   case OMPC_uniform:
7711   case OMPC_to:
7712   case OMPC_from:
7713   case OMPC_use_device_ptr:
7714   case OMPC_is_device_ptr:
7715     llvm_unreachable("Clause is not allowed.");
7716   }
7717   return Res;
7718 }
7719 
7720 // An OpenMP directive such as 'target parallel' has two captured regions:
7721 // for the 'target' and 'parallel' respectively.  This function returns
7722 // the region in which to capture expressions associated with a clause.
7723 // A return value of OMPD_unknown signifies that the expression should not
7724 // be captured.
7725 static OpenMPDirectiveKind getOpenMPCaptureRegionForClause(
7726     OpenMPDirectiveKind DKind, OpenMPClauseKind CKind,
7727     OpenMPDirectiveKind NameModifier = OMPD_unknown) {
7728   OpenMPDirectiveKind CaptureRegion = OMPD_unknown;
7729   switch (CKind) {
7730   case OMPC_if:
7731     switch (DKind) {
7732     case OMPD_target_parallel:
7733     case OMPD_target_parallel_for:
7734     case OMPD_target_parallel_for_simd:
7735       // If this clause applies to the nested 'parallel' region, capture within
7736       // the 'target' region, otherwise do not capture.
7737       if (NameModifier == OMPD_unknown || NameModifier == OMPD_parallel)
7738         CaptureRegion = OMPD_target;
7739       break;
7740     case OMPD_target_teams_distribute_parallel_for:
7741     case OMPD_target_teams_distribute_parallel_for_simd:
7742       // If this clause applies to the nested 'parallel' region, capture within
7743       // the 'teams' region, otherwise do not capture.
7744       if (NameModifier == OMPD_unknown || NameModifier == OMPD_parallel)
7745         CaptureRegion = OMPD_teams;
7746       break;
7747     case OMPD_teams_distribute_parallel_for:
7748     case OMPD_teams_distribute_parallel_for_simd:
7749       CaptureRegion = OMPD_teams;
7750       break;
7751     case OMPD_target_update:
7752     case OMPD_target_enter_data:
7753     case OMPD_target_exit_data:
7754       CaptureRegion = OMPD_task;
7755       break;
7756     case OMPD_cancel:
7757     case OMPD_parallel:
7758     case OMPD_parallel_sections:
7759     case OMPD_parallel_for:
7760     case OMPD_parallel_for_simd:
7761     case OMPD_target:
7762     case OMPD_target_simd:
7763     case OMPD_target_teams:
7764     case OMPD_target_teams_distribute:
7765     case OMPD_target_teams_distribute_simd:
7766     case OMPD_distribute_parallel_for:
7767     case OMPD_distribute_parallel_for_simd:
7768     case OMPD_task:
7769     case OMPD_taskloop:
7770     case OMPD_taskloop_simd:
7771     case OMPD_target_data:
7772       // Do not capture if-clause expressions.
7773       break;
7774     case OMPD_threadprivate:
7775     case OMPD_taskyield:
7776     case OMPD_barrier:
7777     case OMPD_taskwait:
7778     case OMPD_cancellation_point:
7779     case OMPD_flush:
7780     case OMPD_declare_reduction:
7781     case OMPD_declare_simd:
7782     case OMPD_declare_target:
7783     case OMPD_end_declare_target:
7784     case OMPD_teams:
7785     case OMPD_simd:
7786     case OMPD_for:
7787     case OMPD_for_simd:
7788     case OMPD_sections:
7789     case OMPD_section:
7790     case OMPD_single:
7791     case OMPD_master:
7792     case OMPD_critical:
7793     case OMPD_taskgroup:
7794     case OMPD_distribute:
7795     case OMPD_ordered:
7796     case OMPD_atomic:
7797     case OMPD_distribute_simd:
7798     case OMPD_teams_distribute:
7799     case OMPD_teams_distribute_simd:
7800       llvm_unreachable("Unexpected OpenMP directive with if-clause");
7801     case OMPD_unknown:
7802       llvm_unreachable("Unknown OpenMP directive");
7803     }
7804     break;
7805   case OMPC_num_threads:
7806     switch (DKind) {
7807     case OMPD_target_parallel:
7808     case OMPD_target_parallel_for:
7809     case OMPD_target_parallel_for_simd:
7810       CaptureRegion = OMPD_target;
7811       break;
7812     case OMPD_teams_distribute_parallel_for:
7813     case OMPD_teams_distribute_parallel_for_simd:
7814     case OMPD_target_teams_distribute_parallel_for:
7815     case OMPD_target_teams_distribute_parallel_for_simd:
7816       CaptureRegion = OMPD_teams;
7817       break;
7818     case OMPD_parallel:
7819     case OMPD_parallel_sections:
7820     case OMPD_parallel_for:
7821     case OMPD_parallel_for_simd:
7822     case OMPD_distribute_parallel_for:
7823     case OMPD_distribute_parallel_for_simd:
7824       // Do not capture num_threads-clause expressions.
7825       break;
7826     case OMPD_target_data:
7827     case OMPD_target_enter_data:
7828     case OMPD_target_exit_data:
7829     case OMPD_target_update:
7830     case OMPD_target:
7831     case OMPD_target_simd:
7832     case OMPD_target_teams:
7833     case OMPD_target_teams_distribute:
7834     case OMPD_target_teams_distribute_simd:
7835     case OMPD_cancel:
7836     case OMPD_task:
7837     case OMPD_taskloop:
7838     case OMPD_taskloop_simd:
7839     case OMPD_threadprivate:
7840     case OMPD_taskyield:
7841     case OMPD_barrier:
7842     case OMPD_taskwait:
7843     case OMPD_cancellation_point:
7844     case OMPD_flush:
7845     case OMPD_declare_reduction:
7846     case OMPD_declare_simd:
7847     case OMPD_declare_target:
7848     case OMPD_end_declare_target:
7849     case OMPD_teams:
7850     case OMPD_simd:
7851     case OMPD_for:
7852     case OMPD_for_simd:
7853     case OMPD_sections:
7854     case OMPD_section:
7855     case OMPD_single:
7856     case OMPD_master:
7857     case OMPD_critical:
7858     case OMPD_taskgroup:
7859     case OMPD_distribute:
7860     case OMPD_ordered:
7861     case OMPD_atomic:
7862     case OMPD_distribute_simd:
7863     case OMPD_teams_distribute:
7864     case OMPD_teams_distribute_simd:
7865       llvm_unreachable("Unexpected OpenMP directive with num_threads-clause");
7866     case OMPD_unknown:
7867       llvm_unreachable("Unknown OpenMP directive");
7868     }
7869     break;
7870   case OMPC_num_teams:
7871     switch (DKind) {
7872     case OMPD_target_teams:
7873     case OMPD_target_teams_distribute:
7874     case OMPD_target_teams_distribute_simd:
7875     case OMPD_target_teams_distribute_parallel_for:
7876     case OMPD_target_teams_distribute_parallel_for_simd:
7877       CaptureRegion = OMPD_target;
7878       break;
7879     case OMPD_teams_distribute_parallel_for:
7880     case OMPD_teams_distribute_parallel_for_simd:
7881     case OMPD_teams:
7882     case OMPD_teams_distribute:
7883     case OMPD_teams_distribute_simd:
7884       // Do not capture num_teams-clause expressions.
7885       break;
7886     case OMPD_distribute_parallel_for:
7887     case OMPD_distribute_parallel_for_simd:
7888     case OMPD_task:
7889     case OMPD_taskloop:
7890     case OMPD_taskloop_simd:
7891     case OMPD_target_data:
7892     case OMPD_target_enter_data:
7893     case OMPD_target_exit_data:
7894     case OMPD_target_update:
7895     case OMPD_cancel:
7896     case OMPD_parallel:
7897     case OMPD_parallel_sections:
7898     case OMPD_parallel_for:
7899     case OMPD_parallel_for_simd:
7900     case OMPD_target:
7901     case OMPD_target_simd:
7902     case OMPD_target_parallel:
7903     case OMPD_target_parallel_for:
7904     case OMPD_target_parallel_for_simd:
7905     case OMPD_threadprivate:
7906     case OMPD_taskyield:
7907     case OMPD_barrier:
7908     case OMPD_taskwait:
7909     case OMPD_cancellation_point:
7910     case OMPD_flush:
7911     case OMPD_declare_reduction:
7912     case OMPD_declare_simd:
7913     case OMPD_declare_target:
7914     case OMPD_end_declare_target:
7915     case OMPD_simd:
7916     case OMPD_for:
7917     case OMPD_for_simd:
7918     case OMPD_sections:
7919     case OMPD_section:
7920     case OMPD_single:
7921     case OMPD_master:
7922     case OMPD_critical:
7923     case OMPD_taskgroup:
7924     case OMPD_distribute:
7925     case OMPD_ordered:
7926     case OMPD_atomic:
7927     case OMPD_distribute_simd:
7928       llvm_unreachable("Unexpected OpenMP directive with num_teams-clause");
7929     case OMPD_unknown:
7930       llvm_unreachable("Unknown OpenMP directive");
7931     }
7932     break;
7933   case OMPC_thread_limit:
7934     switch (DKind) {
7935     case OMPD_target_teams:
7936     case OMPD_target_teams_distribute:
7937     case OMPD_target_teams_distribute_simd:
7938     case OMPD_target_teams_distribute_parallel_for:
7939     case OMPD_target_teams_distribute_parallel_for_simd:
7940       CaptureRegion = OMPD_target;
7941       break;
7942     case OMPD_teams_distribute_parallel_for:
7943     case OMPD_teams_distribute_parallel_for_simd:
7944     case OMPD_teams:
7945     case OMPD_teams_distribute:
7946     case OMPD_teams_distribute_simd:
7947       // Do not capture thread_limit-clause expressions.
7948       break;
7949     case OMPD_distribute_parallel_for:
7950     case OMPD_distribute_parallel_for_simd:
7951     case OMPD_task:
7952     case OMPD_taskloop:
7953     case OMPD_taskloop_simd:
7954     case OMPD_target_data:
7955     case OMPD_target_enter_data:
7956     case OMPD_target_exit_data:
7957     case OMPD_target_update:
7958     case OMPD_cancel:
7959     case OMPD_parallel:
7960     case OMPD_parallel_sections:
7961     case OMPD_parallel_for:
7962     case OMPD_parallel_for_simd:
7963     case OMPD_target:
7964     case OMPD_target_simd:
7965     case OMPD_target_parallel:
7966     case OMPD_target_parallel_for:
7967     case OMPD_target_parallel_for_simd:
7968     case OMPD_threadprivate:
7969     case OMPD_taskyield:
7970     case OMPD_barrier:
7971     case OMPD_taskwait:
7972     case OMPD_cancellation_point:
7973     case OMPD_flush:
7974     case OMPD_declare_reduction:
7975     case OMPD_declare_simd:
7976     case OMPD_declare_target:
7977     case OMPD_end_declare_target:
7978     case OMPD_simd:
7979     case OMPD_for:
7980     case OMPD_for_simd:
7981     case OMPD_sections:
7982     case OMPD_section:
7983     case OMPD_single:
7984     case OMPD_master:
7985     case OMPD_critical:
7986     case OMPD_taskgroup:
7987     case OMPD_distribute:
7988     case OMPD_ordered:
7989     case OMPD_atomic:
7990     case OMPD_distribute_simd:
7991       llvm_unreachable("Unexpected OpenMP directive with thread_limit-clause");
7992     case OMPD_unknown:
7993       llvm_unreachable("Unknown OpenMP directive");
7994     }
7995     break;
7996   case OMPC_schedule:
7997     switch (DKind) {
7998     case OMPD_parallel_for:
7999     case OMPD_parallel_for_simd:
8000     case OMPD_distribute_parallel_for:
8001     case OMPD_distribute_parallel_for_simd:
8002     case OMPD_teams_distribute_parallel_for:
8003     case OMPD_teams_distribute_parallel_for_simd:
8004     case OMPD_target_parallel_for:
8005     case OMPD_target_parallel_for_simd:
8006     case OMPD_target_teams_distribute_parallel_for:
8007     case OMPD_target_teams_distribute_parallel_for_simd:
8008       CaptureRegion = OMPD_parallel;
8009       break;
8010     case OMPD_for:
8011     case OMPD_for_simd:
8012       // Do not capture schedule-clause expressions.
8013       break;
8014     case OMPD_task:
8015     case OMPD_taskloop:
8016     case OMPD_taskloop_simd:
8017     case OMPD_target_data:
8018     case OMPD_target_enter_data:
8019     case OMPD_target_exit_data:
8020     case OMPD_target_update:
8021     case OMPD_teams:
8022     case OMPD_teams_distribute:
8023     case OMPD_teams_distribute_simd:
8024     case OMPD_target_teams_distribute:
8025     case OMPD_target_teams_distribute_simd:
8026     case OMPD_target:
8027     case OMPD_target_simd:
8028     case OMPD_target_parallel:
8029     case OMPD_cancel:
8030     case OMPD_parallel:
8031     case OMPD_parallel_sections:
8032     case OMPD_threadprivate:
8033     case OMPD_taskyield:
8034     case OMPD_barrier:
8035     case OMPD_taskwait:
8036     case OMPD_cancellation_point:
8037     case OMPD_flush:
8038     case OMPD_declare_reduction:
8039     case OMPD_declare_simd:
8040     case OMPD_declare_target:
8041     case OMPD_end_declare_target:
8042     case OMPD_simd:
8043     case OMPD_sections:
8044     case OMPD_section:
8045     case OMPD_single:
8046     case OMPD_master:
8047     case OMPD_critical:
8048     case OMPD_taskgroup:
8049     case OMPD_distribute:
8050     case OMPD_ordered:
8051     case OMPD_atomic:
8052     case OMPD_distribute_simd:
8053     case OMPD_target_teams:
8054       llvm_unreachable("Unexpected OpenMP directive with schedule clause");
8055     case OMPD_unknown:
8056       llvm_unreachable("Unknown OpenMP directive");
8057     }
8058     break;
8059   case OMPC_dist_schedule:
8060     switch (DKind) {
8061     case OMPD_teams_distribute_parallel_for:
8062     case OMPD_teams_distribute_parallel_for_simd:
8063     case OMPD_teams_distribute:
8064     case OMPD_teams_distribute_simd:
8065     case OMPD_target_teams_distribute_parallel_for:
8066     case OMPD_target_teams_distribute_parallel_for_simd:
8067     case OMPD_target_teams_distribute:
8068     case OMPD_target_teams_distribute_simd:
8069       CaptureRegion = OMPD_teams;
8070       break;
8071     case OMPD_distribute_parallel_for:
8072     case OMPD_distribute_parallel_for_simd:
8073     case OMPD_distribute:
8074     case OMPD_distribute_simd:
8075       // Do not capture thread_limit-clause expressions.
8076       break;
8077     case OMPD_parallel_for:
8078     case OMPD_parallel_for_simd:
8079     case OMPD_target_parallel_for_simd:
8080     case OMPD_target_parallel_for:
8081     case OMPD_task:
8082     case OMPD_taskloop:
8083     case OMPD_taskloop_simd:
8084     case OMPD_target_data:
8085     case OMPD_target_enter_data:
8086     case OMPD_target_exit_data:
8087     case OMPD_target_update:
8088     case OMPD_teams:
8089     case OMPD_target:
8090     case OMPD_target_simd:
8091     case OMPD_target_parallel:
8092     case OMPD_cancel:
8093     case OMPD_parallel:
8094     case OMPD_parallel_sections:
8095     case OMPD_threadprivate:
8096     case OMPD_taskyield:
8097     case OMPD_barrier:
8098     case OMPD_taskwait:
8099     case OMPD_cancellation_point:
8100     case OMPD_flush:
8101     case OMPD_declare_reduction:
8102     case OMPD_declare_simd:
8103     case OMPD_declare_target:
8104     case OMPD_end_declare_target:
8105     case OMPD_simd:
8106     case OMPD_for:
8107     case OMPD_for_simd:
8108     case OMPD_sections:
8109     case OMPD_section:
8110     case OMPD_single:
8111     case OMPD_master:
8112     case OMPD_critical:
8113     case OMPD_taskgroup:
8114     case OMPD_ordered:
8115     case OMPD_atomic:
8116     case OMPD_target_teams:
8117       llvm_unreachable("Unexpected OpenMP directive with schedule clause");
8118     case OMPD_unknown:
8119       llvm_unreachable("Unknown OpenMP directive");
8120     }
8121     break;
8122   case OMPC_device:
8123     switch (DKind) {
8124     case OMPD_target_update:
8125     case OMPD_target_enter_data:
8126     case OMPD_target_exit_data:
8127     case OMPD_target:
8128       CaptureRegion = OMPD_task;
8129       break;
8130     case OMPD_target_teams:
8131     case OMPD_target_teams_distribute:
8132     case OMPD_target_teams_distribute_simd:
8133     case OMPD_target_teams_distribute_parallel_for:
8134     case OMPD_target_teams_distribute_parallel_for_simd:
8135     case OMPD_target_data:
8136     case OMPD_target_simd:
8137     case OMPD_target_parallel:
8138     case OMPD_target_parallel_for:
8139     case OMPD_target_parallel_for_simd:
8140       // Do not capture device-clause expressions.
8141       break;
8142     case OMPD_teams_distribute_parallel_for:
8143     case OMPD_teams_distribute_parallel_for_simd:
8144     case OMPD_teams:
8145     case OMPD_teams_distribute:
8146     case OMPD_teams_distribute_simd:
8147     case OMPD_distribute_parallel_for:
8148     case OMPD_distribute_parallel_for_simd:
8149     case OMPD_task:
8150     case OMPD_taskloop:
8151     case OMPD_taskloop_simd:
8152     case OMPD_cancel:
8153     case OMPD_parallel:
8154     case OMPD_parallel_sections:
8155     case OMPD_parallel_for:
8156     case OMPD_parallel_for_simd:
8157     case OMPD_threadprivate:
8158     case OMPD_taskyield:
8159     case OMPD_barrier:
8160     case OMPD_taskwait:
8161     case OMPD_cancellation_point:
8162     case OMPD_flush:
8163     case OMPD_declare_reduction:
8164     case OMPD_declare_simd:
8165     case OMPD_declare_target:
8166     case OMPD_end_declare_target:
8167     case OMPD_simd:
8168     case OMPD_for:
8169     case OMPD_for_simd:
8170     case OMPD_sections:
8171     case OMPD_section:
8172     case OMPD_single:
8173     case OMPD_master:
8174     case OMPD_critical:
8175     case OMPD_taskgroup:
8176     case OMPD_distribute:
8177     case OMPD_ordered:
8178     case OMPD_atomic:
8179     case OMPD_distribute_simd:
8180       llvm_unreachable("Unexpected OpenMP directive with num_teams-clause");
8181     case OMPD_unknown:
8182       llvm_unreachable("Unknown OpenMP directive");
8183     }
8184     break;
8185   case OMPC_firstprivate:
8186   case OMPC_lastprivate:
8187   case OMPC_reduction:
8188   case OMPC_task_reduction:
8189   case OMPC_in_reduction:
8190   case OMPC_linear:
8191   case OMPC_default:
8192   case OMPC_proc_bind:
8193   case OMPC_final:
8194   case OMPC_safelen:
8195   case OMPC_simdlen:
8196   case OMPC_collapse:
8197   case OMPC_private:
8198   case OMPC_shared:
8199   case OMPC_aligned:
8200   case OMPC_copyin:
8201   case OMPC_copyprivate:
8202   case OMPC_ordered:
8203   case OMPC_nowait:
8204   case OMPC_untied:
8205   case OMPC_mergeable:
8206   case OMPC_threadprivate:
8207   case OMPC_flush:
8208   case OMPC_read:
8209   case OMPC_write:
8210   case OMPC_update:
8211   case OMPC_capture:
8212   case OMPC_seq_cst:
8213   case OMPC_depend:
8214   case OMPC_threads:
8215   case OMPC_simd:
8216   case OMPC_map:
8217   case OMPC_priority:
8218   case OMPC_grainsize:
8219   case OMPC_nogroup:
8220   case OMPC_num_tasks:
8221   case OMPC_hint:
8222   case OMPC_defaultmap:
8223   case OMPC_unknown:
8224   case OMPC_uniform:
8225   case OMPC_to:
8226   case OMPC_from:
8227   case OMPC_use_device_ptr:
8228   case OMPC_is_device_ptr:
8229     llvm_unreachable("Unexpected OpenMP clause.");
8230   }
8231   return CaptureRegion;
8232 }
8233 
8234 OMPClause *Sema::ActOnOpenMPIfClause(OpenMPDirectiveKind NameModifier,
8235                                      Expr *Condition, SourceLocation StartLoc,
8236                                      SourceLocation LParenLoc,
8237                                      SourceLocation NameModifierLoc,
8238                                      SourceLocation ColonLoc,
8239                                      SourceLocation EndLoc) {
8240   Expr *ValExpr = Condition;
8241   Stmt *HelperValStmt = nullptr;
8242   OpenMPDirectiveKind CaptureRegion = OMPD_unknown;
8243   if (!Condition->isValueDependent() && !Condition->isTypeDependent() &&
8244       !Condition->isInstantiationDependent() &&
8245       !Condition->containsUnexpandedParameterPack()) {
8246     ExprResult Val = CheckBooleanCondition(StartLoc, Condition);
8247     if (Val.isInvalid())
8248       return nullptr;
8249 
8250     ValExpr = Val.get();
8251 
8252     OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective();
8253     CaptureRegion =
8254         getOpenMPCaptureRegionForClause(DKind, OMPC_if, NameModifier);
8255     if (CaptureRegion != OMPD_unknown && !CurContext->isDependentContext()) {
8256       ValExpr = MakeFullExpr(ValExpr).get();
8257       llvm::MapVector<Expr *, DeclRefExpr *> Captures;
8258       ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
8259       HelperValStmt = buildPreInits(Context, Captures);
8260     }
8261   }
8262 
8263   return new (Context)
8264       OMPIfClause(NameModifier, ValExpr, HelperValStmt, CaptureRegion, StartLoc,
8265                   LParenLoc, NameModifierLoc, ColonLoc, EndLoc);
8266 }
8267 
8268 OMPClause *Sema::ActOnOpenMPFinalClause(Expr *Condition,
8269                                         SourceLocation StartLoc,
8270                                         SourceLocation LParenLoc,
8271                                         SourceLocation EndLoc) {
8272   Expr *ValExpr = Condition;
8273   if (!Condition->isValueDependent() && !Condition->isTypeDependent() &&
8274       !Condition->isInstantiationDependent() &&
8275       !Condition->containsUnexpandedParameterPack()) {
8276     ExprResult Val = CheckBooleanCondition(StartLoc, Condition);
8277     if (Val.isInvalid())
8278       return nullptr;
8279 
8280     ValExpr = MakeFullExpr(Val.get()).get();
8281   }
8282 
8283   return new (Context) OMPFinalClause(ValExpr, StartLoc, LParenLoc, EndLoc);
8284 }
8285 ExprResult Sema::PerformOpenMPImplicitIntegerConversion(SourceLocation Loc,
8286                                                         Expr *Op) {
8287   if (!Op)
8288     return ExprError();
8289 
8290   class IntConvertDiagnoser : public ICEConvertDiagnoser {
8291   public:
8292     IntConvertDiagnoser()
8293         : ICEConvertDiagnoser(/*AllowScopedEnumerations*/ false, false, true) {}
8294     SemaDiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc,
8295                                          QualType T) override {
8296       return S.Diag(Loc, diag::err_omp_not_integral) << T;
8297     }
8298     SemaDiagnosticBuilder diagnoseIncomplete(Sema &S, SourceLocation Loc,
8299                                              QualType T) override {
8300       return S.Diag(Loc, diag::err_omp_incomplete_type) << T;
8301     }
8302     SemaDiagnosticBuilder diagnoseExplicitConv(Sema &S, SourceLocation Loc,
8303                                                QualType T,
8304                                                QualType ConvTy) override {
8305       return S.Diag(Loc, diag::err_omp_explicit_conversion) << T << ConvTy;
8306     }
8307     SemaDiagnosticBuilder noteExplicitConv(Sema &S, CXXConversionDecl *Conv,
8308                                            QualType ConvTy) override {
8309       return S.Diag(Conv->getLocation(), diag::note_omp_conversion_here)
8310              << ConvTy->isEnumeralType() << ConvTy;
8311     }
8312     SemaDiagnosticBuilder diagnoseAmbiguous(Sema &S, SourceLocation Loc,
8313                                             QualType T) override {
8314       return S.Diag(Loc, diag::err_omp_ambiguous_conversion) << T;
8315     }
8316     SemaDiagnosticBuilder noteAmbiguous(Sema &S, CXXConversionDecl *Conv,
8317                                         QualType ConvTy) override {
8318       return S.Diag(Conv->getLocation(), diag::note_omp_conversion_here)
8319              << ConvTy->isEnumeralType() << ConvTy;
8320     }
8321     SemaDiagnosticBuilder diagnoseConversion(Sema &, SourceLocation, QualType,
8322                                              QualType) override {
8323       llvm_unreachable("conversion functions are permitted");
8324     }
8325   } ConvertDiagnoser;
8326   return PerformContextualImplicitConversion(Loc, Op, ConvertDiagnoser);
8327 }
8328 
8329 static bool IsNonNegativeIntegerValue(Expr *&ValExpr, Sema &SemaRef,
8330                                       OpenMPClauseKind CKind,
8331                                       bool StrictlyPositive) {
8332   if (!ValExpr->isTypeDependent() && !ValExpr->isValueDependent() &&
8333       !ValExpr->isInstantiationDependent()) {
8334     SourceLocation Loc = ValExpr->getExprLoc();
8335     ExprResult Value =
8336         SemaRef.PerformOpenMPImplicitIntegerConversion(Loc, ValExpr);
8337     if (Value.isInvalid())
8338       return false;
8339 
8340     ValExpr = Value.get();
8341     // The expression must evaluate to a non-negative integer value.
8342     llvm::APSInt Result;
8343     if (ValExpr->isIntegerConstantExpr(Result, SemaRef.Context) &&
8344         Result.isSigned() &&
8345         !((!StrictlyPositive && Result.isNonNegative()) ||
8346           (StrictlyPositive && Result.isStrictlyPositive()))) {
8347       SemaRef.Diag(Loc, diag::err_omp_negative_expression_in_clause)
8348           << getOpenMPClauseName(CKind) << (StrictlyPositive ? 1 : 0)
8349           << ValExpr->getSourceRange();
8350       return false;
8351     }
8352   }
8353   return true;
8354 }
8355 
8356 OMPClause *Sema::ActOnOpenMPNumThreadsClause(Expr *NumThreads,
8357                                              SourceLocation StartLoc,
8358                                              SourceLocation LParenLoc,
8359                                              SourceLocation EndLoc) {
8360   Expr *ValExpr = NumThreads;
8361   Stmt *HelperValStmt = nullptr;
8362 
8363   // OpenMP [2.5, Restrictions]
8364   //  The num_threads expression must evaluate to a positive integer value.
8365   if (!IsNonNegativeIntegerValue(ValExpr, *this, OMPC_num_threads,
8366                                  /*StrictlyPositive=*/true))
8367     return nullptr;
8368 
8369   OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective();
8370   OpenMPDirectiveKind CaptureRegion =
8371       getOpenMPCaptureRegionForClause(DKind, OMPC_num_threads);
8372   if (CaptureRegion != OMPD_unknown && !CurContext->isDependentContext()) {
8373     ValExpr = MakeFullExpr(ValExpr).get();
8374     llvm::MapVector<Expr *, DeclRefExpr *> Captures;
8375     ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
8376     HelperValStmt = buildPreInits(Context, Captures);
8377   }
8378 
8379   return new (Context) OMPNumThreadsClause(
8380       ValExpr, HelperValStmt, CaptureRegion, StartLoc, LParenLoc, EndLoc);
8381 }
8382 
8383 ExprResult Sema::VerifyPositiveIntegerConstantInClause(Expr *E,
8384                                                        OpenMPClauseKind CKind,
8385                                                        bool StrictlyPositive) {
8386   if (!E)
8387     return ExprError();
8388   if (E->isValueDependent() || E->isTypeDependent() ||
8389       E->isInstantiationDependent() || E->containsUnexpandedParameterPack())
8390     return E;
8391   llvm::APSInt Result;
8392   ExprResult ICE = VerifyIntegerConstantExpression(E, &Result);
8393   if (ICE.isInvalid())
8394     return ExprError();
8395   if ((StrictlyPositive && !Result.isStrictlyPositive()) ||
8396       (!StrictlyPositive && !Result.isNonNegative())) {
8397     Diag(E->getExprLoc(), diag::err_omp_negative_expression_in_clause)
8398         << getOpenMPClauseName(CKind) << (StrictlyPositive ? 1 : 0)
8399         << E->getSourceRange();
8400     return ExprError();
8401   }
8402   if (CKind == OMPC_aligned && !Result.isPowerOf2()) {
8403     Diag(E->getExprLoc(), diag::warn_omp_alignment_not_power_of_two)
8404         << E->getSourceRange();
8405     return ExprError();
8406   }
8407   if (CKind == OMPC_collapse && DSAStack->getAssociatedLoops() == 1)
8408     DSAStack->setAssociatedLoops(Result.getExtValue());
8409   else if (CKind == OMPC_ordered)
8410     DSAStack->setAssociatedLoops(Result.getExtValue());
8411   return ICE;
8412 }
8413 
8414 OMPClause *Sema::ActOnOpenMPSafelenClause(Expr *Len, SourceLocation StartLoc,
8415                                           SourceLocation LParenLoc,
8416                                           SourceLocation EndLoc) {
8417   // OpenMP [2.8.1, simd construct, Description]
8418   // The parameter of the safelen clause must be a constant
8419   // positive integer expression.
8420   ExprResult Safelen = VerifyPositiveIntegerConstantInClause(Len, OMPC_safelen);
8421   if (Safelen.isInvalid())
8422     return nullptr;
8423   return new (Context)
8424       OMPSafelenClause(Safelen.get(), StartLoc, LParenLoc, EndLoc);
8425 }
8426 
8427 OMPClause *Sema::ActOnOpenMPSimdlenClause(Expr *Len, SourceLocation StartLoc,
8428                                           SourceLocation LParenLoc,
8429                                           SourceLocation EndLoc) {
8430   // OpenMP [2.8.1, simd construct, Description]
8431   // The parameter of the simdlen clause must be a constant
8432   // positive integer expression.
8433   ExprResult Simdlen = VerifyPositiveIntegerConstantInClause(Len, OMPC_simdlen);
8434   if (Simdlen.isInvalid())
8435     return nullptr;
8436   return new (Context)
8437       OMPSimdlenClause(Simdlen.get(), StartLoc, LParenLoc, EndLoc);
8438 }
8439 
8440 OMPClause *Sema::ActOnOpenMPCollapseClause(Expr *NumForLoops,
8441                                            SourceLocation StartLoc,
8442                                            SourceLocation LParenLoc,
8443                                            SourceLocation EndLoc) {
8444   // OpenMP [2.7.1, loop construct, Description]
8445   // OpenMP [2.8.1, simd construct, Description]
8446   // OpenMP [2.9.6, distribute construct, Description]
8447   // The parameter of the collapse clause must be a constant
8448   // positive integer expression.
8449   ExprResult NumForLoopsResult =
8450       VerifyPositiveIntegerConstantInClause(NumForLoops, OMPC_collapse);
8451   if (NumForLoopsResult.isInvalid())
8452     return nullptr;
8453   return new (Context)
8454       OMPCollapseClause(NumForLoopsResult.get(), StartLoc, LParenLoc, EndLoc);
8455 }
8456 
8457 OMPClause *Sema::ActOnOpenMPOrderedClause(SourceLocation StartLoc,
8458                                           SourceLocation EndLoc,
8459                                           SourceLocation LParenLoc,
8460                                           Expr *NumForLoops) {
8461   // OpenMP [2.7.1, loop construct, Description]
8462   // OpenMP [2.8.1, simd construct, Description]
8463   // OpenMP [2.9.6, distribute construct, Description]
8464   // The parameter of the ordered clause must be a constant
8465   // positive integer expression if any.
8466   if (NumForLoops && LParenLoc.isValid()) {
8467     ExprResult NumForLoopsResult =
8468         VerifyPositiveIntegerConstantInClause(NumForLoops, OMPC_ordered);
8469     if (NumForLoopsResult.isInvalid())
8470       return nullptr;
8471     NumForLoops = NumForLoopsResult.get();
8472   } else
8473     NumForLoops = nullptr;
8474   DSAStack->setOrderedRegion(/*IsOrdered=*/true, NumForLoops);
8475   return new (Context)
8476       OMPOrderedClause(NumForLoops, StartLoc, LParenLoc, EndLoc);
8477 }
8478 
8479 OMPClause *Sema::ActOnOpenMPSimpleClause(
8480     OpenMPClauseKind Kind, unsigned Argument, SourceLocation ArgumentLoc,
8481     SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc) {
8482   OMPClause *Res = nullptr;
8483   switch (Kind) {
8484   case OMPC_default:
8485     Res =
8486         ActOnOpenMPDefaultClause(static_cast<OpenMPDefaultClauseKind>(Argument),
8487                                  ArgumentLoc, StartLoc, LParenLoc, EndLoc);
8488     break;
8489   case OMPC_proc_bind:
8490     Res = ActOnOpenMPProcBindClause(
8491         static_cast<OpenMPProcBindClauseKind>(Argument), ArgumentLoc, StartLoc,
8492         LParenLoc, EndLoc);
8493     break;
8494   case OMPC_if:
8495   case OMPC_final:
8496   case OMPC_num_threads:
8497   case OMPC_safelen:
8498   case OMPC_simdlen:
8499   case OMPC_collapse:
8500   case OMPC_schedule:
8501   case OMPC_private:
8502   case OMPC_firstprivate:
8503   case OMPC_lastprivate:
8504   case OMPC_shared:
8505   case OMPC_reduction:
8506   case OMPC_task_reduction:
8507   case OMPC_in_reduction:
8508   case OMPC_linear:
8509   case OMPC_aligned:
8510   case OMPC_copyin:
8511   case OMPC_copyprivate:
8512   case OMPC_ordered:
8513   case OMPC_nowait:
8514   case OMPC_untied:
8515   case OMPC_mergeable:
8516   case OMPC_threadprivate:
8517   case OMPC_flush:
8518   case OMPC_read:
8519   case OMPC_write:
8520   case OMPC_update:
8521   case OMPC_capture:
8522   case OMPC_seq_cst:
8523   case OMPC_depend:
8524   case OMPC_device:
8525   case OMPC_threads:
8526   case OMPC_simd:
8527   case OMPC_map:
8528   case OMPC_num_teams:
8529   case OMPC_thread_limit:
8530   case OMPC_priority:
8531   case OMPC_grainsize:
8532   case OMPC_nogroup:
8533   case OMPC_num_tasks:
8534   case OMPC_hint:
8535   case OMPC_dist_schedule:
8536   case OMPC_defaultmap:
8537   case OMPC_unknown:
8538   case OMPC_uniform:
8539   case OMPC_to:
8540   case OMPC_from:
8541   case OMPC_use_device_ptr:
8542   case OMPC_is_device_ptr:
8543     llvm_unreachable("Clause is not allowed.");
8544   }
8545   return Res;
8546 }
8547 
8548 static std::string
8549 getListOfPossibleValues(OpenMPClauseKind K, unsigned First, unsigned Last,
8550                         ArrayRef<unsigned> Exclude = llvm::None) {
8551   std::string Values;
8552   unsigned Bound = Last >= 2 ? Last - 2 : 0;
8553   unsigned Skipped = Exclude.size();
8554   auto S = Exclude.begin(), E = Exclude.end();
8555   for (unsigned i = First; i < Last; ++i) {
8556     if (std::find(S, E, i) != E) {
8557       --Skipped;
8558       continue;
8559     }
8560     Values += "'";
8561     Values += getOpenMPSimpleClauseTypeName(K, i);
8562     Values += "'";
8563     if (i == Bound - Skipped)
8564       Values += " or ";
8565     else if (i != Bound + 1 - Skipped)
8566       Values += ", ";
8567   }
8568   return Values;
8569 }
8570 
8571 OMPClause *Sema::ActOnOpenMPDefaultClause(OpenMPDefaultClauseKind Kind,
8572                                           SourceLocation KindKwLoc,
8573                                           SourceLocation StartLoc,
8574                                           SourceLocation LParenLoc,
8575                                           SourceLocation EndLoc) {
8576   if (Kind == OMPC_DEFAULT_unknown) {
8577     static_assert(OMPC_DEFAULT_unknown > 0,
8578                   "OMPC_DEFAULT_unknown not greater than 0");
8579     Diag(KindKwLoc, diag::err_omp_unexpected_clause_value)
8580         << getListOfPossibleValues(OMPC_default, /*First=*/0,
8581                                    /*Last=*/OMPC_DEFAULT_unknown)
8582         << getOpenMPClauseName(OMPC_default);
8583     return nullptr;
8584   }
8585   switch (Kind) {
8586   case OMPC_DEFAULT_none:
8587     DSAStack->setDefaultDSANone(KindKwLoc);
8588     break;
8589   case OMPC_DEFAULT_shared:
8590     DSAStack->setDefaultDSAShared(KindKwLoc);
8591     break;
8592   case OMPC_DEFAULT_unknown:
8593     llvm_unreachable("Clause kind is not allowed.");
8594     break;
8595   }
8596   return new (Context)
8597       OMPDefaultClause(Kind, KindKwLoc, StartLoc, LParenLoc, EndLoc);
8598 }
8599 
8600 OMPClause *Sema::ActOnOpenMPProcBindClause(OpenMPProcBindClauseKind Kind,
8601                                            SourceLocation KindKwLoc,
8602                                            SourceLocation StartLoc,
8603                                            SourceLocation LParenLoc,
8604                                            SourceLocation EndLoc) {
8605   if (Kind == OMPC_PROC_BIND_unknown) {
8606     Diag(KindKwLoc, diag::err_omp_unexpected_clause_value)
8607         << getListOfPossibleValues(OMPC_proc_bind, /*First=*/0,
8608                                    /*Last=*/OMPC_PROC_BIND_unknown)
8609         << getOpenMPClauseName(OMPC_proc_bind);
8610     return nullptr;
8611   }
8612   return new (Context)
8613       OMPProcBindClause(Kind, KindKwLoc, StartLoc, LParenLoc, EndLoc);
8614 }
8615 
8616 OMPClause *Sema::ActOnOpenMPSingleExprWithArgClause(
8617     OpenMPClauseKind Kind, ArrayRef<unsigned> Argument, Expr *Expr,
8618     SourceLocation StartLoc, SourceLocation LParenLoc,
8619     ArrayRef<SourceLocation> ArgumentLoc, SourceLocation DelimLoc,
8620     SourceLocation EndLoc) {
8621   OMPClause *Res = nullptr;
8622   switch (Kind) {
8623   case OMPC_schedule:
8624     enum { Modifier1, Modifier2, ScheduleKind, NumberOfElements };
8625     assert(Argument.size() == NumberOfElements &&
8626            ArgumentLoc.size() == NumberOfElements);
8627     Res = ActOnOpenMPScheduleClause(
8628         static_cast<OpenMPScheduleClauseModifier>(Argument[Modifier1]),
8629         static_cast<OpenMPScheduleClauseModifier>(Argument[Modifier2]),
8630         static_cast<OpenMPScheduleClauseKind>(Argument[ScheduleKind]), Expr,
8631         StartLoc, LParenLoc, ArgumentLoc[Modifier1], ArgumentLoc[Modifier2],
8632         ArgumentLoc[ScheduleKind], DelimLoc, EndLoc);
8633     break;
8634   case OMPC_if:
8635     assert(Argument.size() == 1 && ArgumentLoc.size() == 1);
8636     Res = ActOnOpenMPIfClause(static_cast<OpenMPDirectiveKind>(Argument.back()),
8637                               Expr, StartLoc, LParenLoc, ArgumentLoc.back(),
8638                               DelimLoc, EndLoc);
8639     break;
8640   case OMPC_dist_schedule:
8641     Res = ActOnOpenMPDistScheduleClause(
8642         static_cast<OpenMPDistScheduleClauseKind>(Argument.back()), Expr,
8643         StartLoc, LParenLoc, ArgumentLoc.back(), DelimLoc, EndLoc);
8644     break;
8645   case OMPC_defaultmap:
8646     enum { Modifier, DefaultmapKind };
8647     Res = ActOnOpenMPDefaultmapClause(
8648         static_cast<OpenMPDefaultmapClauseModifier>(Argument[Modifier]),
8649         static_cast<OpenMPDefaultmapClauseKind>(Argument[DefaultmapKind]),
8650         StartLoc, LParenLoc, ArgumentLoc[Modifier], ArgumentLoc[DefaultmapKind],
8651         EndLoc);
8652     break;
8653   case OMPC_final:
8654   case OMPC_num_threads:
8655   case OMPC_safelen:
8656   case OMPC_simdlen:
8657   case OMPC_collapse:
8658   case OMPC_default:
8659   case OMPC_proc_bind:
8660   case OMPC_private:
8661   case OMPC_firstprivate:
8662   case OMPC_lastprivate:
8663   case OMPC_shared:
8664   case OMPC_reduction:
8665   case OMPC_task_reduction:
8666   case OMPC_in_reduction:
8667   case OMPC_linear:
8668   case OMPC_aligned:
8669   case OMPC_copyin:
8670   case OMPC_copyprivate:
8671   case OMPC_ordered:
8672   case OMPC_nowait:
8673   case OMPC_untied:
8674   case OMPC_mergeable:
8675   case OMPC_threadprivate:
8676   case OMPC_flush:
8677   case OMPC_read:
8678   case OMPC_write:
8679   case OMPC_update:
8680   case OMPC_capture:
8681   case OMPC_seq_cst:
8682   case OMPC_depend:
8683   case OMPC_device:
8684   case OMPC_threads:
8685   case OMPC_simd:
8686   case OMPC_map:
8687   case OMPC_num_teams:
8688   case OMPC_thread_limit:
8689   case OMPC_priority:
8690   case OMPC_grainsize:
8691   case OMPC_nogroup:
8692   case OMPC_num_tasks:
8693   case OMPC_hint:
8694   case OMPC_unknown:
8695   case OMPC_uniform:
8696   case OMPC_to:
8697   case OMPC_from:
8698   case OMPC_use_device_ptr:
8699   case OMPC_is_device_ptr:
8700     llvm_unreachable("Clause is not allowed.");
8701   }
8702   return Res;
8703 }
8704 
8705 static bool checkScheduleModifiers(Sema &S, OpenMPScheduleClauseModifier M1,
8706                                    OpenMPScheduleClauseModifier M2,
8707                                    SourceLocation M1Loc, SourceLocation M2Loc) {
8708   if (M1 == OMPC_SCHEDULE_MODIFIER_unknown && M1Loc.isValid()) {
8709     SmallVector<unsigned, 2> Excluded;
8710     if (M2 != OMPC_SCHEDULE_MODIFIER_unknown)
8711       Excluded.push_back(M2);
8712     if (M2 == OMPC_SCHEDULE_MODIFIER_nonmonotonic)
8713       Excluded.push_back(OMPC_SCHEDULE_MODIFIER_monotonic);
8714     if (M2 == OMPC_SCHEDULE_MODIFIER_monotonic)
8715       Excluded.push_back(OMPC_SCHEDULE_MODIFIER_nonmonotonic);
8716     S.Diag(M1Loc, diag::err_omp_unexpected_clause_value)
8717         << getListOfPossibleValues(OMPC_schedule,
8718                                    /*First=*/OMPC_SCHEDULE_MODIFIER_unknown + 1,
8719                                    /*Last=*/OMPC_SCHEDULE_MODIFIER_last,
8720                                    Excluded)
8721         << getOpenMPClauseName(OMPC_schedule);
8722     return true;
8723   }
8724   return false;
8725 }
8726 
8727 OMPClause *Sema::ActOnOpenMPScheduleClause(
8728     OpenMPScheduleClauseModifier M1, OpenMPScheduleClauseModifier M2,
8729     OpenMPScheduleClauseKind Kind, Expr *ChunkSize, SourceLocation StartLoc,
8730     SourceLocation LParenLoc, SourceLocation M1Loc, SourceLocation M2Loc,
8731     SourceLocation KindLoc, SourceLocation CommaLoc, SourceLocation EndLoc) {
8732   if (checkScheduleModifiers(*this, M1, M2, M1Loc, M2Loc) ||
8733       checkScheduleModifiers(*this, M2, M1, M2Loc, M1Loc))
8734     return nullptr;
8735   // OpenMP, 2.7.1, Loop Construct, Restrictions
8736   // Either the monotonic modifier or the nonmonotonic modifier can be specified
8737   // but not both.
8738   if ((M1 == M2 && M1 != OMPC_SCHEDULE_MODIFIER_unknown) ||
8739       (M1 == OMPC_SCHEDULE_MODIFIER_monotonic &&
8740        M2 == OMPC_SCHEDULE_MODIFIER_nonmonotonic) ||
8741       (M1 == OMPC_SCHEDULE_MODIFIER_nonmonotonic &&
8742        M2 == OMPC_SCHEDULE_MODIFIER_monotonic)) {
8743     Diag(M2Loc, diag::err_omp_unexpected_schedule_modifier)
8744         << getOpenMPSimpleClauseTypeName(OMPC_schedule, M2)
8745         << getOpenMPSimpleClauseTypeName(OMPC_schedule, M1);
8746     return nullptr;
8747   }
8748   if (Kind == OMPC_SCHEDULE_unknown) {
8749     std::string Values;
8750     if (M1Loc.isInvalid() && M2Loc.isInvalid()) {
8751       unsigned Exclude[] = {OMPC_SCHEDULE_unknown};
8752       Values = getListOfPossibleValues(OMPC_schedule, /*First=*/0,
8753                                        /*Last=*/OMPC_SCHEDULE_MODIFIER_last,
8754                                        Exclude);
8755     } else {
8756       Values = getListOfPossibleValues(OMPC_schedule, /*First=*/0,
8757                                        /*Last=*/OMPC_SCHEDULE_unknown);
8758     }
8759     Diag(KindLoc, diag::err_omp_unexpected_clause_value)
8760         << Values << getOpenMPClauseName(OMPC_schedule);
8761     return nullptr;
8762   }
8763   // OpenMP, 2.7.1, Loop Construct, Restrictions
8764   // The nonmonotonic modifier can only be specified with schedule(dynamic) or
8765   // schedule(guided).
8766   if ((M1 == OMPC_SCHEDULE_MODIFIER_nonmonotonic ||
8767        M2 == OMPC_SCHEDULE_MODIFIER_nonmonotonic) &&
8768       Kind != OMPC_SCHEDULE_dynamic && Kind != OMPC_SCHEDULE_guided) {
8769     Diag(M1 == OMPC_SCHEDULE_MODIFIER_nonmonotonic ? M1Loc : M2Loc,
8770          diag::err_omp_schedule_nonmonotonic_static);
8771     return nullptr;
8772   }
8773   Expr *ValExpr = ChunkSize;
8774   Stmt *HelperValStmt = nullptr;
8775   if (ChunkSize) {
8776     if (!ChunkSize->isValueDependent() && !ChunkSize->isTypeDependent() &&
8777         !ChunkSize->isInstantiationDependent() &&
8778         !ChunkSize->containsUnexpandedParameterPack()) {
8779       SourceLocation ChunkSizeLoc = ChunkSize->getLocStart();
8780       ExprResult Val =
8781           PerformOpenMPImplicitIntegerConversion(ChunkSizeLoc, ChunkSize);
8782       if (Val.isInvalid())
8783         return nullptr;
8784 
8785       ValExpr = Val.get();
8786 
8787       // OpenMP [2.7.1, Restrictions]
8788       //  chunk_size must be a loop invariant integer expression with a positive
8789       //  value.
8790       llvm::APSInt Result;
8791       if (ValExpr->isIntegerConstantExpr(Result, Context)) {
8792         if (Result.isSigned() && !Result.isStrictlyPositive()) {
8793           Diag(ChunkSizeLoc, diag::err_omp_negative_expression_in_clause)
8794               << "schedule" << 1 << ChunkSize->getSourceRange();
8795           return nullptr;
8796         }
8797       } else if (getOpenMPCaptureRegionForClause(
8798                      DSAStack->getCurrentDirective(), OMPC_schedule) !=
8799                      OMPD_unknown &&
8800                  !CurContext->isDependentContext()) {
8801         ValExpr = MakeFullExpr(ValExpr).get();
8802         llvm::MapVector<Expr *, DeclRefExpr *> Captures;
8803         ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
8804         HelperValStmt = buildPreInits(Context, Captures);
8805       }
8806     }
8807   }
8808 
8809   return new (Context)
8810       OMPScheduleClause(StartLoc, LParenLoc, KindLoc, CommaLoc, EndLoc, Kind,
8811                         ValExpr, HelperValStmt, M1, M1Loc, M2, M2Loc);
8812 }
8813 
8814 OMPClause *Sema::ActOnOpenMPClause(OpenMPClauseKind Kind,
8815                                    SourceLocation StartLoc,
8816                                    SourceLocation EndLoc) {
8817   OMPClause *Res = nullptr;
8818   switch (Kind) {
8819   case OMPC_ordered:
8820     Res = ActOnOpenMPOrderedClause(StartLoc, EndLoc);
8821     break;
8822   case OMPC_nowait:
8823     Res = ActOnOpenMPNowaitClause(StartLoc, EndLoc);
8824     break;
8825   case OMPC_untied:
8826     Res = ActOnOpenMPUntiedClause(StartLoc, EndLoc);
8827     break;
8828   case OMPC_mergeable:
8829     Res = ActOnOpenMPMergeableClause(StartLoc, EndLoc);
8830     break;
8831   case OMPC_read:
8832     Res = ActOnOpenMPReadClause(StartLoc, EndLoc);
8833     break;
8834   case OMPC_write:
8835     Res = ActOnOpenMPWriteClause(StartLoc, EndLoc);
8836     break;
8837   case OMPC_update:
8838     Res = ActOnOpenMPUpdateClause(StartLoc, EndLoc);
8839     break;
8840   case OMPC_capture:
8841     Res = ActOnOpenMPCaptureClause(StartLoc, EndLoc);
8842     break;
8843   case OMPC_seq_cst:
8844     Res = ActOnOpenMPSeqCstClause(StartLoc, EndLoc);
8845     break;
8846   case OMPC_threads:
8847     Res = ActOnOpenMPThreadsClause(StartLoc, EndLoc);
8848     break;
8849   case OMPC_simd:
8850     Res = ActOnOpenMPSIMDClause(StartLoc, EndLoc);
8851     break;
8852   case OMPC_nogroup:
8853     Res = ActOnOpenMPNogroupClause(StartLoc, EndLoc);
8854     break;
8855   case OMPC_if:
8856   case OMPC_final:
8857   case OMPC_num_threads:
8858   case OMPC_safelen:
8859   case OMPC_simdlen:
8860   case OMPC_collapse:
8861   case OMPC_schedule:
8862   case OMPC_private:
8863   case OMPC_firstprivate:
8864   case OMPC_lastprivate:
8865   case OMPC_shared:
8866   case OMPC_reduction:
8867   case OMPC_task_reduction:
8868   case OMPC_in_reduction:
8869   case OMPC_linear:
8870   case OMPC_aligned:
8871   case OMPC_copyin:
8872   case OMPC_copyprivate:
8873   case OMPC_default:
8874   case OMPC_proc_bind:
8875   case OMPC_threadprivate:
8876   case OMPC_flush:
8877   case OMPC_depend:
8878   case OMPC_device:
8879   case OMPC_map:
8880   case OMPC_num_teams:
8881   case OMPC_thread_limit:
8882   case OMPC_priority:
8883   case OMPC_grainsize:
8884   case OMPC_num_tasks:
8885   case OMPC_hint:
8886   case OMPC_dist_schedule:
8887   case OMPC_defaultmap:
8888   case OMPC_unknown:
8889   case OMPC_uniform:
8890   case OMPC_to:
8891   case OMPC_from:
8892   case OMPC_use_device_ptr:
8893   case OMPC_is_device_ptr:
8894     llvm_unreachable("Clause is not allowed.");
8895   }
8896   return Res;
8897 }
8898 
8899 OMPClause *Sema::ActOnOpenMPNowaitClause(SourceLocation StartLoc,
8900                                          SourceLocation EndLoc) {
8901   DSAStack->setNowaitRegion();
8902   return new (Context) OMPNowaitClause(StartLoc, EndLoc);
8903 }
8904 
8905 OMPClause *Sema::ActOnOpenMPUntiedClause(SourceLocation StartLoc,
8906                                          SourceLocation EndLoc) {
8907   return new (Context) OMPUntiedClause(StartLoc, EndLoc);
8908 }
8909 
8910 OMPClause *Sema::ActOnOpenMPMergeableClause(SourceLocation StartLoc,
8911                                             SourceLocation EndLoc) {
8912   return new (Context) OMPMergeableClause(StartLoc, EndLoc);
8913 }
8914 
8915 OMPClause *Sema::ActOnOpenMPReadClause(SourceLocation StartLoc,
8916                                        SourceLocation EndLoc) {
8917   return new (Context) OMPReadClause(StartLoc, EndLoc);
8918 }
8919 
8920 OMPClause *Sema::ActOnOpenMPWriteClause(SourceLocation StartLoc,
8921                                         SourceLocation EndLoc) {
8922   return new (Context) OMPWriteClause(StartLoc, EndLoc);
8923 }
8924 
8925 OMPClause *Sema::ActOnOpenMPUpdateClause(SourceLocation StartLoc,
8926                                          SourceLocation EndLoc) {
8927   return new (Context) OMPUpdateClause(StartLoc, EndLoc);
8928 }
8929 
8930 OMPClause *Sema::ActOnOpenMPCaptureClause(SourceLocation StartLoc,
8931                                           SourceLocation EndLoc) {
8932   return new (Context) OMPCaptureClause(StartLoc, EndLoc);
8933 }
8934 
8935 OMPClause *Sema::ActOnOpenMPSeqCstClause(SourceLocation StartLoc,
8936                                          SourceLocation EndLoc) {
8937   return new (Context) OMPSeqCstClause(StartLoc, EndLoc);
8938 }
8939 
8940 OMPClause *Sema::ActOnOpenMPThreadsClause(SourceLocation StartLoc,
8941                                           SourceLocation EndLoc) {
8942   return new (Context) OMPThreadsClause(StartLoc, EndLoc);
8943 }
8944 
8945 OMPClause *Sema::ActOnOpenMPSIMDClause(SourceLocation StartLoc,
8946                                        SourceLocation EndLoc) {
8947   return new (Context) OMPSIMDClause(StartLoc, EndLoc);
8948 }
8949 
8950 OMPClause *Sema::ActOnOpenMPNogroupClause(SourceLocation StartLoc,
8951                                           SourceLocation EndLoc) {
8952   return new (Context) OMPNogroupClause(StartLoc, EndLoc);
8953 }
8954 
8955 OMPClause *Sema::ActOnOpenMPVarListClause(
8956     OpenMPClauseKind Kind, ArrayRef<Expr *> VarList, Expr *TailExpr,
8957     SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation ColonLoc,
8958     SourceLocation EndLoc, CXXScopeSpec &ReductionIdScopeSpec,
8959     const DeclarationNameInfo &ReductionId, OpenMPDependClauseKind DepKind,
8960     OpenMPLinearClauseKind LinKind, OpenMPMapClauseKind MapTypeModifier,
8961     OpenMPMapClauseKind MapType, bool IsMapTypeImplicit,
8962     SourceLocation DepLinMapLoc) {
8963   OMPClause *Res = nullptr;
8964   switch (Kind) {
8965   case OMPC_private:
8966     Res = ActOnOpenMPPrivateClause(VarList, StartLoc, LParenLoc, EndLoc);
8967     break;
8968   case OMPC_firstprivate:
8969     Res = ActOnOpenMPFirstprivateClause(VarList, StartLoc, LParenLoc, EndLoc);
8970     break;
8971   case OMPC_lastprivate:
8972     Res = ActOnOpenMPLastprivateClause(VarList, StartLoc, LParenLoc, EndLoc);
8973     break;
8974   case OMPC_shared:
8975     Res = ActOnOpenMPSharedClause(VarList, StartLoc, LParenLoc, EndLoc);
8976     break;
8977   case OMPC_reduction:
8978     Res = ActOnOpenMPReductionClause(VarList, StartLoc, LParenLoc, ColonLoc,
8979                                      EndLoc, ReductionIdScopeSpec, ReductionId);
8980     break;
8981   case OMPC_task_reduction:
8982     Res = ActOnOpenMPTaskReductionClause(VarList, StartLoc, LParenLoc, ColonLoc,
8983                                          EndLoc, ReductionIdScopeSpec,
8984                                          ReductionId);
8985     break;
8986   case OMPC_in_reduction:
8987     Res =
8988         ActOnOpenMPInReductionClause(VarList, StartLoc, LParenLoc, ColonLoc,
8989                                      EndLoc, ReductionIdScopeSpec, ReductionId);
8990     break;
8991   case OMPC_linear:
8992     Res = ActOnOpenMPLinearClause(VarList, TailExpr, StartLoc, LParenLoc,
8993                                   LinKind, DepLinMapLoc, ColonLoc, EndLoc);
8994     break;
8995   case OMPC_aligned:
8996     Res = ActOnOpenMPAlignedClause(VarList, TailExpr, StartLoc, LParenLoc,
8997                                    ColonLoc, EndLoc);
8998     break;
8999   case OMPC_copyin:
9000     Res = ActOnOpenMPCopyinClause(VarList, StartLoc, LParenLoc, EndLoc);
9001     break;
9002   case OMPC_copyprivate:
9003     Res = ActOnOpenMPCopyprivateClause(VarList, StartLoc, LParenLoc, EndLoc);
9004     break;
9005   case OMPC_flush:
9006     Res = ActOnOpenMPFlushClause(VarList, StartLoc, LParenLoc, EndLoc);
9007     break;
9008   case OMPC_depend:
9009     Res = ActOnOpenMPDependClause(DepKind, DepLinMapLoc, ColonLoc, VarList,
9010                                   StartLoc, LParenLoc, EndLoc);
9011     break;
9012   case OMPC_map:
9013     Res = ActOnOpenMPMapClause(MapTypeModifier, MapType, IsMapTypeImplicit,
9014                                DepLinMapLoc, ColonLoc, VarList, StartLoc,
9015                                LParenLoc, EndLoc);
9016     break;
9017   case OMPC_to:
9018     Res = ActOnOpenMPToClause(VarList, StartLoc, LParenLoc, EndLoc);
9019     break;
9020   case OMPC_from:
9021     Res = ActOnOpenMPFromClause(VarList, StartLoc, LParenLoc, EndLoc);
9022     break;
9023   case OMPC_use_device_ptr:
9024     Res = ActOnOpenMPUseDevicePtrClause(VarList, StartLoc, LParenLoc, EndLoc);
9025     break;
9026   case OMPC_is_device_ptr:
9027     Res = ActOnOpenMPIsDevicePtrClause(VarList, StartLoc, LParenLoc, EndLoc);
9028     break;
9029   case OMPC_if:
9030   case OMPC_final:
9031   case OMPC_num_threads:
9032   case OMPC_safelen:
9033   case OMPC_simdlen:
9034   case OMPC_collapse:
9035   case OMPC_default:
9036   case OMPC_proc_bind:
9037   case OMPC_schedule:
9038   case OMPC_ordered:
9039   case OMPC_nowait:
9040   case OMPC_untied:
9041   case OMPC_mergeable:
9042   case OMPC_threadprivate:
9043   case OMPC_read:
9044   case OMPC_write:
9045   case OMPC_update:
9046   case OMPC_capture:
9047   case OMPC_seq_cst:
9048   case OMPC_device:
9049   case OMPC_threads:
9050   case OMPC_simd:
9051   case OMPC_num_teams:
9052   case OMPC_thread_limit:
9053   case OMPC_priority:
9054   case OMPC_grainsize:
9055   case OMPC_nogroup:
9056   case OMPC_num_tasks:
9057   case OMPC_hint:
9058   case OMPC_dist_schedule:
9059   case OMPC_defaultmap:
9060   case OMPC_unknown:
9061   case OMPC_uniform:
9062     llvm_unreachable("Clause is not allowed.");
9063   }
9064   return Res;
9065 }
9066 
9067 ExprResult Sema::getOpenMPCapturedExpr(VarDecl *Capture, ExprValueKind VK,
9068                                        ExprObjectKind OK, SourceLocation Loc) {
9069   ExprResult Res = BuildDeclRefExpr(
9070       Capture, Capture->getType().getNonReferenceType(), VK_LValue, Loc);
9071   if (!Res.isUsable())
9072     return ExprError();
9073   if (OK == OK_Ordinary && !getLangOpts().CPlusPlus) {
9074     Res = CreateBuiltinUnaryOp(Loc, UO_Deref, Res.get());
9075     if (!Res.isUsable())
9076       return ExprError();
9077   }
9078   if (VK != VK_LValue && Res.get()->isGLValue()) {
9079     Res = DefaultLvalueConversion(Res.get());
9080     if (!Res.isUsable())
9081       return ExprError();
9082   }
9083   return Res;
9084 }
9085 
9086 static std::pair<ValueDecl *, bool>
9087 getPrivateItem(Sema &S, Expr *&RefExpr, SourceLocation &ELoc,
9088                SourceRange &ERange, bool AllowArraySection = false) {
9089   if (RefExpr->isTypeDependent() || RefExpr->isValueDependent() ||
9090       RefExpr->containsUnexpandedParameterPack())
9091     return std::make_pair(nullptr, true);
9092 
9093   // OpenMP [3.1, C/C++]
9094   //  A list item is a variable name.
9095   // OpenMP  [2.9.3.3, Restrictions, p.1]
9096   //  A variable that is part of another variable (as an array or
9097   //  structure element) cannot appear in a private clause.
9098   RefExpr = RefExpr->IgnoreParens();
9099   enum {
9100     NoArrayExpr = -1,
9101     ArraySubscript = 0,
9102     OMPArraySection = 1
9103   } IsArrayExpr = NoArrayExpr;
9104   if (AllowArraySection) {
9105     if (auto *ASE = dyn_cast_or_null<ArraySubscriptExpr>(RefExpr)) {
9106       auto *Base = ASE->getBase()->IgnoreParenImpCasts();
9107       while (auto *TempASE = dyn_cast<ArraySubscriptExpr>(Base))
9108         Base = TempASE->getBase()->IgnoreParenImpCasts();
9109       RefExpr = Base;
9110       IsArrayExpr = ArraySubscript;
9111     } else if (auto *OASE = dyn_cast_or_null<OMPArraySectionExpr>(RefExpr)) {
9112       auto *Base = OASE->getBase()->IgnoreParenImpCasts();
9113       while (auto *TempOASE = dyn_cast<OMPArraySectionExpr>(Base))
9114         Base = TempOASE->getBase()->IgnoreParenImpCasts();
9115       while (auto *TempASE = dyn_cast<ArraySubscriptExpr>(Base))
9116         Base = TempASE->getBase()->IgnoreParenImpCasts();
9117       RefExpr = Base;
9118       IsArrayExpr = OMPArraySection;
9119     }
9120   }
9121   ELoc = RefExpr->getExprLoc();
9122   ERange = RefExpr->getSourceRange();
9123   RefExpr = RefExpr->IgnoreParenImpCasts();
9124   auto *DE = dyn_cast_or_null<DeclRefExpr>(RefExpr);
9125   auto *ME = dyn_cast_or_null<MemberExpr>(RefExpr);
9126   if ((!DE || !isa<VarDecl>(DE->getDecl())) &&
9127       (S.getCurrentThisType().isNull() || !ME ||
9128        !isa<CXXThisExpr>(ME->getBase()->IgnoreParenImpCasts()) ||
9129        !isa<FieldDecl>(ME->getMemberDecl()))) {
9130     if (IsArrayExpr != NoArrayExpr)
9131       S.Diag(ELoc, diag::err_omp_expected_base_var_name) << IsArrayExpr
9132                                                          << ERange;
9133     else {
9134       S.Diag(ELoc,
9135              AllowArraySection
9136                  ? diag::err_omp_expected_var_name_member_expr_or_array_item
9137                  : diag::err_omp_expected_var_name_member_expr)
9138           << (S.getCurrentThisType().isNull() ? 0 : 1) << ERange;
9139     }
9140     return std::make_pair(nullptr, false);
9141   }
9142   return std::make_pair(
9143       getCanonicalDecl(DE ? DE->getDecl() : ME->getMemberDecl()), false);
9144 }
9145 
9146 OMPClause *Sema::ActOnOpenMPPrivateClause(ArrayRef<Expr *> VarList,
9147                                           SourceLocation StartLoc,
9148                                           SourceLocation LParenLoc,
9149                                           SourceLocation EndLoc) {
9150   SmallVector<Expr *, 8> Vars;
9151   SmallVector<Expr *, 8> PrivateCopies;
9152   for (auto &RefExpr : VarList) {
9153     assert(RefExpr && "NULL expr in OpenMP private clause.");
9154     SourceLocation ELoc;
9155     SourceRange ERange;
9156     Expr *SimpleRefExpr = RefExpr;
9157     auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
9158     if (Res.second) {
9159       // It will be analyzed later.
9160       Vars.push_back(RefExpr);
9161       PrivateCopies.push_back(nullptr);
9162     }
9163     ValueDecl *D = Res.first;
9164     if (!D)
9165       continue;
9166 
9167     QualType Type = D->getType();
9168     auto *VD = dyn_cast<VarDecl>(D);
9169 
9170     // OpenMP [2.9.3.3, Restrictions, C/C++, p.3]
9171     //  A variable that appears in a private clause must not have an incomplete
9172     //  type or a reference type.
9173     if (RequireCompleteType(ELoc, Type, diag::err_omp_private_incomplete_type))
9174       continue;
9175     Type = Type.getNonReferenceType();
9176 
9177     // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
9178     // in a Construct]
9179     //  Variables with the predetermined data-sharing attributes may not be
9180     //  listed in data-sharing attributes clauses, except for the cases
9181     //  listed below. For these exceptions only, listing a predetermined
9182     //  variable in a data-sharing attribute clause is allowed and overrides
9183     //  the variable's predetermined data-sharing attributes.
9184     DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, false);
9185     if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_private) {
9186       Diag(ELoc, diag::err_omp_wrong_dsa) << getOpenMPClauseName(DVar.CKind)
9187                                           << getOpenMPClauseName(OMPC_private);
9188       ReportOriginalDSA(*this, DSAStack, D, DVar);
9189       continue;
9190     }
9191 
9192     auto CurrDir = DSAStack->getCurrentDirective();
9193     // Variably modified types are not supported for tasks.
9194     if (!Type->isAnyPointerType() && Type->isVariablyModifiedType() &&
9195         isOpenMPTaskingDirective(CurrDir)) {
9196       Diag(ELoc, diag::err_omp_variably_modified_type_not_supported)
9197           << getOpenMPClauseName(OMPC_private) << Type
9198           << getOpenMPDirectiveName(CurrDir);
9199       bool IsDecl =
9200           !VD ||
9201           VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
9202       Diag(D->getLocation(),
9203            IsDecl ? diag::note_previous_decl : diag::note_defined_here)
9204           << D;
9205       continue;
9206     }
9207 
9208     // OpenMP 4.5 [2.15.5.1, Restrictions, p.3]
9209     // A list item cannot appear in both a map clause and a data-sharing
9210     // attribute clause on the same construct
9211     if (CurrDir == OMPD_target || CurrDir == OMPD_target_parallel ||
9212         CurrDir == OMPD_target_teams ||
9213         CurrDir == OMPD_target_teams_distribute ||
9214         CurrDir == OMPD_target_teams_distribute_parallel_for ||
9215         CurrDir == OMPD_target_teams_distribute_parallel_for_simd ||
9216         CurrDir == OMPD_target_teams_distribute_simd ||
9217         CurrDir == OMPD_target_parallel_for_simd ||
9218         CurrDir == OMPD_target_parallel_for) {
9219       OpenMPClauseKind ConflictKind;
9220       if (DSAStack->checkMappableExprComponentListsForDecl(
9221               VD, /*CurrentRegionOnly=*/true,
9222               [&](OMPClauseMappableExprCommon::MappableExprComponentListRef,
9223                   OpenMPClauseKind WhereFoundClauseKind) -> bool {
9224                 ConflictKind = WhereFoundClauseKind;
9225                 return true;
9226               })) {
9227         Diag(ELoc, diag::err_omp_variable_in_given_clause_and_dsa)
9228             << getOpenMPClauseName(OMPC_private)
9229             << getOpenMPClauseName(ConflictKind)
9230             << getOpenMPDirectiveName(CurrDir);
9231         ReportOriginalDSA(*this, DSAStack, D, DVar);
9232         continue;
9233       }
9234     }
9235 
9236     // OpenMP [2.9.3.3, Restrictions, C/C++, p.1]
9237     //  A variable of class type (or array thereof) that appears in a private
9238     //  clause requires an accessible, unambiguous default constructor for the
9239     //  class type.
9240     // Generate helper private variable and initialize it with the default
9241     // value. The address of the original variable is replaced by the address of
9242     // the new private variable in CodeGen. This new variable is not added to
9243     // IdResolver, so the code in the OpenMP region uses original variable for
9244     // proper diagnostics.
9245     Type = Type.getUnqualifiedType();
9246     auto VDPrivate = buildVarDecl(*this, ELoc, Type, D->getName(),
9247                                   D->hasAttrs() ? &D->getAttrs() : nullptr);
9248     ActOnUninitializedDecl(VDPrivate);
9249     if (VDPrivate->isInvalidDecl())
9250       continue;
9251     auto VDPrivateRefExpr = buildDeclRefExpr(
9252         *this, VDPrivate, RefExpr->getType().getUnqualifiedType(), ELoc);
9253 
9254     DeclRefExpr *Ref = nullptr;
9255     if (!VD && !CurContext->isDependentContext())
9256       Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/false);
9257     DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_private, Ref);
9258     Vars.push_back((VD || CurContext->isDependentContext())
9259                        ? RefExpr->IgnoreParens()
9260                        : Ref);
9261     PrivateCopies.push_back(VDPrivateRefExpr);
9262   }
9263 
9264   if (Vars.empty())
9265     return nullptr;
9266 
9267   return OMPPrivateClause::Create(Context, StartLoc, LParenLoc, EndLoc, Vars,
9268                                   PrivateCopies);
9269 }
9270 
9271 namespace {
9272 class DiagsUninitializedSeveretyRAII {
9273 private:
9274   DiagnosticsEngine &Diags;
9275   SourceLocation SavedLoc;
9276   bool IsIgnored;
9277 
9278 public:
9279   DiagsUninitializedSeveretyRAII(DiagnosticsEngine &Diags, SourceLocation Loc,
9280                                  bool IsIgnored)
9281       : Diags(Diags), SavedLoc(Loc), IsIgnored(IsIgnored) {
9282     if (!IsIgnored) {
9283       Diags.setSeverity(/*Diag*/ diag::warn_uninit_self_reference_in_init,
9284                         /*Map*/ diag::Severity::Ignored, Loc);
9285     }
9286   }
9287   ~DiagsUninitializedSeveretyRAII() {
9288     if (!IsIgnored)
9289       Diags.popMappings(SavedLoc);
9290   }
9291 };
9292 }
9293 
9294 OMPClause *Sema::ActOnOpenMPFirstprivateClause(ArrayRef<Expr *> VarList,
9295                                                SourceLocation StartLoc,
9296                                                SourceLocation LParenLoc,
9297                                                SourceLocation EndLoc) {
9298   SmallVector<Expr *, 8> Vars;
9299   SmallVector<Expr *, 8> PrivateCopies;
9300   SmallVector<Expr *, 8> Inits;
9301   SmallVector<Decl *, 4> ExprCaptures;
9302   bool IsImplicitClause =
9303       StartLoc.isInvalid() && LParenLoc.isInvalid() && EndLoc.isInvalid();
9304   auto ImplicitClauseLoc = DSAStack->getConstructLoc();
9305 
9306   for (auto &RefExpr : VarList) {
9307     assert(RefExpr && "NULL expr in OpenMP firstprivate clause.");
9308     SourceLocation ELoc;
9309     SourceRange ERange;
9310     Expr *SimpleRefExpr = RefExpr;
9311     auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
9312     if (Res.second) {
9313       // It will be analyzed later.
9314       Vars.push_back(RefExpr);
9315       PrivateCopies.push_back(nullptr);
9316       Inits.push_back(nullptr);
9317     }
9318     ValueDecl *D = Res.first;
9319     if (!D)
9320       continue;
9321 
9322     ELoc = IsImplicitClause ? ImplicitClauseLoc : ELoc;
9323     QualType Type = D->getType();
9324     auto *VD = dyn_cast<VarDecl>(D);
9325 
9326     // OpenMP [2.9.3.3, Restrictions, C/C++, p.3]
9327     //  A variable that appears in a private clause must not have an incomplete
9328     //  type or a reference type.
9329     if (RequireCompleteType(ELoc, Type,
9330                             diag::err_omp_firstprivate_incomplete_type))
9331       continue;
9332     Type = Type.getNonReferenceType();
9333 
9334     // OpenMP [2.9.3.4, Restrictions, C/C++, p.1]
9335     //  A variable of class type (or array thereof) that appears in a private
9336     //  clause requires an accessible, unambiguous copy constructor for the
9337     //  class type.
9338     auto ElemType = Context.getBaseElementType(Type).getNonReferenceType();
9339 
9340     // If an implicit firstprivate variable found it was checked already.
9341     DSAStackTy::DSAVarData TopDVar;
9342     if (!IsImplicitClause) {
9343       DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, false);
9344       TopDVar = DVar;
9345       OpenMPDirectiveKind CurrDir = DSAStack->getCurrentDirective();
9346       bool IsConstant = ElemType.isConstant(Context);
9347       // OpenMP [2.4.13, Data-sharing Attribute Clauses]
9348       //  A list item that specifies a given variable may not appear in more
9349       // than one clause on the same directive, except that a variable may be
9350       //  specified in both firstprivate and lastprivate clauses.
9351       // OpenMP 4.5 [2.10.8, Distribute Construct, p.3]
9352       // A list item may appear in a firstprivate or lastprivate clause but not
9353       // both.
9354       if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_firstprivate &&
9355           (isOpenMPDistributeDirective(CurrDir) ||
9356            DVar.CKind != OMPC_lastprivate) &&
9357           DVar.RefExpr) {
9358         Diag(ELoc, diag::err_omp_wrong_dsa)
9359             << getOpenMPClauseName(DVar.CKind)
9360             << getOpenMPClauseName(OMPC_firstprivate);
9361         ReportOriginalDSA(*this, DSAStack, D, DVar);
9362         continue;
9363       }
9364 
9365       // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
9366       // in a Construct]
9367       //  Variables with the predetermined data-sharing attributes may not be
9368       //  listed in data-sharing attributes clauses, except for the cases
9369       //  listed below. For these exceptions only, listing a predetermined
9370       //  variable in a data-sharing attribute clause is allowed and overrides
9371       //  the variable's predetermined data-sharing attributes.
9372       // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
9373       // in a Construct, C/C++, p.2]
9374       //  Variables with const-qualified type having no mutable member may be
9375       //  listed in a firstprivate clause, even if they are static data members.
9376       if (!(IsConstant || (VD && VD->isStaticDataMember())) && !DVar.RefExpr &&
9377           DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_shared) {
9378         Diag(ELoc, diag::err_omp_wrong_dsa)
9379             << getOpenMPClauseName(DVar.CKind)
9380             << getOpenMPClauseName(OMPC_firstprivate);
9381         ReportOriginalDSA(*this, DSAStack, D, DVar);
9382         continue;
9383       }
9384 
9385       // OpenMP [2.9.3.4, Restrictions, p.2]
9386       //  A list item that is private within a parallel region must not appear
9387       //  in a firstprivate clause on a worksharing construct if any of the
9388       //  worksharing regions arising from the worksharing construct ever bind
9389       //  to any of the parallel regions arising from the parallel construct.
9390       // OpenMP 4.5 [2.15.3.4, Restrictions, p.3]
9391       // A list item that is private within a teams region must not appear in a
9392       // firstprivate clause on a distribute construct if any of the distribute
9393       // regions arising from the distribute construct ever bind to any of the
9394       // teams regions arising from the teams construct.
9395       // OpenMP 4.5 [2.15.3.4, Restrictions, p.3]
9396       // A list item that appears in a reduction clause of a teams construct
9397       // must not appear in a firstprivate clause on a distribute construct if
9398       // any of the distribute regions arising from the distribute construct
9399       // ever bind to any of the teams regions arising from the teams construct.
9400       if ((isOpenMPWorksharingDirective(CurrDir) ||
9401            isOpenMPDistributeDirective(CurrDir)) &&
9402           !isOpenMPParallelDirective(CurrDir) &&
9403           !isOpenMPTeamsDirective(CurrDir)) {
9404         DVar = DSAStack->getImplicitDSA(D, true);
9405         if (DVar.CKind != OMPC_shared &&
9406             (isOpenMPParallelDirective(DVar.DKind) ||
9407              isOpenMPTeamsDirective(DVar.DKind) ||
9408              DVar.DKind == OMPD_unknown)) {
9409           Diag(ELoc, diag::err_omp_required_access)
9410               << getOpenMPClauseName(OMPC_firstprivate)
9411               << getOpenMPClauseName(OMPC_shared);
9412           ReportOriginalDSA(*this, DSAStack, D, DVar);
9413           continue;
9414         }
9415       }
9416       // OpenMP [2.9.3.4, Restrictions, p.3]
9417       //  A list item that appears in a reduction clause of a parallel construct
9418       //  must not appear in a firstprivate clause on a worksharing or task
9419       //  construct if any of the worksharing or task regions arising from the
9420       //  worksharing or task construct ever bind to any of the parallel regions
9421       //  arising from the parallel construct.
9422       // OpenMP [2.9.3.4, Restrictions, p.4]
9423       //  A list item that appears in a reduction clause in worksharing
9424       //  construct must not appear in a firstprivate clause in a task construct
9425       //  encountered during execution of any of the worksharing regions arising
9426       //  from the worksharing construct.
9427       if (isOpenMPTaskingDirective(CurrDir)) {
9428         DVar = DSAStack->hasInnermostDSA(
9429             D, [](OpenMPClauseKind C) -> bool { return C == OMPC_reduction; },
9430             [](OpenMPDirectiveKind K) -> bool {
9431               return isOpenMPParallelDirective(K) ||
9432                      isOpenMPWorksharingDirective(K) ||
9433                      isOpenMPTeamsDirective(K);
9434             },
9435             /*FromParent=*/true);
9436         if (DVar.CKind == OMPC_reduction &&
9437             (isOpenMPParallelDirective(DVar.DKind) ||
9438              isOpenMPWorksharingDirective(DVar.DKind) ||
9439              isOpenMPTeamsDirective(DVar.DKind))) {
9440           Diag(ELoc, diag::err_omp_parallel_reduction_in_task_firstprivate)
9441               << getOpenMPDirectiveName(DVar.DKind);
9442           ReportOriginalDSA(*this, DSAStack, D, DVar);
9443           continue;
9444         }
9445       }
9446 
9447       // OpenMP 4.5 [2.15.5.1, Restrictions, p.3]
9448       // A list item cannot appear in both a map clause and a data-sharing
9449       // attribute clause on the same construct
9450       if (isOpenMPTargetExecutionDirective(CurrDir)) {
9451         OpenMPClauseKind ConflictKind;
9452         if (DSAStack->checkMappableExprComponentListsForDecl(
9453                 VD, /*CurrentRegionOnly=*/true,
9454                 [&](OMPClauseMappableExprCommon::MappableExprComponentListRef,
9455                     OpenMPClauseKind WhereFoundClauseKind) -> bool {
9456                   ConflictKind = WhereFoundClauseKind;
9457                   return true;
9458                 })) {
9459           Diag(ELoc, diag::err_omp_variable_in_given_clause_and_dsa)
9460               << getOpenMPClauseName(OMPC_firstprivate)
9461               << getOpenMPClauseName(ConflictKind)
9462               << getOpenMPDirectiveName(DSAStack->getCurrentDirective());
9463           ReportOriginalDSA(*this, DSAStack, D, DVar);
9464           continue;
9465         }
9466       }
9467     }
9468 
9469     // Variably modified types are not supported for tasks.
9470     if (!Type->isAnyPointerType() && Type->isVariablyModifiedType() &&
9471         isOpenMPTaskingDirective(DSAStack->getCurrentDirective())) {
9472       Diag(ELoc, diag::err_omp_variably_modified_type_not_supported)
9473           << getOpenMPClauseName(OMPC_firstprivate) << Type
9474           << getOpenMPDirectiveName(DSAStack->getCurrentDirective());
9475       bool IsDecl =
9476           !VD ||
9477           VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
9478       Diag(D->getLocation(),
9479            IsDecl ? diag::note_previous_decl : diag::note_defined_here)
9480           << D;
9481       continue;
9482     }
9483 
9484     Type = Type.getUnqualifiedType();
9485     auto VDPrivate = buildVarDecl(*this, ELoc, Type, D->getName(),
9486                                   D->hasAttrs() ? &D->getAttrs() : nullptr);
9487     // Generate helper private variable and initialize it with the value of the
9488     // original variable. The address of the original variable is replaced by
9489     // the address of the new private variable in the CodeGen. This new variable
9490     // is not added to IdResolver, so the code in the OpenMP region uses
9491     // original variable for proper diagnostics and variable capturing.
9492     Expr *VDInitRefExpr = nullptr;
9493     // For arrays generate initializer for single element and replace it by the
9494     // original array element in CodeGen.
9495     if (Type->isArrayType()) {
9496       auto VDInit =
9497           buildVarDecl(*this, RefExpr->getExprLoc(), ElemType, D->getName());
9498       VDInitRefExpr = buildDeclRefExpr(*this, VDInit, ElemType, ELoc);
9499       auto Init = DefaultLvalueConversion(VDInitRefExpr).get();
9500       ElemType = ElemType.getUnqualifiedType();
9501       auto *VDInitTemp = buildVarDecl(*this, RefExpr->getExprLoc(), ElemType,
9502                                       ".firstprivate.temp");
9503       InitializedEntity Entity =
9504           InitializedEntity::InitializeVariable(VDInitTemp);
9505       InitializationKind Kind = InitializationKind::CreateCopy(ELoc, ELoc);
9506 
9507       InitializationSequence InitSeq(*this, Entity, Kind, Init);
9508       ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Init);
9509       if (Result.isInvalid())
9510         VDPrivate->setInvalidDecl();
9511       else
9512         VDPrivate->setInit(Result.getAs<Expr>());
9513       // Remove temp variable declaration.
9514       Context.Deallocate(VDInitTemp);
9515     } else {
9516       auto *VDInit = buildVarDecl(*this, RefExpr->getExprLoc(), Type,
9517                                   ".firstprivate.temp");
9518       VDInitRefExpr = buildDeclRefExpr(*this, VDInit, RefExpr->getType(),
9519                                        RefExpr->getExprLoc());
9520       AddInitializerToDecl(VDPrivate,
9521                            DefaultLvalueConversion(VDInitRefExpr).get(),
9522                            /*DirectInit=*/false);
9523     }
9524     if (VDPrivate->isInvalidDecl()) {
9525       if (IsImplicitClause) {
9526         Diag(RefExpr->getExprLoc(),
9527              diag::note_omp_task_predetermined_firstprivate_here);
9528       }
9529       continue;
9530     }
9531     CurContext->addDecl(VDPrivate);
9532     auto VDPrivateRefExpr = buildDeclRefExpr(
9533         *this, VDPrivate, RefExpr->getType().getUnqualifiedType(),
9534         RefExpr->getExprLoc());
9535     DeclRefExpr *Ref = nullptr;
9536     if (!VD && !CurContext->isDependentContext()) {
9537       if (TopDVar.CKind == OMPC_lastprivate)
9538         Ref = TopDVar.PrivateCopy;
9539       else {
9540         Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/true);
9541         if (!IsOpenMPCapturedDecl(D))
9542           ExprCaptures.push_back(Ref->getDecl());
9543       }
9544     }
9545     DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_firstprivate, Ref);
9546     Vars.push_back((VD || CurContext->isDependentContext())
9547                        ? RefExpr->IgnoreParens()
9548                        : Ref);
9549     PrivateCopies.push_back(VDPrivateRefExpr);
9550     Inits.push_back(VDInitRefExpr);
9551   }
9552 
9553   if (Vars.empty())
9554     return nullptr;
9555 
9556   return OMPFirstprivateClause::Create(Context, StartLoc, LParenLoc, EndLoc,
9557                                        Vars, PrivateCopies, Inits,
9558                                        buildPreInits(Context, ExprCaptures));
9559 }
9560 
9561 OMPClause *Sema::ActOnOpenMPLastprivateClause(ArrayRef<Expr *> VarList,
9562                                               SourceLocation StartLoc,
9563                                               SourceLocation LParenLoc,
9564                                               SourceLocation EndLoc) {
9565   SmallVector<Expr *, 8> Vars;
9566   SmallVector<Expr *, 8> SrcExprs;
9567   SmallVector<Expr *, 8> DstExprs;
9568   SmallVector<Expr *, 8> AssignmentOps;
9569   SmallVector<Decl *, 4> ExprCaptures;
9570   SmallVector<Expr *, 4> ExprPostUpdates;
9571   for (auto &RefExpr : VarList) {
9572     assert(RefExpr && "NULL expr in OpenMP lastprivate clause.");
9573     SourceLocation ELoc;
9574     SourceRange ERange;
9575     Expr *SimpleRefExpr = RefExpr;
9576     auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
9577     if (Res.second) {
9578       // It will be analyzed later.
9579       Vars.push_back(RefExpr);
9580       SrcExprs.push_back(nullptr);
9581       DstExprs.push_back(nullptr);
9582       AssignmentOps.push_back(nullptr);
9583     }
9584     ValueDecl *D = Res.first;
9585     if (!D)
9586       continue;
9587 
9588     QualType Type = D->getType();
9589     auto *VD = dyn_cast<VarDecl>(D);
9590 
9591     // OpenMP [2.14.3.5, Restrictions, C/C++, p.2]
9592     //  A variable that appears in a lastprivate clause must not have an
9593     //  incomplete type or a reference type.
9594     if (RequireCompleteType(ELoc, Type,
9595                             diag::err_omp_lastprivate_incomplete_type))
9596       continue;
9597     Type = Type.getNonReferenceType();
9598 
9599     OpenMPDirectiveKind CurrDir = DSAStack->getCurrentDirective();
9600     // OpenMP [2.14.1.1, Data-sharing Attribute Rules for Variables Referenced
9601     // in a Construct]
9602     //  Variables with the predetermined data-sharing attributes may not be
9603     //  listed in data-sharing attributes clauses, except for the cases
9604     //  listed below.
9605     // OpenMP 4.5 [2.10.8, Distribute Construct, p.3]
9606     // A list item may appear in a firstprivate or lastprivate clause but not
9607     // both.
9608     DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, false);
9609     if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_lastprivate &&
9610         (isOpenMPDistributeDirective(CurrDir) ||
9611          DVar.CKind != OMPC_firstprivate) &&
9612         (DVar.CKind != OMPC_private || DVar.RefExpr != nullptr)) {
9613       Diag(ELoc, diag::err_omp_wrong_dsa)
9614           << getOpenMPClauseName(DVar.CKind)
9615           << getOpenMPClauseName(OMPC_lastprivate);
9616       ReportOriginalDSA(*this, DSAStack, D, DVar);
9617       continue;
9618     }
9619 
9620     // OpenMP [2.14.3.5, Restrictions, p.2]
9621     // A list item that is private within a parallel region, or that appears in
9622     // the reduction clause of a parallel construct, must not appear in a
9623     // lastprivate clause on a worksharing construct if any of the corresponding
9624     // worksharing regions ever binds to any of the corresponding parallel
9625     // regions.
9626     DSAStackTy::DSAVarData TopDVar = DVar;
9627     if (isOpenMPWorksharingDirective(CurrDir) &&
9628         !isOpenMPParallelDirective(CurrDir) &&
9629         !isOpenMPTeamsDirective(CurrDir)) {
9630       DVar = DSAStack->getImplicitDSA(D, true);
9631       if (DVar.CKind != OMPC_shared) {
9632         Diag(ELoc, diag::err_omp_required_access)
9633             << getOpenMPClauseName(OMPC_lastprivate)
9634             << getOpenMPClauseName(OMPC_shared);
9635         ReportOriginalDSA(*this, DSAStack, D, DVar);
9636         continue;
9637       }
9638     }
9639 
9640     // OpenMP [2.14.3.5, Restrictions, C++, p.1,2]
9641     //  A variable of class type (or array thereof) that appears in a
9642     //  lastprivate clause requires an accessible, unambiguous default
9643     //  constructor for the class type, unless the list item is also specified
9644     //  in a firstprivate clause.
9645     //  A variable of class type (or array thereof) that appears in a
9646     //  lastprivate clause requires an accessible, unambiguous copy assignment
9647     //  operator for the class type.
9648     Type = Context.getBaseElementType(Type).getNonReferenceType();
9649     auto *SrcVD = buildVarDecl(*this, ERange.getBegin(),
9650                                Type.getUnqualifiedType(), ".lastprivate.src",
9651                                D->hasAttrs() ? &D->getAttrs() : nullptr);
9652     auto *PseudoSrcExpr =
9653         buildDeclRefExpr(*this, SrcVD, Type.getUnqualifiedType(), ELoc);
9654     auto *DstVD =
9655         buildVarDecl(*this, ERange.getBegin(), Type, ".lastprivate.dst",
9656                      D->hasAttrs() ? &D->getAttrs() : nullptr);
9657     auto *PseudoDstExpr = buildDeclRefExpr(*this, DstVD, Type, ELoc);
9658     // For arrays generate assignment operation for single element and replace
9659     // it by the original array element in CodeGen.
9660     auto AssignmentOp = BuildBinOp(/*S=*/nullptr, ELoc, BO_Assign,
9661                                    PseudoDstExpr, PseudoSrcExpr);
9662     if (AssignmentOp.isInvalid())
9663       continue;
9664     AssignmentOp = ActOnFinishFullExpr(AssignmentOp.get(), ELoc,
9665                                        /*DiscardedValue=*/true);
9666     if (AssignmentOp.isInvalid())
9667       continue;
9668 
9669     DeclRefExpr *Ref = nullptr;
9670     if (!VD && !CurContext->isDependentContext()) {
9671       if (TopDVar.CKind == OMPC_firstprivate)
9672         Ref = TopDVar.PrivateCopy;
9673       else {
9674         Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/false);
9675         if (!IsOpenMPCapturedDecl(D))
9676           ExprCaptures.push_back(Ref->getDecl());
9677       }
9678       if (TopDVar.CKind == OMPC_firstprivate ||
9679           (!IsOpenMPCapturedDecl(D) &&
9680            Ref->getDecl()->hasAttr<OMPCaptureNoInitAttr>())) {
9681         ExprResult RefRes = DefaultLvalueConversion(Ref);
9682         if (!RefRes.isUsable())
9683           continue;
9684         ExprResult PostUpdateRes =
9685             BuildBinOp(DSAStack->getCurScope(), ELoc, BO_Assign, SimpleRefExpr,
9686                        RefRes.get());
9687         if (!PostUpdateRes.isUsable())
9688           continue;
9689         ExprPostUpdates.push_back(
9690             IgnoredValueConversions(PostUpdateRes.get()).get());
9691       }
9692     }
9693     DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_lastprivate, Ref);
9694     Vars.push_back((VD || CurContext->isDependentContext())
9695                        ? RefExpr->IgnoreParens()
9696                        : Ref);
9697     SrcExprs.push_back(PseudoSrcExpr);
9698     DstExprs.push_back(PseudoDstExpr);
9699     AssignmentOps.push_back(AssignmentOp.get());
9700   }
9701 
9702   if (Vars.empty())
9703     return nullptr;
9704 
9705   return OMPLastprivateClause::Create(Context, StartLoc, LParenLoc, EndLoc,
9706                                       Vars, SrcExprs, DstExprs, AssignmentOps,
9707                                       buildPreInits(Context, ExprCaptures),
9708                                       buildPostUpdate(*this, ExprPostUpdates));
9709 }
9710 
9711 OMPClause *Sema::ActOnOpenMPSharedClause(ArrayRef<Expr *> VarList,
9712                                          SourceLocation StartLoc,
9713                                          SourceLocation LParenLoc,
9714                                          SourceLocation EndLoc) {
9715   SmallVector<Expr *, 8> Vars;
9716   for (auto &RefExpr : VarList) {
9717     assert(RefExpr && "NULL expr in OpenMP lastprivate clause.");
9718     SourceLocation ELoc;
9719     SourceRange ERange;
9720     Expr *SimpleRefExpr = RefExpr;
9721     auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
9722     if (Res.second) {
9723       // It will be analyzed later.
9724       Vars.push_back(RefExpr);
9725     }
9726     ValueDecl *D = Res.first;
9727     if (!D)
9728       continue;
9729 
9730     auto *VD = dyn_cast<VarDecl>(D);
9731     // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
9732     // in a Construct]
9733     //  Variables with the predetermined data-sharing attributes may not be
9734     //  listed in data-sharing attributes clauses, except for the cases
9735     //  listed below. For these exceptions only, listing a predetermined
9736     //  variable in a data-sharing attribute clause is allowed and overrides
9737     //  the variable's predetermined data-sharing attributes.
9738     DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, false);
9739     if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_shared &&
9740         DVar.RefExpr) {
9741       Diag(ELoc, diag::err_omp_wrong_dsa) << getOpenMPClauseName(DVar.CKind)
9742                                           << getOpenMPClauseName(OMPC_shared);
9743       ReportOriginalDSA(*this, DSAStack, D, DVar);
9744       continue;
9745     }
9746 
9747     DeclRefExpr *Ref = nullptr;
9748     if (!VD && IsOpenMPCapturedDecl(D) && !CurContext->isDependentContext())
9749       Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/true);
9750     DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_shared, Ref);
9751     Vars.push_back((VD || !Ref || CurContext->isDependentContext())
9752                        ? RefExpr->IgnoreParens()
9753                        : Ref);
9754   }
9755 
9756   if (Vars.empty())
9757     return nullptr;
9758 
9759   return OMPSharedClause::Create(Context, StartLoc, LParenLoc, EndLoc, Vars);
9760 }
9761 
9762 namespace {
9763 class DSARefChecker : public StmtVisitor<DSARefChecker, bool> {
9764   DSAStackTy *Stack;
9765 
9766 public:
9767   bool VisitDeclRefExpr(DeclRefExpr *E) {
9768     if (VarDecl *VD = dyn_cast<VarDecl>(E->getDecl())) {
9769       DSAStackTy::DSAVarData DVar = Stack->getTopDSA(VD, false);
9770       if (DVar.CKind == OMPC_shared && !DVar.RefExpr)
9771         return false;
9772       if (DVar.CKind != OMPC_unknown)
9773         return true;
9774       DSAStackTy::DSAVarData DVarPrivate = Stack->hasDSA(
9775           VD, isOpenMPPrivate, [](OpenMPDirectiveKind) -> bool { return true; },
9776           /*FromParent=*/true);
9777       if (DVarPrivate.CKind != OMPC_unknown)
9778         return true;
9779       return false;
9780     }
9781     return false;
9782   }
9783   bool VisitStmt(Stmt *S) {
9784     for (auto Child : S->children()) {
9785       if (Child && Visit(Child))
9786         return true;
9787     }
9788     return false;
9789   }
9790   explicit DSARefChecker(DSAStackTy *S) : Stack(S) {}
9791 };
9792 } // namespace
9793 
9794 namespace {
9795 // Transform MemberExpression for specified FieldDecl of current class to
9796 // DeclRefExpr to specified OMPCapturedExprDecl.
9797 class TransformExprToCaptures : public TreeTransform<TransformExprToCaptures> {
9798   typedef TreeTransform<TransformExprToCaptures> BaseTransform;
9799   ValueDecl *Field;
9800   DeclRefExpr *CapturedExpr;
9801 
9802 public:
9803   TransformExprToCaptures(Sema &SemaRef, ValueDecl *FieldDecl)
9804       : BaseTransform(SemaRef), Field(FieldDecl), CapturedExpr(nullptr) {}
9805 
9806   ExprResult TransformMemberExpr(MemberExpr *E) {
9807     if (isa<CXXThisExpr>(E->getBase()->IgnoreParenImpCasts()) &&
9808         E->getMemberDecl() == Field) {
9809       CapturedExpr = buildCapture(SemaRef, Field, E, /*WithInit=*/false);
9810       return CapturedExpr;
9811     }
9812     return BaseTransform::TransformMemberExpr(E);
9813   }
9814   DeclRefExpr *getCapturedExpr() { return CapturedExpr; }
9815 };
9816 } // namespace
9817 
9818 template <typename T>
9819 static T filterLookupForUDR(SmallVectorImpl<UnresolvedSet<8>> &Lookups,
9820                             const llvm::function_ref<T(ValueDecl *)> &Gen) {
9821   for (auto &Set : Lookups) {
9822     for (auto *D : Set) {
9823       if (auto Res = Gen(cast<ValueDecl>(D)))
9824         return Res;
9825     }
9826   }
9827   return T();
9828 }
9829 
9830 static ExprResult
9831 buildDeclareReductionRef(Sema &SemaRef, SourceLocation Loc, SourceRange Range,
9832                          Scope *S, CXXScopeSpec &ReductionIdScopeSpec,
9833                          const DeclarationNameInfo &ReductionId, QualType Ty,
9834                          CXXCastPath &BasePath, Expr *UnresolvedReduction) {
9835   if (ReductionIdScopeSpec.isInvalid())
9836     return ExprError();
9837   SmallVector<UnresolvedSet<8>, 4> Lookups;
9838   if (S) {
9839     LookupResult Lookup(SemaRef, ReductionId, Sema::LookupOMPReductionName);
9840     Lookup.suppressDiagnostics();
9841     while (S && SemaRef.LookupParsedName(Lookup, S, &ReductionIdScopeSpec)) {
9842       auto *D = Lookup.getRepresentativeDecl();
9843       do {
9844         S = S->getParent();
9845       } while (S && !S->isDeclScope(D));
9846       if (S)
9847         S = S->getParent();
9848       Lookups.push_back(UnresolvedSet<8>());
9849       Lookups.back().append(Lookup.begin(), Lookup.end());
9850       Lookup.clear();
9851     }
9852   } else if (auto *ULE =
9853                  cast_or_null<UnresolvedLookupExpr>(UnresolvedReduction)) {
9854     Lookups.push_back(UnresolvedSet<8>());
9855     Decl *PrevD = nullptr;
9856     for (auto *D : ULE->decls()) {
9857       if (D == PrevD)
9858         Lookups.push_back(UnresolvedSet<8>());
9859       else if (auto *DRD = cast<OMPDeclareReductionDecl>(D))
9860         Lookups.back().addDecl(DRD);
9861       PrevD = D;
9862     }
9863   }
9864   if (SemaRef.CurContext->isDependentContext() || Ty->isDependentType() ||
9865       Ty->isInstantiationDependentType() ||
9866       Ty->containsUnexpandedParameterPack() ||
9867       filterLookupForUDR<bool>(Lookups, [](ValueDecl *D) -> bool {
9868         return !D->isInvalidDecl() &&
9869                (D->getType()->isDependentType() ||
9870                 D->getType()->isInstantiationDependentType() ||
9871                 D->getType()->containsUnexpandedParameterPack());
9872       })) {
9873     UnresolvedSet<8> ResSet;
9874     for (auto &Set : Lookups) {
9875       ResSet.append(Set.begin(), Set.end());
9876       // The last item marks the end of all declarations at the specified scope.
9877       ResSet.addDecl(Set[Set.size() - 1]);
9878     }
9879     return UnresolvedLookupExpr::Create(
9880         SemaRef.Context, /*NamingClass=*/nullptr,
9881         ReductionIdScopeSpec.getWithLocInContext(SemaRef.Context), ReductionId,
9882         /*ADL=*/true, /*Overloaded=*/true, ResSet.begin(), ResSet.end());
9883   }
9884   if (auto *VD = filterLookupForUDR<ValueDecl *>(
9885           Lookups, [&SemaRef, Ty](ValueDecl *D) -> ValueDecl * {
9886             if (!D->isInvalidDecl() &&
9887                 SemaRef.Context.hasSameType(D->getType(), Ty))
9888               return D;
9889             return nullptr;
9890           }))
9891     return SemaRef.BuildDeclRefExpr(VD, Ty, VK_LValue, Loc);
9892   if (auto *VD = filterLookupForUDR<ValueDecl *>(
9893           Lookups, [&SemaRef, Ty, Loc](ValueDecl *D) -> ValueDecl * {
9894             if (!D->isInvalidDecl() &&
9895                 SemaRef.IsDerivedFrom(Loc, Ty, D->getType()) &&
9896                 !Ty.isMoreQualifiedThan(D->getType()))
9897               return D;
9898             return nullptr;
9899           })) {
9900     CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
9901                        /*DetectVirtual=*/false);
9902     if (SemaRef.IsDerivedFrom(Loc, Ty, VD->getType(), Paths)) {
9903       if (!Paths.isAmbiguous(SemaRef.Context.getCanonicalType(
9904               VD->getType().getUnqualifiedType()))) {
9905         if (SemaRef.CheckBaseClassAccess(Loc, VD->getType(), Ty, Paths.front(),
9906                                          /*DiagID=*/0) !=
9907             Sema::AR_inaccessible) {
9908           SemaRef.BuildBasePathArray(Paths, BasePath);
9909           return SemaRef.BuildDeclRefExpr(VD, Ty, VK_LValue, Loc);
9910         }
9911       }
9912     }
9913   }
9914   if (ReductionIdScopeSpec.isSet()) {
9915     SemaRef.Diag(Loc, diag::err_omp_not_resolved_reduction_identifier) << Range;
9916     return ExprError();
9917   }
9918   return ExprEmpty();
9919 }
9920 
9921 namespace {
9922 /// Data for the reduction-based clauses.
9923 struct ReductionData {
9924   /// List of original reduction items.
9925   SmallVector<Expr *, 8> Vars;
9926   /// List of private copies of the reduction items.
9927   SmallVector<Expr *, 8> Privates;
9928   /// LHS expressions for the reduction_op expressions.
9929   SmallVector<Expr *, 8> LHSs;
9930   /// RHS expressions for the reduction_op expressions.
9931   SmallVector<Expr *, 8> RHSs;
9932   /// Reduction operation expression.
9933   SmallVector<Expr *, 8> ReductionOps;
9934   /// Taskgroup descriptors for the corresponding reduction items in
9935   /// in_reduction clauses.
9936   SmallVector<Expr *, 8> TaskgroupDescriptors;
9937   /// List of captures for clause.
9938   SmallVector<Decl *, 4> ExprCaptures;
9939   /// List of postupdate expressions.
9940   SmallVector<Expr *, 4> ExprPostUpdates;
9941   ReductionData() = delete;
9942   /// Reserves required memory for the reduction data.
9943   ReductionData(unsigned Size) {
9944     Vars.reserve(Size);
9945     Privates.reserve(Size);
9946     LHSs.reserve(Size);
9947     RHSs.reserve(Size);
9948     ReductionOps.reserve(Size);
9949     TaskgroupDescriptors.reserve(Size);
9950     ExprCaptures.reserve(Size);
9951     ExprPostUpdates.reserve(Size);
9952   }
9953   /// Stores reduction item and reduction operation only (required for dependent
9954   /// reduction item).
9955   void push(Expr *Item, Expr *ReductionOp) {
9956     Vars.emplace_back(Item);
9957     Privates.emplace_back(nullptr);
9958     LHSs.emplace_back(nullptr);
9959     RHSs.emplace_back(nullptr);
9960     ReductionOps.emplace_back(ReductionOp);
9961     TaskgroupDescriptors.emplace_back(nullptr);
9962   }
9963   /// Stores reduction data.
9964   void push(Expr *Item, Expr *Private, Expr *LHS, Expr *RHS, Expr *ReductionOp,
9965             Expr *TaskgroupDescriptor) {
9966     Vars.emplace_back(Item);
9967     Privates.emplace_back(Private);
9968     LHSs.emplace_back(LHS);
9969     RHSs.emplace_back(RHS);
9970     ReductionOps.emplace_back(ReductionOp);
9971     TaskgroupDescriptors.emplace_back(TaskgroupDescriptor);
9972   }
9973 };
9974 } // namespace
9975 
9976 static bool CheckOMPArraySectionConstantForReduction(
9977     ASTContext &Context, const OMPArraySectionExpr *OASE, bool &SingleElement,
9978     SmallVectorImpl<llvm::APSInt> &ArraySizes) {
9979   const Expr *Length = OASE->getLength();
9980   if (Length == nullptr) {
9981     // For array sections of the form [1:] or [:], we would need to analyze
9982     // the lower bound...
9983     if (OASE->getColonLoc().isValid())
9984       return false;
9985 
9986     // This is an array subscript which has implicit length 1!
9987     SingleElement = true;
9988     ArraySizes.push_back(llvm::APSInt::get(1));
9989   } else {
9990     llvm::APSInt ConstantLengthValue;
9991     if (!Length->EvaluateAsInt(ConstantLengthValue, Context))
9992       return false;
9993 
9994     SingleElement = (ConstantLengthValue.getSExtValue() == 1);
9995     ArraySizes.push_back(ConstantLengthValue);
9996   }
9997 
9998   // Get the base of this array section and walk up from there.
9999   const Expr *Base = OASE->getBase()->IgnoreParenImpCasts();
10000 
10001   // We require length = 1 for all array sections except the right-most to
10002   // guarantee that the memory region is contiguous and has no holes in it.
10003   while (const auto *TempOASE = dyn_cast<OMPArraySectionExpr>(Base)) {
10004     Length = TempOASE->getLength();
10005     if (Length == nullptr) {
10006       // For array sections of the form [1:] or [:], we would need to analyze
10007       // the lower bound...
10008       if (OASE->getColonLoc().isValid())
10009         return false;
10010 
10011       // This is an array subscript which has implicit length 1!
10012       ArraySizes.push_back(llvm::APSInt::get(1));
10013     } else {
10014       llvm::APSInt ConstantLengthValue;
10015       if (!Length->EvaluateAsInt(ConstantLengthValue, Context) ||
10016           ConstantLengthValue.getSExtValue() != 1)
10017         return false;
10018 
10019       ArraySizes.push_back(ConstantLengthValue);
10020     }
10021     Base = TempOASE->getBase()->IgnoreParenImpCasts();
10022   }
10023 
10024   // If we have a single element, we don't need to add the implicit lengths.
10025   if (!SingleElement) {
10026     while (const auto *TempASE = dyn_cast<ArraySubscriptExpr>(Base)) {
10027       // Has implicit length 1!
10028       ArraySizes.push_back(llvm::APSInt::get(1));
10029       Base = TempASE->getBase()->IgnoreParenImpCasts();
10030     }
10031   }
10032 
10033   // This array section can be privatized as a single value or as a constant
10034   // sized array.
10035   return true;
10036 }
10037 
10038 static bool ActOnOMPReductionKindClause(
10039     Sema &S, DSAStackTy *Stack, OpenMPClauseKind ClauseKind,
10040     ArrayRef<Expr *> VarList, SourceLocation StartLoc, SourceLocation LParenLoc,
10041     SourceLocation ColonLoc, SourceLocation EndLoc,
10042     CXXScopeSpec &ReductionIdScopeSpec, const DeclarationNameInfo &ReductionId,
10043     ArrayRef<Expr *> UnresolvedReductions, ReductionData &RD) {
10044   auto DN = ReductionId.getName();
10045   auto OOK = DN.getCXXOverloadedOperator();
10046   BinaryOperatorKind BOK = BO_Comma;
10047 
10048   ASTContext &Context = S.Context;
10049   // OpenMP [2.14.3.6, reduction clause]
10050   // C
10051   // reduction-identifier is either an identifier or one of the following
10052   // operators: +, -, *,  &, |, ^, && and ||
10053   // C++
10054   // reduction-identifier is either an id-expression or one of the following
10055   // operators: +, -, *, &, |, ^, && and ||
10056   switch (OOK) {
10057   case OO_Plus:
10058   case OO_Minus:
10059     BOK = BO_Add;
10060     break;
10061   case OO_Star:
10062     BOK = BO_Mul;
10063     break;
10064   case OO_Amp:
10065     BOK = BO_And;
10066     break;
10067   case OO_Pipe:
10068     BOK = BO_Or;
10069     break;
10070   case OO_Caret:
10071     BOK = BO_Xor;
10072     break;
10073   case OO_AmpAmp:
10074     BOK = BO_LAnd;
10075     break;
10076   case OO_PipePipe:
10077     BOK = BO_LOr;
10078     break;
10079   case OO_New:
10080   case OO_Delete:
10081   case OO_Array_New:
10082   case OO_Array_Delete:
10083   case OO_Slash:
10084   case OO_Percent:
10085   case OO_Tilde:
10086   case OO_Exclaim:
10087   case OO_Equal:
10088   case OO_Less:
10089   case OO_Greater:
10090   case OO_LessEqual:
10091   case OO_GreaterEqual:
10092   case OO_PlusEqual:
10093   case OO_MinusEqual:
10094   case OO_StarEqual:
10095   case OO_SlashEqual:
10096   case OO_PercentEqual:
10097   case OO_CaretEqual:
10098   case OO_AmpEqual:
10099   case OO_PipeEqual:
10100   case OO_LessLess:
10101   case OO_GreaterGreater:
10102   case OO_LessLessEqual:
10103   case OO_GreaterGreaterEqual:
10104   case OO_EqualEqual:
10105   case OO_ExclaimEqual:
10106   case OO_Spaceship:
10107   case OO_PlusPlus:
10108   case OO_MinusMinus:
10109   case OO_Comma:
10110   case OO_ArrowStar:
10111   case OO_Arrow:
10112   case OO_Call:
10113   case OO_Subscript:
10114   case OO_Conditional:
10115   case OO_Coawait:
10116   case NUM_OVERLOADED_OPERATORS:
10117     llvm_unreachable("Unexpected reduction identifier");
10118   case OO_None:
10119     if (auto *II = DN.getAsIdentifierInfo()) {
10120       if (II->isStr("max"))
10121         BOK = BO_GT;
10122       else if (II->isStr("min"))
10123         BOK = BO_LT;
10124     }
10125     break;
10126   }
10127   SourceRange ReductionIdRange;
10128   if (ReductionIdScopeSpec.isValid())
10129     ReductionIdRange.setBegin(ReductionIdScopeSpec.getBeginLoc());
10130   else
10131     ReductionIdRange.setBegin(ReductionId.getBeginLoc());
10132   ReductionIdRange.setEnd(ReductionId.getEndLoc());
10133 
10134   auto IR = UnresolvedReductions.begin(), ER = UnresolvedReductions.end();
10135   bool FirstIter = true;
10136   for (auto RefExpr : VarList) {
10137     assert(RefExpr && "nullptr expr in OpenMP reduction clause.");
10138     // OpenMP [2.1, C/C++]
10139     //  A list item is a variable or array section, subject to the restrictions
10140     //  specified in Section 2.4 on page 42 and in each of the sections
10141     // describing clauses and directives for which a list appears.
10142     // OpenMP  [2.14.3.3, Restrictions, p.1]
10143     //  A variable that is part of another variable (as an array or
10144     //  structure element) cannot appear in a private clause.
10145     if (!FirstIter && IR != ER)
10146       ++IR;
10147     FirstIter = false;
10148     SourceLocation ELoc;
10149     SourceRange ERange;
10150     Expr *SimpleRefExpr = RefExpr;
10151     auto Res = getPrivateItem(S, SimpleRefExpr, ELoc, ERange,
10152                               /*AllowArraySection=*/true);
10153     if (Res.second) {
10154       // Try to find 'declare reduction' corresponding construct before using
10155       // builtin/overloaded operators.
10156       QualType Type = Context.DependentTy;
10157       CXXCastPath BasePath;
10158       ExprResult DeclareReductionRef = buildDeclareReductionRef(
10159           S, ELoc, ERange, Stack->getCurScope(), ReductionIdScopeSpec,
10160           ReductionId, Type, BasePath, IR == ER ? nullptr : *IR);
10161       Expr *ReductionOp = nullptr;
10162       if (S.CurContext->isDependentContext() &&
10163           (DeclareReductionRef.isUnset() ||
10164            isa<UnresolvedLookupExpr>(DeclareReductionRef.get())))
10165         ReductionOp = DeclareReductionRef.get();
10166       // It will be analyzed later.
10167       RD.push(RefExpr, ReductionOp);
10168     }
10169     ValueDecl *D = Res.first;
10170     if (!D)
10171       continue;
10172 
10173     Expr *TaskgroupDescriptor = nullptr;
10174     QualType Type;
10175     auto *ASE = dyn_cast<ArraySubscriptExpr>(RefExpr->IgnoreParens());
10176     auto *OASE = dyn_cast<OMPArraySectionExpr>(RefExpr->IgnoreParens());
10177     if (ASE)
10178       Type = ASE->getType().getNonReferenceType();
10179     else if (OASE) {
10180       auto BaseType = OMPArraySectionExpr::getBaseOriginalType(OASE->getBase());
10181       if (auto *ATy = BaseType->getAsArrayTypeUnsafe())
10182         Type = ATy->getElementType();
10183       else
10184         Type = BaseType->getPointeeType();
10185       Type = Type.getNonReferenceType();
10186     } else
10187       Type = Context.getBaseElementType(D->getType().getNonReferenceType());
10188     auto *VD = dyn_cast<VarDecl>(D);
10189 
10190     // OpenMP [2.9.3.3, Restrictions, C/C++, p.3]
10191     //  A variable that appears in a private clause must not have an incomplete
10192     //  type or a reference type.
10193     if (S.RequireCompleteType(ELoc, Type,
10194                               diag::err_omp_reduction_incomplete_type))
10195       continue;
10196     // OpenMP [2.14.3.6, reduction clause, Restrictions]
10197     // A list item that appears in a reduction clause must not be
10198     // const-qualified.
10199     if (Type.getNonReferenceType().isConstant(Context)) {
10200       S.Diag(ELoc, diag::err_omp_const_reduction_list_item) << ERange;
10201       if (!ASE && !OASE) {
10202         bool IsDecl = !VD || VD->isThisDeclarationADefinition(Context) ==
10203                                  VarDecl::DeclarationOnly;
10204         S.Diag(D->getLocation(),
10205                IsDecl ? diag::note_previous_decl : diag::note_defined_here)
10206             << D;
10207       }
10208       continue;
10209     }
10210     // OpenMP [2.9.3.6, Restrictions, C/C++, p.4]
10211     //  If a list-item is a reference type then it must bind to the same object
10212     //  for all threads of the team.
10213     if (!ASE && !OASE && VD) {
10214       VarDecl *VDDef = VD->getDefinition();
10215       if (VD->getType()->isReferenceType() && VDDef && VDDef->hasInit()) {
10216         DSARefChecker Check(Stack);
10217         if (Check.Visit(VDDef->getInit())) {
10218           S.Diag(ELoc, diag::err_omp_reduction_ref_type_arg)
10219               << getOpenMPClauseName(ClauseKind) << ERange;
10220           S.Diag(VDDef->getLocation(), diag::note_defined_here) << VDDef;
10221           continue;
10222         }
10223       }
10224     }
10225 
10226     // OpenMP [2.14.1.1, Data-sharing Attribute Rules for Variables Referenced
10227     // in a Construct]
10228     //  Variables with the predetermined data-sharing attributes may not be
10229     //  listed in data-sharing attributes clauses, except for the cases
10230     //  listed below. For these exceptions only, listing a predetermined
10231     //  variable in a data-sharing attribute clause is allowed and overrides
10232     //  the variable's predetermined data-sharing attributes.
10233     // OpenMP [2.14.3.6, Restrictions, p.3]
10234     //  Any number of reduction clauses can be specified on the directive,
10235     //  but a list item can appear only once in the reduction clauses for that
10236     //  directive.
10237     DSAStackTy::DSAVarData DVar;
10238     DVar = Stack->getTopDSA(D, false);
10239     if (DVar.CKind == OMPC_reduction) {
10240       S.Diag(ELoc, diag::err_omp_once_referenced)
10241           << getOpenMPClauseName(ClauseKind);
10242       if (DVar.RefExpr)
10243         S.Diag(DVar.RefExpr->getExprLoc(), diag::note_omp_referenced);
10244       continue;
10245     } else if (DVar.CKind != OMPC_unknown) {
10246       S.Diag(ELoc, diag::err_omp_wrong_dsa)
10247           << getOpenMPClauseName(DVar.CKind)
10248           << getOpenMPClauseName(OMPC_reduction);
10249       ReportOriginalDSA(S, Stack, D, DVar);
10250       continue;
10251     }
10252 
10253     // OpenMP [2.14.3.6, Restrictions, p.1]
10254     //  A list item that appears in a reduction clause of a worksharing
10255     //  construct must be shared in the parallel regions to which any of the
10256     //  worksharing regions arising from the worksharing construct bind.
10257     OpenMPDirectiveKind CurrDir = Stack->getCurrentDirective();
10258     if (isOpenMPWorksharingDirective(CurrDir) &&
10259         !isOpenMPParallelDirective(CurrDir) &&
10260         !isOpenMPTeamsDirective(CurrDir)) {
10261       DVar = Stack->getImplicitDSA(D, true);
10262       if (DVar.CKind != OMPC_shared) {
10263         S.Diag(ELoc, diag::err_omp_required_access)
10264             << getOpenMPClauseName(OMPC_reduction)
10265             << getOpenMPClauseName(OMPC_shared);
10266         ReportOriginalDSA(S, Stack, D, DVar);
10267         continue;
10268       }
10269     }
10270 
10271     // Try to find 'declare reduction' corresponding construct before using
10272     // builtin/overloaded operators.
10273     CXXCastPath BasePath;
10274     ExprResult DeclareReductionRef = buildDeclareReductionRef(
10275         S, ELoc, ERange, Stack->getCurScope(), ReductionIdScopeSpec,
10276         ReductionId, Type, BasePath, IR == ER ? nullptr : *IR);
10277     if (DeclareReductionRef.isInvalid())
10278       continue;
10279     if (S.CurContext->isDependentContext() &&
10280         (DeclareReductionRef.isUnset() ||
10281          isa<UnresolvedLookupExpr>(DeclareReductionRef.get()))) {
10282       RD.push(RefExpr, DeclareReductionRef.get());
10283       continue;
10284     }
10285     if (BOK == BO_Comma && DeclareReductionRef.isUnset()) {
10286       // Not allowed reduction identifier is found.
10287       S.Diag(ReductionId.getLocStart(),
10288              diag::err_omp_unknown_reduction_identifier)
10289           << Type << ReductionIdRange;
10290       continue;
10291     }
10292 
10293     // OpenMP [2.14.3.6, reduction clause, Restrictions]
10294     // The type of a list item that appears in a reduction clause must be valid
10295     // for the reduction-identifier. For a max or min reduction in C, the type
10296     // of the list item must be an allowed arithmetic data type: char, int,
10297     // float, double, or _Bool, possibly modified with long, short, signed, or
10298     // unsigned. For a max or min reduction in C++, the type of the list item
10299     // must be an allowed arithmetic data type: char, wchar_t, int, float,
10300     // double, or bool, possibly modified with long, short, signed, or unsigned.
10301     if (DeclareReductionRef.isUnset()) {
10302       if ((BOK == BO_GT || BOK == BO_LT) &&
10303           !(Type->isScalarType() ||
10304             (S.getLangOpts().CPlusPlus && Type->isArithmeticType()))) {
10305         S.Diag(ELoc, diag::err_omp_clause_not_arithmetic_type_arg)
10306             << getOpenMPClauseName(ClauseKind) << S.getLangOpts().CPlusPlus;
10307         if (!ASE && !OASE) {
10308           bool IsDecl = !VD || VD->isThisDeclarationADefinition(Context) ==
10309                                    VarDecl::DeclarationOnly;
10310           S.Diag(D->getLocation(),
10311                  IsDecl ? diag::note_previous_decl : diag::note_defined_here)
10312               << D;
10313         }
10314         continue;
10315       }
10316       if ((BOK == BO_OrAssign || BOK == BO_AndAssign || BOK == BO_XorAssign) &&
10317           !S.getLangOpts().CPlusPlus && Type->isFloatingType()) {
10318         S.Diag(ELoc, diag::err_omp_clause_floating_type_arg)
10319             << getOpenMPClauseName(ClauseKind);
10320         if (!ASE && !OASE) {
10321           bool IsDecl = !VD || VD->isThisDeclarationADefinition(Context) ==
10322                                    VarDecl::DeclarationOnly;
10323           S.Diag(D->getLocation(),
10324                  IsDecl ? diag::note_previous_decl : diag::note_defined_here)
10325               << D;
10326         }
10327         continue;
10328       }
10329     }
10330 
10331     Type = Type.getNonLValueExprType(Context).getUnqualifiedType();
10332     auto *LHSVD = buildVarDecl(S, ELoc, Type, ".reduction.lhs",
10333                                D->hasAttrs() ? &D->getAttrs() : nullptr);
10334     auto *RHSVD = buildVarDecl(S, ELoc, Type, D->getName(),
10335                                D->hasAttrs() ? &D->getAttrs() : nullptr);
10336     auto PrivateTy = Type;
10337 
10338     // Try if we can determine constant lengths for all array sections and avoid
10339     // the VLA.
10340     bool ConstantLengthOASE = false;
10341     if (OASE) {
10342       bool SingleElement;
10343       llvm::SmallVector<llvm::APSInt, 4> ArraySizes;
10344       ConstantLengthOASE = CheckOMPArraySectionConstantForReduction(
10345           Context, OASE, SingleElement, ArraySizes);
10346 
10347       // If we don't have a single element, we must emit a constant array type.
10348       if (ConstantLengthOASE && !SingleElement) {
10349         for (auto &Size : ArraySizes) {
10350           PrivateTy = Context.getConstantArrayType(
10351               PrivateTy, Size, ArrayType::Normal, /*IndexTypeQuals=*/0);
10352         }
10353       }
10354     }
10355 
10356     if ((OASE && !ConstantLengthOASE) ||
10357         (!OASE && !ASE &&
10358          D->getType().getNonReferenceType()->isVariablyModifiedType())) {
10359       if (!Context.getTargetInfo().isVLASupported() &&
10360           S.shouldDiagnoseTargetSupportFromOpenMP()) {
10361         S.Diag(ELoc, diag::err_omp_reduction_vla_unsupported) << !!OASE;
10362         S.Diag(ELoc, diag::note_vla_unsupported);
10363         continue;
10364       }
10365       // For arrays/array sections only:
10366       // Create pseudo array type for private copy. The size for this array will
10367       // be generated during codegen.
10368       // For array subscripts or single variables Private Ty is the same as Type
10369       // (type of the variable or single array element).
10370       PrivateTy = Context.getVariableArrayType(
10371           Type,
10372           new (Context) OpaqueValueExpr(ELoc, Context.getSizeType(), VK_RValue),
10373           ArrayType::Normal, /*IndexTypeQuals=*/0, SourceRange());
10374     } else if (!ASE && !OASE &&
10375                Context.getAsArrayType(D->getType().getNonReferenceType()))
10376       PrivateTy = D->getType().getNonReferenceType();
10377     // Private copy.
10378     auto *PrivateVD = buildVarDecl(S, ELoc, PrivateTy, D->getName(),
10379                                    D->hasAttrs() ? &D->getAttrs() : nullptr);
10380     // Add initializer for private variable.
10381     Expr *Init = nullptr;
10382     auto *LHSDRE = buildDeclRefExpr(S, LHSVD, Type, ELoc);
10383     auto *RHSDRE = buildDeclRefExpr(S, RHSVD, Type, ELoc);
10384     if (DeclareReductionRef.isUsable()) {
10385       auto *DRDRef = DeclareReductionRef.getAs<DeclRefExpr>();
10386       auto *DRD = cast<OMPDeclareReductionDecl>(DRDRef->getDecl());
10387       if (DRD->getInitializer()) {
10388         Init = DRDRef;
10389         RHSVD->setInit(DRDRef);
10390         RHSVD->setInitStyle(VarDecl::CallInit);
10391       }
10392     } else {
10393       switch (BOK) {
10394       case BO_Add:
10395       case BO_Xor:
10396       case BO_Or:
10397       case BO_LOr:
10398         // '+', '-', '^', '|', '||' reduction ops - initializer is '0'.
10399         if (Type->isScalarType() || Type->isAnyComplexType())
10400           Init = S.ActOnIntegerConstant(ELoc, /*Val=*/0).get();
10401         break;
10402       case BO_Mul:
10403       case BO_LAnd:
10404         if (Type->isScalarType() || Type->isAnyComplexType()) {
10405           // '*' and '&&' reduction ops - initializer is '1'.
10406           Init = S.ActOnIntegerConstant(ELoc, /*Val=*/1).get();
10407         }
10408         break;
10409       case BO_And: {
10410         // '&' reduction op - initializer is '~0'.
10411         QualType OrigType = Type;
10412         if (auto *ComplexTy = OrigType->getAs<ComplexType>())
10413           Type = ComplexTy->getElementType();
10414         if (Type->isRealFloatingType()) {
10415           llvm::APFloat InitValue =
10416               llvm::APFloat::getAllOnesValue(Context.getTypeSize(Type),
10417                                              /*isIEEE=*/true);
10418           Init = FloatingLiteral::Create(Context, InitValue, /*isexact=*/true,
10419                                          Type, ELoc);
10420         } else if (Type->isScalarType()) {
10421           auto Size = Context.getTypeSize(Type);
10422           QualType IntTy = Context.getIntTypeForBitwidth(Size, /*Signed=*/0);
10423           llvm::APInt InitValue = llvm::APInt::getAllOnesValue(Size);
10424           Init = IntegerLiteral::Create(Context, InitValue, IntTy, ELoc);
10425         }
10426         if (Init && OrigType->isAnyComplexType()) {
10427           // Init = 0xFFFF + 0xFFFFi;
10428           auto *Im = new (Context) ImaginaryLiteral(Init, OrigType);
10429           Init = S.CreateBuiltinBinOp(ELoc, BO_Add, Init, Im).get();
10430         }
10431         Type = OrigType;
10432         break;
10433       }
10434       case BO_LT:
10435       case BO_GT: {
10436         // 'min' reduction op - initializer is 'Largest representable number in
10437         // the reduction list item type'.
10438         // 'max' reduction op - initializer is 'Least representable number in
10439         // the reduction list item type'.
10440         if (Type->isIntegerType() || Type->isPointerType()) {
10441           bool IsSigned = Type->hasSignedIntegerRepresentation();
10442           auto Size = Context.getTypeSize(Type);
10443           QualType IntTy =
10444               Context.getIntTypeForBitwidth(Size, /*Signed=*/IsSigned);
10445           llvm::APInt InitValue =
10446               (BOK != BO_LT) ? IsSigned ? llvm::APInt::getSignedMinValue(Size)
10447                                         : llvm::APInt::getMinValue(Size)
10448                              : IsSigned ? llvm::APInt::getSignedMaxValue(Size)
10449                                         : llvm::APInt::getMaxValue(Size);
10450           Init = IntegerLiteral::Create(Context, InitValue, IntTy, ELoc);
10451           if (Type->isPointerType()) {
10452             // Cast to pointer type.
10453             auto CastExpr = S.BuildCStyleCastExpr(
10454                 ELoc, Context.getTrivialTypeSourceInfo(Type, ELoc), ELoc, Init);
10455             if (CastExpr.isInvalid())
10456               continue;
10457             Init = CastExpr.get();
10458           }
10459         } else if (Type->isRealFloatingType()) {
10460           llvm::APFloat InitValue = llvm::APFloat::getLargest(
10461               Context.getFloatTypeSemantics(Type), BOK != BO_LT);
10462           Init = FloatingLiteral::Create(Context, InitValue, /*isexact=*/true,
10463                                          Type, ELoc);
10464         }
10465         break;
10466       }
10467       case BO_PtrMemD:
10468       case BO_PtrMemI:
10469       case BO_MulAssign:
10470       case BO_Div:
10471       case BO_Rem:
10472       case BO_Sub:
10473       case BO_Shl:
10474       case BO_Shr:
10475       case BO_LE:
10476       case BO_GE:
10477       case BO_EQ:
10478       case BO_NE:
10479       case BO_Cmp:
10480       case BO_AndAssign:
10481       case BO_XorAssign:
10482       case BO_OrAssign:
10483       case BO_Assign:
10484       case BO_AddAssign:
10485       case BO_SubAssign:
10486       case BO_DivAssign:
10487       case BO_RemAssign:
10488       case BO_ShlAssign:
10489       case BO_ShrAssign:
10490       case BO_Comma:
10491         llvm_unreachable("Unexpected reduction operation");
10492       }
10493     }
10494     if (Init && DeclareReductionRef.isUnset())
10495       S.AddInitializerToDecl(RHSVD, Init, /*DirectInit=*/false);
10496     else if (!Init)
10497       S.ActOnUninitializedDecl(RHSVD);
10498     if (RHSVD->isInvalidDecl())
10499       continue;
10500     if (!RHSVD->hasInit() && DeclareReductionRef.isUnset()) {
10501       S.Diag(ELoc, diag::err_omp_reduction_id_not_compatible)
10502           << Type << ReductionIdRange;
10503       bool IsDecl = !VD || VD->isThisDeclarationADefinition(Context) ==
10504                                VarDecl::DeclarationOnly;
10505       S.Diag(D->getLocation(),
10506              IsDecl ? diag::note_previous_decl : diag::note_defined_here)
10507           << D;
10508       continue;
10509     }
10510     // Store initializer for single element in private copy. Will be used during
10511     // codegen.
10512     PrivateVD->setInit(RHSVD->getInit());
10513     PrivateVD->setInitStyle(RHSVD->getInitStyle());
10514     auto *PrivateDRE = buildDeclRefExpr(S, PrivateVD, PrivateTy, ELoc);
10515     ExprResult ReductionOp;
10516     if (DeclareReductionRef.isUsable()) {
10517       QualType RedTy = DeclareReductionRef.get()->getType();
10518       QualType PtrRedTy = Context.getPointerType(RedTy);
10519       ExprResult LHS = S.CreateBuiltinUnaryOp(ELoc, UO_AddrOf, LHSDRE);
10520       ExprResult RHS = S.CreateBuiltinUnaryOp(ELoc, UO_AddrOf, RHSDRE);
10521       if (!BasePath.empty()) {
10522         LHS = S.DefaultLvalueConversion(LHS.get());
10523         RHS = S.DefaultLvalueConversion(RHS.get());
10524         LHS = ImplicitCastExpr::Create(Context, PtrRedTy,
10525                                        CK_UncheckedDerivedToBase, LHS.get(),
10526                                        &BasePath, LHS.get()->getValueKind());
10527         RHS = ImplicitCastExpr::Create(Context, PtrRedTy,
10528                                        CK_UncheckedDerivedToBase, RHS.get(),
10529                                        &BasePath, RHS.get()->getValueKind());
10530       }
10531       FunctionProtoType::ExtProtoInfo EPI;
10532       QualType Params[] = {PtrRedTy, PtrRedTy};
10533       QualType FnTy = Context.getFunctionType(Context.VoidTy, Params, EPI);
10534       auto *OVE = new (Context) OpaqueValueExpr(
10535           ELoc, Context.getPointerType(FnTy), VK_RValue, OK_Ordinary,
10536           S.DefaultLvalueConversion(DeclareReductionRef.get()).get());
10537       Expr *Args[] = {LHS.get(), RHS.get()};
10538       ReductionOp = new (Context)
10539           CallExpr(Context, OVE, Args, Context.VoidTy, VK_RValue, ELoc);
10540     } else {
10541       ReductionOp = S.BuildBinOp(
10542           Stack->getCurScope(), ReductionId.getLocStart(), BOK, LHSDRE, RHSDRE);
10543       if (ReductionOp.isUsable()) {
10544         if (BOK != BO_LT && BOK != BO_GT) {
10545           ReductionOp =
10546               S.BuildBinOp(Stack->getCurScope(), ReductionId.getLocStart(),
10547                            BO_Assign, LHSDRE, ReductionOp.get());
10548         } else {
10549           auto *ConditionalOp = new (Context)
10550               ConditionalOperator(ReductionOp.get(), ELoc, LHSDRE, ELoc, RHSDRE,
10551                                   Type, VK_LValue, OK_Ordinary);
10552           ReductionOp =
10553               S.BuildBinOp(Stack->getCurScope(), ReductionId.getLocStart(),
10554                            BO_Assign, LHSDRE, ConditionalOp);
10555         }
10556         if (ReductionOp.isUsable())
10557           ReductionOp = S.ActOnFinishFullExpr(ReductionOp.get());
10558       }
10559       if (!ReductionOp.isUsable())
10560         continue;
10561     }
10562 
10563     // OpenMP [2.15.4.6, Restrictions, p.2]
10564     // A list item that appears in an in_reduction clause of a task construct
10565     // must appear in a task_reduction clause of a construct associated with a
10566     // taskgroup region that includes the participating task in its taskgroup
10567     // set. The construct associated with the innermost region that meets this
10568     // condition must specify the same reduction-identifier as the in_reduction
10569     // clause.
10570     if (ClauseKind == OMPC_in_reduction) {
10571       SourceRange ParentSR;
10572       BinaryOperatorKind ParentBOK;
10573       const Expr *ParentReductionOp;
10574       Expr *ParentBOKTD, *ParentReductionOpTD;
10575       DSAStackTy::DSAVarData ParentBOKDSA =
10576           Stack->getTopMostTaskgroupReductionData(D, ParentSR, ParentBOK,
10577                                                   ParentBOKTD);
10578       DSAStackTy::DSAVarData ParentReductionOpDSA =
10579           Stack->getTopMostTaskgroupReductionData(
10580               D, ParentSR, ParentReductionOp, ParentReductionOpTD);
10581       bool IsParentBOK = ParentBOKDSA.DKind != OMPD_unknown;
10582       bool IsParentReductionOp = ParentReductionOpDSA.DKind != OMPD_unknown;
10583       if (!IsParentBOK && !IsParentReductionOp) {
10584         S.Diag(ELoc, diag::err_omp_in_reduction_not_task_reduction);
10585         continue;
10586       }
10587       if ((DeclareReductionRef.isUnset() && IsParentReductionOp) ||
10588           (DeclareReductionRef.isUsable() && IsParentBOK) || BOK != ParentBOK ||
10589           IsParentReductionOp) {
10590         bool EmitError = true;
10591         if (IsParentReductionOp && DeclareReductionRef.isUsable()) {
10592           llvm::FoldingSetNodeID RedId, ParentRedId;
10593           ParentReductionOp->Profile(ParentRedId, Context, /*Canonical=*/true);
10594           DeclareReductionRef.get()->Profile(RedId, Context,
10595                                              /*Canonical=*/true);
10596           EmitError = RedId != ParentRedId;
10597         }
10598         if (EmitError) {
10599           S.Diag(ReductionId.getLocStart(),
10600                  diag::err_omp_reduction_identifier_mismatch)
10601               << ReductionIdRange << RefExpr->getSourceRange();
10602           S.Diag(ParentSR.getBegin(),
10603                  diag::note_omp_previous_reduction_identifier)
10604               << ParentSR
10605               << (IsParentBOK ? ParentBOKDSA.RefExpr
10606                               : ParentReductionOpDSA.RefExpr)
10607                      ->getSourceRange();
10608           continue;
10609         }
10610       }
10611       TaskgroupDescriptor = IsParentBOK ? ParentBOKTD : ParentReductionOpTD;
10612       assert(TaskgroupDescriptor && "Taskgroup descriptor must be defined.");
10613     }
10614 
10615     DeclRefExpr *Ref = nullptr;
10616     Expr *VarsExpr = RefExpr->IgnoreParens();
10617     if (!VD && !S.CurContext->isDependentContext()) {
10618       if (ASE || OASE) {
10619         TransformExprToCaptures RebuildToCapture(S, D);
10620         VarsExpr =
10621             RebuildToCapture.TransformExpr(RefExpr->IgnoreParens()).get();
10622         Ref = RebuildToCapture.getCapturedExpr();
10623       } else {
10624         VarsExpr = Ref = buildCapture(S, D, SimpleRefExpr, /*WithInit=*/false);
10625       }
10626       if (!S.IsOpenMPCapturedDecl(D)) {
10627         RD.ExprCaptures.emplace_back(Ref->getDecl());
10628         if (Ref->getDecl()->hasAttr<OMPCaptureNoInitAttr>()) {
10629           ExprResult RefRes = S.DefaultLvalueConversion(Ref);
10630           if (!RefRes.isUsable())
10631             continue;
10632           ExprResult PostUpdateRes =
10633               S.BuildBinOp(Stack->getCurScope(), ELoc, BO_Assign, SimpleRefExpr,
10634                            RefRes.get());
10635           if (!PostUpdateRes.isUsable())
10636             continue;
10637           if (isOpenMPTaskingDirective(Stack->getCurrentDirective()) ||
10638               Stack->getCurrentDirective() == OMPD_taskgroup) {
10639             S.Diag(RefExpr->getExprLoc(),
10640                    diag::err_omp_reduction_non_addressable_expression)
10641                 << RefExpr->getSourceRange();
10642             continue;
10643           }
10644           RD.ExprPostUpdates.emplace_back(
10645               S.IgnoredValueConversions(PostUpdateRes.get()).get());
10646         }
10647       }
10648     }
10649     // All reduction items are still marked as reduction (to do not increase
10650     // code base size).
10651     Stack->addDSA(D, RefExpr->IgnoreParens(), OMPC_reduction, Ref);
10652     if (CurrDir == OMPD_taskgroup) {
10653       if (DeclareReductionRef.isUsable())
10654         Stack->addTaskgroupReductionData(D, ReductionIdRange,
10655                                          DeclareReductionRef.get());
10656       else
10657         Stack->addTaskgroupReductionData(D, ReductionIdRange, BOK);
10658     }
10659     RD.push(VarsExpr, PrivateDRE, LHSDRE, RHSDRE, ReductionOp.get(),
10660             TaskgroupDescriptor);
10661   }
10662   return RD.Vars.empty();
10663 }
10664 
10665 OMPClause *Sema::ActOnOpenMPReductionClause(
10666     ArrayRef<Expr *> VarList, SourceLocation StartLoc, SourceLocation LParenLoc,
10667     SourceLocation ColonLoc, SourceLocation EndLoc,
10668     CXXScopeSpec &ReductionIdScopeSpec, const DeclarationNameInfo &ReductionId,
10669     ArrayRef<Expr *> UnresolvedReductions) {
10670   ReductionData RD(VarList.size());
10671 
10672   if (ActOnOMPReductionKindClause(*this, DSAStack, OMPC_reduction, VarList,
10673                                   StartLoc, LParenLoc, ColonLoc, EndLoc,
10674                                   ReductionIdScopeSpec, ReductionId,
10675                                   UnresolvedReductions, RD))
10676     return nullptr;
10677 
10678   return OMPReductionClause::Create(
10679       Context, StartLoc, LParenLoc, ColonLoc, EndLoc, RD.Vars,
10680       ReductionIdScopeSpec.getWithLocInContext(Context), ReductionId,
10681       RD.Privates, RD.LHSs, RD.RHSs, RD.ReductionOps,
10682       buildPreInits(Context, RD.ExprCaptures),
10683       buildPostUpdate(*this, RD.ExprPostUpdates));
10684 }
10685 
10686 OMPClause *Sema::ActOnOpenMPTaskReductionClause(
10687     ArrayRef<Expr *> VarList, SourceLocation StartLoc, SourceLocation LParenLoc,
10688     SourceLocation ColonLoc, SourceLocation EndLoc,
10689     CXXScopeSpec &ReductionIdScopeSpec, const DeclarationNameInfo &ReductionId,
10690     ArrayRef<Expr *> UnresolvedReductions) {
10691   ReductionData RD(VarList.size());
10692 
10693   if (ActOnOMPReductionKindClause(*this, DSAStack, OMPC_task_reduction,
10694                                   VarList, StartLoc, LParenLoc, ColonLoc,
10695                                   EndLoc, ReductionIdScopeSpec, ReductionId,
10696                                   UnresolvedReductions, RD))
10697     return nullptr;
10698 
10699   return OMPTaskReductionClause::Create(
10700       Context, StartLoc, LParenLoc, ColonLoc, EndLoc, RD.Vars,
10701       ReductionIdScopeSpec.getWithLocInContext(Context), ReductionId,
10702       RD.Privates, RD.LHSs, RD.RHSs, RD.ReductionOps,
10703       buildPreInits(Context, RD.ExprCaptures),
10704       buildPostUpdate(*this, RD.ExprPostUpdates));
10705 }
10706 
10707 OMPClause *Sema::ActOnOpenMPInReductionClause(
10708     ArrayRef<Expr *> VarList, SourceLocation StartLoc, SourceLocation LParenLoc,
10709     SourceLocation ColonLoc, SourceLocation EndLoc,
10710     CXXScopeSpec &ReductionIdScopeSpec, const DeclarationNameInfo &ReductionId,
10711     ArrayRef<Expr *> UnresolvedReductions) {
10712   ReductionData RD(VarList.size());
10713 
10714   if (ActOnOMPReductionKindClause(*this, DSAStack, OMPC_in_reduction, VarList,
10715                                   StartLoc, LParenLoc, ColonLoc, EndLoc,
10716                                   ReductionIdScopeSpec, ReductionId,
10717                                   UnresolvedReductions, RD))
10718     return nullptr;
10719 
10720   return OMPInReductionClause::Create(
10721       Context, StartLoc, LParenLoc, ColonLoc, EndLoc, RD.Vars,
10722       ReductionIdScopeSpec.getWithLocInContext(Context), ReductionId,
10723       RD.Privates, RD.LHSs, RD.RHSs, RD.ReductionOps, RD.TaskgroupDescriptors,
10724       buildPreInits(Context, RD.ExprCaptures),
10725       buildPostUpdate(*this, RD.ExprPostUpdates));
10726 }
10727 
10728 bool Sema::CheckOpenMPLinearModifier(OpenMPLinearClauseKind LinKind,
10729                                      SourceLocation LinLoc) {
10730   if ((!LangOpts.CPlusPlus && LinKind != OMPC_LINEAR_val) ||
10731       LinKind == OMPC_LINEAR_unknown) {
10732     Diag(LinLoc, diag::err_omp_wrong_linear_modifier) << LangOpts.CPlusPlus;
10733     return true;
10734   }
10735   return false;
10736 }
10737 
10738 bool Sema::CheckOpenMPLinearDecl(ValueDecl *D, SourceLocation ELoc,
10739                                  OpenMPLinearClauseKind LinKind,
10740                                  QualType Type) {
10741   auto *VD = dyn_cast_or_null<VarDecl>(D);
10742   // A variable must not have an incomplete type or a reference type.
10743   if (RequireCompleteType(ELoc, Type, diag::err_omp_linear_incomplete_type))
10744     return true;
10745   if ((LinKind == OMPC_LINEAR_uval || LinKind == OMPC_LINEAR_ref) &&
10746       !Type->isReferenceType()) {
10747     Diag(ELoc, diag::err_omp_wrong_linear_modifier_non_reference)
10748         << Type << getOpenMPSimpleClauseTypeName(OMPC_linear, LinKind);
10749     return true;
10750   }
10751   Type = Type.getNonReferenceType();
10752 
10753   // A list item must not be const-qualified.
10754   if (Type.isConstant(Context)) {
10755     Diag(ELoc, diag::err_omp_const_variable)
10756         << getOpenMPClauseName(OMPC_linear);
10757     if (D) {
10758       bool IsDecl =
10759           !VD ||
10760           VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
10761       Diag(D->getLocation(),
10762            IsDecl ? diag::note_previous_decl : diag::note_defined_here)
10763           << D;
10764     }
10765     return true;
10766   }
10767 
10768   // A list item must be of integral or pointer type.
10769   Type = Type.getUnqualifiedType().getCanonicalType();
10770   const auto *Ty = Type.getTypePtrOrNull();
10771   if (!Ty || (!Ty->isDependentType() && !Ty->isIntegralType(Context) &&
10772               !Ty->isPointerType())) {
10773     Diag(ELoc, diag::err_omp_linear_expected_int_or_ptr) << Type;
10774     if (D) {
10775       bool IsDecl =
10776           !VD ||
10777           VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
10778       Diag(D->getLocation(),
10779            IsDecl ? diag::note_previous_decl : diag::note_defined_here)
10780           << D;
10781     }
10782     return true;
10783   }
10784   return false;
10785 }
10786 
10787 OMPClause *Sema::ActOnOpenMPLinearClause(
10788     ArrayRef<Expr *> VarList, Expr *Step, SourceLocation StartLoc,
10789     SourceLocation LParenLoc, OpenMPLinearClauseKind LinKind,
10790     SourceLocation LinLoc, SourceLocation ColonLoc, SourceLocation EndLoc) {
10791   SmallVector<Expr *, 8> Vars;
10792   SmallVector<Expr *, 8> Privates;
10793   SmallVector<Expr *, 8> Inits;
10794   SmallVector<Decl *, 4> ExprCaptures;
10795   SmallVector<Expr *, 4> ExprPostUpdates;
10796   if (CheckOpenMPLinearModifier(LinKind, LinLoc))
10797     LinKind = OMPC_LINEAR_val;
10798   for (auto &RefExpr : VarList) {
10799     assert(RefExpr && "NULL expr in OpenMP linear clause.");
10800     SourceLocation ELoc;
10801     SourceRange ERange;
10802     Expr *SimpleRefExpr = RefExpr;
10803     auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange,
10804                               /*AllowArraySection=*/false);
10805     if (Res.second) {
10806       // It will be analyzed later.
10807       Vars.push_back(RefExpr);
10808       Privates.push_back(nullptr);
10809       Inits.push_back(nullptr);
10810     }
10811     ValueDecl *D = Res.first;
10812     if (!D)
10813       continue;
10814 
10815     QualType Type = D->getType();
10816     auto *VD = dyn_cast<VarDecl>(D);
10817 
10818     // OpenMP [2.14.3.7, linear clause]
10819     //  A list-item cannot appear in more than one linear clause.
10820     //  A list-item that appears in a linear clause cannot appear in any
10821     //  other data-sharing attribute clause.
10822     DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, false);
10823     if (DVar.RefExpr) {
10824       Diag(ELoc, diag::err_omp_wrong_dsa) << getOpenMPClauseName(DVar.CKind)
10825                                           << getOpenMPClauseName(OMPC_linear);
10826       ReportOriginalDSA(*this, DSAStack, D, DVar);
10827       continue;
10828     }
10829 
10830     if (CheckOpenMPLinearDecl(D, ELoc, LinKind, Type))
10831       continue;
10832     Type = Type.getNonReferenceType().getUnqualifiedType().getCanonicalType();
10833 
10834     // Build private copy of original var.
10835     auto *Private = buildVarDecl(*this, ELoc, Type, D->getName(),
10836                                  D->hasAttrs() ? &D->getAttrs() : nullptr);
10837     auto *PrivateRef = buildDeclRefExpr(*this, Private, Type, ELoc);
10838     // Build var to save initial value.
10839     VarDecl *Init = buildVarDecl(*this, ELoc, Type, ".linear.start");
10840     Expr *InitExpr;
10841     DeclRefExpr *Ref = nullptr;
10842     if (!VD && !CurContext->isDependentContext()) {
10843       Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/false);
10844       if (!IsOpenMPCapturedDecl(D)) {
10845         ExprCaptures.push_back(Ref->getDecl());
10846         if (Ref->getDecl()->hasAttr<OMPCaptureNoInitAttr>()) {
10847           ExprResult RefRes = DefaultLvalueConversion(Ref);
10848           if (!RefRes.isUsable())
10849             continue;
10850           ExprResult PostUpdateRes =
10851               BuildBinOp(DSAStack->getCurScope(), ELoc, BO_Assign,
10852                          SimpleRefExpr, RefRes.get());
10853           if (!PostUpdateRes.isUsable())
10854             continue;
10855           ExprPostUpdates.push_back(
10856               IgnoredValueConversions(PostUpdateRes.get()).get());
10857         }
10858       }
10859     }
10860     if (LinKind == OMPC_LINEAR_uval)
10861       InitExpr = VD ? VD->getInit() : SimpleRefExpr;
10862     else
10863       InitExpr = VD ? SimpleRefExpr : Ref;
10864     AddInitializerToDecl(Init, DefaultLvalueConversion(InitExpr).get(),
10865                          /*DirectInit=*/false);
10866     auto InitRef = buildDeclRefExpr(*this, Init, Type, ELoc);
10867 
10868     DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_linear, Ref);
10869     Vars.push_back((VD || CurContext->isDependentContext())
10870                        ? RefExpr->IgnoreParens()
10871                        : Ref);
10872     Privates.push_back(PrivateRef);
10873     Inits.push_back(InitRef);
10874   }
10875 
10876   if (Vars.empty())
10877     return nullptr;
10878 
10879   Expr *StepExpr = Step;
10880   Expr *CalcStepExpr = nullptr;
10881   if (Step && !Step->isValueDependent() && !Step->isTypeDependent() &&
10882       !Step->isInstantiationDependent() &&
10883       !Step->containsUnexpandedParameterPack()) {
10884     SourceLocation StepLoc = Step->getLocStart();
10885     ExprResult Val = PerformOpenMPImplicitIntegerConversion(StepLoc, Step);
10886     if (Val.isInvalid())
10887       return nullptr;
10888     StepExpr = Val.get();
10889 
10890     // Build var to save the step value.
10891     VarDecl *SaveVar =
10892         buildVarDecl(*this, StepLoc, StepExpr->getType(), ".linear.step");
10893     ExprResult SaveRef =
10894         buildDeclRefExpr(*this, SaveVar, StepExpr->getType(), StepLoc);
10895     ExprResult CalcStep =
10896         BuildBinOp(CurScope, StepLoc, BO_Assign, SaveRef.get(), StepExpr);
10897     CalcStep = ActOnFinishFullExpr(CalcStep.get());
10898 
10899     // Warn about zero linear step (it would be probably better specified as
10900     // making corresponding variables 'const').
10901     llvm::APSInt Result;
10902     bool IsConstant = StepExpr->isIntegerConstantExpr(Result, Context);
10903     if (IsConstant && !Result.isNegative() && !Result.isStrictlyPositive())
10904       Diag(StepLoc, diag::warn_omp_linear_step_zero) << Vars[0]
10905                                                      << (Vars.size() > 1);
10906     if (!IsConstant && CalcStep.isUsable()) {
10907       // Calculate the step beforehand instead of doing this on each iteration.
10908       // (This is not used if the number of iterations may be kfold-ed).
10909       CalcStepExpr = CalcStep.get();
10910     }
10911   }
10912 
10913   return OMPLinearClause::Create(Context, StartLoc, LParenLoc, LinKind, LinLoc,
10914                                  ColonLoc, EndLoc, Vars, Privates, Inits,
10915                                  StepExpr, CalcStepExpr,
10916                                  buildPreInits(Context, ExprCaptures),
10917                                  buildPostUpdate(*this, ExprPostUpdates));
10918 }
10919 
10920 static bool FinishOpenMPLinearClause(OMPLinearClause &Clause, DeclRefExpr *IV,
10921                                      Expr *NumIterations, Sema &SemaRef,
10922                                      Scope *S, DSAStackTy *Stack) {
10923   // Walk the vars and build update/final expressions for the CodeGen.
10924   SmallVector<Expr *, 8> Updates;
10925   SmallVector<Expr *, 8> Finals;
10926   Expr *Step = Clause.getStep();
10927   Expr *CalcStep = Clause.getCalcStep();
10928   // OpenMP [2.14.3.7, linear clause]
10929   // If linear-step is not specified it is assumed to be 1.
10930   if (Step == nullptr)
10931     Step = SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get();
10932   else if (CalcStep) {
10933     Step = cast<BinaryOperator>(CalcStep)->getLHS();
10934   }
10935   bool HasErrors = false;
10936   auto CurInit = Clause.inits().begin();
10937   auto CurPrivate = Clause.privates().begin();
10938   auto LinKind = Clause.getModifier();
10939   for (auto &RefExpr : Clause.varlists()) {
10940     SourceLocation ELoc;
10941     SourceRange ERange;
10942     Expr *SimpleRefExpr = RefExpr;
10943     auto Res = getPrivateItem(SemaRef, SimpleRefExpr, ELoc, ERange,
10944                               /*AllowArraySection=*/false);
10945     ValueDecl *D = Res.first;
10946     if (Res.second || !D) {
10947       Updates.push_back(nullptr);
10948       Finals.push_back(nullptr);
10949       HasErrors = true;
10950       continue;
10951     }
10952     auto &&Info = Stack->isLoopControlVariable(D);
10953     // OpenMP [2.15.11, distribute simd Construct]
10954     // A list item may not appear in a linear clause, unless it is the loop
10955     // iteration variable.
10956     if (isOpenMPDistributeDirective(Stack->getCurrentDirective()) &&
10957         isOpenMPSimdDirective(Stack->getCurrentDirective()) && !Info.first) {
10958       SemaRef.Diag(ELoc,
10959                    diag::err_omp_linear_distribute_var_non_loop_iteration);
10960       Updates.push_back(nullptr);
10961       Finals.push_back(nullptr);
10962       HasErrors = true;
10963       continue;
10964     }
10965     Expr *InitExpr = *CurInit;
10966 
10967     // Build privatized reference to the current linear var.
10968     auto *DE = cast<DeclRefExpr>(SimpleRefExpr);
10969     Expr *CapturedRef;
10970     if (LinKind == OMPC_LINEAR_uval)
10971       CapturedRef = cast<VarDecl>(DE->getDecl())->getInit();
10972     else
10973       CapturedRef =
10974           buildDeclRefExpr(SemaRef, cast<VarDecl>(DE->getDecl()),
10975                            DE->getType().getUnqualifiedType(), DE->getExprLoc(),
10976                            /*RefersToCapture=*/true);
10977 
10978     // Build update: Var = InitExpr + IV * Step
10979     ExprResult Update;
10980     if (!Info.first) {
10981       Update =
10982           BuildCounterUpdate(SemaRef, S, RefExpr->getExprLoc(), *CurPrivate,
10983                              InitExpr, IV, Step, /* Subtract */ false);
10984     } else
10985       Update = *CurPrivate;
10986     Update = SemaRef.ActOnFinishFullExpr(Update.get(), DE->getLocStart(),
10987                                          /*DiscardedValue=*/true);
10988 
10989     // Build final: Var = InitExpr + NumIterations * Step
10990     ExprResult Final;
10991     if (!Info.first) {
10992       Final = BuildCounterUpdate(SemaRef, S, RefExpr->getExprLoc(), CapturedRef,
10993                                  InitExpr, NumIterations, Step,
10994                                  /* Subtract */ false);
10995     } else
10996       Final = *CurPrivate;
10997     Final = SemaRef.ActOnFinishFullExpr(Final.get(), DE->getLocStart(),
10998                                         /*DiscardedValue=*/true);
10999 
11000     if (!Update.isUsable() || !Final.isUsable()) {
11001       Updates.push_back(nullptr);
11002       Finals.push_back(nullptr);
11003       HasErrors = true;
11004     } else {
11005       Updates.push_back(Update.get());
11006       Finals.push_back(Final.get());
11007     }
11008     ++CurInit;
11009     ++CurPrivate;
11010   }
11011   Clause.setUpdates(Updates);
11012   Clause.setFinals(Finals);
11013   return HasErrors;
11014 }
11015 
11016 OMPClause *Sema::ActOnOpenMPAlignedClause(
11017     ArrayRef<Expr *> VarList, Expr *Alignment, SourceLocation StartLoc,
11018     SourceLocation LParenLoc, SourceLocation ColonLoc, SourceLocation EndLoc) {
11019 
11020   SmallVector<Expr *, 8> Vars;
11021   for (auto &RefExpr : VarList) {
11022     assert(RefExpr && "NULL expr in OpenMP linear clause.");
11023     SourceLocation ELoc;
11024     SourceRange ERange;
11025     Expr *SimpleRefExpr = RefExpr;
11026     auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange,
11027                               /*AllowArraySection=*/false);
11028     if (Res.second) {
11029       // It will be analyzed later.
11030       Vars.push_back(RefExpr);
11031     }
11032     ValueDecl *D = Res.first;
11033     if (!D)
11034       continue;
11035 
11036     QualType QType = D->getType();
11037     auto *VD = dyn_cast<VarDecl>(D);
11038 
11039     // OpenMP  [2.8.1, simd construct, Restrictions]
11040     // The type of list items appearing in the aligned clause must be
11041     // array, pointer, reference to array, or reference to pointer.
11042     QType = QType.getNonReferenceType().getUnqualifiedType().getCanonicalType();
11043     const Type *Ty = QType.getTypePtrOrNull();
11044     if (!Ty || (!Ty->isArrayType() && !Ty->isPointerType())) {
11045       Diag(ELoc, diag::err_omp_aligned_expected_array_or_ptr)
11046           << QType << getLangOpts().CPlusPlus << ERange;
11047       bool IsDecl =
11048           !VD ||
11049           VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
11050       Diag(D->getLocation(),
11051            IsDecl ? diag::note_previous_decl : diag::note_defined_here)
11052           << D;
11053       continue;
11054     }
11055 
11056     // OpenMP  [2.8.1, simd construct, Restrictions]
11057     // A list-item cannot appear in more than one aligned clause.
11058     if (Expr *PrevRef = DSAStack->addUniqueAligned(D, SimpleRefExpr)) {
11059       Diag(ELoc, diag::err_omp_aligned_twice) << 0 << ERange;
11060       Diag(PrevRef->getExprLoc(), diag::note_omp_explicit_dsa)
11061           << getOpenMPClauseName(OMPC_aligned);
11062       continue;
11063     }
11064 
11065     DeclRefExpr *Ref = nullptr;
11066     if (!VD && IsOpenMPCapturedDecl(D))
11067       Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/true);
11068     Vars.push_back(DefaultFunctionArrayConversion(
11069                        (VD || !Ref) ? RefExpr->IgnoreParens() : Ref)
11070                        .get());
11071   }
11072 
11073   // OpenMP [2.8.1, simd construct, Description]
11074   // The parameter of the aligned clause, alignment, must be a constant
11075   // positive integer expression.
11076   // If no optional parameter is specified, implementation-defined default
11077   // alignments for SIMD instructions on the target platforms are assumed.
11078   if (Alignment != nullptr) {
11079     ExprResult AlignResult =
11080         VerifyPositiveIntegerConstantInClause(Alignment, OMPC_aligned);
11081     if (AlignResult.isInvalid())
11082       return nullptr;
11083     Alignment = AlignResult.get();
11084   }
11085   if (Vars.empty())
11086     return nullptr;
11087 
11088   return OMPAlignedClause::Create(Context, StartLoc, LParenLoc, ColonLoc,
11089                                   EndLoc, Vars, Alignment);
11090 }
11091 
11092 OMPClause *Sema::ActOnOpenMPCopyinClause(ArrayRef<Expr *> VarList,
11093                                          SourceLocation StartLoc,
11094                                          SourceLocation LParenLoc,
11095                                          SourceLocation EndLoc) {
11096   SmallVector<Expr *, 8> Vars;
11097   SmallVector<Expr *, 8> SrcExprs;
11098   SmallVector<Expr *, 8> DstExprs;
11099   SmallVector<Expr *, 8> AssignmentOps;
11100   for (auto &RefExpr : VarList) {
11101     assert(RefExpr && "NULL expr in OpenMP copyin clause.");
11102     if (isa<DependentScopeDeclRefExpr>(RefExpr)) {
11103       // It will be analyzed later.
11104       Vars.push_back(RefExpr);
11105       SrcExprs.push_back(nullptr);
11106       DstExprs.push_back(nullptr);
11107       AssignmentOps.push_back(nullptr);
11108       continue;
11109     }
11110 
11111     SourceLocation ELoc = RefExpr->getExprLoc();
11112     // OpenMP [2.1, C/C++]
11113     //  A list item is a variable name.
11114     // OpenMP  [2.14.4.1, Restrictions, p.1]
11115     //  A list item that appears in a copyin clause must be threadprivate.
11116     DeclRefExpr *DE = dyn_cast<DeclRefExpr>(RefExpr);
11117     if (!DE || !isa<VarDecl>(DE->getDecl())) {
11118       Diag(ELoc, diag::err_omp_expected_var_name_member_expr)
11119           << 0 << RefExpr->getSourceRange();
11120       continue;
11121     }
11122 
11123     Decl *D = DE->getDecl();
11124     VarDecl *VD = cast<VarDecl>(D);
11125 
11126     QualType Type = VD->getType();
11127     if (Type->isDependentType() || Type->isInstantiationDependentType()) {
11128       // It will be analyzed later.
11129       Vars.push_back(DE);
11130       SrcExprs.push_back(nullptr);
11131       DstExprs.push_back(nullptr);
11132       AssignmentOps.push_back(nullptr);
11133       continue;
11134     }
11135 
11136     // OpenMP [2.14.4.1, Restrictions, C/C++, p.1]
11137     //  A list item that appears in a copyin clause must be threadprivate.
11138     if (!DSAStack->isThreadPrivate(VD)) {
11139       Diag(ELoc, diag::err_omp_required_access)
11140           << getOpenMPClauseName(OMPC_copyin)
11141           << getOpenMPDirectiveName(OMPD_threadprivate);
11142       continue;
11143     }
11144 
11145     // OpenMP [2.14.4.1, Restrictions, C/C++, p.2]
11146     //  A variable of class type (or array thereof) that appears in a
11147     //  copyin clause requires an accessible, unambiguous copy assignment
11148     //  operator for the class type.
11149     auto ElemType = Context.getBaseElementType(Type).getNonReferenceType();
11150     auto *SrcVD =
11151         buildVarDecl(*this, DE->getLocStart(), ElemType.getUnqualifiedType(),
11152                      ".copyin.src", VD->hasAttrs() ? &VD->getAttrs() : nullptr);
11153     auto *PseudoSrcExpr = buildDeclRefExpr(
11154         *this, SrcVD, ElemType.getUnqualifiedType(), DE->getExprLoc());
11155     auto *DstVD =
11156         buildVarDecl(*this, DE->getLocStart(), ElemType, ".copyin.dst",
11157                      VD->hasAttrs() ? &VD->getAttrs() : nullptr);
11158     auto *PseudoDstExpr =
11159         buildDeclRefExpr(*this, DstVD, ElemType, DE->getExprLoc());
11160     // For arrays generate assignment operation for single element and replace
11161     // it by the original array element in CodeGen.
11162     auto AssignmentOp = BuildBinOp(/*S=*/nullptr, DE->getExprLoc(), BO_Assign,
11163                                    PseudoDstExpr, PseudoSrcExpr);
11164     if (AssignmentOp.isInvalid())
11165       continue;
11166     AssignmentOp = ActOnFinishFullExpr(AssignmentOp.get(), DE->getExprLoc(),
11167                                        /*DiscardedValue=*/true);
11168     if (AssignmentOp.isInvalid())
11169       continue;
11170 
11171     DSAStack->addDSA(VD, DE, OMPC_copyin);
11172     Vars.push_back(DE);
11173     SrcExprs.push_back(PseudoSrcExpr);
11174     DstExprs.push_back(PseudoDstExpr);
11175     AssignmentOps.push_back(AssignmentOp.get());
11176   }
11177 
11178   if (Vars.empty())
11179     return nullptr;
11180 
11181   return OMPCopyinClause::Create(Context, StartLoc, LParenLoc, EndLoc, Vars,
11182                                  SrcExprs, DstExprs, AssignmentOps);
11183 }
11184 
11185 OMPClause *Sema::ActOnOpenMPCopyprivateClause(ArrayRef<Expr *> VarList,
11186                                               SourceLocation StartLoc,
11187                                               SourceLocation LParenLoc,
11188                                               SourceLocation EndLoc) {
11189   SmallVector<Expr *, 8> Vars;
11190   SmallVector<Expr *, 8> SrcExprs;
11191   SmallVector<Expr *, 8> DstExprs;
11192   SmallVector<Expr *, 8> AssignmentOps;
11193   for (auto &RefExpr : VarList) {
11194     assert(RefExpr && "NULL expr in OpenMP linear clause.");
11195     SourceLocation ELoc;
11196     SourceRange ERange;
11197     Expr *SimpleRefExpr = RefExpr;
11198     auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange,
11199                               /*AllowArraySection=*/false);
11200     if (Res.second) {
11201       // It will be analyzed later.
11202       Vars.push_back(RefExpr);
11203       SrcExprs.push_back(nullptr);
11204       DstExprs.push_back(nullptr);
11205       AssignmentOps.push_back(nullptr);
11206     }
11207     ValueDecl *D = Res.first;
11208     if (!D)
11209       continue;
11210 
11211     QualType Type = D->getType();
11212     auto *VD = dyn_cast<VarDecl>(D);
11213 
11214     // OpenMP [2.14.4.2, Restrictions, p.2]
11215     //  A list item that appears in a copyprivate clause may not appear in a
11216     //  private or firstprivate clause on the single construct.
11217     if (!VD || !DSAStack->isThreadPrivate(VD)) {
11218       auto DVar = DSAStack->getTopDSA(D, false);
11219       if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_copyprivate &&
11220           DVar.RefExpr) {
11221         Diag(ELoc, diag::err_omp_wrong_dsa)
11222             << getOpenMPClauseName(DVar.CKind)
11223             << getOpenMPClauseName(OMPC_copyprivate);
11224         ReportOriginalDSA(*this, DSAStack, D, DVar);
11225         continue;
11226       }
11227 
11228       // OpenMP [2.11.4.2, Restrictions, p.1]
11229       //  All list items that appear in a copyprivate clause must be either
11230       //  threadprivate or private in the enclosing context.
11231       if (DVar.CKind == OMPC_unknown) {
11232         DVar = DSAStack->getImplicitDSA(D, false);
11233         if (DVar.CKind == OMPC_shared) {
11234           Diag(ELoc, diag::err_omp_required_access)
11235               << getOpenMPClauseName(OMPC_copyprivate)
11236               << "threadprivate or private in the enclosing context";
11237           ReportOriginalDSA(*this, DSAStack, D, DVar);
11238           continue;
11239         }
11240       }
11241     }
11242 
11243     // Variably modified types are not supported.
11244     if (!Type->isAnyPointerType() && Type->isVariablyModifiedType()) {
11245       Diag(ELoc, diag::err_omp_variably_modified_type_not_supported)
11246           << getOpenMPClauseName(OMPC_copyprivate) << Type
11247           << getOpenMPDirectiveName(DSAStack->getCurrentDirective());
11248       bool IsDecl =
11249           !VD ||
11250           VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
11251       Diag(D->getLocation(),
11252            IsDecl ? diag::note_previous_decl : diag::note_defined_here)
11253           << D;
11254       continue;
11255     }
11256 
11257     // OpenMP [2.14.4.1, Restrictions, C/C++, p.2]
11258     //  A variable of class type (or array thereof) that appears in a
11259     //  copyin clause requires an accessible, unambiguous copy assignment
11260     //  operator for the class type.
11261     Type = Context.getBaseElementType(Type.getNonReferenceType())
11262                .getUnqualifiedType();
11263     auto *SrcVD =
11264         buildVarDecl(*this, RefExpr->getLocStart(), Type, ".copyprivate.src",
11265                      D->hasAttrs() ? &D->getAttrs() : nullptr);
11266     auto *PseudoSrcExpr = buildDeclRefExpr(*this, SrcVD, Type, ELoc);
11267     auto *DstVD =
11268         buildVarDecl(*this, RefExpr->getLocStart(), Type, ".copyprivate.dst",
11269                      D->hasAttrs() ? &D->getAttrs() : nullptr);
11270     auto *PseudoDstExpr = buildDeclRefExpr(*this, DstVD, Type, ELoc);
11271     auto AssignmentOp = BuildBinOp(DSAStack->getCurScope(), ELoc, BO_Assign,
11272                                    PseudoDstExpr, PseudoSrcExpr);
11273     if (AssignmentOp.isInvalid())
11274       continue;
11275     AssignmentOp = ActOnFinishFullExpr(AssignmentOp.get(), ELoc,
11276                                        /*DiscardedValue=*/true);
11277     if (AssignmentOp.isInvalid())
11278       continue;
11279 
11280     // No need to mark vars as copyprivate, they are already threadprivate or
11281     // implicitly private.
11282     assert(VD || IsOpenMPCapturedDecl(D));
11283     Vars.push_back(
11284         VD ? RefExpr->IgnoreParens()
11285            : buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/false));
11286     SrcExprs.push_back(PseudoSrcExpr);
11287     DstExprs.push_back(PseudoDstExpr);
11288     AssignmentOps.push_back(AssignmentOp.get());
11289   }
11290 
11291   if (Vars.empty())
11292     return nullptr;
11293 
11294   return OMPCopyprivateClause::Create(Context, StartLoc, LParenLoc, EndLoc,
11295                                       Vars, SrcExprs, DstExprs, AssignmentOps);
11296 }
11297 
11298 OMPClause *Sema::ActOnOpenMPFlushClause(ArrayRef<Expr *> VarList,
11299                                         SourceLocation StartLoc,
11300                                         SourceLocation LParenLoc,
11301                                         SourceLocation EndLoc) {
11302   if (VarList.empty())
11303     return nullptr;
11304 
11305   return OMPFlushClause::Create(Context, StartLoc, LParenLoc, EndLoc, VarList);
11306 }
11307 
11308 OMPClause *
11309 Sema::ActOnOpenMPDependClause(OpenMPDependClauseKind DepKind,
11310                               SourceLocation DepLoc, SourceLocation ColonLoc,
11311                               ArrayRef<Expr *> VarList, SourceLocation StartLoc,
11312                               SourceLocation LParenLoc, SourceLocation EndLoc) {
11313   if (DSAStack->getCurrentDirective() == OMPD_ordered &&
11314       DepKind != OMPC_DEPEND_source && DepKind != OMPC_DEPEND_sink) {
11315     Diag(DepLoc, diag::err_omp_unexpected_clause_value)
11316         << "'source' or 'sink'" << getOpenMPClauseName(OMPC_depend);
11317     return nullptr;
11318   }
11319   if (DSAStack->getCurrentDirective() != OMPD_ordered &&
11320       (DepKind == OMPC_DEPEND_unknown || DepKind == OMPC_DEPEND_source ||
11321        DepKind == OMPC_DEPEND_sink)) {
11322     unsigned Except[] = {OMPC_DEPEND_source, OMPC_DEPEND_sink};
11323     Diag(DepLoc, diag::err_omp_unexpected_clause_value)
11324         << getListOfPossibleValues(OMPC_depend, /*First=*/0,
11325                                    /*Last=*/OMPC_DEPEND_unknown, Except)
11326         << getOpenMPClauseName(OMPC_depend);
11327     return nullptr;
11328   }
11329   SmallVector<Expr *, 8> Vars;
11330   DSAStackTy::OperatorOffsetTy OpsOffs;
11331   llvm::APSInt DepCounter(/*BitWidth=*/32);
11332   llvm::APSInt TotalDepCount(/*BitWidth=*/32);
11333   if (DepKind == OMPC_DEPEND_sink) {
11334     if (auto *OrderedCountExpr = DSAStack->getParentOrderedRegionParam()) {
11335       TotalDepCount = OrderedCountExpr->EvaluateKnownConstInt(Context);
11336       TotalDepCount.setIsUnsigned(/*Val=*/true);
11337     }
11338   }
11339   if ((DepKind != OMPC_DEPEND_sink && DepKind != OMPC_DEPEND_source) ||
11340       DSAStack->getParentOrderedRegionParam()) {
11341     for (auto &RefExpr : VarList) {
11342       assert(RefExpr && "NULL expr in OpenMP shared clause.");
11343       if (isa<DependentScopeDeclRefExpr>(RefExpr)) {
11344         // It will be analyzed later.
11345         Vars.push_back(RefExpr);
11346         continue;
11347       }
11348 
11349       SourceLocation ELoc = RefExpr->getExprLoc();
11350       auto *SimpleExpr = RefExpr->IgnoreParenCasts();
11351       if (DepKind == OMPC_DEPEND_sink) {
11352         if (DepCounter >= TotalDepCount) {
11353           Diag(ELoc, diag::err_omp_depend_sink_unexpected_expr);
11354           continue;
11355         }
11356         ++DepCounter;
11357         // OpenMP  [2.13.9, Summary]
11358         // depend(dependence-type : vec), where dependence-type is:
11359         // 'sink' and where vec is the iteration vector, which has the form:
11360         //  x1 [+- d1], x2 [+- d2 ], . . . , xn [+- dn]
11361         // where n is the value specified by the ordered clause in the loop
11362         // directive, xi denotes the loop iteration variable of the i-th nested
11363         // loop associated with the loop directive, and di is a constant
11364         // non-negative integer.
11365         if (CurContext->isDependentContext()) {
11366           // It will be analyzed later.
11367           Vars.push_back(RefExpr);
11368           continue;
11369         }
11370         SimpleExpr = SimpleExpr->IgnoreImplicit();
11371         OverloadedOperatorKind OOK = OO_None;
11372         SourceLocation OOLoc;
11373         Expr *LHS = SimpleExpr;
11374         Expr *RHS = nullptr;
11375         if (auto *BO = dyn_cast<BinaryOperator>(SimpleExpr)) {
11376           OOK = BinaryOperator::getOverloadedOperator(BO->getOpcode());
11377           OOLoc = BO->getOperatorLoc();
11378           LHS = BO->getLHS()->IgnoreParenImpCasts();
11379           RHS = BO->getRHS()->IgnoreParenImpCasts();
11380         } else if (auto *OCE = dyn_cast<CXXOperatorCallExpr>(SimpleExpr)) {
11381           OOK = OCE->getOperator();
11382           OOLoc = OCE->getOperatorLoc();
11383           LHS = OCE->getArg(/*Arg=*/0)->IgnoreParenImpCasts();
11384           RHS = OCE->getArg(/*Arg=*/1)->IgnoreParenImpCasts();
11385         } else if (auto *MCE = dyn_cast<CXXMemberCallExpr>(SimpleExpr)) {
11386           OOK = MCE->getMethodDecl()
11387                     ->getNameInfo()
11388                     .getName()
11389                     .getCXXOverloadedOperator();
11390           OOLoc = MCE->getCallee()->getExprLoc();
11391           LHS = MCE->getImplicitObjectArgument()->IgnoreParenImpCasts();
11392           RHS = MCE->getArg(/*Arg=*/0)->IgnoreParenImpCasts();
11393         }
11394         SourceLocation ELoc;
11395         SourceRange ERange;
11396         auto Res = getPrivateItem(*this, LHS, ELoc, ERange,
11397                                   /*AllowArraySection=*/false);
11398         if (Res.second) {
11399           // It will be analyzed later.
11400           Vars.push_back(RefExpr);
11401         }
11402         ValueDecl *D = Res.first;
11403         if (!D)
11404           continue;
11405 
11406         if (OOK != OO_Plus && OOK != OO_Minus && (RHS || OOK != OO_None)) {
11407           Diag(OOLoc, diag::err_omp_depend_sink_expected_plus_minus);
11408           continue;
11409         }
11410         if (RHS) {
11411           ExprResult RHSRes = VerifyPositiveIntegerConstantInClause(
11412               RHS, OMPC_depend, /*StrictlyPositive=*/false);
11413           if (RHSRes.isInvalid())
11414             continue;
11415         }
11416         if (!CurContext->isDependentContext() &&
11417             DSAStack->getParentOrderedRegionParam() &&
11418             DepCounter != DSAStack->isParentLoopControlVariable(D).first) {
11419           ValueDecl* VD = DSAStack->getParentLoopControlVariable(
11420               DepCounter.getZExtValue());
11421           if (VD) {
11422             Diag(ELoc, diag::err_omp_depend_sink_expected_loop_iteration)
11423                 << 1 << VD;
11424           } else {
11425              Diag(ELoc, diag::err_omp_depend_sink_expected_loop_iteration) << 0;
11426           }
11427           continue;
11428         }
11429         OpsOffs.push_back({RHS, OOK});
11430       } else {
11431         auto *ASE = dyn_cast<ArraySubscriptExpr>(SimpleExpr);
11432         if (!RefExpr->IgnoreParenImpCasts()->isLValue() ||
11433             (ASE &&
11434              !ASE->getBase()
11435                   ->getType()
11436                   .getNonReferenceType()
11437                   ->isPointerType() &&
11438              !ASE->getBase()->getType().getNonReferenceType()->isArrayType())) {
11439           Diag(ELoc, diag::err_omp_expected_addressable_lvalue_or_array_item)
11440               << RefExpr->getSourceRange();
11441           continue;
11442         }
11443         bool Suppress = getDiagnostics().getSuppressAllDiagnostics();
11444         getDiagnostics().setSuppressAllDiagnostics(/*Val=*/true);
11445         ExprResult Res = CreateBuiltinUnaryOp(ELoc, UO_AddrOf,
11446                                               RefExpr->IgnoreParenImpCasts());
11447         getDiagnostics().setSuppressAllDiagnostics(Suppress);
11448         if (!Res.isUsable() && !isa<OMPArraySectionExpr>(SimpleExpr)) {
11449           Diag(ELoc, diag::err_omp_expected_addressable_lvalue_or_array_item)
11450               << RefExpr->getSourceRange();
11451           continue;
11452         }
11453       }
11454       Vars.push_back(RefExpr->IgnoreParenImpCasts());
11455     }
11456 
11457     if (!CurContext->isDependentContext() && DepKind == OMPC_DEPEND_sink &&
11458         TotalDepCount > VarList.size() &&
11459         DSAStack->getParentOrderedRegionParam() &&
11460         DSAStack->getParentLoopControlVariable(VarList.size() + 1)) {
11461       Diag(EndLoc, diag::err_omp_depend_sink_expected_loop_iteration) << 1
11462           << DSAStack->getParentLoopControlVariable(VarList.size() + 1);
11463     }
11464     if (DepKind != OMPC_DEPEND_source && DepKind != OMPC_DEPEND_sink &&
11465         Vars.empty())
11466       return nullptr;
11467   }
11468   auto *C = OMPDependClause::Create(Context, StartLoc, LParenLoc, EndLoc,
11469                                     DepKind, DepLoc, ColonLoc, Vars);
11470   if (DepKind == OMPC_DEPEND_sink || DepKind == OMPC_DEPEND_source)
11471     DSAStack->addDoacrossDependClause(C, OpsOffs);
11472   return C;
11473 }
11474 
11475 OMPClause *Sema::ActOnOpenMPDeviceClause(Expr *Device, SourceLocation StartLoc,
11476                                          SourceLocation LParenLoc,
11477                                          SourceLocation EndLoc) {
11478   Expr *ValExpr = Device;
11479   Stmt *HelperValStmt = nullptr;
11480 
11481   // OpenMP [2.9.1, Restrictions]
11482   // The device expression must evaluate to a non-negative integer value.
11483   if (!IsNonNegativeIntegerValue(ValExpr, *this, OMPC_device,
11484                                  /*StrictlyPositive=*/false))
11485     return nullptr;
11486 
11487   OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective();
11488   OpenMPDirectiveKind CaptureRegion =
11489       getOpenMPCaptureRegionForClause(DKind, OMPC_device);
11490   if (CaptureRegion != OMPD_unknown && !CurContext->isDependentContext()) {
11491     ValExpr = MakeFullExpr(ValExpr).get();
11492     llvm::MapVector<Expr *, DeclRefExpr *> Captures;
11493     ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
11494     HelperValStmt = buildPreInits(Context, Captures);
11495   }
11496 
11497   return new (Context) OMPDeviceClause(ValExpr, HelperValStmt, CaptureRegion,
11498                                        StartLoc, LParenLoc, EndLoc);
11499 }
11500 
11501 static bool CheckTypeMappable(SourceLocation SL, SourceRange SR, Sema &SemaRef,
11502                               DSAStackTy *Stack, QualType QTy) {
11503   NamedDecl *ND;
11504   if (QTy->isIncompleteType(&ND)) {
11505     SemaRef.Diag(SL, diag::err_incomplete_type) << QTy << SR;
11506     return false;
11507   }
11508   return true;
11509 }
11510 
11511 /// \brief Return true if it can be proven that the provided array expression
11512 /// (array section or array subscript) does NOT specify the whole size of the
11513 /// array whose base type is \a BaseQTy.
11514 static bool CheckArrayExpressionDoesNotReferToWholeSize(Sema &SemaRef,
11515                                                         const Expr *E,
11516                                                         QualType BaseQTy) {
11517   auto *OASE = dyn_cast<OMPArraySectionExpr>(E);
11518 
11519   // If this is an array subscript, it refers to the whole size if the size of
11520   // the dimension is constant and equals 1. Also, an array section assumes the
11521   // format of an array subscript if no colon is used.
11522   if (isa<ArraySubscriptExpr>(E) || (OASE && OASE->getColonLoc().isInvalid())) {
11523     if (auto *ATy = dyn_cast<ConstantArrayType>(BaseQTy.getTypePtr()))
11524       return ATy->getSize().getSExtValue() != 1;
11525     // Size can't be evaluated statically.
11526     return false;
11527   }
11528 
11529   assert(OASE && "Expecting array section if not an array subscript.");
11530   auto *LowerBound = OASE->getLowerBound();
11531   auto *Length = OASE->getLength();
11532 
11533   // If there is a lower bound that does not evaluates to zero, we are not
11534   // covering the whole dimension.
11535   if (LowerBound) {
11536     llvm::APSInt ConstLowerBound;
11537     if (!LowerBound->EvaluateAsInt(ConstLowerBound, SemaRef.getASTContext()))
11538       return false; // Can't get the integer value as a constant.
11539     if (ConstLowerBound.getSExtValue())
11540       return true;
11541   }
11542 
11543   // If we don't have a length we covering the whole dimension.
11544   if (!Length)
11545     return false;
11546 
11547   // If the base is a pointer, we don't have a way to get the size of the
11548   // pointee.
11549   if (BaseQTy->isPointerType())
11550     return false;
11551 
11552   // We can only check if the length is the same as the size of the dimension
11553   // if we have a constant array.
11554   auto *CATy = dyn_cast<ConstantArrayType>(BaseQTy.getTypePtr());
11555   if (!CATy)
11556     return false;
11557 
11558   llvm::APSInt ConstLength;
11559   if (!Length->EvaluateAsInt(ConstLength, SemaRef.getASTContext()))
11560     return false; // Can't get the integer value as a constant.
11561 
11562   return CATy->getSize().getSExtValue() != ConstLength.getSExtValue();
11563 }
11564 
11565 // Return true if it can be proven that the provided array expression (array
11566 // section or array subscript) does NOT specify a single element of the array
11567 // whose base type is \a BaseQTy.
11568 static bool CheckArrayExpressionDoesNotReferToUnitySize(Sema &SemaRef,
11569                                                         const Expr *E,
11570                                                         QualType BaseQTy) {
11571   auto *OASE = dyn_cast<OMPArraySectionExpr>(E);
11572 
11573   // An array subscript always refer to a single element. Also, an array section
11574   // assumes the format of an array subscript if no colon is used.
11575   if (isa<ArraySubscriptExpr>(E) || (OASE && OASE->getColonLoc().isInvalid()))
11576     return false;
11577 
11578   assert(OASE && "Expecting array section if not an array subscript.");
11579   auto *Length = OASE->getLength();
11580 
11581   // If we don't have a length we have to check if the array has unitary size
11582   // for this dimension. Also, we should always expect a length if the base type
11583   // is pointer.
11584   if (!Length) {
11585     if (auto *ATy = dyn_cast<ConstantArrayType>(BaseQTy.getTypePtr()))
11586       return ATy->getSize().getSExtValue() != 1;
11587     // We cannot assume anything.
11588     return false;
11589   }
11590 
11591   // Check if the length evaluates to 1.
11592   llvm::APSInt ConstLength;
11593   if (!Length->EvaluateAsInt(ConstLength, SemaRef.getASTContext()))
11594     return false; // Can't get the integer value as a constant.
11595 
11596   return ConstLength.getSExtValue() != 1;
11597 }
11598 
11599 // Return the expression of the base of the mappable expression or null if it
11600 // cannot be determined and do all the necessary checks to see if the expression
11601 // is valid as a standalone mappable expression. In the process, record all the
11602 // components of the expression.
11603 static Expr *CheckMapClauseExpressionBase(
11604     Sema &SemaRef, Expr *E,
11605     OMPClauseMappableExprCommon::MappableExprComponentList &CurComponents,
11606     OpenMPClauseKind CKind, bool NoDiagnose) {
11607   SourceLocation ELoc = E->getExprLoc();
11608   SourceRange ERange = E->getSourceRange();
11609 
11610   // The base of elements of list in a map clause have to be either:
11611   //  - a reference to variable or field.
11612   //  - a member expression.
11613   //  - an array expression.
11614   //
11615   // E.g. if we have the expression 'r.S.Arr[:12]', we want to retrieve the
11616   // reference to 'r'.
11617   //
11618   // If we have:
11619   //
11620   // struct SS {
11621   //   Bla S;
11622   //   foo() {
11623   //     #pragma omp target map (S.Arr[:12]);
11624   //   }
11625   // }
11626   //
11627   // We want to retrieve the member expression 'this->S';
11628 
11629   Expr *RelevantExpr = nullptr;
11630 
11631   // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.2]
11632   //  If a list item is an array section, it must specify contiguous storage.
11633   //
11634   // For this restriction it is sufficient that we make sure only references
11635   // to variables or fields and array expressions, and that no array sections
11636   // exist except in the rightmost expression (unless they cover the whole
11637   // dimension of the array). E.g. these would be invalid:
11638   //
11639   //   r.ArrS[3:5].Arr[6:7]
11640   //
11641   //   r.ArrS[3:5].x
11642   //
11643   // but these would be valid:
11644   //   r.ArrS[3].Arr[6:7]
11645   //
11646   //   r.ArrS[3].x
11647 
11648   bool AllowUnitySizeArraySection = true;
11649   bool AllowWholeSizeArraySection = true;
11650 
11651   while (!RelevantExpr) {
11652     E = E->IgnoreParenImpCasts();
11653 
11654     if (auto *CurE = dyn_cast<DeclRefExpr>(E)) {
11655       if (!isa<VarDecl>(CurE->getDecl()))
11656         return nullptr;
11657 
11658       RelevantExpr = CurE;
11659 
11660       // If we got a reference to a declaration, we should not expect any array
11661       // section before that.
11662       AllowUnitySizeArraySection = false;
11663       AllowWholeSizeArraySection = false;
11664 
11665       // Record the component.
11666       CurComponents.emplace_back(CurE, CurE->getDecl());
11667     } else if (auto *CurE = dyn_cast<MemberExpr>(E)) {
11668       auto *BaseE = CurE->getBase()->IgnoreParenImpCasts();
11669 
11670       if (isa<CXXThisExpr>(BaseE))
11671         // We found a base expression: this->Val.
11672         RelevantExpr = CurE;
11673       else
11674         E = BaseE;
11675 
11676       if (!isa<FieldDecl>(CurE->getMemberDecl())) {
11677         if (!NoDiagnose) {
11678           SemaRef.Diag(ELoc, diag::err_omp_expected_access_to_data_field)
11679               << CurE->getSourceRange();
11680           return nullptr;
11681         }
11682         if (RelevantExpr)
11683           return nullptr;
11684         continue;
11685       }
11686 
11687       auto *FD = cast<FieldDecl>(CurE->getMemberDecl());
11688 
11689       // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C/C++, p.3]
11690       //  A bit-field cannot appear in a map clause.
11691       //
11692       if (FD->isBitField()) {
11693         if (!NoDiagnose) {
11694           SemaRef.Diag(ELoc, diag::err_omp_bit_fields_forbidden_in_clause)
11695               << CurE->getSourceRange() << getOpenMPClauseName(CKind);
11696           return nullptr;
11697         }
11698         if (RelevantExpr)
11699           return nullptr;
11700         continue;
11701       }
11702 
11703       // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C++, p.1]
11704       //  If the type of a list item is a reference to a type T then the type
11705       //  will be considered to be T for all purposes of this clause.
11706       QualType CurType = BaseE->getType().getNonReferenceType();
11707 
11708       // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C/C++, p.2]
11709       //  A list item cannot be a variable that is a member of a structure with
11710       //  a union type.
11711       //
11712       if (auto *RT = CurType->getAs<RecordType>()) {
11713         if (RT->isUnionType()) {
11714           if (!NoDiagnose) {
11715             SemaRef.Diag(ELoc, diag::err_omp_union_type_not_allowed)
11716                 << CurE->getSourceRange();
11717             return nullptr;
11718           }
11719           continue;
11720         }
11721       }
11722 
11723       // If we got a member expression, we should not expect any array section
11724       // before that:
11725       //
11726       // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.7]
11727       //  If a list item is an element of a structure, only the rightmost symbol
11728       //  of the variable reference can be an array section.
11729       //
11730       AllowUnitySizeArraySection = false;
11731       AllowWholeSizeArraySection = false;
11732 
11733       // Record the component.
11734       CurComponents.emplace_back(CurE, FD);
11735     } else if (auto *CurE = dyn_cast<ArraySubscriptExpr>(E)) {
11736       E = CurE->getBase()->IgnoreParenImpCasts();
11737 
11738       if (!E->getType()->isAnyPointerType() && !E->getType()->isArrayType()) {
11739         if (!NoDiagnose) {
11740           SemaRef.Diag(ELoc, diag::err_omp_expected_base_var_name)
11741               << 0 << CurE->getSourceRange();
11742           return nullptr;
11743         }
11744         continue;
11745       }
11746 
11747       // If we got an array subscript that express the whole dimension we
11748       // can have any array expressions before. If it only expressing part of
11749       // the dimension, we can only have unitary-size array expressions.
11750       if (CheckArrayExpressionDoesNotReferToWholeSize(SemaRef, CurE,
11751                                                       E->getType()))
11752         AllowWholeSizeArraySection = false;
11753 
11754       // Record the component - we don't have any declaration associated.
11755       CurComponents.emplace_back(CurE, nullptr);
11756     } else if (auto *CurE = dyn_cast<OMPArraySectionExpr>(E)) {
11757       assert(!NoDiagnose && "Array sections cannot be implicitly mapped.");
11758       E = CurE->getBase()->IgnoreParenImpCasts();
11759 
11760       QualType CurType =
11761           OMPArraySectionExpr::getBaseOriginalType(E).getCanonicalType();
11762 
11763       // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C++, p.1]
11764       //  If the type of a list item is a reference to a type T then the type
11765       //  will be considered to be T for all purposes of this clause.
11766       if (CurType->isReferenceType())
11767         CurType = CurType->getPointeeType();
11768 
11769       bool IsPointer = CurType->isAnyPointerType();
11770 
11771       if (!IsPointer && !CurType->isArrayType()) {
11772         SemaRef.Diag(ELoc, diag::err_omp_expected_base_var_name)
11773             << 0 << CurE->getSourceRange();
11774         return nullptr;
11775       }
11776 
11777       bool NotWhole =
11778           CheckArrayExpressionDoesNotReferToWholeSize(SemaRef, CurE, CurType);
11779       bool NotUnity =
11780           CheckArrayExpressionDoesNotReferToUnitySize(SemaRef, CurE, CurType);
11781 
11782       if (AllowWholeSizeArraySection) {
11783         // Any array section is currently allowed. Allowing a whole size array
11784         // section implies allowing a unity array section as well.
11785         //
11786         // If this array section refers to the whole dimension we can still
11787         // accept other array sections before this one, except if the base is a
11788         // pointer. Otherwise, only unitary sections are accepted.
11789         if (NotWhole || IsPointer)
11790           AllowWholeSizeArraySection = false;
11791       } else if (AllowUnitySizeArraySection && NotUnity) {
11792         // A unity or whole array section is not allowed and that is not
11793         // compatible with the properties of the current array section.
11794         SemaRef.Diag(
11795             ELoc, diag::err_array_section_does_not_specify_contiguous_storage)
11796             << CurE->getSourceRange();
11797         return nullptr;
11798       }
11799 
11800       // Record the component - we don't have any declaration associated.
11801       CurComponents.emplace_back(CurE, nullptr);
11802     } else {
11803       if (!NoDiagnose) {
11804         // If nothing else worked, this is not a valid map clause expression.
11805         SemaRef.Diag(
11806             ELoc, diag::err_omp_expected_named_var_member_or_array_expression)
11807             << ERange;
11808       }
11809       return nullptr;
11810     }
11811   }
11812 
11813   return RelevantExpr;
11814 }
11815 
11816 // Return true if expression E associated with value VD has conflicts with other
11817 // map information.
11818 static bool CheckMapConflicts(
11819     Sema &SemaRef, DSAStackTy *DSAS, ValueDecl *VD, Expr *E,
11820     bool CurrentRegionOnly,
11821     OMPClauseMappableExprCommon::MappableExprComponentListRef CurComponents,
11822     OpenMPClauseKind CKind) {
11823   assert(VD && E);
11824   SourceLocation ELoc = E->getExprLoc();
11825   SourceRange ERange = E->getSourceRange();
11826 
11827   // In order to easily check the conflicts we need to match each component of
11828   // the expression under test with the components of the expressions that are
11829   // already in the stack.
11830 
11831   assert(!CurComponents.empty() && "Map clause expression with no components!");
11832   assert(CurComponents.back().getAssociatedDeclaration() == VD &&
11833          "Map clause expression with unexpected base!");
11834 
11835   // Variables to help detecting enclosing problems in data environment nests.
11836   bool IsEnclosedByDataEnvironmentExpr = false;
11837   const Expr *EnclosingExpr = nullptr;
11838 
11839   bool FoundError = DSAS->checkMappableExprComponentListsForDecl(
11840       VD, CurrentRegionOnly,
11841       [&](OMPClauseMappableExprCommon::MappableExprComponentListRef
11842               StackComponents,
11843           OpenMPClauseKind) -> bool {
11844 
11845         assert(!StackComponents.empty() &&
11846                "Map clause expression with no components!");
11847         assert(StackComponents.back().getAssociatedDeclaration() == VD &&
11848                "Map clause expression with unexpected base!");
11849 
11850         // The whole expression in the stack.
11851         auto *RE = StackComponents.front().getAssociatedExpression();
11852 
11853         // Expressions must start from the same base. Here we detect at which
11854         // point both expressions diverge from each other and see if we can
11855         // detect if the memory referred to both expressions is contiguous and
11856         // do not overlap.
11857         auto CI = CurComponents.rbegin();
11858         auto CE = CurComponents.rend();
11859         auto SI = StackComponents.rbegin();
11860         auto SE = StackComponents.rend();
11861         for (; CI != CE && SI != SE; ++CI, ++SI) {
11862 
11863           // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.3]
11864           //  At most one list item can be an array item derived from a given
11865           //  variable in map clauses of the same construct.
11866           if (CurrentRegionOnly &&
11867               (isa<ArraySubscriptExpr>(CI->getAssociatedExpression()) ||
11868                isa<OMPArraySectionExpr>(CI->getAssociatedExpression())) &&
11869               (isa<ArraySubscriptExpr>(SI->getAssociatedExpression()) ||
11870                isa<OMPArraySectionExpr>(SI->getAssociatedExpression()))) {
11871             SemaRef.Diag(CI->getAssociatedExpression()->getExprLoc(),
11872                          diag::err_omp_multiple_array_items_in_map_clause)
11873                 << CI->getAssociatedExpression()->getSourceRange();
11874             SemaRef.Diag(SI->getAssociatedExpression()->getExprLoc(),
11875                          diag::note_used_here)
11876                 << SI->getAssociatedExpression()->getSourceRange();
11877             return true;
11878           }
11879 
11880           // Do both expressions have the same kind?
11881           if (CI->getAssociatedExpression()->getStmtClass() !=
11882               SI->getAssociatedExpression()->getStmtClass())
11883             break;
11884 
11885           // Are we dealing with different variables/fields?
11886           if (CI->getAssociatedDeclaration() != SI->getAssociatedDeclaration())
11887             break;
11888         }
11889         // Check if the extra components of the expressions in the enclosing
11890         // data environment are redundant for the current base declaration.
11891         // If they are, the maps completely overlap, which is legal.
11892         for (; SI != SE; ++SI) {
11893           QualType Type;
11894           if (auto *ASE =
11895                   dyn_cast<ArraySubscriptExpr>(SI->getAssociatedExpression())) {
11896             Type = ASE->getBase()->IgnoreParenImpCasts()->getType();
11897           } else if (auto *OASE = dyn_cast<OMPArraySectionExpr>(
11898                          SI->getAssociatedExpression())) {
11899             auto *E = OASE->getBase()->IgnoreParenImpCasts();
11900             Type =
11901                 OMPArraySectionExpr::getBaseOriginalType(E).getCanonicalType();
11902           }
11903           if (Type.isNull() || Type->isAnyPointerType() ||
11904               CheckArrayExpressionDoesNotReferToWholeSize(
11905                   SemaRef, SI->getAssociatedExpression(), Type))
11906             break;
11907         }
11908 
11909         // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.4]
11910         //  List items of map clauses in the same construct must not share
11911         //  original storage.
11912         //
11913         // If the expressions are exactly the same or one is a subset of the
11914         // other, it means they are sharing storage.
11915         if (CI == CE && SI == SE) {
11916           if (CurrentRegionOnly) {
11917             if (CKind == OMPC_map)
11918               SemaRef.Diag(ELoc, diag::err_omp_map_shared_storage) << ERange;
11919             else {
11920               assert(CKind == OMPC_to || CKind == OMPC_from);
11921               SemaRef.Diag(ELoc, diag::err_omp_once_referenced_in_target_update)
11922                   << ERange;
11923             }
11924             SemaRef.Diag(RE->getExprLoc(), diag::note_used_here)
11925                 << RE->getSourceRange();
11926             return true;
11927           } else {
11928             // If we find the same expression in the enclosing data environment,
11929             // that is legal.
11930             IsEnclosedByDataEnvironmentExpr = true;
11931             return false;
11932           }
11933         }
11934 
11935         QualType DerivedType =
11936             std::prev(CI)->getAssociatedDeclaration()->getType();
11937         SourceLocation DerivedLoc =
11938             std::prev(CI)->getAssociatedExpression()->getExprLoc();
11939 
11940         // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C++, p.1]
11941         //  If the type of a list item is a reference to a type T then the type
11942         //  will be considered to be T for all purposes of this clause.
11943         DerivedType = DerivedType.getNonReferenceType();
11944 
11945         // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C/C++, p.1]
11946         //  A variable for which the type is pointer and an array section
11947         //  derived from that variable must not appear as list items of map
11948         //  clauses of the same construct.
11949         //
11950         // Also, cover one of the cases in:
11951         // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.5]
11952         //  If any part of the original storage of a list item has corresponding
11953         //  storage in the device data environment, all of the original storage
11954         //  must have corresponding storage in the device data environment.
11955         //
11956         if (DerivedType->isAnyPointerType()) {
11957           if (CI == CE || SI == SE) {
11958             SemaRef.Diag(
11959                 DerivedLoc,
11960                 diag::err_omp_pointer_mapped_along_with_derived_section)
11961                 << DerivedLoc;
11962           } else {
11963             assert(CI != CE && SI != SE);
11964             SemaRef.Diag(DerivedLoc, diag::err_omp_same_pointer_derreferenced)
11965                 << DerivedLoc;
11966           }
11967           SemaRef.Diag(RE->getExprLoc(), diag::note_used_here)
11968               << RE->getSourceRange();
11969           return true;
11970         }
11971 
11972         // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.4]
11973         //  List items of map clauses in the same construct must not share
11974         //  original storage.
11975         //
11976         // An expression is a subset of the other.
11977         if (CurrentRegionOnly && (CI == CE || SI == SE)) {
11978           if (CKind == OMPC_map)
11979             SemaRef.Diag(ELoc, diag::err_omp_map_shared_storage) << ERange;
11980           else {
11981             assert(CKind == OMPC_to || CKind == OMPC_from);
11982             SemaRef.Diag(ELoc, diag::err_omp_once_referenced_in_target_update)
11983                 << ERange;
11984           }
11985           SemaRef.Diag(RE->getExprLoc(), diag::note_used_here)
11986               << RE->getSourceRange();
11987           return true;
11988         }
11989 
11990         // The current expression uses the same base as other expression in the
11991         // data environment but does not contain it completely.
11992         if (!CurrentRegionOnly && SI != SE)
11993           EnclosingExpr = RE;
11994 
11995         // The current expression is a subset of the expression in the data
11996         // environment.
11997         IsEnclosedByDataEnvironmentExpr |=
11998             (!CurrentRegionOnly && CI != CE && SI == SE);
11999 
12000         return false;
12001       });
12002 
12003   if (CurrentRegionOnly)
12004     return FoundError;
12005 
12006   // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.5]
12007   //  If any part of the original storage of a list item has corresponding
12008   //  storage in the device data environment, all of the original storage must
12009   //  have corresponding storage in the device data environment.
12010   // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.6]
12011   //  If a list item is an element of a structure, and a different element of
12012   //  the structure has a corresponding list item in the device data environment
12013   //  prior to a task encountering the construct associated with the map clause,
12014   //  then the list item must also have a corresponding list item in the device
12015   //  data environment prior to the task encountering the construct.
12016   //
12017   if (EnclosingExpr && !IsEnclosedByDataEnvironmentExpr) {
12018     SemaRef.Diag(ELoc,
12019                  diag::err_omp_original_storage_is_shared_and_does_not_contain)
12020         << ERange;
12021     SemaRef.Diag(EnclosingExpr->getExprLoc(), diag::note_used_here)
12022         << EnclosingExpr->getSourceRange();
12023     return true;
12024   }
12025 
12026   return FoundError;
12027 }
12028 
12029 namespace {
12030 // Utility struct that gathers all the related lists associated with a mappable
12031 // expression.
12032 struct MappableVarListInfo final {
12033   // The list of expressions.
12034   ArrayRef<Expr *> VarList;
12035   // The list of processed expressions.
12036   SmallVector<Expr *, 16> ProcessedVarList;
12037   // The mappble components for each expression.
12038   OMPClauseMappableExprCommon::MappableExprComponentLists VarComponents;
12039   // The base declaration of the variable.
12040   SmallVector<ValueDecl *, 16> VarBaseDeclarations;
12041 
12042   MappableVarListInfo(ArrayRef<Expr *> VarList) : VarList(VarList) {
12043     // We have a list of components and base declarations for each entry in the
12044     // variable list.
12045     VarComponents.reserve(VarList.size());
12046     VarBaseDeclarations.reserve(VarList.size());
12047   }
12048 };
12049 }
12050 
12051 // Check the validity of the provided variable list for the provided clause kind
12052 // \a CKind. In the check process the valid expressions, and mappable expression
12053 // components and variables are extracted and used to fill \a Vars,
12054 // \a ClauseComponents, and \a ClauseBaseDeclarations. \a MapType and
12055 // \a IsMapTypeImplicit are expected to be valid if the clause kind is 'map'.
12056 static void
12057 checkMappableExpressionList(Sema &SemaRef, DSAStackTy *DSAS,
12058                             OpenMPClauseKind CKind, MappableVarListInfo &MVLI,
12059                             SourceLocation StartLoc,
12060                             OpenMPMapClauseKind MapType = OMPC_MAP_unknown,
12061                             bool IsMapTypeImplicit = false) {
12062   // We only expect mappable expressions in 'to', 'from', and 'map' clauses.
12063   assert((CKind == OMPC_map || CKind == OMPC_to || CKind == OMPC_from) &&
12064          "Unexpected clause kind with mappable expressions!");
12065 
12066   // Keep track of the mappable components and base declarations in this clause.
12067   // Each entry in the list is going to have a list of components associated. We
12068   // record each set of the components so that we can build the clause later on.
12069   // In the end we should have the same amount of declarations and component
12070   // lists.
12071 
12072   for (auto &RE : MVLI.VarList) {
12073     assert(RE && "Null expr in omp to/from/map clause");
12074     SourceLocation ELoc = RE->getExprLoc();
12075 
12076     auto *VE = RE->IgnoreParenLValueCasts();
12077 
12078     if (VE->isValueDependent() || VE->isTypeDependent() ||
12079         VE->isInstantiationDependent() ||
12080         VE->containsUnexpandedParameterPack()) {
12081       // We can only analyze this information once the missing information is
12082       // resolved.
12083       MVLI.ProcessedVarList.push_back(RE);
12084       continue;
12085     }
12086 
12087     auto *SimpleExpr = RE->IgnoreParenCasts();
12088 
12089     if (!RE->IgnoreParenImpCasts()->isLValue()) {
12090       SemaRef.Diag(ELoc,
12091                    diag::err_omp_expected_named_var_member_or_array_expression)
12092           << RE->getSourceRange();
12093       continue;
12094     }
12095 
12096     OMPClauseMappableExprCommon::MappableExprComponentList CurComponents;
12097     ValueDecl *CurDeclaration = nullptr;
12098 
12099     // Obtain the array or member expression bases if required. Also, fill the
12100     // components array with all the components identified in the process.
12101     auto *BE = CheckMapClauseExpressionBase(SemaRef, SimpleExpr, CurComponents,
12102                                             CKind, /*NoDiagnose=*/false);
12103     if (!BE)
12104       continue;
12105 
12106     assert(!CurComponents.empty() &&
12107            "Invalid mappable expression information.");
12108 
12109     // For the following checks, we rely on the base declaration which is
12110     // expected to be associated with the last component. The declaration is
12111     // expected to be a variable or a field (if 'this' is being mapped).
12112     CurDeclaration = CurComponents.back().getAssociatedDeclaration();
12113     assert(CurDeclaration && "Null decl on map clause.");
12114     assert(
12115         CurDeclaration->isCanonicalDecl() &&
12116         "Expecting components to have associated only canonical declarations.");
12117 
12118     auto *VD = dyn_cast<VarDecl>(CurDeclaration);
12119     auto *FD = dyn_cast<FieldDecl>(CurDeclaration);
12120 
12121     assert((VD || FD) && "Only variables or fields are expected here!");
12122     (void)FD;
12123 
12124     // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.10]
12125     // threadprivate variables cannot appear in a map clause.
12126     // OpenMP 4.5 [2.10.5, target update Construct]
12127     // threadprivate variables cannot appear in a from clause.
12128     if (VD && DSAS->isThreadPrivate(VD)) {
12129       auto DVar = DSAS->getTopDSA(VD, false);
12130       SemaRef.Diag(ELoc, diag::err_omp_threadprivate_in_clause)
12131           << getOpenMPClauseName(CKind);
12132       ReportOriginalDSA(SemaRef, DSAS, VD, DVar);
12133       continue;
12134     }
12135 
12136     // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.9]
12137     //  A list item cannot appear in both a map clause and a data-sharing
12138     //  attribute clause on the same construct.
12139 
12140     // Check conflicts with other map clause expressions. We check the conflicts
12141     // with the current construct separately from the enclosing data
12142     // environment, because the restrictions are different. We only have to
12143     // check conflicts across regions for the map clauses.
12144     if (CheckMapConflicts(SemaRef, DSAS, CurDeclaration, SimpleExpr,
12145                           /*CurrentRegionOnly=*/true, CurComponents, CKind))
12146       break;
12147     if (CKind == OMPC_map &&
12148         CheckMapConflicts(SemaRef, DSAS, CurDeclaration, SimpleExpr,
12149                           /*CurrentRegionOnly=*/false, CurComponents, CKind))
12150       break;
12151 
12152     // OpenMP 4.5 [2.10.5, target update Construct]
12153     // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C++, p.1]
12154     //  If the type of a list item is a reference to a type T then the type will
12155     //  be considered to be T for all purposes of this clause.
12156     QualType Type = CurDeclaration->getType().getNonReferenceType();
12157 
12158     // OpenMP 4.5 [2.10.5, target update Construct, Restrictions, p.4]
12159     // A list item in a to or from clause must have a mappable type.
12160     // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.9]
12161     //  A list item must have a mappable type.
12162     if (!CheckTypeMappable(VE->getExprLoc(), VE->getSourceRange(), SemaRef,
12163                            DSAS, Type))
12164       continue;
12165 
12166     if (CKind == OMPC_map) {
12167       // target enter data
12168       // OpenMP [2.10.2, Restrictions, p. 99]
12169       // A map-type must be specified in all map clauses and must be either
12170       // to or alloc.
12171       OpenMPDirectiveKind DKind = DSAS->getCurrentDirective();
12172       if (DKind == OMPD_target_enter_data &&
12173           !(MapType == OMPC_MAP_to || MapType == OMPC_MAP_alloc)) {
12174         SemaRef.Diag(StartLoc, diag::err_omp_invalid_map_type_for_directive)
12175             << (IsMapTypeImplicit ? 1 : 0)
12176             << getOpenMPSimpleClauseTypeName(OMPC_map, MapType)
12177             << getOpenMPDirectiveName(DKind);
12178         continue;
12179       }
12180 
12181       // target exit_data
12182       // OpenMP [2.10.3, Restrictions, p. 102]
12183       // A map-type must be specified in all map clauses and must be either
12184       // from, release, or delete.
12185       if (DKind == OMPD_target_exit_data &&
12186           !(MapType == OMPC_MAP_from || MapType == OMPC_MAP_release ||
12187             MapType == OMPC_MAP_delete)) {
12188         SemaRef.Diag(StartLoc, diag::err_omp_invalid_map_type_for_directive)
12189             << (IsMapTypeImplicit ? 1 : 0)
12190             << getOpenMPSimpleClauseTypeName(OMPC_map, MapType)
12191             << getOpenMPDirectiveName(DKind);
12192         continue;
12193       }
12194 
12195       // OpenMP 4.5 [2.15.5.1, Restrictions, p.3]
12196       // A list item cannot appear in both a map clause and a data-sharing
12197       // attribute clause on the same construct
12198       if ((DKind == OMPD_target || DKind == OMPD_target_teams ||
12199            DKind == OMPD_target_teams_distribute ||
12200            DKind == OMPD_target_teams_distribute_parallel_for ||
12201            DKind == OMPD_target_teams_distribute_parallel_for_simd ||
12202            DKind == OMPD_target_teams_distribute_simd) && VD) {
12203         auto DVar = DSAS->getTopDSA(VD, false);
12204         if (isOpenMPPrivate(DVar.CKind)) {
12205           SemaRef.Diag(ELoc, diag::err_omp_variable_in_given_clause_and_dsa)
12206               << getOpenMPClauseName(DVar.CKind)
12207               << getOpenMPClauseName(OMPC_map)
12208               << getOpenMPDirectiveName(DSAS->getCurrentDirective());
12209           ReportOriginalDSA(SemaRef, DSAS, CurDeclaration, DVar);
12210           continue;
12211         }
12212       }
12213     }
12214 
12215     // Save the current expression.
12216     MVLI.ProcessedVarList.push_back(RE);
12217 
12218     // Store the components in the stack so that they can be used to check
12219     // against other clauses later on.
12220     DSAS->addMappableExpressionComponents(CurDeclaration, CurComponents,
12221                                           /*WhereFoundClauseKind=*/OMPC_map);
12222 
12223     // Save the components and declaration to create the clause. For purposes of
12224     // the clause creation, any component list that has has base 'this' uses
12225     // null as base declaration.
12226     MVLI.VarComponents.resize(MVLI.VarComponents.size() + 1);
12227     MVLI.VarComponents.back().append(CurComponents.begin(),
12228                                      CurComponents.end());
12229     MVLI.VarBaseDeclarations.push_back(isa<MemberExpr>(BE) ? nullptr
12230                                                            : CurDeclaration);
12231   }
12232 }
12233 
12234 OMPClause *
12235 Sema::ActOnOpenMPMapClause(OpenMPMapClauseKind MapTypeModifier,
12236                            OpenMPMapClauseKind MapType, bool IsMapTypeImplicit,
12237                            SourceLocation MapLoc, SourceLocation ColonLoc,
12238                            ArrayRef<Expr *> VarList, SourceLocation StartLoc,
12239                            SourceLocation LParenLoc, SourceLocation EndLoc) {
12240   MappableVarListInfo MVLI(VarList);
12241   checkMappableExpressionList(*this, DSAStack, OMPC_map, MVLI, StartLoc,
12242                               MapType, IsMapTypeImplicit);
12243 
12244   // We need to produce a map clause even if we don't have variables so that
12245   // other diagnostics related with non-existing map clauses are accurate.
12246   return OMPMapClause::Create(Context, StartLoc, LParenLoc, EndLoc,
12247                               MVLI.ProcessedVarList, MVLI.VarBaseDeclarations,
12248                               MVLI.VarComponents, MapTypeModifier, MapType,
12249                               IsMapTypeImplicit, MapLoc);
12250 }
12251 
12252 QualType Sema::ActOnOpenMPDeclareReductionType(SourceLocation TyLoc,
12253                                                TypeResult ParsedType) {
12254   assert(ParsedType.isUsable());
12255 
12256   QualType ReductionType = GetTypeFromParser(ParsedType.get());
12257   if (ReductionType.isNull())
12258     return QualType();
12259 
12260   // [OpenMP 4.0], 2.15 declare reduction Directive, Restrictions, C\C++
12261   // A type name in a declare reduction directive cannot be a function type, an
12262   // array type, a reference type, or a type qualified with const, volatile or
12263   // restrict.
12264   if (ReductionType.hasQualifiers()) {
12265     Diag(TyLoc, diag::err_omp_reduction_wrong_type) << 0;
12266     return QualType();
12267   }
12268 
12269   if (ReductionType->isFunctionType()) {
12270     Diag(TyLoc, diag::err_omp_reduction_wrong_type) << 1;
12271     return QualType();
12272   }
12273   if (ReductionType->isReferenceType()) {
12274     Diag(TyLoc, diag::err_omp_reduction_wrong_type) << 2;
12275     return QualType();
12276   }
12277   if (ReductionType->isArrayType()) {
12278     Diag(TyLoc, diag::err_omp_reduction_wrong_type) << 3;
12279     return QualType();
12280   }
12281   return ReductionType;
12282 }
12283 
12284 Sema::DeclGroupPtrTy Sema::ActOnOpenMPDeclareReductionDirectiveStart(
12285     Scope *S, DeclContext *DC, DeclarationName Name,
12286     ArrayRef<std::pair<QualType, SourceLocation>> ReductionTypes,
12287     AccessSpecifier AS, Decl *PrevDeclInScope) {
12288   SmallVector<Decl *, 8> Decls;
12289   Decls.reserve(ReductionTypes.size());
12290 
12291   LookupResult Lookup(*this, Name, SourceLocation(), LookupOMPReductionName,
12292                       forRedeclarationInCurContext());
12293   // [OpenMP 4.0], 2.15 declare reduction Directive, Restrictions
12294   // A reduction-identifier may not be re-declared in the current scope for the
12295   // same type or for a type that is compatible according to the base language
12296   // rules.
12297   llvm::DenseMap<QualType, SourceLocation> PreviousRedeclTypes;
12298   OMPDeclareReductionDecl *PrevDRD = nullptr;
12299   bool InCompoundScope = true;
12300   if (S != nullptr) {
12301     // Find previous declaration with the same name not referenced in other
12302     // declarations.
12303     FunctionScopeInfo *ParentFn = getEnclosingFunction();
12304     InCompoundScope =
12305         (ParentFn != nullptr) && !ParentFn->CompoundScopes.empty();
12306     LookupName(Lookup, S);
12307     FilterLookupForScope(Lookup, DC, S, /*ConsiderLinkage=*/false,
12308                          /*AllowInlineNamespace=*/false);
12309     llvm::DenseMap<OMPDeclareReductionDecl *, bool> UsedAsPrevious;
12310     auto Filter = Lookup.makeFilter();
12311     while (Filter.hasNext()) {
12312       auto *PrevDecl = cast<OMPDeclareReductionDecl>(Filter.next());
12313       if (InCompoundScope) {
12314         auto I = UsedAsPrevious.find(PrevDecl);
12315         if (I == UsedAsPrevious.end())
12316           UsedAsPrevious[PrevDecl] = false;
12317         if (auto *D = PrevDecl->getPrevDeclInScope())
12318           UsedAsPrevious[D] = true;
12319       }
12320       PreviousRedeclTypes[PrevDecl->getType().getCanonicalType()] =
12321           PrevDecl->getLocation();
12322     }
12323     Filter.done();
12324     if (InCompoundScope) {
12325       for (auto &PrevData : UsedAsPrevious) {
12326         if (!PrevData.second) {
12327           PrevDRD = PrevData.first;
12328           break;
12329         }
12330       }
12331     }
12332   } else if (PrevDeclInScope != nullptr) {
12333     auto *PrevDRDInScope = PrevDRD =
12334         cast<OMPDeclareReductionDecl>(PrevDeclInScope);
12335     do {
12336       PreviousRedeclTypes[PrevDRDInScope->getType().getCanonicalType()] =
12337           PrevDRDInScope->getLocation();
12338       PrevDRDInScope = PrevDRDInScope->getPrevDeclInScope();
12339     } while (PrevDRDInScope != nullptr);
12340   }
12341   for (auto &TyData : ReductionTypes) {
12342     auto I = PreviousRedeclTypes.find(TyData.first.getCanonicalType());
12343     bool Invalid = false;
12344     if (I != PreviousRedeclTypes.end()) {
12345       Diag(TyData.second, diag::err_omp_declare_reduction_redefinition)
12346           << TyData.first;
12347       Diag(I->second, diag::note_previous_definition);
12348       Invalid = true;
12349     }
12350     PreviousRedeclTypes[TyData.first.getCanonicalType()] = TyData.second;
12351     auto *DRD = OMPDeclareReductionDecl::Create(Context, DC, TyData.second,
12352                                                 Name, TyData.first, PrevDRD);
12353     DC->addDecl(DRD);
12354     DRD->setAccess(AS);
12355     Decls.push_back(DRD);
12356     if (Invalid)
12357       DRD->setInvalidDecl();
12358     else
12359       PrevDRD = DRD;
12360   }
12361 
12362   return DeclGroupPtrTy::make(
12363       DeclGroupRef::Create(Context, Decls.begin(), Decls.size()));
12364 }
12365 
12366 void Sema::ActOnOpenMPDeclareReductionCombinerStart(Scope *S, Decl *D) {
12367   auto *DRD = cast<OMPDeclareReductionDecl>(D);
12368 
12369   // Enter new function scope.
12370   PushFunctionScope();
12371   getCurFunction()->setHasBranchProtectedScope();
12372   getCurFunction()->setHasOMPDeclareReductionCombiner();
12373 
12374   if (S != nullptr)
12375     PushDeclContext(S, DRD);
12376   else
12377     CurContext = DRD;
12378 
12379   PushExpressionEvaluationContext(
12380       ExpressionEvaluationContext::PotentiallyEvaluated);
12381 
12382   QualType ReductionType = DRD->getType();
12383   // Create 'T* omp_parm;T omp_in;'. All references to 'omp_in' will
12384   // be replaced by '*omp_parm' during codegen. This required because 'omp_in'
12385   // uses semantics of argument handles by value, but it should be passed by
12386   // reference. C lang does not support references, so pass all parameters as
12387   // pointers.
12388   // Create 'T omp_in;' variable.
12389   auto *OmpInParm =
12390       buildVarDecl(*this, D->getLocation(), ReductionType, "omp_in");
12391   // Create 'T* omp_parm;T omp_out;'. All references to 'omp_out' will
12392   // be replaced by '*omp_parm' during codegen. This required because 'omp_out'
12393   // uses semantics of argument handles by value, but it should be passed by
12394   // reference. C lang does not support references, so pass all parameters as
12395   // pointers.
12396   // Create 'T omp_out;' variable.
12397   auto *OmpOutParm =
12398       buildVarDecl(*this, D->getLocation(), ReductionType, "omp_out");
12399   if (S != nullptr) {
12400     PushOnScopeChains(OmpInParm, S);
12401     PushOnScopeChains(OmpOutParm, S);
12402   } else {
12403     DRD->addDecl(OmpInParm);
12404     DRD->addDecl(OmpOutParm);
12405   }
12406 }
12407 
12408 void Sema::ActOnOpenMPDeclareReductionCombinerEnd(Decl *D, Expr *Combiner) {
12409   auto *DRD = cast<OMPDeclareReductionDecl>(D);
12410   DiscardCleanupsInEvaluationContext();
12411   PopExpressionEvaluationContext();
12412 
12413   PopDeclContext();
12414   PopFunctionScopeInfo();
12415 
12416   if (Combiner != nullptr)
12417     DRD->setCombiner(Combiner);
12418   else
12419     DRD->setInvalidDecl();
12420 }
12421 
12422 VarDecl *Sema::ActOnOpenMPDeclareReductionInitializerStart(Scope *S, Decl *D) {
12423   auto *DRD = cast<OMPDeclareReductionDecl>(D);
12424 
12425   // Enter new function scope.
12426   PushFunctionScope();
12427   getCurFunction()->setHasBranchProtectedScope();
12428 
12429   if (S != nullptr)
12430     PushDeclContext(S, DRD);
12431   else
12432     CurContext = DRD;
12433 
12434   PushExpressionEvaluationContext(
12435       ExpressionEvaluationContext::PotentiallyEvaluated);
12436 
12437   QualType ReductionType = DRD->getType();
12438   // Create 'T* omp_parm;T omp_priv;'. All references to 'omp_priv' will
12439   // be replaced by '*omp_parm' during codegen. This required because 'omp_priv'
12440   // uses semantics of argument handles by value, but it should be passed by
12441   // reference. C lang does not support references, so pass all parameters as
12442   // pointers.
12443   // Create 'T omp_priv;' variable.
12444   auto *OmpPrivParm =
12445       buildVarDecl(*this, D->getLocation(), ReductionType, "omp_priv");
12446   // Create 'T* omp_parm;T omp_orig;'. All references to 'omp_orig' will
12447   // be replaced by '*omp_parm' during codegen. This required because 'omp_orig'
12448   // uses semantics of argument handles by value, but it should be passed by
12449   // reference. C lang does not support references, so pass all parameters as
12450   // pointers.
12451   // Create 'T omp_orig;' variable.
12452   auto *OmpOrigParm =
12453       buildVarDecl(*this, D->getLocation(), ReductionType, "omp_orig");
12454   if (S != nullptr) {
12455     PushOnScopeChains(OmpPrivParm, S);
12456     PushOnScopeChains(OmpOrigParm, S);
12457   } else {
12458     DRD->addDecl(OmpPrivParm);
12459     DRD->addDecl(OmpOrigParm);
12460   }
12461   return OmpPrivParm;
12462 }
12463 
12464 void Sema::ActOnOpenMPDeclareReductionInitializerEnd(Decl *D, Expr *Initializer,
12465                                                      VarDecl *OmpPrivParm) {
12466   auto *DRD = cast<OMPDeclareReductionDecl>(D);
12467   DiscardCleanupsInEvaluationContext();
12468   PopExpressionEvaluationContext();
12469 
12470   PopDeclContext();
12471   PopFunctionScopeInfo();
12472 
12473   if (Initializer != nullptr) {
12474     DRD->setInitializer(Initializer, OMPDeclareReductionDecl::CallInit);
12475   } else if (OmpPrivParm->hasInit()) {
12476     DRD->setInitializer(OmpPrivParm->getInit(),
12477                         OmpPrivParm->isDirectInit()
12478                             ? OMPDeclareReductionDecl::DirectInit
12479                             : OMPDeclareReductionDecl::CopyInit);
12480   } else {
12481     DRD->setInvalidDecl();
12482   }
12483 }
12484 
12485 Sema::DeclGroupPtrTy Sema::ActOnOpenMPDeclareReductionDirectiveEnd(
12486     Scope *S, DeclGroupPtrTy DeclReductions, bool IsValid) {
12487   for (auto *D : DeclReductions.get()) {
12488     if (IsValid) {
12489       auto *DRD = cast<OMPDeclareReductionDecl>(D);
12490       if (S != nullptr)
12491         PushOnScopeChains(DRD, S, /*AddToContext=*/false);
12492     } else
12493       D->setInvalidDecl();
12494   }
12495   return DeclReductions;
12496 }
12497 
12498 OMPClause *Sema::ActOnOpenMPNumTeamsClause(Expr *NumTeams,
12499                                            SourceLocation StartLoc,
12500                                            SourceLocation LParenLoc,
12501                                            SourceLocation EndLoc) {
12502   Expr *ValExpr = NumTeams;
12503   Stmt *HelperValStmt = nullptr;
12504 
12505   // OpenMP [teams Constrcut, Restrictions]
12506   // The num_teams expression must evaluate to a positive integer value.
12507   if (!IsNonNegativeIntegerValue(ValExpr, *this, OMPC_num_teams,
12508                                  /*StrictlyPositive=*/true))
12509     return nullptr;
12510 
12511   OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective();
12512   OpenMPDirectiveKind CaptureRegion =
12513       getOpenMPCaptureRegionForClause(DKind, OMPC_num_teams);
12514   if (CaptureRegion != OMPD_unknown && !CurContext->isDependentContext()) {
12515     ValExpr = MakeFullExpr(ValExpr).get();
12516     llvm::MapVector<Expr *, DeclRefExpr *> Captures;
12517     ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
12518     HelperValStmt = buildPreInits(Context, Captures);
12519   }
12520 
12521   return new (Context) OMPNumTeamsClause(ValExpr, HelperValStmt, CaptureRegion,
12522                                          StartLoc, LParenLoc, EndLoc);
12523 }
12524 
12525 OMPClause *Sema::ActOnOpenMPThreadLimitClause(Expr *ThreadLimit,
12526                                               SourceLocation StartLoc,
12527                                               SourceLocation LParenLoc,
12528                                               SourceLocation EndLoc) {
12529   Expr *ValExpr = ThreadLimit;
12530   Stmt *HelperValStmt = nullptr;
12531 
12532   // OpenMP [teams Constrcut, Restrictions]
12533   // The thread_limit expression must evaluate to a positive integer value.
12534   if (!IsNonNegativeIntegerValue(ValExpr, *this, OMPC_thread_limit,
12535                                  /*StrictlyPositive=*/true))
12536     return nullptr;
12537 
12538   OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective();
12539   OpenMPDirectiveKind CaptureRegion =
12540       getOpenMPCaptureRegionForClause(DKind, OMPC_thread_limit);
12541   if (CaptureRegion != OMPD_unknown && !CurContext->isDependentContext()) {
12542     ValExpr = MakeFullExpr(ValExpr).get();
12543     llvm::MapVector<Expr *, DeclRefExpr *> Captures;
12544     ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
12545     HelperValStmt = buildPreInits(Context, Captures);
12546   }
12547 
12548   return new (Context) OMPThreadLimitClause(
12549       ValExpr, HelperValStmt, CaptureRegion, StartLoc, LParenLoc, EndLoc);
12550 }
12551 
12552 OMPClause *Sema::ActOnOpenMPPriorityClause(Expr *Priority,
12553                                            SourceLocation StartLoc,
12554                                            SourceLocation LParenLoc,
12555                                            SourceLocation EndLoc) {
12556   Expr *ValExpr = Priority;
12557 
12558   // OpenMP [2.9.1, task Constrcut]
12559   // The priority-value is a non-negative numerical scalar expression.
12560   if (!IsNonNegativeIntegerValue(ValExpr, *this, OMPC_priority,
12561                                  /*StrictlyPositive=*/false))
12562     return nullptr;
12563 
12564   return new (Context) OMPPriorityClause(ValExpr, StartLoc, LParenLoc, EndLoc);
12565 }
12566 
12567 OMPClause *Sema::ActOnOpenMPGrainsizeClause(Expr *Grainsize,
12568                                             SourceLocation StartLoc,
12569                                             SourceLocation LParenLoc,
12570                                             SourceLocation EndLoc) {
12571   Expr *ValExpr = Grainsize;
12572 
12573   // OpenMP [2.9.2, taskloop Constrcut]
12574   // The parameter of the grainsize clause must be a positive integer
12575   // expression.
12576   if (!IsNonNegativeIntegerValue(ValExpr, *this, OMPC_grainsize,
12577                                  /*StrictlyPositive=*/true))
12578     return nullptr;
12579 
12580   return new (Context) OMPGrainsizeClause(ValExpr, StartLoc, LParenLoc, EndLoc);
12581 }
12582 
12583 OMPClause *Sema::ActOnOpenMPNumTasksClause(Expr *NumTasks,
12584                                            SourceLocation StartLoc,
12585                                            SourceLocation LParenLoc,
12586                                            SourceLocation EndLoc) {
12587   Expr *ValExpr = NumTasks;
12588 
12589   // OpenMP [2.9.2, taskloop Constrcut]
12590   // The parameter of the num_tasks clause must be a positive integer
12591   // expression.
12592   if (!IsNonNegativeIntegerValue(ValExpr, *this, OMPC_num_tasks,
12593                                  /*StrictlyPositive=*/true))
12594     return nullptr;
12595 
12596   return new (Context) OMPNumTasksClause(ValExpr, StartLoc, LParenLoc, EndLoc);
12597 }
12598 
12599 OMPClause *Sema::ActOnOpenMPHintClause(Expr *Hint, SourceLocation StartLoc,
12600                                        SourceLocation LParenLoc,
12601                                        SourceLocation EndLoc) {
12602   // OpenMP [2.13.2, critical construct, Description]
12603   // ... where hint-expression is an integer constant expression that evaluates
12604   // to a valid lock hint.
12605   ExprResult HintExpr = VerifyPositiveIntegerConstantInClause(Hint, OMPC_hint);
12606   if (HintExpr.isInvalid())
12607     return nullptr;
12608   return new (Context)
12609       OMPHintClause(HintExpr.get(), StartLoc, LParenLoc, EndLoc);
12610 }
12611 
12612 OMPClause *Sema::ActOnOpenMPDistScheduleClause(
12613     OpenMPDistScheduleClauseKind Kind, Expr *ChunkSize, SourceLocation StartLoc,
12614     SourceLocation LParenLoc, SourceLocation KindLoc, SourceLocation CommaLoc,
12615     SourceLocation EndLoc) {
12616   if (Kind == OMPC_DIST_SCHEDULE_unknown) {
12617     std::string Values;
12618     Values += "'";
12619     Values += getOpenMPSimpleClauseTypeName(OMPC_dist_schedule, 0);
12620     Values += "'";
12621     Diag(KindLoc, diag::err_omp_unexpected_clause_value)
12622         << Values << getOpenMPClauseName(OMPC_dist_schedule);
12623     return nullptr;
12624   }
12625   Expr *ValExpr = ChunkSize;
12626   Stmt *HelperValStmt = nullptr;
12627   if (ChunkSize) {
12628     if (!ChunkSize->isValueDependent() && !ChunkSize->isTypeDependent() &&
12629         !ChunkSize->isInstantiationDependent() &&
12630         !ChunkSize->containsUnexpandedParameterPack()) {
12631       SourceLocation ChunkSizeLoc = ChunkSize->getLocStart();
12632       ExprResult Val =
12633           PerformOpenMPImplicitIntegerConversion(ChunkSizeLoc, ChunkSize);
12634       if (Val.isInvalid())
12635         return nullptr;
12636 
12637       ValExpr = Val.get();
12638 
12639       // OpenMP [2.7.1, Restrictions]
12640       //  chunk_size must be a loop invariant integer expression with a positive
12641       //  value.
12642       llvm::APSInt Result;
12643       if (ValExpr->isIntegerConstantExpr(Result, Context)) {
12644         if (Result.isSigned() && !Result.isStrictlyPositive()) {
12645           Diag(ChunkSizeLoc, diag::err_omp_negative_expression_in_clause)
12646               << "dist_schedule" << ChunkSize->getSourceRange();
12647           return nullptr;
12648         }
12649       } else if (getOpenMPCaptureRegionForClause(
12650                      DSAStack->getCurrentDirective(), OMPC_dist_schedule) !=
12651                      OMPD_unknown &&
12652                  !CurContext->isDependentContext()) {
12653         ValExpr = MakeFullExpr(ValExpr).get();
12654         llvm::MapVector<Expr *, DeclRefExpr *> Captures;
12655         ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
12656         HelperValStmt = buildPreInits(Context, Captures);
12657       }
12658     }
12659   }
12660 
12661   return new (Context)
12662       OMPDistScheduleClause(StartLoc, LParenLoc, KindLoc, CommaLoc, EndLoc,
12663                             Kind, ValExpr, HelperValStmt);
12664 }
12665 
12666 OMPClause *Sema::ActOnOpenMPDefaultmapClause(
12667     OpenMPDefaultmapClauseModifier M, OpenMPDefaultmapClauseKind Kind,
12668     SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation MLoc,
12669     SourceLocation KindLoc, SourceLocation EndLoc) {
12670   // OpenMP 4.5 only supports 'defaultmap(tofrom: scalar)'
12671   if (M != OMPC_DEFAULTMAP_MODIFIER_tofrom || Kind != OMPC_DEFAULTMAP_scalar) {
12672     std::string Value;
12673     SourceLocation Loc;
12674     Value += "'";
12675     if (M != OMPC_DEFAULTMAP_MODIFIER_tofrom) {
12676       Value += getOpenMPSimpleClauseTypeName(OMPC_defaultmap,
12677                                              OMPC_DEFAULTMAP_MODIFIER_tofrom);
12678       Loc = MLoc;
12679     } else {
12680       Value += getOpenMPSimpleClauseTypeName(OMPC_defaultmap,
12681                                              OMPC_DEFAULTMAP_scalar);
12682       Loc = KindLoc;
12683     }
12684     Value += "'";
12685     Diag(Loc, diag::err_omp_unexpected_clause_value)
12686         << Value << getOpenMPClauseName(OMPC_defaultmap);
12687     return nullptr;
12688   }
12689   DSAStack->setDefaultDMAToFromScalar(StartLoc);
12690 
12691   return new (Context)
12692       OMPDefaultmapClause(StartLoc, LParenLoc, MLoc, KindLoc, EndLoc, Kind, M);
12693 }
12694 
12695 bool Sema::ActOnStartOpenMPDeclareTargetDirective(SourceLocation Loc) {
12696   DeclContext *CurLexicalContext = getCurLexicalContext();
12697   if (!CurLexicalContext->isFileContext() &&
12698       !CurLexicalContext->isExternCContext() &&
12699       !CurLexicalContext->isExternCXXContext() &&
12700       !isa<CXXRecordDecl>(CurLexicalContext) &&
12701       !isa<ClassTemplateDecl>(CurLexicalContext) &&
12702       !isa<ClassTemplatePartialSpecializationDecl>(CurLexicalContext) &&
12703       !isa<ClassTemplateSpecializationDecl>(CurLexicalContext)) {
12704     Diag(Loc, diag::err_omp_region_not_file_context);
12705     return false;
12706   }
12707   if (IsInOpenMPDeclareTargetContext) {
12708     Diag(Loc, diag::err_omp_enclosed_declare_target);
12709     return false;
12710   }
12711 
12712   IsInOpenMPDeclareTargetContext = true;
12713   return true;
12714 }
12715 
12716 void Sema::ActOnFinishOpenMPDeclareTargetDirective() {
12717   assert(IsInOpenMPDeclareTargetContext &&
12718          "Unexpected ActOnFinishOpenMPDeclareTargetDirective");
12719 
12720   IsInOpenMPDeclareTargetContext = false;
12721 }
12722 
12723 void Sema::ActOnOpenMPDeclareTargetName(Scope *CurScope,
12724                                         CXXScopeSpec &ScopeSpec,
12725                                         const DeclarationNameInfo &Id,
12726                                         OMPDeclareTargetDeclAttr::MapTypeTy MT,
12727                                         NamedDeclSetType &SameDirectiveDecls) {
12728   LookupResult Lookup(*this, Id, LookupOrdinaryName);
12729   LookupParsedName(Lookup, CurScope, &ScopeSpec, true);
12730 
12731   if (Lookup.isAmbiguous())
12732     return;
12733   Lookup.suppressDiagnostics();
12734 
12735   if (!Lookup.isSingleResult()) {
12736     if (TypoCorrection Corrected =
12737             CorrectTypo(Id, LookupOrdinaryName, CurScope, nullptr,
12738                         llvm::make_unique<VarOrFuncDeclFilterCCC>(*this),
12739                         CTK_ErrorRecovery)) {
12740       diagnoseTypo(Corrected, PDiag(diag::err_undeclared_var_use_suggest)
12741                                   << Id.getName());
12742       checkDeclIsAllowedInOpenMPTarget(nullptr, Corrected.getCorrectionDecl());
12743       return;
12744     }
12745 
12746     Diag(Id.getLoc(), diag::err_undeclared_var_use) << Id.getName();
12747     return;
12748   }
12749 
12750   NamedDecl *ND = Lookup.getAsSingle<NamedDecl>();
12751   if (isa<VarDecl>(ND) || isa<FunctionDecl>(ND)) {
12752     if (!SameDirectiveDecls.insert(cast<NamedDecl>(ND->getCanonicalDecl())))
12753       Diag(Id.getLoc(), diag::err_omp_declare_target_multiple) << Id.getName();
12754 
12755     if (!ND->hasAttr<OMPDeclareTargetDeclAttr>()) {
12756       Attr *A = OMPDeclareTargetDeclAttr::CreateImplicit(Context, MT);
12757       ND->addAttr(A);
12758       if (ASTMutationListener *ML = Context.getASTMutationListener())
12759         ML->DeclarationMarkedOpenMPDeclareTarget(ND, A);
12760       checkDeclIsAllowedInOpenMPTarget(nullptr, ND, Id.getLoc());
12761     } else if (ND->getAttr<OMPDeclareTargetDeclAttr>()->getMapType() != MT) {
12762       Diag(Id.getLoc(), diag::err_omp_declare_target_to_and_link)
12763           << Id.getName();
12764     }
12765   } else
12766     Diag(Id.getLoc(), diag::err_omp_invalid_target_decl) << Id.getName();
12767 }
12768 
12769 static void checkDeclInTargetContext(SourceLocation SL, SourceRange SR,
12770                                      Sema &SemaRef, Decl *D) {
12771   if (!D)
12772     return;
12773   Decl *LD = nullptr;
12774   if (isa<TagDecl>(D)) {
12775     LD = cast<TagDecl>(D)->getDefinition();
12776   } else if (isa<VarDecl>(D)) {
12777     LD = cast<VarDecl>(D)->getDefinition();
12778 
12779     // If this is an implicit variable that is legal and we do not need to do
12780     // anything.
12781     if (cast<VarDecl>(D)->isImplicit()) {
12782       Attr *A = OMPDeclareTargetDeclAttr::CreateImplicit(
12783           SemaRef.Context, OMPDeclareTargetDeclAttr::MT_To);
12784       D->addAttr(A);
12785       if (ASTMutationListener *ML = SemaRef.Context.getASTMutationListener())
12786         ML->DeclarationMarkedOpenMPDeclareTarget(D, A);
12787       return;
12788     }
12789 
12790   } else if (isa<FunctionDecl>(D)) {
12791     const FunctionDecl *FD = nullptr;
12792     if (cast<FunctionDecl>(D)->hasBody(FD))
12793       LD = const_cast<FunctionDecl *>(FD);
12794 
12795     // If the definition is associated with the current declaration in the
12796     // target region (it can be e.g. a lambda) that is legal and we do not need
12797     // to do anything else.
12798     if (LD == D) {
12799       Attr *A = OMPDeclareTargetDeclAttr::CreateImplicit(
12800           SemaRef.Context, OMPDeclareTargetDeclAttr::MT_To);
12801       D->addAttr(A);
12802       if (ASTMutationListener *ML = SemaRef.Context.getASTMutationListener())
12803         ML->DeclarationMarkedOpenMPDeclareTarget(D, A);
12804       return;
12805     }
12806   }
12807   if (!LD)
12808     LD = D;
12809   if (LD && !LD->hasAttr<OMPDeclareTargetDeclAttr>() &&
12810       (isa<VarDecl>(LD) || isa<FunctionDecl>(LD))) {
12811     // Outlined declaration is not declared target.
12812     if (LD->isOutOfLine()) {
12813       SemaRef.Diag(LD->getLocation(), diag::warn_omp_not_in_target_context);
12814       SemaRef.Diag(SL, diag::note_used_here) << SR;
12815     } else {
12816       DeclContext *DC = LD->getDeclContext();
12817       while (DC) {
12818         if (isa<FunctionDecl>(DC) &&
12819             cast<FunctionDecl>(DC)->hasAttr<OMPDeclareTargetDeclAttr>())
12820           break;
12821         DC = DC->getParent();
12822       }
12823       if (DC)
12824         return;
12825 
12826       // Is not declared in target context.
12827       SemaRef.Diag(LD->getLocation(), diag::warn_omp_not_in_target_context);
12828       SemaRef.Diag(SL, diag::note_used_here) << SR;
12829     }
12830     // Mark decl as declared target to prevent further diagnostic.
12831     Attr *A = OMPDeclareTargetDeclAttr::CreateImplicit(
12832         SemaRef.Context, OMPDeclareTargetDeclAttr::MT_To);
12833     D->addAttr(A);
12834     if (ASTMutationListener *ML = SemaRef.Context.getASTMutationListener())
12835       ML->DeclarationMarkedOpenMPDeclareTarget(D, A);
12836   }
12837 }
12838 
12839 static bool checkValueDeclInTarget(SourceLocation SL, SourceRange SR,
12840                                    Sema &SemaRef, DSAStackTy *Stack,
12841                                    ValueDecl *VD) {
12842   if (VD->hasAttr<OMPDeclareTargetDeclAttr>())
12843     return true;
12844   if (!CheckTypeMappable(SL, SR, SemaRef, Stack, VD->getType()))
12845     return false;
12846   return true;
12847 }
12848 
12849 void Sema::checkDeclIsAllowedInOpenMPTarget(Expr *E, Decl *D,
12850                                             SourceLocation IdLoc) {
12851   if (!D || D->isInvalidDecl())
12852     return;
12853   SourceRange SR = E ? E->getSourceRange() : D->getSourceRange();
12854   SourceLocation SL = E ? E->getLocStart() : D->getLocation();
12855   // 2.10.6: threadprivate variable cannot appear in a declare target directive.
12856   if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
12857     if (DSAStack->isThreadPrivate(VD)) {
12858       Diag(SL, diag::err_omp_threadprivate_in_target);
12859       ReportOriginalDSA(*this, DSAStack, VD, DSAStack->getTopDSA(VD, false));
12860       return;
12861     }
12862   }
12863   if (ValueDecl *VD = dyn_cast<ValueDecl>(D)) {
12864     // Problem if any with var declared with incomplete type will be reported
12865     // as normal, so no need to check it here.
12866     if ((E || !VD->getType()->isIncompleteType()) &&
12867         !checkValueDeclInTarget(SL, SR, *this, DSAStack, VD)) {
12868       // Mark decl as declared target to prevent further diagnostic.
12869       if (isa<VarDecl>(VD) || isa<FunctionDecl>(VD)) {
12870         Attr *A = OMPDeclareTargetDeclAttr::CreateImplicit(
12871             Context, OMPDeclareTargetDeclAttr::MT_To);
12872         VD->addAttr(A);
12873         if (ASTMutationListener *ML = Context.getASTMutationListener())
12874           ML->DeclarationMarkedOpenMPDeclareTarget(VD, A);
12875       }
12876       return;
12877     }
12878   }
12879   if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
12880     if (FD->hasAttr<OMPDeclareTargetDeclAttr>() &&
12881         (FD->getAttr<OMPDeclareTargetDeclAttr>()->getMapType() ==
12882          OMPDeclareTargetDeclAttr::MT_Link)) {
12883       assert(IdLoc.isValid() && "Source location is expected");
12884       Diag(IdLoc, diag::err_omp_function_in_link_clause);
12885       Diag(FD->getLocation(), diag::note_defined_here) << FD;
12886       return;
12887     }
12888   }
12889   if (!E) {
12890     // Checking declaration inside declare target region.
12891     if (!D->hasAttr<OMPDeclareTargetDeclAttr>() &&
12892         (isa<VarDecl>(D) || isa<FunctionDecl>(D))) {
12893       Attr *A = OMPDeclareTargetDeclAttr::CreateImplicit(
12894           Context, OMPDeclareTargetDeclAttr::MT_To);
12895       D->addAttr(A);
12896       if (ASTMutationListener *ML = Context.getASTMutationListener())
12897         ML->DeclarationMarkedOpenMPDeclareTarget(D, A);
12898     }
12899     return;
12900   }
12901   checkDeclInTargetContext(E->getExprLoc(), E->getSourceRange(), *this, D);
12902 }
12903 
12904 OMPClause *Sema::ActOnOpenMPToClause(ArrayRef<Expr *> VarList,
12905                                      SourceLocation StartLoc,
12906                                      SourceLocation LParenLoc,
12907                                      SourceLocation EndLoc) {
12908   MappableVarListInfo MVLI(VarList);
12909   checkMappableExpressionList(*this, DSAStack, OMPC_to, MVLI, StartLoc);
12910   if (MVLI.ProcessedVarList.empty())
12911     return nullptr;
12912 
12913   return OMPToClause::Create(Context, StartLoc, LParenLoc, EndLoc,
12914                              MVLI.ProcessedVarList, MVLI.VarBaseDeclarations,
12915                              MVLI.VarComponents);
12916 }
12917 
12918 OMPClause *Sema::ActOnOpenMPFromClause(ArrayRef<Expr *> VarList,
12919                                        SourceLocation StartLoc,
12920                                        SourceLocation LParenLoc,
12921                                        SourceLocation EndLoc) {
12922   MappableVarListInfo MVLI(VarList);
12923   checkMappableExpressionList(*this, DSAStack, OMPC_from, MVLI, StartLoc);
12924   if (MVLI.ProcessedVarList.empty())
12925     return nullptr;
12926 
12927   return OMPFromClause::Create(Context, StartLoc, LParenLoc, EndLoc,
12928                                MVLI.ProcessedVarList, MVLI.VarBaseDeclarations,
12929                                MVLI.VarComponents);
12930 }
12931 
12932 OMPClause *Sema::ActOnOpenMPUseDevicePtrClause(ArrayRef<Expr *> VarList,
12933                                                SourceLocation StartLoc,
12934                                                SourceLocation LParenLoc,
12935                                                SourceLocation EndLoc) {
12936   MappableVarListInfo MVLI(VarList);
12937   SmallVector<Expr *, 8> PrivateCopies;
12938   SmallVector<Expr *, 8> Inits;
12939 
12940   for (auto &RefExpr : VarList) {
12941     assert(RefExpr && "NULL expr in OpenMP use_device_ptr clause.");
12942     SourceLocation ELoc;
12943     SourceRange ERange;
12944     Expr *SimpleRefExpr = RefExpr;
12945     auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
12946     if (Res.second) {
12947       // It will be analyzed later.
12948       MVLI.ProcessedVarList.push_back(RefExpr);
12949       PrivateCopies.push_back(nullptr);
12950       Inits.push_back(nullptr);
12951     }
12952     ValueDecl *D = Res.first;
12953     if (!D)
12954       continue;
12955 
12956     QualType Type = D->getType();
12957     Type = Type.getNonReferenceType().getUnqualifiedType();
12958 
12959     auto *VD = dyn_cast<VarDecl>(D);
12960 
12961     // Item should be a pointer or reference to pointer.
12962     if (!Type->isPointerType()) {
12963       Diag(ELoc, diag::err_omp_usedeviceptr_not_a_pointer)
12964           << 0 << RefExpr->getSourceRange();
12965       continue;
12966     }
12967 
12968     // Build the private variable and the expression that refers to it.
12969     auto VDPrivate = buildVarDecl(*this, ELoc, Type, D->getName(),
12970                                   D->hasAttrs() ? &D->getAttrs() : nullptr);
12971     if (VDPrivate->isInvalidDecl())
12972       continue;
12973 
12974     CurContext->addDecl(VDPrivate);
12975     auto VDPrivateRefExpr = buildDeclRefExpr(
12976         *this, VDPrivate, RefExpr->getType().getUnqualifiedType(), ELoc);
12977 
12978     // Add temporary variable to initialize the private copy of the pointer.
12979     auto *VDInit =
12980         buildVarDecl(*this, RefExpr->getExprLoc(), Type, ".devptr.temp");
12981     auto *VDInitRefExpr = buildDeclRefExpr(*this, VDInit, RefExpr->getType(),
12982                                            RefExpr->getExprLoc());
12983     AddInitializerToDecl(VDPrivate,
12984                          DefaultLvalueConversion(VDInitRefExpr).get(),
12985                          /*DirectInit=*/false);
12986 
12987     // If required, build a capture to implement the privatization initialized
12988     // with the current list item value.
12989     DeclRefExpr *Ref = nullptr;
12990     if (!VD)
12991       Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/true);
12992     MVLI.ProcessedVarList.push_back(VD ? RefExpr->IgnoreParens() : Ref);
12993     PrivateCopies.push_back(VDPrivateRefExpr);
12994     Inits.push_back(VDInitRefExpr);
12995 
12996     // We need to add a data sharing attribute for this variable to make sure it
12997     // is correctly captured. A variable that shows up in a use_device_ptr has
12998     // similar properties of a first private variable.
12999     DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_firstprivate, Ref);
13000 
13001     // Create a mappable component for the list item. List items in this clause
13002     // only need a component.
13003     MVLI.VarBaseDeclarations.push_back(D);
13004     MVLI.VarComponents.resize(MVLI.VarComponents.size() + 1);
13005     MVLI.VarComponents.back().push_back(
13006         OMPClauseMappableExprCommon::MappableComponent(SimpleRefExpr, D));
13007   }
13008 
13009   if (MVLI.ProcessedVarList.empty())
13010     return nullptr;
13011 
13012   return OMPUseDevicePtrClause::Create(
13013       Context, StartLoc, LParenLoc, EndLoc, MVLI.ProcessedVarList,
13014       PrivateCopies, Inits, MVLI.VarBaseDeclarations, MVLI.VarComponents);
13015 }
13016 
13017 OMPClause *Sema::ActOnOpenMPIsDevicePtrClause(ArrayRef<Expr *> VarList,
13018                                               SourceLocation StartLoc,
13019                                               SourceLocation LParenLoc,
13020                                               SourceLocation EndLoc) {
13021   MappableVarListInfo MVLI(VarList);
13022   for (auto &RefExpr : VarList) {
13023     assert(RefExpr && "NULL expr in OpenMP is_device_ptr clause.");
13024     SourceLocation ELoc;
13025     SourceRange ERange;
13026     Expr *SimpleRefExpr = RefExpr;
13027     auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
13028     if (Res.second) {
13029       // It will be analyzed later.
13030       MVLI.ProcessedVarList.push_back(RefExpr);
13031     }
13032     ValueDecl *D = Res.first;
13033     if (!D)
13034       continue;
13035 
13036     QualType Type = D->getType();
13037     // item should be a pointer or array or reference to pointer or array
13038     if (!Type.getNonReferenceType()->isPointerType() &&
13039         !Type.getNonReferenceType()->isArrayType()) {
13040       Diag(ELoc, diag::err_omp_argument_type_isdeviceptr)
13041           << 0 << RefExpr->getSourceRange();
13042       continue;
13043     }
13044 
13045     // Check if the declaration in the clause does not show up in any data
13046     // sharing attribute.
13047     auto DVar = DSAStack->getTopDSA(D, false);
13048     if (isOpenMPPrivate(DVar.CKind)) {
13049       Diag(ELoc, diag::err_omp_variable_in_given_clause_and_dsa)
13050           << getOpenMPClauseName(DVar.CKind)
13051           << getOpenMPClauseName(OMPC_is_device_ptr)
13052           << getOpenMPDirectiveName(DSAStack->getCurrentDirective());
13053       ReportOriginalDSA(*this, DSAStack, D, DVar);
13054       continue;
13055     }
13056 
13057     Expr *ConflictExpr;
13058     if (DSAStack->checkMappableExprComponentListsForDecl(
13059             D, /*CurrentRegionOnly=*/true,
13060             [&ConflictExpr](
13061                 OMPClauseMappableExprCommon::MappableExprComponentListRef R,
13062                 OpenMPClauseKind) -> bool {
13063               ConflictExpr = R.front().getAssociatedExpression();
13064               return true;
13065             })) {
13066       Diag(ELoc, diag::err_omp_map_shared_storage) << RefExpr->getSourceRange();
13067       Diag(ConflictExpr->getExprLoc(), diag::note_used_here)
13068           << ConflictExpr->getSourceRange();
13069       continue;
13070     }
13071 
13072     // Store the components in the stack so that they can be used to check
13073     // against other clauses later on.
13074     OMPClauseMappableExprCommon::MappableComponent MC(SimpleRefExpr, D);
13075     DSAStack->addMappableExpressionComponents(
13076         D, MC, /*WhereFoundClauseKind=*/OMPC_is_device_ptr);
13077 
13078     // Record the expression we've just processed.
13079     MVLI.ProcessedVarList.push_back(SimpleRefExpr);
13080 
13081     // Create a mappable component for the list item. List items in this clause
13082     // only need a component. We use a null declaration to signal fields in
13083     // 'this'.
13084     assert((isa<DeclRefExpr>(SimpleRefExpr) ||
13085             isa<CXXThisExpr>(cast<MemberExpr>(SimpleRefExpr)->getBase())) &&
13086            "Unexpected device pointer expression!");
13087     MVLI.VarBaseDeclarations.push_back(
13088         isa<DeclRefExpr>(SimpleRefExpr) ? D : nullptr);
13089     MVLI.VarComponents.resize(MVLI.VarComponents.size() + 1);
13090     MVLI.VarComponents.back().push_back(MC);
13091   }
13092 
13093   if (MVLI.ProcessedVarList.empty())
13094     return nullptr;
13095 
13096   return OMPIsDevicePtrClause::Create(
13097       Context, StartLoc, LParenLoc, EndLoc, MVLI.ProcessedVarList,
13098       MVLI.VarBaseDeclarations, MVLI.VarComponents);
13099 }
13100