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/Decl.h"
19 #include "clang/AST/DeclCXX.h"
20 #include "clang/AST/DeclOpenMP.h"
21 #include "clang/AST/StmtCXX.h"
22 #include "clang/AST/StmtOpenMP.h"
23 #include "clang/AST/StmtVisitor.h"
24 #include "clang/Basic/OpenMPKinds.h"
25 #include "clang/Basic/TargetInfo.h"
26 #include "clang/Lex/Preprocessor.h"
27 #include "clang/Sema/Initialization.h"
28 #include "clang/Sema/Lookup.h"
29 #include "clang/Sema/Scope.h"
30 #include "clang/Sema/ScopeInfo.h"
31 #include "clang/Sema/SemaInternal.h"
32 using namespace clang;
34 //===----------------------------------------------------------------------===//
35 // Stack of data-sharing attributes for variables
36 //===----------------------------------------------------------------------===//
39 /// \brief Default data sharing attributes, which can be applied to directive.
40 enum DefaultDataSharingAttributes {
41 DSA_unspecified = 0, /// \brief Data sharing attribute not specified.
42 DSA_none = 1 << 0, /// \brief Default data sharing attribute 'none'.
43 DSA_shared = 1 << 1 /// \brief Default data sharing attribute 'shared'.
46 template <class T> struct MatchesAny {
47 explicit MatchesAny(ArrayRef<T> Arr) : Arr(std::move(Arr)) {}
48 bool operator()(T Kind) {
49 for (auto KindEl : Arr)
58 struct MatchesAlways {
60 template <class T> bool operator()(T) { return true; }
63 typedef MatchesAny<OpenMPClauseKind> MatchesAnyClause;
64 typedef MatchesAny<OpenMPDirectiveKind> MatchesAnyDirective;
66 /// \brief Stack for tracking declarations used in OpenMP directives and
67 /// clauses and their data-sharing attributes.
71 OpenMPDirectiveKind DKind;
72 OpenMPClauseKind CKind;
74 SourceLocation ImplicitDSALoc;
76 : DKind(OMPD_unknown), CKind(OMPC_unknown), RefExpr(nullptr),
82 OpenMPClauseKind Attributes;
85 typedef llvm::SmallDenseMap<VarDecl *, DSAInfo, 64> DeclSAMapTy;
86 typedef llvm::SmallDenseMap<VarDecl *, DeclRefExpr *, 64> AlignedMapTy;
87 typedef llvm::DenseSet<VarDecl *> LoopControlVariablesSetTy;
90 DeclSAMapTy SharingMap;
91 AlignedMapTy AlignedMap;
92 LoopControlVariablesSetTy LCVSet;
93 DefaultDataSharingAttributes DefaultAttr;
94 SourceLocation DefaultAttrLoc;
95 OpenMPDirectiveKind Directive;
96 DeclarationNameInfo DirectiveName;
98 SourceLocation ConstructLoc;
101 unsigned CollapseNumber;
102 SourceLocation InnerTeamsRegionLoc;
103 SharingMapTy(OpenMPDirectiveKind DKind, DeclarationNameInfo Name,
104 Scope *CurScope, SourceLocation Loc)
105 : SharingMap(), AlignedMap(), LCVSet(), DefaultAttr(DSA_unspecified),
106 Directive(DKind), DirectiveName(std::move(Name)), CurScope(CurScope),
107 ConstructLoc(Loc), OrderedRegion(false), NowaitRegion(false),
108 CollapseNumber(1), InnerTeamsRegionLoc() {}
110 : SharingMap(), AlignedMap(), LCVSet(), DefaultAttr(DSA_unspecified),
111 Directive(OMPD_unknown), DirectiveName(), CurScope(nullptr),
112 ConstructLoc(), OrderedRegion(false), NowaitRegion(false),
113 CollapseNumber(1), InnerTeamsRegionLoc() {}
116 typedef SmallVector<SharingMapTy, 64> StackTy;
118 /// \brief Stack of used declaration and their data-sharing attributes.
120 /// \brief true, if check for DSA must be from parent directive, false, if
121 /// from current directive.
122 OpenMPClauseKind ClauseKindMode;
126 typedef SmallVector<SharingMapTy, 8>::reverse_iterator reverse_iterator;
128 DSAVarData getDSA(StackTy::reverse_iterator Iter, VarDecl *D);
130 /// \brief Checks if the variable is a local for OpenMP region.
131 bool isOpenMPLocal(VarDecl *D, StackTy::reverse_iterator Iter);
134 explicit DSAStackTy(Sema &S)
135 : Stack(1), ClauseKindMode(OMPC_unknown), SemaRef(S),
136 ForceCapturing(false) {}
138 bool isClauseParsingMode() const { return ClauseKindMode != OMPC_unknown; }
139 void setClauseParsingMode(OpenMPClauseKind K) { ClauseKindMode = K; }
141 bool isForceVarCapturing() const { return ForceCapturing; }
142 void setForceVarCapturing(bool V) { ForceCapturing = V; }
144 void push(OpenMPDirectiveKind DKind, const DeclarationNameInfo &DirName,
145 Scope *CurScope, SourceLocation Loc) {
146 Stack.push_back(SharingMapTy(DKind, DirName, CurScope, Loc));
147 Stack.back().DefaultAttrLoc = Loc;
151 assert(Stack.size() > 1 && "Data-sharing attributes stack is empty!");
155 /// \brief If 'aligned' declaration for given variable \a D was not seen yet,
156 /// add it and return NULL; otherwise return previous occurrence's expression
158 DeclRefExpr *addUniqueAligned(VarDecl *D, DeclRefExpr *NewDE);
160 /// \brief Register specified variable as loop control variable.
161 void addLoopControlVariable(VarDecl *D);
162 /// \brief Check if the specified variable is a loop control variable for
164 bool isLoopControlVariable(VarDecl *D);
166 /// \brief Adds explicit data sharing attribute to the specified declaration.
167 void addDSA(VarDecl *D, DeclRefExpr *E, OpenMPClauseKind A);
169 /// \brief Returns data sharing attributes from top of the stack for the
170 /// specified declaration.
171 DSAVarData getTopDSA(VarDecl *D, bool FromParent);
172 /// \brief Returns data-sharing attributes for the specified declaration.
173 DSAVarData getImplicitDSA(VarDecl *D, bool FromParent);
174 /// \brief Checks if the specified variables has data-sharing attributes which
175 /// match specified \a CPred predicate in any directive which matches \a DPred
177 template <class ClausesPredicate, class DirectivesPredicate>
178 DSAVarData hasDSA(VarDecl *D, ClausesPredicate CPred,
179 DirectivesPredicate DPred, bool FromParent);
180 /// \brief Checks if the specified variables has data-sharing attributes which
181 /// match specified \a CPred predicate in any innermost directive which
182 /// matches \a DPred predicate.
183 template <class ClausesPredicate, class DirectivesPredicate>
184 DSAVarData hasInnermostDSA(VarDecl *D, ClausesPredicate CPred,
185 DirectivesPredicate DPred,
187 /// \brief Checks if the specified variables has explicit data-sharing
188 /// attributes which match specified \a CPred predicate at the specified
190 bool hasExplicitDSA(VarDecl *D,
191 const llvm::function_ref<bool(OpenMPClauseKind)> &CPred,
193 /// \brief Finds a directive which matches specified \a DPred predicate.
194 template <class NamedDirectivesPredicate>
195 bool hasDirective(NamedDirectivesPredicate DPred, bool FromParent);
197 /// \brief Returns currently analyzed directive.
198 OpenMPDirectiveKind getCurrentDirective() const {
199 return Stack.back().Directive;
201 /// \brief Returns parent directive.
202 OpenMPDirectiveKind getParentDirective() const {
203 if (Stack.size() > 2)
204 return Stack[Stack.size() - 2].Directive;
208 /// \brief Set default data sharing attribute to none.
209 void setDefaultDSANone(SourceLocation Loc) {
210 Stack.back().DefaultAttr = DSA_none;
211 Stack.back().DefaultAttrLoc = Loc;
213 /// \brief Set default data sharing attribute to shared.
214 void setDefaultDSAShared(SourceLocation Loc) {
215 Stack.back().DefaultAttr = DSA_shared;
216 Stack.back().DefaultAttrLoc = Loc;
219 DefaultDataSharingAttributes getDefaultDSA() const {
220 return Stack.back().DefaultAttr;
222 SourceLocation getDefaultDSALocation() const {
223 return Stack.back().DefaultAttrLoc;
226 /// \brief Checks if the specified variable is a threadprivate.
227 bool isThreadPrivate(VarDecl *D) {
228 DSAVarData DVar = getTopDSA(D, false);
229 return isOpenMPThreadPrivate(DVar.CKind);
232 /// \brief Marks current region as ordered (it has an 'ordered' clause).
233 void setOrderedRegion(bool IsOrdered = true) {
234 Stack.back().OrderedRegion = IsOrdered;
236 /// \brief Returns true, if parent region is ordered (has associated
237 /// 'ordered' clause), false - otherwise.
238 bool isParentOrderedRegion() const {
239 if (Stack.size() > 2)
240 return Stack[Stack.size() - 2].OrderedRegion;
243 /// \brief Marks current region as nowait (it has a 'nowait' clause).
244 void setNowaitRegion(bool IsNowait = true) {
245 Stack.back().NowaitRegion = IsNowait;
247 /// \brief Returns true, if parent region is nowait (has associated
248 /// 'nowait' clause), false - otherwise.
249 bool isParentNowaitRegion() const {
250 if (Stack.size() > 2)
251 return Stack[Stack.size() - 2].NowaitRegion;
255 /// \brief Set collapse value for the region.
256 void setCollapseNumber(unsigned Val) { Stack.back().CollapseNumber = Val; }
257 /// \brief Return collapse value for region.
258 unsigned getCollapseNumber() const {
259 return Stack.back().CollapseNumber;
262 /// \brief Marks current target region as one with closely nested teams
264 void setParentTeamsRegionLoc(SourceLocation TeamsRegionLoc) {
265 if (Stack.size() > 2)
266 Stack[Stack.size() - 2].InnerTeamsRegionLoc = TeamsRegionLoc;
268 /// \brief Returns true, if current region has closely nested teams region.
269 bool hasInnerTeamsRegion() const {
270 return getInnerTeamsRegionLoc().isValid();
272 /// \brief Returns location of the nested teams region (if any).
273 SourceLocation getInnerTeamsRegionLoc() const {
274 if (Stack.size() > 1)
275 return Stack.back().InnerTeamsRegionLoc;
276 return SourceLocation();
279 Scope *getCurScope() const { return Stack.back().CurScope; }
280 Scope *getCurScope() { return Stack.back().CurScope; }
281 SourceLocation getConstructLoc() { return Stack.back().ConstructLoc; }
283 bool isParallelOrTaskRegion(OpenMPDirectiveKind DKind) {
284 return isOpenMPParallelDirective(DKind) || DKind == OMPD_task ||
285 isOpenMPTeamsDirective(DKind) || DKind == OMPD_unknown;
289 DSAStackTy::DSAVarData DSAStackTy::getDSA(StackTy::reverse_iterator Iter,
291 D = D->getCanonicalDecl();
293 if (Iter == std::prev(Stack.rend())) {
294 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
295 // in a region but not in construct]
296 // File-scope or namespace-scope variables referenced in called routines
297 // in the region are shared unless they appear in a threadprivate
299 if (!D->isFunctionOrMethodVarDecl() && !isa<ParmVarDecl>(D))
300 DVar.CKind = OMPC_shared;
302 // OpenMP [2.9.1.2, Data-sharing Attribute Rules for Variables Referenced
303 // in a region but not in construct]
304 // Variables with static storage duration that are declared in called
305 // routines in the region are shared.
306 if (D->hasGlobalStorage())
307 DVar.CKind = OMPC_shared;
312 DVar.DKind = Iter->Directive;
313 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
314 // in a Construct, C/C++, predetermined, p.1]
315 // Variables with automatic storage duration that are declared in a scope
316 // inside the construct are private.
317 if (isOpenMPLocal(D, Iter) && D->isLocalVarDecl() &&
318 (D->getStorageClass() == SC_Auto || D->getStorageClass() == SC_None)) {
319 DVar.CKind = OMPC_private;
323 // Explicitly specified attributes and local variables with predetermined
325 if (Iter->SharingMap.count(D)) {
326 DVar.RefExpr = Iter->SharingMap[D].RefExpr;
327 DVar.CKind = Iter->SharingMap[D].Attributes;
328 DVar.ImplicitDSALoc = Iter->DefaultAttrLoc;
332 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
333 // in a Construct, C/C++, implicitly determined, p.1]
334 // In a parallel or task construct, the data-sharing attributes of these
335 // variables are determined by the default clause, if present.
336 switch (Iter->DefaultAttr) {
338 DVar.CKind = OMPC_shared;
339 DVar.ImplicitDSALoc = Iter->DefaultAttrLoc;
343 case DSA_unspecified:
344 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
345 // in a Construct, implicitly determined, p.2]
346 // In a parallel construct, if no default clause is present, these
347 // variables are shared.
348 DVar.ImplicitDSALoc = Iter->DefaultAttrLoc;
349 if (isOpenMPParallelDirective(DVar.DKind) ||
350 isOpenMPTeamsDirective(DVar.DKind)) {
351 DVar.CKind = OMPC_shared;
355 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
356 // in a Construct, implicitly determined, p.4]
357 // In a task construct, if no default clause is present, a variable that in
358 // the enclosing context is determined to be shared by all implicit tasks
359 // bound to the current team is shared.
360 if (DVar.DKind == OMPD_task) {
362 for (StackTy::reverse_iterator I = std::next(Iter), EE = Stack.rend();
364 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables
366 // in a Construct, implicitly determined, p.6]
367 // In a task construct, if no default clause is present, a variable
368 // whose data-sharing attribute is not determined by the rules above is
370 DVarTemp = getDSA(I, D);
371 if (DVarTemp.CKind != OMPC_shared) {
372 DVar.RefExpr = nullptr;
373 DVar.DKind = OMPD_task;
374 DVar.CKind = OMPC_firstprivate;
377 if (isParallelOrTaskRegion(I->Directive))
380 DVar.DKind = OMPD_task;
382 (DVarTemp.CKind == OMPC_unknown) ? OMPC_firstprivate : OMPC_shared;
386 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
387 // in a Construct, implicitly determined, p.3]
388 // For constructs other than task, if no default clause is present, these
389 // variables inherit their data-sharing attributes from the enclosing
391 return getDSA(std::next(Iter), D);
394 DeclRefExpr *DSAStackTy::addUniqueAligned(VarDecl *D, DeclRefExpr *NewDE) {
395 assert(Stack.size() > 1 && "Data sharing attributes stack is empty");
396 D = D->getCanonicalDecl();
397 auto It = Stack.back().AlignedMap.find(D);
398 if (It == Stack.back().AlignedMap.end()) {
399 assert(NewDE && "Unexpected nullptr expr to be added into aligned map");
400 Stack.back().AlignedMap[D] = NewDE;
403 assert(It->second && "Unexpected nullptr expr in the aligned map");
409 void DSAStackTy::addLoopControlVariable(VarDecl *D) {
410 assert(Stack.size() > 1 && "Data-sharing attributes stack is empty");
411 D = D->getCanonicalDecl();
412 Stack.back().LCVSet.insert(D);
415 bool DSAStackTy::isLoopControlVariable(VarDecl *D) {
416 assert(Stack.size() > 1 && "Data-sharing attributes stack is empty");
417 D = D->getCanonicalDecl();
418 return Stack.back().LCVSet.count(D) > 0;
421 void DSAStackTy::addDSA(VarDecl *D, DeclRefExpr *E, OpenMPClauseKind A) {
422 D = D->getCanonicalDecl();
423 if (A == OMPC_threadprivate) {
424 Stack[0].SharingMap[D].Attributes = A;
425 Stack[0].SharingMap[D].RefExpr = E;
427 assert(Stack.size() > 1 && "Data-sharing attributes stack is empty");
428 Stack.back().SharingMap[D].Attributes = A;
429 Stack.back().SharingMap[D].RefExpr = E;
433 bool DSAStackTy::isOpenMPLocal(VarDecl *D, StackTy::reverse_iterator Iter) {
434 D = D->getCanonicalDecl();
435 if (Stack.size() > 2) {
436 reverse_iterator I = Iter, E = std::prev(Stack.rend());
437 Scope *TopScope = nullptr;
438 while (I != E && !isParallelOrTaskRegion(I->Directive)) {
443 TopScope = I->CurScope ? I->CurScope->getParent() : nullptr;
444 Scope *CurScope = getCurScope();
445 while (CurScope != TopScope && !CurScope->isDeclScope(D)) {
446 CurScope = CurScope->getParent();
448 return CurScope != TopScope;
453 /// \brief Build a variable declaration for OpenMP loop iteration variable.
454 static VarDecl *buildVarDecl(Sema &SemaRef, SourceLocation Loc, QualType Type,
456 DeclContext *DC = SemaRef.CurContext;
457 IdentifierInfo *II = &SemaRef.PP.getIdentifierTable().get(Name);
458 TypeSourceInfo *TInfo = SemaRef.Context.getTrivialTypeSourceInfo(Type, Loc);
460 VarDecl::Create(SemaRef.Context, DC, Loc, Loc, II, Type, TInfo, SC_None);
465 static DeclRefExpr *buildDeclRefExpr(Sema &S, VarDecl *D, QualType Ty,
467 bool RefersToCapture = false) {
469 D->markUsed(S.Context);
470 return DeclRefExpr::Create(S.getASTContext(), NestedNameSpecifierLoc(),
471 SourceLocation(), D, RefersToCapture, Loc, Ty,
475 DSAStackTy::DSAVarData DSAStackTy::getTopDSA(VarDecl *D, bool FromParent) {
476 D = D->getCanonicalDecl();
479 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
480 // in a Construct, C/C++, predetermined, p.1]
481 // Variables appearing in threadprivate directives are threadprivate.
482 if ((D->getTLSKind() != VarDecl::TLS_None &&
483 !(D->hasAttr<OMPThreadPrivateDeclAttr>() &&
484 SemaRef.getLangOpts().OpenMPUseTLS &&
485 SemaRef.getASTContext().getTargetInfo().isTLSSupported())) ||
486 (D->getStorageClass() == SC_Register && D->hasAttr<AsmLabelAttr>() &&
487 !D->isLocalVarDecl())) {
488 addDSA(D, buildDeclRefExpr(SemaRef, D, D->getType().getNonReferenceType(),
492 if (Stack[0].SharingMap.count(D)) {
493 DVar.RefExpr = Stack[0].SharingMap[D].RefExpr;
494 DVar.CKind = OMPC_threadprivate;
498 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
499 // in a Construct, C/C++, predetermined, p.1]
500 // Variables with automatic storage duration that are declared in a scope
501 // inside the construct are private.
502 OpenMPDirectiveKind Kind =
503 FromParent ? getParentDirective() : getCurrentDirective();
504 auto StartI = std::next(Stack.rbegin());
505 auto EndI = std::prev(Stack.rend());
506 if (FromParent && StartI != EndI) {
507 StartI = std::next(StartI);
509 if (!isParallelOrTaskRegion(Kind)) {
510 if (isOpenMPLocal(D, StartI) &&
511 ((D->isLocalVarDecl() && (D->getStorageClass() == SC_Auto ||
512 D->getStorageClass() == SC_None)) ||
513 isa<ParmVarDecl>(D))) {
514 DVar.CKind = OMPC_private;
518 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
519 // in a Construct, C/C++, predetermined, p.4]
520 // Static data members are shared.
521 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
522 // in a Construct, C/C++, predetermined, p.7]
523 // Variables with static storage duration that are declared in a scope
524 // inside the construct are shared.
525 if (D->isStaticDataMember() || D->isStaticLocal()) {
526 DSAVarData DVarTemp =
527 hasDSA(D, isOpenMPPrivate, MatchesAlways(), FromParent);
528 if (DVarTemp.CKind != OMPC_unknown && DVarTemp.RefExpr)
531 DVar.CKind = OMPC_shared;
536 QualType Type = D->getType().getNonReferenceType().getCanonicalType();
537 bool IsConstant = Type.isConstant(SemaRef.getASTContext());
538 Type = SemaRef.getASTContext().getBaseElementType(Type);
539 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
540 // in a Construct, C/C++, predetermined, p.6]
541 // Variables with const qualified type having no mutable member are
544 SemaRef.getLangOpts().CPlusPlus ? Type->getAsCXXRecordDecl() : nullptr;
546 !(SemaRef.getLangOpts().CPlusPlus && RD && RD->hasMutableFields())) {
547 // Variables with const-qualified type having no mutable member may be
548 // listed in a firstprivate clause, even if they are static data members.
549 DSAVarData DVarTemp = hasDSA(D, MatchesAnyClause(OMPC_firstprivate),
550 MatchesAlways(), FromParent);
551 if (DVarTemp.CKind == OMPC_firstprivate && DVarTemp.RefExpr)
554 DVar.CKind = OMPC_shared;
558 // Explicitly specified attributes and local variables with predetermined
560 auto I = std::prev(StartI);
561 if (I->SharingMap.count(D)) {
562 DVar.RefExpr = I->SharingMap[D].RefExpr;
563 DVar.CKind = I->SharingMap[D].Attributes;
564 DVar.ImplicitDSALoc = I->DefaultAttrLoc;
570 DSAStackTy::DSAVarData DSAStackTy::getImplicitDSA(VarDecl *D, bool FromParent) {
571 D = D->getCanonicalDecl();
572 auto StartI = Stack.rbegin();
573 auto EndI = std::prev(Stack.rend());
574 if (FromParent && StartI != EndI) {
575 StartI = std::next(StartI);
577 return getDSA(StartI, D);
580 template <class ClausesPredicate, class DirectivesPredicate>
581 DSAStackTy::DSAVarData DSAStackTy::hasDSA(VarDecl *D, ClausesPredicate CPred,
582 DirectivesPredicate DPred,
584 D = D->getCanonicalDecl();
585 auto StartI = std::next(Stack.rbegin());
586 auto EndI = std::prev(Stack.rend());
587 if (FromParent && StartI != EndI) {
588 StartI = std::next(StartI);
590 for (auto I = StartI, EE = EndI; I != EE; ++I) {
591 if (!DPred(I->Directive) && !isParallelOrTaskRegion(I->Directive))
593 DSAVarData DVar = getDSA(I, D);
594 if (CPred(DVar.CKind))
600 template <class ClausesPredicate, class DirectivesPredicate>
601 DSAStackTy::DSAVarData
602 DSAStackTy::hasInnermostDSA(VarDecl *D, ClausesPredicate CPred,
603 DirectivesPredicate DPred, bool FromParent) {
604 D = D->getCanonicalDecl();
605 auto StartI = std::next(Stack.rbegin());
606 auto EndI = std::prev(Stack.rend());
607 if (FromParent && StartI != EndI) {
608 StartI = std::next(StartI);
610 for (auto I = StartI, EE = EndI; I != EE; ++I) {
611 if (!DPred(I->Directive))
613 DSAVarData DVar = getDSA(I, D);
614 if (CPred(DVar.CKind))
621 bool DSAStackTy::hasExplicitDSA(
622 VarDecl *D, const llvm::function_ref<bool(OpenMPClauseKind)> &CPred,
624 if (CPred(ClauseKindMode))
626 if (isClauseParsingMode())
628 D = D->getCanonicalDecl();
629 auto StartI = Stack.rbegin();
630 auto EndI = std::prev(Stack.rend());
631 if (std::distance(StartI, EndI) <= (int)Level)
633 std::advance(StartI, Level);
634 return (StartI->SharingMap.count(D) > 0) && StartI->SharingMap[D].RefExpr &&
635 CPred(StartI->SharingMap[D].Attributes);
638 template <class NamedDirectivesPredicate>
639 bool DSAStackTy::hasDirective(NamedDirectivesPredicate DPred, bool FromParent) {
640 auto StartI = std::next(Stack.rbegin());
641 auto EndI = std::prev(Stack.rend());
642 if (FromParent && StartI != EndI) {
643 StartI = std::next(StartI);
645 for (auto I = StartI, EE = EndI; I != EE; ++I) {
646 if (DPred(I->Directive, I->DirectiveName, I->ConstructLoc))
652 void Sema::InitDataSharingAttributesStack() {
653 VarDataSharingAttributesStack = new DSAStackTy(*this);
656 #define DSAStack static_cast<DSAStackTy *>(VarDataSharingAttributesStack)
658 bool Sema::IsOpenMPCapturedVar(VarDecl *VD) {
659 assert(LangOpts.OpenMP && "OpenMP is not allowed");
660 VD = VD->getCanonicalDecl();
661 if (DSAStack->getCurrentDirective() != OMPD_unknown &&
662 (!DSAStack->isClauseParsingMode() ||
663 DSAStack->getParentDirective() != OMPD_unknown)) {
664 if (DSAStack->isLoopControlVariable(VD) ||
665 (VD->hasLocalStorage() &&
666 isParallelOrTaskRegion(DSAStack->getCurrentDirective())) ||
667 DSAStack->isForceVarCapturing())
669 auto DVarPrivate = DSAStack->getTopDSA(VD, DSAStack->isClauseParsingMode());
670 if (DVarPrivate.CKind != OMPC_unknown && isOpenMPPrivate(DVarPrivate.CKind))
672 DVarPrivate = DSAStack->hasDSA(VD, isOpenMPPrivate, MatchesAlways(),
673 DSAStack->isClauseParsingMode());
674 return DVarPrivate.CKind != OMPC_unknown;
679 bool Sema::isOpenMPPrivateVar(VarDecl *VD, unsigned Level) {
680 assert(LangOpts.OpenMP && "OpenMP is not allowed");
681 return DSAStack->hasExplicitDSA(
682 VD, [](OpenMPClauseKind K) -> bool { return K == OMPC_private; }, Level);
685 void Sema::DestroyDataSharingAttributesStack() { delete DSAStack; }
687 void Sema::StartOpenMPDSABlock(OpenMPDirectiveKind DKind,
688 const DeclarationNameInfo &DirName,
689 Scope *CurScope, SourceLocation Loc) {
690 DSAStack->push(DKind, DirName, CurScope, Loc);
691 PushExpressionEvaluationContext(PotentiallyEvaluated);
694 void Sema::StartOpenMPClause(OpenMPClauseKind K) {
695 DSAStack->setClauseParsingMode(K);
698 void Sema::EndOpenMPClause() {
699 DSAStack->setClauseParsingMode(/*K=*/OMPC_unknown);
702 void Sema::EndOpenMPDSABlock(Stmt *CurDirective) {
703 // OpenMP [2.14.3.5, Restrictions, C/C++, p.1]
704 // A variable of class type (or array thereof) that appears in a lastprivate
705 // clause requires an accessible, unambiguous default constructor for the
706 // class type, unless the list item is also specified in a firstprivate
708 if (auto D = dyn_cast_or_null<OMPExecutableDirective>(CurDirective)) {
709 for (auto *C : D->clauses()) {
710 if (auto *Clause = dyn_cast<OMPLastprivateClause>(C)) {
711 SmallVector<Expr *, 8> PrivateCopies;
712 for (auto *DE : Clause->varlists()) {
713 if (DE->isValueDependent() || DE->isTypeDependent()) {
714 PrivateCopies.push_back(nullptr);
717 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(DE)->getDecl());
718 QualType Type = VD->getType();
719 auto DVar = DSAStack->getTopDSA(VD, false);
720 if (DVar.CKind == OMPC_lastprivate) {
721 // Generate helper private variable and initialize it with the
722 // default value. The address of the original variable is replaced
723 // by the address of the new private variable in CodeGen. This new
724 // variable is not added to IdResolver, so the code in the OpenMP
725 // region uses original variable for proper diagnostics.
727 buildVarDecl(*this, DE->getExprLoc(), Type.getUnqualifiedType(),
729 ActOnUninitializedDecl(VDPrivate, /*TypeMayContainAuto=*/false);
730 if (VDPrivate->isInvalidDecl())
732 PrivateCopies.push_back(buildDeclRefExpr(
733 *this, VDPrivate, DE->getType(), DE->getExprLoc()));
735 // The variable is also a firstprivate, so initialization sequence
736 // for private copy is generated already.
737 PrivateCopies.push_back(nullptr);
740 // Set initializers to private copies if no errors were found.
741 if (PrivateCopies.size() == Clause->varlist_size()) {
742 Clause->setPrivateCopies(PrivateCopies);
749 DiscardCleanupsInEvaluationContext();
750 PopExpressionEvaluationContext();
753 static bool FinishOpenMPLinearClause(OMPLinearClause &Clause, DeclRefExpr *IV,
754 Expr *NumIterations, Sema &SemaRef,
759 class VarDeclFilterCCC : public CorrectionCandidateCallback {
764 explicit VarDeclFilterCCC(Sema &S) : SemaRef(S) {}
765 bool ValidateCandidate(const TypoCorrection &Candidate) override {
766 NamedDecl *ND = Candidate.getCorrectionDecl();
767 if (VarDecl *VD = dyn_cast_or_null<VarDecl>(ND)) {
768 return VD->hasGlobalStorage() &&
769 SemaRef.isDeclInScope(ND, SemaRef.getCurLexicalContext(),
770 SemaRef.getCurScope());
777 ExprResult Sema::ActOnOpenMPIdExpression(Scope *CurScope,
778 CXXScopeSpec &ScopeSpec,
779 const DeclarationNameInfo &Id) {
780 LookupResult Lookup(*this, Id, LookupOrdinaryName);
781 LookupParsedName(Lookup, CurScope, &ScopeSpec, true);
783 if (Lookup.isAmbiguous())
787 if (!Lookup.isSingleResult()) {
788 if (TypoCorrection Corrected = CorrectTypo(
789 Id, LookupOrdinaryName, CurScope, nullptr,
790 llvm::make_unique<VarDeclFilterCCC>(*this), CTK_ErrorRecovery)) {
791 diagnoseTypo(Corrected,
793 ? diag::err_undeclared_var_use_suggest
794 : diag::err_omp_expected_var_arg_suggest)
796 VD = Corrected.getCorrectionDeclAs<VarDecl>();
798 Diag(Id.getLoc(), Lookup.empty() ? diag::err_undeclared_var_use
799 : diag::err_omp_expected_var_arg)
804 if (!(VD = Lookup.getAsSingle<VarDecl>())) {
805 Diag(Id.getLoc(), diag::err_omp_expected_var_arg) << Id.getName();
806 Diag(Lookup.getFoundDecl()->getLocation(), diag::note_declared_at);
810 Lookup.suppressDiagnostics();
812 // OpenMP [2.9.2, Syntax, C/C++]
813 // Variables must be file-scope, namespace-scope, or static block-scope.
814 if (!VD->hasGlobalStorage()) {
815 Diag(Id.getLoc(), diag::err_omp_global_var_arg)
816 << getOpenMPDirectiveName(OMPD_threadprivate) << !VD->isStaticLocal();
818 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
819 Diag(VD->getLocation(),
820 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
825 VarDecl *CanonicalVD = VD->getCanonicalDecl();
826 NamedDecl *ND = cast<NamedDecl>(CanonicalVD);
827 // OpenMP [2.9.2, Restrictions, C/C++, p.2]
828 // A threadprivate directive for file-scope variables must appear outside
829 // any definition or declaration.
830 if (CanonicalVD->getDeclContext()->isTranslationUnit() &&
831 !getCurLexicalContext()->isTranslationUnit()) {
832 Diag(Id.getLoc(), diag::err_omp_var_scope)
833 << getOpenMPDirectiveName(OMPD_threadprivate) << VD;
835 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
836 Diag(VD->getLocation(),
837 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
841 // OpenMP [2.9.2, Restrictions, C/C++, p.3]
842 // A threadprivate directive for static class member variables must appear
843 // in the class definition, in the same scope in which the member
844 // variables are declared.
845 if (CanonicalVD->isStaticDataMember() &&
846 !CanonicalVD->getDeclContext()->Equals(getCurLexicalContext())) {
847 Diag(Id.getLoc(), diag::err_omp_var_scope)
848 << getOpenMPDirectiveName(OMPD_threadprivate) << VD;
850 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
851 Diag(VD->getLocation(),
852 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
856 // OpenMP [2.9.2, Restrictions, C/C++, p.4]
857 // A threadprivate directive for namespace-scope variables must appear
858 // outside any definition or declaration other than the namespace
859 // definition itself.
860 if (CanonicalVD->getDeclContext()->isNamespace() &&
861 (!getCurLexicalContext()->isFileContext() ||
862 !getCurLexicalContext()->Encloses(CanonicalVD->getDeclContext()))) {
863 Diag(Id.getLoc(), diag::err_omp_var_scope)
864 << getOpenMPDirectiveName(OMPD_threadprivate) << VD;
866 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
867 Diag(VD->getLocation(),
868 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
872 // OpenMP [2.9.2, Restrictions, C/C++, p.6]
873 // A threadprivate directive for static block-scope variables must appear
874 // in the scope of the variable and not in a nested scope.
875 if (CanonicalVD->isStaticLocal() && CurScope &&
876 !isDeclInScope(ND, getCurLexicalContext(), CurScope)) {
877 Diag(Id.getLoc(), diag::err_omp_var_scope)
878 << getOpenMPDirectiveName(OMPD_threadprivate) << VD;
880 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
881 Diag(VD->getLocation(),
882 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
887 // OpenMP [2.9.2, Restrictions, C/C++, p.2-6]
888 // A threadprivate directive must lexically precede all references to any
889 // of the variables in its list.
890 if (VD->isUsed() && !DSAStack->isThreadPrivate(VD)) {
891 Diag(Id.getLoc(), diag::err_omp_var_used)
892 << getOpenMPDirectiveName(OMPD_threadprivate) << VD;
896 QualType ExprType = VD->getType().getNonReferenceType();
897 ExprResult DE = buildDeclRefExpr(*this, VD, ExprType, Id.getLoc());
902 Sema::ActOnOpenMPThreadprivateDirective(SourceLocation Loc,
903 ArrayRef<Expr *> VarList) {
904 if (OMPThreadPrivateDecl *D = CheckOMPThreadPrivateDecl(Loc, VarList)) {
905 CurContext->addDecl(D);
906 return DeclGroupPtrTy::make(DeclGroupRef(D));
908 return DeclGroupPtrTy();
912 class LocalVarRefChecker : public ConstStmtVisitor<LocalVarRefChecker, bool> {
916 bool VisitDeclRefExpr(const DeclRefExpr *E) {
917 if (auto VD = dyn_cast<VarDecl>(E->getDecl())) {
918 if (VD->hasLocalStorage()) {
919 SemaRef.Diag(E->getLocStart(),
920 diag::err_omp_local_var_in_threadprivate_init)
921 << E->getSourceRange();
922 SemaRef.Diag(VD->getLocation(), diag::note_defined_here)
923 << VD << VD->getSourceRange();
929 bool VisitStmt(const Stmt *S) {
930 for (auto Child : S->children()) {
931 if (Child && Visit(Child))
936 explicit LocalVarRefChecker(Sema &SemaRef) : SemaRef(SemaRef) {}
940 OMPThreadPrivateDecl *
941 Sema::CheckOMPThreadPrivateDecl(SourceLocation Loc, ArrayRef<Expr *> VarList) {
942 SmallVector<Expr *, 8> Vars;
943 for (auto &RefExpr : VarList) {
944 DeclRefExpr *DE = cast<DeclRefExpr>(RefExpr);
945 VarDecl *VD = cast<VarDecl>(DE->getDecl());
946 SourceLocation ILoc = DE->getExprLoc();
948 QualType QType = VD->getType();
949 if (QType->isDependentType() || QType->isInstantiationDependentType()) {
950 // It will be analyzed later.
955 // OpenMP [2.9.2, Restrictions, C/C++, p.10]
956 // A threadprivate variable must not have an incomplete type.
957 if (RequireCompleteType(ILoc, VD->getType(),
958 diag::err_omp_threadprivate_incomplete_type)) {
962 // OpenMP [2.9.2, Restrictions, C/C++, p.10]
963 // A threadprivate variable must not have a reference type.
964 if (VD->getType()->isReferenceType()) {
965 Diag(ILoc, diag::err_omp_ref_type_arg)
966 << getOpenMPDirectiveName(OMPD_threadprivate) << VD->getType();
968 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
969 Diag(VD->getLocation(),
970 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
975 // Check if this is a TLS variable. If TLS is not being supported, produce
976 // the corresponding diagnostic.
977 if ((VD->getTLSKind() != VarDecl::TLS_None &&
978 !(VD->hasAttr<OMPThreadPrivateDeclAttr>() &&
979 getLangOpts().OpenMPUseTLS &&
980 getASTContext().getTargetInfo().isTLSSupported())) ||
981 (VD->getStorageClass() == SC_Register && VD->hasAttr<AsmLabelAttr>() &&
982 !VD->isLocalVarDecl())) {
983 Diag(ILoc, diag::err_omp_var_thread_local)
984 << VD << ((VD->getTLSKind() != VarDecl::TLS_None) ? 0 : 1);
986 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
987 Diag(VD->getLocation(),
988 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
993 // Check if initial value of threadprivate variable reference variable with
994 // local storage (it is not supported by runtime).
995 if (auto Init = VD->getAnyInitializer()) {
996 LocalVarRefChecker Checker(*this);
997 if (Checker.Visit(Init))
1001 Vars.push_back(RefExpr);
1002 DSAStack->addDSA(VD, DE, OMPC_threadprivate);
1003 VD->addAttr(OMPThreadPrivateDeclAttr::CreateImplicit(
1004 Context, SourceRange(Loc, Loc)));
1005 if (auto *ML = Context.getASTMutationListener())
1006 ML->DeclarationMarkedOpenMPThreadPrivate(VD);
1008 OMPThreadPrivateDecl *D = nullptr;
1009 if (!Vars.empty()) {
1010 D = OMPThreadPrivateDecl::Create(Context, getCurLexicalContext(), Loc,
1012 D->setAccess(AS_public);
1017 static void ReportOriginalDSA(Sema &SemaRef, DSAStackTy *Stack,
1018 const VarDecl *VD, DSAStackTy::DSAVarData DVar,
1019 bool IsLoopIterVar = false) {
1021 SemaRef.Diag(DVar.RefExpr->getExprLoc(), diag::note_omp_explicit_dsa)
1022 << getOpenMPClauseName(DVar.CKind);
1026 PDSA_StaticMemberShared,
1027 PDSA_StaticLocalVarShared,
1028 PDSA_LoopIterVarPrivate,
1029 PDSA_LoopIterVarLinear,
1030 PDSA_LoopIterVarLastprivate,
1031 PDSA_ConstVarShared,
1032 PDSA_GlobalVarShared,
1033 PDSA_TaskVarFirstprivate,
1034 PDSA_LocalVarPrivate,
1036 } Reason = PDSA_Implicit;
1037 bool ReportHint = false;
1038 auto ReportLoc = VD->getLocation();
1039 if (IsLoopIterVar) {
1040 if (DVar.CKind == OMPC_private)
1041 Reason = PDSA_LoopIterVarPrivate;
1042 else if (DVar.CKind == OMPC_lastprivate)
1043 Reason = PDSA_LoopIterVarLastprivate;
1045 Reason = PDSA_LoopIterVarLinear;
1046 } else if (DVar.DKind == OMPD_task && DVar.CKind == OMPC_firstprivate) {
1047 Reason = PDSA_TaskVarFirstprivate;
1048 ReportLoc = DVar.ImplicitDSALoc;
1049 } else if (VD->isStaticLocal())
1050 Reason = PDSA_StaticLocalVarShared;
1051 else if (VD->isStaticDataMember())
1052 Reason = PDSA_StaticMemberShared;
1053 else if (VD->isFileVarDecl())
1054 Reason = PDSA_GlobalVarShared;
1055 else if (VD->getType().isConstant(SemaRef.getASTContext()))
1056 Reason = PDSA_ConstVarShared;
1057 else if (VD->isLocalVarDecl() && DVar.CKind == OMPC_private) {
1059 Reason = PDSA_LocalVarPrivate;
1061 if (Reason != PDSA_Implicit) {
1062 SemaRef.Diag(ReportLoc, diag::note_omp_predetermined_dsa)
1063 << Reason << ReportHint
1064 << getOpenMPDirectiveName(Stack->getCurrentDirective());
1065 } else if (DVar.ImplicitDSALoc.isValid()) {
1066 SemaRef.Diag(DVar.ImplicitDSALoc, diag::note_omp_implicit_dsa)
1067 << getOpenMPClauseName(DVar.CKind);
1072 class DSAAttrChecker : public StmtVisitor<DSAAttrChecker, void> {
1077 llvm::SmallVector<Expr *, 8> ImplicitFirstprivate;
1078 llvm::DenseMap<VarDecl *, Expr *> VarsWithInheritedDSA;
1081 void VisitDeclRefExpr(DeclRefExpr *E) {
1082 if (auto *VD = dyn_cast<VarDecl>(E->getDecl())) {
1083 // Skip internally declared variables.
1084 if (VD->isLocalVarDecl() && !CS->capturesVariable(VD))
1087 auto DVar = Stack->getTopDSA(VD, false);
1088 // Check if the variable has explicit DSA set and stop analysis if it so.
1089 if (DVar.RefExpr) return;
1091 auto ELoc = E->getExprLoc();
1092 auto DKind = Stack->getCurrentDirective();
1093 // The default(none) clause requires that each variable that is referenced
1094 // in the construct, and does not have a predetermined data-sharing
1095 // attribute, must have its data-sharing attribute explicitly determined
1096 // by being listed in a data-sharing attribute clause.
1097 if (DVar.CKind == OMPC_unknown && Stack->getDefaultDSA() == DSA_none &&
1098 isParallelOrTaskRegion(DKind) &&
1099 VarsWithInheritedDSA.count(VD) == 0) {
1100 VarsWithInheritedDSA[VD] = E;
1104 // OpenMP [2.9.3.6, Restrictions, p.2]
1105 // A list item that appears in a reduction clause of the innermost
1106 // enclosing worksharing or parallel construct may not be accessed in an
1108 DVar = Stack->hasInnermostDSA(VD, MatchesAnyClause(OMPC_reduction),
1109 [](OpenMPDirectiveKind K) -> bool {
1110 return isOpenMPParallelDirective(K) ||
1111 isOpenMPWorksharingDirective(K) ||
1112 isOpenMPTeamsDirective(K);
1115 if (DKind == OMPD_task && DVar.CKind == OMPC_reduction) {
1117 SemaRef.Diag(ELoc, diag::err_omp_reduction_in_task);
1118 ReportOriginalDSA(SemaRef, Stack, VD, DVar);
1122 // Define implicit data-sharing attributes for task.
1123 DVar = Stack->getImplicitDSA(VD, false);
1124 if (DKind == OMPD_task && DVar.CKind != OMPC_shared)
1125 ImplicitFirstprivate.push_back(E);
1128 void VisitOMPExecutableDirective(OMPExecutableDirective *S) {
1129 for (auto *C : S->clauses()) {
1130 // Skip analysis of arguments of implicitly defined firstprivate clause
1131 // for task directives.
1132 if (C && (!isa<OMPFirstprivateClause>(C) || C->getLocStart().isValid()))
1133 for (auto *CC : C->children()) {
1139 void VisitStmt(Stmt *S) {
1140 for (auto *C : S->children()) {
1141 if (C && !isa<OMPExecutableDirective>(C))
1146 bool isErrorFound() { return ErrorFound; }
1147 ArrayRef<Expr *> getImplicitFirstprivate() { return ImplicitFirstprivate; }
1148 llvm::DenseMap<VarDecl *, Expr *> &getVarsWithInheritedDSA() {
1149 return VarsWithInheritedDSA;
1152 DSAAttrChecker(DSAStackTy *S, Sema &SemaRef, CapturedStmt *CS)
1153 : Stack(S), SemaRef(SemaRef), ErrorFound(false), CS(CS) {}
1157 void Sema::ActOnOpenMPRegionStart(OpenMPDirectiveKind DKind, Scope *CurScope) {
1159 case OMPD_parallel: {
1160 QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1);
1161 QualType KmpInt32PtrTy = Context.getPointerType(KmpInt32Ty);
1162 Sema::CapturedParamNameType Params[] = {
1163 std::make_pair(".global_tid.", KmpInt32PtrTy),
1164 std::make_pair(".bound_tid.", KmpInt32PtrTy),
1165 std::make_pair(StringRef(), QualType()) // __context with shared vars
1167 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
1172 Sema::CapturedParamNameType Params[] = {
1173 std::make_pair(StringRef(), QualType()) // __context with shared vars
1175 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
1180 Sema::CapturedParamNameType Params[] = {
1181 std::make_pair(StringRef(), QualType()) // __context with shared vars
1183 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
1187 case OMPD_for_simd: {
1188 Sema::CapturedParamNameType Params[] = {
1189 std::make_pair(StringRef(), QualType()) // __context with shared vars
1191 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
1195 case OMPD_sections: {
1196 Sema::CapturedParamNameType Params[] = {
1197 std::make_pair(StringRef(), QualType()) // __context with shared vars
1199 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
1203 case OMPD_section: {
1204 Sema::CapturedParamNameType Params[] = {
1205 std::make_pair(StringRef(), QualType()) // __context with shared vars
1207 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
1212 Sema::CapturedParamNameType Params[] = {
1213 std::make_pair(StringRef(), QualType()) // __context with shared vars
1215 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
1220 Sema::CapturedParamNameType Params[] = {
1221 std::make_pair(StringRef(), QualType()) // __context with shared vars
1223 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
1227 case OMPD_critical: {
1228 Sema::CapturedParamNameType Params[] = {
1229 std::make_pair(StringRef(), QualType()) // __context with shared vars
1231 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
1235 case OMPD_parallel_for: {
1236 QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1);
1237 QualType KmpInt32PtrTy = Context.getPointerType(KmpInt32Ty);
1238 Sema::CapturedParamNameType Params[] = {
1239 std::make_pair(".global_tid.", KmpInt32PtrTy),
1240 std::make_pair(".bound_tid.", KmpInt32PtrTy),
1241 std::make_pair(StringRef(), QualType()) // __context with shared vars
1243 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
1247 case OMPD_parallel_for_simd: {
1248 QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1);
1249 QualType KmpInt32PtrTy = Context.getPointerType(KmpInt32Ty);
1250 Sema::CapturedParamNameType Params[] = {
1251 std::make_pair(".global_tid.", KmpInt32PtrTy),
1252 std::make_pair(".bound_tid.", KmpInt32PtrTy),
1253 std::make_pair(StringRef(), QualType()) // __context with shared vars
1255 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
1259 case OMPD_parallel_sections: {
1260 QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1);
1261 QualType KmpInt32PtrTy = Context.getPointerType(KmpInt32Ty);
1262 Sema::CapturedParamNameType Params[] = {
1263 std::make_pair(".global_tid.", KmpInt32PtrTy),
1264 std::make_pair(".bound_tid.", KmpInt32PtrTy),
1265 std::make_pair(StringRef(), QualType()) // __context with shared vars
1267 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
1272 QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1);
1273 QualType Args[] = {Context.VoidPtrTy.withConst().withRestrict()};
1274 FunctionProtoType::ExtProtoInfo EPI;
1275 EPI.Variadic = true;
1276 QualType CopyFnType = Context.getFunctionType(Context.VoidTy, Args, EPI);
1277 Sema::CapturedParamNameType Params[] = {
1278 std::make_pair(".global_tid.", KmpInt32Ty),
1279 std::make_pair(".part_id.", KmpInt32Ty),
1280 std::make_pair(".privates.",
1281 Context.VoidPtrTy.withConst().withRestrict()),
1284 Context.getPointerType(CopyFnType).withConst().withRestrict()),
1285 std::make_pair(StringRef(), QualType()) // __context with shared vars
1287 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
1289 // Mark this captured region as inlined, because we don't use outlined
1290 // function directly.
1291 getCurCapturedRegion()->TheCapturedDecl->addAttr(
1292 AlwaysInlineAttr::CreateImplicit(
1293 Context, AlwaysInlineAttr::Keyword_forceinline, SourceRange()));
1296 case OMPD_ordered: {
1297 Sema::CapturedParamNameType Params[] = {
1298 std::make_pair(StringRef(), QualType()) // __context with shared vars
1300 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
1305 Sema::CapturedParamNameType Params[] = {
1306 std::make_pair(StringRef(), QualType()) // __context with shared vars
1308 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
1313 Sema::CapturedParamNameType Params[] = {
1314 std::make_pair(StringRef(), QualType()) // __context with shared vars
1316 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
1321 QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1);
1322 QualType KmpInt32PtrTy = Context.getPointerType(KmpInt32Ty);
1323 Sema::CapturedParamNameType Params[] = {
1324 std::make_pair(".global_tid.", KmpInt32PtrTy),
1325 std::make_pair(".bound_tid.", KmpInt32PtrTy),
1326 std::make_pair(StringRef(), QualType()) // __context with shared vars
1328 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
1332 case OMPD_taskgroup: {
1333 Sema::CapturedParamNameType Params[] = {
1334 std::make_pair(StringRef(), QualType()) // __context with shared vars
1336 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
1340 case OMPD_threadprivate:
1341 case OMPD_taskyield:
1344 case OMPD_cancellation_point:
1347 llvm_unreachable("OpenMP Directive is not allowed");
1349 llvm_unreachable("Unknown OpenMP directive");
1353 StmtResult Sema::ActOnOpenMPRegionEnd(StmtResult S,
1354 ArrayRef<OMPClause *> Clauses) {
1355 if (!S.isUsable()) {
1356 ActOnCapturedRegionError();
1359 // This is required for proper codegen.
1360 for (auto *Clause : Clauses) {
1361 if (isOpenMPPrivate(Clause->getClauseKind()) ||
1362 Clause->getClauseKind() == OMPC_copyprivate ||
1363 (getLangOpts().OpenMPUseTLS &&
1364 getASTContext().getTargetInfo().isTLSSupported() &&
1365 Clause->getClauseKind() == OMPC_copyin)) {
1366 DSAStack->setForceVarCapturing(Clause->getClauseKind() == OMPC_copyin);
1367 // Mark all variables in private list clauses as used in inner region.
1368 for (auto *VarRef : Clause->children()) {
1369 if (auto *E = cast_or_null<Expr>(VarRef)) {
1370 MarkDeclarationsReferencedInExpr(E);
1373 DSAStack->setForceVarCapturing(/*V=*/false);
1374 } else if (isParallelOrTaskRegion(DSAStack->getCurrentDirective()) &&
1375 Clause->getClauseKind() == OMPC_schedule) {
1376 // Mark all variables in private list clauses as used in inner region.
1377 // Required for proper codegen of combined directives.
1378 // TODO: add processing for other clauses.
1379 if (auto *E = cast_or_null<Expr>(
1380 cast<OMPScheduleClause>(Clause)->getHelperChunkSize())) {
1381 MarkDeclarationsReferencedInExpr(E);
1385 return ActOnCapturedRegionEnd(S.get());
1388 static bool CheckNestingOfRegions(Sema &SemaRef, DSAStackTy *Stack,
1389 OpenMPDirectiveKind CurrentRegion,
1390 const DeclarationNameInfo &CurrentName,
1391 OpenMPDirectiveKind CancelRegion,
1392 SourceLocation StartLoc) {
1393 // Allowed nesting of constructs
1394 // +------------------+-----------------+------------------------------------+
1395 // | Parent directive | Child directive | Closely (!), No-Closely(+), Both(*)|
1396 // +------------------+-----------------+------------------------------------+
1397 // | parallel | parallel | * |
1398 // | parallel | for | * |
1399 // | parallel | for simd | * |
1400 // | parallel | master | * |
1401 // | parallel | critical | * |
1402 // | parallel | simd | * |
1403 // | parallel | sections | * |
1404 // | parallel | section | + |
1405 // | parallel | single | * |
1406 // | parallel | parallel for | * |
1407 // | parallel |parallel for simd| * |
1408 // | parallel |parallel sections| * |
1409 // | parallel | task | * |
1410 // | parallel | taskyield | * |
1411 // | parallel | barrier | * |
1412 // | parallel | taskwait | * |
1413 // | parallel | taskgroup | * |
1414 // | parallel | flush | * |
1415 // | parallel | ordered | + |
1416 // | parallel | atomic | * |
1417 // | parallel | target | * |
1418 // | parallel | teams | + |
1419 // | parallel | cancellation | |
1421 // | parallel | cancel | ! |
1422 // +------------------+-----------------+------------------------------------+
1423 // | for | parallel | * |
1424 // | for | for | + |
1425 // | for | for simd | + |
1426 // | for | master | + |
1427 // | for | critical | * |
1428 // | for | simd | * |
1429 // | for | sections | + |
1430 // | for | section | + |
1431 // | for | single | + |
1432 // | for | parallel for | * |
1433 // | for |parallel for simd| * |
1434 // | for |parallel sections| * |
1435 // | for | task | * |
1436 // | for | taskyield | * |
1437 // | for | barrier | + |
1438 // | for | taskwait | * |
1439 // | for | taskgroup | * |
1440 // | for | flush | * |
1441 // | for | ordered | * (if construct is ordered) |
1442 // | for | atomic | * |
1443 // | for | target | * |
1444 // | for | teams | + |
1445 // | for | cancellation | |
1447 // | for | cancel | ! |
1448 // +------------------+-----------------+------------------------------------+
1449 // | master | parallel | * |
1450 // | master | for | + |
1451 // | master | for simd | + |
1452 // | master | master | * |
1453 // | master | critical | * |
1454 // | master | simd | * |
1455 // | master | sections | + |
1456 // | master | section | + |
1457 // | master | single | + |
1458 // | master | parallel for | * |
1459 // | master |parallel for simd| * |
1460 // | master |parallel sections| * |
1461 // | master | task | * |
1462 // | master | taskyield | * |
1463 // | master | barrier | + |
1464 // | master | taskwait | * |
1465 // | master | taskgroup | * |
1466 // | master | flush | * |
1467 // | master | ordered | + |
1468 // | master | atomic | * |
1469 // | master | target | * |
1470 // | master | teams | + |
1471 // | master | cancellation | |
1473 // | master | cancel | |
1474 // +------------------+-----------------+------------------------------------+
1475 // | critical | parallel | * |
1476 // | critical | for | + |
1477 // | critical | for simd | + |
1478 // | critical | master | * |
1479 // | critical | critical | * (should have different names) |
1480 // | critical | simd | * |
1481 // | critical | sections | + |
1482 // | critical | section | + |
1483 // | critical | single | + |
1484 // | critical | parallel for | * |
1485 // | critical |parallel for simd| * |
1486 // | critical |parallel sections| * |
1487 // | critical | task | * |
1488 // | critical | taskyield | * |
1489 // | critical | barrier | + |
1490 // | critical | taskwait | * |
1491 // | critical | taskgroup | * |
1492 // | critical | ordered | + |
1493 // | critical | atomic | * |
1494 // | critical | target | * |
1495 // | critical | teams | + |
1496 // | critical | cancellation | |
1498 // | critical | cancel | |
1499 // +------------------+-----------------+------------------------------------+
1500 // | simd | parallel | |
1502 // | simd | for simd | |
1503 // | simd | master | |
1504 // | simd | critical | |
1505 // | simd | simd | |
1506 // | simd | sections | |
1507 // | simd | section | |
1508 // | simd | single | |
1509 // | simd | parallel for | |
1510 // | simd |parallel for simd| |
1511 // | simd |parallel sections| |
1512 // | simd | task | |
1513 // | simd | taskyield | |
1514 // | simd | barrier | |
1515 // | simd | taskwait | |
1516 // | simd | taskgroup | |
1517 // | simd | flush | |
1518 // | simd | ordered | |
1519 // | simd | atomic | |
1520 // | simd | target | |
1521 // | simd | teams | |
1522 // | simd | cancellation | |
1524 // | simd | cancel | |
1525 // +------------------+-----------------+------------------------------------+
1526 // | for simd | parallel | |
1527 // | for simd | for | |
1528 // | for simd | for simd | |
1529 // | for simd | master | |
1530 // | for simd | critical | |
1531 // | for simd | simd | |
1532 // | for simd | sections | |
1533 // | for simd | section | |
1534 // | for simd | single | |
1535 // | for simd | parallel for | |
1536 // | for simd |parallel for simd| |
1537 // | for simd |parallel sections| |
1538 // | for simd | task | |
1539 // | for simd | taskyield | |
1540 // | for simd | barrier | |
1541 // | for simd | taskwait | |
1542 // | for simd | taskgroup | |
1543 // | for simd | flush | |
1544 // | for simd | ordered | |
1545 // | for simd | atomic | |
1546 // | for simd | target | |
1547 // | for simd | teams | |
1548 // | for simd | cancellation | |
1550 // | for simd | cancel | |
1551 // +------------------+-----------------+------------------------------------+
1552 // | parallel for simd| parallel | |
1553 // | parallel for simd| for | |
1554 // | parallel for simd| for simd | |
1555 // | parallel for simd| master | |
1556 // | parallel for simd| critical | |
1557 // | parallel for simd| simd | |
1558 // | parallel for simd| sections | |
1559 // | parallel for simd| section | |
1560 // | parallel for simd| single | |
1561 // | parallel for simd| parallel for | |
1562 // | parallel for simd|parallel for simd| |
1563 // | parallel for simd|parallel sections| |
1564 // | parallel for simd| task | |
1565 // | parallel for simd| taskyield | |
1566 // | parallel for simd| barrier | |
1567 // | parallel for simd| taskwait | |
1568 // | parallel for simd| taskgroup | |
1569 // | parallel for simd| flush | |
1570 // | parallel for simd| ordered | |
1571 // | parallel for simd| atomic | |
1572 // | parallel for simd| target | |
1573 // | parallel for simd| teams | |
1574 // | parallel for simd| cancellation | |
1576 // | parallel for simd| cancel | |
1577 // +------------------+-----------------+------------------------------------+
1578 // | sections | parallel | * |
1579 // | sections | for | + |
1580 // | sections | for simd | + |
1581 // | sections | master | + |
1582 // | sections | critical | * |
1583 // | sections | simd | * |
1584 // | sections | sections | + |
1585 // | sections | section | * |
1586 // | sections | single | + |
1587 // | sections | parallel for | * |
1588 // | sections |parallel for simd| * |
1589 // | sections |parallel sections| * |
1590 // | sections | task | * |
1591 // | sections | taskyield | * |
1592 // | sections | barrier | + |
1593 // | sections | taskwait | * |
1594 // | sections | taskgroup | * |
1595 // | sections | flush | * |
1596 // | sections | ordered | + |
1597 // | sections | atomic | * |
1598 // | sections | target | * |
1599 // | sections | teams | + |
1600 // | sections | cancellation | |
1602 // | sections | cancel | ! |
1603 // +------------------+-----------------+------------------------------------+
1604 // | section | parallel | * |
1605 // | section | for | + |
1606 // | section | for simd | + |
1607 // | section | master | + |
1608 // | section | critical | * |
1609 // | section | simd | * |
1610 // | section | sections | + |
1611 // | section | section | + |
1612 // | section | single | + |
1613 // | section | parallel for | * |
1614 // | section |parallel for simd| * |
1615 // | section |parallel sections| * |
1616 // | section | task | * |
1617 // | section | taskyield | * |
1618 // | section | barrier | + |
1619 // | section | taskwait | * |
1620 // | section | taskgroup | * |
1621 // | section | flush | * |
1622 // | section | ordered | + |
1623 // | section | atomic | * |
1624 // | section | target | * |
1625 // | section | teams | + |
1626 // | section | cancellation | |
1628 // | section | cancel | ! |
1629 // +------------------+-----------------+------------------------------------+
1630 // | single | parallel | * |
1631 // | single | for | + |
1632 // | single | for simd | + |
1633 // | single | master | + |
1634 // | single | critical | * |
1635 // | single | simd | * |
1636 // | single | sections | + |
1637 // | single | section | + |
1638 // | single | single | + |
1639 // | single | parallel for | * |
1640 // | single |parallel for simd| * |
1641 // | single |parallel sections| * |
1642 // | single | task | * |
1643 // | single | taskyield | * |
1644 // | single | barrier | + |
1645 // | single | taskwait | * |
1646 // | single | taskgroup | * |
1647 // | single | flush | * |
1648 // | single | ordered | + |
1649 // | single | atomic | * |
1650 // | single | target | * |
1651 // | single | teams | + |
1652 // | single | cancellation | |
1654 // | single | cancel | |
1655 // +------------------+-----------------+------------------------------------+
1656 // | parallel for | parallel | * |
1657 // | parallel for | for | + |
1658 // | parallel for | for simd | + |
1659 // | parallel for | master | + |
1660 // | parallel for | critical | * |
1661 // | parallel for | simd | * |
1662 // | parallel for | sections | + |
1663 // | parallel for | section | + |
1664 // | parallel for | single | + |
1665 // | parallel for | parallel for | * |
1666 // | parallel for |parallel for simd| * |
1667 // | parallel for |parallel sections| * |
1668 // | parallel for | task | * |
1669 // | parallel for | taskyield | * |
1670 // | parallel for | barrier | + |
1671 // | parallel for | taskwait | * |
1672 // | parallel for | taskgroup | * |
1673 // | parallel for | flush | * |
1674 // | parallel for | ordered | * (if construct is ordered) |
1675 // | parallel for | atomic | * |
1676 // | parallel for | target | * |
1677 // | parallel for | teams | + |
1678 // | parallel for | cancellation | |
1680 // | parallel for | cancel | ! |
1681 // +------------------+-----------------+------------------------------------+
1682 // | parallel sections| parallel | * |
1683 // | parallel sections| for | + |
1684 // | parallel sections| for simd | + |
1685 // | parallel sections| master | + |
1686 // | parallel sections| critical | + |
1687 // | parallel sections| simd | * |
1688 // | parallel sections| sections | + |
1689 // | parallel sections| section | * |
1690 // | parallel sections| single | + |
1691 // | parallel sections| parallel for | * |
1692 // | parallel sections|parallel for simd| * |
1693 // | parallel sections|parallel sections| * |
1694 // | parallel sections| task | * |
1695 // | parallel sections| taskyield | * |
1696 // | parallel sections| barrier | + |
1697 // | parallel sections| taskwait | * |
1698 // | parallel sections| taskgroup | * |
1699 // | parallel sections| flush | * |
1700 // | parallel sections| ordered | + |
1701 // | parallel sections| atomic | * |
1702 // | parallel sections| target | * |
1703 // | parallel sections| teams | + |
1704 // | parallel sections| cancellation | |
1706 // | parallel sections| cancel | ! |
1707 // +------------------+-----------------+------------------------------------+
1708 // | task | parallel | * |
1709 // | task | for | + |
1710 // | task | for simd | + |
1711 // | task | master | + |
1712 // | task | critical | * |
1713 // | task | simd | * |
1714 // | task | sections | + |
1715 // | task | section | + |
1716 // | task | single | + |
1717 // | task | parallel for | * |
1718 // | task |parallel for simd| * |
1719 // | task |parallel sections| * |
1720 // | task | task | * |
1721 // | task | taskyield | * |
1722 // | task | barrier | + |
1723 // | task | taskwait | * |
1724 // | task | taskgroup | * |
1725 // | task | flush | * |
1726 // | task | ordered | + |
1727 // | task | atomic | * |
1728 // | task | target | * |
1729 // | task | teams | + |
1730 // | task | cancellation | |
1732 // | task | cancel | ! |
1733 // +------------------+-----------------+------------------------------------+
1734 // | ordered | parallel | * |
1735 // | ordered | for | + |
1736 // | ordered | for simd | + |
1737 // | ordered | master | * |
1738 // | ordered | critical | * |
1739 // | ordered | simd | * |
1740 // | ordered | sections | + |
1741 // | ordered | section | + |
1742 // | ordered | single | + |
1743 // | ordered | parallel for | * |
1744 // | ordered |parallel for simd| * |
1745 // | ordered |parallel sections| * |
1746 // | ordered | task | * |
1747 // | ordered | taskyield | * |
1748 // | ordered | barrier | + |
1749 // | ordered | taskwait | * |
1750 // | ordered | taskgroup | * |
1751 // | ordered | flush | * |
1752 // | ordered | ordered | + |
1753 // | ordered | atomic | * |
1754 // | ordered | target | * |
1755 // | ordered | teams | + |
1756 // | ordered | cancellation | |
1758 // | ordered | cancel | |
1759 // +------------------+-----------------+------------------------------------+
1760 // | atomic | parallel | |
1761 // | atomic | for | |
1762 // | atomic | for simd | |
1763 // | atomic | master | |
1764 // | atomic | critical | |
1765 // | atomic | simd | |
1766 // | atomic | sections | |
1767 // | atomic | section | |
1768 // | atomic | single | |
1769 // | atomic | parallel for | |
1770 // | atomic |parallel for simd| |
1771 // | atomic |parallel sections| |
1772 // | atomic | task | |
1773 // | atomic | taskyield | |
1774 // | atomic | barrier | |
1775 // | atomic | taskwait | |
1776 // | atomic | taskgroup | |
1777 // | atomic | flush | |
1778 // | atomic | ordered | |
1779 // | atomic | atomic | |
1780 // | atomic | target | |
1781 // | atomic | teams | |
1782 // | atomic | cancellation | |
1784 // | atomic | cancel | |
1785 // +------------------+-----------------+------------------------------------+
1786 // | target | parallel | * |
1787 // | target | for | * |
1788 // | target | for simd | * |
1789 // | target | master | * |
1790 // | target | critical | * |
1791 // | target | simd | * |
1792 // | target | sections | * |
1793 // | target | section | * |
1794 // | target | single | * |
1795 // | target | parallel for | * |
1796 // | target |parallel for simd| * |
1797 // | target |parallel sections| * |
1798 // | target | task | * |
1799 // | target | taskyield | * |
1800 // | target | barrier | * |
1801 // | target | taskwait | * |
1802 // | target | taskgroup | * |
1803 // | target | flush | * |
1804 // | target | ordered | * |
1805 // | target | atomic | * |
1806 // | target | target | * |
1807 // | target | teams | * |
1808 // | target | cancellation | |
1810 // | target | cancel | |
1811 // +------------------+-----------------+------------------------------------+
1812 // | teams | parallel | * |
1813 // | teams | for | + |
1814 // | teams | for simd | + |
1815 // | teams | master | + |
1816 // | teams | critical | + |
1817 // | teams | simd | + |
1818 // | teams | sections | + |
1819 // | teams | section | + |
1820 // | teams | single | + |
1821 // | teams | parallel for | * |
1822 // | teams |parallel for simd| * |
1823 // | teams |parallel sections| * |
1824 // | teams | task | + |
1825 // | teams | taskyield | + |
1826 // | teams | barrier | + |
1827 // | teams | taskwait | + |
1828 // | teams | taskgroup | + |
1829 // | teams | flush | + |
1830 // | teams | ordered | + |
1831 // | teams | atomic | + |
1832 // | teams | target | + |
1833 // | teams | teams | + |
1834 // | teams | cancellation | |
1836 // | teams | cancel | |
1837 // +------------------+-----------------+------------------------------------+
1838 if (Stack->getCurScope()) {
1839 auto ParentRegion = Stack->getParentDirective();
1840 bool NestingProhibited = false;
1841 bool CloseNesting = true;
1844 ShouldBeInParallelRegion,
1845 ShouldBeInOrderedRegion,
1846 ShouldBeInTargetRegion
1847 } Recommend = NoRecommend;
1848 if (isOpenMPSimdDirective(ParentRegion)) {
1849 // OpenMP [2.16, Nesting of Regions]
1850 // OpenMP constructs may not be nested inside a simd region.
1851 SemaRef.Diag(StartLoc, diag::err_omp_prohibited_region_simd);
1854 if (ParentRegion == OMPD_atomic) {
1855 // OpenMP [2.16, Nesting of Regions]
1856 // OpenMP constructs may not be nested inside an atomic region.
1857 SemaRef.Diag(StartLoc, diag::err_omp_prohibited_region_atomic);
1860 if (CurrentRegion == OMPD_section) {
1861 // OpenMP [2.7.2, sections Construct, Restrictions]
1862 // Orphaned section directives are prohibited. That is, the section
1863 // directives must appear within the sections construct and must not be
1864 // encountered elsewhere in the sections region.
1865 if (ParentRegion != OMPD_sections &&
1866 ParentRegion != OMPD_parallel_sections) {
1867 SemaRef.Diag(StartLoc, diag::err_omp_orphaned_section_directive)
1868 << (ParentRegion != OMPD_unknown)
1869 << getOpenMPDirectiveName(ParentRegion);
1874 // Allow some constructs to be orphaned (they could be used in functions,
1875 // called from OpenMP regions with the required preconditions).
1876 if (ParentRegion == OMPD_unknown)
1878 if (CurrentRegion == OMPD_cancellation_point ||
1879 CurrentRegion == OMPD_cancel) {
1880 // OpenMP [2.16, Nesting of Regions]
1881 // A cancellation point construct for which construct-type-clause is
1882 // taskgroup must be nested inside a task construct. A cancellation
1883 // point construct for which construct-type-clause is not taskgroup must
1884 // be closely nested inside an OpenMP construct that matches the type
1885 // specified in construct-type-clause.
1886 // A cancel construct for which construct-type-clause is taskgroup must be
1887 // nested inside a task construct. A cancel construct for which
1888 // construct-type-clause is not taskgroup must be closely nested inside an
1889 // OpenMP construct that matches the type specified in
1890 // construct-type-clause.
1892 !((CancelRegion == OMPD_parallel && ParentRegion == OMPD_parallel) ||
1893 (CancelRegion == OMPD_for && ParentRegion == OMPD_for) ||
1894 (CancelRegion == OMPD_taskgroup && ParentRegion == OMPD_task) ||
1895 (CancelRegion == OMPD_sections &&
1896 (ParentRegion == OMPD_section || ParentRegion == OMPD_sections)));
1897 } else if (CurrentRegion == OMPD_master) {
1898 // OpenMP [2.16, Nesting of Regions]
1899 // A master region may not be closely nested inside a worksharing,
1900 // atomic, or explicit task region.
1901 NestingProhibited = isOpenMPWorksharingDirective(ParentRegion) ||
1902 ParentRegion == OMPD_task;
1903 } else if (CurrentRegion == OMPD_critical && CurrentName.getName()) {
1904 // OpenMP [2.16, Nesting of Regions]
1905 // A critical region may not be nested (closely or otherwise) inside a
1906 // critical region with the same name. Note that this restriction is not
1907 // sufficient to prevent deadlock.
1908 SourceLocation PreviousCriticalLoc;
1910 Stack->hasDirective([CurrentName, &PreviousCriticalLoc](
1911 OpenMPDirectiveKind K,
1912 const DeclarationNameInfo &DNI,
1915 if (K == OMPD_critical &&
1916 DNI.getName() == CurrentName.getName()) {
1917 PreviousCriticalLoc = Loc;
1922 false /* skip top directive */);
1924 SemaRef.Diag(StartLoc,
1925 diag::err_omp_prohibited_region_critical_same_name)
1926 << CurrentName.getName();
1927 if (PreviousCriticalLoc.isValid())
1928 SemaRef.Diag(PreviousCriticalLoc,
1929 diag::note_omp_previous_critical_region);
1932 } else if (CurrentRegion == OMPD_barrier) {
1933 // OpenMP [2.16, Nesting of Regions]
1934 // A barrier region may not be closely nested inside a worksharing,
1935 // explicit task, critical, ordered, atomic, or master region.
1937 isOpenMPWorksharingDirective(ParentRegion) ||
1938 ParentRegion == OMPD_task || ParentRegion == OMPD_master ||
1939 ParentRegion == OMPD_critical || ParentRegion == OMPD_ordered;
1940 } else if (isOpenMPWorksharingDirective(CurrentRegion) &&
1941 !isOpenMPParallelDirective(CurrentRegion)) {
1942 // OpenMP [2.16, Nesting of Regions]
1943 // A worksharing region may not be closely nested inside a worksharing,
1944 // explicit task, critical, ordered, atomic, or master region.
1946 isOpenMPWorksharingDirective(ParentRegion) ||
1947 ParentRegion == OMPD_task || ParentRegion == OMPD_master ||
1948 ParentRegion == OMPD_critical || ParentRegion == OMPD_ordered;
1949 Recommend = ShouldBeInParallelRegion;
1950 } else if (CurrentRegion == OMPD_ordered) {
1951 // OpenMP [2.16, Nesting of Regions]
1952 // An ordered region may not be closely nested inside a critical,
1953 // atomic, or explicit task region.
1954 // An ordered region must be closely nested inside a loop region (or
1955 // parallel loop region) with an ordered clause.
1956 NestingProhibited = ParentRegion == OMPD_critical ||
1957 ParentRegion == OMPD_task ||
1958 !Stack->isParentOrderedRegion();
1959 Recommend = ShouldBeInOrderedRegion;
1960 } else if (isOpenMPTeamsDirective(CurrentRegion)) {
1961 // OpenMP [2.16, Nesting of Regions]
1962 // If specified, a teams construct must be contained within a target
1964 NestingProhibited = ParentRegion != OMPD_target;
1965 Recommend = ShouldBeInTargetRegion;
1966 Stack->setParentTeamsRegionLoc(Stack->getConstructLoc());
1968 if (!NestingProhibited && isOpenMPTeamsDirective(ParentRegion)) {
1969 // OpenMP [2.16, Nesting of Regions]
1970 // distribute, parallel, parallel sections, parallel workshare, and the
1971 // parallel loop and parallel loop SIMD constructs are the only OpenMP
1972 // constructs that can be closely nested in the teams region.
1973 // TODO: add distribute directive.
1974 NestingProhibited = !isOpenMPParallelDirective(CurrentRegion);
1975 Recommend = ShouldBeInParallelRegion;
1977 if (NestingProhibited) {
1978 SemaRef.Diag(StartLoc, diag::err_omp_prohibited_region)
1979 << CloseNesting << getOpenMPDirectiveName(ParentRegion) << Recommend
1980 << getOpenMPDirectiveName(CurrentRegion);
1987 StmtResult Sema::ActOnOpenMPExecutableDirective(
1988 OpenMPDirectiveKind Kind, const DeclarationNameInfo &DirName,
1989 OpenMPDirectiveKind CancelRegion, ArrayRef<OMPClause *> Clauses,
1990 Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc) {
1991 StmtResult Res = StmtError();
1992 if (CheckNestingOfRegions(*this, DSAStack, Kind, DirName, CancelRegion,
1996 llvm::SmallVector<OMPClause *, 8> ClausesWithImplicit;
1997 llvm::DenseMap<VarDecl *, Expr *> VarsWithInheritedDSA;
1998 bool ErrorFound = false;
1999 ClausesWithImplicit.append(Clauses.begin(), Clauses.end());
2001 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
2003 // Check default data sharing attributes for referenced variables.
2004 DSAAttrChecker DSAChecker(DSAStack, *this, cast<CapturedStmt>(AStmt));
2005 DSAChecker.Visit(cast<CapturedStmt>(AStmt)->getCapturedStmt());
2006 if (DSAChecker.isErrorFound())
2008 // Generate list of implicitly defined firstprivate variables.
2009 VarsWithInheritedDSA = DSAChecker.getVarsWithInheritedDSA();
2011 if (!DSAChecker.getImplicitFirstprivate().empty()) {
2012 if (OMPClause *Implicit = ActOnOpenMPFirstprivateClause(
2013 DSAChecker.getImplicitFirstprivate(), SourceLocation(),
2014 SourceLocation(), SourceLocation())) {
2015 ClausesWithImplicit.push_back(Implicit);
2016 ErrorFound = cast<OMPFirstprivateClause>(Implicit)->varlist_size() !=
2017 DSAChecker.getImplicitFirstprivate().size();
2025 Res = ActOnOpenMPParallelDirective(ClausesWithImplicit, AStmt, StartLoc,
2029 Res = ActOnOpenMPSimdDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc,
2030 VarsWithInheritedDSA);
2033 Res = ActOnOpenMPForDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc,
2034 VarsWithInheritedDSA);
2037 Res = ActOnOpenMPForSimdDirective(ClausesWithImplicit, AStmt, StartLoc,
2038 EndLoc, VarsWithInheritedDSA);
2041 Res = ActOnOpenMPSectionsDirective(ClausesWithImplicit, AStmt, StartLoc,
2045 assert(ClausesWithImplicit.empty() &&
2046 "No clauses are allowed for 'omp section' directive");
2047 Res = ActOnOpenMPSectionDirective(AStmt, StartLoc, EndLoc);
2050 Res = ActOnOpenMPSingleDirective(ClausesWithImplicit, AStmt, StartLoc,
2054 assert(ClausesWithImplicit.empty() &&
2055 "No clauses are allowed for 'omp master' directive");
2056 Res = ActOnOpenMPMasterDirective(AStmt, StartLoc, EndLoc);
2059 assert(ClausesWithImplicit.empty() &&
2060 "No clauses are allowed for 'omp critical' directive");
2061 Res = ActOnOpenMPCriticalDirective(DirName, AStmt, StartLoc, EndLoc);
2063 case OMPD_parallel_for:
2064 Res = ActOnOpenMPParallelForDirective(ClausesWithImplicit, AStmt, StartLoc,
2065 EndLoc, VarsWithInheritedDSA);
2067 case OMPD_parallel_for_simd:
2068 Res = ActOnOpenMPParallelForSimdDirective(
2069 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
2071 case OMPD_parallel_sections:
2072 Res = ActOnOpenMPParallelSectionsDirective(ClausesWithImplicit, AStmt,
2077 ActOnOpenMPTaskDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc);
2079 case OMPD_taskyield:
2080 assert(ClausesWithImplicit.empty() &&
2081 "No clauses are allowed for 'omp taskyield' directive");
2082 assert(AStmt == nullptr &&
2083 "No associated statement allowed for 'omp taskyield' directive");
2084 Res = ActOnOpenMPTaskyieldDirective(StartLoc, EndLoc);
2087 assert(ClausesWithImplicit.empty() &&
2088 "No clauses are allowed for 'omp barrier' directive");
2089 assert(AStmt == nullptr &&
2090 "No associated statement allowed for 'omp barrier' directive");
2091 Res = ActOnOpenMPBarrierDirective(StartLoc, EndLoc);
2094 assert(ClausesWithImplicit.empty() &&
2095 "No clauses are allowed for 'omp taskwait' directive");
2096 assert(AStmt == nullptr &&
2097 "No associated statement allowed for 'omp taskwait' directive");
2098 Res = ActOnOpenMPTaskwaitDirective(StartLoc, EndLoc);
2100 case OMPD_taskgroup:
2101 assert(ClausesWithImplicit.empty() &&
2102 "No clauses are allowed for 'omp taskgroup' directive");
2103 Res = ActOnOpenMPTaskgroupDirective(AStmt, StartLoc, EndLoc);
2106 assert(AStmt == nullptr &&
2107 "No associated statement allowed for 'omp flush' directive");
2108 Res = ActOnOpenMPFlushDirective(ClausesWithImplicit, StartLoc, EndLoc);
2111 assert(ClausesWithImplicit.empty() &&
2112 "No clauses are allowed for 'omp ordered' directive");
2113 Res = ActOnOpenMPOrderedDirective(AStmt, StartLoc, EndLoc);
2116 Res = ActOnOpenMPAtomicDirective(ClausesWithImplicit, AStmt, StartLoc,
2121 ActOnOpenMPTeamsDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc);
2124 Res = ActOnOpenMPTargetDirective(ClausesWithImplicit, AStmt, StartLoc,
2127 case OMPD_cancellation_point:
2128 assert(ClausesWithImplicit.empty() &&
2129 "No clauses are allowed for 'omp cancellation point' directive");
2130 assert(AStmt == nullptr && "No associated statement allowed for 'omp "
2131 "cancellation point' directive");
2132 Res = ActOnOpenMPCancellationPointDirective(StartLoc, EndLoc, CancelRegion);
2135 assert(ClausesWithImplicit.empty() &&
2136 "No clauses are allowed for 'omp cancel' directive");
2137 assert(AStmt == nullptr &&
2138 "No associated statement allowed for 'omp cancel' directive");
2139 Res = ActOnOpenMPCancelDirective(StartLoc, EndLoc, CancelRegion);
2141 case OMPD_threadprivate:
2142 llvm_unreachable("OpenMP Directive is not allowed");
2144 llvm_unreachable("Unknown OpenMP directive");
2147 for (auto P : VarsWithInheritedDSA) {
2148 Diag(P.second->getExprLoc(), diag::err_omp_no_dsa_for_variable)
2149 << P.first << P.second->getSourceRange();
2151 if (!VarsWithInheritedDSA.empty())
2159 StmtResult Sema::ActOnOpenMPParallelDirective(ArrayRef<OMPClause *> Clauses,
2161 SourceLocation StartLoc,
2162 SourceLocation EndLoc) {
2163 assert(AStmt && isa<CapturedStmt>(AStmt) && "Captured statement expected");
2164 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
2165 // 1.2.2 OpenMP Language Terminology
2166 // Structured block - An executable statement with a single entry at the
2167 // top and a single exit at the bottom.
2168 // The point of exit cannot be a branch out of the structured block.
2169 // longjmp() and throw() must not violate the entry/exit criteria.
2170 CS->getCapturedDecl()->setNothrow();
2172 getCurFunction()->setHasBranchProtectedScope();
2174 return OMPParallelDirective::Create(Context, StartLoc, EndLoc, Clauses,
2179 /// \brief Helper class for checking canonical form of the OpenMP loops and
2180 /// extracting iteration space of each loop in the loop nest, that will be used
2181 /// for IR generation.
2182 class OpenMPIterationSpaceChecker {
2183 /// \brief Reference to Sema.
2185 /// \brief A location for diagnostics (when there is no some better location).
2186 SourceLocation DefaultLoc;
2187 /// \brief A location for diagnostics (when increment is not compatible).
2188 SourceLocation ConditionLoc;
2189 /// \brief A source location for referring to loop init later.
2190 SourceRange InitSrcRange;
2191 /// \brief A source location for referring to condition later.
2192 SourceRange ConditionSrcRange;
2193 /// \brief A source location for referring to increment later.
2194 SourceRange IncrementSrcRange;
2195 /// \brief Loop variable.
2197 /// \brief Reference to loop variable.
2198 DeclRefExpr *VarRef;
2199 /// \brief Lower bound (initializer for the var).
2201 /// \brief Upper bound.
2203 /// \brief Loop step (increment).
2205 /// \brief This flag is true when condition is one of:
2211 /// \brief This flag is true when condition is strict ( < or > ).
2212 bool TestIsStrictOp;
2213 /// \brief This flag is true when step is subtracted on each iteration.
2217 OpenMPIterationSpaceChecker(Sema &SemaRef, SourceLocation DefaultLoc)
2218 : SemaRef(SemaRef), DefaultLoc(DefaultLoc), ConditionLoc(DefaultLoc),
2219 InitSrcRange(SourceRange()), ConditionSrcRange(SourceRange()),
2220 IncrementSrcRange(SourceRange()), Var(nullptr), VarRef(nullptr),
2221 LB(nullptr), UB(nullptr), Step(nullptr), TestIsLessOp(false),
2222 TestIsStrictOp(false), SubtractStep(false) {}
2223 /// \brief Check init-expr for canonical loop form and save loop counter
2224 /// variable - #Var and its initialization value - #LB.
2225 bool CheckInit(Stmt *S, bool EmitDiags = true);
2226 /// \brief Check test-expr for canonical form, save upper-bound (#UB), flags
2227 /// for less/greater and for strict/non-strict comparison.
2228 bool CheckCond(Expr *S);
2229 /// \brief Check incr-expr for canonical loop form and return true if it
2230 /// does not conform, otherwise save loop step (#Step).
2231 bool CheckInc(Expr *S);
2232 /// \brief Return the loop counter variable.
2233 VarDecl *GetLoopVar() const { return Var; }
2234 /// \brief Return the reference expression to loop counter variable.
2235 DeclRefExpr *GetLoopVarRefExpr() const { return VarRef; }
2236 /// \brief Source range of the loop init.
2237 SourceRange GetInitSrcRange() const { return InitSrcRange; }
2238 /// \brief Source range of the loop condition.
2239 SourceRange GetConditionSrcRange() const { return ConditionSrcRange; }
2240 /// \brief Source range of the loop increment.
2241 SourceRange GetIncrementSrcRange() const { return IncrementSrcRange; }
2242 /// \brief True if the step should be subtracted.
2243 bool ShouldSubtractStep() const { return SubtractStep; }
2244 /// \brief Build the expression to calculate the number of iterations.
2245 Expr *BuildNumIterations(Scope *S, const bool LimitedType) const;
2246 /// \brief Build the precondition expression for the loops.
2247 Expr *BuildPreCond(Scope *S, Expr *Cond) const;
2248 /// \brief Build reference expression to the counter be used for codegen.
2249 Expr *BuildCounterVar() const;
2250 /// \brief Build initization of the counter be used for codegen.
2251 Expr *BuildCounterInit() const;
2252 /// \brief Build step of the counter be used for codegen.
2253 Expr *BuildCounterStep() const;
2254 /// \brief Return true if any expression is dependent.
2255 bool Dependent() const;
2258 /// \brief Check the right-hand side of an assignment in the increment
2260 bool CheckIncRHS(Expr *RHS);
2261 /// \brief Helper to set loop counter variable and its initializer.
2262 bool SetVarAndLB(VarDecl *NewVar, DeclRefExpr *NewVarRefExpr, Expr *NewLB);
2263 /// \brief Helper to set upper bound.
2264 bool SetUB(Expr *NewUB, bool LessOp, bool StrictOp, const SourceRange &SR,
2265 const SourceLocation &SL);
2266 /// \brief Helper to set loop increment.
2267 bool SetStep(Expr *NewStep, bool Subtract);
2270 bool OpenMPIterationSpaceChecker::Dependent() const {
2272 assert(!LB && !UB && !Step);
2275 return Var->getType()->isDependentType() || (LB && LB->isValueDependent()) ||
2276 (UB && UB->isValueDependent()) || (Step && Step->isValueDependent());
2279 template <typename T>
2280 static T *getExprAsWritten(T *E) {
2281 if (auto *ExprTemp = dyn_cast<ExprWithCleanups>(E))
2282 E = ExprTemp->getSubExpr();
2284 if (auto *MTE = dyn_cast<MaterializeTemporaryExpr>(E))
2285 E = MTE->GetTemporaryExpr();
2287 while (auto *Binder = dyn_cast<CXXBindTemporaryExpr>(E))
2288 E = Binder->getSubExpr();
2290 if (auto *ICE = dyn_cast<ImplicitCastExpr>(E))
2291 E = ICE->getSubExprAsWritten();
2292 return E->IgnoreParens();
2295 bool OpenMPIterationSpaceChecker::SetVarAndLB(VarDecl *NewVar,
2296 DeclRefExpr *NewVarRefExpr,
2298 // State consistency checking to ensure correct usage.
2299 assert(Var == nullptr && LB == nullptr && VarRef == nullptr &&
2300 UB == nullptr && Step == nullptr && !TestIsLessOp && !TestIsStrictOp);
2301 if (!NewVar || !NewLB)
2304 VarRef = NewVarRefExpr;
2305 if (auto *CE = dyn_cast_or_null<CXXConstructExpr>(NewLB))
2306 if (const CXXConstructorDecl *Ctor = CE->getConstructor())
2307 if ((Ctor->isCopyOrMoveConstructor() ||
2308 Ctor->isConvertingConstructor(/*AllowExplicit=*/false)) &&
2309 CE->getNumArgs() > 0 && CE->getArg(0) != nullptr)
2310 NewLB = CE->getArg(0)->IgnoreParenImpCasts();
2315 bool OpenMPIterationSpaceChecker::SetUB(Expr *NewUB, bool LessOp, bool StrictOp,
2316 const SourceRange &SR,
2317 const SourceLocation &SL) {
2318 // State consistency checking to ensure correct usage.
2319 assert(Var != nullptr && LB != nullptr && UB == nullptr && Step == nullptr &&
2320 !TestIsLessOp && !TestIsStrictOp);
2324 TestIsLessOp = LessOp;
2325 TestIsStrictOp = StrictOp;
2326 ConditionSrcRange = SR;
2331 bool OpenMPIterationSpaceChecker::SetStep(Expr *NewStep, bool Subtract) {
2332 // State consistency checking to ensure correct usage.
2333 assert(Var != nullptr && LB != nullptr && Step == nullptr);
2336 if (!NewStep->isValueDependent()) {
2337 // Check that the step is integer expression.
2338 SourceLocation StepLoc = NewStep->getLocStart();
2340 SemaRef.PerformOpenMPImplicitIntegerConversion(StepLoc, NewStep);
2341 if (Val.isInvalid())
2343 NewStep = Val.get();
2345 // OpenMP [2.6, Canonical Loop Form, Restrictions]
2346 // If test-expr is of form var relational-op b and relational-op is < or
2347 // <= then incr-expr must cause var to increase on each iteration of the
2348 // loop. If test-expr is of form var relational-op b and relational-op is
2349 // > or >= then incr-expr must cause var to decrease on each iteration of
2351 // If test-expr is of form b relational-op var and relational-op is < or
2352 // <= then incr-expr must cause var to decrease on each iteration of the
2353 // loop. If test-expr is of form b relational-op var and relational-op is
2354 // > or >= then incr-expr must cause var to increase on each iteration of
2356 llvm::APSInt Result;
2357 bool IsConstant = NewStep->isIntegerConstantExpr(Result, SemaRef.Context);
2358 bool IsUnsigned = !NewStep->getType()->hasSignedIntegerRepresentation();
2360 IsConstant && Result.isSigned() && (Subtract != Result.isNegative());
2362 IsConstant && Result.isSigned() && (Subtract == Result.isNegative());
2363 bool IsConstZero = IsConstant && !Result.getBoolValue();
2364 if (UB && (IsConstZero ||
2365 (TestIsLessOp ? (IsConstNeg || (IsUnsigned && Subtract))
2366 : (IsConstPos || (IsUnsigned && !Subtract))))) {
2367 SemaRef.Diag(NewStep->getExprLoc(),
2368 diag::err_omp_loop_incr_not_compatible)
2369 << Var << TestIsLessOp << NewStep->getSourceRange();
2370 SemaRef.Diag(ConditionLoc,
2371 diag::note_omp_loop_cond_requres_compatible_incr)
2372 << TestIsLessOp << ConditionSrcRange;
2375 if (TestIsLessOp == Subtract) {
2376 NewStep = SemaRef.CreateBuiltinUnaryOp(NewStep->getExprLoc(), UO_Minus,
2378 Subtract = !Subtract;
2383 SubtractStep = Subtract;
2387 bool OpenMPIterationSpaceChecker::CheckInit(Stmt *S, bool EmitDiags) {
2388 // Check init-expr for canonical loop form and save loop counter
2389 // variable - #Var and its initialization value - #LB.
2390 // OpenMP [2.6] Canonical loop form. init-expr may be one of the following:
2392 // integer-type var = lb
2393 // random-access-iterator-type var = lb
2394 // pointer-type var = lb
2398 SemaRef.Diag(DefaultLoc, diag::err_omp_loop_not_canonical_init);
2402 InitSrcRange = S->getSourceRange();
2403 if (Expr *E = dyn_cast<Expr>(S))
2404 S = E->IgnoreParens();
2405 if (auto BO = dyn_cast<BinaryOperator>(S)) {
2406 if (BO->getOpcode() == BO_Assign)
2407 if (auto DRE = dyn_cast<DeclRefExpr>(BO->getLHS()->IgnoreParens()))
2408 return SetVarAndLB(dyn_cast<VarDecl>(DRE->getDecl()), DRE,
2410 } else if (auto DS = dyn_cast<DeclStmt>(S)) {
2411 if (DS->isSingleDecl()) {
2412 if (auto Var = dyn_cast_or_null<VarDecl>(DS->getSingleDecl())) {
2413 if (Var->hasInit()) {
2414 // Accept non-canonical init form here but emit ext. warning.
2415 if (Var->getInitStyle() != VarDecl::CInit && EmitDiags)
2416 SemaRef.Diag(S->getLocStart(),
2417 diag::ext_omp_loop_not_canonical_init)
2418 << S->getSourceRange();
2419 return SetVarAndLB(Var, nullptr, Var->getInit());
2423 } else if (auto CE = dyn_cast<CXXOperatorCallExpr>(S))
2424 if (CE->getOperator() == OO_Equal)
2425 if (auto DRE = dyn_cast<DeclRefExpr>(CE->getArg(0)))
2426 return SetVarAndLB(dyn_cast<VarDecl>(DRE->getDecl()), DRE,
2430 SemaRef.Diag(S->getLocStart(), diag::err_omp_loop_not_canonical_init)
2431 << S->getSourceRange();
2436 /// \brief Ignore parenthesizes, implicit casts, copy constructor and return the
2437 /// variable (which may be the loop variable) if possible.
2438 static const VarDecl *GetInitVarDecl(const Expr *E) {
2441 E = getExprAsWritten(E);
2442 if (auto *CE = dyn_cast_or_null<CXXConstructExpr>(E))
2443 if (const CXXConstructorDecl *Ctor = CE->getConstructor())
2444 if ((Ctor->isCopyOrMoveConstructor() ||
2445 Ctor->isConvertingConstructor(/*AllowExplicit=*/false)) &&
2446 CE->getNumArgs() > 0 && CE->getArg(0) != nullptr)
2447 E = CE->getArg(0)->IgnoreParenImpCasts();
2448 auto DRE = dyn_cast_or_null<DeclRefExpr>(E);
2451 return dyn_cast<VarDecl>(DRE->getDecl());
2454 bool OpenMPIterationSpaceChecker::CheckCond(Expr *S) {
2455 // Check test-expr for canonical form, save upper-bound UB, flags for
2456 // less/greater and for strict/non-strict comparison.
2457 // OpenMP [2.6] Canonical loop form. Test-expr may be one of the following:
2458 // var relational-op b
2459 // b relational-op var
2462 SemaRef.Diag(DefaultLoc, diag::err_omp_loop_not_canonical_cond) << Var;
2465 S = getExprAsWritten(S);
2466 SourceLocation CondLoc = S->getLocStart();
2467 if (auto BO = dyn_cast<BinaryOperator>(S)) {
2468 if (BO->isRelationalOp()) {
2469 if (GetInitVarDecl(BO->getLHS()) == Var)
2470 return SetUB(BO->getRHS(),
2471 (BO->getOpcode() == BO_LT || BO->getOpcode() == BO_LE),
2472 (BO->getOpcode() == BO_LT || BO->getOpcode() == BO_GT),
2473 BO->getSourceRange(), BO->getOperatorLoc());
2474 if (GetInitVarDecl(BO->getRHS()) == Var)
2475 return SetUB(BO->getLHS(),
2476 (BO->getOpcode() == BO_GT || BO->getOpcode() == BO_GE),
2477 (BO->getOpcode() == BO_LT || BO->getOpcode() == BO_GT),
2478 BO->getSourceRange(), BO->getOperatorLoc());
2480 } else if (auto CE = dyn_cast<CXXOperatorCallExpr>(S)) {
2481 if (CE->getNumArgs() == 2) {
2482 auto Op = CE->getOperator();
2485 case OO_GreaterEqual:
2488 if (GetInitVarDecl(CE->getArg(0)) == Var)
2489 return SetUB(CE->getArg(1), Op == OO_Less || Op == OO_LessEqual,
2490 Op == OO_Less || Op == OO_Greater, CE->getSourceRange(),
2491 CE->getOperatorLoc());
2492 if (GetInitVarDecl(CE->getArg(1)) == Var)
2493 return SetUB(CE->getArg(0), Op == OO_Greater || Op == OO_GreaterEqual,
2494 Op == OO_Less || Op == OO_Greater, CE->getSourceRange(),
2495 CE->getOperatorLoc());
2502 SemaRef.Diag(CondLoc, diag::err_omp_loop_not_canonical_cond)
2503 << S->getSourceRange() << Var;
2507 bool OpenMPIterationSpaceChecker::CheckIncRHS(Expr *RHS) {
2508 // RHS of canonical loop form increment can be:
2513 RHS = RHS->IgnoreParenImpCasts();
2514 if (auto BO = dyn_cast<BinaryOperator>(RHS)) {
2515 if (BO->isAdditiveOp()) {
2516 bool IsAdd = BO->getOpcode() == BO_Add;
2517 if (GetInitVarDecl(BO->getLHS()) == Var)
2518 return SetStep(BO->getRHS(), !IsAdd);
2519 if (IsAdd && GetInitVarDecl(BO->getRHS()) == Var)
2520 return SetStep(BO->getLHS(), false);
2522 } else if (auto CE = dyn_cast<CXXOperatorCallExpr>(RHS)) {
2523 bool IsAdd = CE->getOperator() == OO_Plus;
2524 if ((IsAdd || CE->getOperator() == OO_Minus) && CE->getNumArgs() == 2) {
2525 if (GetInitVarDecl(CE->getArg(0)) == Var)
2526 return SetStep(CE->getArg(1), !IsAdd);
2527 if (IsAdd && GetInitVarDecl(CE->getArg(1)) == Var)
2528 return SetStep(CE->getArg(0), false);
2531 SemaRef.Diag(RHS->getLocStart(), diag::err_omp_loop_not_canonical_incr)
2532 << RHS->getSourceRange() << Var;
2536 bool OpenMPIterationSpaceChecker::CheckInc(Expr *S) {
2537 // Check incr-expr for canonical loop form and return true if it
2538 // does not conform.
2539 // OpenMP [2.6] Canonical loop form. Test-expr may be one of the following:
2551 SemaRef.Diag(DefaultLoc, diag::err_omp_loop_not_canonical_incr) << Var;
2554 IncrementSrcRange = S->getSourceRange();
2555 S = S->IgnoreParens();
2556 if (auto UO = dyn_cast<UnaryOperator>(S)) {
2557 if (UO->isIncrementDecrementOp() && GetInitVarDecl(UO->getSubExpr()) == Var)
2559 SemaRef.ActOnIntegerConstant(UO->getLocStart(),
2560 (UO->isDecrementOp() ? -1 : 1)).get(),
2562 } else if (auto BO = dyn_cast<BinaryOperator>(S)) {
2563 switch (BO->getOpcode()) {
2566 if (GetInitVarDecl(BO->getLHS()) == Var)
2567 return SetStep(BO->getRHS(), BO->getOpcode() == BO_SubAssign);
2570 if (GetInitVarDecl(BO->getLHS()) == Var)
2571 return CheckIncRHS(BO->getRHS());
2576 } else if (auto CE = dyn_cast<CXXOperatorCallExpr>(S)) {
2577 switch (CE->getOperator()) {
2580 if (GetInitVarDecl(CE->getArg(0)) == Var)
2582 SemaRef.ActOnIntegerConstant(
2584 ((CE->getOperator() == OO_MinusMinus) ? -1 : 1)).get(),
2589 if (GetInitVarDecl(CE->getArg(0)) == Var)
2590 return SetStep(CE->getArg(1), CE->getOperator() == OO_MinusEqual);
2593 if (GetInitVarDecl(CE->getArg(0)) == Var)
2594 return CheckIncRHS(CE->getArg(1));
2600 SemaRef.Diag(S->getLocStart(), diag::err_omp_loop_not_canonical_incr)
2601 << S->getSourceRange() << Var;
2606 // Transform variables declared in GNU statement expressions to new ones to
2607 // avoid crash on codegen.
2608 class TransformToNewDefs : public TreeTransform<TransformToNewDefs> {
2609 typedef TreeTransform<TransformToNewDefs> BaseTransform;
2612 TransformToNewDefs(Sema &SemaRef) : BaseTransform(SemaRef) {}
2614 Decl *TransformDefinition(SourceLocation Loc, Decl *D) {
2615 if (auto *VD = cast<VarDecl>(D))
2616 if (!isa<ParmVarDecl>(D) && !isa<VarTemplateSpecializationDecl>(D) &&
2617 !isa<ImplicitParamDecl>(D)) {
2618 auto *NewVD = VarDecl::Create(
2619 SemaRef.Context, VD->getDeclContext(), VD->getLocStart(),
2620 VD->getLocation(), VD->getIdentifier(), VD->getType(),
2621 VD->getTypeSourceInfo(), VD->getStorageClass());
2622 NewVD->setTSCSpec(VD->getTSCSpec());
2623 NewVD->setInit(VD->getInit());
2624 NewVD->setInitStyle(VD->getInitStyle());
2625 NewVD->setExceptionVariable(VD->isExceptionVariable());
2626 NewVD->setNRVOVariable(VD->isNRVOVariable());
2627 NewVD->setCXXForRangeDecl(VD->isInExternCXXContext());
2628 NewVD->setConstexpr(VD->isConstexpr());
2629 NewVD->setInitCapture(VD->isInitCapture());
2630 NewVD->setPreviousDeclInSameBlockScope(
2631 VD->isPreviousDeclInSameBlockScope());
2632 VD->getDeclContext()->addHiddenDecl(NewVD);
2633 transformedLocalDecl(VD, NewVD);
2636 return BaseTransform::TransformDefinition(Loc, D);
2639 ExprResult TransformDeclRefExpr(DeclRefExpr *E) {
2640 if (auto *NewD = TransformDecl(E->getExprLoc(), E->getDecl()))
2641 if (E->getDecl() != NewD) {
2642 NewD->setReferenced();
2643 NewD->markUsed(SemaRef.Context);
2644 return DeclRefExpr::Create(
2645 SemaRef.Context, E->getQualifierLoc(), E->getTemplateKeywordLoc(),
2646 cast<ValueDecl>(NewD), E->refersToEnclosingVariableOrCapture(),
2647 E->getNameInfo(), E->getType(), E->getValueKind());
2649 return BaseTransform::TransformDeclRefExpr(E);
2654 /// \brief Build the expression to calculate the number of iterations.
2656 OpenMPIterationSpaceChecker::BuildNumIterations(Scope *S,
2657 const bool LimitedType) const {
2658 TransformToNewDefs Transform(SemaRef);
2660 auto VarType = Var->getType().getNonReferenceType();
2661 if (VarType->isIntegerType() || VarType->isPointerType() ||
2662 SemaRef.getLangOpts().CPlusPlus) {
2664 auto *UBExpr = TestIsLessOp ? UB : LB;
2665 auto *LBExpr = TestIsLessOp ? LB : UB;
2666 Expr *Upper = Transform.TransformExpr(UBExpr).get();
2667 Expr *Lower = Transform.TransformExpr(LBExpr).get();
2668 if (!Upper || !Lower)
2670 Upper = SemaRef.PerformImplicitConversion(Upper, UBExpr->getType(),
2671 Sema::AA_Converting,
2672 /*AllowExplicit=*/true)
2674 Lower = SemaRef.PerformImplicitConversion(Lower, LBExpr->getType(),
2675 Sema::AA_Converting,
2676 /*AllowExplicit=*/true)
2678 if (!Upper || !Lower)
2681 Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Sub, Upper, Lower);
2683 if (!Diff.isUsable() && VarType->getAsCXXRecordDecl()) {
2684 // BuildBinOp already emitted error, this one is to point user to upper
2685 // and lower bound, and to tell what is passed to 'operator-'.
2686 SemaRef.Diag(Upper->getLocStart(), diag::err_omp_loop_diff_cxx)
2687 << Upper->getSourceRange() << Lower->getSourceRange();
2692 if (!Diff.isUsable())
2695 // Upper - Lower [- 1]
2697 Diff = SemaRef.BuildBinOp(
2698 S, DefaultLoc, BO_Sub, Diff.get(),
2699 SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get());
2700 if (!Diff.isUsable())
2703 // Upper - Lower [- 1] + Step
2704 auto NewStep = Transform.TransformExpr(Step->IgnoreImplicit());
2705 if (NewStep.isInvalid())
2707 NewStep = SemaRef.PerformImplicitConversion(
2708 NewStep.get(), Step->IgnoreImplicit()->getType(), Sema::AA_Converting,
2709 /*AllowExplicit=*/true);
2710 if (NewStep.isInvalid())
2712 Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Add, Diff.get(), NewStep.get());
2713 if (!Diff.isUsable())
2716 // Parentheses (for dumping/debugging purposes only).
2717 Diff = SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, Diff.get());
2718 if (!Diff.isUsable())
2721 // (Upper - Lower [- 1] + Step) / Step
2722 NewStep = Transform.TransformExpr(Step->IgnoreImplicit());
2723 if (NewStep.isInvalid())
2725 NewStep = SemaRef.PerformImplicitConversion(
2726 NewStep.get(), Step->IgnoreImplicit()->getType(), Sema::AA_Converting,
2727 /*AllowExplicit=*/true);
2728 if (NewStep.isInvalid())
2730 Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Div, Diff.get(), NewStep.get());
2731 if (!Diff.isUsable())
2734 // OpenMP runtime requires 32-bit or 64-bit loop variables.
2735 QualType Type = Diff.get()->getType();
2736 auto &C = SemaRef.Context;
2737 bool UseVarType = VarType->hasIntegerRepresentation() &&
2738 C.getTypeSize(Type) > C.getTypeSize(VarType);
2739 if (!Type->isIntegerType() || UseVarType) {
2741 UseVarType ? C.getTypeSize(VarType) : C.getTypeSize(Type);
2742 bool IsSigned = UseVarType ? VarType->hasSignedIntegerRepresentation()
2743 : Type->hasSignedIntegerRepresentation();
2744 Type = C.getIntTypeForBitwidth(NewSize, IsSigned);
2745 Diff = SemaRef.PerformImplicitConversion(
2746 Diff.get(), Type, Sema::AA_Converting, /*AllowExplicit=*/true);
2747 if (!Diff.isUsable())
2751 unsigned NewSize = (C.getTypeSize(Type) > 32) ? 64 : 32;
2752 if (NewSize != C.getTypeSize(Type)) {
2753 if (NewSize < C.getTypeSize(Type)) {
2754 assert(NewSize == 64 && "incorrect loop var size");
2755 SemaRef.Diag(DefaultLoc, diag::warn_omp_loop_64_bit_var)
2756 << InitSrcRange << ConditionSrcRange;
2758 QualType NewType = C.getIntTypeForBitwidth(
2759 NewSize, Type->hasSignedIntegerRepresentation() ||
2760 C.getTypeSize(Type) < NewSize);
2761 Diff = SemaRef.PerformImplicitConversion(Diff.get(), NewType,
2762 Sema::AA_Converting, true);
2763 if (!Diff.isUsable())
2771 Expr *OpenMPIterationSpaceChecker::BuildPreCond(Scope *S, Expr *Cond) const {
2772 // Try to build LB <op> UB, where <op> is <, >, <=, or >=.
2773 bool Suppress = SemaRef.getDiagnostics().getSuppressAllDiagnostics();
2774 SemaRef.getDiagnostics().setSuppressAllDiagnostics(/*Val=*/true);
2775 TransformToNewDefs Transform(SemaRef);
2777 auto NewLB = Transform.TransformExpr(LB);
2778 auto NewUB = Transform.TransformExpr(UB);
2779 if (NewLB.isInvalid() || NewUB.isInvalid())
2781 NewLB = SemaRef.PerformImplicitConversion(NewLB.get(), LB->getType(),
2782 Sema::AA_Converting,
2783 /*AllowExplicit=*/true);
2784 NewUB = SemaRef.PerformImplicitConversion(NewUB.get(), UB->getType(),
2785 Sema::AA_Converting,
2786 /*AllowExplicit=*/true);
2787 if (NewLB.isInvalid() || NewUB.isInvalid())
2789 auto CondExpr = SemaRef.BuildBinOp(
2790 S, DefaultLoc, TestIsLessOp ? (TestIsStrictOp ? BO_LT : BO_LE)
2791 : (TestIsStrictOp ? BO_GT : BO_GE),
2792 NewLB.get(), NewUB.get());
2793 if (CondExpr.isUsable()) {
2794 CondExpr = SemaRef.PerformImplicitConversion(
2795 CondExpr.get(), SemaRef.Context.BoolTy, /*Action=*/Sema::AA_Casting,
2796 /*AllowExplicit=*/true);
2798 SemaRef.getDiagnostics().setSuppressAllDiagnostics(Suppress);
2799 // Otherwise use original loop conditon and evaluate it in runtime.
2800 return CondExpr.isUsable() ? CondExpr.get() : Cond;
2803 /// \brief Build reference expression to the counter be used for codegen.
2804 Expr *OpenMPIterationSpaceChecker::BuildCounterVar() const {
2805 return buildDeclRefExpr(SemaRef, Var, Var->getType(), DefaultLoc);
2808 /// \brief Build initization of the counter be used for codegen.
2809 Expr *OpenMPIterationSpaceChecker::BuildCounterInit() const { return LB; }
2811 /// \brief Build step of the counter be used for codegen.
2812 Expr *OpenMPIterationSpaceChecker::BuildCounterStep() const { return Step; }
2814 /// \brief Iteration space of a single for loop.
2815 struct LoopIterationSpace {
2816 /// \brief Condition of the loop.
2818 /// \brief This expression calculates the number of iterations in the loop.
2819 /// It is always possible to calculate it before starting the loop.
2820 Expr *NumIterations;
2821 /// \brief The loop counter variable.
2823 /// \brief This is initializer for the initial value of #CounterVar.
2825 /// \brief This is step for the #CounterVar used to generate its update:
2826 /// #CounterVar = #CounterInit + #CounterStep * CurrentIteration.
2828 /// \brief Should step be subtracted?
2830 /// \brief Source range of the loop init.
2831 SourceRange InitSrcRange;
2832 /// \brief Source range of the loop condition.
2833 SourceRange CondSrcRange;
2834 /// \brief Source range of the loop increment.
2835 SourceRange IncSrcRange;
2840 void Sema::ActOnOpenMPLoopInitialization(SourceLocation ForLoc, Stmt *Init) {
2841 assert(getLangOpts().OpenMP && "OpenMP is not active.");
2842 assert(Init && "Expected loop in canonical form.");
2843 unsigned CollapseIteration = DSAStack->getCollapseNumber();
2844 if (CollapseIteration > 0 &&
2845 isOpenMPLoopDirective(DSAStack->getCurrentDirective())) {
2846 OpenMPIterationSpaceChecker ISC(*this, ForLoc);
2847 if (!ISC.CheckInit(Init, /*EmitDiags=*/false)) {
2848 DSAStack->addLoopControlVariable(ISC.GetLoopVar());
2850 DSAStack->setCollapseNumber(CollapseIteration - 1);
2854 /// \brief Called on a for stmt to check and extract its iteration space
2855 /// for further processing (such as collapsing).
2856 static bool CheckOpenMPIterationSpace(
2857 OpenMPDirectiveKind DKind, Stmt *S, Sema &SemaRef, DSAStackTy &DSA,
2858 unsigned CurrentNestedLoopCount, unsigned NestedLoopCount,
2859 Expr *NestedLoopCountExpr,
2860 llvm::DenseMap<VarDecl *, Expr *> &VarsWithImplicitDSA,
2861 LoopIterationSpace &ResultIterSpace) {
2862 // OpenMP [2.6, Canonical Loop Form]
2863 // for (init-expr; test-expr; incr-expr) structured-block
2864 auto For = dyn_cast_or_null<ForStmt>(S);
2866 SemaRef.Diag(S->getLocStart(), diag::err_omp_not_for)
2867 << (NestedLoopCountExpr != nullptr) << getOpenMPDirectiveName(DKind)
2868 << NestedLoopCount << (CurrentNestedLoopCount > 0)
2869 << CurrentNestedLoopCount;
2870 if (NestedLoopCount > 1)
2871 SemaRef.Diag(NestedLoopCountExpr->getExprLoc(),
2872 diag::note_omp_collapse_expr)
2873 << NestedLoopCountExpr->getSourceRange();
2876 assert(For->getBody());
2878 OpenMPIterationSpaceChecker ISC(SemaRef, For->getForLoc());
2881 auto Init = For->getInit();
2882 if (ISC.CheckInit(Init)) {
2886 bool HasErrors = false;
2888 // Check loop variable's type.
2889 auto Var = ISC.GetLoopVar();
2891 // OpenMP [2.6, Canonical Loop Form]
2892 // Var is one of the following:
2893 // A variable of signed or unsigned integer type.
2894 // For C++, a variable of a random access iterator type.
2895 // For C, a variable of a pointer type.
2896 auto VarType = Var->getType();
2897 if (!VarType->isDependentType() && !VarType->isIntegerType() &&
2898 !VarType->isPointerType() &&
2899 !(SemaRef.getLangOpts().CPlusPlus && VarType->isOverloadableType())) {
2900 SemaRef.Diag(Init->getLocStart(), diag::err_omp_loop_variable_type)
2901 << SemaRef.getLangOpts().CPlusPlus;
2905 // OpenMP, 2.14.1.1 Data-sharing Attribute Rules for Variables Referenced in a
2907 // The loop iteration variable(s) in the associated for-loop(s) of a for or
2908 // parallel for construct is (are) private.
2909 // The loop iteration variable in the associated for-loop of a simd construct
2910 // with just one associated for-loop is linear with a constant-linear-step
2911 // that is the increment of the associated for-loop.
2912 // Exclude loop var from the list of variables with implicitly defined data
2913 // sharing attributes.
2914 VarsWithImplicitDSA.erase(Var);
2916 // OpenMP [2.14.1.1, Data-sharing Attribute Rules for Variables Referenced in
2917 // a Construct, C/C++].
2918 // The loop iteration variable in the associated for-loop of a simd construct
2919 // with just one associated for-loop may be listed in a linear clause with a
2920 // constant-linear-step that is the increment of the associated for-loop.
2921 // The loop iteration variable(s) in the associated for-loop(s) of a for or
2922 // parallel for construct may be listed in a private or lastprivate clause.
2923 DSAStackTy::DSAVarData DVar = DSA.getTopDSA(Var, false);
2924 auto LoopVarRefExpr = ISC.GetLoopVarRefExpr();
2925 // If LoopVarRefExpr is nullptr it means the corresponding loop variable is
2926 // declared in the loop and it is predetermined as a private.
2927 auto PredeterminedCKind =
2928 isOpenMPSimdDirective(DKind)
2929 ? ((NestedLoopCount == 1) ? OMPC_linear : OMPC_lastprivate)
2931 if (((isOpenMPSimdDirective(DKind) && DVar.CKind != OMPC_unknown &&
2932 DVar.CKind != OMPC_threadprivate && DVar.CKind != PredeterminedCKind) ||
2933 (isOpenMPWorksharingDirective(DKind) && !isOpenMPSimdDirective(DKind) &&
2934 DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_private &&
2935 DVar.CKind != OMPC_lastprivate && DVar.CKind != OMPC_threadprivate)) &&
2936 ((DVar.CKind != OMPC_private && DVar.CKind != OMPC_threadprivate) ||
2937 DVar.RefExpr != nullptr)) {
2938 SemaRef.Diag(Init->getLocStart(), diag::err_omp_loop_var_dsa)
2939 << getOpenMPClauseName(DVar.CKind) << getOpenMPDirectiveName(DKind)
2940 << getOpenMPClauseName(PredeterminedCKind);
2941 if (DVar.RefExpr == nullptr)
2942 DVar.CKind = PredeterminedCKind;
2943 ReportOriginalDSA(SemaRef, &DSA, Var, DVar, /*IsLoopIterVar=*/true);
2945 } else if (LoopVarRefExpr != nullptr) {
2946 // Make the loop iteration variable private (for worksharing constructs),
2947 // linear (for simd directives with the only one associated loop) or
2948 // lastprivate (for simd directives with several collapsed loops).
2949 if (DVar.CKind == OMPC_unknown)
2950 DVar = DSA.hasDSA(Var, isOpenMPPrivate, MatchesAlways(),
2951 /*FromParent=*/false);
2952 DSA.addDSA(Var, LoopVarRefExpr, PredeterminedCKind);
2955 assert(isOpenMPLoopDirective(DKind) && "DSA for non-loop vars");
2958 HasErrors |= ISC.CheckCond(For->getCond());
2961 HasErrors |= ISC.CheckInc(For->getInc());
2963 if (ISC.Dependent() || SemaRef.CurContext->isDependentContext() || HasErrors)
2966 // Build the loop's iteration space representation.
2967 ResultIterSpace.PreCond = ISC.BuildPreCond(DSA.getCurScope(), For->getCond());
2968 ResultIterSpace.NumIterations = ISC.BuildNumIterations(
2969 DSA.getCurScope(), /* LimitedType */ isOpenMPWorksharingDirective(DKind));
2970 ResultIterSpace.CounterVar = ISC.BuildCounterVar();
2971 ResultIterSpace.CounterInit = ISC.BuildCounterInit();
2972 ResultIterSpace.CounterStep = ISC.BuildCounterStep();
2973 ResultIterSpace.InitSrcRange = ISC.GetInitSrcRange();
2974 ResultIterSpace.CondSrcRange = ISC.GetConditionSrcRange();
2975 ResultIterSpace.IncSrcRange = ISC.GetIncrementSrcRange();
2976 ResultIterSpace.Subtract = ISC.ShouldSubtractStep();
2978 HasErrors |= (ResultIterSpace.PreCond == nullptr ||
2979 ResultIterSpace.NumIterations == nullptr ||
2980 ResultIterSpace.CounterVar == nullptr ||
2981 ResultIterSpace.CounterInit == nullptr ||
2982 ResultIterSpace.CounterStep == nullptr);
2987 /// \brief Build 'VarRef = Start.
2988 static ExprResult BuildCounterInit(Sema &SemaRef, Scope *S, SourceLocation Loc,
2989 ExprResult VarRef, ExprResult Start) {
2990 TransformToNewDefs Transform(SemaRef);
2991 // Build 'VarRef = Start.
2992 auto NewStart = Transform.TransformExpr(Start.get()->IgnoreImplicit());
2993 if (NewStart.isInvalid())
2995 NewStart = SemaRef.PerformImplicitConversion(
2996 NewStart.get(), Start.get()->IgnoreImplicit()->getType(),
2997 Sema::AA_Converting,
2998 /*AllowExplicit=*/true);
2999 if (NewStart.isInvalid())
3001 NewStart = SemaRef.PerformImplicitConversion(
3002 NewStart.get(), VarRef.get()->getType(), Sema::AA_Converting,
3003 /*AllowExplicit=*/true);
3004 if (!NewStart.isUsable())
3008 SemaRef.BuildBinOp(S, Loc, BO_Assign, VarRef.get(), NewStart.get());
3012 /// \brief Build 'VarRef = Start + Iter * Step'.
3013 static ExprResult BuildCounterUpdate(Sema &SemaRef, Scope *S,
3014 SourceLocation Loc, ExprResult VarRef,
3015 ExprResult Start, ExprResult Iter,
3016 ExprResult Step, bool Subtract) {
3017 // Add parentheses (for debugging purposes only).
3018 Iter = SemaRef.ActOnParenExpr(Loc, Loc, Iter.get());
3019 if (!VarRef.isUsable() || !Start.isUsable() || !Iter.isUsable() ||
3023 TransformToNewDefs Transform(SemaRef);
3024 auto NewStep = Transform.TransformExpr(Step.get()->IgnoreImplicit());
3025 if (NewStep.isInvalid())
3027 NewStep = SemaRef.PerformImplicitConversion(
3028 NewStep.get(), Step.get()->IgnoreImplicit()->getType(),
3029 Sema::AA_Converting,
3030 /*AllowExplicit=*/true);
3031 if (NewStep.isInvalid())
3034 SemaRef.BuildBinOp(S, Loc, BO_Mul, Iter.get(), NewStep.get());
3035 if (!Update.isUsable())
3038 // Build 'VarRef = Start + Iter * Step'.
3039 auto NewStart = Transform.TransformExpr(Start.get()->IgnoreImplicit());
3040 if (NewStart.isInvalid())
3042 NewStart = SemaRef.PerformImplicitConversion(
3043 NewStart.get(), Start.get()->IgnoreImplicit()->getType(),
3044 Sema::AA_Converting,
3045 /*AllowExplicit=*/true);
3046 if (NewStart.isInvalid())
3048 Update = SemaRef.BuildBinOp(S, Loc, (Subtract ? BO_Sub : BO_Add),
3049 NewStart.get(), Update.get());
3050 if (!Update.isUsable())
3053 Update = SemaRef.PerformImplicitConversion(
3054 Update.get(), VarRef.get()->getType(), Sema::AA_Converting, true);
3055 if (!Update.isUsable())
3058 Update = SemaRef.BuildBinOp(S, Loc, BO_Assign, VarRef.get(), Update.get());
3062 /// \brief Convert integer expression \a E to make it have at least \a Bits
3064 static ExprResult WidenIterationCount(unsigned Bits, Expr *E,
3068 auto &C = SemaRef.Context;
3069 QualType OldType = E->getType();
3070 unsigned HasBits = C.getTypeSize(OldType);
3071 if (HasBits >= Bits)
3072 return ExprResult(E);
3073 // OK to convert to signed, because new type has more bits than old.
3074 QualType NewType = C.getIntTypeForBitwidth(Bits, /* Signed */ true);
3075 return SemaRef.PerformImplicitConversion(E, NewType, Sema::AA_Converting,
3079 /// \brief Check if the given expression \a E is a constant integer that fits
3080 /// into \a Bits bits.
3081 static bool FitsInto(unsigned Bits, bool Signed, Expr *E, Sema &SemaRef) {
3084 llvm::APSInt Result;
3085 if (E->isIntegerConstantExpr(Result, SemaRef.Context))
3086 return Signed ? Result.isSignedIntN(Bits) : Result.isIntN(Bits);
3090 /// \brief Called on a for stmt to check itself and nested loops (if any).
3091 /// \return Returns 0 if one of the collapsed stmts is not canonical for loop,
3092 /// number of collapsed loops otherwise.
3094 CheckOpenMPLoop(OpenMPDirectiveKind DKind, Expr *NestedLoopCountExpr,
3095 Stmt *AStmt, Sema &SemaRef, DSAStackTy &DSA,
3096 llvm::DenseMap<VarDecl *, Expr *> &VarsWithImplicitDSA,
3097 OMPLoopDirective::HelperExprs &Built) {
3098 unsigned NestedLoopCount = 1;
3099 if (NestedLoopCountExpr) {
3100 // Found 'collapse' clause - calculate collapse number.
3101 llvm::APSInt Result;
3102 if (NestedLoopCountExpr->EvaluateAsInt(Result, SemaRef.getASTContext()))
3103 NestedLoopCount = Result.getLimitedValue();
3105 // This is helper routine for loop directives (e.g., 'for', 'simd',
3106 // 'for simd', etc.).
3107 SmallVector<LoopIterationSpace, 4> IterSpaces;
3108 IterSpaces.resize(NestedLoopCount);
3109 Stmt *CurStmt = AStmt->IgnoreContainers(/* IgnoreCaptured */ true);
3110 for (unsigned Cnt = 0; Cnt < NestedLoopCount; ++Cnt) {
3111 if (CheckOpenMPIterationSpace(DKind, CurStmt, SemaRef, DSA, Cnt,
3112 NestedLoopCount, NestedLoopCountExpr,
3113 VarsWithImplicitDSA, IterSpaces[Cnt]))
3115 // Move on to the next nested for loop, or to the loop body.
3116 // OpenMP [2.8.1, simd construct, Restrictions]
3117 // All loops associated with the construct must be perfectly nested; that
3118 // is, there must be no intervening code nor any OpenMP directive between
3120 CurStmt = cast<ForStmt>(CurStmt)->getBody()->IgnoreContainers();
3123 Built.clear(/* size */ NestedLoopCount);
3125 if (SemaRef.CurContext->isDependentContext())
3126 return NestedLoopCount;
3128 // An example of what is generated for the following code:
3130 // #pragma omp simd collapse(2)
3131 // for (i = 0; i < NI; ++i)
3132 // for (j = J0; j < NJ; j+=2) {
3136 // We generate the code below.
3137 // Note: the loop body may be outlined in CodeGen.
3138 // Note: some counters may be C++ classes, operator- is used to find number of
3139 // iterations and operator+= to calculate counter value.
3140 // Note: decltype(NumIterations) must be integer type (in 'omp for', only i32
3141 // or i64 is currently supported).
3143 // #define NumIterations (NI * ((NJ - J0 - 1 + 2) / 2))
3144 // for (int[32|64]_t IV = 0; IV < NumIterations; ++IV ) {
3145 // .local.i = IV / ((NJ - J0 - 1 + 2) / 2);
3146 // .local.j = J0 + (IV % ((NJ - J0 - 1 + 2) / 2)) * 2;
3147 // // similar updates for vars in clauses (e.g. 'linear')
3148 // <loop body (using local i and j)>
3150 // i = NI; // assign final values of counters
3154 // Last iteration number is (I1 * I2 * ... In) - 1, where I1, I2 ... In are
3155 // the iteration counts of the collapsed for loops.
3156 // Precondition tests if there is at least one iteration (all conditions are
3158 auto PreCond = ExprResult(IterSpaces[0].PreCond);
3159 auto N0 = IterSpaces[0].NumIterations;
3160 ExprResult LastIteration32 = WidenIterationCount(
3161 32 /* Bits */, SemaRef.PerformImplicitConversion(
3162 N0->IgnoreImpCasts(), N0->getType(),
3163 Sema::AA_Converting, /*AllowExplicit=*/true)
3166 ExprResult LastIteration64 = WidenIterationCount(
3167 64 /* Bits */, SemaRef.PerformImplicitConversion(
3168 N0->IgnoreImpCasts(), N0->getType(),
3169 Sema::AA_Converting, /*AllowExplicit=*/true)
3173 if (!LastIteration32.isUsable() || !LastIteration64.isUsable())
3174 return NestedLoopCount;
3176 auto &C = SemaRef.Context;
3177 bool AllCountsNeedLessThan32Bits = C.getTypeSize(N0->getType()) < 32;
3179 Scope *CurScope = DSA.getCurScope();
3180 for (unsigned Cnt = 1; Cnt < NestedLoopCount; ++Cnt) {
3181 if (PreCond.isUsable()) {
3182 PreCond = SemaRef.BuildBinOp(CurScope, SourceLocation(), BO_LAnd,
3183 PreCond.get(), IterSpaces[Cnt].PreCond);
3185 auto N = IterSpaces[Cnt].NumIterations;
3186 AllCountsNeedLessThan32Bits &= C.getTypeSize(N->getType()) < 32;
3187 if (LastIteration32.isUsable())
3188 LastIteration32 = SemaRef.BuildBinOp(
3189 CurScope, SourceLocation(), BO_Mul, LastIteration32.get(),
3190 SemaRef.PerformImplicitConversion(N->IgnoreImpCasts(), N->getType(),
3191 Sema::AA_Converting,
3192 /*AllowExplicit=*/true)
3194 if (LastIteration64.isUsable())
3195 LastIteration64 = SemaRef.BuildBinOp(
3196 CurScope, SourceLocation(), BO_Mul, LastIteration64.get(),
3197 SemaRef.PerformImplicitConversion(N->IgnoreImpCasts(), N->getType(),
3198 Sema::AA_Converting,
3199 /*AllowExplicit=*/true)
3203 // Choose either the 32-bit or 64-bit version.
3204 ExprResult LastIteration = LastIteration64;
3205 if (LastIteration32.isUsable() &&
3206 C.getTypeSize(LastIteration32.get()->getType()) == 32 &&
3207 (AllCountsNeedLessThan32Bits || NestedLoopCount == 1 ||
3210 LastIteration32.get()->getType()->hasSignedIntegerRepresentation(),
3211 LastIteration64.get(), SemaRef)))
3212 LastIteration = LastIteration32;
3214 if (!LastIteration.isUsable())
3217 // Save the number of iterations.
3218 ExprResult NumIterations = LastIteration;
3220 LastIteration = SemaRef.BuildBinOp(
3221 CurScope, SourceLocation(), BO_Sub, LastIteration.get(),
3222 SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get());
3223 if (!LastIteration.isUsable())
3227 // Calculate the last iteration number beforehand instead of doing this on
3228 // each iteration. Do not do this if the number of iterations may be kfold-ed.
3229 llvm::APSInt Result;
3231 LastIteration.get()->isIntegerConstantExpr(Result, SemaRef.Context);
3232 ExprResult CalcLastIteration;
3234 SourceLocation SaveLoc;
3236 buildVarDecl(SemaRef, SaveLoc, LastIteration.get()->getType(),
3237 ".omp.last.iteration");
3238 ExprResult SaveRef = buildDeclRefExpr(
3239 SemaRef, SaveVar, LastIteration.get()->getType(), SaveLoc);
3240 CalcLastIteration = SemaRef.BuildBinOp(CurScope, SaveLoc, BO_Assign,
3241 SaveRef.get(), LastIteration.get());
3242 LastIteration = SaveRef;
3244 // Prepare SaveRef + 1.
3245 NumIterations = SemaRef.BuildBinOp(
3246 CurScope, SaveLoc, BO_Add, SaveRef.get(),
3247 SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get());
3248 if (!NumIterations.isUsable())
3252 SourceLocation InitLoc = IterSpaces[0].InitSrcRange.getBegin();
3254 QualType VType = LastIteration.get()->getType();
3255 // Build variables passed into runtime, nesessary for worksharing directives.
3256 ExprResult LB, UB, IL, ST, EUB;
3257 if (isOpenMPWorksharingDirective(DKind)) {
3258 // Lower bound variable, initialized with zero.
3259 VarDecl *LBDecl = buildVarDecl(SemaRef, InitLoc, VType, ".omp.lb");
3260 LB = buildDeclRefExpr(SemaRef, LBDecl, VType, InitLoc);
3261 SemaRef.AddInitializerToDecl(
3262 LBDecl, SemaRef.ActOnIntegerConstant(InitLoc, 0).get(),
3263 /*DirectInit*/ false, /*TypeMayContainAuto*/ false);
3265 // Upper bound variable, initialized with last iteration number.
3266 VarDecl *UBDecl = buildVarDecl(SemaRef, InitLoc, VType, ".omp.ub");
3267 UB = buildDeclRefExpr(SemaRef, UBDecl, VType, InitLoc);
3268 SemaRef.AddInitializerToDecl(UBDecl, LastIteration.get(),
3269 /*DirectInit*/ false,
3270 /*TypeMayContainAuto*/ false);
3272 // A 32-bit variable-flag where runtime returns 1 for the last iteration.
3273 // This will be used to implement clause 'lastprivate'.
3274 QualType Int32Ty = SemaRef.Context.getIntTypeForBitwidth(32, true);
3275 VarDecl *ILDecl = buildVarDecl(SemaRef, InitLoc, Int32Ty, ".omp.is_last");
3276 IL = buildDeclRefExpr(SemaRef, ILDecl, Int32Ty, InitLoc);
3277 SemaRef.AddInitializerToDecl(
3278 ILDecl, SemaRef.ActOnIntegerConstant(InitLoc, 0).get(),
3279 /*DirectInit*/ false, /*TypeMayContainAuto*/ false);
3281 // Stride variable returned by runtime (we initialize it to 1 by default).
3282 VarDecl *STDecl = buildVarDecl(SemaRef, InitLoc, VType, ".omp.stride");
3283 ST = buildDeclRefExpr(SemaRef, STDecl, VType, InitLoc);
3284 SemaRef.AddInitializerToDecl(
3285 STDecl, SemaRef.ActOnIntegerConstant(InitLoc, 1).get(),
3286 /*DirectInit*/ false, /*TypeMayContainAuto*/ false);
3288 // Build expression: UB = min(UB, LastIteration)
3289 // It is nesessary for CodeGen of directives with static scheduling.
3290 ExprResult IsUBGreater = SemaRef.BuildBinOp(CurScope, InitLoc, BO_GT,
3291 UB.get(), LastIteration.get());
3292 ExprResult CondOp = SemaRef.ActOnConditionalOp(
3293 InitLoc, InitLoc, IsUBGreater.get(), LastIteration.get(), UB.get());
3294 EUB = SemaRef.BuildBinOp(CurScope, InitLoc, BO_Assign, UB.get(),
3296 EUB = SemaRef.ActOnFinishFullExpr(EUB.get());
3299 // Build the iteration variable and its initialization before loop.
3303 VarDecl *IVDecl = buildVarDecl(SemaRef, InitLoc, VType, ".omp.iv");
3304 IV = buildDeclRefExpr(SemaRef, IVDecl, VType, InitLoc);
3305 Expr *RHS = isOpenMPWorksharingDirective(DKind)
3307 : SemaRef.ActOnIntegerConstant(SourceLocation(), 0).get();
3308 Init = SemaRef.BuildBinOp(CurScope, InitLoc, BO_Assign, IV.get(), RHS);
3309 Init = SemaRef.ActOnFinishFullExpr(Init.get());
3312 // Loop condition (IV < NumIterations) or (IV <= UB) for worksharing loops.
3313 SourceLocation CondLoc;
3315 isOpenMPWorksharingDirective(DKind)
3316 ? SemaRef.BuildBinOp(CurScope, CondLoc, BO_LE, IV.get(), UB.get())
3317 : SemaRef.BuildBinOp(CurScope, CondLoc, BO_LT, IV.get(),
3318 NumIterations.get());
3320 // Loop increment (IV = IV + 1)
3321 SourceLocation IncLoc;
3323 SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, IV.get(),
3324 SemaRef.ActOnIntegerConstant(IncLoc, 1).get());
3325 if (!Inc.isUsable())
3327 Inc = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, IV.get(), Inc.get());
3328 Inc = SemaRef.ActOnFinishFullExpr(Inc.get());
3329 if (!Inc.isUsable())
3332 // Increments for worksharing loops (LB = LB + ST; UB = UB + ST).
3333 // Used for directives with static scheduling.
3334 ExprResult NextLB, NextUB;
3335 if (isOpenMPWorksharingDirective(DKind)) {
3337 NextLB = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, LB.get(), ST.get());
3338 if (!NextLB.isUsable())
3342 SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, LB.get(), NextLB.get());
3343 NextLB = SemaRef.ActOnFinishFullExpr(NextLB.get());
3344 if (!NextLB.isUsable())
3347 NextUB = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, UB.get(), ST.get());
3348 if (!NextUB.isUsable())
3352 SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, UB.get(), NextUB.get());
3353 NextUB = SemaRef.ActOnFinishFullExpr(NextUB.get());
3354 if (!NextUB.isUsable())
3358 // Build updates and final values of the loop counters.
3359 bool HasErrors = false;
3360 Built.Counters.resize(NestedLoopCount);
3361 Built.Inits.resize(NestedLoopCount);
3362 Built.Updates.resize(NestedLoopCount);
3363 Built.Finals.resize(NestedLoopCount);
3366 // Go from inner nested loop to outer.
3367 for (int Cnt = NestedLoopCount - 1; Cnt >= 0; --Cnt) {
3368 LoopIterationSpace &IS = IterSpaces[Cnt];
3369 SourceLocation UpdLoc = IS.IncSrcRange.getBegin();
3370 // Build: Iter = (IV / Div) % IS.NumIters
3371 // where Div is product of previous iterations' IS.NumIters.
3373 if (Div.isUsable()) {
3375 SemaRef.BuildBinOp(CurScope, UpdLoc, BO_Div, IV.get(), Div.get());
3378 assert((Cnt == (int)NestedLoopCount - 1) &&
3379 "unusable div expected on first iteration only");
3382 if (Cnt != 0 && Iter.isUsable())
3383 Iter = SemaRef.BuildBinOp(CurScope, UpdLoc, BO_Rem, Iter.get(),
3385 if (!Iter.isUsable()) {
3390 // Build update: IS.CounterVar(Private) = IS.Start + Iter * IS.Step
3391 auto *CounterVar = buildDeclRefExpr(
3392 SemaRef, cast<VarDecl>(cast<DeclRefExpr>(IS.CounterVar)->getDecl()),
3393 IS.CounterVar->getType(), IS.CounterVar->getExprLoc(),
3394 /*RefersToCapture=*/true);
3395 ExprResult Init = BuildCounterInit(SemaRef, CurScope, UpdLoc, CounterVar,
3397 if (!Init.isUsable()) {
3402 BuildCounterUpdate(SemaRef, CurScope, UpdLoc, CounterVar,
3403 IS.CounterInit, Iter, IS.CounterStep, IS.Subtract);
3404 if (!Update.isUsable()) {
3409 // Build final: IS.CounterVar = IS.Start + IS.NumIters * IS.Step
3410 ExprResult Final = BuildCounterUpdate(
3411 SemaRef, CurScope, UpdLoc, CounterVar, IS.CounterInit,
3412 IS.NumIterations, IS.CounterStep, IS.Subtract);
3413 if (!Final.isUsable()) {
3418 // Build Div for the next iteration: Div <- Div * IS.NumIters
3421 Div = IS.NumIterations;
3423 Div = SemaRef.BuildBinOp(CurScope, UpdLoc, BO_Mul, Div.get(),
3426 // Add parentheses (for debugging purposes only).
3428 Div = SemaRef.ActOnParenExpr(UpdLoc, UpdLoc, Div.get());
3429 if (!Div.isUsable()) {
3434 if (!Update.isUsable() || !Final.isUsable()) {
3439 Built.Counters[Cnt] = IS.CounterVar;
3440 Built.Inits[Cnt] = Init.get();
3441 Built.Updates[Cnt] = Update.get();
3442 Built.Finals[Cnt] = Final.get();
3450 Built.IterationVarRef = IV.get();
3451 Built.LastIteration = LastIteration.get();
3452 Built.NumIterations = NumIterations.get();
3453 Built.CalcLastIteration =
3454 SemaRef.ActOnFinishFullExpr(CalcLastIteration.get()).get();
3455 Built.PreCond = PreCond.get();
3456 Built.Cond = Cond.get();
3457 Built.Init = Init.get();
3458 Built.Inc = Inc.get();
3459 Built.LB = LB.get();
3460 Built.UB = UB.get();
3461 Built.IL = IL.get();
3462 Built.ST = ST.get();
3463 Built.EUB = EUB.get();
3464 Built.NLB = NextLB.get();
3465 Built.NUB = NextUB.get();
3467 return NestedLoopCount;
3470 static Expr *GetCollapseNumberExpr(ArrayRef<OMPClause *> Clauses) {
3471 auto &&CollapseFilter = [](const OMPClause *C) -> bool {
3472 return C->getClauseKind() == OMPC_collapse;
3474 OMPExecutableDirective::filtered_clause_iterator<decltype(CollapseFilter)> I(
3475 Clauses, std::move(CollapseFilter));
3477 return cast<OMPCollapseClause>(*I)->getNumForLoops();
3481 StmtResult Sema::ActOnOpenMPSimdDirective(
3482 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
3483 SourceLocation EndLoc,
3484 llvm::DenseMap<VarDecl *, Expr *> &VarsWithImplicitDSA) {
3485 OMPLoopDirective::HelperExprs B;
3486 // In presence of clause 'collapse', it will define the nested loops number.
3487 unsigned NestedLoopCount =
3488 CheckOpenMPLoop(OMPD_simd, GetCollapseNumberExpr(Clauses), AStmt, *this,
3489 *DSAStack, VarsWithImplicitDSA, B);
3490 if (NestedLoopCount == 0)
3493 assert((CurContext->isDependentContext() || B.builtAll()) &&
3494 "omp simd loop exprs were not built");
3496 if (!CurContext->isDependentContext()) {
3497 // Finalize the clauses that need pre-built expressions for CodeGen.
3498 for (auto C : Clauses) {
3499 if (auto LC = dyn_cast<OMPLinearClause>(C))
3500 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
3501 B.NumIterations, *this, CurScope))
3506 getCurFunction()->setHasBranchProtectedScope();
3507 return OMPSimdDirective::Create(Context, StartLoc, EndLoc, NestedLoopCount,
3511 StmtResult Sema::ActOnOpenMPForDirective(
3512 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
3513 SourceLocation EndLoc,
3514 llvm::DenseMap<VarDecl *, Expr *> &VarsWithImplicitDSA) {
3515 OMPLoopDirective::HelperExprs B;
3516 // In presence of clause 'collapse', it will define the nested loops number.
3517 unsigned NestedLoopCount =
3518 CheckOpenMPLoop(OMPD_for, GetCollapseNumberExpr(Clauses), AStmt, *this,
3519 *DSAStack, VarsWithImplicitDSA, B);
3520 if (NestedLoopCount == 0)
3523 assert((CurContext->isDependentContext() || B.builtAll()) &&
3524 "omp for loop exprs were not built");
3526 getCurFunction()->setHasBranchProtectedScope();
3527 return OMPForDirective::Create(Context, StartLoc, EndLoc, NestedLoopCount,
3531 StmtResult Sema::ActOnOpenMPForSimdDirective(
3532 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
3533 SourceLocation EndLoc,
3534 llvm::DenseMap<VarDecl *, Expr *> &VarsWithImplicitDSA) {
3535 OMPLoopDirective::HelperExprs B;
3536 // In presence of clause 'collapse', it will define the nested loops number.
3537 unsigned NestedLoopCount =
3538 CheckOpenMPLoop(OMPD_for_simd, GetCollapseNumberExpr(Clauses), AStmt,
3539 *this, *DSAStack, VarsWithImplicitDSA, B);
3540 if (NestedLoopCount == 0)
3543 assert((CurContext->isDependentContext() || B.builtAll()) &&
3544 "omp for simd loop exprs were not built");
3546 if (!CurContext->isDependentContext()) {
3547 // Finalize the clauses that need pre-built expressions for CodeGen.
3548 for (auto C : Clauses) {
3549 if (auto LC = dyn_cast<OMPLinearClause>(C))
3550 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
3551 B.NumIterations, *this, CurScope))
3556 getCurFunction()->setHasBranchProtectedScope();
3557 return OMPForSimdDirective::Create(Context, StartLoc, EndLoc, NestedLoopCount,
3561 StmtResult Sema::ActOnOpenMPSectionsDirective(ArrayRef<OMPClause *> Clauses,
3563 SourceLocation StartLoc,
3564 SourceLocation EndLoc) {
3565 assert(AStmt && isa<CapturedStmt>(AStmt) && "Captured statement expected");
3566 auto BaseStmt = AStmt;
3567 while (CapturedStmt *CS = dyn_cast_or_null<CapturedStmt>(BaseStmt))
3568 BaseStmt = CS->getCapturedStmt();
3569 if (auto C = dyn_cast_or_null<CompoundStmt>(BaseStmt)) {
3570 auto S = C->children();
3573 // All associated statements must be '#pragma omp section' except for
3575 for (Stmt *SectionStmt : ++S) {
3576 if (!SectionStmt || !isa<OMPSectionDirective>(SectionStmt)) {
3578 Diag(SectionStmt->getLocStart(),
3579 diag::err_omp_sections_substmt_not_section);
3584 Diag(AStmt->getLocStart(), diag::err_omp_sections_not_compound_stmt);
3588 getCurFunction()->setHasBranchProtectedScope();
3590 return OMPSectionsDirective::Create(Context, StartLoc, EndLoc, Clauses,
3594 StmtResult Sema::ActOnOpenMPSectionDirective(Stmt *AStmt,
3595 SourceLocation StartLoc,
3596 SourceLocation EndLoc) {
3597 assert(AStmt && isa<CapturedStmt>(AStmt) && "Captured statement expected");
3599 getCurFunction()->setHasBranchProtectedScope();
3601 return OMPSectionDirective::Create(Context, StartLoc, EndLoc, AStmt);
3604 StmtResult Sema::ActOnOpenMPSingleDirective(ArrayRef<OMPClause *> Clauses,
3606 SourceLocation StartLoc,
3607 SourceLocation EndLoc) {
3608 assert(AStmt && isa<CapturedStmt>(AStmt) && "Captured statement expected");
3610 getCurFunction()->setHasBranchProtectedScope();
3612 // OpenMP [2.7.3, single Construct, Restrictions]
3613 // The copyprivate clause must not be used with the nowait clause.
3614 OMPClause *Nowait = nullptr;
3615 OMPClause *Copyprivate = nullptr;
3616 for (auto *Clause : Clauses) {
3617 if (Clause->getClauseKind() == OMPC_nowait)
3619 else if (Clause->getClauseKind() == OMPC_copyprivate)
3620 Copyprivate = Clause;
3621 if (Copyprivate && Nowait) {
3622 Diag(Copyprivate->getLocStart(),
3623 diag::err_omp_single_copyprivate_with_nowait);
3624 Diag(Nowait->getLocStart(), diag::note_omp_nowait_clause_here);
3629 return OMPSingleDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt);
3632 StmtResult Sema::ActOnOpenMPMasterDirective(Stmt *AStmt,
3633 SourceLocation StartLoc,
3634 SourceLocation EndLoc) {
3635 assert(AStmt && isa<CapturedStmt>(AStmt) && "Captured statement expected");
3637 getCurFunction()->setHasBranchProtectedScope();
3639 return OMPMasterDirective::Create(Context, StartLoc, EndLoc, AStmt);
3643 Sema::ActOnOpenMPCriticalDirective(const DeclarationNameInfo &DirName,
3644 Stmt *AStmt, SourceLocation StartLoc,
3645 SourceLocation EndLoc) {
3646 assert(AStmt && isa<CapturedStmt>(AStmt) && "Captured statement expected");
3648 getCurFunction()->setHasBranchProtectedScope();
3650 return OMPCriticalDirective::Create(Context, DirName, StartLoc, EndLoc,
3654 StmtResult Sema::ActOnOpenMPParallelForDirective(
3655 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
3656 SourceLocation EndLoc,
3657 llvm::DenseMap<VarDecl *, Expr *> &VarsWithImplicitDSA) {
3658 assert(AStmt && isa<CapturedStmt>(AStmt) && "Captured statement expected");
3659 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
3660 // 1.2.2 OpenMP Language Terminology
3661 // Structured block - An executable statement with a single entry at the
3662 // top and a single exit at the bottom.
3663 // The point of exit cannot be a branch out of the structured block.
3664 // longjmp() and throw() must not violate the entry/exit criteria.
3665 CS->getCapturedDecl()->setNothrow();
3667 OMPLoopDirective::HelperExprs B;
3668 // In presence of clause 'collapse', it will define the nested loops number.
3669 unsigned NestedLoopCount =
3670 CheckOpenMPLoop(OMPD_parallel_for, GetCollapseNumberExpr(Clauses), AStmt,
3671 *this, *DSAStack, VarsWithImplicitDSA, B);
3672 if (NestedLoopCount == 0)
3675 assert((CurContext->isDependentContext() || B.builtAll()) &&
3676 "omp parallel for loop exprs were not built");
3678 getCurFunction()->setHasBranchProtectedScope();
3679 return OMPParallelForDirective::Create(Context, StartLoc, EndLoc,
3680 NestedLoopCount, Clauses, AStmt, B);
3683 StmtResult Sema::ActOnOpenMPParallelForSimdDirective(
3684 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
3685 SourceLocation EndLoc,
3686 llvm::DenseMap<VarDecl *, Expr *> &VarsWithImplicitDSA) {
3687 assert(AStmt && isa<CapturedStmt>(AStmt) && "Captured statement expected");
3688 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
3689 // 1.2.2 OpenMP Language Terminology
3690 // Structured block - An executable statement with a single entry at the
3691 // top and a single exit at the bottom.
3692 // The point of exit cannot be a branch out of the structured block.
3693 // longjmp() and throw() must not violate the entry/exit criteria.
3694 CS->getCapturedDecl()->setNothrow();
3696 OMPLoopDirective::HelperExprs B;
3697 // In presence of clause 'collapse', it will define the nested loops number.
3698 unsigned NestedLoopCount =
3699 CheckOpenMPLoop(OMPD_parallel_for_simd, GetCollapseNumberExpr(Clauses),
3700 AStmt, *this, *DSAStack, VarsWithImplicitDSA, B);
3701 if (NestedLoopCount == 0)
3704 if (!CurContext->isDependentContext()) {
3705 // Finalize the clauses that need pre-built expressions for CodeGen.
3706 for (auto C : Clauses) {
3707 if (auto LC = dyn_cast<OMPLinearClause>(C))
3708 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
3709 B.NumIterations, *this, CurScope))
3714 getCurFunction()->setHasBranchProtectedScope();
3715 return OMPParallelForSimdDirective::Create(
3716 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
3720 Sema::ActOnOpenMPParallelSectionsDirective(ArrayRef<OMPClause *> Clauses,
3721 Stmt *AStmt, SourceLocation StartLoc,
3722 SourceLocation EndLoc) {
3723 assert(AStmt && isa<CapturedStmt>(AStmt) && "Captured statement expected");
3724 auto BaseStmt = AStmt;
3725 while (CapturedStmt *CS = dyn_cast_or_null<CapturedStmt>(BaseStmt))
3726 BaseStmt = CS->getCapturedStmt();
3727 if (auto C = dyn_cast_or_null<CompoundStmt>(BaseStmt)) {
3728 auto S = C->children();
3731 // All associated statements must be '#pragma omp section' except for
3733 for (Stmt *SectionStmt : ++S) {
3734 if (!SectionStmt || !isa<OMPSectionDirective>(SectionStmt)) {
3736 Diag(SectionStmt->getLocStart(),
3737 diag::err_omp_parallel_sections_substmt_not_section);
3742 Diag(AStmt->getLocStart(),
3743 diag::err_omp_parallel_sections_not_compound_stmt);
3747 getCurFunction()->setHasBranchProtectedScope();
3749 return OMPParallelSectionsDirective::Create(Context, StartLoc, EndLoc,
3753 StmtResult Sema::ActOnOpenMPTaskDirective(ArrayRef<OMPClause *> Clauses,
3754 Stmt *AStmt, SourceLocation StartLoc,
3755 SourceLocation EndLoc) {
3756 assert(AStmt && isa<CapturedStmt>(AStmt) && "Captured statement expected");
3757 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
3758 // 1.2.2 OpenMP Language Terminology
3759 // Structured block - An executable statement with a single entry at the
3760 // top and a single exit at the bottom.
3761 // The point of exit cannot be a branch out of the structured block.
3762 // longjmp() and throw() must not violate the entry/exit criteria.
3763 CS->getCapturedDecl()->setNothrow();
3765 getCurFunction()->setHasBranchProtectedScope();
3767 return OMPTaskDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt);
3770 StmtResult Sema::ActOnOpenMPTaskyieldDirective(SourceLocation StartLoc,
3771 SourceLocation EndLoc) {
3772 return OMPTaskyieldDirective::Create(Context, StartLoc, EndLoc);
3775 StmtResult Sema::ActOnOpenMPBarrierDirective(SourceLocation StartLoc,
3776 SourceLocation EndLoc) {
3777 return OMPBarrierDirective::Create(Context, StartLoc, EndLoc);
3780 StmtResult Sema::ActOnOpenMPTaskwaitDirective(SourceLocation StartLoc,
3781 SourceLocation EndLoc) {
3782 return OMPTaskwaitDirective::Create(Context, StartLoc, EndLoc);
3785 StmtResult Sema::ActOnOpenMPTaskgroupDirective(Stmt *AStmt,
3786 SourceLocation StartLoc,
3787 SourceLocation EndLoc) {
3788 assert(AStmt && isa<CapturedStmt>(AStmt) && "Captured statement expected");
3790 getCurFunction()->setHasBranchProtectedScope();
3792 return OMPTaskgroupDirective::Create(Context, StartLoc, EndLoc, AStmt);
3795 StmtResult Sema::ActOnOpenMPFlushDirective(ArrayRef<OMPClause *> Clauses,
3796 SourceLocation StartLoc,
3797 SourceLocation EndLoc) {
3798 assert(Clauses.size() <= 1 && "Extra clauses in flush directive");
3799 return OMPFlushDirective::Create(Context, StartLoc, EndLoc, Clauses);
3802 StmtResult Sema::ActOnOpenMPOrderedDirective(Stmt *AStmt,
3803 SourceLocation StartLoc,
3804 SourceLocation EndLoc) {
3805 assert(AStmt && isa<CapturedStmt>(AStmt) && "Captured statement expected");
3807 getCurFunction()->setHasBranchProtectedScope();
3809 return OMPOrderedDirective::Create(Context, StartLoc, EndLoc, AStmt);
3813 /// \brief Helper class for checking expression in 'omp atomic [update]'
3815 class OpenMPAtomicUpdateChecker {
3816 /// \brief Error results for atomic update expressions.
3817 enum ExprAnalysisErrorCode {
3818 /// \brief A statement is not an expression statement.
3820 /// \brief Expression is not builtin binary or unary operation.
3821 NotABinaryOrUnaryExpression,
3822 /// \brief Unary operation is not post-/pre- increment/decrement operation.
3823 NotAnUnaryIncDecExpression,
3824 /// \brief An expression is not of scalar type.
3826 /// \brief A binary operation is not an assignment operation.
3828 /// \brief RHS part of the binary operation is not a binary expression.
3829 NotABinaryExpression,
3830 /// \brief RHS part is not additive/multiplicative/shift/biwise binary
3833 /// \brief RHS binary operation does not have reference to the updated LHS
3835 NotAnUpdateExpression,
3836 /// \brief No errors is found.
3839 /// \brief Reference to Sema.
3841 /// \brief A location for note diagnostics (when error is found).
3842 SourceLocation NoteLoc;
3843 /// \brief 'x' lvalue part of the source atomic expression.
3845 /// \brief 'expr' rvalue part of the source atomic expression.
3847 /// \brief Helper expression of the form
3848 /// 'OpaqueValueExpr(x) binop OpaqueValueExpr(expr)' or
3849 /// 'OpaqueValueExpr(expr) binop OpaqueValueExpr(x)'.
3851 /// \brief Is 'x' a LHS in a RHS part of full update expression. It is
3852 /// important for non-associative operations.
3853 bool IsXLHSInRHSPart;
3854 BinaryOperatorKind Op;
3855 SourceLocation OpLoc;
3856 /// \brief true if the source expression is a postfix unary operation, false
3857 /// if it is a prefix unary operation.
3858 bool IsPostfixUpdate;
3861 OpenMPAtomicUpdateChecker(Sema &SemaRef)
3862 : SemaRef(SemaRef), X(nullptr), E(nullptr), UpdateExpr(nullptr),
3863 IsXLHSInRHSPart(false), Op(BO_PtrMemD), IsPostfixUpdate(false) {}
3864 /// \brief Check specified statement that it is suitable for 'atomic update'
3865 /// constructs and extract 'x', 'expr' and Operation from the original
3866 /// expression. If DiagId and NoteId == 0, then only check is performed
3867 /// without error notification.
3868 /// \param DiagId Diagnostic which should be emitted if error is found.
3869 /// \param NoteId Diagnostic note for the main error message.
3870 /// \return true if statement is not an update expression, false otherwise.
3871 bool checkStatement(Stmt *S, unsigned DiagId = 0, unsigned NoteId = 0);
3872 /// \brief Return the 'x' lvalue part of the source atomic expression.
3873 Expr *getX() const { return X; }
3874 /// \brief Return the 'expr' rvalue part of the source atomic expression.
3875 Expr *getExpr() const { return E; }
3876 /// \brief Return the update expression used in calculation of the updated
3877 /// value. Always has form 'OpaqueValueExpr(x) binop OpaqueValueExpr(expr)' or
3878 /// 'OpaqueValueExpr(expr) binop OpaqueValueExpr(x)'.
3879 Expr *getUpdateExpr() const { return UpdateExpr; }
3880 /// \brief Return true if 'x' is LHS in RHS part of full update expression,
3881 /// false otherwise.
3882 bool isXLHSInRHSPart() const { return IsXLHSInRHSPart; }
3884 /// \brief true if the source expression is a postfix unary operation, false
3885 /// if it is a prefix unary operation.
3886 bool isPostfixUpdate() const { return IsPostfixUpdate; }
3889 bool checkBinaryOperation(BinaryOperator *AtomicBinOp, unsigned DiagId = 0,
3890 unsigned NoteId = 0);
3894 bool OpenMPAtomicUpdateChecker::checkBinaryOperation(
3895 BinaryOperator *AtomicBinOp, unsigned DiagId, unsigned NoteId) {
3896 ExprAnalysisErrorCode ErrorFound = NoError;
3897 SourceLocation ErrorLoc, NoteLoc;
3898 SourceRange ErrorRange, NoteRange;
3899 // Allowed constructs are:
3900 // x = x binop expr;
3901 // x = expr binop x;
3902 if (AtomicBinOp->getOpcode() == BO_Assign) {
3903 X = AtomicBinOp->getLHS();
3904 if (auto *AtomicInnerBinOp = dyn_cast<BinaryOperator>(
3905 AtomicBinOp->getRHS()->IgnoreParenImpCasts())) {
3906 if (AtomicInnerBinOp->isMultiplicativeOp() ||
3907 AtomicInnerBinOp->isAdditiveOp() || AtomicInnerBinOp->isShiftOp() ||
3908 AtomicInnerBinOp->isBitwiseOp()) {
3909 Op = AtomicInnerBinOp->getOpcode();
3910 OpLoc = AtomicInnerBinOp->getOperatorLoc();
3911 auto *LHS = AtomicInnerBinOp->getLHS();
3912 auto *RHS = AtomicInnerBinOp->getRHS();
3913 llvm::FoldingSetNodeID XId, LHSId, RHSId;
3914 X->IgnoreParenImpCasts()->Profile(XId, SemaRef.getASTContext(),
3915 /*Canonical=*/true);
3916 LHS->IgnoreParenImpCasts()->Profile(LHSId, SemaRef.getASTContext(),
3917 /*Canonical=*/true);
3918 RHS->IgnoreParenImpCasts()->Profile(RHSId, SemaRef.getASTContext(),
3919 /*Canonical=*/true);
3922 IsXLHSInRHSPart = true;
3923 } else if (XId == RHSId) {
3925 IsXLHSInRHSPart = false;
3927 ErrorLoc = AtomicInnerBinOp->getExprLoc();
3928 ErrorRange = AtomicInnerBinOp->getSourceRange();
3929 NoteLoc = X->getExprLoc();
3930 NoteRange = X->getSourceRange();
3931 ErrorFound = NotAnUpdateExpression;
3934 ErrorLoc = AtomicInnerBinOp->getExprLoc();
3935 ErrorRange = AtomicInnerBinOp->getSourceRange();
3936 NoteLoc = AtomicInnerBinOp->getOperatorLoc();
3937 NoteRange = SourceRange(NoteLoc, NoteLoc);
3938 ErrorFound = NotABinaryOperator;
3941 NoteLoc = ErrorLoc = AtomicBinOp->getRHS()->getExprLoc();
3942 NoteRange = ErrorRange = AtomicBinOp->getRHS()->getSourceRange();
3943 ErrorFound = NotABinaryExpression;
3946 ErrorLoc = AtomicBinOp->getExprLoc();
3947 ErrorRange = AtomicBinOp->getSourceRange();
3948 NoteLoc = AtomicBinOp->getOperatorLoc();
3949 NoteRange = SourceRange(NoteLoc, NoteLoc);
3950 ErrorFound = NotAnAssignmentOp;
3952 if (ErrorFound != NoError && DiagId != 0 && NoteId != 0) {
3953 SemaRef.Diag(ErrorLoc, DiagId) << ErrorRange;
3954 SemaRef.Diag(NoteLoc, NoteId) << ErrorFound << NoteRange;
3956 } else if (SemaRef.CurContext->isDependentContext())
3957 E = X = UpdateExpr = nullptr;
3958 return ErrorFound != NoError;
3961 bool OpenMPAtomicUpdateChecker::checkStatement(Stmt *S, unsigned DiagId,
3963 ExprAnalysisErrorCode ErrorFound = NoError;
3964 SourceLocation ErrorLoc, NoteLoc;
3965 SourceRange ErrorRange, NoteRange;
3966 // Allowed constructs are:
3972 // x = x binop expr;
3973 // x = expr binop x;
3974 if (auto *AtomicBody = dyn_cast<Expr>(S)) {
3975 AtomicBody = AtomicBody->IgnoreParenImpCasts();
3976 if (AtomicBody->getType()->isScalarType() ||
3977 AtomicBody->isInstantiationDependent()) {
3978 if (auto *AtomicCompAssignOp = dyn_cast<CompoundAssignOperator>(
3979 AtomicBody->IgnoreParenImpCasts())) {
3980 // Check for Compound Assignment Operation
3981 Op = BinaryOperator::getOpForCompoundAssignment(
3982 AtomicCompAssignOp->getOpcode());
3983 OpLoc = AtomicCompAssignOp->getOperatorLoc();
3984 E = AtomicCompAssignOp->getRHS();
3985 X = AtomicCompAssignOp->getLHS();
3986 IsXLHSInRHSPart = true;
3987 } else if (auto *AtomicBinOp = dyn_cast<BinaryOperator>(
3988 AtomicBody->IgnoreParenImpCasts())) {
3989 // Check for Binary Operation
3990 if(checkBinaryOperation(AtomicBinOp, DiagId, NoteId))
3992 } else if (auto *AtomicUnaryOp =
3993 dyn_cast<UnaryOperator>(AtomicBody->IgnoreParenImpCasts())) {
3994 // Check for Unary Operation
3995 if (AtomicUnaryOp->isIncrementDecrementOp()) {
3996 IsPostfixUpdate = AtomicUnaryOp->isPostfix();
3997 Op = AtomicUnaryOp->isIncrementOp() ? BO_Add : BO_Sub;
3998 OpLoc = AtomicUnaryOp->getOperatorLoc();
3999 X = AtomicUnaryOp->getSubExpr();
4000 E = SemaRef.ActOnIntegerConstant(OpLoc, /*uint64_t Val=*/1).get();
4001 IsXLHSInRHSPart = true;
4003 ErrorFound = NotAnUnaryIncDecExpression;
4004 ErrorLoc = AtomicUnaryOp->getExprLoc();
4005 ErrorRange = AtomicUnaryOp->getSourceRange();
4006 NoteLoc = AtomicUnaryOp->getOperatorLoc();
4007 NoteRange = SourceRange(NoteLoc, NoteLoc);
4010 ErrorFound = NotABinaryOrUnaryExpression;
4011 NoteLoc = ErrorLoc = AtomicBody->getExprLoc();
4012 NoteRange = ErrorRange = AtomicBody->getSourceRange();
4015 ErrorFound = NotAScalarType;
4016 NoteLoc = ErrorLoc = AtomicBody->getLocStart();
4017 NoteRange = ErrorRange = SourceRange(NoteLoc, NoteLoc);
4020 ErrorFound = NotAnExpression;
4021 NoteLoc = ErrorLoc = S->getLocStart();
4022 NoteRange = ErrorRange = SourceRange(NoteLoc, NoteLoc);
4024 if (ErrorFound != NoError && DiagId != 0 && NoteId != 0) {
4025 SemaRef.Diag(ErrorLoc, DiagId) << ErrorRange;
4026 SemaRef.Diag(NoteLoc, NoteId) << ErrorFound << NoteRange;
4028 } else if (SemaRef.CurContext->isDependentContext())
4029 E = X = UpdateExpr = nullptr;
4030 if (ErrorFound == NoError && E && X) {
4031 // Build an update expression of form 'OpaqueValueExpr(x) binop
4032 // OpaqueValueExpr(expr)' or 'OpaqueValueExpr(expr) binop
4033 // OpaqueValueExpr(x)' and then cast it to the type of the 'x' expression.
4034 auto *OVEX = new (SemaRef.getASTContext())
4035 OpaqueValueExpr(X->getExprLoc(), X->getType(), VK_RValue);
4036 auto *OVEExpr = new (SemaRef.getASTContext())
4037 OpaqueValueExpr(E->getExprLoc(), E->getType(), VK_RValue);
4039 SemaRef.CreateBuiltinBinOp(OpLoc, Op, IsXLHSInRHSPart ? OVEX : OVEExpr,
4040 IsXLHSInRHSPart ? OVEExpr : OVEX);
4041 if (Update.isInvalid())
4043 Update = SemaRef.PerformImplicitConversion(Update.get(), X->getType(),
4045 if (Update.isInvalid())
4047 UpdateExpr = Update.get();
4049 return ErrorFound != NoError;
4052 StmtResult Sema::ActOnOpenMPAtomicDirective(ArrayRef<OMPClause *> Clauses,
4054 SourceLocation StartLoc,
4055 SourceLocation EndLoc) {
4056 assert(AStmt && isa<CapturedStmt>(AStmt) && "Captured statement expected");
4057 auto CS = cast<CapturedStmt>(AStmt);
4058 // 1.2.2 OpenMP Language Terminology
4059 // Structured block - An executable statement with a single entry at the
4060 // top and a single exit at the bottom.
4061 // The point of exit cannot be a branch out of the structured block.
4062 // longjmp() and throw() must not violate the entry/exit criteria.
4063 OpenMPClauseKind AtomicKind = OMPC_unknown;
4064 SourceLocation AtomicKindLoc;
4065 for (auto *C : Clauses) {
4066 if (C->getClauseKind() == OMPC_read || C->getClauseKind() == OMPC_write ||
4067 C->getClauseKind() == OMPC_update ||
4068 C->getClauseKind() == OMPC_capture) {
4069 if (AtomicKind != OMPC_unknown) {
4070 Diag(C->getLocStart(), diag::err_omp_atomic_several_clauses)
4071 << SourceRange(C->getLocStart(), C->getLocEnd());
4072 Diag(AtomicKindLoc, diag::note_omp_atomic_previous_clause)
4073 << getOpenMPClauseName(AtomicKind);
4075 AtomicKind = C->getClauseKind();
4076 AtomicKindLoc = C->getLocStart();
4081 auto Body = CS->getCapturedStmt();
4082 if (auto *EWC = dyn_cast<ExprWithCleanups>(Body))
4083 Body = EWC->getSubExpr();
4089 bool IsXLHSInRHSPart = false;
4090 bool IsPostfixUpdate = false;
4091 // OpenMP [2.12.6, atomic Construct]
4092 // In the next expressions:
4093 // * x and v (as applicable) are both l-value expressions with scalar type.
4094 // * During the execution of an atomic region, multiple syntactic
4095 // occurrences of x must designate the same storage location.
4096 // * Neither of v and expr (as applicable) may access the storage location
4098 // * Neither of x and expr (as applicable) may access the storage location
4100 // * expr is an expression with scalar type.
4101 // * binop is one of +, *, -, /, &, ^, |, <<, or >>.
4102 // * binop, binop=, ++, and -- are not overloaded operators.
4103 // * The expression x binop expr must be numerically equivalent to x binop
4104 // (expr). This requirement is satisfied if the operators in expr have
4105 // precedence greater than binop, or by using parentheses around expr or
4106 // subexpressions of expr.
4107 // * The expression expr binop x must be numerically equivalent to (expr)
4108 // binop x. This requirement is satisfied if the operators in expr have
4109 // precedence equal to or greater than binop, or by using parentheses around
4110 // expr or subexpressions of expr.
4111 // * For forms that allow multiple occurrences of x, the number of times
4112 // that x is evaluated is unspecified.
4113 if (AtomicKind == OMPC_read) {
4120 } ErrorFound = NoError;
4121 SourceLocation ErrorLoc, NoteLoc;
4122 SourceRange ErrorRange, NoteRange;
4123 // If clause is read:
4125 if (auto AtomicBody = dyn_cast<Expr>(Body)) {
4127 dyn_cast<BinaryOperator>(AtomicBody->IgnoreParenImpCasts());
4128 if (AtomicBinOp && AtomicBinOp->getOpcode() == BO_Assign) {
4129 X = AtomicBinOp->getRHS()->IgnoreParenImpCasts();
4130 V = AtomicBinOp->getLHS()->IgnoreParenImpCasts();
4131 if ((X->isInstantiationDependent() || X->getType()->isScalarType()) &&
4132 (V->isInstantiationDependent() || V->getType()->isScalarType())) {
4133 if (!X->isLValue() || !V->isLValue()) {
4134 auto NotLValueExpr = X->isLValue() ? V : X;
4135 ErrorFound = NotAnLValue;
4136 ErrorLoc = AtomicBinOp->getExprLoc();
4137 ErrorRange = AtomicBinOp->getSourceRange();
4138 NoteLoc = NotLValueExpr->getExprLoc();
4139 NoteRange = NotLValueExpr->getSourceRange();
4141 } else if (!X->isInstantiationDependent() ||
4142 !V->isInstantiationDependent()) {
4143 auto NotScalarExpr =
4144 (X->isInstantiationDependent() || X->getType()->isScalarType())
4147 ErrorFound = NotAScalarType;
4148 ErrorLoc = AtomicBinOp->getExprLoc();
4149 ErrorRange = AtomicBinOp->getSourceRange();
4150 NoteLoc = NotScalarExpr->getExprLoc();
4151 NoteRange = NotScalarExpr->getSourceRange();
4154 ErrorFound = NotAnAssignmentOp;
4155 ErrorLoc = AtomicBody->getExprLoc();
4156 ErrorRange = AtomicBody->getSourceRange();
4157 NoteLoc = AtomicBinOp ? AtomicBinOp->getOperatorLoc()
4158 : AtomicBody->getExprLoc();
4159 NoteRange = AtomicBinOp ? AtomicBinOp->getSourceRange()
4160 : AtomicBody->getSourceRange();
4163 ErrorFound = NotAnExpression;
4164 NoteLoc = ErrorLoc = Body->getLocStart();
4165 NoteRange = ErrorRange = SourceRange(NoteLoc, NoteLoc);
4167 if (ErrorFound != NoError) {
4168 Diag(ErrorLoc, diag::err_omp_atomic_read_not_expression_statement)
4170 Diag(NoteLoc, diag::note_omp_atomic_read_write) << ErrorFound
4173 } else if (CurContext->isDependentContext())
4175 } else if (AtomicKind == OMPC_write) {
4182 } ErrorFound = NoError;
4183 SourceLocation ErrorLoc, NoteLoc;
4184 SourceRange ErrorRange, NoteRange;
4185 // If clause is write:
4187 if (auto AtomicBody = dyn_cast<Expr>(Body)) {
4189 dyn_cast<BinaryOperator>(AtomicBody->IgnoreParenImpCasts());
4190 if (AtomicBinOp && AtomicBinOp->getOpcode() == BO_Assign) {
4191 X = AtomicBinOp->getLHS();
4192 E = AtomicBinOp->getRHS();
4193 if ((X->isInstantiationDependent() || X->getType()->isScalarType()) &&
4194 (E->isInstantiationDependent() || E->getType()->isScalarType())) {
4195 if (!X->isLValue()) {
4196 ErrorFound = NotAnLValue;
4197 ErrorLoc = AtomicBinOp->getExprLoc();
4198 ErrorRange = AtomicBinOp->getSourceRange();
4199 NoteLoc = X->getExprLoc();
4200 NoteRange = X->getSourceRange();
4202 } else if (!X->isInstantiationDependent() ||
4203 !E->isInstantiationDependent()) {
4204 auto NotScalarExpr =
4205 (X->isInstantiationDependent() || X->getType()->isScalarType())
4208 ErrorFound = NotAScalarType;
4209 ErrorLoc = AtomicBinOp->getExprLoc();
4210 ErrorRange = AtomicBinOp->getSourceRange();
4211 NoteLoc = NotScalarExpr->getExprLoc();
4212 NoteRange = NotScalarExpr->getSourceRange();
4215 ErrorFound = NotAnAssignmentOp;
4216 ErrorLoc = AtomicBody->getExprLoc();
4217 ErrorRange = AtomicBody->getSourceRange();
4218 NoteLoc = AtomicBinOp ? AtomicBinOp->getOperatorLoc()
4219 : AtomicBody->getExprLoc();
4220 NoteRange = AtomicBinOp ? AtomicBinOp->getSourceRange()
4221 : AtomicBody->getSourceRange();
4224 ErrorFound = NotAnExpression;
4225 NoteLoc = ErrorLoc = Body->getLocStart();
4226 NoteRange = ErrorRange = SourceRange(NoteLoc, NoteLoc);
4228 if (ErrorFound != NoError) {
4229 Diag(ErrorLoc, diag::err_omp_atomic_write_not_expression_statement)
4231 Diag(NoteLoc, diag::note_omp_atomic_read_write) << ErrorFound
4234 } else if (CurContext->isDependentContext())
4236 } else if (AtomicKind == OMPC_update || AtomicKind == OMPC_unknown) {
4237 // If clause is update:
4243 // x = x binop expr;
4244 // x = expr binop x;
4245 OpenMPAtomicUpdateChecker Checker(*this);
4246 if (Checker.checkStatement(
4247 Body, (AtomicKind == OMPC_update)
4248 ? diag::err_omp_atomic_update_not_expression_statement
4249 : diag::err_omp_atomic_not_expression_statement,
4250 diag::note_omp_atomic_update))
4252 if (!CurContext->isDependentContext()) {
4253 E = Checker.getExpr();
4255 UE = Checker.getUpdateExpr();
4256 IsXLHSInRHSPart = Checker.isXLHSInRHSPart();
4258 } else if (AtomicKind == OMPC_capture) {
4261 NotACompoundStatement,
4262 NotTwoSubstatements,
4263 NotASpecificExpression,
4265 } ErrorFound = NoError;
4266 SourceLocation ErrorLoc, NoteLoc;
4267 SourceRange ErrorRange, NoteRange;
4268 if (auto *AtomicBody = dyn_cast<Expr>(Body)) {
4269 // If clause is a capture:
4274 // v = x binop= expr;
4275 // v = x = x binop expr;
4276 // v = x = expr binop x;
4278 dyn_cast<BinaryOperator>(AtomicBody->IgnoreParenImpCasts());
4279 if (AtomicBinOp && AtomicBinOp->getOpcode() == BO_Assign) {
4280 V = AtomicBinOp->getLHS();
4281 Body = AtomicBinOp->getRHS()->IgnoreParenImpCasts();
4282 OpenMPAtomicUpdateChecker Checker(*this);
4283 if (Checker.checkStatement(
4284 Body, diag::err_omp_atomic_capture_not_expression_statement,
4285 diag::note_omp_atomic_update))
4287 E = Checker.getExpr();
4289 UE = Checker.getUpdateExpr();
4290 IsXLHSInRHSPart = Checker.isXLHSInRHSPart();
4291 IsPostfixUpdate = Checker.isPostfixUpdate();
4293 ErrorLoc = AtomicBody->getExprLoc();
4294 ErrorRange = AtomicBody->getSourceRange();
4295 NoteLoc = AtomicBinOp ? AtomicBinOp->getOperatorLoc()
4296 : AtomicBody->getExprLoc();
4297 NoteRange = AtomicBinOp ? AtomicBinOp->getSourceRange()
4298 : AtomicBody->getSourceRange();
4299 ErrorFound = NotAnAssignmentOp;
4301 if (ErrorFound != NoError) {
4302 Diag(ErrorLoc, diag::err_omp_atomic_capture_not_expression_statement)
4304 Diag(NoteLoc, diag::note_omp_atomic_capture) << ErrorFound << NoteRange;
4306 } else if (CurContext->isDependentContext()) {
4307 UE = V = E = X = nullptr;
4310 // If clause is a capture:
4311 // { v = x; x = expr; }
4316 // { v = x; x binop= expr; }
4317 // { v = x; x = x binop expr; }
4318 // { v = x; x = expr binop x; }
4323 // { x binop= expr; v = x; }
4324 // { x = x binop expr; v = x; }
4325 // { x = expr binop x; v = x; }
4326 if (auto *CS = dyn_cast<CompoundStmt>(Body)) {
4327 // Check that this is { expr1; expr2; }
4328 if (CS->size() == 2) {
4329 auto *First = CS->body_front();
4330 auto *Second = CS->body_back();
4331 if (auto *EWC = dyn_cast<ExprWithCleanups>(First))
4332 First = EWC->getSubExpr()->IgnoreParenImpCasts();
4333 if (auto *EWC = dyn_cast<ExprWithCleanups>(Second))
4334 Second = EWC->getSubExpr()->IgnoreParenImpCasts();
4335 // Need to find what subexpression is 'v' and what is 'x'.
4336 OpenMPAtomicUpdateChecker Checker(*this);
4337 bool IsUpdateExprFound = !Checker.checkStatement(Second);
4338 BinaryOperator *BinOp = nullptr;
4339 if (IsUpdateExprFound) {
4340 BinOp = dyn_cast<BinaryOperator>(First);
4341 IsUpdateExprFound = BinOp && BinOp->getOpcode() == BO_Assign;
4343 if (IsUpdateExprFound && !CurContext->isDependentContext()) {
4348 // { v = x; x binop= expr; }
4349 // { v = x; x = x binop expr; }
4350 // { v = x; x = expr binop x; }
4351 // Check that the first expression has form v = x.
4352 auto *PossibleX = BinOp->getRHS()->IgnoreParenImpCasts();
4353 llvm::FoldingSetNodeID XId, PossibleXId;
4354 Checker.getX()->Profile(XId, Context, /*Canonical=*/true);
4355 PossibleX->Profile(PossibleXId, Context, /*Canonical=*/true);
4356 IsUpdateExprFound = XId == PossibleXId;
4357 if (IsUpdateExprFound) {
4358 V = BinOp->getLHS();
4360 E = Checker.getExpr();
4361 UE = Checker.getUpdateExpr();
4362 IsXLHSInRHSPart = Checker.isXLHSInRHSPart();
4363 IsPostfixUpdate = true;
4366 if (!IsUpdateExprFound) {
4367 IsUpdateExprFound = !Checker.checkStatement(First);
4369 if (IsUpdateExprFound) {
4370 BinOp = dyn_cast<BinaryOperator>(Second);
4371 IsUpdateExprFound = BinOp && BinOp->getOpcode() == BO_Assign;
4373 if (IsUpdateExprFound && !CurContext->isDependentContext()) {
4378 // { x binop= expr; v = x; }
4379 // { x = x binop expr; v = x; }
4380 // { x = expr binop x; v = x; }
4381 // Check that the second expression has form v = x.
4382 auto *PossibleX = BinOp->getRHS()->IgnoreParenImpCasts();
4383 llvm::FoldingSetNodeID XId, PossibleXId;
4384 Checker.getX()->Profile(XId, Context, /*Canonical=*/true);
4385 PossibleX->Profile(PossibleXId, Context, /*Canonical=*/true);
4386 IsUpdateExprFound = XId == PossibleXId;
4387 if (IsUpdateExprFound) {
4388 V = BinOp->getLHS();
4390 E = Checker.getExpr();
4391 UE = Checker.getUpdateExpr();
4392 IsXLHSInRHSPart = Checker.isXLHSInRHSPart();
4393 IsPostfixUpdate = false;
4397 if (!IsUpdateExprFound) {
4398 // { v = x; x = expr; }
4399 auto *FirstBinOp = dyn_cast<BinaryOperator>(First);
4400 if (!FirstBinOp || FirstBinOp->getOpcode() != BO_Assign) {
4401 ErrorFound = NotAnAssignmentOp;
4402 NoteLoc = ErrorLoc = FirstBinOp ? FirstBinOp->getOperatorLoc()
4403 : First->getLocStart();
4404 NoteRange = ErrorRange = FirstBinOp
4405 ? FirstBinOp->getSourceRange()
4406 : SourceRange(ErrorLoc, ErrorLoc);
4408 auto *SecondBinOp = dyn_cast<BinaryOperator>(Second);
4409 if (!SecondBinOp || SecondBinOp->getOpcode() != BO_Assign) {
4410 ErrorFound = NotAnAssignmentOp;
4411 NoteLoc = ErrorLoc = SecondBinOp ? SecondBinOp->getOperatorLoc()
4412 : Second->getLocStart();
4413 NoteRange = ErrorRange = SecondBinOp
4414 ? SecondBinOp->getSourceRange()
4415 : SourceRange(ErrorLoc, ErrorLoc);
4417 auto *PossibleXRHSInFirst =
4418 FirstBinOp->getRHS()->IgnoreParenImpCasts();
4419 auto *PossibleXLHSInSecond =
4420 SecondBinOp->getLHS()->IgnoreParenImpCasts();
4421 llvm::FoldingSetNodeID X1Id, X2Id;
4422 PossibleXRHSInFirst->Profile(X1Id, Context, /*Canonical=*/true);
4423 PossibleXLHSInSecond->Profile(X2Id, Context,
4424 /*Canonical=*/true);
4425 IsUpdateExprFound = X1Id == X2Id;
4426 if (IsUpdateExprFound) {
4427 V = FirstBinOp->getLHS();
4428 X = SecondBinOp->getLHS();
4429 E = SecondBinOp->getRHS();
4431 IsXLHSInRHSPart = false;
4432 IsPostfixUpdate = true;
4434 ErrorFound = NotASpecificExpression;
4435 ErrorLoc = FirstBinOp->getExprLoc();
4436 ErrorRange = FirstBinOp->getSourceRange();
4437 NoteLoc = SecondBinOp->getLHS()->getExprLoc();
4438 NoteRange = SecondBinOp->getRHS()->getSourceRange();
4444 NoteLoc = ErrorLoc = Body->getLocStart();
4445 NoteRange = ErrorRange =
4446 SourceRange(Body->getLocStart(), Body->getLocStart());
4447 ErrorFound = NotTwoSubstatements;
4450 NoteLoc = ErrorLoc = Body->getLocStart();
4451 NoteRange = ErrorRange =
4452 SourceRange(Body->getLocStart(), Body->getLocStart());
4453 ErrorFound = NotACompoundStatement;
4455 if (ErrorFound != NoError) {
4456 Diag(ErrorLoc, diag::err_omp_atomic_capture_not_compound_statement)
4458 Diag(NoteLoc, diag::note_omp_atomic_capture) << ErrorFound << NoteRange;
4460 } else if (CurContext->isDependentContext()) {
4461 UE = V = E = X = nullptr;
4466 getCurFunction()->setHasBranchProtectedScope();
4468 return OMPAtomicDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt,
4469 X, V, E, UE, IsXLHSInRHSPart,
4473 StmtResult Sema::ActOnOpenMPTargetDirective(ArrayRef<OMPClause *> Clauses,
4475 SourceLocation StartLoc,
4476 SourceLocation EndLoc) {
4477 assert(AStmt && isa<CapturedStmt>(AStmt) && "Captured statement expected");
4479 // OpenMP [2.16, Nesting of Regions]
4480 // If specified, a teams construct must be contained within a target
4481 // construct. That target construct must contain no statements or directives
4482 // outside of the teams construct.
4483 if (DSAStack->hasInnerTeamsRegion()) {
4484 auto S = AStmt->IgnoreContainers(/*IgnoreCaptured*/ true);
4485 bool OMPTeamsFound = true;
4486 if (auto *CS = dyn_cast<CompoundStmt>(S)) {
4487 auto I = CS->body_begin();
4488 while (I != CS->body_end()) {
4489 auto OED = dyn_cast<OMPExecutableDirective>(*I);
4490 if (!OED || !isOpenMPTeamsDirective(OED->getDirectiveKind())) {
4491 OMPTeamsFound = false;
4496 assert(I != CS->body_end() && "Not found statement");
4499 if (!OMPTeamsFound) {
4500 Diag(StartLoc, diag::err_omp_target_contains_not_only_teams);
4501 Diag(DSAStack->getInnerTeamsRegionLoc(),
4502 diag::note_omp_nested_teams_construct_here);
4503 Diag(S->getLocStart(), diag::note_omp_nested_statement_here)
4504 << isa<OMPExecutableDirective>(S);
4509 getCurFunction()->setHasBranchProtectedScope();
4511 return OMPTargetDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt);
4514 StmtResult Sema::ActOnOpenMPTeamsDirective(ArrayRef<OMPClause *> Clauses,
4515 Stmt *AStmt, SourceLocation StartLoc,
4516 SourceLocation EndLoc) {
4517 assert(AStmt && isa<CapturedStmt>(AStmt) && "Captured statement expected");
4518 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
4519 // 1.2.2 OpenMP Language Terminology
4520 // Structured block - An executable statement with a single entry at the
4521 // top and a single exit at the bottom.
4522 // The point of exit cannot be a branch out of the structured block.
4523 // longjmp() and throw() must not violate the entry/exit criteria.
4524 CS->getCapturedDecl()->setNothrow();
4526 getCurFunction()->setHasBranchProtectedScope();
4528 return OMPTeamsDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt);
4532 Sema::ActOnOpenMPCancellationPointDirective(SourceLocation StartLoc,
4533 SourceLocation EndLoc,
4534 OpenMPDirectiveKind CancelRegion) {
4535 if (CancelRegion != OMPD_parallel && CancelRegion != OMPD_for &&
4536 CancelRegion != OMPD_sections && CancelRegion != OMPD_taskgroup) {
4537 Diag(StartLoc, diag::err_omp_wrong_cancel_region)
4538 << getOpenMPDirectiveName(CancelRegion);
4541 if (DSAStack->isParentNowaitRegion()) {
4542 Diag(StartLoc, diag::err_omp_parent_cancel_region_nowait) << 0;
4545 if (DSAStack->isParentOrderedRegion()) {
4546 Diag(StartLoc, diag::err_omp_parent_cancel_region_ordered) << 0;
4549 return OMPCancellationPointDirective::Create(Context, StartLoc, EndLoc,
4553 StmtResult Sema::ActOnOpenMPCancelDirective(SourceLocation StartLoc,
4554 SourceLocation EndLoc,
4555 OpenMPDirectiveKind CancelRegion) {
4556 if (CancelRegion != OMPD_parallel && CancelRegion != OMPD_for &&
4557 CancelRegion != OMPD_sections && CancelRegion != OMPD_taskgroup) {
4558 Diag(StartLoc, diag::err_omp_wrong_cancel_region)
4559 << getOpenMPDirectiveName(CancelRegion);
4562 if (DSAStack->isParentNowaitRegion()) {
4563 Diag(StartLoc, diag::err_omp_parent_cancel_region_nowait) << 1;
4566 if (DSAStack->isParentOrderedRegion()) {
4567 Diag(StartLoc, diag::err_omp_parent_cancel_region_ordered) << 1;
4570 return OMPCancelDirective::Create(Context, StartLoc, EndLoc, CancelRegion);
4573 OMPClause *Sema::ActOnOpenMPSingleExprClause(OpenMPClauseKind Kind, Expr *Expr,
4574 SourceLocation StartLoc,
4575 SourceLocation LParenLoc,
4576 SourceLocation EndLoc) {
4577 OMPClause *Res = nullptr;
4580 Res = ActOnOpenMPIfClause(Expr, StartLoc, LParenLoc, EndLoc);
4583 Res = ActOnOpenMPFinalClause(Expr, StartLoc, LParenLoc, EndLoc);
4585 case OMPC_num_threads:
4586 Res = ActOnOpenMPNumThreadsClause(Expr, StartLoc, LParenLoc, EndLoc);
4589 Res = ActOnOpenMPSafelenClause(Expr, StartLoc, LParenLoc, EndLoc);
4592 Res = ActOnOpenMPCollapseClause(Expr, StartLoc, LParenLoc, EndLoc);
4595 case OMPC_proc_bind:
4598 case OMPC_firstprivate:
4599 case OMPC_lastprivate:
4601 case OMPC_reduction:
4605 case OMPC_copyprivate:
4609 case OMPC_mergeable:
4610 case OMPC_threadprivate:
4619 llvm_unreachable("Clause is not allowed.");
4624 OMPClause *Sema::ActOnOpenMPIfClause(Expr *Condition, SourceLocation StartLoc,
4625 SourceLocation LParenLoc,
4626 SourceLocation EndLoc) {
4627 Expr *ValExpr = Condition;
4628 if (!Condition->isValueDependent() && !Condition->isTypeDependent() &&
4629 !Condition->isInstantiationDependent() &&
4630 !Condition->containsUnexpandedParameterPack()) {
4631 ExprResult Val = ActOnBooleanCondition(DSAStack->getCurScope(),
4632 Condition->getExprLoc(), Condition);
4633 if (Val.isInvalid())
4636 ValExpr = Val.get();
4639 return new (Context) OMPIfClause(ValExpr, StartLoc, LParenLoc, EndLoc);
4642 OMPClause *Sema::ActOnOpenMPFinalClause(Expr *Condition,
4643 SourceLocation StartLoc,
4644 SourceLocation LParenLoc,
4645 SourceLocation EndLoc) {
4646 Expr *ValExpr = Condition;
4647 if (!Condition->isValueDependent() && !Condition->isTypeDependent() &&
4648 !Condition->isInstantiationDependent() &&
4649 !Condition->containsUnexpandedParameterPack()) {
4650 ExprResult Val = ActOnBooleanCondition(DSAStack->getCurScope(),
4651 Condition->getExprLoc(), Condition);
4652 if (Val.isInvalid())
4655 ValExpr = Val.get();
4658 return new (Context) OMPFinalClause(ValExpr, StartLoc, LParenLoc, EndLoc);
4660 ExprResult Sema::PerformOpenMPImplicitIntegerConversion(SourceLocation Loc,
4665 class IntConvertDiagnoser : public ICEConvertDiagnoser {
4667 IntConvertDiagnoser()
4668 : ICEConvertDiagnoser(/*AllowScopedEnumerations*/ false, false, true) {}
4669 SemaDiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc,
4670 QualType T) override {
4671 return S.Diag(Loc, diag::err_omp_not_integral) << T;
4673 SemaDiagnosticBuilder diagnoseIncomplete(Sema &S, SourceLocation Loc,
4674 QualType T) override {
4675 return S.Diag(Loc, diag::err_omp_incomplete_type) << T;
4677 SemaDiagnosticBuilder diagnoseExplicitConv(Sema &S, SourceLocation Loc,
4679 QualType ConvTy) override {
4680 return S.Diag(Loc, diag::err_omp_explicit_conversion) << T << ConvTy;
4682 SemaDiagnosticBuilder noteExplicitConv(Sema &S, CXXConversionDecl *Conv,
4683 QualType ConvTy) override {
4684 return S.Diag(Conv->getLocation(), diag::note_omp_conversion_here)
4685 << ConvTy->isEnumeralType() << ConvTy;
4687 SemaDiagnosticBuilder diagnoseAmbiguous(Sema &S, SourceLocation Loc,
4688 QualType T) override {
4689 return S.Diag(Loc, diag::err_omp_ambiguous_conversion) << T;
4691 SemaDiagnosticBuilder noteAmbiguous(Sema &S, CXXConversionDecl *Conv,
4692 QualType ConvTy) override {
4693 return S.Diag(Conv->getLocation(), diag::note_omp_conversion_here)
4694 << ConvTy->isEnumeralType() << ConvTy;
4696 SemaDiagnosticBuilder diagnoseConversion(Sema &, SourceLocation, QualType,
4697 QualType) override {
4698 llvm_unreachable("conversion functions are permitted");
4701 return PerformContextualImplicitConversion(Loc, Op, ConvertDiagnoser);
4704 OMPClause *Sema::ActOnOpenMPNumThreadsClause(Expr *NumThreads,
4705 SourceLocation StartLoc,
4706 SourceLocation LParenLoc,
4707 SourceLocation EndLoc) {
4708 Expr *ValExpr = NumThreads;
4709 if (!NumThreads->isValueDependent() && !NumThreads->isTypeDependent() &&
4710 !NumThreads->containsUnexpandedParameterPack()) {
4711 SourceLocation NumThreadsLoc = NumThreads->getLocStart();
4713 PerformOpenMPImplicitIntegerConversion(NumThreadsLoc, NumThreads);
4714 if (Val.isInvalid())
4717 ValExpr = Val.get();
4719 // OpenMP [2.5, Restrictions]
4720 // The num_threads expression must evaluate to a positive integer value.
4721 llvm::APSInt Result;
4722 if (ValExpr->isIntegerConstantExpr(Result, Context) && Result.isSigned() &&
4723 !Result.isStrictlyPositive()) {
4724 Diag(NumThreadsLoc, diag::err_omp_negative_expression_in_clause)
4725 << "num_threads" << NumThreads->getSourceRange();
4730 return new (Context)
4731 OMPNumThreadsClause(ValExpr, StartLoc, LParenLoc, EndLoc);
4734 ExprResult Sema::VerifyPositiveIntegerConstantInClause(Expr *E,
4735 OpenMPClauseKind CKind) {
4738 if (E->isValueDependent() || E->isTypeDependent() ||
4739 E->isInstantiationDependent() || E->containsUnexpandedParameterPack())
4741 llvm::APSInt Result;
4742 ExprResult ICE = VerifyIntegerConstantExpression(E, &Result);
4743 if (ICE.isInvalid())
4745 if (!Result.isStrictlyPositive()) {
4746 Diag(E->getExprLoc(), diag::err_omp_negative_expression_in_clause)
4747 << getOpenMPClauseName(CKind) << E->getSourceRange();
4750 if (CKind == OMPC_aligned && !Result.isPowerOf2()) {
4751 Diag(E->getExprLoc(), diag::warn_omp_alignment_not_power_of_two)
4752 << E->getSourceRange();
4755 if (CKind == OMPC_collapse) {
4756 DSAStack->setCollapseNumber(Result.getExtValue());
4761 OMPClause *Sema::ActOnOpenMPSafelenClause(Expr *Len, SourceLocation StartLoc,
4762 SourceLocation LParenLoc,
4763 SourceLocation EndLoc) {
4764 // OpenMP [2.8.1, simd construct, Description]
4765 // The parameter of the safelen clause must be a constant
4766 // positive integer expression.
4767 ExprResult Safelen = VerifyPositiveIntegerConstantInClause(Len, OMPC_safelen);
4768 if (Safelen.isInvalid())
4770 return new (Context)
4771 OMPSafelenClause(Safelen.get(), StartLoc, LParenLoc, EndLoc);
4774 OMPClause *Sema::ActOnOpenMPCollapseClause(Expr *NumForLoops,
4775 SourceLocation StartLoc,
4776 SourceLocation LParenLoc,
4777 SourceLocation EndLoc) {
4778 // OpenMP [2.7.1, loop construct, Description]
4779 // OpenMP [2.8.1, simd construct, Description]
4780 // OpenMP [2.9.6, distribute construct, Description]
4781 // The parameter of the collapse clause must be a constant
4782 // positive integer expression.
4783 ExprResult NumForLoopsResult =
4784 VerifyPositiveIntegerConstantInClause(NumForLoops, OMPC_collapse);
4785 if (NumForLoopsResult.isInvalid())
4787 return new (Context)
4788 OMPCollapseClause(NumForLoopsResult.get(), StartLoc, LParenLoc, EndLoc);
4791 OMPClause *Sema::ActOnOpenMPSimpleClause(
4792 OpenMPClauseKind Kind, unsigned Argument, SourceLocation ArgumentLoc,
4793 SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc) {
4794 OMPClause *Res = nullptr;
4798 ActOnOpenMPDefaultClause(static_cast<OpenMPDefaultClauseKind>(Argument),
4799 ArgumentLoc, StartLoc, LParenLoc, EndLoc);
4801 case OMPC_proc_bind:
4802 Res = ActOnOpenMPProcBindClause(
4803 static_cast<OpenMPProcBindClauseKind>(Argument), ArgumentLoc, StartLoc,
4808 case OMPC_num_threads:
4813 case OMPC_firstprivate:
4814 case OMPC_lastprivate:
4816 case OMPC_reduction:
4820 case OMPC_copyprivate:
4824 case OMPC_mergeable:
4825 case OMPC_threadprivate:
4834 llvm_unreachable("Clause is not allowed.");
4839 OMPClause *Sema::ActOnOpenMPDefaultClause(OpenMPDefaultClauseKind Kind,
4840 SourceLocation KindKwLoc,
4841 SourceLocation StartLoc,
4842 SourceLocation LParenLoc,
4843 SourceLocation EndLoc) {
4844 if (Kind == OMPC_DEFAULT_unknown) {
4846 static_assert(OMPC_DEFAULT_unknown > 0,
4847 "OMPC_DEFAULT_unknown not greater than 0");
4848 std::string Sep(", ");
4849 for (unsigned i = 0; i < OMPC_DEFAULT_unknown; ++i) {
4851 Values += getOpenMPSimpleClauseTypeName(OMPC_default, i);
4854 case OMPC_DEFAULT_unknown - 2:
4857 case OMPC_DEFAULT_unknown - 1:
4864 Diag(KindKwLoc, diag::err_omp_unexpected_clause_value)
4865 << Values << getOpenMPClauseName(OMPC_default);
4869 case OMPC_DEFAULT_none:
4870 DSAStack->setDefaultDSANone(KindKwLoc);
4872 case OMPC_DEFAULT_shared:
4873 DSAStack->setDefaultDSAShared(KindKwLoc);
4875 case OMPC_DEFAULT_unknown:
4876 llvm_unreachable("Clause kind is not allowed.");
4879 return new (Context)
4880 OMPDefaultClause(Kind, KindKwLoc, StartLoc, LParenLoc, EndLoc);
4883 OMPClause *Sema::ActOnOpenMPProcBindClause(OpenMPProcBindClauseKind Kind,
4884 SourceLocation KindKwLoc,
4885 SourceLocation StartLoc,
4886 SourceLocation LParenLoc,
4887 SourceLocation EndLoc) {
4888 if (Kind == OMPC_PROC_BIND_unknown) {
4890 std::string Sep(", ");
4891 for (unsigned i = 0; i < OMPC_PROC_BIND_unknown; ++i) {
4893 Values += getOpenMPSimpleClauseTypeName(OMPC_proc_bind, i);
4896 case OMPC_PROC_BIND_unknown - 2:
4899 case OMPC_PROC_BIND_unknown - 1:
4906 Diag(KindKwLoc, diag::err_omp_unexpected_clause_value)
4907 << Values << getOpenMPClauseName(OMPC_proc_bind);
4910 return new (Context)
4911 OMPProcBindClause(Kind, KindKwLoc, StartLoc, LParenLoc, EndLoc);
4914 OMPClause *Sema::ActOnOpenMPSingleExprWithArgClause(
4915 OpenMPClauseKind Kind, unsigned Argument, Expr *Expr,
4916 SourceLocation StartLoc, SourceLocation LParenLoc,
4917 SourceLocation ArgumentLoc, SourceLocation CommaLoc,
4918 SourceLocation EndLoc) {
4919 OMPClause *Res = nullptr;
4922 Res = ActOnOpenMPScheduleClause(
4923 static_cast<OpenMPScheduleClauseKind>(Argument), Expr, StartLoc,
4924 LParenLoc, ArgumentLoc, CommaLoc, EndLoc);
4928 case OMPC_num_threads:
4932 case OMPC_proc_bind:
4934 case OMPC_firstprivate:
4935 case OMPC_lastprivate:
4937 case OMPC_reduction:
4941 case OMPC_copyprivate:
4945 case OMPC_mergeable:
4946 case OMPC_threadprivate:
4955 llvm_unreachable("Clause is not allowed.");
4960 OMPClause *Sema::ActOnOpenMPScheduleClause(
4961 OpenMPScheduleClauseKind Kind, Expr *ChunkSize, SourceLocation StartLoc,
4962 SourceLocation LParenLoc, SourceLocation KindLoc, SourceLocation CommaLoc,
4963 SourceLocation EndLoc) {
4964 if (Kind == OMPC_SCHEDULE_unknown) {
4966 std::string Sep(", ");
4967 for (unsigned i = 0; i < OMPC_SCHEDULE_unknown; ++i) {
4969 Values += getOpenMPSimpleClauseTypeName(OMPC_schedule, i);
4972 case OMPC_SCHEDULE_unknown - 2:
4975 case OMPC_SCHEDULE_unknown - 1:
4982 Diag(KindLoc, diag::err_omp_unexpected_clause_value)
4983 << Values << getOpenMPClauseName(OMPC_schedule);
4986 Expr *ValExpr = ChunkSize;
4987 Expr *HelperValExpr = nullptr;
4989 if (!ChunkSize->isValueDependent() && !ChunkSize->isTypeDependent() &&
4990 !ChunkSize->isInstantiationDependent() &&
4991 !ChunkSize->containsUnexpandedParameterPack()) {
4992 SourceLocation ChunkSizeLoc = ChunkSize->getLocStart();
4994 PerformOpenMPImplicitIntegerConversion(ChunkSizeLoc, ChunkSize);
4995 if (Val.isInvalid())
4998 ValExpr = Val.get();
5000 // OpenMP [2.7.1, Restrictions]
5001 // chunk_size must be a loop invariant integer expression with a positive
5003 llvm::APSInt Result;
5004 if (ValExpr->isIntegerConstantExpr(Result, Context)) {
5005 if (Result.isSigned() && !Result.isStrictlyPositive()) {
5006 Diag(ChunkSizeLoc, diag::err_omp_negative_expression_in_clause)
5007 << "schedule" << ChunkSize->getSourceRange();
5010 } else if (isParallelOrTaskRegion(DSAStack->getCurrentDirective())) {
5011 auto *ImpVar = buildVarDecl(*this, ChunkSize->getExprLoc(),
5012 ChunkSize->getType(), ".chunk.");
5013 auto *ImpVarRef = buildDeclRefExpr(*this, ImpVar, ChunkSize->getType(),
5014 ChunkSize->getExprLoc(),
5015 /*RefersToCapture=*/true);
5016 HelperValExpr = ImpVarRef;
5021 return new (Context) OMPScheduleClause(StartLoc, LParenLoc, KindLoc, CommaLoc,
5022 EndLoc, Kind, ValExpr, HelperValExpr);
5025 OMPClause *Sema::ActOnOpenMPClause(OpenMPClauseKind Kind,
5026 SourceLocation StartLoc,
5027 SourceLocation EndLoc) {
5028 OMPClause *Res = nullptr;
5031 Res = ActOnOpenMPOrderedClause(StartLoc, EndLoc);
5034 Res = ActOnOpenMPNowaitClause(StartLoc, EndLoc);
5037 Res = ActOnOpenMPUntiedClause(StartLoc, EndLoc);
5039 case OMPC_mergeable:
5040 Res = ActOnOpenMPMergeableClause(StartLoc, EndLoc);
5043 Res = ActOnOpenMPReadClause(StartLoc, EndLoc);
5046 Res = ActOnOpenMPWriteClause(StartLoc, EndLoc);
5049 Res = ActOnOpenMPUpdateClause(StartLoc, EndLoc);
5052 Res = ActOnOpenMPCaptureClause(StartLoc, EndLoc);
5055 Res = ActOnOpenMPSeqCstClause(StartLoc, EndLoc);
5059 case OMPC_num_threads:
5064 case OMPC_firstprivate:
5065 case OMPC_lastprivate:
5067 case OMPC_reduction:
5071 case OMPC_copyprivate:
5073 case OMPC_proc_bind:
5074 case OMPC_threadprivate:
5078 llvm_unreachable("Clause is not allowed.");
5083 OMPClause *Sema::ActOnOpenMPOrderedClause(SourceLocation StartLoc,
5084 SourceLocation EndLoc) {
5085 DSAStack->setOrderedRegion();
5086 return new (Context) OMPOrderedClause(StartLoc, EndLoc);
5089 OMPClause *Sema::ActOnOpenMPNowaitClause(SourceLocation StartLoc,
5090 SourceLocation EndLoc) {
5091 DSAStack->setNowaitRegion();
5092 return new (Context) OMPNowaitClause(StartLoc, EndLoc);
5095 OMPClause *Sema::ActOnOpenMPUntiedClause(SourceLocation StartLoc,
5096 SourceLocation EndLoc) {
5097 return new (Context) OMPUntiedClause(StartLoc, EndLoc);
5100 OMPClause *Sema::ActOnOpenMPMergeableClause(SourceLocation StartLoc,
5101 SourceLocation EndLoc) {
5102 return new (Context) OMPMergeableClause(StartLoc, EndLoc);
5105 OMPClause *Sema::ActOnOpenMPReadClause(SourceLocation StartLoc,
5106 SourceLocation EndLoc) {
5107 return new (Context) OMPReadClause(StartLoc, EndLoc);
5110 OMPClause *Sema::ActOnOpenMPWriteClause(SourceLocation StartLoc,
5111 SourceLocation EndLoc) {
5112 return new (Context) OMPWriteClause(StartLoc, EndLoc);
5115 OMPClause *Sema::ActOnOpenMPUpdateClause(SourceLocation StartLoc,
5116 SourceLocation EndLoc) {
5117 return new (Context) OMPUpdateClause(StartLoc, EndLoc);
5120 OMPClause *Sema::ActOnOpenMPCaptureClause(SourceLocation StartLoc,
5121 SourceLocation EndLoc) {
5122 return new (Context) OMPCaptureClause(StartLoc, EndLoc);
5125 OMPClause *Sema::ActOnOpenMPSeqCstClause(SourceLocation StartLoc,
5126 SourceLocation EndLoc) {
5127 return new (Context) OMPSeqCstClause(StartLoc, EndLoc);
5130 OMPClause *Sema::ActOnOpenMPVarListClause(
5131 OpenMPClauseKind Kind, ArrayRef<Expr *> VarList, Expr *TailExpr,
5132 SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation ColonLoc,
5133 SourceLocation EndLoc, CXXScopeSpec &ReductionIdScopeSpec,
5134 const DeclarationNameInfo &ReductionId, OpenMPDependClauseKind DepKind,
5135 SourceLocation DepLoc) {
5136 OMPClause *Res = nullptr;
5139 Res = ActOnOpenMPPrivateClause(VarList, StartLoc, LParenLoc, EndLoc);
5141 case OMPC_firstprivate:
5142 Res = ActOnOpenMPFirstprivateClause(VarList, StartLoc, LParenLoc, EndLoc);
5144 case OMPC_lastprivate:
5145 Res = ActOnOpenMPLastprivateClause(VarList, StartLoc, LParenLoc, EndLoc);
5148 Res = ActOnOpenMPSharedClause(VarList, StartLoc, LParenLoc, EndLoc);
5150 case OMPC_reduction:
5151 Res = ActOnOpenMPReductionClause(VarList, StartLoc, LParenLoc, ColonLoc,
5152 EndLoc, ReductionIdScopeSpec, ReductionId);
5155 Res = ActOnOpenMPLinearClause(VarList, TailExpr, StartLoc, LParenLoc,
5159 Res = ActOnOpenMPAlignedClause(VarList, TailExpr, StartLoc, LParenLoc,
5163 Res = ActOnOpenMPCopyinClause(VarList, StartLoc, LParenLoc, EndLoc);
5165 case OMPC_copyprivate:
5166 Res = ActOnOpenMPCopyprivateClause(VarList, StartLoc, LParenLoc, EndLoc);
5169 Res = ActOnOpenMPFlushClause(VarList, StartLoc, LParenLoc, EndLoc);
5172 Res = ActOnOpenMPDependClause(DepKind, DepLoc, ColonLoc, VarList, StartLoc,
5177 case OMPC_num_threads:
5181 case OMPC_proc_bind:
5186 case OMPC_mergeable:
5187 case OMPC_threadprivate:
5194 llvm_unreachable("Clause is not allowed.");
5199 OMPClause *Sema::ActOnOpenMPPrivateClause(ArrayRef<Expr *> VarList,
5200 SourceLocation StartLoc,
5201 SourceLocation LParenLoc,
5202 SourceLocation EndLoc) {
5203 SmallVector<Expr *, 8> Vars;
5204 SmallVector<Expr *, 8> PrivateCopies;
5205 for (auto &RefExpr : VarList) {
5206 assert(RefExpr && "NULL expr in OpenMP private clause.");
5207 if (isa<DependentScopeDeclRefExpr>(RefExpr)) {
5208 // It will be analyzed later.
5209 Vars.push_back(RefExpr);
5210 PrivateCopies.push_back(nullptr);
5214 SourceLocation ELoc = RefExpr->getExprLoc();
5215 // OpenMP [2.1, C/C++]
5216 // A list item is a variable name.
5217 // OpenMP [2.9.3.3, Restrictions, p.1]
5218 // A variable that is part of another variable (as an array or
5219 // structure element) cannot appear in a private clause.
5220 DeclRefExpr *DE = dyn_cast_or_null<DeclRefExpr>(RefExpr);
5221 if (!DE || !isa<VarDecl>(DE->getDecl())) {
5222 Diag(ELoc, diag::err_omp_expected_var_name) << RefExpr->getSourceRange();
5225 Decl *D = DE->getDecl();
5226 VarDecl *VD = cast<VarDecl>(D);
5228 QualType Type = VD->getType();
5229 if (Type->isDependentType() || Type->isInstantiationDependentType()) {
5230 // It will be analyzed later.
5232 PrivateCopies.push_back(nullptr);
5236 // OpenMP [2.9.3.3, Restrictions, C/C++, p.3]
5237 // A variable that appears in a private clause must not have an incomplete
5238 // type or a reference type.
5239 if (RequireCompleteType(ELoc, Type,
5240 diag::err_omp_private_incomplete_type)) {
5243 if (Type->isReferenceType()) {
5244 Diag(ELoc, diag::err_omp_clause_ref_type_arg)
5245 << getOpenMPClauseName(OMPC_private) << Type;
5247 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
5248 Diag(VD->getLocation(),
5249 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
5254 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
5256 // Variables with the predetermined data-sharing attributes may not be
5257 // listed in data-sharing attributes clauses, except for the cases
5258 // listed below. For these exceptions only, listing a predetermined
5259 // variable in a data-sharing attribute clause is allowed and overrides
5260 // the variable's predetermined data-sharing attributes.
5261 DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(VD, false);
5262 if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_private) {
5263 Diag(ELoc, diag::err_omp_wrong_dsa) << getOpenMPClauseName(DVar.CKind)
5264 << getOpenMPClauseName(OMPC_private);
5265 ReportOriginalDSA(*this, DSAStack, VD, DVar);
5269 // Variably modified types are not supported for tasks.
5270 if (!Type->isAnyPointerType() && Type->isVariablyModifiedType() &&
5271 DSAStack->getCurrentDirective() == OMPD_task) {
5272 Diag(ELoc, diag::err_omp_variably_modified_type_not_supported)
5273 << getOpenMPClauseName(OMPC_private) << Type
5274 << getOpenMPDirectiveName(DSAStack->getCurrentDirective());
5276 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
5277 Diag(VD->getLocation(),
5278 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
5283 // OpenMP [2.9.3.3, Restrictions, C/C++, p.1]
5284 // A variable of class type (or array thereof) that appears in a private
5285 // clause requires an accessible, unambiguous default constructor for the
5287 // Generate helper private variable and initialize it with the default
5288 // value. The address of the original variable is replaced by the address of
5289 // the new private variable in CodeGen. This new variable is not added to
5290 // IdResolver, so the code in the OpenMP region uses original variable for
5291 // proper diagnostics.
5292 Type = Type.getUnqualifiedType();
5293 auto VDPrivate = buildVarDecl(*this, DE->getExprLoc(), Type, VD->getName());
5294 ActOnUninitializedDecl(VDPrivate, /*TypeMayContainAuto=*/false);
5295 if (VDPrivate->isInvalidDecl())
5297 auto VDPrivateRefExpr = buildDeclRefExpr(
5298 *this, VDPrivate, DE->getType().getUnqualifiedType(), DE->getExprLoc());
5300 DSAStack->addDSA(VD, DE, OMPC_private);
5302 PrivateCopies.push_back(VDPrivateRefExpr);
5308 return OMPPrivateClause::Create(Context, StartLoc, LParenLoc, EndLoc, Vars,
5313 class DiagsUninitializedSeveretyRAII {
5315 DiagnosticsEngine &Diags;
5316 SourceLocation SavedLoc;
5320 DiagsUninitializedSeveretyRAII(DiagnosticsEngine &Diags, SourceLocation Loc,
5322 : Diags(Diags), SavedLoc(Loc), IsIgnored(IsIgnored) {
5324 Diags.setSeverity(/*Diag*/ diag::warn_uninit_self_reference_in_init,
5325 /*Map*/ diag::Severity::Ignored, Loc);
5328 ~DiagsUninitializedSeveretyRAII() {
5330 Diags.popMappings(SavedLoc);
5335 OMPClause *Sema::ActOnOpenMPFirstprivateClause(ArrayRef<Expr *> VarList,
5336 SourceLocation StartLoc,
5337 SourceLocation LParenLoc,
5338 SourceLocation EndLoc) {
5339 SmallVector<Expr *, 8> Vars;
5340 SmallVector<Expr *, 8> PrivateCopies;
5341 SmallVector<Expr *, 8> Inits;
5342 bool IsImplicitClause =
5343 StartLoc.isInvalid() && LParenLoc.isInvalid() && EndLoc.isInvalid();
5344 auto ImplicitClauseLoc = DSAStack->getConstructLoc();
5346 for (auto &RefExpr : VarList) {
5347 assert(RefExpr && "NULL expr in OpenMP firstprivate clause.");
5348 if (isa<DependentScopeDeclRefExpr>(RefExpr)) {
5349 // It will be analyzed later.
5350 Vars.push_back(RefExpr);
5351 PrivateCopies.push_back(nullptr);
5352 Inits.push_back(nullptr);
5356 SourceLocation ELoc =
5357 IsImplicitClause ? ImplicitClauseLoc : RefExpr->getExprLoc();
5358 // OpenMP [2.1, C/C++]
5359 // A list item is a variable name.
5360 // OpenMP [2.9.3.3, Restrictions, p.1]
5361 // A variable that is part of another variable (as an array or
5362 // structure element) cannot appear in a private clause.
5363 DeclRefExpr *DE = dyn_cast_or_null<DeclRefExpr>(RefExpr);
5364 if (!DE || !isa<VarDecl>(DE->getDecl())) {
5365 Diag(ELoc, diag::err_omp_expected_var_name) << RefExpr->getSourceRange();
5368 Decl *D = DE->getDecl();
5369 VarDecl *VD = cast<VarDecl>(D);
5371 QualType Type = VD->getType();
5372 if (Type->isDependentType() || Type->isInstantiationDependentType()) {
5373 // It will be analyzed later.
5375 PrivateCopies.push_back(nullptr);
5376 Inits.push_back(nullptr);
5380 // OpenMP [2.9.3.3, Restrictions, C/C++, p.3]
5381 // A variable that appears in a private clause must not have an incomplete
5382 // type or a reference type.
5383 if (RequireCompleteType(ELoc, Type,
5384 diag::err_omp_firstprivate_incomplete_type)) {
5387 if (Type->isReferenceType()) {
5388 if (IsImplicitClause) {
5389 Diag(ImplicitClauseLoc,
5390 diag::err_omp_task_predetermined_firstprivate_ref_type_arg)
5392 Diag(RefExpr->getExprLoc(), diag::note_used_here);
5394 Diag(ELoc, diag::err_omp_clause_ref_type_arg)
5395 << getOpenMPClauseName(OMPC_firstprivate) << Type;
5398 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
5399 Diag(VD->getLocation(),
5400 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
5405 // OpenMP [2.9.3.4, Restrictions, C/C++, p.1]
5406 // A variable of class type (or array thereof) that appears in a private
5407 // clause requires an accessible, unambiguous copy constructor for the
5409 auto ElemType = Context.getBaseElementType(Type).getNonReferenceType();
5411 // If an implicit firstprivate variable found it was checked already.
5412 if (!IsImplicitClause) {
5413 DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(VD, false);
5414 bool IsConstant = ElemType.isConstant(Context);
5415 // OpenMP [2.4.13, Data-sharing Attribute Clauses]
5416 // A list item that specifies a given variable may not appear in more
5417 // than one clause on the same directive, except that a variable may be
5418 // specified in both firstprivate and lastprivate clauses.
5419 if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_firstprivate &&
5420 DVar.CKind != OMPC_lastprivate && DVar.RefExpr) {
5421 Diag(ELoc, diag::err_omp_wrong_dsa)
5422 << getOpenMPClauseName(DVar.CKind)
5423 << getOpenMPClauseName(OMPC_firstprivate);
5424 ReportOriginalDSA(*this, DSAStack, VD, DVar);
5428 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
5430 // Variables with the predetermined data-sharing attributes may not be
5431 // listed in data-sharing attributes clauses, except for the cases
5432 // listed below. For these exceptions only, listing a predetermined
5433 // variable in a data-sharing attribute clause is allowed and overrides
5434 // the variable's predetermined data-sharing attributes.
5435 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
5436 // in a Construct, C/C++, p.2]
5437 // Variables with const-qualified type having no mutable member may be
5438 // listed in a firstprivate clause, even if they are static data members.
5439 if (!(IsConstant || VD->isStaticDataMember()) && !DVar.RefExpr &&
5440 DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_shared) {
5441 Diag(ELoc, diag::err_omp_wrong_dsa)
5442 << getOpenMPClauseName(DVar.CKind)
5443 << getOpenMPClauseName(OMPC_firstprivate);
5444 ReportOriginalDSA(*this, DSAStack, VD, DVar);
5448 OpenMPDirectiveKind CurrDir = DSAStack->getCurrentDirective();
5449 // OpenMP [2.9.3.4, Restrictions, p.2]
5450 // A list item that is private within a parallel region must not appear
5451 // in a firstprivate clause on a worksharing construct if any of the
5452 // worksharing regions arising from the worksharing construct ever bind
5453 // to any of the parallel regions arising from the parallel construct.
5454 if (isOpenMPWorksharingDirective(CurrDir) &&
5455 !isOpenMPParallelDirective(CurrDir)) {
5456 DVar = DSAStack->getImplicitDSA(VD, true);
5457 if (DVar.CKind != OMPC_shared &&
5458 (isOpenMPParallelDirective(DVar.DKind) ||
5459 DVar.DKind == OMPD_unknown)) {
5460 Diag(ELoc, diag::err_omp_required_access)
5461 << getOpenMPClauseName(OMPC_firstprivate)
5462 << getOpenMPClauseName(OMPC_shared);
5463 ReportOriginalDSA(*this, DSAStack, VD, DVar);
5467 // OpenMP [2.9.3.4, Restrictions, p.3]
5468 // A list item that appears in a reduction clause of a parallel construct
5469 // must not appear in a firstprivate clause on a worksharing or task
5470 // construct if any of the worksharing or task regions arising from the
5471 // worksharing or task construct ever bind to any of the parallel regions
5472 // arising from the parallel construct.
5473 // OpenMP [2.9.3.4, Restrictions, p.4]
5474 // A list item that appears in a reduction clause in worksharing
5475 // construct must not appear in a firstprivate clause in a task construct
5476 // encountered during execution of any of the worksharing regions arising
5477 // from the worksharing construct.
5478 if (CurrDir == OMPD_task) {
5480 DSAStack->hasInnermostDSA(VD, MatchesAnyClause(OMPC_reduction),
5481 [](OpenMPDirectiveKind K) -> bool {
5482 return isOpenMPParallelDirective(K) ||
5483 isOpenMPWorksharingDirective(K);
5486 if (DVar.CKind == OMPC_reduction &&
5487 (isOpenMPParallelDirective(DVar.DKind) ||
5488 isOpenMPWorksharingDirective(DVar.DKind))) {
5489 Diag(ELoc, diag::err_omp_parallel_reduction_in_task_firstprivate)
5490 << getOpenMPDirectiveName(DVar.DKind);
5491 ReportOriginalDSA(*this, DSAStack, VD, DVar);
5497 // Variably modified types are not supported for tasks.
5498 if (!Type->isAnyPointerType() && Type->isVariablyModifiedType() &&
5499 DSAStack->getCurrentDirective() == OMPD_task) {
5500 Diag(ELoc, diag::err_omp_variably_modified_type_not_supported)
5501 << getOpenMPClauseName(OMPC_firstprivate) << Type
5502 << getOpenMPDirectiveName(DSAStack->getCurrentDirective());
5504 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
5505 Diag(VD->getLocation(),
5506 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
5511 Type = Type.getUnqualifiedType();
5512 auto VDPrivate = buildVarDecl(*this, ELoc, Type, VD->getName());
5513 // Generate helper private variable and initialize it with the value of the
5514 // original variable. The address of the original variable is replaced by
5515 // the address of the new private variable in the CodeGen. This new variable
5516 // is not added to IdResolver, so the code in the OpenMP region uses
5517 // original variable for proper diagnostics and variable capturing.
5518 Expr *VDInitRefExpr = nullptr;
5519 // For arrays generate initializer for single element and replace it by the
5520 // original array element in CodeGen.
5521 if (Type->isArrayType()) {
5523 buildVarDecl(*this, DE->getExprLoc(), ElemType, VD->getName());
5524 VDInitRefExpr = buildDeclRefExpr(*this, VDInit, ElemType, ELoc);
5525 auto Init = DefaultLvalueConversion(VDInitRefExpr).get();
5526 ElemType = ElemType.getUnqualifiedType();
5527 auto *VDInitTemp = buildVarDecl(*this, DE->getLocStart(), ElemType,
5528 ".firstprivate.temp");
5529 InitializedEntity Entity =
5530 InitializedEntity::InitializeVariable(VDInitTemp);
5531 InitializationKind Kind = InitializationKind::CreateCopy(ELoc, ELoc);
5533 InitializationSequence InitSeq(*this, Entity, Kind, Init);
5534 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Init);
5535 if (Result.isInvalid())
5536 VDPrivate->setInvalidDecl();
5538 VDPrivate->setInit(Result.getAs<Expr>());
5541 buildVarDecl(*this, DE->getLocStart(), Type, ".firstprivate.temp");
5543 buildDeclRefExpr(*this, VDInit, DE->getType(), DE->getExprLoc());
5544 AddInitializerToDecl(VDPrivate,
5545 DefaultLvalueConversion(VDInitRefExpr).get(),
5546 /*DirectInit=*/false, /*TypeMayContainAuto=*/false);
5548 if (VDPrivate->isInvalidDecl()) {
5549 if (IsImplicitClause) {
5550 Diag(DE->getExprLoc(),
5551 diag::note_omp_task_predetermined_firstprivate_here);
5555 CurContext->addDecl(VDPrivate);
5556 auto VDPrivateRefExpr = buildDeclRefExpr(
5557 *this, VDPrivate, DE->getType().getUnqualifiedType(), DE->getExprLoc());
5558 DSAStack->addDSA(VD, DE, OMPC_firstprivate);
5560 PrivateCopies.push_back(VDPrivateRefExpr);
5561 Inits.push_back(VDInitRefExpr);
5567 return OMPFirstprivateClause::Create(Context, StartLoc, LParenLoc, EndLoc,
5568 Vars, PrivateCopies, Inits);
5571 OMPClause *Sema::ActOnOpenMPLastprivateClause(ArrayRef<Expr *> VarList,
5572 SourceLocation StartLoc,
5573 SourceLocation LParenLoc,
5574 SourceLocation EndLoc) {
5575 SmallVector<Expr *, 8> Vars;
5576 SmallVector<Expr *, 8> SrcExprs;
5577 SmallVector<Expr *, 8> DstExprs;
5578 SmallVector<Expr *, 8> AssignmentOps;
5579 for (auto &RefExpr : VarList) {
5580 assert(RefExpr && "NULL expr in OpenMP lastprivate clause.");
5581 if (isa<DependentScopeDeclRefExpr>(RefExpr)) {
5582 // It will be analyzed later.
5583 Vars.push_back(RefExpr);
5584 SrcExprs.push_back(nullptr);
5585 DstExprs.push_back(nullptr);
5586 AssignmentOps.push_back(nullptr);
5590 SourceLocation ELoc = RefExpr->getExprLoc();
5591 // OpenMP [2.1, C/C++]
5592 // A list item is a variable name.
5593 // OpenMP [2.14.3.5, Restrictions, p.1]
5594 // A variable that is part of another variable (as an array or structure
5595 // element) cannot appear in a lastprivate clause.
5596 DeclRefExpr *DE = dyn_cast_or_null<DeclRefExpr>(RefExpr);
5597 if (!DE || !isa<VarDecl>(DE->getDecl())) {
5598 Diag(ELoc, diag::err_omp_expected_var_name) << RefExpr->getSourceRange();
5601 Decl *D = DE->getDecl();
5602 VarDecl *VD = cast<VarDecl>(D);
5604 QualType Type = VD->getType();
5605 if (Type->isDependentType() || Type->isInstantiationDependentType()) {
5606 // It will be analyzed later.
5608 SrcExprs.push_back(nullptr);
5609 DstExprs.push_back(nullptr);
5610 AssignmentOps.push_back(nullptr);
5614 // OpenMP [2.14.3.5, Restrictions, C/C++, p.2]
5615 // A variable that appears in a lastprivate clause must not have an
5616 // incomplete type or a reference type.
5617 if (RequireCompleteType(ELoc, Type,
5618 diag::err_omp_lastprivate_incomplete_type)) {
5621 if (Type->isReferenceType()) {
5622 Diag(ELoc, diag::err_omp_clause_ref_type_arg)
5623 << getOpenMPClauseName(OMPC_lastprivate) << Type;
5625 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
5626 Diag(VD->getLocation(),
5627 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
5632 // OpenMP [2.14.1.1, Data-sharing Attribute Rules for Variables Referenced
5634 // Variables with the predetermined data-sharing attributes may not be
5635 // listed in data-sharing attributes clauses, except for the cases
5637 DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(VD, false);
5638 if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_lastprivate &&
5639 DVar.CKind != OMPC_firstprivate &&
5640 (DVar.CKind != OMPC_private || DVar.RefExpr != nullptr)) {
5641 Diag(ELoc, diag::err_omp_wrong_dsa)
5642 << getOpenMPClauseName(DVar.CKind)
5643 << getOpenMPClauseName(OMPC_lastprivate);
5644 ReportOriginalDSA(*this, DSAStack, VD, DVar);
5648 OpenMPDirectiveKind CurrDir = DSAStack->getCurrentDirective();
5649 // OpenMP [2.14.3.5, Restrictions, p.2]
5650 // A list item that is private within a parallel region, or that appears in
5651 // the reduction clause of a parallel construct, must not appear in a
5652 // lastprivate clause on a worksharing construct if any of the corresponding
5653 // worksharing regions ever binds to any of the corresponding parallel
5655 DSAStackTy::DSAVarData TopDVar = DVar;
5656 if (isOpenMPWorksharingDirective(CurrDir) &&
5657 !isOpenMPParallelDirective(CurrDir)) {
5658 DVar = DSAStack->getImplicitDSA(VD, true);
5659 if (DVar.CKind != OMPC_shared) {
5660 Diag(ELoc, diag::err_omp_required_access)
5661 << getOpenMPClauseName(OMPC_lastprivate)
5662 << getOpenMPClauseName(OMPC_shared);
5663 ReportOriginalDSA(*this, DSAStack, VD, DVar);
5667 // OpenMP [2.14.3.5, Restrictions, C++, p.1,2]
5668 // A variable of class type (or array thereof) that appears in a
5669 // lastprivate clause requires an accessible, unambiguous default
5670 // constructor for the class type, unless the list item is also specified
5671 // in a firstprivate clause.
5672 // A variable of class type (or array thereof) that appears in a
5673 // lastprivate clause requires an accessible, unambiguous copy assignment
5674 // operator for the class type.
5675 Type = Context.getBaseElementType(Type).getNonReferenceType();
5676 auto *SrcVD = buildVarDecl(*this, DE->getLocStart(),
5677 Type.getUnqualifiedType(), ".lastprivate.src");
5678 auto *PseudoSrcExpr = buildDeclRefExpr(
5679 *this, SrcVD, Type.getUnqualifiedType(), DE->getExprLoc());
5681 buildVarDecl(*this, DE->getLocStart(), Type, ".lastprivate.dst");
5682 auto *PseudoDstExpr =
5683 buildDeclRefExpr(*this, DstVD, Type, DE->getExprLoc());
5684 // For arrays generate assignment operation for single element and replace
5685 // it by the original array element in CodeGen.
5686 auto AssignmentOp = BuildBinOp(/*S=*/nullptr, DE->getExprLoc(), BO_Assign,
5687 PseudoDstExpr, PseudoSrcExpr);
5688 if (AssignmentOp.isInvalid())
5690 AssignmentOp = ActOnFinishFullExpr(AssignmentOp.get(), DE->getExprLoc(),
5691 /*DiscardedValue=*/true);
5692 if (AssignmentOp.isInvalid())
5695 if (TopDVar.CKind != OMPC_firstprivate)
5696 DSAStack->addDSA(VD, DE, OMPC_lastprivate);
5698 SrcExprs.push_back(PseudoSrcExpr);
5699 DstExprs.push_back(PseudoDstExpr);
5700 AssignmentOps.push_back(AssignmentOp.get());
5706 return OMPLastprivateClause::Create(Context, StartLoc, LParenLoc, EndLoc,
5707 Vars, SrcExprs, DstExprs, AssignmentOps);
5710 OMPClause *Sema::ActOnOpenMPSharedClause(ArrayRef<Expr *> VarList,
5711 SourceLocation StartLoc,
5712 SourceLocation LParenLoc,
5713 SourceLocation EndLoc) {
5714 SmallVector<Expr *, 8> Vars;
5715 for (auto &RefExpr : VarList) {
5716 assert(RefExpr && "NULL expr in OpenMP shared clause.");
5717 if (isa<DependentScopeDeclRefExpr>(RefExpr)) {
5718 // It will be analyzed later.
5719 Vars.push_back(RefExpr);
5723 SourceLocation ELoc = RefExpr->getExprLoc();
5724 // OpenMP [2.1, C/C++]
5725 // A list item is a variable name.
5726 // OpenMP [2.14.3.2, Restrictions, p.1]
5727 // A variable that is part of another variable (as an array or structure
5728 // element) cannot appear in a shared unless it is a static data member
5730 DeclRefExpr *DE = dyn_cast<DeclRefExpr>(RefExpr);
5731 if (!DE || !isa<VarDecl>(DE->getDecl())) {
5732 Diag(ELoc, diag::err_omp_expected_var_name) << RefExpr->getSourceRange();
5735 Decl *D = DE->getDecl();
5736 VarDecl *VD = cast<VarDecl>(D);
5738 QualType Type = VD->getType();
5739 if (Type->isDependentType() || Type->isInstantiationDependentType()) {
5740 // It will be analyzed later.
5745 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
5747 // Variables with the predetermined data-sharing attributes may not be
5748 // listed in data-sharing attributes clauses, except for the cases
5749 // listed below. For these exceptions only, listing a predetermined
5750 // variable in a data-sharing attribute clause is allowed and overrides
5751 // the variable's predetermined data-sharing attributes.
5752 DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(VD, false);
5753 if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_shared &&
5755 Diag(ELoc, diag::err_omp_wrong_dsa) << getOpenMPClauseName(DVar.CKind)
5756 << getOpenMPClauseName(OMPC_shared);
5757 ReportOriginalDSA(*this, DSAStack, VD, DVar);
5761 DSAStack->addDSA(VD, DE, OMPC_shared);
5768 return OMPSharedClause::Create(Context, StartLoc, LParenLoc, EndLoc, Vars);
5772 class DSARefChecker : public StmtVisitor<DSARefChecker, bool> {
5776 bool VisitDeclRefExpr(DeclRefExpr *E) {
5777 if (VarDecl *VD = dyn_cast<VarDecl>(E->getDecl())) {
5778 DSAStackTy::DSAVarData DVar = Stack->getTopDSA(VD, false);
5779 if (DVar.CKind == OMPC_shared && !DVar.RefExpr)
5781 if (DVar.CKind != OMPC_unknown)
5783 DSAStackTy::DSAVarData DVarPrivate =
5784 Stack->hasDSA(VD, isOpenMPPrivate, MatchesAlways(), false);
5785 if (DVarPrivate.CKind != OMPC_unknown)
5791 bool VisitStmt(Stmt *S) {
5792 for (auto Child : S->children()) {
5793 if (Child && Visit(Child))
5798 explicit DSARefChecker(DSAStackTy *S) : Stack(S) {}
5802 OMPClause *Sema::ActOnOpenMPReductionClause(
5803 ArrayRef<Expr *> VarList, SourceLocation StartLoc, SourceLocation LParenLoc,
5804 SourceLocation ColonLoc, SourceLocation EndLoc,
5805 CXXScopeSpec &ReductionIdScopeSpec,
5806 const DeclarationNameInfo &ReductionId) {
5807 // TODO: Allow scope specification search when 'declare reduction' is
5809 assert(ReductionIdScopeSpec.isEmpty() &&
5810 "No support for scoped reduction identifiers yet.");
5812 auto DN = ReductionId.getName();
5813 auto OOK = DN.getCXXOverloadedOperator();
5814 BinaryOperatorKind BOK = BO_Comma;
5816 // OpenMP [2.14.3.6, reduction clause]
5818 // reduction-identifier is either an identifier or one of the following
5819 // operators: +, -, *, &, |, ^, && and ||
5821 // reduction-identifier is either an id-expression or one of the following
5822 // operators: +, -, *, &, |, ^, && and ||
5823 // FIXME: Only 'min' and 'max' identifiers are supported for now.
5850 case OO_Array_Delete:
5859 case OO_GreaterEqual:
5864 case OO_PercentEqual:
5869 case OO_GreaterGreater:
5870 case OO_LessLessEqual:
5871 case OO_GreaterGreaterEqual:
5873 case OO_ExclaimEqual:
5881 case OO_Conditional:
5882 case NUM_OVERLOADED_OPERATORS:
5883 llvm_unreachable("Unexpected reduction identifier");
5885 if (auto II = DN.getAsIdentifierInfo()) {
5886 if (II->isStr("max"))
5888 else if (II->isStr("min"))
5893 SourceRange ReductionIdRange;
5894 if (ReductionIdScopeSpec.isValid()) {
5895 ReductionIdRange.setBegin(ReductionIdScopeSpec.getBeginLoc());
5897 ReductionIdRange.setEnd(ReductionId.getEndLoc());
5898 if (BOK == BO_Comma) {
5899 // Not allowed reduction identifier is found.
5900 Diag(ReductionId.getLocStart(), diag::err_omp_unknown_reduction_identifier)
5901 << ReductionIdRange;
5905 SmallVector<Expr *, 8> Vars;
5906 SmallVector<Expr *, 8> LHSs;
5907 SmallVector<Expr *, 8> RHSs;
5908 SmallVector<Expr *, 8> ReductionOps;
5909 for (auto RefExpr : VarList) {
5910 assert(RefExpr && "nullptr expr in OpenMP reduction clause.");
5911 if (isa<DependentScopeDeclRefExpr>(RefExpr)) {
5912 // It will be analyzed later.
5913 Vars.push_back(RefExpr);
5914 LHSs.push_back(nullptr);
5915 RHSs.push_back(nullptr);
5916 ReductionOps.push_back(nullptr);
5920 if (RefExpr->isTypeDependent() || RefExpr->isValueDependent() ||
5921 RefExpr->isInstantiationDependent() ||
5922 RefExpr->containsUnexpandedParameterPack()) {
5923 // It will be analyzed later.
5924 Vars.push_back(RefExpr);
5925 LHSs.push_back(nullptr);
5926 RHSs.push_back(nullptr);
5927 ReductionOps.push_back(nullptr);
5931 auto ELoc = RefExpr->getExprLoc();
5932 auto ERange = RefExpr->getSourceRange();
5933 // OpenMP [2.1, C/C++]
5934 // A list item is a variable or array section, subject to the restrictions
5935 // specified in Section 2.4 on page 42 and in each of the sections
5936 // describing clauses and directives for which a list appears.
5937 // OpenMP [2.14.3.3, Restrictions, p.1]
5938 // A variable that is part of another variable (as an array or
5939 // structure element) cannot appear in a private clause.
5940 auto DE = dyn_cast<DeclRefExpr>(RefExpr);
5941 if (!DE || !isa<VarDecl>(DE->getDecl())) {
5942 Diag(ELoc, diag::err_omp_expected_var_name) << ERange;
5945 auto D = DE->getDecl();
5946 auto VD = cast<VarDecl>(D);
5947 auto Type = VD->getType();
5948 // OpenMP [2.9.3.3, Restrictions, C/C++, p.3]
5949 // A variable that appears in a private clause must not have an incomplete
5950 // type or a reference type.
5951 if (RequireCompleteType(ELoc, Type,
5952 diag::err_omp_reduction_incomplete_type))
5954 // OpenMP [2.14.3.6, reduction clause, Restrictions]
5955 // Arrays may not appear in a reduction clause.
5956 if (Type.getNonReferenceType()->isArrayType()) {
5957 Diag(ELoc, diag::err_omp_reduction_type_array) << Type << ERange;
5959 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
5960 Diag(VD->getLocation(),
5961 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
5965 // OpenMP [2.14.3.6, reduction clause, Restrictions]
5966 // A list item that appears in a reduction clause must not be
5968 if (Type.getNonReferenceType().isConstant(Context)) {
5969 Diag(ELoc, diag::err_omp_const_variable)
5970 << getOpenMPClauseName(OMPC_reduction) << Type << ERange;
5972 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
5973 Diag(VD->getLocation(),
5974 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
5978 // OpenMP [2.9.3.6, Restrictions, C/C++, p.4]
5979 // If a list-item is a reference type then it must bind to the same object
5980 // for all threads of the team.
5981 VarDecl *VDDef = VD->getDefinition();
5982 if (Type->isReferenceType() && VDDef) {
5983 DSARefChecker Check(DSAStack);
5984 if (Check.Visit(VDDef->getInit())) {
5985 Diag(ELoc, diag::err_omp_reduction_ref_type_arg) << ERange;
5986 Diag(VDDef->getLocation(), diag::note_defined_here) << VDDef;
5990 // OpenMP [2.14.3.6, reduction clause, Restrictions]
5991 // The type of a list item that appears in a reduction clause must be valid
5992 // for the reduction-identifier. For a max or min reduction in C, the type
5993 // of the list item must be an allowed arithmetic data type: char, int,
5994 // float, double, or _Bool, possibly modified with long, short, signed, or
5995 // unsigned. For a max or min reduction in C++, the type of the list item
5996 // must be an allowed arithmetic data type: char, wchar_t, int, float,
5997 // double, or bool, possibly modified with long, short, signed, or unsigned.
5998 if ((BOK == BO_GT || BOK == BO_LT) &&
5999 !(Type->isScalarType() ||
6000 (getLangOpts().CPlusPlus && Type->isArithmeticType()))) {
6001 Diag(ELoc, diag::err_omp_clause_not_arithmetic_type_arg)
6002 << getLangOpts().CPlusPlus;
6004 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
6005 Diag(VD->getLocation(),
6006 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
6010 if ((BOK == BO_OrAssign || BOK == BO_AndAssign || BOK == BO_XorAssign) &&
6011 !getLangOpts().CPlusPlus && Type->isFloatingType()) {
6012 Diag(ELoc, diag::err_omp_clause_floating_type_arg);
6014 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
6015 Diag(VD->getLocation(),
6016 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
6020 // OpenMP [2.14.1.1, Data-sharing Attribute Rules for Variables Referenced
6022 // Variables with the predetermined data-sharing attributes may not be
6023 // listed in data-sharing attributes clauses, except for the cases
6024 // listed below. For these exceptions only, listing a predetermined
6025 // variable in a data-sharing attribute clause is allowed and overrides
6026 // the variable's predetermined data-sharing attributes.
6027 // OpenMP [2.14.3.6, Restrictions, p.3]
6028 // Any number of reduction clauses can be specified on the directive,
6029 // but a list item can appear only once in the reduction clauses for that
6031 DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(VD, false);
6032 if (DVar.CKind == OMPC_reduction) {
6033 Diag(ELoc, diag::err_omp_once_referenced)
6034 << getOpenMPClauseName(OMPC_reduction);
6036 Diag(DVar.RefExpr->getExprLoc(), diag::note_omp_referenced);
6038 } else if (DVar.CKind != OMPC_unknown) {
6039 Diag(ELoc, diag::err_omp_wrong_dsa)
6040 << getOpenMPClauseName(DVar.CKind)
6041 << getOpenMPClauseName(OMPC_reduction);
6042 ReportOriginalDSA(*this, DSAStack, VD, DVar);
6046 // OpenMP [2.14.3.6, Restrictions, p.1]
6047 // A list item that appears in a reduction clause of a worksharing
6048 // construct must be shared in the parallel regions to which any of the
6049 // worksharing regions arising from the worksharing construct bind.
6050 OpenMPDirectiveKind CurrDir = DSAStack->getCurrentDirective();
6051 if (isOpenMPWorksharingDirective(CurrDir) &&
6052 !isOpenMPParallelDirective(CurrDir)) {
6053 DVar = DSAStack->getImplicitDSA(VD, true);
6054 if (DVar.CKind != OMPC_shared) {
6055 Diag(ELoc, diag::err_omp_required_access)
6056 << getOpenMPClauseName(OMPC_reduction)
6057 << getOpenMPClauseName(OMPC_shared);
6058 ReportOriginalDSA(*this, DSAStack, VD, DVar);
6062 Type = Type.getNonLValueExprType(Context).getUnqualifiedType();
6063 auto *LHSVD = buildVarDecl(*this, ELoc, Type, ".reduction.lhs");
6064 auto *RHSVD = buildVarDecl(*this, ELoc, Type, VD->getName());
6065 // Add initializer for private variable.
6066 Expr *Init = nullptr;
6072 // '+', '-', '^', '|', '||' reduction ops - initializer is '0'.
6073 if (Type->isScalarType() || Type->isAnyComplexType()) {
6074 Init = ActOnIntegerConstant(ELoc, /*Val=*/0).get();
6079 if (Type->isScalarType() || Type->isAnyComplexType()) {
6080 // '*' and '&&' reduction ops - initializer is '1'.
6081 Init = ActOnIntegerConstant(ELoc, /*Val=*/1).get();
6085 // '&' reduction op - initializer is '~0'.
6086 QualType OrigType = Type;
6087 if (auto *ComplexTy = OrigType->getAs<ComplexType>()) {
6088 Type = ComplexTy->getElementType();
6090 if (Type->isRealFloatingType()) {
6091 llvm::APFloat InitValue =
6092 llvm::APFloat::getAllOnesValue(Context.getTypeSize(Type),
6094 Init = FloatingLiteral::Create(Context, InitValue, /*isexact=*/true,
6096 } else if (Type->isScalarType()) {
6097 auto Size = Context.getTypeSize(Type);
6098 QualType IntTy = Context.getIntTypeForBitwidth(Size, /*Signed=*/0);
6099 llvm::APInt InitValue = llvm::APInt::getAllOnesValue(Size);
6100 Init = IntegerLiteral::Create(Context, InitValue, IntTy, ELoc);
6102 if (Init && OrigType->isAnyComplexType()) {
6103 // Init = 0xFFFF + 0xFFFFi;
6104 auto *Im = new (Context) ImaginaryLiteral(Init, OrigType);
6105 Init = CreateBuiltinBinOp(ELoc, BO_Add, Init, Im).get();
6112 // 'min' reduction op - initializer is 'Largest representable number in
6113 // the reduction list item type'.
6114 // 'max' reduction op - initializer is 'Least representable number in
6115 // the reduction list item type'.
6116 if (Type->isIntegerType() || Type->isPointerType()) {
6117 bool IsSigned = Type->hasSignedIntegerRepresentation();
6118 auto Size = Context.getTypeSize(Type);
6120 Context.getIntTypeForBitwidth(Size, /*Signed=*/IsSigned);
6121 llvm::APInt InitValue =
6123 ? IsSigned ? llvm::APInt::getSignedMinValue(Size)
6124 : llvm::APInt::getMinValue(Size)
6125 : IsSigned ? llvm::APInt::getSignedMaxValue(Size)
6126 : llvm::APInt::getMaxValue(Size);
6127 Init = IntegerLiteral::Create(Context, InitValue, IntTy, ELoc);
6128 if (Type->isPointerType()) {
6129 // Cast to pointer type.
6130 auto CastExpr = BuildCStyleCastExpr(
6131 SourceLocation(), Context.getTrivialTypeSourceInfo(Type, ELoc),
6132 SourceLocation(), Init);
6133 if (CastExpr.isInvalid())
6135 Init = CastExpr.get();
6137 } else if (Type->isRealFloatingType()) {
6138 llvm::APFloat InitValue = llvm::APFloat::getLargest(
6139 Context.getFloatTypeSemantics(Type), BOK != BO_LT);
6140 Init = FloatingLiteral::Create(Context, InitValue, /*isexact=*/true,
6168 llvm_unreachable("Unexpected reduction operation");
6171 AddInitializerToDecl(RHSVD, Init, /*DirectInit=*/false,
6172 /*TypeMayContainAuto=*/false);
6174 ActOnUninitializedDecl(RHSVD, /*TypeMayContainAuto=*/false);
6176 if (!RHSVD->hasInit()) {
6177 Diag(ELoc, diag::err_omp_reduction_id_not_compatible) << Type
6178 << ReductionIdRange;
6180 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
6181 Diag(VD->getLocation(),
6182 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
6186 auto *LHSDRE = buildDeclRefExpr(*this, LHSVD, Type, ELoc);
6187 auto *RHSDRE = buildDeclRefExpr(*this, RHSVD, Type, ELoc);
6188 ExprResult ReductionOp =
6189 BuildBinOp(DSAStack->getCurScope(), ReductionId.getLocStart(), BOK,
6191 if (ReductionOp.isUsable()) {
6192 if (BOK != BO_LT && BOK != BO_GT) {
6194 BuildBinOp(DSAStack->getCurScope(), ReductionId.getLocStart(),
6195 BO_Assign, LHSDRE, ReductionOp.get());
6197 auto *ConditionalOp = new (Context) ConditionalOperator(
6198 ReductionOp.get(), SourceLocation(), LHSDRE, SourceLocation(),
6199 RHSDRE, Type, VK_LValue, OK_Ordinary);
6201 BuildBinOp(DSAStack->getCurScope(), ReductionId.getLocStart(),
6202 BO_Assign, LHSDRE, ConditionalOp);
6204 if (ReductionOp.isUsable()) {
6205 ReductionOp = ActOnFinishFullExpr(ReductionOp.get());
6208 if (ReductionOp.isInvalid())
6211 DSAStack->addDSA(VD, DE, OMPC_reduction);
6213 LHSs.push_back(LHSDRE);
6214 RHSs.push_back(RHSDRE);
6215 ReductionOps.push_back(ReductionOp.get());
6221 return OMPReductionClause::Create(
6222 Context, StartLoc, LParenLoc, ColonLoc, EndLoc, Vars,
6223 ReductionIdScopeSpec.getWithLocInContext(Context), ReductionId, LHSs,
6224 RHSs, ReductionOps);
6227 OMPClause *Sema::ActOnOpenMPLinearClause(ArrayRef<Expr *> VarList, Expr *Step,
6228 SourceLocation StartLoc,
6229 SourceLocation LParenLoc,
6230 SourceLocation ColonLoc,
6231 SourceLocation EndLoc) {
6232 SmallVector<Expr *, 8> Vars;
6233 SmallVector<Expr *, 8> Inits;
6234 for (auto &RefExpr : VarList) {
6235 assert(RefExpr && "NULL expr in OpenMP linear clause.");
6236 if (isa<DependentScopeDeclRefExpr>(RefExpr)) {
6237 // It will be analyzed later.
6238 Vars.push_back(RefExpr);
6239 Inits.push_back(nullptr);
6243 // OpenMP [2.14.3.7, linear clause]
6244 // A list item that appears in a linear clause is subject to the private
6245 // clause semantics described in Section 2.14.3.3 on page 159 except as
6246 // noted. In addition, the value of the new list item on each iteration
6247 // of the associated loop(s) corresponds to the value of the original
6248 // list item before entering the construct plus the logical number of
6249 // the iteration times linear-step.
6251 SourceLocation ELoc = RefExpr->getExprLoc();
6252 // OpenMP [2.1, C/C++]
6253 // A list item is a variable name.
6254 // OpenMP [2.14.3.3, Restrictions, p.1]
6255 // A variable that is part of another variable (as an array or
6256 // structure element) cannot appear in a private clause.
6257 DeclRefExpr *DE = dyn_cast<DeclRefExpr>(RefExpr);
6258 if (!DE || !isa<VarDecl>(DE->getDecl())) {
6259 Diag(ELoc, diag::err_omp_expected_var_name) << RefExpr->getSourceRange();
6263 VarDecl *VD = cast<VarDecl>(DE->getDecl());
6265 // OpenMP [2.14.3.7, linear clause]
6266 // A list-item cannot appear in more than one linear clause.
6267 // A list-item that appears in a linear clause cannot appear in any
6268 // other data-sharing attribute clause.
6269 DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(VD, false);
6271 Diag(ELoc, diag::err_omp_wrong_dsa) << getOpenMPClauseName(DVar.CKind)
6272 << getOpenMPClauseName(OMPC_linear);
6273 ReportOriginalDSA(*this, DSAStack, VD, DVar);
6277 QualType QType = VD->getType();
6278 if (QType->isDependentType() || QType->isInstantiationDependentType()) {
6279 // It will be analyzed later.
6281 Inits.push_back(nullptr);
6285 // A variable must not have an incomplete type or a reference type.
6286 if (RequireCompleteType(ELoc, QType,
6287 diag::err_omp_linear_incomplete_type)) {
6290 if (QType->isReferenceType()) {
6291 Diag(ELoc, diag::err_omp_clause_ref_type_arg)
6292 << getOpenMPClauseName(OMPC_linear) << QType;
6294 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
6295 Diag(VD->getLocation(),
6296 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
6301 // A list item must not be const-qualified.
6302 if (QType.isConstant(Context)) {
6303 Diag(ELoc, diag::err_omp_const_variable)
6304 << getOpenMPClauseName(OMPC_linear);
6306 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
6307 Diag(VD->getLocation(),
6308 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
6313 // A list item must be of integral or pointer type.
6314 QType = QType.getUnqualifiedType().getCanonicalType();
6315 const Type *Ty = QType.getTypePtrOrNull();
6316 if (!Ty || (!Ty->isDependentType() && !Ty->isIntegralType(Context) &&
6317 !Ty->isPointerType())) {
6318 Diag(ELoc, diag::err_omp_linear_expected_int_or_ptr) << QType;
6320 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
6321 Diag(VD->getLocation(),
6322 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
6327 // Build var to save initial value.
6328 VarDecl *Init = buildVarDecl(*this, ELoc, QType, ".linear.start");
6329 AddInitializerToDecl(Init, DefaultLvalueConversion(DE).get(),
6330 /*DirectInit*/ false, /*TypeMayContainAuto*/ false);
6331 auto InitRef = buildDeclRefExpr(
6332 *this, Init, DE->getType().getUnqualifiedType(), DE->getExprLoc());
6333 DSAStack->addDSA(VD, DE, OMPC_linear);
6335 Inits.push_back(InitRef);
6341 Expr *StepExpr = Step;
6342 Expr *CalcStepExpr = nullptr;
6343 if (Step && !Step->isValueDependent() && !Step->isTypeDependent() &&
6344 !Step->isInstantiationDependent() &&
6345 !Step->containsUnexpandedParameterPack()) {
6346 SourceLocation StepLoc = Step->getLocStart();
6347 ExprResult Val = PerformOpenMPImplicitIntegerConversion(StepLoc, Step);
6348 if (Val.isInvalid())
6350 StepExpr = Val.get();
6352 // Build var to save the step value.
6354 buildVarDecl(*this, StepLoc, StepExpr->getType(), ".linear.step");
6355 ExprResult SaveRef =
6356 buildDeclRefExpr(*this, SaveVar, StepExpr->getType(), StepLoc);
6357 ExprResult CalcStep =
6358 BuildBinOp(CurScope, StepLoc, BO_Assign, SaveRef.get(), StepExpr);
6360 // Warn about zero linear step (it would be probably better specified as
6361 // making corresponding variables 'const').
6362 llvm::APSInt Result;
6363 bool IsConstant = StepExpr->isIntegerConstantExpr(Result, Context);
6364 if (IsConstant && !Result.isNegative() && !Result.isStrictlyPositive())
6365 Diag(StepLoc, diag::warn_omp_linear_step_zero) << Vars[0]
6366 << (Vars.size() > 1);
6367 if (!IsConstant && CalcStep.isUsable()) {
6368 // Calculate the step beforehand instead of doing this on each iteration.
6369 // (This is not used if the number of iterations may be kfold-ed).
6370 CalcStepExpr = CalcStep.get();
6374 return OMPLinearClause::Create(Context, StartLoc, LParenLoc, ColonLoc, EndLoc,
6375 Vars, Inits, StepExpr, CalcStepExpr);
6378 static bool FinishOpenMPLinearClause(OMPLinearClause &Clause, DeclRefExpr *IV,
6379 Expr *NumIterations, Sema &SemaRef,
6381 // Walk the vars and build update/final expressions for the CodeGen.
6382 SmallVector<Expr *, 8> Updates;
6383 SmallVector<Expr *, 8> Finals;
6384 Expr *Step = Clause.getStep();
6385 Expr *CalcStep = Clause.getCalcStep();
6386 // OpenMP [2.14.3.7, linear clause]
6387 // If linear-step is not specified it is assumed to be 1.
6388 if (Step == nullptr)
6389 Step = SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get();
6391 Step = cast<BinaryOperator>(CalcStep)->getLHS();
6392 bool HasErrors = false;
6393 auto CurInit = Clause.inits().begin();
6394 for (auto &RefExpr : Clause.varlists()) {
6395 Expr *InitExpr = *CurInit;
6397 // Build privatized reference to the current linear var.
6398 auto DE = cast<DeclRefExpr>(RefExpr);
6400 buildDeclRefExpr(SemaRef, cast<VarDecl>(DE->getDecl()),
6401 DE->getType().getUnqualifiedType(), DE->getExprLoc(),
6402 /*RefersToCapture=*/true);
6404 // Build update: Var = InitExpr + IV * Step
6406 BuildCounterUpdate(SemaRef, S, RefExpr->getExprLoc(), PrivateRef,
6407 InitExpr, IV, Step, /* Subtract */ false);
6408 Update = SemaRef.ActOnFinishFullExpr(Update.get());
6410 // Build final: Var = InitExpr + NumIterations * Step
6412 BuildCounterUpdate(SemaRef, S, RefExpr->getExprLoc(), PrivateRef,
6413 InitExpr, NumIterations, Step, /* Subtract */ false);
6414 Final = SemaRef.ActOnFinishFullExpr(Final.get());
6415 if (!Update.isUsable() || !Final.isUsable()) {
6416 Updates.push_back(nullptr);
6417 Finals.push_back(nullptr);
6420 Updates.push_back(Update.get());
6421 Finals.push_back(Final.get());
6425 Clause.setUpdates(Updates);
6426 Clause.setFinals(Finals);
6430 OMPClause *Sema::ActOnOpenMPAlignedClause(
6431 ArrayRef<Expr *> VarList, Expr *Alignment, SourceLocation StartLoc,
6432 SourceLocation LParenLoc, SourceLocation ColonLoc, SourceLocation EndLoc) {
6434 SmallVector<Expr *, 8> Vars;
6435 for (auto &RefExpr : VarList) {
6436 assert(RefExpr && "NULL expr in OpenMP aligned clause.");
6437 if (isa<DependentScopeDeclRefExpr>(RefExpr)) {
6438 // It will be analyzed later.
6439 Vars.push_back(RefExpr);
6443 SourceLocation ELoc = RefExpr->getExprLoc();
6444 // OpenMP [2.1, C/C++]
6445 // A list item is a variable name.
6446 DeclRefExpr *DE = dyn_cast<DeclRefExpr>(RefExpr);
6447 if (!DE || !isa<VarDecl>(DE->getDecl())) {
6448 Diag(ELoc, diag::err_omp_expected_var_name) << RefExpr->getSourceRange();
6452 VarDecl *VD = cast<VarDecl>(DE->getDecl());
6454 // OpenMP [2.8.1, simd construct, Restrictions]
6455 // The type of list items appearing in the aligned clause must be
6456 // array, pointer, reference to array, or reference to pointer.
6457 QualType QType = VD->getType();
6458 QType = QType.getNonReferenceType().getUnqualifiedType().getCanonicalType();
6459 const Type *Ty = QType.getTypePtrOrNull();
6460 if (!Ty || (!Ty->isDependentType() && !Ty->isArrayType() &&
6461 !Ty->isPointerType())) {
6462 Diag(ELoc, diag::err_omp_aligned_expected_array_or_ptr)
6463 << QType << getLangOpts().CPlusPlus << RefExpr->getSourceRange();
6465 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
6466 Diag(VD->getLocation(),
6467 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
6472 // OpenMP [2.8.1, simd construct, Restrictions]
6473 // A list-item cannot appear in more than one aligned clause.
6474 if (DeclRefExpr *PrevRef = DSAStack->addUniqueAligned(VD, DE)) {
6475 Diag(ELoc, diag::err_omp_aligned_twice) << RefExpr->getSourceRange();
6476 Diag(PrevRef->getExprLoc(), diag::note_omp_explicit_dsa)
6477 << getOpenMPClauseName(OMPC_aligned);
6484 // OpenMP [2.8.1, simd construct, Description]
6485 // The parameter of the aligned clause, alignment, must be a constant
6486 // positive integer expression.
6487 // If no optional parameter is specified, implementation-defined default
6488 // alignments for SIMD instructions on the target platforms are assumed.
6489 if (Alignment != nullptr) {
6490 ExprResult AlignResult =
6491 VerifyPositiveIntegerConstantInClause(Alignment, OMPC_aligned);
6492 if (AlignResult.isInvalid())
6494 Alignment = AlignResult.get();
6499 return OMPAlignedClause::Create(Context, StartLoc, LParenLoc, ColonLoc,
6500 EndLoc, Vars, Alignment);
6503 OMPClause *Sema::ActOnOpenMPCopyinClause(ArrayRef<Expr *> VarList,
6504 SourceLocation StartLoc,
6505 SourceLocation LParenLoc,
6506 SourceLocation EndLoc) {
6507 SmallVector<Expr *, 8> Vars;
6508 SmallVector<Expr *, 8> SrcExprs;
6509 SmallVector<Expr *, 8> DstExprs;
6510 SmallVector<Expr *, 8> AssignmentOps;
6511 for (auto &RefExpr : VarList) {
6512 assert(RefExpr && "NULL expr in OpenMP copyin clause.");
6513 if (isa<DependentScopeDeclRefExpr>(RefExpr)) {
6514 // It will be analyzed later.
6515 Vars.push_back(RefExpr);
6516 SrcExprs.push_back(nullptr);
6517 DstExprs.push_back(nullptr);
6518 AssignmentOps.push_back(nullptr);
6522 SourceLocation ELoc = RefExpr->getExprLoc();
6523 // OpenMP [2.1, C/C++]
6524 // A list item is a variable name.
6525 // OpenMP [2.14.4.1, Restrictions, p.1]
6526 // A list item that appears in a copyin clause must be threadprivate.
6527 DeclRefExpr *DE = dyn_cast<DeclRefExpr>(RefExpr);
6528 if (!DE || !isa<VarDecl>(DE->getDecl())) {
6529 Diag(ELoc, diag::err_omp_expected_var_name) << RefExpr->getSourceRange();
6533 Decl *D = DE->getDecl();
6534 VarDecl *VD = cast<VarDecl>(D);
6536 QualType Type = VD->getType();
6537 if (Type->isDependentType() || Type->isInstantiationDependentType()) {
6538 // It will be analyzed later.
6540 SrcExprs.push_back(nullptr);
6541 DstExprs.push_back(nullptr);
6542 AssignmentOps.push_back(nullptr);
6546 // OpenMP [2.14.4.1, Restrictions, C/C++, p.1]
6547 // A list item that appears in a copyin clause must be threadprivate.
6548 if (!DSAStack->isThreadPrivate(VD)) {
6549 Diag(ELoc, diag::err_omp_required_access)
6550 << getOpenMPClauseName(OMPC_copyin)
6551 << getOpenMPDirectiveName(OMPD_threadprivate);
6555 // OpenMP [2.14.4.1, Restrictions, C/C++, p.2]
6556 // A variable of class type (or array thereof) that appears in a
6557 // copyin clause requires an accessible, unambiguous copy assignment
6558 // operator for the class type.
6559 auto ElemType = Context.getBaseElementType(Type).getNonReferenceType();
6560 auto *SrcVD = buildVarDecl(*this, DE->getLocStart(),
6561 ElemType.getUnqualifiedType(), ".copyin.src");
6562 auto *PseudoSrcExpr = buildDeclRefExpr(
6563 *this, SrcVD, ElemType.getUnqualifiedType(), DE->getExprLoc());
6565 buildVarDecl(*this, DE->getLocStart(), ElemType, ".copyin.dst");
6566 auto *PseudoDstExpr =
6567 buildDeclRefExpr(*this, DstVD, ElemType, DE->getExprLoc());
6568 // For arrays generate assignment operation for single element and replace
6569 // it by the original array element in CodeGen.
6570 auto AssignmentOp = BuildBinOp(/*S=*/nullptr, DE->getExprLoc(), BO_Assign,
6571 PseudoDstExpr, PseudoSrcExpr);
6572 if (AssignmentOp.isInvalid())
6574 AssignmentOp = ActOnFinishFullExpr(AssignmentOp.get(), DE->getExprLoc(),
6575 /*DiscardedValue=*/true);
6576 if (AssignmentOp.isInvalid())
6579 DSAStack->addDSA(VD, DE, OMPC_copyin);
6581 SrcExprs.push_back(PseudoSrcExpr);
6582 DstExprs.push_back(PseudoDstExpr);
6583 AssignmentOps.push_back(AssignmentOp.get());
6589 return OMPCopyinClause::Create(Context, StartLoc, LParenLoc, EndLoc, Vars,
6590 SrcExprs, DstExprs, AssignmentOps);
6593 OMPClause *Sema::ActOnOpenMPCopyprivateClause(ArrayRef<Expr *> VarList,
6594 SourceLocation StartLoc,
6595 SourceLocation LParenLoc,
6596 SourceLocation EndLoc) {
6597 SmallVector<Expr *, 8> Vars;
6598 SmallVector<Expr *, 8> SrcExprs;
6599 SmallVector<Expr *, 8> DstExprs;
6600 SmallVector<Expr *, 8> AssignmentOps;
6601 for (auto &RefExpr : VarList) {
6602 assert(RefExpr && "NULL expr in OpenMP copyprivate clause.");
6603 if (isa<DependentScopeDeclRefExpr>(RefExpr)) {
6604 // It will be analyzed later.
6605 Vars.push_back(RefExpr);
6606 SrcExprs.push_back(nullptr);
6607 DstExprs.push_back(nullptr);
6608 AssignmentOps.push_back(nullptr);
6612 SourceLocation ELoc = RefExpr->getExprLoc();
6613 // OpenMP [2.1, C/C++]
6614 // A list item is a variable name.
6615 // OpenMP [2.14.4.1, Restrictions, p.1]
6616 // A list item that appears in a copyin clause must be threadprivate.
6617 DeclRefExpr *DE = dyn_cast<DeclRefExpr>(RefExpr);
6618 if (!DE || !isa<VarDecl>(DE->getDecl())) {
6619 Diag(ELoc, diag::err_omp_expected_var_name) << RefExpr->getSourceRange();
6623 Decl *D = DE->getDecl();
6624 VarDecl *VD = cast<VarDecl>(D);
6626 QualType Type = VD->getType();
6627 if (Type->isDependentType() || Type->isInstantiationDependentType()) {
6628 // It will be analyzed later.
6630 SrcExprs.push_back(nullptr);
6631 DstExprs.push_back(nullptr);
6632 AssignmentOps.push_back(nullptr);
6636 // OpenMP [2.14.4.2, Restrictions, p.2]
6637 // A list item that appears in a copyprivate clause may not appear in a
6638 // private or firstprivate clause on the single construct.
6639 if (!DSAStack->isThreadPrivate(VD)) {
6640 auto DVar = DSAStack->getTopDSA(VD, false);
6641 if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_copyprivate &&
6643 Diag(ELoc, diag::err_omp_wrong_dsa)
6644 << getOpenMPClauseName(DVar.CKind)
6645 << getOpenMPClauseName(OMPC_copyprivate);
6646 ReportOriginalDSA(*this, DSAStack, VD, DVar);
6650 // OpenMP [2.11.4.2, Restrictions, p.1]
6651 // All list items that appear in a copyprivate clause must be either
6652 // threadprivate or private in the enclosing context.
6653 if (DVar.CKind == OMPC_unknown) {
6654 DVar = DSAStack->getImplicitDSA(VD, false);
6655 if (DVar.CKind == OMPC_shared) {
6656 Diag(ELoc, diag::err_omp_required_access)
6657 << getOpenMPClauseName(OMPC_copyprivate)
6658 << "threadprivate or private in the enclosing context";
6659 ReportOriginalDSA(*this, DSAStack, VD, DVar);
6665 // Variably modified types are not supported.
6666 if (!Type->isAnyPointerType() && Type->isVariablyModifiedType()) {
6667 Diag(ELoc, diag::err_omp_variably_modified_type_not_supported)
6668 << getOpenMPClauseName(OMPC_copyprivate) << Type
6669 << getOpenMPDirectiveName(DSAStack->getCurrentDirective());
6671 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
6672 Diag(VD->getLocation(),
6673 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
6678 // OpenMP [2.14.4.1, Restrictions, C/C++, p.2]
6679 // A variable of class type (or array thereof) that appears in a
6680 // copyin clause requires an accessible, unambiguous copy assignment
6681 // operator for the class type.
6682 Type = Context.getBaseElementType(Type).getUnqualifiedType();
6684 buildVarDecl(*this, DE->getLocStart(), Type, ".copyprivate.src");
6685 auto *PseudoSrcExpr =
6686 buildDeclRefExpr(*this, SrcVD, Type, DE->getExprLoc());
6688 buildVarDecl(*this, DE->getLocStart(), Type, ".copyprivate.dst");
6689 auto *PseudoDstExpr =
6690 buildDeclRefExpr(*this, DstVD, Type, DE->getExprLoc());
6691 auto AssignmentOp = BuildBinOp(/*S=*/nullptr, DE->getExprLoc(), BO_Assign,
6692 PseudoDstExpr, PseudoSrcExpr);
6693 if (AssignmentOp.isInvalid())
6695 AssignmentOp = ActOnFinishFullExpr(AssignmentOp.get(), DE->getExprLoc(),
6696 /*DiscardedValue=*/true);
6697 if (AssignmentOp.isInvalid())
6700 // No need to mark vars as copyprivate, they are already threadprivate or
6701 // implicitly private.
6703 SrcExprs.push_back(PseudoSrcExpr);
6704 DstExprs.push_back(PseudoDstExpr);
6705 AssignmentOps.push_back(AssignmentOp.get());
6711 return OMPCopyprivateClause::Create(Context, StartLoc, LParenLoc, EndLoc,
6712 Vars, SrcExprs, DstExprs, AssignmentOps);
6715 OMPClause *Sema::ActOnOpenMPFlushClause(ArrayRef<Expr *> VarList,
6716 SourceLocation StartLoc,
6717 SourceLocation LParenLoc,
6718 SourceLocation EndLoc) {
6719 if (VarList.empty())
6722 return OMPFlushClause::Create(Context, StartLoc, LParenLoc, EndLoc, VarList);
6726 Sema::ActOnOpenMPDependClause(OpenMPDependClauseKind DepKind,
6727 SourceLocation DepLoc, SourceLocation ColonLoc,
6728 ArrayRef<Expr *> VarList, SourceLocation StartLoc,
6729 SourceLocation LParenLoc, SourceLocation EndLoc) {
6730 if (DepKind == OMPC_DEPEND_unknown) {
6732 std::string Sep(", ");
6733 for (unsigned i = 0; i < OMPC_DEPEND_unknown; ++i) {
6735 Values += getOpenMPSimpleClauseTypeName(OMPC_depend, i);
6738 case OMPC_DEPEND_unknown - 2:
6741 case OMPC_DEPEND_unknown - 1:
6748 Diag(DepLoc, diag::err_omp_unexpected_clause_value)
6749 << Values << getOpenMPClauseName(OMPC_depend);
6752 SmallVector<Expr *, 8> Vars;
6753 for (auto &RefExpr : VarList) {
6754 assert(RefExpr && "NULL expr in OpenMP shared clause.");
6755 if (isa<DependentScopeDeclRefExpr>(RefExpr)) {
6756 // It will be analyzed later.
6757 Vars.push_back(RefExpr);
6761 SourceLocation ELoc = RefExpr->getExprLoc();
6762 // OpenMP [2.11.1.1, Restrictions, p.3]
6763 // A variable that is part of another variable (such as a field of a
6764 // structure) but is not an array element or an array section cannot appear
6765 // in a depend clause.
6766 auto *SimpleExpr = RefExpr->IgnoreParenCasts();
6767 DeclRefExpr *DE = dyn_cast<DeclRefExpr>(SimpleExpr);
6768 ArraySubscriptExpr *ASE = dyn_cast<ArraySubscriptExpr>(SimpleExpr);
6769 if (!RefExpr->IgnoreParenImpCasts()->isLValue() || (!ASE && !DE) ||
6770 (DE && !isa<VarDecl>(DE->getDecl())) ||
6771 (ASE && !ASE->getBase()->getType()->isAnyPointerType() &&
6772 !ASE->getBase()->getType()->isArrayType())) {
6773 Diag(ELoc, diag::err_omp_expected_var_name_or_array_item)
6774 << RefExpr->getSourceRange();
6778 Vars.push_back(RefExpr->IgnoreParenImpCasts());
6784 return OMPDependClause::Create(Context, StartLoc, LParenLoc, EndLoc, DepKind,
6785 DepLoc, ColonLoc, Vars);