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 "clang/AST/ASTContext.h"
16 #include "clang/AST/ASTMutationListener.h"
17 #include "clang/AST/Decl.h"
18 #include "clang/AST/DeclCXX.h"
19 #include "clang/AST/DeclOpenMP.h"
20 #include "clang/AST/StmtCXX.h"
21 #include "clang/AST/StmtOpenMP.h"
22 #include "clang/AST/StmtVisitor.h"
23 #include "clang/Basic/OpenMPKinds.h"
24 #include "clang/Lex/Preprocessor.h"
25 #include "clang/Sema/Initialization.h"
26 #include "clang/Sema/Lookup.h"
27 #include "clang/Sema/Scope.h"
28 #include "clang/Sema/ScopeInfo.h"
29 #include "clang/Sema/SemaInternal.h"
30 using namespace clang;
32 //===----------------------------------------------------------------------===//
33 // Stack of data-sharing attributes for variables
34 //===----------------------------------------------------------------------===//
37 /// \brief Default data sharing attributes, which can be applied to directive.
38 enum DefaultDataSharingAttributes {
39 DSA_unspecified = 0, /// \brief Data sharing attribute not specified.
40 DSA_none = 1 << 0, /// \brief Default data sharing attribute 'none'.
41 DSA_shared = 1 << 1 /// \brief Default data sharing attribute 'shared'.
44 template <class T> struct MatchesAny {
45 explicit MatchesAny(ArrayRef<T> Arr) : Arr(std::move(Arr)) {}
46 bool operator()(T Kind) {
47 for (auto KindEl : Arr)
56 struct MatchesAlways {
58 template <class T> bool operator()(T) { return true; }
61 typedef MatchesAny<OpenMPClauseKind> MatchesAnyClause;
62 typedef MatchesAny<OpenMPDirectiveKind> MatchesAnyDirective;
64 /// \brief Stack for tracking declarations used in OpenMP directives and
65 /// clauses and their data-sharing attributes.
69 OpenMPDirectiveKind DKind;
70 OpenMPClauseKind CKind;
72 SourceLocation ImplicitDSALoc;
74 : DKind(OMPD_unknown), CKind(OMPC_unknown), RefExpr(nullptr),
80 OpenMPClauseKind Attributes;
83 typedef llvm::SmallDenseMap<VarDecl *, DSAInfo, 64> DeclSAMapTy;
84 typedef llvm::SmallDenseMap<VarDecl *, DeclRefExpr *, 64> AlignedMapTy;
87 DeclSAMapTy SharingMap;
88 AlignedMapTy AlignedMap;
89 DefaultDataSharingAttributes DefaultAttr;
90 SourceLocation DefaultAttrLoc;
91 OpenMPDirectiveKind Directive;
92 DeclarationNameInfo DirectiveName;
94 SourceLocation ConstructLoc;
96 SourceLocation InnerTeamsRegionLoc;
97 SharingMapTy(OpenMPDirectiveKind DKind, DeclarationNameInfo Name,
98 Scope *CurScope, SourceLocation Loc)
99 : SharingMap(), AlignedMap(), DefaultAttr(DSA_unspecified),
100 Directive(DKind), DirectiveName(std::move(Name)), CurScope(CurScope),
101 ConstructLoc(Loc), OrderedRegion(false), InnerTeamsRegionLoc() {}
103 : SharingMap(), AlignedMap(), DefaultAttr(DSA_unspecified),
104 Directive(OMPD_unknown), DirectiveName(), CurScope(nullptr),
105 ConstructLoc(), OrderedRegion(false), InnerTeamsRegionLoc() {}
108 typedef SmallVector<SharingMapTy, 64> StackTy;
110 /// \brief Stack of used declaration and their data-sharing attributes.
114 typedef SmallVector<SharingMapTy, 8>::reverse_iterator reverse_iterator;
116 DSAVarData getDSA(StackTy::reverse_iterator Iter, VarDecl *D);
118 /// \brief Checks if the variable is a local for OpenMP region.
119 bool isOpenMPLocal(VarDecl *D, StackTy::reverse_iterator Iter);
122 explicit DSAStackTy(Sema &S) : Stack(1), SemaRef(S) {}
124 void push(OpenMPDirectiveKind DKind, const DeclarationNameInfo &DirName,
125 Scope *CurScope, SourceLocation Loc) {
126 Stack.push_back(SharingMapTy(DKind, DirName, CurScope, Loc));
127 Stack.back().DefaultAttrLoc = Loc;
131 assert(Stack.size() > 1 && "Data-sharing attributes stack is empty!");
135 /// \brief If 'aligned' declaration for given variable \a D was not seen yet,
136 /// add it and return NULL; otherwise return previous occurrence's expression
138 DeclRefExpr *addUniqueAligned(VarDecl *D, DeclRefExpr *NewDE);
140 /// \brief Adds explicit data sharing attribute to the specified declaration.
141 void addDSA(VarDecl *D, DeclRefExpr *E, OpenMPClauseKind A);
143 /// \brief Returns data sharing attributes from top of the stack for the
144 /// specified declaration.
145 DSAVarData getTopDSA(VarDecl *D, bool FromParent);
146 /// \brief Returns data-sharing attributes for the specified declaration.
147 DSAVarData getImplicitDSA(VarDecl *D, bool FromParent);
148 /// \brief Checks if the specified variables has data-sharing attributes which
149 /// match specified \a CPred predicate in any directive which matches \a DPred
151 template <class ClausesPredicate, class DirectivesPredicate>
152 DSAVarData hasDSA(VarDecl *D, ClausesPredicate CPred,
153 DirectivesPredicate DPred, bool FromParent);
154 /// \brief Checks if the specified variables has data-sharing attributes which
155 /// match specified \a CPred predicate in any innermost directive which
156 /// matches \a DPred predicate.
157 template <class ClausesPredicate, class DirectivesPredicate>
158 DSAVarData hasInnermostDSA(VarDecl *D, ClausesPredicate CPred,
159 DirectivesPredicate DPred,
161 /// \brief Finds a directive which matches specified \a DPred predicate.
162 template <class NamedDirectivesPredicate>
163 bool hasDirective(NamedDirectivesPredicate DPred, bool FromParent);
165 /// \brief Returns currently analyzed directive.
166 OpenMPDirectiveKind getCurrentDirective() const {
167 return Stack.back().Directive;
169 /// \brief Returns parent directive.
170 OpenMPDirectiveKind getParentDirective() const {
171 if (Stack.size() > 2)
172 return Stack[Stack.size() - 2].Directive;
176 /// \brief Set default data sharing attribute to none.
177 void setDefaultDSANone(SourceLocation Loc) {
178 Stack.back().DefaultAttr = DSA_none;
179 Stack.back().DefaultAttrLoc = Loc;
181 /// \brief Set default data sharing attribute to shared.
182 void setDefaultDSAShared(SourceLocation Loc) {
183 Stack.back().DefaultAttr = DSA_shared;
184 Stack.back().DefaultAttrLoc = Loc;
187 DefaultDataSharingAttributes getDefaultDSA() const {
188 return Stack.back().DefaultAttr;
190 SourceLocation getDefaultDSALocation() const {
191 return Stack.back().DefaultAttrLoc;
194 /// \brief Checks if the specified variable is a threadprivate.
195 bool isThreadPrivate(VarDecl *D) {
196 DSAVarData DVar = getTopDSA(D, false);
197 return isOpenMPThreadPrivate(DVar.CKind);
200 /// \brief Marks current region as ordered (it has an 'ordered' clause).
201 void setOrderedRegion(bool IsOrdered = true) {
202 Stack.back().OrderedRegion = IsOrdered;
204 /// \brief Returns true, if parent region is ordered (has associated
205 /// 'ordered' clause), false - otherwise.
206 bool isParentOrderedRegion() const {
207 if (Stack.size() > 2)
208 return Stack[Stack.size() - 2].OrderedRegion;
212 /// \brief Marks current target region as one with closely nested teams
214 void setParentTeamsRegionLoc(SourceLocation TeamsRegionLoc) {
215 if (Stack.size() > 2)
216 Stack[Stack.size() - 2].InnerTeamsRegionLoc = TeamsRegionLoc;
218 /// \brief Returns true, if current region has closely nested teams region.
219 bool hasInnerTeamsRegion() const {
220 return getInnerTeamsRegionLoc().isValid();
222 /// \brief Returns location of the nested teams region (if any).
223 SourceLocation getInnerTeamsRegionLoc() const {
224 if (Stack.size() > 1)
225 return Stack.back().InnerTeamsRegionLoc;
226 return SourceLocation();
229 Scope *getCurScope() const { return Stack.back().CurScope; }
230 Scope *getCurScope() { return Stack.back().CurScope; }
231 SourceLocation getConstructLoc() { return Stack.back().ConstructLoc; }
233 bool isParallelOrTaskRegion(OpenMPDirectiveKind DKind) {
234 return isOpenMPParallelDirective(DKind) || DKind == OMPD_task ||
235 isOpenMPTeamsDirective(DKind) || DKind == OMPD_unknown;
239 DSAStackTy::DSAVarData DSAStackTy::getDSA(StackTy::reverse_iterator Iter,
242 if (Iter == std::prev(Stack.rend())) {
243 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
244 // in a region but not in construct]
245 // File-scope or namespace-scope variables referenced in called routines
246 // in the region are shared unless they appear in a threadprivate
248 if (!D->isFunctionOrMethodVarDecl() && !isa<ParmVarDecl>(D))
249 DVar.CKind = OMPC_shared;
251 // OpenMP [2.9.1.2, Data-sharing Attribute Rules for Variables Referenced
252 // in a region but not in construct]
253 // Variables with static storage duration that are declared in called
254 // routines in the region are shared.
255 if (D->hasGlobalStorage())
256 DVar.CKind = OMPC_shared;
261 DVar.DKind = Iter->Directive;
262 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
263 // in a Construct, C/C++, predetermined, p.1]
264 // Variables with automatic storage duration that are declared in a scope
265 // inside the construct are private.
266 if (isOpenMPLocal(D, Iter) && D->isLocalVarDecl() &&
267 (D->getStorageClass() == SC_Auto || D->getStorageClass() == SC_None)) {
268 DVar.CKind = OMPC_private;
272 // Explicitly specified attributes and local variables with predetermined
274 if (Iter->SharingMap.count(D)) {
275 DVar.RefExpr = Iter->SharingMap[D].RefExpr;
276 DVar.CKind = Iter->SharingMap[D].Attributes;
277 DVar.ImplicitDSALoc = Iter->DefaultAttrLoc;
281 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
282 // in a Construct, C/C++, implicitly determined, p.1]
283 // In a parallel or task construct, the data-sharing attributes of these
284 // variables are determined by the default clause, if present.
285 switch (Iter->DefaultAttr) {
287 DVar.CKind = OMPC_shared;
288 DVar.ImplicitDSALoc = Iter->DefaultAttrLoc;
292 case DSA_unspecified:
293 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
294 // in a Construct, implicitly determined, p.2]
295 // In a parallel construct, if no default clause is present, these
296 // variables are shared.
297 DVar.ImplicitDSALoc = Iter->DefaultAttrLoc;
298 if (isOpenMPParallelDirective(DVar.DKind) ||
299 isOpenMPTeamsDirective(DVar.DKind)) {
300 DVar.CKind = OMPC_shared;
304 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
305 // in a Construct, implicitly determined, p.4]
306 // In a task construct, if no default clause is present, a variable that in
307 // the enclosing context is determined to be shared by all implicit tasks
308 // bound to the current team is shared.
309 if (DVar.DKind == OMPD_task) {
311 for (StackTy::reverse_iterator I = std::next(Iter),
312 EE = std::prev(Stack.rend());
314 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables
316 // in a Construct, implicitly determined, p.6]
317 // In a task construct, if no default clause is present, a variable
318 // whose data-sharing attribute is not determined by the rules above is
320 DVarTemp = getDSA(I, D);
321 if (DVarTemp.CKind != OMPC_shared) {
322 DVar.RefExpr = nullptr;
323 DVar.DKind = OMPD_task;
324 DVar.CKind = OMPC_firstprivate;
327 if (isParallelOrTaskRegion(I->Directive))
330 DVar.DKind = OMPD_task;
332 (DVarTemp.CKind == OMPC_unknown) ? OMPC_firstprivate : OMPC_shared;
336 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
337 // in a Construct, implicitly determined, p.3]
338 // For constructs other than task, if no default clause is present, these
339 // variables inherit their data-sharing attributes from the enclosing
341 return getDSA(std::next(Iter), D);
344 DeclRefExpr *DSAStackTy::addUniqueAligned(VarDecl *D, DeclRefExpr *NewDE) {
345 assert(Stack.size() > 1 && "Data sharing attributes stack is empty");
346 auto It = Stack.back().AlignedMap.find(D);
347 if (It == Stack.back().AlignedMap.end()) {
348 assert(NewDE && "Unexpected nullptr expr to be added into aligned map");
349 Stack.back().AlignedMap[D] = NewDE;
352 assert(It->second && "Unexpected nullptr expr in the aligned map");
358 void DSAStackTy::addDSA(VarDecl *D, DeclRefExpr *E, OpenMPClauseKind A) {
359 if (A == OMPC_threadprivate) {
360 Stack[0].SharingMap[D].Attributes = A;
361 Stack[0].SharingMap[D].RefExpr = E;
363 assert(Stack.size() > 1 && "Data-sharing attributes stack is empty");
364 Stack.back().SharingMap[D].Attributes = A;
365 Stack.back().SharingMap[D].RefExpr = E;
369 bool DSAStackTy::isOpenMPLocal(VarDecl *D, StackTy::reverse_iterator Iter) {
370 if (Stack.size() > 2) {
371 reverse_iterator I = Iter, E = std::prev(Stack.rend());
372 Scope *TopScope = nullptr;
373 while (I != E && !isParallelOrTaskRegion(I->Directive)) {
378 TopScope = I->CurScope ? I->CurScope->getParent() : nullptr;
379 Scope *CurScope = getCurScope();
380 while (CurScope != TopScope && !CurScope->isDeclScope(D)) {
381 CurScope = CurScope->getParent();
383 return CurScope != TopScope;
388 DSAStackTy::DSAVarData DSAStackTy::getTopDSA(VarDecl *D, bool FromParent) {
391 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
392 // in a Construct, C/C++, predetermined, p.1]
393 // Variables appearing in threadprivate directives are threadprivate.
394 if (D->getTLSKind() != VarDecl::TLS_None ||
395 D->getStorageClass() == SC_Register) {
396 DVar.CKind = OMPC_threadprivate;
399 if (Stack[0].SharingMap.count(D)) {
400 DVar.RefExpr = Stack[0].SharingMap[D].RefExpr;
401 DVar.CKind = OMPC_threadprivate;
405 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
406 // in a Construct, C/C++, predetermined, p.1]
407 // Variables with automatic storage duration that are declared in a scope
408 // inside the construct are private.
409 OpenMPDirectiveKind Kind =
410 FromParent ? getParentDirective() : getCurrentDirective();
411 auto StartI = std::next(Stack.rbegin());
412 auto EndI = std::prev(Stack.rend());
413 if (FromParent && StartI != EndI) {
414 StartI = std::next(StartI);
416 if (!isParallelOrTaskRegion(Kind)) {
417 if (isOpenMPLocal(D, StartI) &&
418 ((D->isLocalVarDecl() && (D->getStorageClass() == SC_Auto ||
419 D->getStorageClass() == SC_None)) ||
420 isa<ParmVarDecl>(D))) {
421 DVar.CKind = OMPC_private;
426 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
427 // in a Construct, C/C++, predetermined, p.4]
428 // Static data members are shared.
429 if (D->isStaticDataMember()) {
430 // Variables with const-qualified type having no mutable member may be
431 // listed in a firstprivate clause, even if they are static data members.
432 DSAVarData DVarTemp = hasDSA(D, MatchesAnyClause(OMPC_firstprivate),
433 MatchesAlways(), FromParent);
434 if (DVarTemp.CKind == OMPC_firstprivate && DVarTemp.RefExpr)
437 DVar.CKind = OMPC_shared;
441 QualType Type = D->getType().getNonReferenceType().getCanonicalType();
442 bool IsConstant = Type.isConstant(SemaRef.getASTContext());
443 while (Type->isArrayType()) {
444 QualType ElemType = cast<ArrayType>(Type.getTypePtr())->getElementType();
445 Type = ElemType.getNonReferenceType().getCanonicalType();
447 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
448 // in a Construct, C/C++, predetermined, p.6]
449 // Variables with const qualified type having no mutable member are
452 SemaRef.getLangOpts().CPlusPlus ? Type->getAsCXXRecordDecl() : nullptr;
454 !(SemaRef.getLangOpts().CPlusPlus && RD && RD->hasMutableFields())) {
455 // Variables with const-qualified type having no mutable member may be
456 // listed in a firstprivate clause, even if they are static data members.
457 DSAVarData DVarTemp = hasDSA(D, MatchesAnyClause(OMPC_firstprivate),
458 MatchesAlways(), FromParent);
459 if (DVarTemp.CKind == OMPC_firstprivate && DVarTemp.RefExpr)
462 DVar.CKind = OMPC_shared;
466 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
467 // in a Construct, C/C++, predetermined, p.7]
468 // Variables with static storage duration that are declared in a scope
469 // inside the construct are shared.
470 if (D->isStaticLocal()) {
471 DVar.CKind = OMPC_shared;
475 // Explicitly specified attributes and local variables with predetermined
477 auto I = std::prev(StartI);
478 if (I->SharingMap.count(D)) {
479 DVar.RefExpr = I->SharingMap[D].RefExpr;
480 DVar.CKind = I->SharingMap[D].Attributes;
481 DVar.ImplicitDSALoc = I->DefaultAttrLoc;
487 DSAStackTy::DSAVarData DSAStackTy::getImplicitDSA(VarDecl *D, bool FromParent) {
488 auto StartI = Stack.rbegin();
489 auto EndI = std::prev(Stack.rend());
490 if (FromParent && StartI != EndI) {
491 StartI = std::next(StartI);
493 return getDSA(StartI, D);
496 template <class ClausesPredicate, class DirectivesPredicate>
497 DSAStackTy::DSAVarData DSAStackTy::hasDSA(VarDecl *D, ClausesPredicate CPred,
498 DirectivesPredicate DPred,
500 auto StartI = std::next(Stack.rbegin());
501 auto EndI = std::prev(Stack.rend());
502 if (FromParent && StartI != EndI) {
503 StartI = std::next(StartI);
505 for (auto I = StartI, EE = EndI; I != EE; ++I) {
506 if (!DPred(I->Directive) && !isParallelOrTaskRegion(I->Directive))
508 DSAVarData DVar = getDSA(I, D);
509 if (CPred(DVar.CKind))
515 template <class ClausesPredicate, class DirectivesPredicate>
516 DSAStackTy::DSAVarData
517 DSAStackTy::hasInnermostDSA(VarDecl *D, ClausesPredicate CPred,
518 DirectivesPredicate DPred, bool FromParent) {
519 auto StartI = std::next(Stack.rbegin());
520 auto EndI = std::prev(Stack.rend());
521 if (FromParent && StartI != EndI) {
522 StartI = std::next(StartI);
524 for (auto I = StartI, EE = EndI; I != EE; ++I) {
525 if (!DPred(I->Directive))
527 DSAVarData DVar = getDSA(I, D);
528 if (CPred(DVar.CKind))
535 template <class NamedDirectivesPredicate>
536 bool DSAStackTy::hasDirective(NamedDirectivesPredicate DPred, bool FromParent) {
537 auto StartI = std::next(Stack.rbegin());
538 auto EndI = std::prev(Stack.rend());
539 if (FromParent && StartI != EndI) {
540 StartI = std::next(StartI);
542 for (auto I = StartI, EE = EndI; I != EE; ++I) {
543 if (DPred(I->Directive, I->DirectiveName, I->ConstructLoc))
549 void Sema::InitDataSharingAttributesStack() {
550 VarDataSharingAttributesStack = new DSAStackTy(*this);
553 #define DSAStack static_cast<DSAStackTy *>(VarDataSharingAttributesStack)
555 bool Sema::IsOpenMPCapturedVar(VarDecl *VD) {
556 assert(LangOpts.OpenMP && "OpenMP is not allowed");
557 if (DSAStack->getCurrentDirective() != OMPD_unknown) {
558 auto DVarPrivate = DSAStack->getTopDSA(VD, /*FromParent=*/false);
559 if (DVarPrivate.CKind != OMPC_unknown && isOpenMPPrivate(DVarPrivate.CKind))
561 DVarPrivate = DSAStack->hasDSA(VD, isOpenMPPrivate, MatchesAlways(),
562 /*FromParent=*/false);
563 return DVarPrivate.CKind != OMPC_unknown;
568 void Sema::DestroyDataSharingAttributesStack() { delete DSAStack; }
570 void Sema::StartOpenMPDSABlock(OpenMPDirectiveKind DKind,
571 const DeclarationNameInfo &DirName,
572 Scope *CurScope, SourceLocation Loc) {
573 DSAStack->push(DKind, DirName, CurScope, Loc);
574 PushExpressionEvaluationContext(PotentiallyEvaluated);
577 void Sema::EndOpenMPDSABlock(Stmt *CurDirective) {
578 // OpenMP [2.14.3.5, Restrictions, C/C++, p.1]
579 // A variable of class type (or array thereof) that appears in a lastprivate
580 // clause requires an accessible, unambiguous default constructor for the
581 // class type, unless the list item is also specified in a firstprivate
583 if (auto D = dyn_cast_or_null<OMPExecutableDirective>(CurDirective)) {
584 for (auto C : D->clauses()) {
585 if (auto Clause = dyn_cast<OMPLastprivateClause>(C)) {
586 for (auto VarRef : Clause->varlists()) {
587 if (VarRef->isValueDependent() || VarRef->isTypeDependent())
589 auto VD = cast<VarDecl>(cast<DeclRefExpr>(VarRef)->getDecl());
590 auto DVar = DSAStack->getTopDSA(VD, false);
591 if (DVar.CKind == OMPC_lastprivate) {
592 SourceLocation ELoc = VarRef->getExprLoc();
593 auto Type = VarRef->getType();
594 if (Type->isArrayType())
595 Type = QualType(Type->getArrayElementTypeNoTypeQual(), 0);
597 getLangOpts().CPlusPlus ? Type->getAsCXXRecordDecl() : nullptr;
598 // FIXME This code must be replaced by actual constructing of the
599 // lastprivate variable.
601 CXXConstructorDecl *CD = LookupDefaultConstructor(RD);
602 PartialDiagnostic PD =
603 PartialDiagnostic(PartialDiagnostic::NullDiagnostic());
605 CheckConstructorAccess(
606 ELoc, CD, InitializedEntity::InitializeTemporary(Type),
607 CD->getAccess(), PD) == AR_inaccessible ||
609 Diag(ELoc, diag::err_omp_required_method)
610 << getOpenMPClauseName(OMPC_lastprivate) << 0;
611 bool IsDecl = VD->isThisDeclarationADefinition(Context) ==
612 VarDecl::DeclarationOnly;
613 Diag(VD->getLocation(), IsDecl ? diag::note_previous_decl
614 : diag::note_defined_here)
616 Diag(RD->getLocation(), diag::note_previous_decl) << RD;
619 MarkFunctionReferenced(ELoc, CD);
620 DiagnoseUseOfDecl(CD, ELoc);
629 DiscardCleanupsInEvaluationContext();
630 PopExpressionEvaluationContext();
635 class VarDeclFilterCCC : public CorrectionCandidateCallback {
640 explicit VarDeclFilterCCC(Sema &S) : SemaRef(S) {}
641 bool ValidateCandidate(const TypoCorrection &Candidate) override {
642 NamedDecl *ND = Candidate.getCorrectionDecl();
643 if (VarDecl *VD = dyn_cast_or_null<VarDecl>(ND)) {
644 return VD->hasGlobalStorage() &&
645 SemaRef.isDeclInScope(ND, SemaRef.getCurLexicalContext(),
646 SemaRef.getCurScope());
653 ExprResult Sema::ActOnOpenMPIdExpression(Scope *CurScope,
654 CXXScopeSpec &ScopeSpec,
655 const DeclarationNameInfo &Id) {
656 LookupResult Lookup(*this, Id, LookupOrdinaryName);
657 LookupParsedName(Lookup, CurScope, &ScopeSpec, true);
659 if (Lookup.isAmbiguous())
663 if (!Lookup.isSingleResult()) {
664 if (TypoCorrection Corrected = CorrectTypo(
665 Id, LookupOrdinaryName, CurScope, nullptr,
666 llvm::make_unique<VarDeclFilterCCC>(*this), CTK_ErrorRecovery)) {
667 diagnoseTypo(Corrected,
669 ? diag::err_undeclared_var_use_suggest
670 : diag::err_omp_expected_var_arg_suggest)
672 VD = Corrected.getCorrectionDeclAs<VarDecl>();
674 Diag(Id.getLoc(), Lookup.empty() ? diag::err_undeclared_var_use
675 : diag::err_omp_expected_var_arg)
680 if (!(VD = Lookup.getAsSingle<VarDecl>())) {
681 Diag(Id.getLoc(), diag::err_omp_expected_var_arg) << Id.getName();
682 Diag(Lookup.getFoundDecl()->getLocation(), diag::note_declared_at);
686 Lookup.suppressDiagnostics();
688 // OpenMP [2.9.2, Syntax, C/C++]
689 // Variables must be file-scope, namespace-scope, or static block-scope.
690 if (!VD->hasGlobalStorage()) {
691 Diag(Id.getLoc(), diag::err_omp_global_var_arg)
692 << getOpenMPDirectiveName(OMPD_threadprivate) << !VD->isStaticLocal();
694 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
695 Diag(VD->getLocation(),
696 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
701 VarDecl *CanonicalVD = VD->getCanonicalDecl();
702 NamedDecl *ND = cast<NamedDecl>(CanonicalVD);
703 // OpenMP [2.9.2, Restrictions, C/C++, p.2]
704 // A threadprivate directive for file-scope variables must appear outside
705 // any definition or declaration.
706 if (CanonicalVD->getDeclContext()->isTranslationUnit() &&
707 !getCurLexicalContext()->isTranslationUnit()) {
708 Diag(Id.getLoc(), diag::err_omp_var_scope)
709 << getOpenMPDirectiveName(OMPD_threadprivate) << VD;
711 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
712 Diag(VD->getLocation(),
713 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
717 // OpenMP [2.9.2, Restrictions, C/C++, p.3]
718 // A threadprivate directive for static class member variables must appear
719 // in the class definition, in the same scope in which the member
720 // variables are declared.
721 if (CanonicalVD->isStaticDataMember() &&
722 !CanonicalVD->getDeclContext()->Equals(getCurLexicalContext())) {
723 Diag(Id.getLoc(), diag::err_omp_var_scope)
724 << getOpenMPDirectiveName(OMPD_threadprivate) << VD;
726 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
727 Diag(VD->getLocation(),
728 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
732 // OpenMP [2.9.2, Restrictions, C/C++, p.4]
733 // A threadprivate directive for namespace-scope variables must appear
734 // outside any definition or declaration other than the namespace
735 // definition itself.
736 if (CanonicalVD->getDeclContext()->isNamespace() &&
737 (!getCurLexicalContext()->isFileContext() ||
738 !getCurLexicalContext()->Encloses(CanonicalVD->getDeclContext()))) {
739 Diag(Id.getLoc(), diag::err_omp_var_scope)
740 << getOpenMPDirectiveName(OMPD_threadprivate) << VD;
742 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
743 Diag(VD->getLocation(),
744 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
748 // OpenMP [2.9.2, Restrictions, C/C++, p.6]
749 // A threadprivate directive for static block-scope variables must appear
750 // in the scope of the variable and not in a nested scope.
751 if (CanonicalVD->isStaticLocal() && CurScope &&
752 !isDeclInScope(ND, getCurLexicalContext(), CurScope)) {
753 Diag(Id.getLoc(), diag::err_omp_var_scope)
754 << getOpenMPDirectiveName(OMPD_threadprivate) << VD;
756 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
757 Diag(VD->getLocation(),
758 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
763 // OpenMP [2.9.2, Restrictions, C/C++, p.2-6]
764 // A threadprivate directive must lexically precede all references to any
765 // of the variables in its list.
767 Diag(Id.getLoc(), diag::err_omp_var_used)
768 << getOpenMPDirectiveName(OMPD_threadprivate) << VD;
772 QualType ExprType = VD->getType().getNonReferenceType();
773 ExprResult DE = BuildDeclRefExpr(VD, ExprType, VK_LValue, Id.getLoc());
778 Sema::ActOnOpenMPThreadprivateDirective(SourceLocation Loc,
779 ArrayRef<Expr *> VarList) {
780 if (OMPThreadPrivateDecl *D = CheckOMPThreadPrivateDecl(Loc, VarList)) {
781 CurContext->addDecl(D);
782 return DeclGroupPtrTy::make(DeclGroupRef(D));
784 return DeclGroupPtrTy();
788 class LocalVarRefChecker : public ConstStmtVisitor<LocalVarRefChecker, bool> {
792 bool VisitDeclRefExpr(const DeclRefExpr *E) {
793 if (auto VD = dyn_cast<VarDecl>(E->getDecl())) {
794 if (VD->hasLocalStorage()) {
795 SemaRef.Diag(E->getLocStart(),
796 diag::err_omp_local_var_in_threadprivate_init)
797 << E->getSourceRange();
798 SemaRef.Diag(VD->getLocation(), diag::note_defined_here)
799 << VD << VD->getSourceRange();
805 bool VisitStmt(const Stmt *S) {
806 for (auto Child : S->children()) {
807 if (Child && Visit(Child))
812 explicit LocalVarRefChecker(Sema &SemaRef) : SemaRef(SemaRef) {}
816 OMPThreadPrivateDecl *
817 Sema::CheckOMPThreadPrivateDecl(SourceLocation Loc, ArrayRef<Expr *> VarList) {
818 SmallVector<Expr *, 8> Vars;
819 for (auto &RefExpr : VarList) {
820 DeclRefExpr *DE = cast<DeclRefExpr>(RefExpr);
821 VarDecl *VD = cast<VarDecl>(DE->getDecl());
822 SourceLocation ILoc = DE->getExprLoc();
824 // OpenMP [2.9.2, Restrictions, C/C++, p.10]
825 // A threadprivate variable must not have an incomplete type.
826 if (RequireCompleteType(ILoc, VD->getType(),
827 diag::err_omp_threadprivate_incomplete_type)) {
831 // OpenMP [2.9.2, Restrictions, C/C++, p.10]
832 // A threadprivate variable must not have a reference type.
833 if (VD->getType()->isReferenceType()) {
834 Diag(ILoc, diag::err_omp_ref_type_arg)
835 << getOpenMPDirectiveName(OMPD_threadprivate) << VD->getType();
837 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
838 Diag(VD->getLocation(),
839 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
844 // Check if this is a TLS variable.
845 if (VD->getTLSKind() != VarDecl::TLS_None ||
846 VD->getStorageClass() == SC_Register) {
847 Diag(ILoc, diag::err_omp_var_thread_local)
848 << VD << ((VD->getTLSKind() != VarDecl::TLS_None) ? 0 : 1);
850 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
851 Diag(VD->getLocation(),
852 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
857 // Check if initial value of threadprivate variable reference variable with
858 // local storage (it is not supported by runtime).
859 if (auto Init = VD->getAnyInitializer()) {
860 LocalVarRefChecker Checker(*this);
861 if (Checker.Visit(Init))
865 Vars.push_back(RefExpr);
866 DSAStack->addDSA(VD, DE, OMPC_threadprivate);
867 VD->addAttr(OMPThreadPrivateDeclAttr::CreateImplicit(
868 Context, SourceRange(Loc, Loc)));
869 if (auto *ML = Context.getASTMutationListener())
870 ML->DeclarationMarkedOpenMPThreadPrivate(VD);
872 OMPThreadPrivateDecl *D = nullptr;
874 D = OMPThreadPrivateDecl::Create(Context, getCurLexicalContext(), Loc,
876 D->setAccess(AS_public);
881 static void ReportOriginalDSA(Sema &SemaRef, DSAStackTy *Stack,
882 const VarDecl *VD, DSAStackTy::DSAVarData DVar,
883 bool IsLoopIterVar = false) {
885 SemaRef.Diag(DVar.RefExpr->getExprLoc(), diag::note_omp_explicit_dsa)
886 << getOpenMPClauseName(DVar.CKind);
890 PDSA_StaticMemberShared,
891 PDSA_StaticLocalVarShared,
892 PDSA_LoopIterVarPrivate,
893 PDSA_LoopIterVarLinear,
894 PDSA_LoopIterVarLastprivate,
896 PDSA_GlobalVarShared,
897 PDSA_TaskVarFirstprivate,
898 PDSA_LocalVarPrivate,
900 } Reason = PDSA_Implicit;
901 bool ReportHint = false;
902 auto ReportLoc = VD->getLocation();
904 if (DVar.CKind == OMPC_private)
905 Reason = PDSA_LoopIterVarPrivate;
906 else if (DVar.CKind == OMPC_lastprivate)
907 Reason = PDSA_LoopIterVarLastprivate;
909 Reason = PDSA_LoopIterVarLinear;
910 } else if (DVar.DKind == OMPD_task && DVar.CKind == OMPC_firstprivate) {
911 Reason = PDSA_TaskVarFirstprivate;
912 ReportLoc = DVar.ImplicitDSALoc;
913 } else if (VD->isStaticLocal())
914 Reason = PDSA_StaticLocalVarShared;
915 else if (VD->isStaticDataMember())
916 Reason = PDSA_StaticMemberShared;
917 else if (VD->isFileVarDecl())
918 Reason = PDSA_GlobalVarShared;
919 else if (VD->getType().isConstant(SemaRef.getASTContext()))
920 Reason = PDSA_ConstVarShared;
921 else if (VD->isLocalVarDecl() && DVar.CKind == OMPC_private) {
923 Reason = PDSA_LocalVarPrivate;
925 if (Reason != PDSA_Implicit) {
926 SemaRef.Diag(ReportLoc, diag::note_omp_predetermined_dsa)
927 << Reason << ReportHint
928 << getOpenMPDirectiveName(Stack->getCurrentDirective());
929 } else if (DVar.ImplicitDSALoc.isValid()) {
930 SemaRef.Diag(DVar.ImplicitDSALoc, diag::note_omp_implicit_dsa)
931 << getOpenMPClauseName(DVar.CKind);
936 class DSAAttrChecker : public StmtVisitor<DSAAttrChecker, void> {
941 llvm::SmallVector<Expr *, 8> ImplicitFirstprivate;
942 llvm::DenseMap<VarDecl *, Expr *> VarsWithInheritedDSA;
945 void VisitDeclRefExpr(DeclRefExpr *E) {
946 if (auto *VD = dyn_cast<VarDecl>(E->getDecl())) {
947 // Skip internally declared variables.
948 if (VD->isLocalVarDecl() && !CS->capturesVariable(VD))
951 auto DVar = Stack->getTopDSA(VD, false);
952 // Check if the variable has explicit DSA set and stop analysis if it so.
953 if (DVar.RefExpr) return;
955 auto ELoc = E->getExprLoc();
956 auto DKind = Stack->getCurrentDirective();
957 // The default(none) clause requires that each variable that is referenced
958 // in the construct, and does not have a predetermined data-sharing
959 // attribute, must have its data-sharing attribute explicitly determined
960 // by being listed in a data-sharing attribute clause.
961 if (DVar.CKind == OMPC_unknown && Stack->getDefaultDSA() == DSA_none &&
962 isParallelOrTaskRegion(DKind) &&
963 VarsWithInheritedDSA.count(VD) == 0) {
964 VarsWithInheritedDSA[VD] = E;
968 // OpenMP [2.9.3.6, Restrictions, p.2]
969 // A list item that appears in a reduction clause of the innermost
970 // enclosing worksharing or parallel construct may not be accessed in an
972 DVar = Stack->hasInnermostDSA(VD, MatchesAnyClause(OMPC_reduction),
973 [](OpenMPDirectiveKind K) -> bool {
974 return isOpenMPParallelDirective(K) ||
975 isOpenMPWorksharingDirective(K) ||
976 isOpenMPTeamsDirective(K);
979 if (DKind == OMPD_task && DVar.CKind == OMPC_reduction) {
981 SemaRef.Diag(ELoc, diag::err_omp_reduction_in_task);
982 ReportOriginalDSA(SemaRef, Stack, VD, DVar);
986 // Define implicit data-sharing attributes for task.
987 DVar = Stack->getImplicitDSA(VD, false);
988 if (DKind == OMPD_task && DVar.CKind != OMPC_shared)
989 ImplicitFirstprivate.push_back(E);
992 void VisitOMPExecutableDirective(OMPExecutableDirective *S) {
993 for (auto *C : S->clauses()) {
994 // Skip analysis of arguments of implicitly defined firstprivate clause
995 // for task directives.
996 if (C && (!isa<OMPFirstprivateClause>(C) || C->getLocStart().isValid()))
997 for (auto *CC : C->children()) {
1003 void VisitStmt(Stmt *S) {
1004 for (auto *C : S->children()) {
1005 if (C && !isa<OMPExecutableDirective>(C))
1010 bool isErrorFound() { return ErrorFound; }
1011 ArrayRef<Expr *> getImplicitFirstprivate() { return ImplicitFirstprivate; }
1012 llvm::DenseMap<VarDecl *, Expr *> &getVarsWithInheritedDSA() {
1013 return VarsWithInheritedDSA;
1016 DSAAttrChecker(DSAStackTy *S, Sema &SemaRef, CapturedStmt *CS)
1017 : Stack(S), SemaRef(SemaRef), ErrorFound(false), CS(CS) {}
1021 void Sema::ActOnOpenMPRegionStart(OpenMPDirectiveKind DKind, Scope *CurScope) {
1023 case OMPD_parallel: {
1024 QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1);
1025 QualType KmpInt32PtrTy = Context.getPointerType(KmpInt32Ty);
1026 Sema::CapturedParamNameType Params[] = {
1027 std::make_pair(".global_tid.", KmpInt32PtrTy),
1028 std::make_pair(".bound_tid.", KmpInt32PtrTy),
1029 std::make_pair(StringRef(), QualType()) // __context with shared vars
1031 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
1036 Sema::CapturedParamNameType Params[] = {
1037 std::make_pair(StringRef(), QualType()) // __context with shared vars
1039 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
1044 Sema::CapturedParamNameType Params[] = {
1045 std::make_pair(StringRef(), QualType()) // __context with shared vars
1047 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
1051 case OMPD_for_simd: {
1052 Sema::CapturedParamNameType Params[] = {
1053 std::make_pair(StringRef(), QualType()) // __context with shared vars
1055 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
1059 case OMPD_sections: {
1060 Sema::CapturedParamNameType Params[] = {
1061 std::make_pair(StringRef(), QualType()) // __context with shared vars
1063 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
1067 case OMPD_section: {
1068 Sema::CapturedParamNameType Params[] = {
1069 std::make_pair(StringRef(), QualType()) // __context with shared vars
1071 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
1076 Sema::CapturedParamNameType Params[] = {
1077 std::make_pair(StringRef(), QualType()) // __context with shared vars
1079 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
1084 Sema::CapturedParamNameType Params[] = {
1085 std::make_pair(StringRef(), QualType()) // __context with shared vars
1087 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
1091 case OMPD_critical: {
1092 Sema::CapturedParamNameType Params[] = {
1093 std::make_pair(StringRef(), QualType()) // __context with shared vars
1095 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
1099 case OMPD_parallel_for: {
1100 QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1);
1101 QualType KmpInt32PtrTy = Context.getPointerType(KmpInt32Ty);
1102 Sema::CapturedParamNameType Params[] = {
1103 std::make_pair(".global_tid.", KmpInt32PtrTy),
1104 std::make_pair(".bound_tid.", KmpInt32PtrTy),
1105 std::make_pair(StringRef(), QualType()) // __context with shared vars
1107 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
1111 case OMPD_parallel_for_simd: {
1112 QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1);
1113 QualType KmpInt32PtrTy = Context.getPointerType(KmpInt32Ty);
1114 Sema::CapturedParamNameType Params[] = {
1115 std::make_pair(".global_tid.", KmpInt32PtrTy),
1116 std::make_pair(".bound_tid.", KmpInt32PtrTy),
1117 std::make_pair(StringRef(), QualType()) // __context with shared vars
1119 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
1123 case OMPD_parallel_sections: {
1124 Sema::CapturedParamNameType Params[] = {
1125 std::make_pair(StringRef(), QualType()) // __context with shared vars
1127 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
1132 Sema::CapturedParamNameType Params[] = {
1133 std::make_pair(StringRef(), QualType()) // __context with shared vars
1135 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
1139 case OMPD_ordered: {
1140 Sema::CapturedParamNameType Params[] = {
1141 std::make_pair(StringRef(), QualType()) // __context with shared vars
1143 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
1148 Sema::CapturedParamNameType Params[] = {
1149 std::make_pair(StringRef(), QualType()) // __context with shared vars
1151 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
1156 Sema::CapturedParamNameType Params[] = {
1157 std::make_pair(StringRef(), QualType()) // __context with shared vars
1159 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
1164 QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1);
1165 QualType KmpInt32PtrTy = Context.getPointerType(KmpInt32Ty);
1166 Sema::CapturedParamNameType Params[] = {
1167 std::make_pair(".global_tid.", KmpInt32PtrTy),
1168 std::make_pair(".bound_tid.", KmpInt32PtrTy),
1169 std::make_pair(StringRef(), QualType()) // __context with shared vars
1171 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
1175 case OMPD_threadprivate:
1176 case OMPD_taskyield:
1180 llvm_unreachable("OpenMP Directive is not allowed");
1182 llvm_unreachable("Unknown OpenMP directive");
1186 static bool CheckNestingOfRegions(Sema &SemaRef, DSAStackTy *Stack,
1187 OpenMPDirectiveKind CurrentRegion,
1188 const DeclarationNameInfo &CurrentName,
1189 SourceLocation StartLoc) {
1190 // Allowed nesting of constructs
1191 // +------------------+-----------------+------------------------------------+
1192 // | Parent directive | Child directive | Closely (!), No-Closely(+), Both(*)|
1193 // +------------------+-----------------+------------------------------------+
1194 // | parallel | parallel | * |
1195 // | parallel | for | * |
1196 // | parallel | for simd | * |
1197 // | parallel | master | * |
1198 // | parallel | critical | * |
1199 // | parallel | simd | * |
1200 // | parallel | sections | * |
1201 // | parallel | section | + |
1202 // | parallel | single | * |
1203 // | parallel | parallel for | * |
1204 // | parallel |parallel for simd| * |
1205 // | parallel |parallel sections| * |
1206 // | parallel | task | * |
1207 // | parallel | taskyield | * |
1208 // | parallel | barrier | * |
1209 // | parallel | taskwait | * |
1210 // | parallel | flush | * |
1211 // | parallel | ordered | + |
1212 // | parallel | atomic | * |
1213 // | parallel | target | * |
1214 // | parallel | teams | + |
1215 // +------------------+-----------------+------------------------------------+
1216 // | for | parallel | * |
1217 // | for | for | + |
1218 // | for | for simd | + |
1219 // | for | master | + |
1220 // | for | critical | * |
1221 // | for | simd | * |
1222 // | for | sections | + |
1223 // | for | section | + |
1224 // | for | single | + |
1225 // | for | parallel for | * |
1226 // | for |parallel for simd| * |
1227 // | for |parallel sections| * |
1228 // | for | task | * |
1229 // | for | taskyield | * |
1230 // | for | barrier | + |
1231 // | for | taskwait | * |
1232 // | for | flush | * |
1233 // | for | ordered | * (if construct is ordered) |
1234 // | for | atomic | * |
1235 // | for | target | * |
1236 // | for | teams | + |
1237 // +------------------+-----------------+------------------------------------+
1238 // | master | parallel | * |
1239 // | master | for | + |
1240 // | master | for simd | + |
1241 // | master | master | * |
1242 // | master | critical | * |
1243 // | master | simd | * |
1244 // | master | sections | + |
1245 // | master | section | + |
1246 // | master | single | + |
1247 // | master | parallel for | * |
1248 // | master |parallel for simd| * |
1249 // | master |parallel sections| * |
1250 // | master | task | * |
1251 // | master | taskyield | * |
1252 // | master | barrier | + |
1253 // | master | taskwait | * |
1254 // | master | flush | * |
1255 // | master | ordered | + |
1256 // | master | atomic | * |
1257 // | master | target | * |
1258 // | master | teams | + |
1259 // +------------------+-----------------+------------------------------------+
1260 // | critical | parallel | * |
1261 // | critical | for | + |
1262 // | critical | for simd | + |
1263 // | critical | master | * |
1264 // | critical | critical | * (should have different names) |
1265 // | critical | simd | * |
1266 // | critical | sections | + |
1267 // | critical | section | + |
1268 // | critical | single | + |
1269 // | critical | parallel for | * |
1270 // | critical |parallel for simd| * |
1271 // | critical |parallel sections| * |
1272 // | critical | task | * |
1273 // | critical | taskyield | * |
1274 // | critical | barrier | + |
1275 // | critical | taskwait | * |
1276 // | critical | ordered | + |
1277 // | critical | atomic | * |
1278 // | critical | target | * |
1279 // | critical | teams | + |
1280 // +------------------+-----------------+------------------------------------+
1281 // | simd | parallel | |
1283 // | simd | for simd | |
1284 // | simd | master | |
1285 // | simd | critical | |
1286 // | simd | simd | |
1287 // | simd | sections | |
1288 // | simd | section | |
1289 // | simd | single | |
1290 // | simd | parallel for | |
1291 // | simd |parallel for simd| |
1292 // | simd |parallel sections| |
1293 // | simd | task | |
1294 // | simd | taskyield | |
1295 // | simd | barrier | |
1296 // | simd | taskwait | |
1297 // | simd | flush | |
1298 // | simd | ordered | |
1299 // | simd | atomic | |
1300 // | simd | target | |
1301 // | simd | teams | |
1302 // +------------------+-----------------+------------------------------------+
1303 // | for simd | parallel | |
1304 // | for simd | for | |
1305 // | for simd | for simd | |
1306 // | for simd | master | |
1307 // | for simd | critical | |
1308 // | for simd | simd | |
1309 // | for simd | sections | |
1310 // | for simd | section | |
1311 // | for simd | single | |
1312 // | for simd | parallel for | |
1313 // | for simd |parallel for simd| |
1314 // | for simd |parallel sections| |
1315 // | for simd | task | |
1316 // | for simd | taskyield | |
1317 // | for simd | barrier | |
1318 // | for simd | taskwait | |
1319 // | for simd | flush | |
1320 // | for simd | ordered | |
1321 // | for simd | atomic | |
1322 // | for simd | target | |
1323 // | for simd | teams | |
1324 // +------------------+-----------------+------------------------------------+
1325 // | parallel for simd| parallel | |
1326 // | parallel for simd| for | |
1327 // | parallel for simd| for simd | |
1328 // | parallel for simd| master | |
1329 // | parallel for simd| critical | |
1330 // | parallel for simd| simd | |
1331 // | parallel for simd| sections | |
1332 // | parallel for simd| section | |
1333 // | parallel for simd| single | |
1334 // | parallel for simd| parallel for | |
1335 // | parallel for simd|parallel for simd| |
1336 // | parallel for simd|parallel sections| |
1337 // | parallel for simd| task | |
1338 // | parallel for simd| taskyield | |
1339 // | parallel for simd| barrier | |
1340 // | parallel for simd| taskwait | |
1341 // | parallel for simd| flush | |
1342 // | parallel for simd| ordered | |
1343 // | parallel for simd| atomic | |
1344 // | parallel for simd| target | |
1345 // | parallel for simd| teams | |
1346 // +------------------+-----------------+------------------------------------+
1347 // | sections | parallel | * |
1348 // | sections | for | + |
1349 // | sections | for simd | + |
1350 // | sections | master | + |
1351 // | sections | critical | * |
1352 // | sections | simd | * |
1353 // | sections | sections | + |
1354 // | sections | section | * |
1355 // | sections | single | + |
1356 // | sections | parallel for | * |
1357 // | sections |parallel for simd| * |
1358 // | sections |parallel sections| * |
1359 // | sections | task | * |
1360 // | sections | taskyield | * |
1361 // | sections | barrier | + |
1362 // | sections | taskwait | * |
1363 // | sections | flush | * |
1364 // | sections | ordered | + |
1365 // | sections | atomic | * |
1366 // | sections | target | * |
1367 // | sections | teams | + |
1368 // +------------------+-----------------+------------------------------------+
1369 // | section | parallel | * |
1370 // | section | for | + |
1371 // | section | for simd | + |
1372 // | section | master | + |
1373 // | section | critical | * |
1374 // | section | simd | * |
1375 // | section | sections | + |
1376 // | section | section | + |
1377 // | section | single | + |
1378 // | section | parallel for | * |
1379 // | section |parallel for simd| * |
1380 // | section |parallel sections| * |
1381 // | section | task | * |
1382 // | section | taskyield | * |
1383 // | section | barrier | + |
1384 // | section | taskwait | * |
1385 // | section | flush | * |
1386 // | section | ordered | + |
1387 // | section | atomic | * |
1388 // | section | target | * |
1389 // | section | teams | + |
1390 // +------------------+-----------------+------------------------------------+
1391 // | single | parallel | * |
1392 // | single | for | + |
1393 // | single | for simd | + |
1394 // | single | master | + |
1395 // | single | critical | * |
1396 // | single | simd | * |
1397 // | single | sections | + |
1398 // | single | section | + |
1399 // | single | single | + |
1400 // | single | parallel for | * |
1401 // | single |parallel for simd| * |
1402 // | single |parallel sections| * |
1403 // | single | task | * |
1404 // | single | taskyield | * |
1405 // | single | barrier | + |
1406 // | single | taskwait | * |
1407 // | single | flush | * |
1408 // | single | ordered | + |
1409 // | single | atomic | * |
1410 // | single | target | * |
1411 // | single | teams | + |
1412 // +------------------+-----------------+------------------------------------+
1413 // | parallel for | parallel | * |
1414 // | parallel for | for | + |
1415 // | parallel for | for simd | + |
1416 // | parallel for | master | + |
1417 // | parallel for | critical | * |
1418 // | parallel for | simd | * |
1419 // | parallel for | sections | + |
1420 // | parallel for | section | + |
1421 // | parallel for | single | + |
1422 // | parallel for | parallel for | * |
1423 // | parallel for |parallel for simd| * |
1424 // | parallel for |parallel sections| * |
1425 // | parallel for | task | * |
1426 // | parallel for | taskyield | * |
1427 // | parallel for | barrier | + |
1428 // | parallel for | taskwait | * |
1429 // | parallel for | flush | * |
1430 // | parallel for | ordered | * (if construct is ordered) |
1431 // | parallel for | atomic | * |
1432 // | parallel for | target | * |
1433 // | parallel for | teams | + |
1434 // +------------------+-----------------+------------------------------------+
1435 // | parallel sections| parallel | * |
1436 // | parallel sections| for | + |
1437 // | parallel sections| for simd | + |
1438 // | parallel sections| master | + |
1439 // | parallel sections| critical | + |
1440 // | parallel sections| simd | * |
1441 // | parallel sections| sections | + |
1442 // | parallel sections| section | * |
1443 // | parallel sections| single | + |
1444 // | parallel sections| parallel for | * |
1445 // | parallel sections|parallel for simd| * |
1446 // | parallel sections|parallel sections| * |
1447 // | parallel sections| task | * |
1448 // | parallel sections| taskyield | * |
1449 // | parallel sections| barrier | + |
1450 // | parallel sections| taskwait | * |
1451 // | parallel sections| flush | * |
1452 // | parallel sections| ordered | + |
1453 // | parallel sections| atomic | * |
1454 // | parallel sections| target | * |
1455 // | parallel sections| teams | + |
1456 // +------------------+-----------------+------------------------------------+
1457 // | task | parallel | * |
1458 // | task | for | + |
1459 // | task | for simd | + |
1460 // | task | master | + |
1461 // | task | critical | * |
1462 // | task | simd | * |
1463 // | task | sections | + |
1464 // | task | section | + |
1465 // | task | single | + |
1466 // | task | parallel for | * |
1467 // | task |parallel for simd| * |
1468 // | task |parallel sections| * |
1469 // | task | task | * |
1470 // | task | taskyield | * |
1471 // | task | barrier | + |
1472 // | task | taskwait | * |
1473 // | task | flush | * |
1474 // | task | ordered | + |
1475 // | task | atomic | * |
1476 // | task | target | * |
1477 // | task | teams | + |
1478 // +------------------+-----------------+------------------------------------+
1479 // | ordered | parallel | * |
1480 // | ordered | for | + |
1481 // | ordered | for simd | + |
1482 // | ordered | master | * |
1483 // | ordered | critical | * |
1484 // | ordered | simd | * |
1485 // | ordered | sections | + |
1486 // | ordered | section | + |
1487 // | ordered | single | + |
1488 // | ordered | parallel for | * |
1489 // | ordered |parallel for simd| * |
1490 // | ordered |parallel sections| * |
1491 // | ordered | task | * |
1492 // | ordered | taskyield | * |
1493 // | ordered | barrier | + |
1494 // | ordered | taskwait | * |
1495 // | ordered | flush | * |
1496 // | ordered | ordered | + |
1497 // | ordered | atomic | * |
1498 // | ordered | target | * |
1499 // | ordered | teams | + |
1500 // +------------------+-----------------+------------------------------------+
1501 // | atomic | parallel | |
1502 // | atomic | for | |
1503 // | atomic | for simd | |
1504 // | atomic | master | |
1505 // | atomic | critical | |
1506 // | atomic | simd | |
1507 // | atomic | sections | |
1508 // | atomic | section | |
1509 // | atomic | single | |
1510 // | atomic | parallel for | |
1511 // | atomic |parallel for simd| |
1512 // | atomic |parallel sections| |
1513 // | atomic | task | |
1514 // | atomic | taskyield | |
1515 // | atomic | barrier | |
1516 // | atomic | taskwait | |
1517 // | atomic | flush | |
1518 // | atomic | ordered | |
1519 // | atomic | atomic | |
1520 // | atomic | target | |
1521 // | atomic | teams | |
1522 // +------------------+-----------------+------------------------------------+
1523 // | target | parallel | * |
1524 // | target | for | * |
1525 // | target | for simd | * |
1526 // | target | master | * |
1527 // | target | critical | * |
1528 // | target | simd | * |
1529 // | target | sections | * |
1530 // | target | section | * |
1531 // | target | single | * |
1532 // | target | parallel for | * |
1533 // | target |parallel for simd| * |
1534 // | target |parallel sections| * |
1535 // | target | task | * |
1536 // | target | taskyield | * |
1537 // | target | barrier | * |
1538 // | target | taskwait | * |
1539 // | target | flush | * |
1540 // | target | ordered | * |
1541 // | target | atomic | * |
1542 // | target | target | * |
1543 // | target | teams | * |
1544 // +------------------+-----------------+------------------------------------+
1545 // | teams | parallel | * |
1546 // | teams | for | + |
1547 // | teams | for simd | + |
1548 // | teams | master | + |
1549 // | teams | critical | + |
1550 // | teams | simd | + |
1551 // | teams | sections | + |
1552 // | teams | section | + |
1553 // | teams | single | + |
1554 // | teams | parallel for | * |
1555 // | teams |parallel for simd| * |
1556 // | teams |parallel sections| * |
1557 // | teams | task | + |
1558 // | teams | taskyield | + |
1559 // | teams | barrier | + |
1560 // | teams | taskwait | + |
1561 // | teams | flush | + |
1562 // | teams | ordered | + |
1563 // | teams | atomic | + |
1564 // | teams | target | + |
1565 // | teams | teams | + |
1566 // +------------------+-----------------+------------------------------------+
1567 if (Stack->getCurScope()) {
1568 auto ParentRegion = Stack->getParentDirective();
1569 bool NestingProhibited = false;
1570 bool CloseNesting = true;
1573 ShouldBeInParallelRegion,
1574 ShouldBeInOrderedRegion,
1575 ShouldBeInTargetRegion
1576 } Recommend = NoRecommend;
1577 if (isOpenMPSimdDirective(ParentRegion)) {
1578 // OpenMP [2.16, Nesting of Regions]
1579 // OpenMP constructs may not be nested inside a simd region.
1580 SemaRef.Diag(StartLoc, diag::err_omp_prohibited_region_simd);
1583 if (ParentRegion == OMPD_atomic) {
1584 // OpenMP [2.16, Nesting of Regions]
1585 // OpenMP constructs may not be nested inside an atomic region.
1586 SemaRef.Diag(StartLoc, diag::err_omp_prohibited_region_atomic);
1589 if (CurrentRegion == OMPD_section) {
1590 // OpenMP [2.7.2, sections Construct, Restrictions]
1591 // Orphaned section directives are prohibited. That is, the section
1592 // directives must appear within the sections construct and must not be
1593 // encountered elsewhere in the sections region.
1594 if (ParentRegion != OMPD_sections &&
1595 ParentRegion != OMPD_parallel_sections) {
1596 SemaRef.Diag(StartLoc, diag::err_omp_orphaned_section_directive)
1597 << (ParentRegion != OMPD_unknown)
1598 << getOpenMPDirectiveName(ParentRegion);
1603 // Allow some constructs to be orphaned (they could be used in functions,
1604 // called from OpenMP regions with the required preconditions).
1605 if (ParentRegion == OMPD_unknown)
1607 if (CurrentRegion == OMPD_master) {
1608 // OpenMP [2.16, Nesting of Regions]
1609 // A master region may not be closely nested inside a worksharing,
1610 // atomic, or explicit task region.
1611 NestingProhibited = isOpenMPWorksharingDirective(ParentRegion) ||
1612 ParentRegion == OMPD_task;
1613 } else if (CurrentRegion == OMPD_critical && CurrentName.getName()) {
1614 // OpenMP [2.16, Nesting of Regions]
1615 // A critical region may not be nested (closely or otherwise) inside a
1616 // critical region with the same name. Note that this restriction is not
1617 // sufficient to prevent deadlock.
1618 SourceLocation PreviousCriticalLoc;
1620 Stack->hasDirective([CurrentName, &PreviousCriticalLoc](
1621 OpenMPDirectiveKind K,
1622 const DeclarationNameInfo &DNI,
1625 if (K == OMPD_critical &&
1626 DNI.getName() == CurrentName.getName()) {
1627 PreviousCriticalLoc = Loc;
1632 false /* skip top directive */);
1634 SemaRef.Diag(StartLoc,
1635 diag::err_omp_prohibited_region_critical_same_name)
1636 << CurrentName.getName();
1637 if (PreviousCriticalLoc.isValid())
1638 SemaRef.Diag(PreviousCriticalLoc,
1639 diag::note_omp_previous_critical_region);
1642 } else if (CurrentRegion == OMPD_barrier) {
1643 // OpenMP [2.16, Nesting of Regions]
1644 // A barrier region may not be closely nested inside a worksharing,
1645 // explicit task, critical, ordered, atomic, or master region.
1647 isOpenMPWorksharingDirective(ParentRegion) ||
1648 ParentRegion == OMPD_task || ParentRegion == OMPD_master ||
1649 ParentRegion == OMPD_critical || ParentRegion == OMPD_ordered;
1650 } else if (isOpenMPWorksharingDirective(CurrentRegion) &&
1651 !isOpenMPParallelDirective(CurrentRegion)) {
1652 // OpenMP [2.16, Nesting of Regions]
1653 // A worksharing region may not be closely nested inside a worksharing,
1654 // explicit task, critical, ordered, atomic, or master region.
1656 isOpenMPWorksharingDirective(ParentRegion) ||
1657 ParentRegion == OMPD_task || ParentRegion == OMPD_master ||
1658 ParentRegion == OMPD_critical || ParentRegion == OMPD_ordered;
1659 Recommend = ShouldBeInParallelRegion;
1660 } else if (CurrentRegion == OMPD_ordered) {
1661 // OpenMP [2.16, Nesting of Regions]
1662 // An ordered region may not be closely nested inside a critical,
1663 // atomic, or explicit task region.
1664 // An ordered region must be closely nested inside a loop region (or
1665 // parallel loop region) with an ordered clause.
1666 NestingProhibited = ParentRegion == OMPD_critical ||
1667 ParentRegion == OMPD_task ||
1668 !Stack->isParentOrderedRegion();
1669 Recommend = ShouldBeInOrderedRegion;
1670 } else if (isOpenMPTeamsDirective(CurrentRegion)) {
1671 // OpenMP [2.16, Nesting of Regions]
1672 // If specified, a teams construct must be contained within a target
1674 NestingProhibited = ParentRegion != OMPD_target;
1675 Recommend = ShouldBeInTargetRegion;
1676 Stack->setParentTeamsRegionLoc(Stack->getConstructLoc());
1678 if (!NestingProhibited && isOpenMPTeamsDirective(ParentRegion)) {
1679 // OpenMP [2.16, Nesting of Regions]
1680 // distribute, parallel, parallel sections, parallel workshare, and the
1681 // parallel loop and parallel loop SIMD constructs are the only OpenMP
1682 // constructs that can be closely nested in the teams region.
1683 // TODO: add distribute directive.
1684 NestingProhibited = !isOpenMPParallelDirective(CurrentRegion);
1685 Recommend = ShouldBeInParallelRegion;
1687 if (NestingProhibited) {
1688 SemaRef.Diag(StartLoc, diag::err_omp_prohibited_region)
1689 << CloseNesting << getOpenMPDirectiveName(ParentRegion) << Recommend
1690 << getOpenMPDirectiveName(CurrentRegion);
1697 StmtResult Sema::ActOnOpenMPExecutableDirective(OpenMPDirectiveKind Kind,
1698 const DeclarationNameInfo &DirName,
1699 ArrayRef<OMPClause *> Clauses,
1701 SourceLocation StartLoc,
1702 SourceLocation EndLoc) {
1703 StmtResult Res = StmtError();
1704 if (CheckNestingOfRegions(*this, DSAStack, Kind, DirName, StartLoc))
1707 llvm::SmallVector<OMPClause *, 8> ClausesWithImplicit;
1708 llvm::DenseMap<VarDecl *, Expr *> VarsWithInheritedDSA;
1709 bool ErrorFound = false;
1710 ClausesWithImplicit.append(Clauses.begin(), Clauses.end());
1712 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
1714 // Check default data sharing attributes for referenced variables.
1715 DSAAttrChecker DSAChecker(DSAStack, *this, cast<CapturedStmt>(AStmt));
1716 DSAChecker.Visit(cast<CapturedStmt>(AStmt)->getCapturedStmt());
1717 if (DSAChecker.isErrorFound())
1719 // Generate list of implicitly defined firstprivate variables.
1720 VarsWithInheritedDSA = DSAChecker.getVarsWithInheritedDSA();
1722 if (!DSAChecker.getImplicitFirstprivate().empty()) {
1723 if (OMPClause *Implicit = ActOnOpenMPFirstprivateClause(
1724 DSAChecker.getImplicitFirstprivate(), SourceLocation(),
1725 SourceLocation(), SourceLocation())) {
1726 ClausesWithImplicit.push_back(Implicit);
1727 ErrorFound = cast<OMPFirstprivateClause>(Implicit)->varlist_size() !=
1728 DSAChecker.getImplicitFirstprivate().size();
1736 Res = ActOnOpenMPParallelDirective(ClausesWithImplicit, AStmt, StartLoc,
1740 Res = ActOnOpenMPSimdDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc,
1741 VarsWithInheritedDSA);
1744 Res = ActOnOpenMPForDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc,
1745 VarsWithInheritedDSA);
1748 Res = ActOnOpenMPForSimdDirective(ClausesWithImplicit, AStmt, StartLoc,
1749 EndLoc, VarsWithInheritedDSA);
1752 Res = ActOnOpenMPSectionsDirective(ClausesWithImplicit, AStmt, StartLoc,
1756 assert(ClausesWithImplicit.empty() &&
1757 "No clauses are allowed for 'omp section' directive");
1758 Res = ActOnOpenMPSectionDirective(AStmt, StartLoc, EndLoc);
1761 Res = ActOnOpenMPSingleDirective(ClausesWithImplicit, AStmt, StartLoc,
1765 assert(ClausesWithImplicit.empty() &&
1766 "No clauses are allowed for 'omp master' directive");
1767 Res = ActOnOpenMPMasterDirective(AStmt, StartLoc, EndLoc);
1770 assert(ClausesWithImplicit.empty() &&
1771 "No clauses are allowed for 'omp critical' directive");
1772 Res = ActOnOpenMPCriticalDirective(DirName, AStmt, StartLoc, EndLoc);
1774 case OMPD_parallel_for:
1775 Res = ActOnOpenMPParallelForDirective(ClausesWithImplicit, AStmt, StartLoc,
1776 EndLoc, VarsWithInheritedDSA);
1778 case OMPD_parallel_for_simd:
1779 Res = ActOnOpenMPParallelForSimdDirective(
1780 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
1782 case OMPD_parallel_sections:
1783 Res = ActOnOpenMPParallelSectionsDirective(ClausesWithImplicit, AStmt,
1788 ActOnOpenMPTaskDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc);
1790 case OMPD_taskyield:
1791 assert(ClausesWithImplicit.empty() &&
1792 "No clauses are allowed for 'omp taskyield' directive");
1793 assert(AStmt == nullptr &&
1794 "No associated statement allowed for 'omp taskyield' directive");
1795 Res = ActOnOpenMPTaskyieldDirective(StartLoc, EndLoc);
1798 assert(ClausesWithImplicit.empty() &&
1799 "No clauses are allowed for 'omp barrier' directive");
1800 assert(AStmt == nullptr &&
1801 "No associated statement allowed for 'omp barrier' directive");
1802 Res = ActOnOpenMPBarrierDirective(StartLoc, EndLoc);
1805 assert(ClausesWithImplicit.empty() &&
1806 "No clauses are allowed for 'omp taskwait' directive");
1807 assert(AStmt == nullptr &&
1808 "No associated statement allowed for 'omp taskwait' directive");
1809 Res = ActOnOpenMPTaskwaitDirective(StartLoc, EndLoc);
1812 assert(AStmt == nullptr &&
1813 "No associated statement allowed for 'omp flush' directive");
1814 Res = ActOnOpenMPFlushDirective(ClausesWithImplicit, StartLoc, EndLoc);
1817 assert(ClausesWithImplicit.empty() &&
1818 "No clauses are allowed for 'omp ordered' directive");
1819 Res = ActOnOpenMPOrderedDirective(AStmt, StartLoc, EndLoc);
1822 Res = ActOnOpenMPAtomicDirective(ClausesWithImplicit, AStmt, StartLoc,
1827 ActOnOpenMPTeamsDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc);
1830 Res = ActOnOpenMPTargetDirective(ClausesWithImplicit, AStmt, StartLoc,
1833 case OMPD_threadprivate:
1834 llvm_unreachable("OpenMP Directive is not allowed");
1836 llvm_unreachable("Unknown OpenMP directive");
1839 for (auto P : VarsWithInheritedDSA) {
1840 Diag(P.second->getExprLoc(), diag::err_omp_no_dsa_for_variable)
1841 << P.first << P.second->getSourceRange();
1843 if (!VarsWithInheritedDSA.empty())
1851 StmtResult Sema::ActOnOpenMPParallelDirective(ArrayRef<OMPClause *> Clauses,
1853 SourceLocation StartLoc,
1854 SourceLocation EndLoc) {
1855 assert(AStmt && isa<CapturedStmt>(AStmt) && "Captured statement expected");
1856 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
1857 // 1.2.2 OpenMP Language Terminology
1858 // Structured block - An executable statement with a single entry at the
1859 // top and a single exit at the bottom.
1860 // The point of exit cannot be a branch out of the structured block.
1861 // longjmp() and throw() must not violate the entry/exit criteria.
1862 CS->getCapturedDecl()->setNothrow();
1864 getCurFunction()->setHasBranchProtectedScope();
1866 return OMPParallelDirective::Create(Context, StartLoc, EndLoc, Clauses,
1871 /// \brief Helper class for checking canonical form of the OpenMP loops and
1872 /// extracting iteration space of each loop in the loop nest, that will be used
1873 /// for IR generation.
1874 class OpenMPIterationSpaceChecker {
1875 /// \brief Reference to Sema.
1877 /// \brief A location for diagnostics (when there is no some better location).
1878 SourceLocation DefaultLoc;
1879 /// \brief A location for diagnostics (when increment is not compatible).
1880 SourceLocation ConditionLoc;
1881 /// \brief A source location for referring to loop init later.
1882 SourceRange InitSrcRange;
1883 /// \brief A source location for referring to condition later.
1884 SourceRange ConditionSrcRange;
1885 /// \brief A source location for referring to increment later.
1886 SourceRange IncrementSrcRange;
1887 /// \brief Loop variable.
1889 /// \brief Reference to loop variable.
1890 DeclRefExpr *VarRef;
1891 /// \brief Lower bound (initializer for the var).
1893 /// \brief Upper bound.
1895 /// \brief Loop step (increment).
1897 /// \brief This flag is true when condition is one of:
1903 /// \brief This flag is true when condition is strict ( < or > ).
1904 bool TestIsStrictOp;
1905 /// \brief This flag is true when step is subtracted on each iteration.
1909 OpenMPIterationSpaceChecker(Sema &SemaRef, SourceLocation DefaultLoc)
1910 : SemaRef(SemaRef), DefaultLoc(DefaultLoc), ConditionLoc(DefaultLoc),
1911 InitSrcRange(SourceRange()), ConditionSrcRange(SourceRange()),
1912 IncrementSrcRange(SourceRange()), Var(nullptr), VarRef(nullptr),
1913 LB(nullptr), UB(nullptr), Step(nullptr), TestIsLessOp(false),
1914 TestIsStrictOp(false), SubtractStep(false) {}
1915 /// \brief Check init-expr for canonical loop form and save loop counter
1916 /// variable - #Var and its initialization value - #LB.
1917 bool CheckInit(Stmt *S);
1918 /// \brief Check test-expr for canonical form, save upper-bound (#UB), flags
1919 /// for less/greater and for strict/non-strict comparison.
1920 bool CheckCond(Expr *S);
1921 /// \brief Check incr-expr for canonical loop form and return true if it
1922 /// does not conform, otherwise save loop step (#Step).
1923 bool CheckInc(Expr *S);
1924 /// \brief Return the loop counter variable.
1925 VarDecl *GetLoopVar() const { return Var; }
1926 /// \brief Return the reference expression to loop counter variable.
1927 DeclRefExpr *GetLoopVarRefExpr() const { return VarRef; }
1928 /// \brief Source range of the loop init.
1929 SourceRange GetInitSrcRange() const { return InitSrcRange; }
1930 /// \brief Source range of the loop condition.
1931 SourceRange GetConditionSrcRange() const { return ConditionSrcRange; }
1932 /// \brief Source range of the loop increment.
1933 SourceRange GetIncrementSrcRange() const { return IncrementSrcRange; }
1934 /// \brief True if the step should be subtracted.
1935 bool ShouldSubtractStep() const { return SubtractStep; }
1936 /// \brief Build the expression to calculate the number of iterations.
1937 Expr *BuildNumIterations(Scope *S, const bool LimitedType) const;
1938 /// \brief Build reference expression to the counter be used for codegen.
1939 Expr *BuildCounterVar() const;
1940 /// \brief Build initization of the counter be used for codegen.
1941 Expr *BuildCounterInit() const;
1942 /// \brief Build step of the counter be used for codegen.
1943 Expr *BuildCounterStep() const;
1944 /// \brief Return true if any expression is dependent.
1945 bool Dependent() const;
1948 /// \brief Check the right-hand side of an assignment in the increment
1950 bool CheckIncRHS(Expr *RHS);
1951 /// \brief Helper to set loop counter variable and its initializer.
1952 bool SetVarAndLB(VarDecl *NewVar, DeclRefExpr *NewVarRefExpr, Expr *NewLB);
1953 /// \brief Helper to set upper bound.
1954 bool SetUB(Expr *NewUB, bool LessOp, bool StrictOp, const SourceRange &SR,
1955 const SourceLocation &SL);
1956 /// \brief Helper to set loop increment.
1957 bool SetStep(Expr *NewStep, bool Subtract);
1960 bool OpenMPIterationSpaceChecker::Dependent() const {
1962 assert(!LB && !UB && !Step);
1965 return Var->getType()->isDependentType() || (LB && LB->isValueDependent()) ||
1966 (UB && UB->isValueDependent()) || (Step && Step->isValueDependent());
1969 bool OpenMPIterationSpaceChecker::SetVarAndLB(VarDecl *NewVar,
1970 DeclRefExpr *NewVarRefExpr,
1972 // State consistency checking to ensure correct usage.
1973 assert(Var == nullptr && LB == nullptr && VarRef == nullptr &&
1974 UB == nullptr && Step == nullptr && !TestIsLessOp && !TestIsStrictOp);
1975 if (!NewVar || !NewLB)
1978 VarRef = NewVarRefExpr;
1983 bool OpenMPIterationSpaceChecker::SetUB(Expr *NewUB, bool LessOp, bool StrictOp,
1984 const SourceRange &SR,
1985 const SourceLocation &SL) {
1986 // State consistency checking to ensure correct usage.
1987 assert(Var != nullptr && LB != nullptr && UB == nullptr && Step == nullptr &&
1988 !TestIsLessOp && !TestIsStrictOp);
1992 TestIsLessOp = LessOp;
1993 TestIsStrictOp = StrictOp;
1994 ConditionSrcRange = SR;
1999 bool OpenMPIterationSpaceChecker::SetStep(Expr *NewStep, bool Subtract) {
2000 // State consistency checking to ensure correct usage.
2001 assert(Var != nullptr && LB != nullptr && Step == nullptr);
2004 if (!NewStep->isValueDependent()) {
2005 // Check that the step is integer expression.
2006 SourceLocation StepLoc = NewStep->getLocStart();
2008 SemaRef.PerformOpenMPImplicitIntegerConversion(StepLoc, NewStep);
2009 if (Val.isInvalid())
2011 NewStep = Val.get();
2013 // OpenMP [2.6, Canonical Loop Form, Restrictions]
2014 // If test-expr is of form var relational-op b and relational-op is < or
2015 // <= then incr-expr must cause var to increase on each iteration of the
2016 // loop. If test-expr is of form var relational-op b and relational-op is
2017 // > or >= then incr-expr must cause var to decrease on each iteration of
2019 // If test-expr is of form b relational-op var and relational-op is < or
2020 // <= then incr-expr must cause var to decrease on each iteration of the
2021 // loop. If test-expr is of form b relational-op var and relational-op is
2022 // > or >= then incr-expr must cause var to increase on each iteration of
2024 llvm::APSInt Result;
2025 bool IsConstant = NewStep->isIntegerConstantExpr(Result, SemaRef.Context);
2026 bool IsUnsigned = !NewStep->getType()->hasSignedIntegerRepresentation();
2028 IsConstant && Result.isSigned() && (Subtract != Result.isNegative());
2030 IsConstant && Result.isSigned() && (Subtract == Result.isNegative());
2031 bool IsConstZero = IsConstant && !Result.getBoolValue();
2032 if (UB && (IsConstZero ||
2033 (TestIsLessOp ? (IsConstNeg || (IsUnsigned && Subtract))
2034 : (IsConstPos || (IsUnsigned && !Subtract))))) {
2035 SemaRef.Diag(NewStep->getExprLoc(),
2036 diag::err_omp_loop_incr_not_compatible)
2037 << Var << TestIsLessOp << NewStep->getSourceRange();
2038 SemaRef.Diag(ConditionLoc,
2039 diag::note_omp_loop_cond_requres_compatible_incr)
2040 << TestIsLessOp << ConditionSrcRange;
2043 if (TestIsLessOp == Subtract) {
2044 NewStep = SemaRef.CreateBuiltinUnaryOp(NewStep->getExprLoc(), UO_Minus,
2046 Subtract = !Subtract;
2051 SubtractStep = Subtract;
2055 bool OpenMPIterationSpaceChecker::CheckInit(Stmt *S) {
2056 // Check init-expr for canonical loop form and save loop counter
2057 // variable - #Var and its initialization value - #LB.
2058 // OpenMP [2.6] Canonical loop form. init-expr may be one of the following:
2060 // integer-type var = lb
2061 // random-access-iterator-type var = lb
2062 // pointer-type var = lb
2065 SemaRef.Diag(DefaultLoc, diag::err_omp_loop_not_canonical_init);
2068 InitSrcRange = S->getSourceRange();
2069 if (Expr *E = dyn_cast<Expr>(S))
2070 S = E->IgnoreParens();
2071 if (auto BO = dyn_cast<BinaryOperator>(S)) {
2072 if (BO->getOpcode() == BO_Assign)
2073 if (auto DRE = dyn_cast<DeclRefExpr>(BO->getLHS()->IgnoreParens()))
2074 return SetVarAndLB(dyn_cast<VarDecl>(DRE->getDecl()), DRE,
2076 } else if (auto DS = dyn_cast<DeclStmt>(S)) {
2077 if (DS->isSingleDecl()) {
2078 if (auto Var = dyn_cast_or_null<VarDecl>(DS->getSingleDecl())) {
2079 if (Var->hasInit()) {
2080 // Accept non-canonical init form here but emit ext. warning.
2081 if (Var->getInitStyle() != VarDecl::CInit)
2082 SemaRef.Diag(S->getLocStart(),
2083 diag::ext_omp_loop_not_canonical_init)
2084 << S->getSourceRange();
2085 return SetVarAndLB(Var, nullptr, Var->getInit());
2089 } else if (auto CE = dyn_cast<CXXOperatorCallExpr>(S))
2090 if (CE->getOperator() == OO_Equal)
2091 if (auto DRE = dyn_cast<DeclRefExpr>(CE->getArg(0)))
2092 return SetVarAndLB(dyn_cast<VarDecl>(DRE->getDecl()), DRE,
2095 SemaRef.Diag(S->getLocStart(), diag::err_omp_loop_not_canonical_init)
2096 << S->getSourceRange();
2100 /// \brief Ignore parenthesizes, implicit casts, copy constructor and return the
2101 /// variable (which may be the loop variable) if possible.
2102 static const VarDecl *GetInitVarDecl(const Expr *E) {
2105 E = E->IgnoreParenImpCasts();
2106 if (auto *CE = dyn_cast_or_null<CXXConstructExpr>(E))
2107 if (const CXXConstructorDecl *Ctor = CE->getConstructor())
2108 if (Ctor->isCopyConstructor() && CE->getNumArgs() == 1 &&
2109 CE->getArg(0) != nullptr)
2110 E = CE->getArg(0)->IgnoreParenImpCasts();
2111 auto DRE = dyn_cast_or_null<DeclRefExpr>(E);
2114 return dyn_cast<VarDecl>(DRE->getDecl());
2117 bool OpenMPIterationSpaceChecker::CheckCond(Expr *S) {
2118 // Check test-expr for canonical form, save upper-bound UB, flags for
2119 // less/greater and for strict/non-strict comparison.
2120 // OpenMP [2.6] Canonical loop form. Test-expr may be one of the following:
2121 // var relational-op b
2122 // b relational-op var
2125 SemaRef.Diag(DefaultLoc, diag::err_omp_loop_not_canonical_cond) << Var;
2128 S = S->IgnoreParenImpCasts();
2129 SourceLocation CondLoc = S->getLocStart();
2130 if (auto BO = dyn_cast<BinaryOperator>(S)) {
2131 if (BO->isRelationalOp()) {
2132 if (GetInitVarDecl(BO->getLHS()) == Var)
2133 return SetUB(BO->getRHS(),
2134 (BO->getOpcode() == BO_LT || BO->getOpcode() == BO_LE),
2135 (BO->getOpcode() == BO_LT || BO->getOpcode() == BO_GT),
2136 BO->getSourceRange(), BO->getOperatorLoc());
2137 if (GetInitVarDecl(BO->getRHS()) == Var)
2138 return SetUB(BO->getLHS(),
2139 (BO->getOpcode() == BO_GT || BO->getOpcode() == BO_GE),
2140 (BO->getOpcode() == BO_LT || BO->getOpcode() == BO_GT),
2141 BO->getSourceRange(), BO->getOperatorLoc());
2143 } else if (auto CE = dyn_cast<CXXOperatorCallExpr>(S)) {
2144 if (CE->getNumArgs() == 2) {
2145 auto Op = CE->getOperator();
2148 case OO_GreaterEqual:
2151 if (GetInitVarDecl(CE->getArg(0)) == Var)
2152 return SetUB(CE->getArg(1), Op == OO_Less || Op == OO_LessEqual,
2153 Op == OO_Less || Op == OO_Greater, CE->getSourceRange(),
2154 CE->getOperatorLoc());
2155 if (GetInitVarDecl(CE->getArg(1)) == Var)
2156 return SetUB(CE->getArg(0), Op == OO_Greater || Op == OO_GreaterEqual,
2157 Op == OO_Less || Op == OO_Greater, CE->getSourceRange(),
2158 CE->getOperatorLoc());
2165 SemaRef.Diag(CondLoc, diag::err_omp_loop_not_canonical_cond)
2166 << S->getSourceRange() << Var;
2170 bool OpenMPIterationSpaceChecker::CheckIncRHS(Expr *RHS) {
2171 // RHS of canonical loop form increment can be:
2176 RHS = RHS->IgnoreParenImpCasts();
2177 if (auto BO = dyn_cast<BinaryOperator>(RHS)) {
2178 if (BO->isAdditiveOp()) {
2179 bool IsAdd = BO->getOpcode() == BO_Add;
2180 if (GetInitVarDecl(BO->getLHS()) == Var)
2181 return SetStep(BO->getRHS(), !IsAdd);
2182 if (IsAdd && GetInitVarDecl(BO->getRHS()) == Var)
2183 return SetStep(BO->getLHS(), false);
2185 } else if (auto CE = dyn_cast<CXXOperatorCallExpr>(RHS)) {
2186 bool IsAdd = CE->getOperator() == OO_Plus;
2187 if ((IsAdd || CE->getOperator() == OO_Minus) && CE->getNumArgs() == 2) {
2188 if (GetInitVarDecl(CE->getArg(0)) == Var)
2189 return SetStep(CE->getArg(1), !IsAdd);
2190 if (IsAdd && GetInitVarDecl(CE->getArg(1)) == Var)
2191 return SetStep(CE->getArg(0), false);
2194 SemaRef.Diag(RHS->getLocStart(), diag::err_omp_loop_not_canonical_incr)
2195 << RHS->getSourceRange() << Var;
2199 bool OpenMPIterationSpaceChecker::CheckInc(Expr *S) {
2200 // Check incr-expr for canonical loop form and return true if it
2201 // does not conform.
2202 // OpenMP [2.6] Canonical loop form. Test-expr may be one of the following:
2214 SemaRef.Diag(DefaultLoc, diag::err_omp_loop_not_canonical_incr) << Var;
2217 IncrementSrcRange = S->getSourceRange();
2218 S = S->IgnoreParens();
2219 if (auto UO = dyn_cast<UnaryOperator>(S)) {
2220 if (UO->isIncrementDecrementOp() && GetInitVarDecl(UO->getSubExpr()) == Var)
2222 SemaRef.ActOnIntegerConstant(UO->getLocStart(),
2223 (UO->isDecrementOp() ? -1 : 1)).get(),
2225 } else if (auto BO = dyn_cast<BinaryOperator>(S)) {
2226 switch (BO->getOpcode()) {
2229 if (GetInitVarDecl(BO->getLHS()) == Var)
2230 return SetStep(BO->getRHS(), BO->getOpcode() == BO_SubAssign);
2233 if (GetInitVarDecl(BO->getLHS()) == Var)
2234 return CheckIncRHS(BO->getRHS());
2239 } else if (auto CE = dyn_cast<CXXOperatorCallExpr>(S)) {
2240 switch (CE->getOperator()) {
2243 if (GetInitVarDecl(CE->getArg(0)) == Var)
2245 SemaRef.ActOnIntegerConstant(
2247 ((CE->getOperator() == OO_MinusMinus) ? -1 : 1)).get(),
2252 if (GetInitVarDecl(CE->getArg(0)) == Var)
2253 return SetStep(CE->getArg(1), CE->getOperator() == OO_MinusEqual);
2256 if (GetInitVarDecl(CE->getArg(0)) == Var)
2257 return CheckIncRHS(CE->getArg(1));
2263 SemaRef.Diag(S->getLocStart(), diag::err_omp_loop_not_canonical_incr)
2264 << S->getSourceRange() << Var;
2268 /// \brief Build the expression to calculate the number of iterations.
2270 OpenMPIterationSpaceChecker::BuildNumIterations(Scope *S,
2271 const bool LimitedType) const {
2273 if (Var->getType()->isIntegerType() || Var->getType()->isPointerType() ||
2274 SemaRef.getLangOpts().CPlusPlus) {
2276 Expr *Upper = TestIsLessOp ? UB : LB;
2277 Expr *Lower = TestIsLessOp ? LB : UB;
2279 Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Sub, Upper, Lower);
2281 if (!Diff.isUsable() && Var->getType()->getAsCXXRecordDecl()) {
2282 // BuildBinOp already emitted error, this one is to point user to upper
2283 // and lower bound, and to tell what is passed to 'operator-'.
2284 SemaRef.Diag(Upper->getLocStart(), diag::err_omp_loop_diff_cxx)
2285 << Upper->getSourceRange() << Lower->getSourceRange();
2290 if (!Diff.isUsable())
2293 // Upper - Lower [- 1]
2295 Diff = SemaRef.BuildBinOp(
2296 S, DefaultLoc, BO_Sub, Diff.get(),
2297 SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get());
2298 if (!Diff.isUsable())
2301 // Upper - Lower [- 1] + Step
2302 Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Add, Diff.get(),
2303 Step->IgnoreImplicit());
2304 if (!Diff.isUsable())
2307 // Parentheses (for dumping/debugging purposes only).
2308 Diff = SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, Diff.get());
2309 if (!Diff.isUsable())
2312 // (Upper - Lower [- 1] + Step) / Step
2313 Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Div, Diff.get(),
2314 Step->IgnoreImplicit());
2315 if (!Diff.isUsable())
2318 // OpenMP runtime requires 32-bit or 64-bit loop variables.
2320 auto &C = SemaRef.Context;
2321 QualType Type = Diff.get()->getType();
2322 unsigned NewSize = (C.getTypeSize(Type) > 32) ? 64 : 32;
2323 if (NewSize != C.getTypeSize(Type)) {
2324 if (NewSize < C.getTypeSize(Type)) {
2325 assert(NewSize == 64 && "incorrect loop var size");
2326 SemaRef.Diag(DefaultLoc, diag::warn_omp_loop_64_bit_var)
2327 << InitSrcRange << ConditionSrcRange;
2329 QualType NewType = C.getIntTypeForBitwidth(
2330 NewSize, Type->hasSignedIntegerRepresentation());
2331 Diff = SemaRef.PerformImplicitConversion(Diff.get(), NewType,
2332 Sema::AA_Converting, true);
2333 if (!Diff.isUsable())
2341 /// \brief Build reference expression to the counter be used for codegen.
2342 Expr *OpenMPIterationSpaceChecker::BuildCounterVar() const {
2343 return DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(),
2344 GetIncrementSrcRange().getBegin(), Var, false,
2345 DefaultLoc, Var->getType(), VK_LValue);
2348 /// \brief Build initization of the counter be used for codegen.
2349 Expr *OpenMPIterationSpaceChecker::BuildCounterInit() const { return LB; }
2351 /// \brief Build step of the counter be used for codegen.
2352 Expr *OpenMPIterationSpaceChecker::BuildCounterStep() const { return Step; }
2354 /// \brief Iteration space of a single for loop.
2355 struct LoopIterationSpace {
2356 /// \brief This expression calculates the number of iterations in the loop.
2357 /// It is always possible to calculate it before starting the loop.
2358 Expr *NumIterations;
2359 /// \brief The loop counter variable.
2361 /// \brief This is initializer for the initial value of #CounterVar.
2363 /// \brief This is step for the #CounterVar used to generate its update:
2364 /// #CounterVar = #CounterInit + #CounterStep * CurrentIteration.
2366 /// \brief Should step be subtracted?
2368 /// \brief Source range of the loop init.
2369 SourceRange InitSrcRange;
2370 /// \brief Source range of the loop condition.
2371 SourceRange CondSrcRange;
2372 /// \brief Source range of the loop increment.
2373 SourceRange IncSrcRange;
2378 /// \brief Called on a for stmt to check and extract its iteration space
2379 /// for further processing (such as collapsing).
2380 static bool CheckOpenMPIterationSpace(
2381 OpenMPDirectiveKind DKind, Stmt *S, Sema &SemaRef, DSAStackTy &DSA,
2382 unsigned CurrentNestedLoopCount, unsigned NestedLoopCount,
2383 Expr *NestedLoopCountExpr,
2384 llvm::DenseMap<VarDecl *, Expr *> &VarsWithImplicitDSA,
2385 LoopIterationSpace &ResultIterSpace) {
2386 // OpenMP [2.6, Canonical Loop Form]
2387 // for (init-expr; test-expr; incr-expr) structured-block
2388 auto For = dyn_cast_or_null<ForStmt>(S);
2390 SemaRef.Diag(S->getLocStart(), diag::err_omp_not_for)
2391 << (NestedLoopCountExpr != nullptr) << getOpenMPDirectiveName(DKind)
2392 << NestedLoopCount << (CurrentNestedLoopCount > 0)
2393 << CurrentNestedLoopCount;
2394 if (NestedLoopCount > 1)
2395 SemaRef.Diag(NestedLoopCountExpr->getExprLoc(),
2396 diag::note_omp_collapse_expr)
2397 << NestedLoopCountExpr->getSourceRange();
2400 assert(For->getBody());
2402 OpenMPIterationSpaceChecker ISC(SemaRef, For->getForLoc());
2405 auto Init = For->getInit();
2406 if (ISC.CheckInit(Init)) {
2410 bool HasErrors = false;
2412 // Check loop variable's type.
2413 auto Var = ISC.GetLoopVar();
2415 // OpenMP [2.6, Canonical Loop Form]
2416 // Var is one of the following:
2417 // A variable of signed or unsigned integer type.
2418 // For C++, a variable of a random access iterator type.
2419 // For C, a variable of a pointer type.
2420 auto VarType = Var->getType();
2421 if (!VarType->isDependentType() && !VarType->isIntegerType() &&
2422 !VarType->isPointerType() &&
2423 !(SemaRef.getLangOpts().CPlusPlus && VarType->isOverloadableType())) {
2424 SemaRef.Diag(Init->getLocStart(), diag::err_omp_loop_variable_type)
2425 << SemaRef.getLangOpts().CPlusPlus;
2429 // OpenMP, 2.14.1.1 Data-sharing Attribute Rules for Variables Referenced in a
2431 // The loop iteration variable(s) in the associated for-loop(s) of a for or
2432 // parallel for construct is (are) private.
2433 // The loop iteration variable in the associated for-loop of a simd construct
2434 // with just one associated for-loop is linear with a constant-linear-step
2435 // that is the increment of the associated for-loop.
2436 // Exclude loop var from the list of variables with implicitly defined data
2437 // sharing attributes.
2438 VarsWithImplicitDSA.erase(Var);
2440 // OpenMP [2.14.1.1, Data-sharing Attribute Rules for Variables Referenced in
2441 // a Construct, C/C++].
2442 // The loop iteration variable in the associated for-loop of a simd construct
2443 // with just one associated for-loop may be listed in a linear clause with a
2444 // constant-linear-step that is the increment of the associated for-loop.
2445 // The loop iteration variable(s) in the associated for-loop(s) of a for or
2446 // parallel for construct may be listed in a private or lastprivate clause.
2447 DSAStackTy::DSAVarData DVar = DSA.getTopDSA(Var, false);
2448 auto LoopVarRefExpr = ISC.GetLoopVarRefExpr();
2449 // If LoopVarRefExpr is nullptr it means the corresponding loop variable is
2450 // declared in the loop and it is predetermined as a private.
2451 auto PredeterminedCKind =
2452 isOpenMPSimdDirective(DKind)
2453 ? ((NestedLoopCount == 1) ? OMPC_linear : OMPC_lastprivate)
2455 if (((isOpenMPSimdDirective(DKind) && DVar.CKind != OMPC_unknown &&
2456 DVar.CKind != PredeterminedCKind) ||
2457 (isOpenMPWorksharingDirective(DKind) && !isOpenMPSimdDirective(DKind) &&
2458 DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_private &&
2459 DVar.CKind != OMPC_lastprivate)) &&
2460 (DVar.CKind != OMPC_private || DVar.RefExpr != nullptr)) {
2461 SemaRef.Diag(Init->getLocStart(), diag::err_omp_loop_var_dsa)
2462 << getOpenMPClauseName(DVar.CKind) << getOpenMPDirectiveName(DKind)
2463 << getOpenMPClauseName(PredeterminedCKind);
2464 ReportOriginalDSA(SemaRef, &DSA, Var, DVar, true);
2466 } else if (LoopVarRefExpr != nullptr) {
2467 // Make the loop iteration variable private (for worksharing constructs),
2468 // linear (for simd directives with the only one associated loop) or
2469 // lastprivate (for simd directives with several collapsed loops).
2470 // FIXME: the next check and error message must be removed once the
2471 // capturing of global variables in loops is fixed.
2472 if (DVar.CKind == OMPC_unknown)
2473 DVar = DSA.hasDSA(Var, isOpenMPPrivate, MatchesAlways(),
2474 /*FromParent=*/false);
2475 if (!Var->hasLocalStorage() && DVar.CKind == OMPC_unknown) {
2476 SemaRef.Diag(Init->getLocStart(), diag::err_omp_global_loop_var_dsa)
2477 << getOpenMPClauseName(PredeterminedCKind)
2478 << getOpenMPDirectiveName(DKind);
2481 DSA.addDSA(Var, LoopVarRefExpr, PredeterminedCKind);
2484 assert(isOpenMPLoopDirective(DKind) && "DSA for non-loop vars");
2487 HasErrors |= ISC.CheckCond(For->getCond());
2490 HasErrors |= ISC.CheckInc(For->getInc());
2492 if (ISC.Dependent() || SemaRef.CurContext->isDependentContext() || HasErrors)
2495 // Build the loop's iteration space representation.
2496 ResultIterSpace.NumIterations = ISC.BuildNumIterations(
2497 DSA.getCurScope(), /* LimitedType */ isOpenMPWorksharingDirective(DKind));
2498 ResultIterSpace.CounterVar = ISC.BuildCounterVar();
2499 ResultIterSpace.CounterInit = ISC.BuildCounterInit();
2500 ResultIterSpace.CounterStep = ISC.BuildCounterStep();
2501 ResultIterSpace.InitSrcRange = ISC.GetInitSrcRange();
2502 ResultIterSpace.CondSrcRange = ISC.GetConditionSrcRange();
2503 ResultIterSpace.IncSrcRange = ISC.GetIncrementSrcRange();
2504 ResultIterSpace.Subtract = ISC.ShouldSubtractStep();
2506 HasErrors |= (ResultIterSpace.NumIterations == nullptr ||
2507 ResultIterSpace.CounterVar == nullptr ||
2508 ResultIterSpace.CounterInit == nullptr ||
2509 ResultIterSpace.CounterStep == nullptr);
2514 /// \brief Build a variable declaration for OpenMP loop iteration variable.
2515 static VarDecl *BuildVarDecl(Sema &SemaRef, SourceLocation Loc, QualType Type,
2517 DeclContext *DC = SemaRef.CurContext;
2518 IdentifierInfo *II = &SemaRef.PP.getIdentifierTable().get(Name);
2519 TypeSourceInfo *TInfo = SemaRef.Context.getTrivialTypeSourceInfo(Type, Loc);
2521 VarDecl::Create(SemaRef.Context, DC, Loc, Loc, II, Type, TInfo, SC_None);
2522 Decl->setImplicit();
2526 /// \brief Build 'VarRef = Start + Iter * Step'.
2527 static ExprResult BuildCounterUpdate(Sema &SemaRef, Scope *S,
2528 SourceLocation Loc, ExprResult VarRef,
2529 ExprResult Start, ExprResult Iter,
2530 ExprResult Step, bool Subtract) {
2531 // Add parentheses (for debugging purposes only).
2532 Iter = SemaRef.ActOnParenExpr(Loc, Loc, Iter.get());
2533 if (!VarRef.isUsable() || !Start.isUsable() || !Iter.isUsable() ||
2537 ExprResult Update = SemaRef.BuildBinOp(S, Loc, BO_Mul, Iter.get(),
2538 Step.get()->IgnoreImplicit());
2539 if (!Update.isUsable())
2542 // Build 'VarRef = Start + Iter * Step'.
2543 Update = SemaRef.BuildBinOp(S, Loc, (Subtract ? BO_Sub : BO_Add),
2544 Start.get()->IgnoreImplicit(), Update.get());
2545 if (!Update.isUsable())
2548 Update = SemaRef.PerformImplicitConversion(
2549 Update.get(), VarRef.get()->getType(), Sema::AA_Converting, true);
2550 if (!Update.isUsable())
2553 Update = SemaRef.BuildBinOp(S, Loc, BO_Assign, VarRef.get(), Update.get());
2557 /// \brief Convert integer expression \a E to make it have at least \a Bits
2559 static ExprResult WidenIterationCount(unsigned Bits, Expr *E,
2563 auto &C = SemaRef.Context;
2564 QualType OldType = E->getType();
2565 unsigned HasBits = C.getTypeSize(OldType);
2566 if (HasBits >= Bits)
2567 return ExprResult(E);
2568 // OK to convert to signed, because new type has more bits than old.
2569 QualType NewType = C.getIntTypeForBitwidth(Bits, /* Signed */ true);
2570 return SemaRef.PerformImplicitConversion(E, NewType, Sema::AA_Converting,
2574 /// \brief Check if the given expression \a E is a constant integer that fits
2575 /// into \a Bits bits.
2576 static bool FitsInto(unsigned Bits, bool Signed, Expr *E, Sema &SemaRef) {
2579 llvm::APSInt Result;
2580 if (E->isIntegerConstantExpr(Result, SemaRef.Context))
2581 return Signed ? Result.isSignedIntN(Bits) : Result.isIntN(Bits);
2585 /// \brief Called on a for stmt to check itself and nested loops (if any).
2586 /// \return Returns 0 if one of the collapsed stmts is not canonical for loop,
2587 /// number of collapsed loops otherwise.
2589 CheckOpenMPLoop(OpenMPDirectiveKind DKind, Expr *NestedLoopCountExpr,
2590 Stmt *AStmt, Sema &SemaRef, DSAStackTy &DSA,
2591 llvm::DenseMap<VarDecl *, Expr *> &VarsWithImplicitDSA,
2592 OMPLoopDirective::HelperExprs &Built) {
2593 unsigned NestedLoopCount = 1;
2594 if (NestedLoopCountExpr) {
2595 // Found 'collapse' clause - calculate collapse number.
2596 llvm::APSInt Result;
2597 if (NestedLoopCountExpr->EvaluateAsInt(Result, SemaRef.getASTContext()))
2598 NestedLoopCount = Result.getLimitedValue();
2600 // This is helper routine for loop directives (e.g., 'for', 'simd',
2601 // 'for simd', etc.).
2602 SmallVector<LoopIterationSpace, 4> IterSpaces;
2603 IterSpaces.resize(NestedLoopCount);
2604 Stmt *CurStmt = AStmt->IgnoreContainers(/* IgnoreCaptured */ true);
2605 for (unsigned Cnt = 0; Cnt < NestedLoopCount; ++Cnt) {
2606 if (CheckOpenMPIterationSpace(DKind, CurStmt, SemaRef, DSA, Cnt,
2607 NestedLoopCount, NestedLoopCountExpr,
2608 VarsWithImplicitDSA, IterSpaces[Cnt]))
2610 // Move on to the next nested for loop, or to the loop body.
2611 // OpenMP [2.8.1, simd construct, Restrictions]
2612 // All loops associated with the construct must be perfectly nested; that
2613 // is, there must be no intervening code nor any OpenMP directive between
2615 CurStmt = cast<ForStmt>(CurStmt)->getBody()->IgnoreContainers();
2618 Built.clear(/* size */ NestedLoopCount);
2620 if (SemaRef.CurContext->isDependentContext())
2621 return NestedLoopCount;
2623 // An example of what is generated for the following code:
2625 // #pragma omp simd collapse(2)
2626 // for (i = 0; i < NI; ++i)
2627 // for (j = J0; j < NJ; j+=2) {
2631 // We generate the code below.
2632 // Note: the loop body may be outlined in CodeGen.
2633 // Note: some counters may be C++ classes, operator- is used to find number of
2634 // iterations and operator+= to calculate counter value.
2635 // Note: decltype(NumIterations) must be integer type (in 'omp for', only i32
2636 // or i64 is currently supported).
2638 // #define NumIterations (NI * ((NJ - J0 - 1 + 2) / 2))
2639 // for (int[32|64]_t IV = 0; IV < NumIterations; ++IV ) {
2640 // .local.i = IV / ((NJ - J0 - 1 + 2) / 2);
2641 // .local.j = J0 + (IV % ((NJ - J0 - 1 + 2) / 2)) * 2;
2642 // // similar updates for vars in clauses (e.g. 'linear')
2643 // <loop body (using local i and j)>
2645 // i = NI; // assign final values of counters
2649 // Last iteration number is (I1 * I2 * ... In) - 1, where I1, I2 ... In are
2650 // the iteration counts of the collapsed for loops.
2651 auto N0 = IterSpaces[0].NumIterations;
2652 ExprResult LastIteration32 = WidenIterationCount(32 /* Bits */, N0, SemaRef);
2653 ExprResult LastIteration64 = WidenIterationCount(64 /* Bits */, N0, SemaRef);
2655 if (!LastIteration32.isUsable() || !LastIteration64.isUsable())
2656 return NestedLoopCount;
2658 auto &C = SemaRef.Context;
2659 bool AllCountsNeedLessThan32Bits = C.getTypeSize(N0->getType()) < 32;
2661 Scope *CurScope = DSA.getCurScope();
2662 for (unsigned Cnt = 1; Cnt < NestedLoopCount; ++Cnt) {
2663 auto N = IterSpaces[Cnt].NumIterations;
2664 AllCountsNeedLessThan32Bits &= C.getTypeSize(N->getType()) < 32;
2665 if (LastIteration32.isUsable())
2666 LastIteration32 = SemaRef.BuildBinOp(CurScope, SourceLocation(), BO_Mul,
2667 LastIteration32.get(), N);
2668 if (LastIteration64.isUsable())
2669 LastIteration64 = SemaRef.BuildBinOp(CurScope, SourceLocation(), BO_Mul,
2670 LastIteration64.get(), N);
2673 // Choose either the 32-bit or 64-bit version.
2674 ExprResult LastIteration = LastIteration64;
2675 if (LastIteration32.isUsable() &&
2676 C.getTypeSize(LastIteration32.get()->getType()) == 32 &&
2677 (AllCountsNeedLessThan32Bits || NestedLoopCount == 1 ||
2680 LastIteration32.get()->getType()->hasSignedIntegerRepresentation(),
2681 LastIteration64.get(), SemaRef)))
2682 LastIteration = LastIteration32;
2684 if (!LastIteration.isUsable())
2687 // Save the number of iterations.
2688 ExprResult NumIterations = LastIteration;
2690 LastIteration = SemaRef.BuildBinOp(
2691 CurScope, SourceLocation(), BO_Sub, LastIteration.get(),
2692 SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get());
2693 if (!LastIteration.isUsable())
2697 // Calculate the last iteration number beforehand instead of doing this on
2698 // each iteration. Do not do this if the number of iterations may be kfold-ed.
2699 llvm::APSInt Result;
2701 LastIteration.get()->isIntegerConstantExpr(Result, SemaRef.Context);
2702 ExprResult CalcLastIteration;
2704 SourceLocation SaveLoc;
2706 BuildVarDecl(SemaRef, SaveLoc, LastIteration.get()->getType(),
2707 ".omp.last.iteration");
2708 ExprResult SaveRef = SemaRef.BuildDeclRefExpr(
2709 SaveVar, LastIteration.get()->getType(), VK_LValue, SaveLoc);
2710 CalcLastIteration = SemaRef.BuildBinOp(CurScope, SaveLoc, BO_Assign,
2711 SaveRef.get(), LastIteration.get());
2712 LastIteration = SaveRef;
2714 // Prepare SaveRef + 1.
2715 NumIterations = SemaRef.BuildBinOp(
2716 CurScope, SaveLoc, BO_Add, SaveRef.get(),
2717 SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get());
2718 if (!NumIterations.isUsable())
2722 SourceLocation InitLoc = IterSpaces[0].InitSrcRange.getBegin();
2724 // Precondition tests if there is at least one iteration (LastIteration > 0).
2725 ExprResult PreCond = SemaRef.BuildBinOp(
2726 CurScope, InitLoc, BO_GT, LastIteration.get(),
2727 SemaRef.ActOnIntegerConstant(SourceLocation(), 0).get());
2729 QualType VType = LastIteration.get()->getType();
2730 // Build variables passed into runtime, nesessary for worksharing directives.
2731 ExprResult LB, UB, IL, ST, EUB;
2732 if (isOpenMPWorksharingDirective(DKind)) {
2733 // Lower bound variable, initialized with zero.
2734 VarDecl *LBDecl = BuildVarDecl(SemaRef, InitLoc, VType, ".omp.lb");
2735 LB = SemaRef.BuildDeclRefExpr(LBDecl, VType, VK_LValue, InitLoc);
2736 SemaRef.AddInitializerToDecl(
2737 LBDecl, SemaRef.ActOnIntegerConstant(InitLoc, 0).get(),
2738 /*DirectInit*/ false, /*TypeMayContainAuto*/ false);
2740 // Upper bound variable, initialized with last iteration number.
2741 VarDecl *UBDecl = BuildVarDecl(SemaRef, InitLoc, VType, ".omp.ub");
2742 UB = SemaRef.BuildDeclRefExpr(UBDecl, VType, VK_LValue, InitLoc);
2743 SemaRef.AddInitializerToDecl(UBDecl, LastIteration.get(),
2744 /*DirectInit*/ false,
2745 /*TypeMayContainAuto*/ false);
2747 // A 32-bit variable-flag where runtime returns 1 for the last iteration.
2748 // This will be used to implement clause 'lastprivate'.
2749 QualType Int32Ty = SemaRef.Context.getIntTypeForBitwidth(32, true);
2750 VarDecl *ILDecl = BuildVarDecl(SemaRef, InitLoc, Int32Ty, ".omp.is_last");
2751 IL = SemaRef.BuildDeclRefExpr(ILDecl, Int32Ty, VK_LValue, InitLoc);
2752 SemaRef.AddInitializerToDecl(
2753 ILDecl, SemaRef.ActOnIntegerConstant(InitLoc, 0).get(),
2754 /*DirectInit*/ false, /*TypeMayContainAuto*/ false);
2756 // Stride variable returned by runtime (we initialize it to 1 by default).
2757 VarDecl *STDecl = BuildVarDecl(SemaRef, InitLoc, VType, ".omp.stride");
2758 ST = SemaRef.BuildDeclRefExpr(STDecl, VType, VK_LValue, InitLoc);
2759 SemaRef.AddInitializerToDecl(
2760 STDecl, SemaRef.ActOnIntegerConstant(InitLoc, 1).get(),
2761 /*DirectInit*/ false, /*TypeMayContainAuto*/ false);
2763 // Build expression: UB = min(UB, LastIteration)
2764 // It is nesessary for CodeGen of directives with static scheduling.
2765 ExprResult IsUBGreater = SemaRef.BuildBinOp(CurScope, InitLoc, BO_GT,
2766 UB.get(), LastIteration.get());
2767 ExprResult CondOp = SemaRef.ActOnConditionalOp(
2768 InitLoc, InitLoc, IsUBGreater.get(), LastIteration.get(), UB.get());
2769 EUB = SemaRef.BuildBinOp(CurScope, InitLoc, BO_Assign, UB.get(),
2771 EUB = SemaRef.ActOnFinishFullExpr(EUB.get());
2774 // Build the iteration variable and its initialization before loop.
2778 VarDecl *IVDecl = BuildVarDecl(SemaRef, InitLoc, VType, ".omp.iv");
2779 IV = SemaRef.BuildDeclRefExpr(IVDecl, VType, VK_LValue, InitLoc);
2780 Expr *RHS = isOpenMPWorksharingDirective(DKind)
2782 : SemaRef.ActOnIntegerConstant(SourceLocation(), 0).get();
2783 Init = SemaRef.BuildBinOp(CurScope, InitLoc, BO_Assign, IV.get(), RHS);
2784 Init = SemaRef.ActOnFinishFullExpr(Init.get());
2787 // Loop condition (IV < NumIterations) or (IV <= UB) for worksharing loops.
2788 SourceLocation CondLoc;
2790 isOpenMPWorksharingDirective(DKind)
2791 ? SemaRef.BuildBinOp(CurScope, CondLoc, BO_LE, IV.get(), UB.get())
2792 : SemaRef.BuildBinOp(CurScope, CondLoc, BO_LT, IV.get(),
2793 NumIterations.get());
2794 // Loop condition with 1 iteration separated (IV < LastIteration)
2795 ExprResult SeparatedCond = SemaRef.BuildBinOp(CurScope, CondLoc, BO_LT,
2796 IV.get(), LastIteration.get());
2798 // Loop increment (IV = IV + 1)
2799 SourceLocation IncLoc;
2801 SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, IV.get(),
2802 SemaRef.ActOnIntegerConstant(IncLoc, 1).get());
2803 if (!Inc.isUsable())
2805 Inc = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, IV.get(), Inc.get());
2806 Inc = SemaRef.ActOnFinishFullExpr(Inc.get());
2807 if (!Inc.isUsable())
2810 // Increments for worksharing loops (LB = LB + ST; UB = UB + ST).
2811 // Used for directives with static scheduling.
2812 ExprResult NextLB, NextUB;
2813 if (isOpenMPWorksharingDirective(DKind)) {
2815 NextLB = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, LB.get(), ST.get());
2816 if (!NextLB.isUsable())
2820 SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, LB.get(), NextLB.get());
2821 NextLB = SemaRef.ActOnFinishFullExpr(NextLB.get());
2822 if (!NextLB.isUsable())
2825 NextUB = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, UB.get(), ST.get());
2826 if (!NextUB.isUsable())
2830 SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, UB.get(), NextUB.get());
2831 NextUB = SemaRef.ActOnFinishFullExpr(NextUB.get());
2832 if (!NextUB.isUsable())
2836 // Build updates and final values of the loop counters.
2837 bool HasErrors = false;
2838 Built.Counters.resize(NestedLoopCount);
2839 Built.Updates.resize(NestedLoopCount);
2840 Built.Finals.resize(NestedLoopCount);
2843 // Go from inner nested loop to outer.
2844 for (int Cnt = NestedLoopCount - 1; Cnt >= 0; --Cnt) {
2845 LoopIterationSpace &IS = IterSpaces[Cnt];
2846 SourceLocation UpdLoc = IS.IncSrcRange.getBegin();
2847 // Build: Iter = (IV / Div) % IS.NumIters
2848 // where Div is product of previous iterations' IS.NumIters.
2850 if (Div.isUsable()) {
2852 SemaRef.BuildBinOp(CurScope, UpdLoc, BO_Div, IV.get(), Div.get());
2855 assert((Cnt == (int)NestedLoopCount - 1) &&
2856 "unusable div expected on first iteration only");
2859 if (Cnt != 0 && Iter.isUsable())
2860 Iter = SemaRef.BuildBinOp(CurScope, UpdLoc, BO_Rem, Iter.get(),
2862 if (!Iter.isUsable()) {
2867 // Build update: IS.CounterVar = IS.Start + Iter * IS.Step
2869 BuildCounterUpdate(SemaRef, CurScope, UpdLoc, IS.CounterVar,
2870 IS.CounterInit, Iter, IS.CounterStep, IS.Subtract);
2871 if (!Update.isUsable()) {
2876 // Build final: IS.CounterVar = IS.Start + IS.NumIters * IS.Step
2877 ExprResult Final = BuildCounterUpdate(
2878 SemaRef, CurScope, UpdLoc, IS.CounterVar, IS.CounterInit,
2879 IS.NumIterations, IS.CounterStep, IS.Subtract);
2880 if (!Final.isUsable()) {
2885 // Build Div for the next iteration: Div <- Div * IS.NumIters
2888 Div = IS.NumIterations;
2890 Div = SemaRef.BuildBinOp(CurScope, UpdLoc, BO_Mul, Div.get(),
2893 // Add parentheses (for debugging purposes only).
2895 Div = SemaRef.ActOnParenExpr(UpdLoc, UpdLoc, Div.get());
2896 if (!Div.isUsable()) {
2901 if (!Update.isUsable() || !Final.isUsable()) {
2906 Built.Counters[Cnt] = IS.CounterVar;
2907 Built.Updates[Cnt] = Update.get();
2908 Built.Finals[Cnt] = Final.get();
2916 Built.IterationVarRef = IV.get();
2917 Built.LastIteration = LastIteration.get();
2918 Built.CalcLastIteration = CalcLastIteration.get();
2919 Built.PreCond = PreCond.get();
2920 Built.Cond = Cond.get();
2921 Built.SeparatedCond = SeparatedCond.get();
2922 Built.Init = Init.get();
2923 Built.Inc = Inc.get();
2924 Built.LB = LB.get();
2925 Built.UB = UB.get();
2926 Built.IL = IL.get();
2927 Built.ST = ST.get();
2928 Built.EUB = EUB.get();
2929 Built.NLB = NextLB.get();
2930 Built.NUB = NextUB.get();
2932 return NestedLoopCount;
2935 static Expr *GetCollapseNumberExpr(ArrayRef<OMPClause *> Clauses) {
2936 auto CollapseFilter = [](const OMPClause *C) -> bool {
2937 return C->getClauseKind() == OMPC_collapse;
2939 OMPExecutableDirective::filtered_clause_iterator<decltype(CollapseFilter)> I(
2940 Clauses, CollapseFilter);
2942 return cast<OMPCollapseClause>(*I)->getNumForLoops();
2946 StmtResult Sema::ActOnOpenMPSimdDirective(
2947 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
2948 SourceLocation EndLoc,
2949 llvm::DenseMap<VarDecl *, Expr *> &VarsWithImplicitDSA) {
2950 OMPLoopDirective::HelperExprs B;
2951 // In presence of clause 'collapse', it will define the nested loops number.
2952 unsigned NestedLoopCount =
2953 CheckOpenMPLoop(OMPD_simd, GetCollapseNumberExpr(Clauses), AStmt, *this,
2954 *DSAStack, VarsWithImplicitDSA, B);
2955 if (NestedLoopCount == 0)
2958 assert((CurContext->isDependentContext() || B.builtAll()) &&
2959 "omp simd loop exprs were not built");
2961 getCurFunction()->setHasBranchProtectedScope();
2962 return OMPSimdDirective::Create(Context, StartLoc, EndLoc, NestedLoopCount,
2966 StmtResult Sema::ActOnOpenMPForDirective(
2967 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
2968 SourceLocation EndLoc,
2969 llvm::DenseMap<VarDecl *, Expr *> &VarsWithImplicitDSA) {
2970 OMPLoopDirective::HelperExprs B;
2971 // In presence of clause 'collapse', it will define the nested loops number.
2972 unsigned NestedLoopCount =
2973 CheckOpenMPLoop(OMPD_for, GetCollapseNumberExpr(Clauses), AStmt, *this,
2974 *DSAStack, VarsWithImplicitDSA, B);
2975 if (NestedLoopCount == 0)
2978 assert((CurContext->isDependentContext() || B.builtAll()) &&
2979 "omp for loop exprs were not built");
2981 getCurFunction()->setHasBranchProtectedScope();
2982 return OMPForDirective::Create(Context, StartLoc, EndLoc, NestedLoopCount,
2986 StmtResult Sema::ActOnOpenMPForSimdDirective(
2987 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
2988 SourceLocation EndLoc,
2989 llvm::DenseMap<VarDecl *, Expr *> &VarsWithImplicitDSA) {
2990 OMPLoopDirective::HelperExprs B;
2991 // In presence of clause 'collapse', it will define the nested loops number.
2992 unsigned NestedLoopCount =
2993 CheckOpenMPLoop(OMPD_for_simd, GetCollapseNumberExpr(Clauses), AStmt,
2994 *this, *DSAStack, VarsWithImplicitDSA, B);
2995 if (NestedLoopCount == 0)
2998 assert((CurContext->isDependentContext() || B.builtAll()) &&
2999 "omp for simd loop exprs were not built");
3001 getCurFunction()->setHasBranchProtectedScope();
3002 return OMPForSimdDirective::Create(Context, StartLoc, EndLoc, NestedLoopCount,
3006 StmtResult Sema::ActOnOpenMPSectionsDirective(ArrayRef<OMPClause *> Clauses,
3008 SourceLocation StartLoc,
3009 SourceLocation EndLoc) {
3010 assert(AStmt && isa<CapturedStmt>(AStmt) && "Captured statement expected");
3011 auto BaseStmt = AStmt;
3012 while (CapturedStmt *CS = dyn_cast_or_null<CapturedStmt>(BaseStmt))
3013 BaseStmt = CS->getCapturedStmt();
3014 if (auto C = dyn_cast_or_null<CompoundStmt>(BaseStmt)) {
3015 auto S = C->children();
3018 // All associated statements must be '#pragma omp section' except for
3021 auto SectionStmt = *S;
3022 if (!SectionStmt || !isa<OMPSectionDirective>(SectionStmt)) {
3024 Diag(SectionStmt->getLocStart(),
3025 diag::err_omp_sections_substmt_not_section);
3030 Diag(AStmt->getLocStart(), diag::err_omp_sections_not_compound_stmt);
3034 getCurFunction()->setHasBranchProtectedScope();
3036 return OMPSectionsDirective::Create(Context, StartLoc, EndLoc, Clauses,
3040 StmtResult Sema::ActOnOpenMPSectionDirective(Stmt *AStmt,
3041 SourceLocation StartLoc,
3042 SourceLocation EndLoc) {
3043 assert(AStmt && isa<CapturedStmt>(AStmt) && "Captured statement expected");
3045 getCurFunction()->setHasBranchProtectedScope();
3047 return OMPSectionDirective::Create(Context, StartLoc, EndLoc, AStmt);
3050 StmtResult Sema::ActOnOpenMPSingleDirective(ArrayRef<OMPClause *> Clauses,
3052 SourceLocation StartLoc,
3053 SourceLocation EndLoc) {
3054 assert(AStmt && isa<CapturedStmt>(AStmt) && "Captured statement expected");
3056 getCurFunction()->setHasBranchProtectedScope();
3058 return OMPSingleDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt);
3061 StmtResult Sema::ActOnOpenMPMasterDirective(Stmt *AStmt,
3062 SourceLocation StartLoc,
3063 SourceLocation EndLoc) {
3064 assert(AStmt && isa<CapturedStmt>(AStmt) && "Captured statement expected");
3066 getCurFunction()->setHasBranchProtectedScope();
3068 return OMPMasterDirective::Create(Context, StartLoc, EndLoc, AStmt);
3072 Sema::ActOnOpenMPCriticalDirective(const DeclarationNameInfo &DirName,
3073 Stmt *AStmt, SourceLocation StartLoc,
3074 SourceLocation EndLoc) {
3075 assert(AStmt && isa<CapturedStmt>(AStmt) && "Captured statement expected");
3077 getCurFunction()->setHasBranchProtectedScope();
3079 return OMPCriticalDirective::Create(Context, DirName, StartLoc, EndLoc,
3083 StmtResult Sema::ActOnOpenMPParallelForDirective(
3084 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
3085 SourceLocation EndLoc,
3086 llvm::DenseMap<VarDecl *, Expr *> &VarsWithImplicitDSA) {
3087 assert(AStmt && isa<CapturedStmt>(AStmt) && "Captured statement expected");
3088 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
3089 // 1.2.2 OpenMP Language Terminology
3090 // Structured block - An executable statement with a single entry at the
3091 // top and a single exit at the bottom.
3092 // The point of exit cannot be a branch out of the structured block.
3093 // longjmp() and throw() must not violate the entry/exit criteria.
3094 CS->getCapturedDecl()->setNothrow();
3096 OMPLoopDirective::HelperExprs B;
3097 // In presence of clause 'collapse', it will define the nested loops number.
3098 unsigned NestedLoopCount =
3099 CheckOpenMPLoop(OMPD_parallel_for, GetCollapseNumberExpr(Clauses), AStmt,
3100 *this, *DSAStack, VarsWithImplicitDSA, B);
3101 if (NestedLoopCount == 0)
3104 assert((CurContext->isDependentContext() || B.builtAll()) &&
3105 "omp parallel for loop exprs were not built");
3107 getCurFunction()->setHasBranchProtectedScope();
3108 return OMPParallelForDirective::Create(Context, StartLoc, EndLoc,
3109 NestedLoopCount, Clauses, AStmt, B);
3112 StmtResult Sema::ActOnOpenMPParallelForSimdDirective(
3113 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
3114 SourceLocation EndLoc,
3115 llvm::DenseMap<VarDecl *, Expr *> &VarsWithImplicitDSA) {
3116 assert(AStmt && isa<CapturedStmt>(AStmt) && "Captured statement expected");
3117 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
3118 // 1.2.2 OpenMP Language Terminology
3119 // Structured block - An executable statement with a single entry at the
3120 // top and a single exit at the bottom.
3121 // The point of exit cannot be a branch out of the structured block.
3122 // longjmp() and throw() must not violate the entry/exit criteria.
3123 CS->getCapturedDecl()->setNothrow();
3125 OMPLoopDirective::HelperExprs B;
3126 // In presence of clause 'collapse', it will define the nested loops number.
3127 unsigned NestedLoopCount =
3128 CheckOpenMPLoop(OMPD_parallel_for_simd, GetCollapseNumberExpr(Clauses),
3129 AStmt, *this, *DSAStack, VarsWithImplicitDSA, B);
3130 if (NestedLoopCount == 0)
3133 getCurFunction()->setHasBranchProtectedScope();
3134 return OMPParallelForSimdDirective::Create(
3135 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
3139 Sema::ActOnOpenMPParallelSectionsDirective(ArrayRef<OMPClause *> Clauses,
3140 Stmt *AStmt, SourceLocation StartLoc,
3141 SourceLocation EndLoc) {
3142 assert(AStmt && isa<CapturedStmt>(AStmt) && "Captured statement expected");
3143 auto BaseStmt = AStmt;
3144 while (CapturedStmt *CS = dyn_cast_or_null<CapturedStmt>(BaseStmt))
3145 BaseStmt = CS->getCapturedStmt();
3146 if (auto C = dyn_cast_or_null<CompoundStmt>(BaseStmt)) {
3147 auto S = C->children();
3150 // All associated statements must be '#pragma omp section' except for
3153 auto SectionStmt = *S;
3154 if (!SectionStmt || !isa<OMPSectionDirective>(SectionStmt)) {
3156 Diag(SectionStmt->getLocStart(),
3157 diag::err_omp_parallel_sections_substmt_not_section);
3162 Diag(AStmt->getLocStart(),
3163 diag::err_omp_parallel_sections_not_compound_stmt);
3167 getCurFunction()->setHasBranchProtectedScope();
3169 return OMPParallelSectionsDirective::Create(Context, StartLoc, EndLoc,
3173 StmtResult Sema::ActOnOpenMPTaskDirective(ArrayRef<OMPClause *> Clauses,
3174 Stmt *AStmt, SourceLocation StartLoc,
3175 SourceLocation EndLoc) {
3176 assert(AStmt && isa<CapturedStmt>(AStmt) && "Captured statement expected");
3177 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
3178 // 1.2.2 OpenMP Language Terminology
3179 // Structured block - An executable statement with a single entry at the
3180 // top and a single exit at the bottom.
3181 // The point of exit cannot be a branch out of the structured block.
3182 // longjmp() and throw() must not violate the entry/exit criteria.
3183 CS->getCapturedDecl()->setNothrow();
3185 getCurFunction()->setHasBranchProtectedScope();
3187 return OMPTaskDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt);
3190 StmtResult Sema::ActOnOpenMPTaskyieldDirective(SourceLocation StartLoc,
3191 SourceLocation EndLoc) {
3192 return OMPTaskyieldDirective::Create(Context, StartLoc, EndLoc);
3195 StmtResult Sema::ActOnOpenMPBarrierDirective(SourceLocation StartLoc,
3196 SourceLocation EndLoc) {
3197 return OMPBarrierDirective::Create(Context, StartLoc, EndLoc);
3200 StmtResult Sema::ActOnOpenMPTaskwaitDirective(SourceLocation StartLoc,
3201 SourceLocation EndLoc) {
3202 return OMPTaskwaitDirective::Create(Context, StartLoc, EndLoc);
3205 StmtResult Sema::ActOnOpenMPFlushDirective(ArrayRef<OMPClause *> Clauses,
3206 SourceLocation StartLoc,
3207 SourceLocation EndLoc) {
3208 assert(Clauses.size() <= 1 && "Extra clauses in flush directive");
3209 return OMPFlushDirective::Create(Context, StartLoc, EndLoc, Clauses);
3212 StmtResult Sema::ActOnOpenMPOrderedDirective(Stmt *AStmt,
3213 SourceLocation StartLoc,
3214 SourceLocation EndLoc) {
3215 assert(AStmt && isa<CapturedStmt>(AStmt) && "Captured statement expected");
3217 getCurFunction()->setHasBranchProtectedScope();
3219 return OMPOrderedDirective::Create(Context, StartLoc, EndLoc, AStmt);
3222 StmtResult Sema::ActOnOpenMPAtomicDirective(ArrayRef<OMPClause *> Clauses,
3224 SourceLocation StartLoc,
3225 SourceLocation EndLoc) {
3226 assert(AStmt && isa<CapturedStmt>(AStmt) && "Captured statement expected");
3227 auto CS = cast<CapturedStmt>(AStmt);
3228 // 1.2.2 OpenMP Language Terminology
3229 // Structured block - An executable statement with a single entry at the
3230 // top and a single exit at the bottom.
3231 // The point of exit cannot be a branch out of the structured block.
3232 // longjmp() and throw() must not violate the entry/exit criteria.
3233 // TODO further analysis of associated statements and clauses.
3234 OpenMPClauseKind AtomicKind = OMPC_unknown;
3235 SourceLocation AtomicKindLoc;
3236 for (auto *C : Clauses) {
3237 if (C->getClauseKind() == OMPC_read || C->getClauseKind() == OMPC_write ||
3238 C->getClauseKind() == OMPC_update ||
3239 C->getClauseKind() == OMPC_capture) {
3240 if (AtomicKind != OMPC_unknown) {
3241 Diag(C->getLocStart(), diag::err_omp_atomic_several_clauses)
3242 << SourceRange(C->getLocStart(), C->getLocEnd());
3243 Diag(AtomicKindLoc, diag::note_omp_atomic_previous_clause)
3244 << getOpenMPClauseName(AtomicKind);
3246 AtomicKind = C->getClauseKind();
3247 AtomicKindLoc = C->getLocStart();
3252 auto Body = CS->getCapturedStmt();
3256 // OpenMP [2.12.6, atomic Construct]
3257 // In the next expressions:
3258 // * x and v (as applicable) are both l-value expressions with scalar type.
3259 // * During the execution of an atomic region, multiple syntactic
3260 // occurrences of x must designate the same storage location.
3261 // * Neither of v and expr (as applicable) may access the storage location
3263 // * Neither of x and expr (as applicable) may access the storage location
3265 // * expr is an expression with scalar type.
3266 // * binop is one of +, *, -, /, &, ^, |, <<, or >>.
3267 // * binop, binop=, ++, and -- are not overloaded operators.
3268 // * The expression x binop expr must be numerically equivalent to x binop
3269 // (expr). This requirement is satisfied if the operators in expr have
3270 // precedence greater than binop, or by using parentheses around expr or
3271 // subexpressions of expr.
3272 // * The expression expr binop x must be numerically equivalent to (expr)
3273 // binop x. This requirement is satisfied if the operators in expr have
3274 // precedence equal to or greater than binop, or by using parentheses around
3275 // expr or subexpressions of expr.
3276 // * For forms that allow multiple occurrences of x, the number of times
3277 // that x is evaluated is unspecified.
3284 } ErrorFound = NoError;
3285 if (AtomicKind == OMPC_read) {
3286 SourceLocation ErrorLoc, NoteLoc;
3287 SourceRange ErrorRange, NoteRange;
3288 // If clause is read:
3290 if (auto AtomicBody = dyn_cast<Expr>(Body)) {
3292 dyn_cast<BinaryOperator>(AtomicBody->IgnoreParenImpCasts());
3293 if (AtomicBinOp && AtomicBinOp->getOpcode() == BO_Assign) {
3294 X = AtomicBinOp->getRHS()->IgnoreParenImpCasts();
3295 V = AtomicBinOp->getLHS()->IgnoreParenImpCasts();
3296 if ((X->isInstantiationDependent() || X->getType()->isScalarType()) &&
3297 (V->isInstantiationDependent() || V->getType()->isScalarType())) {
3298 if (!X->isLValue() || !V->isLValue()) {
3299 auto NotLValueExpr = X->isLValue() ? V : X;
3300 ErrorFound = NotAnLValue;
3301 ErrorLoc = AtomicBinOp->getExprLoc();
3302 ErrorRange = AtomicBinOp->getSourceRange();
3303 NoteLoc = NotLValueExpr->getExprLoc();
3304 NoteRange = NotLValueExpr->getSourceRange();
3306 } else if (!X->isInstantiationDependent() ||
3307 !V->isInstantiationDependent()) {
3308 auto NotScalarExpr =
3309 (X->isInstantiationDependent() || X->getType()->isScalarType())
3312 ErrorFound = NotAScalarType;
3313 ErrorLoc = AtomicBinOp->getExprLoc();
3314 ErrorRange = AtomicBinOp->getSourceRange();
3315 NoteLoc = NotScalarExpr->getExprLoc();
3316 NoteRange = NotScalarExpr->getSourceRange();
3319 ErrorFound = NotAnAssignmentOp;
3320 ErrorLoc = AtomicBody->getExprLoc();
3321 ErrorRange = AtomicBody->getSourceRange();
3322 NoteLoc = AtomicBinOp ? AtomicBinOp->getOperatorLoc()
3323 : AtomicBody->getExprLoc();
3324 NoteRange = AtomicBinOp ? AtomicBinOp->getSourceRange()
3325 : AtomicBody->getSourceRange();
3328 ErrorFound = NotAnExpression;
3329 NoteLoc = ErrorLoc = Body->getLocStart();
3330 NoteRange = ErrorRange = SourceRange(NoteLoc, NoteLoc);
3332 if (ErrorFound != NoError) {
3333 Diag(ErrorLoc, diag::err_omp_atomic_read_not_expression_statement)
3335 Diag(NoteLoc, diag::note_omp_atomic_read_write) << ErrorFound
3338 } else if (CurContext->isDependentContext())
3340 } else if (AtomicKind == OMPC_write) {
3341 SourceLocation ErrorLoc, NoteLoc;
3342 SourceRange ErrorRange, NoteRange;
3343 // If clause is write:
3345 if (auto AtomicBody = dyn_cast<Expr>(Body)) {
3347 dyn_cast<BinaryOperator>(AtomicBody->IgnoreParenImpCasts());
3348 if (AtomicBinOp && AtomicBinOp->getOpcode() == BO_Assign) {
3349 X = AtomicBinOp->getLHS()->IgnoreParenImpCasts();
3350 E = AtomicBinOp->getRHS()->IgnoreParenImpCasts();
3351 if ((X->isInstantiationDependent() || X->getType()->isScalarType()) &&
3352 (E->isInstantiationDependent() || E->getType()->isScalarType())) {
3353 if (!X->isLValue()) {
3354 ErrorFound = NotAnLValue;
3355 ErrorLoc = AtomicBinOp->getExprLoc();
3356 ErrorRange = AtomicBinOp->getSourceRange();
3357 NoteLoc = X->getExprLoc();
3358 NoteRange = X->getSourceRange();
3360 } else if (!X->isInstantiationDependent() ||
3361 !E->isInstantiationDependent()) {
3362 auto NotScalarExpr =
3363 (X->isInstantiationDependent() || X->getType()->isScalarType())
3366 ErrorFound = NotAScalarType;
3367 ErrorLoc = AtomicBinOp->getExprLoc();
3368 ErrorRange = AtomicBinOp->getSourceRange();
3369 NoteLoc = NotScalarExpr->getExprLoc();
3370 NoteRange = NotScalarExpr->getSourceRange();
3373 ErrorFound = NotAnAssignmentOp;
3374 ErrorLoc = AtomicBody->getExprLoc();
3375 ErrorRange = AtomicBody->getSourceRange();
3376 NoteLoc = AtomicBinOp ? AtomicBinOp->getOperatorLoc()
3377 : AtomicBody->getExprLoc();
3378 NoteRange = AtomicBinOp ? AtomicBinOp->getSourceRange()
3379 : AtomicBody->getSourceRange();
3382 ErrorFound = NotAnExpression;
3383 NoteLoc = ErrorLoc = Body->getLocStart();
3384 NoteRange = ErrorRange = SourceRange(NoteLoc, NoteLoc);
3386 if (ErrorFound != NoError) {
3387 Diag(ErrorLoc, diag::err_omp_atomic_write_not_expression_statement)
3389 Diag(NoteLoc, diag::note_omp_atomic_read_write) << ErrorFound
3392 } else if (CurContext->isDependentContext())
3394 } else if (AtomicKind == OMPC_update || AtomicKind == OMPC_unknown) {
3395 if (!isa<Expr>(Body)) {
3396 Diag(Body->getLocStart(),
3397 diag::err_omp_atomic_update_not_expression_statement)
3398 << (AtomicKind == OMPC_update);
3401 } else if (AtomicKind == OMPC_capture) {
3402 if (isa<Expr>(Body) && !isa<BinaryOperator>(Body)) {
3403 Diag(Body->getLocStart(),
3404 diag::err_omp_atomic_capture_not_expression_statement);
3406 } else if (!isa<Expr>(Body) && !isa<CompoundStmt>(Body)) {
3407 Diag(Body->getLocStart(),
3408 diag::err_omp_atomic_capture_not_compound_statement);
3413 getCurFunction()->setHasBranchProtectedScope();
3415 return OMPAtomicDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt,
3419 StmtResult Sema::ActOnOpenMPTargetDirective(ArrayRef<OMPClause *> Clauses,
3421 SourceLocation StartLoc,
3422 SourceLocation EndLoc) {
3423 assert(AStmt && isa<CapturedStmt>(AStmt) && "Captured statement expected");
3425 // OpenMP [2.16, Nesting of Regions]
3426 // If specified, a teams construct must be contained within a target
3427 // construct. That target construct must contain no statements or directives
3428 // outside of the teams construct.
3429 if (DSAStack->hasInnerTeamsRegion()) {
3430 auto S = AStmt->IgnoreContainers(/*IgnoreCaptured*/ true);
3431 bool OMPTeamsFound = true;
3432 if (auto *CS = dyn_cast<CompoundStmt>(S)) {
3433 auto I = CS->body_begin();
3434 while (I != CS->body_end()) {
3435 auto OED = dyn_cast<OMPExecutableDirective>(*I);
3436 if (!OED || !isOpenMPTeamsDirective(OED->getDirectiveKind())) {
3437 OMPTeamsFound = false;
3442 assert(I != CS->body_end() && "Not found statement");
3445 if (!OMPTeamsFound) {
3446 Diag(StartLoc, diag::err_omp_target_contains_not_only_teams);
3447 Diag(DSAStack->getInnerTeamsRegionLoc(),
3448 diag::note_omp_nested_teams_construct_here);
3449 Diag(S->getLocStart(), diag::note_omp_nested_statement_here)
3450 << isa<OMPExecutableDirective>(S);
3455 getCurFunction()->setHasBranchProtectedScope();
3457 return OMPTargetDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt);
3460 StmtResult Sema::ActOnOpenMPTeamsDirective(ArrayRef<OMPClause *> Clauses,
3461 Stmt *AStmt, SourceLocation StartLoc,
3462 SourceLocation EndLoc) {
3463 assert(AStmt && isa<CapturedStmt>(AStmt) && "Captured statement expected");
3464 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
3465 // 1.2.2 OpenMP Language Terminology
3466 // Structured block - An executable statement with a single entry at the
3467 // top and a single exit at the bottom.
3468 // The point of exit cannot be a branch out of the structured block.
3469 // longjmp() and throw() must not violate the entry/exit criteria.
3470 CS->getCapturedDecl()->setNothrow();
3472 getCurFunction()->setHasBranchProtectedScope();
3474 return OMPTeamsDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt);
3477 OMPClause *Sema::ActOnOpenMPSingleExprClause(OpenMPClauseKind Kind, Expr *Expr,
3478 SourceLocation StartLoc,
3479 SourceLocation LParenLoc,
3480 SourceLocation EndLoc) {
3481 OMPClause *Res = nullptr;
3484 Res = ActOnOpenMPIfClause(Expr, StartLoc, LParenLoc, EndLoc);
3487 Res = ActOnOpenMPFinalClause(Expr, StartLoc, LParenLoc, EndLoc);
3489 case OMPC_num_threads:
3490 Res = ActOnOpenMPNumThreadsClause(Expr, StartLoc, LParenLoc, EndLoc);
3493 Res = ActOnOpenMPSafelenClause(Expr, StartLoc, LParenLoc, EndLoc);
3496 Res = ActOnOpenMPCollapseClause(Expr, StartLoc, LParenLoc, EndLoc);
3499 case OMPC_proc_bind:
3502 case OMPC_firstprivate:
3503 case OMPC_lastprivate:
3505 case OMPC_reduction:
3509 case OMPC_copyprivate:
3513 case OMPC_mergeable:
3514 case OMPC_threadprivate:
3522 llvm_unreachable("Clause is not allowed.");
3527 OMPClause *Sema::ActOnOpenMPIfClause(Expr *Condition, SourceLocation StartLoc,
3528 SourceLocation LParenLoc,
3529 SourceLocation EndLoc) {
3530 Expr *ValExpr = Condition;
3531 if (!Condition->isValueDependent() && !Condition->isTypeDependent() &&
3532 !Condition->isInstantiationDependent() &&
3533 !Condition->containsUnexpandedParameterPack()) {
3534 ExprResult Val = ActOnBooleanCondition(DSAStack->getCurScope(),
3535 Condition->getExprLoc(), Condition);
3536 if (Val.isInvalid())
3539 ValExpr = Val.get();
3542 return new (Context) OMPIfClause(ValExpr, StartLoc, LParenLoc, EndLoc);
3545 OMPClause *Sema::ActOnOpenMPFinalClause(Expr *Condition,
3546 SourceLocation StartLoc,
3547 SourceLocation LParenLoc,
3548 SourceLocation EndLoc) {
3549 Expr *ValExpr = Condition;
3550 if (!Condition->isValueDependent() && !Condition->isTypeDependent() &&
3551 !Condition->isInstantiationDependent() &&
3552 !Condition->containsUnexpandedParameterPack()) {
3553 ExprResult Val = ActOnBooleanCondition(DSAStack->getCurScope(),
3554 Condition->getExprLoc(), Condition);
3555 if (Val.isInvalid())
3558 ValExpr = Val.get();
3561 return new (Context) OMPFinalClause(ValExpr, StartLoc, LParenLoc, EndLoc);
3563 ExprResult Sema::PerformOpenMPImplicitIntegerConversion(SourceLocation Loc,
3568 class IntConvertDiagnoser : public ICEConvertDiagnoser {
3570 IntConvertDiagnoser()
3571 : ICEConvertDiagnoser(/*AllowScopedEnumerations*/ false, false, true) {}
3572 SemaDiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc,
3573 QualType T) override {
3574 return S.Diag(Loc, diag::err_omp_not_integral) << T;
3576 SemaDiagnosticBuilder diagnoseIncomplete(Sema &S, SourceLocation Loc,
3577 QualType T) override {
3578 return S.Diag(Loc, diag::err_omp_incomplete_type) << T;
3580 SemaDiagnosticBuilder diagnoseExplicitConv(Sema &S, SourceLocation Loc,
3582 QualType ConvTy) override {
3583 return S.Diag(Loc, diag::err_omp_explicit_conversion) << T << ConvTy;
3585 SemaDiagnosticBuilder noteExplicitConv(Sema &S, CXXConversionDecl *Conv,
3586 QualType ConvTy) override {
3587 return S.Diag(Conv->getLocation(), diag::note_omp_conversion_here)
3588 << ConvTy->isEnumeralType() << ConvTy;
3590 SemaDiagnosticBuilder diagnoseAmbiguous(Sema &S, SourceLocation Loc,
3591 QualType T) override {
3592 return S.Diag(Loc, diag::err_omp_ambiguous_conversion) << T;
3594 SemaDiagnosticBuilder noteAmbiguous(Sema &S, CXXConversionDecl *Conv,
3595 QualType ConvTy) override {
3596 return S.Diag(Conv->getLocation(), diag::note_omp_conversion_here)
3597 << ConvTy->isEnumeralType() << ConvTy;
3599 SemaDiagnosticBuilder diagnoseConversion(Sema &, SourceLocation, QualType,
3600 QualType) override {
3601 llvm_unreachable("conversion functions are permitted");
3604 return PerformContextualImplicitConversion(Loc, Op, ConvertDiagnoser);
3607 OMPClause *Sema::ActOnOpenMPNumThreadsClause(Expr *NumThreads,
3608 SourceLocation StartLoc,
3609 SourceLocation LParenLoc,
3610 SourceLocation EndLoc) {
3611 Expr *ValExpr = NumThreads;
3612 if (!NumThreads->isValueDependent() && !NumThreads->isTypeDependent() &&
3613 !NumThreads->containsUnexpandedParameterPack()) {
3614 SourceLocation NumThreadsLoc = NumThreads->getLocStart();
3616 PerformOpenMPImplicitIntegerConversion(NumThreadsLoc, NumThreads);
3617 if (Val.isInvalid())
3620 ValExpr = Val.get();
3622 // OpenMP [2.5, Restrictions]
3623 // The num_threads expression must evaluate to a positive integer value.
3624 llvm::APSInt Result;
3625 if (ValExpr->isIntegerConstantExpr(Result, Context) && Result.isSigned() &&
3626 !Result.isStrictlyPositive()) {
3627 Diag(NumThreadsLoc, diag::err_omp_negative_expression_in_clause)
3628 << "num_threads" << NumThreads->getSourceRange();
3633 return new (Context)
3634 OMPNumThreadsClause(ValExpr, StartLoc, LParenLoc, EndLoc);
3637 ExprResult Sema::VerifyPositiveIntegerConstantInClause(Expr *E,
3638 OpenMPClauseKind CKind) {
3641 if (E->isValueDependent() || E->isTypeDependent() ||
3642 E->isInstantiationDependent() || E->containsUnexpandedParameterPack())
3644 llvm::APSInt Result;
3645 ExprResult ICE = VerifyIntegerConstantExpression(E, &Result);
3646 if (ICE.isInvalid())
3648 if (!Result.isStrictlyPositive()) {
3649 Diag(E->getExprLoc(), diag::err_omp_negative_expression_in_clause)
3650 << getOpenMPClauseName(CKind) << E->getSourceRange();
3653 if (CKind == OMPC_aligned && !Result.isPowerOf2()) {
3654 Diag(E->getExprLoc(), diag::warn_omp_alignment_not_power_of_two)
3655 << E->getSourceRange();
3661 OMPClause *Sema::ActOnOpenMPSafelenClause(Expr *Len, SourceLocation StartLoc,
3662 SourceLocation LParenLoc,
3663 SourceLocation EndLoc) {
3664 // OpenMP [2.8.1, simd construct, Description]
3665 // The parameter of the safelen clause must be a constant
3666 // positive integer expression.
3667 ExprResult Safelen = VerifyPositiveIntegerConstantInClause(Len, OMPC_safelen);
3668 if (Safelen.isInvalid())
3670 return new (Context)
3671 OMPSafelenClause(Safelen.get(), StartLoc, LParenLoc, EndLoc);
3674 OMPClause *Sema::ActOnOpenMPCollapseClause(Expr *NumForLoops,
3675 SourceLocation StartLoc,
3676 SourceLocation LParenLoc,
3677 SourceLocation EndLoc) {
3678 // OpenMP [2.7.1, loop construct, Description]
3679 // OpenMP [2.8.1, simd construct, Description]
3680 // OpenMP [2.9.6, distribute construct, Description]
3681 // The parameter of the collapse clause must be a constant
3682 // positive integer expression.
3683 ExprResult NumForLoopsResult =
3684 VerifyPositiveIntegerConstantInClause(NumForLoops, OMPC_collapse);
3685 if (NumForLoopsResult.isInvalid())
3687 return new (Context)
3688 OMPCollapseClause(NumForLoopsResult.get(), StartLoc, LParenLoc, EndLoc);
3691 OMPClause *Sema::ActOnOpenMPSimpleClause(
3692 OpenMPClauseKind Kind, unsigned Argument, SourceLocation ArgumentLoc,
3693 SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc) {
3694 OMPClause *Res = nullptr;
3698 ActOnOpenMPDefaultClause(static_cast<OpenMPDefaultClauseKind>(Argument),
3699 ArgumentLoc, StartLoc, LParenLoc, EndLoc);
3701 case OMPC_proc_bind:
3702 Res = ActOnOpenMPProcBindClause(
3703 static_cast<OpenMPProcBindClauseKind>(Argument), ArgumentLoc, StartLoc,
3708 case OMPC_num_threads:
3713 case OMPC_firstprivate:
3714 case OMPC_lastprivate:
3716 case OMPC_reduction:
3720 case OMPC_copyprivate:
3724 case OMPC_mergeable:
3725 case OMPC_threadprivate:
3733 llvm_unreachable("Clause is not allowed.");
3738 OMPClause *Sema::ActOnOpenMPDefaultClause(OpenMPDefaultClauseKind Kind,
3739 SourceLocation KindKwLoc,
3740 SourceLocation StartLoc,
3741 SourceLocation LParenLoc,
3742 SourceLocation EndLoc) {
3743 if (Kind == OMPC_DEFAULT_unknown) {
3745 static_assert(OMPC_DEFAULT_unknown > 0,
3746 "OMPC_DEFAULT_unknown not greater than 0");
3747 std::string Sep(", ");
3748 for (unsigned i = 0; i < OMPC_DEFAULT_unknown; ++i) {
3750 Values += getOpenMPSimpleClauseTypeName(OMPC_default, i);
3753 case OMPC_DEFAULT_unknown - 2:
3756 case OMPC_DEFAULT_unknown - 1:
3763 Diag(KindKwLoc, diag::err_omp_unexpected_clause_value)
3764 << Values << getOpenMPClauseName(OMPC_default);
3768 case OMPC_DEFAULT_none:
3769 DSAStack->setDefaultDSANone(KindKwLoc);
3771 case OMPC_DEFAULT_shared:
3772 DSAStack->setDefaultDSAShared(KindKwLoc);
3774 case OMPC_DEFAULT_unknown:
3775 llvm_unreachable("Clause kind is not allowed.");
3778 return new (Context)
3779 OMPDefaultClause(Kind, KindKwLoc, StartLoc, LParenLoc, EndLoc);
3782 OMPClause *Sema::ActOnOpenMPProcBindClause(OpenMPProcBindClauseKind Kind,
3783 SourceLocation KindKwLoc,
3784 SourceLocation StartLoc,
3785 SourceLocation LParenLoc,
3786 SourceLocation EndLoc) {
3787 if (Kind == OMPC_PROC_BIND_unknown) {
3789 std::string Sep(", ");
3790 for (unsigned i = 0; i < OMPC_PROC_BIND_unknown; ++i) {
3792 Values += getOpenMPSimpleClauseTypeName(OMPC_proc_bind, i);
3795 case OMPC_PROC_BIND_unknown - 2:
3798 case OMPC_PROC_BIND_unknown - 1:
3805 Diag(KindKwLoc, diag::err_omp_unexpected_clause_value)
3806 << Values << getOpenMPClauseName(OMPC_proc_bind);
3809 return new (Context)
3810 OMPProcBindClause(Kind, KindKwLoc, StartLoc, LParenLoc, EndLoc);
3813 OMPClause *Sema::ActOnOpenMPSingleExprWithArgClause(
3814 OpenMPClauseKind Kind, unsigned Argument, Expr *Expr,
3815 SourceLocation StartLoc, SourceLocation LParenLoc,
3816 SourceLocation ArgumentLoc, SourceLocation CommaLoc,
3817 SourceLocation EndLoc) {
3818 OMPClause *Res = nullptr;
3821 Res = ActOnOpenMPScheduleClause(
3822 static_cast<OpenMPScheduleClauseKind>(Argument), Expr, StartLoc,
3823 LParenLoc, ArgumentLoc, CommaLoc, EndLoc);
3827 case OMPC_num_threads:
3831 case OMPC_proc_bind:
3833 case OMPC_firstprivate:
3834 case OMPC_lastprivate:
3836 case OMPC_reduction:
3840 case OMPC_copyprivate:
3844 case OMPC_mergeable:
3845 case OMPC_threadprivate:
3853 llvm_unreachable("Clause is not allowed.");
3858 OMPClause *Sema::ActOnOpenMPScheduleClause(
3859 OpenMPScheduleClauseKind Kind, Expr *ChunkSize, SourceLocation StartLoc,
3860 SourceLocation LParenLoc, SourceLocation KindLoc, SourceLocation CommaLoc,
3861 SourceLocation EndLoc) {
3862 if (Kind == OMPC_SCHEDULE_unknown) {
3864 std::string Sep(", ");
3865 for (unsigned i = 0; i < OMPC_SCHEDULE_unknown; ++i) {
3867 Values += getOpenMPSimpleClauseTypeName(OMPC_schedule, i);
3870 case OMPC_SCHEDULE_unknown - 2:
3873 case OMPC_SCHEDULE_unknown - 1:
3880 Diag(KindLoc, diag::err_omp_unexpected_clause_value)
3881 << Values << getOpenMPClauseName(OMPC_schedule);
3884 Expr *ValExpr = ChunkSize;
3886 if (!ChunkSize->isValueDependent() && !ChunkSize->isTypeDependent() &&
3887 !ChunkSize->isInstantiationDependent() &&
3888 !ChunkSize->containsUnexpandedParameterPack()) {
3889 SourceLocation ChunkSizeLoc = ChunkSize->getLocStart();
3891 PerformOpenMPImplicitIntegerConversion(ChunkSizeLoc, ChunkSize);
3892 if (Val.isInvalid())
3895 ValExpr = Val.get();
3897 // OpenMP [2.7.1, Restrictions]
3898 // chunk_size must be a loop invariant integer expression with a positive
3900 llvm::APSInt Result;
3901 if (ValExpr->isIntegerConstantExpr(Result, Context) &&
3902 Result.isSigned() && !Result.isStrictlyPositive()) {
3903 Diag(ChunkSizeLoc, diag::err_omp_negative_expression_in_clause)
3904 << "schedule" << ChunkSize->getSourceRange();
3910 return new (Context) OMPScheduleClause(StartLoc, LParenLoc, KindLoc, CommaLoc,
3911 EndLoc, Kind, ValExpr);
3914 OMPClause *Sema::ActOnOpenMPClause(OpenMPClauseKind Kind,
3915 SourceLocation StartLoc,
3916 SourceLocation EndLoc) {
3917 OMPClause *Res = nullptr;
3920 Res = ActOnOpenMPOrderedClause(StartLoc, EndLoc);
3923 Res = ActOnOpenMPNowaitClause(StartLoc, EndLoc);
3926 Res = ActOnOpenMPUntiedClause(StartLoc, EndLoc);
3928 case OMPC_mergeable:
3929 Res = ActOnOpenMPMergeableClause(StartLoc, EndLoc);
3932 Res = ActOnOpenMPReadClause(StartLoc, EndLoc);
3935 Res = ActOnOpenMPWriteClause(StartLoc, EndLoc);
3938 Res = ActOnOpenMPUpdateClause(StartLoc, EndLoc);
3941 Res = ActOnOpenMPCaptureClause(StartLoc, EndLoc);
3944 Res = ActOnOpenMPSeqCstClause(StartLoc, EndLoc);
3948 case OMPC_num_threads:
3953 case OMPC_firstprivate:
3954 case OMPC_lastprivate:
3956 case OMPC_reduction:
3960 case OMPC_copyprivate:
3962 case OMPC_proc_bind:
3963 case OMPC_threadprivate:
3966 llvm_unreachable("Clause is not allowed.");
3971 OMPClause *Sema::ActOnOpenMPOrderedClause(SourceLocation StartLoc,
3972 SourceLocation EndLoc) {
3973 DSAStack->setOrderedRegion();
3974 return new (Context) OMPOrderedClause(StartLoc, EndLoc);
3977 OMPClause *Sema::ActOnOpenMPNowaitClause(SourceLocation StartLoc,
3978 SourceLocation EndLoc) {
3979 return new (Context) OMPNowaitClause(StartLoc, EndLoc);
3982 OMPClause *Sema::ActOnOpenMPUntiedClause(SourceLocation StartLoc,
3983 SourceLocation EndLoc) {
3984 return new (Context) OMPUntiedClause(StartLoc, EndLoc);
3987 OMPClause *Sema::ActOnOpenMPMergeableClause(SourceLocation StartLoc,
3988 SourceLocation EndLoc) {
3989 return new (Context) OMPMergeableClause(StartLoc, EndLoc);
3992 OMPClause *Sema::ActOnOpenMPReadClause(SourceLocation StartLoc,
3993 SourceLocation EndLoc) {
3994 return new (Context) OMPReadClause(StartLoc, EndLoc);
3997 OMPClause *Sema::ActOnOpenMPWriteClause(SourceLocation StartLoc,
3998 SourceLocation EndLoc) {
3999 return new (Context) OMPWriteClause(StartLoc, EndLoc);
4002 OMPClause *Sema::ActOnOpenMPUpdateClause(SourceLocation StartLoc,
4003 SourceLocation EndLoc) {
4004 return new (Context) OMPUpdateClause(StartLoc, EndLoc);
4007 OMPClause *Sema::ActOnOpenMPCaptureClause(SourceLocation StartLoc,
4008 SourceLocation EndLoc) {
4009 return new (Context) OMPCaptureClause(StartLoc, EndLoc);
4012 OMPClause *Sema::ActOnOpenMPSeqCstClause(SourceLocation StartLoc,
4013 SourceLocation EndLoc) {
4014 return new (Context) OMPSeqCstClause(StartLoc, EndLoc);
4017 OMPClause *Sema::ActOnOpenMPVarListClause(
4018 OpenMPClauseKind Kind, ArrayRef<Expr *> VarList, Expr *TailExpr,
4019 SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation ColonLoc,
4020 SourceLocation EndLoc, CXXScopeSpec &ReductionIdScopeSpec,
4021 const DeclarationNameInfo &ReductionId) {
4022 OMPClause *Res = nullptr;
4025 Res = ActOnOpenMPPrivateClause(VarList, StartLoc, LParenLoc, EndLoc);
4027 case OMPC_firstprivate:
4028 Res = ActOnOpenMPFirstprivateClause(VarList, StartLoc, LParenLoc, EndLoc);
4030 case OMPC_lastprivate:
4031 Res = ActOnOpenMPLastprivateClause(VarList, StartLoc, LParenLoc, EndLoc);
4034 Res = ActOnOpenMPSharedClause(VarList, StartLoc, LParenLoc, EndLoc);
4036 case OMPC_reduction:
4037 Res = ActOnOpenMPReductionClause(VarList, StartLoc, LParenLoc, ColonLoc,
4038 EndLoc, ReductionIdScopeSpec, ReductionId);
4041 Res = ActOnOpenMPLinearClause(VarList, TailExpr, StartLoc, LParenLoc,
4045 Res = ActOnOpenMPAlignedClause(VarList, TailExpr, StartLoc, LParenLoc,
4049 Res = ActOnOpenMPCopyinClause(VarList, StartLoc, LParenLoc, EndLoc);
4051 case OMPC_copyprivate:
4052 Res = ActOnOpenMPCopyprivateClause(VarList, StartLoc, LParenLoc, EndLoc);
4055 Res = ActOnOpenMPFlushClause(VarList, StartLoc, LParenLoc, EndLoc);
4059 case OMPC_num_threads:
4063 case OMPC_proc_bind:
4068 case OMPC_mergeable:
4069 case OMPC_threadprivate:
4076 llvm_unreachable("Clause is not allowed.");
4081 OMPClause *Sema::ActOnOpenMPPrivateClause(ArrayRef<Expr *> VarList,
4082 SourceLocation StartLoc,
4083 SourceLocation LParenLoc,
4084 SourceLocation EndLoc) {
4085 SmallVector<Expr *, 8> Vars;
4086 SmallVector<Expr *, 8> PrivateCopies;
4087 for (auto &RefExpr : VarList) {
4088 assert(RefExpr && "NULL expr in OpenMP private clause.");
4089 if (isa<DependentScopeDeclRefExpr>(RefExpr)) {
4090 // It will be analyzed later.
4091 Vars.push_back(RefExpr);
4092 PrivateCopies.push_back(nullptr);
4096 SourceLocation ELoc = RefExpr->getExprLoc();
4097 // OpenMP [2.1, C/C++]
4098 // A list item is a variable name.
4099 // OpenMP [2.9.3.3, Restrictions, p.1]
4100 // A variable that is part of another variable (as an array or
4101 // structure element) cannot appear in a private clause.
4102 DeclRefExpr *DE = dyn_cast_or_null<DeclRefExpr>(RefExpr);
4103 if (!DE || !isa<VarDecl>(DE->getDecl())) {
4104 Diag(ELoc, diag::err_omp_expected_var_name) << RefExpr->getSourceRange();
4107 Decl *D = DE->getDecl();
4108 VarDecl *VD = cast<VarDecl>(D);
4110 QualType Type = VD->getType();
4111 if (Type->isDependentType() || Type->isInstantiationDependentType()) {
4112 // It will be analyzed later.
4114 PrivateCopies.push_back(nullptr);
4118 // OpenMP [2.9.3.3, Restrictions, C/C++, p.3]
4119 // A variable that appears in a private clause must not have an incomplete
4120 // type or a reference type.
4121 if (RequireCompleteType(ELoc, Type,
4122 diag::err_omp_private_incomplete_type)) {
4125 if (Type->isReferenceType()) {
4126 Diag(ELoc, diag::err_omp_clause_ref_type_arg)
4127 << getOpenMPClauseName(OMPC_private) << Type;
4129 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
4130 Diag(VD->getLocation(),
4131 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
4136 // OpenMP [2.9.3.3, Restrictions, C/C++, p.1]
4137 // A variable of class type (or array thereof) that appears in a private
4138 // clause requires an accessible, unambiguous default constructor for the
4140 while (Type->isArrayType()) {
4141 Type = cast<ArrayType>(Type.getTypePtr())->getElementType();
4144 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
4146 // Variables with the predetermined data-sharing attributes may not be
4147 // listed in data-sharing attributes clauses, except for the cases
4148 // listed below. For these exceptions only, listing a predetermined
4149 // variable in a data-sharing attribute clause is allowed and overrides
4150 // the variable's predetermined data-sharing attributes.
4151 DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(VD, false);
4152 if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_private) {
4153 Diag(ELoc, diag::err_omp_wrong_dsa) << getOpenMPClauseName(DVar.CKind)
4154 << getOpenMPClauseName(OMPC_private);
4155 ReportOriginalDSA(*this, DSAStack, VD, DVar);
4159 // Generate helper private variable and initialize it with the default
4160 // value. The address of the original variable is replaced by the address of
4161 // the new private variable in CodeGen. This new variable is not added to
4162 // IdResolver, so the code in the OpenMP region uses original variable for
4163 // proper diagnostics.
4165 VarDecl::Create(Context, CurContext, DE->getLocStart(),
4166 DE->getExprLoc(), VD->getIdentifier(), VD->getType(),
4167 VD->getTypeSourceInfo(), /*S*/ SC_Auto);
4168 ActOnUninitializedDecl(VDPrivate, /*TypeMayContainAuto*/ false);
4169 if (VDPrivate->isInvalidDecl())
4171 CurContext->addDecl(VDPrivate);
4172 auto VDPrivateRefExpr =
4173 DeclRefExpr::Create(Context, /*QualifierLoc*/ NestedNameSpecifierLoc(),
4174 /*TemplateKWLoc*/ SourceLocation(), VDPrivate,
4175 /*RefersToEnclosingVariableOrCapture*/ false,
4176 /*NameLoc*/ SourceLocation(), DE->getType(),
4179 DSAStack->addDSA(VD, DE, OMPC_private);
4181 PrivateCopies.push_back(VDPrivateRefExpr);
4187 return OMPPrivateClause::Create(Context, StartLoc, LParenLoc, EndLoc, Vars,
4192 class DiagsUninitializedSeveretyRAII {
4194 DiagnosticsEngine &Diags;
4195 SourceLocation SavedLoc;
4199 DiagsUninitializedSeveretyRAII(DiagnosticsEngine &Diags, SourceLocation Loc,
4201 : Diags(Diags), SavedLoc(Loc), IsIgnored(IsIgnored) {
4203 Diags.setSeverity(/*Diag*/ diag::warn_uninit_self_reference_in_init,
4204 /*Map*/ diag::Severity::Ignored, Loc);
4207 ~DiagsUninitializedSeveretyRAII() {
4209 Diags.popMappings(SavedLoc);
4214 OMPClause *Sema::ActOnOpenMPFirstprivateClause(ArrayRef<Expr *> VarList,
4215 SourceLocation StartLoc,
4216 SourceLocation LParenLoc,
4217 SourceLocation EndLoc) {
4218 SmallVector<Expr *, 8> Vars;
4219 SmallVector<Expr *, 8> PrivateCopies;
4220 SmallVector<Expr *, 8> Inits;
4221 bool IsImplicitClause =
4222 StartLoc.isInvalid() && LParenLoc.isInvalid() && EndLoc.isInvalid();
4223 auto ImplicitClauseLoc = DSAStack->getConstructLoc();
4225 for (auto &RefExpr : VarList) {
4226 assert(RefExpr && "NULL expr in OpenMP firstprivate clause.");
4227 if (isa<DependentScopeDeclRefExpr>(RefExpr)) {
4228 // It will be analyzed later.
4229 Vars.push_back(RefExpr);
4230 PrivateCopies.push_back(nullptr);
4231 Inits.push_back(nullptr);
4235 SourceLocation ELoc =
4236 IsImplicitClause ? ImplicitClauseLoc : RefExpr->getExprLoc();
4237 // OpenMP [2.1, C/C++]
4238 // A list item is a variable name.
4239 // OpenMP [2.9.3.3, Restrictions, p.1]
4240 // A variable that is part of another variable (as an array or
4241 // structure element) cannot appear in a private clause.
4242 DeclRefExpr *DE = dyn_cast_or_null<DeclRefExpr>(RefExpr);
4243 if (!DE || !isa<VarDecl>(DE->getDecl())) {
4244 Diag(ELoc, diag::err_omp_expected_var_name) << RefExpr->getSourceRange();
4247 Decl *D = DE->getDecl();
4248 VarDecl *VD = cast<VarDecl>(D);
4250 QualType Type = VD->getType();
4251 if (Type->isDependentType() || Type->isInstantiationDependentType()) {
4252 // It will be analyzed later.
4254 PrivateCopies.push_back(nullptr);
4255 Inits.push_back(nullptr);
4259 // OpenMP [2.9.3.3, Restrictions, C/C++, p.3]
4260 // A variable that appears in a private clause must not have an incomplete
4261 // type or a reference type.
4262 if (RequireCompleteType(ELoc, Type,
4263 diag::err_omp_firstprivate_incomplete_type)) {
4266 if (Type->isReferenceType()) {
4267 if (IsImplicitClause) {
4268 Diag(ImplicitClauseLoc,
4269 diag::err_omp_task_predetermined_firstprivate_ref_type_arg)
4271 Diag(RefExpr->getExprLoc(), diag::note_used_here);
4273 Diag(ELoc, diag::err_omp_clause_ref_type_arg)
4274 << getOpenMPClauseName(OMPC_firstprivate) << Type;
4277 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
4278 Diag(VD->getLocation(),
4279 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
4284 // OpenMP [2.9.3.4, Restrictions, C/C++, p.1]
4285 // A variable of class type (or array thereof) that appears in a private
4286 // clause requires an accessible, unambiguous copy constructor for the
4288 Type = Context.getBaseElementType(Type);
4290 // If an implicit firstprivate variable found it was checked already.
4291 if (!IsImplicitClause) {
4292 DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(VD, false);
4293 Type = Type.getNonReferenceType().getCanonicalType();
4294 bool IsConstant = Type.isConstant(Context);
4295 Type = Context.getBaseElementType(Type);
4296 // OpenMP [2.4.13, Data-sharing Attribute Clauses]
4297 // A list item that specifies a given variable may not appear in more
4298 // than one clause on the same directive, except that a variable may be
4299 // specified in both firstprivate and lastprivate clauses.
4300 if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_firstprivate &&
4301 DVar.CKind != OMPC_lastprivate && DVar.RefExpr) {
4302 Diag(ELoc, diag::err_omp_wrong_dsa)
4303 << getOpenMPClauseName(DVar.CKind)
4304 << getOpenMPClauseName(OMPC_firstprivate);
4305 ReportOriginalDSA(*this, DSAStack, VD, DVar);
4309 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
4311 // Variables with the predetermined data-sharing attributes may not be
4312 // listed in data-sharing attributes clauses, except for the cases
4313 // listed below. For these exceptions only, listing a predetermined
4314 // variable in a data-sharing attribute clause is allowed and overrides
4315 // the variable's predetermined data-sharing attributes.
4316 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
4317 // in a Construct, C/C++, p.2]
4318 // Variables with const-qualified type having no mutable member may be
4319 // listed in a firstprivate clause, even if they are static data members.
4320 if (!(IsConstant || VD->isStaticDataMember()) && !DVar.RefExpr &&
4321 DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_shared) {
4322 Diag(ELoc, diag::err_omp_wrong_dsa)
4323 << getOpenMPClauseName(DVar.CKind)
4324 << getOpenMPClauseName(OMPC_firstprivate);
4325 ReportOriginalDSA(*this, DSAStack, VD, DVar);
4329 OpenMPDirectiveKind CurrDir = DSAStack->getCurrentDirective();
4330 // OpenMP [2.9.3.4, Restrictions, p.2]
4331 // A list item that is private within a parallel region must not appear
4332 // in a firstprivate clause on a worksharing construct if any of the
4333 // worksharing regions arising from the worksharing construct ever bind
4334 // to any of the parallel regions arising from the parallel construct.
4335 if (isOpenMPWorksharingDirective(CurrDir) &&
4336 !isOpenMPParallelDirective(CurrDir)) {
4337 DVar = DSAStack->getImplicitDSA(VD, true);
4338 if (DVar.CKind != OMPC_shared &&
4339 (isOpenMPParallelDirective(DVar.DKind) ||
4340 DVar.DKind == OMPD_unknown)) {
4341 Diag(ELoc, diag::err_omp_required_access)
4342 << getOpenMPClauseName(OMPC_firstprivate)
4343 << getOpenMPClauseName(OMPC_shared);
4344 ReportOriginalDSA(*this, DSAStack, VD, DVar);
4348 // OpenMP [2.9.3.4, Restrictions, p.3]
4349 // A list item that appears in a reduction clause of a parallel construct
4350 // must not appear in a firstprivate clause on a worksharing or task
4351 // construct if any of the worksharing or task regions arising from the
4352 // worksharing or task construct ever bind to any of the parallel regions
4353 // arising from the parallel construct.
4354 // OpenMP [2.9.3.4, Restrictions, p.4]
4355 // A list item that appears in a reduction clause in worksharing
4356 // construct must not appear in a firstprivate clause in a task construct
4357 // encountered during execution of any of the worksharing regions arising
4358 // from the worksharing construct.
4359 if (CurrDir == OMPD_task) {
4361 DSAStack->hasInnermostDSA(VD, MatchesAnyClause(OMPC_reduction),
4362 [](OpenMPDirectiveKind K) -> bool {
4363 return isOpenMPParallelDirective(K) ||
4364 isOpenMPWorksharingDirective(K);
4367 if (DVar.CKind == OMPC_reduction &&
4368 (isOpenMPParallelDirective(DVar.DKind) ||
4369 isOpenMPWorksharingDirective(DVar.DKind))) {
4370 Diag(ELoc, diag::err_omp_parallel_reduction_in_task_firstprivate)
4371 << getOpenMPDirectiveName(DVar.DKind);
4372 ReportOriginalDSA(*this, DSAStack, VD, DVar);
4378 Type = Type.getUnqualifiedType();
4379 auto VDPrivate = VarDecl::Create(Context, CurContext, DE->getLocStart(),
4380 ELoc, VD->getIdentifier(), VD->getType(),
4381 VD->getTypeSourceInfo(), /*S*/ SC_Auto);
4382 // Generate helper private variable and initialize it with the value of the
4383 // original variable. The address of the original variable is replaced by
4384 // the address of the new private variable in the CodeGen. This new variable
4385 // is not added to IdResolver, so the code in the OpenMP region uses
4386 // original variable for proper diagnostics and variable capturing.
4387 Expr *VDInitRefExpr = nullptr;
4388 // For arrays generate initializer for single element and replace it by the
4389 // original array element in CodeGen.
4390 if (DE->getType()->isArrayType()) {
4391 auto VDInit = VarDecl::Create(Context, CurContext, DE->getLocStart(),
4392 ELoc, VD->getIdentifier(), Type,
4393 VD->getTypeSourceInfo(), /*S*/ SC_Auto);
4394 CurContext->addHiddenDecl(VDInit);
4395 VDInitRefExpr = DeclRefExpr::Create(
4396 Context, /*QualifierLoc*/ NestedNameSpecifierLoc(),
4397 /*TemplateKWLoc*/ SourceLocation(), VDInit,
4398 /*RefersToEnclosingVariableOrCapture*/ true, ELoc, Type,
4400 VDInit->setIsUsed();
4401 auto Init = DefaultLvalueConversion(VDInitRefExpr).get();
4402 InitializedEntity Entity = InitializedEntity::InitializeVariable(VDInit);
4403 InitializationKind Kind = InitializationKind::CreateCopy(ELoc, ELoc);
4405 InitializationSequence InitSeq(*this, Entity, Kind, Init);
4406 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Init);
4407 if (Result.isInvalid())
4408 VDPrivate->setInvalidDecl();
4410 VDPrivate->setInit(Result.getAs<Expr>());
4412 AddInitializerToDecl(
4414 DefaultLvalueConversion(
4415 DeclRefExpr::Create(Context, NestedNameSpecifierLoc(),
4416 SourceLocation(), DE->getDecl(),
4417 /*RefersToEnclosingVariableOrCapture=*/true,
4418 DE->getExprLoc(), DE->getType(),
4419 /*VK=*/VK_LValue)).get(),
4420 /*DirectInit=*/false, /*TypeMayContainAuto=*/false);
4422 if (VDPrivate->isInvalidDecl()) {
4423 if (IsImplicitClause) {
4424 Diag(DE->getExprLoc(),
4425 diag::note_omp_task_predetermined_firstprivate_here);
4429 CurContext->addDecl(VDPrivate);
4430 auto VDPrivateRefExpr =
4431 DeclRefExpr::Create(Context, /*QualifierLoc*/ NestedNameSpecifierLoc(),
4432 /*TemplateKWLoc*/ SourceLocation(), VDPrivate,
4433 /*RefersToEnclosingVariableOrCapture*/ false,
4434 DE->getLocStart(), DE->getType(),
4436 DSAStack->addDSA(VD, DE, OMPC_firstprivate);
4438 PrivateCopies.push_back(VDPrivateRefExpr);
4439 Inits.push_back(VDInitRefExpr);
4445 return OMPFirstprivateClause::Create(Context, StartLoc, LParenLoc, EndLoc,
4446 Vars, PrivateCopies, Inits);
4449 OMPClause *Sema::ActOnOpenMPLastprivateClause(ArrayRef<Expr *> VarList,
4450 SourceLocation StartLoc,
4451 SourceLocation LParenLoc,
4452 SourceLocation EndLoc) {
4453 SmallVector<Expr *, 8> Vars;
4454 for (auto &RefExpr : VarList) {
4455 assert(RefExpr && "NULL expr in OpenMP lastprivate clause.");
4456 if (isa<DependentScopeDeclRefExpr>(RefExpr)) {
4457 // It will be analyzed later.
4458 Vars.push_back(RefExpr);
4462 SourceLocation ELoc = RefExpr->getExprLoc();
4463 // OpenMP [2.1, C/C++]
4464 // A list item is a variable name.
4465 // OpenMP [2.14.3.5, Restrictions, p.1]
4466 // A variable that is part of another variable (as an array or structure
4467 // element) cannot appear in a lastprivate clause.
4468 DeclRefExpr *DE = dyn_cast_or_null<DeclRefExpr>(RefExpr);
4469 if (!DE || !isa<VarDecl>(DE->getDecl())) {
4470 Diag(ELoc, diag::err_omp_expected_var_name) << RefExpr->getSourceRange();
4473 Decl *D = DE->getDecl();
4474 VarDecl *VD = cast<VarDecl>(D);
4476 QualType Type = VD->getType();
4477 if (Type->isDependentType() || Type->isInstantiationDependentType()) {
4478 // It will be analyzed later.
4483 // OpenMP [2.14.3.5, Restrictions, C/C++, p.2]
4484 // A variable that appears in a lastprivate clause must not have an
4485 // incomplete type or a reference type.
4486 if (RequireCompleteType(ELoc, Type,
4487 diag::err_omp_lastprivate_incomplete_type)) {
4490 if (Type->isReferenceType()) {
4491 Diag(ELoc, diag::err_omp_clause_ref_type_arg)
4492 << getOpenMPClauseName(OMPC_lastprivate) << Type;
4494 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
4495 Diag(VD->getLocation(),
4496 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
4501 // OpenMP [2.14.1.1, Data-sharing Attribute Rules for Variables Referenced
4503 // Variables with the predetermined data-sharing attributes may not be
4504 // listed in data-sharing attributes clauses, except for the cases
4506 DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(VD, false);
4507 if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_lastprivate &&
4508 DVar.CKind != OMPC_firstprivate &&
4509 (DVar.CKind != OMPC_private || DVar.RefExpr != nullptr)) {
4510 Diag(ELoc, diag::err_omp_wrong_dsa)
4511 << getOpenMPClauseName(DVar.CKind)
4512 << getOpenMPClauseName(OMPC_lastprivate);
4513 ReportOriginalDSA(*this, DSAStack, VD, DVar);
4517 OpenMPDirectiveKind CurrDir = DSAStack->getCurrentDirective();
4518 // OpenMP [2.14.3.5, Restrictions, p.2]
4519 // A list item that is private within a parallel region, or that appears in
4520 // the reduction clause of a parallel construct, must not appear in a
4521 // lastprivate clause on a worksharing construct if any of the corresponding
4522 // worksharing regions ever binds to any of the corresponding parallel
4524 if (isOpenMPWorksharingDirective(CurrDir) &&
4525 !isOpenMPParallelDirective(CurrDir)) {
4526 DVar = DSAStack->getImplicitDSA(VD, true);
4527 if (DVar.CKind != OMPC_shared) {
4528 Diag(ELoc, diag::err_omp_required_access)
4529 << getOpenMPClauseName(OMPC_lastprivate)
4530 << getOpenMPClauseName(OMPC_shared);
4531 ReportOriginalDSA(*this, DSAStack, VD, DVar);
4535 // OpenMP [2.14.3.5, Restrictions, C++, p.1,2]
4536 // A variable of class type (or array thereof) that appears in a
4537 // lastprivate clause requires an accessible, unambiguous default
4538 // constructor for the class type, unless the list item is also specified
4539 // in a firstprivate clause.
4540 // A variable of class type (or array thereof) that appears in a
4541 // lastprivate clause requires an accessible, unambiguous copy assignment
4542 // operator for the class type.
4543 while (Type.getNonReferenceType()->isArrayType())
4544 Type = cast<ArrayType>(Type.getNonReferenceType().getTypePtr())
4546 CXXRecordDecl *RD = getLangOpts().CPlusPlus
4547 ? Type.getNonReferenceType()->getAsCXXRecordDecl()
4549 // FIXME This code must be replaced by actual copying and destructing of the
4550 // lastprivate variable.
4552 CXXMethodDecl *MD = LookupCopyingAssignment(RD, 0, false, 0);
4553 DeclAccessPair FoundDecl = DeclAccessPair::make(MD, MD->getAccess());
4555 if (CheckMemberAccess(ELoc, RD, FoundDecl) == AR_inaccessible ||
4557 Diag(ELoc, diag::err_omp_required_method)
4558 << getOpenMPClauseName(OMPC_lastprivate) << 2;
4559 bool IsDecl = VD->isThisDeclarationADefinition(Context) ==
4560 VarDecl::DeclarationOnly;
4561 Diag(VD->getLocation(),
4562 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
4564 Diag(RD->getLocation(), diag::note_previous_decl) << RD;
4567 MarkFunctionReferenced(ELoc, MD);
4568 DiagnoseUseOfDecl(MD, ELoc);
4571 CXXDestructorDecl *DD = RD->getDestructor();
4573 PartialDiagnostic PD =
4574 PartialDiagnostic(PartialDiagnostic::NullDiagnostic());
4575 if (CheckDestructorAccess(ELoc, DD, PD) == AR_inaccessible ||
4577 Diag(ELoc, diag::err_omp_required_method)
4578 << getOpenMPClauseName(OMPC_lastprivate) << 4;
4579 bool IsDecl = VD->isThisDeclarationADefinition(Context) ==
4580 VarDecl::DeclarationOnly;
4581 Diag(VD->getLocation(),
4582 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
4584 Diag(RD->getLocation(), diag::note_previous_decl) << RD;
4587 MarkFunctionReferenced(ELoc, DD);
4588 DiagnoseUseOfDecl(DD, ELoc);
4592 if (DVar.CKind != OMPC_firstprivate)
4593 DSAStack->addDSA(VD, DE, OMPC_lastprivate);
4600 return OMPLastprivateClause::Create(Context, StartLoc, LParenLoc, EndLoc,
4604 OMPClause *Sema::ActOnOpenMPSharedClause(ArrayRef<Expr *> VarList,
4605 SourceLocation StartLoc,
4606 SourceLocation LParenLoc,
4607 SourceLocation EndLoc) {
4608 SmallVector<Expr *, 8> Vars;
4609 for (auto &RefExpr : VarList) {
4610 assert(RefExpr && "NULL expr in OpenMP shared clause.");
4611 if (isa<DependentScopeDeclRefExpr>(RefExpr)) {
4612 // It will be analyzed later.
4613 Vars.push_back(RefExpr);
4617 SourceLocation ELoc = RefExpr->getExprLoc();
4618 // OpenMP [2.1, C/C++]
4619 // A list item is a variable name.
4620 // OpenMP [2.14.3.2, Restrictions, p.1]
4621 // A variable that is part of another variable (as an array or structure
4622 // element) cannot appear in a shared unless it is a static data member
4624 DeclRefExpr *DE = dyn_cast<DeclRefExpr>(RefExpr);
4625 if (!DE || !isa<VarDecl>(DE->getDecl())) {
4626 Diag(ELoc, diag::err_omp_expected_var_name) << RefExpr->getSourceRange();
4629 Decl *D = DE->getDecl();
4630 VarDecl *VD = cast<VarDecl>(D);
4632 QualType Type = VD->getType();
4633 if (Type->isDependentType() || Type->isInstantiationDependentType()) {
4634 // It will be analyzed later.
4639 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
4641 // Variables with the predetermined data-sharing attributes may not be
4642 // listed in data-sharing attributes clauses, except for the cases
4643 // listed below. For these exceptions only, listing a predetermined
4644 // variable in a data-sharing attribute clause is allowed and overrides
4645 // the variable's predetermined data-sharing attributes.
4646 DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(VD, false);
4647 if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_shared &&
4649 Diag(ELoc, diag::err_omp_wrong_dsa) << getOpenMPClauseName(DVar.CKind)
4650 << getOpenMPClauseName(OMPC_shared);
4651 ReportOriginalDSA(*this, DSAStack, VD, DVar);
4655 DSAStack->addDSA(VD, DE, OMPC_shared);
4662 return OMPSharedClause::Create(Context, StartLoc, LParenLoc, EndLoc, Vars);
4666 class DSARefChecker : public StmtVisitor<DSARefChecker, bool> {
4670 bool VisitDeclRefExpr(DeclRefExpr *E) {
4671 if (VarDecl *VD = dyn_cast<VarDecl>(E->getDecl())) {
4672 DSAStackTy::DSAVarData DVar = Stack->getTopDSA(VD, false);
4673 if (DVar.CKind == OMPC_shared && !DVar.RefExpr)
4675 if (DVar.CKind != OMPC_unknown)
4677 DSAStackTy::DSAVarData DVarPrivate =
4678 Stack->hasDSA(VD, isOpenMPPrivate, MatchesAlways(), false);
4679 if (DVarPrivate.CKind != OMPC_unknown)
4685 bool VisitStmt(Stmt *S) {
4686 for (auto Child : S->children()) {
4687 if (Child && Visit(Child))
4692 explicit DSARefChecker(DSAStackTy *S) : Stack(S) {}
4696 OMPClause *Sema::ActOnOpenMPReductionClause(
4697 ArrayRef<Expr *> VarList, SourceLocation StartLoc, SourceLocation LParenLoc,
4698 SourceLocation ColonLoc, SourceLocation EndLoc,
4699 CXXScopeSpec &ReductionIdScopeSpec,
4700 const DeclarationNameInfo &ReductionId) {
4701 // TODO: Allow scope specification search when 'declare reduction' is
4703 assert(ReductionIdScopeSpec.isEmpty() &&
4704 "No support for scoped reduction identifiers yet.");
4706 auto DN = ReductionId.getName();
4707 auto OOK = DN.getCXXOverloadedOperator();
4708 BinaryOperatorKind BOK = BO_Comma;
4710 // OpenMP [2.14.3.6, reduction clause]
4712 // reduction-identifier is either an identifier or one of the following
4713 // operators: +, -, *, &, |, ^, && and ||
4715 // reduction-identifier is either an id-expression or one of the following
4716 // operators: +, -, *, &, |, ^, && and ||
4717 // FIXME: Only 'min' and 'max' identifiers are supported for now.
4742 if (auto II = DN.getAsIdentifierInfo()) {
4743 if (II->isStr("max"))
4745 else if (II->isStr("min"))
4750 SourceRange ReductionIdRange;
4751 if (ReductionIdScopeSpec.isValid()) {
4752 ReductionIdRange.setBegin(ReductionIdScopeSpec.getBeginLoc());
4754 ReductionIdRange.setEnd(ReductionId.getEndLoc());
4755 if (BOK == BO_Comma) {
4756 // Not allowed reduction identifier is found.
4757 Diag(ReductionId.getLocStart(), diag::err_omp_unknown_reduction_identifier)
4758 << ReductionIdRange;
4762 SmallVector<Expr *, 8> Vars;
4763 for (auto RefExpr : VarList) {
4764 assert(RefExpr && "nullptr expr in OpenMP reduction clause.");
4765 if (isa<DependentScopeDeclRefExpr>(RefExpr)) {
4766 // It will be analyzed later.
4767 Vars.push_back(RefExpr);
4771 if (RefExpr->isTypeDependent() || RefExpr->isValueDependent() ||
4772 RefExpr->isInstantiationDependent() ||
4773 RefExpr->containsUnexpandedParameterPack()) {
4774 // It will be analyzed later.
4775 Vars.push_back(RefExpr);
4779 auto ELoc = RefExpr->getExprLoc();
4780 auto ERange = RefExpr->getSourceRange();
4781 // OpenMP [2.1, C/C++]
4782 // A list item is a variable or array section, subject to the restrictions
4783 // specified in Section 2.4 on page 42 and in each of the sections
4784 // describing clauses and directives for which a list appears.
4785 // OpenMP [2.14.3.3, Restrictions, p.1]
4786 // A variable that is part of another variable (as an array or
4787 // structure element) cannot appear in a private clause.
4788 auto DE = dyn_cast<DeclRefExpr>(RefExpr);
4789 if (!DE || !isa<VarDecl>(DE->getDecl())) {
4790 Diag(ELoc, diag::err_omp_expected_var_name) << ERange;
4793 auto D = DE->getDecl();
4794 auto VD = cast<VarDecl>(D);
4795 auto Type = VD->getType();
4796 // OpenMP [2.9.3.3, Restrictions, C/C++, p.3]
4797 // A variable that appears in a private clause must not have an incomplete
4798 // type or a reference type.
4799 if (RequireCompleteType(ELoc, Type,
4800 diag::err_omp_reduction_incomplete_type))
4802 // OpenMP [2.14.3.6, reduction clause, Restrictions]
4803 // Arrays may not appear in a reduction clause.
4804 if (Type.getNonReferenceType()->isArrayType()) {
4805 Diag(ELoc, diag::err_omp_reduction_type_array) << Type << ERange;
4807 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
4808 Diag(VD->getLocation(),
4809 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
4813 // OpenMP [2.14.3.6, reduction clause, Restrictions]
4814 // A list item that appears in a reduction clause must not be
4816 if (Type.getNonReferenceType().isConstant(Context)) {
4817 Diag(ELoc, diag::err_omp_const_variable)
4818 << getOpenMPClauseName(OMPC_reduction) << Type << ERange;
4820 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
4821 Diag(VD->getLocation(),
4822 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
4826 // OpenMP [2.9.3.6, Restrictions, C/C++, p.4]
4827 // If a list-item is a reference type then it must bind to the same object
4828 // for all threads of the team.
4829 VarDecl *VDDef = VD->getDefinition();
4830 if (Type->isReferenceType() && VDDef) {
4831 DSARefChecker Check(DSAStack);
4832 if (Check.Visit(VDDef->getInit())) {
4833 Diag(ELoc, diag::err_omp_reduction_ref_type_arg) << ERange;
4834 Diag(VDDef->getLocation(), diag::note_defined_here) << VDDef;
4838 // OpenMP [2.14.3.6, reduction clause, Restrictions]
4839 // The type of a list item that appears in a reduction clause must be valid
4840 // for the reduction-identifier. For a max or min reduction in C, the type
4841 // of the list item must be an allowed arithmetic data type: char, int,
4842 // float, double, or _Bool, possibly modified with long, short, signed, or
4843 // unsigned. For a max or min reduction in C++, the type of the list item
4844 // must be an allowed arithmetic data type: char, wchar_t, int, float,
4845 // double, or bool, possibly modified with long, short, signed, or unsigned.
4846 if ((BOK == BO_GT || BOK == BO_LT) &&
4847 !(Type->isScalarType() ||
4848 (getLangOpts().CPlusPlus && Type->isArithmeticType()))) {
4849 Diag(ELoc, diag::err_omp_clause_not_arithmetic_type_arg)
4850 << getLangOpts().CPlusPlus;
4852 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
4853 Diag(VD->getLocation(),
4854 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
4858 if ((BOK == BO_OrAssign || BOK == BO_AndAssign || BOK == BO_XorAssign) &&
4859 !getLangOpts().CPlusPlus && Type->isFloatingType()) {
4860 Diag(ELoc, diag::err_omp_clause_floating_type_arg);
4862 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
4863 Diag(VD->getLocation(),
4864 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
4868 bool Suppress = getDiagnostics().getSuppressAllDiagnostics();
4869 getDiagnostics().setSuppressAllDiagnostics(true);
4870 ExprResult ReductionOp =
4871 BuildBinOp(DSAStack->getCurScope(), ReductionId.getLocStart(), BOK,
4873 getDiagnostics().setSuppressAllDiagnostics(Suppress);
4874 if (ReductionOp.isInvalid()) {
4875 Diag(ELoc, diag::err_omp_reduction_id_not_compatible) << Type
4876 << ReductionIdRange;
4878 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
4879 Diag(VD->getLocation(),
4880 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
4885 // OpenMP [2.14.1.1, Data-sharing Attribute Rules for Variables Referenced
4887 // Variables with the predetermined data-sharing attributes may not be
4888 // listed in data-sharing attributes clauses, except for the cases
4889 // listed below. For these exceptions only, listing a predetermined
4890 // variable in a data-sharing attribute clause is allowed and overrides
4891 // the variable's predetermined data-sharing attributes.
4892 // OpenMP [2.14.3.6, Restrictions, p.3]
4893 // Any number of reduction clauses can be specified on the directive,
4894 // but a list item can appear only once in the reduction clauses for that
4896 DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(VD, false);
4897 if (DVar.CKind == OMPC_reduction) {
4898 Diag(ELoc, diag::err_omp_once_referenced)
4899 << getOpenMPClauseName(OMPC_reduction);
4901 Diag(DVar.RefExpr->getExprLoc(), diag::note_omp_referenced);
4903 } else if (DVar.CKind != OMPC_unknown) {
4904 Diag(ELoc, diag::err_omp_wrong_dsa)
4905 << getOpenMPClauseName(DVar.CKind)
4906 << getOpenMPClauseName(OMPC_reduction);
4907 ReportOriginalDSA(*this, DSAStack, VD, DVar);
4911 // OpenMP [2.14.3.6, Restrictions, p.1]
4912 // A list item that appears in a reduction clause of a worksharing
4913 // construct must be shared in the parallel regions to which any of the
4914 // worksharing regions arising from the worksharing construct bind.
4915 OpenMPDirectiveKind CurrDir = DSAStack->getCurrentDirective();
4916 if (isOpenMPWorksharingDirective(CurrDir) &&
4917 !isOpenMPParallelDirective(CurrDir)) {
4918 DVar = DSAStack->getImplicitDSA(VD, true);
4919 if (DVar.CKind != OMPC_shared) {
4920 Diag(ELoc, diag::err_omp_required_access)
4921 << getOpenMPClauseName(OMPC_reduction)
4922 << getOpenMPClauseName(OMPC_shared);
4923 ReportOriginalDSA(*this, DSAStack, VD, DVar);
4928 CXXRecordDecl *RD = getLangOpts().CPlusPlus
4929 ? Type.getNonReferenceType()->getAsCXXRecordDecl()
4931 // FIXME This code must be replaced by actual constructing/destructing of
4932 // the reduction variable.
4934 CXXConstructorDecl *CD = LookupDefaultConstructor(RD);
4935 PartialDiagnostic PD =
4936 PartialDiagnostic(PartialDiagnostic::NullDiagnostic());
4938 CheckConstructorAccess(ELoc, CD,
4939 InitializedEntity::InitializeTemporary(Type),
4940 CD->getAccess(), PD) == AR_inaccessible ||
4942 Diag(ELoc, diag::err_omp_required_method)
4943 << getOpenMPClauseName(OMPC_reduction) << 0;
4944 bool IsDecl = VD->isThisDeclarationADefinition(Context) ==
4945 VarDecl::DeclarationOnly;
4946 Diag(VD->getLocation(),
4947 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
4949 Diag(RD->getLocation(), diag::note_previous_decl) << RD;
4952 MarkFunctionReferenced(ELoc, CD);
4953 DiagnoseUseOfDecl(CD, ELoc);
4955 CXXDestructorDecl *DD = RD->getDestructor();
4957 if (CheckDestructorAccess(ELoc, DD, PD) == AR_inaccessible ||
4959 Diag(ELoc, diag::err_omp_required_method)
4960 << getOpenMPClauseName(OMPC_reduction) << 4;
4961 bool IsDecl = VD->isThisDeclarationADefinition(Context) ==
4962 VarDecl::DeclarationOnly;
4963 Diag(VD->getLocation(),
4964 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
4966 Diag(RD->getLocation(), diag::note_previous_decl) << RD;
4969 MarkFunctionReferenced(ELoc, DD);
4970 DiagnoseUseOfDecl(DD, ELoc);
4974 DSAStack->addDSA(VD, DE, OMPC_reduction);
4981 return OMPReductionClause::Create(
4982 Context, StartLoc, LParenLoc, ColonLoc, EndLoc, Vars,
4983 ReductionIdScopeSpec.getWithLocInContext(Context), ReductionId);
4986 OMPClause *Sema::ActOnOpenMPLinearClause(ArrayRef<Expr *> VarList, Expr *Step,
4987 SourceLocation StartLoc,
4988 SourceLocation LParenLoc,
4989 SourceLocation ColonLoc,
4990 SourceLocation EndLoc) {
4991 SmallVector<Expr *, 8> Vars;
4992 for (auto &RefExpr : VarList) {
4993 assert(RefExpr && "NULL expr in OpenMP linear clause.");
4994 if (isa<DependentScopeDeclRefExpr>(RefExpr)) {
4995 // It will be analyzed later.
4996 Vars.push_back(RefExpr);
5000 // OpenMP [2.14.3.7, linear clause]
5001 // A list item that appears in a linear clause is subject to the private
5002 // clause semantics described in Section 2.14.3.3 on page 159 except as
5003 // noted. In addition, the value of the new list item on each iteration
5004 // of the associated loop(s) corresponds to the value of the original
5005 // list item before entering the construct plus the logical number of
5006 // the iteration times linear-step.
5008 SourceLocation ELoc = RefExpr->getExprLoc();
5009 // OpenMP [2.1, C/C++]
5010 // A list item is a variable name.
5011 // OpenMP [2.14.3.3, Restrictions, p.1]
5012 // A variable that is part of another variable (as an array or
5013 // structure element) cannot appear in a private clause.
5014 DeclRefExpr *DE = dyn_cast<DeclRefExpr>(RefExpr);
5015 if (!DE || !isa<VarDecl>(DE->getDecl())) {
5016 Diag(ELoc, diag::err_omp_expected_var_name) << RefExpr->getSourceRange();
5020 VarDecl *VD = cast<VarDecl>(DE->getDecl());
5022 // OpenMP [2.14.3.7, linear clause]
5023 // A list-item cannot appear in more than one linear clause.
5024 // A list-item that appears in a linear clause cannot appear in any
5025 // other data-sharing attribute clause.
5026 DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(VD, false);
5028 Diag(ELoc, diag::err_omp_wrong_dsa) << getOpenMPClauseName(DVar.CKind)
5029 << getOpenMPClauseName(OMPC_linear);
5030 ReportOriginalDSA(*this, DSAStack, VD, DVar);
5034 QualType QType = VD->getType();
5035 if (QType->isDependentType() || QType->isInstantiationDependentType()) {
5036 // It will be analyzed later.
5041 // A variable must not have an incomplete type or a reference type.
5042 if (RequireCompleteType(ELoc, QType,
5043 diag::err_omp_linear_incomplete_type)) {
5046 if (QType->isReferenceType()) {
5047 Diag(ELoc, diag::err_omp_clause_ref_type_arg)
5048 << getOpenMPClauseName(OMPC_linear) << QType;
5050 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
5051 Diag(VD->getLocation(),
5052 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
5057 // A list item must not be const-qualified.
5058 if (QType.isConstant(Context)) {
5059 Diag(ELoc, diag::err_omp_const_variable)
5060 << getOpenMPClauseName(OMPC_linear);
5062 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
5063 Diag(VD->getLocation(),
5064 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
5069 // A list item must be of integral or pointer type.
5070 QType = QType.getUnqualifiedType().getCanonicalType();
5071 const Type *Ty = QType.getTypePtrOrNull();
5072 if (!Ty || (!Ty->isDependentType() && !Ty->isIntegralType(Context) &&
5073 !Ty->isPointerType())) {
5074 Diag(ELoc, diag::err_omp_linear_expected_int_or_ptr) << QType;
5076 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
5077 Diag(VD->getLocation(),
5078 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
5083 DSAStack->addDSA(VD, DE, OMPC_linear);
5090 Expr *StepExpr = Step;
5091 if (Step && !Step->isValueDependent() && !Step->isTypeDependent() &&
5092 !Step->isInstantiationDependent() &&
5093 !Step->containsUnexpandedParameterPack()) {
5094 SourceLocation StepLoc = Step->getLocStart();
5095 ExprResult Val = PerformOpenMPImplicitIntegerConversion(StepLoc, Step);
5096 if (Val.isInvalid())
5098 StepExpr = Val.get();
5100 // Warn about zero linear step (it would be probably better specified as
5101 // making corresponding variables 'const').
5102 llvm::APSInt Result;
5103 if (StepExpr->isIntegerConstantExpr(Result, Context) &&
5104 !Result.isNegative() && !Result.isStrictlyPositive())
5105 Diag(StepLoc, diag::warn_omp_linear_step_zero) << Vars[0]
5106 << (Vars.size() > 1);
5109 return OMPLinearClause::Create(Context, StartLoc, LParenLoc, ColonLoc, EndLoc,
5113 OMPClause *Sema::ActOnOpenMPAlignedClause(
5114 ArrayRef<Expr *> VarList, Expr *Alignment, SourceLocation StartLoc,
5115 SourceLocation LParenLoc, SourceLocation ColonLoc, SourceLocation EndLoc) {
5117 SmallVector<Expr *, 8> Vars;
5118 for (auto &RefExpr : VarList) {
5119 assert(RefExpr && "NULL expr in OpenMP aligned clause.");
5120 if (isa<DependentScopeDeclRefExpr>(RefExpr)) {
5121 // It will be analyzed later.
5122 Vars.push_back(RefExpr);
5126 SourceLocation ELoc = RefExpr->getExprLoc();
5127 // OpenMP [2.1, C/C++]
5128 // A list item is a variable name.
5129 DeclRefExpr *DE = dyn_cast<DeclRefExpr>(RefExpr);
5130 if (!DE || !isa<VarDecl>(DE->getDecl())) {
5131 Diag(ELoc, diag::err_omp_expected_var_name) << RefExpr->getSourceRange();
5135 VarDecl *VD = cast<VarDecl>(DE->getDecl());
5137 // OpenMP [2.8.1, simd construct, Restrictions]
5138 // The type of list items appearing in the aligned clause must be
5139 // array, pointer, reference to array, or reference to pointer.
5140 QualType QType = DE->getType()
5141 .getNonReferenceType()
5142 .getUnqualifiedType()
5143 .getCanonicalType();
5144 const Type *Ty = QType.getTypePtrOrNull();
5145 if (!Ty || (!Ty->isDependentType() && !Ty->isArrayType() &&
5146 !Ty->isPointerType())) {
5147 Diag(ELoc, diag::err_omp_aligned_expected_array_or_ptr)
5148 << QType << getLangOpts().CPlusPlus << RefExpr->getSourceRange();
5150 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
5151 Diag(VD->getLocation(),
5152 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
5157 // OpenMP [2.8.1, simd construct, Restrictions]
5158 // A list-item cannot appear in more than one aligned clause.
5159 if (DeclRefExpr *PrevRef = DSAStack->addUniqueAligned(VD, DE)) {
5160 Diag(ELoc, diag::err_omp_aligned_twice) << RefExpr->getSourceRange();
5161 Diag(PrevRef->getExprLoc(), diag::note_omp_explicit_dsa)
5162 << getOpenMPClauseName(OMPC_aligned);
5169 // OpenMP [2.8.1, simd construct, Description]
5170 // The parameter of the aligned clause, alignment, must be a constant
5171 // positive integer expression.
5172 // If no optional parameter is specified, implementation-defined default
5173 // alignments for SIMD instructions on the target platforms are assumed.
5174 if (Alignment != nullptr) {
5175 ExprResult AlignResult =
5176 VerifyPositiveIntegerConstantInClause(Alignment, OMPC_aligned);
5177 if (AlignResult.isInvalid())
5179 Alignment = AlignResult.get();
5184 return OMPAlignedClause::Create(Context, StartLoc, LParenLoc, ColonLoc,
5185 EndLoc, Vars, Alignment);
5188 OMPClause *Sema::ActOnOpenMPCopyinClause(ArrayRef<Expr *> VarList,
5189 SourceLocation StartLoc,
5190 SourceLocation LParenLoc,
5191 SourceLocation EndLoc) {
5192 SmallVector<Expr *, 8> Vars;
5193 for (auto &RefExpr : VarList) {
5194 assert(RefExpr && "NULL expr in OpenMP copyin clause.");
5195 if (isa<DependentScopeDeclRefExpr>(RefExpr)) {
5196 // It will be analyzed later.
5197 Vars.push_back(RefExpr);
5201 SourceLocation ELoc = RefExpr->getExprLoc();
5202 // OpenMP [2.1, C/C++]
5203 // A list item is a variable name.
5204 // OpenMP [2.14.4.1, Restrictions, p.1]
5205 // A list item that appears in a copyin clause must be threadprivate.
5206 DeclRefExpr *DE = dyn_cast<DeclRefExpr>(RefExpr);
5207 if (!DE || !isa<VarDecl>(DE->getDecl())) {
5208 Diag(ELoc, diag::err_omp_expected_var_name) << RefExpr->getSourceRange();
5212 Decl *D = DE->getDecl();
5213 VarDecl *VD = cast<VarDecl>(D);
5215 QualType Type = VD->getType();
5216 if (Type->isDependentType() || Type->isInstantiationDependentType()) {
5217 // It will be analyzed later.
5222 // OpenMP [2.14.4.1, Restrictions, C/C++, p.1]
5223 // A list item that appears in a copyin clause must be threadprivate.
5224 if (!DSAStack->isThreadPrivate(VD)) {
5225 Diag(ELoc, diag::err_omp_required_access)
5226 << getOpenMPClauseName(OMPC_copyin)
5227 << getOpenMPDirectiveName(OMPD_threadprivate);
5231 // OpenMP [2.14.4.1, Restrictions, C/C++, p.2]
5232 // A variable of class type (or array thereof) that appears in a
5233 // copyin clause requires an accessible, unambiguous copy assignment
5234 // operator for the class type.
5235 Type = Context.getBaseElementType(Type);
5237 getLangOpts().CPlusPlus ? Type->getAsCXXRecordDecl() : nullptr;
5238 // FIXME This code must be replaced by actual assignment of the
5239 // threadprivate variable.
5241 CXXMethodDecl *MD = LookupCopyingAssignment(RD, 0, false, 0);
5242 DeclAccessPair FoundDecl = DeclAccessPair::make(MD, MD->getAccess());
5244 if (CheckMemberAccess(ELoc, RD, FoundDecl) == AR_inaccessible ||
5246 Diag(ELoc, diag::err_omp_required_method)
5247 << getOpenMPClauseName(OMPC_copyin) << 2;
5248 bool IsDecl = VD->isThisDeclarationADefinition(Context) ==
5249 VarDecl::DeclarationOnly;
5250 Diag(VD->getLocation(),
5251 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
5253 Diag(RD->getLocation(), diag::note_previous_decl) << RD;
5256 MarkFunctionReferenced(ELoc, MD);
5257 DiagnoseUseOfDecl(MD, ELoc);
5261 DSAStack->addDSA(VD, DE, OMPC_copyin);
5268 return OMPCopyinClause::Create(Context, StartLoc, LParenLoc, EndLoc, Vars);
5271 OMPClause *Sema::ActOnOpenMPCopyprivateClause(ArrayRef<Expr *> VarList,
5272 SourceLocation StartLoc,
5273 SourceLocation LParenLoc,
5274 SourceLocation EndLoc) {
5275 SmallVector<Expr *, 8> Vars;
5276 for (auto &RefExpr : VarList) {
5277 assert(RefExpr && "NULL expr in OpenMP copyprivate clause.");
5278 if (isa<DependentScopeDeclRefExpr>(RefExpr)) {
5279 // It will be analyzed later.
5280 Vars.push_back(RefExpr);
5284 SourceLocation ELoc = RefExpr->getExprLoc();
5285 // OpenMP [2.1, C/C++]
5286 // A list item is a variable name.
5287 // OpenMP [2.14.4.1, Restrictions, p.1]
5288 // A list item that appears in a copyin clause must be threadprivate.
5289 DeclRefExpr *DE = dyn_cast<DeclRefExpr>(RefExpr);
5290 if (!DE || !isa<VarDecl>(DE->getDecl())) {
5291 Diag(ELoc, diag::err_omp_expected_var_name) << RefExpr->getSourceRange();
5295 Decl *D = DE->getDecl();
5296 VarDecl *VD = cast<VarDecl>(D);
5298 QualType Type = VD->getType();
5299 if (Type->isDependentType() || Type->isInstantiationDependentType()) {
5300 // It will be analyzed later.
5305 // OpenMP [2.14.4.2, Restrictions, p.2]
5306 // A list item that appears in a copyprivate clause may not appear in a
5307 // private or firstprivate clause on the single construct.
5308 if (!DSAStack->isThreadPrivate(VD)) {
5309 auto DVar = DSAStack->getTopDSA(VD, false);
5310 if (DVar.CKind != OMPC_copyprivate && DVar.CKind != OMPC_unknown &&
5311 !(DVar.CKind == OMPC_private && !DVar.RefExpr)) {
5312 Diag(ELoc, diag::err_omp_wrong_dsa)
5313 << getOpenMPClauseName(DVar.CKind)
5314 << getOpenMPClauseName(OMPC_copyprivate);
5315 ReportOriginalDSA(*this, DSAStack, VD, DVar);
5319 // OpenMP [2.11.4.2, Restrictions, p.1]
5320 // All list items that appear in a copyprivate clause must be either
5321 // threadprivate or private in the enclosing context.
5322 if (DVar.CKind == OMPC_unknown) {
5323 DVar = DSAStack->getImplicitDSA(VD, false);
5324 if (DVar.CKind == OMPC_shared) {
5325 Diag(ELoc, diag::err_omp_required_access)
5326 << getOpenMPClauseName(OMPC_copyprivate)
5327 << "threadprivate or private in the enclosing context";
5328 ReportOriginalDSA(*this, DSAStack, VD, DVar);
5334 // OpenMP [2.14.4.1, Restrictions, C/C++, p.2]
5335 // A variable of class type (or array thereof) that appears in a
5336 // copyin clause requires an accessible, unambiguous copy assignment
5337 // operator for the class type.
5338 Type = Context.getBaseElementType(Type);
5340 getLangOpts().CPlusPlus ? Type->getAsCXXRecordDecl() : nullptr;
5341 // FIXME This code must be replaced by actual assignment of the
5342 // threadprivate variable.
5344 CXXMethodDecl *MD = LookupCopyingAssignment(RD, 0, false, 0);
5345 DeclAccessPair FoundDecl = DeclAccessPair::make(MD, MD->getAccess());
5347 if (CheckMemberAccess(ELoc, RD, FoundDecl) == AR_inaccessible ||
5349 Diag(ELoc, diag::err_omp_required_method)
5350 << getOpenMPClauseName(OMPC_copyprivate) << 2;
5351 bool IsDecl = VD->isThisDeclarationADefinition(Context) ==
5352 VarDecl::DeclarationOnly;
5353 Diag(VD->getLocation(),
5354 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
5356 Diag(RD->getLocation(), diag::note_previous_decl) << RD;
5359 MarkFunctionReferenced(ELoc, MD);
5360 DiagnoseUseOfDecl(MD, ELoc);
5364 // No need to mark vars as copyprivate, they are already threadprivate or
5365 // implicitly private.
5372 return OMPCopyprivateClause::Create(Context, StartLoc, LParenLoc, EndLoc, Vars);
5375 OMPClause *Sema::ActOnOpenMPFlushClause(ArrayRef<Expr *> VarList,
5376 SourceLocation StartLoc,
5377 SourceLocation LParenLoc,
5378 SourceLocation EndLoc) {
5379 if (VarList.empty())
5382 return OMPFlushClause::Create(Context, StartLoc, LParenLoc, EndLoc, VarList);