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 /// 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 const Expr *checkMapClauseExpressionBase(
39     Sema &SemaRef, Expr *E,
40     OMPClauseMappableExprCommon::MappableExprComponentList &CurComponents,
41     OpenMPClauseKind CKind, bool NoDiagnose);
42 
43 namespace {
44 /// Default data sharing attributes, which can be applied to directive.
45 enum DefaultDataSharingAttributes {
46   DSA_unspecified = 0, /// Data sharing attribute not specified.
47   DSA_none = 1 << 0,   /// Default data sharing attribute 'none'.
48   DSA_shared = 1 << 1, /// 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 /// Stack for tracking declarations used in OpenMP directives and
58 /// clauses and their data-sharing attributes.
59 class DSAStackTy {
60 public:
61   struct DSAVarData {
62     OpenMPDirectiveKind DKind = OMPD_unknown;
63     OpenMPClauseKind CKind = OMPC_unknown;
64     const Expr *RefExpr = nullptr;
65     DeclRefExpr *PrivateCopy = nullptr;
66     SourceLocation ImplicitDSALoc;
67     DSAVarData() = default;
68     DSAVarData(OpenMPDirectiveKind DKind, OpenMPClauseKind CKind,
69                const Expr *RefExpr, DeclRefExpr *PrivateCopy,
70                SourceLocation ImplicitDSALoc)
71         : DKind(DKind), CKind(CKind), RefExpr(RefExpr),
72           PrivateCopy(PrivateCopy), ImplicitDSALoc(ImplicitDSALoc) {}
73   };
74   using OperatorOffsetTy =
75       llvm::SmallVector<std::pair<Expr *, OverloadedOperatorKind>, 4>;
76 
77 private:
78   struct DSAInfo {
79     OpenMPClauseKind Attributes = OMPC_unknown;
80     /// Pointer to a reference expression and a flag which shows that the
81     /// variable is marked as lastprivate(true) or not (false).
82     llvm::PointerIntPair<const Expr *, 1, bool> RefExpr;
83     DeclRefExpr *PrivateCopy = nullptr;
84   };
85   using DeclSAMapTy = llvm::SmallDenseMap<const ValueDecl *, DSAInfo, 8>;
86   using AlignedMapTy = llvm::SmallDenseMap<const ValueDecl *, const Expr *, 8>;
87   using LCDeclInfo = std::pair<unsigned, VarDecl *>;
88   using LoopControlVariablesMapTy =
89       llvm::SmallDenseMap<const ValueDecl *, LCDeclInfo, 8>;
90   /// Struct that associates a component with the clause kind where they are
91   /// found.
92   struct MappedExprComponentTy {
93     OMPClauseMappableExprCommon::MappableExprComponentLists Components;
94     OpenMPClauseKind Kind = OMPC_unknown;
95   };
96   using MappedExprComponentsTy =
97       llvm::DenseMap<const ValueDecl *, MappedExprComponentTy>;
98   using CriticalsWithHintsTy =
99       llvm::StringMap<std::pair<const OMPCriticalDirective *, llvm::APSInt>>;
100   using DoacrossDependMapTy =
101       llvm::DenseMap<OMPDependClause *, OperatorOffsetTy>;
102   struct ReductionData {
103     using BOKPtrType = llvm::PointerEmbeddedInt<BinaryOperatorKind, 16>;
104     SourceRange ReductionRange;
105     llvm::PointerUnion<const Expr *, BOKPtrType> ReductionOp;
106     ReductionData() = default;
107     void set(BinaryOperatorKind BO, SourceRange RR) {
108       ReductionRange = RR;
109       ReductionOp = BO;
110     }
111     void set(const Expr *RefExpr, SourceRange RR) {
112       ReductionRange = RR;
113       ReductionOp = RefExpr;
114     }
115   };
116   using DeclReductionMapTy =
117       llvm::SmallDenseMap<const ValueDecl *, ReductionData, 4>;
118 
119   struct SharingMapTy {
120     DeclSAMapTy SharingMap;
121     DeclReductionMapTy ReductionMap;
122     AlignedMapTy AlignedMap;
123     MappedExprComponentsTy MappedExprComponents;
124     LoopControlVariablesMapTy LCVMap;
125     DefaultDataSharingAttributes DefaultAttr = DSA_unspecified;
126     SourceLocation DefaultAttrLoc;
127     DefaultMapAttributes DefaultMapAttr = DMA_unspecified;
128     SourceLocation DefaultMapAttrLoc;
129     OpenMPDirectiveKind Directive = OMPD_unknown;
130     DeclarationNameInfo DirectiveName;
131     Scope *CurScope = nullptr;
132     SourceLocation ConstructLoc;
133     /// Set of 'depend' clauses with 'sink|source' dependence kind. Required to
134     /// get the data (loop counters etc.) about enclosing loop-based construct.
135     /// This data is required during codegen.
136     DoacrossDependMapTy DoacrossDepends;
137     /// first argument (Expr *) contains optional argument of the
138     /// 'ordered' clause, the second one is true if the regions has 'ordered'
139     /// clause, false otherwise.
140     llvm::PointerIntPair<const Expr *, 1, bool> OrderedRegion;
141     bool NowaitRegion = false;
142     bool CancelRegion = false;
143     unsigned AssociatedLoops = 1;
144     SourceLocation InnerTeamsRegionLoc;
145     /// Reference to the taskgroup task_reduction reference expression.
146     Expr *TaskgroupReductionRef = nullptr;
147     SharingMapTy(OpenMPDirectiveKind DKind, DeclarationNameInfo Name,
148                  Scope *CurScope, SourceLocation Loc)
149         : Directive(DKind), DirectiveName(Name), CurScope(CurScope),
150           ConstructLoc(Loc) {}
151     SharingMapTy() = default;
152   };
153 
154   using StackTy = SmallVector<SharingMapTy, 4>;
155 
156   /// Stack of used declaration and their data-sharing attributes.
157   DeclSAMapTy Threadprivates;
158   const FunctionScopeInfo *CurrentNonCapturingFunctionScope = nullptr;
159   SmallVector<std::pair<StackTy, const FunctionScopeInfo *>, 4> Stack;
160   /// true, if check for DSA must be from parent directive, false, if
161   /// from current directive.
162   OpenMPClauseKind ClauseKindMode = OMPC_unknown;
163   Sema &SemaRef;
164   bool ForceCapturing = false;
165   CriticalsWithHintsTy Criticals;
166 
167   using iterator = StackTy::const_reverse_iterator;
168 
169   DSAVarData getDSA(iterator &Iter, ValueDecl *D) const;
170 
171   /// Checks if the variable is a local for OpenMP region.
172   bool isOpenMPLocal(VarDecl *D, iterator Iter) const;
173 
174   bool isStackEmpty() const {
175     return Stack.empty() ||
176            Stack.back().second != CurrentNonCapturingFunctionScope ||
177            Stack.back().first.empty();
178   }
179 
180 public:
181   explicit DSAStackTy(Sema &S) : SemaRef(S) {}
182 
183   bool isClauseParsingMode() const { return ClauseKindMode != OMPC_unknown; }
184   OpenMPClauseKind getClauseParsingMode() const {
185     assert(isClauseParsingMode() && "Must be in clause parsing mode.");
186     return ClauseKindMode;
187   }
188   void setClauseParsingMode(OpenMPClauseKind K) { ClauseKindMode = K; }
189 
190   bool isForceVarCapturing() const { return ForceCapturing; }
191   void setForceVarCapturing(bool V) { ForceCapturing = V; }
192 
193   void push(OpenMPDirectiveKind DKind, const DeclarationNameInfo &DirName,
194             Scope *CurScope, SourceLocation Loc) {
195     if (Stack.empty() ||
196         Stack.back().second != CurrentNonCapturingFunctionScope)
197       Stack.emplace_back(StackTy(), CurrentNonCapturingFunctionScope);
198     Stack.back().first.emplace_back(DKind, DirName, CurScope, Loc);
199     Stack.back().first.back().DefaultAttrLoc = Loc;
200   }
201 
202   void pop() {
203     assert(!Stack.back().first.empty() &&
204            "Data-sharing attributes stack is empty!");
205     Stack.back().first.pop_back();
206   }
207 
208   /// Start new OpenMP region stack in new non-capturing function.
209   void pushFunction() {
210     const FunctionScopeInfo *CurFnScope = SemaRef.getCurFunction();
211     assert(!isa<CapturingScopeInfo>(CurFnScope));
212     CurrentNonCapturingFunctionScope = CurFnScope;
213   }
214   /// Pop region stack for non-capturing function.
215   void popFunction(const FunctionScopeInfo *OldFSI) {
216     if (!Stack.empty() && Stack.back().second == OldFSI) {
217       assert(Stack.back().first.empty());
218       Stack.pop_back();
219     }
220     CurrentNonCapturingFunctionScope = nullptr;
221     for (const FunctionScopeInfo *FSI : llvm::reverse(SemaRef.FunctionScopes)) {
222       if (!isa<CapturingScopeInfo>(FSI)) {
223         CurrentNonCapturingFunctionScope = FSI;
224         break;
225       }
226     }
227   }
228 
229   void addCriticalWithHint(const OMPCriticalDirective *D, llvm::APSInt Hint) {
230     Criticals.try_emplace(D->getDirectiveName().getAsString(), D, Hint);
231   }
232   const std::pair<const OMPCriticalDirective *, llvm::APSInt>
233   getCriticalWithHint(const DeclarationNameInfo &Name) const {
234     auto I = Criticals.find(Name.getAsString());
235     if (I != Criticals.end())
236       return I->second;
237     return std::make_pair(nullptr, llvm::APSInt());
238   }
239   /// If 'aligned' declaration for given variable \a D was not seen yet,
240   /// add it and return NULL; otherwise return previous occurrence's expression
241   /// for diagnostics.
242   const Expr *addUniqueAligned(const ValueDecl *D, const Expr *NewDE);
243 
244   /// Register specified variable as loop control variable.
245   void addLoopControlVariable(const ValueDecl *D, VarDecl *Capture);
246   /// Check if the specified variable is a loop control variable for
247   /// current region.
248   /// \return The index of the loop control variable in the list of associated
249   /// for-loops (from outer to inner).
250   const LCDeclInfo isLoopControlVariable(const ValueDecl *D) const;
251   /// Check if the specified variable is a loop control variable for
252   /// parent region.
253   /// \return The index of the loop control variable in the list of associated
254   /// for-loops (from outer to inner).
255   const LCDeclInfo isParentLoopControlVariable(const ValueDecl *D) const;
256   /// Get the loop control variable for the I-th loop (or nullptr) in
257   /// parent directive.
258   const ValueDecl *getParentLoopControlVariable(unsigned I) const;
259 
260   /// Adds explicit data sharing attribute to the specified declaration.
261   void addDSA(const ValueDecl *D, const Expr *E, OpenMPClauseKind A,
262               DeclRefExpr *PrivateCopy = nullptr);
263 
264   /// Adds additional information for the reduction items with the reduction id
265   /// represented as an operator.
266   void addTaskgroupReductionData(const ValueDecl *D, SourceRange SR,
267                                  BinaryOperatorKind BOK);
268   /// Adds additional information for the reduction items with the reduction id
269   /// represented as reduction identifier.
270   void addTaskgroupReductionData(const ValueDecl *D, SourceRange SR,
271                                  const Expr *ReductionRef);
272   /// Returns the location and reduction operation from the innermost parent
273   /// region for the given \p D.
274   const DSAVarData
275   getTopMostTaskgroupReductionData(const ValueDecl *D, SourceRange &SR,
276                                    BinaryOperatorKind &BOK,
277                                    Expr *&TaskgroupDescriptor) const;
278   /// Returns the location and reduction operation from the innermost parent
279   /// region for the given \p D.
280   const DSAVarData
281   getTopMostTaskgroupReductionData(const ValueDecl *D, SourceRange &SR,
282                                    const Expr *&ReductionRef,
283                                    Expr *&TaskgroupDescriptor) const;
284   /// Return reduction reference expression for the current taskgroup.
285   Expr *getTaskgroupReductionRef() const {
286     assert(Stack.back().first.back().Directive == OMPD_taskgroup &&
287            "taskgroup reference expression requested for non taskgroup "
288            "directive.");
289     return Stack.back().first.back().TaskgroupReductionRef;
290   }
291   /// Checks if the given \p VD declaration is actually a taskgroup reduction
292   /// descriptor variable at the \p Level of OpenMP regions.
293   bool isTaskgroupReductionRef(const ValueDecl *VD, unsigned Level) const {
294     return Stack.back().first[Level].TaskgroupReductionRef &&
295            cast<DeclRefExpr>(Stack.back().first[Level].TaskgroupReductionRef)
296                    ->getDecl() == VD;
297   }
298 
299   /// Returns data sharing attributes from top of the stack for the
300   /// specified declaration.
301   const DSAVarData getTopDSA(ValueDecl *D, bool FromParent);
302   /// Returns data-sharing attributes for the specified declaration.
303   const DSAVarData getImplicitDSA(ValueDecl *D, bool FromParent) const;
304   /// Checks if the specified variables has data-sharing attributes which
305   /// match specified \a CPred predicate in any directive which matches \a DPred
306   /// predicate.
307   const DSAVarData
308   hasDSA(ValueDecl *D, const llvm::function_ref<bool(OpenMPClauseKind)> CPred,
309          const llvm::function_ref<bool(OpenMPDirectiveKind)> DPred,
310          bool FromParent) const;
311   /// Checks if the specified variables has data-sharing attributes which
312   /// match specified \a CPred predicate in any innermost directive which
313   /// matches \a DPred predicate.
314   const DSAVarData
315   hasInnermostDSA(ValueDecl *D,
316                   const llvm::function_ref<bool(OpenMPClauseKind)> CPred,
317                   const llvm::function_ref<bool(OpenMPDirectiveKind)> DPred,
318                   bool FromParent) const;
319   /// Checks if the specified variables has explicit data-sharing
320   /// attributes which match specified \a CPred predicate at the specified
321   /// OpenMP region.
322   bool hasExplicitDSA(const ValueDecl *D,
323                       const llvm::function_ref<bool(OpenMPClauseKind)> CPred,
324                       unsigned Level, bool NotLastprivate = false) const;
325 
326   /// Returns true if the directive at level \Level matches in the
327   /// specified \a DPred predicate.
328   bool hasExplicitDirective(
329       const llvm::function_ref<bool(OpenMPDirectiveKind)> DPred,
330       unsigned Level) const;
331 
332   /// Finds a directive which matches specified \a DPred predicate.
333   bool hasDirective(
334       const llvm::function_ref<bool(
335           OpenMPDirectiveKind, const DeclarationNameInfo &, SourceLocation)>
336           DPred,
337       bool FromParent) const;
338 
339   /// Returns currently analyzed directive.
340   OpenMPDirectiveKind getCurrentDirective() const {
341     return isStackEmpty() ? OMPD_unknown : Stack.back().first.back().Directive;
342   }
343   /// Returns directive kind at specified level.
344   OpenMPDirectiveKind getDirective(unsigned Level) const {
345     assert(!isStackEmpty() && "No directive at specified level.");
346     return Stack.back().first[Level].Directive;
347   }
348   /// Returns parent directive.
349   OpenMPDirectiveKind getParentDirective() const {
350     if (isStackEmpty() || Stack.back().first.size() == 1)
351       return OMPD_unknown;
352     return std::next(Stack.back().first.rbegin())->Directive;
353   }
354 
355   /// Set default data sharing attribute to none.
356   void setDefaultDSANone(SourceLocation Loc) {
357     assert(!isStackEmpty());
358     Stack.back().first.back().DefaultAttr = DSA_none;
359     Stack.back().first.back().DefaultAttrLoc = Loc;
360   }
361   /// Set default data sharing attribute to shared.
362   void setDefaultDSAShared(SourceLocation Loc) {
363     assert(!isStackEmpty());
364     Stack.back().first.back().DefaultAttr = DSA_shared;
365     Stack.back().first.back().DefaultAttrLoc = Loc;
366   }
367   /// Set default data mapping attribute to 'tofrom:scalar'.
368   void setDefaultDMAToFromScalar(SourceLocation Loc) {
369     assert(!isStackEmpty());
370     Stack.back().first.back().DefaultMapAttr = DMA_tofrom_scalar;
371     Stack.back().first.back().DefaultMapAttrLoc = Loc;
372   }
373 
374   DefaultDataSharingAttributes getDefaultDSA() const {
375     return isStackEmpty() ? DSA_unspecified
376                           : Stack.back().first.back().DefaultAttr;
377   }
378   SourceLocation getDefaultDSALocation() const {
379     return isStackEmpty() ? SourceLocation()
380                           : Stack.back().first.back().DefaultAttrLoc;
381   }
382   DefaultMapAttributes getDefaultDMA() const {
383     return isStackEmpty() ? DMA_unspecified
384                           : Stack.back().first.back().DefaultMapAttr;
385   }
386   DefaultMapAttributes getDefaultDMAAtLevel(unsigned Level) const {
387     return Stack.back().first[Level].DefaultMapAttr;
388   }
389   SourceLocation getDefaultDMALocation() const {
390     return isStackEmpty() ? SourceLocation()
391                           : Stack.back().first.back().DefaultMapAttrLoc;
392   }
393 
394   /// Checks if the specified variable is a threadprivate.
395   bool isThreadPrivate(VarDecl *D) {
396     const DSAVarData DVar = getTopDSA(D, false);
397     return isOpenMPThreadPrivate(DVar.CKind);
398   }
399 
400   /// Marks current region as ordered (it has an 'ordered' clause).
401   void setOrderedRegion(bool IsOrdered, const Expr *Param) {
402     assert(!isStackEmpty());
403     Stack.back().first.back().OrderedRegion.setInt(IsOrdered);
404     Stack.back().first.back().OrderedRegion.setPointer(Param);
405   }
406   /// Returns true, if parent region is ordered (has associated
407   /// 'ordered' clause), false - otherwise.
408   bool isParentOrderedRegion() const {
409     if (isStackEmpty() || Stack.back().first.size() == 1)
410       return false;
411     return std::next(Stack.back().first.rbegin())->OrderedRegion.getInt();
412   }
413   /// Returns optional parameter for the ordered region.
414   const Expr *getParentOrderedRegionParam() const {
415     if (isStackEmpty() || Stack.back().first.size() == 1)
416       return nullptr;
417     return std::next(Stack.back().first.rbegin())->OrderedRegion.getPointer();
418   }
419   /// Marks current region as nowait (it has a 'nowait' clause).
420   void setNowaitRegion(bool IsNowait = true) {
421     assert(!isStackEmpty());
422     Stack.back().first.back().NowaitRegion = IsNowait;
423   }
424   /// Returns true, if parent region is nowait (has associated
425   /// 'nowait' clause), false - otherwise.
426   bool isParentNowaitRegion() const {
427     if (isStackEmpty() || Stack.back().first.size() == 1)
428       return false;
429     return std::next(Stack.back().first.rbegin())->NowaitRegion;
430   }
431   /// Marks parent region as cancel region.
432   void setParentCancelRegion(bool Cancel = true) {
433     if (!isStackEmpty() && Stack.back().first.size() > 1) {
434       auto &StackElemRef = *std::next(Stack.back().first.rbegin());
435       StackElemRef.CancelRegion |= StackElemRef.CancelRegion || Cancel;
436     }
437   }
438   /// Return true if current region has inner cancel construct.
439   bool isCancelRegion() const {
440     return isStackEmpty() ? false : Stack.back().first.back().CancelRegion;
441   }
442 
443   /// Set collapse value for the region.
444   void setAssociatedLoops(unsigned Val) {
445     assert(!isStackEmpty());
446     Stack.back().first.back().AssociatedLoops = Val;
447   }
448   /// Return collapse value for region.
449   unsigned getAssociatedLoops() const {
450     return isStackEmpty() ? 0 : Stack.back().first.back().AssociatedLoops;
451   }
452 
453   /// Marks current target region as one with closely nested teams
454   /// region.
455   void setParentTeamsRegionLoc(SourceLocation TeamsRegionLoc) {
456     if (!isStackEmpty() && Stack.back().first.size() > 1) {
457       std::next(Stack.back().first.rbegin())->InnerTeamsRegionLoc =
458           TeamsRegionLoc;
459     }
460   }
461   /// Returns true, if current region has closely nested teams region.
462   bool hasInnerTeamsRegion() const {
463     return getInnerTeamsRegionLoc().isValid();
464   }
465   /// Returns location of the nested teams region (if any).
466   SourceLocation getInnerTeamsRegionLoc() const {
467     return isStackEmpty() ? SourceLocation()
468                           : Stack.back().first.back().InnerTeamsRegionLoc;
469   }
470 
471   Scope *getCurScope() const {
472     return isStackEmpty() ? nullptr : Stack.back().first.back().CurScope;
473   }
474   SourceLocation getConstructLoc() const {
475     return isStackEmpty() ? SourceLocation()
476                           : Stack.back().first.back().ConstructLoc;
477   }
478 
479   /// Do the check specified in \a Check to all component lists and return true
480   /// if any issue is found.
481   bool checkMappableExprComponentListsForDecl(
482       const ValueDecl *VD, bool CurrentRegionOnly,
483       const llvm::function_ref<
484           bool(OMPClauseMappableExprCommon::MappableExprComponentListRef,
485                OpenMPClauseKind)>
486           Check) const {
487     if (isStackEmpty())
488       return false;
489     auto SI = Stack.back().first.rbegin();
490     auto SE = Stack.back().first.rend();
491 
492     if (SI == SE)
493       return false;
494 
495     if (CurrentRegionOnly)
496       SE = std::next(SI);
497     else
498       std::advance(SI, 1);
499 
500     for (; SI != SE; ++SI) {
501       auto MI = SI->MappedExprComponents.find(VD);
502       if (MI != SI->MappedExprComponents.end())
503         for (OMPClauseMappableExprCommon::MappableExprComponentListRef L :
504              MI->second.Components)
505           if (Check(L, MI->second.Kind))
506             return true;
507     }
508     return false;
509   }
510 
511   /// Do the check specified in \a Check to all component lists at a given level
512   /// and return true if any issue is found.
513   bool checkMappableExprComponentListsForDeclAtLevel(
514       const ValueDecl *VD, unsigned Level,
515       const llvm::function_ref<
516           bool(OMPClauseMappableExprCommon::MappableExprComponentListRef,
517                OpenMPClauseKind)>
518           Check) const {
519     if (isStackEmpty())
520       return false;
521 
522     auto StartI = Stack.back().first.begin();
523     auto EndI = Stack.back().first.end();
524     if (std::distance(StartI, EndI) <= (int)Level)
525       return false;
526     std::advance(StartI, Level);
527 
528     auto MI = StartI->MappedExprComponents.find(VD);
529     if (MI != StartI->MappedExprComponents.end())
530       for (OMPClauseMappableExprCommon::MappableExprComponentListRef L :
531            MI->second.Components)
532         if (Check(L, MI->second.Kind))
533           return true;
534     return false;
535   }
536 
537   /// Create a new mappable expression component list associated with a given
538   /// declaration and initialize it with the provided list of components.
539   void addMappableExpressionComponents(
540       const ValueDecl *VD,
541       OMPClauseMappableExprCommon::MappableExprComponentListRef Components,
542       OpenMPClauseKind WhereFoundClauseKind) {
543     assert(!isStackEmpty() &&
544            "Not expecting to retrieve components from a empty stack!");
545     MappedExprComponentTy &MEC =
546         Stack.back().first.back().MappedExprComponents[VD];
547     // Create new entry and append the new components there.
548     MEC.Components.resize(MEC.Components.size() + 1);
549     MEC.Components.back().append(Components.begin(), Components.end());
550     MEC.Kind = WhereFoundClauseKind;
551   }
552 
553   unsigned getNestingLevel() const {
554     assert(!isStackEmpty());
555     return Stack.back().first.size() - 1;
556   }
557   void addDoacrossDependClause(OMPDependClause *C,
558                                const OperatorOffsetTy &OpsOffs) {
559     assert(!isStackEmpty() && Stack.back().first.size() > 1);
560     SharingMapTy &StackElem = *std::next(Stack.back().first.rbegin());
561     assert(isOpenMPWorksharingDirective(StackElem.Directive));
562     StackElem.DoacrossDepends.try_emplace(C, OpsOffs);
563   }
564   llvm::iterator_range<DoacrossDependMapTy::const_iterator>
565   getDoacrossDependClauses() const {
566     assert(!isStackEmpty());
567     const SharingMapTy &StackElem = Stack.back().first.back();
568     if (isOpenMPWorksharingDirective(StackElem.Directive)) {
569       const DoacrossDependMapTy &Ref = StackElem.DoacrossDepends;
570       return llvm::make_range(Ref.begin(), Ref.end());
571     }
572     return llvm::make_range(StackElem.DoacrossDepends.end(),
573                             StackElem.DoacrossDepends.end());
574   }
575 };
576 bool isParallelOrTaskRegion(OpenMPDirectiveKind DKind) {
577   return isOpenMPParallelDirective(DKind) || isOpenMPTaskingDirective(DKind) ||
578          isOpenMPTeamsDirective(DKind) || DKind == OMPD_unknown;
579 }
580 
581 } // namespace
582 
583 static const Expr *getExprAsWritten(const Expr *E) {
584   if (const auto *ExprTemp = dyn_cast<ExprWithCleanups>(E))
585     E = ExprTemp->getSubExpr();
586 
587   if (const auto *MTE = dyn_cast<MaterializeTemporaryExpr>(E))
588     E = MTE->GetTemporaryExpr();
589 
590   while (const auto *Binder = dyn_cast<CXXBindTemporaryExpr>(E))
591     E = Binder->getSubExpr();
592 
593   if (const auto *ICE = dyn_cast<ImplicitCastExpr>(E))
594     E = ICE->getSubExprAsWritten();
595   return E->IgnoreParens();
596 }
597 
598 static Expr *getExprAsWritten(Expr *E) {
599   return const_cast<Expr *>(getExprAsWritten(const_cast<const Expr *>(E)));
600 }
601 
602 static const ValueDecl *getCanonicalDecl(const ValueDecl *D) {
603   if (const auto *CED = dyn_cast<OMPCapturedExprDecl>(D))
604     if (const auto *ME = dyn_cast<MemberExpr>(getExprAsWritten(CED->getInit())))
605       D = ME->getMemberDecl();
606   const auto *VD = dyn_cast<VarDecl>(D);
607   const auto *FD = dyn_cast<FieldDecl>(D);
608   if (VD != nullptr) {
609     VD = VD->getCanonicalDecl();
610     D = VD;
611   } else {
612     assert(FD);
613     FD = FD->getCanonicalDecl();
614     D = FD;
615   }
616   return D;
617 }
618 
619 static ValueDecl *getCanonicalDecl(ValueDecl *D) {
620   return const_cast<ValueDecl *>(
621       getCanonicalDecl(const_cast<const ValueDecl *>(D)));
622 }
623 
624 DSAStackTy::DSAVarData DSAStackTy::getDSA(iterator &Iter,
625                                           ValueDecl *D) const {
626   D = getCanonicalDecl(D);
627   auto *VD = dyn_cast<VarDecl>(D);
628   const auto *FD = dyn_cast<FieldDecl>(D);
629   DSAVarData DVar;
630   if (isStackEmpty() || Iter == Stack.back().first.rend()) {
631     // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
632     // in a region but not in construct]
633     //  File-scope or namespace-scope variables referenced in called routines
634     //  in the region are shared unless they appear in a threadprivate
635     //  directive.
636     if (VD && !VD->isFunctionOrMethodVarDecl() && !isa<ParmVarDecl>(VD))
637       DVar.CKind = OMPC_shared;
638 
639     // OpenMP [2.9.1.2, Data-sharing Attribute Rules for Variables Referenced
640     // in a region but not in construct]
641     //  Variables with static storage duration that are declared in called
642     //  routines in the region are shared.
643     if (VD && VD->hasGlobalStorage())
644       DVar.CKind = OMPC_shared;
645 
646     // Non-static data members are shared by default.
647     if (FD)
648       DVar.CKind = OMPC_shared;
649 
650     return DVar;
651   }
652 
653   // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
654   // in a Construct, C/C++, predetermined, p.1]
655   // Variables with automatic storage duration that are declared in a scope
656   // inside the construct are private.
657   if (VD && isOpenMPLocal(VD, Iter) && VD->isLocalVarDecl() &&
658       (VD->getStorageClass() == SC_Auto || VD->getStorageClass() == SC_None)) {
659     DVar.CKind = OMPC_private;
660     return DVar;
661   }
662 
663   DVar.DKind = Iter->Directive;
664   // Explicitly specified attributes and local variables with predetermined
665   // attributes.
666   if (Iter->SharingMap.count(D)) {
667     const DSAInfo &Data = Iter->SharingMap.lookup(D);
668     DVar.RefExpr = Data.RefExpr.getPointer();
669     DVar.PrivateCopy = Data.PrivateCopy;
670     DVar.CKind = Data.Attributes;
671     DVar.ImplicitDSALoc = Iter->DefaultAttrLoc;
672     return DVar;
673   }
674 
675   // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
676   // in a Construct, C/C++, implicitly determined, p.1]
677   //  In a parallel or task construct, the data-sharing attributes of these
678   //  variables are determined by the default clause, if present.
679   switch (Iter->DefaultAttr) {
680   case DSA_shared:
681     DVar.CKind = OMPC_shared;
682     DVar.ImplicitDSALoc = Iter->DefaultAttrLoc;
683     return DVar;
684   case DSA_none:
685     return DVar;
686   case DSA_unspecified:
687     // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
688     // in a Construct, implicitly determined, p.2]
689     //  In a parallel construct, if no default clause is present, these
690     //  variables are shared.
691     DVar.ImplicitDSALoc = Iter->DefaultAttrLoc;
692     if (isOpenMPParallelDirective(DVar.DKind) ||
693         isOpenMPTeamsDirective(DVar.DKind)) {
694       DVar.CKind = OMPC_shared;
695       return DVar;
696     }
697 
698     // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
699     // in a Construct, implicitly determined, p.4]
700     //  In a task construct, if no default clause is present, a variable that in
701     //  the enclosing context is determined to be shared by all implicit tasks
702     //  bound to the current team is shared.
703     if (isOpenMPTaskingDirective(DVar.DKind)) {
704       DSAVarData DVarTemp;
705       iterator I = Iter, E = Stack.back().first.rend();
706       do {
707         ++I;
708         // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables
709         // Referenced in a Construct, implicitly determined, p.6]
710         //  In a task construct, if no default clause is present, a variable
711         //  whose data-sharing attribute is not determined by the rules above is
712         //  firstprivate.
713         DVarTemp = getDSA(I, D);
714         if (DVarTemp.CKind != OMPC_shared) {
715           DVar.RefExpr = nullptr;
716           DVar.CKind = OMPC_firstprivate;
717           return DVar;
718         }
719       } while (I != E && !isParallelOrTaskRegion(I->Directive));
720       DVar.CKind =
721           (DVarTemp.CKind == OMPC_unknown) ? OMPC_firstprivate : OMPC_shared;
722       return DVar;
723     }
724   }
725   // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
726   // in a Construct, implicitly determined, p.3]
727   //  For constructs other than task, if no default clause is present, these
728   //  variables inherit their data-sharing attributes from the enclosing
729   //  context.
730   return getDSA(++Iter, D);
731 }
732 
733 const Expr *DSAStackTy::addUniqueAligned(const ValueDecl *D,
734                                          const Expr *NewDE) {
735   assert(!isStackEmpty() && "Data sharing attributes stack is empty");
736   D = getCanonicalDecl(D);
737   SharingMapTy &StackElem = Stack.back().first.back();
738   auto It = StackElem.AlignedMap.find(D);
739   if (It == StackElem.AlignedMap.end()) {
740     assert(NewDE && "Unexpected nullptr expr to be added into aligned map");
741     StackElem.AlignedMap[D] = NewDE;
742     return nullptr;
743   }
744   assert(It->second && "Unexpected nullptr expr in the aligned map");
745   return It->second;
746 }
747 
748 void DSAStackTy::addLoopControlVariable(const ValueDecl *D, VarDecl *Capture) {
749   assert(!isStackEmpty() && "Data-sharing attributes stack is empty");
750   D = getCanonicalDecl(D);
751   SharingMapTy &StackElem = Stack.back().first.back();
752   StackElem.LCVMap.try_emplace(
753       D, LCDeclInfo(StackElem.LCVMap.size() + 1, Capture));
754 }
755 
756 const DSAStackTy::LCDeclInfo
757 DSAStackTy::isLoopControlVariable(const ValueDecl *D) const {
758   assert(!isStackEmpty() && "Data-sharing attributes stack is empty");
759   D = getCanonicalDecl(D);
760   const SharingMapTy &StackElem = Stack.back().first.back();
761   auto It = StackElem.LCVMap.find(D);
762   if (It != StackElem.LCVMap.end())
763     return It->second;
764   return {0, nullptr};
765 }
766 
767 const DSAStackTy::LCDeclInfo
768 DSAStackTy::isParentLoopControlVariable(const ValueDecl *D) const {
769   assert(!isStackEmpty() && Stack.back().first.size() > 1 &&
770          "Data-sharing attributes stack is empty");
771   D = getCanonicalDecl(D);
772   const SharingMapTy &StackElem = *std::next(Stack.back().first.rbegin());
773   auto It = StackElem.LCVMap.find(D);
774   if (It != StackElem.LCVMap.end())
775     return It->second;
776   return {0, nullptr};
777 }
778 
779 const ValueDecl *DSAStackTy::getParentLoopControlVariable(unsigned I) const {
780   assert(!isStackEmpty() && Stack.back().first.size() > 1 &&
781          "Data-sharing attributes stack is empty");
782   const SharingMapTy &StackElem = *std::next(Stack.back().first.rbegin());
783   if (StackElem.LCVMap.size() < I)
784     return nullptr;
785   for (const auto &Pair : StackElem.LCVMap)
786     if (Pair.second.first == I)
787       return Pair.first;
788   return nullptr;
789 }
790 
791 void DSAStackTy::addDSA(const ValueDecl *D, const Expr *E, OpenMPClauseKind A,
792                         DeclRefExpr *PrivateCopy) {
793   D = getCanonicalDecl(D);
794   if (A == OMPC_threadprivate) {
795     DSAInfo &Data = Threadprivates[D];
796     Data.Attributes = A;
797     Data.RefExpr.setPointer(E);
798     Data.PrivateCopy = nullptr;
799   } else {
800     assert(!isStackEmpty() && "Data-sharing attributes stack is empty");
801     DSAInfo &Data = Stack.back().first.back().SharingMap[D];
802     assert(Data.Attributes == OMPC_unknown || (A == Data.Attributes) ||
803            (A == OMPC_firstprivate && Data.Attributes == OMPC_lastprivate) ||
804            (A == OMPC_lastprivate && Data.Attributes == OMPC_firstprivate) ||
805            (isLoopControlVariable(D).first && A == OMPC_private));
806     if (A == OMPC_lastprivate && Data.Attributes == OMPC_firstprivate) {
807       Data.RefExpr.setInt(/*IntVal=*/true);
808       return;
809     }
810     const bool IsLastprivate =
811         A == OMPC_lastprivate || Data.Attributes == OMPC_lastprivate;
812     Data.Attributes = A;
813     Data.RefExpr.setPointerAndInt(E, IsLastprivate);
814     Data.PrivateCopy = PrivateCopy;
815     if (PrivateCopy) {
816       DSAInfo &Data =
817           Stack.back().first.back().SharingMap[PrivateCopy->getDecl()];
818       Data.Attributes = A;
819       Data.RefExpr.setPointerAndInt(PrivateCopy, IsLastprivate);
820       Data.PrivateCopy = nullptr;
821     }
822   }
823 }
824 
825 /// Build a variable declaration for OpenMP loop iteration variable.
826 static VarDecl *buildVarDecl(Sema &SemaRef, SourceLocation Loc, QualType Type,
827                              StringRef Name, const AttrVec *Attrs = nullptr,
828                              DeclRefExpr *OrigRef = nullptr) {
829   DeclContext *DC = SemaRef.CurContext;
830   IdentifierInfo *II = &SemaRef.PP.getIdentifierTable().get(Name);
831   TypeSourceInfo *TInfo = SemaRef.Context.getTrivialTypeSourceInfo(Type, Loc);
832   auto *Decl =
833       VarDecl::Create(SemaRef.Context, DC, Loc, Loc, II, Type, TInfo, SC_None);
834   if (Attrs) {
835     for (specific_attr_iterator<AlignedAttr> I(Attrs->begin()), E(Attrs->end());
836          I != E; ++I)
837       Decl->addAttr(*I);
838   }
839   Decl->setImplicit();
840   if (OrigRef) {
841     Decl->addAttr(
842         OMPReferencedVarAttr::CreateImplicit(SemaRef.Context, OrigRef));
843   }
844   return Decl;
845 }
846 
847 static DeclRefExpr *buildDeclRefExpr(Sema &S, VarDecl *D, QualType Ty,
848                                      SourceLocation Loc,
849                                      bool RefersToCapture = false) {
850   D->setReferenced();
851   D->markUsed(S.Context);
852   return DeclRefExpr::Create(S.getASTContext(), NestedNameSpecifierLoc(),
853                              SourceLocation(), D, RefersToCapture, Loc, Ty,
854                              VK_LValue);
855 }
856 
857 void DSAStackTy::addTaskgroupReductionData(const ValueDecl *D, SourceRange SR,
858                                            BinaryOperatorKind BOK) {
859   D = getCanonicalDecl(D);
860   assert(!isStackEmpty() && "Data-sharing attributes stack is empty");
861   assert(
862       Stack.back().first.back().SharingMap[D].Attributes == OMPC_reduction &&
863       "Additional reduction info may be specified only for reduction items.");
864   ReductionData &ReductionData = Stack.back().first.back().ReductionMap[D];
865   assert(ReductionData.ReductionRange.isInvalid() &&
866          Stack.back().first.back().Directive == OMPD_taskgroup &&
867          "Additional reduction info may be specified only once for reduction "
868          "items.");
869   ReductionData.set(BOK, SR);
870   Expr *&TaskgroupReductionRef =
871       Stack.back().first.back().TaskgroupReductionRef;
872   if (!TaskgroupReductionRef) {
873     VarDecl *VD = buildVarDecl(SemaRef, SR.getBegin(),
874                                SemaRef.Context.VoidPtrTy, ".task_red.");
875     TaskgroupReductionRef =
876         buildDeclRefExpr(SemaRef, VD, SemaRef.Context.VoidPtrTy, SR.getBegin());
877   }
878 }
879 
880 void DSAStackTy::addTaskgroupReductionData(const ValueDecl *D, SourceRange SR,
881                                            const Expr *ReductionRef) {
882   D = getCanonicalDecl(D);
883   assert(!isStackEmpty() && "Data-sharing attributes stack is empty");
884   assert(
885       Stack.back().first.back().SharingMap[D].Attributes == OMPC_reduction &&
886       "Additional reduction info may be specified only for reduction items.");
887   ReductionData &ReductionData = Stack.back().first.back().ReductionMap[D];
888   assert(ReductionData.ReductionRange.isInvalid() &&
889          Stack.back().first.back().Directive == OMPD_taskgroup &&
890          "Additional reduction info may be specified only once for reduction "
891          "items.");
892   ReductionData.set(ReductionRef, SR);
893   Expr *&TaskgroupReductionRef =
894       Stack.back().first.back().TaskgroupReductionRef;
895   if (!TaskgroupReductionRef) {
896     VarDecl *VD = buildVarDecl(SemaRef, SR.getBegin(),
897                                SemaRef.Context.VoidPtrTy, ".task_red.");
898     TaskgroupReductionRef =
899         buildDeclRefExpr(SemaRef, VD, SemaRef.Context.VoidPtrTy, SR.getBegin());
900   }
901 }
902 
903 const DSAStackTy::DSAVarData DSAStackTy::getTopMostTaskgroupReductionData(
904     const ValueDecl *D, SourceRange &SR, BinaryOperatorKind &BOK,
905     Expr *&TaskgroupDescriptor) const {
906   D = getCanonicalDecl(D);
907   assert(!isStackEmpty() && "Data-sharing attributes stack is empty.");
908   if (Stack.back().first.empty())
909       return DSAVarData();
910   for (iterator I = std::next(Stack.back().first.rbegin(), 1),
911                 E = Stack.back().first.rend();
912        I != E; std::advance(I, 1)) {
913     const DSAInfo &Data = I->SharingMap.lookup(D);
914     if (Data.Attributes != OMPC_reduction || I->Directive != OMPD_taskgroup)
915       continue;
916     const ReductionData &ReductionData = I->ReductionMap.lookup(D);
917     if (!ReductionData.ReductionOp ||
918         ReductionData.ReductionOp.is<const Expr *>())
919       return DSAVarData();
920     SR = ReductionData.ReductionRange;
921     BOK = ReductionData.ReductionOp.get<ReductionData::BOKPtrType>();
922     assert(I->TaskgroupReductionRef && "taskgroup reduction reference "
923                                        "expression for the descriptor is not "
924                                        "set.");
925     TaskgroupDescriptor = I->TaskgroupReductionRef;
926     return DSAVarData(OMPD_taskgroup, OMPC_reduction, Data.RefExpr.getPointer(),
927                       Data.PrivateCopy, I->DefaultAttrLoc);
928   }
929   return DSAVarData();
930 }
931 
932 const DSAStackTy::DSAVarData DSAStackTy::getTopMostTaskgroupReductionData(
933     const ValueDecl *D, SourceRange &SR, const Expr *&ReductionRef,
934     Expr *&TaskgroupDescriptor) const {
935   D = getCanonicalDecl(D);
936   assert(!isStackEmpty() && "Data-sharing attributes stack is empty.");
937   if (Stack.back().first.empty())
938       return DSAVarData();
939   for (iterator I = std::next(Stack.back().first.rbegin(), 1),
940                 E = Stack.back().first.rend();
941        I != E; std::advance(I, 1)) {
942     const DSAInfo &Data = I->SharingMap.lookup(D);
943     if (Data.Attributes != OMPC_reduction || I->Directive != OMPD_taskgroup)
944       continue;
945     const ReductionData &ReductionData = I->ReductionMap.lookup(D);
946     if (!ReductionData.ReductionOp ||
947         !ReductionData.ReductionOp.is<const Expr *>())
948       return DSAVarData();
949     SR = ReductionData.ReductionRange;
950     ReductionRef = ReductionData.ReductionOp.get<const Expr *>();
951     assert(I->TaskgroupReductionRef && "taskgroup reduction reference "
952                                        "expression for the descriptor is not "
953                                        "set.");
954     TaskgroupDescriptor = I->TaskgroupReductionRef;
955     return DSAVarData(OMPD_taskgroup, OMPC_reduction, Data.RefExpr.getPointer(),
956                       Data.PrivateCopy, I->DefaultAttrLoc);
957   }
958   return DSAVarData();
959 }
960 
961 bool DSAStackTy::isOpenMPLocal(VarDecl *D, iterator Iter) const {
962   D = D->getCanonicalDecl();
963   if (!isStackEmpty()) {
964     iterator I = Iter, E = Stack.back().first.rend();
965     Scope *TopScope = nullptr;
966     while (I != E && !isParallelOrTaskRegion(I->Directive) &&
967            !isOpenMPTargetExecutionDirective(I->Directive))
968       ++I;
969     if (I == E)
970       return false;
971     TopScope = I->CurScope ? I->CurScope->getParent() : nullptr;
972     Scope *CurScope = getCurScope();
973     while (CurScope != TopScope && !CurScope->isDeclScope(D))
974       CurScope = CurScope->getParent();
975     return CurScope != TopScope;
976   }
977   return false;
978 }
979 
980 const DSAStackTy::DSAVarData DSAStackTy::getTopDSA(ValueDecl *D,
981                                                    bool FromParent) {
982   D = getCanonicalDecl(D);
983   DSAVarData DVar;
984 
985   auto *VD = dyn_cast<VarDecl>(D);
986   auto TI = Threadprivates.find(D);
987   if (TI != Threadprivates.end()) {
988     DVar.RefExpr = TI->getSecond().RefExpr.getPointer();
989     DVar.CKind = OMPC_threadprivate;
990     return DVar;
991   }
992   if (VD && VD->hasAttr<OMPThreadPrivateDeclAttr>()) {
993     DVar.RefExpr = buildDeclRefExpr(
994         SemaRef, VD, D->getType().getNonReferenceType(),
995         VD->getAttr<OMPThreadPrivateDeclAttr>()->getLocation());
996     DVar.CKind = OMPC_threadprivate;
997     addDSA(D, DVar.RefExpr, OMPC_threadprivate);
998     return DVar;
999   }
1000   // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
1001   // in a Construct, C/C++, predetermined, p.1]
1002   //  Variables appearing in threadprivate directives are threadprivate.
1003   if ((VD && VD->getTLSKind() != VarDecl::TLS_None &&
1004        !(VD->hasAttr<OMPThreadPrivateDeclAttr>() &&
1005          SemaRef.getLangOpts().OpenMPUseTLS &&
1006          SemaRef.getASTContext().getTargetInfo().isTLSSupported())) ||
1007       (VD && VD->getStorageClass() == SC_Register &&
1008        VD->hasAttr<AsmLabelAttr>() && !VD->isLocalVarDecl())) {
1009     DVar.RefExpr = buildDeclRefExpr(
1010         SemaRef, VD, D->getType().getNonReferenceType(), D->getLocation());
1011     DVar.CKind = OMPC_threadprivate;
1012     addDSA(D, DVar.RefExpr, OMPC_threadprivate);
1013     return DVar;
1014   }
1015   if (SemaRef.getLangOpts().OpenMPCUDAMode && VD &&
1016       VD->isLocalVarDeclOrParm() && !isStackEmpty() &&
1017       !isLoopControlVariable(D).first) {
1018     iterator IterTarget =
1019         std::find_if(Stack.back().first.rbegin(), Stack.back().first.rend(),
1020                      [](const SharingMapTy &Data) {
1021                        return isOpenMPTargetExecutionDirective(Data.Directive);
1022                      });
1023     if (IterTarget != Stack.back().first.rend()) {
1024       iterator ParentIterTarget = std::next(IterTarget, 1);
1025       for (iterator Iter = Stack.back().first.rbegin();
1026            Iter != ParentIterTarget; std::advance(Iter, 1)) {
1027         if (isOpenMPLocal(VD, Iter)) {
1028           DVar.RefExpr =
1029               buildDeclRefExpr(SemaRef, VD, D->getType().getNonReferenceType(),
1030                                D->getLocation());
1031           DVar.CKind = OMPC_threadprivate;
1032           return DVar;
1033         }
1034       }
1035       if (!isClauseParsingMode() || IterTarget != Stack.back().first.rbegin()) {
1036         auto DSAIter = IterTarget->SharingMap.find(D);
1037         if (DSAIter != IterTarget->SharingMap.end() &&
1038             isOpenMPPrivate(DSAIter->getSecond().Attributes)) {
1039           DVar.RefExpr = DSAIter->getSecond().RefExpr.getPointer();
1040           DVar.CKind = OMPC_threadprivate;
1041           return DVar;
1042         }
1043         iterator End = Stack.back().first.rend();
1044         if (!SemaRef.isOpenMPCapturedByRef(
1045                 D, std::distance(ParentIterTarget, End))) {
1046           DVar.RefExpr =
1047               buildDeclRefExpr(SemaRef, VD, D->getType().getNonReferenceType(),
1048                                IterTarget->ConstructLoc);
1049           DVar.CKind = OMPC_threadprivate;
1050           return DVar;
1051         }
1052       }
1053     }
1054   }
1055 
1056   if (isStackEmpty())
1057     // Not in OpenMP execution region and top scope was already checked.
1058     return DVar;
1059 
1060   // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
1061   // in a Construct, C/C++, predetermined, p.4]
1062   //  Static data members are shared.
1063   // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
1064   // in a Construct, C/C++, predetermined, p.7]
1065   //  Variables with static storage duration that are declared in a scope
1066   //  inside the construct are shared.
1067   auto &&MatchesAlways = [](OpenMPDirectiveKind) { return true; };
1068   if (VD && VD->isStaticDataMember()) {
1069     DSAVarData DVarTemp = hasDSA(D, isOpenMPPrivate, MatchesAlways, FromParent);
1070     if (DVarTemp.CKind != OMPC_unknown && DVarTemp.RefExpr)
1071       return DVar;
1072 
1073     DVar.CKind = OMPC_shared;
1074     return DVar;
1075   }
1076 
1077   QualType Type = D->getType().getNonReferenceType().getCanonicalType();
1078   bool IsConstant = Type.isConstant(SemaRef.getASTContext());
1079   Type = SemaRef.getASTContext().getBaseElementType(Type);
1080   // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
1081   // in a Construct, C/C++, predetermined, p.6]
1082   //  Variables with const qualified type having no mutable member are
1083   //  shared.
1084   const CXXRecordDecl *RD =
1085       SemaRef.getLangOpts().CPlusPlus ? Type->getAsCXXRecordDecl() : nullptr;
1086   if (const auto *CTSD = dyn_cast_or_null<ClassTemplateSpecializationDecl>(RD))
1087     if (const ClassTemplateDecl *CTD = CTSD->getSpecializedTemplate())
1088       RD = CTD->getTemplatedDecl();
1089   if (IsConstant &&
1090       !(SemaRef.getLangOpts().CPlusPlus && RD && RD->hasDefinition() &&
1091         RD->hasMutableFields())) {
1092     // Variables with const-qualified type having no mutable member may be
1093     // listed in a firstprivate clause, even if they are static data members.
1094     DSAVarData DVarTemp =
1095         hasDSA(D, [](OpenMPClauseKind C) { return C == OMPC_firstprivate; },
1096                MatchesAlways, FromParent);
1097     if (DVarTemp.CKind == OMPC_firstprivate && DVarTemp.RefExpr)
1098       return DVarTemp;
1099 
1100     DVar.CKind = OMPC_shared;
1101     return DVar;
1102   }
1103 
1104   // Explicitly specified attributes and local variables with predetermined
1105   // attributes.
1106   iterator I = Stack.back().first.rbegin();
1107   iterator EndI = Stack.back().first.rend();
1108   if (FromParent && I != EndI)
1109     std::advance(I, 1);
1110   auto It = I->SharingMap.find(D);
1111   if (It != I->SharingMap.end()) {
1112     const DSAInfo &Data = It->getSecond();
1113     DVar.RefExpr = Data.RefExpr.getPointer();
1114     DVar.PrivateCopy = Data.PrivateCopy;
1115     DVar.CKind = Data.Attributes;
1116     DVar.ImplicitDSALoc = I->DefaultAttrLoc;
1117     DVar.DKind = I->Directive;
1118   }
1119 
1120   return DVar;
1121 }
1122 
1123 const DSAStackTy::DSAVarData DSAStackTy::getImplicitDSA(ValueDecl *D,
1124                                                         bool FromParent) const {
1125   if (isStackEmpty()) {
1126     iterator I;
1127     return getDSA(I, D);
1128   }
1129   D = getCanonicalDecl(D);
1130   iterator StartI = Stack.back().first.rbegin();
1131   iterator EndI = Stack.back().first.rend();
1132   if (FromParent && StartI != EndI)
1133     std::advance(StartI, 1);
1134   return getDSA(StartI, D);
1135 }
1136 
1137 const DSAStackTy::DSAVarData
1138 DSAStackTy::hasDSA(ValueDecl *D,
1139                    const llvm::function_ref<bool(OpenMPClauseKind)> CPred,
1140                    const llvm::function_ref<bool(OpenMPDirectiveKind)> DPred,
1141                    bool FromParent) const {
1142   if (isStackEmpty())
1143     return {};
1144   D = getCanonicalDecl(D);
1145   iterator I = Stack.back().first.rbegin();
1146   iterator EndI = Stack.back().first.rend();
1147   if (FromParent && I != EndI)
1148     std::advance(I, 1);
1149   for (; I != EndI; std::advance(I, 1)) {
1150     if (!DPred(I->Directive) && !isParallelOrTaskRegion(I->Directive))
1151       continue;
1152     iterator NewI = I;
1153     DSAVarData DVar = getDSA(NewI, D);
1154     if (I == NewI && CPred(DVar.CKind))
1155       return DVar;
1156   }
1157   return {};
1158 }
1159 
1160 const DSAStackTy::DSAVarData DSAStackTy::hasInnermostDSA(
1161     ValueDecl *D, const llvm::function_ref<bool(OpenMPClauseKind)> CPred,
1162     const llvm::function_ref<bool(OpenMPDirectiveKind)> DPred,
1163     bool FromParent) const {
1164   if (isStackEmpty())
1165     return {};
1166   D = getCanonicalDecl(D);
1167   iterator StartI = Stack.back().first.rbegin();
1168   iterator EndI = Stack.back().first.rend();
1169   if (FromParent && StartI != EndI)
1170     std::advance(StartI, 1);
1171   if (StartI == EndI || !DPred(StartI->Directive))
1172     return {};
1173   iterator NewI = StartI;
1174   DSAVarData DVar = getDSA(NewI, D);
1175   return (NewI == StartI && CPred(DVar.CKind)) ? DVar : DSAVarData();
1176 }
1177 
1178 bool DSAStackTy::hasExplicitDSA(
1179     const ValueDecl *D, const llvm::function_ref<bool(OpenMPClauseKind)> CPred,
1180     unsigned Level, bool NotLastprivate) const {
1181   if (isStackEmpty())
1182     return false;
1183   D = getCanonicalDecl(D);
1184   auto StartI = Stack.back().first.begin();
1185   auto EndI = Stack.back().first.end();
1186   if (std::distance(StartI, EndI) <= (int)Level)
1187     return false;
1188   std::advance(StartI, Level);
1189   auto I = StartI->SharingMap.find(D);
1190   return (I != StartI->SharingMap.end()) &&
1191          I->getSecond().RefExpr.getPointer() &&
1192          CPred(I->getSecond().Attributes) &&
1193          (!NotLastprivate || !I->getSecond().RefExpr.getInt());
1194 }
1195 
1196 bool DSAStackTy::hasExplicitDirective(
1197     const llvm::function_ref<bool(OpenMPDirectiveKind)> DPred,
1198     unsigned Level) const {
1199   if (isStackEmpty())
1200     return false;
1201   auto StartI = Stack.back().first.begin();
1202   auto EndI = Stack.back().first.end();
1203   if (std::distance(StartI, EndI) <= (int)Level)
1204     return false;
1205   std::advance(StartI, Level);
1206   return DPred(StartI->Directive);
1207 }
1208 
1209 bool DSAStackTy::hasDirective(
1210     const llvm::function_ref<bool(OpenMPDirectiveKind,
1211                                   const DeclarationNameInfo &, SourceLocation)>
1212         DPred,
1213     bool FromParent) const {
1214   // We look only in the enclosing region.
1215   if (isStackEmpty())
1216     return false;
1217   auto StartI = std::next(Stack.back().first.rbegin());
1218   auto EndI = Stack.back().first.rend();
1219   if (FromParent && StartI != EndI)
1220     StartI = std::next(StartI);
1221   for (auto I = StartI, EE = EndI; I != EE; ++I) {
1222     if (DPred(I->Directive, I->DirectiveName, I->ConstructLoc))
1223       return true;
1224   }
1225   return false;
1226 }
1227 
1228 void Sema::InitDataSharingAttributesStack() {
1229   VarDataSharingAttributesStack = new DSAStackTy(*this);
1230 }
1231 
1232 #define DSAStack static_cast<DSAStackTy *>(VarDataSharingAttributesStack)
1233 
1234 void Sema::pushOpenMPFunctionRegion() {
1235   DSAStack->pushFunction();
1236 }
1237 
1238 void Sema::popOpenMPFunctionRegion(const FunctionScopeInfo *OldFSI) {
1239   DSAStack->popFunction(OldFSI);
1240 }
1241 
1242 static llvm::Optional<OMPDeclareTargetDeclAttr::MapTypeTy>
1243 isDeclareTargetDeclaration(const ValueDecl *VD) {
1244   for (const Decl *D : VD->redecls()) {
1245     if (!D->hasAttrs())
1246       continue;
1247     if (const auto *Attr = D->getAttr<OMPDeclareTargetDeclAttr>())
1248       return Attr->getMapType();
1249   }
1250   return llvm::None;
1251 }
1252 
1253 bool Sema::isOpenMPCapturedByRef(const ValueDecl *D, unsigned Level) const {
1254   assert(LangOpts.OpenMP && "OpenMP is not allowed");
1255 
1256   ASTContext &Ctx = getASTContext();
1257   bool IsByRef = true;
1258 
1259   // Find the directive that is associated with the provided scope.
1260   D = cast<ValueDecl>(D->getCanonicalDecl());
1261   QualType Ty = D->getType();
1262 
1263   if (DSAStack->hasExplicitDirective(isOpenMPTargetExecutionDirective, Level)) {
1264     // This table summarizes how a given variable should be passed to the device
1265     // given its type and the clauses where it appears. This table is based on
1266     // the description in OpenMP 4.5 [2.10.4, target Construct] and
1267     // OpenMP 4.5 [2.15.5, Data-mapping Attribute Rules and Clauses].
1268     //
1269     // =========================================================================
1270     // | type |  defaultmap   | pvt | first | is_device_ptr |    map   | res.  |
1271     // |      |(tofrom:scalar)|     |  pvt  |               |          |       |
1272     // =========================================================================
1273     // | scl  |               |     |       |       -       |          | bycopy|
1274     // | scl  |               |  -  |   x   |       -       |     -    | bycopy|
1275     // | scl  |               |  x  |   -   |       -       |     -    | null  |
1276     // | scl  |       x       |     |       |       -       |          | byref |
1277     // | scl  |       x       |  -  |   x   |       -       |     -    | bycopy|
1278     // | scl  |       x       |  x  |   -   |       -       |     -    | null  |
1279     // | scl  |               |  -  |   -   |       -       |     x    | byref |
1280     // | scl  |       x       |  -  |   -   |       -       |     x    | byref |
1281     //
1282     // | agg  |      n.a.     |     |       |       -       |          | byref |
1283     // | agg  |      n.a.     |  -  |   x   |       -       |     -    | byref |
1284     // | agg  |      n.a.     |  x  |   -   |       -       |     -    | null  |
1285     // | agg  |      n.a.     |  -  |   -   |       -       |     x    | byref |
1286     // | agg  |      n.a.     |  -  |   -   |       -       |    x[]   | byref |
1287     //
1288     // | ptr  |      n.a.     |     |       |       -       |          | bycopy|
1289     // | ptr  |      n.a.     |  -  |   x   |       -       |     -    | bycopy|
1290     // | ptr  |      n.a.     |  x  |   -   |       -       |     -    | null  |
1291     // | ptr  |      n.a.     |  -  |   -   |       -       |     x    | byref |
1292     // | ptr  |      n.a.     |  -  |   -   |       -       |    x[]   | bycopy|
1293     // | ptr  |      n.a.     |  -  |   -   |       x       |          | bycopy|
1294     // | ptr  |      n.a.     |  -  |   -   |       x       |     x    | bycopy|
1295     // | ptr  |      n.a.     |  -  |   -   |       x       |    x[]   | bycopy|
1296     // =========================================================================
1297     // Legend:
1298     //  scl - scalar
1299     //  ptr - pointer
1300     //  agg - aggregate
1301     //  x - applies
1302     //  - - invalid in this combination
1303     //  [] - mapped with an array section
1304     //  byref - should be mapped by reference
1305     //  byval - should be mapped by value
1306     //  null - initialize a local variable to null on the device
1307     //
1308     // Observations:
1309     //  - All scalar declarations that show up in a map clause have to be passed
1310     //    by reference, because they may have been mapped in the enclosing data
1311     //    environment.
1312     //  - If the scalar value does not fit the size of uintptr, it has to be
1313     //    passed by reference, regardless the result in the table above.
1314     //  - For pointers mapped by value that have either an implicit map or an
1315     //    array section, the runtime library may pass the NULL value to the
1316     //    device instead of the value passed to it by the compiler.
1317 
1318     if (Ty->isReferenceType())
1319       Ty = Ty->castAs<ReferenceType>()->getPointeeType();
1320 
1321     // Locate map clauses and see if the variable being captured is referred to
1322     // in any of those clauses. Here we only care about variables, not fields,
1323     // because fields are part of aggregates.
1324     bool IsVariableUsedInMapClause = false;
1325     bool IsVariableAssociatedWithSection = false;
1326 
1327     DSAStack->checkMappableExprComponentListsForDeclAtLevel(
1328         D, Level,
1329         [&IsVariableUsedInMapClause, &IsVariableAssociatedWithSection, D](
1330             OMPClauseMappableExprCommon::MappableExprComponentListRef
1331                 MapExprComponents,
1332             OpenMPClauseKind WhereFoundClauseKind) {
1333           // Only the map clause information influences how a variable is
1334           // captured. E.g. is_device_ptr does not require changing the default
1335           // behavior.
1336           if (WhereFoundClauseKind != OMPC_map)
1337             return false;
1338 
1339           auto EI = MapExprComponents.rbegin();
1340           auto EE = MapExprComponents.rend();
1341 
1342           assert(EI != EE && "Invalid map expression!");
1343 
1344           if (isa<DeclRefExpr>(EI->getAssociatedExpression()))
1345             IsVariableUsedInMapClause |= EI->getAssociatedDeclaration() == D;
1346 
1347           ++EI;
1348           if (EI == EE)
1349             return false;
1350 
1351           if (isa<ArraySubscriptExpr>(EI->getAssociatedExpression()) ||
1352               isa<OMPArraySectionExpr>(EI->getAssociatedExpression()) ||
1353               isa<MemberExpr>(EI->getAssociatedExpression())) {
1354             IsVariableAssociatedWithSection = true;
1355             // There is nothing more we need to know about this variable.
1356             return true;
1357           }
1358 
1359           // Keep looking for more map info.
1360           return false;
1361         });
1362 
1363     if (IsVariableUsedInMapClause) {
1364       // If variable is identified in a map clause it is always captured by
1365       // reference except if it is a pointer that is dereferenced somehow.
1366       IsByRef = !(Ty->isPointerType() && IsVariableAssociatedWithSection);
1367     } else {
1368       // By default, all the data that has a scalar type is mapped by copy
1369       // (except for reduction variables).
1370       IsByRef =
1371           !Ty->isScalarType() ||
1372           DSAStack->getDefaultDMAAtLevel(Level) == DMA_tofrom_scalar ||
1373           DSAStack->hasExplicitDSA(
1374               D, [](OpenMPClauseKind K) { return K == OMPC_reduction; }, Level);
1375     }
1376   }
1377 
1378   if (IsByRef && Ty.getNonReferenceType()->isScalarType()) {
1379     IsByRef =
1380         !DSAStack->hasExplicitDSA(
1381             D,
1382             [](OpenMPClauseKind K) -> bool { return K == OMPC_firstprivate; },
1383             Level, /*NotLastprivate=*/true) &&
1384         // If the variable is artificial and must be captured by value - try to
1385         // capture by value.
1386         !(isa<OMPCapturedExprDecl>(D) && !D->hasAttr<OMPCaptureNoInitAttr>() &&
1387           !cast<OMPCapturedExprDecl>(D)->getInit()->isGLValue());
1388   }
1389 
1390   // When passing data by copy, we need to make sure it fits the uintptr size
1391   // and alignment, because the runtime library only deals with uintptr types.
1392   // If it does not fit the uintptr size, we need to pass the data by reference
1393   // instead.
1394   if (!IsByRef &&
1395       (Ctx.getTypeSizeInChars(Ty) >
1396            Ctx.getTypeSizeInChars(Ctx.getUIntPtrType()) ||
1397        Ctx.getDeclAlign(D) > Ctx.getTypeAlignInChars(Ctx.getUIntPtrType()))) {
1398     IsByRef = true;
1399   }
1400 
1401   return IsByRef;
1402 }
1403 
1404 unsigned Sema::getOpenMPNestingLevel() const {
1405   assert(getLangOpts().OpenMP);
1406   return DSAStack->getNestingLevel();
1407 }
1408 
1409 bool Sema::isInOpenMPTargetExecutionDirective() const {
1410   return (isOpenMPTargetExecutionDirective(DSAStack->getCurrentDirective()) &&
1411           !DSAStack->isClauseParsingMode()) ||
1412          DSAStack->hasDirective(
1413              [](OpenMPDirectiveKind K, const DeclarationNameInfo &,
1414                 SourceLocation) -> bool {
1415                return isOpenMPTargetExecutionDirective(K);
1416              },
1417              false);
1418 }
1419 
1420 VarDecl *Sema::isOpenMPCapturedDecl(ValueDecl *D) const {
1421   assert(LangOpts.OpenMP && "OpenMP is not allowed");
1422   D = getCanonicalDecl(D);
1423 
1424   // If we are attempting to capture a global variable in a directive with
1425   // 'target' we return true so that this global is also mapped to the device.
1426   //
1427   auto *VD = dyn_cast<VarDecl>(D);
1428   if (VD && !VD->hasLocalStorage() && isInOpenMPTargetExecutionDirective()) {
1429     // If the declaration is enclosed in a 'declare target' directive,
1430     // then it should not be captured.
1431     //
1432     if (isDeclareTargetDeclaration(VD))
1433       return nullptr;
1434     return VD;
1435   }
1436 
1437   if (DSAStack->getCurrentDirective() != OMPD_unknown &&
1438       (!DSAStack->isClauseParsingMode() ||
1439        DSAStack->getParentDirective() != OMPD_unknown)) {
1440     auto &&Info = DSAStack->isLoopControlVariable(D);
1441     if (Info.first ||
1442         (VD && VD->hasLocalStorage() &&
1443          isParallelOrTaskRegion(DSAStack->getCurrentDirective())) ||
1444         (VD && DSAStack->isForceVarCapturing()))
1445       return VD ? VD : Info.second;
1446     DSAStackTy::DSAVarData DVarPrivate =
1447         DSAStack->getTopDSA(D, DSAStack->isClauseParsingMode());
1448     if (DVarPrivate.CKind != OMPC_unknown && isOpenMPPrivate(DVarPrivate.CKind))
1449       return VD ? VD : cast<VarDecl>(DVarPrivate.PrivateCopy->getDecl());
1450     DVarPrivate = DSAStack->hasDSA(D, isOpenMPPrivate,
1451                                    [](OpenMPDirectiveKind) { return true; },
1452                                    DSAStack->isClauseParsingMode());
1453     if (DVarPrivate.CKind != OMPC_unknown)
1454       return VD ? VD : cast<VarDecl>(DVarPrivate.PrivateCopy->getDecl());
1455   }
1456   return nullptr;
1457 }
1458 
1459 void Sema::adjustOpenMPTargetScopeIndex(unsigned &FunctionScopesIndex,
1460                                         unsigned Level) const {
1461   SmallVector<OpenMPDirectiveKind, 4> Regions;
1462   getOpenMPCaptureRegions(Regions, DSAStack->getDirective(Level));
1463   FunctionScopesIndex -= Regions.size();
1464 }
1465 
1466 bool Sema::isOpenMPPrivateDecl(const ValueDecl *D, unsigned Level) const {
1467   assert(LangOpts.OpenMP && "OpenMP is not allowed");
1468   return DSAStack->hasExplicitDSA(
1469              D, [](OpenMPClauseKind K) { return K == OMPC_private; }, Level) ||
1470          (DSAStack->isClauseParsingMode() &&
1471           DSAStack->getClauseParsingMode() == OMPC_private) ||
1472          // Consider taskgroup reduction descriptor variable a private to avoid
1473          // possible capture in the region.
1474          (DSAStack->hasExplicitDirective(
1475               [](OpenMPDirectiveKind K) { return K == OMPD_taskgroup; },
1476               Level) &&
1477           DSAStack->isTaskgroupReductionRef(D, Level));
1478 }
1479 
1480 void Sema::setOpenMPCaptureKind(FieldDecl *FD, const ValueDecl *D,
1481                                 unsigned Level) {
1482   assert(LangOpts.OpenMP && "OpenMP is not allowed");
1483   D = getCanonicalDecl(D);
1484   OpenMPClauseKind OMPC = OMPC_unknown;
1485   for (unsigned I = DSAStack->getNestingLevel() + 1; I > Level; --I) {
1486     const unsigned NewLevel = I - 1;
1487     if (DSAStack->hasExplicitDSA(D,
1488                                  [&OMPC](const OpenMPClauseKind K) {
1489                                    if (isOpenMPPrivate(K)) {
1490                                      OMPC = K;
1491                                      return true;
1492                                    }
1493                                    return false;
1494                                  },
1495                                  NewLevel))
1496       break;
1497     if (DSAStack->checkMappableExprComponentListsForDeclAtLevel(
1498             D, NewLevel,
1499             [](OMPClauseMappableExprCommon::MappableExprComponentListRef,
1500                OpenMPClauseKind) { return true; })) {
1501       OMPC = OMPC_map;
1502       break;
1503     }
1504     if (DSAStack->hasExplicitDirective(isOpenMPTargetExecutionDirective,
1505                                        NewLevel)) {
1506       OMPC = OMPC_map;
1507       if (D->getType()->isScalarType() &&
1508           DSAStack->getDefaultDMAAtLevel(NewLevel) !=
1509               DefaultMapAttributes::DMA_tofrom_scalar)
1510         OMPC = OMPC_firstprivate;
1511       break;
1512     }
1513   }
1514   if (OMPC != OMPC_unknown)
1515     FD->addAttr(OMPCaptureKindAttr::CreateImplicit(Context, OMPC));
1516 }
1517 
1518 bool Sema::isOpenMPTargetCapturedDecl(const ValueDecl *D,
1519                                       unsigned Level) const {
1520   assert(LangOpts.OpenMP && "OpenMP is not allowed");
1521   // Return true if the current level is no longer enclosed in a target region.
1522 
1523   const auto *VD = dyn_cast<VarDecl>(D);
1524   return VD && !VD->hasLocalStorage() &&
1525          DSAStack->hasExplicitDirective(isOpenMPTargetExecutionDirective,
1526                                         Level);
1527 }
1528 
1529 void Sema::DestroyDataSharingAttributesStack() { delete DSAStack; }
1530 
1531 void Sema::StartOpenMPDSABlock(OpenMPDirectiveKind DKind,
1532                                const DeclarationNameInfo &DirName,
1533                                Scope *CurScope, SourceLocation Loc) {
1534   DSAStack->push(DKind, DirName, CurScope, Loc);
1535   PushExpressionEvaluationContext(
1536       ExpressionEvaluationContext::PotentiallyEvaluated);
1537 }
1538 
1539 void Sema::StartOpenMPClause(OpenMPClauseKind K) {
1540   DSAStack->setClauseParsingMode(K);
1541 }
1542 
1543 void Sema::EndOpenMPClause() {
1544   DSAStack->setClauseParsingMode(/*K=*/OMPC_unknown);
1545 }
1546 
1547 void Sema::EndOpenMPDSABlock(Stmt *CurDirective) {
1548   // OpenMP [2.14.3.5, Restrictions, C/C++, p.1]
1549   //  A variable of class type (or array thereof) that appears in a lastprivate
1550   //  clause requires an accessible, unambiguous default constructor for the
1551   //  class type, unless the list item is also specified in a firstprivate
1552   //  clause.
1553   if (const auto *D = dyn_cast_or_null<OMPExecutableDirective>(CurDirective)) {
1554     for (OMPClause *C : D->clauses()) {
1555       if (auto *Clause = dyn_cast<OMPLastprivateClause>(C)) {
1556         SmallVector<Expr *, 8> PrivateCopies;
1557         for (Expr *DE : Clause->varlists()) {
1558           if (DE->isValueDependent() || DE->isTypeDependent()) {
1559             PrivateCopies.push_back(nullptr);
1560             continue;
1561           }
1562           auto *DRE = cast<DeclRefExpr>(DE->IgnoreParens());
1563           auto *VD = cast<VarDecl>(DRE->getDecl());
1564           QualType Type = VD->getType().getNonReferenceType();
1565           const DSAStackTy::DSAVarData DVar =
1566               DSAStack->getTopDSA(VD, /*FromParent=*/false);
1567           if (DVar.CKind == OMPC_lastprivate) {
1568             // Generate helper private variable and initialize it with the
1569             // default value. The address of the original variable is replaced
1570             // by the address of the new private variable in CodeGen. This new
1571             // variable is not added to IdResolver, so the code in the OpenMP
1572             // region uses original variable for proper diagnostics.
1573             VarDecl *VDPrivate = buildVarDecl(
1574                 *this, DE->getExprLoc(), Type.getUnqualifiedType(),
1575                 VD->getName(), VD->hasAttrs() ? &VD->getAttrs() : nullptr, DRE);
1576             ActOnUninitializedDecl(VDPrivate);
1577             if (VDPrivate->isInvalidDecl())
1578               continue;
1579             PrivateCopies.push_back(buildDeclRefExpr(
1580                 *this, VDPrivate, DE->getType(), DE->getExprLoc()));
1581           } else {
1582             // The variable is also a firstprivate, so initialization sequence
1583             // for private copy is generated already.
1584             PrivateCopies.push_back(nullptr);
1585           }
1586         }
1587         // Set initializers to private copies if no errors were found.
1588         if (PrivateCopies.size() == Clause->varlist_size())
1589           Clause->setPrivateCopies(PrivateCopies);
1590       }
1591     }
1592   }
1593 
1594   DSAStack->pop();
1595   DiscardCleanupsInEvaluationContext();
1596   PopExpressionEvaluationContext();
1597 }
1598 
1599 static bool FinishOpenMPLinearClause(OMPLinearClause &Clause, DeclRefExpr *IV,
1600                                      Expr *NumIterations, Sema &SemaRef,
1601                                      Scope *S, DSAStackTy *Stack);
1602 
1603 namespace {
1604 
1605 class VarDeclFilterCCC final : public CorrectionCandidateCallback {
1606 private:
1607   Sema &SemaRef;
1608 
1609 public:
1610   explicit VarDeclFilterCCC(Sema &S) : SemaRef(S) {}
1611   bool ValidateCandidate(const TypoCorrection &Candidate) override {
1612     NamedDecl *ND = Candidate.getCorrectionDecl();
1613     if (const auto *VD = dyn_cast_or_null<VarDecl>(ND)) {
1614       return VD->hasGlobalStorage() &&
1615              SemaRef.isDeclInScope(ND, SemaRef.getCurLexicalContext(),
1616                                    SemaRef.getCurScope());
1617     }
1618     return false;
1619   }
1620 };
1621 
1622 class VarOrFuncDeclFilterCCC final : public CorrectionCandidateCallback {
1623 private:
1624   Sema &SemaRef;
1625 
1626 public:
1627   explicit VarOrFuncDeclFilterCCC(Sema &S) : SemaRef(S) {}
1628   bool ValidateCandidate(const TypoCorrection &Candidate) override {
1629     NamedDecl *ND = Candidate.getCorrectionDecl();
1630     if (ND && (isa<VarDecl>(ND) || isa<FunctionDecl>(ND))) {
1631       return SemaRef.isDeclInScope(ND, SemaRef.getCurLexicalContext(),
1632                                    SemaRef.getCurScope());
1633     }
1634     return false;
1635   }
1636 };
1637 
1638 } // namespace
1639 
1640 ExprResult Sema::ActOnOpenMPIdExpression(Scope *CurScope,
1641                                          CXXScopeSpec &ScopeSpec,
1642                                          const DeclarationNameInfo &Id) {
1643   LookupResult Lookup(*this, Id, LookupOrdinaryName);
1644   LookupParsedName(Lookup, CurScope, &ScopeSpec, true);
1645 
1646   if (Lookup.isAmbiguous())
1647     return ExprError();
1648 
1649   VarDecl *VD;
1650   if (!Lookup.isSingleResult()) {
1651     if (TypoCorrection Corrected = CorrectTypo(
1652             Id, LookupOrdinaryName, CurScope, nullptr,
1653             llvm::make_unique<VarDeclFilterCCC>(*this), CTK_ErrorRecovery)) {
1654       diagnoseTypo(Corrected,
1655                    PDiag(Lookup.empty()
1656                              ? diag::err_undeclared_var_use_suggest
1657                              : diag::err_omp_expected_var_arg_suggest)
1658                        << Id.getName());
1659       VD = Corrected.getCorrectionDeclAs<VarDecl>();
1660     } else {
1661       Diag(Id.getLoc(), Lookup.empty() ? diag::err_undeclared_var_use
1662                                        : diag::err_omp_expected_var_arg)
1663           << Id.getName();
1664       return ExprError();
1665     }
1666   } else if (!(VD = Lookup.getAsSingle<VarDecl>())) {
1667     Diag(Id.getLoc(), diag::err_omp_expected_var_arg) << Id.getName();
1668     Diag(Lookup.getFoundDecl()->getLocation(), diag::note_declared_at);
1669     return ExprError();
1670   }
1671   Lookup.suppressDiagnostics();
1672 
1673   // OpenMP [2.9.2, Syntax, C/C++]
1674   //   Variables must be file-scope, namespace-scope, or static block-scope.
1675   if (!VD->hasGlobalStorage()) {
1676     Diag(Id.getLoc(), diag::err_omp_global_var_arg)
1677         << getOpenMPDirectiveName(OMPD_threadprivate) << !VD->isStaticLocal();
1678     bool IsDecl =
1679         VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
1680     Diag(VD->getLocation(),
1681          IsDecl ? diag::note_previous_decl : diag::note_defined_here)
1682         << VD;
1683     return ExprError();
1684   }
1685 
1686   VarDecl *CanonicalVD = VD->getCanonicalDecl();
1687   NamedDecl *ND = CanonicalVD;
1688   // OpenMP [2.9.2, Restrictions, C/C++, p.2]
1689   //   A threadprivate directive for file-scope variables must appear outside
1690   //   any definition or declaration.
1691   if (CanonicalVD->getDeclContext()->isTranslationUnit() &&
1692       !getCurLexicalContext()->isTranslationUnit()) {
1693     Diag(Id.getLoc(), diag::err_omp_var_scope)
1694         << getOpenMPDirectiveName(OMPD_threadprivate) << VD;
1695     bool IsDecl =
1696         VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
1697     Diag(VD->getLocation(),
1698          IsDecl ? diag::note_previous_decl : diag::note_defined_here)
1699         << VD;
1700     return ExprError();
1701   }
1702   // OpenMP [2.9.2, Restrictions, C/C++, p.3]
1703   //   A threadprivate directive for static class member variables must appear
1704   //   in the class definition, in the same scope in which the member
1705   //   variables are declared.
1706   if (CanonicalVD->isStaticDataMember() &&
1707       !CanonicalVD->getDeclContext()->Equals(getCurLexicalContext())) {
1708     Diag(Id.getLoc(), diag::err_omp_var_scope)
1709         << getOpenMPDirectiveName(OMPD_threadprivate) << VD;
1710     bool IsDecl =
1711         VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
1712     Diag(VD->getLocation(),
1713          IsDecl ? diag::note_previous_decl : diag::note_defined_here)
1714         << VD;
1715     return ExprError();
1716   }
1717   // OpenMP [2.9.2, Restrictions, C/C++, p.4]
1718   //   A threadprivate directive for namespace-scope variables must appear
1719   //   outside any definition or declaration other than the namespace
1720   //   definition itself.
1721   if (CanonicalVD->getDeclContext()->isNamespace() &&
1722       (!getCurLexicalContext()->isFileContext() ||
1723        !getCurLexicalContext()->Encloses(CanonicalVD->getDeclContext()))) {
1724     Diag(Id.getLoc(), diag::err_omp_var_scope)
1725         << getOpenMPDirectiveName(OMPD_threadprivate) << VD;
1726     bool IsDecl =
1727         VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
1728     Diag(VD->getLocation(),
1729          IsDecl ? diag::note_previous_decl : diag::note_defined_here)
1730         << VD;
1731     return ExprError();
1732   }
1733   // OpenMP [2.9.2, Restrictions, C/C++, p.6]
1734   //   A threadprivate directive for static block-scope variables must appear
1735   //   in the scope of the variable and not in a nested scope.
1736   if (CanonicalVD->isStaticLocal() && CurScope &&
1737       !isDeclInScope(ND, getCurLexicalContext(), CurScope)) {
1738     Diag(Id.getLoc(), diag::err_omp_var_scope)
1739         << getOpenMPDirectiveName(OMPD_threadprivate) << VD;
1740     bool IsDecl =
1741         VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
1742     Diag(VD->getLocation(),
1743          IsDecl ? diag::note_previous_decl : diag::note_defined_here)
1744         << VD;
1745     return ExprError();
1746   }
1747 
1748   // OpenMP [2.9.2, Restrictions, C/C++, p.2-6]
1749   //   A threadprivate directive must lexically precede all references to any
1750   //   of the variables in its list.
1751   if (VD->isUsed() && !DSAStack->isThreadPrivate(VD)) {
1752     Diag(Id.getLoc(), diag::err_omp_var_used)
1753         << getOpenMPDirectiveName(OMPD_threadprivate) << VD;
1754     return ExprError();
1755   }
1756 
1757   QualType ExprType = VD->getType().getNonReferenceType();
1758   return DeclRefExpr::Create(Context, NestedNameSpecifierLoc(),
1759                              SourceLocation(), VD,
1760                              /*RefersToEnclosingVariableOrCapture=*/false,
1761                              Id.getLoc(), ExprType, VK_LValue);
1762 }
1763 
1764 Sema::DeclGroupPtrTy
1765 Sema::ActOnOpenMPThreadprivateDirective(SourceLocation Loc,
1766                                         ArrayRef<Expr *> VarList) {
1767   if (OMPThreadPrivateDecl *D = CheckOMPThreadPrivateDecl(Loc, VarList)) {
1768     CurContext->addDecl(D);
1769     return DeclGroupPtrTy::make(DeclGroupRef(D));
1770   }
1771   return nullptr;
1772 }
1773 
1774 namespace {
1775 class LocalVarRefChecker final
1776     : public ConstStmtVisitor<LocalVarRefChecker, bool> {
1777   Sema &SemaRef;
1778 
1779 public:
1780   bool VisitDeclRefExpr(const DeclRefExpr *E) {
1781     if (const auto *VD = dyn_cast<VarDecl>(E->getDecl())) {
1782       if (VD->hasLocalStorage()) {
1783         SemaRef.Diag(E->getLocStart(),
1784                      diag::err_omp_local_var_in_threadprivate_init)
1785             << E->getSourceRange();
1786         SemaRef.Diag(VD->getLocation(), diag::note_defined_here)
1787             << VD << VD->getSourceRange();
1788         return true;
1789       }
1790     }
1791     return false;
1792   }
1793   bool VisitStmt(const Stmt *S) {
1794     for (const Stmt *Child : S->children()) {
1795       if (Child && Visit(Child))
1796         return true;
1797     }
1798     return false;
1799   }
1800   explicit LocalVarRefChecker(Sema &SemaRef) : SemaRef(SemaRef) {}
1801 };
1802 } // namespace
1803 
1804 OMPThreadPrivateDecl *
1805 Sema::CheckOMPThreadPrivateDecl(SourceLocation Loc, ArrayRef<Expr *> VarList) {
1806   SmallVector<Expr *, 8> Vars;
1807   for (Expr *RefExpr : VarList) {
1808     auto *DE = cast<DeclRefExpr>(RefExpr);
1809     auto *VD = cast<VarDecl>(DE->getDecl());
1810     SourceLocation ILoc = DE->getExprLoc();
1811 
1812     // Mark variable as used.
1813     VD->setReferenced();
1814     VD->markUsed(Context);
1815 
1816     QualType QType = VD->getType();
1817     if (QType->isDependentType() || QType->isInstantiationDependentType()) {
1818       // It will be analyzed later.
1819       Vars.push_back(DE);
1820       continue;
1821     }
1822 
1823     // OpenMP [2.9.2, Restrictions, C/C++, p.10]
1824     //   A threadprivate variable must not have an incomplete type.
1825     if (RequireCompleteType(ILoc, VD->getType(),
1826                             diag::err_omp_threadprivate_incomplete_type)) {
1827       continue;
1828     }
1829 
1830     // OpenMP [2.9.2, Restrictions, C/C++, p.10]
1831     //   A threadprivate variable must not have a reference type.
1832     if (VD->getType()->isReferenceType()) {
1833       Diag(ILoc, diag::err_omp_ref_type_arg)
1834           << getOpenMPDirectiveName(OMPD_threadprivate) << VD->getType();
1835       bool IsDecl =
1836           VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
1837       Diag(VD->getLocation(),
1838            IsDecl ? diag::note_previous_decl : diag::note_defined_here)
1839           << VD;
1840       continue;
1841     }
1842 
1843     // Check if this is a TLS variable. If TLS is not being supported, produce
1844     // the corresponding diagnostic.
1845     if ((VD->getTLSKind() != VarDecl::TLS_None &&
1846          !(VD->hasAttr<OMPThreadPrivateDeclAttr>() &&
1847            getLangOpts().OpenMPUseTLS &&
1848            getASTContext().getTargetInfo().isTLSSupported())) ||
1849         (VD->getStorageClass() == SC_Register && VD->hasAttr<AsmLabelAttr>() &&
1850          !VD->isLocalVarDecl())) {
1851       Diag(ILoc, diag::err_omp_var_thread_local)
1852           << VD << ((VD->getTLSKind() != VarDecl::TLS_None) ? 0 : 1);
1853       bool IsDecl =
1854           VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
1855       Diag(VD->getLocation(),
1856            IsDecl ? diag::note_previous_decl : diag::note_defined_here)
1857           << VD;
1858       continue;
1859     }
1860 
1861     // Check if initial value of threadprivate variable reference variable with
1862     // local storage (it is not supported by runtime).
1863     if (const Expr *Init = VD->getAnyInitializer()) {
1864       LocalVarRefChecker Checker(*this);
1865       if (Checker.Visit(Init))
1866         continue;
1867     }
1868 
1869     Vars.push_back(RefExpr);
1870     DSAStack->addDSA(VD, DE, OMPC_threadprivate);
1871     VD->addAttr(OMPThreadPrivateDeclAttr::CreateImplicit(
1872         Context, SourceRange(Loc, Loc)));
1873     if (ASTMutationListener *ML = Context.getASTMutationListener())
1874       ML->DeclarationMarkedOpenMPThreadPrivate(VD);
1875   }
1876   OMPThreadPrivateDecl *D = nullptr;
1877   if (!Vars.empty()) {
1878     D = OMPThreadPrivateDecl::Create(Context, getCurLexicalContext(), Loc,
1879                                      Vars);
1880     D->setAccess(AS_public);
1881   }
1882   return D;
1883 }
1884 
1885 static void reportOriginalDsa(Sema &SemaRef, const DSAStackTy *Stack,
1886                               const ValueDecl *D,
1887                               const DSAStackTy::DSAVarData &DVar,
1888                               bool IsLoopIterVar = false) {
1889   if (DVar.RefExpr) {
1890     SemaRef.Diag(DVar.RefExpr->getExprLoc(), diag::note_omp_explicit_dsa)
1891         << getOpenMPClauseName(DVar.CKind);
1892     return;
1893   }
1894   enum {
1895     PDSA_StaticMemberShared,
1896     PDSA_StaticLocalVarShared,
1897     PDSA_LoopIterVarPrivate,
1898     PDSA_LoopIterVarLinear,
1899     PDSA_LoopIterVarLastprivate,
1900     PDSA_ConstVarShared,
1901     PDSA_GlobalVarShared,
1902     PDSA_TaskVarFirstprivate,
1903     PDSA_LocalVarPrivate,
1904     PDSA_Implicit
1905   } Reason = PDSA_Implicit;
1906   bool ReportHint = false;
1907   auto ReportLoc = D->getLocation();
1908   auto *VD = dyn_cast<VarDecl>(D);
1909   if (IsLoopIterVar) {
1910     if (DVar.CKind == OMPC_private)
1911       Reason = PDSA_LoopIterVarPrivate;
1912     else if (DVar.CKind == OMPC_lastprivate)
1913       Reason = PDSA_LoopIterVarLastprivate;
1914     else
1915       Reason = PDSA_LoopIterVarLinear;
1916   } else if (isOpenMPTaskingDirective(DVar.DKind) &&
1917              DVar.CKind == OMPC_firstprivate) {
1918     Reason = PDSA_TaskVarFirstprivate;
1919     ReportLoc = DVar.ImplicitDSALoc;
1920   } else if (VD && VD->isStaticLocal())
1921     Reason = PDSA_StaticLocalVarShared;
1922   else if (VD && VD->isStaticDataMember())
1923     Reason = PDSA_StaticMemberShared;
1924   else if (VD && VD->isFileVarDecl())
1925     Reason = PDSA_GlobalVarShared;
1926   else if (D->getType().isConstant(SemaRef.getASTContext()))
1927     Reason = PDSA_ConstVarShared;
1928   else if (VD && VD->isLocalVarDecl() && DVar.CKind == OMPC_private) {
1929     ReportHint = true;
1930     Reason = PDSA_LocalVarPrivate;
1931   }
1932   if (Reason != PDSA_Implicit) {
1933     SemaRef.Diag(ReportLoc, diag::note_omp_predetermined_dsa)
1934         << Reason << ReportHint
1935         << getOpenMPDirectiveName(Stack->getCurrentDirective());
1936   } else if (DVar.ImplicitDSALoc.isValid()) {
1937     SemaRef.Diag(DVar.ImplicitDSALoc, diag::note_omp_implicit_dsa)
1938         << getOpenMPClauseName(DVar.CKind);
1939   }
1940 }
1941 
1942 namespace {
1943 class DSAAttrChecker final : public StmtVisitor<DSAAttrChecker, void> {
1944   DSAStackTy *Stack;
1945   Sema &SemaRef;
1946   bool ErrorFound = false;
1947   CapturedStmt *CS = nullptr;
1948   llvm::SmallVector<Expr *, 4> ImplicitFirstprivate;
1949   llvm::SmallVector<Expr *, 4> ImplicitMap;
1950   Sema::VarsWithInheritedDSAType VarsWithInheritedDSA;
1951   llvm::SmallDenseSet<const ValueDecl *, 4> ImplicitDeclarations;
1952 
1953 public:
1954   void VisitDeclRefExpr(DeclRefExpr *E) {
1955     if (E->isTypeDependent() || E->isValueDependent() ||
1956         E->containsUnexpandedParameterPack() || E->isInstantiationDependent())
1957       return;
1958     if (auto *VD = dyn_cast<VarDecl>(E->getDecl())) {
1959       VD = VD->getCanonicalDecl();
1960       // Skip internally declared variables.
1961       if (VD->hasLocalStorage() && !CS->capturesVariable(VD))
1962         return;
1963 
1964       DSAStackTy::DSAVarData DVar = Stack->getTopDSA(VD, /*FromParent=*/false);
1965       // Check if the variable has explicit DSA set and stop analysis if it so.
1966       if (DVar.RefExpr || !ImplicitDeclarations.insert(VD).second)
1967         return;
1968 
1969       // Skip internally declared static variables.
1970       llvm::Optional<OMPDeclareTargetDeclAttr::MapTypeTy> Res =
1971           isDeclareTargetDeclaration(VD);
1972       if (VD->hasGlobalStorage() && !CS->capturesVariable(VD) &&
1973           (!Res || *Res != OMPDeclareTargetDeclAttr::MT_Link))
1974         return;
1975 
1976       SourceLocation ELoc = E->getExprLoc();
1977       OpenMPDirectiveKind DKind = Stack->getCurrentDirective();
1978       // The default(none) clause requires that each variable that is referenced
1979       // in the construct, and does not have a predetermined data-sharing
1980       // attribute, must have its data-sharing attribute explicitly determined
1981       // by being listed in a data-sharing attribute clause.
1982       if (DVar.CKind == OMPC_unknown && Stack->getDefaultDSA() == DSA_none &&
1983           isParallelOrTaskRegion(DKind) &&
1984           VarsWithInheritedDSA.count(VD) == 0) {
1985         VarsWithInheritedDSA[VD] = E;
1986         return;
1987       }
1988 
1989       if (isOpenMPTargetExecutionDirective(DKind) &&
1990           !Stack->isLoopControlVariable(VD).first) {
1991         if (!Stack->checkMappableExprComponentListsForDecl(
1992                 VD, /*CurrentRegionOnly=*/true,
1993                 [](OMPClauseMappableExprCommon::MappableExprComponentListRef
1994                        StackComponents,
1995                    OpenMPClauseKind) {
1996                   // Variable is used if it has been marked as an array, array
1997                   // section or the variable iself.
1998                   return StackComponents.size() == 1 ||
1999                          std::all_of(
2000                              std::next(StackComponents.rbegin()),
2001                              StackComponents.rend(),
2002                              [](const OMPClauseMappableExprCommon::
2003                                     MappableComponent &MC) {
2004                                return MC.getAssociatedDeclaration() ==
2005                                           nullptr &&
2006                                       (isa<OMPArraySectionExpr>(
2007                                            MC.getAssociatedExpression()) ||
2008                                        isa<ArraySubscriptExpr>(
2009                                            MC.getAssociatedExpression()));
2010                              });
2011                 })) {
2012           bool IsFirstprivate = false;
2013           // By default lambdas are captured as firstprivates.
2014           if (const auto *RD =
2015                   VD->getType().getNonReferenceType()->getAsCXXRecordDecl())
2016             IsFirstprivate = RD->isLambda();
2017           IsFirstprivate =
2018               IsFirstprivate ||
2019               (VD->getType().getNonReferenceType()->isScalarType() &&
2020                Stack->getDefaultDMA() != DMA_tofrom_scalar && !Res);
2021           if (IsFirstprivate)
2022             ImplicitFirstprivate.emplace_back(E);
2023           else
2024             ImplicitMap.emplace_back(E);
2025           return;
2026         }
2027       }
2028 
2029       // OpenMP [2.9.3.6, Restrictions, p.2]
2030       //  A list item that appears in a reduction clause of the innermost
2031       //  enclosing worksharing or parallel construct may not be accessed in an
2032       //  explicit task.
2033       DVar = Stack->hasInnermostDSA(
2034           VD, [](OpenMPClauseKind C) { return C == OMPC_reduction; },
2035           [](OpenMPDirectiveKind K) {
2036             return isOpenMPParallelDirective(K) ||
2037                    isOpenMPWorksharingDirective(K) || isOpenMPTeamsDirective(K);
2038           },
2039           /*FromParent=*/true);
2040       if (isOpenMPTaskingDirective(DKind) && DVar.CKind == OMPC_reduction) {
2041         ErrorFound = true;
2042         SemaRef.Diag(ELoc, diag::err_omp_reduction_in_task);
2043         reportOriginalDsa(SemaRef, Stack, VD, DVar);
2044         return;
2045       }
2046 
2047       // Define implicit data-sharing attributes for task.
2048       DVar = Stack->getImplicitDSA(VD, /*FromParent=*/false);
2049       if (isOpenMPTaskingDirective(DKind) && DVar.CKind != OMPC_shared &&
2050           !Stack->isLoopControlVariable(VD).first)
2051         ImplicitFirstprivate.push_back(E);
2052     }
2053   }
2054   void VisitMemberExpr(MemberExpr *E) {
2055     if (E->isTypeDependent() || E->isValueDependent() ||
2056         E->containsUnexpandedParameterPack() || E->isInstantiationDependent())
2057       return;
2058     auto *FD = dyn_cast<FieldDecl>(E->getMemberDecl());
2059     OpenMPDirectiveKind DKind = Stack->getCurrentDirective();
2060     if (isa<CXXThisExpr>(E->getBase()->IgnoreParens())) {
2061       if (!FD)
2062         return;
2063       DSAStackTy::DSAVarData DVar = Stack->getTopDSA(FD, /*FromParent=*/false);
2064       // Check if the variable has explicit DSA set and stop analysis if it
2065       // so.
2066       if (DVar.RefExpr || !ImplicitDeclarations.insert(FD).second)
2067         return;
2068 
2069       if (isOpenMPTargetExecutionDirective(DKind) &&
2070           !Stack->isLoopControlVariable(FD).first &&
2071           !Stack->checkMappableExprComponentListsForDecl(
2072               FD, /*CurrentRegionOnly=*/true,
2073               [](OMPClauseMappableExprCommon::MappableExprComponentListRef
2074                      StackComponents,
2075                  OpenMPClauseKind) {
2076                 return isa<CXXThisExpr>(
2077                     cast<MemberExpr>(
2078                         StackComponents.back().getAssociatedExpression())
2079                         ->getBase()
2080                         ->IgnoreParens());
2081               })) {
2082         // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C/C++, p.3]
2083         //  A bit-field cannot appear in a map clause.
2084         //
2085         if (FD->isBitField())
2086           return;
2087         ImplicitMap.emplace_back(E);
2088         return;
2089       }
2090 
2091       SourceLocation ELoc = E->getExprLoc();
2092       // OpenMP [2.9.3.6, Restrictions, p.2]
2093       //  A list item that appears in a reduction clause of the innermost
2094       //  enclosing worksharing or parallel construct may not be accessed in
2095       //  an  explicit task.
2096       DVar = Stack->hasInnermostDSA(
2097           FD, [](OpenMPClauseKind C) { return C == OMPC_reduction; },
2098           [](OpenMPDirectiveKind K) {
2099             return isOpenMPParallelDirective(K) ||
2100                    isOpenMPWorksharingDirective(K) || isOpenMPTeamsDirective(K);
2101           },
2102           /*FromParent=*/true);
2103       if (isOpenMPTaskingDirective(DKind) && DVar.CKind == OMPC_reduction) {
2104         ErrorFound = true;
2105         SemaRef.Diag(ELoc, diag::err_omp_reduction_in_task);
2106         reportOriginalDsa(SemaRef, Stack, FD, DVar);
2107         return;
2108       }
2109 
2110       // Define implicit data-sharing attributes for task.
2111       DVar = Stack->getImplicitDSA(FD, /*FromParent=*/false);
2112       if (isOpenMPTaskingDirective(DKind) && DVar.CKind != OMPC_shared &&
2113           !Stack->isLoopControlVariable(FD).first)
2114         ImplicitFirstprivate.push_back(E);
2115       return;
2116     }
2117     if (isOpenMPTargetExecutionDirective(DKind)) {
2118       OMPClauseMappableExprCommon::MappableExprComponentList CurComponents;
2119       if (!checkMapClauseExpressionBase(SemaRef, E, CurComponents, OMPC_map,
2120                                         /*NoDiagnose=*/true))
2121         return;
2122       const auto *VD = cast<ValueDecl>(
2123           CurComponents.back().getAssociatedDeclaration()->getCanonicalDecl());
2124       if (!Stack->checkMappableExprComponentListsForDecl(
2125               VD, /*CurrentRegionOnly=*/true,
2126               [&CurComponents](
2127                   OMPClauseMappableExprCommon::MappableExprComponentListRef
2128                       StackComponents,
2129                   OpenMPClauseKind) {
2130                 auto CCI = CurComponents.rbegin();
2131                 auto CCE = CurComponents.rend();
2132                 for (const auto &SC : llvm::reverse(StackComponents)) {
2133                   // Do both expressions have the same kind?
2134                   if (CCI->getAssociatedExpression()->getStmtClass() !=
2135                       SC.getAssociatedExpression()->getStmtClass())
2136                     if (!(isa<OMPArraySectionExpr>(
2137                               SC.getAssociatedExpression()) &&
2138                           isa<ArraySubscriptExpr>(
2139                               CCI->getAssociatedExpression())))
2140                       return false;
2141 
2142                   const Decl *CCD = CCI->getAssociatedDeclaration();
2143                   const Decl *SCD = SC.getAssociatedDeclaration();
2144                   CCD = CCD ? CCD->getCanonicalDecl() : nullptr;
2145                   SCD = SCD ? SCD->getCanonicalDecl() : nullptr;
2146                   if (SCD != CCD)
2147                     return false;
2148                   std::advance(CCI, 1);
2149                   if (CCI == CCE)
2150                     break;
2151                 }
2152                 return true;
2153               })) {
2154         Visit(E->getBase());
2155       }
2156     } else {
2157       Visit(E->getBase());
2158     }
2159   }
2160   void VisitOMPExecutableDirective(OMPExecutableDirective *S) {
2161     for (OMPClause *C : S->clauses()) {
2162       // Skip analysis of arguments of implicitly defined firstprivate clause
2163       // for task|target directives.
2164       // Skip analysis of arguments of implicitly defined map clause for target
2165       // directives.
2166       if (C && !((isa<OMPFirstprivateClause>(C) || isa<OMPMapClause>(C)) &&
2167                  C->isImplicit())) {
2168         for (Stmt *CC : C->children()) {
2169           if (CC)
2170             Visit(CC);
2171         }
2172       }
2173     }
2174   }
2175   void VisitStmt(Stmt *S) {
2176     for (Stmt *C : S->children()) {
2177       if (C && !isa<OMPExecutableDirective>(C))
2178         Visit(C);
2179     }
2180   }
2181 
2182   bool isErrorFound() const { return ErrorFound; }
2183   ArrayRef<Expr *> getImplicitFirstprivate() const {
2184     return ImplicitFirstprivate;
2185   }
2186   ArrayRef<Expr *> getImplicitMap() const { return ImplicitMap; }
2187   const Sema::VarsWithInheritedDSAType &getVarsWithInheritedDSA() const {
2188     return VarsWithInheritedDSA;
2189   }
2190 
2191   DSAAttrChecker(DSAStackTy *S, Sema &SemaRef, CapturedStmt *CS)
2192       : Stack(S), SemaRef(SemaRef), ErrorFound(false), CS(CS) {}
2193 };
2194 } // namespace
2195 
2196 void Sema::ActOnOpenMPRegionStart(OpenMPDirectiveKind DKind, Scope *CurScope) {
2197   switch (DKind) {
2198   case OMPD_parallel:
2199   case OMPD_parallel_for:
2200   case OMPD_parallel_for_simd:
2201   case OMPD_parallel_sections:
2202   case OMPD_teams:
2203   case OMPD_teams_distribute:
2204   case OMPD_teams_distribute_simd: {
2205     QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1).withConst();
2206     QualType KmpInt32PtrTy =
2207         Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
2208     Sema::CapturedParamNameType Params[] = {
2209         std::make_pair(".global_tid.", KmpInt32PtrTy),
2210         std::make_pair(".bound_tid.", KmpInt32PtrTy),
2211         std::make_pair(StringRef(), QualType()) // __context with shared vars
2212     };
2213     ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
2214                              Params);
2215     break;
2216   }
2217   case OMPD_target_teams:
2218   case OMPD_target_parallel:
2219   case OMPD_target_parallel_for:
2220   case OMPD_target_parallel_for_simd:
2221   case OMPD_target_teams_distribute:
2222   case OMPD_target_teams_distribute_simd: {
2223     QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1).withConst();
2224     QualType VoidPtrTy = Context.VoidPtrTy.withConst().withRestrict();
2225     QualType KmpInt32PtrTy =
2226         Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
2227     QualType Args[] = {VoidPtrTy};
2228     FunctionProtoType::ExtProtoInfo EPI;
2229     EPI.Variadic = true;
2230     QualType CopyFnType = Context.getFunctionType(Context.VoidTy, Args, EPI);
2231     Sema::CapturedParamNameType Params[] = {
2232         std::make_pair(".global_tid.", KmpInt32Ty),
2233         std::make_pair(".part_id.", KmpInt32PtrTy),
2234         std::make_pair(".privates.", VoidPtrTy),
2235         std::make_pair(
2236             ".copy_fn.",
2237             Context.getPointerType(CopyFnType).withConst().withRestrict()),
2238         std::make_pair(".task_t.", Context.VoidPtrTy.withConst()),
2239         std::make_pair(StringRef(), QualType()) // __context with shared vars
2240     };
2241     ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
2242                              Params);
2243     // Mark this captured region as inlined, because we don't use outlined
2244     // function directly.
2245     getCurCapturedRegion()->TheCapturedDecl->addAttr(
2246         AlwaysInlineAttr::CreateImplicit(
2247             Context, AlwaysInlineAttr::Keyword_forceinline));
2248     Sema::CapturedParamNameType ParamsTarget[] = {
2249         std::make_pair(StringRef(), QualType()) // __context with shared vars
2250     };
2251     // Start a captured region for 'target' with no implicit parameters.
2252     ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
2253                              ParamsTarget);
2254     Sema::CapturedParamNameType ParamsTeamsOrParallel[] = {
2255         std::make_pair(".global_tid.", KmpInt32PtrTy),
2256         std::make_pair(".bound_tid.", KmpInt32PtrTy),
2257         std::make_pair(StringRef(), QualType()) // __context with shared vars
2258     };
2259     // Start a captured region for 'teams' or 'parallel'.  Both regions have
2260     // the same implicit parameters.
2261     ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
2262                              ParamsTeamsOrParallel);
2263     break;
2264   }
2265   case OMPD_target:
2266   case OMPD_target_simd: {
2267     QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1).withConst();
2268     QualType VoidPtrTy = Context.VoidPtrTy.withConst().withRestrict();
2269     QualType KmpInt32PtrTy =
2270         Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
2271     QualType Args[] = {VoidPtrTy};
2272     FunctionProtoType::ExtProtoInfo EPI;
2273     EPI.Variadic = true;
2274     QualType CopyFnType = Context.getFunctionType(Context.VoidTy, Args, EPI);
2275     Sema::CapturedParamNameType Params[] = {
2276         std::make_pair(".global_tid.", KmpInt32Ty),
2277         std::make_pair(".part_id.", KmpInt32PtrTy),
2278         std::make_pair(".privates.", VoidPtrTy),
2279         std::make_pair(
2280             ".copy_fn.",
2281             Context.getPointerType(CopyFnType).withConst().withRestrict()),
2282         std::make_pair(".task_t.", Context.VoidPtrTy.withConst()),
2283         std::make_pair(StringRef(), QualType()) // __context with shared vars
2284     };
2285     ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
2286                              Params);
2287     // Mark this captured region as inlined, because we don't use outlined
2288     // function directly.
2289     getCurCapturedRegion()->TheCapturedDecl->addAttr(
2290         AlwaysInlineAttr::CreateImplicit(
2291             Context, AlwaysInlineAttr::Keyword_forceinline));
2292     ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
2293                              std::make_pair(StringRef(), QualType()));
2294     break;
2295   }
2296   case OMPD_simd:
2297   case OMPD_for:
2298   case OMPD_for_simd:
2299   case OMPD_sections:
2300   case OMPD_section:
2301   case OMPD_single:
2302   case OMPD_master:
2303   case OMPD_critical:
2304   case OMPD_taskgroup:
2305   case OMPD_distribute:
2306   case OMPD_distribute_simd:
2307   case OMPD_ordered:
2308   case OMPD_atomic:
2309   case OMPD_target_data: {
2310     Sema::CapturedParamNameType Params[] = {
2311         std::make_pair(StringRef(), QualType()) // __context with shared vars
2312     };
2313     ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
2314                              Params);
2315     break;
2316   }
2317   case OMPD_task: {
2318     QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1).withConst();
2319     QualType VoidPtrTy = Context.VoidPtrTy.withConst().withRestrict();
2320     QualType KmpInt32PtrTy =
2321         Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
2322     QualType Args[] = {VoidPtrTy};
2323     FunctionProtoType::ExtProtoInfo EPI;
2324     EPI.Variadic = true;
2325     QualType CopyFnType = Context.getFunctionType(Context.VoidTy, Args, EPI);
2326     Sema::CapturedParamNameType Params[] = {
2327         std::make_pair(".global_tid.", KmpInt32Ty),
2328         std::make_pair(".part_id.", KmpInt32PtrTy),
2329         std::make_pair(".privates.", VoidPtrTy),
2330         std::make_pair(
2331             ".copy_fn.",
2332             Context.getPointerType(CopyFnType).withConst().withRestrict()),
2333         std::make_pair(".task_t.", Context.VoidPtrTy.withConst()),
2334         std::make_pair(StringRef(), QualType()) // __context with shared vars
2335     };
2336     ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
2337                              Params);
2338     // Mark this captured region as inlined, because we don't use outlined
2339     // function directly.
2340     getCurCapturedRegion()->TheCapturedDecl->addAttr(
2341         AlwaysInlineAttr::CreateImplicit(
2342             Context, AlwaysInlineAttr::Keyword_forceinline));
2343     break;
2344   }
2345   case OMPD_taskloop:
2346   case OMPD_taskloop_simd: {
2347     QualType KmpInt32Ty =
2348         Context.getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/1)
2349             .withConst();
2350     QualType KmpUInt64Ty =
2351         Context.getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/0)
2352             .withConst();
2353     QualType KmpInt64Ty =
2354         Context.getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/1)
2355             .withConst();
2356     QualType VoidPtrTy = Context.VoidPtrTy.withConst().withRestrict();
2357     QualType KmpInt32PtrTy =
2358         Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
2359     QualType Args[] = {VoidPtrTy};
2360     FunctionProtoType::ExtProtoInfo EPI;
2361     EPI.Variadic = true;
2362     QualType CopyFnType = Context.getFunctionType(Context.VoidTy, Args, EPI);
2363     Sema::CapturedParamNameType Params[] = {
2364         std::make_pair(".global_tid.", KmpInt32Ty),
2365         std::make_pair(".part_id.", KmpInt32PtrTy),
2366         std::make_pair(".privates.", VoidPtrTy),
2367         std::make_pair(
2368             ".copy_fn.",
2369             Context.getPointerType(CopyFnType).withConst().withRestrict()),
2370         std::make_pair(".task_t.", Context.VoidPtrTy.withConst()),
2371         std::make_pair(".lb.", KmpUInt64Ty),
2372         std::make_pair(".ub.", KmpUInt64Ty),
2373         std::make_pair(".st.", KmpInt64Ty),
2374         std::make_pair(".liter.", KmpInt32Ty),
2375         std::make_pair(".reductions.", VoidPtrTy),
2376         std::make_pair(StringRef(), QualType()) // __context with shared vars
2377     };
2378     ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
2379                              Params);
2380     // Mark this captured region as inlined, because we don't use outlined
2381     // function directly.
2382     getCurCapturedRegion()->TheCapturedDecl->addAttr(
2383         AlwaysInlineAttr::CreateImplicit(
2384             Context, AlwaysInlineAttr::Keyword_forceinline));
2385     break;
2386   }
2387   case OMPD_distribute_parallel_for_simd:
2388   case OMPD_distribute_parallel_for: {
2389     QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1).withConst();
2390     QualType KmpInt32PtrTy =
2391         Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
2392     Sema::CapturedParamNameType Params[] = {
2393         std::make_pair(".global_tid.", KmpInt32PtrTy),
2394         std::make_pair(".bound_tid.", KmpInt32PtrTy),
2395         std::make_pair(".previous.lb.", Context.getSizeType().withConst()),
2396         std::make_pair(".previous.ub.", Context.getSizeType().withConst()),
2397         std::make_pair(StringRef(), QualType()) // __context with shared vars
2398     };
2399     ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
2400                              Params);
2401     break;
2402   }
2403   case OMPD_target_teams_distribute_parallel_for:
2404   case OMPD_target_teams_distribute_parallel_for_simd: {
2405     QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1).withConst();
2406     QualType KmpInt32PtrTy =
2407         Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
2408     QualType VoidPtrTy = Context.VoidPtrTy.withConst().withRestrict();
2409 
2410     QualType Args[] = {VoidPtrTy};
2411     FunctionProtoType::ExtProtoInfo EPI;
2412     EPI.Variadic = true;
2413     QualType CopyFnType = Context.getFunctionType(Context.VoidTy, Args, EPI);
2414     Sema::CapturedParamNameType Params[] = {
2415         std::make_pair(".global_tid.", KmpInt32Ty),
2416         std::make_pair(".part_id.", KmpInt32PtrTy),
2417         std::make_pair(".privates.", VoidPtrTy),
2418         std::make_pair(
2419             ".copy_fn.",
2420             Context.getPointerType(CopyFnType).withConst().withRestrict()),
2421         std::make_pair(".task_t.", Context.VoidPtrTy.withConst()),
2422         std::make_pair(StringRef(), QualType()) // __context with shared vars
2423     };
2424     ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
2425                              Params);
2426     // Mark this captured region as inlined, because we don't use outlined
2427     // function directly.
2428     getCurCapturedRegion()->TheCapturedDecl->addAttr(
2429         AlwaysInlineAttr::CreateImplicit(
2430             Context, AlwaysInlineAttr::Keyword_forceinline));
2431     Sema::CapturedParamNameType ParamsTarget[] = {
2432         std::make_pair(StringRef(), QualType()) // __context with shared vars
2433     };
2434     // Start a captured region for 'target' with no implicit parameters.
2435     ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
2436                              ParamsTarget);
2437 
2438     Sema::CapturedParamNameType ParamsTeams[] = {
2439         std::make_pair(".global_tid.", KmpInt32PtrTy),
2440         std::make_pair(".bound_tid.", KmpInt32PtrTy),
2441         std::make_pair(StringRef(), QualType()) // __context with shared vars
2442     };
2443     // Start a captured region for 'target' with no implicit parameters.
2444     ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
2445                              ParamsTeams);
2446 
2447     Sema::CapturedParamNameType ParamsParallel[] = {
2448         std::make_pair(".global_tid.", KmpInt32PtrTy),
2449         std::make_pair(".bound_tid.", KmpInt32PtrTy),
2450         std::make_pair(".previous.lb.", Context.getSizeType().withConst()),
2451         std::make_pair(".previous.ub.", Context.getSizeType().withConst()),
2452         std::make_pair(StringRef(), QualType()) // __context with shared vars
2453     };
2454     // Start a captured region for 'teams' or 'parallel'.  Both regions have
2455     // the same implicit parameters.
2456     ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
2457                              ParamsParallel);
2458     break;
2459   }
2460 
2461   case OMPD_teams_distribute_parallel_for:
2462   case OMPD_teams_distribute_parallel_for_simd: {
2463     QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1).withConst();
2464     QualType KmpInt32PtrTy =
2465         Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
2466 
2467     Sema::CapturedParamNameType ParamsTeams[] = {
2468         std::make_pair(".global_tid.", KmpInt32PtrTy),
2469         std::make_pair(".bound_tid.", KmpInt32PtrTy),
2470         std::make_pair(StringRef(), QualType()) // __context with shared vars
2471     };
2472     // Start a captured region for 'target' with no implicit parameters.
2473     ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
2474                              ParamsTeams);
2475 
2476     Sema::CapturedParamNameType ParamsParallel[] = {
2477         std::make_pair(".global_tid.", KmpInt32PtrTy),
2478         std::make_pair(".bound_tid.", KmpInt32PtrTy),
2479         std::make_pair(".previous.lb.", Context.getSizeType().withConst()),
2480         std::make_pair(".previous.ub.", Context.getSizeType().withConst()),
2481         std::make_pair(StringRef(), QualType()) // __context with shared vars
2482     };
2483     // Start a captured region for 'teams' or 'parallel'.  Both regions have
2484     // the same implicit parameters.
2485     ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
2486                              ParamsParallel);
2487     break;
2488   }
2489   case OMPD_target_update:
2490   case OMPD_target_enter_data:
2491   case OMPD_target_exit_data: {
2492     QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1).withConst();
2493     QualType VoidPtrTy = Context.VoidPtrTy.withConst().withRestrict();
2494     QualType KmpInt32PtrTy =
2495         Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
2496     QualType Args[] = {VoidPtrTy};
2497     FunctionProtoType::ExtProtoInfo EPI;
2498     EPI.Variadic = true;
2499     QualType CopyFnType = Context.getFunctionType(Context.VoidTy, Args, EPI);
2500     Sema::CapturedParamNameType Params[] = {
2501         std::make_pair(".global_tid.", KmpInt32Ty),
2502         std::make_pair(".part_id.", KmpInt32PtrTy),
2503         std::make_pair(".privates.", VoidPtrTy),
2504         std::make_pair(
2505             ".copy_fn.",
2506             Context.getPointerType(CopyFnType).withConst().withRestrict()),
2507         std::make_pair(".task_t.", Context.VoidPtrTy.withConst()),
2508         std::make_pair(StringRef(), QualType()) // __context with shared vars
2509     };
2510     ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
2511                              Params);
2512     // Mark this captured region as inlined, because we don't use outlined
2513     // function directly.
2514     getCurCapturedRegion()->TheCapturedDecl->addAttr(
2515         AlwaysInlineAttr::CreateImplicit(
2516             Context, AlwaysInlineAttr::Keyword_forceinline));
2517     break;
2518   }
2519   case OMPD_threadprivate:
2520   case OMPD_taskyield:
2521   case OMPD_barrier:
2522   case OMPD_taskwait:
2523   case OMPD_cancellation_point:
2524   case OMPD_cancel:
2525   case OMPD_flush:
2526   case OMPD_declare_reduction:
2527   case OMPD_declare_simd:
2528   case OMPD_declare_target:
2529   case OMPD_end_declare_target:
2530     llvm_unreachable("OpenMP Directive is not allowed");
2531   case OMPD_unknown:
2532     llvm_unreachable("Unknown OpenMP directive");
2533   }
2534 }
2535 
2536 int Sema::getOpenMPCaptureLevels(OpenMPDirectiveKind DKind) {
2537   SmallVector<OpenMPDirectiveKind, 4> CaptureRegions;
2538   getOpenMPCaptureRegions(CaptureRegions, DKind);
2539   return CaptureRegions.size();
2540 }
2541 
2542 static OMPCapturedExprDecl *buildCaptureDecl(Sema &S, IdentifierInfo *Id,
2543                                              Expr *CaptureExpr, bool WithInit,
2544                                              bool AsExpression) {
2545   assert(CaptureExpr);
2546   ASTContext &C = S.getASTContext();
2547   Expr *Init = AsExpression ? CaptureExpr : CaptureExpr->IgnoreImpCasts();
2548   QualType Ty = Init->getType();
2549   if (CaptureExpr->getObjectKind() == OK_Ordinary && CaptureExpr->isGLValue()) {
2550     if (S.getLangOpts().CPlusPlus) {
2551       Ty = C.getLValueReferenceType(Ty);
2552     } else {
2553       Ty = C.getPointerType(Ty);
2554       ExprResult Res =
2555           S.CreateBuiltinUnaryOp(CaptureExpr->getExprLoc(), UO_AddrOf, Init);
2556       if (!Res.isUsable())
2557         return nullptr;
2558       Init = Res.get();
2559     }
2560     WithInit = true;
2561   }
2562   auto *CED = OMPCapturedExprDecl::Create(C, S.CurContext, Id, Ty,
2563                                           CaptureExpr->getLocStart());
2564   if (!WithInit)
2565     CED->addAttr(OMPCaptureNoInitAttr::CreateImplicit(C));
2566   S.CurContext->addHiddenDecl(CED);
2567   S.AddInitializerToDecl(CED, Init, /*DirectInit=*/false);
2568   return CED;
2569 }
2570 
2571 static DeclRefExpr *buildCapture(Sema &S, ValueDecl *D, Expr *CaptureExpr,
2572                                  bool WithInit) {
2573   OMPCapturedExprDecl *CD;
2574   if (VarDecl *VD = S.isOpenMPCapturedDecl(D))
2575     CD = cast<OMPCapturedExprDecl>(VD);
2576   else
2577     CD = buildCaptureDecl(S, D->getIdentifier(), CaptureExpr, WithInit,
2578                           /*AsExpression=*/false);
2579   return buildDeclRefExpr(S, CD, CD->getType().getNonReferenceType(),
2580                           CaptureExpr->getExprLoc());
2581 }
2582 
2583 static ExprResult buildCapture(Sema &S, Expr *CaptureExpr, DeclRefExpr *&Ref) {
2584   CaptureExpr = S.DefaultLvalueConversion(CaptureExpr).get();
2585   if (!Ref) {
2586     OMPCapturedExprDecl *CD = buildCaptureDecl(
2587         S, &S.getASTContext().Idents.get(".capture_expr."), CaptureExpr,
2588         /*WithInit=*/true, /*AsExpression=*/true);
2589     Ref = buildDeclRefExpr(S, CD, CD->getType().getNonReferenceType(),
2590                            CaptureExpr->getExprLoc());
2591   }
2592   ExprResult Res = Ref;
2593   if (!S.getLangOpts().CPlusPlus &&
2594       CaptureExpr->getObjectKind() == OK_Ordinary && CaptureExpr->isGLValue() &&
2595       Ref->getType()->isPointerType()) {
2596     Res = S.CreateBuiltinUnaryOp(CaptureExpr->getExprLoc(), UO_Deref, Ref);
2597     if (!Res.isUsable())
2598       return ExprError();
2599   }
2600   return S.DefaultLvalueConversion(Res.get());
2601 }
2602 
2603 namespace {
2604 // OpenMP directives parsed in this section are represented as a
2605 // CapturedStatement with an associated statement.  If a syntax error
2606 // is detected during the parsing of the associated statement, the
2607 // compiler must abort processing and close the CapturedStatement.
2608 //
2609 // Combined directives such as 'target parallel' have more than one
2610 // nested CapturedStatements.  This RAII ensures that we unwind out
2611 // of all the nested CapturedStatements when an error is found.
2612 class CaptureRegionUnwinderRAII {
2613 private:
2614   Sema &S;
2615   bool &ErrorFound;
2616   OpenMPDirectiveKind DKind = OMPD_unknown;
2617 
2618 public:
2619   CaptureRegionUnwinderRAII(Sema &S, bool &ErrorFound,
2620                             OpenMPDirectiveKind DKind)
2621       : S(S), ErrorFound(ErrorFound), DKind(DKind) {}
2622   ~CaptureRegionUnwinderRAII() {
2623     if (ErrorFound) {
2624       int ThisCaptureLevel = S.getOpenMPCaptureLevels(DKind);
2625       while (--ThisCaptureLevel >= 0)
2626         S.ActOnCapturedRegionError();
2627     }
2628   }
2629 };
2630 } // namespace
2631 
2632 StmtResult Sema::ActOnOpenMPRegionEnd(StmtResult S,
2633                                       ArrayRef<OMPClause *> Clauses) {
2634   bool ErrorFound = false;
2635   CaptureRegionUnwinderRAII CaptureRegionUnwinder(
2636       *this, ErrorFound, DSAStack->getCurrentDirective());
2637   if (!S.isUsable()) {
2638     ErrorFound = true;
2639     return StmtError();
2640   }
2641 
2642   SmallVector<OpenMPDirectiveKind, 4> CaptureRegions;
2643   getOpenMPCaptureRegions(CaptureRegions, DSAStack->getCurrentDirective());
2644   OMPOrderedClause *OC = nullptr;
2645   OMPScheduleClause *SC = nullptr;
2646   SmallVector<const OMPLinearClause *, 4> LCs;
2647   SmallVector<const OMPClauseWithPreInit *, 4> PICs;
2648   // This is required for proper codegen.
2649   for (OMPClause *Clause : Clauses) {
2650     if (isOpenMPTaskingDirective(DSAStack->getCurrentDirective()) &&
2651         Clause->getClauseKind() == OMPC_in_reduction) {
2652       // Capture taskgroup task_reduction descriptors inside the tasking regions
2653       // with the corresponding in_reduction items.
2654       auto *IRC = cast<OMPInReductionClause>(Clause);
2655       for (Expr *E : IRC->taskgroup_descriptors())
2656         if (E)
2657           MarkDeclarationsReferencedInExpr(E);
2658     }
2659     if (isOpenMPPrivate(Clause->getClauseKind()) ||
2660         Clause->getClauseKind() == OMPC_copyprivate ||
2661         (getLangOpts().OpenMPUseTLS &&
2662          getASTContext().getTargetInfo().isTLSSupported() &&
2663          Clause->getClauseKind() == OMPC_copyin)) {
2664       DSAStack->setForceVarCapturing(Clause->getClauseKind() == OMPC_copyin);
2665       // Mark all variables in private list clauses as used in inner region.
2666       for (Stmt *VarRef : Clause->children()) {
2667         if (auto *E = cast_or_null<Expr>(VarRef)) {
2668           MarkDeclarationsReferencedInExpr(E);
2669         }
2670       }
2671       DSAStack->setForceVarCapturing(/*V=*/false);
2672     } else if (CaptureRegions.size() > 1 ||
2673                CaptureRegions.back() != OMPD_unknown) {
2674       if (auto *C = OMPClauseWithPreInit::get(Clause))
2675         PICs.push_back(C);
2676       if (auto *C = OMPClauseWithPostUpdate::get(Clause)) {
2677         if (Expr *E = C->getPostUpdateExpr())
2678           MarkDeclarationsReferencedInExpr(E);
2679       }
2680     }
2681     if (Clause->getClauseKind() == OMPC_schedule)
2682       SC = cast<OMPScheduleClause>(Clause);
2683     else if (Clause->getClauseKind() == OMPC_ordered)
2684       OC = cast<OMPOrderedClause>(Clause);
2685     else if (Clause->getClauseKind() == OMPC_linear)
2686       LCs.push_back(cast<OMPLinearClause>(Clause));
2687   }
2688   // OpenMP, 2.7.1 Loop Construct, Restrictions
2689   // The nonmonotonic modifier cannot be specified if an ordered clause is
2690   // specified.
2691   if (SC &&
2692       (SC->getFirstScheduleModifier() == OMPC_SCHEDULE_MODIFIER_nonmonotonic ||
2693        SC->getSecondScheduleModifier() ==
2694            OMPC_SCHEDULE_MODIFIER_nonmonotonic) &&
2695       OC) {
2696     Diag(SC->getFirstScheduleModifier() == OMPC_SCHEDULE_MODIFIER_nonmonotonic
2697              ? SC->getFirstScheduleModifierLoc()
2698              : SC->getSecondScheduleModifierLoc(),
2699          diag::err_omp_schedule_nonmonotonic_ordered)
2700         << SourceRange(OC->getLocStart(), OC->getLocEnd());
2701     ErrorFound = true;
2702   }
2703   if (!LCs.empty() && OC && OC->getNumForLoops()) {
2704     for (const OMPLinearClause *C : LCs) {
2705       Diag(C->getLocStart(), diag::err_omp_linear_ordered)
2706           << SourceRange(OC->getLocStart(), OC->getLocEnd());
2707     }
2708     ErrorFound = true;
2709   }
2710   if (isOpenMPWorksharingDirective(DSAStack->getCurrentDirective()) &&
2711       isOpenMPSimdDirective(DSAStack->getCurrentDirective()) && OC &&
2712       OC->getNumForLoops()) {
2713     Diag(OC->getLocStart(), diag::err_omp_ordered_simd)
2714         << getOpenMPDirectiveName(DSAStack->getCurrentDirective());
2715     ErrorFound = true;
2716   }
2717   if (ErrorFound) {
2718     return StmtError();
2719   }
2720   StmtResult SR = S;
2721   for (OpenMPDirectiveKind ThisCaptureRegion : llvm::reverse(CaptureRegions)) {
2722     // Mark all variables in private list clauses as used in inner region.
2723     // Required for proper codegen of combined directives.
2724     // TODO: add processing for other clauses.
2725     if (ThisCaptureRegion != OMPD_unknown) {
2726       for (const clang::OMPClauseWithPreInit *C : PICs) {
2727         OpenMPDirectiveKind CaptureRegion = C->getCaptureRegion();
2728         // Find the particular capture region for the clause if the
2729         // directive is a combined one with multiple capture regions.
2730         // If the directive is not a combined one, the capture region
2731         // associated with the clause is OMPD_unknown and is generated
2732         // only once.
2733         if (CaptureRegion == ThisCaptureRegion ||
2734             CaptureRegion == OMPD_unknown) {
2735           if (auto *DS = cast_or_null<DeclStmt>(C->getPreInitStmt())) {
2736             for (Decl *D : DS->decls())
2737               MarkVariableReferenced(D->getLocation(), cast<VarDecl>(D));
2738           }
2739         }
2740       }
2741     }
2742     SR = ActOnCapturedRegionEnd(SR.get());
2743   }
2744   return SR;
2745 }
2746 
2747 static bool checkCancelRegion(Sema &SemaRef, OpenMPDirectiveKind CurrentRegion,
2748                               OpenMPDirectiveKind CancelRegion,
2749                               SourceLocation StartLoc) {
2750   // CancelRegion is only needed for cancel and cancellation_point.
2751   if (CurrentRegion != OMPD_cancel && CurrentRegion != OMPD_cancellation_point)
2752     return false;
2753 
2754   if (CancelRegion == OMPD_parallel || CancelRegion == OMPD_for ||
2755       CancelRegion == OMPD_sections || CancelRegion == OMPD_taskgroup)
2756     return false;
2757 
2758   SemaRef.Diag(StartLoc, diag::err_omp_wrong_cancel_region)
2759       << getOpenMPDirectiveName(CancelRegion);
2760   return true;
2761 }
2762 
2763 static bool checkNestingOfRegions(Sema &SemaRef, const DSAStackTy *Stack,
2764                                   OpenMPDirectiveKind CurrentRegion,
2765                                   const DeclarationNameInfo &CurrentName,
2766                                   OpenMPDirectiveKind CancelRegion,
2767                                   SourceLocation StartLoc) {
2768   if (Stack->getCurScope()) {
2769     OpenMPDirectiveKind ParentRegion = Stack->getParentDirective();
2770     OpenMPDirectiveKind OffendingRegion = ParentRegion;
2771     bool NestingProhibited = false;
2772     bool CloseNesting = true;
2773     bool OrphanSeen = false;
2774     enum {
2775       NoRecommend,
2776       ShouldBeInParallelRegion,
2777       ShouldBeInOrderedRegion,
2778       ShouldBeInTargetRegion,
2779       ShouldBeInTeamsRegion
2780     } Recommend = NoRecommend;
2781     if (isOpenMPSimdDirective(ParentRegion) && CurrentRegion != OMPD_ordered) {
2782       // OpenMP [2.16, Nesting of Regions]
2783       // OpenMP constructs may not be nested inside a simd region.
2784       // OpenMP [2.8.1,simd Construct, Restrictions]
2785       // An ordered construct with the simd clause is the only OpenMP
2786       // construct that can appear in the simd region.
2787       // Allowing a SIMD construct nested in another SIMD construct is an
2788       // extension. The OpenMP 4.5 spec does not allow it. Issue a warning
2789       // message.
2790       SemaRef.Diag(StartLoc, (CurrentRegion != OMPD_simd)
2791                                  ? diag::err_omp_prohibited_region_simd
2792                                  : diag::warn_omp_nesting_simd);
2793       return CurrentRegion != OMPD_simd;
2794     }
2795     if (ParentRegion == OMPD_atomic) {
2796       // OpenMP [2.16, Nesting of Regions]
2797       // OpenMP constructs may not be nested inside an atomic region.
2798       SemaRef.Diag(StartLoc, diag::err_omp_prohibited_region_atomic);
2799       return true;
2800     }
2801     if (CurrentRegion == OMPD_section) {
2802       // OpenMP [2.7.2, sections Construct, Restrictions]
2803       // Orphaned section directives are prohibited. That is, the section
2804       // directives must appear within the sections construct and must not be
2805       // encountered elsewhere in the sections region.
2806       if (ParentRegion != OMPD_sections &&
2807           ParentRegion != OMPD_parallel_sections) {
2808         SemaRef.Diag(StartLoc, diag::err_omp_orphaned_section_directive)
2809             << (ParentRegion != OMPD_unknown)
2810             << getOpenMPDirectiveName(ParentRegion);
2811         return true;
2812       }
2813       return false;
2814     }
2815     // Allow some constructs (except teams) to be orphaned (they could be
2816     // used in functions, called from OpenMP regions with the required
2817     // preconditions).
2818     if (ParentRegion == OMPD_unknown &&
2819         !isOpenMPNestingTeamsDirective(CurrentRegion))
2820       return false;
2821     if (CurrentRegion == OMPD_cancellation_point ||
2822         CurrentRegion == OMPD_cancel) {
2823       // OpenMP [2.16, Nesting of Regions]
2824       // A cancellation point construct for which construct-type-clause is
2825       // taskgroup must be nested inside a task construct. A cancellation
2826       // point construct for which construct-type-clause is not taskgroup must
2827       // be closely nested inside an OpenMP construct that matches the type
2828       // specified in construct-type-clause.
2829       // A cancel construct for which construct-type-clause is taskgroup must be
2830       // nested inside a task construct. A cancel construct for which
2831       // construct-type-clause is not taskgroup must be closely nested inside an
2832       // OpenMP construct that matches the type specified in
2833       // construct-type-clause.
2834       NestingProhibited =
2835           !((CancelRegion == OMPD_parallel &&
2836              (ParentRegion == OMPD_parallel ||
2837               ParentRegion == OMPD_target_parallel)) ||
2838             (CancelRegion == OMPD_for &&
2839              (ParentRegion == OMPD_for || ParentRegion == OMPD_parallel_for ||
2840               ParentRegion == OMPD_target_parallel_for ||
2841               ParentRegion == OMPD_distribute_parallel_for ||
2842               ParentRegion == OMPD_teams_distribute_parallel_for ||
2843               ParentRegion == OMPD_target_teams_distribute_parallel_for)) ||
2844             (CancelRegion == OMPD_taskgroup && ParentRegion == OMPD_task) ||
2845             (CancelRegion == OMPD_sections &&
2846              (ParentRegion == OMPD_section || ParentRegion == OMPD_sections ||
2847               ParentRegion == OMPD_parallel_sections)));
2848     } else if (CurrentRegion == OMPD_master) {
2849       // OpenMP [2.16, Nesting of Regions]
2850       // A master region may not be closely nested inside a worksharing,
2851       // atomic, or explicit task region.
2852       NestingProhibited = isOpenMPWorksharingDirective(ParentRegion) ||
2853                           isOpenMPTaskingDirective(ParentRegion);
2854     } else if (CurrentRegion == OMPD_critical && CurrentName.getName()) {
2855       // OpenMP [2.16, Nesting of Regions]
2856       // A critical region may not be nested (closely or otherwise) inside a
2857       // critical region with the same name. Note that this restriction is not
2858       // sufficient to prevent deadlock.
2859       SourceLocation PreviousCriticalLoc;
2860       bool DeadLock = Stack->hasDirective(
2861           [CurrentName, &PreviousCriticalLoc](OpenMPDirectiveKind K,
2862                                               const DeclarationNameInfo &DNI,
2863                                               SourceLocation Loc) {
2864             if (K == OMPD_critical && DNI.getName() == CurrentName.getName()) {
2865               PreviousCriticalLoc = Loc;
2866               return true;
2867             }
2868             return false;
2869           },
2870           false /* skip top directive */);
2871       if (DeadLock) {
2872         SemaRef.Diag(StartLoc,
2873                      diag::err_omp_prohibited_region_critical_same_name)
2874             << CurrentName.getName();
2875         if (PreviousCriticalLoc.isValid())
2876           SemaRef.Diag(PreviousCriticalLoc,
2877                        diag::note_omp_previous_critical_region);
2878         return true;
2879       }
2880     } else if (CurrentRegion == OMPD_barrier) {
2881       // OpenMP [2.16, Nesting of Regions]
2882       // A barrier region may not be closely nested inside a worksharing,
2883       // explicit task, critical, ordered, atomic, or master region.
2884       NestingProhibited = isOpenMPWorksharingDirective(ParentRegion) ||
2885                           isOpenMPTaskingDirective(ParentRegion) ||
2886                           ParentRegion == OMPD_master ||
2887                           ParentRegion == OMPD_critical ||
2888                           ParentRegion == OMPD_ordered;
2889     } else if (isOpenMPWorksharingDirective(CurrentRegion) &&
2890                !isOpenMPParallelDirective(CurrentRegion) &&
2891                !isOpenMPTeamsDirective(CurrentRegion)) {
2892       // OpenMP [2.16, Nesting of Regions]
2893       // A worksharing region may not be closely nested inside a worksharing,
2894       // explicit task, critical, ordered, atomic, or master region.
2895       NestingProhibited = isOpenMPWorksharingDirective(ParentRegion) ||
2896                           isOpenMPTaskingDirective(ParentRegion) ||
2897                           ParentRegion == OMPD_master ||
2898                           ParentRegion == OMPD_critical ||
2899                           ParentRegion == OMPD_ordered;
2900       Recommend = ShouldBeInParallelRegion;
2901     } else if (CurrentRegion == OMPD_ordered) {
2902       // OpenMP [2.16, Nesting of Regions]
2903       // An ordered region may not be closely nested inside a critical,
2904       // atomic, or explicit task region.
2905       // An ordered region must be closely nested inside a loop region (or
2906       // parallel loop region) with an ordered clause.
2907       // OpenMP [2.8.1,simd Construct, Restrictions]
2908       // An ordered construct with the simd clause is the only OpenMP construct
2909       // that can appear in the simd region.
2910       NestingProhibited = ParentRegion == OMPD_critical ||
2911                           isOpenMPTaskingDirective(ParentRegion) ||
2912                           !(isOpenMPSimdDirective(ParentRegion) ||
2913                             Stack->isParentOrderedRegion());
2914       Recommend = ShouldBeInOrderedRegion;
2915     } else if (isOpenMPNestingTeamsDirective(CurrentRegion)) {
2916       // OpenMP [2.16, Nesting of Regions]
2917       // If specified, a teams construct must be contained within a target
2918       // construct.
2919       NestingProhibited = ParentRegion != OMPD_target;
2920       OrphanSeen = ParentRegion == OMPD_unknown;
2921       Recommend = ShouldBeInTargetRegion;
2922     }
2923     if (!NestingProhibited &&
2924         !isOpenMPTargetExecutionDirective(CurrentRegion) &&
2925         !isOpenMPTargetDataManagementDirective(CurrentRegion) &&
2926         (ParentRegion == OMPD_teams || ParentRegion == OMPD_target_teams)) {
2927       // OpenMP [2.16, Nesting of Regions]
2928       // distribute, parallel, parallel sections, parallel workshare, and the
2929       // parallel loop and parallel loop SIMD constructs are the only OpenMP
2930       // constructs that can be closely nested in the teams region.
2931       NestingProhibited = !isOpenMPParallelDirective(CurrentRegion) &&
2932                           !isOpenMPDistributeDirective(CurrentRegion);
2933       Recommend = ShouldBeInParallelRegion;
2934     }
2935     if (!NestingProhibited &&
2936         isOpenMPNestingDistributeDirective(CurrentRegion)) {
2937       // OpenMP 4.5 [2.17 Nesting of Regions]
2938       // The region associated with the distribute construct must be strictly
2939       // nested inside a teams region
2940       NestingProhibited =
2941           (ParentRegion != OMPD_teams && ParentRegion != OMPD_target_teams);
2942       Recommend = ShouldBeInTeamsRegion;
2943     }
2944     if (!NestingProhibited &&
2945         (isOpenMPTargetExecutionDirective(CurrentRegion) ||
2946          isOpenMPTargetDataManagementDirective(CurrentRegion))) {
2947       // OpenMP 4.5 [2.17 Nesting of Regions]
2948       // If a target, target update, target data, target enter data, or
2949       // target exit data construct is encountered during execution of a
2950       // target region, the behavior is unspecified.
2951       NestingProhibited = Stack->hasDirective(
2952           [&OffendingRegion](OpenMPDirectiveKind K, const DeclarationNameInfo &,
2953                              SourceLocation) {
2954             if (isOpenMPTargetExecutionDirective(K)) {
2955               OffendingRegion = K;
2956               return true;
2957             }
2958             return false;
2959           },
2960           false /* don't skip top directive */);
2961       CloseNesting = false;
2962     }
2963     if (NestingProhibited) {
2964       if (OrphanSeen) {
2965         SemaRef.Diag(StartLoc, diag::err_omp_orphaned_device_directive)
2966             << getOpenMPDirectiveName(CurrentRegion) << Recommend;
2967       } else {
2968         SemaRef.Diag(StartLoc, diag::err_omp_prohibited_region)
2969             << CloseNesting << getOpenMPDirectiveName(OffendingRegion)
2970             << Recommend << getOpenMPDirectiveName(CurrentRegion);
2971       }
2972       return true;
2973     }
2974   }
2975   return false;
2976 }
2977 
2978 static bool checkIfClauses(Sema &S, OpenMPDirectiveKind Kind,
2979                            ArrayRef<OMPClause *> Clauses,
2980                            ArrayRef<OpenMPDirectiveKind> AllowedNameModifiers) {
2981   bool ErrorFound = false;
2982   unsigned NamedModifiersNumber = 0;
2983   SmallVector<const OMPIfClause *, OMPC_unknown + 1> FoundNameModifiers(
2984       OMPD_unknown + 1);
2985   SmallVector<SourceLocation, 4> NameModifierLoc;
2986   for (const OMPClause *C : Clauses) {
2987     if (const auto *IC = dyn_cast_or_null<OMPIfClause>(C)) {
2988       // At most one if clause without a directive-name-modifier can appear on
2989       // the directive.
2990       OpenMPDirectiveKind CurNM = IC->getNameModifier();
2991       if (FoundNameModifiers[CurNM]) {
2992         S.Diag(C->getLocStart(), diag::err_omp_more_one_clause)
2993             << getOpenMPDirectiveName(Kind) << getOpenMPClauseName(OMPC_if)
2994             << (CurNM != OMPD_unknown) << getOpenMPDirectiveName(CurNM);
2995         ErrorFound = true;
2996       } else if (CurNM != OMPD_unknown) {
2997         NameModifierLoc.push_back(IC->getNameModifierLoc());
2998         ++NamedModifiersNumber;
2999       }
3000       FoundNameModifiers[CurNM] = IC;
3001       if (CurNM == OMPD_unknown)
3002         continue;
3003       // Check if the specified name modifier is allowed for the current
3004       // directive.
3005       // At most one if clause with the particular directive-name-modifier can
3006       // appear on the directive.
3007       bool MatchFound = false;
3008       for (auto NM : AllowedNameModifiers) {
3009         if (CurNM == NM) {
3010           MatchFound = true;
3011           break;
3012         }
3013       }
3014       if (!MatchFound) {
3015         S.Diag(IC->getNameModifierLoc(),
3016                diag::err_omp_wrong_if_directive_name_modifier)
3017             << getOpenMPDirectiveName(CurNM) << getOpenMPDirectiveName(Kind);
3018         ErrorFound = true;
3019       }
3020     }
3021   }
3022   // If any if clause on the directive includes a directive-name-modifier then
3023   // all if clauses on the directive must include a directive-name-modifier.
3024   if (FoundNameModifiers[OMPD_unknown] && NamedModifiersNumber > 0) {
3025     if (NamedModifiersNumber == AllowedNameModifiers.size()) {
3026       S.Diag(FoundNameModifiers[OMPD_unknown]->getLocStart(),
3027              diag::err_omp_no_more_if_clause);
3028     } else {
3029       std::string Values;
3030       std::string Sep(", ");
3031       unsigned AllowedCnt = 0;
3032       unsigned TotalAllowedNum =
3033           AllowedNameModifiers.size() - NamedModifiersNumber;
3034       for (unsigned Cnt = 0, End = AllowedNameModifiers.size(); Cnt < End;
3035            ++Cnt) {
3036         OpenMPDirectiveKind NM = AllowedNameModifiers[Cnt];
3037         if (!FoundNameModifiers[NM]) {
3038           Values += "'";
3039           Values += getOpenMPDirectiveName(NM);
3040           Values += "'";
3041           if (AllowedCnt + 2 == TotalAllowedNum)
3042             Values += " or ";
3043           else if (AllowedCnt + 1 != TotalAllowedNum)
3044             Values += Sep;
3045           ++AllowedCnt;
3046         }
3047       }
3048       S.Diag(FoundNameModifiers[OMPD_unknown]->getCondition()->getLocStart(),
3049              diag::err_omp_unnamed_if_clause)
3050           << (TotalAllowedNum > 1) << Values;
3051     }
3052     for (SourceLocation Loc : NameModifierLoc) {
3053       S.Diag(Loc, diag::note_omp_previous_named_if_clause);
3054     }
3055     ErrorFound = true;
3056   }
3057   return ErrorFound;
3058 }
3059 
3060 StmtResult Sema::ActOnOpenMPExecutableDirective(
3061     OpenMPDirectiveKind Kind, const DeclarationNameInfo &DirName,
3062     OpenMPDirectiveKind CancelRegion, ArrayRef<OMPClause *> Clauses,
3063     Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc) {
3064   StmtResult Res = StmtError();
3065   // First check CancelRegion which is then used in checkNestingOfRegions.
3066   if (checkCancelRegion(*this, Kind, CancelRegion, StartLoc) ||
3067       checkNestingOfRegions(*this, DSAStack, Kind, DirName, CancelRegion,
3068                             StartLoc))
3069     return StmtError();
3070 
3071   llvm::SmallVector<OMPClause *, 8> ClausesWithImplicit;
3072   VarsWithInheritedDSAType VarsWithInheritedDSA;
3073   bool ErrorFound = false;
3074   ClausesWithImplicit.append(Clauses.begin(), Clauses.end());
3075   if (AStmt && !CurContext->isDependentContext()) {
3076     assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
3077 
3078     // Check default data sharing attributes for referenced variables.
3079     DSAAttrChecker DSAChecker(DSAStack, *this, cast<CapturedStmt>(AStmt));
3080     int ThisCaptureLevel = getOpenMPCaptureLevels(Kind);
3081     Stmt *S = AStmt;
3082     while (--ThisCaptureLevel >= 0)
3083       S = cast<CapturedStmt>(S)->getCapturedStmt();
3084     DSAChecker.Visit(S);
3085     if (DSAChecker.isErrorFound())
3086       return StmtError();
3087     // Generate list of implicitly defined firstprivate variables.
3088     VarsWithInheritedDSA = DSAChecker.getVarsWithInheritedDSA();
3089 
3090     SmallVector<Expr *, 4> ImplicitFirstprivates(
3091         DSAChecker.getImplicitFirstprivate().begin(),
3092         DSAChecker.getImplicitFirstprivate().end());
3093     SmallVector<Expr *, 4> ImplicitMaps(DSAChecker.getImplicitMap().begin(),
3094                                         DSAChecker.getImplicitMap().end());
3095     // Mark taskgroup task_reduction descriptors as implicitly firstprivate.
3096     for (OMPClause *C : Clauses) {
3097       if (auto *IRC = dyn_cast<OMPInReductionClause>(C)) {
3098         for (Expr *E : IRC->taskgroup_descriptors())
3099           if (E)
3100             ImplicitFirstprivates.emplace_back(E);
3101       }
3102     }
3103     if (!ImplicitFirstprivates.empty()) {
3104       if (OMPClause *Implicit = ActOnOpenMPFirstprivateClause(
3105               ImplicitFirstprivates, SourceLocation(), SourceLocation(),
3106               SourceLocation())) {
3107         ClausesWithImplicit.push_back(Implicit);
3108         ErrorFound = cast<OMPFirstprivateClause>(Implicit)->varlist_size() !=
3109                      ImplicitFirstprivates.size();
3110       } else {
3111         ErrorFound = true;
3112       }
3113     }
3114     if (!ImplicitMaps.empty()) {
3115       if (OMPClause *Implicit = ActOnOpenMPMapClause(
3116               OMPC_MAP_unknown, OMPC_MAP_tofrom, /*IsMapTypeImplicit=*/true,
3117               SourceLocation(), SourceLocation(), ImplicitMaps,
3118               SourceLocation(), SourceLocation(), SourceLocation())) {
3119         ClausesWithImplicit.emplace_back(Implicit);
3120         ErrorFound |=
3121             cast<OMPMapClause>(Implicit)->varlist_size() != ImplicitMaps.size();
3122       } else {
3123         ErrorFound = true;
3124       }
3125     }
3126   }
3127 
3128   llvm::SmallVector<OpenMPDirectiveKind, 4> AllowedNameModifiers;
3129   switch (Kind) {
3130   case OMPD_parallel:
3131     Res = ActOnOpenMPParallelDirective(ClausesWithImplicit, AStmt, StartLoc,
3132                                        EndLoc);
3133     AllowedNameModifiers.push_back(OMPD_parallel);
3134     break;
3135   case OMPD_simd:
3136     Res = ActOnOpenMPSimdDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc,
3137                                    VarsWithInheritedDSA);
3138     break;
3139   case OMPD_for:
3140     Res = ActOnOpenMPForDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc,
3141                                   VarsWithInheritedDSA);
3142     break;
3143   case OMPD_for_simd:
3144     Res = ActOnOpenMPForSimdDirective(ClausesWithImplicit, AStmt, StartLoc,
3145                                       EndLoc, VarsWithInheritedDSA);
3146     break;
3147   case OMPD_sections:
3148     Res = ActOnOpenMPSectionsDirective(ClausesWithImplicit, AStmt, StartLoc,
3149                                        EndLoc);
3150     break;
3151   case OMPD_section:
3152     assert(ClausesWithImplicit.empty() &&
3153            "No clauses are allowed for 'omp section' directive");
3154     Res = ActOnOpenMPSectionDirective(AStmt, StartLoc, EndLoc);
3155     break;
3156   case OMPD_single:
3157     Res = ActOnOpenMPSingleDirective(ClausesWithImplicit, AStmt, StartLoc,
3158                                      EndLoc);
3159     break;
3160   case OMPD_master:
3161     assert(ClausesWithImplicit.empty() &&
3162            "No clauses are allowed for 'omp master' directive");
3163     Res = ActOnOpenMPMasterDirective(AStmt, StartLoc, EndLoc);
3164     break;
3165   case OMPD_critical:
3166     Res = ActOnOpenMPCriticalDirective(DirName, ClausesWithImplicit, AStmt,
3167                                        StartLoc, EndLoc);
3168     break;
3169   case OMPD_parallel_for:
3170     Res = ActOnOpenMPParallelForDirective(ClausesWithImplicit, AStmt, StartLoc,
3171                                           EndLoc, VarsWithInheritedDSA);
3172     AllowedNameModifiers.push_back(OMPD_parallel);
3173     break;
3174   case OMPD_parallel_for_simd:
3175     Res = ActOnOpenMPParallelForSimdDirective(
3176         ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
3177     AllowedNameModifiers.push_back(OMPD_parallel);
3178     break;
3179   case OMPD_parallel_sections:
3180     Res = ActOnOpenMPParallelSectionsDirective(ClausesWithImplicit, AStmt,
3181                                                StartLoc, EndLoc);
3182     AllowedNameModifiers.push_back(OMPD_parallel);
3183     break;
3184   case OMPD_task:
3185     Res =
3186         ActOnOpenMPTaskDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc);
3187     AllowedNameModifiers.push_back(OMPD_task);
3188     break;
3189   case OMPD_taskyield:
3190     assert(ClausesWithImplicit.empty() &&
3191            "No clauses are allowed for 'omp taskyield' directive");
3192     assert(AStmt == nullptr &&
3193            "No associated statement allowed for 'omp taskyield' directive");
3194     Res = ActOnOpenMPTaskyieldDirective(StartLoc, EndLoc);
3195     break;
3196   case OMPD_barrier:
3197     assert(ClausesWithImplicit.empty() &&
3198            "No clauses are allowed for 'omp barrier' directive");
3199     assert(AStmt == nullptr &&
3200            "No associated statement allowed for 'omp barrier' directive");
3201     Res = ActOnOpenMPBarrierDirective(StartLoc, EndLoc);
3202     break;
3203   case OMPD_taskwait:
3204     assert(ClausesWithImplicit.empty() &&
3205            "No clauses are allowed for 'omp taskwait' directive");
3206     assert(AStmt == nullptr &&
3207            "No associated statement allowed for 'omp taskwait' directive");
3208     Res = ActOnOpenMPTaskwaitDirective(StartLoc, EndLoc);
3209     break;
3210   case OMPD_taskgroup:
3211     Res = ActOnOpenMPTaskgroupDirective(ClausesWithImplicit, AStmt, StartLoc,
3212                                         EndLoc);
3213     break;
3214   case OMPD_flush:
3215     assert(AStmt == nullptr &&
3216            "No associated statement allowed for 'omp flush' directive");
3217     Res = ActOnOpenMPFlushDirective(ClausesWithImplicit, StartLoc, EndLoc);
3218     break;
3219   case OMPD_ordered:
3220     Res = ActOnOpenMPOrderedDirective(ClausesWithImplicit, AStmt, StartLoc,
3221                                       EndLoc);
3222     break;
3223   case OMPD_atomic:
3224     Res = ActOnOpenMPAtomicDirective(ClausesWithImplicit, AStmt, StartLoc,
3225                                      EndLoc);
3226     break;
3227   case OMPD_teams:
3228     Res =
3229         ActOnOpenMPTeamsDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc);
3230     break;
3231   case OMPD_target:
3232     Res = ActOnOpenMPTargetDirective(ClausesWithImplicit, AStmt, StartLoc,
3233                                      EndLoc);
3234     AllowedNameModifiers.push_back(OMPD_target);
3235     break;
3236   case OMPD_target_parallel:
3237     Res = ActOnOpenMPTargetParallelDirective(ClausesWithImplicit, AStmt,
3238                                              StartLoc, EndLoc);
3239     AllowedNameModifiers.push_back(OMPD_target);
3240     AllowedNameModifiers.push_back(OMPD_parallel);
3241     break;
3242   case OMPD_target_parallel_for:
3243     Res = ActOnOpenMPTargetParallelForDirective(
3244         ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
3245     AllowedNameModifiers.push_back(OMPD_target);
3246     AllowedNameModifiers.push_back(OMPD_parallel);
3247     break;
3248   case OMPD_cancellation_point:
3249     assert(ClausesWithImplicit.empty() &&
3250            "No clauses are allowed for 'omp cancellation point' directive");
3251     assert(AStmt == nullptr && "No associated statement allowed for 'omp "
3252                                "cancellation point' directive");
3253     Res = ActOnOpenMPCancellationPointDirective(StartLoc, EndLoc, CancelRegion);
3254     break;
3255   case OMPD_cancel:
3256     assert(AStmt == nullptr &&
3257            "No associated statement allowed for 'omp cancel' directive");
3258     Res = ActOnOpenMPCancelDirective(ClausesWithImplicit, StartLoc, EndLoc,
3259                                      CancelRegion);
3260     AllowedNameModifiers.push_back(OMPD_cancel);
3261     break;
3262   case OMPD_target_data:
3263     Res = ActOnOpenMPTargetDataDirective(ClausesWithImplicit, AStmt, StartLoc,
3264                                          EndLoc);
3265     AllowedNameModifiers.push_back(OMPD_target_data);
3266     break;
3267   case OMPD_target_enter_data:
3268     Res = ActOnOpenMPTargetEnterDataDirective(ClausesWithImplicit, StartLoc,
3269                                               EndLoc, AStmt);
3270     AllowedNameModifiers.push_back(OMPD_target_enter_data);
3271     break;
3272   case OMPD_target_exit_data:
3273     Res = ActOnOpenMPTargetExitDataDirective(ClausesWithImplicit, StartLoc,
3274                                              EndLoc, AStmt);
3275     AllowedNameModifiers.push_back(OMPD_target_exit_data);
3276     break;
3277   case OMPD_taskloop:
3278     Res = ActOnOpenMPTaskLoopDirective(ClausesWithImplicit, AStmt, StartLoc,
3279                                        EndLoc, VarsWithInheritedDSA);
3280     AllowedNameModifiers.push_back(OMPD_taskloop);
3281     break;
3282   case OMPD_taskloop_simd:
3283     Res = ActOnOpenMPTaskLoopSimdDirective(ClausesWithImplicit, AStmt, StartLoc,
3284                                            EndLoc, VarsWithInheritedDSA);
3285     AllowedNameModifiers.push_back(OMPD_taskloop);
3286     break;
3287   case OMPD_distribute:
3288     Res = ActOnOpenMPDistributeDirective(ClausesWithImplicit, AStmt, StartLoc,
3289                                          EndLoc, VarsWithInheritedDSA);
3290     break;
3291   case OMPD_target_update:
3292     Res = ActOnOpenMPTargetUpdateDirective(ClausesWithImplicit, StartLoc,
3293                                            EndLoc, AStmt);
3294     AllowedNameModifiers.push_back(OMPD_target_update);
3295     break;
3296   case OMPD_distribute_parallel_for:
3297     Res = ActOnOpenMPDistributeParallelForDirective(
3298         ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
3299     AllowedNameModifiers.push_back(OMPD_parallel);
3300     break;
3301   case OMPD_distribute_parallel_for_simd:
3302     Res = ActOnOpenMPDistributeParallelForSimdDirective(
3303         ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
3304     AllowedNameModifiers.push_back(OMPD_parallel);
3305     break;
3306   case OMPD_distribute_simd:
3307     Res = ActOnOpenMPDistributeSimdDirective(
3308         ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
3309     break;
3310   case OMPD_target_parallel_for_simd:
3311     Res = ActOnOpenMPTargetParallelForSimdDirective(
3312         ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
3313     AllowedNameModifiers.push_back(OMPD_target);
3314     AllowedNameModifiers.push_back(OMPD_parallel);
3315     break;
3316   case OMPD_target_simd:
3317     Res = ActOnOpenMPTargetSimdDirective(ClausesWithImplicit, AStmt, StartLoc,
3318                                          EndLoc, VarsWithInheritedDSA);
3319     AllowedNameModifiers.push_back(OMPD_target);
3320     break;
3321   case OMPD_teams_distribute:
3322     Res = ActOnOpenMPTeamsDistributeDirective(
3323         ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
3324     break;
3325   case OMPD_teams_distribute_simd:
3326     Res = ActOnOpenMPTeamsDistributeSimdDirective(
3327         ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
3328     break;
3329   case OMPD_teams_distribute_parallel_for_simd:
3330     Res = ActOnOpenMPTeamsDistributeParallelForSimdDirective(
3331         ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
3332     AllowedNameModifiers.push_back(OMPD_parallel);
3333     break;
3334   case OMPD_teams_distribute_parallel_for:
3335     Res = ActOnOpenMPTeamsDistributeParallelForDirective(
3336         ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
3337     AllowedNameModifiers.push_back(OMPD_parallel);
3338     break;
3339   case OMPD_target_teams:
3340     Res = ActOnOpenMPTargetTeamsDirective(ClausesWithImplicit, AStmt, StartLoc,
3341                                           EndLoc);
3342     AllowedNameModifiers.push_back(OMPD_target);
3343     break;
3344   case OMPD_target_teams_distribute:
3345     Res = ActOnOpenMPTargetTeamsDistributeDirective(
3346         ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
3347     AllowedNameModifiers.push_back(OMPD_target);
3348     break;
3349   case OMPD_target_teams_distribute_parallel_for:
3350     Res = ActOnOpenMPTargetTeamsDistributeParallelForDirective(
3351         ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
3352     AllowedNameModifiers.push_back(OMPD_target);
3353     AllowedNameModifiers.push_back(OMPD_parallel);
3354     break;
3355   case OMPD_target_teams_distribute_parallel_for_simd:
3356     Res = ActOnOpenMPTargetTeamsDistributeParallelForSimdDirective(
3357         ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
3358     AllowedNameModifiers.push_back(OMPD_target);
3359     AllowedNameModifiers.push_back(OMPD_parallel);
3360     break;
3361   case OMPD_target_teams_distribute_simd:
3362     Res = ActOnOpenMPTargetTeamsDistributeSimdDirective(
3363         ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
3364     AllowedNameModifiers.push_back(OMPD_target);
3365     break;
3366   case OMPD_declare_target:
3367   case OMPD_end_declare_target:
3368   case OMPD_threadprivate:
3369   case OMPD_declare_reduction:
3370   case OMPD_declare_simd:
3371     llvm_unreachable("OpenMP Directive is not allowed");
3372   case OMPD_unknown:
3373     llvm_unreachable("Unknown OpenMP directive");
3374   }
3375 
3376   for (const auto &P : VarsWithInheritedDSA) {
3377     Diag(P.second->getExprLoc(), diag::err_omp_no_dsa_for_variable)
3378         << P.first << P.second->getSourceRange();
3379   }
3380   ErrorFound = !VarsWithInheritedDSA.empty() || ErrorFound;
3381 
3382   if (!AllowedNameModifiers.empty())
3383     ErrorFound = checkIfClauses(*this, Kind, Clauses, AllowedNameModifiers) ||
3384                  ErrorFound;
3385 
3386   if (ErrorFound)
3387     return StmtError();
3388   return Res;
3389 }
3390 
3391 Sema::DeclGroupPtrTy Sema::ActOnOpenMPDeclareSimdDirective(
3392     DeclGroupPtrTy DG, OMPDeclareSimdDeclAttr::BranchStateTy BS, Expr *Simdlen,
3393     ArrayRef<Expr *> Uniforms, ArrayRef<Expr *> Aligneds,
3394     ArrayRef<Expr *> Alignments, ArrayRef<Expr *> Linears,
3395     ArrayRef<unsigned> LinModifiers, ArrayRef<Expr *> Steps, SourceRange SR) {
3396   assert(Aligneds.size() == Alignments.size());
3397   assert(Linears.size() == LinModifiers.size());
3398   assert(Linears.size() == Steps.size());
3399   if (!DG || DG.get().isNull())
3400     return DeclGroupPtrTy();
3401 
3402   if (!DG.get().isSingleDecl()) {
3403     Diag(SR.getBegin(), diag::err_omp_single_decl_in_declare_simd);
3404     return DG;
3405   }
3406   Decl *ADecl = DG.get().getSingleDecl();
3407   if (auto *FTD = dyn_cast<FunctionTemplateDecl>(ADecl))
3408     ADecl = FTD->getTemplatedDecl();
3409 
3410   auto *FD = dyn_cast<FunctionDecl>(ADecl);
3411   if (!FD) {
3412     Diag(ADecl->getLocation(), diag::err_omp_function_expected);
3413     return DeclGroupPtrTy();
3414   }
3415 
3416   // OpenMP [2.8.2, declare simd construct, Description]
3417   // The parameter of the simdlen clause must be a constant positive integer
3418   // expression.
3419   ExprResult SL;
3420   if (Simdlen)
3421     SL = VerifyPositiveIntegerConstantInClause(Simdlen, OMPC_simdlen);
3422   // OpenMP [2.8.2, declare simd construct, Description]
3423   // The special this pointer can be used as if was one of the arguments to the
3424   // function in any of the linear, aligned, or uniform clauses.
3425   // The uniform clause declares one or more arguments to have an invariant
3426   // value for all concurrent invocations of the function in the execution of a
3427   // single SIMD loop.
3428   llvm::DenseMap<const Decl *, const Expr *> UniformedArgs;
3429   const Expr *UniformedLinearThis = nullptr;
3430   for (const Expr *E : Uniforms) {
3431     E = E->IgnoreParenImpCasts();
3432     if (const auto *DRE = dyn_cast<DeclRefExpr>(E))
3433       if (const auto *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl()))
3434         if (FD->getNumParams() > PVD->getFunctionScopeIndex() &&
3435             FD->getParamDecl(PVD->getFunctionScopeIndex())
3436                     ->getCanonicalDecl() == PVD->getCanonicalDecl()) {
3437           UniformedArgs.try_emplace(PVD->getCanonicalDecl(), E);
3438           continue;
3439         }
3440     if (isa<CXXThisExpr>(E)) {
3441       UniformedLinearThis = E;
3442       continue;
3443     }
3444     Diag(E->getExprLoc(), diag::err_omp_param_or_this_in_clause)
3445         << FD->getDeclName() << (isa<CXXMethodDecl>(ADecl) ? 1 : 0);
3446   }
3447   // OpenMP [2.8.2, declare simd construct, Description]
3448   // The aligned clause declares that the object to which each list item points
3449   // is aligned to the number of bytes expressed in the optional parameter of
3450   // the aligned clause.
3451   // The special this pointer can be used as if was one of the arguments to the
3452   // function in any of the linear, aligned, or uniform clauses.
3453   // The type of list items appearing in the aligned clause must be array,
3454   // pointer, reference to array, or reference to pointer.
3455   llvm::DenseMap<const Decl *, const Expr *> AlignedArgs;
3456   const Expr *AlignedThis = nullptr;
3457   for (const Expr *E : Aligneds) {
3458     E = E->IgnoreParenImpCasts();
3459     if (const auto *DRE = dyn_cast<DeclRefExpr>(E))
3460       if (const auto *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl())) {
3461         const VarDecl *CanonPVD = PVD->getCanonicalDecl();
3462         if (FD->getNumParams() > PVD->getFunctionScopeIndex() &&
3463             FD->getParamDecl(PVD->getFunctionScopeIndex())
3464                     ->getCanonicalDecl() == CanonPVD) {
3465           // OpenMP  [2.8.1, simd construct, Restrictions]
3466           // A list-item cannot appear in more than one aligned clause.
3467           if (AlignedArgs.count(CanonPVD) > 0) {
3468             Diag(E->getExprLoc(), diag::err_omp_aligned_twice)
3469                 << 1 << E->getSourceRange();
3470             Diag(AlignedArgs[CanonPVD]->getExprLoc(),
3471                  diag::note_omp_explicit_dsa)
3472                 << getOpenMPClauseName(OMPC_aligned);
3473             continue;
3474           }
3475           AlignedArgs[CanonPVD] = E;
3476           QualType QTy = PVD->getType()
3477                              .getNonReferenceType()
3478                              .getUnqualifiedType()
3479                              .getCanonicalType();
3480           const Type *Ty = QTy.getTypePtrOrNull();
3481           if (!Ty || (!Ty->isArrayType() && !Ty->isPointerType())) {
3482             Diag(E->getExprLoc(), diag::err_omp_aligned_expected_array_or_ptr)
3483                 << QTy << getLangOpts().CPlusPlus << E->getSourceRange();
3484             Diag(PVD->getLocation(), diag::note_previous_decl) << PVD;
3485           }
3486           continue;
3487         }
3488       }
3489     if (isa<CXXThisExpr>(E)) {
3490       if (AlignedThis) {
3491         Diag(E->getExprLoc(), diag::err_omp_aligned_twice)
3492             << 2 << E->getSourceRange();
3493         Diag(AlignedThis->getExprLoc(), diag::note_omp_explicit_dsa)
3494             << getOpenMPClauseName(OMPC_aligned);
3495       }
3496       AlignedThis = E;
3497       continue;
3498     }
3499     Diag(E->getExprLoc(), diag::err_omp_param_or_this_in_clause)
3500         << FD->getDeclName() << (isa<CXXMethodDecl>(ADecl) ? 1 : 0);
3501   }
3502   // The optional parameter of the aligned clause, alignment, must be a constant
3503   // positive integer expression. If no optional parameter is specified,
3504   // implementation-defined default alignments for SIMD instructions on the
3505   // target platforms are assumed.
3506   SmallVector<const Expr *, 4> NewAligns;
3507   for (Expr *E : Alignments) {
3508     ExprResult Align;
3509     if (E)
3510       Align = VerifyPositiveIntegerConstantInClause(E, OMPC_aligned);
3511     NewAligns.push_back(Align.get());
3512   }
3513   // OpenMP [2.8.2, declare simd construct, Description]
3514   // The linear clause declares one or more list items to be private to a SIMD
3515   // lane and to have a linear relationship with respect to the iteration space
3516   // of a loop.
3517   // The special this pointer can be used as if was one of the arguments to the
3518   // function in any of the linear, aligned, or uniform clauses.
3519   // When a linear-step expression is specified in a linear clause it must be
3520   // either a constant integer expression or an integer-typed parameter that is
3521   // specified in a uniform clause on the directive.
3522   llvm::DenseMap<const Decl *, const Expr *> LinearArgs;
3523   const bool IsUniformedThis = UniformedLinearThis != nullptr;
3524   auto MI = LinModifiers.begin();
3525   for (const Expr *E : Linears) {
3526     auto LinKind = static_cast<OpenMPLinearClauseKind>(*MI);
3527     ++MI;
3528     E = E->IgnoreParenImpCasts();
3529     if (const auto *DRE = dyn_cast<DeclRefExpr>(E))
3530       if (const auto *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl())) {
3531         const VarDecl *CanonPVD = PVD->getCanonicalDecl();
3532         if (FD->getNumParams() > PVD->getFunctionScopeIndex() &&
3533             FD->getParamDecl(PVD->getFunctionScopeIndex())
3534                     ->getCanonicalDecl() == CanonPVD) {
3535           // OpenMP  [2.15.3.7, linear Clause, Restrictions]
3536           // A list-item cannot appear in more than one linear clause.
3537           if (LinearArgs.count(CanonPVD) > 0) {
3538             Diag(E->getExprLoc(), diag::err_omp_wrong_dsa)
3539                 << getOpenMPClauseName(OMPC_linear)
3540                 << getOpenMPClauseName(OMPC_linear) << E->getSourceRange();
3541             Diag(LinearArgs[CanonPVD]->getExprLoc(),
3542                  diag::note_omp_explicit_dsa)
3543                 << getOpenMPClauseName(OMPC_linear);
3544             continue;
3545           }
3546           // Each argument can appear in at most one uniform or linear clause.
3547           if (UniformedArgs.count(CanonPVD) > 0) {
3548             Diag(E->getExprLoc(), diag::err_omp_wrong_dsa)
3549                 << getOpenMPClauseName(OMPC_linear)
3550                 << getOpenMPClauseName(OMPC_uniform) << E->getSourceRange();
3551             Diag(UniformedArgs[CanonPVD]->getExprLoc(),
3552                  diag::note_omp_explicit_dsa)
3553                 << getOpenMPClauseName(OMPC_uniform);
3554             continue;
3555           }
3556           LinearArgs[CanonPVD] = E;
3557           if (E->isValueDependent() || E->isTypeDependent() ||
3558               E->isInstantiationDependent() ||
3559               E->containsUnexpandedParameterPack())
3560             continue;
3561           (void)CheckOpenMPLinearDecl(CanonPVD, E->getExprLoc(), LinKind,
3562                                       PVD->getOriginalType());
3563           continue;
3564         }
3565       }
3566     if (isa<CXXThisExpr>(E)) {
3567       if (UniformedLinearThis) {
3568         Diag(E->getExprLoc(), diag::err_omp_wrong_dsa)
3569             << getOpenMPClauseName(OMPC_linear)
3570             << getOpenMPClauseName(IsUniformedThis ? OMPC_uniform : OMPC_linear)
3571             << E->getSourceRange();
3572         Diag(UniformedLinearThis->getExprLoc(), diag::note_omp_explicit_dsa)
3573             << getOpenMPClauseName(IsUniformedThis ? OMPC_uniform
3574                                                    : OMPC_linear);
3575         continue;
3576       }
3577       UniformedLinearThis = E;
3578       if (E->isValueDependent() || E->isTypeDependent() ||
3579           E->isInstantiationDependent() || E->containsUnexpandedParameterPack())
3580         continue;
3581       (void)CheckOpenMPLinearDecl(/*D=*/nullptr, E->getExprLoc(), LinKind,
3582                                   E->getType());
3583       continue;
3584     }
3585     Diag(E->getExprLoc(), diag::err_omp_param_or_this_in_clause)
3586         << FD->getDeclName() << (isa<CXXMethodDecl>(ADecl) ? 1 : 0);
3587   }
3588   Expr *Step = nullptr;
3589   Expr *NewStep = nullptr;
3590   SmallVector<Expr *, 4> NewSteps;
3591   for (Expr *E : Steps) {
3592     // Skip the same step expression, it was checked already.
3593     if (Step == E || !E) {
3594       NewSteps.push_back(E ? NewStep : nullptr);
3595       continue;
3596     }
3597     Step = E;
3598     if (const auto *DRE = dyn_cast<DeclRefExpr>(Step))
3599       if (const auto *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl())) {
3600         const VarDecl *CanonPVD = PVD->getCanonicalDecl();
3601         if (UniformedArgs.count(CanonPVD) == 0) {
3602           Diag(Step->getExprLoc(), diag::err_omp_expected_uniform_param)
3603               << Step->getSourceRange();
3604         } else if (E->isValueDependent() || E->isTypeDependent() ||
3605                    E->isInstantiationDependent() ||
3606                    E->containsUnexpandedParameterPack() ||
3607                    CanonPVD->getType()->hasIntegerRepresentation()) {
3608           NewSteps.push_back(Step);
3609         } else {
3610           Diag(Step->getExprLoc(), diag::err_omp_expected_int_param)
3611               << Step->getSourceRange();
3612         }
3613         continue;
3614       }
3615     NewStep = Step;
3616     if (Step && !Step->isValueDependent() && !Step->isTypeDependent() &&
3617         !Step->isInstantiationDependent() &&
3618         !Step->containsUnexpandedParameterPack()) {
3619       NewStep = PerformOpenMPImplicitIntegerConversion(Step->getExprLoc(), Step)
3620                     .get();
3621       if (NewStep)
3622         NewStep = VerifyIntegerConstantExpression(NewStep).get();
3623     }
3624     NewSteps.push_back(NewStep);
3625   }
3626   auto *NewAttr = OMPDeclareSimdDeclAttr::CreateImplicit(
3627       Context, BS, SL.get(), const_cast<Expr **>(Uniforms.data()),
3628       Uniforms.size(), const_cast<Expr **>(Aligneds.data()), Aligneds.size(),
3629       const_cast<Expr **>(NewAligns.data()), NewAligns.size(),
3630       const_cast<Expr **>(Linears.data()), Linears.size(),
3631       const_cast<unsigned *>(LinModifiers.data()), LinModifiers.size(),
3632       NewSteps.data(), NewSteps.size(), SR);
3633   ADecl->addAttr(NewAttr);
3634   return ConvertDeclToDeclGroup(ADecl);
3635 }
3636 
3637 StmtResult Sema::ActOnOpenMPParallelDirective(ArrayRef<OMPClause *> Clauses,
3638                                               Stmt *AStmt,
3639                                               SourceLocation StartLoc,
3640                                               SourceLocation EndLoc) {
3641   if (!AStmt)
3642     return StmtError();
3643 
3644   auto *CS = cast<CapturedStmt>(AStmt);
3645   // 1.2.2 OpenMP Language Terminology
3646   // Structured block - An executable statement with a single entry at the
3647   // top and a single exit at the bottom.
3648   // The point of exit cannot be a branch out of the structured block.
3649   // longjmp() and throw() must not violate the entry/exit criteria.
3650   CS->getCapturedDecl()->setNothrow();
3651 
3652   setFunctionHasBranchProtectedScope();
3653 
3654   return OMPParallelDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt,
3655                                       DSAStack->isCancelRegion());
3656 }
3657 
3658 namespace {
3659 /// Helper class for checking canonical form of the OpenMP loops and
3660 /// extracting iteration space of each loop in the loop nest, that will be used
3661 /// for IR generation.
3662 class OpenMPIterationSpaceChecker {
3663   /// Reference to Sema.
3664   Sema &SemaRef;
3665   /// A location for diagnostics (when there is no some better location).
3666   SourceLocation DefaultLoc;
3667   /// A location for diagnostics (when increment is not compatible).
3668   SourceLocation ConditionLoc;
3669   /// A source location for referring to loop init later.
3670   SourceRange InitSrcRange;
3671   /// A source location for referring to condition later.
3672   SourceRange ConditionSrcRange;
3673   /// A source location for referring to increment later.
3674   SourceRange IncrementSrcRange;
3675   /// Loop variable.
3676   ValueDecl *LCDecl = nullptr;
3677   /// Reference to loop variable.
3678   Expr *LCRef = nullptr;
3679   /// Lower bound (initializer for the var).
3680   Expr *LB = nullptr;
3681   /// Upper bound.
3682   Expr *UB = nullptr;
3683   /// Loop step (increment).
3684   Expr *Step = nullptr;
3685   /// This flag is true when condition is one of:
3686   ///   Var <  UB
3687   ///   Var <= UB
3688   ///   UB  >  Var
3689   ///   UB  >= Var
3690   bool TestIsLessOp = false;
3691   /// This flag is true when condition is strict ( < or > ).
3692   bool TestIsStrictOp = false;
3693   /// This flag is true when step is subtracted on each iteration.
3694   bool SubtractStep = false;
3695 
3696 public:
3697   OpenMPIterationSpaceChecker(Sema &SemaRef, SourceLocation DefaultLoc)
3698       : SemaRef(SemaRef), DefaultLoc(DefaultLoc), ConditionLoc(DefaultLoc) {}
3699   /// Check init-expr for canonical loop form and save loop counter
3700   /// variable - #Var and its initialization value - #LB.
3701   bool checkAndSetInit(Stmt *S, bool EmitDiags = true);
3702   /// Check test-expr for canonical form, save upper-bound (#UB), flags
3703   /// for less/greater and for strict/non-strict comparison.
3704   bool checkAndSetCond(Expr *S);
3705   /// Check incr-expr for canonical loop form and return true if it
3706   /// does not conform, otherwise save loop step (#Step).
3707   bool checkAndSetInc(Expr *S);
3708   /// Return the loop counter variable.
3709   ValueDecl *getLoopDecl() const { return LCDecl; }
3710   /// Return the reference expression to loop counter variable.
3711   Expr *getLoopDeclRefExpr() const { return LCRef; }
3712   /// Source range of the loop init.
3713   SourceRange getInitSrcRange() const { return InitSrcRange; }
3714   /// Source range of the loop condition.
3715   SourceRange getConditionSrcRange() const { return ConditionSrcRange; }
3716   /// Source range of the loop increment.
3717   SourceRange getIncrementSrcRange() const { return IncrementSrcRange; }
3718   /// True if the step should be subtracted.
3719   bool shouldSubtractStep() const { return SubtractStep; }
3720   /// Build the expression to calculate the number of iterations.
3721   Expr *buildNumIterations(
3722       Scope *S, const bool LimitedType,
3723       llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) const;
3724   /// Build the precondition expression for the loops.
3725   Expr *
3726   buildPreCond(Scope *S, Expr *Cond,
3727                llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) const;
3728   /// Build reference expression to the counter be used for codegen.
3729   DeclRefExpr *
3730   buildCounterVar(llvm::MapVector<const Expr *, DeclRefExpr *> &Captures,
3731                   DSAStackTy &DSA) const;
3732   /// Build reference expression to the private counter be used for
3733   /// codegen.
3734   Expr *buildPrivateCounterVar() const;
3735   /// Build initialization of the counter be used for codegen.
3736   Expr *buildCounterInit() const;
3737   /// Build step of the counter be used for codegen.
3738   Expr *buildCounterStep() const;
3739   /// Return true if any expression is dependent.
3740   bool dependent() const;
3741 
3742 private:
3743   /// Check the right-hand side of an assignment in the increment
3744   /// expression.
3745   bool checkAndSetIncRHS(Expr *RHS);
3746   /// Helper to set loop counter variable and its initializer.
3747   bool setLCDeclAndLB(ValueDecl *NewLCDecl, Expr *NewDeclRefExpr, Expr *NewLB);
3748   /// Helper to set upper bound.
3749   bool setUB(Expr *NewUB, bool LessOp, bool StrictOp, SourceRange SR,
3750              SourceLocation SL);
3751   /// Helper to set loop increment.
3752   bool setStep(Expr *NewStep, bool Subtract);
3753 };
3754 
3755 bool OpenMPIterationSpaceChecker::dependent() const {
3756   if (!LCDecl) {
3757     assert(!LB && !UB && !Step);
3758     return false;
3759   }
3760   return LCDecl->getType()->isDependentType() ||
3761          (LB && LB->isValueDependent()) || (UB && UB->isValueDependent()) ||
3762          (Step && Step->isValueDependent());
3763 }
3764 
3765 bool OpenMPIterationSpaceChecker::setLCDeclAndLB(ValueDecl *NewLCDecl,
3766                                                  Expr *NewLCRefExpr,
3767                                                  Expr *NewLB) {
3768   // State consistency checking to ensure correct usage.
3769   assert(LCDecl == nullptr && LB == nullptr && LCRef == nullptr &&
3770          UB == nullptr && Step == nullptr && !TestIsLessOp && !TestIsStrictOp);
3771   if (!NewLCDecl || !NewLB)
3772     return true;
3773   LCDecl = getCanonicalDecl(NewLCDecl);
3774   LCRef = NewLCRefExpr;
3775   if (auto *CE = dyn_cast_or_null<CXXConstructExpr>(NewLB))
3776     if (const CXXConstructorDecl *Ctor = CE->getConstructor())
3777       if ((Ctor->isCopyOrMoveConstructor() ||
3778            Ctor->isConvertingConstructor(/*AllowExplicit=*/false)) &&
3779           CE->getNumArgs() > 0 && CE->getArg(0) != nullptr)
3780         NewLB = CE->getArg(0)->IgnoreParenImpCasts();
3781   LB = NewLB;
3782   return false;
3783 }
3784 
3785 bool OpenMPIterationSpaceChecker::setUB(Expr *NewUB, bool LessOp, bool StrictOp,
3786                                         SourceRange SR, SourceLocation SL) {
3787   // State consistency checking to ensure correct usage.
3788   assert(LCDecl != nullptr && LB != nullptr && UB == nullptr &&
3789          Step == nullptr && !TestIsLessOp && !TestIsStrictOp);
3790   if (!NewUB)
3791     return true;
3792   UB = NewUB;
3793   TestIsLessOp = LessOp;
3794   TestIsStrictOp = StrictOp;
3795   ConditionSrcRange = SR;
3796   ConditionLoc = SL;
3797   return false;
3798 }
3799 
3800 bool OpenMPIterationSpaceChecker::setStep(Expr *NewStep, bool Subtract) {
3801   // State consistency checking to ensure correct usage.
3802   assert(LCDecl != nullptr && LB != nullptr && Step == nullptr);
3803   if (!NewStep)
3804     return true;
3805   if (!NewStep->isValueDependent()) {
3806     // Check that the step is integer expression.
3807     SourceLocation StepLoc = NewStep->getLocStart();
3808     ExprResult Val = SemaRef.PerformOpenMPImplicitIntegerConversion(
3809         StepLoc, getExprAsWritten(NewStep));
3810     if (Val.isInvalid())
3811       return true;
3812     NewStep = Val.get();
3813 
3814     // OpenMP [2.6, Canonical Loop Form, Restrictions]
3815     //  If test-expr is of form var relational-op b and relational-op is < or
3816     //  <= then incr-expr must cause var to increase on each iteration of the
3817     //  loop. If test-expr is of form var relational-op b and relational-op is
3818     //  > or >= then incr-expr must cause var to decrease on each iteration of
3819     //  the loop.
3820     //  If test-expr is of form b relational-op var and relational-op is < or
3821     //  <= then incr-expr must cause var to decrease on each iteration of the
3822     //  loop. If test-expr is of form b relational-op var and relational-op is
3823     //  > or >= then incr-expr must cause var to increase on each iteration of
3824     //  the loop.
3825     llvm::APSInt Result;
3826     bool IsConstant = NewStep->isIntegerConstantExpr(Result, SemaRef.Context);
3827     bool IsUnsigned = !NewStep->getType()->hasSignedIntegerRepresentation();
3828     bool IsConstNeg =
3829         IsConstant && Result.isSigned() && (Subtract != Result.isNegative());
3830     bool IsConstPos =
3831         IsConstant && Result.isSigned() && (Subtract == Result.isNegative());
3832     bool IsConstZero = IsConstant && !Result.getBoolValue();
3833     if (UB && (IsConstZero ||
3834                (TestIsLessOp ? (IsConstNeg || (IsUnsigned && Subtract))
3835                              : (IsConstPos || (IsUnsigned && !Subtract))))) {
3836       SemaRef.Diag(NewStep->getExprLoc(),
3837                    diag::err_omp_loop_incr_not_compatible)
3838           << LCDecl << TestIsLessOp << NewStep->getSourceRange();
3839       SemaRef.Diag(ConditionLoc,
3840                    diag::note_omp_loop_cond_requres_compatible_incr)
3841           << TestIsLessOp << ConditionSrcRange;
3842       return true;
3843     }
3844     if (TestIsLessOp == Subtract) {
3845       NewStep =
3846           SemaRef.CreateBuiltinUnaryOp(NewStep->getExprLoc(), UO_Minus, NewStep)
3847               .get();
3848       Subtract = !Subtract;
3849     }
3850   }
3851 
3852   Step = NewStep;
3853   SubtractStep = Subtract;
3854   return false;
3855 }
3856 
3857 bool OpenMPIterationSpaceChecker::checkAndSetInit(Stmt *S, bool EmitDiags) {
3858   // Check init-expr for canonical loop form and save loop counter
3859   // variable - #Var and its initialization value - #LB.
3860   // OpenMP [2.6] Canonical loop form. init-expr may be one of the following:
3861   //   var = lb
3862   //   integer-type var = lb
3863   //   random-access-iterator-type var = lb
3864   //   pointer-type var = lb
3865   //
3866   if (!S) {
3867     if (EmitDiags) {
3868       SemaRef.Diag(DefaultLoc, diag::err_omp_loop_not_canonical_init);
3869     }
3870     return true;
3871   }
3872   if (auto *ExprTemp = dyn_cast<ExprWithCleanups>(S))
3873     if (!ExprTemp->cleanupsHaveSideEffects())
3874       S = ExprTemp->getSubExpr();
3875 
3876   InitSrcRange = S->getSourceRange();
3877   if (Expr *E = dyn_cast<Expr>(S))
3878     S = E->IgnoreParens();
3879   if (auto *BO = dyn_cast<BinaryOperator>(S)) {
3880     if (BO->getOpcode() == BO_Assign) {
3881       Expr *LHS = BO->getLHS()->IgnoreParens();
3882       if (auto *DRE = dyn_cast<DeclRefExpr>(LHS)) {
3883         if (auto *CED = dyn_cast<OMPCapturedExprDecl>(DRE->getDecl()))
3884           if (auto *ME = dyn_cast<MemberExpr>(getExprAsWritten(CED->getInit())))
3885             return setLCDeclAndLB(ME->getMemberDecl(), ME, BO->getRHS());
3886         return setLCDeclAndLB(DRE->getDecl(), DRE, BO->getRHS());
3887       }
3888       if (auto *ME = dyn_cast<MemberExpr>(LHS)) {
3889         if (ME->isArrow() &&
3890             isa<CXXThisExpr>(ME->getBase()->IgnoreParenImpCasts()))
3891           return setLCDeclAndLB(ME->getMemberDecl(), ME, BO->getRHS());
3892       }
3893     }
3894   } else if (auto *DS = dyn_cast<DeclStmt>(S)) {
3895     if (DS->isSingleDecl()) {
3896       if (auto *Var = dyn_cast_or_null<VarDecl>(DS->getSingleDecl())) {
3897         if (Var->hasInit() && !Var->getType()->isReferenceType()) {
3898           // Accept non-canonical init form here but emit ext. warning.
3899           if (Var->getInitStyle() != VarDecl::CInit && EmitDiags)
3900             SemaRef.Diag(S->getLocStart(),
3901                          diag::ext_omp_loop_not_canonical_init)
3902                 << S->getSourceRange();
3903           return setLCDeclAndLB(Var, nullptr, Var->getInit());
3904         }
3905       }
3906     }
3907   } else if (auto *CE = dyn_cast<CXXOperatorCallExpr>(S)) {
3908     if (CE->getOperator() == OO_Equal) {
3909       Expr *LHS = CE->getArg(0);
3910       if (auto *DRE = dyn_cast<DeclRefExpr>(LHS)) {
3911         if (auto *CED = dyn_cast<OMPCapturedExprDecl>(DRE->getDecl()))
3912           if (auto *ME = dyn_cast<MemberExpr>(getExprAsWritten(CED->getInit())))
3913             return setLCDeclAndLB(ME->getMemberDecl(), ME, BO->getRHS());
3914         return setLCDeclAndLB(DRE->getDecl(), DRE, CE->getArg(1));
3915       }
3916       if (auto *ME = dyn_cast<MemberExpr>(LHS)) {
3917         if (ME->isArrow() &&
3918             isa<CXXThisExpr>(ME->getBase()->IgnoreParenImpCasts()))
3919           return setLCDeclAndLB(ME->getMemberDecl(), ME, BO->getRHS());
3920       }
3921     }
3922   }
3923 
3924   if (dependent() || SemaRef.CurContext->isDependentContext())
3925     return false;
3926   if (EmitDiags) {
3927     SemaRef.Diag(S->getLocStart(), diag::err_omp_loop_not_canonical_init)
3928         << S->getSourceRange();
3929   }
3930   return true;
3931 }
3932 
3933 /// Ignore parenthesizes, implicit casts, copy constructor and return the
3934 /// variable (which may be the loop variable) if possible.
3935 static const ValueDecl *getInitLCDecl(const Expr *E) {
3936   if (!E)
3937     return nullptr;
3938   E = getExprAsWritten(E);
3939   if (const auto *CE = dyn_cast_or_null<CXXConstructExpr>(E))
3940     if (const CXXConstructorDecl *Ctor = CE->getConstructor())
3941       if ((Ctor->isCopyOrMoveConstructor() ||
3942            Ctor->isConvertingConstructor(/*AllowExplicit=*/false)) &&
3943           CE->getNumArgs() > 0 && CE->getArg(0) != nullptr)
3944         E = CE->getArg(0)->IgnoreParenImpCasts();
3945   if (const auto *DRE = dyn_cast_or_null<DeclRefExpr>(E)) {
3946     if (const auto *VD = dyn_cast<VarDecl>(DRE->getDecl()))
3947       return getCanonicalDecl(VD);
3948   }
3949   if (const auto *ME = dyn_cast_or_null<MemberExpr>(E))
3950     if (ME->isArrow() && isa<CXXThisExpr>(ME->getBase()->IgnoreParenImpCasts()))
3951       return getCanonicalDecl(ME->getMemberDecl());
3952   return nullptr;
3953 }
3954 
3955 bool OpenMPIterationSpaceChecker::checkAndSetCond(Expr *S) {
3956   // Check test-expr for canonical form, save upper-bound UB, flags for
3957   // less/greater and for strict/non-strict comparison.
3958   // OpenMP [2.6] Canonical loop form. Test-expr may be one of the following:
3959   //   var relational-op b
3960   //   b relational-op var
3961   //
3962   if (!S) {
3963     SemaRef.Diag(DefaultLoc, diag::err_omp_loop_not_canonical_cond) << LCDecl;
3964     return true;
3965   }
3966   S = getExprAsWritten(S);
3967   SourceLocation CondLoc = S->getLocStart();
3968   if (auto *BO = dyn_cast<BinaryOperator>(S)) {
3969     if (BO->isRelationalOp()) {
3970       if (getInitLCDecl(BO->getLHS()) == LCDecl)
3971         return setUB(BO->getRHS(),
3972                      (BO->getOpcode() == BO_LT || BO->getOpcode() == BO_LE),
3973                      (BO->getOpcode() == BO_LT || BO->getOpcode() == BO_GT),
3974                      BO->getSourceRange(), BO->getOperatorLoc());
3975       if (getInitLCDecl(BO->getRHS()) == LCDecl)
3976         return setUB(BO->getLHS(),
3977                      (BO->getOpcode() == BO_GT || BO->getOpcode() == BO_GE),
3978                      (BO->getOpcode() == BO_LT || BO->getOpcode() == BO_GT),
3979                      BO->getSourceRange(), BO->getOperatorLoc());
3980     }
3981   } else if (auto *CE = dyn_cast<CXXOperatorCallExpr>(S)) {
3982     if (CE->getNumArgs() == 2) {
3983       auto Op = CE->getOperator();
3984       switch (Op) {
3985       case OO_Greater:
3986       case OO_GreaterEqual:
3987       case OO_Less:
3988       case OO_LessEqual:
3989         if (getInitLCDecl(CE->getArg(0)) == LCDecl)
3990           return setUB(CE->getArg(1), Op == OO_Less || Op == OO_LessEqual,
3991                        Op == OO_Less || Op == OO_Greater, CE->getSourceRange(),
3992                        CE->getOperatorLoc());
3993         if (getInitLCDecl(CE->getArg(1)) == LCDecl)
3994           return setUB(CE->getArg(0), Op == OO_Greater || Op == OO_GreaterEqual,
3995                        Op == OO_Less || Op == OO_Greater, CE->getSourceRange(),
3996                        CE->getOperatorLoc());
3997         break;
3998       default:
3999         break;
4000       }
4001     }
4002   }
4003   if (dependent() || SemaRef.CurContext->isDependentContext())
4004     return false;
4005   SemaRef.Diag(CondLoc, diag::err_omp_loop_not_canonical_cond)
4006       << S->getSourceRange() << LCDecl;
4007   return true;
4008 }
4009 
4010 bool OpenMPIterationSpaceChecker::checkAndSetIncRHS(Expr *RHS) {
4011   // RHS of canonical loop form increment can be:
4012   //   var + incr
4013   //   incr + var
4014   //   var - incr
4015   //
4016   RHS = RHS->IgnoreParenImpCasts();
4017   if (auto *BO = dyn_cast<BinaryOperator>(RHS)) {
4018     if (BO->isAdditiveOp()) {
4019       bool IsAdd = BO->getOpcode() == BO_Add;
4020       if (getInitLCDecl(BO->getLHS()) == LCDecl)
4021         return setStep(BO->getRHS(), !IsAdd);
4022       if (IsAdd && getInitLCDecl(BO->getRHS()) == LCDecl)
4023         return setStep(BO->getLHS(), /*Subtract=*/false);
4024     }
4025   } else if (auto *CE = dyn_cast<CXXOperatorCallExpr>(RHS)) {
4026     bool IsAdd = CE->getOperator() == OO_Plus;
4027     if ((IsAdd || CE->getOperator() == OO_Minus) && CE->getNumArgs() == 2) {
4028       if (getInitLCDecl(CE->getArg(0)) == LCDecl)
4029         return setStep(CE->getArg(1), !IsAdd);
4030       if (IsAdd && getInitLCDecl(CE->getArg(1)) == LCDecl)
4031         return setStep(CE->getArg(0), /*Subtract=*/false);
4032     }
4033   }
4034   if (dependent() || SemaRef.CurContext->isDependentContext())
4035     return false;
4036   SemaRef.Diag(RHS->getLocStart(), diag::err_omp_loop_not_canonical_incr)
4037       << RHS->getSourceRange() << LCDecl;
4038   return true;
4039 }
4040 
4041 bool OpenMPIterationSpaceChecker::checkAndSetInc(Expr *S) {
4042   // Check incr-expr for canonical loop form and return true if it
4043   // does not conform.
4044   // OpenMP [2.6] Canonical loop form. Test-expr may be one of the following:
4045   //   ++var
4046   //   var++
4047   //   --var
4048   //   var--
4049   //   var += incr
4050   //   var -= incr
4051   //   var = var + incr
4052   //   var = incr + var
4053   //   var = var - incr
4054   //
4055   if (!S) {
4056     SemaRef.Diag(DefaultLoc, diag::err_omp_loop_not_canonical_incr) << LCDecl;
4057     return true;
4058   }
4059   if (auto *ExprTemp = dyn_cast<ExprWithCleanups>(S))
4060     if (!ExprTemp->cleanupsHaveSideEffects())
4061       S = ExprTemp->getSubExpr();
4062 
4063   IncrementSrcRange = S->getSourceRange();
4064   S = S->IgnoreParens();
4065   if (auto *UO = dyn_cast<UnaryOperator>(S)) {
4066     if (UO->isIncrementDecrementOp() &&
4067         getInitLCDecl(UO->getSubExpr()) == LCDecl)
4068       return setStep(SemaRef
4069                          .ActOnIntegerConstant(UO->getLocStart(),
4070                                                (UO->isDecrementOp() ? -1 : 1))
4071                          .get(),
4072                      /*Subtract=*/false);
4073   } else if (auto *BO = dyn_cast<BinaryOperator>(S)) {
4074     switch (BO->getOpcode()) {
4075     case BO_AddAssign:
4076     case BO_SubAssign:
4077       if (getInitLCDecl(BO->getLHS()) == LCDecl)
4078         return setStep(BO->getRHS(), BO->getOpcode() == BO_SubAssign);
4079       break;
4080     case BO_Assign:
4081       if (getInitLCDecl(BO->getLHS()) == LCDecl)
4082         return checkAndSetIncRHS(BO->getRHS());
4083       break;
4084     default:
4085       break;
4086     }
4087   } else if (auto *CE = dyn_cast<CXXOperatorCallExpr>(S)) {
4088     switch (CE->getOperator()) {
4089     case OO_PlusPlus:
4090     case OO_MinusMinus:
4091       if (getInitLCDecl(CE->getArg(0)) == LCDecl)
4092         return setStep(SemaRef
4093                            .ActOnIntegerConstant(
4094                                CE->getLocStart(),
4095                                ((CE->getOperator() == OO_MinusMinus) ? -1 : 1))
4096                            .get(),
4097                        /*Subtract=*/false);
4098       break;
4099     case OO_PlusEqual:
4100     case OO_MinusEqual:
4101       if (getInitLCDecl(CE->getArg(0)) == LCDecl)
4102         return setStep(CE->getArg(1), CE->getOperator() == OO_MinusEqual);
4103       break;
4104     case OO_Equal:
4105       if (getInitLCDecl(CE->getArg(0)) == LCDecl)
4106         return checkAndSetIncRHS(CE->getArg(1));
4107       break;
4108     default:
4109       break;
4110     }
4111   }
4112   if (dependent() || SemaRef.CurContext->isDependentContext())
4113     return false;
4114   SemaRef.Diag(S->getLocStart(), diag::err_omp_loop_not_canonical_incr)
4115       << S->getSourceRange() << LCDecl;
4116   return true;
4117 }
4118 
4119 static ExprResult
4120 tryBuildCapture(Sema &SemaRef, Expr *Capture,
4121                 llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) {
4122   if (SemaRef.CurContext->isDependentContext())
4123     return ExprResult(Capture);
4124   if (Capture->isEvaluatable(SemaRef.Context, Expr::SE_AllowSideEffects))
4125     return SemaRef.PerformImplicitConversion(
4126         Capture->IgnoreImpCasts(), Capture->getType(), Sema::AA_Converting,
4127         /*AllowExplicit=*/true);
4128   auto I = Captures.find(Capture);
4129   if (I != Captures.end())
4130     return buildCapture(SemaRef, Capture, I->second);
4131   DeclRefExpr *Ref = nullptr;
4132   ExprResult Res = buildCapture(SemaRef, Capture, Ref);
4133   Captures[Capture] = Ref;
4134   return Res;
4135 }
4136 
4137 /// Build the expression to calculate the number of iterations.
4138 Expr *OpenMPIterationSpaceChecker::buildNumIterations(
4139     Scope *S, const bool LimitedType,
4140     llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) const {
4141   ExprResult Diff;
4142   QualType VarType = LCDecl->getType().getNonReferenceType();
4143   if (VarType->isIntegerType() || VarType->isPointerType() ||
4144       SemaRef.getLangOpts().CPlusPlus) {
4145     // Upper - Lower
4146     Expr *UBExpr = TestIsLessOp ? UB : LB;
4147     Expr *LBExpr = TestIsLessOp ? LB : UB;
4148     Expr *Upper = tryBuildCapture(SemaRef, UBExpr, Captures).get();
4149     Expr *Lower = tryBuildCapture(SemaRef, LBExpr, Captures).get();
4150     if (!Upper || !Lower)
4151       return nullptr;
4152 
4153     Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Sub, Upper, Lower);
4154 
4155     if (!Diff.isUsable() && VarType->getAsCXXRecordDecl()) {
4156       // BuildBinOp already emitted error, this one is to point user to upper
4157       // and lower bound, and to tell what is passed to 'operator-'.
4158       SemaRef.Diag(Upper->getLocStart(), diag::err_omp_loop_diff_cxx)
4159           << Upper->getSourceRange() << Lower->getSourceRange();
4160       return nullptr;
4161     }
4162   }
4163 
4164   if (!Diff.isUsable())
4165     return nullptr;
4166 
4167   // Upper - Lower [- 1]
4168   if (TestIsStrictOp)
4169     Diff = SemaRef.BuildBinOp(
4170         S, DefaultLoc, BO_Sub, Diff.get(),
4171         SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get());
4172   if (!Diff.isUsable())
4173     return nullptr;
4174 
4175   // Upper - Lower [- 1] + Step
4176   ExprResult NewStep = tryBuildCapture(SemaRef, Step, Captures);
4177   if (!NewStep.isUsable())
4178     return nullptr;
4179   Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Add, Diff.get(), NewStep.get());
4180   if (!Diff.isUsable())
4181     return nullptr;
4182 
4183   // Parentheses (for dumping/debugging purposes only).
4184   Diff = SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, Diff.get());
4185   if (!Diff.isUsable())
4186     return nullptr;
4187 
4188   // (Upper - Lower [- 1] + Step) / Step
4189   Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Div, Diff.get(), NewStep.get());
4190   if (!Diff.isUsable())
4191     return nullptr;
4192 
4193   // OpenMP runtime requires 32-bit or 64-bit loop variables.
4194   QualType Type = Diff.get()->getType();
4195   ASTContext &C = SemaRef.Context;
4196   bool UseVarType = VarType->hasIntegerRepresentation() &&
4197                     C.getTypeSize(Type) > C.getTypeSize(VarType);
4198   if (!Type->isIntegerType() || UseVarType) {
4199     unsigned NewSize =
4200         UseVarType ? C.getTypeSize(VarType) : C.getTypeSize(Type);
4201     bool IsSigned = UseVarType ? VarType->hasSignedIntegerRepresentation()
4202                                : Type->hasSignedIntegerRepresentation();
4203     Type = C.getIntTypeForBitwidth(NewSize, IsSigned);
4204     if (!SemaRef.Context.hasSameType(Diff.get()->getType(), Type)) {
4205       Diff = SemaRef.PerformImplicitConversion(
4206           Diff.get(), Type, Sema::AA_Converting, /*AllowExplicit=*/true);
4207       if (!Diff.isUsable())
4208         return nullptr;
4209     }
4210   }
4211   if (LimitedType) {
4212     unsigned NewSize = (C.getTypeSize(Type) > 32) ? 64 : 32;
4213     if (NewSize != C.getTypeSize(Type)) {
4214       if (NewSize < C.getTypeSize(Type)) {
4215         assert(NewSize == 64 && "incorrect loop var size");
4216         SemaRef.Diag(DefaultLoc, diag::warn_omp_loop_64_bit_var)
4217             << InitSrcRange << ConditionSrcRange;
4218       }
4219       QualType NewType = C.getIntTypeForBitwidth(
4220           NewSize, Type->hasSignedIntegerRepresentation() ||
4221                        C.getTypeSize(Type) < NewSize);
4222       if (!SemaRef.Context.hasSameType(Diff.get()->getType(), NewType)) {
4223         Diff = SemaRef.PerformImplicitConversion(Diff.get(), NewType,
4224                                                  Sema::AA_Converting, true);
4225         if (!Diff.isUsable())
4226           return nullptr;
4227       }
4228     }
4229   }
4230 
4231   return Diff.get();
4232 }
4233 
4234 Expr *OpenMPIterationSpaceChecker::buildPreCond(
4235     Scope *S, Expr *Cond,
4236     llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) const {
4237   // Try to build LB <op> UB, where <op> is <, >, <=, or >=.
4238   bool Suppress = SemaRef.getDiagnostics().getSuppressAllDiagnostics();
4239   SemaRef.getDiagnostics().setSuppressAllDiagnostics(/*Val=*/true);
4240 
4241   ExprResult NewLB = tryBuildCapture(SemaRef, LB, Captures);
4242   ExprResult NewUB = tryBuildCapture(SemaRef, UB, Captures);
4243   if (!NewLB.isUsable() || !NewUB.isUsable())
4244     return nullptr;
4245 
4246   ExprResult CondExpr =
4247       SemaRef.BuildBinOp(S, DefaultLoc,
4248                          TestIsLessOp ? (TestIsStrictOp ? BO_LT : BO_LE)
4249                                       : (TestIsStrictOp ? BO_GT : BO_GE),
4250                          NewLB.get(), NewUB.get());
4251   if (CondExpr.isUsable()) {
4252     if (!SemaRef.Context.hasSameUnqualifiedType(CondExpr.get()->getType(),
4253                                                 SemaRef.Context.BoolTy))
4254       CondExpr = SemaRef.PerformImplicitConversion(
4255           CondExpr.get(), SemaRef.Context.BoolTy, /*Action=*/Sema::AA_Casting,
4256           /*AllowExplicit=*/true);
4257   }
4258   SemaRef.getDiagnostics().setSuppressAllDiagnostics(Suppress);
4259   // Otherwise use original loop conditon and evaluate it in runtime.
4260   return CondExpr.isUsable() ? CondExpr.get() : Cond;
4261 }
4262 
4263 /// Build reference expression to the counter be used for codegen.
4264 DeclRefExpr *OpenMPIterationSpaceChecker::buildCounterVar(
4265     llvm::MapVector<const Expr *, DeclRefExpr *> &Captures, DSAStackTy &DSA) const {
4266   auto *VD = dyn_cast<VarDecl>(LCDecl);
4267   if (!VD) {
4268     VD = SemaRef.isOpenMPCapturedDecl(LCDecl);
4269     DeclRefExpr *Ref = buildDeclRefExpr(
4270         SemaRef, VD, VD->getType().getNonReferenceType(), DefaultLoc);
4271     const DSAStackTy::DSAVarData Data =
4272         DSA.getTopDSA(LCDecl, /*FromParent=*/false);
4273     // If the loop control decl is explicitly marked as private, do not mark it
4274     // as captured again.
4275     if (!isOpenMPPrivate(Data.CKind) || !Data.RefExpr)
4276       Captures.insert(std::make_pair(LCRef, Ref));
4277     return Ref;
4278   }
4279   return buildDeclRefExpr(SemaRef, VD, VD->getType().getNonReferenceType(),
4280                           DefaultLoc);
4281 }
4282 
4283 Expr *OpenMPIterationSpaceChecker::buildPrivateCounterVar() const {
4284   if (LCDecl && !LCDecl->isInvalidDecl()) {
4285     QualType Type = LCDecl->getType().getNonReferenceType();
4286     VarDecl *PrivateVar = buildVarDecl(
4287         SemaRef, DefaultLoc, Type, LCDecl->getName(),
4288         LCDecl->hasAttrs() ? &LCDecl->getAttrs() : nullptr,
4289         isa<VarDecl>(LCDecl)
4290             ? buildDeclRefExpr(SemaRef, cast<VarDecl>(LCDecl), Type, DefaultLoc)
4291             : nullptr);
4292     if (PrivateVar->isInvalidDecl())
4293       return nullptr;
4294     return buildDeclRefExpr(SemaRef, PrivateVar, Type, DefaultLoc);
4295   }
4296   return nullptr;
4297 }
4298 
4299 /// Build initialization of the counter to be used for codegen.
4300 Expr *OpenMPIterationSpaceChecker::buildCounterInit() const { return LB; }
4301 
4302 /// Build step of the counter be used for codegen.
4303 Expr *OpenMPIterationSpaceChecker::buildCounterStep() const { return Step; }
4304 
4305 /// Iteration space of a single for loop.
4306 struct LoopIterationSpace final {
4307   /// Condition of the loop.
4308   Expr *PreCond = nullptr;
4309   /// This expression calculates the number of iterations in the loop.
4310   /// It is always possible to calculate it before starting the loop.
4311   Expr *NumIterations = nullptr;
4312   /// The loop counter variable.
4313   Expr *CounterVar = nullptr;
4314   /// Private loop counter variable.
4315   Expr *PrivateCounterVar = nullptr;
4316   /// This is initializer for the initial value of #CounterVar.
4317   Expr *CounterInit = nullptr;
4318   /// This is step for the #CounterVar used to generate its update:
4319   /// #CounterVar = #CounterInit + #CounterStep * CurrentIteration.
4320   Expr *CounterStep = nullptr;
4321   /// Should step be subtracted?
4322   bool Subtract = false;
4323   /// Source range of the loop init.
4324   SourceRange InitSrcRange;
4325   /// Source range of the loop condition.
4326   SourceRange CondSrcRange;
4327   /// Source range of the loop increment.
4328   SourceRange IncSrcRange;
4329 };
4330 
4331 } // namespace
4332 
4333 void Sema::ActOnOpenMPLoopInitialization(SourceLocation ForLoc, Stmt *Init) {
4334   assert(getLangOpts().OpenMP && "OpenMP is not active.");
4335   assert(Init && "Expected loop in canonical form.");
4336   unsigned AssociatedLoops = DSAStack->getAssociatedLoops();
4337   if (AssociatedLoops > 0 &&
4338       isOpenMPLoopDirective(DSAStack->getCurrentDirective())) {
4339     OpenMPIterationSpaceChecker ISC(*this, ForLoc);
4340     if (!ISC.checkAndSetInit(Init, /*EmitDiags=*/false)) {
4341       if (ValueDecl *D = ISC.getLoopDecl()) {
4342         auto *VD = dyn_cast<VarDecl>(D);
4343         if (!VD) {
4344           if (VarDecl *Private = isOpenMPCapturedDecl(D)) {
4345             VD = Private;
4346           } else {
4347             DeclRefExpr *Ref = buildCapture(*this, D, ISC.getLoopDeclRefExpr(),
4348                                             /*WithInit=*/false);
4349             VD = cast<VarDecl>(Ref->getDecl());
4350           }
4351         }
4352         DSAStack->addLoopControlVariable(D, VD);
4353       }
4354     }
4355     DSAStack->setAssociatedLoops(AssociatedLoops - 1);
4356   }
4357 }
4358 
4359 /// Called on a for stmt to check and extract its iteration space
4360 /// for further processing (such as collapsing).
4361 static bool checkOpenMPIterationSpace(
4362     OpenMPDirectiveKind DKind, Stmt *S, Sema &SemaRef, DSAStackTy &DSA,
4363     unsigned CurrentNestedLoopCount, unsigned NestedLoopCount,
4364     Expr *CollapseLoopCountExpr, Expr *OrderedLoopCountExpr,
4365     Sema::VarsWithInheritedDSAType &VarsWithImplicitDSA,
4366     LoopIterationSpace &ResultIterSpace,
4367     llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) {
4368   // OpenMP [2.6, Canonical Loop Form]
4369   //   for (init-expr; test-expr; incr-expr) structured-block
4370   auto *For = dyn_cast_or_null<ForStmt>(S);
4371   if (!For) {
4372     SemaRef.Diag(S->getLocStart(), diag::err_omp_not_for)
4373         << (CollapseLoopCountExpr != nullptr || OrderedLoopCountExpr != nullptr)
4374         << getOpenMPDirectiveName(DKind) << NestedLoopCount
4375         << (CurrentNestedLoopCount > 0) << CurrentNestedLoopCount;
4376     if (NestedLoopCount > 1) {
4377       if (CollapseLoopCountExpr && OrderedLoopCountExpr)
4378         SemaRef.Diag(DSA.getConstructLoc(),
4379                      diag::note_omp_collapse_ordered_expr)
4380             << 2 << CollapseLoopCountExpr->getSourceRange()
4381             << OrderedLoopCountExpr->getSourceRange();
4382       else if (CollapseLoopCountExpr)
4383         SemaRef.Diag(CollapseLoopCountExpr->getExprLoc(),
4384                      diag::note_omp_collapse_ordered_expr)
4385             << 0 << CollapseLoopCountExpr->getSourceRange();
4386       else
4387         SemaRef.Diag(OrderedLoopCountExpr->getExprLoc(),
4388                      diag::note_omp_collapse_ordered_expr)
4389             << 1 << OrderedLoopCountExpr->getSourceRange();
4390     }
4391     return true;
4392   }
4393   assert(For->getBody());
4394 
4395   OpenMPIterationSpaceChecker ISC(SemaRef, For->getForLoc());
4396 
4397   // Check init.
4398   Stmt *Init = For->getInit();
4399   if (ISC.checkAndSetInit(Init))
4400     return true;
4401 
4402   bool HasErrors = false;
4403 
4404   // Check loop variable's type.
4405   if (ValueDecl *LCDecl = ISC.getLoopDecl()) {
4406     Expr *LoopDeclRefExpr = ISC.getLoopDeclRefExpr();
4407 
4408     // OpenMP [2.6, Canonical Loop Form]
4409     // Var is one of the following:
4410     //   A variable of signed or unsigned integer type.
4411     //   For C++, a variable of a random access iterator type.
4412     //   For C, a variable of a pointer type.
4413     QualType VarType = LCDecl->getType().getNonReferenceType();
4414     if (!VarType->isDependentType() && !VarType->isIntegerType() &&
4415         !VarType->isPointerType() &&
4416         !(SemaRef.getLangOpts().CPlusPlus && VarType->isOverloadableType())) {
4417       SemaRef.Diag(Init->getLocStart(), diag::err_omp_loop_variable_type)
4418           << SemaRef.getLangOpts().CPlusPlus;
4419       HasErrors = true;
4420     }
4421 
4422     // OpenMP, 2.14.1.1 Data-sharing Attribute Rules for Variables Referenced in
4423     // a Construct
4424     // The loop iteration variable(s) in the associated for-loop(s) of a for or
4425     // parallel for construct is (are) private.
4426     // The loop iteration variable in the associated for-loop of a simd
4427     // construct with just one associated for-loop is linear with a
4428     // constant-linear-step that is the increment of the associated for-loop.
4429     // Exclude loop var from the list of variables with implicitly defined data
4430     // sharing attributes.
4431     VarsWithImplicitDSA.erase(LCDecl);
4432 
4433     // OpenMP [2.14.1.1, Data-sharing Attribute Rules for Variables Referenced
4434     // in a Construct, C/C++].
4435     // The loop iteration variable in the associated for-loop of a simd
4436     // construct with just one associated for-loop may be listed in a linear
4437     // clause with a constant-linear-step that is the increment of the
4438     // associated for-loop.
4439     // The loop iteration variable(s) in the associated for-loop(s) of a for or
4440     // parallel for construct may be listed in a private or lastprivate clause.
4441     DSAStackTy::DSAVarData DVar = DSA.getTopDSA(LCDecl, false);
4442     // If LoopVarRefExpr is nullptr it means the corresponding loop variable is
4443     // declared in the loop and it is predetermined as a private.
4444     OpenMPClauseKind PredeterminedCKind =
4445         isOpenMPSimdDirective(DKind)
4446             ? ((NestedLoopCount == 1) ? OMPC_linear : OMPC_lastprivate)
4447             : OMPC_private;
4448     if (((isOpenMPSimdDirective(DKind) && DVar.CKind != OMPC_unknown &&
4449           DVar.CKind != PredeterminedCKind) ||
4450          ((isOpenMPWorksharingDirective(DKind) || DKind == OMPD_taskloop ||
4451            isOpenMPDistributeDirective(DKind)) &&
4452           !isOpenMPSimdDirective(DKind) && DVar.CKind != OMPC_unknown &&
4453           DVar.CKind != OMPC_private && DVar.CKind != OMPC_lastprivate)) &&
4454         (DVar.CKind != OMPC_private || DVar.RefExpr != nullptr)) {
4455       SemaRef.Diag(Init->getLocStart(), diag::err_omp_loop_var_dsa)
4456           << getOpenMPClauseName(DVar.CKind) << getOpenMPDirectiveName(DKind)
4457           << getOpenMPClauseName(PredeterminedCKind);
4458       if (DVar.RefExpr == nullptr)
4459         DVar.CKind = PredeterminedCKind;
4460       reportOriginalDsa(SemaRef, &DSA, LCDecl, DVar, /*IsLoopIterVar=*/true);
4461       HasErrors = true;
4462     } else if (LoopDeclRefExpr != nullptr) {
4463       // Make the loop iteration variable private (for worksharing constructs),
4464       // linear (for simd directives with the only one associated loop) or
4465       // lastprivate (for simd directives with several collapsed or ordered
4466       // loops).
4467       if (DVar.CKind == OMPC_unknown)
4468         DVar = DSA.hasDSA(LCDecl, isOpenMPPrivate,
4469                           [](OpenMPDirectiveKind) -> bool { return true; },
4470                           /*FromParent=*/false);
4471       DSA.addDSA(LCDecl, LoopDeclRefExpr, PredeterminedCKind);
4472     }
4473 
4474     assert(isOpenMPLoopDirective(DKind) && "DSA for non-loop vars");
4475 
4476     // Check test-expr.
4477     HasErrors |= ISC.checkAndSetCond(For->getCond());
4478 
4479     // Check incr-expr.
4480     HasErrors |= ISC.checkAndSetInc(For->getInc());
4481   }
4482 
4483   if (ISC.dependent() || SemaRef.CurContext->isDependentContext() || HasErrors)
4484     return HasErrors;
4485 
4486   // Build the loop's iteration space representation.
4487   ResultIterSpace.PreCond =
4488       ISC.buildPreCond(DSA.getCurScope(), For->getCond(), Captures);
4489   ResultIterSpace.NumIterations = ISC.buildNumIterations(
4490       DSA.getCurScope(),
4491       (isOpenMPWorksharingDirective(DKind) ||
4492        isOpenMPTaskLoopDirective(DKind) || isOpenMPDistributeDirective(DKind)),
4493       Captures);
4494   ResultIterSpace.CounterVar = ISC.buildCounterVar(Captures, DSA);
4495   ResultIterSpace.PrivateCounterVar = ISC.buildPrivateCounterVar();
4496   ResultIterSpace.CounterInit = ISC.buildCounterInit();
4497   ResultIterSpace.CounterStep = ISC.buildCounterStep();
4498   ResultIterSpace.InitSrcRange = ISC.getInitSrcRange();
4499   ResultIterSpace.CondSrcRange = ISC.getConditionSrcRange();
4500   ResultIterSpace.IncSrcRange = ISC.getIncrementSrcRange();
4501   ResultIterSpace.Subtract = ISC.shouldSubtractStep();
4502 
4503   HasErrors |= (ResultIterSpace.PreCond == nullptr ||
4504                 ResultIterSpace.NumIterations == nullptr ||
4505                 ResultIterSpace.CounterVar == nullptr ||
4506                 ResultIterSpace.PrivateCounterVar == nullptr ||
4507                 ResultIterSpace.CounterInit == nullptr ||
4508                 ResultIterSpace.CounterStep == nullptr);
4509 
4510   return HasErrors;
4511 }
4512 
4513 /// Build 'VarRef = Start.
4514 static ExprResult
4515 buildCounterInit(Sema &SemaRef, Scope *S, SourceLocation Loc, ExprResult VarRef,
4516                  ExprResult Start,
4517                  llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) {
4518   // Build 'VarRef = Start.
4519   ExprResult NewStart = tryBuildCapture(SemaRef, Start.get(), Captures);
4520   if (!NewStart.isUsable())
4521     return ExprError();
4522   if (!SemaRef.Context.hasSameType(NewStart.get()->getType(),
4523                                    VarRef.get()->getType())) {
4524     NewStart = SemaRef.PerformImplicitConversion(
4525         NewStart.get(), VarRef.get()->getType(), Sema::AA_Converting,
4526         /*AllowExplicit=*/true);
4527     if (!NewStart.isUsable())
4528       return ExprError();
4529   }
4530 
4531   ExprResult Init =
4532       SemaRef.BuildBinOp(S, Loc, BO_Assign, VarRef.get(), NewStart.get());
4533   return Init;
4534 }
4535 
4536 /// Build 'VarRef = Start + Iter * Step'.
4537 static ExprResult buildCounterUpdate(
4538     Sema &SemaRef, Scope *S, SourceLocation Loc, ExprResult VarRef,
4539     ExprResult Start, ExprResult Iter, ExprResult Step, bool Subtract,
4540     llvm::MapVector<const Expr *, DeclRefExpr *> *Captures = nullptr) {
4541   // Add parentheses (for debugging purposes only).
4542   Iter = SemaRef.ActOnParenExpr(Loc, Loc, Iter.get());
4543   if (!VarRef.isUsable() || !Start.isUsable() || !Iter.isUsable() ||
4544       !Step.isUsable())
4545     return ExprError();
4546 
4547   ExprResult NewStep = Step;
4548   if (Captures)
4549     NewStep = tryBuildCapture(SemaRef, Step.get(), *Captures);
4550   if (NewStep.isInvalid())
4551     return ExprError();
4552   ExprResult Update =
4553       SemaRef.BuildBinOp(S, Loc, BO_Mul, Iter.get(), NewStep.get());
4554   if (!Update.isUsable())
4555     return ExprError();
4556 
4557   // Try to build 'VarRef = Start, VarRef (+|-)= Iter * Step' or
4558   // 'VarRef = Start (+|-) Iter * Step'.
4559   ExprResult NewStart = Start;
4560   if (Captures)
4561     NewStart = tryBuildCapture(SemaRef, Start.get(), *Captures);
4562   if (NewStart.isInvalid())
4563     return ExprError();
4564 
4565   // First attempt: try to build 'VarRef = Start, VarRef += Iter * Step'.
4566   ExprResult SavedUpdate = Update;
4567   ExprResult UpdateVal;
4568   if (VarRef.get()->getType()->isOverloadableType() ||
4569       NewStart.get()->getType()->isOverloadableType() ||
4570       Update.get()->getType()->isOverloadableType()) {
4571     bool Suppress = SemaRef.getDiagnostics().getSuppressAllDiagnostics();
4572     SemaRef.getDiagnostics().setSuppressAllDiagnostics(/*Val=*/true);
4573     Update =
4574         SemaRef.BuildBinOp(S, Loc, BO_Assign, VarRef.get(), NewStart.get());
4575     if (Update.isUsable()) {
4576       UpdateVal =
4577           SemaRef.BuildBinOp(S, Loc, Subtract ? BO_SubAssign : BO_AddAssign,
4578                              VarRef.get(), SavedUpdate.get());
4579       if (UpdateVal.isUsable()) {
4580         Update = SemaRef.CreateBuiltinBinOp(Loc, BO_Comma, Update.get(),
4581                                             UpdateVal.get());
4582       }
4583     }
4584     SemaRef.getDiagnostics().setSuppressAllDiagnostics(Suppress);
4585   }
4586 
4587   // Second attempt: try to build 'VarRef = Start (+|-) Iter * Step'.
4588   if (!Update.isUsable() || !UpdateVal.isUsable()) {
4589     Update = SemaRef.BuildBinOp(S, Loc, Subtract ? BO_Sub : BO_Add,
4590                                 NewStart.get(), SavedUpdate.get());
4591     if (!Update.isUsable())
4592       return ExprError();
4593 
4594     if (!SemaRef.Context.hasSameType(Update.get()->getType(),
4595                                      VarRef.get()->getType())) {
4596       Update = SemaRef.PerformImplicitConversion(
4597           Update.get(), VarRef.get()->getType(), Sema::AA_Converting, true);
4598       if (!Update.isUsable())
4599         return ExprError();
4600     }
4601 
4602     Update = SemaRef.BuildBinOp(S, Loc, BO_Assign, VarRef.get(), Update.get());
4603   }
4604   return Update;
4605 }
4606 
4607 /// Convert integer expression \a E to make it have at least \a Bits
4608 /// bits.
4609 static ExprResult widenIterationCount(unsigned Bits, Expr *E, Sema &SemaRef) {
4610   if (E == nullptr)
4611     return ExprError();
4612   ASTContext &C = SemaRef.Context;
4613   QualType OldType = E->getType();
4614   unsigned HasBits = C.getTypeSize(OldType);
4615   if (HasBits >= Bits)
4616     return ExprResult(E);
4617   // OK to convert to signed, because new type has more bits than old.
4618   QualType NewType = C.getIntTypeForBitwidth(Bits, /* Signed */ true);
4619   return SemaRef.PerformImplicitConversion(E, NewType, Sema::AA_Converting,
4620                                            true);
4621 }
4622 
4623 /// Check if the given expression \a E is a constant integer that fits
4624 /// into \a Bits bits.
4625 static bool fitsInto(unsigned Bits, bool Signed, const Expr *E, Sema &SemaRef) {
4626   if (E == nullptr)
4627     return false;
4628   llvm::APSInt Result;
4629   if (E->isIntegerConstantExpr(Result, SemaRef.Context))
4630     return Signed ? Result.isSignedIntN(Bits) : Result.isIntN(Bits);
4631   return false;
4632 }
4633 
4634 /// Build preinits statement for the given declarations.
4635 static Stmt *buildPreInits(ASTContext &Context,
4636                            MutableArrayRef<Decl *> PreInits) {
4637   if (!PreInits.empty()) {
4638     return new (Context) DeclStmt(
4639         DeclGroupRef::Create(Context, PreInits.begin(), PreInits.size()),
4640         SourceLocation(), SourceLocation());
4641   }
4642   return nullptr;
4643 }
4644 
4645 /// Build preinits statement for the given declarations.
4646 static Stmt *
4647 buildPreInits(ASTContext &Context,
4648               const llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) {
4649   if (!Captures.empty()) {
4650     SmallVector<Decl *, 16> PreInits;
4651     for (const auto &Pair : Captures)
4652       PreInits.push_back(Pair.second->getDecl());
4653     return buildPreInits(Context, PreInits);
4654   }
4655   return nullptr;
4656 }
4657 
4658 /// Build postupdate expression for the given list of postupdates expressions.
4659 static Expr *buildPostUpdate(Sema &S, ArrayRef<Expr *> PostUpdates) {
4660   Expr *PostUpdate = nullptr;
4661   if (!PostUpdates.empty()) {
4662     for (Expr *E : PostUpdates) {
4663       Expr *ConvE = S.BuildCStyleCastExpr(
4664                          E->getExprLoc(),
4665                          S.Context.getTrivialTypeSourceInfo(S.Context.VoidTy),
4666                          E->getExprLoc(), E)
4667                         .get();
4668       PostUpdate = PostUpdate
4669                        ? S.CreateBuiltinBinOp(ConvE->getExprLoc(), BO_Comma,
4670                                               PostUpdate, ConvE)
4671                              .get()
4672                        : ConvE;
4673     }
4674   }
4675   return PostUpdate;
4676 }
4677 
4678 /// Called on a for stmt to check itself and nested loops (if any).
4679 /// \return Returns 0 if one of the collapsed stmts is not canonical for loop,
4680 /// number of collapsed loops otherwise.
4681 static unsigned
4682 checkOpenMPLoop(OpenMPDirectiveKind DKind, Expr *CollapseLoopCountExpr,
4683                 Expr *OrderedLoopCountExpr, Stmt *AStmt, Sema &SemaRef,
4684                 DSAStackTy &DSA,
4685                 Sema::VarsWithInheritedDSAType &VarsWithImplicitDSA,
4686                 OMPLoopDirective::HelperExprs &Built) {
4687   unsigned NestedLoopCount = 1;
4688   if (CollapseLoopCountExpr) {
4689     // Found 'collapse' clause - calculate collapse number.
4690     llvm::APSInt Result;
4691     if (CollapseLoopCountExpr->EvaluateAsInt(Result, SemaRef.getASTContext()))
4692       NestedLoopCount = Result.getLimitedValue();
4693   }
4694   if (OrderedLoopCountExpr) {
4695     // Found 'ordered' clause - calculate collapse number.
4696     llvm::APSInt Result;
4697     if (OrderedLoopCountExpr->EvaluateAsInt(Result, SemaRef.getASTContext())) {
4698       if (Result.getLimitedValue() < NestedLoopCount) {
4699         SemaRef.Diag(OrderedLoopCountExpr->getExprLoc(),
4700                      diag::err_omp_wrong_ordered_loop_count)
4701             << OrderedLoopCountExpr->getSourceRange();
4702         SemaRef.Diag(CollapseLoopCountExpr->getExprLoc(),
4703                      diag::note_collapse_loop_count)
4704             << CollapseLoopCountExpr->getSourceRange();
4705       }
4706       NestedLoopCount = Result.getLimitedValue();
4707     }
4708   }
4709   // This is helper routine for loop directives (e.g., 'for', 'simd',
4710   // 'for simd', etc.).
4711   llvm::MapVector<const Expr *, DeclRefExpr *> Captures;
4712   SmallVector<LoopIterationSpace, 4> IterSpaces;
4713   IterSpaces.resize(NestedLoopCount);
4714   Stmt *CurStmt = AStmt->IgnoreContainers(/* IgnoreCaptured */ true);
4715   for (unsigned Cnt = 0; Cnt < NestedLoopCount; ++Cnt) {
4716     if (checkOpenMPIterationSpace(DKind, CurStmt, SemaRef, DSA, Cnt,
4717                                   NestedLoopCount, CollapseLoopCountExpr,
4718                                   OrderedLoopCountExpr, VarsWithImplicitDSA,
4719                                   IterSpaces[Cnt], Captures))
4720       return 0;
4721     // Move on to the next nested for loop, or to the loop body.
4722     // OpenMP [2.8.1, simd construct, Restrictions]
4723     // All loops associated with the construct must be perfectly nested; that
4724     // is, there must be no intervening code nor any OpenMP directive between
4725     // any two loops.
4726     CurStmt = cast<ForStmt>(CurStmt)->getBody()->IgnoreContainers();
4727   }
4728 
4729   Built.clear(/* size */ NestedLoopCount);
4730 
4731   if (SemaRef.CurContext->isDependentContext())
4732     return NestedLoopCount;
4733 
4734   // An example of what is generated for the following code:
4735   //
4736   //   #pragma omp simd collapse(2) ordered(2)
4737   //   for (i = 0; i < NI; ++i)
4738   //     for (k = 0; k < NK; ++k)
4739   //       for (j = J0; j < NJ; j+=2) {
4740   //         <loop body>
4741   //       }
4742   //
4743   // We generate the code below.
4744   // Note: the loop body may be outlined in CodeGen.
4745   // Note: some counters may be C++ classes, operator- is used to find number of
4746   // iterations and operator+= to calculate counter value.
4747   // Note: decltype(NumIterations) must be integer type (in 'omp for', only i32
4748   // or i64 is currently supported).
4749   //
4750   //   #define NumIterations (NI * ((NJ - J0 - 1 + 2) / 2))
4751   //   for (int[32|64]_t IV = 0; IV < NumIterations; ++IV ) {
4752   //     .local.i = IV / ((NJ - J0 - 1 + 2) / 2);
4753   //     .local.j = J0 + (IV % ((NJ - J0 - 1 + 2) / 2)) * 2;
4754   //     // similar updates for vars in clauses (e.g. 'linear')
4755   //     <loop body (using local i and j)>
4756   //   }
4757   //   i = NI; // assign final values of counters
4758   //   j = NJ;
4759   //
4760 
4761   // Last iteration number is (I1 * I2 * ... In) - 1, where I1, I2 ... In are
4762   // the iteration counts of the collapsed for loops.
4763   // Precondition tests if there is at least one iteration (all conditions are
4764   // true).
4765   auto PreCond = ExprResult(IterSpaces[0].PreCond);
4766   Expr *N0 = IterSpaces[0].NumIterations;
4767   ExprResult LastIteration32 =
4768       widenIterationCount(/*Bits=*/32,
4769                           SemaRef
4770                               .PerformImplicitConversion(
4771                                   N0->IgnoreImpCasts(), N0->getType(),
4772                                   Sema::AA_Converting, /*AllowExplicit=*/true)
4773                               .get(),
4774                           SemaRef);
4775   ExprResult LastIteration64 = widenIterationCount(
4776       /*Bits=*/64,
4777       SemaRef
4778           .PerformImplicitConversion(N0->IgnoreImpCasts(), N0->getType(),
4779                                      Sema::AA_Converting,
4780                                      /*AllowExplicit=*/true)
4781           .get(),
4782       SemaRef);
4783 
4784   if (!LastIteration32.isUsable() || !LastIteration64.isUsable())
4785     return NestedLoopCount;
4786 
4787   ASTContext &C = SemaRef.Context;
4788   bool AllCountsNeedLessThan32Bits = C.getTypeSize(N0->getType()) < 32;
4789 
4790   Scope *CurScope = DSA.getCurScope();
4791   for (unsigned Cnt = 1; Cnt < NestedLoopCount; ++Cnt) {
4792     if (PreCond.isUsable()) {
4793       PreCond =
4794           SemaRef.BuildBinOp(CurScope, PreCond.get()->getExprLoc(), BO_LAnd,
4795                              PreCond.get(), IterSpaces[Cnt].PreCond);
4796     }
4797     Expr *N = IterSpaces[Cnt].NumIterations;
4798     SourceLocation Loc = N->getExprLoc();
4799     AllCountsNeedLessThan32Bits &= C.getTypeSize(N->getType()) < 32;
4800     if (LastIteration32.isUsable())
4801       LastIteration32 = SemaRef.BuildBinOp(
4802           CurScope, Loc, BO_Mul, LastIteration32.get(),
4803           SemaRef
4804               .PerformImplicitConversion(N->IgnoreImpCasts(), N->getType(),
4805                                          Sema::AA_Converting,
4806                                          /*AllowExplicit=*/true)
4807               .get());
4808     if (LastIteration64.isUsable())
4809       LastIteration64 = SemaRef.BuildBinOp(
4810           CurScope, Loc, BO_Mul, LastIteration64.get(),
4811           SemaRef
4812               .PerformImplicitConversion(N->IgnoreImpCasts(), N->getType(),
4813                                          Sema::AA_Converting,
4814                                          /*AllowExplicit=*/true)
4815               .get());
4816   }
4817 
4818   // Choose either the 32-bit or 64-bit version.
4819   ExprResult LastIteration = LastIteration64;
4820   if (LastIteration32.isUsable() &&
4821       C.getTypeSize(LastIteration32.get()->getType()) == 32 &&
4822       (AllCountsNeedLessThan32Bits || NestedLoopCount == 1 ||
4823        fitsInto(
4824            /*Bits=*/32,
4825            LastIteration32.get()->getType()->hasSignedIntegerRepresentation(),
4826            LastIteration64.get(), SemaRef)))
4827     LastIteration = LastIteration32;
4828   QualType VType = LastIteration.get()->getType();
4829   QualType RealVType = VType;
4830   QualType StrideVType = VType;
4831   if (isOpenMPTaskLoopDirective(DKind)) {
4832     VType =
4833         SemaRef.Context.getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/0);
4834     StrideVType =
4835         SemaRef.Context.getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/1);
4836   }
4837 
4838   if (!LastIteration.isUsable())
4839     return 0;
4840 
4841   // Save the number of iterations.
4842   ExprResult NumIterations = LastIteration;
4843   {
4844     LastIteration = SemaRef.BuildBinOp(
4845         CurScope, LastIteration.get()->getExprLoc(), BO_Sub,
4846         LastIteration.get(),
4847         SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get());
4848     if (!LastIteration.isUsable())
4849       return 0;
4850   }
4851 
4852   // Calculate the last iteration number beforehand instead of doing this on
4853   // each iteration. Do not do this if the number of iterations may be kfold-ed.
4854   llvm::APSInt Result;
4855   bool IsConstant =
4856       LastIteration.get()->isIntegerConstantExpr(Result, SemaRef.Context);
4857   ExprResult CalcLastIteration;
4858   if (!IsConstant) {
4859     ExprResult SaveRef =
4860         tryBuildCapture(SemaRef, LastIteration.get(), Captures);
4861     LastIteration = SaveRef;
4862 
4863     // Prepare SaveRef + 1.
4864     NumIterations = SemaRef.BuildBinOp(
4865         CurScope, SaveRef.get()->getExprLoc(), BO_Add, SaveRef.get(),
4866         SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get());
4867     if (!NumIterations.isUsable())
4868       return 0;
4869   }
4870 
4871   SourceLocation InitLoc = IterSpaces[0].InitSrcRange.getBegin();
4872 
4873   // Build variables passed into runtime, necessary for worksharing directives.
4874   ExprResult LB, UB, IL, ST, EUB, CombLB, CombUB, PrevLB, PrevUB, CombEUB;
4875   if (isOpenMPWorksharingDirective(DKind) || isOpenMPTaskLoopDirective(DKind) ||
4876       isOpenMPDistributeDirective(DKind)) {
4877     // Lower bound variable, initialized with zero.
4878     VarDecl *LBDecl = buildVarDecl(SemaRef, InitLoc, VType, ".omp.lb");
4879     LB = buildDeclRefExpr(SemaRef, LBDecl, VType, InitLoc);
4880     SemaRef.AddInitializerToDecl(LBDecl,
4881                                  SemaRef.ActOnIntegerConstant(InitLoc, 0).get(),
4882                                  /*DirectInit*/ false);
4883 
4884     // Upper bound variable, initialized with last iteration number.
4885     VarDecl *UBDecl = buildVarDecl(SemaRef, InitLoc, VType, ".omp.ub");
4886     UB = buildDeclRefExpr(SemaRef, UBDecl, VType, InitLoc);
4887     SemaRef.AddInitializerToDecl(UBDecl, LastIteration.get(),
4888                                  /*DirectInit*/ false);
4889 
4890     // A 32-bit variable-flag where runtime returns 1 for the last iteration.
4891     // This will be used to implement clause 'lastprivate'.
4892     QualType Int32Ty = SemaRef.Context.getIntTypeForBitwidth(32, true);
4893     VarDecl *ILDecl = buildVarDecl(SemaRef, InitLoc, Int32Ty, ".omp.is_last");
4894     IL = buildDeclRefExpr(SemaRef, ILDecl, Int32Ty, InitLoc);
4895     SemaRef.AddInitializerToDecl(ILDecl,
4896                                  SemaRef.ActOnIntegerConstant(InitLoc, 0).get(),
4897                                  /*DirectInit*/ false);
4898 
4899     // Stride variable returned by runtime (we initialize it to 1 by default).
4900     VarDecl *STDecl =
4901         buildVarDecl(SemaRef, InitLoc, StrideVType, ".omp.stride");
4902     ST = buildDeclRefExpr(SemaRef, STDecl, StrideVType, InitLoc);
4903     SemaRef.AddInitializerToDecl(STDecl,
4904                                  SemaRef.ActOnIntegerConstant(InitLoc, 1).get(),
4905                                  /*DirectInit*/ false);
4906 
4907     // Build expression: UB = min(UB, LastIteration)
4908     // It is necessary for CodeGen of directives with static scheduling.
4909     ExprResult IsUBGreater = SemaRef.BuildBinOp(CurScope, InitLoc, BO_GT,
4910                                                 UB.get(), LastIteration.get());
4911     ExprResult CondOp = SemaRef.ActOnConditionalOp(
4912         InitLoc, InitLoc, IsUBGreater.get(), LastIteration.get(), UB.get());
4913     EUB = SemaRef.BuildBinOp(CurScope, InitLoc, BO_Assign, UB.get(),
4914                              CondOp.get());
4915     EUB = SemaRef.ActOnFinishFullExpr(EUB.get());
4916 
4917     // If we have a combined directive that combines 'distribute', 'for' or
4918     // 'simd' we need to be able to access the bounds of the schedule of the
4919     // enclosing region. E.g. in 'distribute parallel for' the bounds obtained
4920     // by scheduling 'distribute' have to be passed to the schedule of 'for'.
4921     if (isOpenMPLoopBoundSharingDirective(DKind)) {
4922       // Lower bound variable, initialized with zero.
4923       VarDecl *CombLBDecl =
4924           buildVarDecl(SemaRef, InitLoc, VType, ".omp.comb.lb");
4925       CombLB = buildDeclRefExpr(SemaRef, CombLBDecl, VType, InitLoc);
4926       SemaRef.AddInitializerToDecl(
4927           CombLBDecl, SemaRef.ActOnIntegerConstant(InitLoc, 0).get(),
4928           /*DirectInit*/ false);
4929 
4930       // Upper bound variable, initialized with last iteration number.
4931       VarDecl *CombUBDecl =
4932           buildVarDecl(SemaRef, InitLoc, VType, ".omp.comb.ub");
4933       CombUB = buildDeclRefExpr(SemaRef, CombUBDecl, VType, InitLoc);
4934       SemaRef.AddInitializerToDecl(CombUBDecl, LastIteration.get(),
4935                                    /*DirectInit*/ false);
4936 
4937       ExprResult CombIsUBGreater = SemaRef.BuildBinOp(
4938           CurScope, InitLoc, BO_GT, CombUB.get(), LastIteration.get());
4939       ExprResult CombCondOp =
4940           SemaRef.ActOnConditionalOp(InitLoc, InitLoc, CombIsUBGreater.get(),
4941                                      LastIteration.get(), CombUB.get());
4942       CombEUB = SemaRef.BuildBinOp(CurScope, InitLoc, BO_Assign, CombUB.get(),
4943                                    CombCondOp.get());
4944       CombEUB = SemaRef.ActOnFinishFullExpr(CombEUB.get());
4945 
4946       const CapturedDecl *CD = cast<CapturedStmt>(AStmt)->getCapturedDecl();
4947       // We expect to have at least 2 more parameters than the 'parallel'
4948       // directive does - the lower and upper bounds of the previous schedule.
4949       assert(CD->getNumParams() >= 4 &&
4950              "Unexpected number of parameters in loop combined directive");
4951 
4952       // Set the proper type for the bounds given what we learned from the
4953       // enclosed loops.
4954       ImplicitParamDecl *PrevLBDecl = CD->getParam(/*PrevLB=*/2);
4955       ImplicitParamDecl *PrevUBDecl = CD->getParam(/*PrevUB=*/3);
4956 
4957       // Previous lower and upper bounds are obtained from the region
4958       // parameters.
4959       PrevLB =
4960           buildDeclRefExpr(SemaRef, PrevLBDecl, PrevLBDecl->getType(), InitLoc);
4961       PrevUB =
4962           buildDeclRefExpr(SemaRef, PrevUBDecl, PrevUBDecl->getType(), InitLoc);
4963     }
4964   }
4965 
4966   // Build the iteration variable and its initialization before loop.
4967   ExprResult IV;
4968   ExprResult Init, CombInit;
4969   {
4970     VarDecl *IVDecl = buildVarDecl(SemaRef, InitLoc, RealVType, ".omp.iv");
4971     IV = buildDeclRefExpr(SemaRef, IVDecl, RealVType, InitLoc);
4972     Expr *RHS =
4973         (isOpenMPWorksharingDirective(DKind) ||
4974          isOpenMPTaskLoopDirective(DKind) || isOpenMPDistributeDirective(DKind))
4975             ? LB.get()
4976             : SemaRef.ActOnIntegerConstant(SourceLocation(), 0).get();
4977     Init = SemaRef.BuildBinOp(CurScope, InitLoc, BO_Assign, IV.get(), RHS);
4978     Init = SemaRef.ActOnFinishFullExpr(Init.get());
4979 
4980     if (isOpenMPLoopBoundSharingDirective(DKind)) {
4981       Expr *CombRHS =
4982           (isOpenMPWorksharingDirective(DKind) ||
4983            isOpenMPTaskLoopDirective(DKind) ||
4984            isOpenMPDistributeDirective(DKind))
4985               ? CombLB.get()
4986               : SemaRef.ActOnIntegerConstant(SourceLocation(), 0).get();
4987       CombInit =
4988           SemaRef.BuildBinOp(CurScope, InitLoc, BO_Assign, IV.get(), CombRHS);
4989       CombInit = SemaRef.ActOnFinishFullExpr(CombInit.get());
4990     }
4991   }
4992 
4993   // Loop condition (IV < NumIterations) or (IV <= UB) for worksharing loops.
4994   SourceLocation CondLoc = AStmt->getLocStart();
4995   ExprResult Cond =
4996       (isOpenMPWorksharingDirective(DKind) ||
4997        isOpenMPTaskLoopDirective(DKind) || isOpenMPDistributeDirective(DKind))
4998           ? SemaRef.BuildBinOp(CurScope, CondLoc, BO_LE, IV.get(), UB.get())
4999           : SemaRef.BuildBinOp(CurScope, CondLoc, BO_LT, IV.get(),
5000                                NumIterations.get());
5001   ExprResult CombCond;
5002   if (isOpenMPLoopBoundSharingDirective(DKind)) {
5003     CombCond =
5004         SemaRef.BuildBinOp(CurScope, CondLoc, BO_LE, IV.get(), CombUB.get());
5005   }
5006   // Loop increment (IV = IV + 1)
5007   SourceLocation IncLoc = AStmt->getLocStart();
5008   ExprResult Inc =
5009       SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, IV.get(),
5010                          SemaRef.ActOnIntegerConstant(IncLoc, 1).get());
5011   if (!Inc.isUsable())
5012     return 0;
5013   Inc = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, IV.get(), Inc.get());
5014   Inc = SemaRef.ActOnFinishFullExpr(Inc.get());
5015   if (!Inc.isUsable())
5016     return 0;
5017 
5018   // Increments for worksharing loops (LB = LB + ST; UB = UB + ST).
5019   // Used for directives with static scheduling.
5020   // In combined construct, add combined version that use CombLB and CombUB
5021   // base variables for the update
5022   ExprResult NextLB, NextUB, CombNextLB, CombNextUB;
5023   if (isOpenMPWorksharingDirective(DKind) || isOpenMPTaskLoopDirective(DKind) ||
5024       isOpenMPDistributeDirective(DKind)) {
5025     // LB + ST
5026     NextLB = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, LB.get(), ST.get());
5027     if (!NextLB.isUsable())
5028       return 0;
5029     // LB = LB + ST
5030     NextLB =
5031         SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, LB.get(), NextLB.get());
5032     NextLB = SemaRef.ActOnFinishFullExpr(NextLB.get());
5033     if (!NextLB.isUsable())
5034       return 0;
5035     // UB + ST
5036     NextUB = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, UB.get(), ST.get());
5037     if (!NextUB.isUsable())
5038       return 0;
5039     // UB = UB + ST
5040     NextUB =
5041         SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, UB.get(), NextUB.get());
5042     NextUB = SemaRef.ActOnFinishFullExpr(NextUB.get());
5043     if (!NextUB.isUsable())
5044       return 0;
5045     if (isOpenMPLoopBoundSharingDirective(DKind)) {
5046       CombNextLB =
5047           SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, CombLB.get(), ST.get());
5048       if (!NextLB.isUsable())
5049         return 0;
5050       // LB = LB + ST
5051       CombNextLB = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, CombLB.get(),
5052                                       CombNextLB.get());
5053       CombNextLB = SemaRef.ActOnFinishFullExpr(CombNextLB.get());
5054       if (!CombNextLB.isUsable())
5055         return 0;
5056       // UB + ST
5057       CombNextUB =
5058           SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, CombUB.get(), ST.get());
5059       if (!CombNextUB.isUsable())
5060         return 0;
5061       // UB = UB + ST
5062       CombNextUB = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, CombUB.get(),
5063                                       CombNextUB.get());
5064       CombNextUB = SemaRef.ActOnFinishFullExpr(CombNextUB.get());
5065       if (!CombNextUB.isUsable())
5066         return 0;
5067     }
5068   }
5069 
5070   // Create increment expression for distribute loop when combined in a same
5071   // directive with for as IV = IV + ST; ensure upper bound expression based
5072   // on PrevUB instead of NumIterations - used to implement 'for' when found
5073   // in combination with 'distribute', like in 'distribute parallel for'
5074   SourceLocation DistIncLoc = AStmt->getLocStart();
5075   ExprResult DistCond, DistInc, PrevEUB;
5076   if (isOpenMPLoopBoundSharingDirective(DKind)) {
5077     DistCond = SemaRef.BuildBinOp(CurScope, CondLoc, BO_LE, IV.get(), UB.get());
5078     assert(DistCond.isUsable() && "distribute cond expr was not built");
5079 
5080     DistInc =
5081         SemaRef.BuildBinOp(CurScope, DistIncLoc, BO_Add, IV.get(), ST.get());
5082     assert(DistInc.isUsable() && "distribute inc expr was not built");
5083     DistInc = SemaRef.BuildBinOp(CurScope, DistIncLoc, BO_Assign, IV.get(),
5084                                  DistInc.get());
5085     DistInc = SemaRef.ActOnFinishFullExpr(DistInc.get());
5086     assert(DistInc.isUsable() && "distribute inc expr was not built");
5087 
5088     // Build expression: UB = min(UB, prevUB) for #for in composite or combined
5089     // construct
5090     SourceLocation DistEUBLoc = AStmt->getLocStart();
5091     ExprResult IsUBGreater =
5092         SemaRef.BuildBinOp(CurScope, DistEUBLoc, BO_GT, UB.get(), PrevUB.get());
5093     ExprResult CondOp = SemaRef.ActOnConditionalOp(
5094         DistEUBLoc, DistEUBLoc, IsUBGreater.get(), PrevUB.get(), UB.get());
5095     PrevEUB = SemaRef.BuildBinOp(CurScope, DistIncLoc, BO_Assign, UB.get(),
5096                                  CondOp.get());
5097     PrevEUB = SemaRef.ActOnFinishFullExpr(PrevEUB.get());
5098   }
5099 
5100   // Build updates and final values of the loop counters.
5101   bool HasErrors = false;
5102   Built.Counters.resize(NestedLoopCount);
5103   Built.Inits.resize(NestedLoopCount);
5104   Built.Updates.resize(NestedLoopCount);
5105   Built.Finals.resize(NestedLoopCount);
5106   SmallVector<Expr *, 4> LoopMultipliers;
5107   {
5108     ExprResult Div;
5109     // Go from inner nested loop to outer.
5110     for (int Cnt = NestedLoopCount - 1; Cnt >= 0; --Cnt) {
5111       LoopIterationSpace &IS = IterSpaces[Cnt];
5112       SourceLocation UpdLoc = IS.IncSrcRange.getBegin();
5113       // Build: Iter = (IV / Div) % IS.NumIters
5114       // where Div is product of previous iterations' IS.NumIters.
5115       ExprResult Iter;
5116       if (Div.isUsable()) {
5117         Iter =
5118             SemaRef.BuildBinOp(CurScope, UpdLoc, BO_Div, IV.get(), Div.get());
5119       } else {
5120         Iter = IV;
5121         assert((Cnt == (int)NestedLoopCount - 1) &&
5122                "unusable div expected on first iteration only");
5123       }
5124 
5125       if (Cnt != 0 && Iter.isUsable())
5126         Iter = SemaRef.BuildBinOp(CurScope, UpdLoc, BO_Rem, Iter.get(),
5127                                   IS.NumIterations);
5128       if (!Iter.isUsable()) {
5129         HasErrors = true;
5130         break;
5131       }
5132 
5133       // Build update: IS.CounterVar(Private) = IS.Start + Iter * IS.Step
5134       auto *VD = cast<VarDecl>(cast<DeclRefExpr>(IS.CounterVar)->getDecl());
5135       DeclRefExpr *CounterVar = buildDeclRefExpr(
5136           SemaRef, VD, IS.CounterVar->getType(), IS.CounterVar->getExprLoc(),
5137           /*RefersToCapture=*/true);
5138       ExprResult Init = buildCounterInit(SemaRef, CurScope, UpdLoc, CounterVar,
5139                                          IS.CounterInit, Captures);
5140       if (!Init.isUsable()) {
5141         HasErrors = true;
5142         break;
5143       }
5144       ExprResult Update = buildCounterUpdate(
5145           SemaRef, CurScope, UpdLoc, CounterVar, IS.CounterInit, Iter,
5146           IS.CounterStep, IS.Subtract, &Captures);
5147       if (!Update.isUsable()) {
5148         HasErrors = true;
5149         break;
5150       }
5151 
5152       // Build final: IS.CounterVar = IS.Start + IS.NumIters * IS.Step
5153       ExprResult Final = buildCounterUpdate(
5154           SemaRef, CurScope, UpdLoc, CounterVar, IS.CounterInit,
5155           IS.NumIterations, IS.CounterStep, IS.Subtract, &Captures);
5156       if (!Final.isUsable()) {
5157         HasErrors = true;
5158         break;
5159       }
5160 
5161       // Build Div for the next iteration: Div <- Div * IS.NumIters
5162       if (Cnt != 0) {
5163         if (Div.isUnset())
5164           Div = IS.NumIterations;
5165         else
5166           Div = SemaRef.BuildBinOp(CurScope, UpdLoc, BO_Mul, Div.get(),
5167                                    IS.NumIterations);
5168 
5169         // Add parentheses (for debugging purposes only).
5170         if (Div.isUsable())
5171           Div = tryBuildCapture(SemaRef, Div.get(), Captures);
5172         if (!Div.isUsable()) {
5173           HasErrors = true;
5174           break;
5175         }
5176         LoopMultipliers.push_back(Div.get());
5177       }
5178       if (!Update.isUsable() || !Final.isUsable()) {
5179         HasErrors = true;
5180         break;
5181       }
5182       // Save results
5183       Built.Counters[Cnt] = IS.CounterVar;
5184       Built.PrivateCounters[Cnt] = IS.PrivateCounterVar;
5185       Built.Inits[Cnt] = Init.get();
5186       Built.Updates[Cnt] = Update.get();
5187       Built.Finals[Cnt] = Final.get();
5188     }
5189   }
5190 
5191   if (HasErrors)
5192     return 0;
5193 
5194   // Save results
5195   Built.IterationVarRef = IV.get();
5196   Built.LastIteration = LastIteration.get();
5197   Built.NumIterations = NumIterations.get();
5198   Built.CalcLastIteration =
5199       SemaRef.ActOnFinishFullExpr(CalcLastIteration.get()).get();
5200   Built.PreCond = PreCond.get();
5201   Built.PreInits = buildPreInits(C, Captures);
5202   Built.Cond = Cond.get();
5203   Built.Init = Init.get();
5204   Built.Inc = Inc.get();
5205   Built.LB = LB.get();
5206   Built.UB = UB.get();
5207   Built.IL = IL.get();
5208   Built.ST = ST.get();
5209   Built.EUB = EUB.get();
5210   Built.NLB = NextLB.get();
5211   Built.NUB = NextUB.get();
5212   Built.PrevLB = PrevLB.get();
5213   Built.PrevUB = PrevUB.get();
5214   Built.DistInc = DistInc.get();
5215   Built.PrevEUB = PrevEUB.get();
5216   Built.DistCombinedFields.LB = CombLB.get();
5217   Built.DistCombinedFields.UB = CombUB.get();
5218   Built.DistCombinedFields.EUB = CombEUB.get();
5219   Built.DistCombinedFields.Init = CombInit.get();
5220   Built.DistCombinedFields.Cond = CombCond.get();
5221   Built.DistCombinedFields.NLB = CombNextLB.get();
5222   Built.DistCombinedFields.NUB = CombNextUB.get();
5223 
5224   Expr *CounterVal = SemaRef.DefaultLvalueConversion(IV.get()).get();
5225   // Fill data for doacross depend clauses.
5226   for (const auto &Pair : DSA.getDoacrossDependClauses()) {
5227     if (Pair.first->getDependencyKind() == OMPC_DEPEND_source) {
5228       Pair.first->setCounterValue(CounterVal);
5229     } else {
5230       if (NestedLoopCount != Pair.second.size() ||
5231           NestedLoopCount != LoopMultipliers.size() + 1) {
5232         // Erroneous case - clause has some problems.
5233         Pair.first->setCounterValue(CounterVal);
5234         continue;
5235       }
5236       assert(Pair.first->getDependencyKind() == OMPC_DEPEND_sink);
5237       auto I = Pair.second.rbegin();
5238       auto IS = IterSpaces.rbegin();
5239       auto ILM = LoopMultipliers.rbegin();
5240       Expr *UpCounterVal = CounterVal;
5241       Expr *Multiplier = nullptr;
5242       for (int Cnt = NestedLoopCount - 1; Cnt >= 0; --Cnt) {
5243         if (I->first) {
5244           assert(IS->CounterStep);
5245           Expr *NormalizedOffset =
5246               SemaRef
5247                   .BuildBinOp(CurScope, I->first->getExprLoc(), BO_Div,
5248                               I->first, IS->CounterStep)
5249                   .get();
5250           if (Multiplier) {
5251             NormalizedOffset =
5252                 SemaRef
5253                     .BuildBinOp(CurScope, I->first->getExprLoc(), BO_Mul,
5254                                 NormalizedOffset, Multiplier)
5255                     .get();
5256           }
5257           assert(I->second == OO_Plus || I->second == OO_Minus);
5258           BinaryOperatorKind BOK = (I->second == OO_Plus) ? BO_Add : BO_Sub;
5259           UpCounterVal = SemaRef
5260                              .BuildBinOp(CurScope, I->first->getExprLoc(), BOK,
5261                                          UpCounterVal, NormalizedOffset)
5262                              .get();
5263         }
5264         Multiplier = *ILM;
5265         ++I;
5266         ++IS;
5267         ++ILM;
5268       }
5269       Pair.first->setCounterValue(UpCounterVal);
5270     }
5271   }
5272 
5273   return NestedLoopCount;
5274 }
5275 
5276 static Expr *getCollapseNumberExpr(ArrayRef<OMPClause *> Clauses) {
5277   auto CollapseClauses =
5278       OMPExecutableDirective::getClausesOfKind<OMPCollapseClause>(Clauses);
5279   if (CollapseClauses.begin() != CollapseClauses.end())
5280     return (*CollapseClauses.begin())->getNumForLoops();
5281   return nullptr;
5282 }
5283 
5284 static Expr *getOrderedNumberExpr(ArrayRef<OMPClause *> Clauses) {
5285   auto OrderedClauses =
5286       OMPExecutableDirective::getClausesOfKind<OMPOrderedClause>(Clauses);
5287   if (OrderedClauses.begin() != OrderedClauses.end())
5288     return (*OrderedClauses.begin())->getNumForLoops();
5289   return nullptr;
5290 }
5291 
5292 static bool checkSimdlenSafelenSpecified(Sema &S,
5293                                          const ArrayRef<OMPClause *> Clauses) {
5294   const OMPSafelenClause *Safelen = nullptr;
5295   const OMPSimdlenClause *Simdlen = nullptr;
5296 
5297   for (const OMPClause *Clause : Clauses) {
5298     if (Clause->getClauseKind() == OMPC_safelen)
5299       Safelen = cast<OMPSafelenClause>(Clause);
5300     else if (Clause->getClauseKind() == OMPC_simdlen)
5301       Simdlen = cast<OMPSimdlenClause>(Clause);
5302     if (Safelen && Simdlen)
5303       break;
5304   }
5305 
5306   if (Simdlen && Safelen) {
5307     llvm::APSInt SimdlenRes, SafelenRes;
5308     const Expr *SimdlenLength = Simdlen->getSimdlen();
5309     const Expr *SafelenLength = Safelen->getSafelen();
5310     if (SimdlenLength->isValueDependent() || SimdlenLength->isTypeDependent() ||
5311         SimdlenLength->isInstantiationDependent() ||
5312         SimdlenLength->containsUnexpandedParameterPack())
5313       return false;
5314     if (SafelenLength->isValueDependent() || SafelenLength->isTypeDependent() ||
5315         SafelenLength->isInstantiationDependent() ||
5316         SafelenLength->containsUnexpandedParameterPack())
5317       return false;
5318     SimdlenLength->EvaluateAsInt(SimdlenRes, S.Context);
5319     SafelenLength->EvaluateAsInt(SafelenRes, S.Context);
5320     // OpenMP 4.5 [2.8.1, simd Construct, Restrictions]
5321     // If both simdlen and safelen clauses are specified, the value of the
5322     // simdlen parameter must be less than or equal to the value of the safelen
5323     // parameter.
5324     if (SimdlenRes > SafelenRes) {
5325       S.Diag(SimdlenLength->getExprLoc(),
5326              diag::err_omp_wrong_simdlen_safelen_values)
5327           << SimdlenLength->getSourceRange() << SafelenLength->getSourceRange();
5328       return true;
5329     }
5330   }
5331   return false;
5332 }
5333 
5334 StmtResult
5335 Sema::ActOnOpenMPSimdDirective(ArrayRef<OMPClause *> Clauses, Stmt *AStmt,
5336                                SourceLocation StartLoc, SourceLocation EndLoc,
5337                                VarsWithInheritedDSAType &VarsWithImplicitDSA) {
5338   if (!AStmt)
5339     return StmtError();
5340 
5341   assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
5342   OMPLoopDirective::HelperExprs B;
5343   // In presence of clause 'collapse' or 'ordered' with number of loops, it will
5344   // define the nested loops number.
5345   unsigned NestedLoopCount = checkOpenMPLoop(
5346       OMPD_simd, getCollapseNumberExpr(Clauses), getOrderedNumberExpr(Clauses),
5347       AStmt, *this, *DSAStack, VarsWithImplicitDSA, B);
5348   if (NestedLoopCount == 0)
5349     return StmtError();
5350 
5351   assert((CurContext->isDependentContext() || B.builtAll()) &&
5352          "omp simd loop exprs were not built");
5353 
5354   if (!CurContext->isDependentContext()) {
5355     // Finalize the clauses that need pre-built expressions for CodeGen.
5356     for (OMPClause *C : Clauses) {
5357       if (auto *LC = dyn_cast<OMPLinearClause>(C))
5358         if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
5359                                      B.NumIterations, *this, CurScope,
5360                                      DSAStack))
5361           return StmtError();
5362     }
5363   }
5364 
5365   if (checkSimdlenSafelenSpecified(*this, Clauses))
5366     return StmtError();
5367 
5368   setFunctionHasBranchProtectedScope();
5369   return OMPSimdDirective::Create(Context, StartLoc, EndLoc, NestedLoopCount,
5370                                   Clauses, AStmt, B);
5371 }
5372 
5373 StmtResult
5374 Sema::ActOnOpenMPForDirective(ArrayRef<OMPClause *> Clauses, Stmt *AStmt,
5375                               SourceLocation StartLoc, SourceLocation EndLoc,
5376                               VarsWithInheritedDSAType &VarsWithImplicitDSA) {
5377   if (!AStmt)
5378     return StmtError();
5379 
5380   assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
5381   OMPLoopDirective::HelperExprs B;
5382   // In presence of clause 'collapse' or 'ordered' with number of loops, it will
5383   // define the nested loops number.
5384   unsigned NestedLoopCount = checkOpenMPLoop(
5385       OMPD_for, getCollapseNumberExpr(Clauses), getOrderedNumberExpr(Clauses),
5386       AStmt, *this, *DSAStack, VarsWithImplicitDSA, B);
5387   if (NestedLoopCount == 0)
5388     return StmtError();
5389 
5390   assert((CurContext->isDependentContext() || B.builtAll()) &&
5391          "omp for loop exprs were not built");
5392 
5393   if (!CurContext->isDependentContext()) {
5394     // Finalize the clauses that need pre-built expressions for CodeGen.
5395     for (OMPClause *C : Clauses) {
5396       if (auto *LC = dyn_cast<OMPLinearClause>(C))
5397         if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
5398                                      B.NumIterations, *this, CurScope,
5399                                      DSAStack))
5400           return StmtError();
5401     }
5402   }
5403 
5404   setFunctionHasBranchProtectedScope();
5405   return OMPForDirective::Create(Context, StartLoc, EndLoc, NestedLoopCount,
5406                                  Clauses, AStmt, B, DSAStack->isCancelRegion());
5407 }
5408 
5409 StmtResult Sema::ActOnOpenMPForSimdDirective(
5410     ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
5411     SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
5412   if (!AStmt)
5413     return StmtError();
5414 
5415   assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
5416   OMPLoopDirective::HelperExprs B;
5417   // In presence of clause 'collapse' or 'ordered' with number of loops, it will
5418   // define the nested loops number.
5419   unsigned NestedLoopCount =
5420       checkOpenMPLoop(OMPD_for_simd, getCollapseNumberExpr(Clauses),
5421                       getOrderedNumberExpr(Clauses), AStmt, *this, *DSAStack,
5422                       VarsWithImplicitDSA, B);
5423   if (NestedLoopCount == 0)
5424     return StmtError();
5425 
5426   assert((CurContext->isDependentContext() || B.builtAll()) &&
5427          "omp for simd loop exprs were not built");
5428 
5429   if (!CurContext->isDependentContext()) {
5430     // Finalize the clauses that need pre-built expressions for CodeGen.
5431     for (OMPClause *C : Clauses) {
5432       if (auto *LC = dyn_cast<OMPLinearClause>(C))
5433         if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
5434                                      B.NumIterations, *this, CurScope,
5435                                      DSAStack))
5436           return StmtError();
5437     }
5438   }
5439 
5440   if (checkSimdlenSafelenSpecified(*this, Clauses))
5441     return StmtError();
5442 
5443   setFunctionHasBranchProtectedScope();
5444   return OMPForSimdDirective::Create(Context, StartLoc, EndLoc, NestedLoopCount,
5445                                      Clauses, AStmt, B);
5446 }
5447 
5448 StmtResult Sema::ActOnOpenMPSectionsDirective(ArrayRef<OMPClause *> Clauses,
5449                                               Stmt *AStmt,
5450                                               SourceLocation StartLoc,
5451                                               SourceLocation EndLoc) {
5452   if (!AStmt)
5453     return StmtError();
5454 
5455   assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
5456   auto BaseStmt = AStmt;
5457   while (auto *CS = dyn_cast_or_null<CapturedStmt>(BaseStmt))
5458     BaseStmt = CS->getCapturedStmt();
5459   if (auto *C = dyn_cast_or_null<CompoundStmt>(BaseStmt)) {
5460     auto S = C->children();
5461     if (S.begin() == S.end())
5462       return StmtError();
5463     // All associated statements must be '#pragma omp section' except for
5464     // the first one.
5465     for (Stmt *SectionStmt : llvm::make_range(std::next(S.begin()), S.end())) {
5466       if (!SectionStmt || !isa<OMPSectionDirective>(SectionStmt)) {
5467         if (SectionStmt)
5468           Diag(SectionStmt->getLocStart(),
5469                diag::err_omp_sections_substmt_not_section);
5470         return StmtError();
5471       }
5472       cast<OMPSectionDirective>(SectionStmt)
5473           ->setHasCancel(DSAStack->isCancelRegion());
5474     }
5475   } else {
5476     Diag(AStmt->getLocStart(), diag::err_omp_sections_not_compound_stmt);
5477     return StmtError();
5478   }
5479 
5480   setFunctionHasBranchProtectedScope();
5481 
5482   return OMPSectionsDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt,
5483                                       DSAStack->isCancelRegion());
5484 }
5485 
5486 StmtResult Sema::ActOnOpenMPSectionDirective(Stmt *AStmt,
5487                                              SourceLocation StartLoc,
5488                                              SourceLocation EndLoc) {
5489   if (!AStmt)
5490     return StmtError();
5491 
5492   assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
5493 
5494   setFunctionHasBranchProtectedScope();
5495   DSAStack->setParentCancelRegion(DSAStack->isCancelRegion());
5496 
5497   return OMPSectionDirective::Create(Context, StartLoc, EndLoc, AStmt,
5498                                      DSAStack->isCancelRegion());
5499 }
5500 
5501 StmtResult Sema::ActOnOpenMPSingleDirective(ArrayRef<OMPClause *> Clauses,
5502                                             Stmt *AStmt,
5503                                             SourceLocation StartLoc,
5504                                             SourceLocation EndLoc) {
5505   if (!AStmt)
5506     return StmtError();
5507 
5508   assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
5509 
5510   setFunctionHasBranchProtectedScope();
5511 
5512   // OpenMP [2.7.3, single Construct, Restrictions]
5513   // The copyprivate clause must not be used with the nowait clause.
5514   const OMPClause *Nowait = nullptr;
5515   const OMPClause *Copyprivate = nullptr;
5516   for (const OMPClause *Clause : Clauses) {
5517     if (Clause->getClauseKind() == OMPC_nowait)
5518       Nowait = Clause;
5519     else if (Clause->getClauseKind() == OMPC_copyprivate)
5520       Copyprivate = Clause;
5521     if (Copyprivate && Nowait) {
5522       Diag(Copyprivate->getLocStart(),
5523            diag::err_omp_single_copyprivate_with_nowait);
5524       Diag(Nowait->getLocStart(), diag::note_omp_nowait_clause_here);
5525       return StmtError();
5526     }
5527   }
5528 
5529   return OMPSingleDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt);
5530 }
5531 
5532 StmtResult Sema::ActOnOpenMPMasterDirective(Stmt *AStmt,
5533                                             SourceLocation StartLoc,
5534                                             SourceLocation EndLoc) {
5535   if (!AStmt)
5536     return StmtError();
5537 
5538   assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
5539 
5540   setFunctionHasBranchProtectedScope();
5541 
5542   return OMPMasterDirective::Create(Context, StartLoc, EndLoc, AStmt);
5543 }
5544 
5545 StmtResult Sema::ActOnOpenMPCriticalDirective(
5546     const DeclarationNameInfo &DirName, ArrayRef<OMPClause *> Clauses,
5547     Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc) {
5548   if (!AStmt)
5549     return StmtError();
5550 
5551   assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
5552 
5553   bool ErrorFound = false;
5554   llvm::APSInt Hint;
5555   SourceLocation HintLoc;
5556   bool DependentHint = false;
5557   for (const OMPClause *C : Clauses) {
5558     if (C->getClauseKind() == OMPC_hint) {
5559       if (!DirName.getName()) {
5560         Diag(C->getLocStart(), diag::err_omp_hint_clause_no_name);
5561         ErrorFound = true;
5562       }
5563       Expr *E = cast<OMPHintClause>(C)->getHint();
5564       if (E->isTypeDependent() || E->isValueDependent() ||
5565           E->isInstantiationDependent()) {
5566         DependentHint = true;
5567       } else {
5568         Hint = E->EvaluateKnownConstInt(Context);
5569         HintLoc = C->getLocStart();
5570       }
5571     }
5572   }
5573   if (ErrorFound)
5574     return StmtError();
5575   const auto Pair = DSAStack->getCriticalWithHint(DirName);
5576   if (Pair.first && DirName.getName() && !DependentHint) {
5577     if (llvm::APSInt::compareValues(Hint, Pair.second) != 0) {
5578       Diag(StartLoc, diag::err_omp_critical_with_hint);
5579       if (HintLoc.isValid())
5580         Diag(HintLoc, diag::note_omp_critical_hint_here)
5581             << 0 << Hint.toString(/*Radix=*/10, /*Signed=*/false);
5582       else
5583         Diag(StartLoc, diag::note_omp_critical_no_hint) << 0;
5584       if (const auto *C = Pair.first->getSingleClause<OMPHintClause>()) {
5585         Diag(C->getLocStart(), diag::note_omp_critical_hint_here)
5586             << 1
5587             << C->getHint()->EvaluateKnownConstInt(Context).toString(
5588                    /*Radix=*/10, /*Signed=*/false);
5589       } else {
5590         Diag(Pair.first->getLocStart(), diag::note_omp_critical_no_hint) << 1;
5591       }
5592     }
5593   }
5594 
5595   setFunctionHasBranchProtectedScope();
5596 
5597   auto *Dir = OMPCriticalDirective::Create(Context, DirName, StartLoc, EndLoc,
5598                                            Clauses, AStmt);
5599   if (!Pair.first && DirName.getName() && !DependentHint)
5600     DSAStack->addCriticalWithHint(Dir, Hint);
5601   return Dir;
5602 }
5603 
5604 StmtResult Sema::ActOnOpenMPParallelForDirective(
5605     ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
5606     SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
5607   if (!AStmt)
5608     return StmtError();
5609 
5610   auto *CS = cast<CapturedStmt>(AStmt);
5611   // 1.2.2 OpenMP Language Terminology
5612   // Structured block - An executable statement with a single entry at the
5613   // top and a single exit at the bottom.
5614   // The point of exit cannot be a branch out of the structured block.
5615   // longjmp() and throw() must not violate the entry/exit criteria.
5616   CS->getCapturedDecl()->setNothrow();
5617 
5618   OMPLoopDirective::HelperExprs B;
5619   // In presence of clause 'collapse' or 'ordered' with number of loops, it will
5620   // define the nested loops number.
5621   unsigned NestedLoopCount =
5622       checkOpenMPLoop(OMPD_parallel_for, getCollapseNumberExpr(Clauses),
5623                       getOrderedNumberExpr(Clauses), AStmt, *this, *DSAStack,
5624                       VarsWithImplicitDSA, B);
5625   if (NestedLoopCount == 0)
5626     return StmtError();
5627 
5628   assert((CurContext->isDependentContext() || B.builtAll()) &&
5629          "omp parallel for loop exprs were not built");
5630 
5631   if (!CurContext->isDependentContext()) {
5632     // Finalize the clauses that need pre-built expressions for CodeGen.
5633     for (OMPClause *C : Clauses) {
5634       if (auto *LC = dyn_cast<OMPLinearClause>(C))
5635         if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
5636                                      B.NumIterations, *this, CurScope,
5637                                      DSAStack))
5638           return StmtError();
5639     }
5640   }
5641 
5642   setFunctionHasBranchProtectedScope();
5643   return OMPParallelForDirective::Create(Context, StartLoc, EndLoc,
5644                                          NestedLoopCount, Clauses, AStmt, B,
5645                                          DSAStack->isCancelRegion());
5646 }
5647 
5648 StmtResult Sema::ActOnOpenMPParallelForSimdDirective(
5649     ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
5650     SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
5651   if (!AStmt)
5652     return StmtError();
5653 
5654   auto *CS = cast<CapturedStmt>(AStmt);
5655   // 1.2.2 OpenMP Language Terminology
5656   // Structured block - An executable statement with a single entry at the
5657   // top and a single exit at the bottom.
5658   // The point of exit cannot be a branch out of the structured block.
5659   // longjmp() and throw() must not violate the entry/exit criteria.
5660   CS->getCapturedDecl()->setNothrow();
5661 
5662   OMPLoopDirective::HelperExprs B;
5663   // In presence of clause 'collapse' or 'ordered' with number of loops, it will
5664   // define the nested loops number.
5665   unsigned NestedLoopCount =
5666       checkOpenMPLoop(OMPD_parallel_for_simd, getCollapseNumberExpr(Clauses),
5667                       getOrderedNumberExpr(Clauses), AStmt, *this, *DSAStack,
5668                       VarsWithImplicitDSA, B);
5669   if (NestedLoopCount == 0)
5670     return StmtError();
5671 
5672   if (!CurContext->isDependentContext()) {
5673     // Finalize the clauses that need pre-built expressions for CodeGen.
5674     for (OMPClause *C : Clauses) {
5675       if (auto *LC = dyn_cast<OMPLinearClause>(C))
5676         if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
5677                                      B.NumIterations, *this, CurScope,
5678                                      DSAStack))
5679           return StmtError();
5680     }
5681   }
5682 
5683   if (checkSimdlenSafelenSpecified(*this, Clauses))
5684     return StmtError();
5685 
5686   setFunctionHasBranchProtectedScope();
5687   return OMPParallelForSimdDirective::Create(
5688       Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
5689 }
5690 
5691 StmtResult
5692 Sema::ActOnOpenMPParallelSectionsDirective(ArrayRef<OMPClause *> Clauses,
5693                                            Stmt *AStmt, SourceLocation StartLoc,
5694                                            SourceLocation EndLoc) {
5695   if (!AStmt)
5696     return StmtError();
5697 
5698   assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
5699   auto BaseStmt = AStmt;
5700   while (auto *CS = dyn_cast_or_null<CapturedStmt>(BaseStmt))
5701     BaseStmt = CS->getCapturedStmt();
5702   if (auto *C = dyn_cast_or_null<CompoundStmt>(BaseStmt)) {
5703     auto S = C->children();
5704     if (S.begin() == S.end())
5705       return StmtError();
5706     // All associated statements must be '#pragma omp section' except for
5707     // the first one.
5708     for (Stmt *SectionStmt : llvm::make_range(std::next(S.begin()), S.end())) {
5709       if (!SectionStmt || !isa<OMPSectionDirective>(SectionStmt)) {
5710         if (SectionStmt)
5711           Diag(SectionStmt->getLocStart(),
5712                diag::err_omp_parallel_sections_substmt_not_section);
5713         return StmtError();
5714       }
5715       cast<OMPSectionDirective>(SectionStmt)
5716           ->setHasCancel(DSAStack->isCancelRegion());
5717     }
5718   } else {
5719     Diag(AStmt->getLocStart(),
5720          diag::err_omp_parallel_sections_not_compound_stmt);
5721     return StmtError();
5722   }
5723 
5724   setFunctionHasBranchProtectedScope();
5725 
5726   return OMPParallelSectionsDirective::Create(
5727       Context, StartLoc, EndLoc, Clauses, AStmt, DSAStack->isCancelRegion());
5728 }
5729 
5730 StmtResult Sema::ActOnOpenMPTaskDirective(ArrayRef<OMPClause *> Clauses,
5731                                           Stmt *AStmt, SourceLocation StartLoc,
5732                                           SourceLocation EndLoc) {
5733   if (!AStmt)
5734     return StmtError();
5735 
5736   auto *CS = cast<CapturedStmt>(AStmt);
5737   // 1.2.2 OpenMP Language Terminology
5738   // Structured block - An executable statement with a single entry at the
5739   // top and a single exit at the bottom.
5740   // The point of exit cannot be a branch out of the structured block.
5741   // longjmp() and throw() must not violate the entry/exit criteria.
5742   CS->getCapturedDecl()->setNothrow();
5743 
5744   setFunctionHasBranchProtectedScope();
5745 
5746   return OMPTaskDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt,
5747                                   DSAStack->isCancelRegion());
5748 }
5749 
5750 StmtResult Sema::ActOnOpenMPTaskyieldDirective(SourceLocation StartLoc,
5751                                                SourceLocation EndLoc) {
5752   return OMPTaskyieldDirective::Create(Context, StartLoc, EndLoc);
5753 }
5754 
5755 StmtResult Sema::ActOnOpenMPBarrierDirective(SourceLocation StartLoc,
5756                                              SourceLocation EndLoc) {
5757   return OMPBarrierDirective::Create(Context, StartLoc, EndLoc);
5758 }
5759 
5760 StmtResult Sema::ActOnOpenMPTaskwaitDirective(SourceLocation StartLoc,
5761                                               SourceLocation EndLoc) {
5762   return OMPTaskwaitDirective::Create(Context, StartLoc, EndLoc);
5763 }
5764 
5765 StmtResult Sema::ActOnOpenMPTaskgroupDirective(ArrayRef<OMPClause *> Clauses,
5766                                                Stmt *AStmt,
5767                                                SourceLocation StartLoc,
5768                                                SourceLocation EndLoc) {
5769   if (!AStmt)
5770     return StmtError();
5771 
5772   assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
5773 
5774   setFunctionHasBranchProtectedScope();
5775 
5776   return OMPTaskgroupDirective::Create(Context, StartLoc, EndLoc, Clauses,
5777                                        AStmt,
5778                                        DSAStack->getTaskgroupReductionRef());
5779 }
5780 
5781 StmtResult Sema::ActOnOpenMPFlushDirective(ArrayRef<OMPClause *> Clauses,
5782                                            SourceLocation StartLoc,
5783                                            SourceLocation EndLoc) {
5784   assert(Clauses.size() <= 1 && "Extra clauses in flush directive");
5785   return OMPFlushDirective::Create(Context, StartLoc, EndLoc, Clauses);
5786 }
5787 
5788 StmtResult Sema::ActOnOpenMPOrderedDirective(ArrayRef<OMPClause *> Clauses,
5789                                              Stmt *AStmt,
5790                                              SourceLocation StartLoc,
5791                                              SourceLocation EndLoc) {
5792   const OMPClause *DependFound = nullptr;
5793   const OMPClause *DependSourceClause = nullptr;
5794   const OMPClause *DependSinkClause = nullptr;
5795   bool ErrorFound = false;
5796   const OMPThreadsClause *TC = nullptr;
5797   const OMPSIMDClause *SC = nullptr;
5798   for (const OMPClause *C : Clauses) {
5799     if (auto *DC = dyn_cast<OMPDependClause>(C)) {
5800       DependFound = C;
5801       if (DC->getDependencyKind() == OMPC_DEPEND_source) {
5802         if (DependSourceClause) {
5803           Diag(C->getLocStart(), diag::err_omp_more_one_clause)
5804               << getOpenMPDirectiveName(OMPD_ordered)
5805               << getOpenMPClauseName(OMPC_depend) << 2;
5806           ErrorFound = true;
5807         } else {
5808           DependSourceClause = C;
5809         }
5810         if (DependSinkClause) {
5811           Diag(C->getLocStart(), diag::err_omp_depend_sink_source_not_allowed)
5812               << 0;
5813           ErrorFound = true;
5814         }
5815       } else if (DC->getDependencyKind() == OMPC_DEPEND_sink) {
5816         if (DependSourceClause) {
5817           Diag(C->getLocStart(), diag::err_omp_depend_sink_source_not_allowed)
5818               << 1;
5819           ErrorFound = true;
5820         }
5821         DependSinkClause = C;
5822       }
5823     } else if (C->getClauseKind() == OMPC_threads) {
5824       TC = cast<OMPThreadsClause>(C);
5825     } else if (C->getClauseKind() == OMPC_simd) {
5826       SC = cast<OMPSIMDClause>(C);
5827     }
5828   }
5829   if (!ErrorFound && !SC &&
5830       isOpenMPSimdDirective(DSAStack->getParentDirective())) {
5831     // OpenMP [2.8.1,simd Construct, Restrictions]
5832     // An ordered construct with the simd clause is the only OpenMP construct
5833     // that can appear in the simd region.
5834     Diag(StartLoc, diag::err_omp_prohibited_region_simd);
5835     ErrorFound = true;
5836   } else if (DependFound && (TC || SC)) {
5837     Diag(DependFound->getLocStart(), diag::err_omp_depend_clause_thread_simd)
5838         << getOpenMPClauseName(TC ? TC->getClauseKind() : SC->getClauseKind());
5839     ErrorFound = true;
5840   } else if (DependFound && !DSAStack->getParentOrderedRegionParam()) {
5841     Diag(DependFound->getLocStart(),
5842          diag::err_omp_ordered_directive_without_param);
5843     ErrorFound = true;
5844   } else if (TC || Clauses.empty()) {
5845     if (const Expr *Param = DSAStack->getParentOrderedRegionParam()) {
5846       SourceLocation ErrLoc = TC ? TC->getLocStart() : StartLoc;
5847       Diag(ErrLoc, diag::err_omp_ordered_directive_with_param)
5848           << (TC != nullptr);
5849       Diag(Param->getLocStart(), diag::note_omp_ordered_param);
5850       ErrorFound = true;
5851     }
5852   }
5853   if ((!AStmt && !DependFound) || ErrorFound)
5854     return StmtError();
5855 
5856   if (AStmt) {
5857     assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
5858 
5859     setFunctionHasBranchProtectedScope();
5860   }
5861 
5862   return OMPOrderedDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt);
5863 }
5864 
5865 namespace {
5866 /// Helper class for checking expression in 'omp atomic [update]'
5867 /// construct.
5868 class OpenMPAtomicUpdateChecker {
5869   /// Error results for atomic update expressions.
5870   enum ExprAnalysisErrorCode {
5871     /// A statement is not an expression statement.
5872     NotAnExpression,
5873     /// Expression is not builtin binary or unary operation.
5874     NotABinaryOrUnaryExpression,
5875     /// Unary operation is not post-/pre- increment/decrement operation.
5876     NotAnUnaryIncDecExpression,
5877     /// An expression is not of scalar type.
5878     NotAScalarType,
5879     /// A binary operation is not an assignment operation.
5880     NotAnAssignmentOp,
5881     /// RHS part of the binary operation is not a binary expression.
5882     NotABinaryExpression,
5883     /// RHS part is not additive/multiplicative/shift/biwise binary
5884     /// expression.
5885     NotABinaryOperator,
5886     /// RHS binary operation does not have reference to the updated LHS
5887     /// part.
5888     NotAnUpdateExpression,
5889     /// No errors is found.
5890     NoError
5891   };
5892   /// Reference to Sema.
5893   Sema &SemaRef;
5894   /// A location for note diagnostics (when error is found).
5895   SourceLocation NoteLoc;
5896   /// 'x' lvalue part of the source atomic expression.
5897   Expr *X;
5898   /// 'expr' rvalue part of the source atomic expression.
5899   Expr *E;
5900   /// Helper expression of the form
5901   /// 'OpaqueValueExpr(x) binop OpaqueValueExpr(expr)' or
5902   /// 'OpaqueValueExpr(expr) binop OpaqueValueExpr(x)'.
5903   Expr *UpdateExpr;
5904   /// Is 'x' a LHS in a RHS part of full update expression. It is
5905   /// important for non-associative operations.
5906   bool IsXLHSInRHSPart;
5907   BinaryOperatorKind Op;
5908   SourceLocation OpLoc;
5909   /// true if the source expression is a postfix unary operation, false
5910   /// if it is a prefix unary operation.
5911   bool IsPostfixUpdate;
5912 
5913 public:
5914   OpenMPAtomicUpdateChecker(Sema &SemaRef)
5915       : SemaRef(SemaRef), X(nullptr), E(nullptr), UpdateExpr(nullptr),
5916         IsXLHSInRHSPart(false), Op(BO_PtrMemD), IsPostfixUpdate(false) {}
5917   /// Check specified statement that it is suitable for 'atomic update'
5918   /// constructs and extract 'x', 'expr' and Operation from the original
5919   /// expression. If DiagId and NoteId == 0, then only check is performed
5920   /// without error notification.
5921   /// \param DiagId Diagnostic which should be emitted if error is found.
5922   /// \param NoteId Diagnostic note for the main error message.
5923   /// \return true if statement is not an update expression, false otherwise.
5924   bool checkStatement(Stmt *S, unsigned DiagId = 0, unsigned NoteId = 0);
5925   /// Return the 'x' lvalue part of the source atomic expression.
5926   Expr *getX() const { return X; }
5927   /// Return the 'expr' rvalue part of the source atomic expression.
5928   Expr *getExpr() const { return E; }
5929   /// Return the update expression used in calculation of the updated
5930   /// value. Always has form 'OpaqueValueExpr(x) binop OpaqueValueExpr(expr)' or
5931   /// 'OpaqueValueExpr(expr) binop OpaqueValueExpr(x)'.
5932   Expr *getUpdateExpr() const { return UpdateExpr; }
5933   /// Return true if 'x' is LHS in RHS part of full update expression,
5934   /// false otherwise.
5935   bool isXLHSInRHSPart() const { return IsXLHSInRHSPart; }
5936 
5937   /// true if the source expression is a postfix unary operation, false
5938   /// if it is a prefix unary operation.
5939   bool isPostfixUpdate() const { return IsPostfixUpdate; }
5940 
5941 private:
5942   bool checkBinaryOperation(BinaryOperator *AtomicBinOp, unsigned DiagId = 0,
5943                             unsigned NoteId = 0);
5944 };
5945 } // namespace
5946 
5947 bool OpenMPAtomicUpdateChecker::checkBinaryOperation(
5948     BinaryOperator *AtomicBinOp, unsigned DiagId, unsigned NoteId) {
5949   ExprAnalysisErrorCode ErrorFound = NoError;
5950   SourceLocation ErrorLoc, NoteLoc;
5951   SourceRange ErrorRange, NoteRange;
5952   // Allowed constructs are:
5953   //  x = x binop expr;
5954   //  x = expr binop x;
5955   if (AtomicBinOp->getOpcode() == BO_Assign) {
5956     X = AtomicBinOp->getLHS();
5957     if (const auto *AtomicInnerBinOp = dyn_cast<BinaryOperator>(
5958             AtomicBinOp->getRHS()->IgnoreParenImpCasts())) {
5959       if (AtomicInnerBinOp->isMultiplicativeOp() ||
5960           AtomicInnerBinOp->isAdditiveOp() || AtomicInnerBinOp->isShiftOp() ||
5961           AtomicInnerBinOp->isBitwiseOp()) {
5962         Op = AtomicInnerBinOp->getOpcode();
5963         OpLoc = AtomicInnerBinOp->getOperatorLoc();
5964         Expr *LHS = AtomicInnerBinOp->getLHS();
5965         Expr *RHS = AtomicInnerBinOp->getRHS();
5966         llvm::FoldingSetNodeID XId, LHSId, RHSId;
5967         X->IgnoreParenImpCasts()->Profile(XId, SemaRef.getASTContext(),
5968                                           /*Canonical=*/true);
5969         LHS->IgnoreParenImpCasts()->Profile(LHSId, SemaRef.getASTContext(),
5970                                             /*Canonical=*/true);
5971         RHS->IgnoreParenImpCasts()->Profile(RHSId, SemaRef.getASTContext(),
5972                                             /*Canonical=*/true);
5973         if (XId == LHSId) {
5974           E = RHS;
5975           IsXLHSInRHSPart = true;
5976         } else if (XId == RHSId) {
5977           E = LHS;
5978           IsXLHSInRHSPart = false;
5979         } else {
5980           ErrorLoc = AtomicInnerBinOp->getExprLoc();
5981           ErrorRange = AtomicInnerBinOp->getSourceRange();
5982           NoteLoc = X->getExprLoc();
5983           NoteRange = X->getSourceRange();
5984           ErrorFound = NotAnUpdateExpression;
5985         }
5986       } else {
5987         ErrorLoc = AtomicInnerBinOp->getExprLoc();
5988         ErrorRange = AtomicInnerBinOp->getSourceRange();
5989         NoteLoc = AtomicInnerBinOp->getOperatorLoc();
5990         NoteRange = SourceRange(NoteLoc, NoteLoc);
5991         ErrorFound = NotABinaryOperator;
5992       }
5993     } else {
5994       NoteLoc = ErrorLoc = AtomicBinOp->getRHS()->getExprLoc();
5995       NoteRange = ErrorRange = AtomicBinOp->getRHS()->getSourceRange();
5996       ErrorFound = NotABinaryExpression;
5997     }
5998   } else {
5999     ErrorLoc = AtomicBinOp->getExprLoc();
6000     ErrorRange = AtomicBinOp->getSourceRange();
6001     NoteLoc = AtomicBinOp->getOperatorLoc();
6002     NoteRange = SourceRange(NoteLoc, NoteLoc);
6003     ErrorFound = NotAnAssignmentOp;
6004   }
6005   if (ErrorFound != NoError && DiagId != 0 && NoteId != 0) {
6006     SemaRef.Diag(ErrorLoc, DiagId) << ErrorRange;
6007     SemaRef.Diag(NoteLoc, NoteId) << ErrorFound << NoteRange;
6008     return true;
6009   }
6010   if (SemaRef.CurContext->isDependentContext())
6011     E = X = UpdateExpr = nullptr;
6012   return ErrorFound != NoError;
6013 }
6014 
6015 bool OpenMPAtomicUpdateChecker::checkStatement(Stmt *S, unsigned DiagId,
6016                                                unsigned NoteId) {
6017   ExprAnalysisErrorCode ErrorFound = NoError;
6018   SourceLocation ErrorLoc, NoteLoc;
6019   SourceRange ErrorRange, NoteRange;
6020   // Allowed constructs are:
6021   //  x++;
6022   //  x--;
6023   //  ++x;
6024   //  --x;
6025   //  x binop= expr;
6026   //  x = x binop expr;
6027   //  x = expr binop x;
6028   if (auto *AtomicBody = dyn_cast<Expr>(S)) {
6029     AtomicBody = AtomicBody->IgnoreParenImpCasts();
6030     if (AtomicBody->getType()->isScalarType() ||
6031         AtomicBody->isInstantiationDependent()) {
6032       if (const auto *AtomicCompAssignOp = dyn_cast<CompoundAssignOperator>(
6033               AtomicBody->IgnoreParenImpCasts())) {
6034         // Check for Compound Assignment Operation
6035         Op = BinaryOperator::getOpForCompoundAssignment(
6036             AtomicCompAssignOp->getOpcode());
6037         OpLoc = AtomicCompAssignOp->getOperatorLoc();
6038         E = AtomicCompAssignOp->getRHS();
6039         X = AtomicCompAssignOp->getLHS()->IgnoreParens();
6040         IsXLHSInRHSPart = true;
6041       } else if (auto *AtomicBinOp = dyn_cast<BinaryOperator>(
6042                      AtomicBody->IgnoreParenImpCasts())) {
6043         // Check for Binary Operation
6044         if (checkBinaryOperation(AtomicBinOp, DiagId, NoteId))
6045           return true;
6046       } else if (const auto *AtomicUnaryOp = dyn_cast<UnaryOperator>(
6047                      AtomicBody->IgnoreParenImpCasts())) {
6048         // Check for Unary Operation
6049         if (AtomicUnaryOp->isIncrementDecrementOp()) {
6050           IsPostfixUpdate = AtomicUnaryOp->isPostfix();
6051           Op = AtomicUnaryOp->isIncrementOp() ? BO_Add : BO_Sub;
6052           OpLoc = AtomicUnaryOp->getOperatorLoc();
6053           X = AtomicUnaryOp->getSubExpr()->IgnoreParens();
6054           E = SemaRef.ActOnIntegerConstant(OpLoc, /*uint64_t Val=*/1).get();
6055           IsXLHSInRHSPart = true;
6056         } else {
6057           ErrorFound = NotAnUnaryIncDecExpression;
6058           ErrorLoc = AtomicUnaryOp->getExprLoc();
6059           ErrorRange = AtomicUnaryOp->getSourceRange();
6060           NoteLoc = AtomicUnaryOp->getOperatorLoc();
6061           NoteRange = SourceRange(NoteLoc, NoteLoc);
6062         }
6063       } else if (!AtomicBody->isInstantiationDependent()) {
6064         ErrorFound = NotABinaryOrUnaryExpression;
6065         NoteLoc = ErrorLoc = AtomicBody->getExprLoc();
6066         NoteRange = ErrorRange = AtomicBody->getSourceRange();
6067       }
6068     } else {
6069       ErrorFound = NotAScalarType;
6070       NoteLoc = ErrorLoc = AtomicBody->getLocStart();
6071       NoteRange = ErrorRange = SourceRange(NoteLoc, NoteLoc);
6072     }
6073   } else {
6074     ErrorFound = NotAnExpression;
6075     NoteLoc = ErrorLoc = S->getLocStart();
6076     NoteRange = ErrorRange = SourceRange(NoteLoc, NoteLoc);
6077   }
6078   if (ErrorFound != NoError && DiagId != 0 && NoteId != 0) {
6079     SemaRef.Diag(ErrorLoc, DiagId) << ErrorRange;
6080     SemaRef.Diag(NoteLoc, NoteId) << ErrorFound << NoteRange;
6081     return true;
6082   }
6083   if (SemaRef.CurContext->isDependentContext())
6084     E = X = UpdateExpr = nullptr;
6085   if (ErrorFound == NoError && E && X) {
6086     // Build an update expression of form 'OpaqueValueExpr(x) binop
6087     // OpaqueValueExpr(expr)' or 'OpaqueValueExpr(expr) binop
6088     // OpaqueValueExpr(x)' and then cast it to the type of the 'x' expression.
6089     auto *OVEX = new (SemaRef.getASTContext())
6090         OpaqueValueExpr(X->getExprLoc(), X->getType(), VK_RValue);
6091     auto *OVEExpr = new (SemaRef.getASTContext())
6092         OpaqueValueExpr(E->getExprLoc(), E->getType(), VK_RValue);
6093     ExprResult Update =
6094         SemaRef.CreateBuiltinBinOp(OpLoc, Op, IsXLHSInRHSPart ? OVEX : OVEExpr,
6095                                    IsXLHSInRHSPart ? OVEExpr : OVEX);
6096     if (Update.isInvalid())
6097       return true;
6098     Update = SemaRef.PerformImplicitConversion(Update.get(), X->getType(),
6099                                                Sema::AA_Casting);
6100     if (Update.isInvalid())
6101       return true;
6102     UpdateExpr = Update.get();
6103   }
6104   return ErrorFound != NoError;
6105 }
6106 
6107 StmtResult Sema::ActOnOpenMPAtomicDirective(ArrayRef<OMPClause *> Clauses,
6108                                             Stmt *AStmt,
6109                                             SourceLocation StartLoc,
6110                                             SourceLocation EndLoc) {
6111   if (!AStmt)
6112     return StmtError();
6113 
6114   auto *CS = cast<CapturedStmt>(AStmt);
6115   // 1.2.2 OpenMP Language Terminology
6116   // Structured block - An executable statement with a single entry at the
6117   // top and a single exit at the bottom.
6118   // The point of exit cannot be a branch out of the structured block.
6119   // longjmp() and throw() must not violate the entry/exit criteria.
6120   OpenMPClauseKind AtomicKind = OMPC_unknown;
6121   SourceLocation AtomicKindLoc;
6122   for (const OMPClause *C : Clauses) {
6123     if (C->getClauseKind() == OMPC_read || C->getClauseKind() == OMPC_write ||
6124         C->getClauseKind() == OMPC_update ||
6125         C->getClauseKind() == OMPC_capture) {
6126       if (AtomicKind != OMPC_unknown) {
6127         Diag(C->getLocStart(), diag::err_omp_atomic_several_clauses)
6128             << SourceRange(C->getLocStart(), C->getLocEnd());
6129         Diag(AtomicKindLoc, diag::note_omp_atomic_previous_clause)
6130             << getOpenMPClauseName(AtomicKind);
6131       } else {
6132         AtomicKind = C->getClauseKind();
6133         AtomicKindLoc = C->getLocStart();
6134       }
6135     }
6136   }
6137 
6138   Stmt *Body = CS->getCapturedStmt();
6139   if (auto *EWC = dyn_cast<ExprWithCleanups>(Body))
6140     Body = EWC->getSubExpr();
6141 
6142   Expr *X = nullptr;
6143   Expr *V = nullptr;
6144   Expr *E = nullptr;
6145   Expr *UE = nullptr;
6146   bool IsXLHSInRHSPart = false;
6147   bool IsPostfixUpdate = false;
6148   // OpenMP [2.12.6, atomic Construct]
6149   // In the next expressions:
6150   // * x and v (as applicable) are both l-value expressions with scalar type.
6151   // * During the execution of an atomic region, multiple syntactic
6152   // occurrences of x must designate the same storage location.
6153   // * Neither of v and expr (as applicable) may access the storage location
6154   // designated by x.
6155   // * Neither of x and expr (as applicable) may access the storage location
6156   // designated by v.
6157   // * expr is an expression with scalar type.
6158   // * binop is one of +, *, -, /, &, ^, |, <<, or >>.
6159   // * binop, binop=, ++, and -- are not overloaded operators.
6160   // * The expression x binop expr must be numerically equivalent to x binop
6161   // (expr). This requirement is satisfied if the operators in expr have
6162   // precedence greater than binop, or by using parentheses around expr or
6163   // subexpressions of expr.
6164   // * The expression expr binop x must be numerically equivalent to (expr)
6165   // binop x. This requirement is satisfied if the operators in expr have
6166   // precedence equal to or greater than binop, or by using parentheses around
6167   // expr or subexpressions of expr.
6168   // * For forms that allow multiple occurrences of x, the number of times
6169   // that x is evaluated is unspecified.
6170   if (AtomicKind == OMPC_read) {
6171     enum {
6172       NotAnExpression,
6173       NotAnAssignmentOp,
6174       NotAScalarType,
6175       NotAnLValue,
6176       NoError
6177     } ErrorFound = NoError;
6178     SourceLocation ErrorLoc, NoteLoc;
6179     SourceRange ErrorRange, NoteRange;
6180     // If clause is read:
6181     //  v = x;
6182     if (const auto *AtomicBody = dyn_cast<Expr>(Body)) {
6183       const auto *AtomicBinOp =
6184           dyn_cast<BinaryOperator>(AtomicBody->IgnoreParenImpCasts());
6185       if (AtomicBinOp && AtomicBinOp->getOpcode() == BO_Assign) {
6186         X = AtomicBinOp->getRHS()->IgnoreParenImpCasts();
6187         V = AtomicBinOp->getLHS()->IgnoreParenImpCasts();
6188         if ((X->isInstantiationDependent() || X->getType()->isScalarType()) &&
6189             (V->isInstantiationDependent() || V->getType()->isScalarType())) {
6190           if (!X->isLValue() || !V->isLValue()) {
6191             const Expr *NotLValueExpr = X->isLValue() ? V : X;
6192             ErrorFound = NotAnLValue;
6193             ErrorLoc = AtomicBinOp->getExprLoc();
6194             ErrorRange = AtomicBinOp->getSourceRange();
6195             NoteLoc = NotLValueExpr->getExprLoc();
6196             NoteRange = NotLValueExpr->getSourceRange();
6197           }
6198         } else if (!X->isInstantiationDependent() ||
6199                    !V->isInstantiationDependent()) {
6200           const Expr *NotScalarExpr =
6201               (X->isInstantiationDependent() || X->getType()->isScalarType())
6202                   ? V
6203                   : X;
6204           ErrorFound = NotAScalarType;
6205           ErrorLoc = AtomicBinOp->getExprLoc();
6206           ErrorRange = AtomicBinOp->getSourceRange();
6207           NoteLoc = NotScalarExpr->getExprLoc();
6208           NoteRange = NotScalarExpr->getSourceRange();
6209         }
6210       } else if (!AtomicBody->isInstantiationDependent()) {
6211         ErrorFound = NotAnAssignmentOp;
6212         ErrorLoc = AtomicBody->getExprLoc();
6213         ErrorRange = AtomicBody->getSourceRange();
6214         NoteLoc = AtomicBinOp ? AtomicBinOp->getOperatorLoc()
6215                               : AtomicBody->getExprLoc();
6216         NoteRange = AtomicBinOp ? AtomicBinOp->getSourceRange()
6217                                 : AtomicBody->getSourceRange();
6218       }
6219     } else {
6220       ErrorFound = NotAnExpression;
6221       NoteLoc = ErrorLoc = Body->getLocStart();
6222       NoteRange = ErrorRange = SourceRange(NoteLoc, NoteLoc);
6223     }
6224     if (ErrorFound != NoError) {
6225       Diag(ErrorLoc, diag::err_omp_atomic_read_not_expression_statement)
6226           << ErrorRange;
6227       Diag(NoteLoc, diag::note_omp_atomic_read_write) << ErrorFound
6228                                                       << NoteRange;
6229       return StmtError();
6230     }
6231     if (CurContext->isDependentContext())
6232       V = X = nullptr;
6233   } else if (AtomicKind == OMPC_write) {
6234     enum {
6235       NotAnExpression,
6236       NotAnAssignmentOp,
6237       NotAScalarType,
6238       NotAnLValue,
6239       NoError
6240     } ErrorFound = NoError;
6241     SourceLocation ErrorLoc, NoteLoc;
6242     SourceRange ErrorRange, NoteRange;
6243     // If clause is write:
6244     //  x = expr;
6245     if (const auto *AtomicBody = dyn_cast<Expr>(Body)) {
6246       const auto *AtomicBinOp =
6247           dyn_cast<BinaryOperator>(AtomicBody->IgnoreParenImpCasts());
6248       if (AtomicBinOp && AtomicBinOp->getOpcode() == BO_Assign) {
6249         X = AtomicBinOp->getLHS();
6250         E = AtomicBinOp->getRHS();
6251         if ((X->isInstantiationDependent() || X->getType()->isScalarType()) &&
6252             (E->isInstantiationDependent() || E->getType()->isScalarType())) {
6253           if (!X->isLValue()) {
6254             ErrorFound = NotAnLValue;
6255             ErrorLoc = AtomicBinOp->getExprLoc();
6256             ErrorRange = AtomicBinOp->getSourceRange();
6257             NoteLoc = X->getExprLoc();
6258             NoteRange = X->getSourceRange();
6259           }
6260         } else if (!X->isInstantiationDependent() ||
6261                    !E->isInstantiationDependent()) {
6262           const Expr *NotScalarExpr =
6263               (X->isInstantiationDependent() || X->getType()->isScalarType())
6264                   ? E
6265                   : X;
6266           ErrorFound = NotAScalarType;
6267           ErrorLoc = AtomicBinOp->getExprLoc();
6268           ErrorRange = AtomicBinOp->getSourceRange();
6269           NoteLoc = NotScalarExpr->getExprLoc();
6270           NoteRange = NotScalarExpr->getSourceRange();
6271         }
6272       } else if (!AtomicBody->isInstantiationDependent()) {
6273         ErrorFound = NotAnAssignmentOp;
6274         ErrorLoc = AtomicBody->getExprLoc();
6275         ErrorRange = AtomicBody->getSourceRange();
6276         NoteLoc = AtomicBinOp ? AtomicBinOp->getOperatorLoc()
6277                               : AtomicBody->getExprLoc();
6278         NoteRange = AtomicBinOp ? AtomicBinOp->getSourceRange()
6279                                 : AtomicBody->getSourceRange();
6280       }
6281     } else {
6282       ErrorFound = NotAnExpression;
6283       NoteLoc = ErrorLoc = Body->getLocStart();
6284       NoteRange = ErrorRange = SourceRange(NoteLoc, NoteLoc);
6285     }
6286     if (ErrorFound != NoError) {
6287       Diag(ErrorLoc, diag::err_omp_atomic_write_not_expression_statement)
6288           << ErrorRange;
6289       Diag(NoteLoc, diag::note_omp_atomic_read_write) << ErrorFound
6290                                                       << NoteRange;
6291       return StmtError();
6292     }
6293     if (CurContext->isDependentContext())
6294       E = X = nullptr;
6295   } else if (AtomicKind == OMPC_update || AtomicKind == OMPC_unknown) {
6296     // If clause is update:
6297     //  x++;
6298     //  x--;
6299     //  ++x;
6300     //  --x;
6301     //  x binop= expr;
6302     //  x = x binop expr;
6303     //  x = expr binop x;
6304     OpenMPAtomicUpdateChecker Checker(*this);
6305     if (Checker.checkStatement(
6306             Body, (AtomicKind == OMPC_update)
6307                       ? diag::err_omp_atomic_update_not_expression_statement
6308                       : diag::err_omp_atomic_not_expression_statement,
6309             diag::note_omp_atomic_update))
6310       return StmtError();
6311     if (!CurContext->isDependentContext()) {
6312       E = Checker.getExpr();
6313       X = Checker.getX();
6314       UE = Checker.getUpdateExpr();
6315       IsXLHSInRHSPart = Checker.isXLHSInRHSPart();
6316     }
6317   } else if (AtomicKind == OMPC_capture) {
6318     enum {
6319       NotAnAssignmentOp,
6320       NotACompoundStatement,
6321       NotTwoSubstatements,
6322       NotASpecificExpression,
6323       NoError
6324     } ErrorFound = NoError;
6325     SourceLocation ErrorLoc, NoteLoc;
6326     SourceRange ErrorRange, NoteRange;
6327     if (const auto *AtomicBody = dyn_cast<Expr>(Body)) {
6328       // If clause is a capture:
6329       //  v = x++;
6330       //  v = x--;
6331       //  v = ++x;
6332       //  v = --x;
6333       //  v = x binop= expr;
6334       //  v = x = x binop expr;
6335       //  v = x = expr binop x;
6336       const auto *AtomicBinOp =
6337           dyn_cast<BinaryOperator>(AtomicBody->IgnoreParenImpCasts());
6338       if (AtomicBinOp && AtomicBinOp->getOpcode() == BO_Assign) {
6339         V = AtomicBinOp->getLHS();
6340         Body = AtomicBinOp->getRHS()->IgnoreParenImpCasts();
6341         OpenMPAtomicUpdateChecker Checker(*this);
6342         if (Checker.checkStatement(
6343                 Body, diag::err_omp_atomic_capture_not_expression_statement,
6344                 diag::note_omp_atomic_update))
6345           return StmtError();
6346         E = Checker.getExpr();
6347         X = Checker.getX();
6348         UE = Checker.getUpdateExpr();
6349         IsXLHSInRHSPart = Checker.isXLHSInRHSPart();
6350         IsPostfixUpdate = Checker.isPostfixUpdate();
6351       } else if (!AtomicBody->isInstantiationDependent()) {
6352         ErrorLoc = AtomicBody->getExprLoc();
6353         ErrorRange = AtomicBody->getSourceRange();
6354         NoteLoc = AtomicBinOp ? AtomicBinOp->getOperatorLoc()
6355                               : AtomicBody->getExprLoc();
6356         NoteRange = AtomicBinOp ? AtomicBinOp->getSourceRange()
6357                                 : AtomicBody->getSourceRange();
6358         ErrorFound = NotAnAssignmentOp;
6359       }
6360       if (ErrorFound != NoError) {
6361         Diag(ErrorLoc, diag::err_omp_atomic_capture_not_expression_statement)
6362             << ErrorRange;
6363         Diag(NoteLoc, diag::note_omp_atomic_capture) << ErrorFound << NoteRange;
6364         return StmtError();
6365       }
6366       if (CurContext->isDependentContext())
6367         UE = V = E = X = nullptr;
6368     } else {
6369       // If clause is a capture:
6370       //  { v = x; x = expr; }
6371       //  { v = x; x++; }
6372       //  { v = x; x--; }
6373       //  { v = x; ++x; }
6374       //  { v = x; --x; }
6375       //  { v = x; x binop= expr; }
6376       //  { v = x; x = x binop expr; }
6377       //  { v = x; x = expr binop x; }
6378       //  { x++; v = x; }
6379       //  { x--; v = x; }
6380       //  { ++x; v = x; }
6381       //  { --x; v = x; }
6382       //  { x binop= expr; v = x; }
6383       //  { x = x binop expr; v = x; }
6384       //  { x = expr binop x; v = x; }
6385       if (auto *CS = dyn_cast<CompoundStmt>(Body)) {
6386         // Check that this is { expr1; expr2; }
6387         if (CS->size() == 2) {
6388           Stmt *First = CS->body_front();
6389           Stmt *Second = CS->body_back();
6390           if (auto *EWC = dyn_cast<ExprWithCleanups>(First))
6391             First = EWC->getSubExpr()->IgnoreParenImpCasts();
6392           if (auto *EWC = dyn_cast<ExprWithCleanups>(Second))
6393             Second = EWC->getSubExpr()->IgnoreParenImpCasts();
6394           // Need to find what subexpression is 'v' and what is 'x'.
6395           OpenMPAtomicUpdateChecker Checker(*this);
6396           bool IsUpdateExprFound = !Checker.checkStatement(Second);
6397           BinaryOperator *BinOp = nullptr;
6398           if (IsUpdateExprFound) {
6399             BinOp = dyn_cast<BinaryOperator>(First);
6400             IsUpdateExprFound = BinOp && BinOp->getOpcode() == BO_Assign;
6401           }
6402           if (IsUpdateExprFound && !CurContext->isDependentContext()) {
6403             //  { v = x; x++; }
6404             //  { v = x; x--; }
6405             //  { v = x; ++x; }
6406             //  { v = x; --x; }
6407             //  { v = x; x binop= expr; }
6408             //  { v = x; x = x binop expr; }
6409             //  { v = x; x = expr binop x; }
6410             // Check that the first expression has form v = x.
6411             Expr *PossibleX = BinOp->getRHS()->IgnoreParenImpCasts();
6412             llvm::FoldingSetNodeID XId, PossibleXId;
6413             Checker.getX()->Profile(XId, Context, /*Canonical=*/true);
6414             PossibleX->Profile(PossibleXId, Context, /*Canonical=*/true);
6415             IsUpdateExprFound = XId == PossibleXId;
6416             if (IsUpdateExprFound) {
6417               V = BinOp->getLHS();
6418               X = Checker.getX();
6419               E = Checker.getExpr();
6420               UE = Checker.getUpdateExpr();
6421               IsXLHSInRHSPart = Checker.isXLHSInRHSPart();
6422               IsPostfixUpdate = true;
6423             }
6424           }
6425           if (!IsUpdateExprFound) {
6426             IsUpdateExprFound = !Checker.checkStatement(First);
6427             BinOp = nullptr;
6428             if (IsUpdateExprFound) {
6429               BinOp = dyn_cast<BinaryOperator>(Second);
6430               IsUpdateExprFound = BinOp && BinOp->getOpcode() == BO_Assign;
6431             }
6432             if (IsUpdateExprFound && !CurContext->isDependentContext()) {
6433               //  { x++; v = x; }
6434               //  { x--; v = x; }
6435               //  { ++x; v = x; }
6436               //  { --x; v = x; }
6437               //  { x binop= expr; v = x; }
6438               //  { x = x binop expr; v = x; }
6439               //  { x = expr binop x; v = x; }
6440               // Check that the second expression has form v = x.
6441               Expr *PossibleX = BinOp->getRHS()->IgnoreParenImpCasts();
6442               llvm::FoldingSetNodeID XId, PossibleXId;
6443               Checker.getX()->Profile(XId, Context, /*Canonical=*/true);
6444               PossibleX->Profile(PossibleXId, Context, /*Canonical=*/true);
6445               IsUpdateExprFound = XId == PossibleXId;
6446               if (IsUpdateExprFound) {
6447                 V = BinOp->getLHS();
6448                 X = Checker.getX();
6449                 E = Checker.getExpr();
6450                 UE = Checker.getUpdateExpr();
6451                 IsXLHSInRHSPart = Checker.isXLHSInRHSPart();
6452                 IsPostfixUpdate = false;
6453               }
6454             }
6455           }
6456           if (!IsUpdateExprFound) {
6457             //  { v = x; x = expr; }
6458             auto *FirstExpr = dyn_cast<Expr>(First);
6459             auto *SecondExpr = dyn_cast<Expr>(Second);
6460             if (!FirstExpr || !SecondExpr ||
6461                 !(FirstExpr->isInstantiationDependent() ||
6462                   SecondExpr->isInstantiationDependent())) {
6463               auto *FirstBinOp = dyn_cast<BinaryOperator>(First);
6464               if (!FirstBinOp || FirstBinOp->getOpcode() != BO_Assign) {
6465                 ErrorFound = NotAnAssignmentOp;
6466                 NoteLoc = ErrorLoc = FirstBinOp ? FirstBinOp->getOperatorLoc()
6467                                                 : First->getLocStart();
6468                 NoteRange = ErrorRange = FirstBinOp
6469                                              ? FirstBinOp->getSourceRange()
6470                                              : SourceRange(ErrorLoc, ErrorLoc);
6471               } else {
6472                 auto *SecondBinOp = dyn_cast<BinaryOperator>(Second);
6473                 if (!SecondBinOp || SecondBinOp->getOpcode() != BO_Assign) {
6474                   ErrorFound = NotAnAssignmentOp;
6475                   NoteLoc = ErrorLoc = SecondBinOp
6476                                            ? SecondBinOp->getOperatorLoc()
6477                                            : Second->getLocStart();
6478                   NoteRange = ErrorRange =
6479                       SecondBinOp ? SecondBinOp->getSourceRange()
6480                                   : SourceRange(ErrorLoc, ErrorLoc);
6481                 } else {
6482                   Expr *PossibleXRHSInFirst =
6483                       FirstBinOp->getRHS()->IgnoreParenImpCasts();
6484                   Expr *PossibleXLHSInSecond =
6485                       SecondBinOp->getLHS()->IgnoreParenImpCasts();
6486                   llvm::FoldingSetNodeID X1Id, X2Id;
6487                   PossibleXRHSInFirst->Profile(X1Id, Context,
6488                                                /*Canonical=*/true);
6489                   PossibleXLHSInSecond->Profile(X2Id, Context,
6490                                                 /*Canonical=*/true);
6491                   IsUpdateExprFound = X1Id == X2Id;
6492                   if (IsUpdateExprFound) {
6493                     V = FirstBinOp->getLHS();
6494                     X = SecondBinOp->getLHS();
6495                     E = SecondBinOp->getRHS();
6496                     UE = nullptr;
6497                     IsXLHSInRHSPart = false;
6498                     IsPostfixUpdate = true;
6499                   } else {
6500                     ErrorFound = NotASpecificExpression;
6501                     ErrorLoc = FirstBinOp->getExprLoc();
6502                     ErrorRange = FirstBinOp->getSourceRange();
6503                     NoteLoc = SecondBinOp->getLHS()->getExprLoc();
6504                     NoteRange = SecondBinOp->getRHS()->getSourceRange();
6505                   }
6506                 }
6507               }
6508             }
6509           }
6510         } else {
6511           NoteLoc = ErrorLoc = Body->getLocStart();
6512           NoteRange = ErrorRange =
6513               SourceRange(Body->getLocStart(), Body->getLocStart());
6514           ErrorFound = NotTwoSubstatements;
6515         }
6516       } else {
6517         NoteLoc = ErrorLoc = Body->getLocStart();
6518         NoteRange = ErrorRange =
6519             SourceRange(Body->getLocStart(), Body->getLocStart());
6520         ErrorFound = NotACompoundStatement;
6521       }
6522       if (ErrorFound != NoError) {
6523         Diag(ErrorLoc, diag::err_omp_atomic_capture_not_compound_statement)
6524             << ErrorRange;
6525         Diag(NoteLoc, diag::note_omp_atomic_capture) << ErrorFound << NoteRange;
6526         return StmtError();
6527       }
6528       if (CurContext->isDependentContext())
6529         UE = V = E = X = nullptr;
6530     }
6531   }
6532 
6533   setFunctionHasBranchProtectedScope();
6534 
6535   return OMPAtomicDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt,
6536                                     X, V, E, UE, IsXLHSInRHSPart,
6537                                     IsPostfixUpdate);
6538 }
6539 
6540 StmtResult Sema::ActOnOpenMPTargetDirective(ArrayRef<OMPClause *> Clauses,
6541                                             Stmt *AStmt,
6542                                             SourceLocation StartLoc,
6543                                             SourceLocation EndLoc) {
6544   if (!AStmt)
6545     return StmtError();
6546 
6547   auto *CS = cast<CapturedStmt>(AStmt);
6548   // 1.2.2 OpenMP Language Terminology
6549   // Structured block - An executable statement with a single entry at the
6550   // top and a single exit at the bottom.
6551   // The point of exit cannot be a branch out of the structured block.
6552   // longjmp() and throw() must not violate the entry/exit criteria.
6553   CS->getCapturedDecl()->setNothrow();
6554   for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target);
6555        ThisCaptureLevel > 1; --ThisCaptureLevel) {
6556     CS = cast<CapturedStmt>(CS->getCapturedStmt());
6557     // 1.2.2 OpenMP Language Terminology
6558     // Structured block - An executable statement with a single entry at the
6559     // top and a single exit at the bottom.
6560     // The point of exit cannot be a branch out of the structured block.
6561     // longjmp() and throw() must not violate the entry/exit criteria.
6562     CS->getCapturedDecl()->setNothrow();
6563   }
6564 
6565   // OpenMP [2.16, Nesting of Regions]
6566   // If specified, a teams construct must be contained within a target
6567   // construct. That target construct must contain no statements or directives
6568   // outside of the teams construct.
6569   if (DSAStack->hasInnerTeamsRegion()) {
6570     const Stmt *S = CS->IgnoreContainers(/*IgnoreCaptured=*/true);
6571     bool OMPTeamsFound = true;
6572     if (const auto *CS = dyn_cast<CompoundStmt>(S)) {
6573       auto I = CS->body_begin();
6574       while (I != CS->body_end()) {
6575         const auto *OED = dyn_cast<OMPExecutableDirective>(*I);
6576         if (!OED || !isOpenMPTeamsDirective(OED->getDirectiveKind())) {
6577           OMPTeamsFound = false;
6578           break;
6579         }
6580         ++I;
6581       }
6582       assert(I != CS->body_end() && "Not found statement");
6583       S = *I;
6584     } else {
6585       const auto *OED = dyn_cast<OMPExecutableDirective>(S);
6586       OMPTeamsFound = OED && isOpenMPTeamsDirective(OED->getDirectiveKind());
6587     }
6588     if (!OMPTeamsFound) {
6589       Diag(StartLoc, diag::err_omp_target_contains_not_only_teams);
6590       Diag(DSAStack->getInnerTeamsRegionLoc(),
6591            diag::note_omp_nested_teams_construct_here);
6592       Diag(S->getLocStart(), diag::note_omp_nested_statement_here)
6593           << isa<OMPExecutableDirective>(S);
6594       return StmtError();
6595     }
6596   }
6597 
6598   setFunctionHasBranchProtectedScope();
6599 
6600   return OMPTargetDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt);
6601 }
6602 
6603 StmtResult
6604 Sema::ActOnOpenMPTargetParallelDirective(ArrayRef<OMPClause *> Clauses,
6605                                          Stmt *AStmt, SourceLocation StartLoc,
6606                                          SourceLocation EndLoc) {
6607   if (!AStmt)
6608     return StmtError();
6609 
6610   auto *CS = cast<CapturedStmt>(AStmt);
6611   // 1.2.2 OpenMP Language Terminology
6612   // Structured block - An executable statement with a single entry at the
6613   // top and a single exit at the bottom.
6614   // The point of exit cannot be a branch out of the structured block.
6615   // longjmp() and throw() must not violate the entry/exit criteria.
6616   CS->getCapturedDecl()->setNothrow();
6617   for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_parallel);
6618        ThisCaptureLevel > 1; --ThisCaptureLevel) {
6619     CS = cast<CapturedStmt>(CS->getCapturedStmt());
6620     // 1.2.2 OpenMP Language Terminology
6621     // Structured block - An executable statement with a single entry at the
6622     // top and a single exit at the bottom.
6623     // The point of exit cannot be a branch out of the structured block.
6624     // longjmp() and throw() must not violate the entry/exit criteria.
6625     CS->getCapturedDecl()->setNothrow();
6626   }
6627 
6628   setFunctionHasBranchProtectedScope();
6629 
6630   return OMPTargetParallelDirective::Create(Context, StartLoc, EndLoc, Clauses,
6631                                             AStmt);
6632 }
6633 
6634 StmtResult Sema::ActOnOpenMPTargetParallelForDirective(
6635     ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
6636     SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
6637   if (!AStmt)
6638     return StmtError();
6639 
6640   auto *CS = cast<CapturedStmt>(AStmt);
6641   // 1.2.2 OpenMP Language Terminology
6642   // Structured block - An executable statement with a single entry at the
6643   // top and a single exit at the bottom.
6644   // The point of exit cannot be a branch out of the structured block.
6645   // longjmp() and throw() must not violate the entry/exit criteria.
6646   CS->getCapturedDecl()->setNothrow();
6647   for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_parallel_for);
6648        ThisCaptureLevel > 1; --ThisCaptureLevel) {
6649     CS = cast<CapturedStmt>(CS->getCapturedStmt());
6650     // 1.2.2 OpenMP Language Terminology
6651     // Structured block - An executable statement with a single entry at the
6652     // top and a single exit at the bottom.
6653     // The point of exit cannot be a branch out of the structured block.
6654     // longjmp() and throw() must not violate the entry/exit criteria.
6655     CS->getCapturedDecl()->setNothrow();
6656   }
6657 
6658   OMPLoopDirective::HelperExprs B;
6659   // In presence of clause 'collapse' or 'ordered' with number of loops, it will
6660   // define the nested loops number.
6661   unsigned NestedLoopCount =
6662       checkOpenMPLoop(OMPD_target_parallel_for, getCollapseNumberExpr(Clauses),
6663                       getOrderedNumberExpr(Clauses), CS, *this, *DSAStack,
6664                       VarsWithImplicitDSA, B);
6665   if (NestedLoopCount == 0)
6666     return StmtError();
6667 
6668   assert((CurContext->isDependentContext() || B.builtAll()) &&
6669          "omp target parallel for loop exprs were not built");
6670 
6671   if (!CurContext->isDependentContext()) {
6672     // Finalize the clauses that need pre-built expressions for CodeGen.
6673     for (OMPClause *C : Clauses) {
6674       if (auto *LC = dyn_cast<OMPLinearClause>(C))
6675         if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
6676                                      B.NumIterations, *this, CurScope,
6677                                      DSAStack))
6678           return StmtError();
6679     }
6680   }
6681 
6682   setFunctionHasBranchProtectedScope();
6683   return OMPTargetParallelForDirective::Create(Context, StartLoc, EndLoc,
6684                                                NestedLoopCount, Clauses, AStmt,
6685                                                B, DSAStack->isCancelRegion());
6686 }
6687 
6688 /// Check for existence of a map clause in the list of clauses.
6689 static bool hasClauses(ArrayRef<OMPClause *> Clauses,
6690                        const OpenMPClauseKind K) {
6691   return llvm::any_of(
6692       Clauses, [K](const OMPClause *C) { return C->getClauseKind() == K; });
6693 }
6694 
6695 template <typename... Params>
6696 static bool hasClauses(ArrayRef<OMPClause *> Clauses, const OpenMPClauseKind K,
6697                        const Params... ClauseTypes) {
6698   return hasClauses(Clauses, K) || hasClauses(Clauses, ClauseTypes...);
6699 }
6700 
6701 StmtResult Sema::ActOnOpenMPTargetDataDirective(ArrayRef<OMPClause *> Clauses,
6702                                                 Stmt *AStmt,
6703                                                 SourceLocation StartLoc,
6704                                                 SourceLocation EndLoc) {
6705   if (!AStmt)
6706     return StmtError();
6707 
6708   assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
6709 
6710   // OpenMP [2.10.1, Restrictions, p. 97]
6711   // At least one map clause must appear on the directive.
6712   if (!hasClauses(Clauses, OMPC_map, OMPC_use_device_ptr)) {
6713     Diag(StartLoc, diag::err_omp_no_clause_for_directive)
6714         << "'map' or 'use_device_ptr'"
6715         << getOpenMPDirectiveName(OMPD_target_data);
6716     return StmtError();
6717   }
6718 
6719   setFunctionHasBranchProtectedScope();
6720 
6721   return OMPTargetDataDirective::Create(Context, StartLoc, EndLoc, Clauses,
6722                                         AStmt);
6723 }
6724 
6725 StmtResult
6726 Sema::ActOnOpenMPTargetEnterDataDirective(ArrayRef<OMPClause *> Clauses,
6727                                           SourceLocation StartLoc,
6728                                           SourceLocation EndLoc, Stmt *AStmt) {
6729   if (!AStmt)
6730     return StmtError();
6731 
6732   auto *CS = cast<CapturedStmt>(AStmt);
6733   // 1.2.2 OpenMP Language Terminology
6734   // Structured block - An executable statement with a single entry at the
6735   // top and a single exit at the bottom.
6736   // The point of exit cannot be a branch out of the structured block.
6737   // longjmp() and throw() must not violate the entry/exit criteria.
6738   CS->getCapturedDecl()->setNothrow();
6739   for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_enter_data);
6740        ThisCaptureLevel > 1; --ThisCaptureLevel) {
6741     CS = cast<CapturedStmt>(CS->getCapturedStmt());
6742     // 1.2.2 OpenMP Language Terminology
6743     // Structured block - An executable statement with a single entry at the
6744     // top and a single exit at the bottom.
6745     // The point of exit cannot be a branch out of the structured block.
6746     // longjmp() and throw() must not violate the entry/exit criteria.
6747     CS->getCapturedDecl()->setNothrow();
6748   }
6749 
6750   // OpenMP [2.10.2, Restrictions, p. 99]
6751   // At least one map clause must appear on the directive.
6752   if (!hasClauses(Clauses, OMPC_map)) {
6753     Diag(StartLoc, diag::err_omp_no_clause_for_directive)
6754         << "'map'" << getOpenMPDirectiveName(OMPD_target_enter_data);
6755     return StmtError();
6756   }
6757 
6758   return OMPTargetEnterDataDirective::Create(Context, StartLoc, EndLoc, Clauses,
6759                                              AStmt);
6760 }
6761 
6762 StmtResult
6763 Sema::ActOnOpenMPTargetExitDataDirective(ArrayRef<OMPClause *> Clauses,
6764                                          SourceLocation StartLoc,
6765                                          SourceLocation EndLoc, Stmt *AStmt) {
6766   if (!AStmt)
6767     return StmtError();
6768 
6769   auto *CS = cast<CapturedStmt>(AStmt);
6770   // 1.2.2 OpenMP Language Terminology
6771   // Structured block - An executable statement with a single entry at the
6772   // top and a single exit at the bottom.
6773   // The point of exit cannot be a branch out of the structured block.
6774   // longjmp() and throw() must not violate the entry/exit criteria.
6775   CS->getCapturedDecl()->setNothrow();
6776   for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_exit_data);
6777        ThisCaptureLevel > 1; --ThisCaptureLevel) {
6778     CS = cast<CapturedStmt>(CS->getCapturedStmt());
6779     // 1.2.2 OpenMP Language Terminology
6780     // Structured block - An executable statement with a single entry at the
6781     // top and a single exit at the bottom.
6782     // The point of exit cannot be a branch out of the structured block.
6783     // longjmp() and throw() must not violate the entry/exit criteria.
6784     CS->getCapturedDecl()->setNothrow();
6785   }
6786 
6787   // OpenMP [2.10.3, Restrictions, p. 102]
6788   // At least one map clause must appear on the directive.
6789   if (!hasClauses(Clauses, OMPC_map)) {
6790     Diag(StartLoc, diag::err_omp_no_clause_for_directive)
6791         << "'map'" << getOpenMPDirectiveName(OMPD_target_exit_data);
6792     return StmtError();
6793   }
6794 
6795   return OMPTargetExitDataDirective::Create(Context, StartLoc, EndLoc, Clauses,
6796                                             AStmt);
6797 }
6798 
6799 StmtResult Sema::ActOnOpenMPTargetUpdateDirective(ArrayRef<OMPClause *> Clauses,
6800                                                   SourceLocation StartLoc,
6801                                                   SourceLocation EndLoc,
6802                                                   Stmt *AStmt) {
6803   if (!AStmt)
6804     return StmtError();
6805 
6806   auto *CS = cast<CapturedStmt>(AStmt);
6807   // 1.2.2 OpenMP Language Terminology
6808   // Structured block - An executable statement with a single entry at the
6809   // top and a single exit at the bottom.
6810   // The point of exit cannot be a branch out of the structured block.
6811   // longjmp() and throw() must not violate the entry/exit criteria.
6812   CS->getCapturedDecl()->setNothrow();
6813   for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_update);
6814        ThisCaptureLevel > 1; --ThisCaptureLevel) {
6815     CS = cast<CapturedStmt>(CS->getCapturedStmt());
6816     // 1.2.2 OpenMP Language Terminology
6817     // Structured block - An executable statement with a single entry at the
6818     // top and a single exit at the bottom.
6819     // The point of exit cannot be a branch out of the structured block.
6820     // longjmp() and throw() must not violate the entry/exit criteria.
6821     CS->getCapturedDecl()->setNothrow();
6822   }
6823 
6824   if (!hasClauses(Clauses, OMPC_to, OMPC_from)) {
6825     Diag(StartLoc, diag::err_omp_at_least_one_motion_clause_required);
6826     return StmtError();
6827   }
6828   return OMPTargetUpdateDirective::Create(Context, StartLoc, EndLoc, Clauses,
6829                                           AStmt);
6830 }
6831 
6832 StmtResult Sema::ActOnOpenMPTeamsDirective(ArrayRef<OMPClause *> Clauses,
6833                                            Stmt *AStmt, SourceLocation StartLoc,
6834                                            SourceLocation EndLoc) {
6835   if (!AStmt)
6836     return StmtError();
6837 
6838   auto *CS = cast<CapturedStmt>(AStmt);
6839   // 1.2.2 OpenMP Language Terminology
6840   // Structured block - An executable statement with a single entry at the
6841   // top and a single exit at the bottom.
6842   // The point of exit cannot be a branch out of the structured block.
6843   // longjmp() and throw() must not violate the entry/exit criteria.
6844   CS->getCapturedDecl()->setNothrow();
6845 
6846   setFunctionHasBranchProtectedScope();
6847 
6848   DSAStack->setParentTeamsRegionLoc(StartLoc);
6849 
6850   return OMPTeamsDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt);
6851 }
6852 
6853 StmtResult
6854 Sema::ActOnOpenMPCancellationPointDirective(SourceLocation StartLoc,
6855                                             SourceLocation EndLoc,
6856                                             OpenMPDirectiveKind CancelRegion) {
6857   if (DSAStack->isParentNowaitRegion()) {
6858     Diag(StartLoc, diag::err_omp_parent_cancel_region_nowait) << 0;
6859     return StmtError();
6860   }
6861   if (DSAStack->isParentOrderedRegion()) {
6862     Diag(StartLoc, diag::err_omp_parent_cancel_region_ordered) << 0;
6863     return StmtError();
6864   }
6865   return OMPCancellationPointDirective::Create(Context, StartLoc, EndLoc,
6866                                                CancelRegion);
6867 }
6868 
6869 StmtResult Sema::ActOnOpenMPCancelDirective(ArrayRef<OMPClause *> Clauses,
6870                                             SourceLocation StartLoc,
6871                                             SourceLocation EndLoc,
6872                                             OpenMPDirectiveKind CancelRegion) {
6873   if (DSAStack->isParentNowaitRegion()) {
6874     Diag(StartLoc, diag::err_omp_parent_cancel_region_nowait) << 1;
6875     return StmtError();
6876   }
6877   if (DSAStack->isParentOrderedRegion()) {
6878     Diag(StartLoc, diag::err_omp_parent_cancel_region_ordered) << 1;
6879     return StmtError();
6880   }
6881   DSAStack->setParentCancelRegion(/*Cancel=*/true);
6882   return OMPCancelDirective::Create(Context, StartLoc, EndLoc, Clauses,
6883                                     CancelRegion);
6884 }
6885 
6886 static bool checkGrainsizeNumTasksClauses(Sema &S,
6887                                           ArrayRef<OMPClause *> Clauses) {
6888   const OMPClause *PrevClause = nullptr;
6889   bool ErrorFound = false;
6890   for (const OMPClause *C : Clauses) {
6891     if (C->getClauseKind() == OMPC_grainsize ||
6892         C->getClauseKind() == OMPC_num_tasks) {
6893       if (!PrevClause)
6894         PrevClause = C;
6895       else if (PrevClause->getClauseKind() != C->getClauseKind()) {
6896         S.Diag(C->getLocStart(),
6897                diag::err_omp_grainsize_num_tasks_mutually_exclusive)
6898             << getOpenMPClauseName(C->getClauseKind())
6899             << getOpenMPClauseName(PrevClause->getClauseKind());
6900         S.Diag(PrevClause->getLocStart(),
6901                diag::note_omp_previous_grainsize_num_tasks)
6902             << getOpenMPClauseName(PrevClause->getClauseKind());
6903         ErrorFound = true;
6904       }
6905     }
6906   }
6907   return ErrorFound;
6908 }
6909 
6910 static bool checkReductionClauseWithNogroup(Sema &S,
6911                                             ArrayRef<OMPClause *> Clauses) {
6912   const OMPClause *ReductionClause = nullptr;
6913   const OMPClause *NogroupClause = nullptr;
6914   for (const OMPClause *C : Clauses) {
6915     if (C->getClauseKind() == OMPC_reduction) {
6916       ReductionClause = C;
6917       if (NogroupClause)
6918         break;
6919       continue;
6920     }
6921     if (C->getClauseKind() == OMPC_nogroup) {
6922       NogroupClause = C;
6923       if (ReductionClause)
6924         break;
6925       continue;
6926     }
6927   }
6928   if (ReductionClause && NogroupClause) {
6929     S.Diag(ReductionClause->getLocStart(), diag::err_omp_reduction_with_nogroup)
6930         << SourceRange(NogroupClause->getLocStart(),
6931                        NogroupClause->getLocEnd());
6932     return true;
6933   }
6934   return false;
6935 }
6936 
6937 StmtResult Sema::ActOnOpenMPTaskLoopDirective(
6938     ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
6939     SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
6940   if (!AStmt)
6941     return StmtError();
6942 
6943   assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
6944   OMPLoopDirective::HelperExprs B;
6945   // In presence of clause 'collapse' or 'ordered' with number of loops, it will
6946   // define the nested loops number.
6947   unsigned NestedLoopCount =
6948       checkOpenMPLoop(OMPD_taskloop, getCollapseNumberExpr(Clauses),
6949                       /*OrderedLoopCountExpr=*/nullptr, AStmt, *this, *DSAStack,
6950                       VarsWithImplicitDSA, B);
6951   if (NestedLoopCount == 0)
6952     return StmtError();
6953 
6954   assert((CurContext->isDependentContext() || B.builtAll()) &&
6955          "omp for loop exprs were not built");
6956 
6957   // OpenMP, [2.9.2 taskloop Construct, Restrictions]
6958   // The grainsize clause and num_tasks clause are mutually exclusive and may
6959   // not appear on the same taskloop directive.
6960   if (checkGrainsizeNumTasksClauses(*this, Clauses))
6961     return StmtError();
6962   // OpenMP, [2.9.2 taskloop Construct, Restrictions]
6963   // If a reduction clause is present on the taskloop directive, the nogroup
6964   // clause must not be specified.
6965   if (checkReductionClauseWithNogroup(*this, Clauses))
6966     return StmtError();
6967 
6968   setFunctionHasBranchProtectedScope();
6969   return OMPTaskLoopDirective::Create(Context, StartLoc, EndLoc,
6970                                       NestedLoopCount, Clauses, AStmt, B);
6971 }
6972 
6973 StmtResult Sema::ActOnOpenMPTaskLoopSimdDirective(
6974     ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
6975     SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
6976   if (!AStmt)
6977     return StmtError();
6978 
6979   assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
6980   OMPLoopDirective::HelperExprs B;
6981   // In presence of clause 'collapse' or 'ordered' with number of loops, it will
6982   // define the nested loops number.
6983   unsigned NestedLoopCount =
6984       checkOpenMPLoop(OMPD_taskloop_simd, getCollapseNumberExpr(Clauses),
6985                       /*OrderedLoopCountExpr=*/nullptr, AStmt, *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 (OMPClause *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   // OpenMP, [2.9.2 taskloop Construct, Restrictions]
7005   // The grainsize clause and num_tasks clause are mutually exclusive and may
7006   // not appear on the same taskloop directive.
7007   if (checkGrainsizeNumTasksClauses(*this, Clauses))
7008     return StmtError();
7009   // OpenMP, [2.9.2 taskloop Construct, Restrictions]
7010   // If a reduction clause is present on the taskloop directive, the nogroup
7011   // clause must not be specified.
7012   if (checkReductionClauseWithNogroup(*this, Clauses))
7013     return StmtError();
7014   if (checkSimdlenSafelenSpecified(*this, Clauses))
7015     return StmtError();
7016 
7017   setFunctionHasBranchProtectedScope();
7018   return OMPTaskLoopSimdDirective::Create(Context, StartLoc, EndLoc,
7019                                           NestedLoopCount, Clauses, AStmt, B);
7020 }
7021 
7022 StmtResult Sema::ActOnOpenMPDistributeDirective(
7023     ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
7024     SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
7025   if (!AStmt)
7026     return StmtError();
7027 
7028   assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
7029   OMPLoopDirective::HelperExprs B;
7030   // In presence of clause 'collapse' with number of loops, it will
7031   // define the nested loops number.
7032   unsigned NestedLoopCount =
7033       checkOpenMPLoop(OMPD_distribute, getCollapseNumberExpr(Clauses),
7034                       nullptr /*ordered not a clause on distribute*/, AStmt,
7035                       *this, *DSAStack, VarsWithImplicitDSA, B);
7036   if (NestedLoopCount == 0)
7037     return StmtError();
7038 
7039   assert((CurContext->isDependentContext() || B.builtAll()) &&
7040          "omp for loop exprs were not built");
7041 
7042   setFunctionHasBranchProtectedScope();
7043   return OMPDistributeDirective::Create(Context, StartLoc, EndLoc,
7044                                         NestedLoopCount, Clauses, AStmt, B);
7045 }
7046 
7047 StmtResult Sema::ActOnOpenMPDistributeParallelForDirective(
7048     ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
7049     SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
7050   if (!AStmt)
7051     return StmtError();
7052 
7053   auto *CS = cast<CapturedStmt>(AStmt);
7054   // 1.2.2 OpenMP Language Terminology
7055   // Structured block - An executable statement with a single entry at the
7056   // top and a single exit at the bottom.
7057   // The point of exit cannot be a branch out of the structured block.
7058   // longjmp() and throw() must not violate the entry/exit criteria.
7059   CS->getCapturedDecl()->setNothrow();
7060   for (int ThisCaptureLevel =
7061            getOpenMPCaptureLevels(OMPD_distribute_parallel_for);
7062        ThisCaptureLevel > 1; --ThisCaptureLevel) {
7063     CS = cast<CapturedStmt>(CS->getCapturedStmt());
7064     // 1.2.2 OpenMP Language Terminology
7065     // Structured block - An executable statement with a single entry at the
7066     // top and a single exit at the bottom.
7067     // The point of exit cannot be a branch out of the structured block.
7068     // longjmp() and throw() must not violate the entry/exit criteria.
7069     CS->getCapturedDecl()->setNothrow();
7070   }
7071 
7072   OMPLoopDirective::HelperExprs B;
7073   // In presence of clause 'collapse' with number of loops, it will
7074   // define the nested loops number.
7075   unsigned NestedLoopCount = checkOpenMPLoop(
7076       OMPD_distribute_parallel_for, getCollapseNumberExpr(Clauses),
7077       nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStack,
7078       VarsWithImplicitDSA, B);
7079   if (NestedLoopCount == 0)
7080     return StmtError();
7081 
7082   assert((CurContext->isDependentContext() || B.builtAll()) &&
7083          "omp for loop exprs were not built");
7084 
7085   setFunctionHasBranchProtectedScope();
7086   return OMPDistributeParallelForDirective::Create(
7087       Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B,
7088       DSAStack->isCancelRegion());
7089 }
7090 
7091 StmtResult Sema::ActOnOpenMPDistributeParallelForSimdDirective(
7092     ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
7093     SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
7094   if (!AStmt)
7095     return StmtError();
7096 
7097   auto *CS = cast<CapturedStmt>(AStmt);
7098   // 1.2.2 OpenMP Language Terminology
7099   // Structured block - An executable statement with a single entry at the
7100   // top and a single exit at the bottom.
7101   // The point of exit cannot be a branch out of the structured block.
7102   // longjmp() and throw() must not violate the entry/exit criteria.
7103   CS->getCapturedDecl()->setNothrow();
7104   for (int ThisCaptureLevel =
7105            getOpenMPCaptureLevels(OMPD_distribute_parallel_for_simd);
7106        ThisCaptureLevel > 1; --ThisCaptureLevel) {
7107     CS = cast<CapturedStmt>(CS->getCapturedStmt());
7108     // 1.2.2 OpenMP Language Terminology
7109     // Structured block - An executable statement with a single entry at the
7110     // top and a single exit at the bottom.
7111     // The point of exit cannot be a branch out of the structured block.
7112     // longjmp() and throw() must not violate the entry/exit criteria.
7113     CS->getCapturedDecl()->setNothrow();
7114   }
7115 
7116   OMPLoopDirective::HelperExprs B;
7117   // In presence of clause 'collapse' with number of loops, it will
7118   // define the nested loops number.
7119   unsigned NestedLoopCount = checkOpenMPLoop(
7120       OMPD_distribute_parallel_for_simd, getCollapseNumberExpr(Clauses),
7121       nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStack,
7122       VarsWithImplicitDSA, B);
7123   if (NestedLoopCount == 0)
7124     return StmtError();
7125 
7126   assert((CurContext->isDependentContext() || B.builtAll()) &&
7127          "omp for loop exprs were not built");
7128 
7129   if (!CurContext->isDependentContext()) {
7130     // Finalize the clauses that need pre-built expressions for CodeGen.
7131     for (OMPClause *C : Clauses) {
7132       if (auto *LC = dyn_cast<OMPLinearClause>(C))
7133         if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
7134                                      B.NumIterations, *this, CurScope,
7135                                      DSAStack))
7136           return StmtError();
7137     }
7138   }
7139 
7140   if (checkSimdlenSafelenSpecified(*this, Clauses))
7141     return StmtError();
7142 
7143   setFunctionHasBranchProtectedScope();
7144   return OMPDistributeParallelForSimdDirective::Create(
7145       Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
7146 }
7147 
7148 StmtResult Sema::ActOnOpenMPDistributeSimdDirective(
7149     ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
7150     SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
7151   if (!AStmt)
7152     return StmtError();
7153 
7154   auto *CS = cast<CapturedStmt>(AStmt);
7155   // 1.2.2 OpenMP Language Terminology
7156   // Structured block - An executable statement with a single entry at the
7157   // top and a single exit at the bottom.
7158   // The point of exit cannot be a branch out of the structured block.
7159   // longjmp() and throw() must not violate the entry/exit criteria.
7160   CS->getCapturedDecl()->setNothrow();
7161   for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_distribute_simd);
7162        ThisCaptureLevel > 1; --ThisCaptureLevel) {
7163     CS = cast<CapturedStmt>(CS->getCapturedStmt());
7164     // 1.2.2 OpenMP Language Terminology
7165     // Structured block - An executable statement with a single entry at the
7166     // top and a single exit at the bottom.
7167     // The point of exit cannot be a branch out of the structured block.
7168     // longjmp() and throw() must not violate the entry/exit criteria.
7169     CS->getCapturedDecl()->setNothrow();
7170   }
7171 
7172   OMPLoopDirective::HelperExprs B;
7173   // In presence of clause 'collapse' with number of loops, it will
7174   // define the nested loops number.
7175   unsigned NestedLoopCount =
7176       checkOpenMPLoop(OMPD_distribute_simd, getCollapseNumberExpr(Clauses),
7177                       nullptr /*ordered not a clause on distribute*/, CS, *this,
7178                       *DSAStack, VarsWithImplicitDSA, B);
7179   if (NestedLoopCount == 0)
7180     return StmtError();
7181 
7182   assert((CurContext->isDependentContext() || B.builtAll()) &&
7183          "omp for loop exprs were not built");
7184 
7185   if (!CurContext->isDependentContext()) {
7186     // Finalize the clauses that need pre-built expressions for CodeGen.
7187     for (OMPClause *C : Clauses) {
7188       if (auto *LC = dyn_cast<OMPLinearClause>(C))
7189         if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
7190                                      B.NumIterations, *this, CurScope,
7191                                      DSAStack))
7192           return StmtError();
7193     }
7194   }
7195 
7196   if (checkSimdlenSafelenSpecified(*this, Clauses))
7197     return StmtError();
7198 
7199   setFunctionHasBranchProtectedScope();
7200   return OMPDistributeSimdDirective::Create(Context, StartLoc, EndLoc,
7201                                             NestedLoopCount, Clauses, AStmt, B);
7202 }
7203 
7204 StmtResult Sema::ActOnOpenMPTargetParallelForSimdDirective(
7205     ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
7206     SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
7207   if (!AStmt)
7208     return StmtError();
7209 
7210   auto *CS = cast<CapturedStmt>(AStmt);
7211   // 1.2.2 OpenMP Language Terminology
7212   // Structured block - An executable statement with a single entry at the
7213   // top and a single exit at the bottom.
7214   // The point of exit cannot be a branch out of the structured block.
7215   // longjmp() and throw() must not violate the entry/exit criteria.
7216   CS->getCapturedDecl()->setNothrow();
7217   for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_parallel_for);
7218        ThisCaptureLevel > 1; --ThisCaptureLevel) {
7219     CS = cast<CapturedStmt>(CS->getCapturedStmt());
7220     // 1.2.2 OpenMP Language Terminology
7221     // Structured block - An executable statement with a single entry at the
7222     // top and a single exit at the bottom.
7223     // The point of exit cannot be a branch out of the structured block.
7224     // longjmp() and throw() must not violate the entry/exit criteria.
7225     CS->getCapturedDecl()->setNothrow();
7226   }
7227 
7228   OMPLoopDirective::HelperExprs B;
7229   // In presence of clause 'collapse' or 'ordered' with number of loops, it will
7230   // define the nested loops number.
7231   unsigned NestedLoopCount = checkOpenMPLoop(
7232       OMPD_target_parallel_for_simd, getCollapseNumberExpr(Clauses),
7233       getOrderedNumberExpr(Clauses), CS, *this, *DSAStack,
7234       VarsWithImplicitDSA, B);
7235   if (NestedLoopCount == 0)
7236     return StmtError();
7237 
7238   assert((CurContext->isDependentContext() || B.builtAll()) &&
7239          "omp target parallel for simd loop exprs were not built");
7240 
7241   if (!CurContext->isDependentContext()) {
7242     // Finalize the clauses that need pre-built expressions for CodeGen.
7243     for (OMPClause *C : Clauses) {
7244       if (auto *LC = dyn_cast<OMPLinearClause>(C))
7245         if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
7246                                      B.NumIterations, *this, CurScope,
7247                                      DSAStack))
7248           return StmtError();
7249     }
7250   }
7251   if (checkSimdlenSafelenSpecified(*this, Clauses))
7252     return StmtError();
7253 
7254   setFunctionHasBranchProtectedScope();
7255   return OMPTargetParallelForSimdDirective::Create(
7256       Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
7257 }
7258 
7259 StmtResult Sema::ActOnOpenMPTargetSimdDirective(
7260     ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
7261     SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
7262   if (!AStmt)
7263     return StmtError();
7264 
7265   auto *CS = cast<CapturedStmt>(AStmt);
7266   // 1.2.2 OpenMP Language Terminology
7267   // Structured block - An executable statement with a single entry at the
7268   // top and a single exit at the bottom.
7269   // The point of exit cannot be a branch out of the structured block.
7270   // longjmp() and throw() must not violate the entry/exit criteria.
7271   CS->getCapturedDecl()->setNothrow();
7272   for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_simd);
7273        ThisCaptureLevel > 1; --ThisCaptureLevel) {
7274     CS = cast<CapturedStmt>(CS->getCapturedStmt());
7275     // 1.2.2 OpenMP Language Terminology
7276     // Structured block - An executable statement with a single entry at the
7277     // top and a single exit at the bottom.
7278     // The point of exit cannot be a branch out of the structured block.
7279     // longjmp() and throw() must not violate the entry/exit criteria.
7280     CS->getCapturedDecl()->setNothrow();
7281   }
7282 
7283   OMPLoopDirective::HelperExprs B;
7284   // In presence of clause 'collapse' with number of loops, it will define the
7285   // nested loops number.
7286   unsigned NestedLoopCount =
7287       checkOpenMPLoop(OMPD_target_simd, getCollapseNumberExpr(Clauses),
7288                       getOrderedNumberExpr(Clauses), CS, *this, *DSAStack,
7289                       VarsWithImplicitDSA, B);
7290   if (NestedLoopCount == 0)
7291     return StmtError();
7292 
7293   assert((CurContext->isDependentContext() || B.builtAll()) &&
7294          "omp target simd loop exprs were not built");
7295 
7296   if (!CurContext->isDependentContext()) {
7297     // Finalize the clauses that need pre-built expressions for CodeGen.
7298     for (OMPClause *C : Clauses) {
7299       if (auto *LC = dyn_cast<OMPLinearClause>(C))
7300         if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
7301                                      B.NumIterations, *this, CurScope,
7302                                      DSAStack))
7303           return StmtError();
7304     }
7305   }
7306 
7307   if (checkSimdlenSafelenSpecified(*this, Clauses))
7308     return StmtError();
7309 
7310   setFunctionHasBranchProtectedScope();
7311   return OMPTargetSimdDirective::Create(Context, StartLoc, EndLoc,
7312                                         NestedLoopCount, Clauses, AStmt, B);
7313 }
7314 
7315 StmtResult Sema::ActOnOpenMPTeamsDistributeDirective(
7316     ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
7317     SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
7318   if (!AStmt)
7319     return StmtError();
7320 
7321   auto *CS = cast<CapturedStmt>(AStmt);
7322   // 1.2.2 OpenMP Language Terminology
7323   // Structured block - An executable statement with a single entry at the
7324   // top and a single exit at the bottom.
7325   // The point of exit cannot be a branch out of the structured block.
7326   // longjmp() and throw() must not violate the entry/exit criteria.
7327   CS->getCapturedDecl()->setNothrow();
7328   for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_teams_distribute);
7329        ThisCaptureLevel > 1; --ThisCaptureLevel) {
7330     CS = cast<CapturedStmt>(CS->getCapturedStmt());
7331     // 1.2.2 OpenMP Language Terminology
7332     // Structured block - An executable statement with a single entry at the
7333     // top and a single exit at the bottom.
7334     // The point of exit cannot be a branch out of the structured block.
7335     // longjmp() and throw() must not violate the entry/exit criteria.
7336     CS->getCapturedDecl()->setNothrow();
7337   }
7338 
7339   OMPLoopDirective::HelperExprs B;
7340   // In presence of clause 'collapse' with number of loops, it will
7341   // define the nested loops number.
7342   unsigned NestedLoopCount =
7343       checkOpenMPLoop(OMPD_teams_distribute, getCollapseNumberExpr(Clauses),
7344                       nullptr /*ordered not a clause on distribute*/, CS, *this,
7345                       *DSAStack, VarsWithImplicitDSA, B);
7346   if (NestedLoopCount == 0)
7347     return StmtError();
7348 
7349   assert((CurContext->isDependentContext() || B.builtAll()) &&
7350          "omp teams distribute loop exprs were not built");
7351 
7352   setFunctionHasBranchProtectedScope();
7353 
7354   DSAStack->setParentTeamsRegionLoc(StartLoc);
7355 
7356   return OMPTeamsDistributeDirective::Create(
7357       Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
7358 }
7359 
7360 StmtResult Sema::ActOnOpenMPTeamsDistributeSimdDirective(
7361     ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
7362     SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
7363   if (!AStmt)
7364     return StmtError();
7365 
7366   auto *CS = cast<CapturedStmt>(AStmt);
7367   // 1.2.2 OpenMP Language Terminology
7368   // Structured block - An executable statement with a single entry at the
7369   // top and a single exit at the bottom.
7370   // The point of exit cannot be a branch out of the structured block.
7371   // longjmp() and throw() must not violate the entry/exit criteria.
7372   CS->getCapturedDecl()->setNothrow();
7373   for (int ThisCaptureLevel =
7374            getOpenMPCaptureLevels(OMPD_teams_distribute_simd);
7375        ThisCaptureLevel > 1; --ThisCaptureLevel) {
7376     CS = cast<CapturedStmt>(CS->getCapturedStmt());
7377     // 1.2.2 OpenMP Language Terminology
7378     // Structured block - An executable statement with a single entry at the
7379     // top and a single exit at the bottom.
7380     // The point of exit cannot be a branch out of the structured block.
7381     // longjmp() and throw() must not violate the entry/exit criteria.
7382     CS->getCapturedDecl()->setNothrow();
7383   }
7384 
7385 
7386   OMPLoopDirective::HelperExprs B;
7387   // In presence of clause 'collapse' with number of loops, it will
7388   // define the nested loops number.
7389   unsigned NestedLoopCount = checkOpenMPLoop(
7390       OMPD_teams_distribute_simd, getCollapseNumberExpr(Clauses),
7391       nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStack,
7392       VarsWithImplicitDSA, B);
7393 
7394   if (NestedLoopCount == 0)
7395     return StmtError();
7396 
7397   assert((CurContext->isDependentContext() || B.builtAll()) &&
7398          "omp teams distribute simd loop exprs were not built");
7399 
7400   if (!CurContext->isDependentContext()) {
7401     // Finalize the clauses that need pre-built expressions for CodeGen.
7402     for (OMPClause *C : Clauses) {
7403       if (auto *LC = dyn_cast<OMPLinearClause>(C))
7404         if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
7405                                      B.NumIterations, *this, CurScope,
7406                                      DSAStack))
7407           return StmtError();
7408     }
7409   }
7410 
7411   if (checkSimdlenSafelenSpecified(*this, Clauses))
7412     return StmtError();
7413 
7414   setFunctionHasBranchProtectedScope();
7415 
7416   DSAStack->setParentTeamsRegionLoc(StartLoc);
7417 
7418   return OMPTeamsDistributeSimdDirective::Create(
7419       Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
7420 }
7421 
7422 StmtResult Sema::ActOnOpenMPTeamsDistributeParallelForSimdDirective(
7423     ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
7424     SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
7425   if (!AStmt)
7426     return StmtError();
7427 
7428   auto *CS = cast<CapturedStmt>(AStmt);
7429   // 1.2.2 OpenMP Language Terminology
7430   // Structured block - An executable statement with a single entry at the
7431   // top and a single exit at the bottom.
7432   // The point of exit cannot be a branch out of the structured block.
7433   // longjmp() and throw() must not violate the entry/exit criteria.
7434   CS->getCapturedDecl()->setNothrow();
7435 
7436   for (int ThisCaptureLevel =
7437            getOpenMPCaptureLevels(OMPD_teams_distribute_parallel_for_simd);
7438        ThisCaptureLevel > 1; --ThisCaptureLevel) {
7439     CS = cast<CapturedStmt>(CS->getCapturedStmt());
7440     // 1.2.2 OpenMP Language Terminology
7441     // Structured block - An executable statement with a single entry at the
7442     // top and a single exit at the bottom.
7443     // The point of exit cannot be a branch out of the structured block.
7444     // longjmp() and throw() must not violate the entry/exit criteria.
7445     CS->getCapturedDecl()->setNothrow();
7446   }
7447 
7448   OMPLoopDirective::HelperExprs B;
7449   // In presence of clause 'collapse' with number of loops, it will
7450   // define the nested loops number.
7451   unsigned NestedLoopCount = checkOpenMPLoop(
7452       OMPD_teams_distribute_parallel_for_simd, getCollapseNumberExpr(Clauses),
7453       nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStack,
7454       VarsWithImplicitDSA, B);
7455 
7456   if (NestedLoopCount == 0)
7457     return StmtError();
7458 
7459   assert((CurContext->isDependentContext() || B.builtAll()) &&
7460          "omp for loop exprs were not built");
7461 
7462   if (!CurContext->isDependentContext()) {
7463     // Finalize the clauses that need pre-built expressions for CodeGen.
7464     for (OMPClause *C : Clauses) {
7465       if (auto *LC = dyn_cast<OMPLinearClause>(C))
7466         if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
7467                                      B.NumIterations, *this, CurScope,
7468                                      DSAStack))
7469           return StmtError();
7470     }
7471   }
7472 
7473   if (checkSimdlenSafelenSpecified(*this, Clauses))
7474     return StmtError();
7475 
7476   setFunctionHasBranchProtectedScope();
7477 
7478   DSAStack->setParentTeamsRegionLoc(StartLoc);
7479 
7480   return OMPTeamsDistributeParallelForSimdDirective::Create(
7481       Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
7482 }
7483 
7484 StmtResult Sema::ActOnOpenMPTeamsDistributeParallelForDirective(
7485     ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
7486     SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
7487   if (!AStmt)
7488     return StmtError();
7489 
7490   auto *CS = cast<CapturedStmt>(AStmt);
7491   // 1.2.2 OpenMP Language Terminology
7492   // Structured block - An executable statement with a single entry at the
7493   // top and a single exit at the bottom.
7494   // The point of exit cannot be a branch out of the structured block.
7495   // longjmp() and throw() must not violate the entry/exit criteria.
7496   CS->getCapturedDecl()->setNothrow();
7497 
7498   for (int ThisCaptureLevel =
7499            getOpenMPCaptureLevels(OMPD_teams_distribute_parallel_for);
7500        ThisCaptureLevel > 1; --ThisCaptureLevel) {
7501     CS = cast<CapturedStmt>(CS->getCapturedStmt());
7502     // 1.2.2 OpenMP Language Terminology
7503     // Structured block - An executable statement with a single entry at the
7504     // top and a single exit at the bottom.
7505     // The point of exit cannot be a branch out of the structured block.
7506     // longjmp() and throw() must not violate the entry/exit criteria.
7507     CS->getCapturedDecl()->setNothrow();
7508   }
7509 
7510   OMPLoopDirective::HelperExprs B;
7511   // In presence of clause 'collapse' with number of loops, it will
7512   // define the nested loops number.
7513   unsigned NestedLoopCount = checkOpenMPLoop(
7514       OMPD_teams_distribute_parallel_for, getCollapseNumberExpr(Clauses),
7515       nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStack,
7516       VarsWithImplicitDSA, B);
7517 
7518   if (NestedLoopCount == 0)
7519     return StmtError();
7520 
7521   assert((CurContext->isDependentContext() || B.builtAll()) &&
7522          "omp for loop exprs were not built");
7523 
7524   setFunctionHasBranchProtectedScope();
7525 
7526   DSAStack->setParentTeamsRegionLoc(StartLoc);
7527 
7528   return OMPTeamsDistributeParallelForDirective::Create(
7529       Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B,
7530       DSAStack->isCancelRegion());
7531 }
7532 
7533 StmtResult Sema::ActOnOpenMPTargetTeamsDirective(ArrayRef<OMPClause *> Clauses,
7534                                                  Stmt *AStmt,
7535                                                  SourceLocation StartLoc,
7536                                                  SourceLocation EndLoc) {
7537   if (!AStmt)
7538     return StmtError();
7539 
7540   auto *CS = cast<CapturedStmt>(AStmt);
7541   // 1.2.2 OpenMP Language Terminology
7542   // Structured block - An executable statement with a single entry at the
7543   // top and a single exit at the bottom.
7544   // The point of exit cannot be a branch out of the structured block.
7545   // longjmp() and throw() must not violate the entry/exit criteria.
7546   CS->getCapturedDecl()->setNothrow();
7547 
7548   for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_teams);
7549        ThisCaptureLevel > 1; --ThisCaptureLevel) {
7550     CS = cast<CapturedStmt>(CS->getCapturedStmt());
7551     // 1.2.2 OpenMP Language Terminology
7552     // Structured block - An executable statement with a single entry at the
7553     // top and a single exit at the bottom.
7554     // The point of exit cannot be a branch out of the structured block.
7555     // longjmp() and throw() must not violate the entry/exit criteria.
7556     CS->getCapturedDecl()->setNothrow();
7557   }
7558   setFunctionHasBranchProtectedScope();
7559 
7560   return OMPTargetTeamsDirective::Create(Context, StartLoc, EndLoc, Clauses,
7561                                          AStmt);
7562 }
7563 
7564 StmtResult Sema::ActOnOpenMPTargetTeamsDistributeDirective(
7565     ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
7566     SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
7567   if (!AStmt)
7568     return StmtError();
7569 
7570   auto *CS = cast<CapturedStmt>(AStmt);
7571   // 1.2.2 OpenMP Language Terminology
7572   // Structured block - An executable statement with a single entry at the
7573   // top and a single exit at the bottom.
7574   // The point of exit cannot be a branch out of the structured block.
7575   // longjmp() and throw() must not violate the entry/exit criteria.
7576   CS->getCapturedDecl()->setNothrow();
7577   for (int ThisCaptureLevel =
7578            getOpenMPCaptureLevels(OMPD_target_teams_distribute);
7579        ThisCaptureLevel > 1; --ThisCaptureLevel) {
7580     CS = cast<CapturedStmt>(CS->getCapturedStmt());
7581     // 1.2.2 OpenMP Language Terminology
7582     // Structured block - An executable statement with a single entry at the
7583     // top and a single exit at the bottom.
7584     // The point of exit cannot be a branch out of the structured block.
7585     // longjmp() and throw() must not violate the entry/exit criteria.
7586     CS->getCapturedDecl()->setNothrow();
7587   }
7588 
7589   OMPLoopDirective::HelperExprs B;
7590   // In presence of clause 'collapse' with number of loops, it will
7591   // define the nested loops number.
7592   unsigned NestedLoopCount = checkOpenMPLoop(
7593       OMPD_target_teams_distribute, getCollapseNumberExpr(Clauses),
7594       nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStack,
7595       VarsWithImplicitDSA, B);
7596   if (NestedLoopCount == 0)
7597     return StmtError();
7598 
7599   assert((CurContext->isDependentContext() || B.builtAll()) &&
7600          "omp target teams distribute loop exprs were not built");
7601 
7602   setFunctionHasBranchProtectedScope();
7603   return OMPTargetTeamsDistributeDirective::Create(
7604       Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
7605 }
7606 
7607 StmtResult Sema::ActOnOpenMPTargetTeamsDistributeParallelForDirective(
7608     ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
7609     SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
7610   if (!AStmt)
7611     return StmtError();
7612 
7613   auto *CS = cast<CapturedStmt>(AStmt);
7614   // 1.2.2 OpenMP Language Terminology
7615   // Structured block - An executable statement with a single entry at the
7616   // top and a single exit at the bottom.
7617   // The point of exit cannot be a branch out of the structured block.
7618   // longjmp() and throw() must not violate the entry/exit criteria.
7619   CS->getCapturedDecl()->setNothrow();
7620   for (int ThisCaptureLevel =
7621            getOpenMPCaptureLevels(OMPD_target_teams_distribute_parallel_for);
7622        ThisCaptureLevel > 1; --ThisCaptureLevel) {
7623     CS = cast<CapturedStmt>(CS->getCapturedStmt());
7624     // 1.2.2 OpenMP Language Terminology
7625     // Structured block - An executable statement with a single entry at the
7626     // top and a single exit at the bottom.
7627     // The point of exit cannot be a branch out of the structured block.
7628     // longjmp() and throw() must not violate the entry/exit criteria.
7629     CS->getCapturedDecl()->setNothrow();
7630   }
7631 
7632   OMPLoopDirective::HelperExprs B;
7633   // In presence of clause 'collapse' with number of loops, it will
7634   // define the nested loops number.
7635   unsigned NestedLoopCount = checkOpenMPLoop(
7636       OMPD_target_teams_distribute_parallel_for, getCollapseNumberExpr(Clauses),
7637       nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStack,
7638       VarsWithImplicitDSA, B);
7639   if (NestedLoopCount == 0)
7640     return StmtError();
7641 
7642   assert((CurContext->isDependentContext() || B.builtAll()) &&
7643          "omp target teams distribute parallel for loop exprs were not built");
7644 
7645   if (!CurContext->isDependentContext()) {
7646     // Finalize the clauses that need pre-built expressions for CodeGen.
7647     for (OMPClause *C : Clauses) {
7648       if (auto *LC = dyn_cast<OMPLinearClause>(C))
7649         if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
7650                                      B.NumIterations, *this, CurScope,
7651                                      DSAStack))
7652           return StmtError();
7653     }
7654   }
7655 
7656   setFunctionHasBranchProtectedScope();
7657   return OMPTargetTeamsDistributeParallelForDirective::Create(
7658       Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B,
7659       DSAStack->isCancelRegion());
7660 }
7661 
7662 StmtResult Sema::ActOnOpenMPTargetTeamsDistributeParallelForSimdDirective(
7663     ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
7664     SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
7665   if (!AStmt)
7666     return StmtError();
7667 
7668   auto *CS = cast<CapturedStmt>(AStmt);
7669   // 1.2.2 OpenMP Language Terminology
7670   // Structured block - An executable statement with a single entry at the
7671   // top and a single exit at the bottom.
7672   // The point of exit cannot be a branch out of the structured block.
7673   // longjmp() and throw() must not violate the entry/exit criteria.
7674   CS->getCapturedDecl()->setNothrow();
7675   for (int ThisCaptureLevel = getOpenMPCaptureLevels(
7676            OMPD_target_teams_distribute_parallel_for_simd);
7677        ThisCaptureLevel > 1; --ThisCaptureLevel) {
7678     CS = cast<CapturedStmt>(CS->getCapturedStmt());
7679     // 1.2.2 OpenMP Language Terminology
7680     // Structured block - An executable statement with a single entry at the
7681     // top and a single exit at the bottom.
7682     // The point of exit cannot be a branch out of the structured block.
7683     // longjmp() and throw() must not violate the entry/exit criteria.
7684     CS->getCapturedDecl()->setNothrow();
7685   }
7686 
7687   OMPLoopDirective::HelperExprs B;
7688   // In presence of clause 'collapse' with number of loops, it will
7689   // define the nested loops number.
7690   unsigned NestedLoopCount =
7691       checkOpenMPLoop(OMPD_target_teams_distribute_parallel_for_simd,
7692                       getCollapseNumberExpr(Clauses),
7693                       nullptr /*ordered not a clause on distribute*/, CS, *this,
7694                       *DSAStack, VarsWithImplicitDSA, B);
7695   if (NestedLoopCount == 0)
7696     return StmtError();
7697 
7698   assert((CurContext->isDependentContext() || B.builtAll()) &&
7699          "omp target teams distribute parallel for simd loop exprs were not "
7700          "built");
7701 
7702   if (!CurContext->isDependentContext()) {
7703     // Finalize the clauses that need pre-built expressions for CodeGen.
7704     for (OMPClause *C : Clauses) {
7705       if (auto *LC = dyn_cast<OMPLinearClause>(C))
7706         if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
7707                                      B.NumIterations, *this, CurScope,
7708                                      DSAStack))
7709           return StmtError();
7710     }
7711   }
7712 
7713   if (checkSimdlenSafelenSpecified(*this, Clauses))
7714     return StmtError();
7715 
7716   setFunctionHasBranchProtectedScope();
7717   return OMPTargetTeamsDistributeParallelForSimdDirective::Create(
7718       Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
7719 }
7720 
7721 StmtResult Sema::ActOnOpenMPTargetTeamsDistributeSimdDirective(
7722     ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
7723     SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
7724   if (!AStmt)
7725     return StmtError();
7726 
7727   auto *CS = cast<CapturedStmt>(AStmt);
7728   // 1.2.2 OpenMP Language Terminology
7729   // Structured block - An executable statement with a single entry at the
7730   // top and a single exit at the bottom.
7731   // The point of exit cannot be a branch out of the structured block.
7732   // longjmp() and throw() must not violate the entry/exit criteria.
7733   CS->getCapturedDecl()->setNothrow();
7734   for (int ThisCaptureLevel =
7735            getOpenMPCaptureLevels(OMPD_target_teams_distribute_simd);
7736        ThisCaptureLevel > 1; --ThisCaptureLevel) {
7737     CS = cast<CapturedStmt>(CS->getCapturedStmt());
7738     // 1.2.2 OpenMP Language Terminology
7739     // Structured block - An executable statement with a single entry at the
7740     // top and a single exit at the bottom.
7741     // The point of exit cannot be a branch out of the structured block.
7742     // longjmp() and throw() must not violate the entry/exit criteria.
7743     CS->getCapturedDecl()->setNothrow();
7744   }
7745 
7746   OMPLoopDirective::HelperExprs B;
7747   // In presence of clause 'collapse' with number of loops, it will
7748   // define the nested loops number.
7749   unsigned NestedLoopCount = checkOpenMPLoop(
7750       OMPD_target_teams_distribute_simd, getCollapseNumberExpr(Clauses),
7751       nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStack,
7752       VarsWithImplicitDSA, B);
7753   if (NestedLoopCount == 0)
7754     return StmtError();
7755 
7756   assert((CurContext->isDependentContext() || B.builtAll()) &&
7757          "omp target teams distribute simd loop exprs were not built");
7758 
7759   if (!CurContext->isDependentContext()) {
7760     // Finalize the clauses that need pre-built expressions for CodeGen.
7761     for (OMPClause *C : Clauses) {
7762       if (auto *LC = dyn_cast<OMPLinearClause>(C))
7763         if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
7764                                      B.NumIterations, *this, CurScope,
7765                                      DSAStack))
7766           return StmtError();
7767     }
7768   }
7769 
7770   if (checkSimdlenSafelenSpecified(*this, Clauses))
7771     return StmtError();
7772 
7773   setFunctionHasBranchProtectedScope();
7774   return OMPTargetTeamsDistributeSimdDirective::Create(
7775       Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
7776 }
7777 
7778 OMPClause *Sema::ActOnOpenMPSingleExprClause(OpenMPClauseKind Kind, Expr *Expr,
7779                                              SourceLocation StartLoc,
7780                                              SourceLocation LParenLoc,
7781                                              SourceLocation EndLoc) {
7782   OMPClause *Res = nullptr;
7783   switch (Kind) {
7784   case OMPC_final:
7785     Res = ActOnOpenMPFinalClause(Expr, StartLoc, LParenLoc, EndLoc);
7786     break;
7787   case OMPC_num_threads:
7788     Res = ActOnOpenMPNumThreadsClause(Expr, StartLoc, LParenLoc, EndLoc);
7789     break;
7790   case OMPC_safelen:
7791     Res = ActOnOpenMPSafelenClause(Expr, StartLoc, LParenLoc, EndLoc);
7792     break;
7793   case OMPC_simdlen:
7794     Res = ActOnOpenMPSimdlenClause(Expr, StartLoc, LParenLoc, EndLoc);
7795     break;
7796   case OMPC_collapse:
7797     Res = ActOnOpenMPCollapseClause(Expr, StartLoc, LParenLoc, EndLoc);
7798     break;
7799   case OMPC_ordered:
7800     Res = ActOnOpenMPOrderedClause(StartLoc, EndLoc, LParenLoc, Expr);
7801     break;
7802   case OMPC_device:
7803     Res = ActOnOpenMPDeviceClause(Expr, StartLoc, LParenLoc, EndLoc);
7804     break;
7805   case OMPC_num_teams:
7806     Res = ActOnOpenMPNumTeamsClause(Expr, StartLoc, LParenLoc, EndLoc);
7807     break;
7808   case OMPC_thread_limit:
7809     Res = ActOnOpenMPThreadLimitClause(Expr, StartLoc, LParenLoc, EndLoc);
7810     break;
7811   case OMPC_priority:
7812     Res = ActOnOpenMPPriorityClause(Expr, StartLoc, LParenLoc, EndLoc);
7813     break;
7814   case OMPC_grainsize:
7815     Res = ActOnOpenMPGrainsizeClause(Expr, StartLoc, LParenLoc, EndLoc);
7816     break;
7817   case OMPC_num_tasks:
7818     Res = ActOnOpenMPNumTasksClause(Expr, StartLoc, LParenLoc, EndLoc);
7819     break;
7820   case OMPC_hint:
7821     Res = ActOnOpenMPHintClause(Expr, StartLoc, LParenLoc, EndLoc);
7822     break;
7823   case OMPC_if:
7824   case OMPC_default:
7825   case OMPC_proc_bind:
7826   case OMPC_schedule:
7827   case OMPC_private:
7828   case OMPC_firstprivate:
7829   case OMPC_lastprivate:
7830   case OMPC_shared:
7831   case OMPC_reduction:
7832   case OMPC_task_reduction:
7833   case OMPC_in_reduction:
7834   case OMPC_linear:
7835   case OMPC_aligned:
7836   case OMPC_copyin:
7837   case OMPC_copyprivate:
7838   case OMPC_nowait:
7839   case OMPC_untied:
7840   case OMPC_mergeable:
7841   case OMPC_threadprivate:
7842   case OMPC_flush:
7843   case OMPC_read:
7844   case OMPC_write:
7845   case OMPC_update:
7846   case OMPC_capture:
7847   case OMPC_seq_cst:
7848   case OMPC_depend:
7849   case OMPC_threads:
7850   case OMPC_simd:
7851   case OMPC_map:
7852   case OMPC_nogroup:
7853   case OMPC_dist_schedule:
7854   case OMPC_defaultmap:
7855   case OMPC_unknown:
7856   case OMPC_uniform:
7857   case OMPC_to:
7858   case OMPC_from:
7859   case OMPC_use_device_ptr:
7860   case OMPC_is_device_ptr:
7861     llvm_unreachable("Clause is not allowed.");
7862   }
7863   return Res;
7864 }
7865 
7866 // An OpenMP directive such as 'target parallel' has two captured regions:
7867 // for the 'target' and 'parallel' respectively.  This function returns
7868 // the region in which to capture expressions associated with a clause.
7869 // A return value of OMPD_unknown signifies that the expression should not
7870 // be captured.
7871 static OpenMPDirectiveKind getOpenMPCaptureRegionForClause(
7872     OpenMPDirectiveKind DKind, OpenMPClauseKind CKind,
7873     OpenMPDirectiveKind NameModifier = OMPD_unknown) {
7874   OpenMPDirectiveKind CaptureRegion = OMPD_unknown;
7875   switch (CKind) {
7876   case OMPC_if:
7877     switch (DKind) {
7878     case OMPD_target_parallel:
7879     case OMPD_target_parallel_for:
7880     case OMPD_target_parallel_for_simd:
7881       // If this clause applies to the nested 'parallel' region, capture within
7882       // the 'target' region, otherwise do not capture.
7883       if (NameModifier == OMPD_unknown || NameModifier == OMPD_parallel)
7884         CaptureRegion = OMPD_target;
7885       break;
7886     case OMPD_target_teams_distribute_parallel_for:
7887     case OMPD_target_teams_distribute_parallel_for_simd:
7888       // If this clause applies to the nested 'parallel' region, capture within
7889       // the 'teams' region, otherwise do not capture.
7890       if (NameModifier == OMPD_unknown || NameModifier == OMPD_parallel)
7891         CaptureRegion = OMPD_teams;
7892       break;
7893     case OMPD_teams_distribute_parallel_for:
7894     case OMPD_teams_distribute_parallel_for_simd:
7895       CaptureRegion = OMPD_teams;
7896       break;
7897     case OMPD_target_update:
7898     case OMPD_target_enter_data:
7899     case OMPD_target_exit_data:
7900       CaptureRegion = OMPD_task;
7901       break;
7902     case OMPD_cancel:
7903     case OMPD_parallel:
7904     case OMPD_parallel_sections:
7905     case OMPD_parallel_for:
7906     case OMPD_parallel_for_simd:
7907     case OMPD_target:
7908     case OMPD_target_simd:
7909     case OMPD_target_teams:
7910     case OMPD_target_teams_distribute:
7911     case OMPD_target_teams_distribute_simd:
7912     case OMPD_distribute_parallel_for:
7913     case OMPD_distribute_parallel_for_simd:
7914     case OMPD_task:
7915     case OMPD_taskloop:
7916     case OMPD_taskloop_simd:
7917     case OMPD_target_data:
7918       // Do not capture if-clause expressions.
7919       break;
7920     case OMPD_threadprivate:
7921     case OMPD_taskyield:
7922     case OMPD_barrier:
7923     case OMPD_taskwait:
7924     case OMPD_cancellation_point:
7925     case OMPD_flush:
7926     case OMPD_declare_reduction:
7927     case OMPD_declare_simd:
7928     case OMPD_declare_target:
7929     case OMPD_end_declare_target:
7930     case OMPD_teams:
7931     case OMPD_simd:
7932     case OMPD_for:
7933     case OMPD_for_simd:
7934     case OMPD_sections:
7935     case OMPD_section:
7936     case OMPD_single:
7937     case OMPD_master:
7938     case OMPD_critical:
7939     case OMPD_taskgroup:
7940     case OMPD_distribute:
7941     case OMPD_ordered:
7942     case OMPD_atomic:
7943     case OMPD_distribute_simd:
7944     case OMPD_teams_distribute:
7945     case OMPD_teams_distribute_simd:
7946       llvm_unreachable("Unexpected OpenMP directive with if-clause");
7947     case OMPD_unknown:
7948       llvm_unreachable("Unknown OpenMP directive");
7949     }
7950     break;
7951   case OMPC_num_threads:
7952     switch (DKind) {
7953     case OMPD_target_parallel:
7954     case OMPD_target_parallel_for:
7955     case OMPD_target_parallel_for_simd:
7956       CaptureRegion = OMPD_target;
7957       break;
7958     case OMPD_teams_distribute_parallel_for:
7959     case OMPD_teams_distribute_parallel_for_simd:
7960     case OMPD_target_teams_distribute_parallel_for:
7961     case OMPD_target_teams_distribute_parallel_for_simd:
7962       CaptureRegion = OMPD_teams;
7963       break;
7964     case OMPD_parallel:
7965     case OMPD_parallel_sections:
7966     case OMPD_parallel_for:
7967     case OMPD_parallel_for_simd:
7968     case OMPD_distribute_parallel_for:
7969     case OMPD_distribute_parallel_for_simd:
7970       // Do not capture num_threads-clause expressions.
7971       break;
7972     case OMPD_target_data:
7973     case OMPD_target_enter_data:
7974     case OMPD_target_exit_data:
7975     case OMPD_target_update:
7976     case OMPD_target:
7977     case OMPD_target_simd:
7978     case OMPD_target_teams:
7979     case OMPD_target_teams_distribute:
7980     case OMPD_target_teams_distribute_simd:
7981     case OMPD_cancel:
7982     case OMPD_task:
7983     case OMPD_taskloop:
7984     case OMPD_taskloop_simd:
7985     case OMPD_threadprivate:
7986     case OMPD_taskyield:
7987     case OMPD_barrier:
7988     case OMPD_taskwait:
7989     case OMPD_cancellation_point:
7990     case OMPD_flush:
7991     case OMPD_declare_reduction:
7992     case OMPD_declare_simd:
7993     case OMPD_declare_target:
7994     case OMPD_end_declare_target:
7995     case OMPD_teams:
7996     case OMPD_simd:
7997     case OMPD_for:
7998     case OMPD_for_simd:
7999     case OMPD_sections:
8000     case OMPD_section:
8001     case OMPD_single:
8002     case OMPD_master:
8003     case OMPD_critical:
8004     case OMPD_taskgroup:
8005     case OMPD_distribute:
8006     case OMPD_ordered:
8007     case OMPD_atomic:
8008     case OMPD_distribute_simd:
8009     case OMPD_teams_distribute:
8010     case OMPD_teams_distribute_simd:
8011       llvm_unreachable("Unexpected OpenMP directive with num_threads-clause");
8012     case OMPD_unknown:
8013       llvm_unreachable("Unknown OpenMP directive");
8014     }
8015     break;
8016   case OMPC_num_teams:
8017     switch (DKind) {
8018     case OMPD_target_teams:
8019     case OMPD_target_teams_distribute:
8020     case OMPD_target_teams_distribute_simd:
8021     case OMPD_target_teams_distribute_parallel_for:
8022     case OMPD_target_teams_distribute_parallel_for_simd:
8023       CaptureRegion = OMPD_target;
8024       break;
8025     case OMPD_teams_distribute_parallel_for:
8026     case OMPD_teams_distribute_parallel_for_simd:
8027     case OMPD_teams:
8028     case OMPD_teams_distribute:
8029     case OMPD_teams_distribute_simd:
8030       // Do not capture num_teams-clause expressions.
8031       break;
8032     case OMPD_distribute_parallel_for:
8033     case OMPD_distribute_parallel_for_simd:
8034     case OMPD_task:
8035     case OMPD_taskloop:
8036     case OMPD_taskloop_simd:
8037     case OMPD_target_data:
8038     case OMPD_target_enter_data:
8039     case OMPD_target_exit_data:
8040     case OMPD_target_update:
8041     case OMPD_cancel:
8042     case OMPD_parallel:
8043     case OMPD_parallel_sections:
8044     case OMPD_parallel_for:
8045     case OMPD_parallel_for_simd:
8046     case OMPD_target:
8047     case OMPD_target_simd:
8048     case OMPD_target_parallel:
8049     case OMPD_target_parallel_for:
8050     case OMPD_target_parallel_for_simd:
8051     case OMPD_threadprivate:
8052     case OMPD_taskyield:
8053     case OMPD_barrier:
8054     case OMPD_taskwait:
8055     case OMPD_cancellation_point:
8056     case OMPD_flush:
8057     case OMPD_declare_reduction:
8058     case OMPD_declare_simd:
8059     case OMPD_declare_target:
8060     case OMPD_end_declare_target:
8061     case OMPD_simd:
8062     case OMPD_for:
8063     case OMPD_for_simd:
8064     case OMPD_sections:
8065     case OMPD_section:
8066     case OMPD_single:
8067     case OMPD_master:
8068     case OMPD_critical:
8069     case OMPD_taskgroup:
8070     case OMPD_distribute:
8071     case OMPD_ordered:
8072     case OMPD_atomic:
8073     case OMPD_distribute_simd:
8074       llvm_unreachable("Unexpected OpenMP directive with num_teams-clause");
8075     case OMPD_unknown:
8076       llvm_unreachable("Unknown OpenMP directive");
8077     }
8078     break;
8079   case OMPC_thread_limit:
8080     switch (DKind) {
8081     case OMPD_target_teams:
8082     case OMPD_target_teams_distribute:
8083     case OMPD_target_teams_distribute_simd:
8084     case OMPD_target_teams_distribute_parallel_for:
8085     case OMPD_target_teams_distribute_parallel_for_simd:
8086       CaptureRegion = OMPD_target;
8087       break;
8088     case OMPD_teams_distribute_parallel_for:
8089     case OMPD_teams_distribute_parallel_for_simd:
8090     case OMPD_teams:
8091     case OMPD_teams_distribute:
8092     case OMPD_teams_distribute_simd:
8093       // Do not capture thread_limit-clause expressions.
8094       break;
8095     case OMPD_distribute_parallel_for:
8096     case OMPD_distribute_parallel_for_simd:
8097     case OMPD_task:
8098     case OMPD_taskloop:
8099     case OMPD_taskloop_simd:
8100     case OMPD_target_data:
8101     case OMPD_target_enter_data:
8102     case OMPD_target_exit_data:
8103     case OMPD_target_update:
8104     case OMPD_cancel:
8105     case OMPD_parallel:
8106     case OMPD_parallel_sections:
8107     case OMPD_parallel_for:
8108     case OMPD_parallel_for_simd:
8109     case OMPD_target:
8110     case OMPD_target_simd:
8111     case OMPD_target_parallel:
8112     case OMPD_target_parallel_for:
8113     case OMPD_target_parallel_for_simd:
8114     case OMPD_threadprivate:
8115     case OMPD_taskyield:
8116     case OMPD_barrier:
8117     case OMPD_taskwait:
8118     case OMPD_cancellation_point:
8119     case OMPD_flush:
8120     case OMPD_declare_reduction:
8121     case OMPD_declare_simd:
8122     case OMPD_declare_target:
8123     case OMPD_end_declare_target:
8124     case OMPD_simd:
8125     case OMPD_for:
8126     case OMPD_for_simd:
8127     case OMPD_sections:
8128     case OMPD_section:
8129     case OMPD_single:
8130     case OMPD_master:
8131     case OMPD_critical:
8132     case OMPD_taskgroup:
8133     case OMPD_distribute:
8134     case OMPD_ordered:
8135     case OMPD_atomic:
8136     case OMPD_distribute_simd:
8137       llvm_unreachable("Unexpected OpenMP directive with thread_limit-clause");
8138     case OMPD_unknown:
8139       llvm_unreachable("Unknown OpenMP directive");
8140     }
8141     break;
8142   case OMPC_schedule:
8143     switch (DKind) {
8144     case OMPD_parallel_for:
8145     case OMPD_parallel_for_simd:
8146     case OMPD_distribute_parallel_for:
8147     case OMPD_distribute_parallel_for_simd:
8148     case OMPD_teams_distribute_parallel_for:
8149     case OMPD_teams_distribute_parallel_for_simd:
8150     case OMPD_target_parallel_for:
8151     case OMPD_target_parallel_for_simd:
8152     case OMPD_target_teams_distribute_parallel_for:
8153     case OMPD_target_teams_distribute_parallel_for_simd:
8154       CaptureRegion = OMPD_parallel;
8155       break;
8156     case OMPD_for:
8157     case OMPD_for_simd:
8158       // Do not capture schedule-clause expressions.
8159       break;
8160     case OMPD_task:
8161     case OMPD_taskloop:
8162     case OMPD_taskloop_simd:
8163     case OMPD_target_data:
8164     case OMPD_target_enter_data:
8165     case OMPD_target_exit_data:
8166     case OMPD_target_update:
8167     case OMPD_teams:
8168     case OMPD_teams_distribute:
8169     case OMPD_teams_distribute_simd:
8170     case OMPD_target_teams_distribute:
8171     case OMPD_target_teams_distribute_simd:
8172     case OMPD_target:
8173     case OMPD_target_simd:
8174     case OMPD_target_parallel:
8175     case OMPD_cancel:
8176     case OMPD_parallel:
8177     case OMPD_parallel_sections:
8178     case OMPD_threadprivate:
8179     case OMPD_taskyield:
8180     case OMPD_barrier:
8181     case OMPD_taskwait:
8182     case OMPD_cancellation_point:
8183     case OMPD_flush:
8184     case OMPD_declare_reduction:
8185     case OMPD_declare_simd:
8186     case OMPD_declare_target:
8187     case OMPD_end_declare_target:
8188     case OMPD_simd:
8189     case OMPD_sections:
8190     case OMPD_section:
8191     case OMPD_single:
8192     case OMPD_master:
8193     case OMPD_critical:
8194     case OMPD_taskgroup:
8195     case OMPD_distribute:
8196     case OMPD_ordered:
8197     case OMPD_atomic:
8198     case OMPD_distribute_simd:
8199     case OMPD_target_teams:
8200       llvm_unreachable("Unexpected OpenMP directive with schedule clause");
8201     case OMPD_unknown:
8202       llvm_unreachable("Unknown OpenMP directive");
8203     }
8204     break;
8205   case OMPC_dist_schedule:
8206     switch (DKind) {
8207     case OMPD_teams_distribute_parallel_for:
8208     case OMPD_teams_distribute_parallel_for_simd:
8209     case OMPD_teams_distribute:
8210     case OMPD_teams_distribute_simd:
8211     case OMPD_target_teams_distribute_parallel_for:
8212     case OMPD_target_teams_distribute_parallel_for_simd:
8213     case OMPD_target_teams_distribute:
8214     case OMPD_target_teams_distribute_simd:
8215       CaptureRegion = OMPD_teams;
8216       break;
8217     case OMPD_distribute_parallel_for:
8218     case OMPD_distribute_parallel_for_simd:
8219     case OMPD_distribute:
8220     case OMPD_distribute_simd:
8221       // Do not capture thread_limit-clause expressions.
8222       break;
8223     case OMPD_parallel_for:
8224     case OMPD_parallel_for_simd:
8225     case OMPD_target_parallel_for_simd:
8226     case OMPD_target_parallel_for:
8227     case OMPD_task:
8228     case OMPD_taskloop:
8229     case OMPD_taskloop_simd:
8230     case OMPD_target_data:
8231     case OMPD_target_enter_data:
8232     case OMPD_target_exit_data:
8233     case OMPD_target_update:
8234     case OMPD_teams:
8235     case OMPD_target:
8236     case OMPD_target_simd:
8237     case OMPD_target_parallel:
8238     case OMPD_cancel:
8239     case OMPD_parallel:
8240     case OMPD_parallel_sections:
8241     case OMPD_threadprivate:
8242     case OMPD_taskyield:
8243     case OMPD_barrier:
8244     case OMPD_taskwait:
8245     case OMPD_cancellation_point:
8246     case OMPD_flush:
8247     case OMPD_declare_reduction:
8248     case OMPD_declare_simd:
8249     case OMPD_declare_target:
8250     case OMPD_end_declare_target:
8251     case OMPD_simd:
8252     case OMPD_for:
8253     case OMPD_for_simd:
8254     case OMPD_sections:
8255     case OMPD_section:
8256     case OMPD_single:
8257     case OMPD_master:
8258     case OMPD_critical:
8259     case OMPD_taskgroup:
8260     case OMPD_ordered:
8261     case OMPD_atomic:
8262     case OMPD_target_teams:
8263       llvm_unreachable("Unexpected OpenMP directive with schedule clause");
8264     case OMPD_unknown:
8265       llvm_unreachable("Unknown OpenMP directive");
8266     }
8267     break;
8268   case OMPC_device:
8269     switch (DKind) {
8270     case OMPD_target_update:
8271     case OMPD_target_enter_data:
8272     case OMPD_target_exit_data:
8273     case OMPD_target:
8274     case OMPD_target_simd:
8275     case OMPD_target_teams:
8276     case OMPD_target_parallel:
8277     case OMPD_target_teams_distribute:
8278     case OMPD_target_teams_distribute_simd:
8279     case OMPD_target_parallel_for:
8280     case OMPD_target_parallel_for_simd:
8281     case OMPD_target_teams_distribute_parallel_for:
8282     case OMPD_target_teams_distribute_parallel_for_simd:
8283       CaptureRegion = OMPD_task;
8284       break;
8285     case OMPD_target_data:
8286       // Do not capture device-clause expressions.
8287       break;
8288     case OMPD_teams_distribute_parallel_for:
8289     case OMPD_teams_distribute_parallel_for_simd:
8290     case OMPD_teams:
8291     case OMPD_teams_distribute:
8292     case OMPD_teams_distribute_simd:
8293     case OMPD_distribute_parallel_for:
8294     case OMPD_distribute_parallel_for_simd:
8295     case OMPD_task:
8296     case OMPD_taskloop:
8297     case OMPD_taskloop_simd:
8298     case OMPD_cancel:
8299     case OMPD_parallel:
8300     case OMPD_parallel_sections:
8301     case OMPD_parallel_for:
8302     case OMPD_parallel_for_simd:
8303     case OMPD_threadprivate:
8304     case OMPD_taskyield:
8305     case OMPD_barrier:
8306     case OMPD_taskwait:
8307     case OMPD_cancellation_point:
8308     case OMPD_flush:
8309     case OMPD_declare_reduction:
8310     case OMPD_declare_simd:
8311     case OMPD_declare_target:
8312     case OMPD_end_declare_target:
8313     case OMPD_simd:
8314     case OMPD_for:
8315     case OMPD_for_simd:
8316     case OMPD_sections:
8317     case OMPD_section:
8318     case OMPD_single:
8319     case OMPD_master:
8320     case OMPD_critical:
8321     case OMPD_taskgroup:
8322     case OMPD_distribute:
8323     case OMPD_ordered:
8324     case OMPD_atomic:
8325     case OMPD_distribute_simd:
8326       llvm_unreachable("Unexpected OpenMP directive with num_teams-clause");
8327     case OMPD_unknown:
8328       llvm_unreachable("Unknown OpenMP directive");
8329     }
8330     break;
8331   case OMPC_firstprivate:
8332   case OMPC_lastprivate:
8333   case OMPC_reduction:
8334   case OMPC_task_reduction:
8335   case OMPC_in_reduction:
8336   case OMPC_linear:
8337   case OMPC_default:
8338   case OMPC_proc_bind:
8339   case OMPC_final:
8340   case OMPC_safelen:
8341   case OMPC_simdlen:
8342   case OMPC_collapse:
8343   case OMPC_private:
8344   case OMPC_shared:
8345   case OMPC_aligned:
8346   case OMPC_copyin:
8347   case OMPC_copyprivate:
8348   case OMPC_ordered:
8349   case OMPC_nowait:
8350   case OMPC_untied:
8351   case OMPC_mergeable:
8352   case OMPC_threadprivate:
8353   case OMPC_flush:
8354   case OMPC_read:
8355   case OMPC_write:
8356   case OMPC_update:
8357   case OMPC_capture:
8358   case OMPC_seq_cst:
8359   case OMPC_depend:
8360   case OMPC_threads:
8361   case OMPC_simd:
8362   case OMPC_map:
8363   case OMPC_priority:
8364   case OMPC_grainsize:
8365   case OMPC_nogroup:
8366   case OMPC_num_tasks:
8367   case OMPC_hint:
8368   case OMPC_defaultmap:
8369   case OMPC_unknown:
8370   case OMPC_uniform:
8371   case OMPC_to:
8372   case OMPC_from:
8373   case OMPC_use_device_ptr:
8374   case OMPC_is_device_ptr:
8375     llvm_unreachable("Unexpected OpenMP clause.");
8376   }
8377   return CaptureRegion;
8378 }
8379 
8380 OMPClause *Sema::ActOnOpenMPIfClause(OpenMPDirectiveKind NameModifier,
8381                                      Expr *Condition, SourceLocation StartLoc,
8382                                      SourceLocation LParenLoc,
8383                                      SourceLocation NameModifierLoc,
8384                                      SourceLocation ColonLoc,
8385                                      SourceLocation EndLoc) {
8386   Expr *ValExpr = Condition;
8387   Stmt *HelperValStmt = nullptr;
8388   OpenMPDirectiveKind CaptureRegion = OMPD_unknown;
8389   if (!Condition->isValueDependent() && !Condition->isTypeDependent() &&
8390       !Condition->isInstantiationDependent() &&
8391       !Condition->containsUnexpandedParameterPack()) {
8392     ExprResult Val = CheckBooleanCondition(StartLoc, Condition);
8393     if (Val.isInvalid())
8394       return nullptr;
8395 
8396     ValExpr = Val.get();
8397 
8398     OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective();
8399     CaptureRegion =
8400         getOpenMPCaptureRegionForClause(DKind, OMPC_if, NameModifier);
8401     if (CaptureRegion != OMPD_unknown && !CurContext->isDependentContext()) {
8402       ValExpr = MakeFullExpr(ValExpr).get();
8403       llvm::MapVector<const Expr *, DeclRefExpr *> Captures;
8404       ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
8405       HelperValStmt = buildPreInits(Context, Captures);
8406     }
8407   }
8408 
8409   return new (Context)
8410       OMPIfClause(NameModifier, ValExpr, HelperValStmt, CaptureRegion, StartLoc,
8411                   LParenLoc, NameModifierLoc, ColonLoc, EndLoc);
8412 }
8413 
8414 OMPClause *Sema::ActOnOpenMPFinalClause(Expr *Condition,
8415                                         SourceLocation StartLoc,
8416                                         SourceLocation LParenLoc,
8417                                         SourceLocation EndLoc) {
8418   Expr *ValExpr = Condition;
8419   if (!Condition->isValueDependent() && !Condition->isTypeDependent() &&
8420       !Condition->isInstantiationDependent() &&
8421       !Condition->containsUnexpandedParameterPack()) {
8422     ExprResult Val = CheckBooleanCondition(StartLoc, Condition);
8423     if (Val.isInvalid())
8424       return nullptr;
8425 
8426     ValExpr = MakeFullExpr(Val.get()).get();
8427   }
8428 
8429   return new (Context) OMPFinalClause(ValExpr, StartLoc, LParenLoc, EndLoc);
8430 }
8431 ExprResult Sema::PerformOpenMPImplicitIntegerConversion(SourceLocation Loc,
8432                                                         Expr *Op) {
8433   if (!Op)
8434     return ExprError();
8435 
8436   class IntConvertDiagnoser : public ICEConvertDiagnoser {
8437   public:
8438     IntConvertDiagnoser()
8439         : ICEConvertDiagnoser(/*AllowScopedEnumerations*/ false, false, true) {}
8440     SemaDiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc,
8441                                          QualType T) override {
8442       return S.Diag(Loc, diag::err_omp_not_integral) << T;
8443     }
8444     SemaDiagnosticBuilder diagnoseIncomplete(Sema &S, SourceLocation Loc,
8445                                              QualType T) override {
8446       return S.Diag(Loc, diag::err_omp_incomplete_type) << T;
8447     }
8448     SemaDiagnosticBuilder diagnoseExplicitConv(Sema &S, SourceLocation Loc,
8449                                                QualType T,
8450                                                QualType ConvTy) override {
8451       return S.Diag(Loc, diag::err_omp_explicit_conversion) << T << ConvTy;
8452     }
8453     SemaDiagnosticBuilder noteExplicitConv(Sema &S, CXXConversionDecl *Conv,
8454                                            QualType ConvTy) override {
8455       return S.Diag(Conv->getLocation(), diag::note_omp_conversion_here)
8456              << ConvTy->isEnumeralType() << ConvTy;
8457     }
8458     SemaDiagnosticBuilder diagnoseAmbiguous(Sema &S, SourceLocation Loc,
8459                                             QualType T) override {
8460       return S.Diag(Loc, diag::err_omp_ambiguous_conversion) << T;
8461     }
8462     SemaDiagnosticBuilder noteAmbiguous(Sema &S, CXXConversionDecl *Conv,
8463                                         QualType ConvTy) override {
8464       return S.Diag(Conv->getLocation(), diag::note_omp_conversion_here)
8465              << ConvTy->isEnumeralType() << ConvTy;
8466     }
8467     SemaDiagnosticBuilder diagnoseConversion(Sema &, SourceLocation, QualType,
8468                                              QualType) override {
8469       llvm_unreachable("conversion functions are permitted");
8470     }
8471   } ConvertDiagnoser;
8472   return PerformContextualImplicitConversion(Loc, Op, ConvertDiagnoser);
8473 }
8474 
8475 static bool isNonNegativeIntegerValue(Expr *&ValExpr, Sema &SemaRef,
8476                                       OpenMPClauseKind CKind,
8477                                       bool StrictlyPositive) {
8478   if (!ValExpr->isTypeDependent() && !ValExpr->isValueDependent() &&
8479       !ValExpr->isInstantiationDependent()) {
8480     SourceLocation Loc = ValExpr->getExprLoc();
8481     ExprResult Value =
8482         SemaRef.PerformOpenMPImplicitIntegerConversion(Loc, ValExpr);
8483     if (Value.isInvalid())
8484       return false;
8485 
8486     ValExpr = Value.get();
8487     // The expression must evaluate to a non-negative integer value.
8488     llvm::APSInt Result;
8489     if (ValExpr->isIntegerConstantExpr(Result, SemaRef.Context) &&
8490         Result.isSigned() &&
8491         !((!StrictlyPositive && Result.isNonNegative()) ||
8492           (StrictlyPositive && Result.isStrictlyPositive()))) {
8493       SemaRef.Diag(Loc, diag::err_omp_negative_expression_in_clause)
8494           << getOpenMPClauseName(CKind) << (StrictlyPositive ? 1 : 0)
8495           << ValExpr->getSourceRange();
8496       return false;
8497     }
8498   }
8499   return true;
8500 }
8501 
8502 OMPClause *Sema::ActOnOpenMPNumThreadsClause(Expr *NumThreads,
8503                                              SourceLocation StartLoc,
8504                                              SourceLocation LParenLoc,
8505                                              SourceLocation EndLoc) {
8506   Expr *ValExpr = NumThreads;
8507   Stmt *HelperValStmt = nullptr;
8508 
8509   // OpenMP [2.5, Restrictions]
8510   //  The num_threads expression must evaluate to a positive integer value.
8511   if (!isNonNegativeIntegerValue(ValExpr, *this, OMPC_num_threads,
8512                                  /*StrictlyPositive=*/true))
8513     return nullptr;
8514 
8515   OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective();
8516   OpenMPDirectiveKind CaptureRegion =
8517       getOpenMPCaptureRegionForClause(DKind, OMPC_num_threads);
8518   if (CaptureRegion != OMPD_unknown && !CurContext->isDependentContext()) {
8519     ValExpr = MakeFullExpr(ValExpr).get();
8520     llvm::MapVector<const Expr *, DeclRefExpr *> Captures;
8521     ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
8522     HelperValStmt = buildPreInits(Context, Captures);
8523   }
8524 
8525   return new (Context) OMPNumThreadsClause(
8526       ValExpr, HelperValStmt, CaptureRegion, StartLoc, LParenLoc, EndLoc);
8527 }
8528 
8529 ExprResult Sema::VerifyPositiveIntegerConstantInClause(Expr *E,
8530                                                        OpenMPClauseKind CKind,
8531                                                        bool StrictlyPositive) {
8532   if (!E)
8533     return ExprError();
8534   if (E->isValueDependent() || E->isTypeDependent() ||
8535       E->isInstantiationDependent() || E->containsUnexpandedParameterPack())
8536     return E;
8537   llvm::APSInt Result;
8538   ExprResult ICE = VerifyIntegerConstantExpression(E, &Result);
8539   if (ICE.isInvalid())
8540     return ExprError();
8541   if ((StrictlyPositive && !Result.isStrictlyPositive()) ||
8542       (!StrictlyPositive && !Result.isNonNegative())) {
8543     Diag(E->getExprLoc(), diag::err_omp_negative_expression_in_clause)
8544         << getOpenMPClauseName(CKind) << (StrictlyPositive ? 1 : 0)
8545         << E->getSourceRange();
8546     return ExprError();
8547   }
8548   if (CKind == OMPC_aligned && !Result.isPowerOf2()) {
8549     Diag(E->getExprLoc(), diag::warn_omp_alignment_not_power_of_two)
8550         << E->getSourceRange();
8551     return ExprError();
8552   }
8553   if (CKind == OMPC_collapse && DSAStack->getAssociatedLoops() == 1)
8554     DSAStack->setAssociatedLoops(Result.getExtValue());
8555   else if (CKind == OMPC_ordered)
8556     DSAStack->setAssociatedLoops(Result.getExtValue());
8557   return ICE;
8558 }
8559 
8560 OMPClause *Sema::ActOnOpenMPSafelenClause(Expr *Len, SourceLocation StartLoc,
8561                                           SourceLocation LParenLoc,
8562                                           SourceLocation EndLoc) {
8563   // OpenMP [2.8.1, simd construct, Description]
8564   // The parameter of the safelen clause must be a constant
8565   // positive integer expression.
8566   ExprResult Safelen = VerifyPositiveIntegerConstantInClause(Len, OMPC_safelen);
8567   if (Safelen.isInvalid())
8568     return nullptr;
8569   return new (Context)
8570       OMPSafelenClause(Safelen.get(), StartLoc, LParenLoc, EndLoc);
8571 }
8572 
8573 OMPClause *Sema::ActOnOpenMPSimdlenClause(Expr *Len, SourceLocation StartLoc,
8574                                           SourceLocation LParenLoc,
8575                                           SourceLocation EndLoc) {
8576   // OpenMP [2.8.1, simd construct, Description]
8577   // The parameter of the simdlen clause must be a constant
8578   // positive integer expression.
8579   ExprResult Simdlen = VerifyPositiveIntegerConstantInClause(Len, OMPC_simdlen);
8580   if (Simdlen.isInvalid())
8581     return nullptr;
8582   return new (Context)
8583       OMPSimdlenClause(Simdlen.get(), StartLoc, LParenLoc, EndLoc);
8584 }
8585 
8586 OMPClause *Sema::ActOnOpenMPCollapseClause(Expr *NumForLoops,
8587                                            SourceLocation StartLoc,
8588                                            SourceLocation LParenLoc,
8589                                            SourceLocation EndLoc) {
8590   // OpenMP [2.7.1, loop construct, Description]
8591   // OpenMP [2.8.1, simd construct, Description]
8592   // OpenMP [2.9.6, distribute construct, Description]
8593   // The parameter of the collapse clause must be a constant
8594   // positive integer expression.
8595   ExprResult NumForLoopsResult =
8596       VerifyPositiveIntegerConstantInClause(NumForLoops, OMPC_collapse);
8597   if (NumForLoopsResult.isInvalid())
8598     return nullptr;
8599   return new (Context)
8600       OMPCollapseClause(NumForLoopsResult.get(), StartLoc, LParenLoc, EndLoc);
8601 }
8602 
8603 OMPClause *Sema::ActOnOpenMPOrderedClause(SourceLocation StartLoc,
8604                                           SourceLocation EndLoc,
8605                                           SourceLocation LParenLoc,
8606                                           Expr *NumForLoops) {
8607   // OpenMP [2.7.1, loop construct, Description]
8608   // OpenMP [2.8.1, simd construct, Description]
8609   // OpenMP [2.9.6, distribute construct, Description]
8610   // The parameter of the ordered clause must be a constant
8611   // positive integer expression if any.
8612   if (NumForLoops && LParenLoc.isValid()) {
8613     ExprResult NumForLoopsResult =
8614         VerifyPositiveIntegerConstantInClause(NumForLoops, OMPC_ordered);
8615     if (NumForLoopsResult.isInvalid())
8616       return nullptr;
8617     NumForLoops = NumForLoopsResult.get();
8618   } else {
8619     NumForLoops = nullptr;
8620   }
8621   DSAStack->setOrderedRegion(/*IsOrdered=*/true, NumForLoops);
8622   return new (Context)
8623       OMPOrderedClause(NumForLoops, StartLoc, LParenLoc, EndLoc);
8624 }
8625 
8626 OMPClause *Sema::ActOnOpenMPSimpleClause(
8627     OpenMPClauseKind Kind, unsigned Argument, SourceLocation ArgumentLoc,
8628     SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc) {
8629   OMPClause *Res = nullptr;
8630   switch (Kind) {
8631   case OMPC_default:
8632     Res =
8633         ActOnOpenMPDefaultClause(static_cast<OpenMPDefaultClauseKind>(Argument),
8634                                  ArgumentLoc, StartLoc, LParenLoc, EndLoc);
8635     break;
8636   case OMPC_proc_bind:
8637     Res = ActOnOpenMPProcBindClause(
8638         static_cast<OpenMPProcBindClauseKind>(Argument), ArgumentLoc, StartLoc,
8639         LParenLoc, EndLoc);
8640     break;
8641   case OMPC_if:
8642   case OMPC_final:
8643   case OMPC_num_threads:
8644   case OMPC_safelen:
8645   case OMPC_simdlen:
8646   case OMPC_collapse:
8647   case OMPC_schedule:
8648   case OMPC_private:
8649   case OMPC_firstprivate:
8650   case OMPC_lastprivate:
8651   case OMPC_shared:
8652   case OMPC_reduction:
8653   case OMPC_task_reduction:
8654   case OMPC_in_reduction:
8655   case OMPC_linear:
8656   case OMPC_aligned:
8657   case OMPC_copyin:
8658   case OMPC_copyprivate:
8659   case OMPC_ordered:
8660   case OMPC_nowait:
8661   case OMPC_untied:
8662   case OMPC_mergeable:
8663   case OMPC_threadprivate:
8664   case OMPC_flush:
8665   case OMPC_read:
8666   case OMPC_write:
8667   case OMPC_update:
8668   case OMPC_capture:
8669   case OMPC_seq_cst:
8670   case OMPC_depend:
8671   case OMPC_device:
8672   case OMPC_threads:
8673   case OMPC_simd:
8674   case OMPC_map:
8675   case OMPC_num_teams:
8676   case OMPC_thread_limit:
8677   case OMPC_priority:
8678   case OMPC_grainsize:
8679   case OMPC_nogroup:
8680   case OMPC_num_tasks:
8681   case OMPC_hint:
8682   case OMPC_dist_schedule:
8683   case OMPC_defaultmap:
8684   case OMPC_unknown:
8685   case OMPC_uniform:
8686   case OMPC_to:
8687   case OMPC_from:
8688   case OMPC_use_device_ptr:
8689   case OMPC_is_device_ptr:
8690     llvm_unreachable("Clause is not allowed.");
8691   }
8692   return Res;
8693 }
8694 
8695 static std::string
8696 getListOfPossibleValues(OpenMPClauseKind K, unsigned First, unsigned Last,
8697                         ArrayRef<unsigned> Exclude = llvm::None) {
8698   SmallString<256> Buffer;
8699   llvm::raw_svector_ostream Out(Buffer);
8700   unsigned Bound = Last >= 2 ? Last - 2 : 0;
8701   unsigned Skipped = Exclude.size();
8702   auto S = Exclude.begin(), E = Exclude.end();
8703   for (unsigned I = First; I < Last; ++I) {
8704     if (std::find(S, E, I) != E) {
8705       --Skipped;
8706       continue;
8707     }
8708     Out << "'" << getOpenMPSimpleClauseTypeName(K, I) << "'";
8709     if (I == Bound - Skipped)
8710       Out << " or ";
8711     else if (I != Bound + 1 - Skipped)
8712       Out << ", ";
8713   }
8714   return Out.str();
8715 }
8716 
8717 OMPClause *Sema::ActOnOpenMPDefaultClause(OpenMPDefaultClauseKind Kind,
8718                                           SourceLocation KindKwLoc,
8719                                           SourceLocation StartLoc,
8720                                           SourceLocation LParenLoc,
8721                                           SourceLocation EndLoc) {
8722   if (Kind == OMPC_DEFAULT_unknown) {
8723     static_assert(OMPC_DEFAULT_unknown > 0,
8724                   "OMPC_DEFAULT_unknown not greater than 0");
8725     Diag(KindKwLoc, diag::err_omp_unexpected_clause_value)
8726         << getListOfPossibleValues(OMPC_default, /*First=*/0,
8727                                    /*Last=*/OMPC_DEFAULT_unknown)
8728         << getOpenMPClauseName(OMPC_default);
8729     return nullptr;
8730   }
8731   switch (Kind) {
8732   case OMPC_DEFAULT_none:
8733     DSAStack->setDefaultDSANone(KindKwLoc);
8734     break;
8735   case OMPC_DEFAULT_shared:
8736     DSAStack->setDefaultDSAShared(KindKwLoc);
8737     break;
8738   case OMPC_DEFAULT_unknown:
8739     llvm_unreachable("Clause kind is not allowed.");
8740     break;
8741   }
8742   return new (Context)
8743       OMPDefaultClause(Kind, KindKwLoc, StartLoc, LParenLoc, EndLoc);
8744 }
8745 
8746 OMPClause *Sema::ActOnOpenMPProcBindClause(OpenMPProcBindClauseKind Kind,
8747                                            SourceLocation KindKwLoc,
8748                                            SourceLocation StartLoc,
8749                                            SourceLocation LParenLoc,
8750                                            SourceLocation EndLoc) {
8751   if (Kind == OMPC_PROC_BIND_unknown) {
8752     Diag(KindKwLoc, diag::err_omp_unexpected_clause_value)
8753         << getListOfPossibleValues(OMPC_proc_bind, /*First=*/0,
8754                                    /*Last=*/OMPC_PROC_BIND_unknown)
8755         << getOpenMPClauseName(OMPC_proc_bind);
8756     return nullptr;
8757   }
8758   return new (Context)
8759       OMPProcBindClause(Kind, KindKwLoc, StartLoc, LParenLoc, EndLoc);
8760 }
8761 
8762 OMPClause *Sema::ActOnOpenMPSingleExprWithArgClause(
8763     OpenMPClauseKind Kind, ArrayRef<unsigned> Argument, Expr *Expr,
8764     SourceLocation StartLoc, SourceLocation LParenLoc,
8765     ArrayRef<SourceLocation> ArgumentLoc, SourceLocation DelimLoc,
8766     SourceLocation EndLoc) {
8767   OMPClause *Res = nullptr;
8768   switch (Kind) {
8769   case OMPC_schedule:
8770     enum { Modifier1, Modifier2, ScheduleKind, NumberOfElements };
8771     assert(Argument.size() == NumberOfElements &&
8772            ArgumentLoc.size() == NumberOfElements);
8773     Res = ActOnOpenMPScheduleClause(
8774         static_cast<OpenMPScheduleClauseModifier>(Argument[Modifier1]),
8775         static_cast<OpenMPScheduleClauseModifier>(Argument[Modifier2]),
8776         static_cast<OpenMPScheduleClauseKind>(Argument[ScheduleKind]), Expr,
8777         StartLoc, LParenLoc, ArgumentLoc[Modifier1], ArgumentLoc[Modifier2],
8778         ArgumentLoc[ScheduleKind], DelimLoc, EndLoc);
8779     break;
8780   case OMPC_if:
8781     assert(Argument.size() == 1 && ArgumentLoc.size() == 1);
8782     Res = ActOnOpenMPIfClause(static_cast<OpenMPDirectiveKind>(Argument.back()),
8783                               Expr, StartLoc, LParenLoc, ArgumentLoc.back(),
8784                               DelimLoc, EndLoc);
8785     break;
8786   case OMPC_dist_schedule:
8787     Res = ActOnOpenMPDistScheduleClause(
8788         static_cast<OpenMPDistScheduleClauseKind>(Argument.back()), Expr,
8789         StartLoc, LParenLoc, ArgumentLoc.back(), DelimLoc, EndLoc);
8790     break;
8791   case OMPC_defaultmap:
8792     enum { Modifier, DefaultmapKind };
8793     Res = ActOnOpenMPDefaultmapClause(
8794         static_cast<OpenMPDefaultmapClauseModifier>(Argument[Modifier]),
8795         static_cast<OpenMPDefaultmapClauseKind>(Argument[DefaultmapKind]),
8796         StartLoc, LParenLoc, ArgumentLoc[Modifier], ArgumentLoc[DefaultmapKind],
8797         EndLoc);
8798     break;
8799   case OMPC_final:
8800   case OMPC_num_threads:
8801   case OMPC_safelen:
8802   case OMPC_simdlen:
8803   case OMPC_collapse:
8804   case OMPC_default:
8805   case OMPC_proc_bind:
8806   case OMPC_private:
8807   case OMPC_firstprivate:
8808   case OMPC_lastprivate:
8809   case OMPC_shared:
8810   case OMPC_reduction:
8811   case OMPC_task_reduction:
8812   case OMPC_in_reduction:
8813   case OMPC_linear:
8814   case OMPC_aligned:
8815   case OMPC_copyin:
8816   case OMPC_copyprivate:
8817   case OMPC_ordered:
8818   case OMPC_nowait:
8819   case OMPC_untied:
8820   case OMPC_mergeable:
8821   case OMPC_threadprivate:
8822   case OMPC_flush:
8823   case OMPC_read:
8824   case OMPC_write:
8825   case OMPC_update:
8826   case OMPC_capture:
8827   case OMPC_seq_cst:
8828   case OMPC_depend:
8829   case OMPC_device:
8830   case OMPC_threads:
8831   case OMPC_simd:
8832   case OMPC_map:
8833   case OMPC_num_teams:
8834   case OMPC_thread_limit:
8835   case OMPC_priority:
8836   case OMPC_grainsize:
8837   case OMPC_nogroup:
8838   case OMPC_num_tasks:
8839   case OMPC_hint:
8840   case OMPC_unknown:
8841   case OMPC_uniform:
8842   case OMPC_to:
8843   case OMPC_from:
8844   case OMPC_use_device_ptr:
8845   case OMPC_is_device_ptr:
8846     llvm_unreachable("Clause is not allowed.");
8847   }
8848   return Res;
8849 }
8850 
8851 static bool checkScheduleModifiers(Sema &S, OpenMPScheduleClauseModifier M1,
8852                                    OpenMPScheduleClauseModifier M2,
8853                                    SourceLocation M1Loc, SourceLocation M2Loc) {
8854   if (M1 == OMPC_SCHEDULE_MODIFIER_unknown && M1Loc.isValid()) {
8855     SmallVector<unsigned, 2> Excluded;
8856     if (M2 != OMPC_SCHEDULE_MODIFIER_unknown)
8857       Excluded.push_back(M2);
8858     if (M2 == OMPC_SCHEDULE_MODIFIER_nonmonotonic)
8859       Excluded.push_back(OMPC_SCHEDULE_MODIFIER_monotonic);
8860     if (M2 == OMPC_SCHEDULE_MODIFIER_monotonic)
8861       Excluded.push_back(OMPC_SCHEDULE_MODIFIER_nonmonotonic);
8862     S.Diag(M1Loc, diag::err_omp_unexpected_clause_value)
8863         << getListOfPossibleValues(OMPC_schedule,
8864                                    /*First=*/OMPC_SCHEDULE_MODIFIER_unknown + 1,
8865                                    /*Last=*/OMPC_SCHEDULE_MODIFIER_last,
8866                                    Excluded)
8867         << getOpenMPClauseName(OMPC_schedule);
8868     return true;
8869   }
8870   return false;
8871 }
8872 
8873 OMPClause *Sema::ActOnOpenMPScheduleClause(
8874     OpenMPScheduleClauseModifier M1, OpenMPScheduleClauseModifier M2,
8875     OpenMPScheduleClauseKind Kind, Expr *ChunkSize, SourceLocation StartLoc,
8876     SourceLocation LParenLoc, SourceLocation M1Loc, SourceLocation M2Loc,
8877     SourceLocation KindLoc, SourceLocation CommaLoc, SourceLocation EndLoc) {
8878   if (checkScheduleModifiers(*this, M1, M2, M1Loc, M2Loc) ||
8879       checkScheduleModifiers(*this, M2, M1, M2Loc, M1Loc))
8880     return nullptr;
8881   // OpenMP, 2.7.1, Loop Construct, Restrictions
8882   // Either the monotonic modifier or the nonmonotonic modifier can be specified
8883   // but not both.
8884   if ((M1 == M2 && M1 != OMPC_SCHEDULE_MODIFIER_unknown) ||
8885       (M1 == OMPC_SCHEDULE_MODIFIER_monotonic &&
8886        M2 == OMPC_SCHEDULE_MODIFIER_nonmonotonic) ||
8887       (M1 == OMPC_SCHEDULE_MODIFIER_nonmonotonic &&
8888        M2 == OMPC_SCHEDULE_MODIFIER_monotonic)) {
8889     Diag(M2Loc, diag::err_omp_unexpected_schedule_modifier)
8890         << getOpenMPSimpleClauseTypeName(OMPC_schedule, M2)
8891         << getOpenMPSimpleClauseTypeName(OMPC_schedule, M1);
8892     return nullptr;
8893   }
8894   if (Kind == OMPC_SCHEDULE_unknown) {
8895     std::string Values;
8896     if (M1Loc.isInvalid() && M2Loc.isInvalid()) {
8897       unsigned Exclude[] = {OMPC_SCHEDULE_unknown};
8898       Values = getListOfPossibleValues(OMPC_schedule, /*First=*/0,
8899                                        /*Last=*/OMPC_SCHEDULE_MODIFIER_last,
8900                                        Exclude);
8901     } else {
8902       Values = getListOfPossibleValues(OMPC_schedule, /*First=*/0,
8903                                        /*Last=*/OMPC_SCHEDULE_unknown);
8904     }
8905     Diag(KindLoc, diag::err_omp_unexpected_clause_value)
8906         << Values << getOpenMPClauseName(OMPC_schedule);
8907     return nullptr;
8908   }
8909   // OpenMP, 2.7.1, Loop Construct, Restrictions
8910   // The nonmonotonic modifier can only be specified with schedule(dynamic) or
8911   // schedule(guided).
8912   if ((M1 == OMPC_SCHEDULE_MODIFIER_nonmonotonic ||
8913        M2 == OMPC_SCHEDULE_MODIFIER_nonmonotonic) &&
8914       Kind != OMPC_SCHEDULE_dynamic && Kind != OMPC_SCHEDULE_guided) {
8915     Diag(M1 == OMPC_SCHEDULE_MODIFIER_nonmonotonic ? M1Loc : M2Loc,
8916          diag::err_omp_schedule_nonmonotonic_static);
8917     return nullptr;
8918   }
8919   Expr *ValExpr = ChunkSize;
8920   Stmt *HelperValStmt = nullptr;
8921   if (ChunkSize) {
8922     if (!ChunkSize->isValueDependent() && !ChunkSize->isTypeDependent() &&
8923         !ChunkSize->isInstantiationDependent() &&
8924         !ChunkSize->containsUnexpandedParameterPack()) {
8925       SourceLocation ChunkSizeLoc = ChunkSize->getLocStart();
8926       ExprResult Val =
8927           PerformOpenMPImplicitIntegerConversion(ChunkSizeLoc, ChunkSize);
8928       if (Val.isInvalid())
8929         return nullptr;
8930 
8931       ValExpr = Val.get();
8932 
8933       // OpenMP [2.7.1, Restrictions]
8934       //  chunk_size must be a loop invariant integer expression with a positive
8935       //  value.
8936       llvm::APSInt Result;
8937       if (ValExpr->isIntegerConstantExpr(Result, Context)) {
8938         if (Result.isSigned() && !Result.isStrictlyPositive()) {
8939           Diag(ChunkSizeLoc, diag::err_omp_negative_expression_in_clause)
8940               << "schedule" << 1 << ChunkSize->getSourceRange();
8941           return nullptr;
8942         }
8943       } else if (getOpenMPCaptureRegionForClause(
8944                      DSAStack->getCurrentDirective(), OMPC_schedule) !=
8945                      OMPD_unknown &&
8946                  !CurContext->isDependentContext()) {
8947         ValExpr = MakeFullExpr(ValExpr).get();
8948         llvm::MapVector<const Expr *, DeclRefExpr *> Captures;
8949         ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
8950         HelperValStmt = buildPreInits(Context, Captures);
8951       }
8952     }
8953   }
8954 
8955   return new (Context)
8956       OMPScheduleClause(StartLoc, LParenLoc, KindLoc, CommaLoc, EndLoc, Kind,
8957                         ValExpr, HelperValStmt, M1, M1Loc, M2, M2Loc);
8958 }
8959 
8960 OMPClause *Sema::ActOnOpenMPClause(OpenMPClauseKind Kind,
8961                                    SourceLocation StartLoc,
8962                                    SourceLocation EndLoc) {
8963   OMPClause *Res = nullptr;
8964   switch (Kind) {
8965   case OMPC_ordered:
8966     Res = ActOnOpenMPOrderedClause(StartLoc, EndLoc);
8967     break;
8968   case OMPC_nowait:
8969     Res = ActOnOpenMPNowaitClause(StartLoc, EndLoc);
8970     break;
8971   case OMPC_untied:
8972     Res = ActOnOpenMPUntiedClause(StartLoc, EndLoc);
8973     break;
8974   case OMPC_mergeable:
8975     Res = ActOnOpenMPMergeableClause(StartLoc, EndLoc);
8976     break;
8977   case OMPC_read:
8978     Res = ActOnOpenMPReadClause(StartLoc, EndLoc);
8979     break;
8980   case OMPC_write:
8981     Res = ActOnOpenMPWriteClause(StartLoc, EndLoc);
8982     break;
8983   case OMPC_update:
8984     Res = ActOnOpenMPUpdateClause(StartLoc, EndLoc);
8985     break;
8986   case OMPC_capture:
8987     Res = ActOnOpenMPCaptureClause(StartLoc, EndLoc);
8988     break;
8989   case OMPC_seq_cst:
8990     Res = ActOnOpenMPSeqCstClause(StartLoc, EndLoc);
8991     break;
8992   case OMPC_threads:
8993     Res = ActOnOpenMPThreadsClause(StartLoc, EndLoc);
8994     break;
8995   case OMPC_simd:
8996     Res = ActOnOpenMPSIMDClause(StartLoc, EndLoc);
8997     break;
8998   case OMPC_nogroup:
8999     Res = ActOnOpenMPNogroupClause(StartLoc, EndLoc);
9000     break;
9001   case OMPC_if:
9002   case OMPC_final:
9003   case OMPC_num_threads:
9004   case OMPC_safelen:
9005   case OMPC_simdlen:
9006   case OMPC_collapse:
9007   case OMPC_schedule:
9008   case OMPC_private:
9009   case OMPC_firstprivate:
9010   case OMPC_lastprivate:
9011   case OMPC_shared:
9012   case OMPC_reduction:
9013   case OMPC_task_reduction:
9014   case OMPC_in_reduction:
9015   case OMPC_linear:
9016   case OMPC_aligned:
9017   case OMPC_copyin:
9018   case OMPC_copyprivate:
9019   case OMPC_default:
9020   case OMPC_proc_bind:
9021   case OMPC_threadprivate:
9022   case OMPC_flush:
9023   case OMPC_depend:
9024   case OMPC_device:
9025   case OMPC_map:
9026   case OMPC_num_teams:
9027   case OMPC_thread_limit:
9028   case OMPC_priority:
9029   case OMPC_grainsize:
9030   case OMPC_num_tasks:
9031   case OMPC_hint:
9032   case OMPC_dist_schedule:
9033   case OMPC_defaultmap:
9034   case OMPC_unknown:
9035   case OMPC_uniform:
9036   case OMPC_to:
9037   case OMPC_from:
9038   case OMPC_use_device_ptr:
9039   case OMPC_is_device_ptr:
9040     llvm_unreachable("Clause is not allowed.");
9041   }
9042   return Res;
9043 }
9044 
9045 OMPClause *Sema::ActOnOpenMPNowaitClause(SourceLocation StartLoc,
9046                                          SourceLocation EndLoc) {
9047   DSAStack->setNowaitRegion();
9048   return new (Context) OMPNowaitClause(StartLoc, EndLoc);
9049 }
9050 
9051 OMPClause *Sema::ActOnOpenMPUntiedClause(SourceLocation StartLoc,
9052                                          SourceLocation EndLoc) {
9053   return new (Context) OMPUntiedClause(StartLoc, EndLoc);
9054 }
9055 
9056 OMPClause *Sema::ActOnOpenMPMergeableClause(SourceLocation StartLoc,
9057                                             SourceLocation EndLoc) {
9058   return new (Context) OMPMergeableClause(StartLoc, EndLoc);
9059 }
9060 
9061 OMPClause *Sema::ActOnOpenMPReadClause(SourceLocation StartLoc,
9062                                        SourceLocation EndLoc) {
9063   return new (Context) OMPReadClause(StartLoc, EndLoc);
9064 }
9065 
9066 OMPClause *Sema::ActOnOpenMPWriteClause(SourceLocation StartLoc,
9067                                         SourceLocation EndLoc) {
9068   return new (Context) OMPWriteClause(StartLoc, EndLoc);
9069 }
9070 
9071 OMPClause *Sema::ActOnOpenMPUpdateClause(SourceLocation StartLoc,
9072                                          SourceLocation EndLoc) {
9073   return new (Context) OMPUpdateClause(StartLoc, EndLoc);
9074 }
9075 
9076 OMPClause *Sema::ActOnOpenMPCaptureClause(SourceLocation StartLoc,
9077                                           SourceLocation EndLoc) {
9078   return new (Context) OMPCaptureClause(StartLoc, EndLoc);
9079 }
9080 
9081 OMPClause *Sema::ActOnOpenMPSeqCstClause(SourceLocation StartLoc,
9082                                          SourceLocation EndLoc) {
9083   return new (Context) OMPSeqCstClause(StartLoc, EndLoc);
9084 }
9085 
9086 OMPClause *Sema::ActOnOpenMPThreadsClause(SourceLocation StartLoc,
9087                                           SourceLocation EndLoc) {
9088   return new (Context) OMPThreadsClause(StartLoc, EndLoc);
9089 }
9090 
9091 OMPClause *Sema::ActOnOpenMPSIMDClause(SourceLocation StartLoc,
9092                                        SourceLocation EndLoc) {
9093   return new (Context) OMPSIMDClause(StartLoc, EndLoc);
9094 }
9095 
9096 OMPClause *Sema::ActOnOpenMPNogroupClause(SourceLocation StartLoc,
9097                                           SourceLocation EndLoc) {
9098   return new (Context) OMPNogroupClause(StartLoc, EndLoc);
9099 }
9100 
9101 OMPClause *Sema::ActOnOpenMPVarListClause(
9102     OpenMPClauseKind Kind, ArrayRef<Expr *> VarList, Expr *TailExpr,
9103     SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation ColonLoc,
9104     SourceLocation EndLoc, CXXScopeSpec &ReductionIdScopeSpec,
9105     const DeclarationNameInfo &ReductionId, OpenMPDependClauseKind DepKind,
9106     OpenMPLinearClauseKind LinKind, OpenMPMapClauseKind MapTypeModifier,
9107     OpenMPMapClauseKind MapType, bool IsMapTypeImplicit,
9108     SourceLocation DepLinMapLoc) {
9109   OMPClause *Res = nullptr;
9110   switch (Kind) {
9111   case OMPC_private:
9112     Res = ActOnOpenMPPrivateClause(VarList, StartLoc, LParenLoc, EndLoc);
9113     break;
9114   case OMPC_firstprivate:
9115     Res = ActOnOpenMPFirstprivateClause(VarList, StartLoc, LParenLoc, EndLoc);
9116     break;
9117   case OMPC_lastprivate:
9118     Res = ActOnOpenMPLastprivateClause(VarList, StartLoc, LParenLoc, EndLoc);
9119     break;
9120   case OMPC_shared:
9121     Res = ActOnOpenMPSharedClause(VarList, StartLoc, LParenLoc, EndLoc);
9122     break;
9123   case OMPC_reduction:
9124     Res = ActOnOpenMPReductionClause(VarList, StartLoc, LParenLoc, ColonLoc,
9125                                      EndLoc, ReductionIdScopeSpec, ReductionId);
9126     break;
9127   case OMPC_task_reduction:
9128     Res = ActOnOpenMPTaskReductionClause(VarList, StartLoc, LParenLoc, ColonLoc,
9129                                          EndLoc, ReductionIdScopeSpec,
9130                                          ReductionId);
9131     break;
9132   case OMPC_in_reduction:
9133     Res =
9134         ActOnOpenMPInReductionClause(VarList, StartLoc, LParenLoc, ColonLoc,
9135                                      EndLoc, ReductionIdScopeSpec, ReductionId);
9136     break;
9137   case OMPC_linear:
9138     Res = ActOnOpenMPLinearClause(VarList, TailExpr, StartLoc, LParenLoc,
9139                                   LinKind, DepLinMapLoc, ColonLoc, EndLoc);
9140     break;
9141   case OMPC_aligned:
9142     Res = ActOnOpenMPAlignedClause(VarList, TailExpr, StartLoc, LParenLoc,
9143                                    ColonLoc, EndLoc);
9144     break;
9145   case OMPC_copyin:
9146     Res = ActOnOpenMPCopyinClause(VarList, StartLoc, LParenLoc, EndLoc);
9147     break;
9148   case OMPC_copyprivate:
9149     Res = ActOnOpenMPCopyprivateClause(VarList, StartLoc, LParenLoc, EndLoc);
9150     break;
9151   case OMPC_flush:
9152     Res = ActOnOpenMPFlushClause(VarList, StartLoc, LParenLoc, EndLoc);
9153     break;
9154   case OMPC_depend:
9155     Res = ActOnOpenMPDependClause(DepKind, DepLinMapLoc, ColonLoc, VarList,
9156                                   StartLoc, LParenLoc, EndLoc);
9157     break;
9158   case OMPC_map:
9159     Res = ActOnOpenMPMapClause(MapTypeModifier, MapType, IsMapTypeImplicit,
9160                                DepLinMapLoc, ColonLoc, VarList, StartLoc,
9161                                LParenLoc, EndLoc);
9162     break;
9163   case OMPC_to:
9164     Res = ActOnOpenMPToClause(VarList, StartLoc, LParenLoc, EndLoc);
9165     break;
9166   case OMPC_from:
9167     Res = ActOnOpenMPFromClause(VarList, StartLoc, LParenLoc, EndLoc);
9168     break;
9169   case OMPC_use_device_ptr:
9170     Res = ActOnOpenMPUseDevicePtrClause(VarList, StartLoc, LParenLoc, EndLoc);
9171     break;
9172   case OMPC_is_device_ptr:
9173     Res = ActOnOpenMPIsDevicePtrClause(VarList, StartLoc, LParenLoc, EndLoc);
9174     break;
9175   case OMPC_if:
9176   case OMPC_final:
9177   case OMPC_num_threads:
9178   case OMPC_safelen:
9179   case OMPC_simdlen:
9180   case OMPC_collapse:
9181   case OMPC_default:
9182   case OMPC_proc_bind:
9183   case OMPC_schedule:
9184   case OMPC_ordered:
9185   case OMPC_nowait:
9186   case OMPC_untied:
9187   case OMPC_mergeable:
9188   case OMPC_threadprivate:
9189   case OMPC_read:
9190   case OMPC_write:
9191   case OMPC_update:
9192   case OMPC_capture:
9193   case OMPC_seq_cst:
9194   case OMPC_device:
9195   case OMPC_threads:
9196   case OMPC_simd:
9197   case OMPC_num_teams:
9198   case OMPC_thread_limit:
9199   case OMPC_priority:
9200   case OMPC_grainsize:
9201   case OMPC_nogroup:
9202   case OMPC_num_tasks:
9203   case OMPC_hint:
9204   case OMPC_dist_schedule:
9205   case OMPC_defaultmap:
9206   case OMPC_unknown:
9207   case OMPC_uniform:
9208     llvm_unreachable("Clause is not allowed.");
9209   }
9210   return Res;
9211 }
9212 
9213 ExprResult Sema::getOpenMPCapturedExpr(VarDecl *Capture, ExprValueKind VK,
9214                                        ExprObjectKind OK, SourceLocation Loc) {
9215   ExprResult Res = BuildDeclRefExpr(
9216       Capture, Capture->getType().getNonReferenceType(), VK_LValue, Loc);
9217   if (!Res.isUsable())
9218     return ExprError();
9219   if (OK == OK_Ordinary && !getLangOpts().CPlusPlus) {
9220     Res = CreateBuiltinUnaryOp(Loc, UO_Deref, Res.get());
9221     if (!Res.isUsable())
9222       return ExprError();
9223   }
9224   if (VK != VK_LValue && Res.get()->isGLValue()) {
9225     Res = DefaultLvalueConversion(Res.get());
9226     if (!Res.isUsable())
9227       return ExprError();
9228   }
9229   return Res;
9230 }
9231 
9232 static std::pair<ValueDecl *, bool>
9233 getPrivateItem(Sema &S, Expr *&RefExpr, SourceLocation &ELoc,
9234                SourceRange &ERange, bool AllowArraySection = false) {
9235   if (RefExpr->isTypeDependent() || RefExpr->isValueDependent() ||
9236       RefExpr->containsUnexpandedParameterPack())
9237     return std::make_pair(nullptr, true);
9238 
9239   // OpenMP [3.1, C/C++]
9240   //  A list item is a variable name.
9241   // OpenMP  [2.9.3.3, Restrictions, p.1]
9242   //  A variable that is part of another variable (as an array or
9243   //  structure element) cannot appear in a private clause.
9244   RefExpr = RefExpr->IgnoreParens();
9245   enum {
9246     NoArrayExpr = -1,
9247     ArraySubscript = 0,
9248     OMPArraySection = 1
9249   } IsArrayExpr = NoArrayExpr;
9250   if (AllowArraySection) {
9251     if (auto *ASE = dyn_cast_or_null<ArraySubscriptExpr>(RefExpr)) {
9252       Expr *Base = ASE->getBase()->IgnoreParenImpCasts();
9253       while (auto *TempASE = dyn_cast<ArraySubscriptExpr>(Base))
9254         Base = TempASE->getBase()->IgnoreParenImpCasts();
9255       RefExpr = Base;
9256       IsArrayExpr = ArraySubscript;
9257     } else if (auto *OASE = dyn_cast_or_null<OMPArraySectionExpr>(RefExpr)) {
9258       Expr *Base = OASE->getBase()->IgnoreParenImpCasts();
9259       while (auto *TempOASE = dyn_cast<OMPArraySectionExpr>(Base))
9260         Base = TempOASE->getBase()->IgnoreParenImpCasts();
9261       while (auto *TempASE = dyn_cast<ArraySubscriptExpr>(Base))
9262         Base = TempASE->getBase()->IgnoreParenImpCasts();
9263       RefExpr = Base;
9264       IsArrayExpr = OMPArraySection;
9265     }
9266   }
9267   ELoc = RefExpr->getExprLoc();
9268   ERange = RefExpr->getSourceRange();
9269   RefExpr = RefExpr->IgnoreParenImpCasts();
9270   auto *DE = dyn_cast_or_null<DeclRefExpr>(RefExpr);
9271   auto *ME = dyn_cast_or_null<MemberExpr>(RefExpr);
9272   if ((!DE || !isa<VarDecl>(DE->getDecl())) &&
9273       (S.getCurrentThisType().isNull() || !ME ||
9274        !isa<CXXThisExpr>(ME->getBase()->IgnoreParenImpCasts()) ||
9275        !isa<FieldDecl>(ME->getMemberDecl()))) {
9276     if (IsArrayExpr != NoArrayExpr) {
9277       S.Diag(ELoc, diag::err_omp_expected_base_var_name) << IsArrayExpr
9278                                                          << ERange;
9279     } else {
9280       S.Diag(ELoc,
9281              AllowArraySection
9282                  ? diag::err_omp_expected_var_name_member_expr_or_array_item
9283                  : diag::err_omp_expected_var_name_member_expr)
9284           << (S.getCurrentThisType().isNull() ? 0 : 1) << ERange;
9285     }
9286     return std::make_pair(nullptr, false);
9287   }
9288   return std::make_pair(
9289       getCanonicalDecl(DE ? DE->getDecl() : ME->getMemberDecl()), false);
9290 }
9291 
9292 OMPClause *Sema::ActOnOpenMPPrivateClause(ArrayRef<Expr *> VarList,
9293                                           SourceLocation StartLoc,
9294                                           SourceLocation LParenLoc,
9295                                           SourceLocation EndLoc) {
9296   SmallVector<Expr *, 8> Vars;
9297   SmallVector<Expr *, 8> PrivateCopies;
9298   for (Expr *RefExpr : VarList) {
9299     assert(RefExpr && "NULL expr in OpenMP private clause.");
9300     SourceLocation ELoc;
9301     SourceRange ERange;
9302     Expr *SimpleRefExpr = RefExpr;
9303     auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
9304     if (Res.second) {
9305       // It will be analyzed later.
9306       Vars.push_back(RefExpr);
9307       PrivateCopies.push_back(nullptr);
9308     }
9309     ValueDecl *D = Res.first;
9310     if (!D)
9311       continue;
9312 
9313     QualType Type = D->getType();
9314     auto *VD = dyn_cast<VarDecl>(D);
9315 
9316     // OpenMP [2.9.3.3, Restrictions, C/C++, p.3]
9317     //  A variable that appears in a private clause must not have an incomplete
9318     //  type or a reference type.
9319     if (RequireCompleteType(ELoc, Type, diag::err_omp_private_incomplete_type))
9320       continue;
9321     Type = Type.getNonReferenceType();
9322 
9323     // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
9324     // in a Construct]
9325     //  Variables with the predetermined data-sharing attributes may not be
9326     //  listed in data-sharing attributes clauses, except for the cases
9327     //  listed below. For these exceptions only, listing a predetermined
9328     //  variable in a data-sharing attribute clause is allowed and overrides
9329     //  the variable's predetermined data-sharing attributes.
9330     DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, /*FromParent=*/false);
9331     if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_private) {
9332       Diag(ELoc, diag::err_omp_wrong_dsa) << getOpenMPClauseName(DVar.CKind)
9333                                           << getOpenMPClauseName(OMPC_private);
9334       reportOriginalDsa(*this, DSAStack, D, DVar);
9335       continue;
9336     }
9337 
9338     OpenMPDirectiveKind CurrDir = DSAStack->getCurrentDirective();
9339     // Variably modified types are not supported for tasks.
9340     if (!Type->isAnyPointerType() && Type->isVariablyModifiedType() &&
9341         isOpenMPTaskingDirective(CurrDir)) {
9342       Diag(ELoc, diag::err_omp_variably_modified_type_not_supported)
9343           << getOpenMPClauseName(OMPC_private) << Type
9344           << getOpenMPDirectiveName(CurrDir);
9345       bool IsDecl =
9346           !VD ||
9347           VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
9348       Diag(D->getLocation(),
9349            IsDecl ? diag::note_previous_decl : diag::note_defined_here)
9350           << D;
9351       continue;
9352     }
9353 
9354     // OpenMP 4.5 [2.15.5.1, Restrictions, p.3]
9355     // A list item cannot appear in both a map clause and a data-sharing
9356     // attribute clause on the same construct
9357     if (isOpenMPTargetExecutionDirective(CurrDir)) {
9358       OpenMPClauseKind ConflictKind;
9359       if (DSAStack->checkMappableExprComponentListsForDecl(
9360               VD, /*CurrentRegionOnly=*/true,
9361               [&](OMPClauseMappableExprCommon::MappableExprComponentListRef,
9362                   OpenMPClauseKind WhereFoundClauseKind) -> bool {
9363                 ConflictKind = WhereFoundClauseKind;
9364                 return true;
9365               })) {
9366         Diag(ELoc, diag::err_omp_variable_in_given_clause_and_dsa)
9367             << getOpenMPClauseName(OMPC_private)
9368             << getOpenMPClauseName(ConflictKind)
9369             << getOpenMPDirectiveName(CurrDir);
9370         reportOriginalDsa(*this, DSAStack, D, DVar);
9371         continue;
9372       }
9373     }
9374 
9375     // OpenMP [2.9.3.3, Restrictions, C/C++, p.1]
9376     //  A variable of class type (or array thereof) that appears in a private
9377     //  clause requires an accessible, unambiguous default constructor for the
9378     //  class type.
9379     // Generate helper private variable and initialize it with the default
9380     // value. The address of the original variable is replaced by the address of
9381     // the new private variable in CodeGen. This new variable is not added to
9382     // IdResolver, so the code in the OpenMP region uses original variable for
9383     // proper diagnostics.
9384     Type = Type.getUnqualifiedType();
9385     VarDecl *VDPrivate =
9386         buildVarDecl(*this, ELoc, Type, D->getName(),
9387                      D->hasAttrs() ? &D->getAttrs() : nullptr,
9388                      VD ? cast<DeclRefExpr>(SimpleRefExpr) : nullptr);
9389     ActOnUninitializedDecl(VDPrivate);
9390     if (VDPrivate->isInvalidDecl())
9391       continue;
9392     DeclRefExpr *VDPrivateRefExpr = buildDeclRefExpr(
9393         *this, VDPrivate, RefExpr->getType().getUnqualifiedType(), ELoc);
9394 
9395     DeclRefExpr *Ref = nullptr;
9396     if (!VD && !CurContext->isDependentContext())
9397       Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/false);
9398     DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_private, Ref);
9399     Vars.push_back((VD || CurContext->isDependentContext())
9400                        ? RefExpr->IgnoreParens()
9401                        : Ref);
9402     PrivateCopies.push_back(VDPrivateRefExpr);
9403   }
9404 
9405   if (Vars.empty())
9406     return nullptr;
9407 
9408   return OMPPrivateClause::Create(Context, StartLoc, LParenLoc, EndLoc, Vars,
9409                                   PrivateCopies);
9410 }
9411 
9412 namespace {
9413 class DiagsUninitializedSeveretyRAII {
9414 private:
9415   DiagnosticsEngine &Diags;
9416   SourceLocation SavedLoc;
9417   bool IsIgnored = false;
9418 
9419 public:
9420   DiagsUninitializedSeveretyRAII(DiagnosticsEngine &Diags, SourceLocation Loc,
9421                                  bool IsIgnored)
9422       : Diags(Diags), SavedLoc(Loc), IsIgnored(IsIgnored) {
9423     if (!IsIgnored) {
9424       Diags.setSeverity(/*Diag*/ diag::warn_uninit_self_reference_in_init,
9425                         /*Map*/ diag::Severity::Ignored, Loc);
9426     }
9427   }
9428   ~DiagsUninitializedSeveretyRAII() {
9429     if (!IsIgnored)
9430       Diags.popMappings(SavedLoc);
9431   }
9432 };
9433 }
9434 
9435 OMPClause *Sema::ActOnOpenMPFirstprivateClause(ArrayRef<Expr *> VarList,
9436                                                SourceLocation StartLoc,
9437                                                SourceLocation LParenLoc,
9438                                                SourceLocation EndLoc) {
9439   SmallVector<Expr *, 8> Vars;
9440   SmallVector<Expr *, 8> PrivateCopies;
9441   SmallVector<Expr *, 8> Inits;
9442   SmallVector<Decl *, 4> ExprCaptures;
9443   bool IsImplicitClause =
9444       StartLoc.isInvalid() && LParenLoc.isInvalid() && EndLoc.isInvalid();
9445   SourceLocation ImplicitClauseLoc = DSAStack->getConstructLoc();
9446 
9447   for (Expr *RefExpr : VarList) {
9448     assert(RefExpr && "NULL expr in OpenMP firstprivate clause.");
9449     SourceLocation ELoc;
9450     SourceRange ERange;
9451     Expr *SimpleRefExpr = RefExpr;
9452     auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
9453     if (Res.second) {
9454       // It will be analyzed later.
9455       Vars.push_back(RefExpr);
9456       PrivateCopies.push_back(nullptr);
9457       Inits.push_back(nullptr);
9458     }
9459     ValueDecl *D = Res.first;
9460     if (!D)
9461       continue;
9462 
9463     ELoc = IsImplicitClause ? ImplicitClauseLoc : ELoc;
9464     QualType Type = D->getType();
9465     auto *VD = dyn_cast<VarDecl>(D);
9466 
9467     // OpenMP [2.9.3.3, Restrictions, C/C++, p.3]
9468     //  A variable that appears in a private clause must not have an incomplete
9469     //  type or a reference type.
9470     if (RequireCompleteType(ELoc, Type,
9471                             diag::err_omp_firstprivate_incomplete_type))
9472       continue;
9473     Type = Type.getNonReferenceType();
9474 
9475     // OpenMP [2.9.3.4, Restrictions, C/C++, p.1]
9476     //  A variable of class type (or array thereof) that appears in a private
9477     //  clause requires an accessible, unambiguous copy constructor for the
9478     //  class type.
9479     QualType ElemType = Context.getBaseElementType(Type).getNonReferenceType();
9480 
9481     // If an implicit firstprivate variable found it was checked already.
9482     DSAStackTy::DSAVarData TopDVar;
9483     if (!IsImplicitClause) {
9484       DSAStackTy::DSAVarData DVar =
9485           DSAStack->getTopDSA(D, /*FromParent=*/false);
9486       TopDVar = DVar;
9487       OpenMPDirectiveKind CurrDir = DSAStack->getCurrentDirective();
9488       bool IsConstant = ElemType.isConstant(Context);
9489       // OpenMP [2.4.13, Data-sharing Attribute Clauses]
9490       //  A list item that specifies a given variable may not appear in more
9491       // than one clause on the same directive, except that a variable may be
9492       //  specified in both firstprivate and lastprivate clauses.
9493       // OpenMP 4.5 [2.10.8, Distribute Construct, p.3]
9494       // A list item may appear in a firstprivate or lastprivate clause but not
9495       // both.
9496       if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_firstprivate &&
9497           (isOpenMPDistributeDirective(CurrDir) ||
9498            DVar.CKind != OMPC_lastprivate) &&
9499           DVar.RefExpr) {
9500         Diag(ELoc, diag::err_omp_wrong_dsa)
9501             << getOpenMPClauseName(DVar.CKind)
9502             << getOpenMPClauseName(OMPC_firstprivate);
9503         reportOriginalDsa(*this, DSAStack, D, DVar);
9504         continue;
9505       }
9506 
9507       // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
9508       // in a Construct]
9509       //  Variables with the predetermined data-sharing attributes may not be
9510       //  listed in data-sharing attributes clauses, except for the cases
9511       //  listed below. For these exceptions only, listing a predetermined
9512       //  variable in a data-sharing attribute clause is allowed and overrides
9513       //  the variable's predetermined data-sharing attributes.
9514       // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
9515       // in a Construct, C/C++, p.2]
9516       //  Variables with const-qualified type having no mutable member may be
9517       //  listed in a firstprivate clause, even if they are static data members.
9518       if (!(IsConstant || (VD && VD->isStaticDataMember())) && !DVar.RefExpr &&
9519           DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_shared) {
9520         Diag(ELoc, diag::err_omp_wrong_dsa)
9521             << getOpenMPClauseName(DVar.CKind)
9522             << getOpenMPClauseName(OMPC_firstprivate);
9523         reportOriginalDsa(*this, DSAStack, D, DVar);
9524         continue;
9525       }
9526 
9527       // OpenMP [2.9.3.4, Restrictions, p.2]
9528       //  A list item that is private within a parallel region must not appear
9529       //  in a firstprivate clause on a worksharing construct if any of the
9530       //  worksharing regions arising from the worksharing construct ever bind
9531       //  to any of the parallel regions arising from the parallel construct.
9532       // OpenMP 4.5 [2.15.3.4, Restrictions, p.3]
9533       // A list item that is private within a teams region must not appear in a
9534       // firstprivate clause on a distribute construct if any of the distribute
9535       // regions arising from the distribute construct ever bind to any of the
9536       // teams regions arising from the teams construct.
9537       // OpenMP 4.5 [2.15.3.4, Restrictions, p.3]
9538       // A list item that appears in a reduction clause of a teams construct
9539       // must not appear in a firstprivate clause on a distribute construct if
9540       // any of the distribute regions arising from the distribute construct
9541       // ever bind to any of the teams regions arising from the teams construct.
9542       if ((isOpenMPWorksharingDirective(CurrDir) ||
9543            isOpenMPDistributeDirective(CurrDir)) &&
9544           !isOpenMPParallelDirective(CurrDir) &&
9545           !isOpenMPTeamsDirective(CurrDir)) {
9546         DVar = DSAStack->getImplicitDSA(D, true);
9547         if (DVar.CKind != OMPC_shared &&
9548             (isOpenMPParallelDirective(DVar.DKind) ||
9549              isOpenMPTeamsDirective(DVar.DKind) ||
9550              DVar.DKind == OMPD_unknown)) {
9551           Diag(ELoc, diag::err_omp_required_access)
9552               << getOpenMPClauseName(OMPC_firstprivate)
9553               << getOpenMPClauseName(OMPC_shared);
9554           reportOriginalDsa(*this, DSAStack, D, DVar);
9555           continue;
9556         }
9557       }
9558       // OpenMP [2.9.3.4, Restrictions, p.3]
9559       //  A list item that appears in a reduction clause of a parallel construct
9560       //  must not appear in a firstprivate clause on a worksharing or task
9561       //  construct if any of the worksharing or task regions arising from the
9562       //  worksharing or task construct ever bind to any of the parallel regions
9563       //  arising from the parallel construct.
9564       // OpenMP [2.9.3.4, Restrictions, p.4]
9565       //  A list item that appears in a reduction clause in worksharing
9566       //  construct must not appear in a firstprivate clause in a task construct
9567       //  encountered during execution of any of the worksharing regions arising
9568       //  from the worksharing construct.
9569       if (isOpenMPTaskingDirective(CurrDir)) {
9570         DVar = DSAStack->hasInnermostDSA(
9571             D, [](OpenMPClauseKind C) { return C == OMPC_reduction; },
9572             [](OpenMPDirectiveKind K) {
9573               return isOpenMPParallelDirective(K) ||
9574                      isOpenMPWorksharingDirective(K) ||
9575                      isOpenMPTeamsDirective(K);
9576             },
9577             /*FromParent=*/true);
9578         if (DVar.CKind == OMPC_reduction &&
9579             (isOpenMPParallelDirective(DVar.DKind) ||
9580              isOpenMPWorksharingDirective(DVar.DKind) ||
9581              isOpenMPTeamsDirective(DVar.DKind))) {
9582           Diag(ELoc, diag::err_omp_parallel_reduction_in_task_firstprivate)
9583               << getOpenMPDirectiveName(DVar.DKind);
9584           reportOriginalDsa(*this, DSAStack, D, DVar);
9585           continue;
9586         }
9587       }
9588 
9589       // OpenMP 4.5 [2.15.5.1, Restrictions, p.3]
9590       // A list item cannot appear in both a map clause and a data-sharing
9591       // attribute clause on the same construct
9592       if (isOpenMPTargetExecutionDirective(CurrDir)) {
9593         OpenMPClauseKind ConflictKind;
9594         if (DSAStack->checkMappableExprComponentListsForDecl(
9595                 VD, /*CurrentRegionOnly=*/true,
9596                 [&ConflictKind](
9597                     OMPClauseMappableExprCommon::MappableExprComponentListRef,
9598                     OpenMPClauseKind WhereFoundClauseKind) {
9599                   ConflictKind = WhereFoundClauseKind;
9600                   return true;
9601                 })) {
9602           Diag(ELoc, diag::err_omp_variable_in_given_clause_and_dsa)
9603               << getOpenMPClauseName(OMPC_firstprivate)
9604               << getOpenMPClauseName(ConflictKind)
9605               << getOpenMPDirectiveName(DSAStack->getCurrentDirective());
9606           reportOriginalDsa(*this, DSAStack, D, DVar);
9607           continue;
9608         }
9609       }
9610     }
9611 
9612     // Variably modified types are not supported for tasks.
9613     if (!Type->isAnyPointerType() && Type->isVariablyModifiedType() &&
9614         isOpenMPTaskingDirective(DSAStack->getCurrentDirective())) {
9615       Diag(ELoc, diag::err_omp_variably_modified_type_not_supported)
9616           << getOpenMPClauseName(OMPC_firstprivate) << Type
9617           << getOpenMPDirectiveName(DSAStack->getCurrentDirective());
9618       bool IsDecl =
9619           !VD ||
9620           VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
9621       Diag(D->getLocation(),
9622            IsDecl ? diag::note_previous_decl : diag::note_defined_here)
9623           << D;
9624       continue;
9625     }
9626 
9627     Type = Type.getUnqualifiedType();
9628     VarDecl *VDPrivate =
9629         buildVarDecl(*this, ELoc, Type, D->getName(),
9630                      D->hasAttrs() ? &D->getAttrs() : nullptr,
9631                      VD ? cast<DeclRefExpr>(SimpleRefExpr) : nullptr);
9632     // Generate helper private variable and initialize it with the value of the
9633     // original variable. The address of the original variable is replaced by
9634     // the address of the new private variable in the CodeGen. This new variable
9635     // is not added to IdResolver, so the code in the OpenMP region uses
9636     // original variable for proper diagnostics and variable capturing.
9637     Expr *VDInitRefExpr = nullptr;
9638     // For arrays generate initializer for single element and replace it by the
9639     // original array element in CodeGen.
9640     if (Type->isArrayType()) {
9641       VarDecl *VDInit =
9642           buildVarDecl(*this, RefExpr->getExprLoc(), ElemType, D->getName());
9643       VDInitRefExpr = buildDeclRefExpr(*this, VDInit, ElemType, ELoc);
9644       Expr *Init = DefaultLvalueConversion(VDInitRefExpr).get();
9645       ElemType = ElemType.getUnqualifiedType();
9646       VarDecl *VDInitTemp = buildVarDecl(*this, RefExpr->getExprLoc(), ElemType,
9647                                          ".firstprivate.temp");
9648       InitializedEntity Entity =
9649           InitializedEntity::InitializeVariable(VDInitTemp);
9650       InitializationKind Kind = InitializationKind::CreateCopy(ELoc, ELoc);
9651 
9652       InitializationSequence InitSeq(*this, Entity, Kind, Init);
9653       ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Init);
9654       if (Result.isInvalid())
9655         VDPrivate->setInvalidDecl();
9656       else
9657         VDPrivate->setInit(Result.getAs<Expr>());
9658       // Remove temp variable declaration.
9659       Context.Deallocate(VDInitTemp);
9660     } else {
9661       VarDecl *VDInit = buildVarDecl(*this, RefExpr->getExprLoc(), Type,
9662                                      ".firstprivate.temp");
9663       VDInitRefExpr = buildDeclRefExpr(*this, VDInit, RefExpr->getType(),
9664                                        RefExpr->getExprLoc());
9665       AddInitializerToDecl(VDPrivate,
9666                            DefaultLvalueConversion(VDInitRefExpr).get(),
9667                            /*DirectInit=*/false);
9668     }
9669     if (VDPrivate->isInvalidDecl()) {
9670       if (IsImplicitClause) {
9671         Diag(RefExpr->getExprLoc(),
9672              diag::note_omp_task_predetermined_firstprivate_here);
9673       }
9674       continue;
9675     }
9676     CurContext->addDecl(VDPrivate);
9677     DeclRefExpr *VDPrivateRefExpr = buildDeclRefExpr(
9678         *this, VDPrivate, RefExpr->getType().getUnqualifiedType(),
9679         RefExpr->getExprLoc());
9680     DeclRefExpr *Ref = nullptr;
9681     if (!VD && !CurContext->isDependentContext()) {
9682       if (TopDVar.CKind == OMPC_lastprivate) {
9683         Ref = TopDVar.PrivateCopy;
9684       } else {
9685         Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/true);
9686         if (!isOpenMPCapturedDecl(D))
9687           ExprCaptures.push_back(Ref->getDecl());
9688       }
9689     }
9690     DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_firstprivate, Ref);
9691     Vars.push_back((VD || CurContext->isDependentContext())
9692                        ? RefExpr->IgnoreParens()
9693                        : Ref);
9694     PrivateCopies.push_back(VDPrivateRefExpr);
9695     Inits.push_back(VDInitRefExpr);
9696   }
9697 
9698   if (Vars.empty())
9699     return nullptr;
9700 
9701   return OMPFirstprivateClause::Create(Context, StartLoc, LParenLoc, EndLoc,
9702                                        Vars, PrivateCopies, Inits,
9703                                        buildPreInits(Context, ExprCaptures));
9704 }
9705 
9706 OMPClause *Sema::ActOnOpenMPLastprivateClause(ArrayRef<Expr *> VarList,
9707                                               SourceLocation StartLoc,
9708                                               SourceLocation LParenLoc,
9709                                               SourceLocation EndLoc) {
9710   SmallVector<Expr *, 8> Vars;
9711   SmallVector<Expr *, 8> SrcExprs;
9712   SmallVector<Expr *, 8> DstExprs;
9713   SmallVector<Expr *, 8> AssignmentOps;
9714   SmallVector<Decl *, 4> ExprCaptures;
9715   SmallVector<Expr *, 4> ExprPostUpdates;
9716   for (Expr *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       SrcExprs.push_back(nullptr);
9726       DstExprs.push_back(nullptr);
9727       AssignmentOps.push_back(nullptr);
9728     }
9729     ValueDecl *D = Res.first;
9730     if (!D)
9731       continue;
9732 
9733     QualType Type = D->getType();
9734     auto *VD = dyn_cast<VarDecl>(D);
9735 
9736     // OpenMP [2.14.3.5, Restrictions, C/C++, p.2]
9737     //  A variable that appears in a lastprivate clause must not have an
9738     //  incomplete type or a reference type.
9739     if (RequireCompleteType(ELoc, Type,
9740                             diag::err_omp_lastprivate_incomplete_type))
9741       continue;
9742     Type = Type.getNonReferenceType();
9743 
9744     OpenMPDirectiveKind CurrDir = DSAStack->getCurrentDirective();
9745     // OpenMP [2.14.1.1, Data-sharing Attribute Rules for Variables Referenced
9746     // in a Construct]
9747     //  Variables with the predetermined data-sharing attributes may not be
9748     //  listed in data-sharing attributes clauses, except for the cases
9749     //  listed below.
9750     // OpenMP 4.5 [2.10.8, Distribute Construct, p.3]
9751     // A list item may appear in a firstprivate or lastprivate clause but not
9752     // both.
9753     DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, /*FromParent=*/false);
9754     if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_lastprivate &&
9755         (isOpenMPDistributeDirective(CurrDir) ||
9756          DVar.CKind != OMPC_firstprivate) &&
9757         (DVar.CKind != OMPC_private || DVar.RefExpr != nullptr)) {
9758       Diag(ELoc, diag::err_omp_wrong_dsa)
9759           << getOpenMPClauseName(DVar.CKind)
9760           << getOpenMPClauseName(OMPC_lastprivate);
9761       reportOriginalDsa(*this, DSAStack, D, DVar);
9762       continue;
9763     }
9764 
9765     // OpenMP [2.14.3.5, Restrictions, p.2]
9766     // A list item that is private within a parallel region, or that appears in
9767     // the reduction clause of a parallel construct, must not appear in a
9768     // lastprivate clause on a worksharing construct if any of the corresponding
9769     // worksharing regions ever binds to any of the corresponding parallel
9770     // regions.
9771     DSAStackTy::DSAVarData TopDVar = DVar;
9772     if (isOpenMPWorksharingDirective(CurrDir) &&
9773         !isOpenMPParallelDirective(CurrDir) &&
9774         !isOpenMPTeamsDirective(CurrDir)) {
9775       DVar = DSAStack->getImplicitDSA(D, true);
9776       if (DVar.CKind != OMPC_shared) {
9777         Diag(ELoc, diag::err_omp_required_access)
9778             << getOpenMPClauseName(OMPC_lastprivate)
9779             << getOpenMPClauseName(OMPC_shared);
9780         reportOriginalDsa(*this, DSAStack, D, DVar);
9781         continue;
9782       }
9783     }
9784 
9785     // OpenMP [2.14.3.5, Restrictions, C++, p.1,2]
9786     //  A variable of class type (or array thereof) that appears in a
9787     //  lastprivate clause requires an accessible, unambiguous default
9788     //  constructor for the class type, unless the list item is also specified
9789     //  in a firstprivate clause.
9790     //  A variable of class type (or array thereof) that appears in a
9791     //  lastprivate clause requires an accessible, unambiguous copy assignment
9792     //  operator for the class type.
9793     Type = Context.getBaseElementType(Type).getNonReferenceType();
9794     VarDecl *SrcVD = buildVarDecl(*this, ERange.getBegin(),
9795                                   Type.getUnqualifiedType(), ".lastprivate.src",
9796                                   D->hasAttrs() ? &D->getAttrs() : nullptr);
9797     DeclRefExpr *PseudoSrcExpr =
9798         buildDeclRefExpr(*this, SrcVD, Type.getUnqualifiedType(), ELoc);
9799     VarDecl *DstVD =
9800         buildVarDecl(*this, ERange.getBegin(), Type, ".lastprivate.dst",
9801                      D->hasAttrs() ? &D->getAttrs() : nullptr);
9802     DeclRefExpr *PseudoDstExpr = buildDeclRefExpr(*this, DstVD, Type, ELoc);
9803     // For arrays generate assignment operation for single element and replace
9804     // it by the original array element in CodeGen.
9805     ExprResult AssignmentOp = BuildBinOp(/*S=*/nullptr, ELoc, BO_Assign,
9806                                          PseudoDstExpr, PseudoSrcExpr);
9807     if (AssignmentOp.isInvalid())
9808       continue;
9809     AssignmentOp = ActOnFinishFullExpr(AssignmentOp.get(), ELoc,
9810                                        /*DiscardedValue=*/true);
9811     if (AssignmentOp.isInvalid())
9812       continue;
9813 
9814     DeclRefExpr *Ref = nullptr;
9815     if (!VD && !CurContext->isDependentContext()) {
9816       if (TopDVar.CKind == OMPC_firstprivate) {
9817         Ref = TopDVar.PrivateCopy;
9818       } else {
9819         Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/false);
9820         if (!isOpenMPCapturedDecl(D))
9821           ExprCaptures.push_back(Ref->getDecl());
9822       }
9823       if (TopDVar.CKind == OMPC_firstprivate ||
9824           (!isOpenMPCapturedDecl(D) &&
9825            Ref->getDecl()->hasAttr<OMPCaptureNoInitAttr>())) {
9826         ExprResult RefRes = DefaultLvalueConversion(Ref);
9827         if (!RefRes.isUsable())
9828           continue;
9829         ExprResult PostUpdateRes =
9830             BuildBinOp(DSAStack->getCurScope(), ELoc, BO_Assign, SimpleRefExpr,
9831                        RefRes.get());
9832         if (!PostUpdateRes.isUsable())
9833           continue;
9834         ExprPostUpdates.push_back(
9835             IgnoredValueConversions(PostUpdateRes.get()).get());
9836       }
9837     }
9838     DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_lastprivate, Ref);
9839     Vars.push_back((VD || CurContext->isDependentContext())
9840                        ? RefExpr->IgnoreParens()
9841                        : Ref);
9842     SrcExprs.push_back(PseudoSrcExpr);
9843     DstExprs.push_back(PseudoDstExpr);
9844     AssignmentOps.push_back(AssignmentOp.get());
9845   }
9846 
9847   if (Vars.empty())
9848     return nullptr;
9849 
9850   return OMPLastprivateClause::Create(Context, StartLoc, LParenLoc, EndLoc,
9851                                       Vars, SrcExprs, DstExprs, AssignmentOps,
9852                                       buildPreInits(Context, ExprCaptures),
9853                                       buildPostUpdate(*this, ExprPostUpdates));
9854 }
9855 
9856 OMPClause *Sema::ActOnOpenMPSharedClause(ArrayRef<Expr *> VarList,
9857                                          SourceLocation StartLoc,
9858                                          SourceLocation LParenLoc,
9859                                          SourceLocation EndLoc) {
9860   SmallVector<Expr *, 8> Vars;
9861   for (Expr *RefExpr : VarList) {
9862     assert(RefExpr && "NULL expr in OpenMP lastprivate clause.");
9863     SourceLocation ELoc;
9864     SourceRange ERange;
9865     Expr *SimpleRefExpr = RefExpr;
9866     auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
9867     if (Res.second) {
9868       // It will be analyzed later.
9869       Vars.push_back(RefExpr);
9870     }
9871     ValueDecl *D = Res.first;
9872     if (!D)
9873       continue;
9874 
9875     auto *VD = dyn_cast<VarDecl>(D);
9876     // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
9877     // in a Construct]
9878     //  Variables with the predetermined data-sharing attributes may not be
9879     //  listed in data-sharing attributes clauses, except for the cases
9880     //  listed below. For these exceptions only, listing a predetermined
9881     //  variable in a data-sharing attribute clause is allowed and overrides
9882     //  the variable's predetermined data-sharing attributes.
9883     DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, /*FromParent=*/false);
9884     if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_shared &&
9885         DVar.RefExpr) {
9886       Diag(ELoc, diag::err_omp_wrong_dsa) << getOpenMPClauseName(DVar.CKind)
9887                                           << getOpenMPClauseName(OMPC_shared);
9888       reportOriginalDsa(*this, DSAStack, D, DVar);
9889       continue;
9890     }
9891 
9892     DeclRefExpr *Ref = nullptr;
9893     if (!VD && isOpenMPCapturedDecl(D) && !CurContext->isDependentContext())
9894       Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/true);
9895     DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_shared, Ref);
9896     Vars.push_back((VD || !Ref || CurContext->isDependentContext())
9897                        ? RefExpr->IgnoreParens()
9898                        : Ref);
9899   }
9900 
9901   if (Vars.empty())
9902     return nullptr;
9903 
9904   return OMPSharedClause::Create(Context, StartLoc, LParenLoc, EndLoc, Vars);
9905 }
9906 
9907 namespace {
9908 class DSARefChecker : public StmtVisitor<DSARefChecker, bool> {
9909   DSAStackTy *Stack;
9910 
9911 public:
9912   bool VisitDeclRefExpr(DeclRefExpr *E) {
9913     if (auto *VD = dyn_cast<VarDecl>(E->getDecl())) {
9914       DSAStackTy::DSAVarData DVar = Stack->getTopDSA(VD, /*FromParent=*/false);
9915       if (DVar.CKind == OMPC_shared && !DVar.RefExpr)
9916         return false;
9917       if (DVar.CKind != OMPC_unknown)
9918         return true;
9919       DSAStackTy::DSAVarData DVarPrivate = Stack->hasDSA(
9920           VD, isOpenMPPrivate, [](OpenMPDirectiveKind) { return true; },
9921           /*FromParent=*/true);
9922       return DVarPrivate.CKind != OMPC_unknown;
9923     }
9924     return false;
9925   }
9926   bool VisitStmt(Stmt *S) {
9927     for (Stmt *Child : S->children()) {
9928       if (Child && Visit(Child))
9929         return true;
9930     }
9931     return false;
9932   }
9933   explicit DSARefChecker(DSAStackTy *S) : Stack(S) {}
9934 };
9935 } // namespace
9936 
9937 namespace {
9938 // Transform MemberExpression for specified FieldDecl of current class to
9939 // DeclRefExpr to specified OMPCapturedExprDecl.
9940 class TransformExprToCaptures : public TreeTransform<TransformExprToCaptures> {
9941   typedef TreeTransform<TransformExprToCaptures> BaseTransform;
9942   ValueDecl *Field = nullptr;
9943   DeclRefExpr *CapturedExpr = nullptr;
9944 
9945 public:
9946   TransformExprToCaptures(Sema &SemaRef, ValueDecl *FieldDecl)
9947       : BaseTransform(SemaRef), Field(FieldDecl), CapturedExpr(nullptr) {}
9948 
9949   ExprResult TransformMemberExpr(MemberExpr *E) {
9950     if (isa<CXXThisExpr>(E->getBase()->IgnoreParenImpCasts()) &&
9951         E->getMemberDecl() == Field) {
9952       CapturedExpr = buildCapture(SemaRef, Field, E, /*WithInit=*/false);
9953       return CapturedExpr;
9954     }
9955     return BaseTransform::TransformMemberExpr(E);
9956   }
9957   DeclRefExpr *getCapturedExpr() { return CapturedExpr; }
9958 };
9959 } // namespace
9960 
9961 template <typename T, typename U>
9962 static T filterLookupForUDR(SmallVectorImpl<U> &Lookups,
9963                             const llvm::function_ref<T(ValueDecl *)> Gen) {
9964   for (U &Set : Lookups) {
9965     for (auto *D : Set) {
9966       if (T Res = Gen(cast<ValueDecl>(D)))
9967         return Res;
9968     }
9969   }
9970   return T();
9971 }
9972 
9973 static ExprResult
9974 buildDeclareReductionRef(Sema &SemaRef, SourceLocation Loc, SourceRange Range,
9975                          Scope *S, CXXScopeSpec &ReductionIdScopeSpec,
9976                          const DeclarationNameInfo &ReductionId, QualType Ty,
9977                          CXXCastPath &BasePath, Expr *UnresolvedReduction) {
9978   if (ReductionIdScopeSpec.isInvalid())
9979     return ExprError();
9980   SmallVector<UnresolvedSet<8>, 4> Lookups;
9981   if (S) {
9982     LookupResult Lookup(SemaRef, ReductionId, Sema::LookupOMPReductionName);
9983     Lookup.suppressDiagnostics();
9984     while (S && SemaRef.LookupParsedName(Lookup, S, &ReductionIdScopeSpec)) {
9985       NamedDecl *D = Lookup.getRepresentativeDecl();
9986       do {
9987         S = S->getParent();
9988       } while (S && !S->isDeclScope(D));
9989       if (S)
9990         S = S->getParent();
9991       Lookups.push_back(UnresolvedSet<8>());
9992       Lookups.back().append(Lookup.begin(), Lookup.end());
9993       Lookup.clear();
9994     }
9995   } else if (auto *ULE =
9996                  cast_or_null<UnresolvedLookupExpr>(UnresolvedReduction)) {
9997     Lookups.push_back(UnresolvedSet<8>());
9998     Decl *PrevD = nullptr;
9999     for (NamedDecl *D : ULE->decls()) {
10000       if (D == PrevD)
10001         Lookups.push_back(UnresolvedSet<8>());
10002       else if (auto *DRD = cast<OMPDeclareReductionDecl>(D))
10003         Lookups.back().addDecl(DRD);
10004       PrevD = D;
10005     }
10006   }
10007   if (SemaRef.CurContext->isDependentContext() || Ty->isDependentType() ||
10008       Ty->isInstantiationDependentType() ||
10009       Ty->containsUnexpandedParameterPack() ||
10010       filterLookupForUDR<bool>(Lookups, [](ValueDecl *D) {
10011         return !D->isInvalidDecl() &&
10012                (D->getType()->isDependentType() ||
10013                 D->getType()->isInstantiationDependentType() ||
10014                 D->getType()->containsUnexpandedParameterPack());
10015       })) {
10016     UnresolvedSet<8> ResSet;
10017     for (const UnresolvedSet<8> &Set : Lookups) {
10018       ResSet.append(Set.begin(), Set.end());
10019       // The last item marks the end of all declarations at the specified scope.
10020       ResSet.addDecl(Set[Set.size() - 1]);
10021     }
10022     return UnresolvedLookupExpr::Create(
10023         SemaRef.Context, /*NamingClass=*/nullptr,
10024         ReductionIdScopeSpec.getWithLocInContext(SemaRef.Context), ReductionId,
10025         /*ADL=*/true, /*Overloaded=*/true, ResSet.begin(), ResSet.end());
10026   }
10027   if (auto *VD = filterLookupForUDR<ValueDecl *>(
10028           Lookups, [&SemaRef, Ty](ValueDecl *D) -> ValueDecl * {
10029             if (!D->isInvalidDecl() &&
10030                 SemaRef.Context.hasSameType(D->getType(), Ty))
10031               return D;
10032             return nullptr;
10033           }))
10034     return SemaRef.BuildDeclRefExpr(VD, Ty, VK_LValue, Loc);
10035   if (auto *VD = filterLookupForUDR<ValueDecl *>(
10036           Lookups, [&SemaRef, Ty, Loc](ValueDecl *D) -> ValueDecl * {
10037             if (!D->isInvalidDecl() &&
10038                 SemaRef.IsDerivedFrom(Loc, Ty, D->getType()) &&
10039                 !Ty.isMoreQualifiedThan(D->getType()))
10040               return D;
10041             return nullptr;
10042           })) {
10043     CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
10044                        /*DetectVirtual=*/false);
10045     if (SemaRef.IsDerivedFrom(Loc, Ty, VD->getType(), Paths)) {
10046       if (!Paths.isAmbiguous(SemaRef.Context.getCanonicalType(
10047               VD->getType().getUnqualifiedType()))) {
10048         if (SemaRef.CheckBaseClassAccess(Loc, VD->getType(), Ty, Paths.front(),
10049                                          /*DiagID=*/0) !=
10050             Sema::AR_inaccessible) {
10051           SemaRef.BuildBasePathArray(Paths, BasePath);
10052           return SemaRef.BuildDeclRefExpr(VD, Ty, VK_LValue, Loc);
10053         }
10054       }
10055     }
10056   }
10057   if (ReductionIdScopeSpec.isSet()) {
10058     SemaRef.Diag(Loc, diag::err_omp_not_resolved_reduction_identifier) << Range;
10059     return ExprError();
10060   }
10061   return ExprEmpty();
10062 }
10063 
10064 namespace {
10065 /// Data for the reduction-based clauses.
10066 struct ReductionData {
10067   /// List of original reduction items.
10068   SmallVector<Expr *, 8> Vars;
10069   /// List of private copies of the reduction items.
10070   SmallVector<Expr *, 8> Privates;
10071   /// LHS expressions for the reduction_op expressions.
10072   SmallVector<Expr *, 8> LHSs;
10073   /// RHS expressions for the reduction_op expressions.
10074   SmallVector<Expr *, 8> RHSs;
10075   /// Reduction operation expression.
10076   SmallVector<Expr *, 8> ReductionOps;
10077   /// Taskgroup descriptors for the corresponding reduction items in
10078   /// in_reduction clauses.
10079   SmallVector<Expr *, 8> TaskgroupDescriptors;
10080   /// List of captures for clause.
10081   SmallVector<Decl *, 4> ExprCaptures;
10082   /// List of postupdate expressions.
10083   SmallVector<Expr *, 4> ExprPostUpdates;
10084   ReductionData() = delete;
10085   /// Reserves required memory for the reduction data.
10086   ReductionData(unsigned Size) {
10087     Vars.reserve(Size);
10088     Privates.reserve(Size);
10089     LHSs.reserve(Size);
10090     RHSs.reserve(Size);
10091     ReductionOps.reserve(Size);
10092     TaskgroupDescriptors.reserve(Size);
10093     ExprCaptures.reserve(Size);
10094     ExprPostUpdates.reserve(Size);
10095   }
10096   /// Stores reduction item and reduction operation only (required for dependent
10097   /// reduction item).
10098   void push(Expr *Item, Expr *ReductionOp) {
10099     Vars.emplace_back(Item);
10100     Privates.emplace_back(nullptr);
10101     LHSs.emplace_back(nullptr);
10102     RHSs.emplace_back(nullptr);
10103     ReductionOps.emplace_back(ReductionOp);
10104     TaskgroupDescriptors.emplace_back(nullptr);
10105   }
10106   /// Stores reduction data.
10107   void push(Expr *Item, Expr *Private, Expr *LHS, Expr *RHS, Expr *ReductionOp,
10108             Expr *TaskgroupDescriptor) {
10109     Vars.emplace_back(Item);
10110     Privates.emplace_back(Private);
10111     LHSs.emplace_back(LHS);
10112     RHSs.emplace_back(RHS);
10113     ReductionOps.emplace_back(ReductionOp);
10114     TaskgroupDescriptors.emplace_back(TaskgroupDescriptor);
10115   }
10116 };
10117 } // namespace
10118 
10119 static bool checkOMPArraySectionConstantForReduction(
10120     ASTContext &Context, const OMPArraySectionExpr *OASE, bool &SingleElement,
10121     SmallVectorImpl<llvm::APSInt> &ArraySizes) {
10122   const Expr *Length = OASE->getLength();
10123   if (Length == nullptr) {
10124     // For array sections of the form [1:] or [:], we would need to analyze
10125     // the lower bound...
10126     if (OASE->getColonLoc().isValid())
10127       return false;
10128 
10129     // This is an array subscript which has implicit length 1!
10130     SingleElement = true;
10131     ArraySizes.push_back(llvm::APSInt::get(1));
10132   } else {
10133     llvm::APSInt ConstantLengthValue;
10134     if (!Length->EvaluateAsInt(ConstantLengthValue, Context))
10135       return false;
10136 
10137     SingleElement = (ConstantLengthValue.getSExtValue() == 1);
10138     ArraySizes.push_back(ConstantLengthValue);
10139   }
10140 
10141   // Get the base of this array section and walk up from there.
10142   const Expr *Base = OASE->getBase()->IgnoreParenImpCasts();
10143 
10144   // We require length = 1 for all array sections except the right-most to
10145   // guarantee that the memory region is contiguous and has no holes in it.
10146   while (const auto *TempOASE = dyn_cast<OMPArraySectionExpr>(Base)) {
10147     Length = TempOASE->getLength();
10148     if (Length == nullptr) {
10149       // For array sections of the form [1:] or [:], we would need to analyze
10150       // the lower bound...
10151       if (OASE->getColonLoc().isValid())
10152         return false;
10153 
10154       // This is an array subscript which has implicit length 1!
10155       ArraySizes.push_back(llvm::APSInt::get(1));
10156     } else {
10157       llvm::APSInt ConstantLengthValue;
10158       if (!Length->EvaluateAsInt(ConstantLengthValue, Context) ||
10159           ConstantLengthValue.getSExtValue() != 1)
10160         return false;
10161 
10162       ArraySizes.push_back(ConstantLengthValue);
10163     }
10164     Base = TempOASE->getBase()->IgnoreParenImpCasts();
10165   }
10166 
10167   // If we have a single element, we don't need to add the implicit lengths.
10168   if (!SingleElement) {
10169     while (const auto *TempASE = dyn_cast<ArraySubscriptExpr>(Base)) {
10170       // Has implicit length 1!
10171       ArraySizes.push_back(llvm::APSInt::get(1));
10172       Base = TempASE->getBase()->IgnoreParenImpCasts();
10173     }
10174   }
10175 
10176   // This array section can be privatized as a single value or as a constant
10177   // sized array.
10178   return true;
10179 }
10180 
10181 static bool actOnOMPReductionKindClause(
10182     Sema &S, DSAStackTy *Stack, OpenMPClauseKind ClauseKind,
10183     ArrayRef<Expr *> VarList, SourceLocation StartLoc, SourceLocation LParenLoc,
10184     SourceLocation ColonLoc, SourceLocation EndLoc,
10185     CXXScopeSpec &ReductionIdScopeSpec, const DeclarationNameInfo &ReductionId,
10186     ArrayRef<Expr *> UnresolvedReductions, ReductionData &RD) {
10187   DeclarationName DN = ReductionId.getName();
10188   OverloadedOperatorKind OOK = DN.getCXXOverloadedOperator();
10189   BinaryOperatorKind BOK = BO_Comma;
10190 
10191   ASTContext &Context = S.Context;
10192   // OpenMP [2.14.3.6, reduction clause]
10193   // C
10194   // reduction-identifier is either an identifier or one of the following
10195   // operators: +, -, *,  &, |, ^, && and ||
10196   // C++
10197   // reduction-identifier is either an id-expression or one of the following
10198   // operators: +, -, *, &, |, ^, && and ||
10199   switch (OOK) {
10200   case OO_Plus:
10201   case OO_Minus:
10202     BOK = BO_Add;
10203     break;
10204   case OO_Star:
10205     BOK = BO_Mul;
10206     break;
10207   case OO_Amp:
10208     BOK = BO_And;
10209     break;
10210   case OO_Pipe:
10211     BOK = BO_Or;
10212     break;
10213   case OO_Caret:
10214     BOK = BO_Xor;
10215     break;
10216   case OO_AmpAmp:
10217     BOK = BO_LAnd;
10218     break;
10219   case OO_PipePipe:
10220     BOK = BO_LOr;
10221     break;
10222   case OO_New:
10223   case OO_Delete:
10224   case OO_Array_New:
10225   case OO_Array_Delete:
10226   case OO_Slash:
10227   case OO_Percent:
10228   case OO_Tilde:
10229   case OO_Exclaim:
10230   case OO_Equal:
10231   case OO_Less:
10232   case OO_Greater:
10233   case OO_LessEqual:
10234   case OO_GreaterEqual:
10235   case OO_PlusEqual:
10236   case OO_MinusEqual:
10237   case OO_StarEqual:
10238   case OO_SlashEqual:
10239   case OO_PercentEqual:
10240   case OO_CaretEqual:
10241   case OO_AmpEqual:
10242   case OO_PipeEqual:
10243   case OO_LessLess:
10244   case OO_GreaterGreater:
10245   case OO_LessLessEqual:
10246   case OO_GreaterGreaterEqual:
10247   case OO_EqualEqual:
10248   case OO_ExclaimEqual:
10249   case OO_Spaceship:
10250   case OO_PlusPlus:
10251   case OO_MinusMinus:
10252   case OO_Comma:
10253   case OO_ArrowStar:
10254   case OO_Arrow:
10255   case OO_Call:
10256   case OO_Subscript:
10257   case OO_Conditional:
10258   case OO_Coawait:
10259   case NUM_OVERLOADED_OPERATORS:
10260     llvm_unreachable("Unexpected reduction identifier");
10261   case OO_None:
10262     if (IdentifierInfo *II = DN.getAsIdentifierInfo()) {
10263       if (II->isStr("max"))
10264         BOK = BO_GT;
10265       else if (II->isStr("min"))
10266         BOK = BO_LT;
10267     }
10268     break;
10269   }
10270   SourceRange ReductionIdRange;
10271   if (ReductionIdScopeSpec.isValid())
10272     ReductionIdRange.setBegin(ReductionIdScopeSpec.getBeginLoc());
10273   else
10274     ReductionIdRange.setBegin(ReductionId.getBeginLoc());
10275   ReductionIdRange.setEnd(ReductionId.getEndLoc());
10276 
10277   auto IR = UnresolvedReductions.begin(), ER = UnresolvedReductions.end();
10278   bool FirstIter = true;
10279   for (Expr *RefExpr : VarList) {
10280     assert(RefExpr && "nullptr expr in OpenMP reduction clause.");
10281     // OpenMP [2.1, C/C++]
10282     //  A list item is a variable or array section, subject to the restrictions
10283     //  specified in Section 2.4 on page 42 and in each of the sections
10284     // describing clauses and directives for which a list appears.
10285     // OpenMP  [2.14.3.3, Restrictions, p.1]
10286     //  A variable that is part of another variable (as an array or
10287     //  structure element) cannot appear in a private clause.
10288     if (!FirstIter && IR != ER)
10289       ++IR;
10290     FirstIter = false;
10291     SourceLocation ELoc;
10292     SourceRange ERange;
10293     Expr *SimpleRefExpr = RefExpr;
10294     auto Res = getPrivateItem(S, SimpleRefExpr, ELoc, ERange,
10295                               /*AllowArraySection=*/true);
10296     if (Res.second) {
10297       // Try to find 'declare reduction' corresponding construct before using
10298       // builtin/overloaded operators.
10299       QualType Type = Context.DependentTy;
10300       CXXCastPath BasePath;
10301       ExprResult DeclareReductionRef = buildDeclareReductionRef(
10302           S, ELoc, ERange, Stack->getCurScope(), ReductionIdScopeSpec,
10303           ReductionId, Type, BasePath, IR == ER ? nullptr : *IR);
10304       Expr *ReductionOp = nullptr;
10305       if (S.CurContext->isDependentContext() &&
10306           (DeclareReductionRef.isUnset() ||
10307            isa<UnresolvedLookupExpr>(DeclareReductionRef.get())))
10308         ReductionOp = DeclareReductionRef.get();
10309       // It will be analyzed later.
10310       RD.push(RefExpr, ReductionOp);
10311     }
10312     ValueDecl *D = Res.first;
10313     if (!D)
10314       continue;
10315 
10316     Expr *TaskgroupDescriptor = nullptr;
10317     QualType Type;
10318     auto *ASE = dyn_cast<ArraySubscriptExpr>(RefExpr->IgnoreParens());
10319     auto *OASE = dyn_cast<OMPArraySectionExpr>(RefExpr->IgnoreParens());
10320     if (ASE) {
10321       Type = ASE->getType().getNonReferenceType();
10322     } else if (OASE) {
10323       QualType BaseType =
10324           OMPArraySectionExpr::getBaseOriginalType(OASE->getBase());
10325       if (const auto *ATy = BaseType->getAsArrayTypeUnsafe())
10326         Type = ATy->getElementType();
10327       else
10328         Type = BaseType->getPointeeType();
10329       Type = Type.getNonReferenceType();
10330     } else {
10331       Type = Context.getBaseElementType(D->getType().getNonReferenceType());
10332     }
10333     auto *VD = dyn_cast<VarDecl>(D);
10334 
10335     // OpenMP [2.9.3.3, Restrictions, C/C++, p.3]
10336     //  A variable that appears in a private clause must not have an incomplete
10337     //  type or a reference type.
10338     if (S.RequireCompleteType(ELoc, Type,
10339                               diag::err_omp_reduction_incomplete_type))
10340       continue;
10341     // OpenMP [2.14.3.6, reduction clause, Restrictions]
10342     // A list item that appears in a reduction clause must not be
10343     // const-qualified.
10344     if (Type.getNonReferenceType().isConstant(Context)) {
10345       S.Diag(ELoc, diag::err_omp_const_reduction_list_item) << ERange;
10346       if (!ASE && !OASE) {
10347         bool IsDecl = !VD || VD->isThisDeclarationADefinition(Context) ==
10348                                  VarDecl::DeclarationOnly;
10349         S.Diag(D->getLocation(),
10350                IsDecl ? diag::note_previous_decl : diag::note_defined_here)
10351             << D;
10352       }
10353       continue;
10354     }
10355     // OpenMP [2.9.3.6, Restrictions, C/C++, p.4]
10356     //  If a list-item is a reference type then it must bind to the same object
10357     //  for all threads of the team.
10358     if (!ASE && !OASE && VD) {
10359       VarDecl *VDDef = VD->getDefinition();
10360       if (VD->getType()->isReferenceType() && VDDef && VDDef->hasInit()) {
10361         DSARefChecker Check(Stack);
10362         if (Check.Visit(VDDef->getInit())) {
10363           S.Diag(ELoc, diag::err_omp_reduction_ref_type_arg)
10364               << getOpenMPClauseName(ClauseKind) << ERange;
10365           S.Diag(VDDef->getLocation(), diag::note_defined_here) << VDDef;
10366           continue;
10367         }
10368       }
10369     }
10370 
10371     // OpenMP [2.14.1.1, Data-sharing Attribute Rules for Variables Referenced
10372     // in a Construct]
10373     //  Variables with the predetermined data-sharing attributes may not be
10374     //  listed in data-sharing attributes clauses, except for the cases
10375     //  listed below. For these exceptions only, listing a predetermined
10376     //  variable in a data-sharing attribute clause is allowed and overrides
10377     //  the variable's predetermined data-sharing attributes.
10378     // OpenMP [2.14.3.6, Restrictions, p.3]
10379     //  Any number of reduction clauses can be specified on the directive,
10380     //  but a list item can appear only once in the reduction clauses for that
10381     //  directive.
10382     DSAStackTy::DSAVarData DVar = Stack->getTopDSA(D, /*FromParent=*/false);
10383     if (DVar.CKind == OMPC_reduction) {
10384       S.Diag(ELoc, diag::err_omp_once_referenced)
10385           << getOpenMPClauseName(ClauseKind);
10386       if (DVar.RefExpr)
10387         S.Diag(DVar.RefExpr->getExprLoc(), diag::note_omp_referenced);
10388       continue;
10389     }
10390     if (DVar.CKind != OMPC_unknown) {
10391       S.Diag(ELoc, diag::err_omp_wrong_dsa)
10392           << getOpenMPClauseName(DVar.CKind)
10393           << getOpenMPClauseName(OMPC_reduction);
10394       reportOriginalDsa(S, Stack, D, DVar);
10395       continue;
10396     }
10397 
10398     // OpenMP [2.14.3.6, Restrictions, p.1]
10399     //  A list item that appears in a reduction clause of a worksharing
10400     //  construct must be shared in the parallel regions to which any of the
10401     //  worksharing regions arising from the worksharing construct bind.
10402     OpenMPDirectiveKind CurrDir = Stack->getCurrentDirective();
10403     if (isOpenMPWorksharingDirective(CurrDir) &&
10404         !isOpenMPParallelDirective(CurrDir) &&
10405         !isOpenMPTeamsDirective(CurrDir)) {
10406       DVar = Stack->getImplicitDSA(D, true);
10407       if (DVar.CKind != OMPC_shared) {
10408         S.Diag(ELoc, diag::err_omp_required_access)
10409             << getOpenMPClauseName(OMPC_reduction)
10410             << getOpenMPClauseName(OMPC_shared);
10411         reportOriginalDsa(S, Stack, D, DVar);
10412         continue;
10413       }
10414     }
10415 
10416     // Try to find 'declare reduction' corresponding construct before using
10417     // builtin/overloaded operators.
10418     CXXCastPath BasePath;
10419     ExprResult DeclareReductionRef = buildDeclareReductionRef(
10420         S, ELoc, ERange, Stack->getCurScope(), ReductionIdScopeSpec,
10421         ReductionId, Type, BasePath, IR == ER ? nullptr : *IR);
10422     if (DeclareReductionRef.isInvalid())
10423       continue;
10424     if (S.CurContext->isDependentContext() &&
10425         (DeclareReductionRef.isUnset() ||
10426          isa<UnresolvedLookupExpr>(DeclareReductionRef.get()))) {
10427       RD.push(RefExpr, DeclareReductionRef.get());
10428       continue;
10429     }
10430     if (BOK == BO_Comma && DeclareReductionRef.isUnset()) {
10431       // Not allowed reduction identifier is found.
10432       S.Diag(ReductionId.getLocStart(),
10433              diag::err_omp_unknown_reduction_identifier)
10434           << Type << ReductionIdRange;
10435       continue;
10436     }
10437 
10438     // OpenMP [2.14.3.6, reduction clause, Restrictions]
10439     // The type of a list item that appears in a reduction clause must be valid
10440     // for the reduction-identifier. For a max or min reduction in C, the type
10441     // of the list item must be an allowed arithmetic data type: char, int,
10442     // float, double, or _Bool, possibly modified with long, short, signed, or
10443     // unsigned. For a max or min reduction in C++, the type of the list item
10444     // must be an allowed arithmetic data type: char, wchar_t, int, float,
10445     // double, or bool, possibly modified with long, short, signed, or unsigned.
10446     if (DeclareReductionRef.isUnset()) {
10447       if ((BOK == BO_GT || BOK == BO_LT) &&
10448           !(Type->isScalarType() ||
10449             (S.getLangOpts().CPlusPlus && Type->isArithmeticType()))) {
10450         S.Diag(ELoc, diag::err_omp_clause_not_arithmetic_type_arg)
10451             << getOpenMPClauseName(ClauseKind) << S.getLangOpts().CPlusPlus;
10452         if (!ASE && !OASE) {
10453           bool IsDecl = !VD || VD->isThisDeclarationADefinition(Context) ==
10454                                    VarDecl::DeclarationOnly;
10455           S.Diag(D->getLocation(),
10456                  IsDecl ? diag::note_previous_decl : diag::note_defined_here)
10457               << D;
10458         }
10459         continue;
10460       }
10461       if ((BOK == BO_OrAssign || BOK == BO_AndAssign || BOK == BO_XorAssign) &&
10462           !S.getLangOpts().CPlusPlus && Type->isFloatingType()) {
10463         S.Diag(ELoc, diag::err_omp_clause_floating_type_arg)
10464             << getOpenMPClauseName(ClauseKind);
10465         if (!ASE && !OASE) {
10466           bool IsDecl = !VD || VD->isThisDeclarationADefinition(Context) ==
10467                                    VarDecl::DeclarationOnly;
10468           S.Diag(D->getLocation(),
10469                  IsDecl ? diag::note_previous_decl : diag::note_defined_here)
10470               << D;
10471         }
10472         continue;
10473       }
10474     }
10475 
10476     Type = Type.getNonLValueExprType(Context).getUnqualifiedType();
10477     VarDecl *LHSVD = buildVarDecl(S, ELoc, Type, ".reduction.lhs",
10478                                   D->hasAttrs() ? &D->getAttrs() : nullptr);
10479     VarDecl *RHSVD = buildVarDecl(S, ELoc, Type, D->getName(),
10480                                   D->hasAttrs() ? &D->getAttrs() : nullptr);
10481     QualType PrivateTy = Type;
10482 
10483     // Try if we can determine constant lengths for all array sections and avoid
10484     // the VLA.
10485     bool ConstantLengthOASE = false;
10486     if (OASE) {
10487       bool SingleElement;
10488       llvm::SmallVector<llvm::APSInt, 4> ArraySizes;
10489       ConstantLengthOASE = checkOMPArraySectionConstantForReduction(
10490           Context, OASE, SingleElement, ArraySizes);
10491 
10492       // If we don't have a single element, we must emit a constant array type.
10493       if (ConstantLengthOASE && !SingleElement) {
10494         for (llvm::APSInt &Size : ArraySizes)
10495           PrivateTy = Context.getConstantArrayType(
10496               PrivateTy, Size, ArrayType::Normal, /*IndexTypeQuals=*/0);
10497       }
10498     }
10499 
10500     if ((OASE && !ConstantLengthOASE) ||
10501         (!OASE && !ASE &&
10502          D->getType().getNonReferenceType()->isVariablyModifiedType())) {
10503       if (!Context.getTargetInfo().isVLASupported() &&
10504           S.shouldDiagnoseTargetSupportFromOpenMP()) {
10505         S.Diag(ELoc, diag::err_omp_reduction_vla_unsupported) << !!OASE;
10506         S.Diag(ELoc, diag::note_vla_unsupported);
10507         continue;
10508       }
10509       // For arrays/array sections only:
10510       // Create pseudo array type for private copy. The size for this array will
10511       // be generated during codegen.
10512       // For array subscripts or single variables Private Ty is the same as Type
10513       // (type of the variable or single array element).
10514       PrivateTy = Context.getVariableArrayType(
10515           Type,
10516           new (Context) OpaqueValueExpr(ELoc, Context.getSizeType(), VK_RValue),
10517           ArrayType::Normal, /*IndexTypeQuals=*/0, SourceRange());
10518     } else if (!ASE && !OASE &&
10519                Context.getAsArrayType(D->getType().getNonReferenceType())) {
10520       PrivateTy = D->getType().getNonReferenceType();
10521     }
10522     // Private copy.
10523     VarDecl *PrivateVD =
10524         buildVarDecl(S, ELoc, PrivateTy, D->getName(),
10525                      D->hasAttrs() ? &D->getAttrs() : nullptr,
10526                      VD ? cast<DeclRefExpr>(SimpleRefExpr) : nullptr);
10527     // Add initializer for private variable.
10528     Expr *Init = nullptr;
10529     DeclRefExpr *LHSDRE = buildDeclRefExpr(S, LHSVD, Type, ELoc);
10530     DeclRefExpr *RHSDRE = buildDeclRefExpr(S, RHSVD, Type, ELoc);
10531     if (DeclareReductionRef.isUsable()) {
10532       auto *DRDRef = DeclareReductionRef.getAs<DeclRefExpr>();
10533       auto *DRD = cast<OMPDeclareReductionDecl>(DRDRef->getDecl());
10534       if (DRD->getInitializer()) {
10535         Init = DRDRef;
10536         RHSVD->setInit(DRDRef);
10537         RHSVD->setInitStyle(VarDecl::CallInit);
10538       }
10539     } else {
10540       switch (BOK) {
10541       case BO_Add:
10542       case BO_Xor:
10543       case BO_Or:
10544       case BO_LOr:
10545         // '+', '-', '^', '|', '||' reduction ops - initializer is '0'.
10546         if (Type->isScalarType() || Type->isAnyComplexType())
10547           Init = S.ActOnIntegerConstant(ELoc, /*Val=*/0).get();
10548         break;
10549       case BO_Mul:
10550       case BO_LAnd:
10551         if (Type->isScalarType() || Type->isAnyComplexType()) {
10552           // '*' and '&&' reduction ops - initializer is '1'.
10553           Init = S.ActOnIntegerConstant(ELoc, /*Val=*/1).get();
10554         }
10555         break;
10556       case BO_And: {
10557         // '&' reduction op - initializer is '~0'.
10558         QualType OrigType = Type;
10559         if (auto *ComplexTy = OrigType->getAs<ComplexType>())
10560           Type = ComplexTy->getElementType();
10561         if (Type->isRealFloatingType()) {
10562           llvm::APFloat InitValue =
10563               llvm::APFloat::getAllOnesValue(Context.getTypeSize(Type),
10564                                              /*isIEEE=*/true);
10565           Init = FloatingLiteral::Create(Context, InitValue, /*isexact=*/true,
10566                                          Type, ELoc);
10567         } else if (Type->isScalarType()) {
10568           uint64_t Size = Context.getTypeSize(Type);
10569           QualType IntTy = Context.getIntTypeForBitwidth(Size, /*Signed=*/0);
10570           llvm::APInt InitValue = llvm::APInt::getAllOnesValue(Size);
10571           Init = IntegerLiteral::Create(Context, InitValue, IntTy, ELoc);
10572         }
10573         if (Init && OrigType->isAnyComplexType()) {
10574           // Init = 0xFFFF + 0xFFFFi;
10575           auto *Im = new (Context) ImaginaryLiteral(Init, OrigType);
10576           Init = S.CreateBuiltinBinOp(ELoc, BO_Add, Init, Im).get();
10577         }
10578         Type = OrigType;
10579         break;
10580       }
10581       case BO_LT:
10582       case BO_GT: {
10583         // 'min' reduction op - initializer is 'Largest representable number in
10584         // the reduction list item type'.
10585         // 'max' reduction op - initializer is 'Least representable number in
10586         // the reduction list item type'.
10587         if (Type->isIntegerType() || Type->isPointerType()) {
10588           bool IsSigned = Type->hasSignedIntegerRepresentation();
10589           uint64_t Size = Context.getTypeSize(Type);
10590           QualType IntTy =
10591               Context.getIntTypeForBitwidth(Size, /*Signed=*/IsSigned);
10592           llvm::APInt InitValue =
10593               (BOK != BO_LT) ? IsSigned ? llvm::APInt::getSignedMinValue(Size)
10594                                         : llvm::APInt::getMinValue(Size)
10595                              : IsSigned ? llvm::APInt::getSignedMaxValue(Size)
10596                                         : llvm::APInt::getMaxValue(Size);
10597           Init = IntegerLiteral::Create(Context, InitValue, IntTy, ELoc);
10598           if (Type->isPointerType()) {
10599             // Cast to pointer type.
10600             ExprResult CastExpr = S.BuildCStyleCastExpr(
10601                 ELoc, Context.getTrivialTypeSourceInfo(Type, ELoc), ELoc, Init);
10602             if (CastExpr.isInvalid())
10603               continue;
10604             Init = CastExpr.get();
10605           }
10606         } else if (Type->isRealFloatingType()) {
10607           llvm::APFloat InitValue = llvm::APFloat::getLargest(
10608               Context.getFloatTypeSemantics(Type), BOK != BO_LT);
10609           Init = FloatingLiteral::Create(Context, InitValue, /*isexact=*/true,
10610                                          Type, ELoc);
10611         }
10612         break;
10613       }
10614       case BO_PtrMemD:
10615       case BO_PtrMemI:
10616       case BO_MulAssign:
10617       case BO_Div:
10618       case BO_Rem:
10619       case BO_Sub:
10620       case BO_Shl:
10621       case BO_Shr:
10622       case BO_LE:
10623       case BO_GE:
10624       case BO_EQ:
10625       case BO_NE:
10626       case BO_Cmp:
10627       case BO_AndAssign:
10628       case BO_XorAssign:
10629       case BO_OrAssign:
10630       case BO_Assign:
10631       case BO_AddAssign:
10632       case BO_SubAssign:
10633       case BO_DivAssign:
10634       case BO_RemAssign:
10635       case BO_ShlAssign:
10636       case BO_ShrAssign:
10637       case BO_Comma:
10638         llvm_unreachable("Unexpected reduction operation");
10639       }
10640     }
10641     if (Init && DeclareReductionRef.isUnset())
10642       S.AddInitializerToDecl(RHSVD, Init, /*DirectInit=*/false);
10643     else if (!Init)
10644       S.ActOnUninitializedDecl(RHSVD);
10645     if (RHSVD->isInvalidDecl())
10646       continue;
10647     if (!RHSVD->hasInit() && DeclareReductionRef.isUnset()) {
10648       S.Diag(ELoc, diag::err_omp_reduction_id_not_compatible)
10649           << Type << ReductionIdRange;
10650       bool IsDecl = !VD || VD->isThisDeclarationADefinition(Context) ==
10651                                VarDecl::DeclarationOnly;
10652       S.Diag(D->getLocation(),
10653              IsDecl ? diag::note_previous_decl : diag::note_defined_here)
10654           << D;
10655       continue;
10656     }
10657     // Store initializer for single element in private copy. Will be used during
10658     // codegen.
10659     PrivateVD->setInit(RHSVD->getInit());
10660     PrivateVD->setInitStyle(RHSVD->getInitStyle());
10661     DeclRefExpr *PrivateDRE = buildDeclRefExpr(S, PrivateVD, PrivateTy, ELoc);
10662     ExprResult ReductionOp;
10663     if (DeclareReductionRef.isUsable()) {
10664       QualType RedTy = DeclareReductionRef.get()->getType();
10665       QualType PtrRedTy = Context.getPointerType(RedTy);
10666       ExprResult LHS = S.CreateBuiltinUnaryOp(ELoc, UO_AddrOf, LHSDRE);
10667       ExprResult RHS = S.CreateBuiltinUnaryOp(ELoc, UO_AddrOf, RHSDRE);
10668       if (!BasePath.empty()) {
10669         LHS = S.DefaultLvalueConversion(LHS.get());
10670         RHS = S.DefaultLvalueConversion(RHS.get());
10671         LHS = ImplicitCastExpr::Create(Context, PtrRedTy,
10672                                        CK_UncheckedDerivedToBase, LHS.get(),
10673                                        &BasePath, LHS.get()->getValueKind());
10674         RHS = ImplicitCastExpr::Create(Context, PtrRedTy,
10675                                        CK_UncheckedDerivedToBase, RHS.get(),
10676                                        &BasePath, RHS.get()->getValueKind());
10677       }
10678       FunctionProtoType::ExtProtoInfo EPI;
10679       QualType Params[] = {PtrRedTy, PtrRedTy};
10680       QualType FnTy = Context.getFunctionType(Context.VoidTy, Params, EPI);
10681       auto *OVE = new (Context) OpaqueValueExpr(
10682           ELoc, Context.getPointerType(FnTy), VK_RValue, OK_Ordinary,
10683           S.DefaultLvalueConversion(DeclareReductionRef.get()).get());
10684       Expr *Args[] = {LHS.get(), RHS.get()};
10685       ReductionOp = new (Context)
10686           CallExpr(Context, OVE, Args, Context.VoidTy, VK_RValue, ELoc);
10687     } else {
10688       ReductionOp = S.BuildBinOp(
10689           Stack->getCurScope(), ReductionId.getLocStart(), BOK, LHSDRE, RHSDRE);
10690       if (ReductionOp.isUsable()) {
10691         if (BOK != BO_LT && BOK != BO_GT) {
10692           ReductionOp =
10693               S.BuildBinOp(Stack->getCurScope(), ReductionId.getLocStart(),
10694                            BO_Assign, LHSDRE, ReductionOp.get());
10695         } else {
10696           auto *ConditionalOp = new (Context)
10697               ConditionalOperator(ReductionOp.get(), ELoc, LHSDRE, ELoc, RHSDRE,
10698                                   Type, VK_LValue, OK_Ordinary);
10699           ReductionOp =
10700               S.BuildBinOp(Stack->getCurScope(), ReductionId.getLocStart(),
10701                            BO_Assign, LHSDRE, ConditionalOp);
10702         }
10703         if (ReductionOp.isUsable())
10704           ReductionOp = S.ActOnFinishFullExpr(ReductionOp.get());
10705       }
10706       if (!ReductionOp.isUsable())
10707         continue;
10708     }
10709 
10710     // OpenMP [2.15.4.6, Restrictions, p.2]
10711     // A list item that appears in an in_reduction clause of a task construct
10712     // must appear in a task_reduction clause of a construct associated with a
10713     // taskgroup region that includes the participating task in its taskgroup
10714     // set. The construct associated with the innermost region that meets this
10715     // condition must specify the same reduction-identifier as the in_reduction
10716     // clause.
10717     if (ClauseKind == OMPC_in_reduction) {
10718       SourceRange ParentSR;
10719       BinaryOperatorKind ParentBOK;
10720       const Expr *ParentReductionOp;
10721       Expr *ParentBOKTD, *ParentReductionOpTD;
10722       DSAStackTy::DSAVarData ParentBOKDSA =
10723           Stack->getTopMostTaskgroupReductionData(D, ParentSR, ParentBOK,
10724                                                   ParentBOKTD);
10725       DSAStackTy::DSAVarData ParentReductionOpDSA =
10726           Stack->getTopMostTaskgroupReductionData(
10727               D, ParentSR, ParentReductionOp, ParentReductionOpTD);
10728       bool IsParentBOK = ParentBOKDSA.DKind != OMPD_unknown;
10729       bool IsParentReductionOp = ParentReductionOpDSA.DKind != OMPD_unknown;
10730       if (!IsParentBOK && !IsParentReductionOp) {
10731         S.Diag(ELoc, diag::err_omp_in_reduction_not_task_reduction);
10732         continue;
10733       }
10734       if ((DeclareReductionRef.isUnset() && IsParentReductionOp) ||
10735           (DeclareReductionRef.isUsable() && IsParentBOK) || BOK != ParentBOK ||
10736           IsParentReductionOp) {
10737         bool EmitError = true;
10738         if (IsParentReductionOp && DeclareReductionRef.isUsable()) {
10739           llvm::FoldingSetNodeID RedId, ParentRedId;
10740           ParentReductionOp->Profile(ParentRedId, Context, /*Canonical=*/true);
10741           DeclareReductionRef.get()->Profile(RedId, Context,
10742                                              /*Canonical=*/true);
10743           EmitError = RedId != ParentRedId;
10744         }
10745         if (EmitError) {
10746           S.Diag(ReductionId.getLocStart(),
10747                  diag::err_omp_reduction_identifier_mismatch)
10748               << ReductionIdRange << RefExpr->getSourceRange();
10749           S.Diag(ParentSR.getBegin(),
10750                  diag::note_omp_previous_reduction_identifier)
10751               << ParentSR
10752               << (IsParentBOK ? ParentBOKDSA.RefExpr
10753                               : ParentReductionOpDSA.RefExpr)
10754                      ->getSourceRange();
10755           continue;
10756         }
10757       }
10758       TaskgroupDescriptor = IsParentBOK ? ParentBOKTD : ParentReductionOpTD;
10759       assert(TaskgroupDescriptor && "Taskgroup descriptor must be defined.");
10760     }
10761 
10762     DeclRefExpr *Ref = nullptr;
10763     Expr *VarsExpr = RefExpr->IgnoreParens();
10764     if (!VD && !S.CurContext->isDependentContext()) {
10765       if (ASE || OASE) {
10766         TransformExprToCaptures RebuildToCapture(S, D);
10767         VarsExpr =
10768             RebuildToCapture.TransformExpr(RefExpr->IgnoreParens()).get();
10769         Ref = RebuildToCapture.getCapturedExpr();
10770       } else {
10771         VarsExpr = Ref = buildCapture(S, D, SimpleRefExpr, /*WithInit=*/false);
10772       }
10773       if (!S.isOpenMPCapturedDecl(D)) {
10774         RD.ExprCaptures.emplace_back(Ref->getDecl());
10775         if (Ref->getDecl()->hasAttr<OMPCaptureNoInitAttr>()) {
10776           ExprResult RefRes = S.DefaultLvalueConversion(Ref);
10777           if (!RefRes.isUsable())
10778             continue;
10779           ExprResult PostUpdateRes =
10780               S.BuildBinOp(Stack->getCurScope(), ELoc, BO_Assign, SimpleRefExpr,
10781                            RefRes.get());
10782           if (!PostUpdateRes.isUsable())
10783             continue;
10784           if (isOpenMPTaskingDirective(Stack->getCurrentDirective()) ||
10785               Stack->getCurrentDirective() == OMPD_taskgroup) {
10786             S.Diag(RefExpr->getExprLoc(),
10787                    diag::err_omp_reduction_non_addressable_expression)
10788                 << RefExpr->getSourceRange();
10789             continue;
10790           }
10791           RD.ExprPostUpdates.emplace_back(
10792               S.IgnoredValueConversions(PostUpdateRes.get()).get());
10793         }
10794       }
10795     }
10796     // All reduction items are still marked as reduction (to do not increase
10797     // code base size).
10798     Stack->addDSA(D, RefExpr->IgnoreParens(), OMPC_reduction, Ref);
10799     if (CurrDir == OMPD_taskgroup) {
10800       if (DeclareReductionRef.isUsable())
10801         Stack->addTaskgroupReductionData(D, ReductionIdRange,
10802                                          DeclareReductionRef.get());
10803       else
10804         Stack->addTaskgroupReductionData(D, ReductionIdRange, BOK);
10805     }
10806     RD.push(VarsExpr, PrivateDRE, LHSDRE, RHSDRE, ReductionOp.get(),
10807             TaskgroupDescriptor);
10808   }
10809   return RD.Vars.empty();
10810 }
10811 
10812 OMPClause *Sema::ActOnOpenMPReductionClause(
10813     ArrayRef<Expr *> VarList, SourceLocation StartLoc, SourceLocation LParenLoc,
10814     SourceLocation ColonLoc, SourceLocation EndLoc,
10815     CXXScopeSpec &ReductionIdScopeSpec, const DeclarationNameInfo &ReductionId,
10816     ArrayRef<Expr *> UnresolvedReductions) {
10817   ReductionData RD(VarList.size());
10818   if (actOnOMPReductionKindClause(*this, DSAStack, OMPC_reduction, VarList,
10819                                   StartLoc, LParenLoc, ColonLoc, EndLoc,
10820                                   ReductionIdScopeSpec, ReductionId,
10821                                   UnresolvedReductions, RD))
10822     return nullptr;
10823 
10824   return OMPReductionClause::Create(
10825       Context, StartLoc, LParenLoc, ColonLoc, EndLoc, RD.Vars,
10826       ReductionIdScopeSpec.getWithLocInContext(Context), ReductionId,
10827       RD.Privates, RD.LHSs, RD.RHSs, RD.ReductionOps,
10828       buildPreInits(Context, RD.ExprCaptures),
10829       buildPostUpdate(*this, RD.ExprPostUpdates));
10830 }
10831 
10832 OMPClause *Sema::ActOnOpenMPTaskReductionClause(
10833     ArrayRef<Expr *> VarList, SourceLocation StartLoc, SourceLocation LParenLoc,
10834     SourceLocation ColonLoc, SourceLocation EndLoc,
10835     CXXScopeSpec &ReductionIdScopeSpec, const DeclarationNameInfo &ReductionId,
10836     ArrayRef<Expr *> UnresolvedReductions) {
10837   ReductionData RD(VarList.size());
10838   if (actOnOMPReductionKindClause(*this, DSAStack, OMPC_task_reduction, VarList,
10839                                   StartLoc, LParenLoc, ColonLoc, EndLoc,
10840                                   ReductionIdScopeSpec, ReductionId,
10841                                   UnresolvedReductions, RD))
10842     return nullptr;
10843 
10844   return OMPTaskReductionClause::Create(
10845       Context, StartLoc, LParenLoc, ColonLoc, EndLoc, RD.Vars,
10846       ReductionIdScopeSpec.getWithLocInContext(Context), ReductionId,
10847       RD.Privates, RD.LHSs, RD.RHSs, RD.ReductionOps,
10848       buildPreInits(Context, RD.ExprCaptures),
10849       buildPostUpdate(*this, RD.ExprPostUpdates));
10850 }
10851 
10852 OMPClause *Sema::ActOnOpenMPInReductionClause(
10853     ArrayRef<Expr *> VarList, SourceLocation StartLoc, SourceLocation LParenLoc,
10854     SourceLocation ColonLoc, SourceLocation EndLoc,
10855     CXXScopeSpec &ReductionIdScopeSpec, const DeclarationNameInfo &ReductionId,
10856     ArrayRef<Expr *> UnresolvedReductions) {
10857   ReductionData RD(VarList.size());
10858   if (actOnOMPReductionKindClause(*this, DSAStack, OMPC_in_reduction, VarList,
10859                                   StartLoc, LParenLoc, ColonLoc, EndLoc,
10860                                   ReductionIdScopeSpec, ReductionId,
10861                                   UnresolvedReductions, RD))
10862     return nullptr;
10863 
10864   return OMPInReductionClause::Create(
10865       Context, StartLoc, LParenLoc, ColonLoc, EndLoc, RD.Vars,
10866       ReductionIdScopeSpec.getWithLocInContext(Context), ReductionId,
10867       RD.Privates, RD.LHSs, RD.RHSs, RD.ReductionOps, RD.TaskgroupDescriptors,
10868       buildPreInits(Context, RD.ExprCaptures),
10869       buildPostUpdate(*this, RD.ExprPostUpdates));
10870 }
10871 
10872 bool Sema::CheckOpenMPLinearModifier(OpenMPLinearClauseKind LinKind,
10873                                      SourceLocation LinLoc) {
10874   if ((!LangOpts.CPlusPlus && LinKind != OMPC_LINEAR_val) ||
10875       LinKind == OMPC_LINEAR_unknown) {
10876     Diag(LinLoc, diag::err_omp_wrong_linear_modifier) << LangOpts.CPlusPlus;
10877     return true;
10878   }
10879   return false;
10880 }
10881 
10882 bool Sema::CheckOpenMPLinearDecl(const ValueDecl *D, SourceLocation ELoc,
10883                                  OpenMPLinearClauseKind LinKind,
10884                                  QualType Type) {
10885   const auto *VD = dyn_cast_or_null<VarDecl>(D);
10886   // A variable must not have an incomplete type or a reference type.
10887   if (RequireCompleteType(ELoc, Type, diag::err_omp_linear_incomplete_type))
10888     return true;
10889   if ((LinKind == OMPC_LINEAR_uval || LinKind == OMPC_LINEAR_ref) &&
10890       !Type->isReferenceType()) {
10891     Diag(ELoc, diag::err_omp_wrong_linear_modifier_non_reference)
10892         << Type << getOpenMPSimpleClauseTypeName(OMPC_linear, LinKind);
10893     return true;
10894   }
10895   Type = Type.getNonReferenceType();
10896 
10897   // A list item must not be const-qualified.
10898   if (Type.isConstant(Context)) {
10899     Diag(ELoc, diag::err_omp_const_variable)
10900         << getOpenMPClauseName(OMPC_linear);
10901     if (D) {
10902       bool IsDecl =
10903           !VD ||
10904           VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
10905       Diag(D->getLocation(),
10906            IsDecl ? diag::note_previous_decl : diag::note_defined_here)
10907           << D;
10908     }
10909     return true;
10910   }
10911 
10912   // A list item must be of integral or pointer type.
10913   Type = Type.getUnqualifiedType().getCanonicalType();
10914   const auto *Ty = Type.getTypePtrOrNull();
10915   if (!Ty || (!Ty->isDependentType() && !Ty->isIntegralType(Context) &&
10916               !Ty->isPointerType())) {
10917     Diag(ELoc, diag::err_omp_linear_expected_int_or_ptr) << Type;
10918     if (D) {
10919       bool IsDecl =
10920           !VD ||
10921           VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
10922       Diag(D->getLocation(),
10923            IsDecl ? diag::note_previous_decl : diag::note_defined_here)
10924           << D;
10925     }
10926     return true;
10927   }
10928   return false;
10929 }
10930 
10931 OMPClause *Sema::ActOnOpenMPLinearClause(
10932     ArrayRef<Expr *> VarList, Expr *Step, SourceLocation StartLoc,
10933     SourceLocation LParenLoc, OpenMPLinearClauseKind LinKind,
10934     SourceLocation LinLoc, SourceLocation ColonLoc, SourceLocation EndLoc) {
10935   SmallVector<Expr *, 8> Vars;
10936   SmallVector<Expr *, 8> Privates;
10937   SmallVector<Expr *, 8> Inits;
10938   SmallVector<Decl *, 4> ExprCaptures;
10939   SmallVector<Expr *, 4> ExprPostUpdates;
10940   if (CheckOpenMPLinearModifier(LinKind, LinLoc))
10941     LinKind = OMPC_LINEAR_val;
10942   for (Expr *RefExpr : VarList) {
10943     assert(RefExpr && "NULL expr in OpenMP linear clause.");
10944     SourceLocation ELoc;
10945     SourceRange ERange;
10946     Expr *SimpleRefExpr = RefExpr;
10947     auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange,
10948                               /*AllowArraySection=*/false);
10949     if (Res.second) {
10950       // It will be analyzed later.
10951       Vars.push_back(RefExpr);
10952       Privates.push_back(nullptr);
10953       Inits.push_back(nullptr);
10954     }
10955     ValueDecl *D = Res.first;
10956     if (!D)
10957       continue;
10958 
10959     QualType Type = D->getType();
10960     auto *VD = dyn_cast<VarDecl>(D);
10961 
10962     // OpenMP [2.14.3.7, linear clause]
10963     //  A list-item cannot appear in more than one linear clause.
10964     //  A list-item that appears in a linear clause cannot appear in any
10965     //  other data-sharing attribute clause.
10966     DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, /*FromParent=*/false);
10967     if (DVar.RefExpr) {
10968       Diag(ELoc, diag::err_omp_wrong_dsa) << getOpenMPClauseName(DVar.CKind)
10969                                           << getOpenMPClauseName(OMPC_linear);
10970       reportOriginalDsa(*this, DSAStack, D, DVar);
10971       continue;
10972     }
10973 
10974     if (CheckOpenMPLinearDecl(D, ELoc, LinKind, Type))
10975       continue;
10976     Type = Type.getNonReferenceType().getUnqualifiedType().getCanonicalType();
10977 
10978     // Build private copy of original var.
10979     VarDecl *Private =
10980         buildVarDecl(*this, ELoc, Type, D->getName(),
10981                      D->hasAttrs() ? &D->getAttrs() : nullptr,
10982                      VD ? cast<DeclRefExpr>(SimpleRefExpr) : nullptr);
10983     DeclRefExpr *PrivateRef = buildDeclRefExpr(*this, Private, Type, ELoc);
10984     // Build var to save initial value.
10985     VarDecl *Init = buildVarDecl(*this, ELoc, Type, ".linear.start");
10986     Expr *InitExpr;
10987     DeclRefExpr *Ref = nullptr;
10988     if (!VD && !CurContext->isDependentContext()) {
10989       Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/false);
10990       if (!isOpenMPCapturedDecl(D)) {
10991         ExprCaptures.push_back(Ref->getDecl());
10992         if (Ref->getDecl()->hasAttr<OMPCaptureNoInitAttr>()) {
10993           ExprResult RefRes = DefaultLvalueConversion(Ref);
10994           if (!RefRes.isUsable())
10995             continue;
10996           ExprResult PostUpdateRes =
10997               BuildBinOp(DSAStack->getCurScope(), ELoc, BO_Assign,
10998                          SimpleRefExpr, RefRes.get());
10999           if (!PostUpdateRes.isUsable())
11000             continue;
11001           ExprPostUpdates.push_back(
11002               IgnoredValueConversions(PostUpdateRes.get()).get());
11003         }
11004       }
11005     }
11006     if (LinKind == OMPC_LINEAR_uval)
11007       InitExpr = VD ? VD->getInit() : SimpleRefExpr;
11008     else
11009       InitExpr = VD ? SimpleRefExpr : Ref;
11010     AddInitializerToDecl(Init, DefaultLvalueConversion(InitExpr).get(),
11011                          /*DirectInit=*/false);
11012     DeclRefExpr *InitRef = buildDeclRefExpr(*this, Init, Type, ELoc);
11013 
11014     DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_linear, Ref);
11015     Vars.push_back((VD || CurContext->isDependentContext())
11016                        ? RefExpr->IgnoreParens()
11017                        : Ref);
11018     Privates.push_back(PrivateRef);
11019     Inits.push_back(InitRef);
11020   }
11021 
11022   if (Vars.empty())
11023     return nullptr;
11024 
11025   Expr *StepExpr = Step;
11026   Expr *CalcStepExpr = nullptr;
11027   if (Step && !Step->isValueDependent() && !Step->isTypeDependent() &&
11028       !Step->isInstantiationDependent() &&
11029       !Step->containsUnexpandedParameterPack()) {
11030     SourceLocation StepLoc = Step->getLocStart();
11031     ExprResult Val = PerformOpenMPImplicitIntegerConversion(StepLoc, Step);
11032     if (Val.isInvalid())
11033       return nullptr;
11034     StepExpr = Val.get();
11035 
11036     // Build var to save the step value.
11037     VarDecl *SaveVar =
11038         buildVarDecl(*this, StepLoc, StepExpr->getType(), ".linear.step");
11039     ExprResult SaveRef =
11040         buildDeclRefExpr(*this, SaveVar, StepExpr->getType(), StepLoc);
11041     ExprResult CalcStep =
11042         BuildBinOp(CurScope, StepLoc, BO_Assign, SaveRef.get(), StepExpr);
11043     CalcStep = ActOnFinishFullExpr(CalcStep.get());
11044 
11045     // Warn about zero linear step (it would be probably better specified as
11046     // making corresponding variables 'const').
11047     llvm::APSInt Result;
11048     bool IsConstant = StepExpr->isIntegerConstantExpr(Result, Context);
11049     if (IsConstant && !Result.isNegative() && !Result.isStrictlyPositive())
11050       Diag(StepLoc, diag::warn_omp_linear_step_zero) << Vars[0]
11051                                                      << (Vars.size() > 1);
11052     if (!IsConstant && CalcStep.isUsable()) {
11053       // Calculate the step beforehand instead of doing this on each iteration.
11054       // (This is not used if the number of iterations may be kfold-ed).
11055       CalcStepExpr = CalcStep.get();
11056     }
11057   }
11058 
11059   return OMPLinearClause::Create(Context, StartLoc, LParenLoc, LinKind, LinLoc,
11060                                  ColonLoc, EndLoc, Vars, Privates, Inits,
11061                                  StepExpr, CalcStepExpr,
11062                                  buildPreInits(Context, ExprCaptures),
11063                                  buildPostUpdate(*this, ExprPostUpdates));
11064 }
11065 
11066 static bool FinishOpenMPLinearClause(OMPLinearClause &Clause, DeclRefExpr *IV,
11067                                      Expr *NumIterations, Sema &SemaRef,
11068                                      Scope *S, DSAStackTy *Stack) {
11069   // Walk the vars and build update/final expressions for the CodeGen.
11070   SmallVector<Expr *, 8> Updates;
11071   SmallVector<Expr *, 8> Finals;
11072   Expr *Step = Clause.getStep();
11073   Expr *CalcStep = Clause.getCalcStep();
11074   // OpenMP [2.14.3.7, linear clause]
11075   // If linear-step is not specified it is assumed to be 1.
11076   if (!Step)
11077     Step = SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get();
11078   else if (CalcStep)
11079     Step = cast<BinaryOperator>(CalcStep)->getLHS();
11080   bool HasErrors = false;
11081   auto CurInit = Clause.inits().begin();
11082   auto CurPrivate = Clause.privates().begin();
11083   OpenMPLinearClauseKind LinKind = Clause.getModifier();
11084   for (Expr *RefExpr : Clause.varlists()) {
11085     SourceLocation ELoc;
11086     SourceRange ERange;
11087     Expr *SimpleRefExpr = RefExpr;
11088     auto Res = getPrivateItem(SemaRef, SimpleRefExpr, ELoc, ERange,
11089                               /*AllowArraySection=*/false);
11090     ValueDecl *D = Res.first;
11091     if (Res.second || !D) {
11092       Updates.push_back(nullptr);
11093       Finals.push_back(nullptr);
11094       HasErrors = true;
11095       continue;
11096     }
11097     auto &&Info = Stack->isLoopControlVariable(D);
11098     // OpenMP [2.15.11, distribute simd Construct]
11099     // A list item may not appear in a linear clause, unless it is the loop
11100     // iteration variable.
11101     if (isOpenMPDistributeDirective(Stack->getCurrentDirective()) &&
11102         isOpenMPSimdDirective(Stack->getCurrentDirective()) && !Info.first) {
11103       SemaRef.Diag(ELoc,
11104                    diag::err_omp_linear_distribute_var_non_loop_iteration);
11105       Updates.push_back(nullptr);
11106       Finals.push_back(nullptr);
11107       HasErrors = true;
11108       continue;
11109     }
11110     Expr *InitExpr = *CurInit;
11111 
11112     // Build privatized reference to the current linear var.
11113     auto *DE = cast<DeclRefExpr>(SimpleRefExpr);
11114     Expr *CapturedRef;
11115     if (LinKind == OMPC_LINEAR_uval)
11116       CapturedRef = cast<VarDecl>(DE->getDecl())->getInit();
11117     else
11118       CapturedRef =
11119           buildDeclRefExpr(SemaRef, cast<VarDecl>(DE->getDecl()),
11120                            DE->getType().getUnqualifiedType(), DE->getExprLoc(),
11121                            /*RefersToCapture=*/true);
11122 
11123     // Build update: Var = InitExpr + IV * Step
11124     ExprResult Update;
11125     if (!Info.first)
11126       Update =
11127           buildCounterUpdate(SemaRef, S, RefExpr->getExprLoc(), *CurPrivate,
11128                              InitExpr, IV, Step, /* Subtract */ false);
11129     else
11130       Update = *CurPrivate;
11131     Update = SemaRef.ActOnFinishFullExpr(Update.get(), DE->getLocStart(),
11132                                          /*DiscardedValue=*/true);
11133 
11134     // Build final: Var = InitExpr + NumIterations * Step
11135     ExprResult Final;
11136     if (!Info.first)
11137       Final =
11138           buildCounterUpdate(SemaRef, S, RefExpr->getExprLoc(), CapturedRef,
11139                              InitExpr, NumIterations, Step, /*Subtract=*/false);
11140     else
11141       Final = *CurPrivate;
11142     Final = SemaRef.ActOnFinishFullExpr(Final.get(), DE->getLocStart(),
11143                                         /*DiscardedValue=*/true);
11144 
11145     if (!Update.isUsable() || !Final.isUsable()) {
11146       Updates.push_back(nullptr);
11147       Finals.push_back(nullptr);
11148       HasErrors = true;
11149     } else {
11150       Updates.push_back(Update.get());
11151       Finals.push_back(Final.get());
11152     }
11153     ++CurInit;
11154     ++CurPrivate;
11155   }
11156   Clause.setUpdates(Updates);
11157   Clause.setFinals(Finals);
11158   return HasErrors;
11159 }
11160 
11161 OMPClause *Sema::ActOnOpenMPAlignedClause(
11162     ArrayRef<Expr *> VarList, Expr *Alignment, SourceLocation StartLoc,
11163     SourceLocation LParenLoc, SourceLocation ColonLoc, SourceLocation EndLoc) {
11164   SmallVector<Expr *, 8> Vars;
11165   for (Expr *RefExpr : VarList) {
11166     assert(RefExpr && "NULL expr in OpenMP linear clause.");
11167     SourceLocation ELoc;
11168     SourceRange ERange;
11169     Expr *SimpleRefExpr = RefExpr;
11170     auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange,
11171                               /*AllowArraySection=*/false);
11172     if (Res.second) {
11173       // It will be analyzed later.
11174       Vars.push_back(RefExpr);
11175     }
11176     ValueDecl *D = Res.first;
11177     if (!D)
11178       continue;
11179 
11180     QualType QType = D->getType();
11181     auto *VD = dyn_cast<VarDecl>(D);
11182 
11183     // OpenMP  [2.8.1, simd construct, Restrictions]
11184     // The type of list items appearing in the aligned clause must be
11185     // array, pointer, reference to array, or reference to pointer.
11186     QType = QType.getNonReferenceType().getUnqualifiedType().getCanonicalType();
11187     const Type *Ty = QType.getTypePtrOrNull();
11188     if (!Ty || (!Ty->isArrayType() && !Ty->isPointerType())) {
11189       Diag(ELoc, diag::err_omp_aligned_expected_array_or_ptr)
11190           << QType << getLangOpts().CPlusPlus << ERange;
11191       bool IsDecl =
11192           !VD ||
11193           VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
11194       Diag(D->getLocation(),
11195            IsDecl ? diag::note_previous_decl : diag::note_defined_here)
11196           << D;
11197       continue;
11198     }
11199 
11200     // OpenMP  [2.8.1, simd construct, Restrictions]
11201     // A list-item cannot appear in more than one aligned clause.
11202     if (const Expr *PrevRef = DSAStack->addUniqueAligned(D, SimpleRefExpr)) {
11203       Diag(ELoc, diag::err_omp_aligned_twice) << 0 << ERange;
11204       Diag(PrevRef->getExprLoc(), diag::note_omp_explicit_dsa)
11205           << getOpenMPClauseName(OMPC_aligned);
11206       continue;
11207     }
11208 
11209     DeclRefExpr *Ref = nullptr;
11210     if (!VD && isOpenMPCapturedDecl(D))
11211       Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/true);
11212     Vars.push_back(DefaultFunctionArrayConversion(
11213                        (VD || !Ref) ? RefExpr->IgnoreParens() : Ref)
11214                        .get());
11215   }
11216 
11217   // OpenMP [2.8.1, simd construct, Description]
11218   // The parameter of the aligned clause, alignment, must be a constant
11219   // positive integer expression.
11220   // If no optional parameter is specified, implementation-defined default
11221   // alignments for SIMD instructions on the target platforms are assumed.
11222   if (Alignment != nullptr) {
11223     ExprResult AlignResult =
11224         VerifyPositiveIntegerConstantInClause(Alignment, OMPC_aligned);
11225     if (AlignResult.isInvalid())
11226       return nullptr;
11227     Alignment = AlignResult.get();
11228   }
11229   if (Vars.empty())
11230     return nullptr;
11231 
11232   return OMPAlignedClause::Create(Context, StartLoc, LParenLoc, ColonLoc,
11233                                   EndLoc, Vars, Alignment);
11234 }
11235 
11236 OMPClause *Sema::ActOnOpenMPCopyinClause(ArrayRef<Expr *> VarList,
11237                                          SourceLocation StartLoc,
11238                                          SourceLocation LParenLoc,
11239                                          SourceLocation EndLoc) {
11240   SmallVector<Expr *, 8> Vars;
11241   SmallVector<Expr *, 8> SrcExprs;
11242   SmallVector<Expr *, 8> DstExprs;
11243   SmallVector<Expr *, 8> AssignmentOps;
11244   for (Expr *RefExpr : VarList) {
11245     assert(RefExpr && "NULL expr in OpenMP copyin clause.");
11246     if (isa<DependentScopeDeclRefExpr>(RefExpr)) {
11247       // It will be analyzed later.
11248       Vars.push_back(RefExpr);
11249       SrcExprs.push_back(nullptr);
11250       DstExprs.push_back(nullptr);
11251       AssignmentOps.push_back(nullptr);
11252       continue;
11253     }
11254 
11255     SourceLocation ELoc = RefExpr->getExprLoc();
11256     // OpenMP [2.1, C/C++]
11257     //  A list item is a variable name.
11258     // OpenMP  [2.14.4.1, Restrictions, p.1]
11259     //  A list item that appears in a copyin clause must be threadprivate.
11260     auto *DE = dyn_cast<DeclRefExpr>(RefExpr);
11261     if (!DE || !isa<VarDecl>(DE->getDecl())) {
11262       Diag(ELoc, diag::err_omp_expected_var_name_member_expr)
11263           << 0 << RefExpr->getSourceRange();
11264       continue;
11265     }
11266 
11267     Decl *D = DE->getDecl();
11268     auto *VD = cast<VarDecl>(D);
11269 
11270     QualType Type = VD->getType();
11271     if (Type->isDependentType() || Type->isInstantiationDependentType()) {
11272       // It will be analyzed later.
11273       Vars.push_back(DE);
11274       SrcExprs.push_back(nullptr);
11275       DstExprs.push_back(nullptr);
11276       AssignmentOps.push_back(nullptr);
11277       continue;
11278     }
11279 
11280     // OpenMP [2.14.4.1, Restrictions, C/C++, p.1]
11281     //  A list item that appears in a copyin clause must be threadprivate.
11282     if (!DSAStack->isThreadPrivate(VD)) {
11283       Diag(ELoc, diag::err_omp_required_access)
11284           << getOpenMPClauseName(OMPC_copyin)
11285           << getOpenMPDirectiveName(OMPD_threadprivate);
11286       continue;
11287     }
11288 
11289     // OpenMP [2.14.4.1, Restrictions, C/C++, p.2]
11290     //  A variable of class type (or array thereof) that appears in a
11291     //  copyin clause requires an accessible, unambiguous copy assignment
11292     //  operator for the class type.
11293     QualType ElemType = Context.getBaseElementType(Type).getNonReferenceType();
11294     VarDecl *SrcVD =
11295         buildVarDecl(*this, DE->getLocStart(), ElemType.getUnqualifiedType(),
11296                      ".copyin.src", VD->hasAttrs() ? &VD->getAttrs() : nullptr);
11297     DeclRefExpr *PseudoSrcExpr = buildDeclRefExpr(
11298         *this, SrcVD, ElemType.getUnqualifiedType(), DE->getExprLoc());
11299     VarDecl *DstVD =
11300         buildVarDecl(*this, DE->getLocStart(), ElemType, ".copyin.dst",
11301                      VD->hasAttrs() ? &VD->getAttrs() : nullptr);
11302     DeclRefExpr *PseudoDstExpr =
11303         buildDeclRefExpr(*this, DstVD, ElemType, DE->getExprLoc());
11304     // For arrays generate assignment operation for single element and replace
11305     // it by the original array element in CodeGen.
11306     ExprResult AssignmentOp =
11307         BuildBinOp(/*S=*/nullptr, DE->getExprLoc(), BO_Assign, PseudoDstExpr,
11308                    PseudoSrcExpr);
11309     if (AssignmentOp.isInvalid())
11310       continue;
11311     AssignmentOp = ActOnFinishFullExpr(AssignmentOp.get(), DE->getExprLoc(),
11312                                        /*DiscardedValue=*/true);
11313     if (AssignmentOp.isInvalid())
11314       continue;
11315 
11316     DSAStack->addDSA(VD, DE, OMPC_copyin);
11317     Vars.push_back(DE);
11318     SrcExprs.push_back(PseudoSrcExpr);
11319     DstExprs.push_back(PseudoDstExpr);
11320     AssignmentOps.push_back(AssignmentOp.get());
11321   }
11322 
11323   if (Vars.empty())
11324     return nullptr;
11325 
11326   return OMPCopyinClause::Create(Context, StartLoc, LParenLoc, EndLoc, Vars,
11327                                  SrcExprs, DstExprs, AssignmentOps);
11328 }
11329 
11330 OMPClause *Sema::ActOnOpenMPCopyprivateClause(ArrayRef<Expr *> VarList,
11331                                               SourceLocation StartLoc,
11332                                               SourceLocation LParenLoc,
11333                                               SourceLocation EndLoc) {
11334   SmallVector<Expr *, 8> Vars;
11335   SmallVector<Expr *, 8> SrcExprs;
11336   SmallVector<Expr *, 8> DstExprs;
11337   SmallVector<Expr *, 8> AssignmentOps;
11338   for (Expr *RefExpr : VarList) {
11339     assert(RefExpr && "NULL expr in OpenMP linear clause.");
11340     SourceLocation ELoc;
11341     SourceRange ERange;
11342     Expr *SimpleRefExpr = RefExpr;
11343     auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange,
11344                               /*AllowArraySection=*/false);
11345     if (Res.second) {
11346       // It will be analyzed later.
11347       Vars.push_back(RefExpr);
11348       SrcExprs.push_back(nullptr);
11349       DstExprs.push_back(nullptr);
11350       AssignmentOps.push_back(nullptr);
11351     }
11352     ValueDecl *D = Res.first;
11353     if (!D)
11354       continue;
11355 
11356     QualType Type = D->getType();
11357     auto *VD = dyn_cast<VarDecl>(D);
11358 
11359     // OpenMP [2.14.4.2, Restrictions, p.2]
11360     //  A list item that appears in a copyprivate clause may not appear in a
11361     //  private or firstprivate clause on the single construct.
11362     if (!VD || !DSAStack->isThreadPrivate(VD)) {
11363       DSAStackTy::DSAVarData DVar =
11364           DSAStack->getTopDSA(D, /*FromParent=*/false);
11365       if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_copyprivate &&
11366           DVar.RefExpr) {
11367         Diag(ELoc, diag::err_omp_wrong_dsa)
11368             << getOpenMPClauseName(DVar.CKind)
11369             << getOpenMPClauseName(OMPC_copyprivate);
11370         reportOriginalDsa(*this, DSAStack, D, DVar);
11371         continue;
11372       }
11373 
11374       // OpenMP [2.11.4.2, Restrictions, p.1]
11375       //  All list items that appear in a copyprivate clause must be either
11376       //  threadprivate or private in the enclosing context.
11377       if (DVar.CKind == OMPC_unknown) {
11378         DVar = DSAStack->getImplicitDSA(D, false);
11379         if (DVar.CKind == OMPC_shared) {
11380           Diag(ELoc, diag::err_omp_required_access)
11381               << getOpenMPClauseName(OMPC_copyprivate)
11382               << "threadprivate or private in the enclosing context";
11383           reportOriginalDsa(*this, DSAStack, D, DVar);
11384           continue;
11385         }
11386       }
11387     }
11388 
11389     // Variably modified types are not supported.
11390     if (!Type->isAnyPointerType() && Type->isVariablyModifiedType()) {
11391       Diag(ELoc, diag::err_omp_variably_modified_type_not_supported)
11392           << getOpenMPClauseName(OMPC_copyprivate) << Type
11393           << getOpenMPDirectiveName(DSAStack->getCurrentDirective());
11394       bool IsDecl =
11395           !VD ||
11396           VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
11397       Diag(D->getLocation(),
11398            IsDecl ? diag::note_previous_decl : diag::note_defined_here)
11399           << D;
11400       continue;
11401     }
11402 
11403     // OpenMP [2.14.4.1, Restrictions, C/C++, p.2]
11404     //  A variable of class type (or array thereof) that appears in a
11405     //  copyin clause requires an accessible, unambiguous copy assignment
11406     //  operator for the class type.
11407     Type = Context.getBaseElementType(Type.getNonReferenceType())
11408                .getUnqualifiedType();
11409     VarDecl *SrcVD =
11410         buildVarDecl(*this, RefExpr->getLocStart(), Type, ".copyprivate.src",
11411                      D->hasAttrs() ? &D->getAttrs() : nullptr);
11412     DeclRefExpr *PseudoSrcExpr = buildDeclRefExpr(*this, SrcVD, Type, ELoc);
11413     VarDecl *DstVD =
11414         buildVarDecl(*this, RefExpr->getLocStart(), Type, ".copyprivate.dst",
11415                      D->hasAttrs() ? &D->getAttrs() : nullptr);
11416     DeclRefExpr *PseudoDstExpr = buildDeclRefExpr(*this, DstVD, Type, ELoc);
11417     ExprResult AssignmentOp = BuildBinOp(
11418         DSAStack->getCurScope(), ELoc, BO_Assign, PseudoDstExpr, PseudoSrcExpr);
11419     if (AssignmentOp.isInvalid())
11420       continue;
11421     AssignmentOp = ActOnFinishFullExpr(AssignmentOp.get(), ELoc,
11422                                        /*DiscardedValue=*/true);
11423     if (AssignmentOp.isInvalid())
11424       continue;
11425 
11426     // No need to mark vars as copyprivate, they are already threadprivate or
11427     // implicitly private.
11428     assert(VD || isOpenMPCapturedDecl(D));
11429     Vars.push_back(
11430         VD ? RefExpr->IgnoreParens()
11431            : buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/false));
11432     SrcExprs.push_back(PseudoSrcExpr);
11433     DstExprs.push_back(PseudoDstExpr);
11434     AssignmentOps.push_back(AssignmentOp.get());
11435   }
11436 
11437   if (Vars.empty())
11438     return nullptr;
11439 
11440   return OMPCopyprivateClause::Create(Context, StartLoc, LParenLoc, EndLoc,
11441                                       Vars, SrcExprs, DstExprs, AssignmentOps);
11442 }
11443 
11444 OMPClause *Sema::ActOnOpenMPFlushClause(ArrayRef<Expr *> VarList,
11445                                         SourceLocation StartLoc,
11446                                         SourceLocation LParenLoc,
11447                                         SourceLocation EndLoc) {
11448   if (VarList.empty())
11449     return nullptr;
11450 
11451   return OMPFlushClause::Create(Context, StartLoc, LParenLoc, EndLoc, VarList);
11452 }
11453 
11454 OMPClause *
11455 Sema::ActOnOpenMPDependClause(OpenMPDependClauseKind DepKind,
11456                               SourceLocation DepLoc, SourceLocation ColonLoc,
11457                               ArrayRef<Expr *> VarList, SourceLocation StartLoc,
11458                               SourceLocation LParenLoc, SourceLocation EndLoc) {
11459   if (DSAStack->getCurrentDirective() == OMPD_ordered &&
11460       DepKind != OMPC_DEPEND_source && DepKind != OMPC_DEPEND_sink) {
11461     Diag(DepLoc, diag::err_omp_unexpected_clause_value)
11462         << "'source' or 'sink'" << getOpenMPClauseName(OMPC_depend);
11463     return nullptr;
11464   }
11465   if (DSAStack->getCurrentDirective() != OMPD_ordered &&
11466       (DepKind == OMPC_DEPEND_unknown || DepKind == OMPC_DEPEND_source ||
11467        DepKind == OMPC_DEPEND_sink)) {
11468     unsigned Except[] = {OMPC_DEPEND_source, OMPC_DEPEND_sink};
11469     Diag(DepLoc, diag::err_omp_unexpected_clause_value)
11470         << getListOfPossibleValues(OMPC_depend, /*First=*/0,
11471                                    /*Last=*/OMPC_DEPEND_unknown, Except)
11472         << getOpenMPClauseName(OMPC_depend);
11473     return nullptr;
11474   }
11475   SmallVector<Expr *, 8> Vars;
11476   DSAStackTy::OperatorOffsetTy OpsOffs;
11477   llvm::APSInt DepCounter(/*BitWidth=*/32);
11478   llvm::APSInt TotalDepCount(/*BitWidth=*/32);
11479   if (DepKind == OMPC_DEPEND_sink) {
11480     if (const Expr *OrderedCountExpr = DSAStack->getParentOrderedRegionParam()) {
11481       TotalDepCount = OrderedCountExpr->EvaluateKnownConstInt(Context);
11482       TotalDepCount.setIsUnsigned(/*Val=*/true);
11483     }
11484   }
11485   for (Expr *RefExpr : VarList) {
11486     assert(RefExpr && "NULL expr in OpenMP shared clause.");
11487     if (isa<DependentScopeDeclRefExpr>(RefExpr)) {
11488       // It will be analyzed later.
11489       Vars.push_back(RefExpr);
11490       continue;
11491     }
11492 
11493     SourceLocation ELoc = RefExpr->getExprLoc();
11494     Expr *SimpleExpr = RefExpr->IgnoreParenCasts();
11495     if (DepKind == OMPC_DEPEND_sink) {
11496       if (DSAStack->getParentOrderedRegionParam() &&
11497           DepCounter >= TotalDepCount) {
11498         Diag(ELoc, diag::err_omp_depend_sink_unexpected_expr);
11499         continue;
11500       }
11501       ++DepCounter;
11502       // OpenMP  [2.13.9, Summary]
11503       // depend(dependence-type : vec), where dependence-type is:
11504       // 'sink' and where vec is the iteration vector, which has the form:
11505       //  x1 [+- d1], x2 [+- d2 ], . . . , xn [+- dn]
11506       // where n is the value specified by the ordered clause in the loop
11507       // directive, xi denotes the loop iteration variable of the i-th nested
11508       // loop associated with the loop directive, and di is a constant
11509       // non-negative integer.
11510       if (CurContext->isDependentContext()) {
11511         // It will be analyzed later.
11512         Vars.push_back(RefExpr);
11513         continue;
11514       }
11515       SimpleExpr = SimpleExpr->IgnoreImplicit();
11516       OverloadedOperatorKind OOK = OO_None;
11517       SourceLocation OOLoc;
11518       Expr *LHS = SimpleExpr;
11519       Expr *RHS = nullptr;
11520       if (auto *BO = dyn_cast<BinaryOperator>(SimpleExpr)) {
11521         OOK = BinaryOperator::getOverloadedOperator(BO->getOpcode());
11522         OOLoc = BO->getOperatorLoc();
11523         LHS = BO->getLHS()->IgnoreParenImpCasts();
11524         RHS = BO->getRHS()->IgnoreParenImpCasts();
11525       } else if (auto *OCE = dyn_cast<CXXOperatorCallExpr>(SimpleExpr)) {
11526         OOK = OCE->getOperator();
11527         OOLoc = OCE->getOperatorLoc();
11528         LHS = OCE->getArg(/*Arg=*/0)->IgnoreParenImpCasts();
11529         RHS = OCE->getArg(/*Arg=*/1)->IgnoreParenImpCasts();
11530       } else if (auto *MCE = dyn_cast<CXXMemberCallExpr>(SimpleExpr)) {
11531         OOK = MCE->getMethodDecl()
11532                   ->getNameInfo()
11533                   .getName()
11534                   .getCXXOverloadedOperator();
11535         OOLoc = MCE->getCallee()->getExprLoc();
11536         LHS = MCE->getImplicitObjectArgument()->IgnoreParenImpCasts();
11537         RHS = MCE->getArg(/*Arg=*/0)->IgnoreParenImpCasts();
11538       }
11539       SourceLocation ELoc;
11540       SourceRange ERange;
11541       auto Res = getPrivateItem(*this, LHS, ELoc, ERange,
11542                                 /*AllowArraySection=*/false);
11543       if (Res.second) {
11544         // It will be analyzed later.
11545         Vars.push_back(RefExpr);
11546       }
11547       ValueDecl *D = Res.first;
11548       if (!D)
11549         continue;
11550 
11551       if (OOK != OO_Plus && OOK != OO_Minus && (RHS || OOK != OO_None)) {
11552         Diag(OOLoc, diag::err_omp_depend_sink_expected_plus_minus);
11553         continue;
11554       }
11555       if (RHS) {
11556         ExprResult RHSRes = VerifyPositiveIntegerConstantInClause(
11557             RHS, OMPC_depend, /*StrictlyPositive=*/false);
11558         if (RHSRes.isInvalid())
11559           continue;
11560       }
11561       if (!CurContext->isDependentContext() &&
11562           DSAStack->getParentOrderedRegionParam() &&
11563           DepCounter != DSAStack->isParentLoopControlVariable(D).first) {
11564         const ValueDecl *VD =
11565             DSAStack->getParentLoopControlVariable(DepCounter.getZExtValue());
11566         if (VD)
11567           Diag(ELoc, diag::err_omp_depend_sink_expected_loop_iteration)
11568               << 1 << VD;
11569         else
11570           Diag(ELoc, diag::err_omp_depend_sink_expected_loop_iteration) << 0;
11571         continue;
11572       }
11573       OpsOffs.emplace_back(RHS, OOK);
11574     } else {
11575       auto *ASE = dyn_cast<ArraySubscriptExpr>(SimpleExpr);
11576       if (!RefExpr->IgnoreParenImpCasts()->isLValue() ||
11577           (ASE &&
11578            !ASE->getBase()->getType().getNonReferenceType()->isPointerType() &&
11579            !ASE->getBase()->getType().getNonReferenceType()->isArrayType())) {
11580         Diag(ELoc, diag::err_omp_expected_addressable_lvalue_or_array_item)
11581             << RefExpr->getSourceRange();
11582         continue;
11583       }
11584       bool Suppress = getDiagnostics().getSuppressAllDiagnostics();
11585       getDiagnostics().setSuppressAllDiagnostics(/*Val=*/true);
11586       ExprResult Res =
11587           CreateBuiltinUnaryOp(ELoc, UO_AddrOf, RefExpr->IgnoreParenImpCasts());
11588       getDiagnostics().setSuppressAllDiagnostics(Suppress);
11589       if (!Res.isUsable() && !isa<OMPArraySectionExpr>(SimpleExpr)) {
11590         Diag(ELoc, diag::err_omp_expected_addressable_lvalue_or_array_item)
11591             << RefExpr->getSourceRange();
11592         continue;
11593       }
11594     }
11595     Vars.push_back(RefExpr->IgnoreParenImpCasts());
11596   }
11597 
11598   if (!CurContext->isDependentContext() && DepKind == OMPC_DEPEND_sink &&
11599       TotalDepCount > VarList.size() &&
11600       DSAStack->getParentOrderedRegionParam() &&
11601       DSAStack->getParentLoopControlVariable(VarList.size() + 1)) {
11602     Diag(EndLoc, diag::err_omp_depend_sink_expected_loop_iteration)
11603         << 1 << DSAStack->getParentLoopControlVariable(VarList.size() + 1);
11604   }
11605   if (DepKind != OMPC_DEPEND_source && DepKind != OMPC_DEPEND_sink &&
11606       Vars.empty())
11607     return nullptr;
11608 
11609   auto *C = OMPDependClause::Create(Context, StartLoc, LParenLoc, EndLoc,
11610                                     DepKind, DepLoc, ColonLoc, Vars);
11611   if ((DepKind == OMPC_DEPEND_sink || DepKind == OMPC_DEPEND_source) &&
11612       DSAStack->isParentOrderedRegion())
11613     DSAStack->addDoacrossDependClause(C, OpsOffs);
11614   return C;
11615 }
11616 
11617 OMPClause *Sema::ActOnOpenMPDeviceClause(Expr *Device, SourceLocation StartLoc,
11618                                          SourceLocation LParenLoc,
11619                                          SourceLocation EndLoc) {
11620   Expr *ValExpr = Device;
11621   Stmt *HelperValStmt = nullptr;
11622 
11623   // OpenMP [2.9.1, Restrictions]
11624   // The device expression must evaluate to a non-negative integer value.
11625   if (!isNonNegativeIntegerValue(ValExpr, *this, OMPC_device,
11626                                  /*StrictlyPositive=*/false))
11627     return nullptr;
11628 
11629   OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective();
11630   OpenMPDirectiveKind CaptureRegion =
11631       getOpenMPCaptureRegionForClause(DKind, OMPC_device);
11632   if (CaptureRegion != OMPD_unknown && !CurContext->isDependentContext()) {
11633     ValExpr = MakeFullExpr(ValExpr).get();
11634     llvm::MapVector<const Expr *, DeclRefExpr *> Captures;
11635     ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
11636     HelperValStmt = buildPreInits(Context, Captures);
11637   }
11638 
11639   return new (Context) OMPDeviceClause(ValExpr, HelperValStmt, CaptureRegion,
11640                                        StartLoc, LParenLoc, EndLoc);
11641 }
11642 
11643 static bool checkTypeMappable(SourceLocation SL, SourceRange SR, Sema &SemaRef,
11644                               DSAStackTy *Stack, QualType QTy,
11645                               bool FullCheck = true) {
11646   NamedDecl *ND;
11647   if (QTy->isIncompleteType(&ND)) {
11648     SemaRef.Diag(SL, diag::err_incomplete_type) << QTy << SR;
11649     return false;
11650   }
11651   if (FullCheck && !SemaRef.CurContext->isDependentContext() &&
11652       !QTy.isTrivialType(SemaRef.Context))
11653     SemaRef.Diag(SL, diag::warn_omp_non_trivial_type_mapped) << QTy << SR;
11654   return true;
11655 }
11656 
11657 /// Return true if it can be proven that the provided array expression
11658 /// (array section or array subscript) does NOT specify the whole size of the
11659 /// array whose base type is \a BaseQTy.
11660 static bool checkArrayExpressionDoesNotReferToWholeSize(Sema &SemaRef,
11661                                                         const Expr *E,
11662                                                         QualType BaseQTy) {
11663   const auto *OASE = dyn_cast<OMPArraySectionExpr>(E);
11664 
11665   // If this is an array subscript, it refers to the whole size if the size of
11666   // the dimension is constant and equals 1. Also, an array section assumes the
11667   // format of an array subscript if no colon is used.
11668   if (isa<ArraySubscriptExpr>(E) || (OASE && OASE->getColonLoc().isInvalid())) {
11669     if (const auto *ATy = dyn_cast<ConstantArrayType>(BaseQTy.getTypePtr()))
11670       return ATy->getSize().getSExtValue() != 1;
11671     // Size can't be evaluated statically.
11672     return false;
11673   }
11674 
11675   assert(OASE && "Expecting array section if not an array subscript.");
11676   const Expr *LowerBound = OASE->getLowerBound();
11677   const Expr *Length = OASE->getLength();
11678 
11679   // If there is a lower bound that does not evaluates to zero, we are not
11680   // covering the whole dimension.
11681   if (LowerBound) {
11682     llvm::APSInt ConstLowerBound;
11683     if (!LowerBound->EvaluateAsInt(ConstLowerBound, SemaRef.getASTContext()))
11684       return false; // Can't get the integer value as a constant.
11685     if (ConstLowerBound.getSExtValue())
11686       return true;
11687   }
11688 
11689   // If we don't have a length we covering the whole dimension.
11690   if (!Length)
11691     return false;
11692 
11693   // If the base is a pointer, we don't have a way to get the size of the
11694   // pointee.
11695   if (BaseQTy->isPointerType())
11696     return false;
11697 
11698   // We can only check if the length is the same as the size of the dimension
11699   // if we have a constant array.
11700   const auto *CATy = dyn_cast<ConstantArrayType>(BaseQTy.getTypePtr());
11701   if (!CATy)
11702     return false;
11703 
11704   llvm::APSInt ConstLength;
11705   if (!Length->EvaluateAsInt(ConstLength, SemaRef.getASTContext()))
11706     return false; // Can't get the integer value as a constant.
11707 
11708   return CATy->getSize().getSExtValue() != ConstLength.getSExtValue();
11709 }
11710 
11711 // Return true if it can be proven that the provided array expression (array
11712 // section or array subscript) does NOT specify a single element of the array
11713 // whose base type is \a BaseQTy.
11714 static bool checkArrayExpressionDoesNotReferToUnitySize(Sema &SemaRef,
11715                                                         const Expr *E,
11716                                                         QualType BaseQTy) {
11717   const auto *OASE = dyn_cast<OMPArraySectionExpr>(E);
11718 
11719   // An array subscript always refer to a single element. Also, an array section
11720   // assumes the format of an array subscript if no colon is used.
11721   if (isa<ArraySubscriptExpr>(E) || (OASE && OASE->getColonLoc().isInvalid()))
11722     return false;
11723 
11724   assert(OASE && "Expecting array section if not an array subscript.");
11725   const Expr *Length = OASE->getLength();
11726 
11727   // If we don't have a length we have to check if the array has unitary size
11728   // for this dimension. Also, we should always expect a length if the base type
11729   // is pointer.
11730   if (!Length) {
11731     if (const auto *ATy = dyn_cast<ConstantArrayType>(BaseQTy.getTypePtr()))
11732       return ATy->getSize().getSExtValue() != 1;
11733     // We cannot assume anything.
11734     return false;
11735   }
11736 
11737   // Check if the length evaluates to 1.
11738   llvm::APSInt ConstLength;
11739   if (!Length->EvaluateAsInt(ConstLength, SemaRef.getASTContext()))
11740     return false; // Can't get the integer value as a constant.
11741 
11742   return ConstLength.getSExtValue() != 1;
11743 }
11744 
11745 // Return the expression of the base of the mappable expression or null if it
11746 // cannot be determined and do all the necessary checks to see if the expression
11747 // is valid as a standalone mappable expression. In the process, record all the
11748 // components of the expression.
11749 static const Expr *checkMapClauseExpressionBase(
11750     Sema &SemaRef, Expr *E,
11751     OMPClauseMappableExprCommon::MappableExprComponentList &CurComponents,
11752     OpenMPClauseKind CKind, bool NoDiagnose) {
11753   SourceLocation ELoc = E->getExprLoc();
11754   SourceRange ERange = E->getSourceRange();
11755 
11756   // The base of elements of list in a map clause have to be either:
11757   //  - a reference to variable or field.
11758   //  - a member expression.
11759   //  - an array expression.
11760   //
11761   // E.g. if we have the expression 'r.S.Arr[:12]', we want to retrieve the
11762   // reference to 'r'.
11763   //
11764   // If we have:
11765   //
11766   // struct SS {
11767   //   Bla S;
11768   //   foo() {
11769   //     #pragma omp target map (S.Arr[:12]);
11770   //   }
11771   // }
11772   //
11773   // We want to retrieve the member expression 'this->S';
11774 
11775   const Expr *RelevantExpr = nullptr;
11776 
11777   // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.2]
11778   //  If a list item is an array section, it must specify contiguous storage.
11779   //
11780   // For this restriction it is sufficient that we make sure only references
11781   // to variables or fields and array expressions, and that no array sections
11782   // exist except in the rightmost expression (unless they cover the whole
11783   // dimension of the array). E.g. these would be invalid:
11784   //
11785   //   r.ArrS[3:5].Arr[6:7]
11786   //
11787   //   r.ArrS[3:5].x
11788   //
11789   // but these would be valid:
11790   //   r.ArrS[3].Arr[6:7]
11791   //
11792   //   r.ArrS[3].x
11793 
11794   bool AllowUnitySizeArraySection = true;
11795   bool AllowWholeSizeArraySection = true;
11796 
11797   while (!RelevantExpr) {
11798     E = E->IgnoreParenImpCasts();
11799 
11800     if (auto *CurE = dyn_cast<DeclRefExpr>(E)) {
11801       if (!isa<VarDecl>(CurE->getDecl()))
11802         return nullptr;
11803 
11804       RelevantExpr = CurE;
11805 
11806       // If we got a reference to a declaration, we should not expect any array
11807       // section before that.
11808       AllowUnitySizeArraySection = false;
11809       AllowWholeSizeArraySection = false;
11810 
11811       // Record the component.
11812       CurComponents.emplace_back(CurE, CurE->getDecl());
11813     } else if (auto *CurE = dyn_cast<MemberExpr>(E)) {
11814       Expr *BaseE = CurE->getBase()->IgnoreParenImpCasts();
11815 
11816       if (isa<CXXThisExpr>(BaseE))
11817         // We found a base expression: this->Val.
11818         RelevantExpr = CurE;
11819       else
11820         E = BaseE;
11821 
11822       if (!isa<FieldDecl>(CurE->getMemberDecl())) {
11823         if (!NoDiagnose) {
11824           SemaRef.Diag(ELoc, diag::err_omp_expected_access_to_data_field)
11825               << CurE->getSourceRange();
11826           return nullptr;
11827         }
11828         if (RelevantExpr)
11829           return nullptr;
11830         continue;
11831       }
11832 
11833       auto *FD = cast<FieldDecl>(CurE->getMemberDecl());
11834 
11835       // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C/C++, p.3]
11836       //  A bit-field cannot appear in a map clause.
11837       //
11838       if (FD->isBitField()) {
11839         if (!NoDiagnose) {
11840           SemaRef.Diag(ELoc, diag::err_omp_bit_fields_forbidden_in_clause)
11841               << CurE->getSourceRange() << getOpenMPClauseName(CKind);
11842           return nullptr;
11843         }
11844         if (RelevantExpr)
11845           return nullptr;
11846         continue;
11847       }
11848 
11849       // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C++, p.1]
11850       //  If the type of a list item is a reference to a type T then the type
11851       //  will be considered to be T for all purposes of this clause.
11852       QualType CurType = BaseE->getType().getNonReferenceType();
11853 
11854       // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C/C++, p.2]
11855       //  A list item cannot be a variable that is a member of a structure with
11856       //  a union type.
11857       //
11858       if (CurType->isUnionType()) {
11859         if (!NoDiagnose) {
11860           SemaRef.Diag(ELoc, diag::err_omp_union_type_not_allowed)
11861               << CurE->getSourceRange();
11862           return nullptr;
11863         }
11864         continue;
11865       }
11866 
11867       // If we got a member expression, we should not expect any array section
11868       // before that:
11869       //
11870       // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.7]
11871       //  If a list item is an element of a structure, only the rightmost symbol
11872       //  of the variable reference can be an array section.
11873       //
11874       AllowUnitySizeArraySection = false;
11875       AllowWholeSizeArraySection = false;
11876 
11877       // Record the component.
11878       CurComponents.emplace_back(CurE, FD);
11879     } else if (auto *CurE = dyn_cast<ArraySubscriptExpr>(E)) {
11880       E = CurE->getBase()->IgnoreParenImpCasts();
11881 
11882       if (!E->getType()->isAnyPointerType() && !E->getType()->isArrayType()) {
11883         if (!NoDiagnose) {
11884           SemaRef.Diag(ELoc, diag::err_omp_expected_base_var_name)
11885               << 0 << CurE->getSourceRange();
11886           return nullptr;
11887         }
11888         continue;
11889       }
11890 
11891       // If we got an array subscript that express the whole dimension we
11892       // can have any array expressions before. If it only expressing part of
11893       // the dimension, we can only have unitary-size array expressions.
11894       if (checkArrayExpressionDoesNotReferToWholeSize(SemaRef, CurE,
11895                                                       E->getType()))
11896         AllowWholeSizeArraySection = false;
11897 
11898       // Record the component - we don't have any declaration associated.
11899       CurComponents.emplace_back(CurE, nullptr);
11900     } else if (auto *CurE = dyn_cast<OMPArraySectionExpr>(E)) {
11901       assert(!NoDiagnose && "Array sections cannot be implicitly mapped.");
11902       E = CurE->getBase()->IgnoreParenImpCasts();
11903 
11904       QualType CurType =
11905           OMPArraySectionExpr::getBaseOriginalType(E).getCanonicalType();
11906 
11907       // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C++, p.1]
11908       //  If the type of a list item is a reference to a type T then the type
11909       //  will be considered to be T for all purposes of this clause.
11910       if (CurType->isReferenceType())
11911         CurType = CurType->getPointeeType();
11912 
11913       bool IsPointer = CurType->isAnyPointerType();
11914 
11915       if (!IsPointer && !CurType->isArrayType()) {
11916         SemaRef.Diag(ELoc, diag::err_omp_expected_base_var_name)
11917             << 0 << CurE->getSourceRange();
11918         return nullptr;
11919       }
11920 
11921       bool NotWhole =
11922           checkArrayExpressionDoesNotReferToWholeSize(SemaRef, CurE, CurType);
11923       bool NotUnity =
11924           checkArrayExpressionDoesNotReferToUnitySize(SemaRef, CurE, CurType);
11925 
11926       if (AllowWholeSizeArraySection) {
11927         // Any array section is currently allowed. Allowing a whole size array
11928         // section implies allowing a unity array section as well.
11929         //
11930         // If this array section refers to the whole dimension we can still
11931         // accept other array sections before this one, except if the base is a
11932         // pointer. Otherwise, only unitary sections are accepted.
11933         if (NotWhole || IsPointer)
11934           AllowWholeSizeArraySection = false;
11935       } else if (AllowUnitySizeArraySection && NotUnity) {
11936         // A unity or whole array section is not allowed and that is not
11937         // compatible with the properties of the current array section.
11938         SemaRef.Diag(
11939             ELoc, diag::err_array_section_does_not_specify_contiguous_storage)
11940             << CurE->getSourceRange();
11941         return nullptr;
11942       }
11943 
11944       // Record the component - we don't have any declaration associated.
11945       CurComponents.emplace_back(CurE, nullptr);
11946     } else {
11947       if (!NoDiagnose) {
11948         // If nothing else worked, this is not a valid map clause expression.
11949         SemaRef.Diag(
11950             ELoc, diag::err_omp_expected_named_var_member_or_array_expression)
11951             << ERange;
11952       }
11953       return nullptr;
11954     }
11955   }
11956 
11957   return RelevantExpr;
11958 }
11959 
11960 // Return true if expression E associated with value VD has conflicts with other
11961 // map information.
11962 static bool checkMapConflicts(
11963     Sema &SemaRef, DSAStackTy *DSAS, const ValueDecl *VD, const Expr *E,
11964     bool CurrentRegionOnly,
11965     OMPClauseMappableExprCommon::MappableExprComponentListRef CurComponents,
11966     OpenMPClauseKind CKind) {
11967   assert(VD && E);
11968   SourceLocation ELoc = E->getExprLoc();
11969   SourceRange ERange = E->getSourceRange();
11970 
11971   // In order to easily check the conflicts we need to match each component of
11972   // the expression under test with the components of the expressions that are
11973   // already in the stack.
11974 
11975   assert(!CurComponents.empty() && "Map clause expression with no components!");
11976   assert(CurComponents.back().getAssociatedDeclaration() == VD &&
11977          "Map clause expression with unexpected base!");
11978 
11979   // Variables to help detecting enclosing problems in data environment nests.
11980   bool IsEnclosedByDataEnvironmentExpr = false;
11981   const Expr *EnclosingExpr = nullptr;
11982 
11983   bool FoundError = DSAS->checkMappableExprComponentListsForDecl(
11984       VD, CurrentRegionOnly,
11985       [&IsEnclosedByDataEnvironmentExpr, &SemaRef, VD, CurrentRegionOnly, ELoc,
11986        ERange, CKind, &EnclosingExpr,
11987        CurComponents](OMPClauseMappableExprCommon::MappableExprComponentListRef
11988                           StackComponents,
11989                       OpenMPClauseKind) {
11990         assert(!StackComponents.empty() &&
11991                "Map clause expression with no components!");
11992         assert(StackComponents.back().getAssociatedDeclaration() == VD &&
11993                "Map clause expression with unexpected base!");
11994         (void)VD;
11995 
11996         // The whole expression in the stack.
11997         const Expr *RE = StackComponents.front().getAssociatedExpression();
11998 
11999         // Expressions must start from the same base. Here we detect at which
12000         // point both expressions diverge from each other and see if we can
12001         // detect if the memory referred to both expressions is contiguous and
12002         // do not overlap.
12003         auto CI = CurComponents.rbegin();
12004         auto CE = CurComponents.rend();
12005         auto SI = StackComponents.rbegin();
12006         auto SE = StackComponents.rend();
12007         for (; CI != CE && SI != SE; ++CI, ++SI) {
12008 
12009           // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.3]
12010           //  At most one list item can be an array item derived from a given
12011           //  variable in map clauses of the same construct.
12012           if (CurrentRegionOnly &&
12013               (isa<ArraySubscriptExpr>(CI->getAssociatedExpression()) ||
12014                isa<OMPArraySectionExpr>(CI->getAssociatedExpression())) &&
12015               (isa<ArraySubscriptExpr>(SI->getAssociatedExpression()) ||
12016                isa<OMPArraySectionExpr>(SI->getAssociatedExpression()))) {
12017             SemaRef.Diag(CI->getAssociatedExpression()->getExprLoc(),
12018                          diag::err_omp_multiple_array_items_in_map_clause)
12019                 << CI->getAssociatedExpression()->getSourceRange();
12020             SemaRef.Diag(SI->getAssociatedExpression()->getExprLoc(),
12021                          diag::note_used_here)
12022                 << SI->getAssociatedExpression()->getSourceRange();
12023             return true;
12024           }
12025 
12026           // Do both expressions have the same kind?
12027           if (CI->getAssociatedExpression()->getStmtClass() !=
12028               SI->getAssociatedExpression()->getStmtClass())
12029             break;
12030 
12031           // Are we dealing with different variables/fields?
12032           if (CI->getAssociatedDeclaration() != SI->getAssociatedDeclaration())
12033             break;
12034         }
12035         // Check if the extra components of the expressions in the enclosing
12036         // data environment are redundant for the current base declaration.
12037         // If they are, the maps completely overlap, which is legal.
12038         for (; SI != SE; ++SI) {
12039           QualType Type;
12040           if (const auto *ASE =
12041                   dyn_cast<ArraySubscriptExpr>(SI->getAssociatedExpression())) {
12042             Type = ASE->getBase()->IgnoreParenImpCasts()->getType();
12043           } else if (const auto *OASE = dyn_cast<OMPArraySectionExpr>(
12044                          SI->getAssociatedExpression())) {
12045             const Expr *E = OASE->getBase()->IgnoreParenImpCasts();
12046             Type =
12047                 OMPArraySectionExpr::getBaseOriginalType(E).getCanonicalType();
12048           }
12049           if (Type.isNull() || Type->isAnyPointerType() ||
12050               checkArrayExpressionDoesNotReferToWholeSize(
12051                   SemaRef, SI->getAssociatedExpression(), Type))
12052             break;
12053         }
12054 
12055         // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.4]
12056         //  List items of map clauses in the same construct must not share
12057         //  original storage.
12058         //
12059         // If the expressions are exactly the same or one is a subset of the
12060         // other, it means they are sharing storage.
12061         if (CI == CE && SI == SE) {
12062           if (CurrentRegionOnly) {
12063             if (CKind == OMPC_map) {
12064               SemaRef.Diag(ELoc, diag::err_omp_map_shared_storage) << ERange;
12065             } else {
12066               assert(CKind == OMPC_to || CKind == OMPC_from);
12067               SemaRef.Diag(ELoc, diag::err_omp_once_referenced_in_target_update)
12068                   << ERange;
12069             }
12070             SemaRef.Diag(RE->getExprLoc(), diag::note_used_here)
12071                 << RE->getSourceRange();
12072             return true;
12073           }
12074           // If we find the same expression in the enclosing data environment,
12075           // that is legal.
12076           IsEnclosedByDataEnvironmentExpr = true;
12077           return false;
12078         }
12079 
12080         QualType DerivedType =
12081             std::prev(CI)->getAssociatedDeclaration()->getType();
12082         SourceLocation DerivedLoc =
12083             std::prev(CI)->getAssociatedExpression()->getExprLoc();
12084 
12085         // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C++, p.1]
12086         //  If the type of a list item is a reference to a type T then the type
12087         //  will be considered to be T for all purposes of this clause.
12088         DerivedType = DerivedType.getNonReferenceType();
12089 
12090         // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C/C++, p.1]
12091         //  A variable for which the type is pointer and an array section
12092         //  derived from that variable must not appear as list items of map
12093         //  clauses of the same construct.
12094         //
12095         // Also, cover one of the cases in:
12096         // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.5]
12097         //  If any part of the original storage of a list item has corresponding
12098         //  storage in the device data environment, all of the original storage
12099         //  must have corresponding storage in the device data environment.
12100         //
12101         if (DerivedType->isAnyPointerType()) {
12102           if (CI == CE || SI == SE) {
12103             SemaRef.Diag(
12104                 DerivedLoc,
12105                 diag::err_omp_pointer_mapped_along_with_derived_section)
12106                 << DerivedLoc;
12107             SemaRef.Diag(RE->getExprLoc(), diag::note_used_here)
12108                 << RE->getSourceRange();
12109             return true;
12110           }
12111           if (CI->getAssociatedExpression()->getStmtClass() !=
12112                          SI->getAssociatedExpression()->getStmtClass() ||
12113                      CI->getAssociatedDeclaration()->getCanonicalDecl() ==
12114                          SI->getAssociatedDeclaration()->getCanonicalDecl()) {
12115             assert(CI != CE && SI != SE);
12116             SemaRef.Diag(DerivedLoc, diag::err_omp_same_pointer_dereferenced)
12117                 << DerivedLoc;
12118             SemaRef.Diag(RE->getExprLoc(), diag::note_used_here)
12119                 << RE->getSourceRange();
12120             return true;
12121           }
12122         }
12123 
12124         // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.4]
12125         //  List items of map clauses in the same construct must not share
12126         //  original storage.
12127         //
12128         // An expression is a subset of the other.
12129         if (CurrentRegionOnly && (CI == CE || SI == SE)) {
12130           if (CKind == OMPC_map) {
12131             SemaRef.Diag(ELoc, diag::err_omp_map_shared_storage) << ERange;
12132           } else {
12133             assert(CKind == OMPC_to || CKind == OMPC_from);
12134             SemaRef.Diag(ELoc, diag::err_omp_once_referenced_in_target_update)
12135                 << ERange;
12136           }
12137           SemaRef.Diag(RE->getExprLoc(), diag::note_used_here)
12138               << RE->getSourceRange();
12139           return true;
12140         }
12141 
12142         // The current expression uses the same base as other expression in the
12143         // data environment but does not contain it completely.
12144         if (!CurrentRegionOnly && SI != SE)
12145           EnclosingExpr = RE;
12146 
12147         // The current expression is a subset of the expression in the data
12148         // environment.
12149         IsEnclosedByDataEnvironmentExpr |=
12150             (!CurrentRegionOnly && CI != CE && SI == SE);
12151 
12152         return false;
12153       });
12154 
12155   if (CurrentRegionOnly)
12156     return FoundError;
12157 
12158   // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.5]
12159   //  If any part of the original storage of a list item has corresponding
12160   //  storage in the device data environment, all of the original storage must
12161   //  have corresponding storage in the device data environment.
12162   // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.6]
12163   //  If a list item is an element of a structure, and a different element of
12164   //  the structure has a corresponding list item in the device data environment
12165   //  prior to a task encountering the construct associated with the map clause,
12166   //  then the list item must also have a corresponding list item in the device
12167   //  data environment prior to the task encountering the construct.
12168   //
12169   if (EnclosingExpr && !IsEnclosedByDataEnvironmentExpr) {
12170     SemaRef.Diag(ELoc,
12171                  diag::err_omp_original_storage_is_shared_and_does_not_contain)
12172         << ERange;
12173     SemaRef.Diag(EnclosingExpr->getExprLoc(), diag::note_used_here)
12174         << EnclosingExpr->getSourceRange();
12175     return true;
12176   }
12177 
12178   return FoundError;
12179 }
12180 
12181 namespace {
12182 // Utility struct that gathers all the related lists associated with a mappable
12183 // expression.
12184 struct MappableVarListInfo {
12185   // The list of expressions.
12186   ArrayRef<Expr *> VarList;
12187   // The list of processed expressions.
12188   SmallVector<Expr *, 16> ProcessedVarList;
12189   // The mappble components for each expression.
12190   OMPClauseMappableExprCommon::MappableExprComponentLists VarComponents;
12191   // The base declaration of the variable.
12192   SmallVector<ValueDecl *, 16> VarBaseDeclarations;
12193 
12194   MappableVarListInfo(ArrayRef<Expr *> VarList) : VarList(VarList) {
12195     // We have a list of components and base declarations for each entry in the
12196     // variable list.
12197     VarComponents.reserve(VarList.size());
12198     VarBaseDeclarations.reserve(VarList.size());
12199   }
12200 };
12201 }
12202 
12203 // Check the validity of the provided variable list for the provided clause kind
12204 // \a CKind. In the check process the valid expressions, and mappable expression
12205 // components and variables are extracted and used to fill \a Vars,
12206 // \a ClauseComponents, and \a ClauseBaseDeclarations. \a MapType and
12207 // \a IsMapTypeImplicit are expected to be valid if the clause kind is 'map'.
12208 static void
12209 checkMappableExpressionList(Sema &SemaRef, DSAStackTy *DSAS,
12210                             OpenMPClauseKind CKind, MappableVarListInfo &MVLI,
12211                             SourceLocation StartLoc,
12212                             OpenMPMapClauseKind MapType = OMPC_MAP_unknown,
12213                             bool IsMapTypeImplicit = false) {
12214   // We only expect mappable expressions in 'to', 'from', and 'map' clauses.
12215   assert((CKind == OMPC_map || CKind == OMPC_to || CKind == OMPC_from) &&
12216          "Unexpected clause kind with mappable expressions!");
12217 
12218   // Keep track of the mappable components and base declarations in this clause.
12219   // Each entry in the list is going to have a list of components associated. We
12220   // record each set of the components so that we can build the clause later on.
12221   // In the end we should have the same amount of declarations and component
12222   // lists.
12223 
12224   for (Expr *RE : MVLI.VarList) {
12225     assert(RE && "Null expr in omp to/from/map clause");
12226     SourceLocation ELoc = RE->getExprLoc();
12227 
12228     const Expr *VE = RE->IgnoreParenLValueCasts();
12229 
12230     if (VE->isValueDependent() || VE->isTypeDependent() ||
12231         VE->isInstantiationDependent() ||
12232         VE->containsUnexpandedParameterPack()) {
12233       // We can only analyze this information once the missing information is
12234       // resolved.
12235       MVLI.ProcessedVarList.push_back(RE);
12236       continue;
12237     }
12238 
12239     Expr *SimpleExpr = RE->IgnoreParenCasts();
12240 
12241     if (!RE->IgnoreParenImpCasts()->isLValue()) {
12242       SemaRef.Diag(ELoc,
12243                    diag::err_omp_expected_named_var_member_or_array_expression)
12244           << RE->getSourceRange();
12245       continue;
12246     }
12247 
12248     OMPClauseMappableExprCommon::MappableExprComponentList CurComponents;
12249     ValueDecl *CurDeclaration = nullptr;
12250 
12251     // Obtain the array or member expression bases if required. Also, fill the
12252     // components array with all the components identified in the process.
12253     const Expr *BE = checkMapClauseExpressionBase(
12254         SemaRef, SimpleExpr, CurComponents, CKind, /*NoDiagnose=*/false);
12255     if (!BE)
12256       continue;
12257 
12258     assert(!CurComponents.empty() &&
12259            "Invalid mappable expression information.");
12260 
12261     // For the following checks, we rely on the base declaration which is
12262     // expected to be associated with the last component. The declaration is
12263     // expected to be a variable or a field (if 'this' is being mapped).
12264     CurDeclaration = CurComponents.back().getAssociatedDeclaration();
12265     assert(CurDeclaration && "Null decl on map clause.");
12266     assert(
12267         CurDeclaration->isCanonicalDecl() &&
12268         "Expecting components to have associated only canonical declarations.");
12269 
12270     auto *VD = dyn_cast<VarDecl>(CurDeclaration);
12271     const auto *FD = dyn_cast<FieldDecl>(CurDeclaration);
12272 
12273     assert((VD || FD) && "Only variables or fields are expected here!");
12274     (void)FD;
12275 
12276     // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.10]
12277     // threadprivate variables cannot appear in a map clause.
12278     // OpenMP 4.5 [2.10.5, target update Construct]
12279     // threadprivate variables cannot appear in a from clause.
12280     if (VD && DSAS->isThreadPrivate(VD)) {
12281       DSAStackTy::DSAVarData DVar = DSAS->getTopDSA(VD, /*FromParent=*/false);
12282       SemaRef.Diag(ELoc, diag::err_omp_threadprivate_in_clause)
12283           << getOpenMPClauseName(CKind);
12284       reportOriginalDsa(SemaRef, DSAS, VD, DVar);
12285       continue;
12286     }
12287 
12288     // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.9]
12289     //  A list item cannot appear in both a map clause and a data-sharing
12290     //  attribute clause on the same construct.
12291 
12292     // Check conflicts with other map clause expressions. We check the conflicts
12293     // with the current construct separately from the enclosing data
12294     // environment, because the restrictions are different. We only have to
12295     // check conflicts across regions for the map clauses.
12296     if (checkMapConflicts(SemaRef, DSAS, CurDeclaration, SimpleExpr,
12297                           /*CurrentRegionOnly=*/true, CurComponents, CKind))
12298       break;
12299     if (CKind == OMPC_map &&
12300         checkMapConflicts(SemaRef, DSAS, CurDeclaration, SimpleExpr,
12301                           /*CurrentRegionOnly=*/false, CurComponents, CKind))
12302       break;
12303 
12304     // OpenMP 4.5 [2.10.5, target update Construct]
12305     // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C++, p.1]
12306     //  If the type of a list item is a reference to a type T then the type will
12307     //  be considered to be T for all purposes of this clause.
12308     auto I = llvm::find_if(
12309         CurComponents,
12310         [](const OMPClauseMappableExprCommon::MappableComponent &MC) {
12311           return MC.getAssociatedDeclaration();
12312         });
12313     assert(I != CurComponents.end() && "Null decl on map clause.");
12314     QualType Type =
12315         I->getAssociatedDeclaration()->getType().getNonReferenceType();
12316 
12317     // OpenMP 4.5 [2.10.5, target update Construct, Restrictions, p.4]
12318     // A list item in a to or from clause must have a mappable type.
12319     // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.9]
12320     //  A list item must have a mappable type.
12321     if (!checkTypeMappable(VE->getExprLoc(), VE->getSourceRange(), SemaRef,
12322                            DSAS, Type))
12323       continue;
12324 
12325     if (CKind == OMPC_map) {
12326       // target enter data
12327       // OpenMP [2.10.2, Restrictions, p. 99]
12328       // A map-type must be specified in all map clauses and must be either
12329       // to or alloc.
12330       OpenMPDirectiveKind DKind = DSAS->getCurrentDirective();
12331       if (DKind == OMPD_target_enter_data &&
12332           !(MapType == OMPC_MAP_to || MapType == OMPC_MAP_alloc)) {
12333         SemaRef.Diag(StartLoc, diag::err_omp_invalid_map_type_for_directive)
12334             << (IsMapTypeImplicit ? 1 : 0)
12335             << getOpenMPSimpleClauseTypeName(OMPC_map, MapType)
12336             << getOpenMPDirectiveName(DKind);
12337         continue;
12338       }
12339 
12340       // target exit_data
12341       // OpenMP [2.10.3, Restrictions, p. 102]
12342       // A map-type must be specified in all map clauses and must be either
12343       // from, release, or delete.
12344       if (DKind == OMPD_target_exit_data &&
12345           !(MapType == OMPC_MAP_from || MapType == OMPC_MAP_release ||
12346             MapType == OMPC_MAP_delete)) {
12347         SemaRef.Diag(StartLoc, diag::err_omp_invalid_map_type_for_directive)
12348             << (IsMapTypeImplicit ? 1 : 0)
12349             << getOpenMPSimpleClauseTypeName(OMPC_map, MapType)
12350             << getOpenMPDirectiveName(DKind);
12351         continue;
12352       }
12353 
12354       // OpenMP 4.5 [2.15.5.1, Restrictions, p.3]
12355       // A list item cannot appear in both a map clause and a data-sharing
12356       // attribute clause on the same construct
12357       if (VD && isOpenMPTargetExecutionDirective(DKind)) {
12358         DSAStackTy::DSAVarData DVar = DSAS->getTopDSA(VD, /*FromParent=*/false);
12359         if (isOpenMPPrivate(DVar.CKind)) {
12360           SemaRef.Diag(ELoc, diag::err_omp_variable_in_given_clause_and_dsa)
12361               << getOpenMPClauseName(DVar.CKind)
12362               << getOpenMPClauseName(OMPC_map)
12363               << getOpenMPDirectiveName(DSAS->getCurrentDirective());
12364           reportOriginalDsa(SemaRef, DSAS, CurDeclaration, DVar);
12365           continue;
12366         }
12367       }
12368     }
12369 
12370     // Save the current expression.
12371     MVLI.ProcessedVarList.push_back(RE);
12372 
12373     // Store the components in the stack so that they can be used to check
12374     // against other clauses later on.
12375     DSAS->addMappableExpressionComponents(CurDeclaration, CurComponents,
12376                                           /*WhereFoundClauseKind=*/OMPC_map);
12377 
12378     // Save the components and declaration to create the clause. For purposes of
12379     // the clause creation, any component list that has has base 'this' uses
12380     // null as base declaration.
12381     MVLI.VarComponents.resize(MVLI.VarComponents.size() + 1);
12382     MVLI.VarComponents.back().append(CurComponents.begin(),
12383                                      CurComponents.end());
12384     MVLI.VarBaseDeclarations.push_back(isa<MemberExpr>(BE) ? nullptr
12385                                                            : CurDeclaration);
12386   }
12387 }
12388 
12389 OMPClause *
12390 Sema::ActOnOpenMPMapClause(OpenMPMapClauseKind MapTypeModifier,
12391                            OpenMPMapClauseKind MapType, bool IsMapTypeImplicit,
12392                            SourceLocation MapLoc, SourceLocation ColonLoc,
12393                            ArrayRef<Expr *> VarList, SourceLocation StartLoc,
12394                            SourceLocation LParenLoc, SourceLocation EndLoc) {
12395   MappableVarListInfo MVLI(VarList);
12396   checkMappableExpressionList(*this, DSAStack, OMPC_map, MVLI, StartLoc,
12397                               MapType, IsMapTypeImplicit);
12398 
12399   // We need to produce a map clause even if we don't have variables so that
12400   // other diagnostics related with non-existing map clauses are accurate.
12401   return OMPMapClause::Create(Context, StartLoc, LParenLoc, EndLoc,
12402                               MVLI.ProcessedVarList, MVLI.VarBaseDeclarations,
12403                               MVLI.VarComponents, MapTypeModifier, MapType,
12404                               IsMapTypeImplicit, MapLoc);
12405 }
12406 
12407 QualType Sema::ActOnOpenMPDeclareReductionType(SourceLocation TyLoc,
12408                                                TypeResult ParsedType) {
12409   assert(ParsedType.isUsable());
12410 
12411   QualType ReductionType = GetTypeFromParser(ParsedType.get());
12412   if (ReductionType.isNull())
12413     return QualType();
12414 
12415   // [OpenMP 4.0], 2.15 declare reduction Directive, Restrictions, C\C++
12416   // A type name in a declare reduction directive cannot be a function type, an
12417   // array type, a reference type, or a type qualified with const, volatile or
12418   // restrict.
12419   if (ReductionType.hasQualifiers()) {
12420     Diag(TyLoc, diag::err_omp_reduction_wrong_type) << 0;
12421     return QualType();
12422   }
12423 
12424   if (ReductionType->isFunctionType()) {
12425     Diag(TyLoc, diag::err_omp_reduction_wrong_type) << 1;
12426     return QualType();
12427   }
12428   if (ReductionType->isReferenceType()) {
12429     Diag(TyLoc, diag::err_omp_reduction_wrong_type) << 2;
12430     return QualType();
12431   }
12432   if (ReductionType->isArrayType()) {
12433     Diag(TyLoc, diag::err_omp_reduction_wrong_type) << 3;
12434     return QualType();
12435   }
12436   return ReductionType;
12437 }
12438 
12439 Sema::DeclGroupPtrTy Sema::ActOnOpenMPDeclareReductionDirectiveStart(
12440     Scope *S, DeclContext *DC, DeclarationName Name,
12441     ArrayRef<std::pair<QualType, SourceLocation>> ReductionTypes,
12442     AccessSpecifier AS, Decl *PrevDeclInScope) {
12443   SmallVector<Decl *, 8> Decls;
12444   Decls.reserve(ReductionTypes.size());
12445 
12446   LookupResult Lookup(*this, Name, SourceLocation(), LookupOMPReductionName,
12447                       forRedeclarationInCurContext());
12448   // [OpenMP 4.0], 2.15 declare reduction Directive, Restrictions
12449   // A reduction-identifier may not be re-declared in the current scope for the
12450   // same type or for a type that is compatible according to the base language
12451   // rules.
12452   llvm::DenseMap<QualType, SourceLocation> PreviousRedeclTypes;
12453   OMPDeclareReductionDecl *PrevDRD = nullptr;
12454   bool InCompoundScope = true;
12455   if (S != nullptr) {
12456     // Find previous declaration with the same name not referenced in other
12457     // declarations.
12458     FunctionScopeInfo *ParentFn = getEnclosingFunction();
12459     InCompoundScope =
12460         (ParentFn != nullptr) && !ParentFn->CompoundScopes.empty();
12461     LookupName(Lookup, S);
12462     FilterLookupForScope(Lookup, DC, S, /*ConsiderLinkage=*/false,
12463                          /*AllowInlineNamespace=*/false);
12464     llvm::DenseMap<OMPDeclareReductionDecl *, bool> UsedAsPrevious;
12465     LookupResult::Filter Filter = Lookup.makeFilter();
12466     while (Filter.hasNext()) {
12467       auto *PrevDecl = cast<OMPDeclareReductionDecl>(Filter.next());
12468       if (InCompoundScope) {
12469         auto I = UsedAsPrevious.find(PrevDecl);
12470         if (I == UsedAsPrevious.end())
12471           UsedAsPrevious[PrevDecl] = false;
12472         if (OMPDeclareReductionDecl *D = PrevDecl->getPrevDeclInScope())
12473           UsedAsPrevious[D] = true;
12474       }
12475       PreviousRedeclTypes[PrevDecl->getType().getCanonicalType()] =
12476           PrevDecl->getLocation();
12477     }
12478     Filter.done();
12479     if (InCompoundScope) {
12480       for (const auto &PrevData : UsedAsPrevious) {
12481         if (!PrevData.second) {
12482           PrevDRD = PrevData.first;
12483           break;
12484         }
12485       }
12486     }
12487   } else if (PrevDeclInScope != nullptr) {
12488     auto *PrevDRDInScope = PrevDRD =
12489         cast<OMPDeclareReductionDecl>(PrevDeclInScope);
12490     do {
12491       PreviousRedeclTypes[PrevDRDInScope->getType().getCanonicalType()] =
12492           PrevDRDInScope->getLocation();
12493       PrevDRDInScope = PrevDRDInScope->getPrevDeclInScope();
12494     } while (PrevDRDInScope != nullptr);
12495   }
12496   for (const auto &TyData : ReductionTypes) {
12497     const auto I = PreviousRedeclTypes.find(TyData.first.getCanonicalType());
12498     bool Invalid = false;
12499     if (I != PreviousRedeclTypes.end()) {
12500       Diag(TyData.second, diag::err_omp_declare_reduction_redefinition)
12501           << TyData.first;
12502       Diag(I->second, diag::note_previous_definition);
12503       Invalid = true;
12504     }
12505     PreviousRedeclTypes[TyData.first.getCanonicalType()] = TyData.second;
12506     auto *DRD = OMPDeclareReductionDecl::Create(Context, DC, TyData.second,
12507                                                 Name, TyData.first, PrevDRD);
12508     DC->addDecl(DRD);
12509     DRD->setAccess(AS);
12510     Decls.push_back(DRD);
12511     if (Invalid)
12512       DRD->setInvalidDecl();
12513     else
12514       PrevDRD = DRD;
12515   }
12516 
12517   return DeclGroupPtrTy::make(
12518       DeclGroupRef::Create(Context, Decls.begin(), Decls.size()));
12519 }
12520 
12521 void Sema::ActOnOpenMPDeclareReductionCombinerStart(Scope *S, Decl *D) {
12522   auto *DRD = cast<OMPDeclareReductionDecl>(D);
12523 
12524   // Enter new function scope.
12525   PushFunctionScope();
12526   setFunctionHasBranchProtectedScope();
12527   getCurFunction()->setHasOMPDeclareReductionCombiner();
12528 
12529   if (S != nullptr)
12530     PushDeclContext(S, DRD);
12531   else
12532     CurContext = DRD;
12533 
12534   PushExpressionEvaluationContext(
12535       ExpressionEvaluationContext::PotentiallyEvaluated);
12536 
12537   QualType ReductionType = DRD->getType();
12538   // Create 'T* omp_parm;T omp_in;'. All references to 'omp_in' will
12539   // be replaced by '*omp_parm' during codegen. This required because 'omp_in'
12540   // uses semantics of argument handles by value, but it should be passed by
12541   // reference. C lang does not support references, so pass all parameters as
12542   // pointers.
12543   // Create 'T omp_in;' variable.
12544   VarDecl *OmpInParm =
12545       buildVarDecl(*this, D->getLocation(), ReductionType, "omp_in");
12546   // Create 'T* omp_parm;T omp_out;'. All references to 'omp_out' will
12547   // be replaced by '*omp_parm' during codegen. This required because 'omp_out'
12548   // uses semantics of argument handles by value, but it should be passed by
12549   // reference. C lang does not support references, so pass all parameters as
12550   // pointers.
12551   // Create 'T omp_out;' variable.
12552   VarDecl *OmpOutParm =
12553       buildVarDecl(*this, D->getLocation(), ReductionType, "omp_out");
12554   if (S != nullptr) {
12555     PushOnScopeChains(OmpInParm, S);
12556     PushOnScopeChains(OmpOutParm, S);
12557   } else {
12558     DRD->addDecl(OmpInParm);
12559     DRD->addDecl(OmpOutParm);
12560   }
12561 }
12562 
12563 void Sema::ActOnOpenMPDeclareReductionCombinerEnd(Decl *D, Expr *Combiner) {
12564   auto *DRD = cast<OMPDeclareReductionDecl>(D);
12565   DiscardCleanupsInEvaluationContext();
12566   PopExpressionEvaluationContext();
12567 
12568   PopDeclContext();
12569   PopFunctionScopeInfo();
12570 
12571   if (Combiner != nullptr)
12572     DRD->setCombiner(Combiner);
12573   else
12574     DRD->setInvalidDecl();
12575 }
12576 
12577 VarDecl *Sema::ActOnOpenMPDeclareReductionInitializerStart(Scope *S, Decl *D) {
12578   auto *DRD = cast<OMPDeclareReductionDecl>(D);
12579 
12580   // Enter new function scope.
12581   PushFunctionScope();
12582   setFunctionHasBranchProtectedScope();
12583 
12584   if (S != nullptr)
12585     PushDeclContext(S, DRD);
12586   else
12587     CurContext = DRD;
12588 
12589   PushExpressionEvaluationContext(
12590       ExpressionEvaluationContext::PotentiallyEvaluated);
12591 
12592   QualType ReductionType = DRD->getType();
12593   // Create 'T* omp_parm;T omp_priv;'. All references to 'omp_priv' will
12594   // be replaced by '*omp_parm' during codegen. This required because 'omp_priv'
12595   // uses semantics of argument handles by value, but it should be passed by
12596   // reference. C lang does not support references, so pass all parameters as
12597   // pointers.
12598   // Create 'T omp_priv;' variable.
12599   VarDecl *OmpPrivParm =
12600       buildVarDecl(*this, D->getLocation(), ReductionType, "omp_priv");
12601   // Create 'T* omp_parm;T omp_orig;'. All references to 'omp_orig' will
12602   // be replaced by '*omp_parm' during codegen. This required because 'omp_orig'
12603   // uses semantics of argument handles by value, but it should be passed by
12604   // reference. C lang does not support references, so pass all parameters as
12605   // pointers.
12606   // Create 'T omp_orig;' variable.
12607   VarDecl *OmpOrigParm =
12608       buildVarDecl(*this, D->getLocation(), ReductionType, "omp_orig");
12609   if (S != nullptr) {
12610     PushOnScopeChains(OmpPrivParm, S);
12611     PushOnScopeChains(OmpOrigParm, S);
12612   } else {
12613     DRD->addDecl(OmpPrivParm);
12614     DRD->addDecl(OmpOrigParm);
12615   }
12616   return OmpPrivParm;
12617 }
12618 
12619 void Sema::ActOnOpenMPDeclareReductionInitializerEnd(Decl *D, Expr *Initializer,
12620                                                      VarDecl *OmpPrivParm) {
12621   auto *DRD = cast<OMPDeclareReductionDecl>(D);
12622   DiscardCleanupsInEvaluationContext();
12623   PopExpressionEvaluationContext();
12624 
12625   PopDeclContext();
12626   PopFunctionScopeInfo();
12627 
12628   if (Initializer != nullptr) {
12629     DRD->setInitializer(Initializer, OMPDeclareReductionDecl::CallInit);
12630   } else if (OmpPrivParm->hasInit()) {
12631     DRD->setInitializer(OmpPrivParm->getInit(),
12632                         OmpPrivParm->isDirectInit()
12633                             ? OMPDeclareReductionDecl::DirectInit
12634                             : OMPDeclareReductionDecl::CopyInit);
12635   } else {
12636     DRD->setInvalidDecl();
12637   }
12638 }
12639 
12640 Sema::DeclGroupPtrTy Sema::ActOnOpenMPDeclareReductionDirectiveEnd(
12641     Scope *S, DeclGroupPtrTy DeclReductions, bool IsValid) {
12642   for (Decl *D : DeclReductions.get()) {
12643     if (IsValid) {
12644       if (S)
12645         PushOnScopeChains(cast<OMPDeclareReductionDecl>(D), S,
12646                           /*AddToContext=*/false);
12647     } else {
12648       D->setInvalidDecl();
12649     }
12650   }
12651   return DeclReductions;
12652 }
12653 
12654 OMPClause *Sema::ActOnOpenMPNumTeamsClause(Expr *NumTeams,
12655                                            SourceLocation StartLoc,
12656                                            SourceLocation LParenLoc,
12657                                            SourceLocation EndLoc) {
12658   Expr *ValExpr = NumTeams;
12659   Stmt *HelperValStmt = nullptr;
12660 
12661   // OpenMP [teams Constrcut, Restrictions]
12662   // The num_teams expression must evaluate to a positive integer value.
12663   if (!isNonNegativeIntegerValue(ValExpr, *this, OMPC_num_teams,
12664                                  /*StrictlyPositive=*/true))
12665     return nullptr;
12666 
12667   OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective();
12668   OpenMPDirectiveKind CaptureRegion =
12669       getOpenMPCaptureRegionForClause(DKind, OMPC_num_teams);
12670   if (CaptureRegion != OMPD_unknown && !CurContext->isDependentContext()) {
12671     ValExpr = MakeFullExpr(ValExpr).get();
12672     llvm::MapVector<const Expr *, DeclRefExpr *> Captures;
12673     ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
12674     HelperValStmt = buildPreInits(Context, Captures);
12675   }
12676 
12677   return new (Context) OMPNumTeamsClause(ValExpr, HelperValStmt, CaptureRegion,
12678                                          StartLoc, LParenLoc, EndLoc);
12679 }
12680 
12681 OMPClause *Sema::ActOnOpenMPThreadLimitClause(Expr *ThreadLimit,
12682                                               SourceLocation StartLoc,
12683                                               SourceLocation LParenLoc,
12684                                               SourceLocation EndLoc) {
12685   Expr *ValExpr = ThreadLimit;
12686   Stmt *HelperValStmt = nullptr;
12687 
12688   // OpenMP [teams Constrcut, Restrictions]
12689   // The thread_limit expression must evaluate to a positive integer value.
12690   if (!isNonNegativeIntegerValue(ValExpr, *this, OMPC_thread_limit,
12691                                  /*StrictlyPositive=*/true))
12692     return nullptr;
12693 
12694   OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective();
12695   OpenMPDirectiveKind CaptureRegion =
12696       getOpenMPCaptureRegionForClause(DKind, OMPC_thread_limit);
12697   if (CaptureRegion != OMPD_unknown && !CurContext->isDependentContext()) {
12698     ValExpr = MakeFullExpr(ValExpr).get();
12699     llvm::MapVector<const Expr *, DeclRefExpr *> Captures;
12700     ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
12701     HelperValStmt = buildPreInits(Context, Captures);
12702   }
12703 
12704   return new (Context) OMPThreadLimitClause(
12705       ValExpr, HelperValStmt, CaptureRegion, StartLoc, LParenLoc, EndLoc);
12706 }
12707 
12708 OMPClause *Sema::ActOnOpenMPPriorityClause(Expr *Priority,
12709                                            SourceLocation StartLoc,
12710                                            SourceLocation LParenLoc,
12711                                            SourceLocation EndLoc) {
12712   Expr *ValExpr = Priority;
12713 
12714   // OpenMP [2.9.1, task Constrcut]
12715   // The priority-value is a non-negative numerical scalar expression.
12716   if (!isNonNegativeIntegerValue(ValExpr, *this, OMPC_priority,
12717                                  /*StrictlyPositive=*/false))
12718     return nullptr;
12719 
12720   return new (Context) OMPPriorityClause(ValExpr, StartLoc, LParenLoc, EndLoc);
12721 }
12722 
12723 OMPClause *Sema::ActOnOpenMPGrainsizeClause(Expr *Grainsize,
12724                                             SourceLocation StartLoc,
12725                                             SourceLocation LParenLoc,
12726                                             SourceLocation EndLoc) {
12727   Expr *ValExpr = Grainsize;
12728 
12729   // OpenMP [2.9.2, taskloop Constrcut]
12730   // The parameter of the grainsize clause must be a positive integer
12731   // expression.
12732   if (!isNonNegativeIntegerValue(ValExpr, *this, OMPC_grainsize,
12733                                  /*StrictlyPositive=*/true))
12734     return nullptr;
12735 
12736   return new (Context) OMPGrainsizeClause(ValExpr, StartLoc, LParenLoc, EndLoc);
12737 }
12738 
12739 OMPClause *Sema::ActOnOpenMPNumTasksClause(Expr *NumTasks,
12740                                            SourceLocation StartLoc,
12741                                            SourceLocation LParenLoc,
12742                                            SourceLocation EndLoc) {
12743   Expr *ValExpr = NumTasks;
12744 
12745   // OpenMP [2.9.2, taskloop Constrcut]
12746   // The parameter of the num_tasks clause must be a positive integer
12747   // expression.
12748   if (!isNonNegativeIntegerValue(ValExpr, *this, OMPC_num_tasks,
12749                                  /*StrictlyPositive=*/true))
12750     return nullptr;
12751 
12752   return new (Context) OMPNumTasksClause(ValExpr, StartLoc, LParenLoc, EndLoc);
12753 }
12754 
12755 OMPClause *Sema::ActOnOpenMPHintClause(Expr *Hint, SourceLocation StartLoc,
12756                                        SourceLocation LParenLoc,
12757                                        SourceLocation EndLoc) {
12758   // OpenMP [2.13.2, critical construct, Description]
12759   // ... where hint-expression is an integer constant expression that evaluates
12760   // to a valid lock hint.
12761   ExprResult HintExpr = VerifyPositiveIntegerConstantInClause(Hint, OMPC_hint);
12762   if (HintExpr.isInvalid())
12763     return nullptr;
12764   return new (Context)
12765       OMPHintClause(HintExpr.get(), StartLoc, LParenLoc, EndLoc);
12766 }
12767 
12768 OMPClause *Sema::ActOnOpenMPDistScheduleClause(
12769     OpenMPDistScheduleClauseKind Kind, Expr *ChunkSize, SourceLocation StartLoc,
12770     SourceLocation LParenLoc, SourceLocation KindLoc, SourceLocation CommaLoc,
12771     SourceLocation EndLoc) {
12772   if (Kind == OMPC_DIST_SCHEDULE_unknown) {
12773     std::string Values;
12774     Values += "'";
12775     Values += getOpenMPSimpleClauseTypeName(OMPC_dist_schedule, 0);
12776     Values += "'";
12777     Diag(KindLoc, diag::err_omp_unexpected_clause_value)
12778         << Values << getOpenMPClauseName(OMPC_dist_schedule);
12779     return nullptr;
12780   }
12781   Expr *ValExpr = ChunkSize;
12782   Stmt *HelperValStmt = nullptr;
12783   if (ChunkSize) {
12784     if (!ChunkSize->isValueDependent() && !ChunkSize->isTypeDependent() &&
12785         !ChunkSize->isInstantiationDependent() &&
12786         !ChunkSize->containsUnexpandedParameterPack()) {
12787       SourceLocation ChunkSizeLoc = ChunkSize->getLocStart();
12788       ExprResult Val =
12789           PerformOpenMPImplicitIntegerConversion(ChunkSizeLoc, ChunkSize);
12790       if (Val.isInvalid())
12791         return nullptr;
12792 
12793       ValExpr = Val.get();
12794 
12795       // OpenMP [2.7.1, Restrictions]
12796       //  chunk_size must be a loop invariant integer expression with a positive
12797       //  value.
12798       llvm::APSInt Result;
12799       if (ValExpr->isIntegerConstantExpr(Result, Context)) {
12800         if (Result.isSigned() && !Result.isStrictlyPositive()) {
12801           Diag(ChunkSizeLoc, diag::err_omp_negative_expression_in_clause)
12802               << "dist_schedule" << ChunkSize->getSourceRange();
12803           return nullptr;
12804         }
12805       } else if (getOpenMPCaptureRegionForClause(
12806                      DSAStack->getCurrentDirective(), OMPC_dist_schedule) !=
12807                      OMPD_unknown &&
12808                  !CurContext->isDependentContext()) {
12809         ValExpr = MakeFullExpr(ValExpr).get();
12810         llvm::MapVector<const Expr *, DeclRefExpr *> Captures;
12811         ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
12812         HelperValStmt = buildPreInits(Context, Captures);
12813       }
12814     }
12815   }
12816 
12817   return new (Context)
12818       OMPDistScheduleClause(StartLoc, LParenLoc, KindLoc, CommaLoc, EndLoc,
12819                             Kind, ValExpr, HelperValStmt);
12820 }
12821 
12822 OMPClause *Sema::ActOnOpenMPDefaultmapClause(
12823     OpenMPDefaultmapClauseModifier M, OpenMPDefaultmapClauseKind Kind,
12824     SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation MLoc,
12825     SourceLocation KindLoc, SourceLocation EndLoc) {
12826   // OpenMP 4.5 only supports 'defaultmap(tofrom: scalar)'
12827   if (M != OMPC_DEFAULTMAP_MODIFIER_tofrom || Kind != OMPC_DEFAULTMAP_scalar) {
12828     std::string Value;
12829     SourceLocation Loc;
12830     Value += "'";
12831     if (M != OMPC_DEFAULTMAP_MODIFIER_tofrom) {
12832       Value += getOpenMPSimpleClauseTypeName(OMPC_defaultmap,
12833                                              OMPC_DEFAULTMAP_MODIFIER_tofrom);
12834       Loc = MLoc;
12835     } else {
12836       Value += getOpenMPSimpleClauseTypeName(OMPC_defaultmap,
12837                                              OMPC_DEFAULTMAP_scalar);
12838       Loc = KindLoc;
12839     }
12840     Value += "'";
12841     Diag(Loc, diag::err_omp_unexpected_clause_value)
12842         << Value << getOpenMPClauseName(OMPC_defaultmap);
12843     return nullptr;
12844   }
12845   DSAStack->setDefaultDMAToFromScalar(StartLoc);
12846 
12847   return new (Context)
12848       OMPDefaultmapClause(StartLoc, LParenLoc, MLoc, KindLoc, EndLoc, Kind, M);
12849 }
12850 
12851 bool Sema::ActOnStartOpenMPDeclareTargetDirective(SourceLocation Loc) {
12852   DeclContext *CurLexicalContext = getCurLexicalContext();
12853   if (!CurLexicalContext->isFileContext() &&
12854       !CurLexicalContext->isExternCContext() &&
12855       !CurLexicalContext->isExternCXXContext() &&
12856       !isa<CXXRecordDecl>(CurLexicalContext) &&
12857       !isa<ClassTemplateDecl>(CurLexicalContext) &&
12858       !isa<ClassTemplatePartialSpecializationDecl>(CurLexicalContext) &&
12859       !isa<ClassTemplateSpecializationDecl>(CurLexicalContext)) {
12860     Diag(Loc, diag::err_omp_region_not_file_context);
12861     return false;
12862   }
12863   if (IsInOpenMPDeclareTargetContext) {
12864     Diag(Loc, diag::err_omp_enclosed_declare_target);
12865     return false;
12866   }
12867 
12868   IsInOpenMPDeclareTargetContext = true;
12869   return true;
12870 }
12871 
12872 void Sema::ActOnFinishOpenMPDeclareTargetDirective() {
12873   assert(IsInOpenMPDeclareTargetContext &&
12874          "Unexpected ActOnFinishOpenMPDeclareTargetDirective");
12875   IsInOpenMPDeclareTargetContext = false;
12876 }
12877 
12878 void Sema::ActOnOpenMPDeclareTargetName(Scope *CurScope,
12879                                         CXXScopeSpec &ScopeSpec,
12880                                         const DeclarationNameInfo &Id,
12881                                         OMPDeclareTargetDeclAttr::MapTypeTy MT,
12882                                         NamedDeclSetType &SameDirectiveDecls) {
12883   LookupResult Lookup(*this, Id, LookupOrdinaryName);
12884   LookupParsedName(Lookup, CurScope, &ScopeSpec, true);
12885 
12886   if (Lookup.isAmbiguous())
12887     return;
12888   Lookup.suppressDiagnostics();
12889 
12890   if (!Lookup.isSingleResult()) {
12891     if (TypoCorrection Corrected =
12892             CorrectTypo(Id, LookupOrdinaryName, CurScope, nullptr,
12893                         llvm::make_unique<VarOrFuncDeclFilterCCC>(*this),
12894                         CTK_ErrorRecovery)) {
12895       diagnoseTypo(Corrected, PDiag(diag::err_undeclared_var_use_suggest)
12896                                   << Id.getName());
12897       checkDeclIsAllowedInOpenMPTarget(nullptr, Corrected.getCorrectionDecl());
12898       return;
12899     }
12900 
12901     Diag(Id.getLoc(), diag::err_undeclared_var_use) << Id.getName();
12902     return;
12903   }
12904 
12905   NamedDecl *ND = Lookup.getAsSingle<NamedDecl>();
12906   if (isa<VarDecl>(ND) || isa<FunctionDecl>(ND)) {
12907     if (!SameDirectiveDecls.insert(cast<NamedDecl>(ND->getCanonicalDecl())))
12908       Diag(Id.getLoc(), diag::err_omp_declare_target_multiple) << Id.getName();
12909     if (!ND->hasAttr<OMPDeclareTargetDeclAttr>()) {
12910       auto *A = OMPDeclareTargetDeclAttr::CreateImplicit(Context, MT);
12911       ND->addAttr(A);
12912       if (ASTMutationListener *ML = Context.getASTMutationListener())
12913         ML->DeclarationMarkedOpenMPDeclareTarget(ND, A);
12914       checkDeclIsAllowedInOpenMPTarget(nullptr, ND, Id.getLoc());
12915     } else if (ND->getAttr<OMPDeclareTargetDeclAttr>()->getMapType() != MT) {
12916       Diag(Id.getLoc(), diag::err_omp_declare_target_to_and_link)
12917           << Id.getName();
12918     }
12919   } else {
12920     Diag(Id.getLoc(), diag::err_omp_invalid_target_decl) << Id.getName();
12921   }
12922 }
12923 
12924 static void checkDeclInTargetContext(SourceLocation SL, SourceRange SR,
12925                                      Sema &SemaRef, Decl *D) {
12926   if (!D)
12927     return;
12928   const Decl *LD = nullptr;
12929   if (isa<TagDecl>(D)) {
12930     LD = cast<TagDecl>(D)->getDefinition();
12931   } else if (isa<VarDecl>(D)) {
12932     LD = cast<VarDecl>(D)->getDefinition();
12933 
12934     // If this is an implicit variable that is legal and we do not need to do
12935     // anything.
12936     if (cast<VarDecl>(D)->isImplicit()) {
12937       auto *A = OMPDeclareTargetDeclAttr::CreateImplicit(
12938           SemaRef.Context, OMPDeclareTargetDeclAttr::MT_To);
12939       D->addAttr(A);
12940       if (ASTMutationListener *ML = SemaRef.Context.getASTMutationListener())
12941         ML->DeclarationMarkedOpenMPDeclareTarget(D, A);
12942       return;
12943     }
12944   } else if (const auto *F = dyn_cast<FunctionDecl>(D)) {
12945     const FunctionDecl *FD = nullptr;
12946     if (cast<FunctionDecl>(D)->hasBody(FD)) {
12947       LD = FD;
12948       // If the definition is associated with the current declaration in the
12949       // target region (it can be e.g. a lambda) that is legal and we do not
12950       // need to do anything else.
12951       if (LD == D) {
12952         auto *A = OMPDeclareTargetDeclAttr::CreateImplicit(
12953             SemaRef.Context, OMPDeclareTargetDeclAttr::MT_To);
12954         D->addAttr(A);
12955         if (ASTMutationListener *ML = SemaRef.Context.getASTMutationListener())
12956           ML->DeclarationMarkedOpenMPDeclareTarget(D, A);
12957         return;
12958       }
12959     } else if (F->isFunctionTemplateSpecialization() &&
12960                F->getTemplateSpecializationKind() ==
12961                    TSK_ImplicitInstantiation) {
12962       // Check if the function is implicitly instantiated from the template
12963       // defined in the declare target region.
12964       const FunctionTemplateDecl *FTD = F->getPrimaryTemplate();
12965       if (FTD && FTD->hasAttr<OMPDeclareTargetDeclAttr>())
12966         return;
12967     }
12968   }
12969   if (!LD)
12970     LD = D;
12971   if (LD && !LD->hasAttr<OMPDeclareTargetDeclAttr>() &&
12972       ((isa<VarDecl>(LD) && !isa<ParmVarDecl>(LD)) || isa<FunctionDecl>(LD))) {
12973     // Outlined declaration is not declared target.
12974     if (!isa<FunctionDecl>(LD)) {
12975       if (LD->isOutOfLine()) {
12976         SemaRef.Diag(LD->getLocation(), diag::warn_omp_not_in_target_context);
12977         SemaRef.Diag(SL, diag::note_used_here) << SR;
12978       } else {
12979         const DeclContext *DC = LD->getDeclContext();
12980         while (DC &&
12981                (!isa<FunctionDecl>(DC) ||
12982                 !cast<FunctionDecl>(DC)->hasAttr<OMPDeclareTargetDeclAttr>()))
12983           DC = DC->getParent();
12984         if (DC)
12985           return;
12986 
12987         // Is not declared in target context.
12988         SemaRef.Diag(LD->getLocation(), diag::warn_omp_not_in_target_context);
12989         SemaRef.Diag(SL, diag::note_used_here) << SR;
12990       }
12991     }
12992     // Mark decl as declared target to prevent further diagnostic.
12993     auto *A = OMPDeclareTargetDeclAttr::CreateImplicit(
12994         SemaRef.Context, OMPDeclareTargetDeclAttr::MT_To);
12995     D->addAttr(A);
12996     if (ASTMutationListener *ML = SemaRef.Context.getASTMutationListener())
12997       ML->DeclarationMarkedOpenMPDeclareTarget(D, A);
12998   }
12999 }
13000 
13001 static bool checkValueDeclInTarget(SourceLocation SL, SourceRange SR,
13002                                    Sema &SemaRef, DSAStackTy *Stack,
13003                                    ValueDecl *VD) {
13004   return VD->hasAttr<OMPDeclareTargetDeclAttr>() ||
13005          checkTypeMappable(SL, SR, SemaRef, Stack, VD->getType(),
13006                            /*FullCheck=*/false);
13007 }
13008 
13009 void Sema::checkDeclIsAllowedInOpenMPTarget(Expr *E, Decl *D,
13010                                             SourceLocation IdLoc) {
13011   if (!D || D->isInvalidDecl())
13012     return;
13013   SourceRange SR = E ? E->getSourceRange() : D->getSourceRange();
13014   SourceLocation SL = E ? E->getLocStart() : D->getLocation();
13015   // 2.10.6: threadprivate variable cannot appear in a declare target directive.
13016   if (auto *VD = dyn_cast<VarDecl>(D)) {
13017     if (DSAStack->isThreadPrivate(VD)) {
13018       Diag(SL, diag::err_omp_threadprivate_in_target);
13019       reportOriginalDsa(*this, DSAStack, VD, DSAStack->getTopDSA(VD, false));
13020       return;
13021     }
13022   }
13023   if (auto *VD = dyn_cast<ValueDecl>(D)) {
13024     // Problem if any with var declared with incomplete type will be reported
13025     // as normal, so no need to check it here.
13026     if ((E || !VD->getType()->isIncompleteType()) &&
13027         !checkValueDeclInTarget(SL, SR, *this, DSAStack, VD)) {
13028       // Mark decl as declared target to prevent further diagnostic.
13029       if (isa<VarDecl>(VD) || isa<FunctionDecl>(VD) ||
13030           isa<FunctionTemplateDecl>(VD)) {
13031         auto *A = OMPDeclareTargetDeclAttr::CreateImplicit(
13032             Context, OMPDeclareTargetDeclAttr::MT_To);
13033         VD->addAttr(A);
13034         if (ASTMutationListener *ML = Context.getASTMutationListener())
13035           ML->DeclarationMarkedOpenMPDeclareTarget(VD, A);
13036       }
13037       return;
13038     }
13039   }
13040   if (const auto *FD = dyn_cast<FunctionDecl>(D)) {
13041     if (FD->hasAttr<OMPDeclareTargetDeclAttr>() &&
13042         (FD->getAttr<OMPDeclareTargetDeclAttr>()->getMapType() ==
13043          OMPDeclareTargetDeclAttr::MT_Link)) {
13044       assert(IdLoc.isValid() && "Source location is expected");
13045       Diag(IdLoc, diag::err_omp_function_in_link_clause);
13046       Diag(FD->getLocation(), diag::note_defined_here) << FD;
13047       return;
13048     }
13049   }
13050   if (const auto *FTD = dyn_cast<FunctionTemplateDecl>(D)) {
13051     if (FTD->hasAttr<OMPDeclareTargetDeclAttr>() &&
13052         (FTD->getAttr<OMPDeclareTargetDeclAttr>()->getMapType() ==
13053          OMPDeclareTargetDeclAttr::MT_Link)) {
13054       assert(IdLoc.isValid() && "Source location is expected");
13055       Diag(IdLoc, diag::err_omp_function_in_link_clause);
13056       Diag(FTD->getLocation(), diag::note_defined_here) << FTD;
13057       return;
13058     }
13059   }
13060   if (!E) {
13061     // Checking declaration inside declare target region.
13062     if (!D->hasAttr<OMPDeclareTargetDeclAttr>() &&
13063         (isa<VarDecl>(D) || isa<FunctionDecl>(D) ||
13064          isa<FunctionTemplateDecl>(D))) {
13065       auto *A = OMPDeclareTargetDeclAttr::CreateImplicit(
13066           Context, OMPDeclareTargetDeclAttr::MT_To);
13067       D->addAttr(A);
13068       if (ASTMutationListener *ML = Context.getASTMutationListener())
13069         ML->DeclarationMarkedOpenMPDeclareTarget(D, A);
13070     }
13071     return;
13072   }
13073   checkDeclInTargetContext(E->getExprLoc(), E->getSourceRange(), *this, D);
13074 }
13075 
13076 OMPClause *Sema::ActOnOpenMPToClause(ArrayRef<Expr *> VarList,
13077                                      SourceLocation StartLoc,
13078                                      SourceLocation LParenLoc,
13079                                      SourceLocation EndLoc) {
13080   MappableVarListInfo MVLI(VarList);
13081   checkMappableExpressionList(*this, DSAStack, OMPC_to, MVLI, StartLoc);
13082   if (MVLI.ProcessedVarList.empty())
13083     return nullptr;
13084 
13085   return OMPToClause::Create(Context, StartLoc, LParenLoc, EndLoc,
13086                              MVLI.ProcessedVarList, MVLI.VarBaseDeclarations,
13087                              MVLI.VarComponents);
13088 }
13089 
13090 OMPClause *Sema::ActOnOpenMPFromClause(ArrayRef<Expr *> VarList,
13091                                        SourceLocation StartLoc,
13092                                        SourceLocation LParenLoc,
13093                                        SourceLocation EndLoc) {
13094   MappableVarListInfo MVLI(VarList);
13095   checkMappableExpressionList(*this, DSAStack, OMPC_from, MVLI, StartLoc);
13096   if (MVLI.ProcessedVarList.empty())
13097     return nullptr;
13098 
13099   return OMPFromClause::Create(Context, StartLoc, LParenLoc, EndLoc,
13100                                MVLI.ProcessedVarList, MVLI.VarBaseDeclarations,
13101                                MVLI.VarComponents);
13102 }
13103 
13104 OMPClause *Sema::ActOnOpenMPUseDevicePtrClause(ArrayRef<Expr *> VarList,
13105                                                SourceLocation StartLoc,
13106                                                SourceLocation LParenLoc,
13107                                                SourceLocation EndLoc) {
13108   MappableVarListInfo MVLI(VarList);
13109   SmallVector<Expr *, 8> PrivateCopies;
13110   SmallVector<Expr *, 8> Inits;
13111 
13112   for (Expr *RefExpr : VarList) {
13113     assert(RefExpr && "NULL expr in OpenMP use_device_ptr clause.");
13114     SourceLocation ELoc;
13115     SourceRange ERange;
13116     Expr *SimpleRefExpr = RefExpr;
13117     auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
13118     if (Res.second) {
13119       // It will be analyzed later.
13120       MVLI.ProcessedVarList.push_back(RefExpr);
13121       PrivateCopies.push_back(nullptr);
13122       Inits.push_back(nullptr);
13123     }
13124     ValueDecl *D = Res.first;
13125     if (!D)
13126       continue;
13127 
13128     QualType Type = D->getType();
13129     Type = Type.getNonReferenceType().getUnqualifiedType();
13130 
13131     auto *VD = dyn_cast<VarDecl>(D);
13132 
13133     // Item should be a pointer or reference to pointer.
13134     if (!Type->isPointerType()) {
13135       Diag(ELoc, diag::err_omp_usedeviceptr_not_a_pointer)
13136           << 0 << RefExpr->getSourceRange();
13137       continue;
13138     }
13139 
13140     // Build the private variable and the expression that refers to it.
13141     auto VDPrivate =
13142         buildVarDecl(*this, ELoc, Type, D->getName(),
13143                      D->hasAttrs() ? &D->getAttrs() : nullptr,
13144                      VD ? cast<DeclRefExpr>(SimpleRefExpr) : nullptr);
13145     if (VDPrivate->isInvalidDecl())
13146       continue;
13147 
13148     CurContext->addDecl(VDPrivate);
13149     DeclRefExpr *VDPrivateRefExpr = buildDeclRefExpr(
13150         *this, VDPrivate, RefExpr->getType().getUnqualifiedType(), ELoc);
13151 
13152     // Add temporary variable to initialize the private copy of the pointer.
13153     VarDecl *VDInit =
13154         buildVarDecl(*this, RefExpr->getExprLoc(), Type, ".devptr.temp");
13155     DeclRefExpr *VDInitRefExpr = buildDeclRefExpr(
13156         *this, VDInit, RefExpr->getType(), RefExpr->getExprLoc());
13157     AddInitializerToDecl(VDPrivate,
13158                          DefaultLvalueConversion(VDInitRefExpr).get(),
13159                          /*DirectInit=*/false);
13160 
13161     // If required, build a capture to implement the privatization initialized
13162     // with the current list item value.
13163     DeclRefExpr *Ref = nullptr;
13164     if (!VD)
13165       Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/true);
13166     MVLI.ProcessedVarList.push_back(VD ? RefExpr->IgnoreParens() : Ref);
13167     PrivateCopies.push_back(VDPrivateRefExpr);
13168     Inits.push_back(VDInitRefExpr);
13169 
13170     // We need to add a data sharing attribute for this variable to make sure it
13171     // is correctly captured. A variable that shows up in a use_device_ptr has
13172     // similar properties of a first private variable.
13173     DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_firstprivate, Ref);
13174 
13175     // Create a mappable component for the list item. List items in this clause
13176     // only need a component.
13177     MVLI.VarBaseDeclarations.push_back(D);
13178     MVLI.VarComponents.resize(MVLI.VarComponents.size() + 1);
13179     MVLI.VarComponents.back().push_back(
13180         OMPClauseMappableExprCommon::MappableComponent(SimpleRefExpr, D));
13181   }
13182 
13183   if (MVLI.ProcessedVarList.empty())
13184     return nullptr;
13185 
13186   return OMPUseDevicePtrClause::Create(
13187       Context, StartLoc, LParenLoc, EndLoc, MVLI.ProcessedVarList,
13188       PrivateCopies, Inits, MVLI.VarBaseDeclarations, MVLI.VarComponents);
13189 }
13190 
13191 OMPClause *Sema::ActOnOpenMPIsDevicePtrClause(ArrayRef<Expr *> VarList,
13192                                               SourceLocation StartLoc,
13193                                               SourceLocation LParenLoc,
13194                                               SourceLocation EndLoc) {
13195   MappableVarListInfo MVLI(VarList);
13196   for (Expr *RefExpr : VarList) {
13197     assert(RefExpr && "NULL expr in OpenMP is_device_ptr clause.");
13198     SourceLocation ELoc;
13199     SourceRange ERange;
13200     Expr *SimpleRefExpr = RefExpr;
13201     auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
13202     if (Res.second) {
13203       // It will be analyzed later.
13204       MVLI.ProcessedVarList.push_back(RefExpr);
13205     }
13206     ValueDecl *D = Res.first;
13207     if (!D)
13208       continue;
13209 
13210     QualType Type = D->getType();
13211     // item should be a pointer or array or reference to pointer or array
13212     if (!Type.getNonReferenceType()->isPointerType() &&
13213         !Type.getNonReferenceType()->isArrayType()) {
13214       Diag(ELoc, diag::err_omp_argument_type_isdeviceptr)
13215           << 0 << RefExpr->getSourceRange();
13216       continue;
13217     }
13218 
13219     // Check if the declaration in the clause does not show up in any data
13220     // sharing attribute.
13221     DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, /*FromParent=*/false);
13222     if (isOpenMPPrivate(DVar.CKind)) {
13223       Diag(ELoc, diag::err_omp_variable_in_given_clause_and_dsa)
13224           << getOpenMPClauseName(DVar.CKind)
13225           << getOpenMPClauseName(OMPC_is_device_ptr)
13226           << getOpenMPDirectiveName(DSAStack->getCurrentDirective());
13227       reportOriginalDsa(*this, DSAStack, D, DVar);
13228       continue;
13229     }
13230 
13231     const Expr *ConflictExpr;
13232     if (DSAStack->checkMappableExprComponentListsForDecl(
13233             D, /*CurrentRegionOnly=*/true,
13234             [&ConflictExpr](
13235                 OMPClauseMappableExprCommon::MappableExprComponentListRef R,
13236                 OpenMPClauseKind) -> bool {
13237               ConflictExpr = R.front().getAssociatedExpression();
13238               return true;
13239             })) {
13240       Diag(ELoc, diag::err_omp_map_shared_storage) << RefExpr->getSourceRange();
13241       Diag(ConflictExpr->getExprLoc(), diag::note_used_here)
13242           << ConflictExpr->getSourceRange();
13243       continue;
13244     }
13245 
13246     // Store the components in the stack so that they can be used to check
13247     // against other clauses later on.
13248     OMPClauseMappableExprCommon::MappableComponent MC(SimpleRefExpr, D);
13249     DSAStack->addMappableExpressionComponents(
13250         D, MC, /*WhereFoundClauseKind=*/OMPC_is_device_ptr);
13251 
13252     // Record the expression we've just processed.
13253     MVLI.ProcessedVarList.push_back(SimpleRefExpr);
13254 
13255     // Create a mappable component for the list item. List items in this clause
13256     // only need a component. We use a null declaration to signal fields in
13257     // 'this'.
13258     assert((isa<DeclRefExpr>(SimpleRefExpr) ||
13259             isa<CXXThisExpr>(cast<MemberExpr>(SimpleRefExpr)->getBase())) &&
13260            "Unexpected device pointer expression!");
13261     MVLI.VarBaseDeclarations.push_back(
13262         isa<DeclRefExpr>(SimpleRefExpr) ? D : nullptr);
13263     MVLI.VarComponents.resize(MVLI.VarComponents.size() + 1);
13264     MVLI.VarComponents.back().push_back(MC);
13265   }
13266 
13267   if (MVLI.ProcessedVarList.empty())
13268     return nullptr;
13269 
13270   return OMPIsDevicePtrClause::Create(
13271       Context, StartLoc, LParenLoc, EndLoc, MVLI.ProcessedVarList,
13272       MVLI.VarBaseDeclarations, MVLI.VarComponents);
13273 }
13274