1 //===--- SemaOpenMP.cpp - Semantic Analysis for OpenMP constructs ---------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 /// \brief This file implements semantic analysis for OpenMP directives and
13 //===----------------------------------------------------------------------===//
15 #include "TreeTransform.h"
16 #include "clang/AST/ASTContext.h"
17 #include "clang/AST/ASTMutationListener.h"
18 #include "clang/AST/CXXInheritance.h"
19 #include "clang/AST/Decl.h"
20 #include "clang/AST/DeclCXX.h"
21 #include "clang/AST/DeclOpenMP.h"
22 #include "clang/AST/StmtCXX.h"
23 #include "clang/AST/StmtOpenMP.h"
24 #include "clang/AST/StmtVisitor.h"
25 #include "clang/AST/TypeOrdering.h"
26 #include "clang/Basic/OpenMPKinds.h"
27 #include "clang/Basic/TargetInfo.h"
28 #include "clang/Lex/Preprocessor.h"
29 #include "clang/Sema/Initialization.h"
30 #include "clang/Sema/Lookup.h"
31 #include "clang/Sema/Scope.h"
32 #include "clang/Sema/ScopeInfo.h"
33 #include "clang/Sema/SemaInternal.h"
34 using namespace clang;
36 //===----------------------------------------------------------------------===//
37 // Stack of data-sharing attributes for variables
38 //===----------------------------------------------------------------------===//
41 /// \brief Default data sharing attributes, which can be applied to directive.
42 enum DefaultDataSharingAttributes {
43 DSA_unspecified = 0, /// \brief Data sharing attribute not specified.
44 DSA_none = 1 << 0, /// \brief Default data sharing attribute 'none'.
45 DSA_shared = 1 << 1 /// \brief Default data sharing attribute 'shared'.
48 /// \brief Stack for tracking declarations used in OpenMP directives and
49 /// clauses and their data-sharing attributes.
50 class DSAStackTy final {
52 struct DSAVarData final {
53 OpenMPDirectiveKind DKind = OMPD_unknown;
54 OpenMPClauseKind CKind = OMPC_unknown;
55 Expr *RefExpr = nullptr;
56 DeclRefExpr *PrivateCopy = nullptr;
57 SourceLocation ImplicitDSALoc;
60 typedef llvm::SmallVector<std::pair<Expr *, OverloadedOperatorKind>, 4>
64 struct DSAInfo final {
65 OpenMPClauseKind Attributes = OMPC_unknown;
66 /// Pointer to a reference expression and a flag which shows that the
67 /// variable is marked as lastprivate(true) or not (false).
68 llvm::PointerIntPair<Expr *, 1, bool> RefExpr;
69 DeclRefExpr *PrivateCopy = nullptr;
71 typedef llvm::DenseMap<ValueDecl *, DSAInfo> DeclSAMapTy;
72 typedef llvm::DenseMap<ValueDecl *, Expr *> AlignedMapTy;
73 typedef std::pair<unsigned, VarDecl *> LCDeclInfo;
74 typedef llvm::DenseMap<ValueDecl *, LCDeclInfo> LoopControlVariablesMapTy;
75 /// Struct that associates a component with the clause kind where they are
77 struct MappedExprComponentTy {
78 OMPClauseMappableExprCommon::MappableExprComponentLists Components;
79 OpenMPClauseKind Kind = OMPC_unknown;
81 typedef llvm::DenseMap<ValueDecl *, MappedExprComponentTy>
82 MappedExprComponentsTy;
83 typedef llvm::StringMap<std::pair<OMPCriticalDirective *, llvm::APSInt>>
85 typedef llvm::DenseMap<OMPDependClause *, OperatorOffsetTy>
88 struct SharingMapTy final {
89 DeclSAMapTy SharingMap;
90 AlignedMapTy AlignedMap;
91 MappedExprComponentsTy MappedExprComponents;
92 LoopControlVariablesMapTy LCVMap;
93 DefaultDataSharingAttributes DefaultAttr = DSA_unspecified;
94 SourceLocation DefaultAttrLoc;
95 OpenMPDirectiveKind Directive = OMPD_unknown;
96 DeclarationNameInfo DirectiveName;
97 Scope *CurScope = nullptr;
98 SourceLocation ConstructLoc;
99 /// Set of 'depend' clauses with 'sink|source' dependence kind. Required to
100 /// get the data (loop counters etc.) about enclosing loop-based construct.
101 /// This data is required during codegen.
102 DoacrossDependMapTy DoacrossDepends;
103 /// \brief first argument (Expr *) contains optional argument of the
104 /// 'ordered' clause, the second one is true if the regions has 'ordered'
105 /// clause, false otherwise.
106 llvm::PointerIntPair<Expr *, 1, bool> OrderedRegion;
107 bool NowaitRegion = false;
108 bool CancelRegion = false;
109 unsigned AssociatedLoops = 1;
110 SourceLocation InnerTeamsRegionLoc;
111 SharingMapTy(OpenMPDirectiveKind DKind, DeclarationNameInfo Name,
112 Scope *CurScope, SourceLocation Loc)
113 : Directive(DKind), DirectiveName(Name), CurScope(CurScope),
118 typedef SmallVector<SharingMapTy, 4> StackTy;
120 /// \brief Stack of used declaration and their data-sharing attributes.
122 /// \brief true, if check for DSA must be from parent directive, false, if
123 /// from current directive.
124 OpenMPClauseKind ClauseKindMode = OMPC_unknown;
126 bool ForceCapturing = false;
127 CriticalsWithHintsTy Criticals;
129 typedef SmallVector<SharingMapTy, 8>::reverse_iterator reverse_iterator;
131 DSAVarData getDSA(StackTy::reverse_iterator &Iter, ValueDecl *D);
133 /// \brief Checks if the variable is a local for OpenMP region.
134 bool isOpenMPLocal(VarDecl *D, StackTy::reverse_iterator Iter);
137 explicit DSAStackTy(Sema &S) : Stack(1), SemaRef(S) {}
139 bool isClauseParsingMode() const { return ClauseKindMode != OMPC_unknown; }
140 void setClauseParsingMode(OpenMPClauseKind K) { ClauseKindMode = K; }
142 bool isForceVarCapturing() const { return ForceCapturing; }
143 void setForceVarCapturing(bool V) { ForceCapturing = V; }
145 void push(OpenMPDirectiveKind DKind, const DeclarationNameInfo &DirName,
146 Scope *CurScope, SourceLocation Loc) {
147 Stack.push_back(SharingMapTy(DKind, DirName, CurScope, Loc));
148 Stack.back().DefaultAttrLoc = Loc;
152 assert(Stack.size() > 1 && "Data-sharing attributes stack is empty!");
156 void addCriticalWithHint(OMPCriticalDirective *D, llvm::APSInt Hint) {
157 Criticals[D->getDirectiveName().getAsString()] = std::make_pair(D, Hint);
159 const std::pair<OMPCriticalDirective *, llvm::APSInt>
160 getCriticalWithHint(const DeclarationNameInfo &Name) const {
161 auto I = Criticals.find(Name.getAsString());
162 if (I != Criticals.end())
164 return std::make_pair(nullptr, llvm::APSInt());
166 /// \brief If 'aligned' declaration for given variable \a D was not seen yet,
167 /// add it and return NULL; otherwise return previous occurrence's expression
169 Expr *addUniqueAligned(ValueDecl *D, Expr *NewDE);
171 /// \brief Register specified variable as loop control variable.
172 void addLoopControlVariable(ValueDecl *D, VarDecl *Capture);
173 /// \brief Check if the specified variable is a loop control variable for
175 /// \return The index of the loop control variable in the list of associated
176 /// for-loops (from outer to inner).
177 LCDeclInfo isLoopControlVariable(ValueDecl *D);
178 /// \brief Check if the specified variable is a loop control variable for
180 /// \return The index of the loop control variable in the list of associated
181 /// for-loops (from outer to inner).
182 LCDeclInfo isParentLoopControlVariable(ValueDecl *D);
183 /// \brief Get the loop control variable for the I-th loop (or nullptr) in
184 /// parent directive.
185 ValueDecl *getParentLoopControlVariable(unsigned I);
187 /// \brief Adds explicit data sharing attribute to the specified declaration.
188 void addDSA(ValueDecl *D, Expr *E, OpenMPClauseKind A,
189 DeclRefExpr *PrivateCopy = nullptr);
191 /// \brief Returns data sharing attributes from top of the stack for the
192 /// specified declaration.
193 DSAVarData getTopDSA(ValueDecl *D, bool FromParent);
194 /// \brief Returns data-sharing attributes for the specified declaration.
195 DSAVarData getImplicitDSA(ValueDecl *D, bool FromParent);
196 /// \brief Checks if the specified variables has data-sharing attributes which
197 /// match specified \a CPred predicate in any directive which matches \a DPred
199 DSAVarData hasDSA(ValueDecl *D,
200 const llvm::function_ref<bool(OpenMPClauseKind)> &CPred,
201 const llvm::function_ref<bool(OpenMPDirectiveKind)> &DPred,
203 /// \brief Checks if the specified variables has data-sharing attributes which
204 /// match specified \a CPred predicate in any innermost directive which
205 /// matches \a DPred predicate.
207 hasInnermostDSA(ValueDecl *D,
208 const llvm::function_ref<bool(OpenMPClauseKind)> &CPred,
209 const llvm::function_ref<bool(OpenMPDirectiveKind)> &DPred,
211 /// \brief Checks if the specified variables has explicit data-sharing
212 /// attributes which match specified \a CPred predicate at the specified
214 bool hasExplicitDSA(ValueDecl *D,
215 const llvm::function_ref<bool(OpenMPClauseKind)> &CPred,
216 unsigned Level, bool NotLastprivate = false);
218 /// \brief Returns true if the directive at level \Level matches in the
219 /// specified \a DPred predicate.
220 bool hasExplicitDirective(
221 const llvm::function_ref<bool(OpenMPDirectiveKind)> &DPred,
224 /// \brief Finds a directive which matches specified \a DPred predicate.
225 bool hasDirective(const llvm::function_ref<bool(OpenMPDirectiveKind,
226 const DeclarationNameInfo &,
227 SourceLocation)> &DPred,
230 /// \brief Returns currently analyzed directive.
231 OpenMPDirectiveKind getCurrentDirective() const {
232 return Stack.back().Directive;
234 /// \brief Returns parent directive.
235 OpenMPDirectiveKind getParentDirective() const {
236 if (Stack.size() > 2)
237 return Stack[Stack.size() - 2].Directive;
241 /// \brief Set default data sharing attribute to none.
242 void setDefaultDSANone(SourceLocation Loc) {
243 Stack.back().DefaultAttr = DSA_none;
244 Stack.back().DefaultAttrLoc = Loc;
246 /// \brief Set default data sharing attribute to shared.
247 void setDefaultDSAShared(SourceLocation Loc) {
248 Stack.back().DefaultAttr = DSA_shared;
249 Stack.back().DefaultAttrLoc = Loc;
252 DefaultDataSharingAttributes getDefaultDSA() const {
253 return Stack.back().DefaultAttr;
255 SourceLocation getDefaultDSALocation() const {
256 return Stack.back().DefaultAttrLoc;
259 /// \brief Checks if the specified variable is a threadprivate.
260 bool isThreadPrivate(VarDecl *D) {
261 DSAVarData DVar = getTopDSA(D, false);
262 return isOpenMPThreadPrivate(DVar.CKind);
265 /// \brief Marks current region as ordered (it has an 'ordered' clause).
266 void setOrderedRegion(bool IsOrdered, Expr *Param) {
267 Stack.back().OrderedRegion.setInt(IsOrdered);
268 Stack.back().OrderedRegion.setPointer(Param);
270 /// \brief Returns true, if parent region is ordered (has associated
271 /// 'ordered' clause), false - otherwise.
272 bool isParentOrderedRegion() const {
273 if (Stack.size() > 2)
274 return Stack[Stack.size() - 2].OrderedRegion.getInt();
277 /// \brief Returns optional parameter for the ordered region.
278 Expr *getParentOrderedRegionParam() const {
279 if (Stack.size() > 2)
280 return Stack[Stack.size() - 2].OrderedRegion.getPointer();
283 /// \brief Marks current region as nowait (it has a 'nowait' clause).
284 void setNowaitRegion(bool IsNowait = true) {
285 Stack.back().NowaitRegion = IsNowait;
287 /// \brief Returns true, if parent region is nowait (has associated
288 /// 'nowait' clause), false - otherwise.
289 bool isParentNowaitRegion() const {
290 if (Stack.size() > 2)
291 return Stack[Stack.size() - 2].NowaitRegion;
294 /// \brief Marks parent region as cancel region.
295 void setParentCancelRegion(bool Cancel = true) {
296 if (Stack.size() > 2)
297 Stack[Stack.size() - 2].CancelRegion =
298 Stack[Stack.size() - 2].CancelRegion || Cancel;
300 /// \brief Return true if current region has inner cancel construct.
301 bool isCancelRegion() const { return Stack.back().CancelRegion; }
303 /// \brief Set collapse value for the region.
304 void setAssociatedLoops(unsigned Val) { Stack.back().AssociatedLoops = Val; }
305 /// \brief Return collapse value for region.
306 unsigned getAssociatedLoops() const { return Stack.back().AssociatedLoops; }
308 /// \brief Marks current target region as one with closely nested teams
310 void setParentTeamsRegionLoc(SourceLocation TeamsRegionLoc) {
311 if (Stack.size() > 2)
312 Stack[Stack.size() - 2].InnerTeamsRegionLoc = TeamsRegionLoc;
314 /// \brief Returns true, if current region has closely nested teams region.
315 bool hasInnerTeamsRegion() const {
316 return getInnerTeamsRegionLoc().isValid();
318 /// \brief Returns location of the nested teams region (if any).
319 SourceLocation getInnerTeamsRegionLoc() const {
320 if (Stack.size() > 1)
321 return Stack.back().InnerTeamsRegionLoc;
322 return SourceLocation();
325 Scope *getCurScope() const { return Stack.back().CurScope; }
326 Scope *getCurScope() { return Stack.back().CurScope; }
327 SourceLocation getConstructLoc() { return Stack.back().ConstructLoc; }
329 /// Do the check specified in \a Check to all component lists and return true
330 /// if any issue is found.
331 bool checkMappableExprComponentListsForDecl(
332 ValueDecl *VD, bool CurrentRegionOnly,
333 const llvm::function_ref<
334 bool(OMPClauseMappableExprCommon::MappableExprComponentListRef,
335 OpenMPClauseKind)> &Check) {
336 auto SI = Stack.rbegin();
337 auto SE = Stack.rend();
342 if (CurrentRegionOnly) {
348 for (; SI != SE; ++SI) {
349 auto MI = SI->MappedExprComponents.find(VD);
350 if (MI != SI->MappedExprComponents.end())
351 for (auto &L : MI->second.Components)
352 if (Check(L, MI->second.Kind))
358 /// Create a new mappable expression component list associated with a given
359 /// declaration and initialize it with the provided list of components.
360 void addMappableExpressionComponents(
362 OMPClauseMappableExprCommon::MappableExprComponentListRef Components,
363 OpenMPClauseKind WhereFoundClauseKind) {
364 assert(Stack.size() > 1 &&
365 "Not expecting to retrieve components from a empty stack!");
366 auto &MEC = Stack.back().MappedExprComponents[VD];
367 // Create new entry and append the new components there.
368 MEC.Components.resize(MEC.Components.size() + 1);
369 MEC.Components.back().append(Components.begin(), Components.end());
370 MEC.Kind = WhereFoundClauseKind;
373 unsigned getNestingLevel() const {
374 assert(Stack.size() > 1);
375 return Stack.size() - 2;
377 void addDoacrossDependClause(OMPDependClause *C, OperatorOffsetTy &OpsOffs) {
378 assert(Stack.size() > 2);
379 assert(isOpenMPWorksharingDirective(Stack[Stack.size() - 2].Directive));
380 Stack[Stack.size() - 2].DoacrossDepends.insert({C, OpsOffs});
382 llvm::iterator_range<DoacrossDependMapTy::const_iterator>
383 getDoacrossDependClauses() const {
384 assert(Stack.size() > 1);
385 if (isOpenMPWorksharingDirective(Stack[Stack.size() - 1].Directive)) {
386 auto &Ref = Stack[Stack.size() - 1].DoacrossDepends;
387 return llvm::make_range(Ref.begin(), Ref.end());
389 return llvm::make_range(Stack[0].DoacrossDepends.end(),
390 Stack[0].DoacrossDepends.end());
393 bool isParallelOrTaskRegion(OpenMPDirectiveKind DKind) {
394 return isOpenMPParallelDirective(DKind) || isOpenMPTaskingDirective(DKind) ||
395 isOpenMPTeamsDirective(DKind) || DKind == OMPD_unknown;
399 static ValueDecl *getCanonicalDecl(ValueDecl *D) {
400 auto *VD = dyn_cast<VarDecl>(D);
401 auto *FD = dyn_cast<FieldDecl>(D);
403 VD = VD->getCanonicalDecl();
407 FD = FD->getCanonicalDecl();
413 DSAStackTy::DSAVarData DSAStackTy::getDSA(StackTy::reverse_iterator &Iter,
415 D = getCanonicalDecl(D);
416 auto *VD = dyn_cast<VarDecl>(D);
417 auto *FD = dyn_cast<FieldDecl>(D);
419 if (Iter == std::prev(Stack.rend())) {
420 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
421 // in a region but not in construct]
422 // File-scope or namespace-scope variables referenced in called routines
423 // in the region are shared unless they appear in a threadprivate
425 if (VD && !VD->isFunctionOrMethodVarDecl() && !isa<ParmVarDecl>(D))
426 DVar.CKind = OMPC_shared;
428 // OpenMP [2.9.1.2, Data-sharing Attribute Rules for Variables Referenced
429 // in a region but not in construct]
430 // Variables with static storage duration that are declared in called
431 // routines in the region are shared.
432 if (VD && VD->hasGlobalStorage())
433 DVar.CKind = OMPC_shared;
435 // Non-static data members are shared by default.
437 DVar.CKind = OMPC_shared;
442 DVar.DKind = Iter->Directive;
443 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
444 // in a Construct, C/C++, predetermined, p.1]
445 // Variables with automatic storage duration that are declared in a scope
446 // inside the construct are private.
447 if (VD && isOpenMPLocal(VD, Iter) && VD->isLocalVarDecl() &&
448 (VD->getStorageClass() == SC_Auto || VD->getStorageClass() == SC_None)) {
449 DVar.CKind = OMPC_private;
453 // Explicitly specified attributes and local variables with predetermined
455 if (Iter->SharingMap.count(D)) {
456 DVar.RefExpr = Iter->SharingMap[D].RefExpr.getPointer();
457 DVar.PrivateCopy = Iter->SharingMap[D].PrivateCopy;
458 DVar.CKind = Iter->SharingMap[D].Attributes;
459 DVar.ImplicitDSALoc = Iter->DefaultAttrLoc;
463 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
464 // in a Construct, C/C++, implicitly determined, p.1]
465 // In a parallel or task construct, the data-sharing attributes of these
466 // variables are determined by the default clause, if present.
467 switch (Iter->DefaultAttr) {
469 DVar.CKind = OMPC_shared;
470 DVar.ImplicitDSALoc = Iter->DefaultAttrLoc;
474 case DSA_unspecified:
475 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
476 // in a Construct, implicitly determined, p.2]
477 // In a parallel construct, if no default clause is present, these
478 // variables are shared.
479 DVar.ImplicitDSALoc = Iter->DefaultAttrLoc;
480 if (isOpenMPParallelDirective(DVar.DKind) ||
481 isOpenMPTeamsDirective(DVar.DKind)) {
482 DVar.CKind = OMPC_shared;
486 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
487 // in a Construct, implicitly determined, p.4]
488 // In a task construct, if no default clause is present, a variable that in
489 // the enclosing context is determined to be shared by all implicit tasks
490 // bound to the current team is shared.
491 if (isOpenMPTaskingDirective(DVar.DKind)) {
493 for (StackTy::reverse_iterator I = std::next(Iter), EE = Stack.rend();
495 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables
496 // Referenced in a Construct, implicitly determined, p.6]
497 // In a task construct, if no default clause is present, a variable
498 // whose data-sharing attribute is not determined by the rules above is
500 DVarTemp = getDSA(I, D);
501 if (DVarTemp.CKind != OMPC_shared) {
502 DVar.RefExpr = nullptr;
503 DVar.CKind = OMPC_firstprivate;
506 if (isParallelOrTaskRegion(I->Directive))
510 (DVarTemp.CKind == OMPC_unknown) ? OMPC_firstprivate : OMPC_shared;
514 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
515 // in a Construct, implicitly determined, p.3]
516 // For constructs other than task, if no default clause is present, these
517 // variables inherit their data-sharing attributes from the enclosing
519 return getDSA(++Iter, D);
522 Expr *DSAStackTy::addUniqueAligned(ValueDecl *D, Expr *NewDE) {
523 assert(Stack.size() > 1 && "Data sharing attributes stack is empty");
524 D = getCanonicalDecl(D);
525 auto It = Stack.back().AlignedMap.find(D);
526 if (It == Stack.back().AlignedMap.end()) {
527 assert(NewDE && "Unexpected nullptr expr to be added into aligned map");
528 Stack.back().AlignedMap[D] = NewDE;
531 assert(It->second && "Unexpected nullptr expr in the aligned map");
537 void DSAStackTy::addLoopControlVariable(ValueDecl *D, VarDecl *Capture) {
538 assert(Stack.size() > 1 && "Data-sharing attributes stack is empty");
539 D = getCanonicalDecl(D);
540 Stack.back().LCVMap.insert(
541 std::make_pair(D, LCDeclInfo(Stack.back().LCVMap.size() + 1, Capture)));
544 DSAStackTy::LCDeclInfo DSAStackTy::isLoopControlVariable(ValueDecl *D) {
545 assert(Stack.size() > 1 && "Data-sharing attributes stack is empty");
546 D = getCanonicalDecl(D);
547 return Stack.back().LCVMap.count(D) > 0 ? Stack.back().LCVMap[D]
548 : LCDeclInfo(0, nullptr);
551 DSAStackTy::LCDeclInfo DSAStackTy::isParentLoopControlVariable(ValueDecl *D) {
552 assert(Stack.size() > 2 && "Data-sharing attributes stack is empty");
553 D = getCanonicalDecl(D);
554 return Stack[Stack.size() - 2].LCVMap.count(D) > 0
555 ? Stack[Stack.size() - 2].LCVMap[D]
556 : LCDeclInfo(0, nullptr);
559 ValueDecl *DSAStackTy::getParentLoopControlVariable(unsigned I) {
560 assert(Stack.size() > 2 && "Data-sharing attributes stack is empty");
561 if (Stack[Stack.size() - 2].LCVMap.size() < I)
563 for (auto &Pair : Stack[Stack.size() - 2].LCVMap) {
564 if (Pair.second.first == I)
570 void DSAStackTy::addDSA(ValueDecl *D, Expr *E, OpenMPClauseKind A,
571 DeclRefExpr *PrivateCopy) {
572 D = getCanonicalDecl(D);
573 if (A == OMPC_threadprivate) {
574 auto &Data = Stack[0].SharingMap[D];
576 Data.RefExpr.setPointer(E);
577 Data.PrivateCopy = nullptr;
579 assert(Stack.size() > 1 && "Data-sharing attributes stack is empty");
580 auto &Data = Stack.back().SharingMap[D];
581 assert(Data.Attributes == OMPC_unknown || (A == Data.Attributes) ||
582 (A == OMPC_firstprivate && Data.Attributes == OMPC_lastprivate) ||
583 (A == OMPC_lastprivate && Data.Attributes == OMPC_firstprivate) ||
584 (isLoopControlVariable(D).first && A == OMPC_private));
585 if (A == OMPC_lastprivate && Data.Attributes == OMPC_firstprivate) {
586 Data.RefExpr.setInt(/*IntVal=*/true);
589 const bool IsLastprivate =
590 A == OMPC_lastprivate || Data.Attributes == OMPC_lastprivate;
592 Data.RefExpr.setPointerAndInt(E, IsLastprivate);
593 Data.PrivateCopy = PrivateCopy;
595 auto &Data = Stack.back().SharingMap[PrivateCopy->getDecl()];
597 Data.RefExpr.setPointerAndInt(PrivateCopy, IsLastprivate);
598 Data.PrivateCopy = nullptr;
603 bool DSAStackTy::isOpenMPLocal(VarDecl *D, StackTy::reverse_iterator Iter) {
604 D = D->getCanonicalDecl();
605 if (Stack.size() > 2) {
606 reverse_iterator I = Iter, E = std::prev(Stack.rend());
607 Scope *TopScope = nullptr;
608 while (I != E && !isParallelOrTaskRegion(I->Directive)) {
613 TopScope = I->CurScope ? I->CurScope->getParent() : nullptr;
614 Scope *CurScope = getCurScope();
615 while (CurScope != TopScope && !CurScope->isDeclScope(D)) {
616 CurScope = CurScope->getParent();
618 return CurScope != TopScope;
623 /// \brief Build a variable declaration for OpenMP loop iteration variable.
624 static VarDecl *buildVarDecl(Sema &SemaRef, SourceLocation Loc, QualType Type,
625 StringRef Name, const AttrVec *Attrs = nullptr) {
626 DeclContext *DC = SemaRef.CurContext;
627 IdentifierInfo *II = &SemaRef.PP.getIdentifierTable().get(Name);
628 TypeSourceInfo *TInfo = SemaRef.Context.getTrivialTypeSourceInfo(Type, Loc);
630 VarDecl::Create(SemaRef.Context, DC, Loc, Loc, II, Type, TInfo, SC_None);
632 for (specific_attr_iterator<AlignedAttr> I(Attrs->begin()), E(Attrs->end());
640 static DeclRefExpr *buildDeclRefExpr(Sema &S, VarDecl *D, QualType Ty,
642 bool RefersToCapture = false) {
644 D->markUsed(S.Context);
645 return DeclRefExpr::Create(S.getASTContext(), NestedNameSpecifierLoc(),
646 SourceLocation(), D, RefersToCapture, Loc, Ty,
650 DSAStackTy::DSAVarData DSAStackTy::getTopDSA(ValueDecl *D, bool FromParent) {
651 D = getCanonicalDecl(D);
654 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
655 // in a Construct, C/C++, predetermined, p.1]
656 // Variables appearing in threadprivate directives are threadprivate.
657 auto *VD = dyn_cast<VarDecl>(D);
658 if ((VD && VD->getTLSKind() != VarDecl::TLS_None &&
659 !(VD->hasAttr<OMPThreadPrivateDeclAttr>() &&
660 SemaRef.getLangOpts().OpenMPUseTLS &&
661 SemaRef.getASTContext().getTargetInfo().isTLSSupported())) ||
662 (VD && VD->getStorageClass() == SC_Register &&
663 VD->hasAttr<AsmLabelAttr>() && !VD->isLocalVarDecl())) {
664 addDSA(D, buildDeclRefExpr(SemaRef, VD, D->getType().getNonReferenceType(),
668 if (Stack[0].SharingMap.count(D)) {
669 DVar.RefExpr = Stack[0].SharingMap[D].RefExpr.getPointer();
670 DVar.CKind = OMPC_threadprivate;
674 if (Stack.size() == 1) {
675 // Not in OpenMP execution region and top scope was already checked.
679 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
680 // in a Construct, C/C++, predetermined, p.4]
681 // Static data members are shared.
682 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
683 // in a Construct, C/C++, predetermined, p.7]
684 // Variables with static storage duration that are declared in a scope
685 // inside the construct are shared.
686 auto &&MatchesAlways = [](OpenMPDirectiveKind) -> bool { return true; };
687 if (VD && VD->isStaticDataMember()) {
688 DSAVarData DVarTemp = hasDSA(D, isOpenMPPrivate, MatchesAlways, FromParent);
689 if (DVarTemp.CKind != OMPC_unknown && DVarTemp.RefExpr)
692 DVar.CKind = OMPC_shared;
696 QualType Type = D->getType().getNonReferenceType().getCanonicalType();
697 bool IsConstant = Type.isConstant(SemaRef.getASTContext());
698 Type = SemaRef.getASTContext().getBaseElementType(Type);
699 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
700 // in a Construct, C/C++, predetermined, p.6]
701 // Variables with const qualified type having no mutable member are
704 SemaRef.getLangOpts().CPlusPlus ? Type->getAsCXXRecordDecl() : nullptr;
705 if (auto *CTSD = dyn_cast_or_null<ClassTemplateSpecializationDecl>(RD))
706 if (auto *CTD = CTSD->getSpecializedTemplate())
707 RD = CTD->getTemplatedDecl();
709 !(SemaRef.getLangOpts().CPlusPlus && RD && RD->hasDefinition() &&
710 RD->hasMutableFields())) {
711 // Variables with const-qualified type having no mutable member may be
712 // listed in a firstprivate clause, even if they are static data members.
713 DSAVarData DVarTemp = hasDSA(
714 D, [](OpenMPClauseKind C) -> bool { return C == OMPC_firstprivate; },
715 MatchesAlways, FromParent);
716 if (DVarTemp.CKind == OMPC_firstprivate && DVarTemp.RefExpr)
719 DVar.CKind = OMPC_shared;
723 // Explicitly specified attributes and local variables with predetermined
725 auto StartI = std::next(Stack.rbegin());
726 auto EndI = std::prev(Stack.rend());
727 if (FromParent && StartI != EndI) {
728 StartI = std::next(StartI);
730 auto I = std::prev(StartI);
731 if (I->SharingMap.count(D)) {
732 DVar.RefExpr = I->SharingMap[D].RefExpr.getPointer();
733 DVar.PrivateCopy = I->SharingMap[D].PrivateCopy;
734 DVar.CKind = I->SharingMap[D].Attributes;
735 DVar.ImplicitDSALoc = I->DefaultAttrLoc;
741 DSAStackTy::DSAVarData DSAStackTy::getImplicitDSA(ValueDecl *D,
743 D = getCanonicalDecl(D);
744 auto StartI = Stack.rbegin();
745 auto EndI = std::prev(Stack.rend());
746 if (FromParent && StartI != EndI) {
747 StartI = std::next(StartI);
749 return getDSA(StartI, D);
752 DSAStackTy::DSAVarData
753 DSAStackTy::hasDSA(ValueDecl *D,
754 const llvm::function_ref<bool(OpenMPClauseKind)> &CPred,
755 const llvm::function_ref<bool(OpenMPDirectiveKind)> &DPred,
757 D = getCanonicalDecl(D);
758 auto StartI = std::next(Stack.rbegin());
759 auto EndI = Stack.rend();
760 if (FromParent && StartI != EndI) {
761 StartI = std::next(StartI);
763 for (auto I = StartI, EE = EndI; I != EE; ++I) {
764 if (!DPred(I->Directive) && !isParallelOrTaskRegion(I->Directive))
766 DSAVarData DVar = getDSA(I, D);
767 if (CPred(DVar.CKind))
773 DSAStackTy::DSAVarData DSAStackTy::hasInnermostDSA(
774 ValueDecl *D, const llvm::function_ref<bool(OpenMPClauseKind)> &CPred,
775 const llvm::function_ref<bool(OpenMPDirectiveKind)> &DPred,
777 D = getCanonicalDecl(D);
778 auto StartI = std::next(Stack.rbegin());
779 auto EndI = Stack.rend();
780 if (FromParent && StartI != EndI)
781 StartI = std::next(StartI);
782 if (StartI == EndI || !DPred(StartI->Directive))
784 DSAVarData DVar = getDSA(StartI, D);
785 return CPred(DVar.CKind) ? DVar : DSAVarData();
788 bool DSAStackTy::hasExplicitDSA(
789 ValueDecl *D, const llvm::function_ref<bool(OpenMPClauseKind)> &CPred,
790 unsigned Level, bool NotLastprivate) {
791 if (CPred(ClauseKindMode))
793 D = getCanonicalDecl(D);
794 auto StartI = std::next(Stack.begin());
795 auto EndI = Stack.end();
796 if (std::distance(StartI, EndI) <= (int)Level)
798 std::advance(StartI, Level);
799 return (StartI->SharingMap.count(D) > 0) &&
800 StartI->SharingMap[D].RefExpr.getPointer() &&
801 CPred(StartI->SharingMap[D].Attributes) &&
802 (!NotLastprivate || !StartI->SharingMap[D].RefExpr.getInt());
805 bool DSAStackTy::hasExplicitDirective(
806 const llvm::function_ref<bool(OpenMPDirectiveKind)> &DPred,
808 auto StartI = std::next(Stack.begin());
809 auto EndI = Stack.end();
810 if (std::distance(StartI, EndI) <= (int)Level)
812 std::advance(StartI, Level);
813 return DPred(StartI->Directive);
816 bool DSAStackTy::hasDirective(
817 const llvm::function_ref<bool(OpenMPDirectiveKind,
818 const DeclarationNameInfo &, SourceLocation)>
821 // We look only in the enclosing region.
822 if (Stack.size() < 2)
824 auto StartI = std::next(Stack.rbegin());
825 auto EndI = std::prev(Stack.rend());
826 if (FromParent && StartI != EndI) {
827 StartI = std::next(StartI);
829 for (auto I = StartI, EE = EndI; I != EE; ++I) {
830 if (DPred(I->Directive, I->DirectiveName, I->ConstructLoc))
836 void Sema::InitDataSharingAttributesStack() {
837 VarDataSharingAttributesStack = new DSAStackTy(*this);
840 #define DSAStack static_cast<DSAStackTy *>(VarDataSharingAttributesStack)
842 bool Sema::IsOpenMPCapturedByRef(ValueDecl *D, unsigned Level) {
843 assert(LangOpts.OpenMP && "OpenMP is not allowed");
845 auto &Ctx = getASTContext();
848 // Find the directive that is associated with the provided scope.
849 auto Ty = D->getType();
851 if (DSAStack->hasExplicitDirective(isOpenMPTargetExecutionDirective, Level)) {
852 // This table summarizes how a given variable should be passed to the device
853 // given its type and the clauses where it appears. This table is based on
854 // the description in OpenMP 4.5 [2.10.4, target Construct] and
855 // OpenMP 4.5 [2.15.5, Data-mapping Attribute Rules and Clauses].
857 // =========================================================================
858 // | type | defaultmap | pvt | first | is_device_ptr | map | res. |
859 // | |(tofrom:scalar)| | pvt | | | |
860 // =========================================================================
861 // | scl | | | | - | | bycopy|
862 // | scl | | - | x | - | - | bycopy|
863 // | scl | | x | - | - | - | null |
864 // | scl | x | | | - | | byref |
865 // | scl | x | - | x | - | - | bycopy|
866 // | scl | x | x | - | - | - | null |
867 // | scl | | - | - | - | x | byref |
868 // | scl | x | - | - | - | x | byref |
870 // | agg | n.a. | | | - | | byref |
871 // | agg | n.a. | - | x | - | - | byref |
872 // | agg | n.a. | x | - | - | - | null |
873 // | agg | n.a. | - | - | - | x | byref |
874 // | agg | n.a. | - | - | - | x[] | byref |
876 // | ptr | n.a. | | | - | | bycopy|
877 // | ptr | n.a. | - | x | - | - | bycopy|
878 // | ptr | n.a. | x | - | - | - | null |
879 // | ptr | n.a. | - | - | - | x | byref |
880 // | ptr | n.a. | - | - | - | x[] | bycopy|
881 // | ptr | n.a. | - | - | x | | bycopy|
882 // | ptr | n.a. | - | - | x | x | bycopy|
883 // | ptr | n.a. | - | - | x | x[] | bycopy|
884 // =========================================================================
890 // - - invalid in this combination
891 // [] - mapped with an array section
892 // byref - should be mapped by reference
893 // byval - should be mapped by value
894 // null - initialize a local variable to null on the device
897 // - All scalar declarations that show up in a map clause have to be passed
898 // by reference, because they may have been mapped in the enclosing data
900 // - If the scalar value does not fit the size of uintptr, it has to be
901 // passed by reference, regardless the result in the table above.
902 // - For pointers mapped by value that have either an implicit map or an
903 // array section, the runtime library may pass the NULL value to the
904 // device instead of the value passed to it by the compiler.
906 if (Ty->isReferenceType())
907 Ty = Ty->castAs<ReferenceType>()->getPointeeType();
909 // Locate map clauses and see if the variable being captured is referred to
910 // in any of those clauses. Here we only care about variables, not fields,
911 // because fields are part of aggregates.
912 bool IsVariableUsedInMapClause = false;
913 bool IsVariableAssociatedWithSection = false;
915 DSAStack->checkMappableExprComponentListsForDecl(
916 D, /*CurrentRegionOnly=*/true,
917 [&](OMPClauseMappableExprCommon::MappableExprComponentListRef
919 OpenMPClauseKind WhereFoundClauseKind) {
920 // Only the map clause information influences how a variable is
921 // captured. E.g. is_device_ptr does not require changing the default
923 if (WhereFoundClauseKind != OMPC_map)
926 auto EI = MapExprComponents.rbegin();
927 auto EE = MapExprComponents.rend();
929 assert(EI != EE && "Invalid map expression!");
931 if (isa<DeclRefExpr>(EI->getAssociatedExpression()))
932 IsVariableUsedInMapClause |= EI->getAssociatedDeclaration() == D;
938 if (isa<ArraySubscriptExpr>(EI->getAssociatedExpression()) ||
939 isa<OMPArraySectionExpr>(EI->getAssociatedExpression()) ||
940 isa<MemberExpr>(EI->getAssociatedExpression())) {
941 IsVariableAssociatedWithSection = true;
942 // There is nothing more we need to know about this variable.
946 // Keep looking for more map info.
950 if (IsVariableUsedInMapClause) {
951 // If variable is identified in a map clause it is always captured by
952 // reference except if it is a pointer that is dereferenced somehow.
953 IsByRef = !(Ty->isPointerType() && IsVariableAssociatedWithSection);
955 // By default, all the data that has a scalar type is mapped by copy.
956 IsByRef = !Ty->isScalarType();
960 if (IsByRef && Ty.getNonReferenceType()->isScalarType()) {
961 IsByRef = !DSAStack->hasExplicitDSA(
962 D, [](OpenMPClauseKind K) -> bool { return K == OMPC_firstprivate; },
963 Level, /*NotLastprivate=*/true);
966 // When passing data by copy, we need to make sure it fits the uintptr size
967 // and alignment, because the runtime library only deals with uintptr types.
968 // If it does not fit the uintptr size, we need to pass the data by reference
971 (Ctx.getTypeSizeInChars(Ty) >
972 Ctx.getTypeSizeInChars(Ctx.getUIntPtrType()) ||
973 Ctx.getDeclAlign(D) > Ctx.getTypeAlignInChars(Ctx.getUIntPtrType()))) {
980 unsigned Sema::getOpenMPNestingLevel() const {
981 assert(getLangOpts().OpenMP);
982 return DSAStack->getNestingLevel();
985 VarDecl *Sema::IsOpenMPCapturedDecl(ValueDecl *D) {
986 assert(LangOpts.OpenMP && "OpenMP is not allowed");
987 D = getCanonicalDecl(D);
989 // If we are attempting to capture a global variable in a directive with
990 // 'target' we return true so that this global is also mapped to the device.
992 // FIXME: If the declaration is enclosed in a 'declare target' directive,
993 // then it should not be captured. Therefore, an extra check has to be
994 // inserted here once support for 'declare target' is added.
996 auto *VD = dyn_cast<VarDecl>(D);
997 if (VD && !VD->hasLocalStorage()) {
998 if (DSAStack->getCurrentDirective() == OMPD_target &&
999 !DSAStack->isClauseParsingMode())
1001 if (DSAStack->hasDirective(
1002 [](OpenMPDirectiveKind K, const DeclarationNameInfo &,
1003 SourceLocation) -> bool {
1004 return isOpenMPTargetExecutionDirective(K);
1010 if (DSAStack->getCurrentDirective() != OMPD_unknown &&
1011 (!DSAStack->isClauseParsingMode() ||
1012 DSAStack->getParentDirective() != OMPD_unknown)) {
1013 auto &&Info = DSAStack->isLoopControlVariable(D);
1015 (VD && VD->hasLocalStorage() &&
1016 isParallelOrTaskRegion(DSAStack->getCurrentDirective())) ||
1017 (VD && DSAStack->isForceVarCapturing()))
1018 return VD ? VD : Info.second;
1019 auto DVarPrivate = DSAStack->getTopDSA(D, DSAStack->isClauseParsingMode());
1020 if (DVarPrivate.CKind != OMPC_unknown && isOpenMPPrivate(DVarPrivate.CKind))
1021 return VD ? VD : cast<VarDecl>(DVarPrivate.PrivateCopy->getDecl());
1022 DVarPrivate = DSAStack->hasDSA(
1023 D, isOpenMPPrivate, [](OpenMPDirectiveKind) -> bool { return true; },
1024 DSAStack->isClauseParsingMode());
1025 if (DVarPrivate.CKind != OMPC_unknown)
1026 return VD ? VD : cast<VarDecl>(DVarPrivate.PrivateCopy->getDecl());
1031 bool Sema::isOpenMPPrivateDecl(ValueDecl *D, unsigned Level) {
1032 assert(LangOpts.OpenMP && "OpenMP is not allowed");
1033 return DSAStack->hasExplicitDSA(
1034 D, [](OpenMPClauseKind K) -> bool { return K == OMPC_private; }, Level);
1037 bool Sema::isOpenMPTargetCapturedDecl(ValueDecl *D, unsigned Level) {
1038 assert(LangOpts.OpenMP && "OpenMP is not allowed");
1039 // Return true if the current level is no longer enclosed in a target region.
1041 auto *VD = dyn_cast<VarDecl>(D);
1042 return VD && !VD->hasLocalStorage() &&
1043 DSAStack->hasExplicitDirective(isOpenMPTargetExecutionDirective,
1047 void Sema::DestroyDataSharingAttributesStack() { delete DSAStack; }
1049 void Sema::StartOpenMPDSABlock(OpenMPDirectiveKind DKind,
1050 const DeclarationNameInfo &DirName,
1051 Scope *CurScope, SourceLocation Loc) {
1052 DSAStack->push(DKind, DirName, CurScope, Loc);
1053 PushExpressionEvaluationContext(PotentiallyEvaluated);
1056 void Sema::StartOpenMPClause(OpenMPClauseKind K) {
1057 DSAStack->setClauseParsingMode(K);
1060 void Sema::EndOpenMPClause() {
1061 DSAStack->setClauseParsingMode(/*K=*/OMPC_unknown);
1064 void Sema::EndOpenMPDSABlock(Stmt *CurDirective) {
1065 // OpenMP [2.14.3.5, Restrictions, C/C++, p.1]
1066 // A variable of class type (or array thereof) that appears in a lastprivate
1067 // clause requires an accessible, unambiguous default constructor for the
1068 // class type, unless the list item is also specified in a firstprivate
1070 if (auto *D = dyn_cast_or_null<OMPExecutableDirective>(CurDirective)) {
1071 for (auto *C : D->clauses()) {
1072 if (auto *Clause = dyn_cast<OMPLastprivateClause>(C)) {
1073 SmallVector<Expr *, 8> PrivateCopies;
1074 for (auto *DE : Clause->varlists()) {
1075 if (DE->isValueDependent() || DE->isTypeDependent()) {
1076 PrivateCopies.push_back(nullptr);
1079 auto *DRE = cast<DeclRefExpr>(DE->IgnoreParens());
1080 VarDecl *VD = cast<VarDecl>(DRE->getDecl());
1081 QualType Type = VD->getType().getNonReferenceType();
1082 auto DVar = DSAStack->getTopDSA(VD, false);
1083 if (DVar.CKind == OMPC_lastprivate) {
1084 // Generate helper private variable and initialize it with the
1085 // default value. The address of the original variable is replaced
1086 // by the address of the new private variable in CodeGen. This new
1087 // variable is not added to IdResolver, so the code in the OpenMP
1088 // region uses original variable for proper diagnostics.
1089 auto *VDPrivate = buildVarDecl(
1090 *this, DE->getExprLoc(), Type.getUnqualifiedType(),
1091 VD->getName(), VD->hasAttrs() ? &VD->getAttrs() : nullptr);
1092 ActOnUninitializedDecl(VDPrivate, /*TypeMayContainAuto=*/false);
1093 if (VDPrivate->isInvalidDecl())
1095 PrivateCopies.push_back(buildDeclRefExpr(
1096 *this, VDPrivate, DE->getType(), DE->getExprLoc()));
1098 // The variable is also a firstprivate, so initialization sequence
1099 // for private copy is generated already.
1100 PrivateCopies.push_back(nullptr);
1103 // Set initializers to private copies if no errors were found.
1104 if (PrivateCopies.size() == Clause->varlist_size())
1105 Clause->setPrivateCopies(PrivateCopies);
1111 DiscardCleanupsInEvaluationContext();
1112 PopExpressionEvaluationContext();
1115 static bool FinishOpenMPLinearClause(OMPLinearClause &Clause, DeclRefExpr *IV,
1116 Expr *NumIterations, Sema &SemaRef,
1117 Scope *S, DSAStackTy *Stack);
1121 class VarDeclFilterCCC : public CorrectionCandidateCallback {
1126 explicit VarDeclFilterCCC(Sema &S) : SemaRef(S) {}
1127 bool ValidateCandidate(const TypoCorrection &Candidate) override {
1128 NamedDecl *ND = Candidate.getCorrectionDecl();
1129 if (auto *VD = dyn_cast_or_null<VarDecl>(ND)) {
1130 return VD->hasGlobalStorage() &&
1131 SemaRef.isDeclInScope(ND, SemaRef.getCurLexicalContext(),
1132 SemaRef.getCurScope());
1138 class VarOrFuncDeclFilterCCC : public CorrectionCandidateCallback {
1143 explicit VarOrFuncDeclFilterCCC(Sema &S) : SemaRef(S) {}
1144 bool ValidateCandidate(const TypoCorrection &Candidate) override {
1145 NamedDecl *ND = Candidate.getCorrectionDecl();
1146 if (isa<VarDecl>(ND) || isa<FunctionDecl>(ND)) {
1147 return SemaRef.isDeclInScope(ND, SemaRef.getCurLexicalContext(),
1148 SemaRef.getCurScope());
1156 ExprResult Sema::ActOnOpenMPIdExpression(Scope *CurScope,
1157 CXXScopeSpec &ScopeSpec,
1158 const DeclarationNameInfo &Id) {
1159 LookupResult Lookup(*this, Id, LookupOrdinaryName);
1160 LookupParsedName(Lookup, CurScope, &ScopeSpec, true);
1162 if (Lookup.isAmbiguous())
1166 if (!Lookup.isSingleResult()) {
1167 if (TypoCorrection Corrected = CorrectTypo(
1168 Id, LookupOrdinaryName, CurScope, nullptr,
1169 llvm::make_unique<VarDeclFilterCCC>(*this), CTK_ErrorRecovery)) {
1170 diagnoseTypo(Corrected,
1171 PDiag(Lookup.empty()
1172 ? diag::err_undeclared_var_use_suggest
1173 : diag::err_omp_expected_var_arg_suggest)
1175 VD = Corrected.getCorrectionDeclAs<VarDecl>();
1177 Diag(Id.getLoc(), Lookup.empty() ? diag::err_undeclared_var_use
1178 : diag::err_omp_expected_var_arg)
1183 if (!(VD = Lookup.getAsSingle<VarDecl>())) {
1184 Diag(Id.getLoc(), diag::err_omp_expected_var_arg) << Id.getName();
1185 Diag(Lookup.getFoundDecl()->getLocation(), diag::note_declared_at);
1189 Lookup.suppressDiagnostics();
1191 // OpenMP [2.9.2, Syntax, C/C++]
1192 // Variables must be file-scope, namespace-scope, or static block-scope.
1193 if (!VD->hasGlobalStorage()) {
1194 Diag(Id.getLoc(), diag::err_omp_global_var_arg)
1195 << getOpenMPDirectiveName(OMPD_threadprivate) << !VD->isStaticLocal();
1197 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
1198 Diag(VD->getLocation(),
1199 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
1204 VarDecl *CanonicalVD = VD->getCanonicalDecl();
1205 NamedDecl *ND = cast<NamedDecl>(CanonicalVD);
1206 // OpenMP [2.9.2, Restrictions, C/C++, p.2]
1207 // A threadprivate directive for file-scope variables must appear outside
1208 // any definition or declaration.
1209 if (CanonicalVD->getDeclContext()->isTranslationUnit() &&
1210 !getCurLexicalContext()->isTranslationUnit()) {
1211 Diag(Id.getLoc(), diag::err_omp_var_scope)
1212 << getOpenMPDirectiveName(OMPD_threadprivate) << VD;
1214 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
1215 Diag(VD->getLocation(),
1216 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
1220 // OpenMP [2.9.2, Restrictions, C/C++, p.3]
1221 // A threadprivate directive for static class member variables must appear
1222 // in the class definition, in the same scope in which the member
1223 // variables are declared.
1224 if (CanonicalVD->isStaticDataMember() &&
1225 !CanonicalVD->getDeclContext()->Equals(getCurLexicalContext())) {
1226 Diag(Id.getLoc(), diag::err_omp_var_scope)
1227 << getOpenMPDirectiveName(OMPD_threadprivate) << VD;
1229 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
1230 Diag(VD->getLocation(),
1231 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
1235 // OpenMP [2.9.2, Restrictions, C/C++, p.4]
1236 // A threadprivate directive for namespace-scope variables must appear
1237 // outside any definition or declaration other than the namespace
1238 // definition itself.
1239 if (CanonicalVD->getDeclContext()->isNamespace() &&
1240 (!getCurLexicalContext()->isFileContext() ||
1241 !getCurLexicalContext()->Encloses(CanonicalVD->getDeclContext()))) {
1242 Diag(Id.getLoc(), diag::err_omp_var_scope)
1243 << getOpenMPDirectiveName(OMPD_threadprivate) << VD;
1245 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
1246 Diag(VD->getLocation(),
1247 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
1251 // OpenMP [2.9.2, Restrictions, C/C++, p.6]
1252 // A threadprivate directive for static block-scope variables must appear
1253 // in the scope of the variable and not in a nested scope.
1254 if (CanonicalVD->isStaticLocal() && CurScope &&
1255 !isDeclInScope(ND, getCurLexicalContext(), CurScope)) {
1256 Diag(Id.getLoc(), diag::err_omp_var_scope)
1257 << getOpenMPDirectiveName(OMPD_threadprivate) << VD;
1259 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
1260 Diag(VD->getLocation(),
1261 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
1266 // OpenMP [2.9.2, Restrictions, C/C++, p.2-6]
1267 // A threadprivate directive must lexically precede all references to any
1268 // of the variables in its list.
1269 if (VD->isUsed() && !DSAStack->isThreadPrivate(VD)) {
1270 Diag(Id.getLoc(), diag::err_omp_var_used)
1271 << getOpenMPDirectiveName(OMPD_threadprivate) << VD;
1275 QualType ExprType = VD->getType().getNonReferenceType();
1276 return DeclRefExpr::Create(Context, NestedNameSpecifierLoc(),
1277 SourceLocation(), VD,
1278 /*RefersToEnclosingVariableOrCapture=*/false,
1279 Id.getLoc(), ExprType, VK_LValue);
1282 Sema::DeclGroupPtrTy
1283 Sema::ActOnOpenMPThreadprivateDirective(SourceLocation Loc,
1284 ArrayRef<Expr *> VarList) {
1285 if (OMPThreadPrivateDecl *D = CheckOMPThreadPrivateDecl(Loc, VarList)) {
1286 CurContext->addDecl(D);
1287 return DeclGroupPtrTy::make(DeclGroupRef(D));
1293 class LocalVarRefChecker : public ConstStmtVisitor<LocalVarRefChecker, bool> {
1297 bool VisitDeclRefExpr(const DeclRefExpr *E) {
1298 if (auto *VD = dyn_cast<VarDecl>(E->getDecl())) {
1299 if (VD->hasLocalStorage()) {
1300 SemaRef.Diag(E->getLocStart(),
1301 diag::err_omp_local_var_in_threadprivate_init)
1302 << E->getSourceRange();
1303 SemaRef.Diag(VD->getLocation(), diag::note_defined_here)
1304 << VD << VD->getSourceRange();
1310 bool VisitStmt(const Stmt *S) {
1311 for (auto Child : S->children()) {
1312 if (Child && Visit(Child))
1317 explicit LocalVarRefChecker(Sema &SemaRef) : SemaRef(SemaRef) {}
1321 OMPThreadPrivateDecl *
1322 Sema::CheckOMPThreadPrivateDecl(SourceLocation Loc, ArrayRef<Expr *> VarList) {
1323 SmallVector<Expr *, 8> Vars;
1324 for (auto &RefExpr : VarList) {
1325 DeclRefExpr *DE = cast<DeclRefExpr>(RefExpr);
1326 VarDecl *VD = cast<VarDecl>(DE->getDecl());
1327 SourceLocation ILoc = DE->getExprLoc();
1329 // Mark variable as used.
1330 VD->setReferenced();
1331 VD->markUsed(Context);
1333 QualType QType = VD->getType();
1334 if (QType->isDependentType() || QType->isInstantiationDependentType()) {
1335 // It will be analyzed later.
1340 // OpenMP [2.9.2, Restrictions, C/C++, p.10]
1341 // A threadprivate variable must not have an incomplete type.
1342 if (RequireCompleteType(ILoc, VD->getType(),
1343 diag::err_omp_threadprivate_incomplete_type)) {
1347 // OpenMP [2.9.2, Restrictions, C/C++, p.10]
1348 // A threadprivate variable must not have a reference type.
1349 if (VD->getType()->isReferenceType()) {
1350 Diag(ILoc, diag::err_omp_ref_type_arg)
1351 << getOpenMPDirectiveName(OMPD_threadprivate) << VD->getType();
1353 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
1354 Diag(VD->getLocation(),
1355 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
1360 // Check if this is a TLS variable. If TLS is not being supported, produce
1361 // the corresponding diagnostic.
1362 if ((VD->getTLSKind() != VarDecl::TLS_None &&
1363 !(VD->hasAttr<OMPThreadPrivateDeclAttr>() &&
1364 getLangOpts().OpenMPUseTLS &&
1365 getASTContext().getTargetInfo().isTLSSupported())) ||
1366 (VD->getStorageClass() == SC_Register && VD->hasAttr<AsmLabelAttr>() &&
1367 !VD->isLocalVarDecl())) {
1368 Diag(ILoc, diag::err_omp_var_thread_local)
1369 << VD << ((VD->getTLSKind() != VarDecl::TLS_None) ? 0 : 1);
1371 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
1372 Diag(VD->getLocation(),
1373 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
1378 // Check if initial value of threadprivate variable reference variable with
1379 // local storage (it is not supported by runtime).
1380 if (auto Init = VD->getAnyInitializer()) {
1381 LocalVarRefChecker Checker(*this);
1382 if (Checker.Visit(Init))
1386 Vars.push_back(RefExpr);
1387 DSAStack->addDSA(VD, DE, OMPC_threadprivate);
1388 VD->addAttr(OMPThreadPrivateDeclAttr::CreateImplicit(
1389 Context, SourceRange(Loc, Loc)));
1390 if (auto *ML = Context.getASTMutationListener())
1391 ML->DeclarationMarkedOpenMPThreadPrivate(VD);
1393 OMPThreadPrivateDecl *D = nullptr;
1394 if (!Vars.empty()) {
1395 D = OMPThreadPrivateDecl::Create(Context, getCurLexicalContext(), Loc,
1397 D->setAccess(AS_public);
1402 static void ReportOriginalDSA(Sema &SemaRef, DSAStackTy *Stack,
1403 const ValueDecl *D, DSAStackTy::DSAVarData DVar,
1404 bool IsLoopIterVar = false) {
1406 SemaRef.Diag(DVar.RefExpr->getExprLoc(), diag::note_omp_explicit_dsa)
1407 << getOpenMPClauseName(DVar.CKind);
1411 PDSA_StaticMemberShared,
1412 PDSA_StaticLocalVarShared,
1413 PDSA_LoopIterVarPrivate,
1414 PDSA_LoopIterVarLinear,
1415 PDSA_LoopIterVarLastprivate,
1416 PDSA_ConstVarShared,
1417 PDSA_GlobalVarShared,
1418 PDSA_TaskVarFirstprivate,
1419 PDSA_LocalVarPrivate,
1421 } Reason = PDSA_Implicit;
1422 bool ReportHint = false;
1423 auto ReportLoc = D->getLocation();
1424 auto *VD = dyn_cast<VarDecl>(D);
1425 if (IsLoopIterVar) {
1426 if (DVar.CKind == OMPC_private)
1427 Reason = PDSA_LoopIterVarPrivate;
1428 else if (DVar.CKind == OMPC_lastprivate)
1429 Reason = PDSA_LoopIterVarLastprivate;
1431 Reason = PDSA_LoopIterVarLinear;
1432 } else if (isOpenMPTaskingDirective(DVar.DKind) &&
1433 DVar.CKind == OMPC_firstprivate) {
1434 Reason = PDSA_TaskVarFirstprivate;
1435 ReportLoc = DVar.ImplicitDSALoc;
1436 } else if (VD && VD->isStaticLocal())
1437 Reason = PDSA_StaticLocalVarShared;
1438 else if (VD && VD->isStaticDataMember())
1439 Reason = PDSA_StaticMemberShared;
1440 else if (VD && VD->isFileVarDecl())
1441 Reason = PDSA_GlobalVarShared;
1442 else if (D->getType().isConstant(SemaRef.getASTContext()))
1443 Reason = PDSA_ConstVarShared;
1444 else if (VD && VD->isLocalVarDecl() && DVar.CKind == OMPC_private) {
1446 Reason = PDSA_LocalVarPrivate;
1448 if (Reason != PDSA_Implicit) {
1449 SemaRef.Diag(ReportLoc, diag::note_omp_predetermined_dsa)
1450 << Reason << ReportHint
1451 << getOpenMPDirectiveName(Stack->getCurrentDirective());
1452 } else if (DVar.ImplicitDSALoc.isValid()) {
1453 SemaRef.Diag(DVar.ImplicitDSALoc, diag::note_omp_implicit_dsa)
1454 << getOpenMPClauseName(DVar.CKind);
1459 class DSAAttrChecker : public StmtVisitor<DSAAttrChecker, void> {
1464 llvm::SmallVector<Expr *, 8> ImplicitFirstprivate;
1465 llvm::DenseMap<ValueDecl *, Expr *> VarsWithInheritedDSA;
1468 void VisitDeclRefExpr(DeclRefExpr *E) {
1469 if (E->isTypeDependent() || E->isValueDependent() ||
1470 E->containsUnexpandedParameterPack() || E->isInstantiationDependent())
1472 if (auto *VD = dyn_cast<VarDecl>(E->getDecl())) {
1473 // Skip internally declared variables.
1474 if (VD->isLocalVarDecl() && !CS->capturesVariable(VD))
1477 auto DVar = Stack->getTopDSA(VD, false);
1478 // Check if the variable has explicit DSA set and stop analysis if it so.
1482 auto ELoc = E->getExprLoc();
1483 auto DKind = Stack->getCurrentDirective();
1484 // The default(none) clause requires that each variable that is referenced
1485 // in the construct, and does not have a predetermined data-sharing
1486 // attribute, must have its data-sharing attribute explicitly determined
1487 // by being listed in a data-sharing attribute clause.
1488 if (DVar.CKind == OMPC_unknown && Stack->getDefaultDSA() == DSA_none &&
1489 isParallelOrTaskRegion(DKind) &&
1490 VarsWithInheritedDSA.count(VD) == 0) {
1491 VarsWithInheritedDSA[VD] = E;
1495 // OpenMP [2.9.3.6, Restrictions, p.2]
1496 // A list item that appears in a reduction clause of the innermost
1497 // enclosing worksharing or parallel construct may not be accessed in an
1499 DVar = Stack->hasInnermostDSA(
1500 VD, [](OpenMPClauseKind C) -> bool { return C == OMPC_reduction; },
1501 [](OpenMPDirectiveKind K) -> bool {
1502 return isOpenMPParallelDirective(K) ||
1503 isOpenMPWorksharingDirective(K) || isOpenMPTeamsDirective(K);
1506 if (isOpenMPTaskingDirective(DKind) && DVar.CKind == OMPC_reduction) {
1508 SemaRef.Diag(ELoc, diag::err_omp_reduction_in_task);
1509 ReportOriginalDSA(SemaRef, Stack, VD, DVar);
1513 // Define implicit data-sharing attributes for task.
1514 DVar = Stack->getImplicitDSA(VD, false);
1515 if (isOpenMPTaskingDirective(DKind) && DVar.CKind != OMPC_shared &&
1516 !Stack->isLoopControlVariable(VD).first)
1517 ImplicitFirstprivate.push_back(E);
1520 void VisitMemberExpr(MemberExpr *E) {
1521 if (E->isTypeDependent() || E->isValueDependent() ||
1522 E->containsUnexpandedParameterPack() || E->isInstantiationDependent())
1524 if (isa<CXXThisExpr>(E->getBase()->IgnoreParens())) {
1525 if (auto *FD = dyn_cast<FieldDecl>(E->getMemberDecl())) {
1526 auto DVar = Stack->getTopDSA(FD, false);
1527 // Check if the variable has explicit DSA set and stop analysis if it
1532 auto ELoc = E->getExprLoc();
1533 auto DKind = Stack->getCurrentDirective();
1534 // OpenMP [2.9.3.6, Restrictions, p.2]
1535 // A list item that appears in a reduction clause of the innermost
1536 // enclosing worksharing or parallel construct may not be accessed in
1537 // an explicit task.
1538 DVar = Stack->hasInnermostDSA(
1539 FD, [](OpenMPClauseKind C) -> bool { return C == OMPC_reduction; },
1540 [](OpenMPDirectiveKind K) -> bool {
1541 return isOpenMPParallelDirective(K) ||
1542 isOpenMPWorksharingDirective(K) ||
1543 isOpenMPTeamsDirective(K);
1546 if (isOpenMPTaskingDirective(DKind) && DVar.CKind == OMPC_reduction) {
1548 SemaRef.Diag(ELoc, diag::err_omp_reduction_in_task);
1549 ReportOriginalDSA(SemaRef, Stack, FD, DVar);
1553 // Define implicit data-sharing attributes for task.
1554 DVar = Stack->getImplicitDSA(FD, false);
1555 if (isOpenMPTaskingDirective(DKind) && DVar.CKind != OMPC_shared &&
1556 !Stack->isLoopControlVariable(FD).first)
1557 ImplicitFirstprivate.push_back(E);
1560 Visit(E->getBase());
1562 void VisitOMPExecutableDirective(OMPExecutableDirective *S) {
1563 for (auto *C : S->clauses()) {
1564 // Skip analysis of arguments of implicitly defined firstprivate clause
1565 // for task directives.
1566 if (C && (!isa<OMPFirstprivateClause>(C) || C->getLocStart().isValid()))
1567 for (auto *CC : C->children()) {
1573 void VisitStmt(Stmt *S) {
1574 for (auto *C : S->children()) {
1575 if (C && !isa<OMPExecutableDirective>(C))
1580 bool isErrorFound() { return ErrorFound; }
1581 ArrayRef<Expr *> getImplicitFirstprivate() { return ImplicitFirstprivate; }
1582 llvm::DenseMap<ValueDecl *, Expr *> &getVarsWithInheritedDSA() {
1583 return VarsWithInheritedDSA;
1586 DSAAttrChecker(DSAStackTy *S, Sema &SemaRef, CapturedStmt *CS)
1587 : Stack(S), SemaRef(SemaRef), ErrorFound(false), CS(CS) {}
1591 void Sema::ActOnOpenMPRegionStart(OpenMPDirectiveKind DKind, Scope *CurScope) {
1594 case OMPD_parallel_for:
1595 case OMPD_parallel_for_simd:
1596 case OMPD_parallel_sections:
1598 case OMPD_target_teams: {
1599 QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1);
1600 QualType KmpInt32PtrTy =
1601 Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
1602 Sema::CapturedParamNameType Params[] = {
1603 std::make_pair(".global_tid.", KmpInt32PtrTy),
1604 std::make_pair(".bound_tid.", KmpInt32PtrTy),
1605 std::make_pair(StringRef(), QualType()) // __context with shared vars
1607 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
1619 case OMPD_taskgroup:
1620 case OMPD_distribute:
1623 case OMPD_target_data:
1625 case OMPD_target_parallel:
1626 case OMPD_target_parallel_for:
1627 case OMPD_target_parallel_for_simd:
1628 case OMPD_target_simd: {
1629 Sema::CapturedParamNameType Params[] = {
1630 std::make_pair(StringRef(), QualType()) // __context with shared vars
1632 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
1637 QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1);
1638 QualType Args[] = {Context.VoidPtrTy.withConst().withRestrict()};
1639 FunctionProtoType::ExtProtoInfo EPI;
1640 EPI.Variadic = true;
1641 QualType CopyFnType = Context.getFunctionType(Context.VoidTy, Args, EPI);
1642 Sema::CapturedParamNameType Params[] = {
1643 std::make_pair(".global_tid.", KmpInt32Ty),
1644 std::make_pair(".part_id.", Context.getPointerType(KmpInt32Ty)),
1645 std::make_pair(".privates.", Context.VoidPtrTy.withConst()),
1646 std::make_pair(".copy_fn.",
1647 Context.getPointerType(CopyFnType).withConst()),
1648 std::make_pair(".task_t.", Context.VoidPtrTy.withConst()),
1649 std::make_pair(StringRef(), QualType()) // __context with shared vars
1651 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
1653 // Mark this captured region as inlined, because we don't use outlined
1654 // function directly.
1655 getCurCapturedRegion()->TheCapturedDecl->addAttr(
1656 AlwaysInlineAttr::CreateImplicit(
1657 Context, AlwaysInlineAttr::Keyword_forceinline, SourceRange()));
1661 case OMPD_taskloop_simd: {
1662 QualType KmpInt32Ty =
1663 Context.getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/1);
1664 QualType KmpUInt64Ty =
1665 Context.getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/0);
1666 QualType KmpInt64Ty =
1667 Context.getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/1);
1668 QualType Args[] = {Context.VoidPtrTy.withConst().withRestrict()};
1669 FunctionProtoType::ExtProtoInfo EPI;
1670 EPI.Variadic = true;
1671 QualType CopyFnType = Context.getFunctionType(Context.VoidTy, Args, EPI);
1672 Sema::CapturedParamNameType Params[] = {
1673 std::make_pair(".global_tid.", KmpInt32Ty),
1674 std::make_pair(".part_id.", Context.getPointerType(KmpInt32Ty)),
1675 std::make_pair(".privates.",
1676 Context.VoidPtrTy.withConst().withRestrict()),
1679 Context.getPointerType(CopyFnType).withConst().withRestrict()),
1680 std::make_pair(".task_t.", Context.VoidPtrTy.withConst()),
1681 std::make_pair(".lb.", KmpUInt64Ty),
1682 std::make_pair(".ub.", KmpUInt64Ty), std::make_pair(".st.", KmpInt64Ty),
1683 std::make_pair(".liter.", KmpInt32Ty),
1684 std::make_pair(StringRef(), QualType()) // __context with shared vars
1686 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
1688 // Mark this captured region as inlined, because we don't use outlined
1689 // function directly.
1690 getCurCapturedRegion()->TheCapturedDecl->addAttr(
1691 AlwaysInlineAttr::CreateImplicit(
1692 Context, AlwaysInlineAttr::Keyword_forceinline, SourceRange()));
1695 case OMPD_distribute_parallel_for_simd:
1696 case OMPD_distribute_simd:
1697 case OMPD_distribute_parallel_for:
1698 case OMPD_teams_distribute:
1699 case OMPD_teams_distribute_simd:
1700 case OMPD_teams_distribute_parallel_for_simd:
1701 case OMPD_teams_distribute_parallel_for:
1702 case OMPD_target_teams_distribute:
1703 case OMPD_target_teams_distribute_parallel_for:
1704 case OMPD_target_teams_distribute_parallel_for_simd: {
1705 QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1);
1706 QualType KmpInt32PtrTy =
1707 Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
1708 Sema::CapturedParamNameType Params[] = {
1709 std::make_pair(".global_tid.", KmpInt32PtrTy),
1710 std::make_pair(".bound_tid.", KmpInt32PtrTy),
1711 std::make_pair(".previous.lb.", Context.getSizeType()),
1712 std::make_pair(".previous.ub.", Context.getSizeType()),
1713 std::make_pair(StringRef(), QualType()) // __context with shared vars
1715 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
1719 case OMPD_threadprivate:
1720 case OMPD_taskyield:
1723 case OMPD_cancellation_point:
1726 case OMPD_target_enter_data:
1727 case OMPD_target_exit_data:
1728 case OMPD_declare_reduction:
1729 case OMPD_declare_simd:
1730 case OMPD_declare_target:
1731 case OMPD_end_declare_target:
1732 case OMPD_target_update:
1733 llvm_unreachable("OpenMP Directive is not allowed");
1735 llvm_unreachable("Unknown OpenMP directive");
1739 static OMPCapturedExprDecl *buildCaptureDecl(Sema &S, IdentifierInfo *Id,
1740 Expr *CaptureExpr, bool WithInit,
1741 bool AsExpression) {
1742 assert(CaptureExpr);
1743 ASTContext &C = S.getASTContext();
1744 Expr *Init = AsExpression ? CaptureExpr : CaptureExpr->IgnoreImpCasts();
1745 QualType Ty = Init->getType();
1746 if (CaptureExpr->getObjectKind() == OK_Ordinary && CaptureExpr->isGLValue()) {
1747 if (S.getLangOpts().CPlusPlus)
1748 Ty = C.getLValueReferenceType(Ty);
1750 Ty = C.getPointerType(Ty);
1752 S.CreateBuiltinUnaryOp(CaptureExpr->getExprLoc(), UO_AddrOf, Init);
1753 if (!Res.isUsable())
1759 auto *CED = OMPCapturedExprDecl::Create(C, S.CurContext, Id, Ty,
1760 CaptureExpr->getLocStart());
1762 CED->addAttr(OMPCaptureNoInitAttr::CreateImplicit(C, SourceRange()));
1763 S.CurContext->addHiddenDecl(CED);
1764 S.AddInitializerToDecl(CED, Init, /*DirectInit=*/false,
1765 /*TypeMayContainAuto=*/true);
1769 static DeclRefExpr *buildCapture(Sema &S, ValueDecl *D, Expr *CaptureExpr,
1771 OMPCapturedExprDecl *CD;
1772 if (auto *VD = S.IsOpenMPCapturedDecl(D))
1773 CD = cast<OMPCapturedExprDecl>(VD);
1775 CD = buildCaptureDecl(S, D->getIdentifier(), CaptureExpr, WithInit,
1776 /*AsExpression=*/false);
1777 return buildDeclRefExpr(S, CD, CD->getType().getNonReferenceType(),
1778 CaptureExpr->getExprLoc());
1781 static ExprResult buildCapture(Sema &S, Expr *CaptureExpr, DeclRefExpr *&Ref) {
1784 buildCaptureDecl(S, &S.getASTContext().Idents.get(".capture_expr."),
1785 CaptureExpr, /*WithInit=*/true, /*AsExpression=*/true);
1786 Ref = buildDeclRefExpr(S, CD, CD->getType().getNonReferenceType(),
1787 CaptureExpr->getExprLoc());
1789 ExprResult Res = Ref;
1790 if (!S.getLangOpts().CPlusPlus &&
1791 CaptureExpr->getObjectKind() == OK_Ordinary && CaptureExpr->isGLValue() &&
1792 Ref->getType()->isPointerType())
1793 Res = S.CreateBuiltinUnaryOp(CaptureExpr->getExprLoc(), UO_Deref, Ref);
1794 if (!Res.isUsable())
1796 return CaptureExpr->isGLValue() ? Res : S.DefaultLvalueConversion(Res.get());
1799 StmtResult Sema::ActOnOpenMPRegionEnd(StmtResult S,
1800 ArrayRef<OMPClause *> Clauses) {
1801 if (!S.isUsable()) {
1802 ActOnCapturedRegionError();
1806 OMPOrderedClause *OC = nullptr;
1807 OMPScheduleClause *SC = nullptr;
1808 SmallVector<OMPLinearClause *, 4> LCs;
1809 // This is required for proper codegen.
1810 for (auto *Clause : Clauses) {
1811 if (isOpenMPPrivate(Clause->getClauseKind()) ||
1812 Clause->getClauseKind() == OMPC_copyprivate ||
1813 (getLangOpts().OpenMPUseTLS &&
1814 getASTContext().getTargetInfo().isTLSSupported() &&
1815 Clause->getClauseKind() == OMPC_copyin)) {
1816 DSAStack->setForceVarCapturing(Clause->getClauseKind() == OMPC_copyin);
1817 // Mark all variables in private list clauses as used in inner region.
1818 for (auto *VarRef : Clause->children()) {
1819 if (auto *E = cast_or_null<Expr>(VarRef)) {
1820 MarkDeclarationsReferencedInExpr(E);
1823 DSAStack->setForceVarCapturing(/*V=*/false);
1824 } else if (isParallelOrTaskRegion(DSAStack->getCurrentDirective())) {
1825 // Mark all variables in private list clauses as used in inner region.
1826 // Required for proper codegen of combined directives.
1827 // TODO: add processing for other clauses.
1828 if (auto *C = OMPClauseWithPreInit::get(Clause)) {
1829 if (auto *DS = cast_or_null<DeclStmt>(C->getPreInitStmt())) {
1830 for (auto *D : DS->decls())
1831 MarkVariableReferenced(D->getLocation(), cast<VarDecl>(D));
1834 if (auto *C = OMPClauseWithPostUpdate::get(Clause)) {
1835 if (auto *E = C->getPostUpdateExpr())
1836 MarkDeclarationsReferencedInExpr(E);
1839 if (Clause->getClauseKind() == OMPC_schedule)
1840 SC = cast<OMPScheduleClause>(Clause);
1841 else if (Clause->getClauseKind() == OMPC_ordered)
1842 OC = cast<OMPOrderedClause>(Clause);
1843 else if (Clause->getClauseKind() == OMPC_linear)
1844 LCs.push_back(cast<OMPLinearClause>(Clause));
1846 bool ErrorFound = false;
1847 // OpenMP, 2.7.1 Loop Construct, Restrictions
1848 // The nonmonotonic modifier cannot be specified if an ordered clause is
1851 (SC->getFirstScheduleModifier() == OMPC_SCHEDULE_MODIFIER_nonmonotonic ||
1852 SC->getSecondScheduleModifier() ==
1853 OMPC_SCHEDULE_MODIFIER_nonmonotonic) &&
1855 Diag(SC->getFirstScheduleModifier() == OMPC_SCHEDULE_MODIFIER_nonmonotonic
1856 ? SC->getFirstScheduleModifierLoc()
1857 : SC->getSecondScheduleModifierLoc(),
1858 diag::err_omp_schedule_nonmonotonic_ordered)
1859 << SourceRange(OC->getLocStart(), OC->getLocEnd());
1862 if (!LCs.empty() && OC && OC->getNumForLoops()) {
1863 for (auto *C : LCs) {
1864 Diag(C->getLocStart(), diag::err_omp_linear_ordered)
1865 << SourceRange(OC->getLocStart(), OC->getLocEnd());
1869 if (isOpenMPWorksharingDirective(DSAStack->getCurrentDirective()) &&
1870 isOpenMPSimdDirective(DSAStack->getCurrentDirective()) && OC &&
1871 OC->getNumForLoops()) {
1872 Diag(OC->getLocStart(), diag::err_omp_ordered_simd)
1873 << getOpenMPDirectiveName(DSAStack->getCurrentDirective());
1877 ActOnCapturedRegionError();
1880 return ActOnCapturedRegionEnd(S.get());
1883 static bool CheckNestingOfRegions(Sema &SemaRef, DSAStackTy *Stack,
1884 OpenMPDirectiveKind CurrentRegion,
1885 const DeclarationNameInfo &CurrentName,
1886 OpenMPDirectiveKind CancelRegion,
1887 SourceLocation StartLoc) {
1888 if (Stack->getCurScope()) {
1889 auto ParentRegion = Stack->getParentDirective();
1890 auto OffendingRegion = ParentRegion;
1891 bool NestingProhibited = false;
1892 bool CloseNesting = true;
1893 bool OrphanSeen = false;
1896 ShouldBeInParallelRegion,
1897 ShouldBeInOrderedRegion,
1898 ShouldBeInTargetRegion,
1899 ShouldBeInTeamsRegion
1900 } Recommend = NoRecommend;
1901 if (isOpenMPSimdDirective(ParentRegion) && CurrentRegion != OMPD_ordered) {
1902 // OpenMP [2.16, Nesting of Regions]
1903 // OpenMP constructs may not be nested inside a simd region.
1904 // OpenMP [2.8.1,simd Construct, Restrictions]
1905 // An ordered construct with the simd clause is the only OpenMP
1906 // construct that can appear in the simd region.
1907 // Allowing a SIMD construct nested in another SIMD construct is an
1908 // extension. The OpenMP 4.5 spec does not allow it. Issue a warning
1910 SemaRef.Diag(StartLoc, (CurrentRegion != OMPD_simd)
1911 ? diag::err_omp_prohibited_region_simd
1912 : diag::warn_omp_nesting_simd);
1913 return CurrentRegion != OMPD_simd;
1915 if (ParentRegion == OMPD_atomic) {
1916 // OpenMP [2.16, Nesting of Regions]
1917 // OpenMP constructs may not be nested inside an atomic region.
1918 SemaRef.Diag(StartLoc, diag::err_omp_prohibited_region_atomic);
1921 if (CurrentRegion == OMPD_section) {
1922 // OpenMP [2.7.2, sections Construct, Restrictions]
1923 // Orphaned section directives are prohibited. That is, the section
1924 // directives must appear within the sections construct and must not be
1925 // encountered elsewhere in the sections region.
1926 if (ParentRegion != OMPD_sections &&
1927 ParentRegion != OMPD_parallel_sections) {
1928 SemaRef.Diag(StartLoc, diag::err_omp_orphaned_section_directive)
1929 << (ParentRegion != OMPD_unknown)
1930 << getOpenMPDirectiveName(ParentRegion);
1935 // Allow some constructs (except teams) to be orphaned (they could be
1936 // used in functions, called from OpenMP regions with the required
1938 if (ParentRegion == OMPD_unknown &&
1939 !isOpenMPNestingTeamsDirective(CurrentRegion))
1941 if (CurrentRegion == OMPD_cancellation_point ||
1942 CurrentRegion == OMPD_cancel) {
1943 // OpenMP [2.16, Nesting of Regions]
1944 // A cancellation point construct for which construct-type-clause is
1945 // taskgroup must be nested inside a task construct. A cancellation
1946 // point construct for which construct-type-clause is not taskgroup must
1947 // be closely nested inside an OpenMP construct that matches the type
1948 // specified in construct-type-clause.
1949 // A cancel construct for which construct-type-clause is taskgroup must be
1950 // nested inside a task construct. A cancel construct for which
1951 // construct-type-clause is not taskgroup must be closely nested inside an
1952 // OpenMP construct that matches the type specified in
1953 // construct-type-clause.
1955 !((CancelRegion == OMPD_parallel &&
1956 (ParentRegion == OMPD_parallel ||
1957 ParentRegion == OMPD_target_parallel)) ||
1958 (CancelRegion == OMPD_for &&
1959 (ParentRegion == OMPD_for || ParentRegion == OMPD_parallel_for ||
1960 ParentRegion == OMPD_target_parallel_for)) ||
1961 (CancelRegion == OMPD_taskgroup && ParentRegion == OMPD_task) ||
1962 (CancelRegion == OMPD_sections &&
1963 (ParentRegion == OMPD_section || ParentRegion == OMPD_sections ||
1964 ParentRegion == OMPD_parallel_sections)));
1965 } else if (CurrentRegion == OMPD_master) {
1966 // OpenMP [2.16, Nesting of Regions]
1967 // A master region may not be closely nested inside a worksharing,
1968 // atomic, or explicit task region.
1969 NestingProhibited = isOpenMPWorksharingDirective(ParentRegion) ||
1970 isOpenMPTaskingDirective(ParentRegion);
1971 } else if (CurrentRegion == OMPD_critical && CurrentName.getName()) {
1972 // OpenMP [2.16, Nesting of Regions]
1973 // A critical region may not be nested (closely or otherwise) inside a
1974 // critical region with the same name. Note that this restriction is not
1975 // sufficient to prevent deadlock.
1976 SourceLocation PreviousCriticalLoc;
1977 bool DeadLock = Stack->hasDirective(
1978 [CurrentName, &PreviousCriticalLoc](OpenMPDirectiveKind K,
1979 const DeclarationNameInfo &DNI,
1980 SourceLocation Loc) -> bool {
1981 if (K == OMPD_critical && DNI.getName() == CurrentName.getName()) {
1982 PreviousCriticalLoc = Loc;
1987 false /* skip top directive */);
1989 SemaRef.Diag(StartLoc,
1990 diag::err_omp_prohibited_region_critical_same_name)
1991 << CurrentName.getName();
1992 if (PreviousCriticalLoc.isValid())
1993 SemaRef.Diag(PreviousCriticalLoc,
1994 diag::note_omp_previous_critical_region);
1997 } else if (CurrentRegion == OMPD_barrier) {
1998 // OpenMP [2.16, Nesting of Regions]
1999 // A barrier region may not be closely nested inside a worksharing,
2000 // explicit task, critical, ordered, atomic, or master region.
2001 NestingProhibited = isOpenMPWorksharingDirective(ParentRegion) ||
2002 isOpenMPTaskingDirective(ParentRegion) ||
2003 ParentRegion == OMPD_master ||
2004 ParentRegion == OMPD_critical ||
2005 ParentRegion == OMPD_ordered;
2006 } else if (isOpenMPWorksharingDirective(CurrentRegion) &&
2007 !isOpenMPParallelDirective(CurrentRegion) &&
2008 !isOpenMPTeamsDirective(CurrentRegion)) {
2009 // OpenMP [2.16, Nesting of Regions]
2010 // A worksharing region may not be closely nested inside a worksharing,
2011 // explicit task, critical, ordered, atomic, or master region.
2012 NestingProhibited = isOpenMPWorksharingDirective(ParentRegion) ||
2013 isOpenMPTaskingDirective(ParentRegion) ||
2014 ParentRegion == OMPD_master ||
2015 ParentRegion == OMPD_critical ||
2016 ParentRegion == OMPD_ordered;
2017 Recommend = ShouldBeInParallelRegion;
2018 } else if (CurrentRegion == OMPD_ordered) {
2019 // OpenMP [2.16, Nesting of Regions]
2020 // An ordered region may not be closely nested inside a critical,
2021 // atomic, or explicit task region.
2022 // An ordered region must be closely nested inside a loop region (or
2023 // parallel loop region) with an ordered clause.
2024 // OpenMP [2.8.1,simd Construct, Restrictions]
2025 // An ordered construct with the simd clause is the only OpenMP construct
2026 // that can appear in the simd region.
2027 NestingProhibited = ParentRegion == OMPD_critical ||
2028 isOpenMPTaskingDirective(ParentRegion) ||
2029 !(isOpenMPSimdDirective(ParentRegion) ||
2030 Stack->isParentOrderedRegion());
2031 Recommend = ShouldBeInOrderedRegion;
2032 } else if (isOpenMPNestingTeamsDirective(CurrentRegion)) {
2033 // OpenMP [2.16, Nesting of Regions]
2034 // If specified, a teams construct must be contained within a target
2036 NestingProhibited = ParentRegion != OMPD_target;
2037 OrphanSeen = ParentRegion == OMPD_unknown;
2038 Recommend = ShouldBeInTargetRegion;
2039 Stack->setParentTeamsRegionLoc(Stack->getConstructLoc());
2041 if (!NestingProhibited &&
2042 !isOpenMPTargetExecutionDirective(CurrentRegion) &&
2043 !isOpenMPTargetDataManagementDirective(CurrentRegion) &&
2044 (ParentRegion == OMPD_teams || ParentRegion == OMPD_target_teams)) {
2045 // OpenMP [2.16, Nesting of Regions]
2046 // distribute, parallel, parallel sections, parallel workshare, and the
2047 // parallel loop and parallel loop SIMD constructs are the only OpenMP
2048 // constructs that can be closely nested in the teams region.
2049 NestingProhibited = !isOpenMPParallelDirective(CurrentRegion) &&
2050 !isOpenMPDistributeDirective(CurrentRegion);
2051 Recommend = ShouldBeInParallelRegion;
2053 if (!NestingProhibited &&
2054 isOpenMPNestingDistributeDirective(CurrentRegion)) {
2055 // OpenMP 4.5 [2.17 Nesting of Regions]
2056 // The region associated with the distribute construct must be strictly
2057 // nested inside a teams region
2059 (ParentRegion != OMPD_teams && ParentRegion != OMPD_target_teams);
2060 Recommend = ShouldBeInTeamsRegion;
2062 if (!NestingProhibited &&
2063 (isOpenMPTargetExecutionDirective(CurrentRegion) ||
2064 isOpenMPTargetDataManagementDirective(CurrentRegion))) {
2065 // OpenMP 4.5 [2.17 Nesting of Regions]
2066 // If a target, target update, target data, target enter data, or
2067 // target exit data construct is encountered during execution of a
2068 // target region, the behavior is unspecified.
2069 NestingProhibited = Stack->hasDirective(
2070 [&OffendingRegion](OpenMPDirectiveKind K, const DeclarationNameInfo &,
2071 SourceLocation) -> bool {
2072 if (isOpenMPTargetExecutionDirective(K)) {
2073 OffendingRegion = K;
2078 false /* don't skip top directive */);
2079 CloseNesting = false;
2081 if (NestingProhibited) {
2083 SemaRef.Diag(StartLoc, diag::err_omp_orphaned_device_directive)
2084 << getOpenMPDirectiveName(CurrentRegion) << Recommend;
2086 SemaRef.Diag(StartLoc, diag::err_omp_prohibited_region)
2087 << CloseNesting << getOpenMPDirectiveName(OffendingRegion)
2088 << Recommend << getOpenMPDirectiveName(CurrentRegion);
2096 static bool checkIfClauses(Sema &S, OpenMPDirectiveKind Kind,
2097 ArrayRef<OMPClause *> Clauses,
2098 ArrayRef<OpenMPDirectiveKind> AllowedNameModifiers) {
2099 bool ErrorFound = false;
2100 unsigned NamedModifiersNumber = 0;
2101 SmallVector<const OMPIfClause *, OMPC_unknown + 1> FoundNameModifiers(
2103 SmallVector<SourceLocation, 4> NameModifierLoc;
2104 for (const auto *C : Clauses) {
2105 if (const auto *IC = dyn_cast_or_null<OMPIfClause>(C)) {
2106 // At most one if clause without a directive-name-modifier can appear on
2108 OpenMPDirectiveKind CurNM = IC->getNameModifier();
2109 if (FoundNameModifiers[CurNM]) {
2110 S.Diag(C->getLocStart(), diag::err_omp_more_one_clause)
2111 << getOpenMPDirectiveName(Kind) << getOpenMPClauseName(OMPC_if)
2112 << (CurNM != OMPD_unknown) << getOpenMPDirectiveName(CurNM);
2114 } else if (CurNM != OMPD_unknown) {
2115 NameModifierLoc.push_back(IC->getNameModifierLoc());
2116 ++NamedModifiersNumber;
2118 FoundNameModifiers[CurNM] = IC;
2119 if (CurNM == OMPD_unknown)
2121 // Check if the specified name modifier is allowed for the current
2123 // At most one if clause with the particular directive-name-modifier can
2124 // appear on the directive.
2125 bool MatchFound = false;
2126 for (auto NM : AllowedNameModifiers) {
2133 S.Diag(IC->getNameModifierLoc(),
2134 diag::err_omp_wrong_if_directive_name_modifier)
2135 << getOpenMPDirectiveName(CurNM) << getOpenMPDirectiveName(Kind);
2140 // If any if clause on the directive includes a directive-name-modifier then
2141 // all if clauses on the directive must include a directive-name-modifier.
2142 if (FoundNameModifiers[OMPD_unknown] && NamedModifiersNumber > 0) {
2143 if (NamedModifiersNumber == AllowedNameModifiers.size()) {
2144 S.Diag(FoundNameModifiers[OMPD_unknown]->getLocStart(),
2145 diag::err_omp_no_more_if_clause);
2148 std::string Sep(", ");
2149 unsigned AllowedCnt = 0;
2150 unsigned TotalAllowedNum =
2151 AllowedNameModifiers.size() - NamedModifiersNumber;
2152 for (unsigned Cnt = 0, End = AllowedNameModifiers.size(); Cnt < End;
2154 OpenMPDirectiveKind NM = AllowedNameModifiers[Cnt];
2155 if (!FoundNameModifiers[NM]) {
2157 Values += getOpenMPDirectiveName(NM);
2159 if (AllowedCnt + 2 == TotalAllowedNum)
2161 else if (AllowedCnt + 1 != TotalAllowedNum)
2166 S.Diag(FoundNameModifiers[OMPD_unknown]->getCondition()->getLocStart(),
2167 diag::err_omp_unnamed_if_clause)
2168 << (TotalAllowedNum > 1) << Values;
2170 for (auto Loc : NameModifierLoc) {
2171 S.Diag(Loc, diag::note_omp_previous_named_if_clause);
2178 StmtResult Sema::ActOnOpenMPExecutableDirective(
2179 OpenMPDirectiveKind Kind, const DeclarationNameInfo &DirName,
2180 OpenMPDirectiveKind CancelRegion, ArrayRef<OMPClause *> Clauses,
2181 Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc) {
2182 StmtResult Res = StmtError();
2183 if (CheckNestingOfRegions(*this, DSAStack, Kind, DirName, CancelRegion,
2187 llvm::SmallVector<OMPClause *, 8> ClausesWithImplicit;
2188 llvm::DenseMap<ValueDecl *, Expr *> VarsWithInheritedDSA;
2189 bool ErrorFound = false;
2190 ClausesWithImplicit.append(Clauses.begin(), Clauses.end());
2192 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
2194 // Check default data sharing attributes for referenced variables.
2195 DSAAttrChecker DSAChecker(DSAStack, *this, cast<CapturedStmt>(AStmt));
2196 DSAChecker.Visit(cast<CapturedStmt>(AStmt)->getCapturedStmt());
2197 if (DSAChecker.isErrorFound())
2199 // Generate list of implicitly defined firstprivate variables.
2200 VarsWithInheritedDSA = DSAChecker.getVarsWithInheritedDSA();
2202 if (!DSAChecker.getImplicitFirstprivate().empty()) {
2203 if (OMPClause *Implicit = ActOnOpenMPFirstprivateClause(
2204 DSAChecker.getImplicitFirstprivate(), SourceLocation(),
2205 SourceLocation(), SourceLocation())) {
2206 ClausesWithImplicit.push_back(Implicit);
2207 ErrorFound = cast<OMPFirstprivateClause>(Implicit)->varlist_size() !=
2208 DSAChecker.getImplicitFirstprivate().size();
2214 llvm::SmallVector<OpenMPDirectiveKind, 4> AllowedNameModifiers;
2217 Res = ActOnOpenMPParallelDirective(ClausesWithImplicit, AStmt, StartLoc,
2219 AllowedNameModifiers.push_back(OMPD_parallel);
2222 Res = ActOnOpenMPSimdDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc,
2223 VarsWithInheritedDSA);
2226 Res = ActOnOpenMPForDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc,
2227 VarsWithInheritedDSA);
2230 Res = ActOnOpenMPForSimdDirective(ClausesWithImplicit, AStmt, StartLoc,
2231 EndLoc, VarsWithInheritedDSA);
2234 Res = ActOnOpenMPSectionsDirective(ClausesWithImplicit, AStmt, StartLoc,
2238 assert(ClausesWithImplicit.empty() &&
2239 "No clauses are allowed for 'omp section' directive");
2240 Res = ActOnOpenMPSectionDirective(AStmt, StartLoc, EndLoc);
2243 Res = ActOnOpenMPSingleDirective(ClausesWithImplicit, AStmt, StartLoc,
2247 assert(ClausesWithImplicit.empty() &&
2248 "No clauses are allowed for 'omp master' directive");
2249 Res = ActOnOpenMPMasterDirective(AStmt, StartLoc, EndLoc);
2252 Res = ActOnOpenMPCriticalDirective(DirName, ClausesWithImplicit, AStmt,
2255 case OMPD_parallel_for:
2256 Res = ActOnOpenMPParallelForDirective(ClausesWithImplicit, AStmt, StartLoc,
2257 EndLoc, VarsWithInheritedDSA);
2258 AllowedNameModifiers.push_back(OMPD_parallel);
2260 case OMPD_parallel_for_simd:
2261 Res = ActOnOpenMPParallelForSimdDirective(
2262 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
2263 AllowedNameModifiers.push_back(OMPD_parallel);
2265 case OMPD_parallel_sections:
2266 Res = ActOnOpenMPParallelSectionsDirective(ClausesWithImplicit, AStmt,
2268 AllowedNameModifiers.push_back(OMPD_parallel);
2272 ActOnOpenMPTaskDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc);
2273 AllowedNameModifiers.push_back(OMPD_task);
2275 case OMPD_taskyield:
2276 assert(ClausesWithImplicit.empty() &&
2277 "No clauses are allowed for 'omp taskyield' directive");
2278 assert(AStmt == nullptr &&
2279 "No associated statement allowed for 'omp taskyield' directive");
2280 Res = ActOnOpenMPTaskyieldDirective(StartLoc, EndLoc);
2283 assert(ClausesWithImplicit.empty() &&
2284 "No clauses are allowed for 'omp barrier' directive");
2285 assert(AStmt == nullptr &&
2286 "No associated statement allowed for 'omp barrier' directive");
2287 Res = ActOnOpenMPBarrierDirective(StartLoc, EndLoc);
2290 assert(ClausesWithImplicit.empty() &&
2291 "No clauses are allowed for 'omp taskwait' directive");
2292 assert(AStmt == nullptr &&
2293 "No associated statement allowed for 'omp taskwait' directive");
2294 Res = ActOnOpenMPTaskwaitDirective(StartLoc, EndLoc);
2296 case OMPD_taskgroup:
2297 assert(ClausesWithImplicit.empty() &&
2298 "No clauses are allowed for 'omp taskgroup' directive");
2299 Res = ActOnOpenMPTaskgroupDirective(AStmt, StartLoc, EndLoc);
2302 assert(AStmt == nullptr &&
2303 "No associated statement allowed for 'omp flush' directive");
2304 Res = ActOnOpenMPFlushDirective(ClausesWithImplicit, StartLoc, EndLoc);
2307 Res = ActOnOpenMPOrderedDirective(ClausesWithImplicit, AStmt, StartLoc,
2311 Res = ActOnOpenMPAtomicDirective(ClausesWithImplicit, AStmt, StartLoc,
2316 ActOnOpenMPTeamsDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc);
2319 Res = ActOnOpenMPTargetDirective(ClausesWithImplicit, AStmt, StartLoc,
2321 AllowedNameModifiers.push_back(OMPD_target);
2323 case OMPD_target_parallel:
2324 Res = ActOnOpenMPTargetParallelDirective(ClausesWithImplicit, AStmt,
2326 AllowedNameModifiers.push_back(OMPD_target);
2327 AllowedNameModifiers.push_back(OMPD_parallel);
2329 case OMPD_target_parallel_for:
2330 Res = ActOnOpenMPTargetParallelForDirective(
2331 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
2332 AllowedNameModifiers.push_back(OMPD_target);
2333 AllowedNameModifiers.push_back(OMPD_parallel);
2335 case OMPD_cancellation_point:
2336 assert(ClausesWithImplicit.empty() &&
2337 "No clauses are allowed for 'omp cancellation point' directive");
2338 assert(AStmt == nullptr && "No associated statement allowed for 'omp "
2339 "cancellation point' directive");
2340 Res = ActOnOpenMPCancellationPointDirective(StartLoc, EndLoc, CancelRegion);
2343 assert(AStmt == nullptr &&
2344 "No associated statement allowed for 'omp cancel' directive");
2345 Res = ActOnOpenMPCancelDirective(ClausesWithImplicit, StartLoc, EndLoc,
2347 AllowedNameModifiers.push_back(OMPD_cancel);
2349 case OMPD_target_data:
2350 Res = ActOnOpenMPTargetDataDirective(ClausesWithImplicit, AStmt, StartLoc,
2352 AllowedNameModifiers.push_back(OMPD_target_data);
2354 case OMPD_target_enter_data:
2355 Res = ActOnOpenMPTargetEnterDataDirective(ClausesWithImplicit, StartLoc,
2357 AllowedNameModifiers.push_back(OMPD_target_enter_data);
2359 case OMPD_target_exit_data:
2360 Res = ActOnOpenMPTargetExitDataDirective(ClausesWithImplicit, StartLoc,
2362 AllowedNameModifiers.push_back(OMPD_target_exit_data);
2365 Res = ActOnOpenMPTaskLoopDirective(ClausesWithImplicit, AStmt, StartLoc,
2366 EndLoc, VarsWithInheritedDSA);
2367 AllowedNameModifiers.push_back(OMPD_taskloop);
2369 case OMPD_taskloop_simd:
2370 Res = ActOnOpenMPTaskLoopSimdDirective(ClausesWithImplicit, AStmt, StartLoc,
2371 EndLoc, VarsWithInheritedDSA);
2372 AllowedNameModifiers.push_back(OMPD_taskloop);
2374 case OMPD_distribute:
2375 Res = ActOnOpenMPDistributeDirective(ClausesWithImplicit, AStmt, StartLoc,
2376 EndLoc, VarsWithInheritedDSA);
2378 case OMPD_target_update:
2379 assert(!AStmt && "Statement is not allowed for target update");
2381 ActOnOpenMPTargetUpdateDirective(ClausesWithImplicit, StartLoc, EndLoc);
2382 AllowedNameModifiers.push_back(OMPD_target_update);
2384 case OMPD_distribute_parallel_for:
2385 Res = ActOnOpenMPDistributeParallelForDirective(
2386 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
2387 AllowedNameModifiers.push_back(OMPD_parallel);
2389 case OMPD_distribute_parallel_for_simd:
2390 Res = ActOnOpenMPDistributeParallelForSimdDirective(
2391 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
2392 AllowedNameModifiers.push_back(OMPD_parallel);
2394 case OMPD_distribute_simd:
2395 Res = ActOnOpenMPDistributeSimdDirective(
2396 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
2398 case OMPD_target_parallel_for_simd:
2399 Res = ActOnOpenMPTargetParallelForSimdDirective(
2400 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
2401 AllowedNameModifiers.push_back(OMPD_target);
2402 AllowedNameModifiers.push_back(OMPD_parallel);
2404 case OMPD_target_simd:
2405 Res = ActOnOpenMPTargetSimdDirective(ClausesWithImplicit, AStmt, StartLoc,
2406 EndLoc, VarsWithInheritedDSA);
2407 AllowedNameModifiers.push_back(OMPD_target);
2409 case OMPD_teams_distribute:
2410 Res = ActOnOpenMPTeamsDistributeDirective(
2411 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
2413 case OMPD_teams_distribute_simd:
2414 Res = ActOnOpenMPTeamsDistributeSimdDirective(
2415 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
2417 case OMPD_teams_distribute_parallel_for_simd:
2418 Res = ActOnOpenMPTeamsDistributeParallelForSimdDirective(
2419 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
2420 AllowedNameModifiers.push_back(OMPD_parallel);
2422 case OMPD_teams_distribute_parallel_for:
2423 Res = ActOnOpenMPTeamsDistributeParallelForDirective(
2424 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
2425 AllowedNameModifiers.push_back(OMPD_parallel);
2427 case OMPD_target_teams:
2428 Res = ActOnOpenMPTargetTeamsDirective(ClausesWithImplicit, AStmt, StartLoc,
2430 AllowedNameModifiers.push_back(OMPD_target);
2432 case OMPD_target_teams_distribute:
2433 Res = ActOnOpenMPTargetTeamsDistributeDirective(
2434 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
2435 AllowedNameModifiers.push_back(OMPD_target);
2437 case OMPD_target_teams_distribute_parallel_for:
2438 Res = ActOnOpenMPTargetTeamsDistributeParallelForDirective(
2439 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
2440 AllowedNameModifiers.push_back(OMPD_target);
2441 AllowedNameModifiers.push_back(OMPD_parallel);
2443 case OMPD_target_teams_distribute_parallel_for_simd:
2444 Res = ActOnOpenMPTargetTeamsDistributeParallelForSimdDirective(
2445 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
2446 AllowedNameModifiers.push_back(OMPD_target);
2447 AllowedNameModifiers.push_back(OMPD_parallel);
2449 case OMPD_declare_target:
2450 case OMPD_end_declare_target:
2451 case OMPD_threadprivate:
2452 case OMPD_declare_reduction:
2453 case OMPD_declare_simd:
2454 llvm_unreachable("OpenMP Directive is not allowed");
2456 llvm_unreachable("Unknown OpenMP directive");
2459 for (auto P : VarsWithInheritedDSA) {
2460 Diag(P.second->getExprLoc(), diag::err_omp_no_dsa_for_variable)
2461 << P.first << P.second->getSourceRange();
2463 ErrorFound = !VarsWithInheritedDSA.empty() || ErrorFound;
2465 if (!AllowedNameModifiers.empty())
2466 ErrorFound = checkIfClauses(*this, Kind, Clauses, AllowedNameModifiers) ||
2474 Sema::DeclGroupPtrTy Sema::ActOnOpenMPDeclareSimdDirective(
2475 DeclGroupPtrTy DG, OMPDeclareSimdDeclAttr::BranchStateTy BS, Expr *Simdlen,
2476 ArrayRef<Expr *> Uniforms, ArrayRef<Expr *> Aligneds,
2477 ArrayRef<Expr *> Alignments, ArrayRef<Expr *> Linears,
2478 ArrayRef<unsigned> LinModifiers, ArrayRef<Expr *> Steps, SourceRange SR) {
2479 assert(Aligneds.size() == Alignments.size());
2480 assert(Linears.size() == LinModifiers.size());
2481 assert(Linears.size() == Steps.size());
2482 if (!DG || DG.get().isNull())
2483 return DeclGroupPtrTy();
2485 if (!DG.get().isSingleDecl()) {
2486 Diag(SR.getBegin(), diag::err_omp_single_decl_in_declare_simd);
2489 auto *ADecl = DG.get().getSingleDecl();
2490 if (auto *FTD = dyn_cast<FunctionTemplateDecl>(ADecl))
2491 ADecl = FTD->getTemplatedDecl();
2493 auto *FD = dyn_cast<FunctionDecl>(ADecl);
2495 Diag(ADecl->getLocation(), diag::err_omp_function_expected);
2496 return DeclGroupPtrTy();
2499 // OpenMP [2.8.2, declare simd construct, Description]
2500 // The parameter of the simdlen clause must be a constant positive integer
2504 SL = VerifyPositiveIntegerConstantInClause(Simdlen, OMPC_simdlen);
2505 // OpenMP [2.8.2, declare simd construct, Description]
2506 // The special this pointer can be used as if was one of the arguments to the
2507 // function in any of the linear, aligned, or uniform clauses.
2508 // The uniform clause declares one or more arguments to have an invariant
2509 // value for all concurrent invocations of the function in the execution of a
2510 // single SIMD loop.
2511 llvm::DenseMap<Decl *, Expr *> UniformedArgs;
2512 Expr *UniformedLinearThis = nullptr;
2513 for (auto *E : Uniforms) {
2514 E = E->IgnoreParenImpCasts();
2515 if (auto *DRE = dyn_cast<DeclRefExpr>(E))
2516 if (auto *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl()))
2517 if (FD->getNumParams() > PVD->getFunctionScopeIndex() &&
2518 FD->getParamDecl(PVD->getFunctionScopeIndex())
2519 ->getCanonicalDecl() == PVD->getCanonicalDecl()) {
2520 UniformedArgs.insert(std::make_pair(PVD->getCanonicalDecl(), E));
2523 if (isa<CXXThisExpr>(E)) {
2524 UniformedLinearThis = E;
2527 Diag(E->getExprLoc(), diag::err_omp_param_or_this_in_clause)
2528 << FD->getDeclName() << (isa<CXXMethodDecl>(ADecl) ? 1 : 0);
2530 // OpenMP [2.8.2, declare simd construct, Description]
2531 // The aligned clause declares that the object to which each list item points
2532 // is aligned to the number of bytes expressed in the optional parameter of
2533 // the aligned clause.
2534 // The special this pointer can be used as if was one of the arguments to the
2535 // function in any of the linear, aligned, or uniform clauses.
2536 // The type of list items appearing in the aligned clause must be array,
2537 // pointer, reference to array, or reference to pointer.
2538 llvm::DenseMap<Decl *, Expr *> AlignedArgs;
2539 Expr *AlignedThis = nullptr;
2540 for (auto *E : Aligneds) {
2541 E = E->IgnoreParenImpCasts();
2542 if (auto *DRE = dyn_cast<DeclRefExpr>(E))
2543 if (auto *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl())) {
2544 auto *CanonPVD = PVD->getCanonicalDecl();
2545 if (FD->getNumParams() > PVD->getFunctionScopeIndex() &&
2546 FD->getParamDecl(PVD->getFunctionScopeIndex())
2547 ->getCanonicalDecl() == CanonPVD) {
2548 // OpenMP [2.8.1, simd construct, Restrictions]
2549 // A list-item cannot appear in more than one aligned clause.
2550 if (AlignedArgs.count(CanonPVD) > 0) {
2551 Diag(E->getExprLoc(), diag::err_omp_aligned_twice)
2552 << 1 << E->getSourceRange();
2553 Diag(AlignedArgs[CanonPVD]->getExprLoc(),
2554 diag::note_omp_explicit_dsa)
2555 << getOpenMPClauseName(OMPC_aligned);
2558 AlignedArgs[CanonPVD] = E;
2559 QualType QTy = PVD->getType()
2560 .getNonReferenceType()
2561 .getUnqualifiedType()
2562 .getCanonicalType();
2563 const Type *Ty = QTy.getTypePtrOrNull();
2564 if (!Ty || (!Ty->isArrayType() && !Ty->isPointerType())) {
2565 Diag(E->getExprLoc(), diag::err_omp_aligned_expected_array_or_ptr)
2566 << QTy << getLangOpts().CPlusPlus << E->getSourceRange();
2567 Diag(PVD->getLocation(), diag::note_previous_decl) << PVD;
2572 if (isa<CXXThisExpr>(E)) {
2574 Diag(E->getExprLoc(), diag::err_omp_aligned_twice)
2575 << 2 << E->getSourceRange();
2576 Diag(AlignedThis->getExprLoc(), diag::note_omp_explicit_dsa)
2577 << getOpenMPClauseName(OMPC_aligned);
2582 Diag(E->getExprLoc(), diag::err_omp_param_or_this_in_clause)
2583 << FD->getDeclName() << (isa<CXXMethodDecl>(ADecl) ? 1 : 0);
2585 // The optional parameter of the aligned clause, alignment, must be a constant
2586 // positive integer expression. If no optional parameter is specified,
2587 // implementation-defined default alignments for SIMD instructions on the
2588 // target platforms are assumed.
2589 SmallVector<Expr *, 4> NewAligns;
2590 for (auto *E : Alignments) {
2593 Align = VerifyPositiveIntegerConstantInClause(E, OMPC_aligned);
2594 NewAligns.push_back(Align.get());
2596 // OpenMP [2.8.2, declare simd construct, Description]
2597 // The linear clause declares one or more list items to be private to a SIMD
2598 // lane and to have a linear relationship with respect to the iteration space
2600 // The special this pointer can be used as if was one of the arguments to the
2601 // function in any of the linear, aligned, or uniform clauses.
2602 // When a linear-step expression is specified in a linear clause it must be
2603 // either a constant integer expression or an integer-typed parameter that is
2604 // specified in a uniform clause on the directive.
2605 llvm::DenseMap<Decl *, Expr *> LinearArgs;
2606 const bool IsUniformedThis = UniformedLinearThis != nullptr;
2607 auto MI = LinModifiers.begin();
2608 for (auto *E : Linears) {
2609 auto LinKind = static_cast<OpenMPLinearClauseKind>(*MI);
2611 E = E->IgnoreParenImpCasts();
2612 if (auto *DRE = dyn_cast<DeclRefExpr>(E))
2613 if (auto *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl())) {
2614 auto *CanonPVD = PVD->getCanonicalDecl();
2615 if (FD->getNumParams() > PVD->getFunctionScopeIndex() &&
2616 FD->getParamDecl(PVD->getFunctionScopeIndex())
2617 ->getCanonicalDecl() == CanonPVD) {
2618 // OpenMP [2.15.3.7, linear Clause, Restrictions]
2619 // A list-item cannot appear in more than one linear clause.
2620 if (LinearArgs.count(CanonPVD) > 0) {
2621 Diag(E->getExprLoc(), diag::err_omp_wrong_dsa)
2622 << getOpenMPClauseName(OMPC_linear)
2623 << getOpenMPClauseName(OMPC_linear) << E->getSourceRange();
2624 Diag(LinearArgs[CanonPVD]->getExprLoc(),
2625 diag::note_omp_explicit_dsa)
2626 << getOpenMPClauseName(OMPC_linear);
2629 // Each argument can appear in at most one uniform or linear clause.
2630 if (UniformedArgs.count(CanonPVD) > 0) {
2631 Diag(E->getExprLoc(), diag::err_omp_wrong_dsa)
2632 << getOpenMPClauseName(OMPC_linear)
2633 << getOpenMPClauseName(OMPC_uniform) << E->getSourceRange();
2634 Diag(UniformedArgs[CanonPVD]->getExprLoc(),
2635 diag::note_omp_explicit_dsa)
2636 << getOpenMPClauseName(OMPC_uniform);
2639 LinearArgs[CanonPVD] = E;
2640 if (E->isValueDependent() || E->isTypeDependent() ||
2641 E->isInstantiationDependent() ||
2642 E->containsUnexpandedParameterPack())
2644 (void)CheckOpenMPLinearDecl(CanonPVD, E->getExprLoc(), LinKind,
2645 PVD->getOriginalType());
2649 if (isa<CXXThisExpr>(E)) {
2650 if (UniformedLinearThis) {
2651 Diag(E->getExprLoc(), diag::err_omp_wrong_dsa)
2652 << getOpenMPClauseName(OMPC_linear)
2653 << getOpenMPClauseName(IsUniformedThis ? OMPC_uniform : OMPC_linear)
2654 << E->getSourceRange();
2655 Diag(UniformedLinearThis->getExprLoc(), diag::note_omp_explicit_dsa)
2656 << getOpenMPClauseName(IsUniformedThis ? OMPC_uniform
2660 UniformedLinearThis = E;
2661 if (E->isValueDependent() || E->isTypeDependent() ||
2662 E->isInstantiationDependent() || E->containsUnexpandedParameterPack())
2664 (void)CheckOpenMPLinearDecl(/*D=*/nullptr, E->getExprLoc(), LinKind,
2668 Diag(E->getExprLoc(), diag::err_omp_param_or_this_in_clause)
2669 << FD->getDeclName() << (isa<CXXMethodDecl>(ADecl) ? 1 : 0);
2671 Expr *Step = nullptr;
2672 Expr *NewStep = nullptr;
2673 SmallVector<Expr *, 4> NewSteps;
2674 for (auto *E : Steps) {
2675 // Skip the same step expression, it was checked already.
2676 if (Step == E || !E) {
2677 NewSteps.push_back(E ? NewStep : nullptr);
2681 if (auto *DRE = dyn_cast<DeclRefExpr>(Step))
2682 if (auto *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl())) {
2683 auto *CanonPVD = PVD->getCanonicalDecl();
2684 if (UniformedArgs.count(CanonPVD) == 0) {
2685 Diag(Step->getExprLoc(), diag::err_omp_expected_uniform_param)
2686 << Step->getSourceRange();
2687 } else if (E->isValueDependent() || E->isTypeDependent() ||
2688 E->isInstantiationDependent() ||
2689 E->containsUnexpandedParameterPack() ||
2690 CanonPVD->getType()->hasIntegerRepresentation())
2691 NewSteps.push_back(Step);
2693 Diag(Step->getExprLoc(), diag::err_omp_expected_int_param)
2694 << Step->getSourceRange();
2699 if (Step && !Step->isValueDependent() && !Step->isTypeDependent() &&
2700 !Step->isInstantiationDependent() &&
2701 !Step->containsUnexpandedParameterPack()) {
2702 NewStep = PerformOpenMPImplicitIntegerConversion(Step->getExprLoc(), Step)
2705 NewStep = VerifyIntegerConstantExpression(NewStep).get();
2707 NewSteps.push_back(NewStep);
2709 auto *NewAttr = OMPDeclareSimdDeclAttr::CreateImplicit(
2710 Context, BS, SL.get(), const_cast<Expr **>(Uniforms.data()),
2711 Uniforms.size(), const_cast<Expr **>(Aligneds.data()), Aligneds.size(),
2712 const_cast<Expr **>(NewAligns.data()), NewAligns.size(),
2713 const_cast<Expr **>(Linears.data()), Linears.size(),
2714 const_cast<unsigned *>(LinModifiers.data()), LinModifiers.size(),
2715 NewSteps.data(), NewSteps.size(), SR);
2716 ADecl->addAttr(NewAttr);
2717 return ConvertDeclToDeclGroup(ADecl);
2720 StmtResult Sema::ActOnOpenMPParallelDirective(ArrayRef<OMPClause *> Clauses,
2722 SourceLocation StartLoc,
2723 SourceLocation EndLoc) {
2727 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
2728 // 1.2.2 OpenMP Language Terminology
2729 // Structured block - An executable statement with a single entry at the
2730 // top and a single exit at the bottom.
2731 // The point of exit cannot be a branch out of the structured block.
2732 // longjmp() and throw() must not violate the entry/exit criteria.
2733 CS->getCapturedDecl()->setNothrow();
2735 getCurFunction()->setHasBranchProtectedScope();
2737 return OMPParallelDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt,
2738 DSAStack->isCancelRegion());
2742 /// \brief Helper class for checking canonical form of the OpenMP loops and
2743 /// extracting iteration space of each loop in the loop nest, that will be used
2744 /// for IR generation.
2745 class OpenMPIterationSpaceChecker {
2746 /// \brief Reference to Sema.
2748 /// \brief A location for diagnostics (when there is no some better location).
2749 SourceLocation DefaultLoc;
2750 /// \brief A location for diagnostics (when increment is not compatible).
2751 SourceLocation ConditionLoc;
2752 /// \brief A source location for referring to loop init later.
2753 SourceRange InitSrcRange;
2754 /// \brief A source location for referring to condition later.
2755 SourceRange ConditionSrcRange;
2756 /// \brief A source location for referring to increment later.
2757 SourceRange IncrementSrcRange;
2758 /// \brief Loop variable.
2759 ValueDecl *LCDecl = nullptr;
2760 /// \brief Reference to loop variable.
2761 Expr *LCRef = nullptr;
2762 /// \brief Lower bound (initializer for the var).
2764 /// \brief Upper bound.
2766 /// \brief Loop step (increment).
2767 Expr *Step = nullptr;
2768 /// \brief This flag is true when condition is one of:
2773 bool TestIsLessOp = false;
2774 /// \brief This flag is true when condition is strict ( < or > ).
2775 bool TestIsStrictOp = false;
2776 /// \brief This flag is true when step is subtracted on each iteration.
2777 bool SubtractStep = false;
2780 OpenMPIterationSpaceChecker(Sema &SemaRef, SourceLocation DefaultLoc)
2781 : SemaRef(SemaRef), DefaultLoc(DefaultLoc), ConditionLoc(DefaultLoc) {}
2782 /// \brief Check init-expr for canonical loop form and save loop counter
2783 /// variable - #Var and its initialization value - #LB.
2784 bool CheckInit(Stmt *S, bool EmitDiags = true);
2785 /// \brief Check test-expr for canonical form, save upper-bound (#UB), flags
2786 /// for less/greater and for strict/non-strict comparison.
2787 bool CheckCond(Expr *S);
2788 /// \brief Check incr-expr for canonical loop form and return true if it
2789 /// does not conform, otherwise save loop step (#Step).
2790 bool CheckInc(Expr *S);
2791 /// \brief Return the loop counter variable.
2792 ValueDecl *GetLoopDecl() const { return LCDecl; }
2793 /// \brief Return the reference expression to loop counter variable.
2794 Expr *GetLoopDeclRefExpr() const { return LCRef; }
2795 /// \brief Source range of the loop init.
2796 SourceRange GetInitSrcRange() const { return InitSrcRange; }
2797 /// \brief Source range of the loop condition.
2798 SourceRange GetConditionSrcRange() const { return ConditionSrcRange; }
2799 /// \brief Source range of the loop increment.
2800 SourceRange GetIncrementSrcRange() const { return IncrementSrcRange; }
2801 /// \brief True if the step should be subtracted.
2802 bool ShouldSubtractStep() const { return SubtractStep; }
2803 /// \brief Build the expression to calculate the number of iterations.
2805 BuildNumIterations(Scope *S, const bool LimitedType,
2806 llvm::MapVector<Expr *, DeclRefExpr *> &Captures) const;
2807 /// \brief Build the precondition expression for the loops.
2808 Expr *BuildPreCond(Scope *S, Expr *Cond,
2809 llvm::MapVector<Expr *, DeclRefExpr *> &Captures) const;
2810 /// \brief Build reference expression to the counter be used for codegen.
2811 DeclRefExpr *BuildCounterVar(llvm::MapVector<Expr *, DeclRefExpr *> &Captures,
2812 DSAStackTy &DSA) const;
2813 /// \brief Build reference expression to the private counter be used for
2815 Expr *BuildPrivateCounterVar() const;
2816 /// \brief Build initialization of the counter be used for codegen.
2817 Expr *BuildCounterInit() const;
2818 /// \brief Build step of the counter be used for codegen.
2819 Expr *BuildCounterStep() const;
2820 /// \brief Return true if any expression is dependent.
2821 bool Dependent() const;
2824 /// \brief Check the right-hand side of an assignment in the increment
2826 bool CheckIncRHS(Expr *RHS);
2827 /// \brief Helper to set loop counter variable and its initializer.
2828 bool SetLCDeclAndLB(ValueDecl *NewLCDecl, Expr *NewDeclRefExpr, Expr *NewLB);
2829 /// \brief Helper to set upper bound.
2830 bool SetUB(Expr *NewUB, bool LessOp, bool StrictOp, SourceRange SR,
2832 /// \brief Helper to set loop increment.
2833 bool SetStep(Expr *NewStep, bool Subtract);
2836 bool OpenMPIterationSpaceChecker::Dependent() const {
2838 assert(!LB && !UB && !Step);
2841 return LCDecl->getType()->isDependentType() ||
2842 (LB && LB->isValueDependent()) || (UB && UB->isValueDependent()) ||
2843 (Step && Step->isValueDependent());
2846 static Expr *getExprAsWritten(Expr *E) {
2847 if (auto *ExprTemp = dyn_cast<ExprWithCleanups>(E))
2848 E = ExprTemp->getSubExpr();
2850 if (auto *MTE = dyn_cast<MaterializeTemporaryExpr>(E))
2851 E = MTE->GetTemporaryExpr();
2853 while (auto *Binder = dyn_cast<CXXBindTemporaryExpr>(E))
2854 E = Binder->getSubExpr();
2856 if (auto *ICE = dyn_cast<ImplicitCastExpr>(E))
2857 E = ICE->getSubExprAsWritten();
2858 return E->IgnoreParens();
2861 bool OpenMPIterationSpaceChecker::SetLCDeclAndLB(ValueDecl *NewLCDecl,
2864 // State consistency checking to ensure correct usage.
2865 assert(LCDecl == nullptr && LB == nullptr && LCRef == nullptr &&
2866 UB == nullptr && Step == nullptr && !TestIsLessOp && !TestIsStrictOp);
2867 if (!NewLCDecl || !NewLB)
2869 LCDecl = getCanonicalDecl(NewLCDecl);
2870 LCRef = NewLCRefExpr;
2871 if (auto *CE = dyn_cast_or_null<CXXConstructExpr>(NewLB))
2872 if (const CXXConstructorDecl *Ctor = CE->getConstructor())
2873 if ((Ctor->isCopyOrMoveConstructor() ||
2874 Ctor->isConvertingConstructor(/*AllowExplicit=*/false)) &&
2875 CE->getNumArgs() > 0 && CE->getArg(0) != nullptr)
2876 NewLB = CE->getArg(0)->IgnoreParenImpCasts();
2881 bool OpenMPIterationSpaceChecker::SetUB(Expr *NewUB, bool LessOp, bool StrictOp,
2882 SourceRange SR, SourceLocation SL) {
2883 // State consistency checking to ensure correct usage.
2884 assert(LCDecl != nullptr && LB != nullptr && UB == nullptr &&
2885 Step == nullptr && !TestIsLessOp && !TestIsStrictOp);
2889 TestIsLessOp = LessOp;
2890 TestIsStrictOp = StrictOp;
2891 ConditionSrcRange = SR;
2896 bool OpenMPIterationSpaceChecker::SetStep(Expr *NewStep, bool Subtract) {
2897 // State consistency checking to ensure correct usage.
2898 assert(LCDecl != nullptr && LB != nullptr && Step == nullptr);
2901 if (!NewStep->isValueDependent()) {
2902 // Check that the step is integer expression.
2903 SourceLocation StepLoc = NewStep->getLocStart();
2905 SemaRef.PerformOpenMPImplicitIntegerConversion(StepLoc, NewStep);
2906 if (Val.isInvalid())
2908 NewStep = Val.get();
2910 // OpenMP [2.6, Canonical Loop Form, Restrictions]
2911 // If test-expr is of form var relational-op b and relational-op is < or
2912 // <= then incr-expr must cause var to increase on each iteration of the
2913 // loop. If test-expr is of form var relational-op b and relational-op is
2914 // > or >= then incr-expr must cause var to decrease on each iteration of
2916 // If test-expr is of form b relational-op var and relational-op is < or
2917 // <= then incr-expr must cause var to decrease on each iteration of the
2918 // loop. If test-expr is of form b relational-op var and relational-op is
2919 // > or >= then incr-expr must cause var to increase on each iteration of
2921 llvm::APSInt Result;
2922 bool IsConstant = NewStep->isIntegerConstantExpr(Result, SemaRef.Context);
2923 bool IsUnsigned = !NewStep->getType()->hasSignedIntegerRepresentation();
2925 IsConstant && Result.isSigned() && (Subtract != Result.isNegative());
2927 IsConstant && Result.isSigned() && (Subtract == Result.isNegative());
2928 bool IsConstZero = IsConstant && !Result.getBoolValue();
2929 if (UB && (IsConstZero ||
2930 (TestIsLessOp ? (IsConstNeg || (IsUnsigned && Subtract))
2931 : (IsConstPos || (IsUnsigned && !Subtract))))) {
2932 SemaRef.Diag(NewStep->getExprLoc(),
2933 diag::err_omp_loop_incr_not_compatible)
2934 << LCDecl << TestIsLessOp << NewStep->getSourceRange();
2935 SemaRef.Diag(ConditionLoc,
2936 diag::note_omp_loop_cond_requres_compatible_incr)
2937 << TestIsLessOp << ConditionSrcRange;
2940 if (TestIsLessOp == Subtract) {
2942 SemaRef.CreateBuiltinUnaryOp(NewStep->getExprLoc(), UO_Minus, NewStep)
2944 Subtract = !Subtract;
2949 SubtractStep = Subtract;
2953 bool OpenMPIterationSpaceChecker::CheckInit(Stmt *S, bool EmitDiags) {
2954 // Check init-expr for canonical loop form and save loop counter
2955 // variable - #Var and its initialization value - #LB.
2956 // OpenMP [2.6] Canonical loop form. init-expr may be one of the following:
2958 // integer-type var = lb
2959 // random-access-iterator-type var = lb
2960 // pointer-type var = lb
2964 SemaRef.Diag(DefaultLoc, diag::err_omp_loop_not_canonical_init);
2968 if (auto *ExprTemp = dyn_cast<ExprWithCleanups>(S))
2969 if (!ExprTemp->cleanupsHaveSideEffects())
2970 S = ExprTemp->getSubExpr();
2972 InitSrcRange = S->getSourceRange();
2973 if (Expr *E = dyn_cast<Expr>(S))
2974 S = E->IgnoreParens();
2975 if (auto *BO = dyn_cast<BinaryOperator>(S)) {
2976 if (BO->getOpcode() == BO_Assign) {
2977 auto *LHS = BO->getLHS()->IgnoreParens();
2978 if (auto *DRE = dyn_cast<DeclRefExpr>(LHS)) {
2979 if (auto *CED = dyn_cast<OMPCapturedExprDecl>(DRE->getDecl()))
2980 if (auto *ME = dyn_cast<MemberExpr>(getExprAsWritten(CED->getInit())))
2981 return SetLCDeclAndLB(ME->getMemberDecl(), ME, BO->getRHS());
2982 return SetLCDeclAndLB(DRE->getDecl(), DRE, BO->getRHS());
2984 if (auto *ME = dyn_cast<MemberExpr>(LHS)) {
2985 if (ME->isArrow() &&
2986 isa<CXXThisExpr>(ME->getBase()->IgnoreParenImpCasts()))
2987 return SetLCDeclAndLB(ME->getMemberDecl(), ME, BO->getRHS());
2990 } else if (auto *DS = dyn_cast<DeclStmt>(S)) {
2991 if (DS->isSingleDecl()) {
2992 if (auto *Var = dyn_cast_or_null<VarDecl>(DS->getSingleDecl())) {
2993 if (Var->hasInit() && !Var->getType()->isReferenceType()) {
2994 // Accept non-canonical init form here but emit ext. warning.
2995 if (Var->getInitStyle() != VarDecl::CInit && EmitDiags)
2996 SemaRef.Diag(S->getLocStart(),
2997 diag::ext_omp_loop_not_canonical_init)
2998 << S->getSourceRange();
2999 return SetLCDeclAndLB(Var, nullptr, Var->getInit());
3003 } else if (auto *CE = dyn_cast<CXXOperatorCallExpr>(S)) {
3004 if (CE->getOperator() == OO_Equal) {
3005 auto *LHS = CE->getArg(0);
3006 if (auto *DRE = dyn_cast<DeclRefExpr>(LHS)) {
3007 if (auto *CED = dyn_cast<OMPCapturedExprDecl>(DRE->getDecl()))
3008 if (auto *ME = dyn_cast<MemberExpr>(getExprAsWritten(CED->getInit())))
3009 return SetLCDeclAndLB(ME->getMemberDecl(), ME, BO->getRHS());
3010 return SetLCDeclAndLB(DRE->getDecl(), DRE, CE->getArg(1));
3012 if (auto *ME = dyn_cast<MemberExpr>(LHS)) {
3013 if (ME->isArrow() &&
3014 isa<CXXThisExpr>(ME->getBase()->IgnoreParenImpCasts()))
3015 return SetLCDeclAndLB(ME->getMemberDecl(), ME, BO->getRHS());
3020 if (Dependent() || SemaRef.CurContext->isDependentContext())
3023 SemaRef.Diag(S->getLocStart(), diag::err_omp_loop_not_canonical_init)
3024 << S->getSourceRange();
3029 /// \brief Ignore parenthesizes, implicit casts, copy constructor and return the
3030 /// variable (which may be the loop variable) if possible.
3031 static const ValueDecl *GetInitLCDecl(Expr *E) {
3034 E = getExprAsWritten(E);
3035 if (auto *CE = dyn_cast_or_null<CXXConstructExpr>(E))
3036 if (const CXXConstructorDecl *Ctor = CE->getConstructor())
3037 if ((Ctor->isCopyOrMoveConstructor() ||
3038 Ctor->isConvertingConstructor(/*AllowExplicit=*/false)) &&
3039 CE->getNumArgs() > 0 && CE->getArg(0) != nullptr)
3040 E = CE->getArg(0)->IgnoreParenImpCasts();
3041 if (auto *DRE = dyn_cast_or_null<DeclRefExpr>(E)) {
3042 if (auto *VD = dyn_cast<VarDecl>(DRE->getDecl())) {
3043 if (auto *CED = dyn_cast<OMPCapturedExprDecl>(VD))
3044 if (auto *ME = dyn_cast<MemberExpr>(getExprAsWritten(CED->getInit())))
3045 return getCanonicalDecl(ME->getMemberDecl());
3046 return getCanonicalDecl(VD);
3049 if (auto *ME = dyn_cast_or_null<MemberExpr>(E))
3050 if (ME->isArrow() && isa<CXXThisExpr>(ME->getBase()->IgnoreParenImpCasts()))
3051 return getCanonicalDecl(ME->getMemberDecl());
3055 bool OpenMPIterationSpaceChecker::CheckCond(Expr *S) {
3056 // Check test-expr for canonical form, save upper-bound UB, flags for
3057 // less/greater and for strict/non-strict comparison.
3058 // OpenMP [2.6] Canonical loop form. Test-expr may be one of the following:
3059 // var relational-op b
3060 // b relational-op var
3063 SemaRef.Diag(DefaultLoc, diag::err_omp_loop_not_canonical_cond) << LCDecl;
3066 S = getExprAsWritten(S);
3067 SourceLocation CondLoc = S->getLocStart();
3068 if (auto *BO = dyn_cast<BinaryOperator>(S)) {
3069 if (BO->isRelationalOp()) {
3070 if (GetInitLCDecl(BO->getLHS()) == LCDecl)
3071 return SetUB(BO->getRHS(),
3072 (BO->getOpcode() == BO_LT || BO->getOpcode() == BO_LE),
3073 (BO->getOpcode() == BO_LT || BO->getOpcode() == BO_GT),
3074 BO->getSourceRange(), BO->getOperatorLoc());
3075 if (GetInitLCDecl(BO->getRHS()) == LCDecl)
3076 return SetUB(BO->getLHS(),
3077 (BO->getOpcode() == BO_GT || BO->getOpcode() == BO_GE),
3078 (BO->getOpcode() == BO_LT || BO->getOpcode() == BO_GT),
3079 BO->getSourceRange(), BO->getOperatorLoc());
3081 } else if (auto *CE = dyn_cast<CXXOperatorCallExpr>(S)) {
3082 if (CE->getNumArgs() == 2) {
3083 auto Op = CE->getOperator();
3086 case OO_GreaterEqual:
3089 if (GetInitLCDecl(CE->getArg(0)) == LCDecl)
3090 return SetUB(CE->getArg(1), Op == OO_Less || Op == OO_LessEqual,
3091 Op == OO_Less || Op == OO_Greater, CE->getSourceRange(),
3092 CE->getOperatorLoc());
3093 if (GetInitLCDecl(CE->getArg(1)) == LCDecl)
3094 return SetUB(CE->getArg(0), Op == OO_Greater || Op == OO_GreaterEqual,
3095 Op == OO_Less || Op == OO_Greater, CE->getSourceRange(),
3096 CE->getOperatorLoc());
3103 if (Dependent() || SemaRef.CurContext->isDependentContext())
3105 SemaRef.Diag(CondLoc, diag::err_omp_loop_not_canonical_cond)
3106 << S->getSourceRange() << LCDecl;
3110 bool OpenMPIterationSpaceChecker::CheckIncRHS(Expr *RHS) {
3111 // RHS of canonical loop form increment can be:
3116 RHS = RHS->IgnoreParenImpCasts();
3117 if (auto *BO = dyn_cast<BinaryOperator>(RHS)) {
3118 if (BO->isAdditiveOp()) {
3119 bool IsAdd = BO->getOpcode() == BO_Add;
3120 if (GetInitLCDecl(BO->getLHS()) == LCDecl)
3121 return SetStep(BO->getRHS(), !IsAdd);
3122 if (IsAdd && GetInitLCDecl(BO->getRHS()) == LCDecl)
3123 return SetStep(BO->getLHS(), false);
3125 } else if (auto *CE = dyn_cast<CXXOperatorCallExpr>(RHS)) {
3126 bool IsAdd = CE->getOperator() == OO_Plus;
3127 if ((IsAdd || CE->getOperator() == OO_Minus) && CE->getNumArgs() == 2) {
3128 if (GetInitLCDecl(CE->getArg(0)) == LCDecl)
3129 return SetStep(CE->getArg(1), !IsAdd);
3130 if (IsAdd && GetInitLCDecl(CE->getArg(1)) == LCDecl)
3131 return SetStep(CE->getArg(0), false);
3134 if (Dependent() || SemaRef.CurContext->isDependentContext())
3136 SemaRef.Diag(RHS->getLocStart(), diag::err_omp_loop_not_canonical_incr)
3137 << RHS->getSourceRange() << LCDecl;
3141 bool OpenMPIterationSpaceChecker::CheckInc(Expr *S) {
3142 // Check incr-expr for canonical loop form and return true if it
3143 // does not conform.
3144 // OpenMP [2.6] Canonical loop form. Test-expr may be one of the following:
3156 SemaRef.Diag(DefaultLoc, diag::err_omp_loop_not_canonical_incr) << LCDecl;
3159 if (auto *ExprTemp = dyn_cast<ExprWithCleanups>(S))
3160 if (!ExprTemp->cleanupsHaveSideEffects())
3161 S = ExprTemp->getSubExpr();
3163 IncrementSrcRange = S->getSourceRange();
3164 S = S->IgnoreParens();
3165 if (auto *UO = dyn_cast<UnaryOperator>(S)) {
3166 if (UO->isIncrementDecrementOp() &&
3167 GetInitLCDecl(UO->getSubExpr()) == LCDecl)
3168 return SetStep(SemaRef
3169 .ActOnIntegerConstant(UO->getLocStart(),
3170 (UO->isDecrementOp() ? -1 : 1))
3173 } else if (auto *BO = dyn_cast<BinaryOperator>(S)) {
3174 switch (BO->getOpcode()) {
3177 if (GetInitLCDecl(BO->getLHS()) == LCDecl)
3178 return SetStep(BO->getRHS(), BO->getOpcode() == BO_SubAssign);
3181 if (GetInitLCDecl(BO->getLHS()) == LCDecl)
3182 return CheckIncRHS(BO->getRHS());
3187 } else if (auto *CE = dyn_cast<CXXOperatorCallExpr>(S)) {
3188 switch (CE->getOperator()) {
3191 if (GetInitLCDecl(CE->getArg(0)) == LCDecl)
3192 return SetStep(SemaRef
3193 .ActOnIntegerConstant(
3195 ((CE->getOperator() == OO_MinusMinus) ? -1 : 1))
3201 if (GetInitLCDecl(CE->getArg(0)) == LCDecl)
3202 return SetStep(CE->getArg(1), CE->getOperator() == OO_MinusEqual);
3205 if (GetInitLCDecl(CE->getArg(0)) == LCDecl)
3206 return CheckIncRHS(CE->getArg(1));
3212 if (Dependent() || SemaRef.CurContext->isDependentContext())
3214 SemaRef.Diag(S->getLocStart(), diag::err_omp_loop_not_canonical_incr)
3215 << S->getSourceRange() << LCDecl;
3220 tryBuildCapture(Sema &SemaRef, Expr *Capture,
3221 llvm::MapVector<Expr *, DeclRefExpr *> &Captures) {
3222 if (SemaRef.CurContext->isDependentContext())
3223 return ExprResult(Capture);
3224 if (Capture->isEvaluatable(SemaRef.Context, Expr::SE_AllowSideEffects))
3225 return SemaRef.PerformImplicitConversion(
3226 Capture->IgnoreImpCasts(), Capture->getType(), Sema::AA_Converting,
3227 /*AllowExplicit=*/true);
3228 auto I = Captures.find(Capture);
3229 if (I != Captures.end())
3230 return buildCapture(SemaRef, Capture, I->second);
3231 DeclRefExpr *Ref = nullptr;
3232 ExprResult Res = buildCapture(SemaRef, Capture, Ref);
3233 Captures[Capture] = Ref;
3237 /// \brief Build the expression to calculate the number of iterations.
3238 Expr *OpenMPIterationSpaceChecker::BuildNumIterations(
3239 Scope *S, const bool LimitedType,
3240 llvm::MapVector<Expr *, DeclRefExpr *> &Captures) const {
3242 auto VarType = LCDecl->getType().getNonReferenceType();
3243 if (VarType->isIntegerType() || VarType->isPointerType() ||
3244 SemaRef.getLangOpts().CPlusPlus) {
3246 auto *UBExpr = TestIsLessOp ? UB : LB;
3247 auto *LBExpr = TestIsLessOp ? LB : UB;
3248 Expr *Upper = tryBuildCapture(SemaRef, UBExpr, Captures).get();
3249 Expr *Lower = tryBuildCapture(SemaRef, LBExpr, Captures).get();
3250 if (!Upper || !Lower)
3253 Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Sub, Upper, Lower);
3255 if (!Diff.isUsable() && VarType->getAsCXXRecordDecl()) {
3256 // BuildBinOp already emitted error, this one is to point user to upper
3257 // and lower bound, and to tell what is passed to 'operator-'.
3258 SemaRef.Diag(Upper->getLocStart(), diag::err_omp_loop_diff_cxx)
3259 << Upper->getSourceRange() << Lower->getSourceRange();
3264 if (!Diff.isUsable())
3267 // Upper - Lower [- 1]
3269 Diff = SemaRef.BuildBinOp(
3270 S, DefaultLoc, BO_Sub, Diff.get(),
3271 SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get());
3272 if (!Diff.isUsable())
3275 // Upper - Lower [- 1] + Step
3276 auto NewStep = tryBuildCapture(SemaRef, Step, Captures);
3277 if (!NewStep.isUsable())
3279 Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Add, Diff.get(), NewStep.get());
3280 if (!Diff.isUsable())
3283 // Parentheses (for dumping/debugging purposes only).
3284 Diff = SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, Diff.get());
3285 if (!Diff.isUsable())
3288 // (Upper - Lower [- 1] + Step) / Step
3289 Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Div, Diff.get(), NewStep.get());
3290 if (!Diff.isUsable())
3293 // OpenMP runtime requires 32-bit or 64-bit loop variables.
3294 QualType Type = Diff.get()->getType();
3295 auto &C = SemaRef.Context;
3296 bool UseVarType = VarType->hasIntegerRepresentation() &&
3297 C.getTypeSize(Type) > C.getTypeSize(VarType);
3298 if (!Type->isIntegerType() || UseVarType) {
3300 UseVarType ? C.getTypeSize(VarType) : C.getTypeSize(Type);
3301 bool IsSigned = UseVarType ? VarType->hasSignedIntegerRepresentation()
3302 : Type->hasSignedIntegerRepresentation();
3303 Type = C.getIntTypeForBitwidth(NewSize, IsSigned);
3304 if (!SemaRef.Context.hasSameType(Diff.get()->getType(), Type)) {
3305 Diff = SemaRef.PerformImplicitConversion(
3306 Diff.get(), Type, Sema::AA_Converting, /*AllowExplicit=*/true);
3307 if (!Diff.isUsable())
3312 unsigned NewSize = (C.getTypeSize(Type) > 32) ? 64 : 32;
3313 if (NewSize != C.getTypeSize(Type)) {
3314 if (NewSize < C.getTypeSize(Type)) {
3315 assert(NewSize == 64 && "incorrect loop var size");
3316 SemaRef.Diag(DefaultLoc, diag::warn_omp_loop_64_bit_var)
3317 << InitSrcRange << ConditionSrcRange;
3319 QualType NewType = C.getIntTypeForBitwidth(
3320 NewSize, Type->hasSignedIntegerRepresentation() ||
3321 C.getTypeSize(Type) < NewSize);
3322 if (!SemaRef.Context.hasSameType(Diff.get()->getType(), NewType)) {
3323 Diff = SemaRef.PerformImplicitConversion(Diff.get(), NewType,
3324 Sema::AA_Converting, true);
3325 if (!Diff.isUsable())
3334 Expr *OpenMPIterationSpaceChecker::BuildPreCond(
3335 Scope *S, Expr *Cond,
3336 llvm::MapVector<Expr *, DeclRefExpr *> &Captures) const {
3337 // Try to build LB <op> UB, where <op> is <, >, <=, or >=.
3338 bool Suppress = SemaRef.getDiagnostics().getSuppressAllDiagnostics();
3339 SemaRef.getDiagnostics().setSuppressAllDiagnostics(/*Val=*/true);
3341 auto NewLB = tryBuildCapture(SemaRef, LB, Captures);
3342 auto NewUB = tryBuildCapture(SemaRef, UB, Captures);
3343 if (!NewLB.isUsable() || !NewUB.isUsable())
3346 auto CondExpr = SemaRef.BuildBinOp(
3347 S, DefaultLoc, TestIsLessOp ? (TestIsStrictOp ? BO_LT : BO_LE)
3348 : (TestIsStrictOp ? BO_GT : BO_GE),
3349 NewLB.get(), NewUB.get());
3350 if (CondExpr.isUsable()) {
3351 if (!SemaRef.Context.hasSameUnqualifiedType(CondExpr.get()->getType(),
3352 SemaRef.Context.BoolTy))
3353 CondExpr = SemaRef.PerformImplicitConversion(
3354 CondExpr.get(), SemaRef.Context.BoolTy, /*Action=*/Sema::AA_Casting,
3355 /*AllowExplicit=*/true);
3357 SemaRef.getDiagnostics().setSuppressAllDiagnostics(Suppress);
3358 // Otherwise use original loop conditon and evaluate it in runtime.
3359 return CondExpr.isUsable() ? CondExpr.get() : Cond;
3362 /// \brief Build reference expression to the counter be used for codegen.
3363 DeclRefExpr *OpenMPIterationSpaceChecker::BuildCounterVar(
3364 llvm::MapVector<Expr *, DeclRefExpr *> &Captures, DSAStackTy &DSA) const {
3365 auto *VD = dyn_cast<VarDecl>(LCDecl);
3367 VD = SemaRef.IsOpenMPCapturedDecl(LCDecl);
3368 auto *Ref = buildDeclRefExpr(
3369 SemaRef, VD, VD->getType().getNonReferenceType(), DefaultLoc);
3370 DSAStackTy::DSAVarData Data = DSA.getTopDSA(LCDecl, /*FromParent=*/false);
3371 // If the loop control decl is explicitly marked as private, do not mark it
3372 // as captured again.
3373 if (!isOpenMPPrivate(Data.CKind) || !Data.RefExpr)
3374 Captures.insert(std::make_pair(LCRef, Ref));
3377 return buildDeclRefExpr(SemaRef, VD, VD->getType().getNonReferenceType(),
3381 Expr *OpenMPIterationSpaceChecker::BuildPrivateCounterVar() const {
3382 if (LCDecl && !LCDecl->isInvalidDecl()) {
3383 auto Type = LCDecl->getType().getNonReferenceType();
3385 buildVarDecl(SemaRef, DefaultLoc, Type, LCDecl->getName(),
3386 LCDecl->hasAttrs() ? &LCDecl->getAttrs() : nullptr);
3387 if (PrivateVar->isInvalidDecl())
3389 return buildDeclRefExpr(SemaRef, PrivateVar, Type, DefaultLoc);
3394 /// \brief Build initialization of the counter to be used for codegen.
3395 Expr *OpenMPIterationSpaceChecker::BuildCounterInit() const { return LB; }
3397 /// \brief Build step of the counter be used for codegen.
3398 Expr *OpenMPIterationSpaceChecker::BuildCounterStep() const { return Step; }
3400 /// \brief Iteration space of a single for loop.
3401 struct LoopIterationSpace final {
3402 /// \brief Condition of the loop.
3403 Expr *PreCond = nullptr;
3404 /// \brief This expression calculates the number of iterations in the loop.
3405 /// It is always possible to calculate it before starting the loop.
3406 Expr *NumIterations = nullptr;
3407 /// \brief The loop counter variable.
3408 Expr *CounterVar = nullptr;
3409 /// \brief Private loop counter variable.
3410 Expr *PrivateCounterVar = nullptr;
3411 /// \brief This is initializer for the initial value of #CounterVar.
3412 Expr *CounterInit = nullptr;
3413 /// \brief This is step for the #CounterVar used to generate its update:
3414 /// #CounterVar = #CounterInit + #CounterStep * CurrentIteration.
3415 Expr *CounterStep = nullptr;
3416 /// \brief Should step be subtracted?
3417 bool Subtract = false;
3418 /// \brief Source range of the loop init.
3419 SourceRange InitSrcRange;
3420 /// \brief Source range of the loop condition.
3421 SourceRange CondSrcRange;
3422 /// \brief Source range of the loop increment.
3423 SourceRange IncSrcRange;
3428 void Sema::ActOnOpenMPLoopInitialization(SourceLocation ForLoc, Stmt *Init) {
3429 assert(getLangOpts().OpenMP && "OpenMP is not active.");
3430 assert(Init && "Expected loop in canonical form.");
3431 unsigned AssociatedLoops = DSAStack->getAssociatedLoops();
3432 if (AssociatedLoops > 0 &&
3433 isOpenMPLoopDirective(DSAStack->getCurrentDirective())) {
3434 OpenMPIterationSpaceChecker ISC(*this, ForLoc);
3435 if (!ISC.CheckInit(Init, /*EmitDiags=*/false)) {
3436 if (auto *D = ISC.GetLoopDecl()) {
3437 auto *VD = dyn_cast<VarDecl>(D);
3439 if (auto *Private = IsOpenMPCapturedDecl(D))
3442 auto *Ref = buildCapture(*this, D, ISC.GetLoopDeclRefExpr(),
3443 /*WithInit=*/false);
3444 VD = cast<VarDecl>(Ref->getDecl());
3447 DSAStack->addLoopControlVariable(D, VD);
3450 DSAStack->setAssociatedLoops(AssociatedLoops - 1);
3454 /// \brief Called on a for stmt to check and extract its iteration space
3455 /// for further processing (such as collapsing).
3456 static bool CheckOpenMPIterationSpace(
3457 OpenMPDirectiveKind DKind, Stmt *S, Sema &SemaRef, DSAStackTy &DSA,
3458 unsigned CurrentNestedLoopCount, unsigned NestedLoopCount,
3459 Expr *CollapseLoopCountExpr, Expr *OrderedLoopCountExpr,
3460 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA,
3461 LoopIterationSpace &ResultIterSpace,
3462 llvm::MapVector<Expr *, DeclRefExpr *> &Captures) {
3463 // OpenMP [2.6, Canonical Loop Form]
3464 // for (init-expr; test-expr; incr-expr) structured-block
3465 auto *For = dyn_cast_or_null<ForStmt>(S);
3467 SemaRef.Diag(S->getLocStart(), diag::err_omp_not_for)
3468 << (CollapseLoopCountExpr != nullptr || OrderedLoopCountExpr != nullptr)
3469 << getOpenMPDirectiveName(DKind) << NestedLoopCount
3470 << (CurrentNestedLoopCount > 0) << CurrentNestedLoopCount;
3471 if (NestedLoopCount > 1) {
3472 if (CollapseLoopCountExpr && OrderedLoopCountExpr)
3473 SemaRef.Diag(DSA.getConstructLoc(),
3474 diag::note_omp_collapse_ordered_expr)
3475 << 2 << CollapseLoopCountExpr->getSourceRange()
3476 << OrderedLoopCountExpr->getSourceRange();
3477 else if (CollapseLoopCountExpr)
3478 SemaRef.Diag(CollapseLoopCountExpr->getExprLoc(),
3479 diag::note_omp_collapse_ordered_expr)
3480 << 0 << CollapseLoopCountExpr->getSourceRange();
3482 SemaRef.Diag(OrderedLoopCountExpr->getExprLoc(),
3483 diag::note_omp_collapse_ordered_expr)
3484 << 1 << OrderedLoopCountExpr->getSourceRange();
3488 assert(For->getBody());
3490 OpenMPIterationSpaceChecker ISC(SemaRef, For->getForLoc());
3493 auto Init = For->getInit();
3494 if (ISC.CheckInit(Init))
3497 bool HasErrors = false;
3499 // Check loop variable's type.
3500 if (auto *LCDecl = ISC.GetLoopDecl()) {
3501 auto *LoopDeclRefExpr = ISC.GetLoopDeclRefExpr();
3503 // OpenMP [2.6, Canonical Loop Form]
3504 // Var is one of the following:
3505 // A variable of signed or unsigned integer type.
3506 // For C++, a variable of a random access iterator type.
3507 // For C, a variable of a pointer type.
3508 auto VarType = LCDecl->getType().getNonReferenceType();
3509 if (!VarType->isDependentType() && !VarType->isIntegerType() &&
3510 !VarType->isPointerType() &&
3511 !(SemaRef.getLangOpts().CPlusPlus && VarType->isOverloadableType())) {
3512 SemaRef.Diag(Init->getLocStart(), diag::err_omp_loop_variable_type)
3513 << SemaRef.getLangOpts().CPlusPlus;
3517 // OpenMP, 2.14.1.1 Data-sharing Attribute Rules for Variables Referenced in
3519 // The loop iteration variable(s) in the associated for-loop(s) of a for or
3520 // parallel for construct is (are) private.
3521 // The loop iteration variable in the associated for-loop of a simd
3522 // construct with just one associated for-loop is linear with a
3523 // constant-linear-step that is the increment of the associated for-loop.
3524 // Exclude loop var from the list of variables with implicitly defined data
3525 // sharing attributes.
3526 VarsWithImplicitDSA.erase(LCDecl);
3528 // OpenMP [2.14.1.1, Data-sharing Attribute Rules for Variables Referenced
3529 // in a Construct, C/C++].
3530 // The loop iteration variable in the associated for-loop of a simd
3531 // construct with just one associated for-loop may be listed in a linear
3532 // clause with a constant-linear-step that is the increment of the
3533 // associated for-loop.
3534 // The loop iteration variable(s) in the associated for-loop(s) of a for or
3535 // parallel for construct may be listed in a private or lastprivate clause.
3536 DSAStackTy::DSAVarData DVar = DSA.getTopDSA(LCDecl, false);
3537 // If LoopVarRefExpr is nullptr it means the corresponding loop variable is
3538 // declared in the loop and it is predetermined as a private.
3539 auto PredeterminedCKind =
3540 isOpenMPSimdDirective(DKind)
3541 ? ((NestedLoopCount == 1) ? OMPC_linear : OMPC_lastprivate)
3543 if (((isOpenMPSimdDirective(DKind) && DVar.CKind != OMPC_unknown &&
3544 DVar.CKind != PredeterminedCKind) ||
3545 ((isOpenMPWorksharingDirective(DKind) || DKind == OMPD_taskloop ||
3546 isOpenMPDistributeDirective(DKind)) &&
3547 !isOpenMPSimdDirective(DKind) && DVar.CKind != OMPC_unknown &&
3548 DVar.CKind != OMPC_private && DVar.CKind != OMPC_lastprivate)) &&
3549 (DVar.CKind != OMPC_private || DVar.RefExpr != nullptr)) {
3550 SemaRef.Diag(Init->getLocStart(), diag::err_omp_loop_var_dsa)
3551 << getOpenMPClauseName(DVar.CKind) << getOpenMPDirectiveName(DKind)
3552 << getOpenMPClauseName(PredeterminedCKind);
3553 if (DVar.RefExpr == nullptr)
3554 DVar.CKind = PredeterminedCKind;
3555 ReportOriginalDSA(SemaRef, &DSA, LCDecl, DVar, /*IsLoopIterVar=*/true);
3557 } else if (LoopDeclRefExpr != nullptr) {
3558 // Make the loop iteration variable private (for worksharing constructs),
3559 // linear (for simd directives with the only one associated loop) or
3560 // lastprivate (for simd directives with several collapsed or ordered
3562 if (DVar.CKind == OMPC_unknown)
3563 DVar = DSA.hasDSA(LCDecl, isOpenMPPrivate,
3564 [](OpenMPDirectiveKind) -> bool { return true; },
3565 /*FromParent=*/false);
3566 DSA.addDSA(LCDecl, LoopDeclRefExpr, PredeterminedCKind);
3569 assert(isOpenMPLoopDirective(DKind) && "DSA for non-loop vars");
3572 HasErrors |= ISC.CheckCond(For->getCond());
3575 HasErrors |= ISC.CheckInc(For->getInc());
3578 if (ISC.Dependent() || SemaRef.CurContext->isDependentContext() || HasErrors)
3581 // Build the loop's iteration space representation.
3582 ResultIterSpace.PreCond =
3583 ISC.BuildPreCond(DSA.getCurScope(), For->getCond(), Captures);
3584 ResultIterSpace.NumIterations = ISC.BuildNumIterations(
3586 (isOpenMPWorksharingDirective(DKind) ||
3587 isOpenMPTaskLoopDirective(DKind) || isOpenMPDistributeDirective(DKind)),
3589 ResultIterSpace.CounterVar = ISC.BuildCounterVar(Captures, DSA);
3590 ResultIterSpace.PrivateCounterVar = ISC.BuildPrivateCounterVar();
3591 ResultIterSpace.CounterInit = ISC.BuildCounterInit();
3592 ResultIterSpace.CounterStep = ISC.BuildCounterStep();
3593 ResultIterSpace.InitSrcRange = ISC.GetInitSrcRange();
3594 ResultIterSpace.CondSrcRange = ISC.GetConditionSrcRange();
3595 ResultIterSpace.IncSrcRange = ISC.GetIncrementSrcRange();
3596 ResultIterSpace.Subtract = ISC.ShouldSubtractStep();
3598 HasErrors |= (ResultIterSpace.PreCond == nullptr ||
3599 ResultIterSpace.NumIterations == nullptr ||
3600 ResultIterSpace.CounterVar == nullptr ||
3601 ResultIterSpace.PrivateCounterVar == nullptr ||
3602 ResultIterSpace.CounterInit == nullptr ||
3603 ResultIterSpace.CounterStep == nullptr);
3608 /// \brief Build 'VarRef = Start.
3610 BuildCounterInit(Sema &SemaRef, Scope *S, SourceLocation Loc, ExprResult VarRef,
3612 llvm::MapVector<Expr *, DeclRefExpr *> &Captures) {
3613 // Build 'VarRef = Start.
3614 auto NewStart = tryBuildCapture(SemaRef, Start.get(), Captures);
3615 if (!NewStart.isUsable())
3617 if (!SemaRef.Context.hasSameType(NewStart.get()->getType(),
3618 VarRef.get()->getType())) {
3619 NewStart = SemaRef.PerformImplicitConversion(
3620 NewStart.get(), VarRef.get()->getType(), Sema::AA_Converting,
3621 /*AllowExplicit=*/true);
3622 if (!NewStart.isUsable())
3627 SemaRef.BuildBinOp(S, Loc, BO_Assign, VarRef.get(), NewStart.get());
3631 /// \brief Build 'VarRef = Start + Iter * Step'.
3633 BuildCounterUpdate(Sema &SemaRef, Scope *S, SourceLocation Loc,
3634 ExprResult VarRef, ExprResult Start, ExprResult Iter,
3635 ExprResult Step, bool Subtract,
3636 llvm::MapVector<Expr *, DeclRefExpr *> *Captures = nullptr) {
3637 // Add parentheses (for debugging purposes only).
3638 Iter = SemaRef.ActOnParenExpr(Loc, Loc, Iter.get());
3639 if (!VarRef.isUsable() || !Start.isUsable() || !Iter.isUsable() ||
3643 ExprResult NewStep = Step;
3645 NewStep = tryBuildCapture(SemaRef, Step.get(), *Captures);
3646 if (NewStep.isInvalid())
3649 SemaRef.BuildBinOp(S, Loc, BO_Mul, Iter.get(), NewStep.get());
3650 if (!Update.isUsable())
3653 // Try to build 'VarRef = Start, VarRef (+|-)= Iter * Step' or
3654 // 'VarRef = Start (+|-) Iter * Step'.
3655 ExprResult NewStart = Start;
3657 NewStart = tryBuildCapture(SemaRef, Start.get(), *Captures);
3658 if (NewStart.isInvalid())
3661 // First attempt: try to build 'VarRef = Start, VarRef += Iter * Step'.
3662 ExprResult SavedUpdate = Update;
3663 ExprResult UpdateVal;
3664 if (VarRef.get()->getType()->isOverloadableType() ||
3665 NewStart.get()->getType()->isOverloadableType() ||
3666 Update.get()->getType()->isOverloadableType()) {
3667 bool Suppress = SemaRef.getDiagnostics().getSuppressAllDiagnostics();
3668 SemaRef.getDiagnostics().setSuppressAllDiagnostics(/*Val=*/true);
3670 SemaRef.BuildBinOp(S, Loc, BO_Assign, VarRef.get(), NewStart.get());
3671 if (Update.isUsable()) {
3673 SemaRef.BuildBinOp(S, Loc, Subtract ? BO_SubAssign : BO_AddAssign,
3674 VarRef.get(), SavedUpdate.get());
3675 if (UpdateVal.isUsable()) {
3676 Update = SemaRef.CreateBuiltinBinOp(Loc, BO_Comma, Update.get(),
3680 SemaRef.getDiagnostics().setSuppressAllDiagnostics(Suppress);
3683 // Second attempt: try to build 'VarRef = Start (+|-) Iter * Step'.
3684 if (!Update.isUsable() || !UpdateVal.isUsable()) {
3685 Update = SemaRef.BuildBinOp(S, Loc, Subtract ? BO_Sub : BO_Add,
3686 NewStart.get(), SavedUpdate.get());
3687 if (!Update.isUsable())
3690 if (!SemaRef.Context.hasSameType(Update.get()->getType(),
3691 VarRef.get()->getType())) {
3692 Update = SemaRef.PerformImplicitConversion(
3693 Update.get(), VarRef.get()->getType(), Sema::AA_Converting, true);
3694 if (!Update.isUsable())
3698 Update = SemaRef.BuildBinOp(S, Loc, BO_Assign, VarRef.get(), Update.get());
3703 /// \brief Convert integer expression \a E to make it have at least \a Bits
3705 static ExprResult WidenIterationCount(unsigned Bits, Expr *E, Sema &SemaRef) {
3708 auto &C = SemaRef.Context;
3709 QualType OldType = E->getType();
3710 unsigned HasBits = C.getTypeSize(OldType);
3711 if (HasBits >= Bits)
3712 return ExprResult(E);
3713 // OK to convert to signed, because new type has more bits than old.
3714 QualType NewType = C.getIntTypeForBitwidth(Bits, /* Signed */ true);
3715 return SemaRef.PerformImplicitConversion(E, NewType, Sema::AA_Converting,
3719 /// \brief Check if the given expression \a E is a constant integer that fits
3720 /// into \a Bits bits.
3721 static bool FitsInto(unsigned Bits, bool Signed, Expr *E, Sema &SemaRef) {
3724 llvm::APSInt Result;
3725 if (E->isIntegerConstantExpr(Result, SemaRef.Context))
3726 return Signed ? Result.isSignedIntN(Bits) : Result.isIntN(Bits);
3730 /// Build preinits statement for the given declarations.
3731 static Stmt *buildPreInits(ASTContext &Context,
3732 SmallVectorImpl<Decl *> &PreInits) {
3733 if (!PreInits.empty()) {
3734 return new (Context) DeclStmt(
3735 DeclGroupRef::Create(Context, PreInits.begin(), PreInits.size()),
3736 SourceLocation(), SourceLocation());
3741 /// Build preinits statement for the given declarations.
3742 static Stmt *buildPreInits(ASTContext &Context,
3743 llvm::MapVector<Expr *, DeclRefExpr *> &Captures) {
3744 if (!Captures.empty()) {
3745 SmallVector<Decl *, 16> PreInits;
3746 for (auto &Pair : Captures)
3747 PreInits.push_back(Pair.second->getDecl());
3748 return buildPreInits(Context, PreInits);
3753 /// Build postupdate expression for the given list of postupdates expressions.
3754 static Expr *buildPostUpdate(Sema &S, ArrayRef<Expr *> PostUpdates) {
3755 Expr *PostUpdate = nullptr;
3756 if (!PostUpdates.empty()) {
3757 for (auto *E : PostUpdates) {
3758 Expr *ConvE = S.BuildCStyleCastExpr(
3760 S.Context.getTrivialTypeSourceInfo(S.Context.VoidTy),
3763 PostUpdate = PostUpdate
3764 ? S.CreateBuiltinBinOp(ConvE->getExprLoc(), BO_Comma,
3773 /// \brief Called on a for stmt to check itself and nested loops (if any).
3774 /// \return Returns 0 if one of the collapsed stmts is not canonical for loop,
3775 /// number of collapsed loops otherwise.
3777 CheckOpenMPLoop(OpenMPDirectiveKind DKind, Expr *CollapseLoopCountExpr,
3778 Expr *OrderedLoopCountExpr, Stmt *AStmt, Sema &SemaRef,
3780 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA,
3781 OMPLoopDirective::HelperExprs &Built) {
3782 unsigned NestedLoopCount = 1;
3783 if (CollapseLoopCountExpr) {
3784 // Found 'collapse' clause - calculate collapse number.
3785 llvm::APSInt Result;
3786 if (CollapseLoopCountExpr->EvaluateAsInt(Result, SemaRef.getASTContext()))
3787 NestedLoopCount = Result.getLimitedValue();
3789 if (OrderedLoopCountExpr) {
3790 // Found 'ordered' clause - calculate collapse number.
3791 llvm::APSInt Result;
3792 if (OrderedLoopCountExpr->EvaluateAsInt(Result, SemaRef.getASTContext())) {
3793 if (Result.getLimitedValue() < NestedLoopCount) {
3794 SemaRef.Diag(OrderedLoopCountExpr->getExprLoc(),
3795 diag::err_omp_wrong_ordered_loop_count)
3796 << OrderedLoopCountExpr->getSourceRange();
3797 SemaRef.Diag(CollapseLoopCountExpr->getExprLoc(),
3798 diag::note_collapse_loop_count)
3799 << CollapseLoopCountExpr->getSourceRange();
3801 NestedLoopCount = Result.getLimitedValue();
3804 // This is helper routine for loop directives (e.g., 'for', 'simd',
3805 // 'for simd', etc.).
3806 llvm::MapVector<Expr *, DeclRefExpr *> Captures;
3807 SmallVector<LoopIterationSpace, 4> IterSpaces;
3808 IterSpaces.resize(NestedLoopCount);
3809 Stmt *CurStmt = AStmt->IgnoreContainers(/* IgnoreCaptured */ true);
3810 for (unsigned Cnt = 0; Cnt < NestedLoopCount; ++Cnt) {
3811 if (CheckOpenMPIterationSpace(DKind, CurStmt, SemaRef, DSA, Cnt,
3812 NestedLoopCount, CollapseLoopCountExpr,
3813 OrderedLoopCountExpr, VarsWithImplicitDSA,
3814 IterSpaces[Cnt], Captures))
3816 // Move on to the next nested for loop, or to the loop body.
3817 // OpenMP [2.8.1, simd construct, Restrictions]
3818 // All loops associated with the construct must be perfectly nested; that
3819 // is, there must be no intervening code nor any OpenMP directive between
3821 CurStmt = cast<ForStmt>(CurStmt)->getBody()->IgnoreContainers();
3824 Built.clear(/* size */ NestedLoopCount);
3826 if (SemaRef.CurContext->isDependentContext())
3827 return NestedLoopCount;
3829 // An example of what is generated for the following code:
3831 // #pragma omp simd collapse(2) ordered(2)
3832 // for (i = 0; i < NI; ++i)
3833 // for (k = 0; k < NK; ++k)
3834 // for (j = J0; j < NJ; j+=2) {
3838 // We generate the code below.
3839 // Note: the loop body may be outlined in CodeGen.
3840 // Note: some counters may be C++ classes, operator- is used to find number of
3841 // iterations and operator+= to calculate counter value.
3842 // Note: decltype(NumIterations) must be integer type (in 'omp for', only i32
3843 // or i64 is currently supported).
3845 // #define NumIterations (NI * ((NJ - J0 - 1 + 2) / 2))
3846 // for (int[32|64]_t IV = 0; IV < NumIterations; ++IV ) {
3847 // .local.i = IV / ((NJ - J0 - 1 + 2) / 2);
3848 // .local.j = J0 + (IV % ((NJ - J0 - 1 + 2) / 2)) * 2;
3849 // // similar updates for vars in clauses (e.g. 'linear')
3850 // <loop body (using local i and j)>
3852 // i = NI; // assign final values of counters
3856 // Last iteration number is (I1 * I2 * ... In) - 1, where I1, I2 ... In are
3857 // the iteration counts of the collapsed for loops.
3858 // Precondition tests if there is at least one iteration (all conditions are
3860 auto PreCond = ExprResult(IterSpaces[0].PreCond);
3861 auto N0 = IterSpaces[0].NumIterations;
3862 ExprResult LastIteration32 = WidenIterationCount(
3863 32 /* Bits */, SemaRef
3864 .PerformImplicitConversion(
3865 N0->IgnoreImpCasts(), N0->getType(),
3866 Sema::AA_Converting, /*AllowExplicit=*/true)
3869 ExprResult LastIteration64 = WidenIterationCount(
3870 64 /* Bits */, SemaRef
3871 .PerformImplicitConversion(
3872 N0->IgnoreImpCasts(), N0->getType(),
3873 Sema::AA_Converting, /*AllowExplicit=*/true)
3877 if (!LastIteration32.isUsable() || !LastIteration64.isUsable())
3878 return NestedLoopCount;
3880 auto &C = SemaRef.Context;
3881 bool AllCountsNeedLessThan32Bits = C.getTypeSize(N0->getType()) < 32;
3883 Scope *CurScope = DSA.getCurScope();
3884 for (unsigned Cnt = 1; Cnt < NestedLoopCount; ++Cnt) {
3885 if (PreCond.isUsable()) {
3887 SemaRef.BuildBinOp(CurScope, PreCond.get()->getExprLoc(), BO_LAnd,
3888 PreCond.get(), IterSpaces[Cnt].PreCond);
3890 auto N = IterSpaces[Cnt].NumIterations;
3891 SourceLocation Loc = N->getExprLoc();
3892 AllCountsNeedLessThan32Bits &= C.getTypeSize(N->getType()) < 32;
3893 if (LastIteration32.isUsable())
3894 LastIteration32 = SemaRef.BuildBinOp(
3895 CurScope, Loc, BO_Mul, LastIteration32.get(),
3897 .PerformImplicitConversion(N->IgnoreImpCasts(), N->getType(),
3898 Sema::AA_Converting,
3899 /*AllowExplicit=*/true)
3901 if (LastIteration64.isUsable())
3902 LastIteration64 = SemaRef.BuildBinOp(
3903 CurScope, Loc, BO_Mul, LastIteration64.get(),
3905 .PerformImplicitConversion(N->IgnoreImpCasts(), N->getType(),
3906 Sema::AA_Converting,
3907 /*AllowExplicit=*/true)
3911 // Choose either the 32-bit or 64-bit version.
3912 ExprResult LastIteration = LastIteration64;
3913 if (LastIteration32.isUsable() &&
3914 C.getTypeSize(LastIteration32.get()->getType()) == 32 &&
3915 (AllCountsNeedLessThan32Bits || NestedLoopCount == 1 ||
3918 LastIteration32.get()->getType()->hasSignedIntegerRepresentation(),
3919 LastIteration64.get(), SemaRef)))
3920 LastIteration = LastIteration32;
3921 QualType VType = LastIteration.get()->getType();
3922 QualType RealVType = VType;
3923 QualType StrideVType = VType;
3924 if (isOpenMPTaskLoopDirective(DKind)) {
3926 SemaRef.Context.getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/0);
3928 SemaRef.Context.getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/1);
3931 if (!LastIteration.isUsable())
3934 // Save the number of iterations.
3935 ExprResult NumIterations = LastIteration;
3937 LastIteration = SemaRef.BuildBinOp(
3938 CurScope, LastIteration.get()->getExprLoc(), BO_Sub,
3939 LastIteration.get(),
3940 SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get());
3941 if (!LastIteration.isUsable())
3945 // Calculate the last iteration number beforehand instead of doing this on
3946 // each iteration. Do not do this if the number of iterations may be kfold-ed.
3947 llvm::APSInt Result;
3949 LastIteration.get()->isIntegerConstantExpr(Result, SemaRef.Context);
3950 ExprResult CalcLastIteration;
3952 ExprResult SaveRef =
3953 tryBuildCapture(SemaRef, LastIteration.get(), Captures);
3954 LastIteration = SaveRef;
3956 // Prepare SaveRef + 1.
3957 NumIterations = SemaRef.BuildBinOp(
3958 CurScope, SaveRef.get()->getExprLoc(), BO_Add, SaveRef.get(),
3959 SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get());
3960 if (!NumIterations.isUsable())
3964 SourceLocation InitLoc = IterSpaces[0].InitSrcRange.getBegin();
3966 // Build variables passed into runtime, necessary for worksharing directives.
3967 ExprResult LB, UB, IL, ST, EUB, PrevLB, PrevUB;
3968 if (isOpenMPWorksharingDirective(DKind) || isOpenMPTaskLoopDirective(DKind) ||
3969 isOpenMPDistributeDirective(DKind)) {
3970 // Lower bound variable, initialized with zero.
3971 VarDecl *LBDecl = buildVarDecl(SemaRef, InitLoc, VType, ".omp.lb");
3972 LB = buildDeclRefExpr(SemaRef, LBDecl, VType, InitLoc);
3973 SemaRef.AddInitializerToDecl(
3974 LBDecl, SemaRef.ActOnIntegerConstant(InitLoc, 0).get(),
3975 /*DirectInit*/ false, /*TypeMayContainAuto*/ false);
3977 // Upper bound variable, initialized with last iteration number.
3978 VarDecl *UBDecl = buildVarDecl(SemaRef, InitLoc, VType, ".omp.ub");
3979 UB = buildDeclRefExpr(SemaRef, UBDecl, VType, InitLoc);
3980 SemaRef.AddInitializerToDecl(UBDecl, LastIteration.get(),
3981 /*DirectInit*/ false,
3982 /*TypeMayContainAuto*/ false);
3984 // A 32-bit variable-flag where runtime returns 1 for the last iteration.
3985 // This will be used to implement clause 'lastprivate'.
3986 QualType Int32Ty = SemaRef.Context.getIntTypeForBitwidth(32, true);
3987 VarDecl *ILDecl = buildVarDecl(SemaRef, InitLoc, Int32Ty, ".omp.is_last");
3988 IL = buildDeclRefExpr(SemaRef, ILDecl, Int32Ty, InitLoc);
3989 SemaRef.AddInitializerToDecl(
3990 ILDecl, SemaRef.ActOnIntegerConstant(InitLoc, 0).get(),
3991 /*DirectInit*/ false, /*TypeMayContainAuto*/ false);
3993 // Stride variable returned by runtime (we initialize it to 1 by default).
3995 buildVarDecl(SemaRef, InitLoc, StrideVType, ".omp.stride");
3996 ST = buildDeclRefExpr(SemaRef, STDecl, StrideVType, InitLoc);
3997 SemaRef.AddInitializerToDecl(
3998 STDecl, SemaRef.ActOnIntegerConstant(InitLoc, 1).get(),
3999 /*DirectInit*/ false, /*TypeMayContainAuto*/ false);
4001 // Build expression: UB = min(UB, LastIteration)
4002 // It is necessary for CodeGen of directives with static scheduling.
4003 ExprResult IsUBGreater = SemaRef.BuildBinOp(CurScope, InitLoc, BO_GT,
4004 UB.get(), LastIteration.get());
4005 ExprResult CondOp = SemaRef.ActOnConditionalOp(
4006 InitLoc, InitLoc, IsUBGreater.get(), LastIteration.get(), UB.get());
4007 EUB = SemaRef.BuildBinOp(CurScope, InitLoc, BO_Assign, UB.get(),
4009 EUB = SemaRef.ActOnFinishFullExpr(EUB.get());
4011 // If we have a combined directive that combines 'distribute', 'for' or
4012 // 'simd' we need to be able to access the bounds of the schedule of the
4013 // enclosing region. E.g. in 'distribute parallel for' the bounds obtained
4014 // by scheduling 'distribute' have to be passed to the schedule of 'for'.
4015 if (isOpenMPLoopBoundSharingDirective(DKind)) {
4016 auto *CD = cast<CapturedStmt>(AStmt)->getCapturedDecl();
4018 // We expect to have at least 2 more parameters than the 'parallel'
4019 // directive does - the lower and upper bounds of the previous schedule.
4020 assert(CD->getNumParams() >= 4 &&
4021 "Unexpected number of parameters in loop combined directive");
4023 // Set the proper type for the bounds given what we learned from the
4025 auto *PrevLBDecl = CD->getParam(/*PrevLB=*/2);
4026 auto *PrevUBDecl = CD->getParam(/*PrevUB=*/3);
4028 // Previous lower and upper bounds are obtained from the region
4031 buildDeclRefExpr(SemaRef, PrevLBDecl, PrevLBDecl->getType(), InitLoc);
4033 buildDeclRefExpr(SemaRef, PrevUBDecl, PrevUBDecl->getType(), InitLoc);
4037 // Build the iteration variable and its initialization before loop.
4041 VarDecl *IVDecl = buildVarDecl(SemaRef, InitLoc, RealVType, ".omp.iv");
4042 IV = buildDeclRefExpr(SemaRef, IVDecl, RealVType, InitLoc);
4044 (isOpenMPWorksharingDirective(DKind) ||
4045 isOpenMPTaskLoopDirective(DKind) || isOpenMPDistributeDirective(DKind))
4047 : SemaRef.ActOnIntegerConstant(SourceLocation(), 0).get();
4048 Init = SemaRef.BuildBinOp(CurScope, InitLoc, BO_Assign, IV.get(), RHS);
4049 Init = SemaRef.ActOnFinishFullExpr(Init.get());
4052 // Loop condition (IV < NumIterations) or (IV <= UB) for worksharing loops.
4053 SourceLocation CondLoc;
4055 (isOpenMPWorksharingDirective(DKind) ||
4056 isOpenMPTaskLoopDirective(DKind) || isOpenMPDistributeDirective(DKind))
4057 ? SemaRef.BuildBinOp(CurScope, CondLoc, BO_LE, IV.get(), UB.get())
4058 : SemaRef.BuildBinOp(CurScope, CondLoc, BO_LT, IV.get(),
4059 NumIterations.get());
4061 // Loop increment (IV = IV + 1)
4062 SourceLocation IncLoc;
4064 SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, IV.get(),
4065 SemaRef.ActOnIntegerConstant(IncLoc, 1).get());
4066 if (!Inc.isUsable())
4068 Inc = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, IV.get(), Inc.get());
4069 Inc = SemaRef.ActOnFinishFullExpr(Inc.get());
4070 if (!Inc.isUsable())
4073 // Increments for worksharing loops (LB = LB + ST; UB = UB + ST).
4074 // Used for directives with static scheduling.
4075 ExprResult NextLB, NextUB;
4076 if (isOpenMPWorksharingDirective(DKind) || isOpenMPTaskLoopDirective(DKind) ||
4077 isOpenMPDistributeDirective(DKind)) {
4079 NextLB = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, LB.get(), ST.get());
4080 if (!NextLB.isUsable())
4084 SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, LB.get(), NextLB.get());
4085 NextLB = SemaRef.ActOnFinishFullExpr(NextLB.get());
4086 if (!NextLB.isUsable())
4089 NextUB = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, UB.get(), ST.get());
4090 if (!NextUB.isUsable())
4094 SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, UB.get(), NextUB.get());
4095 NextUB = SemaRef.ActOnFinishFullExpr(NextUB.get());
4096 if (!NextUB.isUsable())
4100 // Build updates and final values of the loop counters.
4101 bool HasErrors = false;
4102 Built.Counters.resize(NestedLoopCount);
4103 Built.Inits.resize(NestedLoopCount);
4104 Built.Updates.resize(NestedLoopCount);
4105 Built.Finals.resize(NestedLoopCount);
4106 SmallVector<Expr *, 4> LoopMultipliers;
4109 // Go from inner nested loop to outer.
4110 for (int Cnt = NestedLoopCount - 1; Cnt >= 0; --Cnt) {
4111 LoopIterationSpace &IS = IterSpaces[Cnt];
4112 SourceLocation UpdLoc = IS.IncSrcRange.getBegin();
4113 // Build: Iter = (IV / Div) % IS.NumIters
4114 // where Div is product of previous iterations' IS.NumIters.
4116 if (Div.isUsable()) {
4118 SemaRef.BuildBinOp(CurScope, UpdLoc, BO_Div, IV.get(), Div.get());
4121 assert((Cnt == (int)NestedLoopCount - 1) &&
4122 "unusable div expected on first iteration only");
4125 if (Cnt != 0 && Iter.isUsable())
4126 Iter = SemaRef.BuildBinOp(CurScope, UpdLoc, BO_Rem, Iter.get(),
4128 if (!Iter.isUsable()) {
4133 // Build update: IS.CounterVar(Private) = IS.Start + Iter * IS.Step
4134 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(IS.CounterVar)->getDecl());
4135 auto *CounterVar = buildDeclRefExpr(SemaRef, VD, IS.CounterVar->getType(),
4136 IS.CounterVar->getExprLoc(),
4137 /*RefersToCapture=*/true);
4138 ExprResult Init = BuildCounterInit(SemaRef, CurScope, UpdLoc, CounterVar,
4139 IS.CounterInit, Captures);
4140 if (!Init.isUsable()) {
4144 ExprResult Update = BuildCounterUpdate(
4145 SemaRef, CurScope, UpdLoc, CounterVar, IS.CounterInit, Iter,
4146 IS.CounterStep, IS.Subtract, &Captures);
4147 if (!Update.isUsable()) {
4152 // Build final: IS.CounterVar = IS.Start + IS.NumIters * IS.Step
4153 ExprResult Final = BuildCounterUpdate(
4154 SemaRef, CurScope, UpdLoc, CounterVar, IS.CounterInit,
4155 IS.NumIterations, IS.CounterStep, IS.Subtract, &Captures);
4156 if (!Final.isUsable()) {
4161 // Build Div for the next iteration: Div <- Div * IS.NumIters
4164 Div = IS.NumIterations;
4166 Div = SemaRef.BuildBinOp(CurScope, UpdLoc, BO_Mul, Div.get(),
4169 // Add parentheses (for debugging purposes only).
4171 Div = tryBuildCapture(SemaRef, Div.get(), Captures);
4172 if (!Div.isUsable()) {
4176 LoopMultipliers.push_back(Div.get());
4178 if (!Update.isUsable() || !Final.isUsable()) {
4183 Built.Counters[Cnt] = IS.CounterVar;
4184 Built.PrivateCounters[Cnt] = IS.PrivateCounterVar;
4185 Built.Inits[Cnt] = Init.get();
4186 Built.Updates[Cnt] = Update.get();
4187 Built.Finals[Cnt] = Final.get();
4195 Built.IterationVarRef = IV.get();
4196 Built.LastIteration = LastIteration.get();
4197 Built.NumIterations = NumIterations.get();
4198 Built.CalcLastIteration =
4199 SemaRef.ActOnFinishFullExpr(CalcLastIteration.get()).get();
4200 Built.PreCond = PreCond.get();
4201 Built.PreInits = buildPreInits(C, Captures);
4202 Built.Cond = Cond.get();
4203 Built.Init = Init.get();
4204 Built.Inc = Inc.get();
4205 Built.LB = LB.get();
4206 Built.UB = UB.get();
4207 Built.IL = IL.get();
4208 Built.ST = ST.get();
4209 Built.EUB = EUB.get();
4210 Built.NLB = NextLB.get();
4211 Built.NUB = NextUB.get();
4212 Built.PrevLB = PrevLB.get();
4213 Built.PrevUB = PrevUB.get();
4215 Expr *CounterVal = SemaRef.DefaultLvalueConversion(IV.get()).get();
4216 // Fill data for doacross depend clauses.
4217 for (auto Pair : DSA.getDoacrossDependClauses()) {
4218 if (Pair.first->getDependencyKind() == OMPC_DEPEND_source)
4219 Pair.first->setCounterValue(CounterVal);
4221 if (NestedLoopCount != Pair.second.size() ||
4222 NestedLoopCount != LoopMultipliers.size() + 1) {
4223 // Erroneous case - clause has some problems.
4224 Pair.first->setCounterValue(CounterVal);
4227 assert(Pair.first->getDependencyKind() == OMPC_DEPEND_sink);
4228 auto I = Pair.second.rbegin();
4229 auto IS = IterSpaces.rbegin();
4230 auto ILM = LoopMultipliers.rbegin();
4231 Expr *UpCounterVal = CounterVal;
4232 Expr *Multiplier = nullptr;
4233 for (int Cnt = NestedLoopCount - 1; Cnt >= 0; --Cnt) {
4235 assert(IS->CounterStep);
4236 Expr *NormalizedOffset =
4238 .BuildBinOp(CurScope, I->first->getExprLoc(), BO_Div,
4239 I->first, IS->CounterStep)
4244 .BuildBinOp(CurScope, I->first->getExprLoc(), BO_Mul,
4245 NormalizedOffset, Multiplier)
4248 assert(I->second == OO_Plus || I->second == OO_Minus);
4249 BinaryOperatorKind BOK = (I->second == OO_Plus) ? BO_Add : BO_Sub;
4250 UpCounterVal = SemaRef
4251 .BuildBinOp(CurScope, I->first->getExprLoc(), BOK,
4252 UpCounterVal, NormalizedOffset)
4260 Pair.first->setCounterValue(UpCounterVal);
4264 return NestedLoopCount;
4267 static Expr *getCollapseNumberExpr(ArrayRef<OMPClause *> Clauses) {
4268 auto CollapseClauses =
4269 OMPExecutableDirective::getClausesOfKind<OMPCollapseClause>(Clauses);
4270 if (CollapseClauses.begin() != CollapseClauses.end())
4271 return (*CollapseClauses.begin())->getNumForLoops();
4275 static Expr *getOrderedNumberExpr(ArrayRef<OMPClause *> Clauses) {
4276 auto OrderedClauses =
4277 OMPExecutableDirective::getClausesOfKind<OMPOrderedClause>(Clauses);
4278 if (OrderedClauses.begin() != OrderedClauses.end())
4279 return (*OrderedClauses.begin())->getNumForLoops();
4283 static bool checkSimdlenSafelenSpecified(Sema &S,
4284 const ArrayRef<OMPClause *> Clauses) {
4285 OMPSafelenClause *Safelen = nullptr;
4286 OMPSimdlenClause *Simdlen = nullptr;
4288 for (auto *Clause : Clauses) {
4289 if (Clause->getClauseKind() == OMPC_safelen)
4290 Safelen = cast<OMPSafelenClause>(Clause);
4291 else if (Clause->getClauseKind() == OMPC_simdlen)
4292 Simdlen = cast<OMPSimdlenClause>(Clause);
4293 if (Safelen && Simdlen)
4297 if (Simdlen && Safelen) {
4298 llvm::APSInt SimdlenRes, SafelenRes;
4299 auto SimdlenLength = Simdlen->getSimdlen();
4300 auto SafelenLength = Safelen->getSafelen();
4301 if (SimdlenLength->isValueDependent() || SimdlenLength->isTypeDependent() ||
4302 SimdlenLength->isInstantiationDependent() ||
4303 SimdlenLength->containsUnexpandedParameterPack())
4305 if (SafelenLength->isValueDependent() || SafelenLength->isTypeDependent() ||
4306 SafelenLength->isInstantiationDependent() ||
4307 SafelenLength->containsUnexpandedParameterPack())
4309 SimdlenLength->EvaluateAsInt(SimdlenRes, S.Context);
4310 SafelenLength->EvaluateAsInt(SafelenRes, S.Context);
4311 // OpenMP 4.5 [2.8.1, simd Construct, Restrictions]
4312 // If both simdlen and safelen clauses are specified, the value of the
4313 // simdlen parameter must be less than or equal to the value of the safelen
4315 if (SimdlenRes > SafelenRes) {
4316 S.Diag(SimdlenLength->getExprLoc(),
4317 diag::err_omp_wrong_simdlen_safelen_values)
4318 << SimdlenLength->getSourceRange() << SafelenLength->getSourceRange();
4325 StmtResult Sema::ActOnOpenMPSimdDirective(
4326 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
4327 SourceLocation EndLoc,
4328 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
4332 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
4333 OMPLoopDirective::HelperExprs B;
4334 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
4335 // define the nested loops number.
4336 unsigned NestedLoopCount = CheckOpenMPLoop(
4337 OMPD_simd, getCollapseNumberExpr(Clauses), getOrderedNumberExpr(Clauses),
4338 AStmt, *this, *DSAStack, VarsWithImplicitDSA, B);
4339 if (NestedLoopCount == 0)
4342 assert((CurContext->isDependentContext() || B.builtAll()) &&
4343 "omp simd loop exprs were not built");
4345 if (!CurContext->isDependentContext()) {
4346 // Finalize the clauses that need pre-built expressions for CodeGen.
4347 for (auto C : Clauses) {
4348 if (auto *LC = dyn_cast<OMPLinearClause>(C))
4349 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
4350 B.NumIterations, *this, CurScope,
4356 if (checkSimdlenSafelenSpecified(*this, Clauses))
4359 getCurFunction()->setHasBranchProtectedScope();
4360 return OMPSimdDirective::Create(Context, StartLoc, EndLoc, NestedLoopCount,
4364 StmtResult Sema::ActOnOpenMPForDirective(
4365 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
4366 SourceLocation EndLoc,
4367 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
4371 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
4372 OMPLoopDirective::HelperExprs B;
4373 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
4374 // define the nested loops number.
4375 unsigned NestedLoopCount = CheckOpenMPLoop(
4376 OMPD_for, getCollapseNumberExpr(Clauses), getOrderedNumberExpr(Clauses),
4377 AStmt, *this, *DSAStack, VarsWithImplicitDSA, B);
4378 if (NestedLoopCount == 0)
4381 assert((CurContext->isDependentContext() || B.builtAll()) &&
4382 "omp for loop exprs were not built");
4384 if (!CurContext->isDependentContext()) {
4385 // Finalize the clauses that need pre-built expressions for CodeGen.
4386 for (auto C : Clauses) {
4387 if (auto *LC = dyn_cast<OMPLinearClause>(C))
4388 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
4389 B.NumIterations, *this, CurScope,
4395 getCurFunction()->setHasBranchProtectedScope();
4396 return OMPForDirective::Create(Context, StartLoc, EndLoc, NestedLoopCount,
4397 Clauses, AStmt, B, DSAStack->isCancelRegion());
4400 StmtResult Sema::ActOnOpenMPForSimdDirective(
4401 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
4402 SourceLocation EndLoc,
4403 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
4407 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
4408 OMPLoopDirective::HelperExprs B;
4409 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
4410 // define the nested loops number.
4411 unsigned NestedLoopCount =
4412 CheckOpenMPLoop(OMPD_for_simd, getCollapseNumberExpr(Clauses),
4413 getOrderedNumberExpr(Clauses), AStmt, *this, *DSAStack,
4414 VarsWithImplicitDSA, B);
4415 if (NestedLoopCount == 0)
4418 assert((CurContext->isDependentContext() || B.builtAll()) &&
4419 "omp for simd loop exprs were not built");
4421 if (!CurContext->isDependentContext()) {
4422 // Finalize the clauses that need pre-built expressions for CodeGen.
4423 for (auto C : Clauses) {
4424 if (auto *LC = dyn_cast<OMPLinearClause>(C))
4425 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
4426 B.NumIterations, *this, CurScope,
4432 if (checkSimdlenSafelenSpecified(*this, Clauses))
4435 getCurFunction()->setHasBranchProtectedScope();
4436 return OMPForSimdDirective::Create(Context, StartLoc, EndLoc, NestedLoopCount,
4440 StmtResult Sema::ActOnOpenMPSectionsDirective(ArrayRef<OMPClause *> Clauses,
4442 SourceLocation StartLoc,
4443 SourceLocation EndLoc) {
4447 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
4448 auto BaseStmt = AStmt;
4449 while (auto *CS = dyn_cast_or_null<CapturedStmt>(BaseStmt))
4450 BaseStmt = CS->getCapturedStmt();
4451 if (auto *C = dyn_cast_or_null<CompoundStmt>(BaseStmt)) {
4452 auto S = C->children();
4453 if (S.begin() == S.end())
4455 // All associated statements must be '#pragma omp section' except for
4457 for (Stmt *SectionStmt : llvm::make_range(std::next(S.begin()), S.end())) {
4458 if (!SectionStmt || !isa<OMPSectionDirective>(SectionStmt)) {
4460 Diag(SectionStmt->getLocStart(),
4461 diag::err_omp_sections_substmt_not_section);
4464 cast<OMPSectionDirective>(SectionStmt)
4465 ->setHasCancel(DSAStack->isCancelRegion());
4468 Diag(AStmt->getLocStart(), diag::err_omp_sections_not_compound_stmt);
4472 getCurFunction()->setHasBranchProtectedScope();
4474 return OMPSectionsDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt,
4475 DSAStack->isCancelRegion());
4478 StmtResult Sema::ActOnOpenMPSectionDirective(Stmt *AStmt,
4479 SourceLocation StartLoc,
4480 SourceLocation EndLoc) {
4484 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
4486 getCurFunction()->setHasBranchProtectedScope();
4487 DSAStack->setParentCancelRegion(DSAStack->isCancelRegion());
4489 return OMPSectionDirective::Create(Context, StartLoc, EndLoc, AStmt,
4490 DSAStack->isCancelRegion());
4493 StmtResult Sema::ActOnOpenMPSingleDirective(ArrayRef<OMPClause *> Clauses,
4495 SourceLocation StartLoc,
4496 SourceLocation EndLoc) {
4500 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
4502 getCurFunction()->setHasBranchProtectedScope();
4504 // OpenMP [2.7.3, single Construct, Restrictions]
4505 // The copyprivate clause must not be used with the nowait clause.
4506 OMPClause *Nowait = nullptr;
4507 OMPClause *Copyprivate = nullptr;
4508 for (auto *Clause : Clauses) {
4509 if (Clause->getClauseKind() == OMPC_nowait)
4511 else if (Clause->getClauseKind() == OMPC_copyprivate)
4512 Copyprivate = Clause;
4513 if (Copyprivate && Nowait) {
4514 Diag(Copyprivate->getLocStart(),
4515 diag::err_omp_single_copyprivate_with_nowait);
4516 Diag(Nowait->getLocStart(), diag::note_omp_nowait_clause_here);
4521 return OMPSingleDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt);
4524 StmtResult Sema::ActOnOpenMPMasterDirective(Stmt *AStmt,
4525 SourceLocation StartLoc,
4526 SourceLocation EndLoc) {
4530 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
4532 getCurFunction()->setHasBranchProtectedScope();
4534 return OMPMasterDirective::Create(Context, StartLoc, EndLoc, AStmt);
4537 StmtResult Sema::ActOnOpenMPCriticalDirective(
4538 const DeclarationNameInfo &DirName, ArrayRef<OMPClause *> Clauses,
4539 Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc) {
4543 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
4545 bool ErrorFound = false;
4547 SourceLocation HintLoc;
4548 bool DependentHint = false;
4549 for (auto *C : Clauses) {
4550 if (C->getClauseKind() == OMPC_hint) {
4551 if (!DirName.getName()) {
4552 Diag(C->getLocStart(), diag::err_omp_hint_clause_no_name);
4555 Expr *E = cast<OMPHintClause>(C)->getHint();
4556 if (E->isTypeDependent() || E->isValueDependent() ||
4557 E->isInstantiationDependent())
4558 DependentHint = true;
4560 Hint = E->EvaluateKnownConstInt(Context);
4561 HintLoc = C->getLocStart();
4567 auto Pair = DSAStack->getCriticalWithHint(DirName);
4568 if (Pair.first && DirName.getName() && !DependentHint) {
4569 if (llvm::APSInt::compareValues(Hint, Pair.second) != 0) {
4570 Diag(StartLoc, diag::err_omp_critical_with_hint);
4571 if (HintLoc.isValid()) {
4572 Diag(HintLoc, diag::note_omp_critical_hint_here)
4573 << 0 << Hint.toString(/*Radix=*/10, /*Signed=*/false);
4575 Diag(StartLoc, diag::note_omp_critical_no_hint) << 0;
4576 if (auto *C = Pair.first->getSingleClause<OMPHintClause>()) {
4577 Diag(C->getLocStart(), diag::note_omp_critical_hint_here)
4579 << C->getHint()->EvaluateKnownConstInt(Context).toString(
4580 /*Radix=*/10, /*Signed=*/false);
4582 Diag(Pair.first->getLocStart(), diag::note_omp_critical_no_hint) << 1;
4586 getCurFunction()->setHasBranchProtectedScope();
4588 auto *Dir = OMPCriticalDirective::Create(Context, DirName, StartLoc, EndLoc,
4590 if (!Pair.first && DirName.getName() && !DependentHint)
4591 DSAStack->addCriticalWithHint(Dir, Hint);
4595 StmtResult Sema::ActOnOpenMPParallelForDirective(
4596 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
4597 SourceLocation EndLoc,
4598 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
4602 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
4603 // 1.2.2 OpenMP Language Terminology
4604 // Structured block - An executable statement with a single entry at the
4605 // top and a single exit at the bottom.
4606 // The point of exit cannot be a branch out of the structured block.
4607 // longjmp() and throw() must not violate the entry/exit criteria.
4608 CS->getCapturedDecl()->setNothrow();
4610 OMPLoopDirective::HelperExprs B;
4611 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
4612 // define the nested loops number.
4613 unsigned NestedLoopCount =
4614 CheckOpenMPLoop(OMPD_parallel_for, getCollapseNumberExpr(Clauses),
4615 getOrderedNumberExpr(Clauses), AStmt, *this, *DSAStack,
4616 VarsWithImplicitDSA, B);
4617 if (NestedLoopCount == 0)
4620 assert((CurContext->isDependentContext() || B.builtAll()) &&
4621 "omp parallel for loop exprs were not built");
4623 if (!CurContext->isDependentContext()) {
4624 // Finalize the clauses that need pre-built expressions for CodeGen.
4625 for (auto C : Clauses) {
4626 if (auto *LC = dyn_cast<OMPLinearClause>(C))
4627 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
4628 B.NumIterations, *this, CurScope,
4634 getCurFunction()->setHasBranchProtectedScope();
4635 return OMPParallelForDirective::Create(Context, StartLoc, EndLoc,
4636 NestedLoopCount, Clauses, AStmt, B,
4637 DSAStack->isCancelRegion());
4640 StmtResult Sema::ActOnOpenMPParallelForSimdDirective(
4641 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
4642 SourceLocation EndLoc,
4643 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
4647 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
4648 // 1.2.2 OpenMP Language Terminology
4649 // Structured block - An executable statement with a single entry at the
4650 // top and a single exit at the bottom.
4651 // The point of exit cannot be a branch out of the structured block.
4652 // longjmp() and throw() must not violate the entry/exit criteria.
4653 CS->getCapturedDecl()->setNothrow();
4655 OMPLoopDirective::HelperExprs B;
4656 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
4657 // define the nested loops number.
4658 unsigned NestedLoopCount =
4659 CheckOpenMPLoop(OMPD_parallel_for_simd, getCollapseNumberExpr(Clauses),
4660 getOrderedNumberExpr(Clauses), AStmt, *this, *DSAStack,
4661 VarsWithImplicitDSA, B);
4662 if (NestedLoopCount == 0)
4665 if (!CurContext->isDependentContext()) {
4666 // Finalize the clauses that need pre-built expressions for CodeGen.
4667 for (auto C : Clauses) {
4668 if (auto *LC = dyn_cast<OMPLinearClause>(C))
4669 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
4670 B.NumIterations, *this, CurScope,
4676 if (checkSimdlenSafelenSpecified(*this, Clauses))
4679 getCurFunction()->setHasBranchProtectedScope();
4680 return OMPParallelForSimdDirective::Create(
4681 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
4685 Sema::ActOnOpenMPParallelSectionsDirective(ArrayRef<OMPClause *> Clauses,
4686 Stmt *AStmt, SourceLocation StartLoc,
4687 SourceLocation EndLoc) {
4691 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
4692 auto BaseStmt = AStmt;
4693 while (auto *CS = dyn_cast_or_null<CapturedStmt>(BaseStmt))
4694 BaseStmt = CS->getCapturedStmt();
4695 if (auto *C = dyn_cast_or_null<CompoundStmt>(BaseStmt)) {
4696 auto S = C->children();
4697 if (S.begin() == S.end())
4699 // All associated statements must be '#pragma omp section' except for
4701 for (Stmt *SectionStmt : llvm::make_range(std::next(S.begin()), S.end())) {
4702 if (!SectionStmt || !isa<OMPSectionDirective>(SectionStmt)) {
4704 Diag(SectionStmt->getLocStart(),
4705 diag::err_omp_parallel_sections_substmt_not_section);
4708 cast<OMPSectionDirective>(SectionStmt)
4709 ->setHasCancel(DSAStack->isCancelRegion());
4712 Diag(AStmt->getLocStart(),
4713 diag::err_omp_parallel_sections_not_compound_stmt);
4717 getCurFunction()->setHasBranchProtectedScope();
4719 return OMPParallelSectionsDirective::Create(
4720 Context, StartLoc, EndLoc, Clauses, AStmt, DSAStack->isCancelRegion());
4723 StmtResult Sema::ActOnOpenMPTaskDirective(ArrayRef<OMPClause *> Clauses,
4724 Stmt *AStmt, SourceLocation StartLoc,
4725 SourceLocation EndLoc) {
4729 auto *CS = cast<CapturedStmt>(AStmt);
4730 // 1.2.2 OpenMP Language Terminology
4731 // Structured block - An executable statement with a single entry at the
4732 // top and a single exit at the bottom.
4733 // The point of exit cannot be a branch out of the structured block.
4734 // longjmp() and throw() must not violate the entry/exit criteria.
4735 CS->getCapturedDecl()->setNothrow();
4737 getCurFunction()->setHasBranchProtectedScope();
4739 return OMPTaskDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt,
4740 DSAStack->isCancelRegion());
4743 StmtResult Sema::ActOnOpenMPTaskyieldDirective(SourceLocation StartLoc,
4744 SourceLocation EndLoc) {
4745 return OMPTaskyieldDirective::Create(Context, StartLoc, EndLoc);
4748 StmtResult Sema::ActOnOpenMPBarrierDirective(SourceLocation StartLoc,
4749 SourceLocation EndLoc) {
4750 return OMPBarrierDirective::Create(Context, StartLoc, EndLoc);
4753 StmtResult Sema::ActOnOpenMPTaskwaitDirective(SourceLocation StartLoc,
4754 SourceLocation EndLoc) {
4755 return OMPTaskwaitDirective::Create(Context, StartLoc, EndLoc);
4758 StmtResult Sema::ActOnOpenMPTaskgroupDirective(Stmt *AStmt,
4759 SourceLocation StartLoc,
4760 SourceLocation EndLoc) {
4764 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
4766 getCurFunction()->setHasBranchProtectedScope();
4768 return OMPTaskgroupDirective::Create(Context, StartLoc, EndLoc, AStmt);
4771 StmtResult Sema::ActOnOpenMPFlushDirective(ArrayRef<OMPClause *> Clauses,
4772 SourceLocation StartLoc,
4773 SourceLocation EndLoc) {
4774 assert(Clauses.size() <= 1 && "Extra clauses in flush directive");
4775 return OMPFlushDirective::Create(Context, StartLoc, EndLoc, Clauses);
4778 StmtResult Sema::ActOnOpenMPOrderedDirective(ArrayRef<OMPClause *> Clauses,
4780 SourceLocation StartLoc,
4781 SourceLocation EndLoc) {
4782 OMPClause *DependFound = nullptr;
4783 OMPClause *DependSourceClause = nullptr;
4784 OMPClause *DependSinkClause = nullptr;
4785 bool ErrorFound = false;
4786 OMPThreadsClause *TC = nullptr;
4787 OMPSIMDClause *SC = nullptr;
4788 for (auto *C : Clauses) {
4789 if (auto *DC = dyn_cast<OMPDependClause>(C)) {
4791 if (DC->getDependencyKind() == OMPC_DEPEND_source) {
4792 if (DependSourceClause) {
4793 Diag(C->getLocStart(), diag::err_omp_more_one_clause)
4794 << getOpenMPDirectiveName(OMPD_ordered)
4795 << getOpenMPClauseName(OMPC_depend) << 2;
4798 DependSourceClause = C;
4799 if (DependSinkClause) {
4800 Diag(C->getLocStart(), diag::err_omp_depend_sink_source_not_allowed)
4804 } else if (DC->getDependencyKind() == OMPC_DEPEND_sink) {
4805 if (DependSourceClause) {
4806 Diag(C->getLocStart(), diag::err_omp_depend_sink_source_not_allowed)
4810 DependSinkClause = C;
4812 } else if (C->getClauseKind() == OMPC_threads)
4813 TC = cast<OMPThreadsClause>(C);
4814 else if (C->getClauseKind() == OMPC_simd)
4815 SC = cast<OMPSIMDClause>(C);
4817 if (!ErrorFound && !SC &&
4818 isOpenMPSimdDirective(DSAStack->getParentDirective())) {
4819 // OpenMP [2.8.1,simd Construct, Restrictions]
4820 // An ordered construct with the simd clause is the only OpenMP construct
4821 // that can appear in the simd region.
4822 Diag(StartLoc, diag::err_omp_prohibited_region_simd);
4824 } else if (DependFound && (TC || SC)) {
4825 Diag(DependFound->getLocStart(), diag::err_omp_depend_clause_thread_simd)
4826 << getOpenMPClauseName(TC ? TC->getClauseKind() : SC->getClauseKind());
4828 } else if (DependFound && !DSAStack->getParentOrderedRegionParam()) {
4829 Diag(DependFound->getLocStart(),
4830 diag::err_omp_ordered_directive_without_param);
4832 } else if (TC || Clauses.empty()) {
4833 if (auto *Param = DSAStack->getParentOrderedRegionParam()) {
4834 SourceLocation ErrLoc = TC ? TC->getLocStart() : StartLoc;
4835 Diag(ErrLoc, diag::err_omp_ordered_directive_with_param)
4837 Diag(Param->getLocStart(), diag::note_omp_ordered_param);
4841 if ((!AStmt && !DependFound) || ErrorFound)
4845 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
4847 getCurFunction()->setHasBranchProtectedScope();
4850 return OMPOrderedDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt);
4854 /// \brief Helper class for checking expression in 'omp atomic [update]'
4856 class OpenMPAtomicUpdateChecker {
4857 /// \brief Error results for atomic update expressions.
4858 enum ExprAnalysisErrorCode {
4859 /// \brief A statement is not an expression statement.
4861 /// \brief Expression is not builtin binary or unary operation.
4862 NotABinaryOrUnaryExpression,
4863 /// \brief Unary operation is not post-/pre- increment/decrement operation.
4864 NotAnUnaryIncDecExpression,
4865 /// \brief An expression is not of scalar type.
4867 /// \brief A binary operation is not an assignment operation.
4869 /// \brief RHS part of the binary operation is not a binary expression.
4870 NotABinaryExpression,
4871 /// \brief RHS part is not additive/multiplicative/shift/biwise binary
4874 /// \brief RHS binary operation does not have reference to the updated LHS
4876 NotAnUpdateExpression,
4877 /// \brief No errors is found.
4880 /// \brief Reference to Sema.
4882 /// \brief A location for note diagnostics (when error is found).
4883 SourceLocation NoteLoc;
4884 /// \brief 'x' lvalue part of the source atomic expression.
4886 /// \brief 'expr' rvalue part of the source atomic expression.
4888 /// \brief Helper expression of the form
4889 /// 'OpaqueValueExpr(x) binop OpaqueValueExpr(expr)' or
4890 /// 'OpaqueValueExpr(expr) binop OpaqueValueExpr(x)'.
4892 /// \brief Is 'x' a LHS in a RHS part of full update expression. It is
4893 /// important for non-associative operations.
4894 bool IsXLHSInRHSPart;
4895 BinaryOperatorKind Op;
4896 SourceLocation OpLoc;
4897 /// \brief true if the source expression is a postfix unary operation, false
4898 /// if it is a prefix unary operation.
4899 bool IsPostfixUpdate;
4902 OpenMPAtomicUpdateChecker(Sema &SemaRef)
4903 : SemaRef(SemaRef), X(nullptr), E(nullptr), UpdateExpr(nullptr),
4904 IsXLHSInRHSPart(false), Op(BO_PtrMemD), IsPostfixUpdate(false) {}
4905 /// \brief Check specified statement that it is suitable for 'atomic update'
4906 /// constructs and extract 'x', 'expr' and Operation from the original
4907 /// expression. If DiagId and NoteId == 0, then only check is performed
4908 /// without error notification.
4909 /// \param DiagId Diagnostic which should be emitted if error is found.
4910 /// \param NoteId Diagnostic note for the main error message.
4911 /// \return true if statement is not an update expression, false otherwise.
4912 bool checkStatement(Stmt *S, unsigned DiagId = 0, unsigned NoteId = 0);
4913 /// \brief Return the 'x' lvalue part of the source atomic expression.
4914 Expr *getX() const { return X; }
4915 /// \brief Return the 'expr' rvalue part of the source atomic expression.
4916 Expr *getExpr() const { return E; }
4917 /// \brief Return the update expression used in calculation of the updated
4918 /// value. Always has form 'OpaqueValueExpr(x) binop OpaqueValueExpr(expr)' or
4919 /// 'OpaqueValueExpr(expr) binop OpaqueValueExpr(x)'.
4920 Expr *getUpdateExpr() const { return UpdateExpr; }
4921 /// \brief Return true if 'x' is LHS in RHS part of full update expression,
4922 /// false otherwise.
4923 bool isXLHSInRHSPart() const { return IsXLHSInRHSPart; }
4925 /// \brief true if the source expression is a postfix unary operation, false
4926 /// if it is a prefix unary operation.
4927 bool isPostfixUpdate() const { return IsPostfixUpdate; }
4930 bool checkBinaryOperation(BinaryOperator *AtomicBinOp, unsigned DiagId = 0,
4931 unsigned NoteId = 0);
4935 bool OpenMPAtomicUpdateChecker::checkBinaryOperation(
4936 BinaryOperator *AtomicBinOp, unsigned DiagId, unsigned NoteId) {
4937 ExprAnalysisErrorCode ErrorFound = NoError;
4938 SourceLocation ErrorLoc, NoteLoc;
4939 SourceRange ErrorRange, NoteRange;
4940 // Allowed constructs are:
4941 // x = x binop expr;
4942 // x = expr binop x;
4943 if (AtomicBinOp->getOpcode() == BO_Assign) {
4944 X = AtomicBinOp->getLHS();
4945 if (auto *AtomicInnerBinOp = dyn_cast<BinaryOperator>(
4946 AtomicBinOp->getRHS()->IgnoreParenImpCasts())) {
4947 if (AtomicInnerBinOp->isMultiplicativeOp() ||
4948 AtomicInnerBinOp->isAdditiveOp() || AtomicInnerBinOp->isShiftOp() ||
4949 AtomicInnerBinOp->isBitwiseOp()) {
4950 Op = AtomicInnerBinOp->getOpcode();
4951 OpLoc = AtomicInnerBinOp->getOperatorLoc();
4952 auto *LHS = AtomicInnerBinOp->getLHS();
4953 auto *RHS = AtomicInnerBinOp->getRHS();
4954 llvm::FoldingSetNodeID XId, LHSId, RHSId;
4955 X->IgnoreParenImpCasts()->Profile(XId, SemaRef.getASTContext(),
4956 /*Canonical=*/true);
4957 LHS->IgnoreParenImpCasts()->Profile(LHSId, SemaRef.getASTContext(),
4958 /*Canonical=*/true);
4959 RHS->IgnoreParenImpCasts()->Profile(RHSId, SemaRef.getASTContext(),
4960 /*Canonical=*/true);
4963 IsXLHSInRHSPart = true;
4964 } else if (XId == RHSId) {
4966 IsXLHSInRHSPart = false;
4968 ErrorLoc = AtomicInnerBinOp->getExprLoc();
4969 ErrorRange = AtomicInnerBinOp->getSourceRange();
4970 NoteLoc = X->getExprLoc();
4971 NoteRange = X->getSourceRange();
4972 ErrorFound = NotAnUpdateExpression;
4975 ErrorLoc = AtomicInnerBinOp->getExprLoc();
4976 ErrorRange = AtomicInnerBinOp->getSourceRange();
4977 NoteLoc = AtomicInnerBinOp->getOperatorLoc();
4978 NoteRange = SourceRange(NoteLoc, NoteLoc);
4979 ErrorFound = NotABinaryOperator;
4982 NoteLoc = ErrorLoc = AtomicBinOp->getRHS()->getExprLoc();
4983 NoteRange = ErrorRange = AtomicBinOp->getRHS()->getSourceRange();
4984 ErrorFound = NotABinaryExpression;
4987 ErrorLoc = AtomicBinOp->getExprLoc();
4988 ErrorRange = AtomicBinOp->getSourceRange();
4989 NoteLoc = AtomicBinOp->getOperatorLoc();
4990 NoteRange = SourceRange(NoteLoc, NoteLoc);
4991 ErrorFound = NotAnAssignmentOp;
4993 if (ErrorFound != NoError && DiagId != 0 && NoteId != 0) {
4994 SemaRef.Diag(ErrorLoc, DiagId) << ErrorRange;
4995 SemaRef.Diag(NoteLoc, NoteId) << ErrorFound << NoteRange;
4997 } else if (SemaRef.CurContext->isDependentContext())
4998 E = X = UpdateExpr = nullptr;
4999 return ErrorFound != NoError;
5002 bool OpenMPAtomicUpdateChecker::checkStatement(Stmt *S, unsigned DiagId,
5004 ExprAnalysisErrorCode ErrorFound = NoError;
5005 SourceLocation ErrorLoc, NoteLoc;
5006 SourceRange ErrorRange, NoteRange;
5007 // Allowed constructs are:
5013 // x = x binop expr;
5014 // x = expr binop x;
5015 if (auto *AtomicBody = dyn_cast<Expr>(S)) {
5016 AtomicBody = AtomicBody->IgnoreParenImpCasts();
5017 if (AtomicBody->getType()->isScalarType() ||
5018 AtomicBody->isInstantiationDependent()) {
5019 if (auto *AtomicCompAssignOp = dyn_cast<CompoundAssignOperator>(
5020 AtomicBody->IgnoreParenImpCasts())) {
5021 // Check for Compound Assignment Operation
5022 Op = BinaryOperator::getOpForCompoundAssignment(
5023 AtomicCompAssignOp->getOpcode());
5024 OpLoc = AtomicCompAssignOp->getOperatorLoc();
5025 E = AtomicCompAssignOp->getRHS();
5026 X = AtomicCompAssignOp->getLHS()->IgnoreParens();
5027 IsXLHSInRHSPart = true;
5028 } else if (auto *AtomicBinOp = dyn_cast<BinaryOperator>(
5029 AtomicBody->IgnoreParenImpCasts())) {
5030 // Check for Binary Operation
5031 if (checkBinaryOperation(AtomicBinOp, DiagId, NoteId))
5033 } else if (auto *AtomicUnaryOp = dyn_cast<UnaryOperator>(
5034 AtomicBody->IgnoreParenImpCasts())) {
5035 // Check for Unary Operation
5036 if (AtomicUnaryOp->isIncrementDecrementOp()) {
5037 IsPostfixUpdate = AtomicUnaryOp->isPostfix();
5038 Op = AtomicUnaryOp->isIncrementOp() ? BO_Add : BO_Sub;
5039 OpLoc = AtomicUnaryOp->getOperatorLoc();
5040 X = AtomicUnaryOp->getSubExpr()->IgnoreParens();
5041 E = SemaRef.ActOnIntegerConstant(OpLoc, /*uint64_t Val=*/1).get();
5042 IsXLHSInRHSPart = true;
5044 ErrorFound = NotAnUnaryIncDecExpression;
5045 ErrorLoc = AtomicUnaryOp->getExprLoc();
5046 ErrorRange = AtomicUnaryOp->getSourceRange();
5047 NoteLoc = AtomicUnaryOp->getOperatorLoc();
5048 NoteRange = SourceRange(NoteLoc, NoteLoc);
5050 } else if (!AtomicBody->isInstantiationDependent()) {
5051 ErrorFound = NotABinaryOrUnaryExpression;
5052 NoteLoc = ErrorLoc = AtomicBody->getExprLoc();
5053 NoteRange = ErrorRange = AtomicBody->getSourceRange();
5056 ErrorFound = NotAScalarType;
5057 NoteLoc = ErrorLoc = AtomicBody->getLocStart();
5058 NoteRange = ErrorRange = SourceRange(NoteLoc, NoteLoc);
5061 ErrorFound = NotAnExpression;
5062 NoteLoc = ErrorLoc = S->getLocStart();
5063 NoteRange = ErrorRange = SourceRange(NoteLoc, NoteLoc);
5065 if (ErrorFound != NoError && DiagId != 0 && NoteId != 0) {
5066 SemaRef.Diag(ErrorLoc, DiagId) << ErrorRange;
5067 SemaRef.Diag(NoteLoc, NoteId) << ErrorFound << NoteRange;
5069 } else if (SemaRef.CurContext->isDependentContext())
5070 E = X = UpdateExpr = nullptr;
5071 if (ErrorFound == NoError && E && X) {
5072 // Build an update expression of form 'OpaqueValueExpr(x) binop
5073 // OpaqueValueExpr(expr)' or 'OpaqueValueExpr(expr) binop
5074 // OpaqueValueExpr(x)' and then cast it to the type of the 'x' expression.
5075 auto *OVEX = new (SemaRef.getASTContext())
5076 OpaqueValueExpr(X->getExprLoc(), X->getType(), VK_RValue);
5077 auto *OVEExpr = new (SemaRef.getASTContext())
5078 OpaqueValueExpr(E->getExprLoc(), E->getType(), VK_RValue);
5080 SemaRef.CreateBuiltinBinOp(OpLoc, Op, IsXLHSInRHSPart ? OVEX : OVEExpr,
5081 IsXLHSInRHSPart ? OVEExpr : OVEX);
5082 if (Update.isInvalid())
5084 Update = SemaRef.PerformImplicitConversion(Update.get(), X->getType(),
5086 if (Update.isInvalid())
5088 UpdateExpr = Update.get();
5090 return ErrorFound != NoError;
5093 StmtResult Sema::ActOnOpenMPAtomicDirective(ArrayRef<OMPClause *> Clauses,
5095 SourceLocation StartLoc,
5096 SourceLocation EndLoc) {
5100 auto *CS = cast<CapturedStmt>(AStmt);
5101 // 1.2.2 OpenMP Language Terminology
5102 // Structured block - An executable statement with a single entry at the
5103 // top and a single exit at the bottom.
5104 // The point of exit cannot be a branch out of the structured block.
5105 // longjmp() and throw() must not violate the entry/exit criteria.
5106 OpenMPClauseKind AtomicKind = OMPC_unknown;
5107 SourceLocation AtomicKindLoc;
5108 for (auto *C : Clauses) {
5109 if (C->getClauseKind() == OMPC_read || C->getClauseKind() == OMPC_write ||
5110 C->getClauseKind() == OMPC_update ||
5111 C->getClauseKind() == OMPC_capture) {
5112 if (AtomicKind != OMPC_unknown) {
5113 Diag(C->getLocStart(), diag::err_omp_atomic_several_clauses)
5114 << SourceRange(C->getLocStart(), C->getLocEnd());
5115 Diag(AtomicKindLoc, diag::note_omp_atomic_previous_clause)
5116 << getOpenMPClauseName(AtomicKind);
5118 AtomicKind = C->getClauseKind();
5119 AtomicKindLoc = C->getLocStart();
5124 auto Body = CS->getCapturedStmt();
5125 if (auto *EWC = dyn_cast<ExprWithCleanups>(Body))
5126 Body = EWC->getSubExpr();
5132 bool IsXLHSInRHSPart = false;
5133 bool IsPostfixUpdate = false;
5134 // OpenMP [2.12.6, atomic Construct]
5135 // In the next expressions:
5136 // * x and v (as applicable) are both l-value expressions with scalar type.
5137 // * During the execution of an atomic region, multiple syntactic
5138 // occurrences of x must designate the same storage location.
5139 // * Neither of v and expr (as applicable) may access the storage location
5141 // * Neither of x and expr (as applicable) may access the storage location
5143 // * expr is an expression with scalar type.
5144 // * binop is one of +, *, -, /, &, ^, |, <<, or >>.
5145 // * binop, binop=, ++, and -- are not overloaded operators.
5146 // * The expression x binop expr must be numerically equivalent to x binop
5147 // (expr). This requirement is satisfied if the operators in expr have
5148 // precedence greater than binop, or by using parentheses around expr or
5149 // subexpressions of expr.
5150 // * The expression expr binop x must be numerically equivalent to (expr)
5151 // binop x. This requirement is satisfied if the operators in expr have
5152 // precedence equal to or greater than binop, or by using parentheses around
5153 // expr or subexpressions of expr.
5154 // * For forms that allow multiple occurrences of x, the number of times
5155 // that x is evaluated is unspecified.
5156 if (AtomicKind == OMPC_read) {
5163 } ErrorFound = NoError;
5164 SourceLocation ErrorLoc, NoteLoc;
5165 SourceRange ErrorRange, NoteRange;
5166 // If clause is read:
5168 if (auto *AtomicBody = dyn_cast<Expr>(Body)) {
5170 dyn_cast<BinaryOperator>(AtomicBody->IgnoreParenImpCasts());
5171 if (AtomicBinOp && AtomicBinOp->getOpcode() == BO_Assign) {
5172 X = AtomicBinOp->getRHS()->IgnoreParenImpCasts();
5173 V = AtomicBinOp->getLHS()->IgnoreParenImpCasts();
5174 if ((X->isInstantiationDependent() || X->getType()->isScalarType()) &&
5175 (V->isInstantiationDependent() || V->getType()->isScalarType())) {
5176 if (!X->isLValue() || !V->isLValue()) {
5177 auto NotLValueExpr = X->isLValue() ? V : X;
5178 ErrorFound = NotAnLValue;
5179 ErrorLoc = AtomicBinOp->getExprLoc();
5180 ErrorRange = AtomicBinOp->getSourceRange();
5181 NoteLoc = NotLValueExpr->getExprLoc();
5182 NoteRange = NotLValueExpr->getSourceRange();
5184 } else if (!X->isInstantiationDependent() ||
5185 !V->isInstantiationDependent()) {
5186 auto NotScalarExpr =
5187 (X->isInstantiationDependent() || X->getType()->isScalarType())
5190 ErrorFound = NotAScalarType;
5191 ErrorLoc = AtomicBinOp->getExprLoc();
5192 ErrorRange = AtomicBinOp->getSourceRange();
5193 NoteLoc = NotScalarExpr->getExprLoc();
5194 NoteRange = NotScalarExpr->getSourceRange();
5196 } else if (!AtomicBody->isInstantiationDependent()) {
5197 ErrorFound = NotAnAssignmentOp;
5198 ErrorLoc = AtomicBody->getExprLoc();
5199 ErrorRange = AtomicBody->getSourceRange();
5200 NoteLoc = AtomicBinOp ? AtomicBinOp->getOperatorLoc()
5201 : AtomicBody->getExprLoc();
5202 NoteRange = AtomicBinOp ? AtomicBinOp->getSourceRange()
5203 : AtomicBody->getSourceRange();
5206 ErrorFound = NotAnExpression;
5207 NoteLoc = ErrorLoc = Body->getLocStart();
5208 NoteRange = ErrorRange = SourceRange(NoteLoc, NoteLoc);
5210 if (ErrorFound != NoError) {
5211 Diag(ErrorLoc, diag::err_omp_atomic_read_not_expression_statement)
5213 Diag(NoteLoc, diag::note_omp_atomic_read_write) << ErrorFound
5216 } else if (CurContext->isDependentContext())
5218 } else if (AtomicKind == OMPC_write) {
5225 } ErrorFound = NoError;
5226 SourceLocation ErrorLoc, NoteLoc;
5227 SourceRange ErrorRange, NoteRange;
5228 // If clause is write:
5230 if (auto *AtomicBody = dyn_cast<Expr>(Body)) {
5232 dyn_cast<BinaryOperator>(AtomicBody->IgnoreParenImpCasts());
5233 if (AtomicBinOp && AtomicBinOp->getOpcode() == BO_Assign) {
5234 X = AtomicBinOp->getLHS();
5235 E = AtomicBinOp->getRHS();
5236 if ((X->isInstantiationDependent() || X->getType()->isScalarType()) &&
5237 (E->isInstantiationDependent() || E->getType()->isScalarType())) {
5238 if (!X->isLValue()) {
5239 ErrorFound = NotAnLValue;
5240 ErrorLoc = AtomicBinOp->getExprLoc();
5241 ErrorRange = AtomicBinOp->getSourceRange();
5242 NoteLoc = X->getExprLoc();
5243 NoteRange = X->getSourceRange();
5245 } else if (!X->isInstantiationDependent() ||
5246 !E->isInstantiationDependent()) {
5247 auto NotScalarExpr =
5248 (X->isInstantiationDependent() || X->getType()->isScalarType())
5251 ErrorFound = NotAScalarType;
5252 ErrorLoc = AtomicBinOp->getExprLoc();
5253 ErrorRange = AtomicBinOp->getSourceRange();
5254 NoteLoc = NotScalarExpr->getExprLoc();
5255 NoteRange = NotScalarExpr->getSourceRange();
5257 } else if (!AtomicBody->isInstantiationDependent()) {
5258 ErrorFound = NotAnAssignmentOp;
5259 ErrorLoc = AtomicBody->getExprLoc();
5260 ErrorRange = AtomicBody->getSourceRange();
5261 NoteLoc = AtomicBinOp ? AtomicBinOp->getOperatorLoc()
5262 : AtomicBody->getExprLoc();
5263 NoteRange = AtomicBinOp ? AtomicBinOp->getSourceRange()
5264 : AtomicBody->getSourceRange();
5267 ErrorFound = NotAnExpression;
5268 NoteLoc = ErrorLoc = Body->getLocStart();
5269 NoteRange = ErrorRange = SourceRange(NoteLoc, NoteLoc);
5271 if (ErrorFound != NoError) {
5272 Diag(ErrorLoc, diag::err_omp_atomic_write_not_expression_statement)
5274 Diag(NoteLoc, diag::note_omp_atomic_read_write) << ErrorFound
5277 } else if (CurContext->isDependentContext())
5279 } else if (AtomicKind == OMPC_update || AtomicKind == OMPC_unknown) {
5280 // If clause is update:
5286 // x = x binop expr;
5287 // x = expr binop x;
5288 OpenMPAtomicUpdateChecker Checker(*this);
5289 if (Checker.checkStatement(
5290 Body, (AtomicKind == OMPC_update)
5291 ? diag::err_omp_atomic_update_not_expression_statement
5292 : diag::err_omp_atomic_not_expression_statement,
5293 diag::note_omp_atomic_update))
5295 if (!CurContext->isDependentContext()) {
5296 E = Checker.getExpr();
5298 UE = Checker.getUpdateExpr();
5299 IsXLHSInRHSPart = Checker.isXLHSInRHSPart();
5301 } else if (AtomicKind == OMPC_capture) {
5304 NotACompoundStatement,
5305 NotTwoSubstatements,
5306 NotASpecificExpression,
5308 } ErrorFound = NoError;
5309 SourceLocation ErrorLoc, NoteLoc;
5310 SourceRange ErrorRange, NoteRange;
5311 if (auto *AtomicBody = dyn_cast<Expr>(Body)) {
5312 // If clause is a capture:
5317 // v = x binop= expr;
5318 // v = x = x binop expr;
5319 // v = x = expr binop x;
5321 dyn_cast<BinaryOperator>(AtomicBody->IgnoreParenImpCasts());
5322 if (AtomicBinOp && AtomicBinOp->getOpcode() == BO_Assign) {
5323 V = AtomicBinOp->getLHS();
5324 Body = AtomicBinOp->getRHS()->IgnoreParenImpCasts();
5325 OpenMPAtomicUpdateChecker Checker(*this);
5326 if (Checker.checkStatement(
5327 Body, diag::err_omp_atomic_capture_not_expression_statement,
5328 diag::note_omp_atomic_update))
5330 E = Checker.getExpr();
5332 UE = Checker.getUpdateExpr();
5333 IsXLHSInRHSPart = Checker.isXLHSInRHSPart();
5334 IsPostfixUpdate = Checker.isPostfixUpdate();
5335 } else if (!AtomicBody->isInstantiationDependent()) {
5336 ErrorLoc = AtomicBody->getExprLoc();
5337 ErrorRange = AtomicBody->getSourceRange();
5338 NoteLoc = AtomicBinOp ? AtomicBinOp->getOperatorLoc()
5339 : AtomicBody->getExprLoc();
5340 NoteRange = AtomicBinOp ? AtomicBinOp->getSourceRange()
5341 : AtomicBody->getSourceRange();
5342 ErrorFound = NotAnAssignmentOp;
5344 if (ErrorFound != NoError) {
5345 Diag(ErrorLoc, diag::err_omp_atomic_capture_not_expression_statement)
5347 Diag(NoteLoc, diag::note_omp_atomic_capture) << ErrorFound << NoteRange;
5349 } else if (CurContext->isDependentContext()) {
5350 UE = V = E = X = nullptr;
5353 // If clause is a capture:
5354 // { v = x; x = expr; }
5359 // { v = x; x binop= expr; }
5360 // { v = x; x = x binop expr; }
5361 // { v = x; x = expr binop x; }
5366 // { x binop= expr; v = x; }
5367 // { x = x binop expr; v = x; }
5368 // { x = expr binop x; v = x; }
5369 if (auto *CS = dyn_cast<CompoundStmt>(Body)) {
5370 // Check that this is { expr1; expr2; }
5371 if (CS->size() == 2) {
5372 auto *First = CS->body_front();
5373 auto *Second = CS->body_back();
5374 if (auto *EWC = dyn_cast<ExprWithCleanups>(First))
5375 First = EWC->getSubExpr()->IgnoreParenImpCasts();
5376 if (auto *EWC = dyn_cast<ExprWithCleanups>(Second))
5377 Second = EWC->getSubExpr()->IgnoreParenImpCasts();
5378 // Need to find what subexpression is 'v' and what is 'x'.
5379 OpenMPAtomicUpdateChecker Checker(*this);
5380 bool IsUpdateExprFound = !Checker.checkStatement(Second);
5381 BinaryOperator *BinOp = nullptr;
5382 if (IsUpdateExprFound) {
5383 BinOp = dyn_cast<BinaryOperator>(First);
5384 IsUpdateExprFound = BinOp && BinOp->getOpcode() == BO_Assign;
5386 if (IsUpdateExprFound && !CurContext->isDependentContext()) {
5391 // { v = x; x binop= expr; }
5392 // { v = x; x = x binop expr; }
5393 // { v = x; x = expr binop x; }
5394 // Check that the first expression has form v = x.
5395 auto *PossibleX = BinOp->getRHS()->IgnoreParenImpCasts();
5396 llvm::FoldingSetNodeID XId, PossibleXId;
5397 Checker.getX()->Profile(XId, Context, /*Canonical=*/true);
5398 PossibleX->Profile(PossibleXId, Context, /*Canonical=*/true);
5399 IsUpdateExprFound = XId == PossibleXId;
5400 if (IsUpdateExprFound) {
5401 V = BinOp->getLHS();
5403 E = Checker.getExpr();
5404 UE = Checker.getUpdateExpr();
5405 IsXLHSInRHSPart = Checker.isXLHSInRHSPart();
5406 IsPostfixUpdate = true;
5409 if (!IsUpdateExprFound) {
5410 IsUpdateExprFound = !Checker.checkStatement(First);
5412 if (IsUpdateExprFound) {
5413 BinOp = dyn_cast<BinaryOperator>(Second);
5414 IsUpdateExprFound = BinOp && BinOp->getOpcode() == BO_Assign;
5416 if (IsUpdateExprFound && !CurContext->isDependentContext()) {
5421 // { x binop= expr; v = x; }
5422 // { x = x binop expr; v = x; }
5423 // { x = expr binop x; v = x; }
5424 // Check that the second expression has form v = x.
5425 auto *PossibleX = BinOp->getRHS()->IgnoreParenImpCasts();
5426 llvm::FoldingSetNodeID XId, PossibleXId;
5427 Checker.getX()->Profile(XId, Context, /*Canonical=*/true);
5428 PossibleX->Profile(PossibleXId, Context, /*Canonical=*/true);
5429 IsUpdateExprFound = XId == PossibleXId;
5430 if (IsUpdateExprFound) {
5431 V = BinOp->getLHS();
5433 E = Checker.getExpr();
5434 UE = Checker.getUpdateExpr();
5435 IsXLHSInRHSPart = Checker.isXLHSInRHSPart();
5436 IsPostfixUpdate = false;
5440 if (!IsUpdateExprFound) {
5441 // { v = x; x = expr; }
5442 auto *FirstExpr = dyn_cast<Expr>(First);
5443 auto *SecondExpr = dyn_cast<Expr>(Second);
5444 if (!FirstExpr || !SecondExpr ||
5445 !(FirstExpr->isInstantiationDependent() ||
5446 SecondExpr->isInstantiationDependent())) {
5447 auto *FirstBinOp = dyn_cast<BinaryOperator>(First);
5448 if (!FirstBinOp || FirstBinOp->getOpcode() != BO_Assign) {
5449 ErrorFound = NotAnAssignmentOp;
5450 NoteLoc = ErrorLoc = FirstBinOp ? FirstBinOp->getOperatorLoc()
5451 : First->getLocStart();
5452 NoteRange = ErrorRange = FirstBinOp
5453 ? FirstBinOp->getSourceRange()
5454 : SourceRange(ErrorLoc, ErrorLoc);
5456 auto *SecondBinOp = dyn_cast<BinaryOperator>(Second);
5457 if (!SecondBinOp || SecondBinOp->getOpcode() != BO_Assign) {
5458 ErrorFound = NotAnAssignmentOp;
5459 NoteLoc = ErrorLoc = SecondBinOp
5460 ? SecondBinOp->getOperatorLoc()
5461 : Second->getLocStart();
5462 NoteRange = ErrorRange =
5463 SecondBinOp ? SecondBinOp->getSourceRange()
5464 : SourceRange(ErrorLoc, ErrorLoc);
5466 auto *PossibleXRHSInFirst =
5467 FirstBinOp->getRHS()->IgnoreParenImpCasts();
5468 auto *PossibleXLHSInSecond =
5469 SecondBinOp->getLHS()->IgnoreParenImpCasts();
5470 llvm::FoldingSetNodeID X1Id, X2Id;
5471 PossibleXRHSInFirst->Profile(X1Id, Context,
5472 /*Canonical=*/true);
5473 PossibleXLHSInSecond->Profile(X2Id, Context,
5474 /*Canonical=*/true);
5475 IsUpdateExprFound = X1Id == X2Id;
5476 if (IsUpdateExprFound) {
5477 V = FirstBinOp->getLHS();
5478 X = SecondBinOp->getLHS();
5479 E = SecondBinOp->getRHS();
5481 IsXLHSInRHSPart = false;
5482 IsPostfixUpdate = true;
5484 ErrorFound = NotASpecificExpression;
5485 ErrorLoc = FirstBinOp->getExprLoc();
5486 ErrorRange = FirstBinOp->getSourceRange();
5487 NoteLoc = SecondBinOp->getLHS()->getExprLoc();
5488 NoteRange = SecondBinOp->getRHS()->getSourceRange();
5495 NoteLoc = ErrorLoc = Body->getLocStart();
5496 NoteRange = ErrorRange =
5497 SourceRange(Body->getLocStart(), Body->getLocStart());
5498 ErrorFound = NotTwoSubstatements;
5501 NoteLoc = ErrorLoc = Body->getLocStart();
5502 NoteRange = ErrorRange =
5503 SourceRange(Body->getLocStart(), Body->getLocStart());
5504 ErrorFound = NotACompoundStatement;
5506 if (ErrorFound != NoError) {
5507 Diag(ErrorLoc, diag::err_omp_atomic_capture_not_compound_statement)
5509 Diag(NoteLoc, diag::note_omp_atomic_capture) << ErrorFound << NoteRange;
5511 } else if (CurContext->isDependentContext()) {
5512 UE = V = E = X = nullptr;
5517 getCurFunction()->setHasBranchProtectedScope();
5519 return OMPAtomicDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt,
5520 X, V, E, UE, IsXLHSInRHSPart,
5524 StmtResult Sema::ActOnOpenMPTargetDirective(ArrayRef<OMPClause *> Clauses,
5526 SourceLocation StartLoc,
5527 SourceLocation EndLoc) {
5531 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
5532 // 1.2.2 OpenMP Language Terminology
5533 // Structured block - An executable statement with a single entry at the
5534 // top and a single exit at the bottom.
5535 // The point of exit cannot be a branch out of the structured block.
5536 // longjmp() and throw() must not violate the entry/exit criteria.
5537 CS->getCapturedDecl()->setNothrow();
5539 // OpenMP [2.16, Nesting of Regions]
5540 // If specified, a teams construct must be contained within a target
5541 // construct. That target construct must contain no statements or directives
5542 // outside of the teams construct.
5543 if (DSAStack->hasInnerTeamsRegion()) {
5544 auto S = AStmt->IgnoreContainers(/*IgnoreCaptured*/ true);
5545 bool OMPTeamsFound = true;
5546 if (auto *CS = dyn_cast<CompoundStmt>(S)) {
5547 auto I = CS->body_begin();
5548 while (I != CS->body_end()) {
5549 auto *OED = dyn_cast<OMPExecutableDirective>(*I);
5550 if (!OED || !isOpenMPTeamsDirective(OED->getDirectiveKind())) {
5551 OMPTeamsFound = false;
5556 assert(I != CS->body_end() && "Not found statement");
5559 auto *OED = dyn_cast<OMPExecutableDirective>(S);
5560 OMPTeamsFound = OED && isOpenMPTeamsDirective(OED->getDirectiveKind());
5562 if (!OMPTeamsFound) {
5563 Diag(StartLoc, diag::err_omp_target_contains_not_only_teams);
5564 Diag(DSAStack->getInnerTeamsRegionLoc(),
5565 diag::note_omp_nested_teams_construct_here);
5566 Diag(S->getLocStart(), diag::note_omp_nested_statement_here)
5567 << isa<OMPExecutableDirective>(S);
5572 getCurFunction()->setHasBranchProtectedScope();
5574 return OMPTargetDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt);
5578 Sema::ActOnOpenMPTargetParallelDirective(ArrayRef<OMPClause *> Clauses,
5579 Stmt *AStmt, SourceLocation StartLoc,
5580 SourceLocation EndLoc) {
5584 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
5585 // 1.2.2 OpenMP Language Terminology
5586 // Structured block - An executable statement with a single entry at the
5587 // top and a single exit at the bottom.
5588 // The point of exit cannot be a branch out of the structured block.
5589 // longjmp() and throw() must not violate the entry/exit criteria.
5590 CS->getCapturedDecl()->setNothrow();
5592 getCurFunction()->setHasBranchProtectedScope();
5594 return OMPTargetParallelDirective::Create(Context, StartLoc, EndLoc, Clauses,
5598 StmtResult Sema::ActOnOpenMPTargetParallelForDirective(
5599 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
5600 SourceLocation EndLoc,
5601 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
5605 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
5606 // 1.2.2 OpenMP Language Terminology
5607 // Structured block - An executable statement with a single entry at the
5608 // top and a single exit at the bottom.
5609 // The point of exit cannot be a branch out of the structured block.
5610 // longjmp() and throw() must not violate the entry/exit criteria.
5611 CS->getCapturedDecl()->setNothrow();
5613 OMPLoopDirective::HelperExprs B;
5614 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
5615 // define the nested loops number.
5616 unsigned NestedLoopCount =
5617 CheckOpenMPLoop(OMPD_target_parallel_for, getCollapseNumberExpr(Clauses),
5618 getOrderedNumberExpr(Clauses), AStmt, *this, *DSAStack,
5619 VarsWithImplicitDSA, B);
5620 if (NestedLoopCount == 0)
5623 assert((CurContext->isDependentContext() || B.builtAll()) &&
5624 "omp target parallel for loop exprs were not built");
5626 if (!CurContext->isDependentContext()) {
5627 // Finalize the clauses that need pre-built expressions for CodeGen.
5628 for (auto C : Clauses) {
5629 if (auto *LC = dyn_cast<OMPLinearClause>(C))
5630 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
5631 B.NumIterations, *this, CurScope,
5637 getCurFunction()->setHasBranchProtectedScope();
5638 return OMPTargetParallelForDirective::Create(Context, StartLoc, EndLoc,
5639 NestedLoopCount, Clauses, AStmt,
5640 B, DSAStack->isCancelRegion());
5643 /// \brief Check for existence of a map clause in the list of clauses.
5644 static bool HasMapClause(ArrayRef<OMPClause *> Clauses) {
5645 for (ArrayRef<OMPClause *>::iterator I = Clauses.begin(), E = Clauses.end();
5647 if (*I != nullptr && (*I)->getClauseKind() == OMPC_map) {
5655 StmtResult Sema::ActOnOpenMPTargetDataDirective(ArrayRef<OMPClause *> Clauses,
5657 SourceLocation StartLoc,
5658 SourceLocation EndLoc) {
5662 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
5664 // OpenMP [2.10.1, Restrictions, p. 97]
5665 // At least one map clause must appear on the directive.
5666 if (!HasMapClause(Clauses)) {
5667 Diag(StartLoc, diag::err_omp_no_map_for_directive)
5668 << getOpenMPDirectiveName(OMPD_target_data);
5672 getCurFunction()->setHasBranchProtectedScope();
5674 return OMPTargetDataDirective::Create(Context, StartLoc, EndLoc, Clauses,
5679 Sema::ActOnOpenMPTargetEnterDataDirective(ArrayRef<OMPClause *> Clauses,
5680 SourceLocation StartLoc,
5681 SourceLocation EndLoc) {
5682 // OpenMP [2.10.2, Restrictions, p. 99]
5683 // At least one map clause must appear on the directive.
5684 if (!HasMapClause(Clauses)) {
5685 Diag(StartLoc, diag::err_omp_no_map_for_directive)
5686 << getOpenMPDirectiveName(OMPD_target_enter_data);
5690 return OMPTargetEnterDataDirective::Create(Context, StartLoc, EndLoc,
5695 Sema::ActOnOpenMPTargetExitDataDirective(ArrayRef<OMPClause *> Clauses,
5696 SourceLocation StartLoc,
5697 SourceLocation EndLoc) {
5698 // OpenMP [2.10.3, Restrictions, p. 102]
5699 // At least one map clause must appear on the directive.
5700 if (!HasMapClause(Clauses)) {
5701 Diag(StartLoc, diag::err_omp_no_map_for_directive)
5702 << getOpenMPDirectiveName(OMPD_target_exit_data);
5706 return OMPTargetExitDataDirective::Create(Context, StartLoc, EndLoc, Clauses);
5709 StmtResult Sema::ActOnOpenMPTargetUpdateDirective(ArrayRef<OMPClause *> Clauses,
5710 SourceLocation StartLoc,
5711 SourceLocation EndLoc) {
5712 bool seenMotionClause = false;
5713 for (auto *C : Clauses) {
5714 if (C->getClauseKind() == OMPC_to || C->getClauseKind() == OMPC_from)
5715 seenMotionClause = true;
5717 if (!seenMotionClause) {
5718 Diag(StartLoc, diag::err_omp_at_least_one_motion_clause_required);
5721 return OMPTargetUpdateDirective::Create(Context, StartLoc, EndLoc, Clauses);
5724 StmtResult Sema::ActOnOpenMPTeamsDirective(ArrayRef<OMPClause *> Clauses,
5725 Stmt *AStmt, SourceLocation StartLoc,
5726 SourceLocation EndLoc) {
5730 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
5731 // 1.2.2 OpenMP Language Terminology
5732 // Structured block - An executable statement with a single entry at the
5733 // top and a single exit at the bottom.
5734 // The point of exit cannot be a branch out of the structured block.
5735 // longjmp() and throw() must not violate the entry/exit criteria.
5736 CS->getCapturedDecl()->setNothrow();
5738 getCurFunction()->setHasBranchProtectedScope();
5740 return OMPTeamsDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt);
5744 Sema::ActOnOpenMPCancellationPointDirective(SourceLocation StartLoc,
5745 SourceLocation EndLoc,
5746 OpenMPDirectiveKind CancelRegion) {
5747 if (CancelRegion != OMPD_parallel && CancelRegion != OMPD_for &&
5748 CancelRegion != OMPD_sections && CancelRegion != OMPD_taskgroup) {
5749 Diag(StartLoc, diag::err_omp_wrong_cancel_region)
5750 << getOpenMPDirectiveName(CancelRegion);
5753 if (DSAStack->isParentNowaitRegion()) {
5754 Diag(StartLoc, diag::err_omp_parent_cancel_region_nowait) << 0;
5757 if (DSAStack->isParentOrderedRegion()) {
5758 Diag(StartLoc, diag::err_omp_parent_cancel_region_ordered) << 0;
5761 return OMPCancellationPointDirective::Create(Context, StartLoc, EndLoc,
5765 StmtResult Sema::ActOnOpenMPCancelDirective(ArrayRef<OMPClause *> Clauses,
5766 SourceLocation StartLoc,
5767 SourceLocation EndLoc,
5768 OpenMPDirectiveKind CancelRegion) {
5769 if (CancelRegion != OMPD_parallel && CancelRegion != OMPD_for &&
5770 CancelRegion != OMPD_sections && CancelRegion != OMPD_taskgroup) {
5771 Diag(StartLoc, diag::err_omp_wrong_cancel_region)
5772 << getOpenMPDirectiveName(CancelRegion);
5775 if (DSAStack->isParentNowaitRegion()) {
5776 Diag(StartLoc, diag::err_omp_parent_cancel_region_nowait) << 1;
5779 if (DSAStack->isParentOrderedRegion()) {
5780 Diag(StartLoc, diag::err_omp_parent_cancel_region_ordered) << 1;
5783 DSAStack->setParentCancelRegion(/*Cancel=*/true);
5784 return OMPCancelDirective::Create(Context, StartLoc, EndLoc, Clauses,
5788 static bool checkGrainsizeNumTasksClauses(Sema &S,
5789 ArrayRef<OMPClause *> Clauses) {
5790 OMPClause *PrevClause = nullptr;
5791 bool ErrorFound = false;
5792 for (auto *C : Clauses) {
5793 if (C->getClauseKind() == OMPC_grainsize ||
5794 C->getClauseKind() == OMPC_num_tasks) {
5797 else if (PrevClause->getClauseKind() != C->getClauseKind()) {
5798 S.Diag(C->getLocStart(),
5799 diag::err_omp_grainsize_num_tasks_mutually_exclusive)
5800 << getOpenMPClauseName(C->getClauseKind())
5801 << getOpenMPClauseName(PrevClause->getClauseKind());
5802 S.Diag(PrevClause->getLocStart(),
5803 diag::note_omp_previous_grainsize_num_tasks)
5804 << getOpenMPClauseName(PrevClause->getClauseKind());
5812 StmtResult Sema::ActOnOpenMPTaskLoopDirective(
5813 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
5814 SourceLocation EndLoc,
5815 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
5819 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
5820 OMPLoopDirective::HelperExprs B;
5821 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
5822 // define the nested loops number.
5823 unsigned NestedLoopCount =
5824 CheckOpenMPLoop(OMPD_taskloop, getCollapseNumberExpr(Clauses),
5825 /*OrderedLoopCountExpr=*/nullptr, AStmt, *this, *DSAStack,
5826 VarsWithImplicitDSA, B);
5827 if (NestedLoopCount == 0)
5830 assert((CurContext->isDependentContext() || B.builtAll()) &&
5831 "omp for loop exprs were not built");
5833 // OpenMP, [2.9.2 taskloop Construct, Restrictions]
5834 // The grainsize clause and num_tasks clause are mutually exclusive and may
5835 // not appear on the same taskloop directive.
5836 if (checkGrainsizeNumTasksClauses(*this, Clauses))
5839 getCurFunction()->setHasBranchProtectedScope();
5840 return OMPTaskLoopDirective::Create(Context, StartLoc, EndLoc,
5841 NestedLoopCount, Clauses, AStmt, B);
5844 StmtResult Sema::ActOnOpenMPTaskLoopSimdDirective(
5845 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
5846 SourceLocation EndLoc,
5847 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
5851 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
5852 OMPLoopDirective::HelperExprs B;
5853 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
5854 // define the nested loops number.
5855 unsigned NestedLoopCount =
5856 CheckOpenMPLoop(OMPD_taskloop_simd, getCollapseNumberExpr(Clauses),
5857 /*OrderedLoopCountExpr=*/nullptr, AStmt, *this, *DSAStack,
5858 VarsWithImplicitDSA, B);
5859 if (NestedLoopCount == 0)
5862 assert((CurContext->isDependentContext() || B.builtAll()) &&
5863 "omp for loop exprs were not built");
5865 if (!CurContext->isDependentContext()) {
5866 // Finalize the clauses that need pre-built expressions for CodeGen.
5867 for (auto C : Clauses) {
5868 if (auto *LC = dyn_cast<OMPLinearClause>(C))
5869 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
5870 B.NumIterations, *this, CurScope,
5876 // OpenMP, [2.9.2 taskloop Construct, Restrictions]
5877 // The grainsize clause and num_tasks clause are mutually exclusive and may
5878 // not appear on the same taskloop directive.
5879 if (checkGrainsizeNumTasksClauses(*this, Clauses))
5882 getCurFunction()->setHasBranchProtectedScope();
5883 return OMPTaskLoopSimdDirective::Create(Context, StartLoc, EndLoc,
5884 NestedLoopCount, Clauses, AStmt, B);
5887 StmtResult Sema::ActOnOpenMPDistributeDirective(
5888 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
5889 SourceLocation EndLoc,
5890 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
5894 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
5895 OMPLoopDirective::HelperExprs B;
5896 // In presence of clause 'collapse' with number of loops, it will
5897 // define the nested loops number.
5898 unsigned NestedLoopCount =
5899 CheckOpenMPLoop(OMPD_distribute, getCollapseNumberExpr(Clauses),
5900 nullptr /*ordered not a clause on distribute*/, AStmt,
5901 *this, *DSAStack, VarsWithImplicitDSA, B);
5902 if (NestedLoopCount == 0)
5905 assert((CurContext->isDependentContext() || B.builtAll()) &&
5906 "omp for loop exprs were not built");
5908 getCurFunction()->setHasBranchProtectedScope();
5909 return OMPDistributeDirective::Create(Context, StartLoc, EndLoc,
5910 NestedLoopCount, Clauses, AStmt, B);
5913 StmtResult Sema::ActOnOpenMPDistributeParallelForDirective(
5914 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
5915 SourceLocation EndLoc,
5916 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
5920 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
5921 // 1.2.2 OpenMP Language Terminology
5922 // Structured block - An executable statement with a single entry at the
5923 // top and a single exit at the bottom.
5924 // The point of exit cannot be a branch out of the structured block.
5925 // longjmp() and throw() must not violate the entry/exit criteria.
5926 CS->getCapturedDecl()->setNothrow();
5928 OMPLoopDirective::HelperExprs B;
5929 // In presence of clause 'collapse' with number of loops, it will
5930 // define the nested loops number.
5931 unsigned NestedLoopCount = CheckOpenMPLoop(
5932 OMPD_distribute_parallel_for, getCollapseNumberExpr(Clauses),
5933 nullptr /*ordered not a clause on distribute*/, AStmt, *this, *DSAStack,
5934 VarsWithImplicitDSA, B);
5935 if (NestedLoopCount == 0)
5938 assert((CurContext->isDependentContext() || B.builtAll()) &&
5939 "omp for loop exprs were not built");
5941 getCurFunction()->setHasBranchProtectedScope();
5942 return OMPDistributeParallelForDirective::Create(
5943 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
5946 StmtResult Sema::ActOnOpenMPDistributeParallelForSimdDirective(
5947 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
5948 SourceLocation EndLoc,
5949 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
5953 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
5954 // 1.2.2 OpenMP Language Terminology
5955 // Structured block - An executable statement with a single entry at the
5956 // top and a single exit at the bottom.
5957 // The point of exit cannot be a branch out of the structured block.
5958 // longjmp() and throw() must not violate the entry/exit criteria.
5959 CS->getCapturedDecl()->setNothrow();
5961 OMPLoopDirective::HelperExprs B;
5962 // In presence of clause 'collapse' with number of loops, it will
5963 // define the nested loops number.
5964 unsigned NestedLoopCount = CheckOpenMPLoop(
5965 OMPD_distribute_parallel_for_simd, getCollapseNumberExpr(Clauses),
5966 nullptr /*ordered not a clause on distribute*/, AStmt, *this, *DSAStack,
5967 VarsWithImplicitDSA, B);
5968 if (NestedLoopCount == 0)
5971 assert((CurContext->isDependentContext() || B.builtAll()) &&
5972 "omp for loop exprs were not built");
5974 if (checkSimdlenSafelenSpecified(*this, Clauses))
5977 getCurFunction()->setHasBranchProtectedScope();
5978 return OMPDistributeParallelForSimdDirective::Create(
5979 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
5982 StmtResult Sema::ActOnOpenMPDistributeSimdDirective(
5983 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
5984 SourceLocation EndLoc,
5985 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
5989 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
5990 // 1.2.2 OpenMP Language Terminology
5991 // Structured block - An executable statement with a single entry at the
5992 // top and a single exit at the bottom.
5993 // The point of exit cannot be a branch out of the structured block.
5994 // longjmp() and throw() must not violate the entry/exit criteria.
5995 CS->getCapturedDecl()->setNothrow();
5997 OMPLoopDirective::HelperExprs B;
5998 // In presence of clause 'collapse' with number of loops, it will
5999 // define the nested loops number.
6000 unsigned NestedLoopCount =
6001 CheckOpenMPLoop(OMPD_distribute_simd, getCollapseNumberExpr(Clauses),
6002 nullptr /*ordered not a clause on distribute*/, AStmt,
6003 *this, *DSAStack, VarsWithImplicitDSA, B);
6004 if (NestedLoopCount == 0)
6007 assert((CurContext->isDependentContext() || B.builtAll()) &&
6008 "omp for loop exprs were not built");
6010 if (checkSimdlenSafelenSpecified(*this, Clauses))
6013 getCurFunction()->setHasBranchProtectedScope();
6014 return OMPDistributeSimdDirective::Create(Context, StartLoc, EndLoc,
6015 NestedLoopCount, Clauses, AStmt, B);
6018 StmtResult Sema::ActOnOpenMPTargetParallelForSimdDirective(
6019 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
6020 SourceLocation EndLoc,
6021 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
6025 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
6026 // 1.2.2 OpenMP Language Terminology
6027 // Structured block - An executable statement with a single entry at the
6028 // top and a single exit at the bottom.
6029 // The point of exit cannot be a branch out of the structured block.
6030 // longjmp() and throw() must not violate the entry/exit criteria.
6031 CS->getCapturedDecl()->setNothrow();
6033 OMPLoopDirective::HelperExprs B;
6034 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
6035 // define the nested loops number.
6036 unsigned NestedLoopCount = CheckOpenMPLoop(
6037 OMPD_target_parallel_for_simd, getCollapseNumberExpr(Clauses),
6038 getOrderedNumberExpr(Clauses), AStmt, *this, *DSAStack,
6039 VarsWithImplicitDSA, B);
6040 if (NestedLoopCount == 0)
6043 assert((CurContext->isDependentContext() || B.builtAll()) &&
6044 "omp target parallel for simd loop exprs were not built");
6046 if (!CurContext->isDependentContext()) {
6047 // Finalize the clauses that need pre-built expressions for CodeGen.
6048 for (auto C : Clauses) {
6049 if (auto *LC = dyn_cast<OMPLinearClause>(C))
6050 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
6051 B.NumIterations, *this, CurScope,
6056 if (checkSimdlenSafelenSpecified(*this, Clauses))
6059 getCurFunction()->setHasBranchProtectedScope();
6060 return OMPTargetParallelForSimdDirective::Create(
6061 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
6064 StmtResult Sema::ActOnOpenMPTargetSimdDirective(
6065 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
6066 SourceLocation EndLoc,
6067 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
6071 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
6072 // 1.2.2 OpenMP Language Terminology
6073 // Structured block - An executable statement with a single entry at the
6074 // top and a single exit at the bottom.
6075 // The point of exit cannot be a branch out of the structured block.
6076 // longjmp() and throw() must not violate the entry/exit criteria.
6077 CS->getCapturedDecl()->setNothrow();
6079 OMPLoopDirective::HelperExprs B;
6080 // In presence of clause 'collapse' with number of loops, it will define the
6081 // nested loops number.
6082 unsigned NestedLoopCount =
6083 CheckOpenMPLoop(OMPD_target_simd, getCollapseNumberExpr(Clauses),
6084 getOrderedNumberExpr(Clauses), AStmt, *this, *DSAStack,
6085 VarsWithImplicitDSA, B);
6086 if (NestedLoopCount == 0)
6089 assert((CurContext->isDependentContext() || B.builtAll()) &&
6090 "omp target simd loop exprs were not built");
6092 if (!CurContext->isDependentContext()) {
6093 // Finalize the clauses that need pre-built expressions for CodeGen.
6094 for (auto C : Clauses) {
6095 if (auto *LC = dyn_cast<OMPLinearClause>(C))
6096 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
6097 B.NumIterations, *this, CurScope,
6103 if (checkSimdlenSafelenSpecified(*this, Clauses))
6106 getCurFunction()->setHasBranchProtectedScope();
6107 return OMPTargetSimdDirective::Create(Context, StartLoc, EndLoc,
6108 NestedLoopCount, Clauses, AStmt, B);
6111 StmtResult Sema::ActOnOpenMPTeamsDistributeDirective(
6112 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
6113 SourceLocation EndLoc,
6114 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
6118 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
6119 // 1.2.2 OpenMP Language Terminology
6120 // Structured block - An executable statement with a single entry at the
6121 // top and a single exit at the bottom.
6122 // The point of exit cannot be a branch out of the structured block.
6123 // longjmp() and throw() must not violate the entry/exit criteria.
6124 CS->getCapturedDecl()->setNothrow();
6126 OMPLoopDirective::HelperExprs B;
6127 // In presence of clause 'collapse' with number of loops, it will
6128 // define the nested loops number.
6129 unsigned NestedLoopCount =
6130 CheckOpenMPLoop(OMPD_teams_distribute, getCollapseNumberExpr(Clauses),
6131 nullptr /*ordered not a clause on distribute*/, AStmt,
6132 *this, *DSAStack, VarsWithImplicitDSA, B);
6133 if (NestedLoopCount == 0)
6136 assert((CurContext->isDependentContext() || B.builtAll()) &&
6137 "omp teams distribute loop exprs were not built");
6139 getCurFunction()->setHasBranchProtectedScope();
6140 return OMPTeamsDistributeDirective::Create(
6141 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
6144 StmtResult Sema::ActOnOpenMPTeamsDistributeSimdDirective(
6145 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
6146 SourceLocation EndLoc,
6147 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
6151 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
6152 // 1.2.2 OpenMP Language Terminology
6153 // Structured block - An executable statement with a single entry at the
6154 // top and a single exit at the bottom.
6155 // The point of exit cannot be a branch out of the structured block.
6156 // longjmp() and throw() must not violate the entry/exit criteria.
6157 CS->getCapturedDecl()->setNothrow();
6159 OMPLoopDirective::HelperExprs B;
6160 // In presence of clause 'collapse' with number of loops, it will
6161 // define the nested loops number.
6162 unsigned NestedLoopCount = CheckOpenMPLoop(
6163 OMPD_teams_distribute_simd, getCollapseNumberExpr(Clauses),
6164 nullptr /*ordered not a clause on distribute*/, AStmt, *this, *DSAStack,
6165 VarsWithImplicitDSA, B);
6167 if (NestedLoopCount == 0)
6170 assert((CurContext->isDependentContext() || B.builtAll()) &&
6171 "omp teams distribute simd loop exprs were not built");
6173 if (!CurContext->isDependentContext()) {
6174 // Finalize the clauses that need pre-built expressions for CodeGen.
6175 for (auto C : Clauses) {
6176 if (auto *LC = dyn_cast<OMPLinearClause>(C))
6177 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
6178 B.NumIterations, *this, CurScope,
6184 if (checkSimdlenSafelenSpecified(*this, Clauses))
6187 getCurFunction()->setHasBranchProtectedScope();
6188 return OMPTeamsDistributeSimdDirective::Create(
6189 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
6192 StmtResult Sema::ActOnOpenMPTeamsDistributeParallelForSimdDirective(
6193 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
6194 SourceLocation EndLoc,
6195 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
6199 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
6200 // 1.2.2 OpenMP Language Terminology
6201 // Structured block - An executable statement with a single entry at the
6202 // top and a single exit at the bottom.
6203 // The point of exit cannot be a branch out of the structured block.
6204 // longjmp() and throw() must not violate the entry/exit criteria.
6205 CS->getCapturedDecl()->setNothrow();
6207 OMPLoopDirective::HelperExprs B;
6208 // In presence of clause 'collapse' with number of loops, it will
6209 // define the nested loops number.
6210 auto NestedLoopCount = CheckOpenMPLoop(
6211 OMPD_teams_distribute_parallel_for_simd, getCollapseNumberExpr(Clauses),
6212 nullptr /*ordered not a clause on distribute*/, AStmt, *this, *DSAStack,
6213 VarsWithImplicitDSA, B);
6215 if (NestedLoopCount == 0)
6218 assert((CurContext->isDependentContext() || B.builtAll()) &&
6219 "omp for loop exprs were not built");
6221 if (!CurContext->isDependentContext()) {
6222 // Finalize the clauses that need pre-built expressions for CodeGen.
6223 for (auto C : Clauses) {
6224 if (auto *LC = dyn_cast<OMPLinearClause>(C))
6225 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
6226 B.NumIterations, *this, CurScope,
6232 if (checkSimdlenSafelenSpecified(*this, Clauses))
6235 getCurFunction()->setHasBranchProtectedScope();
6236 return OMPTeamsDistributeParallelForSimdDirective::Create(
6237 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
6240 StmtResult Sema::ActOnOpenMPTeamsDistributeParallelForDirective(
6241 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
6242 SourceLocation EndLoc,
6243 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
6247 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
6248 // 1.2.2 OpenMP Language Terminology
6249 // Structured block - An executable statement with a single entry at the
6250 // top and a single exit at the bottom.
6251 // The point of exit cannot be a branch out of the structured block.
6252 // longjmp() and throw() must not violate the entry/exit criteria.
6253 CS->getCapturedDecl()->setNothrow();
6255 OMPLoopDirective::HelperExprs B;
6256 // In presence of clause 'collapse' with number of loops, it will
6257 // define the nested loops number.
6258 unsigned NestedLoopCount = CheckOpenMPLoop(
6259 OMPD_teams_distribute_parallel_for, getCollapseNumberExpr(Clauses),
6260 nullptr /*ordered not a clause on distribute*/, AStmt, *this, *DSAStack,
6261 VarsWithImplicitDSA, B);
6263 if (NestedLoopCount == 0)
6266 assert((CurContext->isDependentContext() || B.builtAll()) &&
6267 "omp for loop exprs were not built");
6269 if (!CurContext->isDependentContext()) {
6270 // Finalize the clauses that need pre-built expressions for CodeGen.
6271 for (auto C : Clauses) {
6272 if (auto *LC = dyn_cast<OMPLinearClause>(C))
6273 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
6274 B.NumIterations, *this, CurScope,
6280 getCurFunction()->setHasBranchProtectedScope();
6281 return OMPTeamsDistributeParallelForDirective::Create(
6282 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
6285 StmtResult Sema::ActOnOpenMPTargetTeamsDirective(ArrayRef<OMPClause *> Clauses,
6287 SourceLocation StartLoc,
6288 SourceLocation EndLoc) {
6292 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
6293 // 1.2.2 OpenMP Language Terminology
6294 // Structured block - An executable statement with a single entry at the
6295 // top and a single exit at the bottom.
6296 // The point of exit cannot be a branch out of the structured block.
6297 // longjmp() and throw() must not violate the entry/exit criteria.
6298 CS->getCapturedDecl()->setNothrow();
6300 getCurFunction()->setHasBranchProtectedScope();
6302 return OMPTargetTeamsDirective::Create(Context, StartLoc, EndLoc, Clauses,
6306 StmtResult Sema::ActOnOpenMPTargetTeamsDistributeDirective(
6307 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
6308 SourceLocation EndLoc,
6309 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
6313 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
6314 // 1.2.2 OpenMP Language Terminology
6315 // Structured block - An executable statement with a single entry at the
6316 // top and a single exit at the bottom.
6317 // The point of exit cannot be a branch out of the structured block.
6318 // longjmp() and throw() must not violate the entry/exit criteria.
6319 CS->getCapturedDecl()->setNothrow();
6321 OMPLoopDirective::HelperExprs B;
6322 // In presence of clause 'collapse' with number of loops, it will
6323 // define the nested loops number.
6324 auto NestedLoopCount = CheckOpenMPLoop(
6325 OMPD_target_teams_distribute,
6326 getCollapseNumberExpr(Clauses),
6327 nullptr /*ordered not a clause on distribute*/, AStmt, *this, *DSAStack,
6328 VarsWithImplicitDSA, B);
6329 if (NestedLoopCount == 0)
6332 assert((CurContext->isDependentContext() || B.builtAll()) &&
6333 "omp target teams distribute loop exprs were not built");
6335 getCurFunction()->setHasBranchProtectedScope();
6336 return OMPTargetTeamsDistributeDirective::Create(
6337 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
6340 StmtResult Sema::ActOnOpenMPTargetTeamsDistributeParallelForDirective(
6341 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
6342 SourceLocation EndLoc,
6343 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
6347 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
6348 // 1.2.2 OpenMP Language Terminology
6349 // Structured block - An executable statement with a single entry at the
6350 // top and a single exit at the bottom.
6351 // The point of exit cannot be a branch out of the structured block.
6352 // longjmp() and throw() must not violate the entry/exit criteria.
6353 CS->getCapturedDecl()->setNothrow();
6355 OMPLoopDirective::HelperExprs B;
6356 // In presence of clause 'collapse' with number of loops, it will
6357 // define the nested loops number.
6358 auto NestedLoopCount = CheckOpenMPLoop(
6359 OMPD_target_teams_distribute_parallel_for,
6360 getCollapseNumberExpr(Clauses),
6361 nullptr /*ordered not a clause on distribute*/, AStmt, *this, *DSAStack,
6362 VarsWithImplicitDSA, B);
6363 if (NestedLoopCount == 0)
6366 assert((CurContext->isDependentContext() || B.builtAll()) &&
6367 "omp target teams distribute parallel for loop exprs were not built");
6369 if (!CurContext->isDependentContext()) {
6370 // Finalize the clauses that need pre-built expressions for CodeGen.
6371 for (auto C : Clauses) {
6372 if (auto *LC = dyn_cast<OMPLinearClause>(C))
6373 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
6374 B.NumIterations, *this, CurScope,
6380 getCurFunction()->setHasBranchProtectedScope();
6381 return OMPTargetTeamsDistributeParallelForDirective::Create(
6382 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
6385 StmtResult Sema::ActOnOpenMPTargetTeamsDistributeParallelForSimdDirective(
6386 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
6387 SourceLocation EndLoc,
6388 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
6392 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
6393 // 1.2.2 OpenMP Language Terminology
6394 // Structured block - An executable statement with a single entry at the
6395 // top and a single exit at the bottom.
6396 // The point of exit cannot be a branch out of the structured block.
6397 // longjmp() and throw() must not violate the entry/exit criteria.
6398 CS->getCapturedDecl()->setNothrow();
6400 OMPLoopDirective::HelperExprs B;
6401 // In presence of clause 'collapse' with number of loops, it will
6402 // define the nested loops number.
6403 auto NestedLoopCount = CheckOpenMPLoop(
6404 OMPD_target_teams_distribute_parallel_for_simd,
6405 getCollapseNumberExpr(Clauses),
6406 nullptr /*ordered not a clause on distribute*/, AStmt, *this, *DSAStack,
6407 VarsWithImplicitDSA, B);
6408 if (NestedLoopCount == 0)
6411 assert((CurContext->isDependentContext() || B.builtAll()) &&
6412 "omp target teams distribute parallel for simd loop exprs were not "
6415 if (!CurContext->isDependentContext()) {
6416 // Finalize the clauses that need pre-built expressions for CodeGen.
6417 for (auto C : Clauses) {
6418 if (auto *LC = dyn_cast<OMPLinearClause>(C))
6419 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
6420 B.NumIterations, *this, CurScope,
6426 getCurFunction()->setHasBranchProtectedScope();
6427 return OMPTargetTeamsDistributeParallelForSimdDirective::Create(
6428 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
6431 OMPClause *Sema::ActOnOpenMPSingleExprClause(OpenMPClauseKind Kind, Expr *Expr,
6432 SourceLocation StartLoc,
6433 SourceLocation LParenLoc,
6434 SourceLocation EndLoc) {
6435 OMPClause *Res = nullptr;
6438 Res = ActOnOpenMPFinalClause(Expr, StartLoc, LParenLoc, EndLoc);
6440 case OMPC_num_threads:
6441 Res = ActOnOpenMPNumThreadsClause(Expr, StartLoc, LParenLoc, EndLoc);
6444 Res = ActOnOpenMPSafelenClause(Expr, StartLoc, LParenLoc, EndLoc);
6447 Res = ActOnOpenMPSimdlenClause(Expr, StartLoc, LParenLoc, EndLoc);
6450 Res = ActOnOpenMPCollapseClause(Expr, StartLoc, LParenLoc, EndLoc);
6453 Res = ActOnOpenMPOrderedClause(StartLoc, EndLoc, LParenLoc, Expr);
6456 Res = ActOnOpenMPDeviceClause(Expr, StartLoc, LParenLoc, EndLoc);
6458 case OMPC_num_teams:
6459 Res = ActOnOpenMPNumTeamsClause(Expr, StartLoc, LParenLoc, EndLoc);
6461 case OMPC_thread_limit:
6462 Res = ActOnOpenMPThreadLimitClause(Expr, StartLoc, LParenLoc, EndLoc);
6465 Res = ActOnOpenMPPriorityClause(Expr, StartLoc, LParenLoc, EndLoc);
6467 case OMPC_grainsize:
6468 Res = ActOnOpenMPGrainsizeClause(Expr, StartLoc, LParenLoc, EndLoc);
6470 case OMPC_num_tasks:
6471 Res = ActOnOpenMPNumTasksClause(Expr, StartLoc, LParenLoc, EndLoc);
6474 Res = ActOnOpenMPHintClause(Expr, StartLoc, LParenLoc, EndLoc);
6478 case OMPC_proc_bind:
6481 case OMPC_firstprivate:
6482 case OMPC_lastprivate:
6484 case OMPC_reduction:
6488 case OMPC_copyprivate:
6491 case OMPC_mergeable:
6492 case OMPC_threadprivate:
6504 case OMPC_dist_schedule:
6505 case OMPC_defaultmap:
6510 case OMPC_use_device_ptr:
6511 case OMPC_is_device_ptr:
6512 llvm_unreachable("Clause is not allowed.");
6517 OMPClause *Sema::ActOnOpenMPIfClause(OpenMPDirectiveKind NameModifier,
6518 Expr *Condition, SourceLocation StartLoc,
6519 SourceLocation LParenLoc,
6520 SourceLocation NameModifierLoc,
6521 SourceLocation ColonLoc,
6522 SourceLocation EndLoc) {
6523 Expr *ValExpr = Condition;
6524 if (!Condition->isValueDependent() && !Condition->isTypeDependent() &&
6525 !Condition->isInstantiationDependent() &&
6526 !Condition->containsUnexpandedParameterPack()) {
6527 ExprResult Val = CheckBooleanCondition(StartLoc, Condition);
6528 if (Val.isInvalid())
6531 ValExpr = MakeFullExpr(Val.get()).get();
6534 return new (Context) OMPIfClause(NameModifier, ValExpr, StartLoc, LParenLoc,
6535 NameModifierLoc, ColonLoc, EndLoc);
6538 OMPClause *Sema::ActOnOpenMPFinalClause(Expr *Condition,
6539 SourceLocation StartLoc,
6540 SourceLocation LParenLoc,
6541 SourceLocation EndLoc) {
6542 Expr *ValExpr = Condition;
6543 if (!Condition->isValueDependent() && !Condition->isTypeDependent() &&
6544 !Condition->isInstantiationDependent() &&
6545 !Condition->containsUnexpandedParameterPack()) {
6546 ExprResult Val = CheckBooleanCondition(StartLoc, Condition);
6547 if (Val.isInvalid())
6550 ValExpr = MakeFullExpr(Val.get()).get();
6553 return new (Context) OMPFinalClause(ValExpr, StartLoc, LParenLoc, EndLoc);
6555 ExprResult Sema::PerformOpenMPImplicitIntegerConversion(SourceLocation Loc,
6560 class IntConvertDiagnoser : public ICEConvertDiagnoser {
6562 IntConvertDiagnoser()
6563 : ICEConvertDiagnoser(/*AllowScopedEnumerations*/ false, false, true) {}
6564 SemaDiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc,
6565 QualType T) override {
6566 return S.Diag(Loc, diag::err_omp_not_integral) << T;
6568 SemaDiagnosticBuilder diagnoseIncomplete(Sema &S, SourceLocation Loc,
6569 QualType T) override {
6570 return S.Diag(Loc, diag::err_omp_incomplete_type) << T;
6572 SemaDiagnosticBuilder diagnoseExplicitConv(Sema &S, SourceLocation Loc,
6574 QualType ConvTy) override {
6575 return S.Diag(Loc, diag::err_omp_explicit_conversion) << T << ConvTy;
6577 SemaDiagnosticBuilder noteExplicitConv(Sema &S, CXXConversionDecl *Conv,
6578 QualType ConvTy) override {
6579 return S.Diag(Conv->getLocation(), diag::note_omp_conversion_here)
6580 << ConvTy->isEnumeralType() << ConvTy;
6582 SemaDiagnosticBuilder diagnoseAmbiguous(Sema &S, SourceLocation Loc,
6583 QualType T) override {
6584 return S.Diag(Loc, diag::err_omp_ambiguous_conversion) << T;
6586 SemaDiagnosticBuilder noteAmbiguous(Sema &S, CXXConversionDecl *Conv,
6587 QualType ConvTy) override {
6588 return S.Diag(Conv->getLocation(), diag::note_omp_conversion_here)
6589 << ConvTy->isEnumeralType() << ConvTy;
6591 SemaDiagnosticBuilder diagnoseConversion(Sema &, SourceLocation, QualType,
6592 QualType) override {
6593 llvm_unreachable("conversion functions are permitted");
6596 return PerformContextualImplicitConversion(Loc, Op, ConvertDiagnoser);
6599 static bool IsNonNegativeIntegerValue(Expr *&ValExpr, Sema &SemaRef,
6600 OpenMPClauseKind CKind,
6601 bool StrictlyPositive) {
6602 if (!ValExpr->isTypeDependent() && !ValExpr->isValueDependent() &&
6603 !ValExpr->isInstantiationDependent()) {
6604 SourceLocation Loc = ValExpr->getExprLoc();
6606 SemaRef.PerformOpenMPImplicitIntegerConversion(Loc, ValExpr);
6607 if (Value.isInvalid())
6610 ValExpr = Value.get();
6611 // The expression must evaluate to a non-negative integer value.
6612 llvm::APSInt Result;
6613 if (ValExpr->isIntegerConstantExpr(Result, SemaRef.Context) &&
6614 Result.isSigned() &&
6615 !((!StrictlyPositive && Result.isNonNegative()) ||
6616 (StrictlyPositive && Result.isStrictlyPositive()))) {
6617 SemaRef.Diag(Loc, diag::err_omp_negative_expression_in_clause)
6618 << getOpenMPClauseName(CKind) << (StrictlyPositive ? 1 : 0)
6619 << ValExpr->getSourceRange();
6626 OMPClause *Sema::ActOnOpenMPNumThreadsClause(Expr *NumThreads,
6627 SourceLocation StartLoc,
6628 SourceLocation LParenLoc,
6629 SourceLocation EndLoc) {
6630 Expr *ValExpr = NumThreads;
6632 // OpenMP [2.5, Restrictions]
6633 // The num_threads expression must evaluate to a positive integer value.
6634 if (!IsNonNegativeIntegerValue(ValExpr, *this, OMPC_num_threads,
6635 /*StrictlyPositive=*/true))
6638 return new (Context)
6639 OMPNumThreadsClause(ValExpr, StartLoc, LParenLoc, EndLoc);
6642 ExprResult Sema::VerifyPositiveIntegerConstantInClause(Expr *E,
6643 OpenMPClauseKind CKind,
6644 bool StrictlyPositive) {
6647 if (E->isValueDependent() || E->isTypeDependent() ||
6648 E->isInstantiationDependent() || E->containsUnexpandedParameterPack())
6650 llvm::APSInt Result;
6651 ExprResult ICE = VerifyIntegerConstantExpression(E, &Result);
6652 if (ICE.isInvalid())
6654 if ((StrictlyPositive && !Result.isStrictlyPositive()) ||
6655 (!StrictlyPositive && !Result.isNonNegative())) {
6656 Diag(E->getExprLoc(), diag::err_omp_negative_expression_in_clause)
6657 << getOpenMPClauseName(CKind) << (StrictlyPositive ? 1 : 0)
6658 << E->getSourceRange();
6661 if (CKind == OMPC_aligned && !Result.isPowerOf2()) {
6662 Diag(E->getExprLoc(), diag::warn_omp_alignment_not_power_of_two)
6663 << E->getSourceRange();
6666 if (CKind == OMPC_collapse && DSAStack->getAssociatedLoops() == 1)
6667 DSAStack->setAssociatedLoops(Result.getExtValue());
6668 else if (CKind == OMPC_ordered)
6669 DSAStack->setAssociatedLoops(Result.getExtValue());
6673 OMPClause *Sema::ActOnOpenMPSafelenClause(Expr *Len, SourceLocation StartLoc,
6674 SourceLocation LParenLoc,
6675 SourceLocation EndLoc) {
6676 // OpenMP [2.8.1, simd construct, Description]
6677 // The parameter of the safelen clause must be a constant
6678 // positive integer expression.
6679 ExprResult Safelen = VerifyPositiveIntegerConstantInClause(Len, OMPC_safelen);
6680 if (Safelen.isInvalid())
6682 return new (Context)
6683 OMPSafelenClause(Safelen.get(), StartLoc, LParenLoc, EndLoc);
6686 OMPClause *Sema::ActOnOpenMPSimdlenClause(Expr *Len, SourceLocation StartLoc,
6687 SourceLocation LParenLoc,
6688 SourceLocation EndLoc) {
6689 // OpenMP [2.8.1, simd construct, Description]
6690 // The parameter of the simdlen clause must be a constant
6691 // positive integer expression.
6692 ExprResult Simdlen = VerifyPositiveIntegerConstantInClause(Len, OMPC_simdlen);
6693 if (Simdlen.isInvalid())
6695 return new (Context)
6696 OMPSimdlenClause(Simdlen.get(), StartLoc, LParenLoc, EndLoc);
6699 OMPClause *Sema::ActOnOpenMPCollapseClause(Expr *NumForLoops,
6700 SourceLocation StartLoc,
6701 SourceLocation LParenLoc,
6702 SourceLocation EndLoc) {
6703 // OpenMP [2.7.1, loop construct, Description]
6704 // OpenMP [2.8.1, simd construct, Description]
6705 // OpenMP [2.9.6, distribute construct, Description]
6706 // The parameter of the collapse clause must be a constant
6707 // positive integer expression.
6708 ExprResult NumForLoopsResult =
6709 VerifyPositiveIntegerConstantInClause(NumForLoops, OMPC_collapse);
6710 if (NumForLoopsResult.isInvalid())
6712 return new (Context)
6713 OMPCollapseClause(NumForLoopsResult.get(), StartLoc, LParenLoc, EndLoc);
6716 OMPClause *Sema::ActOnOpenMPOrderedClause(SourceLocation StartLoc,
6717 SourceLocation EndLoc,
6718 SourceLocation LParenLoc,
6719 Expr *NumForLoops) {
6720 // OpenMP [2.7.1, loop construct, Description]
6721 // OpenMP [2.8.1, simd construct, Description]
6722 // OpenMP [2.9.6, distribute construct, Description]
6723 // The parameter of the ordered clause must be a constant
6724 // positive integer expression if any.
6725 if (NumForLoops && LParenLoc.isValid()) {
6726 ExprResult NumForLoopsResult =
6727 VerifyPositiveIntegerConstantInClause(NumForLoops, OMPC_ordered);
6728 if (NumForLoopsResult.isInvalid())
6730 NumForLoops = NumForLoopsResult.get();
6732 NumForLoops = nullptr;
6733 DSAStack->setOrderedRegion(/*IsOrdered=*/true, NumForLoops);
6734 return new (Context)
6735 OMPOrderedClause(NumForLoops, StartLoc, LParenLoc, EndLoc);
6738 OMPClause *Sema::ActOnOpenMPSimpleClause(
6739 OpenMPClauseKind Kind, unsigned Argument, SourceLocation ArgumentLoc,
6740 SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc) {
6741 OMPClause *Res = nullptr;
6745 ActOnOpenMPDefaultClause(static_cast<OpenMPDefaultClauseKind>(Argument),
6746 ArgumentLoc, StartLoc, LParenLoc, EndLoc);
6748 case OMPC_proc_bind:
6749 Res = ActOnOpenMPProcBindClause(
6750 static_cast<OpenMPProcBindClauseKind>(Argument), ArgumentLoc, StartLoc,
6755 case OMPC_num_threads:
6761 case OMPC_firstprivate:
6762 case OMPC_lastprivate:
6764 case OMPC_reduction:
6768 case OMPC_copyprivate:
6772 case OMPC_mergeable:
6773 case OMPC_threadprivate:
6785 case OMPC_num_teams:
6786 case OMPC_thread_limit:
6788 case OMPC_grainsize:
6790 case OMPC_num_tasks:
6792 case OMPC_dist_schedule:
6793 case OMPC_defaultmap:
6798 case OMPC_use_device_ptr:
6799 case OMPC_is_device_ptr:
6800 llvm_unreachable("Clause is not allowed.");
6806 getListOfPossibleValues(OpenMPClauseKind K, unsigned First, unsigned Last,
6807 ArrayRef<unsigned> Exclude = llvm::None) {
6809 unsigned Bound = Last >= 2 ? Last - 2 : 0;
6810 unsigned Skipped = Exclude.size();
6811 auto S = Exclude.begin(), E = Exclude.end();
6812 for (unsigned i = First; i < Last; ++i) {
6813 if (std::find(S, E, i) != E) {
6818 Values += getOpenMPSimpleClauseTypeName(K, i);
6820 if (i == Bound - Skipped)
6822 else if (i != Bound + 1 - Skipped)
6828 OMPClause *Sema::ActOnOpenMPDefaultClause(OpenMPDefaultClauseKind Kind,
6829 SourceLocation KindKwLoc,
6830 SourceLocation StartLoc,
6831 SourceLocation LParenLoc,
6832 SourceLocation EndLoc) {
6833 if (Kind == OMPC_DEFAULT_unknown) {
6834 static_assert(OMPC_DEFAULT_unknown > 0,
6835 "OMPC_DEFAULT_unknown not greater than 0");
6836 Diag(KindKwLoc, diag::err_omp_unexpected_clause_value)
6837 << getListOfPossibleValues(OMPC_default, /*First=*/0,
6838 /*Last=*/OMPC_DEFAULT_unknown)
6839 << getOpenMPClauseName(OMPC_default);
6843 case OMPC_DEFAULT_none:
6844 DSAStack->setDefaultDSANone(KindKwLoc);
6846 case OMPC_DEFAULT_shared:
6847 DSAStack->setDefaultDSAShared(KindKwLoc);
6849 case OMPC_DEFAULT_unknown:
6850 llvm_unreachable("Clause kind is not allowed.");
6853 return new (Context)
6854 OMPDefaultClause(Kind, KindKwLoc, StartLoc, LParenLoc, EndLoc);
6857 OMPClause *Sema::ActOnOpenMPProcBindClause(OpenMPProcBindClauseKind Kind,
6858 SourceLocation KindKwLoc,
6859 SourceLocation StartLoc,
6860 SourceLocation LParenLoc,
6861 SourceLocation EndLoc) {
6862 if (Kind == OMPC_PROC_BIND_unknown) {
6863 Diag(KindKwLoc, diag::err_omp_unexpected_clause_value)
6864 << getListOfPossibleValues(OMPC_proc_bind, /*First=*/0,
6865 /*Last=*/OMPC_PROC_BIND_unknown)
6866 << getOpenMPClauseName(OMPC_proc_bind);
6869 return new (Context)
6870 OMPProcBindClause(Kind, KindKwLoc, StartLoc, LParenLoc, EndLoc);
6873 OMPClause *Sema::ActOnOpenMPSingleExprWithArgClause(
6874 OpenMPClauseKind Kind, ArrayRef<unsigned> Argument, Expr *Expr,
6875 SourceLocation StartLoc, SourceLocation LParenLoc,
6876 ArrayRef<SourceLocation> ArgumentLoc, SourceLocation DelimLoc,
6877 SourceLocation EndLoc) {
6878 OMPClause *Res = nullptr;
6881 enum { Modifier1, Modifier2, ScheduleKind, NumberOfElements };
6882 assert(Argument.size() == NumberOfElements &&
6883 ArgumentLoc.size() == NumberOfElements);
6884 Res = ActOnOpenMPScheduleClause(
6885 static_cast<OpenMPScheduleClauseModifier>(Argument[Modifier1]),
6886 static_cast<OpenMPScheduleClauseModifier>(Argument[Modifier2]),
6887 static_cast<OpenMPScheduleClauseKind>(Argument[ScheduleKind]), Expr,
6888 StartLoc, LParenLoc, ArgumentLoc[Modifier1], ArgumentLoc[Modifier2],
6889 ArgumentLoc[ScheduleKind], DelimLoc, EndLoc);
6892 assert(Argument.size() == 1 && ArgumentLoc.size() == 1);
6893 Res = ActOnOpenMPIfClause(static_cast<OpenMPDirectiveKind>(Argument.back()),
6894 Expr, StartLoc, LParenLoc, ArgumentLoc.back(),
6897 case OMPC_dist_schedule:
6898 Res = ActOnOpenMPDistScheduleClause(
6899 static_cast<OpenMPDistScheduleClauseKind>(Argument.back()), Expr,
6900 StartLoc, LParenLoc, ArgumentLoc.back(), DelimLoc, EndLoc);
6902 case OMPC_defaultmap:
6903 enum { Modifier, DefaultmapKind };
6904 Res = ActOnOpenMPDefaultmapClause(
6905 static_cast<OpenMPDefaultmapClauseModifier>(Argument[Modifier]),
6906 static_cast<OpenMPDefaultmapClauseKind>(Argument[DefaultmapKind]),
6907 StartLoc, LParenLoc, ArgumentLoc[Modifier], ArgumentLoc[DefaultmapKind],
6911 case OMPC_num_threads:
6916 case OMPC_proc_bind:
6918 case OMPC_firstprivate:
6919 case OMPC_lastprivate:
6921 case OMPC_reduction:
6925 case OMPC_copyprivate:
6929 case OMPC_mergeable:
6930 case OMPC_threadprivate:
6942 case OMPC_num_teams:
6943 case OMPC_thread_limit:
6945 case OMPC_grainsize:
6947 case OMPC_num_tasks:
6953 case OMPC_use_device_ptr:
6954 case OMPC_is_device_ptr:
6955 llvm_unreachable("Clause is not allowed.");
6960 static bool checkScheduleModifiers(Sema &S, OpenMPScheduleClauseModifier M1,
6961 OpenMPScheduleClauseModifier M2,
6962 SourceLocation M1Loc, SourceLocation M2Loc) {
6963 if (M1 == OMPC_SCHEDULE_MODIFIER_unknown && M1Loc.isValid()) {
6964 SmallVector<unsigned, 2> Excluded;
6965 if (M2 != OMPC_SCHEDULE_MODIFIER_unknown)
6966 Excluded.push_back(M2);
6967 if (M2 == OMPC_SCHEDULE_MODIFIER_nonmonotonic)
6968 Excluded.push_back(OMPC_SCHEDULE_MODIFIER_monotonic);
6969 if (M2 == OMPC_SCHEDULE_MODIFIER_monotonic)
6970 Excluded.push_back(OMPC_SCHEDULE_MODIFIER_nonmonotonic);
6971 S.Diag(M1Loc, diag::err_omp_unexpected_clause_value)
6972 << getListOfPossibleValues(OMPC_schedule,
6973 /*First=*/OMPC_SCHEDULE_MODIFIER_unknown + 1,
6974 /*Last=*/OMPC_SCHEDULE_MODIFIER_last,
6976 << getOpenMPClauseName(OMPC_schedule);
6982 OMPClause *Sema::ActOnOpenMPScheduleClause(
6983 OpenMPScheduleClauseModifier M1, OpenMPScheduleClauseModifier M2,
6984 OpenMPScheduleClauseKind Kind, Expr *ChunkSize, SourceLocation StartLoc,
6985 SourceLocation LParenLoc, SourceLocation M1Loc, SourceLocation M2Loc,
6986 SourceLocation KindLoc, SourceLocation CommaLoc, SourceLocation EndLoc) {
6987 if (checkScheduleModifiers(*this, M1, M2, M1Loc, M2Loc) ||
6988 checkScheduleModifiers(*this, M2, M1, M2Loc, M1Loc))
6990 // OpenMP, 2.7.1, Loop Construct, Restrictions
6991 // Either the monotonic modifier or the nonmonotonic modifier can be specified
6993 if ((M1 == M2 && M1 != OMPC_SCHEDULE_MODIFIER_unknown) ||
6994 (M1 == OMPC_SCHEDULE_MODIFIER_monotonic &&
6995 M2 == OMPC_SCHEDULE_MODIFIER_nonmonotonic) ||
6996 (M1 == OMPC_SCHEDULE_MODIFIER_nonmonotonic &&
6997 M2 == OMPC_SCHEDULE_MODIFIER_monotonic)) {
6998 Diag(M2Loc, diag::err_omp_unexpected_schedule_modifier)
6999 << getOpenMPSimpleClauseTypeName(OMPC_schedule, M2)
7000 << getOpenMPSimpleClauseTypeName(OMPC_schedule, M1);
7003 if (Kind == OMPC_SCHEDULE_unknown) {
7005 if (M1Loc.isInvalid() && M2Loc.isInvalid()) {
7006 unsigned Exclude[] = {OMPC_SCHEDULE_unknown};
7007 Values = getListOfPossibleValues(OMPC_schedule, /*First=*/0,
7008 /*Last=*/OMPC_SCHEDULE_MODIFIER_last,
7011 Values = getListOfPossibleValues(OMPC_schedule, /*First=*/0,
7012 /*Last=*/OMPC_SCHEDULE_unknown);
7014 Diag(KindLoc, diag::err_omp_unexpected_clause_value)
7015 << Values << getOpenMPClauseName(OMPC_schedule);
7018 // OpenMP, 2.7.1, Loop Construct, Restrictions
7019 // The nonmonotonic modifier can only be specified with schedule(dynamic) or
7020 // schedule(guided).
7021 if ((M1 == OMPC_SCHEDULE_MODIFIER_nonmonotonic ||
7022 M2 == OMPC_SCHEDULE_MODIFIER_nonmonotonic) &&
7023 Kind != OMPC_SCHEDULE_dynamic && Kind != OMPC_SCHEDULE_guided) {
7024 Diag(M1 == OMPC_SCHEDULE_MODIFIER_nonmonotonic ? M1Loc : M2Loc,
7025 diag::err_omp_schedule_nonmonotonic_static);
7028 Expr *ValExpr = ChunkSize;
7029 Stmt *HelperValStmt = nullptr;
7031 if (!ChunkSize->isValueDependent() && !ChunkSize->isTypeDependent() &&
7032 !ChunkSize->isInstantiationDependent() &&
7033 !ChunkSize->containsUnexpandedParameterPack()) {
7034 SourceLocation ChunkSizeLoc = ChunkSize->getLocStart();
7036 PerformOpenMPImplicitIntegerConversion(ChunkSizeLoc, ChunkSize);
7037 if (Val.isInvalid())
7040 ValExpr = Val.get();
7042 // OpenMP [2.7.1, Restrictions]
7043 // chunk_size must be a loop invariant integer expression with a positive
7045 llvm::APSInt Result;
7046 if (ValExpr->isIntegerConstantExpr(Result, Context)) {
7047 if (Result.isSigned() && !Result.isStrictlyPositive()) {
7048 Diag(ChunkSizeLoc, diag::err_omp_negative_expression_in_clause)
7049 << "schedule" << 1 << ChunkSize->getSourceRange();
7052 } else if (isParallelOrTaskRegion(DSAStack->getCurrentDirective()) &&
7053 !CurContext->isDependentContext()) {
7054 llvm::MapVector<Expr *, DeclRefExpr *> Captures;
7055 ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
7056 HelperValStmt = buildPreInits(Context, Captures);
7061 return new (Context)
7062 OMPScheduleClause(StartLoc, LParenLoc, KindLoc, CommaLoc, EndLoc, Kind,
7063 ValExpr, HelperValStmt, M1, M1Loc, M2, M2Loc);
7066 OMPClause *Sema::ActOnOpenMPClause(OpenMPClauseKind Kind,
7067 SourceLocation StartLoc,
7068 SourceLocation EndLoc) {
7069 OMPClause *Res = nullptr;
7072 Res = ActOnOpenMPOrderedClause(StartLoc, EndLoc);
7075 Res = ActOnOpenMPNowaitClause(StartLoc, EndLoc);
7078 Res = ActOnOpenMPUntiedClause(StartLoc, EndLoc);
7080 case OMPC_mergeable:
7081 Res = ActOnOpenMPMergeableClause(StartLoc, EndLoc);
7084 Res = ActOnOpenMPReadClause(StartLoc, EndLoc);
7087 Res = ActOnOpenMPWriteClause(StartLoc, EndLoc);
7090 Res = ActOnOpenMPUpdateClause(StartLoc, EndLoc);
7093 Res = ActOnOpenMPCaptureClause(StartLoc, EndLoc);
7096 Res = ActOnOpenMPSeqCstClause(StartLoc, EndLoc);
7099 Res = ActOnOpenMPThreadsClause(StartLoc, EndLoc);
7102 Res = ActOnOpenMPSIMDClause(StartLoc, EndLoc);
7105 Res = ActOnOpenMPNogroupClause(StartLoc, EndLoc);
7109 case OMPC_num_threads:
7115 case OMPC_firstprivate:
7116 case OMPC_lastprivate:
7118 case OMPC_reduction:
7122 case OMPC_copyprivate:
7124 case OMPC_proc_bind:
7125 case OMPC_threadprivate:
7130 case OMPC_num_teams:
7131 case OMPC_thread_limit:
7133 case OMPC_grainsize:
7134 case OMPC_num_tasks:
7136 case OMPC_dist_schedule:
7137 case OMPC_defaultmap:
7142 case OMPC_use_device_ptr:
7143 case OMPC_is_device_ptr:
7144 llvm_unreachable("Clause is not allowed.");
7149 OMPClause *Sema::ActOnOpenMPNowaitClause(SourceLocation StartLoc,
7150 SourceLocation EndLoc) {
7151 DSAStack->setNowaitRegion();
7152 return new (Context) OMPNowaitClause(StartLoc, EndLoc);
7155 OMPClause *Sema::ActOnOpenMPUntiedClause(SourceLocation StartLoc,
7156 SourceLocation EndLoc) {
7157 return new (Context) OMPUntiedClause(StartLoc, EndLoc);
7160 OMPClause *Sema::ActOnOpenMPMergeableClause(SourceLocation StartLoc,
7161 SourceLocation EndLoc) {
7162 return new (Context) OMPMergeableClause(StartLoc, EndLoc);
7165 OMPClause *Sema::ActOnOpenMPReadClause(SourceLocation StartLoc,
7166 SourceLocation EndLoc) {
7167 return new (Context) OMPReadClause(StartLoc, EndLoc);
7170 OMPClause *Sema::ActOnOpenMPWriteClause(SourceLocation StartLoc,
7171 SourceLocation EndLoc) {
7172 return new (Context) OMPWriteClause(StartLoc, EndLoc);
7175 OMPClause *Sema::ActOnOpenMPUpdateClause(SourceLocation StartLoc,
7176 SourceLocation EndLoc) {
7177 return new (Context) OMPUpdateClause(StartLoc, EndLoc);
7180 OMPClause *Sema::ActOnOpenMPCaptureClause(SourceLocation StartLoc,
7181 SourceLocation EndLoc) {
7182 return new (Context) OMPCaptureClause(StartLoc, EndLoc);
7185 OMPClause *Sema::ActOnOpenMPSeqCstClause(SourceLocation StartLoc,
7186 SourceLocation EndLoc) {
7187 return new (Context) OMPSeqCstClause(StartLoc, EndLoc);
7190 OMPClause *Sema::ActOnOpenMPThreadsClause(SourceLocation StartLoc,
7191 SourceLocation EndLoc) {
7192 return new (Context) OMPThreadsClause(StartLoc, EndLoc);
7195 OMPClause *Sema::ActOnOpenMPSIMDClause(SourceLocation StartLoc,
7196 SourceLocation EndLoc) {
7197 return new (Context) OMPSIMDClause(StartLoc, EndLoc);
7200 OMPClause *Sema::ActOnOpenMPNogroupClause(SourceLocation StartLoc,
7201 SourceLocation EndLoc) {
7202 return new (Context) OMPNogroupClause(StartLoc, EndLoc);
7205 OMPClause *Sema::ActOnOpenMPVarListClause(
7206 OpenMPClauseKind Kind, ArrayRef<Expr *> VarList, Expr *TailExpr,
7207 SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation ColonLoc,
7208 SourceLocation EndLoc, CXXScopeSpec &ReductionIdScopeSpec,
7209 const DeclarationNameInfo &ReductionId, OpenMPDependClauseKind DepKind,
7210 OpenMPLinearClauseKind LinKind, OpenMPMapClauseKind MapTypeModifier,
7211 OpenMPMapClauseKind MapType, bool IsMapTypeImplicit,
7212 SourceLocation DepLinMapLoc) {
7213 OMPClause *Res = nullptr;
7216 Res = ActOnOpenMPPrivateClause(VarList, StartLoc, LParenLoc, EndLoc);
7218 case OMPC_firstprivate:
7219 Res = ActOnOpenMPFirstprivateClause(VarList, StartLoc, LParenLoc, EndLoc);
7221 case OMPC_lastprivate:
7222 Res = ActOnOpenMPLastprivateClause(VarList, StartLoc, LParenLoc, EndLoc);
7225 Res = ActOnOpenMPSharedClause(VarList, StartLoc, LParenLoc, EndLoc);
7227 case OMPC_reduction:
7228 Res = ActOnOpenMPReductionClause(VarList, StartLoc, LParenLoc, ColonLoc,
7229 EndLoc, ReductionIdScopeSpec, ReductionId);
7232 Res = ActOnOpenMPLinearClause(VarList, TailExpr, StartLoc, LParenLoc,
7233 LinKind, DepLinMapLoc, ColonLoc, EndLoc);
7236 Res = ActOnOpenMPAlignedClause(VarList, TailExpr, StartLoc, LParenLoc,
7240 Res = ActOnOpenMPCopyinClause(VarList, StartLoc, LParenLoc, EndLoc);
7242 case OMPC_copyprivate:
7243 Res = ActOnOpenMPCopyprivateClause(VarList, StartLoc, LParenLoc, EndLoc);
7246 Res = ActOnOpenMPFlushClause(VarList, StartLoc, LParenLoc, EndLoc);
7249 Res = ActOnOpenMPDependClause(DepKind, DepLinMapLoc, ColonLoc, VarList,
7250 StartLoc, LParenLoc, EndLoc);
7253 Res = ActOnOpenMPMapClause(MapTypeModifier, MapType, IsMapTypeImplicit,
7254 DepLinMapLoc, ColonLoc, VarList, StartLoc,
7258 Res = ActOnOpenMPToClause(VarList, StartLoc, LParenLoc, EndLoc);
7261 Res = ActOnOpenMPFromClause(VarList, StartLoc, LParenLoc, EndLoc);
7263 case OMPC_use_device_ptr:
7264 Res = ActOnOpenMPUseDevicePtrClause(VarList, StartLoc, LParenLoc, EndLoc);
7266 case OMPC_is_device_ptr:
7267 Res = ActOnOpenMPIsDevicePtrClause(VarList, StartLoc, LParenLoc, EndLoc);
7271 case OMPC_num_threads:
7276 case OMPC_proc_bind:
7281 case OMPC_mergeable:
7282 case OMPC_threadprivate:
7291 case OMPC_num_teams:
7292 case OMPC_thread_limit:
7294 case OMPC_grainsize:
7296 case OMPC_num_tasks:
7298 case OMPC_dist_schedule:
7299 case OMPC_defaultmap:
7302 llvm_unreachable("Clause is not allowed.");
7307 ExprResult Sema::getOpenMPCapturedExpr(VarDecl *Capture, ExprValueKind VK,
7308 ExprObjectKind OK, SourceLocation Loc) {
7309 ExprResult Res = BuildDeclRefExpr(
7310 Capture, Capture->getType().getNonReferenceType(), VK_LValue, Loc);
7311 if (!Res.isUsable())
7313 if (OK == OK_Ordinary && !getLangOpts().CPlusPlus) {
7314 Res = CreateBuiltinUnaryOp(Loc, UO_Deref, Res.get());
7315 if (!Res.isUsable())
7318 if (VK != VK_LValue && Res.get()->isGLValue()) {
7319 Res = DefaultLvalueConversion(Res.get());
7320 if (!Res.isUsable())
7326 static std::pair<ValueDecl *, bool>
7327 getPrivateItem(Sema &S, Expr *&RefExpr, SourceLocation &ELoc,
7328 SourceRange &ERange, bool AllowArraySection = false) {
7329 if (RefExpr->isTypeDependent() || RefExpr->isValueDependent() ||
7330 RefExpr->containsUnexpandedParameterPack())
7331 return std::make_pair(nullptr, true);
7333 // OpenMP [3.1, C/C++]
7334 // A list item is a variable name.
7335 // OpenMP [2.9.3.3, Restrictions, p.1]
7336 // A variable that is part of another variable (as an array or
7337 // structure element) cannot appear in a private clause.
7338 RefExpr = RefExpr->IgnoreParens();
7343 } IsArrayExpr = NoArrayExpr;
7344 if (AllowArraySection) {
7345 if (auto *ASE = dyn_cast_or_null<ArraySubscriptExpr>(RefExpr)) {
7346 auto *Base = ASE->getBase()->IgnoreParenImpCasts();
7347 while (auto *TempASE = dyn_cast<ArraySubscriptExpr>(Base))
7348 Base = TempASE->getBase()->IgnoreParenImpCasts();
7350 IsArrayExpr = ArraySubscript;
7351 } else if (auto *OASE = dyn_cast_or_null<OMPArraySectionExpr>(RefExpr)) {
7352 auto *Base = OASE->getBase()->IgnoreParenImpCasts();
7353 while (auto *TempOASE = dyn_cast<OMPArraySectionExpr>(Base))
7354 Base = TempOASE->getBase()->IgnoreParenImpCasts();
7355 while (auto *TempASE = dyn_cast<ArraySubscriptExpr>(Base))
7356 Base = TempASE->getBase()->IgnoreParenImpCasts();
7358 IsArrayExpr = OMPArraySection;
7361 ELoc = RefExpr->getExprLoc();
7362 ERange = RefExpr->getSourceRange();
7363 RefExpr = RefExpr->IgnoreParenImpCasts();
7364 auto *DE = dyn_cast_or_null<DeclRefExpr>(RefExpr);
7365 auto *ME = dyn_cast_or_null<MemberExpr>(RefExpr);
7366 if ((!DE || !isa<VarDecl>(DE->getDecl())) &&
7367 (S.getCurrentThisType().isNull() || !ME ||
7368 !isa<CXXThisExpr>(ME->getBase()->IgnoreParenImpCasts()) ||
7369 !isa<FieldDecl>(ME->getMemberDecl()))) {
7370 if (IsArrayExpr != NoArrayExpr)
7371 S.Diag(ELoc, diag::err_omp_expected_base_var_name) << IsArrayExpr
7376 ? diag::err_omp_expected_var_name_member_expr_or_array_item
7377 : diag::err_omp_expected_var_name_member_expr)
7378 << (S.getCurrentThisType().isNull() ? 0 : 1) << ERange;
7380 return std::make_pair(nullptr, false);
7382 return std::make_pair(DE ? DE->getDecl() : ME->getMemberDecl(), false);
7385 OMPClause *Sema::ActOnOpenMPPrivateClause(ArrayRef<Expr *> VarList,
7386 SourceLocation StartLoc,
7387 SourceLocation LParenLoc,
7388 SourceLocation EndLoc) {
7389 SmallVector<Expr *, 8> Vars;
7390 SmallVector<Expr *, 8> PrivateCopies;
7391 for (auto &RefExpr : VarList) {
7392 assert(RefExpr && "NULL expr in OpenMP private clause.");
7393 SourceLocation ELoc;
7395 Expr *SimpleRefExpr = RefExpr;
7396 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
7398 // It will be analyzed later.
7399 Vars.push_back(RefExpr);
7400 PrivateCopies.push_back(nullptr);
7402 ValueDecl *D = Res.first;
7406 QualType Type = D->getType();
7407 auto *VD = dyn_cast<VarDecl>(D);
7409 // OpenMP [2.9.3.3, Restrictions, C/C++, p.3]
7410 // A variable that appears in a private clause must not have an incomplete
7411 // type or a reference type.
7412 if (RequireCompleteType(ELoc, Type, diag::err_omp_private_incomplete_type))
7414 Type = Type.getNonReferenceType();
7416 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
7418 // Variables with the predetermined data-sharing attributes may not be
7419 // listed in data-sharing attributes clauses, except for the cases
7420 // listed below. For these exceptions only, listing a predetermined
7421 // variable in a data-sharing attribute clause is allowed and overrides
7422 // the variable's predetermined data-sharing attributes.
7423 DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, false);
7424 if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_private) {
7425 Diag(ELoc, diag::err_omp_wrong_dsa) << getOpenMPClauseName(DVar.CKind)
7426 << getOpenMPClauseName(OMPC_private);
7427 ReportOriginalDSA(*this, DSAStack, D, DVar);
7431 auto CurrDir = DSAStack->getCurrentDirective();
7432 // Variably modified types are not supported for tasks.
7433 if (!Type->isAnyPointerType() && Type->isVariablyModifiedType() &&
7434 isOpenMPTaskingDirective(CurrDir)) {
7435 Diag(ELoc, diag::err_omp_variably_modified_type_not_supported)
7436 << getOpenMPClauseName(OMPC_private) << Type
7437 << getOpenMPDirectiveName(CurrDir);
7440 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
7441 Diag(D->getLocation(),
7442 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
7447 // OpenMP 4.5 [2.15.5.1, Restrictions, p.3]
7448 // A list item cannot appear in both a map clause and a data-sharing
7449 // attribute clause on the same construct
7450 if (CurrDir == OMPD_target || CurrDir == OMPD_target_parallel ||
7451 CurrDir == OMPD_target_teams ||
7452 CurrDir == OMPD_target_teams_distribute ||
7453 CurrDir == OMPD_target_teams_distribute_parallel_for ||
7454 CurrDir == OMPD_target_teams_distribute_parallel_for_simd) {
7455 OpenMPClauseKind ConflictKind;
7456 if (DSAStack->checkMappableExprComponentListsForDecl(
7457 VD, /*CurrentRegionOnly=*/true,
7458 [&](OMPClauseMappableExprCommon::MappableExprComponentListRef,
7459 OpenMPClauseKind WhereFoundClauseKind) -> bool {
7460 ConflictKind = WhereFoundClauseKind;
7463 Diag(ELoc, diag::err_omp_variable_in_given_clause_and_dsa)
7464 << getOpenMPClauseName(OMPC_private)
7465 << getOpenMPClauseName(ConflictKind)
7466 << getOpenMPDirectiveName(CurrDir);
7467 ReportOriginalDSA(*this, DSAStack, D, DVar);
7472 // OpenMP [2.9.3.3, Restrictions, C/C++, p.1]
7473 // A variable of class type (or array thereof) that appears in a private
7474 // clause requires an accessible, unambiguous default constructor for the
7476 // Generate helper private variable and initialize it with the default
7477 // value. The address of the original variable is replaced by the address of
7478 // the new private variable in CodeGen. This new variable is not added to
7479 // IdResolver, so the code in the OpenMP region uses original variable for
7480 // proper diagnostics.
7481 Type = Type.getUnqualifiedType();
7482 auto VDPrivate = buildVarDecl(*this, ELoc, Type, D->getName(),
7483 D->hasAttrs() ? &D->getAttrs() : nullptr);
7484 ActOnUninitializedDecl(VDPrivate, /*TypeMayContainAuto=*/false);
7485 if (VDPrivate->isInvalidDecl())
7487 auto VDPrivateRefExpr = buildDeclRefExpr(
7488 *this, VDPrivate, RefExpr->getType().getUnqualifiedType(), ELoc);
7490 DeclRefExpr *Ref = nullptr;
7491 if (!VD && !CurContext->isDependentContext())
7492 Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/false);
7493 DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_private, Ref);
7494 Vars.push_back((VD || CurContext->isDependentContext())
7495 ? RefExpr->IgnoreParens()
7497 PrivateCopies.push_back(VDPrivateRefExpr);
7503 return OMPPrivateClause::Create(Context, StartLoc, LParenLoc, EndLoc, Vars,
7508 class DiagsUninitializedSeveretyRAII {
7510 DiagnosticsEngine &Diags;
7511 SourceLocation SavedLoc;
7515 DiagsUninitializedSeveretyRAII(DiagnosticsEngine &Diags, SourceLocation Loc,
7517 : Diags(Diags), SavedLoc(Loc), IsIgnored(IsIgnored) {
7519 Diags.setSeverity(/*Diag*/ diag::warn_uninit_self_reference_in_init,
7520 /*Map*/ diag::Severity::Ignored, Loc);
7523 ~DiagsUninitializedSeveretyRAII() {
7525 Diags.popMappings(SavedLoc);
7530 OMPClause *Sema::ActOnOpenMPFirstprivateClause(ArrayRef<Expr *> VarList,
7531 SourceLocation StartLoc,
7532 SourceLocation LParenLoc,
7533 SourceLocation EndLoc) {
7534 SmallVector<Expr *, 8> Vars;
7535 SmallVector<Expr *, 8> PrivateCopies;
7536 SmallVector<Expr *, 8> Inits;
7537 SmallVector<Decl *, 4> ExprCaptures;
7538 bool IsImplicitClause =
7539 StartLoc.isInvalid() && LParenLoc.isInvalid() && EndLoc.isInvalid();
7540 auto ImplicitClauseLoc = DSAStack->getConstructLoc();
7542 for (auto &RefExpr : VarList) {
7543 assert(RefExpr && "NULL expr in OpenMP firstprivate clause.");
7544 SourceLocation ELoc;
7546 Expr *SimpleRefExpr = RefExpr;
7547 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
7549 // It will be analyzed later.
7550 Vars.push_back(RefExpr);
7551 PrivateCopies.push_back(nullptr);
7552 Inits.push_back(nullptr);
7554 ValueDecl *D = Res.first;
7558 ELoc = IsImplicitClause ? ImplicitClauseLoc : ELoc;
7559 QualType Type = D->getType();
7560 auto *VD = dyn_cast<VarDecl>(D);
7562 // OpenMP [2.9.3.3, Restrictions, C/C++, p.3]
7563 // A variable that appears in a private clause must not have an incomplete
7564 // type or a reference type.
7565 if (RequireCompleteType(ELoc, Type,
7566 diag::err_omp_firstprivate_incomplete_type))
7568 Type = Type.getNonReferenceType();
7570 // OpenMP [2.9.3.4, Restrictions, C/C++, p.1]
7571 // A variable of class type (or array thereof) that appears in a private
7572 // clause requires an accessible, unambiguous copy constructor for the
7574 auto ElemType = Context.getBaseElementType(Type).getNonReferenceType();
7576 // If an implicit firstprivate variable found it was checked already.
7577 DSAStackTy::DSAVarData TopDVar;
7578 if (!IsImplicitClause) {
7579 DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, false);
7581 bool IsConstant = ElemType.isConstant(Context);
7582 // OpenMP [2.4.13, Data-sharing Attribute Clauses]
7583 // A list item that specifies a given variable may not appear in more
7584 // than one clause on the same directive, except that a variable may be
7585 // specified in both firstprivate and lastprivate clauses.
7586 if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_firstprivate &&
7587 DVar.CKind != OMPC_lastprivate && DVar.RefExpr) {
7588 Diag(ELoc, diag::err_omp_wrong_dsa)
7589 << getOpenMPClauseName(DVar.CKind)
7590 << getOpenMPClauseName(OMPC_firstprivate);
7591 ReportOriginalDSA(*this, DSAStack, D, DVar);
7595 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
7597 // Variables with the predetermined data-sharing attributes may not be
7598 // listed in data-sharing attributes clauses, except for the cases
7599 // listed below. For these exceptions only, listing a predetermined
7600 // variable in a data-sharing attribute clause is allowed and overrides
7601 // the variable's predetermined data-sharing attributes.
7602 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
7603 // in a Construct, C/C++, p.2]
7604 // Variables with const-qualified type having no mutable member may be
7605 // listed in a firstprivate clause, even if they are static data members.
7606 if (!(IsConstant || (VD && VD->isStaticDataMember())) && !DVar.RefExpr &&
7607 DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_shared) {
7608 Diag(ELoc, diag::err_omp_wrong_dsa)
7609 << getOpenMPClauseName(DVar.CKind)
7610 << getOpenMPClauseName(OMPC_firstprivate);
7611 ReportOriginalDSA(*this, DSAStack, D, DVar);
7615 OpenMPDirectiveKind CurrDir = DSAStack->getCurrentDirective();
7616 // OpenMP [2.9.3.4, Restrictions, p.2]
7617 // A list item that is private within a parallel region must not appear
7618 // in a firstprivate clause on a worksharing construct if any of the
7619 // worksharing regions arising from the worksharing construct ever bind
7620 // to any of the parallel regions arising from the parallel construct.
7621 if (isOpenMPWorksharingDirective(CurrDir) &&
7622 !isOpenMPParallelDirective(CurrDir) &&
7623 !isOpenMPTeamsDirective(CurrDir)) {
7624 DVar = DSAStack->getImplicitDSA(D, true);
7625 if (DVar.CKind != OMPC_shared &&
7626 (isOpenMPParallelDirective(DVar.DKind) ||
7627 DVar.DKind == OMPD_unknown)) {
7628 Diag(ELoc, diag::err_omp_required_access)
7629 << getOpenMPClauseName(OMPC_firstprivate)
7630 << getOpenMPClauseName(OMPC_shared);
7631 ReportOriginalDSA(*this, DSAStack, D, DVar);
7635 // OpenMP [2.9.3.4, Restrictions, p.3]
7636 // A list item that appears in a reduction clause of a parallel construct
7637 // must not appear in a firstprivate clause on a worksharing or task
7638 // construct if any of the worksharing or task regions arising from the
7639 // worksharing or task construct ever bind to any of the parallel regions
7640 // arising from the parallel construct.
7641 // OpenMP [2.9.3.4, Restrictions, p.4]
7642 // A list item that appears in a reduction clause in worksharing
7643 // construct must not appear in a firstprivate clause in a task construct
7644 // encountered during execution of any of the worksharing regions arising
7645 // from the worksharing construct.
7646 if (isOpenMPTaskingDirective(CurrDir)) {
7647 DVar = DSAStack->hasInnermostDSA(
7648 D, [](OpenMPClauseKind C) -> bool { return C == OMPC_reduction; },
7649 [](OpenMPDirectiveKind K) -> bool {
7650 return isOpenMPParallelDirective(K) ||
7651 isOpenMPWorksharingDirective(K);
7654 if (DVar.CKind == OMPC_reduction &&
7655 (isOpenMPParallelDirective(DVar.DKind) ||
7656 isOpenMPWorksharingDirective(DVar.DKind))) {
7657 Diag(ELoc, diag::err_omp_parallel_reduction_in_task_firstprivate)
7658 << getOpenMPDirectiveName(DVar.DKind);
7659 ReportOriginalDSA(*this, DSAStack, D, DVar);
7664 // OpenMP 4.5 [2.15.3.4, Restrictions, p.3]
7665 // A list item that is private within a teams region must not appear in a
7666 // firstprivate clause on a distribute construct if any of the distribute
7667 // regions arising from the distribute construct ever bind to any of the
7668 // teams regions arising from the teams construct.
7669 // OpenMP 4.5 [2.15.3.4, Restrictions, p.3]
7670 // A list item that appears in a reduction clause of a teams construct
7671 // must not appear in a firstprivate clause on a distribute construct if
7672 // any of the distribute regions arising from the distribute construct
7673 // ever bind to any of the teams regions arising from the teams construct.
7674 // OpenMP 4.5 [2.10.8, Distribute Construct, p.3]
7675 // A list item may appear in a firstprivate or lastprivate clause but not
7677 if (CurrDir == OMPD_distribute) {
7678 DVar = DSAStack->hasInnermostDSA(
7679 D, [](OpenMPClauseKind C) -> bool { return C == OMPC_private; },
7680 [](OpenMPDirectiveKind K) -> bool {
7681 return isOpenMPTeamsDirective(K);
7684 if (DVar.CKind == OMPC_private && isOpenMPTeamsDirective(DVar.DKind)) {
7685 Diag(ELoc, diag::err_omp_firstprivate_distribute_private_teams);
7686 ReportOriginalDSA(*this, DSAStack, D, DVar);
7689 DVar = DSAStack->hasInnermostDSA(
7690 D, [](OpenMPClauseKind C) -> bool { return C == OMPC_reduction; },
7691 [](OpenMPDirectiveKind K) -> bool {
7692 return isOpenMPTeamsDirective(K);
7695 if (DVar.CKind == OMPC_reduction &&
7696 isOpenMPTeamsDirective(DVar.DKind)) {
7697 Diag(ELoc, diag::err_omp_firstprivate_distribute_in_teams_reduction);
7698 ReportOriginalDSA(*this, DSAStack, D, DVar);
7701 DVar = DSAStack->getTopDSA(D, false);
7702 if (DVar.CKind == OMPC_lastprivate) {
7703 Diag(ELoc, diag::err_omp_firstprivate_and_lastprivate_in_distribute);
7704 ReportOriginalDSA(*this, DSAStack, D, DVar);
7708 // OpenMP 4.5 [2.15.5.1, Restrictions, p.3]
7709 // A list item cannot appear in both a map clause and a data-sharing
7710 // attribute clause on the same construct
7711 if (CurrDir == OMPD_target || CurrDir == OMPD_target_parallel ||
7712 CurrDir == OMPD_target_teams ||
7713 CurrDir == OMPD_target_teams_distribute ||
7714 CurrDir == OMPD_target_teams_distribute_parallel_for ||
7715 CurrDir == OMPD_target_teams_distribute_parallel_for_simd) {
7716 OpenMPClauseKind ConflictKind;
7717 if (DSAStack->checkMappableExprComponentListsForDecl(
7718 VD, /*CurrentRegionOnly=*/true,
7719 [&](OMPClauseMappableExprCommon::MappableExprComponentListRef,
7720 OpenMPClauseKind WhereFoundClauseKind) -> bool {
7721 ConflictKind = WhereFoundClauseKind;
7724 Diag(ELoc, diag::err_omp_variable_in_given_clause_and_dsa)
7725 << getOpenMPClauseName(OMPC_firstprivate)
7726 << getOpenMPClauseName(ConflictKind)
7727 << getOpenMPDirectiveName(DSAStack->getCurrentDirective());
7728 ReportOriginalDSA(*this, DSAStack, D, DVar);
7734 // Variably modified types are not supported for tasks.
7735 if (!Type->isAnyPointerType() && Type->isVariablyModifiedType() &&
7736 isOpenMPTaskingDirective(DSAStack->getCurrentDirective())) {
7737 Diag(ELoc, diag::err_omp_variably_modified_type_not_supported)
7738 << getOpenMPClauseName(OMPC_firstprivate) << Type
7739 << getOpenMPDirectiveName(DSAStack->getCurrentDirective());
7742 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
7743 Diag(D->getLocation(),
7744 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
7749 Type = Type.getUnqualifiedType();
7750 auto VDPrivate = buildVarDecl(*this, ELoc, Type, D->getName(),
7751 D->hasAttrs() ? &D->getAttrs() : nullptr);
7752 // Generate helper private variable and initialize it with the value of the
7753 // original variable. The address of the original variable is replaced by
7754 // the address of the new private variable in the CodeGen. This new variable
7755 // is not added to IdResolver, so the code in the OpenMP region uses
7756 // original variable for proper diagnostics and variable capturing.
7757 Expr *VDInitRefExpr = nullptr;
7758 // For arrays generate initializer for single element and replace it by the
7759 // original array element in CodeGen.
7760 if (Type->isArrayType()) {
7762 buildVarDecl(*this, RefExpr->getExprLoc(), ElemType, D->getName());
7763 VDInitRefExpr = buildDeclRefExpr(*this, VDInit, ElemType, ELoc);
7764 auto Init = DefaultLvalueConversion(VDInitRefExpr).get();
7765 ElemType = ElemType.getUnqualifiedType();
7766 auto *VDInitTemp = buildVarDecl(*this, RefExpr->getExprLoc(), ElemType,
7767 ".firstprivate.temp");
7768 InitializedEntity Entity =
7769 InitializedEntity::InitializeVariable(VDInitTemp);
7770 InitializationKind Kind = InitializationKind::CreateCopy(ELoc, ELoc);
7772 InitializationSequence InitSeq(*this, Entity, Kind, Init);
7773 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Init);
7774 if (Result.isInvalid())
7775 VDPrivate->setInvalidDecl();
7777 VDPrivate->setInit(Result.getAs<Expr>());
7778 // Remove temp variable declaration.
7779 Context.Deallocate(VDInitTemp);
7781 auto *VDInit = buildVarDecl(*this, RefExpr->getExprLoc(), Type,
7782 ".firstprivate.temp");
7783 VDInitRefExpr = buildDeclRefExpr(*this, VDInit, RefExpr->getType(),
7784 RefExpr->getExprLoc());
7785 AddInitializerToDecl(VDPrivate,
7786 DefaultLvalueConversion(VDInitRefExpr).get(),
7787 /*DirectInit=*/false, /*TypeMayContainAuto=*/false);
7789 if (VDPrivate->isInvalidDecl()) {
7790 if (IsImplicitClause) {
7791 Diag(RefExpr->getExprLoc(),
7792 diag::note_omp_task_predetermined_firstprivate_here);
7796 CurContext->addDecl(VDPrivate);
7797 auto VDPrivateRefExpr = buildDeclRefExpr(
7798 *this, VDPrivate, RefExpr->getType().getUnqualifiedType(),
7799 RefExpr->getExprLoc());
7800 DeclRefExpr *Ref = nullptr;
7801 if (!VD && !CurContext->isDependentContext()) {
7802 if (TopDVar.CKind == OMPC_lastprivate)
7803 Ref = TopDVar.PrivateCopy;
7805 Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/true);
7806 if (!IsOpenMPCapturedDecl(D))
7807 ExprCaptures.push_back(Ref->getDecl());
7810 DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_firstprivate, Ref);
7811 Vars.push_back((VD || CurContext->isDependentContext())
7812 ? RefExpr->IgnoreParens()
7814 PrivateCopies.push_back(VDPrivateRefExpr);
7815 Inits.push_back(VDInitRefExpr);
7821 return OMPFirstprivateClause::Create(Context, StartLoc, LParenLoc, EndLoc,
7822 Vars, PrivateCopies, Inits,
7823 buildPreInits(Context, ExprCaptures));
7826 OMPClause *Sema::ActOnOpenMPLastprivateClause(ArrayRef<Expr *> VarList,
7827 SourceLocation StartLoc,
7828 SourceLocation LParenLoc,
7829 SourceLocation EndLoc) {
7830 SmallVector<Expr *, 8> Vars;
7831 SmallVector<Expr *, 8> SrcExprs;
7832 SmallVector<Expr *, 8> DstExprs;
7833 SmallVector<Expr *, 8> AssignmentOps;
7834 SmallVector<Decl *, 4> ExprCaptures;
7835 SmallVector<Expr *, 4> ExprPostUpdates;
7836 for (auto &RefExpr : VarList) {
7837 assert(RefExpr && "NULL expr in OpenMP lastprivate clause.");
7838 SourceLocation ELoc;
7840 Expr *SimpleRefExpr = RefExpr;
7841 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
7843 // It will be analyzed later.
7844 Vars.push_back(RefExpr);
7845 SrcExprs.push_back(nullptr);
7846 DstExprs.push_back(nullptr);
7847 AssignmentOps.push_back(nullptr);
7849 ValueDecl *D = Res.first;
7853 QualType Type = D->getType();
7854 auto *VD = dyn_cast<VarDecl>(D);
7856 // OpenMP [2.14.3.5, Restrictions, C/C++, p.2]
7857 // A variable that appears in a lastprivate clause must not have an
7858 // incomplete type or a reference type.
7859 if (RequireCompleteType(ELoc, Type,
7860 diag::err_omp_lastprivate_incomplete_type))
7862 Type = Type.getNonReferenceType();
7864 // OpenMP [2.14.1.1, Data-sharing Attribute Rules for Variables Referenced
7866 // Variables with the predetermined data-sharing attributes may not be
7867 // listed in data-sharing attributes clauses, except for the cases
7869 DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, false);
7870 if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_lastprivate &&
7871 DVar.CKind != OMPC_firstprivate &&
7872 (DVar.CKind != OMPC_private || DVar.RefExpr != nullptr)) {
7873 Diag(ELoc, diag::err_omp_wrong_dsa)
7874 << getOpenMPClauseName(DVar.CKind)
7875 << getOpenMPClauseName(OMPC_lastprivate);
7876 ReportOriginalDSA(*this, DSAStack, D, DVar);
7880 OpenMPDirectiveKind CurrDir = DSAStack->getCurrentDirective();
7881 // OpenMP [2.14.3.5, Restrictions, p.2]
7882 // A list item that is private within a parallel region, or that appears in
7883 // the reduction clause of a parallel construct, must not appear in a
7884 // lastprivate clause on a worksharing construct if any of the corresponding
7885 // worksharing regions ever binds to any of the corresponding parallel
7887 DSAStackTy::DSAVarData TopDVar = DVar;
7888 if (isOpenMPWorksharingDirective(CurrDir) &&
7889 !isOpenMPParallelDirective(CurrDir) &&
7890 !isOpenMPTeamsDirective(CurrDir)) {
7891 DVar = DSAStack->getImplicitDSA(D, true);
7892 if (DVar.CKind != OMPC_shared) {
7893 Diag(ELoc, diag::err_omp_required_access)
7894 << getOpenMPClauseName(OMPC_lastprivate)
7895 << getOpenMPClauseName(OMPC_shared);
7896 ReportOriginalDSA(*this, DSAStack, D, DVar);
7901 // OpenMP 4.5 [2.10.8, Distribute Construct, p.3]
7902 // A list item may appear in a firstprivate or lastprivate clause but not
7904 if (CurrDir == OMPD_distribute) {
7905 DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, false);
7906 if (DVar.CKind == OMPC_firstprivate) {
7907 Diag(ELoc, diag::err_omp_firstprivate_and_lastprivate_in_distribute);
7908 ReportOriginalDSA(*this, DSAStack, D, DVar);
7913 // OpenMP [2.14.3.5, Restrictions, C++, p.1,2]
7914 // A variable of class type (or array thereof) that appears in a
7915 // lastprivate clause requires an accessible, unambiguous default
7916 // constructor for the class type, unless the list item is also specified
7917 // in a firstprivate clause.
7918 // A variable of class type (or array thereof) that appears in a
7919 // lastprivate clause requires an accessible, unambiguous copy assignment
7920 // operator for the class type.
7921 Type = Context.getBaseElementType(Type).getNonReferenceType();
7922 auto *SrcVD = buildVarDecl(*this, ERange.getBegin(),
7923 Type.getUnqualifiedType(), ".lastprivate.src",
7924 D->hasAttrs() ? &D->getAttrs() : nullptr);
7925 auto *PseudoSrcExpr =
7926 buildDeclRefExpr(*this, SrcVD, Type.getUnqualifiedType(), ELoc);
7928 buildVarDecl(*this, ERange.getBegin(), Type, ".lastprivate.dst",
7929 D->hasAttrs() ? &D->getAttrs() : nullptr);
7930 auto *PseudoDstExpr = buildDeclRefExpr(*this, DstVD, Type, ELoc);
7931 // For arrays generate assignment operation for single element and replace
7932 // it by the original array element in CodeGen.
7933 auto AssignmentOp = BuildBinOp(/*S=*/nullptr, ELoc, BO_Assign,
7934 PseudoDstExpr, PseudoSrcExpr);
7935 if (AssignmentOp.isInvalid())
7937 AssignmentOp = ActOnFinishFullExpr(AssignmentOp.get(), ELoc,
7938 /*DiscardedValue=*/true);
7939 if (AssignmentOp.isInvalid())
7942 DeclRefExpr *Ref = nullptr;
7943 if (!VD && !CurContext->isDependentContext()) {
7944 if (TopDVar.CKind == OMPC_firstprivate)
7945 Ref = TopDVar.PrivateCopy;
7947 Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/false);
7948 if (!IsOpenMPCapturedDecl(D))
7949 ExprCaptures.push_back(Ref->getDecl());
7951 if (TopDVar.CKind == OMPC_firstprivate ||
7952 (!IsOpenMPCapturedDecl(D) &&
7953 Ref->getDecl()->hasAttr<OMPCaptureNoInitAttr>())) {
7954 ExprResult RefRes = DefaultLvalueConversion(Ref);
7955 if (!RefRes.isUsable())
7957 ExprResult PostUpdateRes =
7958 BuildBinOp(DSAStack->getCurScope(), ELoc, BO_Assign, SimpleRefExpr,
7960 if (!PostUpdateRes.isUsable())
7962 ExprPostUpdates.push_back(
7963 IgnoredValueConversions(PostUpdateRes.get()).get());
7966 DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_lastprivate, Ref);
7967 Vars.push_back((VD || CurContext->isDependentContext())
7968 ? RefExpr->IgnoreParens()
7970 SrcExprs.push_back(PseudoSrcExpr);
7971 DstExprs.push_back(PseudoDstExpr);
7972 AssignmentOps.push_back(AssignmentOp.get());
7978 return OMPLastprivateClause::Create(Context, StartLoc, LParenLoc, EndLoc,
7979 Vars, SrcExprs, DstExprs, AssignmentOps,
7980 buildPreInits(Context, ExprCaptures),
7981 buildPostUpdate(*this, ExprPostUpdates));
7984 OMPClause *Sema::ActOnOpenMPSharedClause(ArrayRef<Expr *> VarList,
7985 SourceLocation StartLoc,
7986 SourceLocation LParenLoc,
7987 SourceLocation EndLoc) {
7988 SmallVector<Expr *, 8> Vars;
7989 for (auto &RefExpr : VarList) {
7990 assert(RefExpr && "NULL expr in OpenMP lastprivate clause.");
7991 SourceLocation ELoc;
7993 Expr *SimpleRefExpr = RefExpr;
7994 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
7996 // It will be analyzed later.
7997 Vars.push_back(RefExpr);
7999 ValueDecl *D = Res.first;
8003 auto *VD = dyn_cast<VarDecl>(D);
8004 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
8006 // Variables with the predetermined data-sharing attributes may not be
8007 // listed in data-sharing attributes clauses, except for the cases
8008 // listed below. For these exceptions only, listing a predetermined
8009 // variable in a data-sharing attribute clause is allowed and overrides
8010 // the variable's predetermined data-sharing attributes.
8011 DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, false);
8012 if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_shared &&
8014 Diag(ELoc, diag::err_omp_wrong_dsa) << getOpenMPClauseName(DVar.CKind)
8015 << getOpenMPClauseName(OMPC_shared);
8016 ReportOriginalDSA(*this, DSAStack, D, DVar);
8020 DeclRefExpr *Ref = nullptr;
8021 if (!VD && IsOpenMPCapturedDecl(D) && !CurContext->isDependentContext())
8022 Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/true);
8023 DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_shared, Ref);
8024 Vars.push_back((VD || !Ref || CurContext->isDependentContext())
8025 ? RefExpr->IgnoreParens()
8032 return OMPSharedClause::Create(Context, StartLoc, LParenLoc, EndLoc, Vars);
8036 class DSARefChecker : public StmtVisitor<DSARefChecker, bool> {
8040 bool VisitDeclRefExpr(DeclRefExpr *E) {
8041 if (VarDecl *VD = dyn_cast<VarDecl>(E->getDecl())) {
8042 DSAStackTy::DSAVarData DVar = Stack->getTopDSA(VD, false);
8043 if (DVar.CKind == OMPC_shared && !DVar.RefExpr)
8045 if (DVar.CKind != OMPC_unknown)
8047 DSAStackTy::DSAVarData DVarPrivate = Stack->hasDSA(
8048 VD, isOpenMPPrivate, [](OpenMPDirectiveKind) -> bool { return true; },
8050 if (DVarPrivate.CKind != OMPC_unknown)
8056 bool VisitStmt(Stmt *S) {
8057 for (auto Child : S->children()) {
8058 if (Child && Visit(Child))
8063 explicit DSARefChecker(DSAStackTy *S) : Stack(S) {}
8068 // Transform MemberExpression for specified FieldDecl of current class to
8069 // DeclRefExpr to specified OMPCapturedExprDecl.
8070 class TransformExprToCaptures : public TreeTransform<TransformExprToCaptures> {
8071 typedef TreeTransform<TransformExprToCaptures> BaseTransform;
8073 DeclRefExpr *CapturedExpr;
8076 TransformExprToCaptures(Sema &SemaRef, ValueDecl *FieldDecl)
8077 : BaseTransform(SemaRef), Field(FieldDecl), CapturedExpr(nullptr) {}
8079 ExprResult TransformMemberExpr(MemberExpr *E) {
8080 if (isa<CXXThisExpr>(E->getBase()->IgnoreParenImpCasts()) &&
8081 E->getMemberDecl() == Field) {
8082 CapturedExpr = buildCapture(SemaRef, Field, E, /*WithInit=*/false);
8083 return CapturedExpr;
8085 return BaseTransform::TransformMemberExpr(E);
8087 DeclRefExpr *getCapturedExpr() { return CapturedExpr; }
8091 template <typename T>
8092 static T filterLookupForUDR(SmallVectorImpl<UnresolvedSet<8>> &Lookups,
8093 const llvm::function_ref<T(ValueDecl *)> &Gen) {
8094 for (auto &Set : Lookups) {
8095 for (auto *D : Set) {
8096 if (auto Res = Gen(cast<ValueDecl>(D)))
8104 buildDeclareReductionRef(Sema &SemaRef, SourceLocation Loc, SourceRange Range,
8105 Scope *S, CXXScopeSpec &ReductionIdScopeSpec,
8106 const DeclarationNameInfo &ReductionId, QualType Ty,
8107 CXXCastPath &BasePath, Expr *UnresolvedReduction) {
8108 if (ReductionIdScopeSpec.isInvalid())
8110 SmallVector<UnresolvedSet<8>, 4> Lookups;
8112 LookupResult Lookup(SemaRef, ReductionId, Sema::LookupOMPReductionName);
8113 Lookup.suppressDiagnostics();
8114 while (S && SemaRef.LookupParsedName(Lookup, S, &ReductionIdScopeSpec)) {
8115 auto *D = Lookup.getRepresentativeDecl();
8118 } while (S && !S->isDeclScope(D));
8121 Lookups.push_back(UnresolvedSet<8>());
8122 Lookups.back().append(Lookup.begin(), Lookup.end());
8125 } else if (auto *ULE =
8126 cast_or_null<UnresolvedLookupExpr>(UnresolvedReduction)) {
8127 Lookups.push_back(UnresolvedSet<8>());
8128 Decl *PrevD = nullptr;
8129 for (auto *D : ULE->decls()) {
8131 Lookups.push_back(UnresolvedSet<8>());
8132 else if (auto *DRD = cast<OMPDeclareReductionDecl>(D))
8133 Lookups.back().addDecl(DRD);
8137 if (Ty->isDependentType() || Ty->isInstantiationDependentType() ||
8138 Ty->containsUnexpandedParameterPack() ||
8139 filterLookupForUDR<bool>(Lookups, [](ValueDecl *D) -> bool {
8140 return !D->isInvalidDecl() &&
8141 (D->getType()->isDependentType() ||
8142 D->getType()->isInstantiationDependentType() ||
8143 D->getType()->containsUnexpandedParameterPack());
8145 UnresolvedSet<8> ResSet;
8146 for (auto &Set : Lookups) {
8147 ResSet.append(Set.begin(), Set.end());
8148 // The last item marks the end of all declarations at the specified scope.
8149 ResSet.addDecl(Set[Set.size() - 1]);
8151 return UnresolvedLookupExpr::Create(
8152 SemaRef.Context, /*NamingClass=*/nullptr,
8153 ReductionIdScopeSpec.getWithLocInContext(SemaRef.Context), ReductionId,
8154 /*ADL=*/true, /*Overloaded=*/true, ResSet.begin(), ResSet.end());
8156 if (auto *VD = filterLookupForUDR<ValueDecl *>(
8157 Lookups, [&SemaRef, Ty](ValueDecl *D) -> ValueDecl * {
8158 if (!D->isInvalidDecl() &&
8159 SemaRef.Context.hasSameType(D->getType(), Ty))
8163 return SemaRef.BuildDeclRefExpr(VD, Ty, VK_LValue, Loc);
8164 if (auto *VD = filterLookupForUDR<ValueDecl *>(
8165 Lookups, [&SemaRef, Ty, Loc](ValueDecl *D) -> ValueDecl * {
8166 if (!D->isInvalidDecl() &&
8167 SemaRef.IsDerivedFrom(Loc, Ty, D->getType()) &&
8168 !Ty.isMoreQualifiedThan(D->getType()))
8172 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
8173 /*DetectVirtual=*/false);
8174 if (SemaRef.IsDerivedFrom(Loc, Ty, VD->getType(), Paths)) {
8175 if (!Paths.isAmbiguous(SemaRef.Context.getCanonicalType(
8176 VD->getType().getUnqualifiedType()))) {
8177 if (SemaRef.CheckBaseClassAccess(Loc, VD->getType(), Ty, Paths.front(),
8179 Sema::AR_inaccessible) {
8180 SemaRef.BuildBasePathArray(Paths, BasePath);
8181 return SemaRef.BuildDeclRefExpr(VD, Ty, VK_LValue, Loc);
8186 if (ReductionIdScopeSpec.isSet()) {
8187 SemaRef.Diag(Loc, diag::err_omp_not_resolved_reduction_identifier) << Range;
8193 OMPClause *Sema::ActOnOpenMPReductionClause(
8194 ArrayRef<Expr *> VarList, SourceLocation StartLoc, SourceLocation LParenLoc,
8195 SourceLocation ColonLoc, SourceLocation EndLoc,
8196 CXXScopeSpec &ReductionIdScopeSpec, const DeclarationNameInfo &ReductionId,
8197 ArrayRef<Expr *> UnresolvedReductions) {
8198 auto DN = ReductionId.getName();
8199 auto OOK = DN.getCXXOverloadedOperator();
8200 BinaryOperatorKind BOK = BO_Comma;
8202 // OpenMP [2.14.3.6, reduction clause]
8204 // reduction-identifier is either an identifier or one of the following
8205 // operators: +, -, *, &, |, ^, && and ||
8207 // reduction-identifier is either an id-expression or one of the following
8208 // operators: +, -, *, &, |, ^, && and ||
8209 // FIXME: Only 'min' and 'max' identifiers are supported for now.
8236 case OO_Array_Delete:
8245 case OO_GreaterEqual:
8250 case OO_PercentEqual:
8255 case OO_GreaterGreater:
8256 case OO_LessLessEqual:
8257 case OO_GreaterGreaterEqual:
8259 case OO_ExclaimEqual:
8267 case OO_Conditional:
8269 case NUM_OVERLOADED_OPERATORS:
8270 llvm_unreachable("Unexpected reduction identifier");
8272 if (auto II = DN.getAsIdentifierInfo()) {
8273 if (II->isStr("max"))
8275 else if (II->isStr("min"))
8280 SourceRange ReductionIdRange;
8281 if (ReductionIdScopeSpec.isValid())
8282 ReductionIdRange.setBegin(ReductionIdScopeSpec.getBeginLoc());
8283 ReductionIdRange.setEnd(ReductionId.getEndLoc());
8285 SmallVector<Expr *, 8> Vars;
8286 SmallVector<Expr *, 8> Privates;
8287 SmallVector<Expr *, 8> LHSs;
8288 SmallVector<Expr *, 8> RHSs;
8289 SmallVector<Expr *, 8> ReductionOps;
8290 SmallVector<Decl *, 4> ExprCaptures;
8291 SmallVector<Expr *, 4> ExprPostUpdates;
8292 auto IR = UnresolvedReductions.begin(), ER = UnresolvedReductions.end();
8293 bool FirstIter = true;
8294 for (auto RefExpr : VarList) {
8295 assert(RefExpr && "nullptr expr in OpenMP reduction clause.");
8296 // OpenMP [2.1, C/C++]
8297 // A list item is a variable or array section, subject to the restrictions
8298 // specified in Section 2.4 on page 42 and in each of the sections
8299 // describing clauses and directives for which a list appears.
8300 // OpenMP [2.14.3.3, Restrictions, p.1]
8301 // A variable that is part of another variable (as an array or
8302 // structure element) cannot appear in a private clause.
8303 if (!FirstIter && IR != ER)
8306 SourceLocation ELoc;
8308 Expr *SimpleRefExpr = RefExpr;
8309 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange,
8310 /*AllowArraySection=*/true);
8312 // It will be analyzed later.
8313 Vars.push_back(RefExpr);
8314 Privates.push_back(nullptr);
8315 LHSs.push_back(nullptr);
8316 RHSs.push_back(nullptr);
8317 // Try to find 'declare reduction' corresponding construct before using
8318 // builtin/overloaded operators.
8319 QualType Type = Context.DependentTy;
8320 CXXCastPath BasePath;
8321 ExprResult DeclareReductionRef = buildDeclareReductionRef(
8322 *this, ELoc, ERange, DSAStack->getCurScope(), ReductionIdScopeSpec,
8323 ReductionId, Type, BasePath, IR == ER ? nullptr : *IR);
8324 if (CurContext->isDependentContext() &&
8325 (DeclareReductionRef.isUnset() ||
8326 isa<UnresolvedLookupExpr>(DeclareReductionRef.get())))
8327 ReductionOps.push_back(DeclareReductionRef.get());
8329 ReductionOps.push_back(nullptr);
8331 ValueDecl *D = Res.first;
8336 auto *ASE = dyn_cast<ArraySubscriptExpr>(RefExpr->IgnoreParens());
8337 auto *OASE = dyn_cast<OMPArraySectionExpr>(RefExpr->IgnoreParens());
8339 Type = ASE->getType().getNonReferenceType();
8341 auto BaseType = OMPArraySectionExpr::getBaseOriginalType(OASE->getBase());
8342 if (auto *ATy = BaseType->getAsArrayTypeUnsafe())
8343 Type = ATy->getElementType();
8345 Type = BaseType->getPointeeType();
8346 Type = Type.getNonReferenceType();
8348 Type = Context.getBaseElementType(D->getType().getNonReferenceType());
8349 auto *VD = dyn_cast<VarDecl>(D);
8351 // OpenMP [2.9.3.3, Restrictions, C/C++, p.3]
8352 // A variable that appears in a private clause must not have an incomplete
8353 // type or a reference type.
8354 if (RequireCompleteType(ELoc, Type,
8355 diag::err_omp_reduction_incomplete_type))
8357 // OpenMP [2.14.3.6, reduction clause, Restrictions]
8358 // A list item that appears in a reduction clause must not be
8360 if (Type.getNonReferenceType().isConstant(Context)) {
8361 Diag(ELoc, diag::err_omp_const_reduction_list_item)
8362 << getOpenMPClauseName(OMPC_reduction) << Type << ERange;
8363 if (!ASE && !OASE) {
8364 bool IsDecl = !VD ||
8365 VD->isThisDeclarationADefinition(Context) ==
8366 VarDecl::DeclarationOnly;
8367 Diag(D->getLocation(),
8368 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
8373 // OpenMP [2.9.3.6, Restrictions, C/C++, p.4]
8374 // If a list-item is a reference type then it must bind to the same object
8375 // for all threads of the team.
8376 if (!ASE && !OASE && VD) {
8377 VarDecl *VDDef = VD->getDefinition();
8378 if (VD->getType()->isReferenceType() && VDDef && VDDef->hasInit()) {
8379 DSARefChecker Check(DSAStack);
8380 if (Check.Visit(VDDef->getInit())) {
8381 Diag(ELoc, diag::err_omp_reduction_ref_type_arg) << ERange;
8382 Diag(VDDef->getLocation(), diag::note_defined_here) << VDDef;
8388 // OpenMP [2.14.1.1, Data-sharing Attribute Rules for Variables Referenced
8390 // Variables with the predetermined data-sharing attributes may not be
8391 // listed in data-sharing attributes clauses, except for the cases
8392 // listed below. For these exceptions only, listing a predetermined
8393 // variable in a data-sharing attribute clause is allowed and overrides
8394 // the variable's predetermined data-sharing attributes.
8395 // OpenMP [2.14.3.6, Restrictions, p.3]
8396 // Any number of reduction clauses can be specified on the directive,
8397 // but a list item can appear only once in the reduction clauses for that
8399 DSAStackTy::DSAVarData DVar;
8400 DVar = DSAStack->getTopDSA(D, false);
8401 if (DVar.CKind == OMPC_reduction) {
8402 Diag(ELoc, diag::err_omp_once_referenced)
8403 << getOpenMPClauseName(OMPC_reduction);
8405 Diag(DVar.RefExpr->getExprLoc(), diag::note_omp_referenced);
8406 } else if (DVar.CKind != OMPC_unknown) {
8407 Diag(ELoc, diag::err_omp_wrong_dsa)
8408 << getOpenMPClauseName(DVar.CKind)
8409 << getOpenMPClauseName(OMPC_reduction);
8410 ReportOriginalDSA(*this, DSAStack, D, DVar);
8414 // OpenMP [2.14.3.6, Restrictions, p.1]
8415 // A list item that appears in a reduction clause of a worksharing
8416 // construct must be shared in the parallel regions to which any of the
8417 // worksharing regions arising from the worksharing construct bind.
8418 OpenMPDirectiveKind CurrDir = DSAStack->getCurrentDirective();
8419 if (isOpenMPWorksharingDirective(CurrDir) &&
8420 !isOpenMPParallelDirective(CurrDir) &&
8421 !isOpenMPTeamsDirective(CurrDir)) {
8422 DVar = DSAStack->getImplicitDSA(D, true);
8423 if (DVar.CKind != OMPC_shared) {
8424 Diag(ELoc, diag::err_omp_required_access)
8425 << getOpenMPClauseName(OMPC_reduction)
8426 << getOpenMPClauseName(OMPC_shared);
8427 ReportOriginalDSA(*this, DSAStack, D, DVar);
8432 // Try to find 'declare reduction' corresponding construct before using
8433 // builtin/overloaded operators.
8434 CXXCastPath BasePath;
8435 ExprResult DeclareReductionRef = buildDeclareReductionRef(
8436 *this, ELoc, ERange, DSAStack->getCurScope(), ReductionIdScopeSpec,
8437 ReductionId, Type, BasePath, IR == ER ? nullptr : *IR);
8438 if (DeclareReductionRef.isInvalid())
8440 if (CurContext->isDependentContext() &&
8441 (DeclareReductionRef.isUnset() ||
8442 isa<UnresolvedLookupExpr>(DeclareReductionRef.get()))) {
8443 Vars.push_back(RefExpr);
8444 Privates.push_back(nullptr);
8445 LHSs.push_back(nullptr);
8446 RHSs.push_back(nullptr);
8447 ReductionOps.push_back(DeclareReductionRef.get());
8450 if (BOK == BO_Comma && DeclareReductionRef.isUnset()) {
8451 // Not allowed reduction identifier is found.
8452 Diag(ReductionId.getLocStart(),
8453 diag::err_omp_unknown_reduction_identifier)
8454 << Type << ReductionIdRange;
8458 // OpenMP [2.14.3.6, reduction clause, Restrictions]
8459 // The type of a list item that appears in a reduction clause must be valid
8460 // for the reduction-identifier. For a max or min reduction in C, the type
8461 // of the list item must be an allowed arithmetic data type: char, int,
8462 // float, double, or _Bool, possibly modified with long, short, signed, or
8463 // unsigned. For a max or min reduction in C++, the type of the list item
8464 // must be an allowed arithmetic data type: char, wchar_t, int, float,
8465 // double, or bool, possibly modified with long, short, signed, or unsigned.
8466 if (DeclareReductionRef.isUnset()) {
8467 if ((BOK == BO_GT || BOK == BO_LT) &&
8468 !(Type->isScalarType() ||
8469 (getLangOpts().CPlusPlus && Type->isArithmeticType()))) {
8470 Diag(ELoc, diag::err_omp_clause_not_arithmetic_type_arg)
8471 << getLangOpts().CPlusPlus;
8472 if (!ASE && !OASE) {
8473 bool IsDecl = !VD ||
8474 VD->isThisDeclarationADefinition(Context) ==
8475 VarDecl::DeclarationOnly;
8476 Diag(D->getLocation(),
8477 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
8482 if ((BOK == BO_OrAssign || BOK == BO_AndAssign || BOK == BO_XorAssign) &&
8483 !getLangOpts().CPlusPlus && Type->isFloatingType()) {
8484 Diag(ELoc, diag::err_omp_clause_floating_type_arg);
8485 if (!ASE && !OASE) {
8486 bool IsDecl = !VD ||
8487 VD->isThisDeclarationADefinition(Context) ==
8488 VarDecl::DeclarationOnly;
8489 Diag(D->getLocation(),
8490 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
8497 Type = Type.getNonLValueExprType(Context).getUnqualifiedType();
8498 auto *LHSVD = buildVarDecl(*this, ELoc, Type, ".reduction.lhs",
8499 D->hasAttrs() ? &D->getAttrs() : nullptr);
8500 auto *RHSVD = buildVarDecl(*this, ELoc, Type, D->getName(),
8501 D->hasAttrs() ? &D->getAttrs() : nullptr);
8502 auto PrivateTy = Type;
8505 D->getType().getNonReferenceType()->isVariablyModifiedType())) {
8506 // For arrays/array sections only:
8507 // Create pseudo array type for private copy. The size for this array will
8508 // be generated during codegen.
8509 // For array subscripts or single variables Private Ty is the same as Type
8510 // (type of the variable or single array element).
8511 PrivateTy = Context.getVariableArrayType(
8512 Type, new (Context) OpaqueValueExpr(SourceLocation(),
8513 Context.getSizeType(), VK_RValue),
8514 ArrayType::Normal, /*IndexTypeQuals=*/0, SourceRange());
8515 } else if (!ASE && !OASE &&
8516 Context.getAsArrayType(D->getType().getNonReferenceType()))
8517 PrivateTy = D->getType().getNonReferenceType();
8519 auto *PrivateVD = buildVarDecl(*this, ELoc, PrivateTy, D->getName(),
8520 D->hasAttrs() ? &D->getAttrs() : nullptr);
8521 // Add initializer for private variable.
8522 Expr *Init = nullptr;
8523 auto *LHSDRE = buildDeclRefExpr(*this, LHSVD, Type, ELoc);
8524 auto *RHSDRE = buildDeclRefExpr(*this, RHSVD, Type, ELoc);
8525 if (DeclareReductionRef.isUsable()) {
8526 auto *DRDRef = DeclareReductionRef.getAs<DeclRefExpr>();
8527 auto *DRD = cast<OMPDeclareReductionDecl>(DRDRef->getDecl());
8528 if (DRD->getInitializer()) {
8530 RHSVD->setInit(DRDRef);
8531 RHSVD->setInitStyle(VarDecl::CallInit);
8539 // '+', '-', '^', '|', '||' reduction ops - initializer is '0'.
8540 if (Type->isScalarType() || Type->isAnyComplexType())
8541 Init = ActOnIntegerConstant(ELoc, /*Val=*/0).get();
8545 if (Type->isScalarType() || Type->isAnyComplexType()) {
8546 // '*' and '&&' reduction ops - initializer is '1'.
8547 Init = ActOnIntegerConstant(ELoc, /*Val=*/1).get();
8551 // '&' reduction op - initializer is '~0'.
8552 QualType OrigType = Type;
8553 if (auto *ComplexTy = OrigType->getAs<ComplexType>())
8554 Type = ComplexTy->getElementType();
8555 if (Type->isRealFloatingType()) {
8556 llvm::APFloat InitValue =
8557 llvm::APFloat::getAllOnesValue(Context.getTypeSize(Type),
8559 Init = FloatingLiteral::Create(Context, InitValue, /*isexact=*/true,
8561 } else if (Type->isScalarType()) {
8562 auto Size = Context.getTypeSize(Type);
8563 QualType IntTy = Context.getIntTypeForBitwidth(Size, /*Signed=*/0);
8564 llvm::APInt InitValue = llvm::APInt::getAllOnesValue(Size);
8565 Init = IntegerLiteral::Create(Context, InitValue, IntTy, ELoc);
8567 if (Init && OrigType->isAnyComplexType()) {
8568 // Init = 0xFFFF + 0xFFFFi;
8569 auto *Im = new (Context) ImaginaryLiteral(Init, OrigType);
8570 Init = CreateBuiltinBinOp(ELoc, BO_Add, Init, Im).get();
8577 // 'min' reduction op - initializer is 'Largest representable number in
8578 // the reduction list item type'.
8579 // 'max' reduction op - initializer is 'Least representable number in
8580 // the reduction list item type'.
8581 if (Type->isIntegerType() || Type->isPointerType()) {
8582 bool IsSigned = Type->hasSignedIntegerRepresentation();
8583 auto Size = Context.getTypeSize(Type);
8585 Context.getIntTypeForBitwidth(Size, /*Signed=*/IsSigned);
8586 llvm::APInt InitValue =
8588 ? IsSigned ? llvm::APInt::getSignedMinValue(Size)
8589 : llvm::APInt::getMinValue(Size)
8590 : IsSigned ? llvm::APInt::getSignedMaxValue(Size)
8591 : llvm::APInt::getMaxValue(Size);
8592 Init = IntegerLiteral::Create(Context, InitValue, IntTy, ELoc);
8593 if (Type->isPointerType()) {
8594 // Cast to pointer type.
8595 auto CastExpr = BuildCStyleCastExpr(
8596 SourceLocation(), Context.getTrivialTypeSourceInfo(Type, ELoc),
8597 SourceLocation(), Init);
8598 if (CastExpr.isInvalid())
8600 Init = CastExpr.get();
8602 } else if (Type->isRealFloatingType()) {
8603 llvm::APFloat InitValue = llvm::APFloat::getLargest(
8604 Context.getFloatTypeSemantics(Type), BOK != BO_LT);
8605 Init = FloatingLiteral::Create(Context, InitValue, /*isexact=*/true,
8633 llvm_unreachable("Unexpected reduction operation");
8636 if (Init && DeclareReductionRef.isUnset()) {
8637 AddInitializerToDecl(RHSVD, Init, /*DirectInit=*/false,
8638 /*TypeMayContainAuto=*/false);
8640 ActOnUninitializedDecl(RHSVD, /*TypeMayContainAuto=*/false);
8641 if (RHSVD->isInvalidDecl())
8643 if (!RHSVD->hasInit() && DeclareReductionRef.isUnset()) {
8644 Diag(ELoc, diag::err_omp_reduction_id_not_compatible) << Type
8645 << ReductionIdRange;
8648 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
8649 Diag(D->getLocation(),
8650 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
8654 // Store initializer for single element in private copy. Will be used during
8656 PrivateVD->setInit(RHSVD->getInit());
8657 PrivateVD->setInitStyle(RHSVD->getInitStyle());
8658 auto *PrivateDRE = buildDeclRefExpr(*this, PrivateVD, PrivateTy, ELoc);
8659 ExprResult ReductionOp;
8660 if (DeclareReductionRef.isUsable()) {
8661 QualType RedTy = DeclareReductionRef.get()->getType();
8662 QualType PtrRedTy = Context.getPointerType(RedTy);
8663 ExprResult LHS = CreateBuiltinUnaryOp(ELoc, UO_AddrOf, LHSDRE);
8664 ExprResult RHS = CreateBuiltinUnaryOp(ELoc, UO_AddrOf, RHSDRE);
8665 if (!BasePath.empty()) {
8666 LHS = DefaultLvalueConversion(LHS.get());
8667 RHS = DefaultLvalueConversion(RHS.get());
8668 LHS = ImplicitCastExpr::Create(Context, PtrRedTy,
8669 CK_UncheckedDerivedToBase, LHS.get(),
8670 &BasePath, LHS.get()->getValueKind());
8671 RHS = ImplicitCastExpr::Create(Context, PtrRedTy,
8672 CK_UncheckedDerivedToBase, RHS.get(),
8673 &BasePath, RHS.get()->getValueKind());
8675 FunctionProtoType::ExtProtoInfo EPI;
8676 QualType Params[] = {PtrRedTy, PtrRedTy};
8677 QualType FnTy = Context.getFunctionType(Context.VoidTy, Params, EPI);
8678 auto *OVE = new (Context) OpaqueValueExpr(
8679 ELoc, Context.getPointerType(FnTy), VK_RValue, OK_Ordinary,
8680 DefaultLvalueConversion(DeclareReductionRef.get()).get());
8681 Expr *Args[] = {LHS.get(), RHS.get()};
8682 ReductionOp = new (Context)
8683 CallExpr(Context, OVE, Args, Context.VoidTy, VK_RValue, ELoc);
8685 ReductionOp = BuildBinOp(DSAStack->getCurScope(),
8686 ReductionId.getLocStart(), BOK, LHSDRE, RHSDRE);
8687 if (ReductionOp.isUsable()) {
8688 if (BOK != BO_LT && BOK != BO_GT) {
8690 BuildBinOp(DSAStack->getCurScope(), ReductionId.getLocStart(),
8691 BO_Assign, LHSDRE, ReductionOp.get());
8693 auto *ConditionalOp = new (Context) ConditionalOperator(
8694 ReductionOp.get(), SourceLocation(), LHSDRE, SourceLocation(),
8695 RHSDRE, Type, VK_LValue, OK_Ordinary);
8697 BuildBinOp(DSAStack->getCurScope(), ReductionId.getLocStart(),
8698 BO_Assign, LHSDRE, ConditionalOp);
8700 ReductionOp = ActOnFinishFullExpr(ReductionOp.get());
8702 if (ReductionOp.isInvalid())
8706 DeclRefExpr *Ref = nullptr;
8707 Expr *VarsExpr = RefExpr->IgnoreParens();
8708 if (!VD && !CurContext->isDependentContext()) {
8710 TransformExprToCaptures RebuildToCapture(*this, D);
8712 RebuildToCapture.TransformExpr(RefExpr->IgnoreParens()).get();
8713 Ref = RebuildToCapture.getCapturedExpr();
8716 buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/false);
8718 if (!IsOpenMPCapturedDecl(D)) {
8719 ExprCaptures.push_back(Ref->getDecl());
8720 if (Ref->getDecl()->hasAttr<OMPCaptureNoInitAttr>()) {
8721 ExprResult RefRes = DefaultLvalueConversion(Ref);
8722 if (!RefRes.isUsable())
8724 ExprResult PostUpdateRes =
8725 BuildBinOp(DSAStack->getCurScope(), ELoc, BO_Assign,
8726 SimpleRefExpr, RefRes.get());
8727 if (!PostUpdateRes.isUsable())
8729 ExprPostUpdates.push_back(
8730 IgnoredValueConversions(PostUpdateRes.get()).get());
8734 DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_reduction, Ref);
8735 Vars.push_back(VarsExpr);
8736 Privates.push_back(PrivateDRE);
8737 LHSs.push_back(LHSDRE);
8738 RHSs.push_back(RHSDRE);
8739 ReductionOps.push_back(ReductionOp.get());
8745 return OMPReductionClause::Create(
8746 Context, StartLoc, LParenLoc, ColonLoc, EndLoc, Vars,
8747 ReductionIdScopeSpec.getWithLocInContext(Context), ReductionId, Privates,
8748 LHSs, RHSs, ReductionOps, buildPreInits(Context, ExprCaptures),
8749 buildPostUpdate(*this, ExprPostUpdates));
8752 bool Sema::CheckOpenMPLinearModifier(OpenMPLinearClauseKind LinKind,
8753 SourceLocation LinLoc) {
8754 if ((!LangOpts.CPlusPlus && LinKind != OMPC_LINEAR_val) ||
8755 LinKind == OMPC_LINEAR_unknown) {
8756 Diag(LinLoc, diag::err_omp_wrong_linear_modifier) << LangOpts.CPlusPlus;
8762 bool Sema::CheckOpenMPLinearDecl(ValueDecl *D, SourceLocation ELoc,
8763 OpenMPLinearClauseKind LinKind,
8765 auto *VD = dyn_cast_or_null<VarDecl>(D);
8766 // A variable must not have an incomplete type or a reference type.
8767 if (RequireCompleteType(ELoc, Type, diag::err_omp_linear_incomplete_type))
8769 if ((LinKind == OMPC_LINEAR_uval || LinKind == OMPC_LINEAR_ref) &&
8770 !Type->isReferenceType()) {
8771 Diag(ELoc, diag::err_omp_wrong_linear_modifier_non_reference)
8772 << Type << getOpenMPSimpleClauseTypeName(OMPC_linear, LinKind);
8775 Type = Type.getNonReferenceType();
8777 // A list item must not be const-qualified.
8778 if (Type.isConstant(Context)) {
8779 Diag(ELoc, diag::err_omp_const_variable)
8780 << getOpenMPClauseName(OMPC_linear);
8784 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
8785 Diag(D->getLocation(),
8786 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
8792 // A list item must be of integral or pointer type.
8793 Type = Type.getUnqualifiedType().getCanonicalType();
8794 const auto *Ty = Type.getTypePtrOrNull();
8795 if (!Ty || (!Ty->isDependentType() && !Ty->isIntegralType(Context) &&
8796 !Ty->isPointerType())) {
8797 Diag(ELoc, diag::err_omp_linear_expected_int_or_ptr) << Type;
8801 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
8802 Diag(D->getLocation(),
8803 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
8811 OMPClause *Sema::ActOnOpenMPLinearClause(
8812 ArrayRef<Expr *> VarList, Expr *Step, SourceLocation StartLoc,
8813 SourceLocation LParenLoc, OpenMPLinearClauseKind LinKind,
8814 SourceLocation LinLoc, SourceLocation ColonLoc, SourceLocation EndLoc) {
8815 SmallVector<Expr *, 8> Vars;
8816 SmallVector<Expr *, 8> Privates;
8817 SmallVector<Expr *, 8> Inits;
8818 SmallVector<Decl *, 4> ExprCaptures;
8819 SmallVector<Expr *, 4> ExprPostUpdates;
8820 if (CheckOpenMPLinearModifier(LinKind, LinLoc))
8821 LinKind = OMPC_LINEAR_val;
8822 for (auto &RefExpr : VarList) {
8823 assert(RefExpr && "NULL expr in OpenMP linear clause.");
8824 SourceLocation ELoc;
8826 Expr *SimpleRefExpr = RefExpr;
8827 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange,
8828 /*AllowArraySection=*/false);
8830 // It will be analyzed later.
8831 Vars.push_back(RefExpr);
8832 Privates.push_back(nullptr);
8833 Inits.push_back(nullptr);
8835 ValueDecl *D = Res.first;
8839 QualType Type = D->getType();
8840 auto *VD = dyn_cast<VarDecl>(D);
8842 // OpenMP [2.14.3.7, linear clause]
8843 // A list-item cannot appear in more than one linear clause.
8844 // A list-item that appears in a linear clause cannot appear in any
8845 // other data-sharing attribute clause.
8846 DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, false);
8848 Diag(ELoc, diag::err_omp_wrong_dsa) << getOpenMPClauseName(DVar.CKind)
8849 << getOpenMPClauseName(OMPC_linear);
8850 ReportOriginalDSA(*this, DSAStack, D, DVar);
8854 if (CheckOpenMPLinearDecl(D, ELoc, LinKind, Type))
8856 Type = Type.getNonReferenceType().getUnqualifiedType().getCanonicalType();
8858 // Build private copy of original var.
8859 auto *Private = buildVarDecl(*this, ELoc, Type, D->getName(),
8860 D->hasAttrs() ? &D->getAttrs() : nullptr);
8861 auto *PrivateRef = buildDeclRefExpr(*this, Private, Type, ELoc);
8862 // Build var to save initial value.
8863 VarDecl *Init = buildVarDecl(*this, ELoc, Type, ".linear.start");
8865 DeclRefExpr *Ref = nullptr;
8866 if (!VD && !CurContext->isDependentContext()) {
8867 Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/false);
8868 if (!IsOpenMPCapturedDecl(D)) {
8869 ExprCaptures.push_back(Ref->getDecl());
8870 if (Ref->getDecl()->hasAttr<OMPCaptureNoInitAttr>()) {
8871 ExprResult RefRes = DefaultLvalueConversion(Ref);
8872 if (!RefRes.isUsable())
8874 ExprResult PostUpdateRes =
8875 BuildBinOp(DSAStack->getCurScope(), ELoc, BO_Assign,
8876 SimpleRefExpr, RefRes.get());
8877 if (!PostUpdateRes.isUsable())
8879 ExprPostUpdates.push_back(
8880 IgnoredValueConversions(PostUpdateRes.get()).get());
8884 if (LinKind == OMPC_LINEAR_uval)
8885 InitExpr = VD ? VD->getInit() : SimpleRefExpr;
8887 InitExpr = VD ? SimpleRefExpr : Ref;
8888 AddInitializerToDecl(Init, DefaultLvalueConversion(InitExpr).get(),
8889 /*DirectInit=*/false, /*TypeMayContainAuto=*/false);
8890 auto InitRef = buildDeclRefExpr(*this, Init, Type, ELoc);
8892 DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_linear, Ref);
8893 Vars.push_back((VD || CurContext->isDependentContext())
8894 ? RefExpr->IgnoreParens()
8896 Privates.push_back(PrivateRef);
8897 Inits.push_back(InitRef);
8903 Expr *StepExpr = Step;
8904 Expr *CalcStepExpr = nullptr;
8905 if (Step && !Step->isValueDependent() && !Step->isTypeDependent() &&
8906 !Step->isInstantiationDependent() &&
8907 !Step->containsUnexpandedParameterPack()) {
8908 SourceLocation StepLoc = Step->getLocStart();
8909 ExprResult Val = PerformOpenMPImplicitIntegerConversion(StepLoc, Step);
8910 if (Val.isInvalid())
8912 StepExpr = Val.get();
8914 // Build var to save the step value.
8916 buildVarDecl(*this, StepLoc, StepExpr->getType(), ".linear.step");
8917 ExprResult SaveRef =
8918 buildDeclRefExpr(*this, SaveVar, StepExpr->getType(), StepLoc);
8919 ExprResult CalcStep =
8920 BuildBinOp(CurScope, StepLoc, BO_Assign, SaveRef.get(), StepExpr);
8921 CalcStep = ActOnFinishFullExpr(CalcStep.get());
8923 // Warn about zero linear step (it would be probably better specified as
8924 // making corresponding variables 'const').
8925 llvm::APSInt Result;
8926 bool IsConstant = StepExpr->isIntegerConstantExpr(Result, Context);
8927 if (IsConstant && !Result.isNegative() && !Result.isStrictlyPositive())
8928 Diag(StepLoc, diag::warn_omp_linear_step_zero) << Vars[0]
8929 << (Vars.size() > 1);
8930 if (!IsConstant && CalcStep.isUsable()) {
8931 // Calculate the step beforehand instead of doing this on each iteration.
8932 // (This is not used if the number of iterations may be kfold-ed).
8933 CalcStepExpr = CalcStep.get();
8937 return OMPLinearClause::Create(Context, StartLoc, LParenLoc, LinKind, LinLoc,
8938 ColonLoc, EndLoc, Vars, Privates, Inits,
8939 StepExpr, CalcStepExpr,
8940 buildPreInits(Context, ExprCaptures),
8941 buildPostUpdate(*this, ExprPostUpdates));
8944 static bool FinishOpenMPLinearClause(OMPLinearClause &Clause, DeclRefExpr *IV,
8945 Expr *NumIterations, Sema &SemaRef,
8946 Scope *S, DSAStackTy *Stack) {
8947 // Walk the vars and build update/final expressions for the CodeGen.
8948 SmallVector<Expr *, 8> Updates;
8949 SmallVector<Expr *, 8> Finals;
8950 Expr *Step = Clause.getStep();
8951 Expr *CalcStep = Clause.getCalcStep();
8952 // OpenMP [2.14.3.7, linear clause]
8953 // If linear-step is not specified it is assumed to be 1.
8954 if (Step == nullptr)
8955 Step = SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get();
8956 else if (CalcStep) {
8957 Step = cast<BinaryOperator>(CalcStep)->getLHS();
8959 bool HasErrors = false;
8960 auto CurInit = Clause.inits().begin();
8961 auto CurPrivate = Clause.privates().begin();
8962 auto LinKind = Clause.getModifier();
8963 for (auto &RefExpr : Clause.varlists()) {
8964 SourceLocation ELoc;
8966 Expr *SimpleRefExpr = RefExpr;
8967 auto Res = getPrivateItem(SemaRef, SimpleRefExpr, ELoc, ERange,
8968 /*AllowArraySection=*/false);
8969 ValueDecl *D = Res.first;
8970 if (Res.second || !D) {
8971 Updates.push_back(nullptr);
8972 Finals.push_back(nullptr);
8976 if (auto *CED = dyn_cast<OMPCapturedExprDecl>(D)) {
8977 D = cast<MemberExpr>(CED->getInit()->IgnoreParenImpCasts())
8980 auto &&Info = Stack->isLoopControlVariable(D);
8981 Expr *InitExpr = *CurInit;
8983 // Build privatized reference to the current linear var.
8984 auto *DE = cast<DeclRefExpr>(SimpleRefExpr);
8986 if (LinKind == OMPC_LINEAR_uval)
8987 CapturedRef = cast<VarDecl>(DE->getDecl())->getInit();
8990 buildDeclRefExpr(SemaRef, cast<VarDecl>(DE->getDecl()),
8991 DE->getType().getUnqualifiedType(), DE->getExprLoc(),
8992 /*RefersToCapture=*/true);
8994 // Build update: Var = InitExpr + IV * Step
8998 BuildCounterUpdate(SemaRef, S, RefExpr->getExprLoc(), *CurPrivate,
8999 InitExpr, IV, Step, /* Subtract */ false);
9001 Update = *CurPrivate;
9002 Update = SemaRef.ActOnFinishFullExpr(Update.get(), DE->getLocStart(),
9003 /*DiscardedValue=*/true);
9005 // Build final: Var = InitExpr + NumIterations * Step
9008 Final = BuildCounterUpdate(SemaRef, S, RefExpr->getExprLoc(), CapturedRef,
9009 InitExpr, NumIterations, Step,
9010 /* Subtract */ false);
9012 Final = *CurPrivate;
9013 Final = SemaRef.ActOnFinishFullExpr(Final.get(), DE->getLocStart(),
9014 /*DiscardedValue=*/true);
9016 if (!Update.isUsable() || !Final.isUsable()) {
9017 Updates.push_back(nullptr);
9018 Finals.push_back(nullptr);
9021 Updates.push_back(Update.get());
9022 Finals.push_back(Final.get());
9027 Clause.setUpdates(Updates);
9028 Clause.setFinals(Finals);
9032 OMPClause *Sema::ActOnOpenMPAlignedClause(
9033 ArrayRef<Expr *> VarList, Expr *Alignment, SourceLocation StartLoc,
9034 SourceLocation LParenLoc, SourceLocation ColonLoc, SourceLocation EndLoc) {
9036 SmallVector<Expr *, 8> Vars;
9037 for (auto &RefExpr : VarList) {
9038 assert(RefExpr && "NULL expr in OpenMP linear clause.");
9039 SourceLocation ELoc;
9041 Expr *SimpleRefExpr = RefExpr;
9042 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange,
9043 /*AllowArraySection=*/false);
9045 // It will be analyzed later.
9046 Vars.push_back(RefExpr);
9048 ValueDecl *D = Res.first;
9052 QualType QType = D->getType();
9053 auto *VD = dyn_cast<VarDecl>(D);
9055 // OpenMP [2.8.1, simd construct, Restrictions]
9056 // The type of list items appearing in the aligned clause must be
9057 // array, pointer, reference to array, or reference to pointer.
9058 QType = QType.getNonReferenceType().getUnqualifiedType().getCanonicalType();
9059 const Type *Ty = QType.getTypePtrOrNull();
9060 if (!Ty || (!Ty->isArrayType() && !Ty->isPointerType())) {
9061 Diag(ELoc, diag::err_omp_aligned_expected_array_or_ptr)
9062 << QType << getLangOpts().CPlusPlus << ERange;
9065 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
9066 Diag(D->getLocation(),
9067 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
9072 // OpenMP [2.8.1, simd construct, Restrictions]
9073 // A list-item cannot appear in more than one aligned clause.
9074 if (Expr *PrevRef = DSAStack->addUniqueAligned(D, SimpleRefExpr)) {
9075 Diag(ELoc, diag::err_omp_aligned_twice) << 0 << ERange;
9076 Diag(PrevRef->getExprLoc(), diag::note_omp_explicit_dsa)
9077 << getOpenMPClauseName(OMPC_aligned);
9081 DeclRefExpr *Ref = nullptr;
9082 if (!VD && IsOpenMPCapturedDecl(D))
9083 Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/true);
9084 Vars.push_back(DefaultFunctionArrayConversion(
9085 (VD || !Ref) ? RefExpr->IgnoreParens() : Ref)
9089 // OpenMP [2.8.1, simd construct, Description]
9090 // The parameter of the aligned clause, alignment, must be a constant
9091 // positive integer expression.
9092 // If no optional parameter is specified, implementation-defined default
9093 // alignments for SIMD instructions on the target platforms are assumed.
9094 if (Alignment != nullptr) {
9095 ExprResult AlignResult =
9096 VerifyPositiveIntegerConstantInClause(Alignment, OMPC_aligned);
9097 if (AlignResult.isInvalid())
9099 Alignment = AlignResult.get();
9104 return OMPAlignedClause::Create(Context, StartLoc, LParenLoc, ColonLoc,
9105 EndLoc, Vars, Alignment);
9108 OMPClause *Sema::ActOnOpenMPCopyinClause(ArrayRef<Expr *> VarList,
9109 SourceLocation StartLoc,
9110 SourceLocation LParenLoc,
9111 SourceLocation EndLoc) {
9112 SmallVector<Expr *, 8> Vars;
9113 SmallVector<Expr *, 8> SrcExprs;
9114 SmallVector<Expr *, 8> DstExprs;
9115 SmallVector<Expr *, 8> AssignmentOps;
9116 for (auto &RefExpr : VarList) {
9117 assert(RefExpr && "NULL expr in OpenMP copyin clause.");
9118 if (isa<DependentScopeDeclRefExpr>(RefExpr)) {
9119 // It will be analyzed later.
9120 Vars.push_back(RefExpr);
9121 SrcExprs.push_back(nullptr);
9122 DstExprs.push_back(nullptr);
9123 AssignmentOps.push_back(nullptr);
9127 SourceLocation ELoc = RefExpr->getExprLoc();
9128 // OpenMP [2.1, C/C++]
9129 // A list item is a variable name.
9130 // OpenMP [2.14.4.1, Restrictions, p.1]
9131 // A list item that appears in a copyin clause must be threadprivate.
9132 DeclRefExpr *DE = dyn_cast<DeclRefExpr>(RefExpr);
9133 if (!DE || !isa<VarDecl>(DE->getDecl())) {
9134 Diag(ELoc, diag::err_omp_expected_var_name_member_expr)
9135 << 0 << RefExpr->getSourceRange();
9139 Decl *D = DE->getDecl();
9140 VarDecl *VD = cast<VarDecl>(D);
9142 QualType Type = VD->getType();
9143 if (Type->isDependentType() || Type->isInstantiationDependentType()) {
9144 // It will be analyzed later.
9146 SrcExprs.push_back(nullptr);
9147 DstExprs.push_back(nullptr);
9148 AssignmentOps.push_back(nullptr);
9152 // OpenMP [2.14.4.1, Restrictions, C/C++, p.1]
9153 // A list item that appears in a copyin clause must be threadprivate.
9154 if (!DSAStack->isThreadPrivate(VD)) {
9155 Diag(ELoc, diag::err_omp_required_access)
9156 << getOpenMPClauseName(OMPC_copyin)
9157 << getOpenMPDirectiveName(OMPD_threadprivate);
9161 // OpenMP [2.14.4.1, Restrictions, C/C++, p.2]
9162 // A variable of class type (or array thereof) that appears in a
9163 // copyin clause requires an accessible, unambiguous copy assignment
9164 // operator for the class type.
9165 auto ElemType = Context.getBaseElementType(Type).getNonReferenceType();
9167 buildVarDecl(*this, DE->getLocStart(), ElemType.getUnqualifiedType(),
9168 ".copyin.src", VD->hasAttrs() ? &VD->getAttrs() : nullptr);
9169 auto *PseudoSrcExpr = buildDeclRefExpr(
9170 *this, SrcVD, ElemType.getUnqualifiedType(), DE->getExprLoc());
9172 buildVarDecl(*this, DE->getLocStart(), ElemType, ".copyin.dst",
9173 VD->hasAttrs() ? &VD->getAttrs() : nullptr);
9174 auto *PseudoDstExpr =
9175 buildDeclRefExpr(*this, DstVD, ElemType, DE->getExprLoc());
9176 // For arrays generate assignment operation for single element and replace
9177 // it by the original array element in CodeGen.
9178 auto AssignmentOp = BuildBinOp(/*S=*/nullptr, DE->getExprLoc(), BO_Assign,
9179 PseudoDstExpr, PseudoSrcExpr);
9180 if (AssignmentOp.isInvalid())
9182 AssignmentOp = ActOnFinishFullExpr(AssignmentOp.get(), DE->getExprLoc(),
9183 /*DiscardedValue=*/true);
9184 if (AssignmentOp.isInvalid())
9187 DSAStack->addDSA(VD, DE, OMPC_copyin);
9189 SrcExprs.push_back(PseudoSrcExpr);
9190 DstExprs.push_back(PseudoDstExpr);
9191 AssignmentOps.push_back(AssignmentOp.get());
9197 return OMPCopyinClause::Create(Context, StartLoc, LParenLoc, EndLoc, Vars,
9198 SrcExprs, DstExprs, AssignmentOps);
9201 OMPClause *Sema::ActOnOpenMPCopyprivateClause(ArrayRef<Expr *> VarList,
9202 SourceLocation StartLoc,
9203 SourceLocation LParenLoc,
9204 SourceLocation EndLoc) {
9205 SmallVector<Expr *, 8> Vars;
9206 SmallVector<Expr *, 8> SrcExprs;
9207 SmallVector<Expr *, 8> DstExprs;
9208 SmallVector<Expr *, 8> AssignmentOps;
9209 for (auto &RefExpr : VarList) {
9210 assert(RefExpr && "NULL expr in OpenMP linear clause.");
9211 SourceLocation ELoc;
9213 Expr *SimpleRefExpr = RefExpr;
9214 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange,
9215 /*AllowArraySection=*/false);
9217 // It will be analyzed later.
9218 Vars.push_back(RefExpr);
9219 SrcExprs.push_back(nullptr);
9220 DstExprs.push_back(nullptr);
9221 AssignmentOps.push_back(nullptr);
9223 ValueDecl *D = Res.first;
9227 QualType Type = D->getType();
9228 auto *VD = dyn_cast<VarDecl>(D);
9230 // OpenMP [2.14.4.2, Restrictions, p.2]
9231 // A list item that appears in a copyprivate clause may not appear in a
9232 // private or firstprivate clause on the single construct.
9233 if (!VD || !DSAStack->isThreadPrivate(VD)) {
9234 auto DVar = DSAStack->getTopDSA(D, false);
9235 if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_copyprivate &&
9237 Diag(ELoc, diag::err_omp_wrong_dsa)
9238 << getOpenMPClauseName(DVar.CKind)
9239 << getOpenMPClauseName(OMPC_copyprivate);
9240 ReportOriginalDSA(*this, DSAStack, D, DVar);
9244 // OpenMP [2.11.4.2, Restrictions, p.1]
9245 // All list items that appear in a copyprivate clause must be either
9246 // threadprivate or private in the enclosing context.
9247 if (DVar.CKind == OMPC_unknown) {
9248 DVar = DSAStack->getImplicitDSA(D, false);
9249 if (DVar.CKind == OMPC_shared) {
9250 Diag(ELoc, diag::err_omp_required_access)
9251 << getOpenMPClauseName(OMPC_copyprivate)
9252 << "threadprivate or private in the enclosing context";
9253 ReportOriginalDSA(*this, DSAStack, D, DVar);
9259 // Variably modified types are not supported.
9260 if (!Type->isAnyPointerType() && Type->isVariablyModifiedType()) {
9261 Diag(ELoc, diag::err_omp_variably_modified_type_not_supported)
9262 << getOpenMPClauseName(OMPC_copyprivate) << Type
9263 << getOpenMPDirectiveName(DSAStack->getCurrentDirective());
9266 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
9267 Diag(D->getLocation(),
9268 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
9273 // OpenMP [2.14.4.1, Restrictions, C/C++, p.2]
9274 // A variable of class type (or array thereof) that appears in a
9275 // copyin clause requires an accessible, unambiguous copy assignment
9276 // operator for the class type.
9277 Type = Context.getBaseElementType(Type.getNonReferenceType())
9278 .getUnqualifiedType();
9280 buildVarDecl(*this, RefExpr->getLocStart(), Type, ".copyprivate.src",
9281 D->hasAttrs() ? &D->getAttrs() : nullptr);
9282 auto *PseudoSrcExpr = buildDeclRefExpr(*this, SrcVD, Type, ELoc);
9284 buildVarDecl(*this, RefExpr->getLocStart(), Type, ".copyprivate.dst",
9285 D->hasAttrs() ? &D->getAttrs() : nullptr);
9286 auto *PseudoDstExpr = buildDeclRefExpr(*this, DstVD, Type, ELoc);
9287 auto AssignmentOp = BuildBinOp(DSAStack->getCurScope(), ELoc, BO_Assign,
9288 PseudoDstExpr, PseudoSrcExpr);
9289 if (AssignmentOp.isInvalid())
9291 AssignmentOp = ActOnFinishFullExpr(AssignmentOp.get(), ELoc,
9292 /*DiscardedValue=*/true);
9293 if (AssignmentOp.isInvalid())
9296 // No need to mark vars as copyprivate, they are already threadprivate or
9297 // implicitly private.
9298 assert(VD || IsOpenMPCapturedDecl(D));
9300 VD ? RefExpr->IgnoreParens()
9301 : buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/false));
9302 SrcExprs.push_back(PseudoSrcExpr);
9303 DstExprs.push_back(PseudoDstExpr);
9304 AssignmentOps.push_back(AssignmentOp.get());
9310 return OMPCopyprivateClause::Create(Context, StartLoc, LParenLoc, EndLoc,
9311 Vars, SrcExprs, DstExprs, AssignmentOps);
9314 OMPClause *Sema::ActOnOpenMPFlushClause(ArrayRef<Expr *> VarList,
9315 SourceLocation StartLoc,
9316 SourceLocation LParenLoc,
9317 SourceLocation EndLoc) {
9318 if (VarList.empty())
9321 return OMPFlushClause::Create(Context, StartLoc, LParenLoc, EndLoc, VarList);
9325 Sema::ActOnOpenMPDependClause(OpenMPDependClauseKind DepKind,
9326 SourceLocation DepLoc, SourceLocation ColonLoc,
9327 ArrayRef<Expr *> VarList, SourceLocation StartLoc,
9328 SourceLocation LParenLoc, SourceLocation EndLoc) {
9329 if (DSAStack->getCurrentDirective() == OMPD_ordered &&
9330 DepKind != OMPC_DEPEND_source && DepKind != OMPC_DEPEND_sink) {
9331 Diag(DepLoc, diag::err_omp_unexpected_clause_value)
9332 << "'source' or 'sink'" << getOpenMPClauseName(OMPC_depend);
9335 if (DSAStack->getCurrentDirective() != OMPD_ordered &&
9336 (DepKind == OMPC_DEPEND_unknown || DepKind == OMPC_DEPEND_source ||
9337 DepKind == OMPC_DEPEND_sink)) {
9338 unsigned Except[] = {OMPC_DEPEND_source, OMPC_DEPEND_sink};
9339 Diag(DepLoc, diag::err_omp_unexpected_clause_value)
9340 << getListOfPossibleValues(OMPC_depend, /*First=*/0,
9341 /*Last=*/OMPC_DEPEND_unknown, Except)
9342 << getOpenMPClauseName(OMPC_depend);
9345 SmallVector<Expr *, 8> Vars;
9346 DSAStackTy::OperatorOffsetTy OpsOffs;
9347 llvm::APSInt DepCounter(/*BitWidth=*/32);
9348 llvm::APSInt TotalDepCount(/*BitWidth=*/32);
9349 if (DepKind == OMPC_DEPEND_sink) {
9350 if (auto *OrderedCountExpr = DSAStack->getParentOrderedRegionParam()) {
9351 TotalDepCount = OrderedCountExpr->EvaluateKnownConstInt(Context);
9352 TotalDepCount.setIsUnsigned(/*Val=*/true);
9355 if ((DepKind != OMPC_DEPEND_sink && DepKind != OMPC_DEPEND_source) ||
9356 DSAStack->getParentOrderedRegionParam()) {
9357 for (auto &RefExpr : VarList) {
9358 assert(RefExpr && "NULL expr in OpenMP shared clause.");
9359 if (isa<DependentScopeDeclRefExpr>(RefExpr)) {
9360 // It will be analyzed later.
9361 Vars.push_back(RefExpr);
9365 SourceLocation ELoc = RefExpr->getExprLoc();
9366 auto *SimpleExpr = RefExpr->IgnoreParenCasts();
9367 if (DepKind == OMPC_DEPEND_sink) {
9368 if (DepCounter >= TotalDepCount) {
9369 Diag(ELoc, diag::err_omp_depend_sink_unexpected_expr);
9373 // OpenMP [2.13.9, Summary]
9374 // depend(dependence-type : vec), where dependence-type is:
9375 // 'sink' and where vec is the iteration vector, which has the form:
9376 // x1 [+- d1], x2 [+- d2 ], . . . , xn [+- dn]
9377 // where n is the value specified by the ordered clause in the loop
9378 // directive, xi denotes the loop iteration variable of the i-th nested
9379 // loop associated with the loop directive, and di is a constant
9380 // non-negative integer.
9381 if (CurContext->isDependentContext()) {
9382 // It will be analyzed later.
9383 Vars.push_back(RefExpr);
9386 SimpleExpr = SimpleExpr->IgnoreImplicit();
9387 OverloadedOperatorKind OOK = OO_None;
9388 SourceLocation OOLoc;
9389 Expr *LHS = SimpleExpr;
9390 Expr *RHS = nullptr;
9391 if (auto *BO = dyn_cast<BinaryOperator>(SimpleExpr)) {
9392 OOK = BinaryOperator::getOverloadedOperator(BO->getOpcode());
9393 OOLoc = BO->getOperatorLoc();
9394 LHS = BO->getLHS()->IgnoreParenImpCasts();
9395 RHS = BO->getRHS()->IgnoreParenImpCasts();
9396 } else if (auto *OCE = dyn_cast<CXXOperatorCallExpr>(SimpleExpr)) {
9397 OOK = OCE->getOperator();
9398 OOLoc = OCE->getOperatorLoc();
9399 LHS = OCE->getArg(/*Arg=*/0)->IgnoreParenImpCasts();
9400 RHS = OCE->getArg(/*Arg=*/1)->IgnoreParenImpCasts();
9401 } else if (auto *MCE = dyn_cast<CXXMemberCallExpr>(SimpleExpr)) {
9402 OOK = MCE->getMethodDecl()
9405 .getCXXOverloadedOperator();
9406 OOLoc = MCE->getCallee()->getExprLoc();
9407 LHS = MCE->getImplicitObjectArgument()->IgnoreParenImpCasts();
9408 RHS = MCE->getArg(/*Arg=*/0)->IgnoreParenImpCasts();
9410 SourceLocation ELoc;
9412 auto Res = getPrivateItem(*this, LHS, ELoc, ERange,
9413 /*AllowArraySection=*/false);
9415 // It will be analyzed later.
9416 Vars.push_back(RefExpr);
9418 ValueDecl *D = Res.first;
9422 if (OOK != OO_Plus && OOK != OO_Minus && (RHS || OOK != OO_None)) {
9423 Diag(OOLoc, diag::err_omp_depend_sink_expected_plus_minus);
9427 ExprResult RHSRes = VerifyPositiveIntegerConstantInClause(
9428 RHS, OMPC_depend, /*StrictlyPositive=*/false);
9429 if (RHSRes.isInvalid())
9432 if (!CurContext->isDependentContext() &&
9433 DSAStack->getParentOrderedRegionParam() &&
9434 DepCounter != DSAStack->isParentLoopControlVariable(D).first) {
9435 Diag(ELoc, diag::err_omp_depend_sink_expected_loop_iteration)
9436 << DSAStack->getParentLoopControlVariable(
9437 DepCounter.getZExtValue());
9440 OpsOffs.push_back({RHS, OOK});
9442 // OpenMP [2.11.1.1, Restrictions, p.3]
9443 // A variable that is part of another variable (such as a field of a
9444 // structure) but is not an array element or an array section cannot
9445 // appear in a depend clause.
9446 auto *DE = dyn_cast<DeclRefExpr>(SimpleExpr);
9447 auto *ASE = dyn_cast<ArraySubscriptExpr>(SimpleExpr);
9448 auto *OASE = dyn_cast<OMPArraySectionExpr>(SimpleExpr);
9449 if (!RefExpr->IgnoreParenImpCasts()->isLValue() ||
9450 (!ASE && !DE && !OASE) || (DE && !isa<VarDecl>(DE->getDecl())) ||
9454 .getNonReferenceType()
9455 ->isPointerType() &&
9456 !ASE->getBase()->getType().getNonReferenceType()->isArrayType())) {
9457 Diag(ELoc, diag::err_omp_expected_var_name_member_expr_or_array_item)
9458 << 0 << RefExpr->getSourceRange();
9462 Vars.push_back(RefExpr->IgnoreParenImpCasts());
9465 if (!CurContext->isDependentContext() && DepKind == OMPC_DEPEND_sink &&
9466 TotalDepCount > VarList.size() &&
9467 DSAStack->getParentOrderedRegionParam()) {
9468 Diag(EndLoc, diag::err_omp_depend_sink_expected_loop_iteration)
9469 << DSAStack->getParentLoopControlVariable(VarList.size() + 1);
9471 if (DepKind != OMPC_DEPEND_source && DepKind != OMPC_DEPEND_sink &&
9475 auto *C = OMPDependClause::Create(Context, StartLoc, LParenLoc, EndLoc,
9476 DepKind, DepLoc, ColonLoc, Vars);
9477 if (DepKind == OMPC_DEPEND_sink || DepKind == OMPC_DEPEND_source)
9478 DSAStack->addDoacrossDependClause(C, OpsOffs);
9482 OMPClause *Sema::ActOnOpenMPDeviceClause(Expr *Device, SourceLocation StartLoc,
9483 SourceLocation LParenLoc,
9484 SourceLocation EndLoc) {
9485 Expr *ValExpr = Device;
9487 // OpenMP [2.9.1, Restrictions]
9488 // The device expression must evaluate to a non-negative integer value.
9489 if (!IsNonNegativeIntegerValue(ValExpr, *this, OMPC_device,
9490 /*StrictlyPositive=*/false))
9493 return new (Context) OMPDeviceClause(ValExpr, StartLoc, LParenLoc, EndLoc);
9496 static bool IsCXXRecordForMappable(Sema &SemaRef, SourceLocation Loc,
9497 DSAStackTy *Stack, CXXRecordDecl *RD) {
9498 if (!RD || RD->isInvalidDecl())
9501 auto QTy = SemaRef.Context.getRecordType(RD);
9502 if (RD->isDynamicClass()) {
9503 SemaRef.Diag(Loc, diag::err_omp_not_mappable_type) << QTy;
9504 SemaRef.Diag(RD->getLocation(), diag::note_omp_polymorphic_in_target);
9508 bool IsCorrect = true;
9509 for (auto *I : DC->decls()) {
9511 if (auto *MD = dyn_cast<CXXMethodDecl>(I)) {
9512 if (MD->isStatic()) {
9513 SemaRef.Diag(Loc, diag::err_omp_not_mappable_type) << QTy;
9514 SemaRef.Diag(MD->getLocation(),
9515 diag::note_omp_static_member_in_target);
9518 } else if (auto *VD = dyn_cast<VarDecl>(I)) {
9519 if (VD->isStaticDataMember()) {
9520 SemaRef.Diag(Loc, diag::err_omp_not_mappable_type) << QTy;
9521 SemaRef.Diag(VD->getLocation(),
9522 diag::note_omp_static_member_in_target);
9529 for (auto &I : RD->bases()) {
9530 if (!IsCXXRecordForMappable(SemaRef, I.getLocStart(), Stack,
9531 I.getType()->getAsCXXRecordDecl()))
9537 static bool CheckTypeMappable(SourceLocation SL, SourceRange SR, Sema &SemaRef,
9538 DSAStackTy *Stack, QualType QTy) {
9540 if (QTy->isIncompleteType(&ND)) {
9541 SemaRef.Diag(SL, diag::err_incomplete_type) << QTy << SR;
9543 } else if (CXXRecordDecl *RD = dyn_cast_or_null<CXXRecordDecl>(ND)) {
9544 if (!RD->isInvalidDecl() && !IsCXXRecordForMappable(SemaRef, SL, Stack, RD))
9550 /// \brief Return true if it can be proven that the provided array expression
9551 /// (array section or array subscript) does NOT specify the whole size of the
9552 /// array whose base type is \a BaseQTy.
9553 static bool CheckArrayExpressionDoesNotReferToWholeSize(Sema &SemaRef,
9556 auto *OASE = dyn_cast<OMPArraySectionExpr>(E);
9558 // If this is an array subscript, it refers to the whole size if the size of
9559 // the dimension is constant and equals 1. Also, an array section assumes the
9560 // format of an array subscript if no colon is used.
9561 if (isa<ArraySubscriptExpr>(E) || (OASE && OASE->getColonLoc().isInvalid())) {
9562 if (auto *ATy = dyn_cast<ConstantArrayType>(BaseQTy.getTypePtr()))
9563 return ATy->getSize().getSExtValue() != 1;
9564 // Size can't be evaluated statically.
9568 assert(OASE && "Expecting array section if not an array subscript.");
9569 auto *LowerBound = OASE->getLowerBound();
9570 auto *Length = OASE->getLength();
9572 // If there is a lower bound that does not evaluates to zero, we are not
9573 // covering the whole dimension.
9575 llvm::APSInt ConstLowerBound;
9576 if (!LowerBound->EvaluateAsInt(ConstLowerBound, SemaRef.getASTContext()))
9577 return false; // Can't get the integer value as a constant.
9578 if (ConstLowerBound.getSExtValue())
9582 // If we don't have a length we covering the whole dimension.
9586 // If the base is a pointer, we don't have a way to get the size of the
9588 if (BaseQTy->isPointerType())
9591 // We can only check if the length is the same as the size of the dimension
9592 // if we have a constant array.
9593 auto *CATy = dyn_cast<ConstantArrayType>(BaseQTy.getTypePtr());
9597 llvm::APSInt ConstLength;
9598 if (!Length->EvaluateAsInt(ConstLength, SemaRef.getASTContext()))
9599 return false; // Can't get the integer value as a constant.
9601 return CATy->getSize().getSExtValue() != ConstLength.getSExtValue();
9604 // Return true if it can be proven that the provided array expression (array
9605 // section or array subscript) does NOT specify a single element of the array
9606 // whose base type is \a BaseQTy.
9607 static bool CheckArrayExpressionDoesNotReferToUnitySize(Sema &SemaRef,
9610 auto *OASE = dyn_cast<OMPArraySectionExpr>(E);
9612 // An array subscript always refer to a single element. Also, an array section
9613 // assumes the format of an array subscript if no colon is used.
9614 if (isa<ArraySubscriptExpr>(E) || (OASE && OASE->getColonLoc().isInvalid()))
9617 assert(OASE && "Expecting array section if not an array subscript.");
9618 auto *Length = OASE->getLength();
9620 // If we don't have a length we have to check if the array has unitary size
9621 // for this dimension. Also, we should always expect a length if the base type
9624 if (auto *ATy = dyn_cast<ConstantArrayType>(BaseQTy.getTypePtr()))
9625 return ATy->getSize().getSExtValue() != 1;
9626 // We cannot assume anything.
9630 // Check if the length evaluates to 1.
9631 llvm::APSInt ConstLength;
9632 if (!Length->EvaluateAsInt(ConstLength, SemaRef.getASTContext()))
9633 return false; // Can't get the integer value as a constant.
9635 return ConstLength.getSExtValue() != 1;
9638 // Return the expression of the base of the mappable expression or null if it
9639 // cannot be determined and do all the necessary checks to see if the expression
9640 // is valid as a standalone mappable expression. In the process, record all the
9641 // components of the expression.
9642 static Expr *CheckMapClauseExpressionBase(
9643 Sema &SemaRef, Expr *E,
9644 OMPClauseMappableExprCommon::MappableExprComponentList &CurComponents,
9645 OpenMPClauseKind CKind) {
9646 SourceLocation ELoc = E->getExprLoc();
9647 SourceRange ERange = E->getSourceRange();
9649 // The base of elements of list in a map clause have to be either:
9650 // - a reference to variable or field.
9651 // - a member expression.
9652 // - an array expression.
9654 // E.g. if we have the expression 'r.S.Arr[:12]', we want to retrieve the
9655 // reference to 'r'.
9662 // #pragma omp target map (S.Arr[:12]);
9666 // We want to retrieve the member expression 'this->S';
9668 Expr *RelevantExpr = nullptr;
9670 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.2]
9671 // If a list item is an array section, it must specify contiguous storage.
9673 // For this restriction it is sufficient that we make sure only references
9674 // to variables or fields and array expressions, and that no array sections
9675 // exist except in the rightmost expression (unless they cover the whole
9676 // dimension of the array). E.g. these would be invalid:
9678 // r.ArrS[3:5].Arr[6:7]
9682 // but these would be valid:
9683 // r.ArrS[3].Arr[6:7]
9687 bool AllowUnitySizeArraySection = true;
9688 bool AllowWholeSizeArraySection = true;
9690 while (!RelevantExpr) {
9691 E = E->IgnoreParenImpCasts();
9693 if (auto *CurE = dyn_cast<DeclRefExpr>(E)) {
9694 if (!isa<VarDecl>(CurE->getDecl()))
9697 RelevantExpr = CurE;
9699 // If we got a reference to a declaration, we should not expect any array
9700 // section before that.
9701 AllowUnitySizeArraySection = false;
9702 AllowWholeSizeArraySection = false;
9704 // Record the component.
9705 CurComponents.push_back(OMPClauseMappableExprCommon::MappableComponent(
9706 CurE, CurE->getDecl()));
9710 if (auto *CurE = dyn_cast<MemberExpr>(E)) {
9711 auto *BaseE = CurE->getBase()->IgnoreParenImpCasts();
9713 if (isa<CXXThisExpr>(BaseE))
9714 // We found a base expression: this->Val.
9715 RelevantExpr = CurE;
9719 if (!isa<FieldDecl>(CurE->getMemberDecl())) {
9720 SemaRef.Diag(ELoc, diag::err_omp_expected_access_to_data_field)
9721 << CurE->getSourceRange();
9725 auto *FD = cast<FieldDecl>(CurE->getMemberDecl());
9727 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C/C++, p.3]
9728 // A bit-field cannot appear in a map clause.
9730 if (FD->isBitField()) {
9731 SemaRef.Diag(ELoc, diag::err_omp_bit_fields_forbidden_in_clause)
9732 << CurE->getSourceRange() << getOpenMPClauseName(CKind);
9736 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C++, p.1]
9737 // If the type of a list item is a reference to a type T then the type
9738 // will be considered to be T for all purposes of this clause.
9739 QualType CurType = BaseE->getType().getNonReferenceType();
9741 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C/C++, p.2]
9742 // A list item cannot be a variable that is a member of a structure with
9745 if (auto *RT = CurType->getAs<RecordType>())
9746 if (RT->isUnionType()) {
9747 SemaRef.Diag(ELoc, diag::err_omp_union_type_not_allowed)
9748 << CurE->getSourceRange();
9752 // If we got a member expression, we should not expect any array section
9755 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.7]
9756 // If a list item is an element of a structure, only the rightmost symbol
9757 // of the variable reference can be an array section.
9759 AllowUnitySizeArraySection = false;
9760 AllowWholeSizeArraySection = false;
9762 // Record the component.
9763 CurComponents.push_back(
9764 OMPClauseMappableExprCommon::MappableComponent(CurE, FD));
9768 if (auto *CurE = dyn_cast<ArraySubscriptExpr>(E)) {
9769 E = CurE->getBase()->IgnoreParenImpCasts();
9771 if (!E->getType()->isAnyPointerType() && !E->getType()->isArrayType()) {
9772 SemaRef.Diag(ELoc, diag::err_omp_expected_base_var_name)
9773 << 0 << CurE->getSourceRange();
9777 // If we got an array subscript that express the whole dimension we
9778 // can have any array expressions before. If it only expressing part of
9779 // the dimension, we can only have unitary-size array expressions.
9780 if (CheckArrayExpressionDoesNotReferToWholeSize(SemaRef, CurE,
9782 AllowWholeSizeArraySection = false;
9784 // Record the component - we don't have any declaration associated.
9785 CurComponents.push_back(
9786 OMPClauseMappableExprCommon::MappableComponent(CurE, nullptr));
9790 if (auto *CurE = dyn_cast<OMPArraySectionExpr>(E)) {
9791 E = CurE->getBase()->IgnoreParenImpCasts();
9794 OMPArraySectionExpr::getBaseOriginalType(E).getCanonicalType();
9796 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C++, p.1]
9797 // If the type of a list item is a reference to a type T then the type
9798 // will be considered to be T for all purposes of this clause.
9799 if (CurType->isReferenceType())
9800 CurType = CurType->getPointeeType();
9802 bool IsPointer = CurType->isAnyPointerType();
9804 if (!IsPointer && !CurType->isArrayType()) {
9805 SemaRef.Diag(ELoc, diag::err_omp_expected_base_var_name)
9806 << 0 << CurE->getSourceRange();
9811 CheckArrayExpressionDoesNotReferToWholeSize(SemaRef, CurE, CurType);
9813 CheckArrayExpressionDoesNotReferToUnitySize(SemaRef, CurE, CurType);
9815 if (AllowWholeSizeArraySection) {
9816 // Any array section is currently allowed. Allowing a whole size array
9817 // section implies allowing a unity array section as well.
9819 // If this array section refers to the whole dimension we can still
9820 // accept other array sections before this one, except if the base is a
9821 // pointer. Otherwise, only unitary sections are accepted.
9822 if (NotWhole || IsPointer)
9823 AllowWholeSizeArraySection = false;
9824 } else if (AllowUnitySizeArraySection && NotUnity) {
9825 // A unity or whole array section is not allowed and that is not
9826 // compatible with the properties of the current array section.
9828 ELoc, diag::err_array_section_does_not_specify_contiguous_storage)
9829 << CurE->getSourceRange();
9833 // Record the component - we don't have any declaration associated.
9834 CurComponents.push_back(
9835 OMPClauseMappableExprCommon::MappableComponent(CurE, nullptr));
9839 // If nothing else worked, this is not a valid map clause expression.
9841 diag::err_omp_expected_named_var_member_or_array_expression)
9846 return RelevantExpr;
9849 // Return true if expression E associated with value VD has conflicts with other
9851 static bool CheckMapConflicts(
9852 Sema &SemaRef, DSAStackTy *DSAS, ValueDecl *VD, Expr *E,
9853 bool CurrentRegionOnly,
9854 OMPClauseMappableExprCommon::MappableExprComponentListRef CurComponents,
9855 OpenMPClauseKind CKind) {
9857 SourceLocation ELoc = E->getExprLoc();
9858 SourceRange ERange = E->getSourceRange();
9860 // In order to easily check the conflicts we need to match each component of
9861 // the expression under test with the components of the expressions that are
9862 // already in the stack.
9864 assert(!CurComponents.empty() && "Map clause expression with no components!");
9865 assert(CurComponents.back().getAssociatedDeclaration() == VD &&
9866 "Map clause expression with unexpected base!");
9868 // Variables to help detecting enclosing problems in data environment nests.
9869 bool IsEnclosedByDataEnvironmentExpr = false;
9870 const Expr *EnclosingExpr = nullptr;
9872 bool FoundError = DSAS->checkMappableExprComponentListsForDecl(
9873 VD, CurrentRegionOnly,
9874 [&](OMPClauseMappableExprCommon::MappableExprComponentListRef
9876 OpenMPClauseKind) -> bool {
9878 assert(!StackComponents.empty() &&
9879 "Map clause expression with no components!");
9880 assert(StackComponents.back().getAssociatedDeclaration() == VD &&
9881 "Map clause expression with unexpected base!");
9883 // The whole expression in the stack.
9884 auto *RE = StackComponents.front().getAssociatedExpression();
9886 // Expressions must start from the same base. Here we detect at which
9887 // point both expressions diverge from each other and see if we can
9888 // detect if the memory referred to both expressions is contiguous and
9890 auto CI = CurComponents.rbegin();
9891 auto CE = CurComponents.rend();
9892 auto SI = StackComponents.rbegin();
9893 auto SE = StackComponents.rend();
9894 for (; CI != CE && SI != SE; ++CI, ++SI) {
9896 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.3]
9897 // At most one list item can be an array item derived from a given
9898 // variable in map clauses of the same construct.
9899 if (CurrentRegionOnly &&
9900 (isa<ArraySubscriptExpr>(CI->getAssociatedExpression()) ||
9901 isa<OMPArraySectionExpr>(CI->getAssociatedExpression())) &&
9902 (isa<ArraySubscriptExpr>(SI->getAssociatedExpression()) ||
9903 isa<OMPArraySectionExpr>(SI->getAssociatedExpression()))) {
9904 SemaRef.Diag(CI->getAssociatedExpression()->getExprLoc(),
9905 diag::err_omp_multiple_array_items_in_map_clause)
9906 << CI->getAssociatedExpression()->getSourceRange();
9907 SemaRef.Diag(SI->getAssociatedExpression()->getExprLoc(),
9908 diag::note_used_here)
9909 << SI->getAssociatedExpression()->getSourceRange();
9913 // Do both expressions have the same kind?
9914 if (CI->getAssociatedExpression()->getStmtClass() !=
9915 SI->getAssociatedExpression()->getStmtClass())
9918 // Are we dealing with different variables/fields?
9919 if (CI->getAssociatedDeclaration() != SI->getAssociatedDeclaration())
9922 // Check if the extra components of the expressions in the enclosing
9923 // data environment are redundant for the current base declaration.
9924 // If they are, the maps completely overlap, which is legal.
9925 for (; SI != SE; ++SI) {
9928 dyn_cast<ArraySubscriptExpr>(SI->getAssociatedExpression())) {
9929 Type = ASE->getBase()->IgnoreParenImpCasts()->getType();
9930 } else if (auto *OASE = dyn_cast<OMPArraySectionExpr>(
9931 SI->getAssociatedExpression())) {
9932 auto *E = OASE->getBase()->IgnoreParenImpCasts();
9934 OMPArraySectionExpr::getBaseOriginalType(E).getCanonicalType();
9936 if (Type.isNull() || Type->isAnyPointerType() ||
9937 CheckArrayExpressionDoesNotReferToWholeSize(
9938 SemaRef, SI->getAssociatedExpression(), Type))
9942 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.4]
9943 // List items of map clauses in the same construct must not share
9944 // original storage.
9946 // If the expressions are exactly the same or one is a subset of the
9947 // other, it means they are sharing storage.
9948 if (CI == CE && SI == SE) {
9949 if (CurrentRegionOnly) {
9950 if (CKind == OMPC_map)
9951 SemaRef.Diag(ELoc, diag::err_omp_map_shared_storage) << ERange;
9953 assert(CKind == OMPC_to || CKind == OMPC_from);
9954 SemaRef.Diag(ELoc, diag::err_omp_once_referenced_in_target_update)
9957 SemaRef.Diag(RE->getExprLoc(), diag::note_used_here)
9958 << RE->getSourceRange();
9961 // If we find the same expression in the enclosing data environment,
9963 IsEnclosedByDataEnvironmentExpr = true;
9968 QualType DerivedType =
9969 std::prev(CI)->getAssociatedDeclaration()->getType();
9970 SourceLocation DerivedLoc =
9971 std::prev(CI)->getAssociatedExpression()->getExprLoc();
9973 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C++, p.1]
9974 // If the type of a list item is a reference to a type T then the type
9975 // will be considered to be T for all purposes of this clause.
9976 DerivedType = DerivedType.getNonReferenceType();
9978 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C/C++, p.1]
9979 // A variable for which the type is pointer and an array section
9980 // derived from that variable must not appear as list items of map
9981 // clauses of the same construct.
9983 // Also, cover one of the cases in:
9984 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.5]
9985 // If any part of the original storage of a list item has corresponding
9986 // storage in the device data environment, all of the original storage
9987 // must have corresponding storage in the device data environment.
9989 if (DerivedType->isAnyPointerType()) {
9990 if (CI == CE || SI == SE) {
9993 diag::err_omp_pointer_mapped_along_with_derived_section)
9996 assert(CI != CE && SI != SE);
9997 SemaRef.Diag(DerivedLoc, diag::err_omp_same_pointer_derreferenced)
10000 SemaRef.Diag(RE->getExprLoc(), diag::note_used_here)
10001 << RE->getSourceRange();
10005 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.4]
10006 // List items of map clauses in the same construct must not share
10007 // original storage.
10009 // An expression is a subset of the other.
10010 if (CurrentRegionOnly && (CI == CE || SI == SE)) {
10011 if (CKind == OMPC_map)
10012 SemaRef.Diag(ELoc, diag::err_omp_map_shared_storage) << ERange;
10014 assert(CKind == OMPC_to || CKind == OMPC_from);
10015 SemaRef.Diag(ELoc, diag::err_omp_once_referenced_in_target_update)
10018 SemaRef.Diag(RE->getExprLoc(), diag::note_used_here)
10019 << RE->getSourceRange();
10023 // The current expression uses the same base as other expression in the
10024 // data environment but does not contain it completely.
10025 if (!CurrentRegionOnly && SI != SE)
10026 EnclosingExpr = RE;
10028 // The current expression is a subset of the expression in the data
10030 IsEnclosedByDataEnvironmentExpr |=
10031 (!CurrentRegionOnly && CI != CE && SI == SE);
10036 if (CurrentRegionOnly)
10039 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.5]
10040 // If any part of the original storage of a list item has corresponding
10041 // storage in the device data environment, all of the original storage must
10042 // have corresponding storage in the device data environment.
10043 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.6]
10044 // If a list item is an element of a structure, and a different element of
10045 // the structure has a corresponding list item in the device data environment
10046 // prior to a task encountering the construct associated with the map clause,
10047 // then the list item must also have a corresponding list item in the device
10048 // data environment prior to the task encountering the construct.
10050 if (EnclosingExpr && !IsEnclosedByDataEnvironmentExpr) {
10052 diag::err_omp_original_storage_is_shared_and_does_not_contain)
10054 SemaRef.Diag(EnclosingExpr->getExprLoc(), diag::note_used_here)
10055 << EnclosingExpr->getSourceRange();
10063 // Utility struct that gathers all the related lists associated with a mappable
10065 struct MappableVarListInfo final {
10066 // The list of expressions.
10067 ArrayRef<Expr *> VarList;
10068 // The list of processed expressions.
10069 SmallVector<Expr *, 16> ProcessedVarList;
10070 // The mappble components for each expression.
10071 OMPClauseMappableExprCommon::MappableExprComponentLists VarComponents;
10072 // The base declaration of the variable.
10073 SmallVector<ValueDecl *, 16> VarBaseDeclarations;
10075 MappableVarListInfo(ArrayRef<Expr *> VarList) : VarList(VarList) {
10076 // We have a list of components and base declarations for each entry in the
10078 VarComponents.reserve(VarList.size());
10079 VarBaseDeclarations.reserve(VarList.size());
10084 // Check the validity of the provided variable list for the provided clause kind
10085 // \a CKind. In the check process the valid expressions, and mappable expression
10086 // components and variables are extracted and used to fill \a Vars,
10087 // \a ClauseComponents, and \a ClauseBaseDeclarations. \a MapType and
10088 // \a IsMapTypeImplicit are expected to be valid if the clause kind is 'map'.
10090 checkMappableExpressionList(Sema &SemaRef, DSAStackTy *DSAS,
10091 OpenMPClauseKind CKind, MappableVarListInfo &MVLI,
10092 SourceLocation StartLoc,
10093 OpenMPMapClauseKind MapType = OMPC_MAP_unknown,
10094 bool IsMapTypeImplicit = false) {
10095 // We only expect mappable expressions in 'to', 'from', and 'map' clauses.
10096 assert((CKind == OMPC_map || CKind == OMPC_to || CKind == OMPC_from) &&
10097 "Unexpected clause kind with mappable expressions!");
10099 // Keep track of the mappable components and base declarations in this clause.
10100 // Each entry in the list is going to have a list of components associated. We
10101 // record each set of the components so that we can build the clause later on.
10102 // In the end we should have the same amount of declarations and component
10105 for (auto &RE : MVLI.VarList) {
10106 assert(RE && "Null expr in omp to/from/map clause");
10107 SourceLocation ELoc = RE->getExprLoc();
10109 auto *VE = RE->IgnoreParenLValueCasts();
10111 if (VE->isValueDependent() || VE->isTypeDependent() ||
10112 VE->isInstantiationDependent() ||
10113 VE->containsUnexpandedParameterPack()) {
10114 // We can only analyze this information once the missing information is
10116 MVLI.ProcessedVarList.push_back(RE);
10120 auto *SimpleExpr = RE->IgnoreParenCasts();
10122 if (!RE->IgnoreParenImpCasts()->isLValue()) {
10124 diag::err_omp_expected_named_var_member_or_array_expression)
10125 << RE->getSourceRange();
10129 OMPClauseMappableExprCommon::MappableExprComponentList CurComponents;
10130 ValueDecl *CurDeclaration = nullptr;
10132 // Obtain the array or member expression bases if required. Also, fill the
10133 // components array with all the components identified in the process.
10135 CheckMapClauseExpressionBase(SemaRef, SimpleExpr, CurComponents, CKind);
10139 assert(!CurComponents.empty() &&
10140 "Invalid mappable expression information.");
10142 // For the following checks, we rely on the base declaration which is
10143 // expected to be associated with the last component. The declaration is
10144 // expected to be a variable or a field (if 'this' is being mapped).
10145 CurDeclaration = CurComponents.back().getAssociatedDeclaration();
10146 assert(CurDeclaration && "Null decl on map clause.");
10148 CurDeclaration->isCanonicalDecl() &&
10149 "Expecting components to have associated only canonical declarations.");
10151 auto *VD = dyn_cast<VarDecl>(CurDeclaration);
10152 auto *FD = dyn_cast<FieldDecl>(CurDeclaration);
10154 assert((VD || FD) && "Only variables or fields are expected here!");
10157 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.10]
10158 // threadprivate variables cannot appear in a map clause.
10159 // OpenMP 4.5 [2.10.5, target update Construct]
10160 // threadprivate variables cannot appear in a from clause.
10161 if (VD && DSAS->isThreadPrivate(VD)) {
10162 auto DVar = DSAS->getTopDSA(VD, false);
10163 SemaRef.Diag(ELoc, diag::err_omp_threadprivate_in_clause)
10164 << getOpenMPClauseName(CKind);
10165 ReportOriginalDSA(SemaRef, DSAS, VD, DVar);
10169 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.9]
10170 // A list item cannot appear in both a map clause and a data-sharing
10171 // attribute clause on the same construct.
10173 // Check conflicts with other map clause expressions. We check the conflicts
10174 // with the current construct separately from the enclosing data
10175 // environment, because the restrictions are different. We only have to
10176 // check conflicts across regions for the map clauses.
10177 if (CheckMapConflicts(SemaRef, DSAS, CurDeclaration, SimpleExpr,
10178 /*CurrentRegionOnly=*/true, CurComponents, CKind))
10180 if (CKind == OMPC_map &&
10181 CheckMapConflicts(SemaRef, DSAS, CurDeclaration, SimpleExpr,
10182 /*CurrentRegionOnly=*/false, CurComponents, CKind))
10185 // OpenMP 4.5 [2.10.5, target update Construct]
10186 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C++, p.1]
10187 // If the type of a list item is a reference to a type T then the type will
10188 // be considered to be T for all purposes of this clause.
10189 QualType Type = CurDeclaration->getType().getNonReferenceType();
10191 // OpenMP 4.5 [2.10.5, target update Construct, Restrictions, p.4]
10192 // A list item in a to or from clause must have a mappable type.
10193 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.9]
10194 // A list item must have a mappable type.
10195 if (!CheckTypeMappable(VE->getExprLoc(), VE->getSourceRange(), SemaRef,
10199 if (CKind == OMPC_map) {
10200 // target enter data
10201 // OpenMP [2.10.2, Restrictions, p. 99]
10202 // A map-type must be specified in all map clauses and must be either
10204 OpenMPDirectiveKind DKind = DSAS->getCurrentDirective();
10205 if (DKind == OMPD_target_enter_data &&
10206 !(MapType == OMPC_MAP_to || MapType == OMPC_MAP_alloc)) {
10207 SemaRef.Diag(StartLoc, diag::err_omp_invalid_map_type_for_directive)
10208 << (IsMapTypeImplicit ? 1 : 0)
10209 << getOpenMPSimpleClauseTypeName(OMPC_map, MapType)
10210 << getOpenMPDirectiveName(DKind);
10214 // target exit_data
10215 // OpenMP [2.10.3, Restrictions, p. 102]
10216 // A map-type must be specified in all map clauses and must be either
10217 // from, release, or delete.
10218 if (DKind == OMPD_target_exit_data &&
10219 !(MapType == OMPC_MAP_from || MapType == OMPC_MAP_release ||
10220 MapType == OMPC_MAP_delete)) {
10221 SemaRef.Diag(StartLoc, diag::err_omp_invalid_map_type_for_directive)
10222 << (IsMapTypeImplicit ? 1 : 0)
10223 << getOpenMPSimpleClauseTypeName(OMPC_map, MapType)
10224 << getOpenMPDirectiveName(DKind);
10228 // OpenMP 4.5 [2.15.5.1, Restrictions, p.3]
10229 // A list item cannot appear in both a map clause and a data-sharing
10230 // attribute clause on the same construct
10231 if ((DKind == OMPD_target || DKind == OMPD_target_teams ||
10232 DKind == OMPD_target_teams_distribute ||
10233 DKind == OMPD_target_teams_distribute_parallel_for ||
10234 DKind == OMPD_target_teams_distribute_parallel_for_simd) && VD) {
10235 auto DVar = DSAS->getTopDSA(VD, false);
10236 if (isOpenMPPrivate(DVar.CKind)) {
10237 SemaRef.Diag(ELoc, diag::err_omp_variable_in_given_clause_and_dsa)
10238 << getOpenMPClauseName(DVar.CKind)
10239 << getOpenMPClauseName(OMPC_map)
10240 << getOpenMPDirectiveName(DSAS->getCurrentDirective());
10241 ReportOriginalDSA(SemaRef, DSAS, CurDeclaration, DVar);
10247 // Save the current expression.
10248 MVLI.ProcessedVarList.push_back(RE);
10250 // Store the components in the stack so that they can be used to check
10251 // against other clauses later on.
10252 DSAS->addMappableExpressionComponents(CurDeclaration, CurComponents,
10253 /*WhereFoundClauseKind=*/OMPC_map);
10255 // Save the components and declaration to create the clause. For purposes of
10256 // the clause creation, any component list that has has base 'this' uses
10257 // null as base declaration.
10258 MVLI.VarComponents.resize(MVLI.VarComponents.size() + 1);
10259 MVLI.VarComponents.back().append(CurComponents.begin(),
10260 CurComponents.end());
10261 MVLI.VarBaseDeclarations.push_back(isa<MemberExpr>(BE) ? nullptr
10267 Sema::ActOnOpenMPMapClause(OpenMPMapClauseKind MapTypeModifier,
10268 OpenMPMapClauseKind MapType, bool IsMapTypeImplicit,
10269 SourceLocation MapLoc, SourceLocation ColonLoc,
10270 ArrayRef<Expr *> VarList, SourceLocation StartLoc,
10271 SourceLocation LParenLoc, SourceLocation EndLoc) {
10272 MappableVarListInfo MVLI(VarList);
10273 checkMappableExpressionList(*this, DSAStack, OMPC_map, MVLI, StartLoc,
10274 MapType, IsMapTypeImplicit);
10276 // We need to produce a map clause even if we don't have variables so that
10277 // other diagnostics related with non-existing map clauses are accurate.
10278 return OMPMapClause::Create(Context, StartLoc, LParenLoc, EndLoc,
10279 MVLI.ProcessedVarList, MVLI.VarBaseDeclarations,
10280 MVLI.VarComponents, MapTypeModifier, MapType,
10281 IsMapTypeImplicit, MapLoc);
10284 QualType Sema::ActOnOpenMPDeclareReductionType(SourceLocation TyLoc,
10285 TypeResult ParsedType) {
10286 assert(ParsedType.isUsable());
10288 QualType ReductionType = GetTypeFromParser(ParsedType.get());
10289 if (ReductionType.isNull())
10292 // [OpenMP 4.0], 2.15 declare reduction Directive, Restrictions, C\C++
10293 // A type name in a declare reduction directive cannot be a function type, an
10294 // array type, a reference type, or a type qualified with const, volatile or
10296 if (ReductionType.hasQualifiers()) {
10297 Diag(TyLoc, diag::err_omp_reduction_wrong_type) << 0;
10301 if (ReductionType->isFunctionType()) {
10302 Diag(TyLoc, diag::err_omp_reduction_wrong_type) << 1;
10305 if (ReductionType->isReferenceType()) {
10306 Diag(TyLoc, diag::err_omp_reduction_wrong_type) << 2;
10309 if (ReductionType->isArrayType()) {
10310 Diag(TyLoc, diag::err_omp_reduction_wrong_type) << 3;
10313 return ReductionType;
10316 Sema::DeclGroupPtrTy Sema::ActOnOpenMPDeclareReductionDirectiveStart(
10317 Scope *S, DeclContext *DC, DeclarationName Name,
10318 ArrayRef<std::pair<QualType, SourceLocation>> ReductionTypes,
10319 AccessSpecifier AS, Decl *PrevDeclInScope) {
10320 SmallVector<Decl *, 8> Decls;
10321 Decls.reserve(ReductionTypes.size());
10323 LookupResult Lookup(*this, Name, SourceLocation(), LookupOMPReductionName,
10325 // [OpenMP 4.0], 2.15 declare reduction Directive, Restrictions
10326 // A reduction-identifier may not be re-declared in the current scope for the
10327 // same type or for a type that is compatible according to the base language
10329 llvm::DenseMap<QualType, SourceLocation> PreviousRedeclTypes;
10330 OMPDeclareReductionDecl *PrevDRD = nullptr;
10331 bool InCompoundScope = true;
10332 if (S != nullptr) {
10333 // Find previous declaration with the same name not referenced in other
10335 FunctionScopeInfo *ParentFn = getEnclosingFunction();
10337 (ParentFn != nullptr) && !ParentFn->CompoundScopes.empty();
10338 LookupName(Lookup, S);
10339 FilterLookupForScope(Lookup, DC, S, /*ConsiderLinkage=*/false,
10340 /*AllowInlineNamespace=*/false);
10341 llvm::DenseMap<OMPDeclareReductionDecl *, bool> UsedAsPrevious;
10342 auto Filter = Lookup.makeFilter();
10343 while (Filter.hasNext()) {
10344 auto *PrevDecl = cast<OMPDeclareReductionDecl>(Filter.next());
10345 if (InCompoundScope) {
10346 auto I = UsedAsPrevious.find(PrevDecl);
10347 if (I == UsedAsPrevious.end())
10348 UsedAsPrevious[PrevDecl] = false;
10349 if (auto *D = PrevDecl->getPrevDeclInScope())
10350 UsedAsPrevious[D] = true;
10352 PreviousRedeclTypes[PrevDecl->getType().getCanonicalType()] =
10353 PrevDecl->getLocation();
10356 if (InCompoundScope) {
10357 for (auto &PrevData : UsedAsPrevious) {
10358 if (!PrevData.second) {
10359 PrevDRD = PrevData.first;
10364 } else if (PrevDeclInScope != nullptr) {
10365 auto *PrevDRDInScope = PrevDRD =
10366 cast<OMPDeclareReductionDecl>(PrevDeclInScope);
10368 PreviousRedeclTypes[PrevDRDInScope->getType().getCanonicalType()] =
10369 PrevDRDInScope->getLocation();
10370 PrevDRDInScope = PrevDRDInScope->getPrevDeclInScope();
10371 } while (PrevDRDInScope != nullptr);
10373 for (auto &TyData : ReductionTypes) {
10374 auto I = PreviousRedeclTypes.find(TyData.first.getCanonicalType());
10375 bool Invalid = false;
10376 if (I != PreviousRedeclTypes.end()) {
10377 Diag(TyData.second, diag::err_omp_declare_reduction_redefinition)
10379 Diag(I->second, diag::note_previous_definition);
10382 PreviousRedeclTypes[TyData.first.getCanonicalType()] = TyData.second;
10383 auto *DRD = OMPDeclareReductionDecl::Create(Context, DC, TyData.second,
10384 Name, TyData.first, PrevDRD);
10386 DRD->setAccess(AS);
10387 Decls.push_back(DRD);
10389 DRD->setInvalidDecl();
10394 return DeclGroupPtrTy::make(
10395 DeclGroupRef::Create(Context, Decls.begin(), Decls.size()));
10398 void Sema::ActOnOpenMPDeclareReductionCombinerStart(Scope *S, Decl *D) {
10399 auto *DRD = cast<OMPDeclareReductionDecl>(D);
10401 // Enter new function scope.
10402 PushFunctionScope();
10403 getCurFunction()->setHasBranchProtectedScope();
10404 getCurFunction()->setHasOMPDeclareReductionCombiner();
10407 PushDeclContext(S, DRD);
10411 PushExpressionEvaluationContext(PotentiallyEvaluated);
10413 QualType ReductionType = DRD->getType();
10414 // Create 'T* omp_parm;T omp_in;'. All references to 'omp_in' will
10415 // be replaced by '*omp_parm' during codegen. This required because 'omp_in'
10416 // uses semantics of argument handles by value, but it should be passed by
10417 // reference. C lang does not support references, so pass all parameters as
10419 // Create 'T omp_in;' variable.
10421 buildVarDecl(*this, D->getLocation(), ReductionType, "omp_in");
10422 // Create 'T* omp_parm;T omp_out;'. All references to 'omp_out' will
10423 // be replaced by '*omp_parm' during codegen. This required because 'omp_out'
10424 // uses semantics of argument handles by value, but it should be passed by
10425 // reference. C lang does not support references, so pass all parameters as
10427 // Create 'T omp_out;' variable.
10429 buildVarDecl(*this, D->getLocation(), ReductionType, "omp_out");
10430 if (S != nullptr) {
10431 PushOnScopeChains(OmpInParm, S);
10432 PushOnScopeChains(OmpOutParm, S);
10434 DRD->addDecl(OmpInParm);
10435 DRD->addDecl(OmpOutParm);
10439 void Sema::ActOnOpenMPDeclareReductionCombinerEnd(Decl *D, Expr *Combiner) {
10440 auto *DRD = cast<OMPDeclareReductionDecl>(D);
10441 DiscardCleanupsInEvaluationContext();
10442 PopExpressionEvaluationContext();
10445 PopFunctionScopeInfo();
10447 if (Combiner != nullptr)
10448 DRD->setCombiner(Combiner);
10450 DRD->setInvalidDecl();
10453 void Sema::ActOnOpenMPDeclareReductionInitializerStart(Scope *S, Decl *D) {
10454 auto *DRD = cast<OMPDeclareReductionDecl>(D);
10456 // Enter new function scope.
10457 PushFunctionScope();
10458 getCurFunction()->setHasBranchProtectedScope();
10461 PushDeclContext(S, DRD);
10465 PushExpressionEvaluationContext(PotentiallyEvaluated);
10467 QualType ReductionType = DRD->getType();
10468 // Create 'T* omp_parm;T omp_priv;'. All references to 'omp_priv' will
10469 // be replaced by '*omp_parm' during codegen. This required because 'omp_priv'
10470 // uses semantics of argument handles by value, but it should be passed by
10471 // reference. C lang does not support references, so pass all parameters as
10473 // Create 'T omp_priv;' variable.
10474 auto *OmpPrivParm =
10475 buildVarDecl(*this, D->getLocation(), ReductionType, "omp_priv");
10476 // Create 'T* omp_parm;T omp_orig;'. All references to 'omp_orig' will
10477 // be replaced by '*omp_parm' during codegen. This required because 'omp_orig'
10478 // uses semantics of argument handles by value, but it should be passed by
10479 // reference. C lang does not support references, so pass all parameters as
10481 // Create 'T omp_orig;' variable.
10482 auto *OmpOrigParm =
10483 buildVarDecl(*this, D->getLocation(), ReductionType, "omp_orig");
10484 if (S != nullptr) {
10485 PushOnScopeChains(OmpPrivParm, S);
10486 PushOnScopeChains(OmpOrigParm, S);
10488 DRD->addDecl(OmpPrivParm);
10489 DRD->addDecl(OmpOrigParm);
10493 void Sema::ActOnOpenMPDeclareReductionInitializerEnd(Decl *D,
10494 Expr *Initializer) {
10495 auto *DRD = cast<OMPDeclareReductionDecl>(D);
10496 DiscardCleanupsInEvaluationContext();
10497 PopExpressionEvaluationContext();
10500 PopFunctionScopeInfo();
10502 if (Initializer != nullptr)
10503 DRD->setInitializer(Initializer);
10505 DRD->setInvalidDecl();
10508 Sema::DeclGroupPtrTy Sema::ActOnOpenMPDeclareReductionDirectiveEnd(
10509 Scope *S, DeclGroupPtrTy DeclReductions, bool IsValid) {
10510 for (auto *D : DeclReductions.get()) {
10512 auto *DRD = cast<OMPDeclareReductionDecl>(D);
10514 PushOnScopeChains(DRD, S, /*AddToContext=*/false);
10516 D->setInvalidDecl();
10518 return DeclReductions;
10521 OMPClause *Sema::ActOnOpenMPNumTeamsClause(Expr *NumTeams,
10522 SourceLocation StartLoc,
10523 SourceLocation LParenLoc,
10524 SourceLocation EndLoc) {
10525 Expr *ValExpr = NumTeams;
10527 // OpenMP [teams Constrcut, Restrictions]
10528 // The num_teams expression must evaluate to a positive integer value.
10529 if (!IsNonNegativeIntegerValue(ValExpr, *this, OMPC_num_teams,
10530 /*StrictlyPositive=*/true))
10533 return new (Context) OMPNumTeamsClause(ValExpr, StartLoc, LParenLoc, EndLoc);
10536 OMPClause *Sema::ActOnOpenMPThreadLimitClause(Expr *ThreadLimit,
10537 SourceLocation StartLoc,
10538 SourceLocation LParenLoc,
10539 SourceLocation EndLoc) {
10540 Expr *ValExpr = ThreadLimit;
10542 // OpenMP [teams Constrcut, Restrictions]
10543 // The thread_limit expression must evaluate to a positive integer value.
10544 if (!IsNonNegativeIntegerValue(ValExpr, *this, OMPC_thread_limit,
10545 /*StrictlyPositive=*/true))
10548 return new (Context)
10549 OMPThreadLimitClause(ValExpr, StartLoc, LParenLoc, EndLoc);
10552 OMPClause *Sema::ActOnOpenMPPriorityClause(Expr *Priority,
10553 SourceLocation StartLoc,
10554 SourceLocation LParenLoc,
10555 SourceLocation EndLoc) {
10556 Expr *ValExpr = Priority;
10558 // OpenMP [2.9.1, task Constrcut]
10559 // The priority-value is a non-negative numerical scalar expression.
10560 if (!IsNonNegativeIntegerValue(ValExpr, *this, OMPC_priority,
10561 /*StrictlyPositive=*/false))
10564 return new (Context) OMPPriorityClause(ValExpr, StartLoc, LParenLoc, EndLoc);
10567 OMPClause *Sema::ActOnOpenMPGrainsizeClause(Expr *Grainsize,
10568 SourceLocation StartLoc,
10569 SourceLocation LParenLoc,
10570 SourceLocation EndLoc) {
10571 Expr *ValExpr = Grainsize;
10573 // OpenMP [2.9.2, taskloop Constrcut]
10574 // The parameter of the grainsize clause must be a positive integer
10576 if (!IsNonNegativeIntegerValue(ValExpr, *this, OMPC_grainsize,
10577 /*StrictlyPositive=*/true))
10580 return new (Context) OMPGrainsizeClause(ValExpr, StartLoc, LParenLoc, EndLoc);
10583 OMPClause *Sema::ActOnOpenMPNumTasksClause(Expr *NumTasks,
10584 SourceLocation StartLoc,
10585 SourceLocation LParenLoc,
10586 SourceLocation EndLoc) {
10587 Expr *ValExpr = NumTasks;
10589 // OpenMP [2.9.2, taskloop Constrcut]
10590 // The parameter of the num_tasks clause must be a positive integer
10592 if (!IsNonNegativeIntegerValue(ValExpr, *this, OMPC_num_tasks,
10593 /*StrictlyPositive=*/true))
10596 return new (Context) OMPNumTasksClause(ValExpr, StartLoc, LParenLoc, EndLoc);
10599 OMPClause *Sema::ActOnOpenMPHintClause(Expr *Hint, SourceLocation StartLoc,
10600 SourceLocation LParenLoc,
10601 SourceLocation EndLoc) {
10602 // OpenMP [2.13.2, critical construct, Description]
10603 // ... where hint-expression is an integer constant expression that evaluates
10604 // to a valid lock hint.
10605 ExprResult HintExpr = VerifyPositiveIntegerConstantInClause(Hint, OMPC_hint);
10606 if (HintExpr.isInvalid())
10608 return new (Context)
10609 OMPHintClause(HintExpr.get(), StartLoc, LParenLoc, EndLoc);
10612 OMPClause *Sema::ActOnOpenMPDistScheduleClause(
10613 OpenMPDistScheduleClauseKind Kind, Expr *ChunkSize, SourceLocation StartLoc,
10614 SourceLocation LParenLoc, SourceLocation KindLoc, SourceLocation CommaLoc,
10615 SourceLocation EndLoc) {
10616 if (Kind == OMPC_DIST_SCHEDULE_unknown) {
10617 std::string Values;
10619 Values += getOpenMPSimpleClauseTypeName(OMPC_dist_schedule, 0);
10621 Diag(KindLoc, diag::err_omp_unexpected_clause_value)
10622 << Values << getOpenMPClauseName(OMPC_dist_schedule);
10625 Expr *ValExpr = ChunkSize;
10626 Stmt *HelperValStmt = nullptr;
10628 if (!ChunkSize->isValueDependent() && !ChunkSize->isTypeDependent() &&
10629 !ChunkSize->isInstantiationDependent() &&
10630 !ChunkSize->containsUnexpandedParameterPack()) {
10631 SourceLocation ChunkSizeLoc = ChunkSize->getLocStart();
10633 PerformOpenMPImplicitIntegerConversion(ChunkSizeLoc, ChunkSize);
10634 if (Val.isInvalid())
10637 ValExpr = Val.get();
10639 // OpenMP [2.7.1, Restrictions]
10640 // chunk_size must be a loop invariant integer expression with a positive
10642 llvm::APSInt Result;
10643 if (ValExpr->isIntegerConstantExpr(Result, Context)) {
10644 if (Result.isSigned() && !Result.isStrictlyPositive()) {
10645 Diag(ChunkSizeLoc, diag::err_omp_negative_expression_in_clause)
10646 << "dist_schedule" << ChunkSize->getSourceRange();
10649 } else if (isParallelOrTaskRegion(DSAStack->getCurrentDirective()) &&
10650 !CurContext->isDependentContext()) {
10651 llvm::MapVector<Expr *, DeclRefExpr *> Captures;
10652 ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
10653 HelperValStmt = buildPreInits(Context, Captures);
10658 return new (Context)
10659 OMPDistScheduleClause(StartLoc, LParenLoc, KindLoc, CommaLoc, EndLoc,
10660 Kind, ValExpr, HelperValStmt);
10663 OMPClause *Sema::ActOnOpenMPDefaultmapClause(
10664 OpenMPDefaultmapClauseModifier M, OpenMPDefaultmapClauseKind Kind,
10665 SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation MLoc,
10666 SourceLocation KindLoc, SourceLocation EndLoc) {
10667 // OpenMP 4.5 only supports 'defaultmap(tofrom: scalar)'
10668 if (M != OMPC_DEFAULTMAP_MODIFIER_tofrom || Kind != OMPC_DEFAULTMAP_scalar) {
10670 SourceLocation Loc;
10672 if (M != OMPC_DEFAULTMAP_MODIFIER_tofrom) {
10673 Value += getOpenMPSimpleClauseTypeName(OMPC_defaultmap,
10674 OMPC_DEFAULTMAP_MODIFIER_tofrom);
10677 Value += getOpenMPSimpleClauseTypeName(OMPC_defaultmap,
10678 OMPC_DEFAULTMAP_scalar);
10682 Diag(Loc, diag::err_omp_unexpected_clause_value)
10683 << Value << getOpenMPClauseName(OMPC_defaultmap);
10687 return new (Context)
10688 OMPDefaultmapClause(StartLoc, LParenLoc, MLoc, KindLoc, EndLoc, Kind, M);
10691 bool Sema::ActOnStartOpenMPDeclareTargetDirective(SourceLocation Loc) {
10692 DeclContext *CurLexicalContext = getCurLexicalContext();
10693 if (!CurLexicalContext->isFileContext() &&
10694 !CurLexicalContext->isExternCContext() &&
10695 !CurLexicalContext->isExternCXXContext()) {
10696 Diag(Loc, diag::err_omp_region_not_file_context);
10699 if (IsInOpenMPDeclareTargetContext) {
10700 Diag(Loc, diag::err_omp_enclosed_declare_target);
10704 IsInOpenMPDeclareTargetContext = true;
10708 void Sema::ActOnFinishOpenMPDeclareTargetDirective() {
10709 assert(IsInOpenMPDeclareTargetContext &&
10710 "Unexpected ActOnFinishOpenMPDeclareTargetDirective");
10712 IsInOpenMPDeclareTargetContext = false;
10715 void Sema::ActOnOpenMPDeclareTargetName(Scope *CurScope,
10716 CXXScopeSpec &ScopeSpec,
10717 const DeclarationNameInfo &Id,
10718 OMPDeclareTargetDeclAttr::MapTypeTy MT,
10719 NamedDeclSetType &SameDirectiveDecls) {
10720 LookupResult Lookup(*this, Id, LookupOrdinaryName);
10721 LookupParsedName(Lookup, CurScope, &ScopeSpec, true);
10723 if (Lookup.isAmbiguous())
10725 Lookup.suppressDiagnostics();
10727 if (!Lookup.isSingleResult()) {
10728 if (TypoCorrection Corrected =
10729 CorrectTypo(Id, LookupOrdinaryName, CurScope, nullptr,
10730 llvm::make_unique<VarOrFuncDeclFilterCCC>(*this),
10731 CTK_ErrorRecovery)) {
10732 diagnoseTypo(Corrected, PDiag(diag::err_undeclared_var_use_suggest)
10734 checkDeclIsAllowedInOpenMPTarget(nullptr, Corrected.getCorrectionDecl());
10738 Diag(Id.getLoc(), diag::err_undeclared_var_use) << Id.getName();
10742 NamedDecl *ND = Lookup.getAsSingle<NamedDecl>();
10743 if (isa<VarDecl>(ND) || isa<FunctionDecl>(ND)) {
10744 if (!SameDirectiveDecls.insert(cast<NamedDecl>(ND->getCanonicalDecl())))
10745 Diag(Id.getLoc(), diag::err_omp_declare_target_multiple) << Id.getName();
10747 if (!ND->hasAttr<OMPDeclareTargetDeclAttr>()) {
10748 Attr *A = OMPDeclareTargetDeclAttr::CreateImplicit(Context, MT);
10750 if (ASTMutationListener *ML = Context.getASTMutationListener())
10751 ML->DeclarationMarkedOpenMPDeclareTarget(ND, A);
10752 checkDeclIsAllowedInOpenMPTarget(nullptr, ND);
10753 } else if (ND->getAttr<OMPDeclareTargetDeclAttr>()->getMapType() != MT) {
10754 Diag(Id.getLoc(), diag::err_omp_declare_target_to_and_link)
10758 Diag(Id.getLoc(), diag::err_omp_invalid_target_decl) << Id.getName();
10761 static void checkDeclInTargetContext(SourceLocation SL, SourceRange SR,
10762 Sema &SemaRef, Decl *D) {
10765 Decl *LD = nullptr;
10766 if (isa<TagDecl>(D)) {
10767 LD = cast<TagDecl>(D)->getDefinition();
10768 } else if (isa<VarDecl>(D)) {
10769 LD = cast<VarDecl>(D)->getDefinition();
10771 // If this is an implicit variable that is legal and we do not need to do
10773 if (cast<VarDecl>(D)->isImplicit()) {
10774 Attr *A = OMPDeclareTargetDeclAttr::CreateImplicit(
10775 SemaRef.Context, OMPDeclareTargetDeclAttr::MT_To);
10777 if (ASTMutationListener *ML = SemaRef.Context.getASTMutationListener())
10778 ML->DeclarationMarkedOpenMPDeclareTarget(D, A);
10782 } else if (isa<FunctionDecl>(D)) {
10783 const FunctionDecl *FD = nullptr;
10784 if (cast<FunctionDecl>(D)->hasBody(FD))
10785 LD = const_cast<FunctionDecl *>(FD);
10787 // If the definition is associated with the current declaration in the
10788 // target region (it can be e.g. a lambda) that is legal and we do not need
10789 // to do anything else.
10791 Attr *A = OMPDeclareTargetDeclAttr::CreateImplicit(
10792 SemaRef.Context, OMPDeclareTargetDeclAttr::MT_To);
10794 if (ASTMutationListener *ML = SemaRef.Context.getASTMutationListener())
10795 ML->DeclarationMarkedOpenMPDeclareTarget(D, A);
10801 if (LD && !LD->hasAttr<OMPDeclareTargetDeclAttr>() &&
10802 (isa<VarDecl>(LD) || isa<FunctionDecl>(LD))) {
10803 // Outlined declaration is not declared target.
10804 if (LD->isOutOfLine()) {
10805 SemaRef.Diag(LD->getLocation(), diag::warn_omp_not_in_target_context);
10806 SemaRef.Diag(SL, diag::note_used_here) << SR;
10808 DeclContext *DC = LD->getDeclContext();
10810 if (isa<FunctionDecl>(DC) &&
10811 cast<FunctionDecl>(DC)->hasAttr<OMPDeclareTargetDeclAttr>())
10813 DC = DC->getParent();
10818 // Is not declared in target context.
10819 SemaRef.Diag(LD->getLocation(), diag::warn_omp_not_in_target_context);
10820 SemaRef.Diag(SL, diag::note_used_here) << SR;
10822 // Mark decl as declared target to prevent further diagnostic.
10823 Attr *A = OMPDeclareTargetDeclAttr::CreateImplicit(
10824 SemaRef.Context, OMPDeclareTargetDeclAttr::MT_To);
10826 if (ASTMutationListener *ML = SemaRef.Context.getASTMutationListener())
10827 ML->DeclarationMarkedOpenMPDeclareTarget(D, A);
10831 static bool checkValueDeclInTarget(SourceLocation SL, SourceRange SR,
10832 Sema &SemaRef, DSAStackTy *Stack,
10834 if (VD->hasAttr<OMPDeclareTargetDeclAttr>())
10836 if (!CheckTypeMappable(SL, SR, SemaRef, Stack, VD->getType()))
10841 void Sema::checkDeclIsAllowedInOpenMPTarget(Expr *E, Decl *D) {
10842 if (!D || D->isInvalidDecl())
10844 SourceRange SR = E ? E->getSourceRange() : D->getSourceRange();
10845 SourceLocation SL = E ? E->getLocStart() : D->getLocation();
10846 // 2.10.6: threadprivate variable cannot appear in a declare target directive.
10847 if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
10848 if (DSAStack->isThreadPrivate(VD)) {
10849 Diag(SL, diag::err_omp_threadprivate_in_target);
10850 ReportOriginalDSA(*this, DSAStack, VD, DSAStack->getTopDSA(VD, false));
10854 if (ValueDecl *VD = dyn_cast<ValueDecl>(D)) {
10855 // Problem if any with var declared with incomplete type will be reported
10856 // as normal, so no need to check it here.
10857 if ((E || !VD->getType()->isIncompleteType()) &&
10858 !checkValueDeclInTarget(SL, SR, *this, DSAStack, VD)) {
10859 // Mark decl as declared target to prevent further diagnostic.
10860 if (isa<VarDecl>(VD) || isa<FunctionDecl>(VD)) {
10861 Attr *A = OMPDeclareTargetDeclAttr::CreateImplicit(
10862 Context, OMPDeclareTargetDeclAttr::MT_To);
10864 if (ASTMutationListener *ML = Context.getASTMutationListener())
10865 ML->DeclarationMarkedOpenMPDeclareTarget(VD, A);
10871 // Checking declaration inside declare target region.
10872 if (!D->hasAttr<OMPDeclareTargetDeclAttr>() &&
10873 (isa<VarDecl>(D) || isa<FunctionDecl>(D))) {
10874 Attr *A = OMPDeclareTargetDeclAttr::CreateImplicit(
10875 Context, OMPDeclareTargetDeclAttr::MT_To);
10877 if (ASTMutationListener *ML = Context.getASTMutationListener())
10878 ML->DeclarationMarkedOpenMPDeclareTarget(D, A);
10882 checkDeclInTargetContext(E->getExprLoc(), E->getSourceRange(), *this, D);
10885 OMPClause *Sema::ActOnOpenMPToClause(ArrayRef<Expr *> VarList,
10886 SourceLocation StartLoc,
10887 SourceLocation LParenLoc,
10888 SourceLocation EndLoc) {
10889 MappableVarListInfo MVLI(VarList);
10890 checkMappableExpressionList(*this, DSAStack, OMPC_to, MVLI, StartLoc);
10891 if (MVLI.ProcessedVarList.empty())
10894 return OMPToClause::Create(Context, StartLoc, LParenLoc, EndLoc,
10895 MVLI.ProcessedVarList, MVLI.VarBaseDeclarations,
10896 MVLI.VarComponents);
10899 OMPClause *Sema::ActOnOpenMPFromClause(ArrayRef<Expr *> VarList,
10900 SourceLocation StartLoc,
10901 SourceLocation LParenLoc,
10902 SourceLocation EndLoc) {
10903 MappableVarListInfo MVLI(VarList);
10904 checkMappableExpressionList(*this, DSAStack, OMPC_from, MVLI, StartLoc);
10905 if (MVLI.ProcessedVarList.empty())
10908 return OMPFromClause::Create(Context, StartLoc, LParenLoc, EndLoc,
10909 MVLI.ProcessedVarList, MVLI.VarBaseDeclarations,
10910 MVLI.VarComponents);
10913 OMPClause *Sema::ActOnOpenMPUseDevicePtrClause(ArrayRef<Expr *> VarList,
10914 SourceLocation StartLoc,
10915 SourceLocation LParenLoc,
10916 SourceLocation EndLoc) {
10917 MappableVarListInfo MVLI(VarList);
10918 SmallVector<Expr *, 8> PrivateCopies;
10919 SmallVector<Expr *, 8> Inits;
10921 for (auto &RefExpr : VarList) {
10922 assert(RefExpr && "NULL expr in OpenMP use_device_ptr clause.");
10923 SourceLocation ELoc;
10924 SourceRange ERange;
10925 Expr *SimpleRefExpr = RefExpr;
10926 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
10928 // It will be analyzed later.
10929 MVLI.ProcessedVarList.push_back(RefExpr);
10930 PrivateCopies.push_back(nullptr);
10931 Inits.push_back(nullptr);
10933 ValueDecl *D = Res.first;
10937 QualType Type = D->getType();
10938 Type = Type.getNonReferenceType().getUnqualifiedType();
10940 auto *VD = dyn_cast<VarDecl>(D);
10942 // Item should be a pointer or reference to pointer.
10943 if (!Type->isPointerType()) {
10944 Diag(ELoc, diag::err_omp_usedeviceptr_not_a_pointer)
10945 << 0 << RefExpr->getSourceRange();
10949 // Build the private variable and the expression that refers to it.
10950 auto VDPrivate = buildVarDecl(*this, ELoc, Type, D->getName(),
10951 D->hasAttrs() ? &D->getAttrs() : nullptr);
10952 if (VDPrivate->isInvalidDecl())
10955 CurContext->addDecl(VDPrivate);
10956 auto VDPrivateRefExpr = buildDeclRefExpr(
10957 *this, VDPrivate, RefExpr->getType().getUnqualifiedType(), ELoc);
10959 // Add temporary variable to initialize the private copy of the pointer.
10961 buildVarDecl(*this, RefExpr->getExprLoc(), Type, ".devptr.temp");
10962 auto *VDInitRefExpr = buildDeclRefExpr(*this, VDInit, RefExpr->getType(),
10963 RefExpr->getExprLoc());
10964 AddInitializerToDecl(VDPrivate,
10965 DefaultLvalueConversion(VDInitRefExpr).get(),
10966 /*DirectInit=*/false, /*TypeMayContainAuto=*/false);
10968 // If required, build a capture to implement the privatization initialized
10969 // with the current list item value.
10970 DeclRefExpr *Ref = nullptr;
10972 Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/true);
10973 MVLI.ProcessedVarList.push_back(VD ? RefExpr->IgnoreParens() : Ref);
10974 PrivateCopies.push_back(VDPrivateRefExpr);
10975 Inits.push_back(VDInitRefExpr);
10977 // We need to add a data sharing attribute for this variable to make sure it
10978 // is correctly captured. A variable that shows up in a use_device_ptr has
10979 // similar properties of a first private variable.
10980 DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_firstprivate, Ref);
10982 // Create a mappable component for the list item. List items in this clause
10983 // only need a component.
10984 MVLI.VarBaseDeclarations.push_back(D);
10985 MVLI.VarComponents.resize(MVLI.VarComponents.size() + 1);
10986 MVLI.VarComponents.back().push_back(
10987 OMPClauseMappableExprCommon::MappableComponent(SimpleRefExpr, D));
10990 if (MVLI.ProcessedVarList.empty())
10993 return OMPUseDevicePtrClause::Create(
10994 Context, StartLoc, LParenLoc, EndLoc, MVLI.ProcessedVarList,
10995 PrivateCopies, Inits, MVLI.VarBaseDeclarations, MVLI.VarComponents);
10998 OMPClause *Sema::ActOnOpenMPIsDevicePtrClause(ArrayRef<Expr *> VarList,
10999 SourceLocation StartLoc,
11000 SourceLocation LParenLoc,
11001 SourceLocation EndLoc) {
11002 MappableVarListInfo MVLI(VarList);
11003 for (auto &RefExpr : VarList) {
11004 assert(RefExpr && "NULL expr in OpenMP is_device_ptr clause.");
11005 SourceLocation ELoc;
11006 SourceRange ERange;
11007 Expr *SimpleRefExpr = RefExpr;
11008 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
11010 // It will be analyzed later.
11011 MVLI.ProcessedVarList.push_back(RefExpr);
11013 ValueDecl *D = Res.first;
11017 QualType Type = D->getType();
11018 // item should be a pointer or array or reference to pointer or array
11019 if (!Type.getNonReferenceType()->isPointerType() &&
11020 !Type.getNonReferenceType()->isArrayType()) {
11021 Diag(ELoc, diag::err_omp_argument_type_isdeviceptr)
11022 << 0 << RefExpr->getSourceRange();
11026 // Check if the declaration in the clause does not show up in any data
11027 // sharing attribute.
11028 auto DVar = DSAStack->getTopDSA(D, false);
11029 if (isOpenMPPrivate(DVar.CKind)) {
11030 Diag(ELoc, diag::err_omp_variable_in_given_clause_and_dsa)
11031 << getOpenMPClauseName(DVar.CKind)
11032 << getOpenMPClauseName(OMPC_is_device_ptr)
11033 << getOpenMPDirectiveName(DSAStack->getCurrentDirective());
11034 ReportOriginalDSA(*this, DSAStack, D, DVar);
11038 Expr *ConflictExpr;
11039 if (DSAStack->checkMappableExprComponentListsForDecl(
11040 D, /*CurrentRegionOnly=*/true,
11042 OMPClauseMappableExprCommon::MappableExprComponentListRef R,
11043 OpenMPClauseKind) -> bool {
11044 ConflictExpr = R.front().getAssociatedExpression();
11047 Diag(ELoc, diag::err_omp_map_shared_storage) << RefExpr->getSourceRange();
11048 Diag(ConflictExpr->getExprLoc(), diag::note_used_here)
11049 << ConflictExpr->getSourceRange();
11053 // Store the components in the stack so that they can be used to check
11054 // against other clauses later on.
11055 OMPClauseMappableExprCommon::MappableComponent MC(SimpleRefExpr, D);
11056 DSAStack->addMappableExpressionComponents(
11057 D, MC, /*WhereFoundClauseKind=*/OMPC_is_device_ptr);
11059 // Record the expression we've just processed.
11060 MVLI.ProcessedVarList.push_back(SimpleRefExpr);
11062 // Create a mappable component for the list item. List items in this clause
11063 // only need a component. We use a null declaration to signal fields in
11065 assert((isa<DeclRefExpr>(SimpleRefExpr) ||
11066 isa<CXXThisExpr>(cast<MemberExpr>(SimpleRefExpr)->getBase())) &&
11067 "Unexpected device pointer expression!");
11068 MVLI.VarBaseDeclarations.push_back(
11069 isa<DeclRefExpr>(SimpleRefExpr) ? D : nullptr);
11070 MVLI.VarComponents.resize(MVLI.VarComponents.size() + 1);
11071 MVLI.VarComponents.back().push_back(MC);
11074 if (MVLI.ProcessedVarList.empty())
11077 return OMPIsDevicePtrClause::Create(
11078 Context, StartLoc, LParenLoc, EndLoc, MVLI.ProcessedVarList,
11079 MVLI.VarBaseDeclarations, MVLI.VarComponents);