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;
85 typedef llvm::DenseSet<VarDecl *> LoopControlVariablesSetTy;
88 DeclSAMapTy SharingMap;
89 AlignedMapTy AlignedMap;
90 LoopControlVariablesSetTy LCVSet;
91 DefaultDataSharingAttributes DefaultAttr;
92 SourceLocation DefaultAttrLoc;
93 OpenMPDirectiveKind Directive;
94 DeclarationNameInfo DirectiveName;
96 SourceLocation ConstructLoc;
99 unsigned CollapseNumber;
100 SourceLocation InnerTeamsRegionLoc;
101 SharingMapTy(OpenMPDirectiveKind DKind, DeclarationNameInfo Name,
102 Scope *CurScope, SourceLocation Loc)
103 : SharingMap(), AlignedMap(), LCVSet(), DefaultAttr(DSA_unspecified),
104 Directive(DKind), DirectiveName(std::move(Name)), CurScope(CurScope),
105 ConstructLoc(Loc), OrderedRegion(false), NowaitRegion(false),
106 CollapseNumber(1), InnerTeamsRegionLoc() {}
108 : SharingMap(), AlignedMap(), LCVSet(), DefaultAttr(DSA_unspecified),
109 Directive(OMPD_unknown), DirectiveName(), CurScope(nullptr),
110 ConstructLoc(), OrderedRegion(false), NowaitRegion(false),
111 CollapseNumber(1), InnerTeamsRegionLoc() {}
114 typedef SmallVector<SharingMapTy, 64> StackTy;
116 /// \brief Stack of used declaration and their data-sharing attributes.
118 /// \brief true, if check for DSA must be from parent directive, false, if
119 /// from current directive.
120 OpenMPClauseKind ClauseKindMode;
123 typedef SmallVector<SharingMapTy, 8>::reverse_iterator reverse_iterator;
125 DSAVarData getDSA(StackTy::reverse_iterator Iter, VarDecl *D);
127 /// \brief Checks if the variable is a local for OpenMP region.
128 bool isOpenMPLocal(VarDecl *D, StackTy::reverse_iterator Iter);
131 explicit DSAStackTy(Sema &S)
132 : Stack(1), ClauseKindMode(OMPC_unknown), SemaRef(S) {}
134 bool isClauseParsingMode() const { return ClauseKindMode != OMPC_unknown; }
135 void setClauseParsingMode(OpenMPClauseKind K) { ClauseKindMode = K; }
137 void push(OpenMPDirectiveKind DKind, const DeclarationNameInfo &DirName,
138 Scope *CurScope, SourceLocation Loc) {
139 Stack.push_back(SharingMapTy(DKind, DirName, CurScope, Loc));
140 Stack.back().DefaultAttrLoc = Loc;
144 assert(Stack.size() > 1 && "Data-sharing attributes stack is empty!");
148 /// \brief If 'aligned' declaration for given variable \a D was not seen yet,
149 /// add it and return NULL; otherwise return previous occurrence's expression
151 DeclRefExpr *addUniqueAligned(VarDecl *D, DeclRefExpr *NewDE);
153 /// \brief Register specified variable as loop control variable.
154 void addLoopControlVariable(VarDecl *D);
155 /// \brief Check if the specified variable is a loop control variable for
157 bool isLoopControlVariable(VarDecl *D);
159 /// \brief Adds explicit data sharing attribute to the specified declaration.
160 void addDSA(VarDecl *D, DeclRefExpr *E, OpenMPClauseKind A);
162 /// \brief Returns data sharing attributes from top of the stack for the
163 /// specified declaration.
164 DSAVarData getTopDSA(VarDecl *D, bool FromParent);
165 /// \brief Returns data-sharing attributes for the specified declaration.
166 DSAVarData getImplicitDSA(VarDecl *D, bool FromParent);
167 /// \brief Checks if the specified variables has data-sharing attributes which
168 /// match specified \a CPred predicate in any directive which matches \a DPred
170 template <class ClausesPredicate, class DirectivesPredicate>
171 DSAVarData hasDSA(VarDecl *D, ClausesPredicate CPred,
172 DirectivesPredicate DPred, bool FromParent);
173 /// \brief Checks if the specified variables has data-sharing attributes which
174 /// match specified \a CPred predicate in any innermost directive which
175 /// matches \a DPred predicate.
176 template <class ClausesPredicate, class DirectivesPredicate>
177 DSAVarData hasInnermostDSA(VarDecl *D, ClausesPredicate CPred,
178 DirectivesPredicate DPred,
180 /// \brief Checks if the specified variables has explicit data-sharing
181 /// attributes which match specified \a CPred predicate at the specified
183 bool hasExplicitDSA(VarDecl *D,
184 const llvm::function_ref<bool(OpenMPClauseKind)> &CPred,
186 /// \brief Finds a directive which matches specified \a DPred predicate.
187 template <class NamedDirectivesPredicate>
188 bool hasDirective(NamedDirectivesPredicate DPred, bool FromParent);
190 /// \brief Returns currently analyzed directive.
191 OpenMPDirectiveKind getCurrentDirective() const {
192 return Stack.back().Directive;
194 /// \brief Returns parent directive.
195 OpenMPDirectiveKind getParentDirective() const {
196 if (Stack.size() > 2)
197 return Stack[Stack.size() - 2].Directive;
201 /// \brief Set default data sharing attribute to none.
202 void setDefaultDSANone(SourceLocation Loc) {
203 Stack.back().DefaultAttr = DSA_none;
204 Stack.back().DefaultAttrLoc = Loc;
206 /// \brief Set default data sharing attribute to shared.
207 void setDefaultDSAShared(SourceLocation Loc) {
208 Stack.back().DefaultAttr = DSA_shared;
209 Stack.back().DefaultAttrLoc = Loc;
212 DefaultDataSharingAttributes getDefaultDSA() const {
213 return Stack.back().DefaultAttr;
215 SourceLocation getDefaultDSALocation() const {
216 return Stack.back().DefaultAttrLoc;
219 /// \brief Checks if the specified variable is a threadprivate.
220 bool isThreadPrivate(VarDecl *D) {
221 DSAVarData DVar = getTopDSA(D, false);
222 return isOpenMPThreadPrivate(DVar.CKind);
225 /// \brief Marks current region as ordered (it has an 'ordered' clause).
226 void setOrderedRegion(bool IsOrdered = true) {
227 Stack.back().OrderedRegion = IsOrdered;
229 /// \brief Returns true, if parent region is ordered (has associated
230 /// 'ordered' clause), false - otherwise.
231 bool isParentOrderedRegion() const {
232 if (Stack.size() > 2)
233 return Stack[Stack.size() - 2].OrderedRegion;
236 /// \brief Marks current region as nowait (it has a 'nowait' clause).
237 void setNowaitRegion(bool IsNowait = true) {
238 Stack.back().NowaitRegion = IsNowait;
240 /// \brief Returns true, if parent region is nowait (has associated
241 /// 'nowait' clause), false - otherwise.
242 bool isParentNowaitRegion() const {
243 if (Stack.size() > 2)
244 return Stack[Stack.size() - 2].NowaitRegion;
248 /// \brief Set collapse value for the region.
249 void setCollapseNumber(unsigned Val) { Stack.back().CollapseNumber = Val; }
250 /// \brief Return collapse value for region.
251 unsigned getCollapseNumber() const {
252 return Stack.back().CollapseNumber;
255 /// \brief Marks current target region as one with closely nested teams
257 void setParentTeamsRegionLoc(SourceLocation TeamsRegionLoc) {
258 if (Stack.size() > 2)
259 Stack[Stack.size() - 2].InnerTeamsRegionLoc = TeamsRegionLoc;
261 /// \brief Returns true, if current region has closely nested teams region.
262 bool hasInnerTeamsRegion() const {
263 return getInnerTeamsRegionLoc().isValid();
265 /// \brief Returns location of the nested teams region (if any).
266 SourceLocation getInnerTeamsRegionLoc() const {
267 if (Stack.size() > 1)
268 return Stack.back().InnerTeamsRegionLoc;
269 return SourceLocation();
272 Scope *getCurScope() const { return Stack.back().CurScope; }
273 Scope *getCurScope() { return Stack.back().CurScope; }
274 SourceLocation getConstructLoc() { return Stack.back().ConstructLoc; }
276 bool isParallelOrTaskRegion(OpenMPDirectiveKind DKind) {
277 return isOpenMPParallelDirective(DKind) || DKind == OMPD_task ||
278 isOpenMPTeamsDirective(DKind) || DKind == OMPD_unknown;
282 DSAStackTy::DSAVarData DSAStackTy::getDSA(StackTy::reverse_iterator Iter,
284 D = D->getCanonicalDecl();
286 if (Iter == std::prev(Stack.rend())) {
287 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
288 // in a region but not in construct]
289 // File-scope or namespace-scope variables referenced in called routines
290 // in the region are shared unless they appear in a threadprivate
292 if (!D->isFunctionOrMethodVarDecl() && !isa<ParmVarDecl>(D))
293 DVar.CKind = OMPC_shared;
295 // OpenMP [2.9.1.2, Data-sharing Attribute Rules for Variables Referenced
296 // in a region but not in construct]
297 // Variables with static storage duration that are declared in called
298 // routines in the region are shared.
299 if (D->hasGlobalStorage())
300 DVar.CKind = OMPC_shared;
305 DVar.DKind = Iter->Directive;
306 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
307 // in a Construct, C/C++, predetermined, p.1]
308 // Variables with automatic storage duration that are declared in a scope
309 // inside the construct are private.
310 if (isOpenMPLocal(D, Iter) && D->isLocalVarDecl() &&
311 (D->getStorageClass() == SC_Auto || D->getStorageClass() == SC_None)) {
312 DVar.CKind = OMPC_private;
316 // Explicitly specified attributes and local variables with predetermined
318 if (Iter->SharingMap.count(D)) {
319 DVar.RefExpr = Iter->SharingMap[D].RefExpr;
320 DVar.CKind = Iter->SharingMap[D].Attributes;
321 DVar.ImplicitDSALoc = Iter->DefaultAttrLoc;
325 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
326 // in a Construct, C/C++, implicitly determined, p.1]
327 // In a parallel or task construct, the data-sharing attributes of these
328 // variables are determined by the default clause, if present.
329 switch (Iter->DefaultAttr) {
331 DVar.CKind = OMPC_shared;
332 DVar.ImplicitDSALoc = Iter->DefaultAttrLoc;
336 case DSA_unspecified:
337 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
338 // in a Construct, implicitly determined, p.2]
339 // In a parallel construct, if no default clause is present, these
340 // variables are shared.
341 DVar.ImplicitDSALoc = Iter->DefaultAttrLoc;
342 if (isOpenMPParallelDirective(DVar.DKind) ||
343 isOpenMPTeamsDirective(DVar.DKind)) {
344 DVar.CKind = OMPC_shared;
348 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
349 // in a Construct, implicitly determined, p.4]
350 // In a task construct, if no default clause is present, a variable that in
351 // the enclosing context is determined to be shared by all implicit tasks
352 // bound to the current team is shared.
353 if (DVar.DKind == OMPD_task) {
355 for (StackTy::reverse_iterator I = std::next(Iter), EE = Stack.rend();
357 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables
359 // in a Construct, implicitly determined, p.6]
360 // In a task construct, if no default clause is present, a variable
361 // whose data-sharing attribute is not determined by the rules above is
363 DVarTemp = getDSA(I, D);
364 if (DVarTemp.CKind != OMPC_shared) {
365 DVar.RefExpr = nullptr;
366 DVar.DKind = OMPD_task;
367 DVar.CKind = OMPC_firstprivate;
370 if (isParallelOrTaskRegion(I->Directive))
373 DVar.DKind = OMPD_task;
375 (DVarTemp.CKind == OMPC_unknown) ? OMPC_firstprivate : OMPC_shared;
379 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
380 // in a Construct, implicitly determined, p.3]
381 // For constructs other than task, if no default clause is present, these
382 // variables inherit their data-sharing attributes from the enclosing
384 return getDSA(std::next(Iter), D);
387 DeclRefExpr *DSAStackTy::addUniqueAligned(VarDecl *D, DeclRefExpr *NewDE) {
388 assert(Stack.size() > 1 && "Data sharing attributes stack is empty");
389 D = D->getCanonicalDecl();
390 auto It = Stack.back().AlignedMap.find(D);
391 if (It == Stack.back().AlignedMap.end()) {
392 assert(NewDE && "Unexpected nullptr expr to be added into aligned map");
393 Stack.back().AlignedMap[D] = NewDE;
396 assert(It->second && "Unexpected nullptr expr in the aligned map");
402 void DSAStackTy::addLoopControlVariable(VarDecl *D) {
403 assert(Stack.size() > 1 && "Data-sharing attributes stack is empty");
404 D = D->getCanonicalDecl();
405 Stack.back().LCVSet.insert(D);
408 bool DSAStackTy::isLoopControlVariable(VarDecl *D) {
409 assert(Stack.size() > 1 && "Data-sharing attributes stack is empty");
410 D = D->getCanonicalDecl();
411 return Stack.back().LCVSet.count(D) > 0;
414 void DSAStackTy::addDSA(VarDecl *D, DeclRefExpr *E, OpenMPClauseKind A) {
415 D = D->getCanonicalDecl();
416 if (A == OMPC_threadprivate) {
417 Stack[0].SharingMap[D].Attributes = A;
418 Stack[0].SharingMap[D].RefExpr = E;
420 assert(Stack.size() > 1 && "Data-sharing attributes stack is empty");
421 Stack.back().SharingMap[D].Attributes = A;
422 Stack.back().SharingMap[D].RefExpr = E;
426 bool DSAStackTy::isOpenMPLocal(VarDecl *D, StackTy::reverse_iterator Iter) {
427 D = D->getCanonicalDecl();
428 if (Stack.size() > 2) {
429 reverse_iterator I = Iter, E = std::prev(Stack.rend());
430 Scope *TopScope = nullptr;
431 while (I != E && !isParallelOrTaskRegion(I->Directive)) {
436 TopScope = I->CurScope ? I->CurScope->getParent() : nullptr;
437 Scope *CurScope = getCurScope();
438 while (CurScope != TopScope && !CurScope->isDeclScope(D)) {
439 CurScope = CurScope->getParent();
441 return CurScope != TopScope;
446 /// \brief Build a variable declaration for OpenMP loop iteration variable.
447 static VarDecl *buildVarDecl(Sema &SemaRef, SourceLocation Loc, QualType Type,
449 DeclContext *DC = SemaRef.CurContext;
450 IdentifierInfo *II = &SemaRef.PP.getIdentifierTable().get(Name);
451 TypeSourceInfo *TInfo = SemaRef.Context.getTrivialTypeSourceInfo(Type, Loc);
453 VarDecl::Create(SemaRef.Context, DC, Loc, Loc, II, Type, TInfo, SC_None);
458 static DeclRefExpr *buildDeclRefExpr(Sema &S, VarDecl *D, QualType Ty,
460 bool RefersToCapture = false) {
462 D->markUsed(S.Context);
463 return DeclRefExpr::Create(S.getASTContext(), NestedNameSpecifierLoc(),
464 SourceLocation(), D, RefersToCapture, Loc, Ty,
468 DSAStackTy::DSAVarData DSAStackTy::getTopDSA(VarDecl *D, bool FromParent) {
469 D = D->getCanonicalDecl();
472 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
473 // in a Construct, C/C++, predetermined, p.1]
474 // Variables appearing in threadprivate directives are threadprivate.
475 if (D->getTLSKind() != VarDecl::TLS_None ||
476 (D->getStorageClass() == SC_Register && D->hasAttr<AsmLabelAttr>() &&
477 !D->isLocalVarDecl())) {
478 addDSA(D, buildDeclRefExpr(SemaRef, D, D->getType().getNonReferenceType(),
482 if (Stack[0].SharingMap.count(D)) {
483 DVar.RefExpr = Stack[0].SharingMap[D].RefExpr;
484 DVar.CKind = OMPC_threadprivate;
488 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
489 // in a Construct, C/C++, predetermined, p.1]
490 // Variables with automatic storage duration that are declared in a scope
491 // inside the construct are private.
492 OpenMPDirectiveKind Kind =
493 FromParent ? getParentDirective() : getCurrentDirective();
494 auto StartI = std::next(Stack.rbegin());
495 auto EndI = std::prev(Stack.rend());
496 if (FromParent && StartI != EndI) {
497 StartI = std::next(StartI);
499 if (!isParallelOrTaskRegion(Kind)) {
500 if (isOpenMPLocal(D, StartI) &&
501 ((D->isLocalVarDecl() && (D->getStorageClass() == SC_Auto ||
502 D->getStorageClass() == SC_None)) ||
503 isa<ParmVarDecl>(D))) {
504 DVar.CKind = OMPC_private;
508 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
509 // in a Construct, C/C++, predetermined, p.4]
510 // Static data members are shared.
511 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
512 // in a Construct, C/C++, predetermined, p.7]
513 // Variables with static storage duration that are declared in a scope
514 // inside the construct are shared.
515 if (D->isStaticDataMember() || D->isStaticLocal()) {
516 DSAVarData DVarTemp =
517 hasDSA(D, isOpenMPPrivate, MatchesAlways(), FromParent);
518 if (DVarTemp.CKind != OMPC_unknown && DVarTemp.RefExpr)
521 DVar.CKind = OMPC_shared;
526 QualType Type = D->getType().getNonReferenceType().getCanonicalType();
527 bool IsConstant = Type.isConstant(SemaRef.getASTContext());
528 Type = SemaRef.getASTContext().getBaseElementType(Type);
529 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
530 // in a Construct, C/C++, predetermined, p.6]
531 // Variables with const qualified type having no mutable member are
534 SemaRef.getLangOpts().CPlusPlus ? Type->getAsCXXRecordDecl() : nullptr;
536 !(SemaRef.getLangOpts().CPlusPlus && RD && RD->hasMutableFields())) {
537 // Variables with const-qualified type having no mutable member may be
538 // listed in a firstprivate clause, even if they are static data members.
539 DSAVarData DVarTemp = hasDSA(D, MatchesAnyClause(OMPC_firstprivate),
540 MatchesAlways(), FromParent);
541 if (DVarTemp.CKind == OMPC_firstprivate && DVarTemp.RefExpr)
544 DVar.CKind = OMPC_shared;
548 // Explicitly specified attributes and local variables with predetermined
550 auto I = std::prev(StartI);
551 if (I->SharingMap.count(D)) {
552 DVar.RefExpr = I->SharingMap[D].RefExpr;
553 DVar.CKind = I->SharingMap[D].Attributes;
554 DVar.ImplicitDSALoc = I->DefaultAttrLoc;
560 DSAStackTy::DSAVarData DSAStackTy::getImplicitDSA(VarDecl *D, bool FromParent) {
561 D = D->getCanonicalDecl();
562 auto StartI = Stack.rbegin();
563 auto EndI = std::prev(Stack.rend());
564 if (FromParent && StartI != EndI) {
565 StartI = std::next(StartI);
567 return getDSA(StartI, D);
570 template <class ClausesPredicate, class DirectivesPredicate>
571 DSAStackTy::DSAVarData DSAStackTy::hasDSA(VarDecl *D, ClausesPredicate CPred,
572 DirectivesPredicate DPred,
574 D = D->getCanonicalDecl();
575 auto StartI = std::next(Stack.rbegin());
576 auto EndI = std::prev(Stack.rend());
577 if (FromParent && StartI != EndI) {
578 StartI = std::next(StartI);
580 for (auto I = StartI, EE = EndI; I != EE; ++I) {
581 if (!DPred(I->Directive) && !isParallelOrTaskRegion(I->Directive))
583 DSAVarData DVar = getDSA(I, D);
584 if (CPred(DVar.CKind))
590 template <class ClausesPredicate, class DirectivesPredicate>
591 DSAStackTy::DSAVarData
592 DSAStackTy::hasInnermostDSA(VarDecl *D, ClausesPredicate CPred,
593 DirectivesPredicate DPred, bool FromParent) {
594 D = D->getCanonicalDecl();
595 auto StartI = std::next(Stack.rbegin());
596 auto EndI = std::prev(Stack.rend());
597 if (FromParent && StartI != EndI) {
598 StartI = std::next(StartI);
600 for (auto I = StartI, EE = EndI; I != EE; ++I) {
601 if (!DPred(I->Directive))
603 DSAVarData DVar = getDSA(I, D);
604 if (CPred(DVar.CKind))
611 bool DSAStackTy::hasExplicitDSA(
612 VarDecl *D, const llvm::function_ref<bool(OpenMPClauseKind)> &CPred,
614 if (CPred(ClauseKindMode))
616 if (isClauseParsingMode())
618 D = D->getCanonicalDecl();
619 auto StartI = Stack.rbegin();
620 auto EndI = std::prev(Stack.rend());
621 if (std::distance(StartI, EndI) <= (int)Level)
623 std::advance(StartI, Level);
624 return (StartI->SharingMap.count(D) > 0) && StartI->SharingMap[D].RefExpr &&
625 CPred(StartI->SharingMap[D].Attributes);
628 template <class NamedDirectivesPredicate>
629 bool DSAStackTy::hasDirective(NamedDirectivesPredicate DPred, bool FromParent) {
630 auto StartI = std::next(Stack.rbegin());
631 auto EndI = std::prev(Stack.rend());
632 if (FromParent && StartI != EndI) {
633 StartI = std::next(StartI);
635 for (auto I = StartI, EE = EndI; I != EE; ++I) {
636 if (DPred(I->Directive, I->DirectiveName, I->ConstructLoc))
642 void Sema::InitDataSharingAttributesStack() {
643 VarDataSharingAttributesStack = new DSAStackTy(*this);
646 #define DSAStack static_cast<DSAStackTy *>(VarDataSharingAttributesStack)
648 bool Sema::IsOpenMPCapturedVar(VarDecl *VD) {
649 assert(LangOpts.OpenMP && "OpenMP is not allowed");
650 VD = VD->getCanonicalDecl();
651 if (DSAStack->getCurrentDirective() != OMPD_unknown) {
652 if (DSAStack->isLoopControlVariable(VD) ||
653 (VD->hasLocalStorage() &&
654 isParallelOrTaskRegion(DSAStack->getCurrentDirective())))
656 auto DVarPrivate = DSAStack->getTopDSA(VD, DSAStack->isClauseParsingMode());
657 if (DVarPrivate.CKind != OMPC_unknown && isOpenMPPrivate(DVarPrivate.CKind))
659 DVarPrivate = DSAStack->hasDSA(VD, isOpenMPPrivate, MatchesAlways(),
660 DSAStack->isClauseParsingMode());
661 return DVarPrivate.CKind != OMPC_unknown;
666 bool Sema::isOpenMPPrivateVar(VarDecl *VD, unsigned Level) {
667 assert(LangOpts.OpenMP && "OpenMP is not allowed");
668 return DSAStack->hasExplicitDSA(
669 VD, [](OpenMPClauseKind K) -> bool { return K == OMPC_private; }, Level);
672 void Sema::DestroyDataSharingAttributesStack() { delete DSAStack; }
674 void Sema::StartOpenMPDSABlock(OpenMPDirectiveKind DKind,
675 const DeclarationNameInfo &DirName,
676 Scope *CurScope, SourceLocation Loc) {
677 DSAStack->push(DKind, DirName, CurScope, Loc);
678 PushExpressionEvaluationContext(PotentiallyEvaluated);
681 void Sema::StartOpenMPClause(OpenMPClauseKind K) {
682 DSAStack->setClauseParsingMode(K);
685 void Sema::EndOpenMPClause() {
686 DSAStack->setClauseParsingMode(/*K=*/OMPC_unknown);
689 void Sema::EndOpenMPDSABlock(Stmt *CurDirective) {
690 // OpenMP [2.14.3.5, Restrictions, C/C++, p.1]
691 // A variable of class type (or array thereof) that appears in a lastprivate
692 // clause requires an accessible, unambiguous default constructor for the
693 // class type, unless the list item is also specified in a firstprivate
695 if (auto D = dyn_cast_or_null<OMPExecutableDirective>(CurDirective)) {
696 for (auto *C : D->clauses()) {
697 if (auto *Clause = dyn_cast<OMPLastprivateClause>(C)) {
698 SmallVector<Expr *, 8> PrivateCopies;
699 for (auto *DE : Clause->varlists()) {
700 if (DE->isValueDependent() || DE->isTypeDependent()) {
701 PrivateCopies.push_back(nullptr);
704 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(DE)->getDecl());
705 QualType Type = VD->getType();
706 auto DVar = DSAStack->getTopDSA(VD, false);
707 if (DVar.CKind == OMPC_lastprivate) {
708 // Generate helper private variable and initialize it with the
709 // default value. The address of the original variable is replaced
710 // by the address of the new private variable in CodeGen. This new
711 // variable is not added to IdResolver, so the code in the OpenMP
712 // region uses original variable for proper diagnostics.
714 buildVarDecl(*this, DE->getExprLoc(), Type.getUnqualifiedType(),
716 ActOnUninitializedDecl(VDPrivate, /*TypeMayContainAuto=*/false);
717 if (VDPrivate->isInvalidDecl())
719 PrivateCopies.push_back(buildDeclRefExpr(
720 *this, VDPrivate, DE->getType(), DE->getExprLoc()));
722 // The variable is also a firstprivate, so initialization sequence
723 // for private copy is generated already.
724 PrivateCopies.push_back(nullptr);
727 // Set initializers to private copies if no errors were found.
728 if (PrivateCopies.size() == Clause->varlist_size()) {
729 Clause->setPrivateCopies(PrivateCopies);
736 DiscardCleanupsInEvaluationContext();
737 PopExpressionEvaluationContext();
740 static bool FinishOpenMPLinearClause(OMPLinearClause &Clause, DeclRefExpr *IV,
741 Expr *NumIterations, Sema &SemaRef,
746 class VarDeclFilterCCC : public CorrectionCandidateCallback {
751 explicit VarDeclFilterCCC(Sema &S) : SemaRef(S) {}
752 bool ValidateCandidate(const TypoCorrection &Candidate) override {
753 NamedDecl *ND = Candidate.getCorrectionDecl();
754 if (VarDecl *VD = dyn_cast_or_null<VarDecl>(ND)) {
755 return VD->hasGlobalStorage() &&
756 SemaRef.isDeclInScope(ND, SemaRef.getCurLexicalContext(),
757 SemaRef.getCurScope());
764 ExprResult Sema::ActOnOpenMPIdExpression(Scope *CurScope,
765 CXXScopeSpec &ScopeSpec,
766 const DeclarationNameInfo &Id) {
767 LookupResult Lookup(*this, Id, LookupOrdinaryName);
768 LookupParsedName(Lookup, CurScope, &ScopeSpec, true);
770 if (Lookup.isAmbiguous())
774 if (!Lookup.isSingleResult()) {
775 if (TypoCorrection Corrected = CorrectTypo(
776 Id, LookupOrdinaryName, CurScope, nullptr,
777 llvm::make_unique<VarDeclFilterCCC>(*this), CTK_ErrorRecovery)) {
778 diagnoseTypo(Corrected,
780 ? diag::err_undeclared_var_use_suggest
781 : diag::err_omp_expected_var_arg_suggest)
783 VD = Corrected.getCorrectionDeclAs<VarDecl>();
785 Diag(Id.getLoc(), Lookup.empty() ? diag::err_undeclared_var_use
786 : diag::err_omp_expected_var_arg)
791 if (!(VD = Lookup.getAsSingle<VarDecl>())) {
792 Diag(Id.getLoc(), diag::err_omp_expected_var_arg) << Id.getName();
793 Diag(Lookup.getFoundDecl()->getLocation(), diag::note_declared_at);
797 Lookup.suppressDiagnostics();
799 // OpenMP [2.9.2, Syntax, C/C++]
800 // Variables must be file-scope, namespace-scope, or static block-scope.
801 if (!VD->hasGlobalStorage()) {
802 Diag(Id.getLoc(), diag::err_omp_global_var_arg)
803 << getOpenMPDirectiveName(OMPD_threadprivate) << !VD->isStaticLocal();
805 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
806 Diag(VD->getLocation(),
807 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
812 VarDecl *CanonicalVD = VD->getCanonicalDecl();
813 NamedDecl *ND = cast<NamedDecl>(CanonicalVD);
814 // OpenMP [2.9.2, Restrictions, C/C++, p.2]
815 // A threadprivate directive for file-scope variables must appear outside
816 // any definition or declaration.
817 if (CanonicalVD->getDeclContext()->isTranslationUnit() &&
818 !getCurLexicalContext()->isTranslationUnit()) {
819 Diag(Id.getLoc(), diag::err_omp_var_scope)
820 << getOpenMPDirectiveName(OMPD_threadprivate) << VD;
822 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
823 Diag(VD->getLocation(),
824 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
828 // OpenMP [2.9.2, Restrictions, C/C++, p.3]
829 // A threadprivate directive for static class member variables must appear
830 // in the class definition, in the same scope in which the member
831 // variables are declared.
832 if (CanonicalVD->isStaticDataMember() &&
833 !CanonicalVD->getDeclContext()->Equals(getCurLexicalContext())) {
834 Diag(Id.getLoc(), diag::err_omp_var_scope)
835 << getOpenMPDirectiveName(OMPD_threadprivate) << VD;
837 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
838 Diag(VD->getLocation(),
839 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
843 // OpenMP [2.9.2, Restrictions, C/C++, p.4]
844 // A threadprivate directive for namespace-scope variables must appear
845 // outside any definition or declaration other than the namespace
846 // definition itself.
847 if (CanonicalVD->getDeclContext()->isNamespace() &&
848 (!getCurLexicalContext()->isFileContext() ||
849 !getCurLexicalContext()->Encloses(CanonicalVD->getDeclContext()))) {
850 Diag(Id.getLoc(), diag::err_omp_var_scope)
851 << getOpenMPDirectiveName(OMPD_threadprivate) << VD;
853 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
854 Diag(VD->getLocation(),
855 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
859 // OpenMP [2.9.2, Restrictions, C/C++, p.6]
860 // A threadprivate directive for static block-scope variables must appear
861 // in the scope of the variable and not in a nested scope.
862 if (CanonicalVD->isStaticLocal() && CurScope &&
863 !isDeclInScope(ND, getCurLexicalContext(), CurScope)) {
864 Diag(Id.getLoc(), diag::err_omp_var_scope)
865 << getOpenMPDirectiveName(OMPD_threadprivate) << VD;
867 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
868 Diag(VD->getLocation(),
869 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
874 // OpenMP [2.9.2, Restrictions, C/C++, p.2-6]
875 // A threadprivate directive must lexically precede all references to any
876 // of the variables in its list.
877 if (VD->isUsed() && !DSAStack->isThreadPrivate(VD)) {
878 Diag(Id.getLoc(), diag::err_omp_var_used)
879 << getOpenMPDirectiveName(OMPD_threadprivate) << VD;
883 QualType ExprType = VD->getType().getNonReferenceType();
884 ExprResult DE = buildDeclRefExpr(*this, VD, ExprType, Id.getLoc());
889 Sema::ActOnOpenMPThreadprivateDirective(SourceLocation Loc,
890 ArrayRef<Expr *> VarList) {
891 if (OMPThreadPrivateDecl *D = CheckOMPThreadPrivateDecl(Loc, VarList)) {
892 CurContext->addDecl(D);
893 return DeclGroupPtrTy::make(DeclGroupRef(D));
895 return DeclGroupPtrTy();
899 class LocalVarRefChecker : public ConstStmtVisitor<LocalVarRefChecker, bool> {
903 bool VisitDeclRefExpr(const DeclRefExpr *E) {
904 if (auto VD = dyn_cast<VarDecl>(E->getDecl())) {
905 if (VD->hasLocalStorage()) {
906 SemaRef.Diag(E->getLocStart(),
907 diag::err_omp_local_var_in_threadprivate_init)
908 << E->getSourceRange();
909 SemaRef.Diag(VD->getLocation(), diag::note_defined_here)
910 << VD << VD->getSourceRange();
916 bool VisitStmt(const Stmt *S) {
917 for (auto Child : S->children()) {
918 if (Child && Visit(Child))
923 explicit LocalVarRefChecker(Sema &SemaRef) : SemaRef(SemaRef) {}
927 OMPThreadPrivateDecl *
928 Sema::CheckOMPThreadPrivateDecl(SourceLocation Loc, ArrayRef<Expr *> VarList) {
929 SmallVector<Expr *, 8> Vars;
930 for (auto &RefExpr : VarList) {
931 DeclRefExpr *DE = cast<DeclRefExpr>(RefExpr);
932 VarDecl *VD = cast<VarDecl>(DE->getDecl());
933 SourceLocation ILoc = DE->getExprLoc();
935 QualType QType = VD->getType();
936 if (QType->isDependentType() || QType->isInstantiationDependentType()) {
937 // It will be analyzed later.
942 // OpenMP [2.9.2, Restrictions, C/C++, p.10]
943 // A threadprivate variable must not have an incomplete type.
944 if (RequireCompleteType(ILoc, VD->getType(),
945 diag::err_omp_threadprivate_incomplete_type)) {
949 // OpenMP [2.9.2, Restrictions, C/C++, p.10]
950 // A threadprivate variable must not have a reference type.
951 if (VD->getType()->isReferenceType()) {
952 Diag(ILoc, diag::err_omp_ref_type_arg)
953 << getOpenMPDirectiveName(OMPD_threadprivate) << VD->getType();
955 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
956 Diag(VD->getLocation(),
957 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
962 // Check if this is a TLS variable.
963 if (VD->getTLSKind() != VarDecl::TLS_None ||
964 (VD->getStorageClass() == SC_Register && VD->hasAttr<AsmLabelAttr>() &&
965 !VD->isLocalVarDecl())) {
966 Diag(ILoc, diag::err_omp_var_thread_local)
967 << VD << ((VD->getTLSKind() != VarDecl::TLS_None) ? 0 : 1);
969 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
970 Diag(VD->getLocation(),
971 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
976 // Check if initial value of threadprivate variable reference variable with
977 // local storage (it is not supported by runtime).
978 if (auto Init = VD->getAnyInitializer()) {
979 LocalVarRefChecker Checker(*this);
980 if (Checker.Visit(Init))
984 Vars.push_back(RefExpr);
985 DSAStack->addDSA(VD, DE, OMPC_threadprivate);
986 VD->addAttr(OMPThreadPrivateDeclAttr::CreateImplicit(
987 Context, SourceRange(Loc, Loc)));
988 if (auto *ML = Context.getASTMutationListener())
989 ML->DeclarationMarkedOpenMPThreadPrivate(VD);
991 OMPThreadPrivateDecl *D = nullptr;
993 D = OMPThreadPrivateDecl::Create(Context, getCurLexicalContext(), Loc,
995 D->setAccess(AS_public);
1000 static void ReportOriginalDSA(Sema &SemaRef, DSAStackTy *Stack,
1001 const VarDecl *VD, DSAStackTy::DSAVarData DVar,
1002 bool IsLoopIterVar = false) {
1004 SemaRef.Diag(DVar.RefExpr->getExprLoc(), diag::note_omp_explicit_dsa)
1005 << getOpenMPClauseName(DVar.CKind);
1009 PDSA_StaticMemberShared,
1010 PDSA_StaticLocalVarShared,
1011 PDSA_LoopIterVarPrivate,
1012 PDSA_LoopIterVarLinear,
1013 PDSA_LoopIterVarLastprivate,
1014 PDSA_ConstVarShared,
1015 PDSA_GlobalVarShared,
1016 PDSA_TaskVarFirstprivate,
1017 PDSA_LocalVarPrivate,
1019 } Reason = PDSA_Implicit;
1020 bool ReportHint = false;
1021 auto ReportLoc = VD->getLocation();
1022 if (IsLoopIterVar) {
1023 if (DVar.CKind == OMPC_private)
1024 Reason = PDSA_LoopIterVarPrivate;
1025 else if (DVar.CKind == OMPC_lastprivate)
1026 Reason = PDSA_LoopIterVarLastprivate;
1028 Reason = PDSA_LoopIterVarLinear;
1029 } else if (DVar.DKind == OMPD_task && DVar.CKind == OMPC_firstprivate) {
1030 Reason = PDSA_TaskVarFirstprivate;
1031 ReportLoc = DVar.ImplicitDSALoc;
1032 } else if (VD->isStaticLocal())
1033 Reason = PDSA_StaticLocalVarShared;
1034 else if (VD->isStaticDataMember())
1035 Reason = PDSA_StaticMemberShared;
1036 else if (VD->isFileVarDecl())
1037 Reason = PDSA_GlobalVarShared;
1038 else if (VD->getType().isConstant(SemaRef.getASTContext()))
1039 Reason = PDSA_ConstVarShared;
1040 else if (VD->isLocalVarDecl() && DVar.CKind == OMPC_private) {
1042 Reason = PDSA_LocalVarPrivate;
1044 if (Reason != PDSA_Implicit) {
1045 SemaRef.Diag(ReportLoc, diag::note_omp_predetermined_dsa)
1046 << Reason << ReportHint
1047 << getOpenMPDirectiveName(Stack->getCurrentDirective());
1048 } else if (DVar.ImplicitDSALoc.isValid()) {
1049 SemaRef.Diag(DVar.ImplicitDSALoc, diag::note_omp_implicit_dsa)
1050 << getOpenMPClauseName(DVar.CKind);
1055 class DSAAttrChecker : public StmtVisitor<DSAAttrChecker, void> {
1060 llvm::SmallVector<Expr *, 8> ImplicitFirstprivate;
1061 llvm::DenseMap<VarDecl *, Expr *> VarsWithInheritedDSA;
1064 void VisitDeclRefExpr(DeclRefExpr *E) {
1065 if (auto *VD = dyn_cast<VarDecl>(E->getDecl())) {
1066 // Skip internally declared variables.
1067 if (VD->isLocalVarDecl() && !CS->capturesVariable(VD))
1070 auto DVar = Stack->getTopDSA(VD, false);
1071 // Check if the variable has explicit DSA set and stop analysis if it so.
1072 if (DVar.RefExpr) return;
1074 auto ELoc = E->getExprLoc();
1075 auto DKind = Stack->getCurrentDirective();
1076 // The default(none) clause requires that each variable that is referenced
1077 // in the construct, and does not have a predetermined data-sharing
1078 // attribute, must have its data-sharing attribute explicitly determined
1079 // by being listed in a data-sharing attribute clause.
1080 if (DVar.CKind == OMPC_unknown && Stack->getDefaultDSA() == DSA_none &&
1081 isParallelOrTaskRegion(DKind) &&
1082 VarsWithInheritedDSA.count(VD) == 0) {
1083 VarsWithInheritedDSA[VD] = E;
1087 // OpenMP [2.9.3.6, Restrictions, p.2]
1088 // A list item that appears in a reduction clause of the innermost
1089 // enclosing worksharing or parallel construct may not be accessed in an
1091 DVar = Stack->hasInnermostDSA(VD, MatchesAnyClause(OMPC_reduction),
1092 [](OpenMPDirectiveKind K) -> bool {
1093 return isOpenMPParallelDirective(K) ||
1094 isOpenMPWorksharingDirective(K) ||
1095 isOpenMPTeamsDirective(K);
1098 if (DKind == OMPD_task && DVar.CKind == OMPC_reduction) {
1100 SemaRef.Diag(ELoc, diag::err_omp_reduction_in_task);
1101 ReportOriginalDSA(SemaRef, Stack, VD, DVar);
1105 // Define implicit data-sharing attributes for task.
1106 DVar = Stack->getImplicitDSA(VD, false);
1107 if (DKind == OMPD_task && DVar.CKind != OMPC_shared)
1108 ImplicitFirstprivate.push_back(E);
1111 void VisitOMPExecutableDirective(OMPExecutableDirective *S) {
1112 for (auto *C : S->clauses()) {
1113 // Skip analysis of arguments of implicitly defined firstprivate clause
1114 // for task directives.
1115 if (C && (!isa<OMPFirstprivateClause>(C) || C->getLocStart().isValid()))
1116 for (auto *CC : C->children()) {
1122 void VisitStmt(Stmt *S) {
1123 for (auto *C : S->children()) {
1124 if (C && !isa<OMPExecutableDirective>(C))
1129 bool isErrorFound() { return ErrorFound; }
1130 ArrayRef<Expr *> getImplicitFirstprivate() { return ImplicitFirstprivate; }
1131 llvm::DenseMap<VarDecl *, Expr *> &getVarsWithInheritedDSA() {
1132 return VarsWithInheritedDSA;
1135 DSAAttrChecker(DSAStackTy *S, Sema &SemaRef, CapturedStmt *CS)
1136 : Stack(S), SemaRef(SemaRef), ErrorFound(false), CS(CS) {}
1140 void Sema::ActOnOpenMPRegionStart(OpenMPDirectiveKind DKind, Scope *CurScope) {
1142 case OMPD_parallel: {
1143 QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1);
1144 QualType KmpInt32PtrTy = Context.getPointerType(KmpInt32Ty);
1145 Sema::CapturedParamNameType Params[] = {
1146 std::make_pair(".global_tid.", KmpInt32PtrTy),
1147 std::make_pair(".bound_tid.", KmpInt32PtrTy),
1148 std::make_pair(StringRef(), QualType()) // __context with shared vars
1150 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
1155 Sema::CapturedParamNameType Params[] = {
1156 std::make_pair(StringRef(), QualType()) // __context with shared vars
1158 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
1163 Sema::CapturedParamNameType Params[] = {
1164 std::make_pair(StringRef(), QualType()) // __context with shared vars
1166 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
1170 case OMPD_for_simd: {
1171 Sema::CapturedParamNameType Params[] = {
1172 std::make_pair(StringRef(), QualType()) // __context with shared vars
1174 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
1178 case OMPD_sections: {
1179 Sema::CapturedParamNameType Params[] = {
1180 std::make_pair(StringRef(), QualType()) // __context with shared vars
1182 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
1186 case OMPD_section: {
1187 Sema::CapturedParamNameType Params[] = {
1188 std::make_pair(StringRef(), QualType()) // __context with shared vars
1190 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
1195 Sema::CapturedParamNameType Params[] = {
1196 std::make_pair(StringRef(), QualType()) // __context with shared vars
1198 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
1203 Sema::CapturedParamNameType Params[] = {
1204 std::make_pair(StringRef(), QualType()) // __context with shared vars
1206 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
1210 case OMPD_critical: {
1211 Sema::CapturedParamNameType Params[] = {
1212 std::make_pair(StringRef(), QualType()) // __context with shared vars
1214 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
1218 case OMPD_parallel_for: {
1219 QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1);
1220 QualType KmpInt32PtrTy = Context.getPointerType(KmpInt32Ty);
1221 Sema::CapturedParamNameType Params[] = {
1222 std::make_pair(".global_tid.", KmpInt32PtrTy),
1223 std::make_pair(".bound_tid.", KmpInt32PtrTy),
1224 std::make_pair(StringRef(), QualType()) // __context with shared vars
1226 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
1230 case OMPD_parallel_for_simd: {
1231 QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1);
1232 QualType KmpInt32PtrTy = Context.getPointerType(KmpInt32Ty);
1233 Sema::CapturedParamNameType Params[] = {
1234 std::make_pair(".global_tid.", KmpInt32PtrTy),
1235 std::make_pair(".bound_tid.", KmpInt32PtrTy),
1236 std::make_pair(StringRef(), QualType()) // __context with shared vars
1238 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
1242 case OMPD_parallel_sections: {
1243 QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1);
1244 QualType KmpInt32PtrTy = Context.getPointerType(KmpInt32Ty);
1245 Sema::CapturedParamNameType Params[] = {
1246 std::make_pair(".global_tid.", KmpInt32PtrTy),
1247 std::make_pair(".bound_tid.", KmpInt32PtrTy),
1248 std::make_pair(StringRef(), QualType()) // __context with shared vars
1250 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
1255 QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1);
1256 QualType Args[] = {Context.VoidPtrTy.withConst().withRestrict()};
1257 FunctionProtoType::ExtProtoInfo EPI;
1258 EPI.Variadic = true;
1259 QualType CopyFnType = Context.getFunctionType(Context.VoidTy, Args, EPI);
1260 Sema::CapturedParamNameType Params[] = {
1261 std::make_pair(".global_tid.", KmpInt32Ty),
1262 std::make_pair(".part_id.", KmpInt32Ty),
1263 std::make_pair(".privates.",
1264 Context.VoidPtrTy.withConst().withRestrict()),
1267 Context.getPointerType(CopyFnType).withConst().withRestrict()),
1268 std::make_pair(StringRef(), QualType()) // __context with shared vars
1270 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
1272 // Mark this captured region as inlined, because we don't use outlined
1273 // function directly.
1274 getCurCapturedRegion()->TheCapturedDecl->addAttr(
1275 AlwaysInlineAttr::CreateImplicit(
1276 Context, AlwaysInlineAttr::Keyword_forceinline, SourceRange()));
1279 case OMPD_ordered: {
1280 Sema::CapturedParamNameType Params[] = {
1281 std::make_pair(StringRef(), QualType()) // __context with shared vars
1283 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
1288 Sema::CapturedParamNameType Params[] = {
1289 std::make_pair(StringRef(), QualType()) // __context with shared vars
1291 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
1296 Sema::CapturedParamNameType Params[] = {
1297 std::make_pair(StringRef(), QualType()) // __context with shared vars
1299 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
1304 QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1);
1305 QualType KmpInt32PtrTy = Context.getPointerType(KmpInt32Ty);
1306 Sema::CapturedParamNameType Params[] = {
1307 std::make_pair(".global_tid.", KmpInt32PtrTy),
1308 std::make_pair(".bound_tid.", KmpInt32PtrTy),
1309 std::make_pair(StringRef(), QualType()) // __context with shared vars
1311 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
1315 case OMPD_taskgroup: {
1316 Sema::CapturedParamNameType Params[] = {
1317 std::make_pair(StringRef(), QualType()) // __context with shared vars
1319 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
1323 case OMPD_threadprivate:
1324 case OMPD_taskyield:
1327 case OMPD_cancellation_point:
1330 llvm_unreachable("OpenMP Directive is not allowed");
1332 llvm_unreachable("Unknown OpenMP directive");
1336 StmtResult Sema::ActOnOpenMPRegionEnd(StmtResult S,
1337 ArrayRef<OMPClause *> Clauses) {
1338 if (!S.isUsable()) {
1339 ActOnCapturedRegionError();
1342 // This is required for proper codegen.
1343 for (auto *Clause : Clauses) {
1344 if (isOpenMPPrivate(Clause->getClauseKind()) ||
1345 Clause->getClauseKind() == OMPC_copyprivate) {
1346 // Mark all variables in private list clauses as used in inner region.
1347 for (auto *VarRef : Clause->children()) {
1348 if (auto *E = cast_or_null<Expr>(VarRef)) {
1349 MarkDeclarationsReferencedInExpr(E);
1352 } else if (isParallelOrTaskRegion(DSAStack->getCurrentDirective()) &&
1353 Clause->getClauseKind() == OMPC_schedule) {
1354 // Mark all variables in private list clauses as used in inner region.
1355 // Required for proper codegen of combined directives.
1356 // TODO: add processing for other clauses.
1357 if (auto *E = cast_or_null<Expr>(
1358 cast<OMPScheduleClause>(Clause)->getHelperChunkSize())) {
1359 MarkDeclarationsReferencedInExpr(E);
1363 return ActOnCapturedRegionEnd(S.get());
1366 static bool CheckNestingOfRegions(Sema &SemaRef, DSAStackTy *Stack,
1367 OpenMPDirectiveKind CurrentRegion,
1368 const DeclarationNameInfo &CurrentName,
1369 OpenMPDirectiveKind CancelRegion,
1370 SourceLocation StartLoc) {
1371 // Allowed nesting of constructs
1372 // +------------------+-----------------+------------------------------------+
1373 // | Parent directive | Child directive | Closely (!), No-Closely(+), Both(*)|
1374 // +------------------+-----------------+------------------------------------+
1375 // | parallel | parallel | * |
1376 // | parallel | for | * |
1377 // | parallel | for simd | * |
1378 // | parallel | master | * |
1379 // | parallel | critical | * |
1380 // | parallel | simd | * |
1381 // | parallel | sections | * |
1382 // | parallel | section | + |
1383 // | parallel | single | * |
1384 // | parallel | parallel for | * |
1385 // | parallel |parallel for simd| * |
1386 // | parallel |parallel sections| * |
1387 // | parallel | task | * |
1388 // | parallel | taskyield | * |
1389 // | parallel | barrier | * |
1390 // | parallel | taskwait | * |
1391 // | parallel | taskgroup | * |
1392 // | parallel | flush | * |
1393 // | parallel | ordered | + |
1394 // | parallel | atomic | * |
1395 // | parallel | target | * |
1396 // | parallel | teams | + |
1397 // | parallel | cancellation | |
1399 // | parallel | cancel | ! |
1400 // +------------------+-----------------+------------------------------------+
1401 // | for | parallel | * |
1402 // | for | for | + |
1403 // | for | for simd | + |
1404 // | for | master | + |
1405 // | for | critical | * |
1406 // | for | simd | * |
1407 // | for | sections | + |
1408 // | for | section | + |
1409 // | for | single | + |
1410 // | for | parallel for | * |
1411 // | for |parallel for simd| * |
1412 // | for |parallel sections| * |
1413 // | for | task | * |
1414 // | for | taskyield | * |
1415 // | for | barrier | + |
1416 // | for | taskwait | * |
1417 // | for | taskgroup | * |
1418 // | for | flush | * |
1419 // | for | ordered | * (if construct is ordered) |
1420 // | for | atomic | * |
1421 // | for | target | * |
1422 // | for | teams | + |
1423 // | for | cancellation | |
1425 // | for | cancel | ! |
1426 // +------------------+-----------------+------------------------------------+
1427 // | master | parallel | * |
1428 // | master | for | + |
1429 // | master | for simd | + |
1430 // | master | master | * |
1431 // | master | critical | * |
1432 // | master | simd | * |
1433 // | master | sections | + |
1434 // | master | section | + |
1435 // | master | single | + |
1436 // | master | parallel for | * |
1437 // | master |parallel for simd| * |
1438 // | master |parallel sections| * |
1439 // | master | task | * |
1440 // | master | taskyield | * |
1441 // | master | barrier | + |
1442 // | master | taskwait | * |
1443 // | master | taskgroup | * |
1444 // | master | flush | * |
1445 // | master | ordered | + |
1446 // | master | atomic | * |
1447 // | master | target | * |
1448 // | master | teams | + |
1449 // | master | cancellation | |
1451 // | master | cancel | |
1452 // +------------------+-----------------+------------------------------------+
1453 // | critical | parallel | * |
1454 // | critical | for | + |
1455 // | critical | for simd | + |
1456 // | critical | master | * |
1457 // | critical | critical | * (should have different names) |
1458 // | critical | simd | * |
1459 // | critical | sections | + |
1460 // | critical | section | + |
1461 // | critical | single | + |
1462 // | critical | parallel for | * |
1463 // | critical |parallel for simd| * |
1464 // | critical |parallel sections| * |
1465 // | critical | task | * |
1466 // | critical | taskyield | * |
1467 // | critical | barrier | + |
1468 // | critical | taskwait | * |
1469 // | critical | taskgroup | * |
1470 // | critical | ordered | + |
1471 // | critical | atomic | * |
1472 // | critical | target | * |
1473 // | critical | teams | + |
1474 // | critical | cancellation | |
1476 // | critical | cancel | |
1477 // +------------------+-----------------+------------------------------------+
1478 // | simd | parallel | |
1480 // | simd | for simd | |
1481 // | simd | master | |
1482 // | simd | critical | |
1483 // | simd | simd | |
1484 // | simd | sections | |
1485 // | simd | section | |
1486 // | simd | single | |
1487 // | simd | parallel for | |
1488 // | simd |parallel for simd| |
1489 // | simd |parallel sections| |
1490 // | simd | task | |
1491 // | simd | taskyield | |
1492 // | simd | barrier | |
1493 // | simd | taskwait | |
1494 // | simd | taskgroup | |
1495 // | simd | flush | |
1496 // | simd | ordered | |
1497 // | simd | atomic | |
1498 // | simd | target | |
1499 // | simd | teams | |
1500 // | simd | cancellation | |
1502 // | simd | cancel | |
1503 // +------------------+-----------------+------------------------------------+
1504 // | for simd | parallel | |
1505 // | for simd | for | |
1506 // | for simd | for simd | |
1507 // | for simd | master | |
1508 // | for simd | critical | |
1509 // | for simd | simd | |
1510 // | for simd | sections | |
1511 // | for simd | section | |
1512 // | for simd | single | |
1513 // | for simd | parallel for | |
1514 // | for simd |parallel for simd| |
1515 // | for simd |parallel sections| |
1516 // | for simd | task | |
1517 // | for simd | taskyield | |
1518 // | for simd | barrier | |
1519 // | for simd | taskwait | |
1520 // | for simd | taskgroup | |
1521 // | for simd | flush | |
1522 // | for simd | ordered | |
1523 // | for simd | atomic | |
1524 // | for simd | target | |
1525 // | for simd | teams | |
1526 // | for simd | cancellation | |
1528 // | for simd | cancel | |
1529 // +------------------+-----------------+------------------------------------+
1530 // | parallel for simd| parallel | |
1531 // | parallel for simd| for | |
1532 // | parallel for simd| for simd | |
1533 // | parallel for simd| master | |
1534 // | parallel for simd| critical | |
1535 // | parallel for simd| simd | |
1536 // | parallel for simd| sections | |
1537 // | parallel for simd| section | |
1538 // | parallel for simd| single | |
1539 // | parallel for simd| parallel for | |
1540 // | parallel for simd|parallel for simd| |
1541 // | parallel for simd|parallel sections| |
1542 // | parallel for simd| task | |
1543 // | parallel for simd| taskyield | |
1544 // | parallel for simd| barrier | |
1545 // | parallel for simd| taskwait | |
1546 // | parallel for simd| taskgroup | |
1547 // | parallel for simd| flush | |
1548 // | parallel for simd| ordered | |
1549 // | parallel for simd| atomic | |
1550 // | parallel for simd| target | |
1551 // | parallel for simd| teams | |
1552 // | parallel for simd| cancellation | |
1554 // | parallel for simd| cancel | |
1555 // +------------------+-----------------+------------------------------------+
1556 // | sections | parallel | * |
1557 // | sections | for | + |
1558 // | sections | for simd | + |
1559 // | sections | master | + |
1560 // | sections | critical | * |
1561 // | sections | simd | * |
1562 // | sections | sections | + |
1563 // | sections | section | * |
1564 // | sections | single | + |
1565 // | sections | parallel for | * |
1566 // | sections |parallel for simd| * |
1567 // | sections |parallel sections| * |
1568 // | sections | task | * |
1569 // | sections | taskyield | * |
1570 // | sections | barrier | + |
1571 // | sections | taskwait | * |
1572 // | sections | taskgroup | * |
1573 // | sections | flush | * |
1574 // | sections | ordered | + |
1575 // | sections | atomic | * |
1576 // | sections | target | * |
1577 // | sections | teams | + |
1578 // | sections | cancellation | |
1580 // | sections | cancel | ! |
1581 // +------------------+-----------------+------------------------------------+
1582 // | section | parallel | * |
1583 // | section | for | + |
1584 // | section | for simd | + |
1585 // | section | master | + |
1586 // | section | critical | * |
1587 // | section | simd | * |
1588 // | section | sections | + |
1589 // | section | section | + |
1590 // | section | single | + |
1591 // | section | parallel for | * |
1592 // | section |parallel for simd| * |
1593 // | section |parallel sections| * |
1594 // | section | task | * |
1595 // | section | taskyield | * |
1596 // | section | barrier | + |
1597 // | section | taskwait | * |
1598 // | section | taskgroup | * |
1599 // | section | flush | * |
1600 // | section | ordered | + |
1601 // | section | atomic | * |
1602 // | section | target | * |
1603 // | section | teams | + |
1604 // | section | cancellation | |
1606 // | section | cancel | ! |
1607 // +------------------+-----------------+------------------------------------+
1608 // | single | parallel | * |
1609 // | single | for | + |
1610 // | single | for simd | + |
1611 // | single | master | + |
1612 // | single | critical | * |
1613 // | single | simd | * |
1614 // | single | sections | + |
1615 // | single | section | + |
1616 // | single | single | + |
1617 // | single | parallel for | * |
1618 // | single |parallel for simd| * |
1619 // | single |parallel sections| * |
1620 // | single | task | * |
1621 // | single | taskyield | * |
1622 // | single | barrier | + |
1623 // | single | taskwait | * |
1624 // | single | taskgroup | * |
1625 // | single | flush | * |
1626 // | single | ordered | + |
1627 // | single | atomic | * |
1628 // | single | target | * |
1629 // | single | teams | + |
1630 // | single | cancellation | |
1632 // | single | cancel | |
1633 // +------------------+-----------------+------------------------------------+
1634 // | parallel for | parallel | * |
1635 // | parallel for | for | + |
1636 // | parallel for | for simd | + |
1637 // | parallel for | master | + |
1638 // | parallel for | critical | * |
1639 // | parallel for | simd | * |
1640 // | parallel for | sections | + |
1641 // | parallel for | section | + |
1642 // | parallel for | single | + |
1643 // | parallel for | parallel for | * |
1644 // | parallel for |parallel for simd| * |
1645 // | parallel for |parallel sections| * |
1646 // | parallel for | task | * |
1647 // | parallel for | taskyield | * |
1648 // | parallel for | barrier | + |
1649 // | parallel for | taskwait | * |
1650 // | parallel for | taskgroup | * |
1651 // | parallel for | flush | * |
1652 // | parallel for | ordered | * (if construct is ordered) |
1653 // | parallel for | atomic | * |
1654 // | parallel for | target | * |
1655 // | parallel for | teams | + |
1656 // | parallel for | cancellation | |
1658 // | parallel for | cancel | ! |
1659 // +------------------+-----------------+------------------------------------+
1660 // | parallel sections| parallel | * |
1661 // | parallel sections| for | + |
1662 // | parallel sections| for simd | + |
1663 // | parallel sections| master | + |
1664 // | parallel sections| critical | + |
1665 // | parallel sections| simd | * |
1666 // | parallel sections| sections | + |
1667 // | parallel sections| section | * |
1668 // | parallel sections| single | + |
1669 // | parallel sections| parallel for | * |
1670 // | parallel sections|parallel for simd| * |
1671 // | parallel sections|parallel sections| * |
1672 // | parallel sections| task | * |
1673 // | parallel sections| taskyield | * |
1674 // | parallel sections| barrier | + |
1675 // | parallel sections| taskwait | * |
1676 // | parallel sections| taskgroup | * |
1677 // | parallel sections| flush | * |
1678 // | parallel sections| ordered | + |
1679 // | parallel sections| atomic | * |
1680 // | parallel sections| target | * |
1681 // | parallel sections| teams | + |
1682 // | parallel sections| cancellation | |
1684 // | parallel sections| cancel | ! |
1685 // +------------------+-----------------+------------------------------------+
1686 // | task | parallel | * |
1687 // | task | for | + |
1688 // | task | for simd | + |
1689 // | task | master | + |
1690 // | task | critical | * |
1691 // | task | simd | * |
1692 // | task | sections | + |
1693 // | task | section | + |
1694 // | task | single | + |
1695 // | task | parallel for | * |
1696 // | task |parallel for simd| * |
1697 // | task |parallel sections| * |
1698 // | task | task | * |
1699 // | task | taskyield | * |
1700 // | task | barrier | + |
1701 // | task | taskwait | * |
1702 // | task | taskgroup | * |
1703 // | task | flush | * |
1704 // | task | ordered | + |
1705 // | task | atomic | * |
1706 // | task | target | * |
1707 // | task | teams | + |
1708 // | task | cancellation | |
1710 // | task | cancel | ! |
1711 // +------------------+-----------------+------------------------------------+
1712 // | ordered | parallel | * |
1713 // | ordered | for | + |
1714 // | ordered | for simd | + |
1715 // | ordered | master | * |
1716 // | ordered | critical | * |
1717 // | ordered | simd | * |
1718 // | ordered | sections | + |
1719 // | ordered | section | + |
1720 // | ordered | single | + |
1721 // | ordered | parallel for | * |
1722 // | ordered |parallel for simd| * |
1723 // | ordered |parallel sections| * |
1724 // | ordered | task | * |
1725 // | ordered | taskyield | * |
1726 // | ordered | barrier | + |
1727 // | ordered | taskwait | * |
1728 // | ordered | taskgroup | * |
1729 // | ordered | flush | * |
1730 // | ordered | ordered | + |
1731 // | ordered | atomic | * |
1732 // | ordered | target | * |
1733 // | ordered | teams | + |
1734 // | ordered | cancellation | |
1736 // | ordered | cancel | |
1737 // +------------------+-----------------+------------------------------------+
1738 // | atomic | parallel | |
1739 // | atomic | for | |
1740 // | atomic | for simd | |
1741 // | atomic | master | |
1742 // | atomic | critical | |
1743 // | atomic | simd | |
1744 // | atomic | sections | |
1745 // | atomic | section | |
1746 // | atomic | single | |
1747 // | atomic | parallel for | |
1748 // | atomic |parallel for simd| |
1749 // | atomic |parallel sections| |
1750 // | atomic | task | |
1751 // | atomic | taskyield | |
1752 // | atomic | barrier | |
1753 // | atomic | taskwait | |
1754 // | atomic | taskgroup | |
1755 // | atomic | flush | |
1756 // | atomic | ordered | |
1757 // | atomic | atomic | |
1758 // | atomic | target | |
1759 // | atomic | teams | |
1760 // | atomic | cancellation | |
1762 // | atomic | cancel | |
1763 // +------------------+-----------------+------------------------------------+
1764 // | target | parallel | * |
1765 // | target | for | * |
1766 // | target | for simd | * |
1767 // | target | master | * |
1768 // | target | critical | * |
1769 // | target | simd | * |
1770 // | target | sections | * |
1771 // | target | section | * |
1772 // | target | single | * |
1773 // | target | parallel for | * |
1774 // | target |parallel for simd| * |
1775 // | target |parallel sections| * |
1776 // | target | task | * |
1777 // | target | taskyield | * |
1778 // | target | barrier | * |
1779 // | target | taskwait | * |
1780 // | target | taskgroup | * |
1781 // | target | flush | * |
1782 // | target | ordered | * |
1783 // | target | atomic | * |
1784 // | target | target | * |
1785 // | target | teams | * |
1786 // | target | cancellation | |
1788 // | target | cancel | |
1789 // +------------------+-----------------+------------------------------------+
1790 // | teams | parallel | * |
1791 // | teams | for | + |
1792 // | teams | for simd | + |
1793 // | teams | master | + |
1794 // | teams | critical | + |
1795 // | teams | simd | + |
1796 // | teams | sections | + |
1797 // | teams | section | + |
1798 // | teams | single | + |
1799 // | teams | parallel for | * |
1800 // | teams |parallel for simd| * |
1801 // | teams |parallel sections| * |
1802 // | teams | task | + |
1803 // | teams | taskyield | + |
1804 // | teams | barrier | + |
1805 // | teams | taskwait | + |
1806 // | teams | taskgroup | + |
1807 // | teams | flush | + |
1808 // | teams | ordered | + |
1809 // | teams | atomic | + |
1810 // | teams | target | + |
1811 // | teams | teams | + |
1812 // | teams | cancellation | |
1814 // | teams | cancel | |
1815 // +------------------+-----------------+------------------------------------+
1816 if (Stack->getCurScope()) {
1817 auto ParentRegion = Stack->getParentDirective();
1818 bool NestingProhibited = false;
1819 bool CloseNesting = true;
1822 ShouldBeInParallelRegion,
1823 ShouldBeInOrderedRegion,
1824 ShouldBeInTargetRegion
1825 } Recommend = NoRecommend;
1826 if (isOpenMPSimdDirective(ParentRegion)) {
1827 // OpenMP [2.16, Nesting of Regions]
1828 // OpenMP constructs may not be nested inside a simd region.
1829 SemaRef.Diag(StartLoc, diag::err_omp_prohibited_region_simd);
1832 if (ParentRegion == OMPD_atomic) {
1833 // OpenMP [2.16, Nesting of Regions]
1834 // OpenMP constructs may not be nested inside an atomic region.
1835 SemaRef.Diag(StartLoc, diag::err_omp_prohibited_region_atomic);
1838 if (CurrentRegion == OMPD_section) {
1839 // OpenMP [2.7.2, sections Construct, Restrictions]
1840 // Orphaned section directives are prohibited. That is, the section
1841 // directives must appear within the sections construct and must not be
1842 // encountered elsewhere in the sections region.
1843 if (ParentRegion != OMPD_sections &&
1844 ParentRegion != OMPD_parallel_sections) {
1845 SemaRef.Diag(StartLoc, diag::err_omp_orphaned_section_directive)
1846 << (ParentRegion != OMPD_unknown)
1847 << getOpenMPDirectiveName(ParentRegion);
1852 // Allow some constructs to be orphaned (they could be used in functions,
1853 // called from OpenMP regions with the required preconditions).
1854 if (ParentRegion == OMPD_unknown)
1856 if (CurrentRegion == OMPD_cancellation_point ||
1857 CurrentRegion == OMPD_cancel) {
1858 // OpenMP [2.16, Nesting of Regions]
1859 // A cancellation point construct for which construct-type-clause is
1860 // taskgroup must be nested inside a task construct. A cancellation
1861 // point construct for which construct-type-clause is not taskgroup must
1862 // be closely nested inside an OpenMP construct that matches the type
1863 // specified in construct-type-clause.
1864 // A cancel construct for which construct-type-clause is taskgroup must be
1865 // nested inside a task construct. A cancel construct for which
1866 // construct-type-clause is not taskgroup must be closely nested inside an
1867 // OpenMP construct that matches the type specified in
1868 // construct-type-clause.
1870 !((CancelRegion == OMPD_parallel && ParentRegion == OMPD_parallel) ||
1871 (CancelRegion == OMPD_for && ParentRegion == OMPD_for) ||
1872 (CancelRegion == OMPD_taskgroup && ParentRegion == OMPD_task) ||
1873 (CancelRegion == OMPD_sections &&
1874 (ParentRegion == OMPD_section || ParentRegion == OMPD_sections)));
1875 } else if (CurrentRegion == OMPD_master) {
1876 // OpenMP [2.16, Nesting of Regions]
1877 // A master region may not be closely nested inside a worksharing,
1878 // atomic, or explicit task region.
1879 NestingProhibited = isOpenMPWorksharingDirective(ParentRegion) ||
1880 ParentRegion == OMPD_task;
1881 } else if (CurrentRegion == OMPD_critical && CurrentName.getName()) {
1882 // OpenMP [2.16, Nesting of Regions]
1883 // A critical region may not be nested (closely or otherwise) inside a
1884 // critical region with the same name. Note that this restriction is not
1885 // sufficient to prevent deadlock.
1886 SourceLocation PreviousCriticalLoc;
1888 Stack->hasDirective([CurrentName, &PreviousCriticalLoc](
1889 OpenMPDirectiveKind K,
1890 const DeclarationNameInfo &DNI,
1893 if (K == OMPD_critical &&
1894 DNI.getName() == CurrentName.getName()) {
1895 PreviousCriticalLoc = Loc;
1900 false /* skip top directive */);
1902 SemaRef.Diag(StartLoc,
1903 diag::err_omp_prohibited_region_critical_same_name)
1904 << CurrentName.getName();
1905 if (PreviousCriticalLoc.isValid())
1906 SemaRef.Diag(PreviousCriticalLoc,
1907 diag::note_omp_previous_critical_region);
1910 } else if (CurrentRegion == OMPD_barrier) {
1911 // OpenMP [2.16, Nesting of Regions]
1912 // A barrier region may not be closely nested inside a worksharing,
1913 // explicit task, critical, ordered, atomic, or master region.
1915 isOpenMPWorksharingDirective(ParentRegion) ||
1916 ParentRegion == OMPD_task || ParentRegion == OMPD_master ||
1917 ParentRegion == OMPD_critical || ParentRegion == OMPD_ordered;
1918 } else if (isOpenMPWorksharingDirective(CurrentRegion) &&
1919 !isOpenMPParallelDirective(CurrentRegion)) {
1920 // OpenMP [2.16, Nesting of Regions]
1921 // A worksharing region may not be closely nested inside a worksharing,
1922 // explicit task, critical, ordered, atomic, or master region.
1924 isOpenMPWorksharingDirective(ParentRegion) ||
1925 ParentRegion == OMPD_task || ParentRegion == OMPD_master ||
1926 ParentRegion == OMPD_critical || ParentRegion == OMPD_ordered;
1927 Recommend = ShouldBeInParallelRegion;
1928 } else if (CurrentRegion == OMPD_ordered) {
1929 // OpenMP [2.16, Nesting of Regions]
1930 // An ordered region may not be closely nested inside a critical,
1931 // atomic, or explicit task region.
1932 // An ordered region must be closely nested inside a loop region (or
1933 // parallel loop region) with an ordered clause.
1934 NestingProhibited = ParentRegion == OMPD_critical ||
1935 ParentRegion == OMPD_task ||
1936 !Stack->isParentOrderedRegion();
1937 Recommend = ShouldBeInOrderedRegion;
1938 } else if (isOpenMPTeamsDirective(CurrentRegion)) {
1939 // OpenMP [2.16, Nesting of Regions]
1940 // If specified, a teams construct must be contained within a target
1942 NestingProhibited = ParentRegion != OMPD_target;
1943 Recommend = ShouldBeInTargetRegion;
1944 Stack->setParentTeamsRegionLoc(Stack->getConstructLoc());
1946 if (!NestingProhibited && isOpenMPTeamsDirective(ParentRegion)) {
1947 // OpenMP [2.16, Nesting of Regions]
1948 // distribute, parallel, parallel sections, parallel workshare, and the
1949 // parallel loop and parallel loop SIMD constructs are the only OpenMP
1950 // constructs that can be closely nested in the teams region.
1951 // TODO: add distribute directive.
1952 NestingProhibited = !isOpenMPParallelDirective(CurrentRegion);
1953 Recommend = ShouldBeInParallelRegion;
1955 if (NestingProhibited) {
1956 SemaRef.Diag(StartLoc, diag::err_omp_prohibited_region)
1957 << CloseNesting << getOpenMPDirectiveName(ParentRegion) << Recommend
1958 << getOpenMPDirectiveName(CurrentRegion);
1965 StmtResult Sema::ActOnOpenMPExecutableDirective(
1966 OpenMPDirectiveKind Kind, const DeclarationNameInfo &DirName,
1967 OpenMPDirectiveKind CancelRegion, ArrayRef<OMPClause *> Clauses,
1968 Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc) {
1969 StmtResult Res = StmtError();
1970 if (CheckNestingOfRegions(*this, DSAStack, Kind, DirName, CancelRegion,
1974 llvm::SmallVector<OMPClause *, 8> ClausesWithImplicit;
1975 llvm::DenseMap<VarDecl *, Expr *> VarsWithInheritedDSA;
1976 bool ErrorFound = false;
1977 ClausesWithImplicit.append(Clauses.begin(), Clauses.end());
1979 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
1981 // Check default data sharing attributes for referenced variables.
1982 DSAAttrChecker DSAChecker(DSAStack, *this, cast<CapturedStmt>(AStmt));
1983 DSAChecker.Visit(cast<CapturedStmt>(AStmt)->getCapturedStmt());
1984 if (DSAChecker.isErrorFound())
1986 // Generate list of implicitly defined firstprivate variables.
1987 VarsWithInheritedDSA = DSAChecker.getVarsWithInheritedDSA();
1989 if (!DSAChecker.getImplicitFirstprivate().empty()) {
1990 if (OMPClause *Implicit = ActOnOpenMPFirstprivateClause(
1991 DSAChecker.getImplicitFirstprivate(), SourceLocation(),
1992 SourceLocation(), SourceLocation())) {
1993 ClausesWithImplicit.push_back(Implicit);
1994 ErrorFound = cast<OMPFirstprivateClause>(Implicit)->varlist_size() !=
1995 DSAChecker.getImplicitFirstprivate().size();
2003 Res = ActOnOpenMPParallelDirective(ClausesWithImplicit, AStmt, StartLoc,
2007 Res = ActOnOpenMPSimdDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc,
2008 VarsWithInheritedDSA);
2011 Res = ActOnOpenMPForDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc,
2012 VarsWithInheritedDSA);
2015 Res = ActOnOpenMPForSimdDirective(ClausesWithImplicit, AStmt, StartLoc,
2016 EndLoc, VarsWithInheritedDSA);
2019 Res = ActOnOpenMPSectionsDirective(ClausesWithImplicit, AStmt, StartLoc,
2023 assert(ClausesWithImplicit.empty() &&
2024 "No clauses are allowed for 'omp section' directive");
2025 Res = ActOnOpenMPSectionDirective(AStmt, StartLoc, EndLoc);
2028 Res = ActOnOpenMPSingleDirective(ClausesWithImplicit, AStmt, StartLoc,
2032 assert(ClausesWithImplicit.empty() &&
2033 "No clauses are allowed for 'omp master' directive");
2034 Res = ActOnOpenMPMasterDirective(AStmt, StartLoc, EndLoc);
2037 assert(ClausesWithImplicit.empty() &&
2038 "No clauses are allowed for 'omp critical' directive");
2039 Res = ActOnOpenMPCriticalDirective(DirName, AStmt, StartLoc, EndLoc);
2041 case OMPD_parallel_for:
2042 Res = ActOnOpenMPParallelForDirective(ClausesWithImplicit, AStmt, StartLoc,
2043 EndLoc, VarsWithInheritedDSA);
2045 case OMPD_parallel_for_simd:
2046 Res = ActOnOpenMPParallelForSimdDirective(
2047 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
2049 case OMPD_parallel_sections:
2050 Res = ActOnOpenMPParallelSectionsDirective(ClausesWithImplicit, AStmt,
2055 ActOnOpenMPTaskDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc);
2057 case OMPD_taskyield:
2058 assert(ClausesWithImplicit.empty() &&
2059 "No clauses are allowed for 'omp taskyield' directive");
2060 assert(AStmt == nullptr &&
2061 "No associated statement allowed for 'omp taskyield' directive");
2062 Res = ActOnOpenMPTaskyieldDirective(StartLoc, EndLoc);
2065 assert(ClausesWithImplicit.empty() &&
2066 "No clauses are allowed for 'omp barrier' directive");
2067 assert(AStmt == nullptr &&
2068 "No associated statement allowed for 'omp barrier' directive");
2069 Res = ActOnOpenMPBarrierDirective(StartLoc, EndLoc);
2072 assert(ClausesWithImplicit.empty() &&
2073 "No clauses are allowed for 'omp taskwait' directive");
2074 assert(AStmt == nullptr &&
2075 "No associated statement allowed for 'omp taskwait' directive");
2076 Res = ActOnOpenMPTaskwaitDirective(StartLoc, EndLoc);
2078 case OMPD_taskgroup:
2079 assert(ClausesWithImplicit.empty() &&
2080 "No clauses are allowed for 'omp taskgroup' directive");
2081 Res = ActOnOpenMPTaskgroupDirective(AStmt, StartLoc, EndLoc);
2084 assert(AStmt == nullptr &&
2085 "No associated statement allowed for 'omp flush' directive");
2086 Res = ActOnOpenMPFlushDirective(ClausesWithImplicit, StartLoc, EndLoc);
2089 assert(ClausesWithImplicit.empty() &&
2090 "No clauses are allowed for 'omp ordered' directive");
2091 Res = ActOnOpenMPOrderedDirective(AStmt, StartLoc, EndLoc);
2094 Res = ActOnOpenMPAtomicDirective(ClausesWithImplicit, AStmt, StartLoc,
2099 ActOnOpenMPTeamsDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc);
2102 Res = ActOnOpenMPTargetDirective(ClausesWithImplicit, AStmt, StartLoc,
2105 case OMPD_cancellation_point:
2106 assert(ClausesWithImplicit.empty() &&
2107 "No clauses are allowed for 'omp cancellation point' directive");
2108 assert(AStmt == nullptr && "No associated statement allowed for 'omp "
2109 "cancellation point' directive");
2110 Res = ActOnOpenMPCancellationPointDirective(StartLoc, EndLoc, CancelRegion);
2113 assert(ClausesWithImplicit.empty() &&
2114 "No clauses are allowed for 'omp cancel' directive");
2115 assert(AStmt == nullptr &&
2116 "No associated statement allowed for 'omp cancel' directive");
2117 Res = ActOnOpenMPCancelDirective(StartLoc, EndLoc, CancelRegion);
2119 case OMPD_threadprivate:
2120 llvm_unreachable("OpenMP Directive is not allowed");
2122 llvm_unreachable("Unknown OpenMP directive");
2125 for (auto P : VarsWithInheritedDSA) {
2126 Diag(P.second->getExprLoc(), diag::err_omp_no_dsa_for_variable)
2127 << P.first << P.second->getSourceRange();
2129 if (!VarsWithInheritedDSA.empty())
2137 StmtResult Sema::ActOnOpenMPParallelDirective(ArrayRef<OMPClause *> Clauses,
2139 SourceLocation StartLoc,
2140 SourceLocation EndLoc) {
2141 assert(AStmt && isa<CapturedStmt>(AStmt) && "Captured statement expected");
2142 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
2143 // 1.2.2 OpenMP Language Terminology
2144 // Structured block - An executable statement with a single entry at the
2145 // top and a single exit at the bottom.
2146 // The point of exit cannot be a branch out of the structured block.
2147 // longjmp() and throw() must not violate the entry/exit criteria.
2148 CS->getCapturedDecl()->setNothrow();
2150 getCurFunction()->setHasBranchProtectedScope();
2152 return OMPParallelDirective::Create(Context, StartLoc, EndLoc, Clauses,
2157 /// \brief Helper class for checking canonical form of the OpenMP loops and
2158 /// extracting iteration space of each loop in the loop nest, that will be used
2159 /// for IR generation.
2160 class OpenMPIterationSpaceChecker {
2161 /// \brief Reference to Sema.
2163 /// \brief A location for diagnostics (when there is no some better location).
2164 SourceLocation DefaultLoc;
2165 /// \brief A location for diagnostics (when increment is not compatible).
2166 SourceLocation ConditionLoc;
2167 /// \brief A source location for referring to loop init later.
2168 SourceRange InitSrcRange;
2169 /// \brief A source location for referring to condition later.
2170 SourceRange ConditionSrcRange;
2171 /// \brief A source location for referring to increment later.
2172 SourceRange IncrementSrcRange;
2173 /// \brief Loop variable.
2175 /// \brief Reference to loop variable.
2176 DeclRefExpr *VarRef;
2177 /// \brief Lower bound (initializer for the var).
2179 /// \brief Upper bound.
2181 /// \brief Loop step (increment).
2183 /// \brief This flag is true when condition is one of:
2189 /// \brief This flag is true when condition is strict ( < or > ).
2190 bool TestIsStrictOp;
2191 /// \brief This flag is true when step is subtracted on each iteration.
2195 OpenMPIterationSpaceChecker(Sema &SemaRef, SourceLocation DefaultLoc)
2196 : SemaRef(SemaRef), DefaultLoc(DefaultLoc), ConditionLoc(DefaultLoc),
2197 InitSrcRange(SourceRange()), ConditionSrcRange(SourceRange()),
2198 IncrementSrcRange(SourceRange()), Var(nullptr), VarRef(nullptr),
2199 LB(nullptr), UB(nullptr), Step(nullptr), TestIsLessOp(false),
2200 TestIsStrictOp(false), SubtractStep(false) {}
2201 /// \brief Check init-expr for canonical loop form and save loop counter
2202 /// variable - #Var and its initialization value - #LB.
2203 bool CheckInit(Stmt *S, bool EmitDiags = true);
2204 /// \brief Check test-expr for canonical form, save upper-bound (#UB), flags
2205 /// for less/greater and for strict/non-strict comparison.
2206 bool CheckCond(Expr *S);
2207 /// \brief Check incr-expr for canonical loop form and return true if it
2208 /// does not conform, otherwise save loop step (#Step).
2209 bool CheckInc(Expr *S);
2210 /// \brief Return the loop counter variable.
2211 VarDecl *GetLoopVar() const { return Var; }
2212 /// \brief Return the reference expression to loop counter variable.
2213 DeclRefExpr *GetLoopVarRefExpr() const { return VarRef; }
2214 /// \brief Source range of the loop init.
2215 SourceRange GetInitSrcRange() const { return InitSrcRange; }
2216 /// \brief Source range of the loop condition.
2217 SourceRange GetConditionSrcRange() const { return ConditionSrcRange; }
2218 /// \brief Source range of the loop increment.
2219 SourceRange GetIncrementSrcRange() const { return IncrementSrcRange; }
2220 /// \brief True if the step should be subtracted.
2221 bool ShouldSubtractStep() const { return SubtractStep; }
2222 /// \brief Build the expression to calculate the number of iterations.
2223 Expr *BuildNumIterations(Scope *S, const bool LimitedType) const;
2224 /// \brief Build the precondition expression for the loops.
2225 Expr *BuildPreCond(Scope *S, Expr *Cond) const;
2226 /// \brief Build reference expression to the counter be used for codegen.
2227 Expr *BuildCounterVar() const;
2228 /// \brief Build initization of the counter be used for codegen.
2229 Expr *BuildCounterInit() const;
2230 /// \brief Build step of the counter be used for codegen.
2231 Expr *BuildCounterStep() const;
2232 /// \brief Return true if any expression is dependent.
2233 bool Dependent() const;
2236 /// \brief Check the right-hand side of an assignment in the increment
2238 bool CheckIncRHS(Expr *RHS);
2239 /// \brief Helper to set loop counter variable and its initializer.
2240 bool SetVarAndLB(VarDecl *NewVar, DeclRefExpr *NewVarRefExpr, Expr *NewLB);
2241 /// \brief Helper to set upper bound.
2242 bool SetUB(Expr *NewUB, bool LessOp, bool StrictOp, const SourceRange &SR,
2243 const SourceLocation &SL);
2244 /// \brief Helper to set loop increment.
2245 bool SetStep(Expr *NewStep, bool Subtract);
2248 bool OpenMPIterationSpaceChecker::Dependent() const {
2250 assert(!LB && !UB && !Step);
2253 return Var->getType()->isDependentType() || (LB && LB->isValueDependent()) ||
2254 (UB && UB->isValueDependent()) || (Step && Step->isValueDependent());
2257 bool OpenMPIterationSpaceChecker::SetVarAndLB(VarDecl *NewVar,
2258 DeclRefExpr *NewVarRefExpr,
2260 // State consistency checking to ensure correct usage.
2261 assert(Var == nullptr && LB == nullptr && VarRef == nullptr &&
2262 UB == nullptr && Step == nullptr && !TestIsLessOp && !TestIsStrictOp);
2263 if (!NewVar || !NewLB)
2266 VarRef = NewVarRefExpr;
2271 bool OpenMPIterationSpaceChecker::SetUB(Expr *NewUB, bool LessOp, bool StrictOp,
2272 const SourceRange &SR,
2273 const SourceLocation &SL) {
2274 // State consistency checking to ensure correct usage.
2275 assert(Var != nullptr && LB != nullptr && UB == nullptr && Step == nullptr &&
2276 !TestIsLessOp && !TestIsStrictOp);
2280 TestIsLessOp = LessOp;
2281 TestIsStrictOp = StrictOp;
2282 ConditionSrcRange = SR;
2287 bool OpenMPIterationSpaceChecker::SetStep(Expr *NewStep, bool Subtract) {
2288 // State consistency checking to ensure correct usage.
2289 assert(Var != nullptr && LB != nullptr && Step == nullptr);
2292 if (!NewStep->isValueDependent()) {
2293 // Check that the step is integer expression.
2294 SourceLocation StepLoc = NewStep->getLocStart();
2296 SemaRef.PerformOpenMPImplicitIntegerConversion(StepLoc, NewStep);
2297 if (Val.isInvalid())
2299 NewStep = Val.get();
2301 // OpenMP [2.6, Canonical Loop Form, Restrictions]
2302 // If test-expr is of form var relational-op b and relational-op is < or
2303 // <= then incr-expr must cause var to increase on each iteration of the
2304 // loop. If test-expr is of form var relational-op b and relational-op is
2305 // > or >= then incr-expr must cause var to decrease on each iteration of
2307 // If test-expr is of form b relational-op var and relational-op is < or
2308 // <= then incr-expr must cause var to decrease on each iteration of the
2309 // loop. If test-expr is of form b relational-op var and relational-op is
2310 // > or >= then incr-expr must cause var to increase on each iteration of
2312 llvm::APSInt Result;
2313 bool IsConstant = NewStep->isIntegerConstantExpr(Result, SemaRef.Context);
2314 bool IsUnsigned = !NewStep->getType()->hasSignedIntegerRepresentation();
2316 IsConstant && Result.isSigned() && (Subtract != Result.isNegative());
2318 IsConstant && Result.isSigned() && (Subtract == Result.isNegative());
2319 bool IsConstZero = IsConstant && !Result.getBoolValue();
2320 if (UB && (IsConstZero ||
2321 (TestIsLessOp ? (IsConstNeg || (IsUnsigned && Subtract))
2322 : (IsConstPos || (IsUnsigned && !Subtract))))) {
2323 SemaRef.Diag(NewStep->getExprLoc(),
2324 diag::err_omp_loop_incr_not_compatible)
2325 << Var << TestIsLessOp << NewStep->getSourceRange();
2326 SemaRef.Diag(ConditionLoc,
2327 diag::note_omp_loop_cond_requres_compatible_incr)
2328 << TestIsLessOp << ConditionSrcRange;
2331 if (TestIsLessOp == Subtract) {
2332 NewStep = SemaRef.CreateBuiltinUnaryOp(NewStep->getExprLoc(), UO_Minus,
2334 Subtract = !Subtract;
2339 SubtractStep = Subtract;
2343 bool OpenMPIterationSpaceChecker::CheckInit(Stmt *S, bool EmitDiags) {
2344 // Check init-expr for canonical loop form and save loop counter
2345 // variable - #Var and its initialization value - #LB.
2346 // OpenMP [2.6] Canonical loop form. init-expr may be one of the following:
2348 // integer-type var = lb
2349 // random-access-iterator-type var = lb
2350 // pointer-type var = lb
2354 SemaRef.Diag(DefaultLoc, diag::err_omp_loop_not_canonical_init);
2358 InitSrcRange = S->getSourceRange();
2359 if (Expr *E = dyn_cast<Expr>(S))
2360 S = E->IgnoreParens();
2361 if (auto BO = dyn_cast<BinaryOperator>(S)) {
2362 if (BO->getOpcode() == BO_Assign)
2363 if (auto DRE = dyn_cast<DeclRefExpr>(BO->getLHS()->IgnoreParens()))
2364 return SetVarAndLB(dyn_cast<VarDecl>(DRE->getDecl()), DRE,
2366 } else if (auto DS = dyn_cast<DeclStmt>(S)) {
2367 if (DS->isSingleDecl()) {
2368 if (auto Var = dyn_cast_or_null<VarDecl>(DS->getSingleDecl())) {
2369 if (Var->hasInit()) {
2370 // Accept non-canonical init form here but emit ext. warning.
2371 if (Var->getInitStyle() != VarDecl::CInit && EmitDiags)
2372 SemaRef.Diag(S->getLocStart(),
2373 diag::ext_omp_loop_not_canonical_init)
2374 << S->getSourceRange();
2375 return SetVarAndLB(Var, nullptr, Var->getInit());
2379 } else if (auto CE = dyn_cast<CXXOperatorCallExpr>(S))
2380 if (CE->getOperator() == OO_Equal)
2381 if (auto DRE = dyn_cast<DeclRefExpr>(CE->getArg(0)))
2382 return SetVarAndLB(dyn_cast<VarDecl>(DRE->getDecl()), DRE,
2386 SemaRef.Diag(S->getLocStart(), diag::err_omp_loop_not_canonical_init)
2387 << S->getSourceRange();
2392 /// \brief Ignore parenthesizes, implicit casts, copy constructor and return the
2393 /// variable (which may be the loop variable) if possible.
2394 static const VarDecl *GetInitVarDecl(const Expr *E) {
2397 E = E->IgnoreParenImpCasts();
2398 if (auto *CE = dyn_cast_or_null<CXXConstructExpr>(E))
2399 if (const CXXConstructorDecl *Ctor = CE->getConstructor())
2400 if (Ctor->isCopyConstructor() && CE->getNumArgs() == 1 &&
2401 CE->getArg(0) != nullptr)
2402 E = CE->getArg(0)->IgnoreParenImpCasts();
2403 auto DRE = dyn_cast_or_null<DeclRefExpr>(E);
2406 return dyn_cast<VarDecl>(DRE->getDecl());
2409 bool OpenMPIterationSpaceChecker::CheckCond(Expr *S) {
2410 // Check test-expr for canonical form, save upper-bound UB, flags for
2411 // less/greater and for strict/non-strict comparison.
2412 // OpenMP [2.6] Canonical loop form. Test-expr may be one of the following:
2413 // var relational-op b
2414 // b relational-op var
2417 SemaRef.Diag(DefaultLoc, diag::err_omp_loop_not_canonical_cond) << Var;
2420 S = S->IgnoreParenImpCasts();
2421 SourceLocation CondLoc = S->getLocStart();
2422 if (auto BO = dyn_cast<BinaryOperator>(S)) {
2423 if (BO->isRelationalOp()) {
2424 if (GetInitVarDecl(BO->getLHS()) == Var)
2425 return SetUB(BO->getRHS(),
2426 (BO->getOpcode() == BO_LT || BO->getOpcode() == BO_LE),
2427 (BO->getOpcode() == BO_LT || BO->getOpcode() == BO_GT),
2428 BO->getSourceRange(), BO->getOperatorLoc());
2429 if (GetInitVarDecl(BO->getRHS()) == Var)
2430 return SetUB(BO->getLHS(),
2431 (BO->getOpcode() == BO_GT || BO->getOpcode() == BO_GE),
2432 (BO->getOpcode() == BO_LT || BO->getOpcode() == BO_GT),
2433 BO->getSourceRange(), BO->getOperatorLoc());
2435 } else if (auto CE = dyn_cast<CXXOperatorCallExpr>(S)) {
2436 if (CE->getNumArgs() == 2) {
2437 auto Op = CE->getOperator();
2440 case OO_GreaterEqual:
2443 if (GetInitVarDecl(CE->getArg(0)) == Var)
2444 return SetUB(CE->getArg(1), Op == OO_Less || Op == OO_LessEqual,
2445 Op == OO_Less || Op == OO_Greater, CE->getSourceRange(),
2446 CE->getOperatorLoc());
2447 if (GetInitVarDecl(CE->getArg(1)) == Var)
2448 return SetUB(CE->getArg(0), Op == OO_Greater || Op == OO_GreaterEqual,
2449 Op == OO_Less || Op == OO_Greater, CE->getSourceRange(),
2450 CE->getOperatorLoc());
2457 SemaRef.Diag(CondLoc, diag::err_omp_loop_not_canonical_cond)
2458 << S->getSourceRange() << Var;
2462 bool OpenMPIterationSpaceChecker::CheckIncRHS(Expr *RHS) {
2463 // RHS of canonical loop form increment can be:
2468 RHS = RHS->IgnoreParenImpCasts();
2469 if (auto BO = dyn_cast<BinaryOperator>(RHS)) {
2470 if (BO->isAdditiveOp()) {
2471 bool IsAdd = BO->getOpcode() == BO_Add;
2472 if (GetInitVarDecl(BO->getLHS()) == Var)
2473 return SetStep(BO->getRHS(), !IsAdd);
2474 if (IsAdd && GetInitVarDecl(BO->getRHS()) == Var)
2475 return SetStep(BO->getLHS(), false);
2477 } else if (auto CE = dyn_cast<CXXOperatorCallExpr>(RHS)) {
2478 bool IsAdd = CE->getOperator() == OO_Plus;
2479 if ((IsAdd || CE->getOperator() == OO_Minus) && CE->getNumArgs() == 2) {
2480 if (GetInitVarDecl(CE->getArg(0)) == Var)
2481 return SetStep(CE->getArg(1), !IsAdd);
2482 if (IsAdd && GetInitVarDecl(CE->getArg(1)) == Var)
2483 return SetStep(CE->getArg(0), false);
2486 SemaRef.Diag(RHS->getLocStart(), diag::err_omp_loop_not_canonical_incr)
2487 << RHS->getSourceRange() << Var;
2491 bool OpenMPIterationSpaceChecker::CheckInc(Expr *S) {
2492 // Check incr-expr for canonical loop form and return true if it
2493 // does not conform.
2494 // OpenMP [2.6] Canonical loop form. Test-expr may be one of the following:
2506 SemaRef.Diag(DefaultLoc, diag::err_omp_loop_not_canonical_incr) << Var;
2509 IncrementSrcRange = S->getSourceRange();
2510 S = S->IgnoreParens();
2511 if (auto UO = dyn_cast<UnaryOperator>(S)) {
2512 if (UO->isIncrementDecrementOp() && GetInitVarDecl(UO->getSubExpr()) == Var)
2514 SemaRef.ActOnIntegerConstant(UO->getLocStart(),
2515 (UO->isDecrementOp() ? -1 : 1)).get(),
2517 } else if (auto BO = dyn_cast<BinaryOperator>(S)) {
2518 switch (BO->getOpcode()) {
2521 if (GetInitVarDecl(BO->getLHS()) == Var)
2522 return SetStep(BO->getRHS(), BO->getOpcode() == BO_SubAssign);
2525 if (GetInitVarDecl(BO->getLHS()) == Var)
2526 return CheckIncRHS(BO->getRHS());
2531 } else if (auto CE = dyn_cast<CXXOperatorCallExpr>(S)) {
2532 switch (CE->getOperator()) {
2535 if (GetInitVarDecl(CE->getArg(0)) == Var)
2537 SemaRef.ActOnIntegerConstant(
2539 ((CE->getOperator() == OO_MinusMinus) ? -1 : 1)).get(),
2544 if (GetInitVarDecl(CE->getArg(0)) == Var)
2545 return SetStep(CE->getArg(1), CE->getOperator() == OO_MinusEqual);
2548 if (GetInitVarDecl(CE->getArg(0)) == Var)
2549 return CheckIncRHS(CE->getArg(1));
2555 SemaRef.Diag(S->getLocStart(), diag::err_omp_loop_not_canonical_incr)
2556 << S->getSourceRange() << Var;
2560 /// \brief Build the expression to calculate the number of iterations.
2562 OpenMPIterationSpaceChecker::BuildNumIterations(Scope *S,
2563 const bool LimitedType) const {
2565 if (Var->getType()->isIntegerType() || Var->getType()->isPointerType() ||
2566 SemaRef.getLangOpts().CPlusPlus) {
2568 Expr *Upper = TestIsLessOp ? UB : LB;
2569 Expr *Lower = TestIsLessOp ? LB : UB;
2571 Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Sub, Upper, Lower);
2573 if (!Diff.isUsable() && Var->getType()->getAsCXXRecordDecl()) {
2574 // BuildBinOp already emitted error, this one is to point user to upper
2575 // and lower bound, and to tell what is passed to 'operator-'.
2576 SemaRef.Diag(Upper->getLocStart(), diag::err_omp_loop_diff_cxx)
2577 << Upper->getSourceRange() << Lower->getSourceRange();
2582 if (!Diff.isUsable())
2585 // Upper - Lower [- 1]
2587 Diff = SemaRef.BuildBinOp(
2588 S, DefaultLoc, BO_Sub, Diff.get(),
2589 SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get());
2590 if (!Diff.isUsable())
2593 // Upper - Lower [- 1] + Step
2594 Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Add, Diff.get(),
2595 Step->IgnoreImplicit());
2596 if (!Diff.isUsable())
2599 // Parentheses (for dumping/debugging purposes only).
2600 Diff = SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, Diff.get());
2601 if (!Diff.isUsable())
2604 // (Upper - Lower [- 1] + Step) / Step
2605 Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Div, Diff.get(),
2606 Step->IgnoreImplicit());
2607 if (!Diff.isUsable())
2610 // OpenMP runtime requires 32-bit or 64-bit loop variables.
2612 auto &C = SemaRef.Context;
2613 QualType Type = Diff.get()->getType();
2614 unsigned NewSize = (C.getTypeSize(Type) > 32) ? 64 : 32;
2615 if (NewSize != C.getTypeSize(Type)) {
2616 if (NewSize < C.getTypeSize(Type)) {
2617 assert(NewSize == 64 && "incorrect loop var size");
2618 SemaRef.Diag(DefaultLoc, diag::warn_omp_loop_64_bit_var)
2619 << InitSrcRange << ConditionSrcRange;
2621 QualType NewType = C.getIntTypeForBitwidth(
2622 NewSize, Type->hasSignedIntegerRepresentation());
2623 Diff = SemaRef.PerformImplicitConversion(Diff.get(), NewType,
2624 Sema::AA_Converting, true);
2625 if (!Diff.isUsable())
2633 Expr *OpenMPIterationSpaceChecker::BuildPreCond(Scope *S, Expr *Cond) const {
2634 // Try to build LB <op> UB, where <op> is <, >, <=, or >=.
2635 bool Suppress = SemaRef.getDiagnostics().getSuppressAllDiagnostics();
2636 SemaRef.getDiagnostics().setSuppressAllDiagnostics(/*Val=*/true);
2637 auto CondExpr = SemaRef.BuildBinOp(
2638 S, DefaultLoc, TestIsLessOp ? (TestIsStrictOp ? BO_LT : BO_LE)
2639 : (TestIsStrictOp ? BO_GT : BO_GE),
2641 SemaRef.getDiagnostics().setSuppressAllDiagnostics(Suppress);
2642 // Otherwise use original loop conditon and evaluate it in runtime.
2643 return CondExpr.isUsable() ? CondExpr.get() : Cond;
2646 /// \brief Build reference expression to the counter be used for codegen.
2647 Expr *OpenMPIterationSpaceChecker::BuildCounterVar() const {
2648 return buildDeclRefExpr(SemaRef, Var, Var->getType(), DefaultLoc);
2651 /// \brief Build initization of the counter be used for codegen.
2652 Expr *OpenMPIterationSpaceChecker::BuildCounterInit() const { return LB; }
2654 /// \brief Build step of the counter be used for codegen.
2655 Expr *OpenMPIterationSpaceChecker::BuildCounterStep() const { return Step; }
2657 /// \brief Iteration space of a single for loop.
2658 struct LoopIterationSpace {
2659 /// \brief Condition of the loop.
2661 /// \brief This expression calculates the number of iterations in the loop.
2662 /// It is always possible to calculate it before starting the loop.
2663 Expr *NumIterations;
2664 /// \brief The loop counter variable.
2666 /// \brief This is initializer for the initial value of #CounterVar.
2668 /// \brief This is step for the #CounterVar used to generate its update:
2669 /// #CounterVar = #CounterInit + #CounterStep * CurrentIteration.
2671 /// \brief Should step be subtracted?
2673 /// \brief Source range of the loop init.
2674 SourceRange InitSrcRange;
2675 /// \brief Source range of the loop condition.
2676 SourceRange CondSrcRange;
2677 /// \brief Source range of the loop increment.
2678 SourceRange IncSrcRange;
2683 void Sema::ActOnOpenMPLoopInitialization(SourceLocation ForLoc, Stmt *Init) {
2684 assert(getLangOpts().OpenMP && "OpenMP is not active.");
2685 assert(Init && "Expected loop in canonical form.");
2686 unsigned CollapseIteration = DSAStack->getCollapseNumber();
2687 if (CollapseIteration > 0 &&
2688 isOpenMPLoopDirective(DSAStack->getCurrentDirective())) {
2689 OpenMPIterationSpaceChecker ISC(*this, ForLoc);
2690 if (!ISC.CheckInit(Init, /*EmitDiags=*/false)) {
2691 DSAStack->addLoopControlVariable(ISC.GetLoopVar());
2693 DSAStack->setCollapseNumber(CollapseIteration - 1);
2697 /// \brief Called on a for stmt to check and extract its iteration space
2698 /// for further processing (such as collapsing).
2699 static bool CheckOpenMPIterationSpace(
2700 OpenMPDirectiveKind DKind, Stmt *S, Sema &SemaRef, DSAStackTy &DSA,
2701 unsigned CurrentNestedLoopCount, unsigned NestedLoopCount,
2702 Expr *NestedLoopCountExpr,
2703 llvm::DenseMap<VarDecl *, Expr *> &VarsWithImplicitDSA,
2704 LoopIterationSpace &ResultIterSpace) {
2705 // OpenMP [2.6, Canonical Loop Form]
2706 // for (init-expr; test-expr; incr-expr) structured-block
2707 auto For = dyn_cast_or_null<ForStmt>(S);
2709 SemaRef.Diag(S->getLocStart(), diag::err_omp_not_for)
2710 << (NestedLoopCountExpr != nullptr) << getOpenMPDirectiveName(DKind)
2711 << NestedLoopCount << (CurrentNestedLoopCount > 0)
2712 << CurrentNestedLoopCount;
2713 if (NestedLoopCount > 1)
2714 SemaRef.Diag(NestedLoopCountExpr->getExprLoc(),
2715 diag::note_omp_collapse_expr)
2716 << NestedLoopCountExpr->getSourceRange();
2719 assert(For->getBody());
2721 OpenMPIterationSpaceChecker ISC(SemaRef, For->getForLoc());
2724 auto Init = For->getInit();
2725 if (ISC.CheckInit(Init)) {
2729 bool HasErrors = false;
2731 // Check loop variable's type.
2732 auto Var = ISC.GetLoopVar();
2734 // OpenMP [2.6, Canonical Loop Form]
2735 // Var is one of the following:
2736 // A variable of signed or unsigned integer type.
2737 // For C++, a variable of a random access iterator type.
2738 // For C, a variable of a pointer type.
2739 auto VarType = Var->getType();
2740 if (!VarType->isDependentType() && !VarType->isIntegerType() &&
2741 !VarType->isPointerType() &&
2742 !(SemaRef.getLangOpts().CPlusPlus && VarType->isOverloadableType())) {
2743 SemaRef.Diag(Init->getLocStart(), diag::err_omp_loop_variable_type)
2744 << SemaRef.getLangOpts().CPlusPlus;
2748 // OpenMP, 2.14.1.1 Data-sharing Attribute Rules for Variables Referenced in a
2750 // The loop iteration variable(s) in the associated for-loop(s) of a for or
2751 // parallel for construct is (are) private.
2752 // The loop iteration variable in the associated for-loop of a simd construct
2753 // with just one associated for-loop is linear with a constant-linear-step
2754 // that is the increment of the associated for-loop.
2755 // Exclude loop var from the list of variables with implicitly defined data
2756 // sharing attributes.
2757 VarsWithImplicitDSA.erase(Var);
2759 // OpenMP [2.14.1.1, Data-sharing Attribute Rules for Variables Referenced in
2760 // a Construct, C/C++].
2761 // The loop iteration variable in the associated for-loop of a simd construct
2762 // with just one associated for-loop may be listed in a linear clause with a
2763 // constant-linear-step that is the increment of the associated for-loop.
2764 // The loop iteration variable(s) in the associated for-loop(s) of a for or
2765 // parallel for construct may be listed in a private or lastprivate clause.
2766 DSAStackTy::DSAVarData DVar = DSA.getTopDSA(Var, false);
2767 auto LoopVarRefExpr = ISC.GetLoopVarRefExpr();
2768 // If LoopVarRefExpr is nullptr it means the corresponding loop variable is
2769 // declared in the loop and it is predetermined as a private.
2770 auto PredeterminedCKind =
2771 isOpenMPSimdDirective(DKind)
2772 ? ((NestedLoopCount == 1) ? OMPC_linear : OMPC_lastprivate)
2774 if (((isOpenMPSimdDirective(DKind) && DVar.CKind != OMPC_unknown &&
2775 DVar.CKind != OMPC_threadprivate && DVar.CKind != PredeterminedCKind) ||
2776 (isOpenMPWorksharingDirective(DKind) && !isOpenMPSimdDirective(DKind) &&
2777 DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_private &&
2778 DVar.CKind != OMPC_lastprivate && DVar.CKind != OMPC_threadprivate)) &&
2779 ((DVar.CKind != OMPC_private && DVar.CKind != OMPC_threadprivate) ||
2780 DVar.RefExpr != nullptr)) {
2781 SemaRef.Diag(Init->getLocStart(), diag::err_omp_loop_var_dsa)
2782 << getOpenMPClauseName(DVar.CKind) << getOpenMPDirectiveName(DKind)
2783 << getOpenMPClauseName(PredeterminedCKind);
2784 if (DVar.RefExpr == nullptr)
2785 DVar.CKind = PredeterminedCKind;
2786 ReportOriginalDSA(SemaRef, &DSA, Var, DVar, /*IsLoopIterVar=*/true);
2788 } else if (LoopVarRefExpr != nullptr) {
2789 // Make the loop iteration variable private (for worksharing constructs),
2790 // linear (for simd directives with the only one associated loop) or
2791 // lastprivate (for simd directives with several collapsed loops).
2792 if (DVar.CKind == OMPC_unknown)
2793 DVar = DSA.hasDSA(Var, isOpenMPPrivate, MatchesAlways(),
2794 /*FromParent=*/false);
2795 DSA.addDSA(Var, LoopVarRefExpr, PredeterminedCKind);
2798 assert(isOpenMPLoopDirective(DKind) && "DSA for non-loop vars");
2801 HasErrors |= ISC.CheckCond(For->getCond());
2804 HasErrors |= ISC.CheckInc(For->getInc());
2806 if (ISC.Dependent() || SemaRef.CurContext->isDependentContext() || HasErrors)
2809 // Build the loop's iteration space representation.
2810 ResultIterSpace.PreCond = ISC.BuildPreCond(DSA.getCurScope(), For->getCond());
2811 ResultIterSpace.NumIterations = ISC.BuildNumIterations(
2812 DSA.getCurScope(), /* LimitedType */ isOpenMPWorksharingDirective(DKind));
2813 ResultIterSpace.CounterVar = ISC.BuildCounterVar();
2814 ResultIterSpace.CounterInit = ISC.BuildCounterInit();
2815 ResultIterSpace.CounterStep = ISC.BuildCounterStep();
2816 ResultIterSpace.InitSrcRange = ISC.GetInitSrcRange();
2817 ResultIterSpace.CondSrcRange = ISC.GetConditionSrcRange();
2818 ResultIterSpace.IncSrcRange = ISC.GetIncrementSrcRange();
2819 ResultIterSpace.Subtract = ISC.ShouldSubtractStep();
2821 HasErrors |= (ResultIterSpace.PreCond == nullptr ||
2822 ResultIterSpace.NumIterations == nullptr ||
2823 ResultIterSpace.CounterVar == nullptr ||
2824 ResultIterSpace.CounterInit == nullptr ||
2825 ResultIterSpace.CounterStep == nullptr);
2830 /// \brief Build 'VarRef = Start + Iter * Step'.
2831 static ExprResult BuildCounterUpdate(Sema &SemaRef, Scope *S,
2832 SourceLocation Loc, ExprResult VarRef,
2833 ExprResult Start, ExprResult Iter,
2834 ExprResult Step, bool Subtract) {
2835 // Add parentheses (for debugging purposes only).
2836 Iter = SemaRef.ActOnParenExpr(Loc, Loc, Iter.get());
2837 if (!VarRef.isUsable() || !Start.isUsable() || !Iter.isUsable() ||
2841 ExprResult Update = SemaRef.BuildBinOp(S, Loc, BO_Mul, Iter.get(),
2842 Step.get()->IgnoreImplicit());
2843 if (!Update.isUsable())
2846 // Build 'VarRef = Start + Iter * Step'.
2847 Update = SemaRef.BuildBinOp(S, Loc, (Subtract ? BO_Sub : BO_Add),
2848 Start.get()->IgnoreImplicit(), Update.get());
2849 if (!Update.isUsable())
2852 Update = SemaRef.PerformImplicitConversion(
2853 Update.get(), VarRef.get()->getType(), Sema::AA_Converting, true);
2854 if (!Update.isUsable())
2857 Update = SemaRef.BuildBinOp(S, Loc, BO_Assign, VarRef.get(), Update.get());
2861 /// \brief Convert integer expression \a E to make it have at least \a Bits
2863 static ExprResult WidenIterationCount(unsigned Bits, Expr *E,
2867 auto &C = SemaRef.Context;
2868 QualType OldType = E->getType();
2869 unsigned HasBits = C.getTypeSize(OldType);
2870 if (HasBits >= Bits)
2871 return ExprResult(E);
2872 // OK to convert to signed, because new type has more bits than old.
2873 QualType NewType = C.getIntTypeForBitwidth(Bits, /* Signed */ true);
2874 return SemaRef.PerformImplicitConversion(E, NewType, Sema::AA_Converting,
2878 /// \brief Check if the given expression \a E is a constant integer that fits
2879 /// into \a Bits bits.
2880 static bool FitsInto(unsigned Bits, bool Signed, Expr *E, Sema &SemaRef) {
2883 llvm::APSInt Result;
2884 if (E->isIntegerConstantExpr(Result, SemaRef.Context))
2885 return Signed ? Result.isSignedIntN(Bits) : Result.isIntN(Bits);
2889 /// \brief Called on a for stmt to check itself and nested loops (if any).
2890 /// \return Returns 0 if one of the collapsed stmts is not canonical for loop,
2891 /// number of collapsed loops otherwise.
2893 CheckOpenMPLoop(OpenMPDirectiveKind DKind, Expr *NestedLoopCountExpr,
2894 Stmt *AStmt, Sema &SemaRef, DSAStackTy &DSA,
2895 llvm::DenseMap<VarDecl *, Expr *> &VarsWithImplicitDSA,
2896 OMPLoopDirective::HelperExprs &Built) {
2897 unsigned NestedLoopCount = 1;
2898 if (NestedLoopCountExpr) {
2899 // Found 'collapse' clause - calculate collapse number.
2900 llvm::APSInt Result;
2901 if (NestedLoopCountExpr->EvaluateAsInt(Result, SemaRef.getASTContext()))
2902 NestedLoopCount = Result.getLimitedValue();
2904 // This is helper routine for loop directives (e.g., 'for', 'simd',
2905 // 'for simd', etc.).
2906 SmallVector<LoopIterationSpace, 4> IterSpaces;
2907 IterSpaces.resize(NestedLoopCount);
2908 Stmt *CurStmt = AStmt->IgnoreContainers(/* IgnoreCaptured */ true);
2909 for (unsigned Cnt = 0; Cnt < NestedLoopCount; ++Cnt) {
2910 if (CheckOpenMPIterationSpace(DKind, CurStmt, SemaRef, DSA, Cnt,
2911 NestedLoopCount, NestedLoopCountExpr,
2912 VarsWithImplicitDSA, IterSpaces[Cnt]))
2914 // Move on to the next nested for loop, or to the loop body.
2915 // OpenMP [2.8.1, simd construct, Restrictions]
2916 // All loops associated with the construct must be perfectly nested; that
2917 // is, there must be no intervening code nor any OpenMP directive between
2919 CurStmt = cast<ForStmt>(CurStmt)->getBody()->IgnoreContainers();
2922 Built.clear(/* size */ NestedLoopCount);
2924 if (SemaRef.CurContext->isDependentContext())
2925 return NestedLoopCount;
2927 // An example of what is generated for the following code:
2929 // #pragma omp simd collapse(2)
2930 // for (i = 0; i < NI; ++i)
2931 // for (j = J0; j < NJ; j+=2) {
2935 // We generate the code below.
2936 // Note: the loop body may be outlined in CodeGen.
2937 // Note: some counters may be C++ classes, operator- is used to find number of
2938 // iterations and operator+= to calculate counter value.
2939 // Note: decltype(NumIterations) must be integer type (in 'omp for', only i32
2940 // or i64 is currently supported).
2942 // #define NumIterations (NI * ((NJ - J0 - 1 + 2) / 2))
2943 // for (int[32|64]_t IV = 0; IV < NumIterations; ++IV ) {
2944 // .local.i = IV / ((NJ - J0 - 1 + 2) / 2);
2945 // .local.j = J0 + (IV % ((NJ - J0 - 1 + 2) / 2)) * 2;
2946 // // similar updates for vars in clauses (e.g. 'linear')
2947 // <loop body (using local i and j)>
2949 // i = NI; // assign final values of counters
2953 // Last iteration number is (I1 * I2 * ... In) - 1, where I1, I2 ... In are
2954 // the iteration counts of the collapsed for loops.
2955 // Precondition tests if there is at least one iteration (all conditions are
2957 auto PreCond = ExprResult(IterSpaces[0].PreCond);
2958 auto N0 = IterSpaces[0].NumIterations;
2959 ExprResult LastIteration32 = WidenIterationCount(32 /* Bits */, N0, SemaRef);
2960 ExprResult LastIteration64 = WidenIterationCount(64 /* Bits */, N0, SemaRef);
2962 if (!LastIteration32.isUsable() || !LastIteration64.isUsable())
2963 return NestedLoopCount;
2965 auto &C = SemaRef.Context;
2966 bool AllCountsNeedLessThan32Bits = C.getTypeSize(N0->getType()) < 32;
2968 Scope *CurScope = DSA.getCurScope();
2969 for (unsigned Cnt = 1; Cnt < NestedLoopCount; ++Cnt) {
2970 if (PreCond.isUsable()) {
2971 PreCond = SemaRef.BuildBinOp(CurScope, SourceLocation(), BO_LAnd,
2972 PreCond.get(), IterSpaces[Cnt].PreCond);
2974 auto N = IterSpaces[Cnt].NumIterations;
2975 AllCountsNeedLessThan32Bits &= C.getTypeSize(N->getType()) < 32;
2976 if (LastIteration32.isUsable())
2977 LastIteration32 = SemaRef.BuildBinOp(CurScope, SourceLocation(), BO_Mul,
2978 LastIteration32.get(), N);
2979 if (LastIteration64.isUsable())
2980 LastIteration64 = SemaRef.BuildBinOp(CurScope, SourceLocation(), BO_Mul,
2981 LastIteration64.get(), N);
2984 // Choose either the 32-bit or 64-bit version.
2985 ExprResult LastIteration = LastIteration64;
2986 if (LastIteration32.isUsable() &&
2987 C.getTypeSize(LastIteration32.get()->getType()) == 32 &&
2988 (AllCountsNeedLessThan32Bits || NestedLoopCount == 1 ||
2991 LastIteration32.get()->getType()->hasSignedIntegerRepresentation(),
2992 LastIteration64.get(), SemaRef)))
2993 LastIteration = LastIteration32;
2995 if (!LastIteration.isUsable())
2998 // Save the number of iterations.
2999 ExprResult NumIterations = LastIteration;
3001 LastIteration = SemaRef.BuildBinOp(
3002 CurScope, SourceLocation(), BO_Sub, LastIteration.get(),
3003 SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get());
3004 if (!LastIteration.isUsable())
3008 // Calculate the last iteration number beforehand instead of doing this on
3009 // each iteration. Do not do this if the number of iterations may be kfold-ed.
3010 llvm::APSInt Result;
3012 LastIteration.get()->isIntegerConstantExpr(Result, SemaRef.Context);
3013 ExprResult CalcLastIteration;
3015 SourceLocation SaveLoc;
3017 buildVarDecl(SemaRef, SaveLoc, LastIteration.get()->getType(),
3018 ".omp.last.iteration");
3019 ExprResult SaveRef = buildDeclRefExpr(
3020 SemaRef, SaveVar, LastIteration.get()->getType(), SaveLoc);
3021 CalcLastIteration = SemaRef.BuildBinOp(CurScope, SaveLoc, BO_Assign,
3022 SaveRef.get(), LastIteration.get());
3023 LastIteration = SaveRef;
3025 // Prepare SaveRef + 1.
3026 NumIterations = SemaRef.BuildBinOp(
3027 CurScope, SaveLoc, BO_Add, SaveRef.get(),
3028 SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get());
3029 if (!NumIterations.isUsable())
3033 SourceLocation InitLoc = IterSpaces[0].InitSrcRange.getBegin();
3035 QualType VType = LastIteration.get()->getType();
3036 // Build variables passed into runtime, nesessary for worksharing directives.
3037 ExprResult LB, UB, IL, ST, EUB;
3038 if (isOpenMPWorksharingDirective(DKind)) {
3039 // Lower bound variable, initialized with zero.
3040 VarDecl *LBDecl = buildVarDecl(SemaRef, InitLoc, VType, ".omp.lb");
3041 LB = buildDeclRefExpr(SemaRef, LBDecl, VType, InitLoc);
3042 SemaRef.AddInitializerToDecl(
3043 LBDecl, SemaRef.ActOnIntegerConstant(InitLoc, 0).get(),
3044 /*DirectInit*/ false, /*TypeMayContainAuto*/ false);
3046 // Upper bound variable, initialized with last iteration number.
3047 VarDecl *UBDecl = buildVarDecl(SemaRef, InitLoc, VType, ".omp.ub");
3048 UB = buildDeclRefExpr(SemaRef, UBDecl, VType, InitLoc);
3049 SemaRef.AddInitializerToDecl(UBDecl, LastIteration.get(),
3050 /*DirectInit*/ false,
3051 /*TypeMayContainAuto*/ false);
3053 // A 32-bit variable-flag where runtime returns 1 for the last iteration.
3054 // This will be used to implement clause 'lastprivate'.
3055 QualType Int32Ty = SemaRef.Context.getIntTypeForBitwidth(32, true);
3056 VarDecl *ILDecl = buildVarDecl(SemaRef, InitLoc, Int32Ty, ".omp.is_last");
3057 IL = buildDeclRefExpr(SemaRef, ILDecl, Int32Ty, InitLoc);
3058 SemaRef.AddInitializerToDecl(
3059 ILDecl, SemaRef.ActOnIntegerConstant(InitLoc, 0).get(),
3060 /*DirectInit*/ false, /*TypeMayContainAuto*/ false);
3062 // Stride variable returned by runtime (we initialize it to 1 by default).
3063 VarDecl *STDecl = buildVarDecl(SemaRef, InitLoc, VType, ".omp.stride");
3064 ST = buildDeclRefExpr(SemaRef, STDecl, VType, InitLoc);
3065 SemaRef.AddInitializerToDecl(
3066 STDecl, SemaRef.ActOnIntegerConstant(InitLoc, 1).get(),
3067 /*DirectInit*/ false, /*TypeMayContainAuto*/ false);
3069 // Build expression: UB = min(UB, LastIteration)
3070 // It is nesessary for CodeGen of directives with static scheduling.
3071 ExprResult IsUBGreater = SemaRef.BuildBinOp(CurScope, InitLoc, BO_GT,
3072 UB.get(), LastIteration.get());
3073 ExprResult CondOp = SemaRef.ActOnConditionalOp(
3074 InitLoc, InitLoc, IsUBGreater.get(), LastIteration.get(), UB.get());
3075 EUB = SemaRef.BuildBinOp(CurScope, InitLoc, BO_Assign, UB.get(),
3077 EUB = SemaRef.ActOnFinishFullExpr(EUB.get());
3080 // Build the iteration variable and its initialization before loop.
3084 VarDecl *IVDecl = buildVarDecl(SemaRef, InitLoc, VType, ".omp.iv");
3085 IV = buildDeclRefExpr(SemaRef, IVDecl, VType, InitLoc);
3086 Expr *RHS = isOpenMPWorksharingDirective(DKind)
3088 : SemaRef.ActOnIntegerConstant(SourceLocation(), 0).get();
3089 Init = SemaRef.BuildBinOp(CurScope, InitLoc, BO_Assign, IV.get(), RHS);
3090 Init = SemaRef.ActOnFinishFullExpr(Init.get());
3093 // Loop condition (IV < NumIterations) or (IV <= UB) for worksharing loops.
3094 SourceLocation CondLoc;
3096 isOpenMPWorksharingDirective(DKind)
3097 ? SemaRef.BuildBinOp(CurScope, CondLoc, BO_LE, IV.get(), UB.get())
3098 : SemaRef.BuildBinOp(CurScope, CondLoc, BO_LT, IV.get(),
3099 NumIterations.get());
3101 // Loop increment (IV = IV + 1)
3102 SourceLocation IncLoc;
3104 SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, IV.get(),
3105 SemaRef.ActOnIntegerConstant(IncLoc, 1).get());
3106 if (!Inc.isUsable())
3108 Inc = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, IV.get(), Inc.get());
3109 Inc = SemaRef.ActOnFinishFullExpr(Inc.get());
3110 if (!Inc.isUsable())
3113 // Increments for worksharing loops (LB = LB + ST; UB = UB + ST).
3114 // Used for directives with static scheduling.
3115 ExprResult NextLB, NextUB;
3116 if (isOpenMPWorksharingDirective(DKind)) {
3118 NextLB = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, LB.get(), ST.get());
3119 if (!NextLB.isUsable())
3123 SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, LB.get(), NextLB.get());
3124 NextLB = SemaRef.ActOnFinishFullExpr(NextLB.get());
3125 if (!NextLB.isUsable())
3128 NextUB = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, UB.get(), ST.get());
3129 if (!NextUB.isUsable())
3133 SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, UB.get(), NextUB.get());
3134 NextUB = SemaRef.ActOnFinishFullExpr(NextUB.get());
3135 if (!NextUB.isUsable())
3139 // Build updates and final values of the loop counters.
3140 bool HasErrors = false;
3141 Built.Counters.resize(NestedLoopCount);
3142 Built.Updates.resize(NestedLoopCount);
3143 Built.Finals.resize(NestedLoopCount);
3146 // Go from inner nested loop to outer.
3147 for (int Cnt = NestedLoopCount - 1; Cnt >= 0; --Cnt) {
3148 LoopIterationSpace &IS = IterSpaces[Cnt];
3149 SourceLocation UpdLoc = IS.IncSrcRange.getBegin();
3150 // Build: Iter = (IV / Div) % IS.NumIters
3151 // where Div is product of previous iterations' IS.NumIters.
3153 if (Div.isUsable()) {
3155 SemaRef.BuildBinOp(CurScope, UpdLoc, BO_Div, IV.get(), Div.get());
3158 assert((Cnt == (int)NestedLoopCount - 1) &&
3159 "unusable div expected on first iteration only");
3162 if (Cnt != 0 && Iter.isUsable())
3163 Iter = SemaRef.BuildBinOp(CurScope, UpdLoc, BO_Rem, Iter.get(),
3165 if (!Iter.isUsable()) {
3170 // Build update: IS.CounterVar(Private) = IS.Start + Iter * IS.Step
3171 auto *CounterVar = buildDeclRefExpr(
3172 SemaRef, cast<VarDecl>(cast<DeclRefExpr>(IS.CounterVar)->getDecl()),
3173 IS.CounterVar->getType(), IS.CounterVar->getExprLoc(),
3174 /*RefersToCapture=*/true);
3176 BuildCounterUpdate(SemaRef, CurScope, UpdLoc, CounterVar,
3177 IS.CounterInit, Iter, IS.CounterStep, IS.Subtract);
3178 if (!Update.isUsable()) {
3183 // Build final: IS.CounterVar = IS.Start + IS.NumIters * IS.Step
3184 ExprResult Final = BuildCounterUpdate(
3185 SemaRef, CurScope, UpdLoc, CounterVar, IS.CounterInit,
3186 IS.NumIterations, IS.CounterStep, IS.Subtract);
3187 if (!Final.isUsable()) {
3192 // Build Div for the next iteration: Div <- Div * IS.NumIters
3195 Div = IS.NumIterations;
3197 Div = SemaRef.BuildBinOp(CurScope, UpdLoc, BO_Mul, Div.get(),
3200 // Add parentheses (for debugging purposes only).
3202 Div = SemaRef.ActOnParenExpr(UpdLoc, UpdLoc, Div.get());
3203 if (!Div.isUsable()) {
3208 if (!Update.isUsable() || !Final.isUsable()) {
3213 Built.Counters[Cnt] = IS.CounterVar;
3214 Built.Updates[Cnt] = Update.get();
3215 Built.Finals[Cnt] = Final.get();
3223 Built.IterationVarRef = IV.get();
3224 Built.LastIteration = LastIteration.get();
3225 Built.NumIterations = NumIterations.get();
3226 Built.CalcLastIteration = CalcLastIteration.get();
3227 Built.PreCond = PreCond.get();
3228 Built.Cond = Cond.get();
3229 Built.Init = Init.get();
3230 Built.Inc = Inc.get();
3231 Built.LB = LB.get();
3232 Built.UB = UB.get();
3233 Built.IL = IL.get();
3234 Built.ST = ST.get();
3235 Built.EUB = EUB.get();
3236 Built.NLB = NextLB.get();
3237 Built.NUB = NextUB.get();
3239 return NestedLoopCount;
3242 static Expr *GetCollapseNumberExpr(ArrayRef<OMPClause *> Clauses) {
3243 auto &&CollapseFilter = [](const OMPClause *C) -> bool {
3244 return C->getClauseKind() == OMPC_collapse;
3246 OMPExecutableDirective::filtered_clause_iterator<decltype(CollapseFilter)> I(
3247 Clauses, std::move(CollapseFilter));
3249 return cast<OMPCollapseClause>(*I)->getNumForLoops();
3253 StmtResult Sema::ActOnOpenMPSimdDirective(
3254 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
3255 SourceLocation EndLoc,
3256 llvm::DenseMap<VarDecl *, Expr *> &VarsWithImplicitDSA) {
3257 OMPLoopDirective::HelperExprs B;
3258 // In presence of clause 'collapse', it will define the nested loops number.
3259 unsigned NestedLoopCount =
3260 CheckOpenMPLoop(OMPD_simd, GetCollapseNumberExpr(Clauses), AStmt, *this,
3261 *DSAStack, VarsWithImplicitDSA, B);
3262 if (NestedLoopCount == 0)
3265 assert((CurContext->isDependentContext() || B.builtAll()) &&
3266 "omp simd loop exprs were not built");
3268 if (!CurContext->isDependentContext()) {
3269 // Finalize the clauses that need pre-built expressions for CodeGen.
3270 for (auto C : Clauses) {
3271 if (auto LC = dyn_cast<OMPLinearClause>(C))
3272 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
3273 B.NumIterations, *this, CurScope))
3278 getCurFunction()->setHasBranchProtectedScope();
3279 return OMPSimdDirective::Create(Context, StartLoc, EndLoc, NestedLoopCount,
3283 StmtResult Sema::ActOnOpenMPForDirective(
3284 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
3285 SourceLocation EndLoc,
3286 llvm::DenseMap<VarDecl *, Expr *> &VarsWithImplicitDSA) {
3287 OMPLoopDirective::HelperExprs B;
3288 // In presence of clause 'collapse', it will define the nested loops number.
3289 unsigned NestedLoopCount =
3290 CheckOpenMPLoop(OMPD_for, GetCollapseNumberExpr(Clauses), AStmt, *this,
3291 *DSAStack, VarsWithImplicitDSA, B);
3292 if (NestedLoopCount == 0)
3295 assert((CurContext->isDependentContext() || B.builtAll()) &&
3296 "omp for loop exprs were not built");
3298 getCurFunction()->setHasBranchProtectedScope();
3299 return OMPForDirective::Create(Context, StartLoc, EndLoc, NestedLoopCount,
3303 StmtResult Sema::ActOnOpenMPForSimdDirective(
3304 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
3305 SourceLocation EndLoc,
3306 llvm::DenseMap<VarDecl *, Expr *> &VarsWithImplicitDSA) {
3307 OMPLoopDirective::HelperExprs B;
3308 // In presence of clause 'collapse', it will define the nested loops number.
3309 unsigned NestedLoopCount =
3310 CheckOpenMPLoop(OMPD_for_simd, GetCollapseNumberExpr(Clauses), AStmt,
3311 *this, *DSAStack, VarsWithImplicitDSA, B);
3312 if (NestedLoopCount == 0)
3315 assert((CurContext->isDependentContext() || B.builtAll()) &&
3316 "omp for simd loop exprs were not built");
3318 if (!CurContext->isDependentContext()) {
3319 // Finalize the clauses that need pre-built expressions for CodeGen.
3320 for (auto C : Clauses) {
3321 if (auto LC = dyn_cast<OMPLinearClause>(C))
3322 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
3323 B.NumIterations, *this, CurScope))
3328 getCurFunction()->setHasBranchProtectedScope();
3329 return OMPForSimdDirective::Create(Context, StartLoc, EndLoc, NestedLoopCount,
3333 StmtResult Sema::ActOnOpenMPSectionsDirective(ArrayRef<OMPClause *> Clauses,
3335 SourceLocation StartLoc,
3336 SourceLocation EndLoc) {
3337 assert(AStmt && isa<CapturedStmt>(AStmt) && "Captured statement expected");
3338 auto BaseStmt = AStmt;
3339 while (CapturedStmt *CS = dyn_cast_or_null<CapturedStmt>(BaseStmt))
3340 BaseStmt = CS->getCapturedStmt();
3341 if (auto C = dyn_cast_or_null<CompoundStmt>(BaseStmt)) {
3342 auto S = C->children();
3345 // All associated statements must be '#pragma omp section' except for
3347 for (Stmt *SectionStmt : ++S) {
3348 if (!SectionStmt || !isa<OMPSectionDirective>(SectionStmt)) {
3350 Diag(SectionStmt->getLocStart(),
3351 diag::err_omp_sections_substmt_not_section);
3356 Diag(AStmt->getLocStart(), diag::err_omp_sections_not_compound_stmt);
3360 getCurFunction()->setHasBranchProtectedScope();
3362 return OMPSectionsDirective::Create(Context, StartLoc, EndLoc, Clauses,
3366 StmtResult Sema::ActOnOpenMPSectionDirective(Stmt *AStmt,
3367 SourceLocation StartLoc,
3368 SourceLocation EndLoc) {
3369 assert(AStmt && isa<CapturedStmt>(AStmt) && "Captured statement expected");
3371 getCurFunction()->setHasBranchProtectedScope();
3373 return OMPSectionDirective::Create(Context, StartLoc, EndLoc, AStmt);
3376 StmtResult Sema::ActOnOpenMPSingleDirective(ArrayRef<OMPClause *> Clauses,
3378 SourceLocation StartLoc,
3379 SourceLocation EndLoc) {
3380 assert(AStmt && isa<CapturedStmt>(AStmt) && "Captured statement expected");
3382 getCurFunction()->setHasBranchProtectedScope();
3384 // OpenMP [2.7.3, single Construct, Restrictions]
3385 // The copyprivate clause must not be used with the nowait clause.
3386 OMPClause *Nowait = nullptr;
3387 OMPClause *Copyprivate = nullptr;
3388 for (auto *Clause : Clauses) {
3389 if (Clause->getClauseKind() == OMPC_nowait)
3391 else if (Clause->getClauseKind() == OMPC_copyprivate)
3392 Copyprivate = Clause;
3393 if (Copyprivate && Nowait) {
3394 Diag(Copyprivate->getLocStart(),
3395 diag::err_omp_single_copyprivate_with_nowait);
3396 Diag(Nowait->getLocStart(), diag::note_omp_nowait_clause_here);
3401 return OMPSingleDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt);
3404 StmtResult Sema::ActOnOpenMPMasterDirective(Stmt *AStmt,
3405 SourceLocation StartLoc,
3406 SourceLocation EndLoc) {
3407 assert(AStmt && isa<CapturedStmt>(AStmt) && "Captured statement expected");
3409 getCurFunction()->setHasBranchProtectedScope();
3411 return OMPMasterDirective::Create(Context, StartLoc, EndLoc, AStmt);
3415 Sema::ActOnOpenMPCriticalDirective(const DeclarationNameInfo &DirName,
3416 Stmt *AStmt, SourceLocation StartLoc,
3417 SourceLocation EndLoc) {
3418 assert(AStmt && isa<CapturedStmt>(AStmt) && "Captured statement expected");
3420 getCurFunction()->setHasBranchProtectedScope();
3422 return OMPCriticalDirective::Create(Context, DirName, StartLoc, EndLoc,
3426 StmtResult Sema::ActOnOpenMPParallelForDirective(
3427 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
3428 SourceLocation EndLoc,
3429 llvm::DenseMap<VarDecl *, Expr *> &VarsWithImplicitDSA) {
3430 assert(AStmt && isa<CapturedStmt>(AStmt) && "Captured statement expected");
3431 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
3432 // 1.2.2 OpenMP Language Terminology
3433 // Structured block - An executable statement with a single entry at the
3434 // top and a single exit at the bottom.
3435 // The point of exit cannot be a branch out of the structured block.
3436 // longjmp() and throw() must not violate the entry/exit criteria.
3437 CS->getCapturedDecl()->setNothrow();
3439 OMPLoopDirective::HelperExprs B;
3440 // In presence of clause 'collapse', it will define the nested loops number.
3441 unsigned NestedLoopCount =
3442 CheckOpenMPLoop(OMPD_parallel_for, GetCollapseNumberExpr(Clauses), AStmt,
3443 *this, *DSAStack, VarsWithImplicitDSA, B);
3444 if (NestedLoopCount == 0)
3447 assert((CurContext->isDependentContext() || B.builtAll()) &&
3448 "omp parallel for loop exprs were not built");
3450 getCurFunction()->setHasBranchProtectedScope();
3451 return OMPParallelForDirective::Create(Context, StartLoc, EndLoc,
3452 NestedLoopCount, Clauses, AStmt, B);
3455 StmtResult Sema::ActOnOpenMPParallelForSimdDirective(
3456 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
3457 SourceLocation EndLoc,
3458 llvm::DenseMap<VarDecl *, Expr *> &VarsWithImplicitDSA) {
3459 assert(AStmt && isa<CapturedStmt>(AStmt) && "Captured statement expected");
3460 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
3461 // 1.2.2 OpenMP Language Terminology
3462 // Structured block - An executable statement with a single entry at the
3463 // top and a single exit at the bottom.
3464 // The point of exit cannot be a branch out of the structured block.
3465 // longjmp() and throw() must not violate the entry/exit criteria.
3466 CS->getCapturedDecl()->setNothrow();
3468 OMPLoopDirective::HelperExprs B;
3469 // In presence of clause 'collapse', it will define the nested loops number.
3470 unsigned NestedLoopCount =
3471 CheckOpenMPLoop(OMPD_parallel_for_simd, GetCollapseNumberExpr(Clauses),
3472 AStmt, *this, *DSAStack, VarsWithImplicitDSA, B);
3473 if (NestedLoopCount == 0)
3476 if (!CurContext->isDependentContext()) {
3477 // Finalize the clauses that need pre-built expressions for CodeGen.
3478 for (auto C : Clauses) {
3479 if (auto LC = dyn_cast<OMPLinearClause>(C))
3480 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
3481 B.NumIterations, *this, CurScope))
3486 getCurFunction()->setHasBranchProtectedScope();
3487 return OMPParallelForSimdDirective::Create(
3488 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
3492 Sema::ActOnOpenMPParallelSectionsDirective(ArrayRef<OMPClause *> Clauses,
3493 Stmt *AStmt, SourceLocation StartLoc,
3494 SourceLocation EndLoc) {
3495 assert(AStmt && isa<CapturedStmt>(AStmt) && "Captured statement expected");
3496 auto BaseStmt = AStmt;
3497 while (CapturedStmt *CS = dyn_cast_or_null<CapturedStmt>(BaseStmt))
3498 BaseStmt = CS->getCapturedStmt();
3499 if (auto C = dyn_cast_or_null<CompoundStmt>(BaseStmt)) {
3500 auto S = C->children();
3503 // All associated statements must be '#pragma omp section' except for
3505 for (Stmt *SectionStmt : ++S) {
3506 if (!SectionStmt || !isa<OMPSectionDirective>(SectionStmt)) {
3508 Diag(SectionStmt->getLocStart(),
3509 diag::err_omp_parallel_sections_substmt_not_section);
3514 Diag(AStmt->getLocStart(),
3515 diag::err_omp_parallel_sections_not_compound_stmt);
3519 getCurFunction()->setHasBranchProtectedScope();
3521 return OMPParallelSectionsDirective::Create(Context, StartLoc, EndLoc,
3525 StmtResult Sema::ActOnOpenMPTaskDirective(ArrayRef<OMPClause *> Clauses,
3526 Stmt *AStmt, SourceLocation StartLoc,
3527 SourceLocation EndLoc) {
3528 assert(AStmt && isa<CapturedStmt>(AStmt) && "Captured statement expected");
3529 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
3530 // 1.2.2 OpenMP Language Terminology
3531 // Structured block - An executable statement with a single entry at the
3532 // top and a single exit at the bottom.
3533 // The point of exit cannot be a branch out of the structured block.
3534 // longjmp() and throw() must not violate the entry/exit criteria.
3535 CS->getCapturedDecl()->setNothrow();
3537 getCurFunction()->setHasBranchProtectedScope();
3539 return OMPTaskDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt);
3542 StmtResult Sema::ActOnOpenMPTaskyieldDirective(SourceLocation StartLoc,
3543 SourceLocation EndLoc) {
3544 return OMPTaskyieldDirective::Create(Context, StartLoc, EndLoc);
3547 StmtResult Sema::ActOnOpenMPBarrierDirective(SourceLocation StartLoc,
3548 SourceLocation EndLoc) {
3549 return OMPBarrierDirective::Create(Context, StartLoc, EndLoc);
3552 StmtResult Sema::ActOnOpenMPTaskwaitDirective(SourceLocation StartLoc,
3553 SourceLocation EndLoc) {
3554 return OMPTaskwaitDirective::Create(Context, StartLoc, EndLoc);
3557 StmtResult Sema::ActOnOpenMPTaskgroupDirective(Stmt *AStmt,
3558 SourceLocation StartLoc,
3559 SourceLocation EndLoc) {
3560 assert(AStmt && isa<CapturedStmt>(AStmt) && "Captured statement expected");
3562 getCurFunction()->setHasBranchProtectedScope();
3564 return OMPTaskgroupDirective::Create(Context, StartLoc, EndLoc, AStmt);
3567 StmtResult Sema::ActOnOpenMPFlushDirective(ArrayRef<OMPClause *> Clauses,
3568 SourceLocation StartLoc,
3569 SourceLocation EndLoc) {
3570 assert(Clauses.size() <= 1 && "Extra clauses in flush directive");
3571 return OMPFlushDirective::Create(Context, StartLoc, EndLoc, Clauses);
3574 StmtResult Sema::ActOnOpenMPOrderedDirective(Stmt *AStmt,
3575 SourceLocation StartLoc,
3576 SourceLocation EndLoc) {
3577 assert(AStmt && isa<CapturedStmt>(AStmt) && "Captured statement expected");
3579 getCurFunction()->setHasBranchProtectedScope();
3581 return OMPOrderedDirective::Create(Context, StartLoc, EndLoc, AStmt);
3585 /// \brief Helper class for checking expression in 'omp atomic [update]'
3587 class OpenMPAtomicUpdateChecker {
3588 /// \brief Error results for atomic update expressions.
3589 enum ExprAnalysisErrorCode {
3590 /// \brief A statement is not an expression statement.
3592 /// \brief Expression is not builtin binary or unary operation.
3593 NotABinaryOrUnaryExpression,
3594 /// \brief Unary operation is not post-/pre- increment/decrement operation.
3595 NotAnUnaryIncDecExpression,
3596 /// \brief An expression is not of scalar type.
3598 /// \brief A binary operation is not an assignment operation.
3600 /// \brief RHS part of the binary operation is not a binary expression.
3601 NotABinaryExpression,
3602 /// \brief RHS part is not additive/multiplicative/shift/biwise binary
3605 /// \brief RHS binary operation does not have reference to the updated LHS
3607 NotAnUpdateExpression,
3608 /// \brief No errors is found.
3611 /// \brief Reference to Sema.
3613 /// \brief A location for note diagnostics (when error is found).
3614 SourceLocation NoteLoc;
3615 /// \brief 'x' lvalue part of the source atomic expression.
3617 /// \brief 'expr' rvalue part of the source atomic expression.
3619 /// \brief Helper expression of the form
3620 /// 'OpaqueValueExpr(x) binop OpaqueValueExpr(expr)' or
3621 /// 'OpaqueValueExpr(expr) binop OpaqueValueExpr(x)'.
3623 /// \brief Is 'x' a LHS in a RHS part of full update expression. It is
3624 /// important for non-associative operations.
3625 bool IsXLHSInRHSPart;
3626 BinaryOperatorKind Op;
3627 SourceLocation OpLoc;
3628 /// \brief true if the source expression is a postfix unary operation, false
3629 /// if it is a prefix unary operation.
3630 bool IsPostfixUpdate;
3633 OpenMPAtomicUpdateChecker(Sema &SemaRef)
3634 : SemaRef(SemaRef), X(nullptr), E(nullptr), UpdateExpr(nullptr),
3635 IsXLHSInRHSPart(false), Op(BO_PtrMemD), IsPostfixUpdate(false) {}
3636 /// \brief Check specified statement that it is suitable for 'atomic update'
3637 /// constructs and extract 'x', 'expr' and Operation from the original
3638 /// expression. If DiagId and NoteId == 0, then only check is performed
3639 /// without error notification.
3640 /// \param DiagId Diagnostic which should be emitted if error is found.
3641 /// \param NoteId Diagnostic note for the main error message.
3642 /// \return true if statement is not an update expression, false otherwise.
3643 bool checkStatement(Stmt *S, unsigned DiagId = 0, unsigned NoteId = 0);
3644 /// \brief Return the 'x' lvalue part of the source atomic expression.
3645 Expr *getX() const { return X; }
3646 /// \brief Return the 'expr' rvalue part of the source atomic expression.
3647 Expr *getExpr() const { return E; }
3648 /// \brief Return the update expression used in calculation of the updated
3649 /// value. Always has form 'OpaqueValueExpr(x) binop OpaqueValueExpr(expr)' or
3650 /// 'OpaqueValueExpr(expr) binop OpaqueValueExpr(x)'.
3651 Expr *getUpdateExpr() const { return UpdateExpr; }
3652 /// \brief Return true if 'x' is LHS in RHS part of full update expression,
3653 /// false otherwise.
3654 bool isXLHSInRHSPart() const { return IsXLHSInRHSPart; }
3656 /// \brief true if the source expression is a postfix unary operation, false
3657 /// if it is a prefix unary operation.
3658 bool isPostfixUpdate() const { return IsPostfixUpdate; }
3661 bool checkBinaryOperation(BinaryOperator *AtomicBinOp, unsigned DiagId = 0,
3662 unsigned NoteId = 0);
3666 bool OpenMPAtomicUpdateChecker::checkBinaryOperation(
3667 BinaryOperator *AtomicBinOp, unsigned DiagId, unsigned NoteId) {
3668 ExprAnalysisErrorCode ErrorFound = NoError;
3669 SourceLocation ErrorLoc, NoteLoc;
3670 SourceRange ErrorRange, NoteRange;
3671 // Allowed constructs are:
3672 // x = x binop expr;
3673 // x = expr binop x;
3674 if (AtomicBinOp->getOpcode() == BO_Assign) {
3675 X = AtomicBinOp->getLHS();
3676 if (auto *AtomicInnerBinOp = dyn_cast<BinaryOperator>(
3677 AtomicBinOp->getRHS()->IgnoreParenImpCasts())) {
3678 if (AtomicInnerBinOp->isMultiplicativeOp() ||
3679 AtomicInnerBinOp->isAdditiveOp() || AtomicInnerBinOp->isShiftOp() ||
3680 AtomicInnerBinOp->isBitwiseOp()) {
3681 Op = AtomicInnerBinOp->getOpcode();
3682 OpLoc = AtomicInnerBinOp->getOperatorLoc();
3683 auto *LHS = AtomicInnerBinOp->getLHS();
3684 auto *RHS = AtomicInnerBinOp->getRHS();
3685 llvm::FoldingSetNodeID XId, LHSId, RHSId;
3686 X->IgnoreParenImpCasts()->Profile(XId, SemaRef.getASTContext(),
3687 /*Canonical=*/true);
3688 LHS->IgnoreParenImpCasts()->Profile(LHSId, SemaRef.getASTContext(),
3689 /*Canonical=*/true);
3690 RHS->IgnoreParenImpCasts()->Profile(RHSId, SemaRef.getASTContext(),
3691 /*Canonical=*/true);
3694 IsXLHSInRHSPart = true;
3695 } else if (XId == RHSId) {
3697 IsXLHSInRHSPart = false;
3699 ErrorLoc = AtomicInnerBinOp->getExprLoc();
3700 ErrorRange = AtomicInnerBinOp->getSourceRange();
3701 NoteLoc = X->getExprLoc();
3702 NoteRange = X->getSourceRange();
3703 ErrorFound = NotAnUpdateExpression;
3706 ErrorLoc = AtomicInnerBinOp->getExprLoc();
3707 ErrorRange = AtomicInnerBinOp->getSourceRange();
3708 NoteLoc = AtomicInnerBinOp->getOperatorLoc();
3709 NoteRange = SourceRange(NoteLoc, NoteLoc);
3710 ErrorFound = NotABinaryOperator;
3713 NoteLoc = ErrorLoc = AtomicBinOp->getRHS()->getExprLoc();
3714 NoteRange = ErrorRange = AtomicBinOp->getRHS()->getSourceRange();
3715 ErrorFound = NotABinaryExpression;
3718 ErrorLoc = AtomicBinOp->getExprLoc();
3719 ErrorRange = AtomicBinOp->getSourceRange();
3720 NoteLoc = AtomicBinOp->getOperatorLoc();
3721 NoteRange = SourceRange(NoteLoc, NoteLoc);
3722 ErrorFound = NotAnAssignmentOp;
3724 if (ErrorFound != NoError && DiagId != 0 && NoteId != 0) {
3725 SemaRef.Diag(ErrorLoc, DiagId) << ErrorRange;
3726 SemaRef.Diag(NoteLoc, NoteId) << ErrorFound << NoteRange;
3728 } else if (SemaRef.CurContext->isDependentContext())
3729 E = X = UpdateExpr = nullptr;
3730 return ErrorFound != NoError;
3733 bool OpenMPAtomicUpdateChecker::checkStatement(Stmt *S, unsigned DiagId,
3735 ExprAnalysisErrorCode ErrorFound = NoError;
3736 SourceLocation ErrorLoc, NoteLoc;
3737 SourceRange ErrorRange, NoteRange;
3738 // Allowed constructs are:
3744 // x = x binop expr;
3745 // x = expr binop x;
3746 if (auto *AtomicBody = dyn_cast<Expr>(S)) {
3747 AtomicBody = AtomicBody->IgnoreParenImpCasts();
3748 if (AtomicBody->getType()->isScalarType() ||
3749 AtomicBody->isInstantiationDependent()) {
3750 if (auto *AtomicCompAssignOp = dyn_cast<CompoundAssignOperator>(
3751 AtomicBody->IgnoreParenImpCasts())) {
3752 // Check for Compound Assignment Operation
3753 Op = BinaryOperator::getOpForCompoundAssignment(
3754 AtomicCompAssignOp->getOpcode());
3755 OpLoc = AtomicCompAssignOp->getOperatorLoc();
3756 E = AtomicCompAssignOp->getRHS();
3757 X = AtomicCompAssignOp->getLHS();
3758 IsXLHSInRHSPart = true;
3759 } else if (auto *AtomicBinOp = dyn_cast<BinaryOperator>(
3760 AtomicBody->IgnoreParenImpCasts())) {
3761 // Check for Binary Operation
3762 if(checkBinaryOperation(AtomicBinOp, DiagId, NoteId))
3764 } else if (auto *AtomicUnaryOp =
3765 dyn_cast<UnaryOperator>(AtomicBody->IgnoreParenImpCasts())) {
3766 // Check for Unary Operation
3767 if (AtomicUnaryOp->isIncrementDecrementOp()) {
3768 IsPostfixUpdate = AtomicUnaryOp->isPostfix();
3769 Op = AtomicUnaryOp->isIncrementOp() ? BO_Add : BO_Sub;
3770 OpLoc = AtomicUnaryOp->getOperatorLoc();
3771 X = AtomicUnaryOp->getSubExpr();
3772 E = SemaRef.ActOnIntegerConstant(OpLoc, /*uint64_t Val=*/1).get();
3773 IsXLHSInRHSPart = true;
3775 ErrorFound = NotAnUnaryIncDecExpression;
3776 ErrorLoc = AtomicUnaryOp->getExprLoc();
3777 ErrorRange = AtomicUnaryOp->getSourceRange();
3778 NoteLoc = AtomicUnaryOp->getOperatorLoc();
3779 NoteRange = SourceRange(NoteLoc, NoteLoc);
3782 ErrorFound = NotABinaryOrUnaryExpression;
3783 NoteLoc = ErrorLoc = AtomicBody->getExprLoc();
3784 NoteRange = ErrorRange = AtomicBody->getSourceRange();
3787 ErrorFound = NotAScalarType;
3788 NoteLoc = ErrorLoc = AtomicBody->getLocStart();
3789 NoteRange = ErrorRange = SourceRange(NoteLoc, NoteLoc);
3792 ErrorFound = NotAnExpression;
3793 NoteLoc = ErrorLoc = S->getLocStart();
3794 NoteRange = ErrorRange = SourceRange(NoteLoc, NoteLoc);
3796 if (ErrorFound != NoError && DiagId != 0 && NoteId != 0) {
3797 SemaRef.Diag(ErrorLoc, DiagId) << ErrorRange;
3798 SemaRef.Diag(NoteLoc, NoteId) << ErrorFound << NoteRange;
3800 } else if (SemaRef.CurContext->isDependentContext())
3801 E = X = UpdateExpr = nullptr;
3802 if (ErrorFound == NoError && E && X) {
3803 // Build an update expression of form 'OpaqueValueExpr(x) binop
3804 // OpaqueValueExpr(expr)' or 'OpaqueValueExpr(expr) binop
3805 // OpaqueValueExpr(x)' and then cast it to the type of the 'x' expression.
3806 auto *OVEX = new (SemaRef.getASTContext())
3807 OpaqueValueExpr(X->getExprLoc(), X->getType(), VK_RValue);
3808 auto *OVEExpr = new (SemaRef.getASTContext())
3809 OpaqueValueExpr(E->getExprLoc(), E->getType(), VK_RValue);
3811 SemaRef.CreateBuiltinBinOp(OpLoc, Op, IsXLHSInRHSPart ? OVEX : OVEExpr,
3812 IsXLHSInRHSPart ? OVEExpr : OVEX);
3813 if (Update.isInvalid())
3815 Update = SemaRef.PerformImplicitConversion(Update.get(), X->getType(),
3817 if (Update.isInvalid())
3819 UpdateExpr = Update.get();
3821 return ErrorFound != NoError;
3824 StmtResult Sema::ActOnOpenMPAtomicDirective(ArrayRef<OMPClause *> Clauses,
3826 SourceLocation StartLoc,
3827 SourceLocation EndLoc) {
3828 assert(AStmt && isa<CapturedStmt>(AStmt) && "Captured statement expected");
3829 auto CS = cast<CapturedStmt>(AStmt);
3830 // 1.2.2 OpenMP Language Terminology
3831 // Structured block - An executable statement with a single entry at the
3832 // top and a single exit at the bottom.
3833 // The point of exit cannot be a branch out of the structured block.
3834 // longjmp() and throw() must not violate the entry/exit criteria.
3835 OpenMPClauseKind AtomicKind = OMPC_unknown;
3836 SourceLocation AtomicKindLoc;
3837 for (auto *C : Clauses) {
3838 if (C->getClauseKind() == OMPC_read || C->getClauseKind() == OMPC_write ||
3839 C->getClauseKind() == OMPC_update ||
3840 C->getClauseKind() == OMPC_capture) {
3841 if (AtomicKind != OMPC_unknown) {
3842 Diag(C->getLocStart(), diag::err_omp_atomic_several_clauses)
3843 << SourceRange(C->getLocStart(), C->getLocEnd());
3844 Diag(AtomicKindLoc, diag::note_omp_atomic_previous_clause)
3845 << getOpenMPClauseName(AtomicKind);
3847 AtomicKind = C->getClauseKind();
3848 AtomicKindLoc = C->getLocStart();
3853 auto Body = CS->getCapturedStmt();
3854 if (auto *EWC = dyn_cast<ExprWithCleanups>(Body))
3855 Body = EWC->getSubExpr();
3861 bool IsXLHSInRHSPart = false;
3862 bool IsPostfixUpdate = false;
3863 // OpenMP [2.12.6, atomic Construct]
3864 // In the next expressions:
3865 // * x and v (as applicable) are both l-value expressions with scalar type.
3866 // * During the execution of an atomic region, multiple syntactic
3867 // occurrences of x must designate the same storage location.
3868 // * Neither of v and expr (as applicable) may access the storage location
3870 // * Neither of x and expr (as applicable) may access the storage location
3872 // * expr is an expression with scalar type.
3873 // * binop is one of +, *, -, /, &, ^, |, <<, or >>.
3874 // * binop, binop=, ++, and -- are not overloaded operators.
3875 // * The expression x binop expr must be numerically equivalent to x binop
3876 // (expr). This requirement is satisfied if the operators in expr have
3877 // precedence greater than binop, or by using parentheses around expr or
3878 // subexpressions of expr.
3879 // * The expression expr binop x must be numerically equivalent to (expr)
3880 // binop x. This requirement is satisfied if the operators in expr have
3881 // precedence equal to or greater than binop, or by using parentheses around
3882 // expr or subexpressions of expr.
3883 // * For forms that allow multiple occurrences of x, the number of times
3884 // that x is evaluated is unspecified.
3885 if (AtomicKind == OMPC_read) {
3892 } ErrorFound = NoError;
3893 SourceLocation ErrorLoc, NoteLoc;
3894 SourceRange ErrorRange, NoteRange;
3895 // If clause is read:
3897 if (auto AtomicBody = dyn_cast<Expr>(Body)) {
3899 dyn_cast<BinaryOperator>(AtomicBody->IgnoreParenImpCasts());
3900 if (AtomicBinOp && AtomicBinOp->getOpcode() == BO_Assign) {
3901 X = AtomicBinOp->getRHS()->IgnoreParenImpCasts();
3902 V = AtomicBinOp->getLHS()->IgnoreParenImpCasts();
3903 if ((X->isInstantiationDependent() || X->getType()->isScalarType()) &&
3904 (V->isInstantiationDependent() || V->getType()->isScalarType())) {
3905 if (!X->isLValue() || !V->isLValue()) {
3906 auto NotLValueExpr = X->isLValue() ? V : X;
3907 ErrorFound = NotAnLValue;
3908 ErrorLoc = AtomicBinOp->getExprLoc();
3909 ErrorRange = AtomicBinOp->getSourceRange();
3910 NoteLoc = NotLValueExpr->getExprLoc();
3911 NoteRange = NotLValueExpr->getSourceRange();
3913 } else if (!X->isInstantiationDependent() ||
3914 !V->isInstantiationDependent()) {
3915 auto NotScalarExpr =
3916 (X->isInstantiationDependent() || X->getType()->isScalarType())
3919 ErrorFound = NotAScalarType;
3920 ErrorLoc = AtomicBinOp->getExprLoc();
3921 ErrorRange = AtomicBinOp->getSourceRange();
3922 NoteLoc = NotScalarExpr->getExprLoc();
3923 NoteRange = NotScalarExpr->getSourceRange();
3926 ErrorFound = NotAnAssignmentOp;
3927 ErrorLoc = AtomicBody->getExprLoc();
3928 ErrorRange = AtomicBody->getSourceRange();
3929 NoteLoc = AtomicBinOp ? AtomicBinOp->getOperatorLoc()
3930 : AtomicBody->getExprLoc();
3931 NoteRange = AtomicBinOp ? AtomicBinOp->getSourceRange()
3932 : AtomicBody->getSourceRange();
3935 ErrorFound = NotAnExpression;
3936 NoteLoc = ErrorLoc = Body->getLocStart();
3937 NoteRange = ErrorRange = SourceRange(NoteLoc, NoteLoc);
3939 if (ErrorFound != NoError) {
3940 Diag(ErrorLoc, diag::err_omp_atomic_read_not_expression_statement)
3942 Diag(NoteLoc, diag::note_omp_atomic_read_write) << ErrorFound
3945 } else if (CurContext->isDependentContext())
3947 } else if (AtomicKind == OMPC_write) {
3954 } ErrorFound = NoError;
3955 SourceLocation ErrorLoc, NoteLoc;
3956 SourceRange ErrorRange, NoteRange;
3957 // If clause is write:
3959 if (auto AtomicBody = dyn_cast<Expr>(Body)) {
3961 dyn_cast<BinaryOperator>(AtomicBody->IgnoreParenImpCasts());
3962 if (AtomicBinOp && AtomicBinOp->getOpcode() == BO_Assign) {
3963 X = AtomicBinOp->getLHS();
3964 E = AtomicBinOp->getRHS();
3965 if ((X->isInstantiationDependent() || X->getType()->isScalarType()) &&
3966 (E->isInstantiationDependent() || E->getType()->isScalarType())) {
3967 if (!X->isLValue()) {
3968 ErrorFound = NotAnLValue;
3969 ErrorLoc = AtomicBinOp->getExprLoc();
3970 ErrorRange = AtomicBinOp->getSourceRange();
3971 NoteLoc = X->getExprLoc();
3972 NoteRange = X->getSourceRange();
3974 } else if (!X->isInstantiationDependent() ||
3975 !E->isInstantiationDependent()) {
3976 auto NotScalarExpr =
3977 (X->isInstantiationDependent() || X->getType()->isScalarType())
3980 ErrorFound = NotAScalarType;
3981 ErrorLoc = AtomicBinOp->getExprLoc();
3982 ErrorRange = AtomicBinOp->getSourceRange();
3983 NoteLoc = NotScalarExpr->getExprLoc();
3984 NoteRange = NotScalarExpr->getSourceRange();
3987 ErrorFound = NotAnAssignmentOp;
3988 ErrorLoc = AtomicBody->getExprLoc();
3989 ErrorRange = AtomicBody->getSourceRange();
3990 NoteLoc = AtomicBinOp ? AtomicBinOp->getOperatorLoc()
3991 : AtomicBody->getExprLoc();
3992 NoteRange = AtomicBinOp ? AtomicBinOp->getSourceRange()
3993 : AtomicBody->getSourceRange();
3996 ErrorFound = NotAnExpression;
3997 NoteLoc = ErrorLoc = Body->getLocStart();
3998 NoteRange = ErrorRange = SourceRange(NoteLoc, NoteLoc);
4000 if (ErrorFound != NoError) {
4001 Diag(ErrorLoc, diag::err_omp_atomic_write_not_expression_statement)
4003 Diag(NoteLoc, diag::note_omp_atomic_read_write) << ErrorFound
4006 } else if (CurContext->isDependentContext())
4008 } else if (AtomicKind == OMPC_update || AtomicKind == OMPC_unknown) {
4009 // If clause is update:
4015 // x = x binop expr;
4016 // x = expr binop x;
4017 OpenMPAtomicUpdateChecker Checker(*this);
4018 if (Checker.checkStatement(
4019 Body, (AtomicKind == OMPC_update)
4020 ? diag::err_omp_atomic_update_not_expression_statement
4021 : diag::err_omp_atomic_not_expression_statement,
4022 diag::note_omp_atomic_update))
4024 if (!CurContext->isDependentContext()) {
4025 E = Checker.getExpr();
4027 UE = Checker.getUpdateExpr();
4028 IsXLHSInRHSPart = Checker.isXLHSInRHSPart();
4030 } else if (AtomicKind == OMPC_capture) {
4033 NotACompoundStatement,
4034 NotTwoSubstatements,
4035 NotASpecificExpression,
4037 } ErrorFound = NoError;
4038 SourceLocation ErrorLoc, NoteLoc;
4039 SourceRange ErrorRange, NoteRange;
4040 if (auto *AtomicBody = dyn_cast<Expr>(Body)) {
4041 // If clause is a capture:
4046 // v = x binop= expr;
4047 // v = x = x binop expr;
4048 // v = x = expr binop x;
4050 dyn_cast<BinaryOperator>(AtomicBody->IgnoreParenImpCasts());
4051 if (AtomicBinOp && AtomicBinOp->getOpcode() == BO_Assign) {
4052 V = AtomicBinOp->getLHS();
4053 Body = AtomicBinOp->getRHS()->IgnoreParenImpCasts();
4054 OpenMPAtomicUpdateChecker Checker(*this);
4055 if (Checker.checkStatement(
4056 Body, diag::err_omp_atomic_capture_not_expression_statement,
4057 diag::note_omp_atomic_update))
4059 E = Checker.getExpr();
4061 UE = Checker.getUpdateExpr();
4062 IsXLHSInRHSPart = Checker.isXLHSInRHSPart();
4063 IsPostfixUpdate = Checker.isPostfixUpdate();
4065 ErrorLoc = AtomicBody->getExprLoc();
4066 ErrorRange = AtomicBody->getSourceRange();
4067 NoteLoc = AtomicBinOp ? AtomicBinOp->getOperatorLoc()
4068 : AtomicBody->getExprLoc();
4069 NoteRange = AtomicBinOp ? AtomicBinOp->getSourceRange()
4070 : AtomicBody->getSourceRange();
4071 ErrorFound = NotAnAssignmentOp;
4073 if (ErrorFound != NoError) {
4074 Diag(ErrorLoc, diag::err_omp_atomic_capture_not_expression_statement)
4076 Diag(NoteLoc, diag::note_omp_atomic_capture) << ErrorFound << NoteRange;
4078 } else if (CurContext->isDependentContext()) {
4079 UE = V = E = X = nullptr;
4082 // If clause is a capture:
4083 // { v = x; x = expr; }
4088 // { v = x; x binop= expr; }
4089 // { v = x; x = x binop expr; }
4090 // { v = x; x = expr binop x; }
4095 // { x binop= expr; v = x; }
4096 // { x = x binop expr; v = x; }
4097 // { x = expr binop x; v = x; }
4098 if (auto *CS = dyn_cast<CompoundStmt>(Body)) {
4099 // Check that this is { expr1; expr2; }
4100 if (CS->size() == 2) {
4101 auto *First = CS->body_front();
4102 auto *Second = CS->body_back();
4103 if (auto *EWC = dyn_cast<ExprWithCleanups>(First))
4104 First = EWC->getSubExpr()->IgnoreParenImpCasts();
4105 if (auto *EWC = dyn_cast<ExprWithCleanups>(Second))
4106 Second = EWC->getSubExpr()->IgnoreParenImpCasts();
4107 // Need to find what subexpression is 'v' and what is 'x'.
4108 OpenMPAtomicUpdateChecker Checker(*this);
4109 bool IsUpdateExprFound = !Checker.checkStatement(Second);
4110 BinaryOperator *BinOp = nullptr;
4111 if (IsUpdateExprFound) {
4112 BinOp = dyn_cast<BinaryOperator>(First);
4113 IsUpdateExprFound = BinOp && BinOp->getOpcode() == BO_Assign;
4115 if (IsUpdateExprFound && !CurContext->isDependentContext()) {
4120 // { v = x; x binop= expr; }
4121 // { v = x; x = x binop expr; }
4122 // { v = x; x = expr binop x; }
4123 // Check that the first expression has form v = x.
4124 auto *PossibleX = BinOp->getRHS()->IgnoreParenImpCasts();
4125 llvm::FoldingSetNodeID XId, PossibleXId;
4126 Checker.getX()->Profile(XId, Context, /*Canonical=*/true);
4127 PossibleX->Profile(PossibleXId, Context, /*Canonical=*/true);
4128 IsUpdateExprFound = XId == PossibleXId;
4129 if (IsUpdateExprFound) {
4130 V = BinOp->getLHS();
4132 E = Checker.getExpr();
4133 UE = Checker.getUpdateExpr();
4134 IsXLHSInRHSPart = Checker.isXLHSInRHSPart();
4135 IsPostfixUpdate = true;
4138 if (!IsUpdateExprFound) {
4139 IsUpdateExprFound = !Checker.checkStatement(First);
4141 if (IsUpdateExprFound) {
4142 BinOp = dyn_cast<BinaryOperator>(Second);
4143 IsUpdateExprFound = BinOp && BinOp->getOpcode() == BO_Assign;
4145 if (IsUpdateExprFound && !CurContext->isDependentContext()) {
4150 // { x binop= expr; v = x; }
4151 // { x = x binop expr; v = x; }
4152 // { x = expr binop x; v = x; }
4153 // Check that the second expression has form v = x.
4154 auto *PossibleX = BinOp->getRHS()->IgnoreParenImpCasts();
4155 llvm::FoldingSetNodeID XId, PossibleXId;
4156 Checker.getX()->Profile(XId, Context, /*Canonical=*/true);
4157 PossibleX->Profile(PossibleXId, Context, /*Canonical=*/true);
4158 IsUpdateExprFound = XId == PossibleXId;
4159 if (IsUpdateExprFound) {
4160 V = BinOp->getLHS();
4162 E = Checker.getExpr();
4163 UE = Checker.getUpdateExpr();
4164 IsXLHSInRHSPart = Checker.isXLHSInRHSPart();
4165 IsPostfixUpdate = false;
4169 if (!IsUpdateExprFound) {
4170 // { v = x; x = expr; }
4171 auto *FirstBinOp = dyn_cast<BinaryOperator>(First);
4172 if (!FirstBinOp || FirstBinOp->getOpcode() != BO_Assign) {
4173 ErrorFound = NotAnAssignmentOp;
4174 NoteLoc = ErrorLoc = FirstBinOp ? FirstBinOp->getOperatorLoc()
4175 : First->getLocStart();
4176 NoteRange = ErrorRange = FirstBinOp
4177 ? FirstBinOp->getSourceRange()
4178 : SourceRange(ErrorLoc, ErrorLoc);
4180 auto *SecondBinOp = dyn_cast<BinaryOperator>(Second);
4181 if (!SecondBinOp || SecondBinOp->getOpcode() != BO_Assign) {
4182 ErrorFound = NotAnAssignmentOp;
4183 NoteLoc = ErrorLoc = SecondBinOp ? SecondBinOp->getOperatorLoc()
4184 : Second->getLocStart();
4185 NoteRange = ErrorRange = SecondBinOp
4186 ? SecondBinOp->getSourceRange()
4187 : SourceRange(ErrorLoc, ErrorLoc);
4189 auto *PossibleXRHSInFirst =
4190 FirstBinOp->getRHS()->IgnoreParenImpCasts();
4191 auto *PossibleXLHSInSecond =
4192 SecondBinOp->getLHS()->IgnoreParenImpCasts();
4193 llvm::FoldingSetNodeID X1Id, X2Id;
4194 PossibleXRHSInFirst->Profile(X1Id, Context, /*Canonical=*/true);
4195 PossibleXLHSInSecond->Profile(X2Id, Context,
4196 /*Canonical=*/true);
4197 IsUpdateExprFound = X1Id == X2Id;
4198 if (IsUpdateExprFound) {
4199 V = FirstBinOp->getLHS();
4200 X = SecondBinOp->getLHS();
4201 E = SecondBinOp->getRHS();
4203 IsXLHSInRHSPart = false;
4204 IsPostfixUpdate = true;
4206 ErrorFound = NotASpecificExpression;
4207 ErrorLoc = FirstBinOp->getExprLoc();
4208 ErrorRange = FirstBinOp->getSourceRange();
4209 NoteLoc = SecondBinOp->getLHS()->getExprLoc();
4210 NoteRange = SecondBinOp->getRHS()->getSourceRange();
4216 NoteLoc = ErrorLoc = Body->getLocStart();
4217 NoteRange = ErrorRange =
4218 SourceRange(Body->getLocStart(), Body->getLocStart());
4219 ErrorFound = NotTwoSubstatements;
4222 NoteLoc = ErrorLoc = Body->getLocStart();
4223 NoteRange = ErrorRange =
4224 SourceRange(Body->getLocStart(), Body->getLocStart());
4225 ErrorFound = NotACompoundStatement;
4227 if (ErrorFound != NoError) {
4228 Diag(ErrorLoc, diag::err_omp_atomic_capture_not_compound_statement)
4230 Diag(NoteLoc, diag::note_omp_atomic_capture) << ErrorFound << NoteRange;
4232 } else if (CurContext->isDependentContext()) {
4233 UE = V = E = X = nullptr;
4238 getCurFunction()->setHasBranchProtectedScope();
4240 return OMPAtomicDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt,
4241 X, V, E, UE, IsXLHSInRHSPart,
4245 StmtResult Sema::ActOnOpenMPTargetDirective(ArrayRef<OMPClause *> Clauses,
4247 SourceLocation StartLoc,
4248 SourceLocation EndLoc) {
4249 assert(AStmt && isa<CapturedStmt>(AStmt) && "Captured statement expected");
4251 // OpenMP [2.16, Nesting of Regions]
4252 // If specified, a teams construct must be contained within a target
4253 // construct. That target construct must contain no statements or directives
4254 // outside of the teams construct.
4255 if (DSAStack->hasInnerTeamsRegion()) {
4256 auto S = AStmt->IgnoreContainers(/*IgnoreCaptured*/ true);
4257 bool OMPTeamsFound = true;
4258 if (auto *CS = dyn_cast<CompoundStmt>(S)) {
4259 auto I = CS->body_begin();
4260 while (I != CS->body_end()) {
4261 auto OED = dyn_cast<OMPExecutableDirective>(*I);
4262 if (!OED || !isOpenMPTeamsDirective(OED->getDirectiveKind())) {
4263 OMPTeamsFound = false;
4268 assert(I != CS->body_end() && "Not found statement");
4271 if (!OMPTeamsFound) {
4272 Diag(StartLoc, diag::err_omp_target_contains_not_only_teams);
4273 Diag(DSAStack->getInnerTeamsRegionLoc(),
4274 diag::note_omp_nested_teams_construct_here);
4275 Diag(S->getLocStart(), diag::note_omp_nested_statement_here)
4276 << isa<OMPExecutableDirective>(S);
4281 getCurFunction()->setHasBranchProtectedScope();
4283 return OMPTargetDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt);
4286 StmtResult Sema::ActOnOpenMPTeamsDirective(ArrayRef<OMPClause *> Clauses,
4287 Stmt *AStmt, SourceLocation StartLoc,
4288 SourceLocation EndLoc) {
4289 assert(AStmt && isa<CapturedStmt>(AStmt) && "Captured statement expected");
4290 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
4291 // 1.2.2 OpenMP Language Terminology
4292 // Structured block - An executable statement with a single entry at the
4293 // top and a single exit at the bottom.
4294 // The point of exit cannot be a branch out of the structured block.
4295 // longjmp() and throw() must not violate the entry/exit criteria.
4296 CS->getCapturedDecl()->setNothrow();
4298 getCurFunction()->setHasBranchProtectedScope();
4300 return OMPTeamsDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt);
4304 Sema::ActOnOpenMPCancellationPointDirective(SourceLocation StartLoc,
4305 SourceLocation EndLoc,
4306 OpenMPDirectiveKind CancelRegion) {
4307 if (CancelRegion != OMPD_parallel && CancelRegion != OMPD_for &&
4308 CancelRegion != OMPD_sections && CancelRegion != OMPD_taskgroup) {
4309 Diag(StartLoc, diag::err_omp_wrong_cancel_region)
4310 << getOpenMPDirectiveName(CancelRegion);
4313 if (DSAStack->isParentNowaitRegion()) {
4314 Diag(StartLoc, diag::err_omp_parent_cancel_region_nowait) << 0;
4317 if (DSAStack->isParentOrderedRegion()) {
4318 Diag(StartLoc, diag::err_omp_parent_cancel_region_ordered) << 0;
4321 return OMPCancellationPointDirective::Create(Context, StartLoc, EndLoc,
4325 StmtResult Sema::ActOnOpenMPCancelDirective(SourceLocation StartLoc,
4326 SourceLocation EndLoc,
4327 OpenMPDirectiveKind CancelRegion) {
4328 if (CancelRegion != OMPD_parallel && CancelRegion != OMPD_for &&
4329 CancelRegion != OMPD_sections && CancelRegion != OMPD_taskgroup) {
4330 Diag(StartLoc, diag::err_omp_wrong_cancel_region)
4331 << getOpenMPDirectiveName(CancelRegion);
4334 if (DSAStack->isParentNowaitRegion()) {
4335 Diag(StartLoc, diag::err_omp_parent_cancel_region_nowait) << 1;
4338 if (DSAStack->isParentOrderedRegion()) {
4339 Diag(StartLoc, diag::err_omp_parent_cancel_region_ordered) << 1;
4342 return OMPCancelDirective::Create(Context, StartLoc, EndLoc, CancelRegion);
4345 OMPClause *Sema::ActOnOpenMPSingleExprClause(OpenMPClauseKind Kind, Expr *Expr,
4346 SourceLocation StartLoc,
4347 SourceLocation LParenLoc,
4348 SourceLocation EndLoc) {
4349 OMPClause *Res = nullptr;
4352 Res = ActOnOpenMPIfClause(Expr, StartLoc, LParenLoc, EndLoc);
4355 Res = ActOnOpenMPFinalClause(Expr, StartLoc, LParenLoc, EndLoc);
4357 case OMPC_num_threads:
4358 Res = ActOnOpenMPNumThreadsClause(Expr, StartLoc, LParenLoc, EndLoc);
4361 Res = ActOnOpenMPSafelenClause(Expr, StartLoc, LParenLoc, EndLoc);
4364 Res = ActOnOpenMPCollapseClause(Expr, StartLoc, LParenLoc, EndLoc);
4367 case OMPC_proc_bind:
4370 case OMPC_firstprivate:
4371 case OMPC_lastprivate:
4373 case OMPC_reduction:
4377 case OMPC_copyprivate:
4381 case OMPC_mergeable:
4382 case OMPC_threadprivate:
4391 llvm_unreachable("Clause is not allowed.");
4396 OMPClause *Sema::ActOnOpenMPIfClause(Expr *Condition, SourceLocation StartLoc,
4397 SourceLocation LParenLoc,
4398 SourceLocation EndLoc) {
4399 Expr *ValExpr = Condition;
4400 if (!Condition->isValueDependent() && !Condition->isTypeDependent() &&
4401 !Condition->isInstantiationDependent() &&
4402 !Condition->containsUnexpandedParameterPack()) {
4403 ExprResult Val = ActOnBooleanCondition(DSAStack->getCurScope(),
4404 Condition->getExprLoc(), Condition);
4405 if (Val.isInvalid())
4408 ValExpr = Val.get();
4411 return new (Context) OMPIfClause(ValExpr, StartLoc, LParenLoc, EndLoc);
4414 OMPClause *Sema::ActOnOpenMPFinalClause(Expr *Condition,
4415 SourceLocation StartLoc,
4416 SourceLocation LParenLoc,
4417 SourceLocation EndLoc) {
4418 Expr *ValExpr = Condition;
4419 if (!Condition->isValueDependent() && !Condition->isTypeDependent() &&
4420 !Condition->isInstantiationDependent() &&
4421 !Condition->containsUnexpandedParameterPack()) {
4422 ExprResult Val = ActOnBooleanCondition(DSAStack->getCurScope(),
4423 Condition->getExprLoc(), Condition);
4424 if (Val.isInvalid())
4427 ValExpr = Val.get();
4430 return new (Context) OMPFinalClause(ValExpr, StartLoc, LParenLoc, EndLoc);
4432 ExprResult Sema::PerformOpenMPImplicitIntegerConversion(SourceLocation Loc,
4437 class IntConvertDiagnoser : public ICEConvertDiagnoser {
4439 IntConvertDiagnoser()
4440 : ICEConvertDiagnoser(/*AllowScopedEnumerations*/ false, false, true) {}
4441 SemaDiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc,
4442 QualType T) override {
4443 return S.Diag(Loc, diag::err_omp_not_integral) << T;
4445 SemaDiagnosticBuilder diagnoseIncomplete(Sema &S, SourceLocation Loc,
4446 QualType T) override {
4447 return S.Diag(Loc, diag::err_omp_incomplete_type) << T;
4449 SemaDiagnosticBuilder diagnoseExplicitConv(Sema &S, SourceLocation Loc,
4451 QualType ConvTy) override {
4452 return S.Diag(Loc, diag::err_omp_explicit_conversion) << T << ConvTy;
4454 SemaDiagnosticBuilder noteExplicitConv(Sema &S, CXXConversionDecl *Conv,
4455 QualType ConvTy) override {
4456 return S.Diag(Conv->getLocation(), diag::note_omp_conversion_here)
4457 << ConvTy->isEnumeralType() << ConvTy;
4459 SemaDiagnosticBuilder diagnoseAmbiguous(Sema &S, SourceLocation Loc,
4460 QualType T) override {
4461 return S.Diag(Loc, diag::err_omp_ambiguous_conversion) << T;
4463 SemaDiagnosticBuilder noteAmbiguous(Sema &S, CXXConversionDecl *Conv,
4464 QualType ConvTy) override {
4465 return S.Diag(Conv->getLocation(), diag::note_omp_conversion_here)
4466 << ConvTy->isEnumeralType() << ConvTy;
4468 SemaDiagnosticBuilder diagnoseConversion(Sema &, SourceLocation, QualType,
4469 QualType) override {
4470 llvm_unreachable("conversion functions are permitted");
4473 return PerformContextualImplicitConversion(Loc, Op, ConvertDiagnoser);
4476 OMPClause *Sema::ActOnOpenMPNumThreadsClause(Expr *NumThreads,
4477 SourceLocation StartLoc,
4478 SourceLocation LParenLoc,
4479 SourceLocation EndLoc) {
4480 Expr *ValExpr = NumThreads;
4481 if (!NumThreads->isValueDependent() && !NumThreads->isTypeDependent() &&
4482 !NumThreads->containsUnexpandedParameterPack()) {
4483 SourceLocation NumThreadsLoc = NumThreads->getLocStart();
4485 PerformOpenMPImplicitIntegerConversion(NumThreadsLoc, NumThreads);
4486 if (Val.isInvalid())
4489 ValExpr = Val.get();
4491 // OpenMP [2.5, Restrictions]
4492 // The num_threads expression must evaluate to a positive integer value.
4493 llvm::APSInt Result;
4494 if (ValExpr->isIntegerConstantExpr(Result, Context) && Result.isSigned() &&
4495 !Result.isStrictlyPositive()) {
4496 Diag(NumThreadsLoc, diag::err_omp_negative_expression_in_clause)
4497 << "num_threads" << NumThreads->getSourceRange();
4502 return new (Context)
4503 OMPNumThreadsClause(ValExpr, StartLoc, LParenLoc, EndLoc);
4506 ExprResult Sema::VerifyPositiveIntegerConstantInClause(Expr *E,
4507 OpenMPClauseKind CKind) {
4510 if (E->isValueDependent() || E->isTypeDependent() ||
4511 E->isInstantiationDependent() || E->containsUnexpandedParameterPack())
4513 llvm::APSInt Result;
4514 ExprResult ICE = VerifyIntegerConstantExpression(E, &Result);
4515 if (ICE.isInvalid())
4517 if (!Result.isStrictlyPositive()) {
4518 Diag(E->getExprLoc(), diag::err_omp_negative_expression_in_clause)
4519 << getOpenMPClauseName(CKind) << E->getSourceRange();
4522 if (CKind == OMPC_aligned && !Result.isPowerOf2()) {
4523 Diag(E->getExprLoc(), diag::warn_omp_alignment_not_power_of_two)
4524 << E->getSourceRange();
4527 if (CKind == OMPC_collapse) {
4528 DSAStack->setCollapseNumber(Result.getExtValue());
4533 OMPClause *Sema::ActOnOpenMPSafelenClause(Expr *Len, SourceLocation StartLoc,
4534 SourceLocation LParenLoc,
4535 SourceLocation EndLoc) {
4536 // OpenMP [2.8.1, simd construct, Description]
4537 // The parameter of the safelen clause must be a constant
4538 // positive integer expression.
4539 ExprResult Safelen = VerifyPositiveIntegerConstantInClause(Len, OMPC_safelen);
4540 if (Safelen.isInvalid())
4542 return new (Context)
4543 OMPSafelenClause(Safelen.get(), StartLoc, LParenLoc, EndLoc);
4546 OMPClause *Sema::ActOnOpenMPCollapseClause(Expr *NumForLoops,
4547 SourceLocation StartLoc,
4548 SourceLocation LParenLoc,
4549 SourceLocation EndLoc) {
4550 // OpenMP [2.7.1, loop construct, Description]
4551 // OpenMP [2.8.1, simd construct, Description]
4552 // OpenMP [2.9.6, distribute construct, Description]
4553 // The parameter of the collapse clause must be a constant
4554 // positive integer expression.
4555 ExprResult NumForLoopsResult =
4556 VerifyPositiveIntegerConstantInClause(NumForLoops, OMPC_collapse);
4557 if (NumForLoopsResult.isInvalid())
4559 return new (Context)
4560 OMPCollapseClause(NumForLoopsResult.get(), StartLoc, LParenLoc, EndLoc);
4563 OMPClause *Sema::ActOnOpenMPSimpleClause(
4564 OpenMPClauseKind Kind, unsigned Argument, SourceLocation ArgumentLoc,
4565 SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc) {
4566 OMPClause *Res = nullptr;
4570 ActOnOpenMPDefaultClause(static_cast<OpenMPDefaultClauseKind>(Argument),
4571 ArgumentLoc, StartLoc, LParenLoc, EndLoc);
4573 case OMPC_proc_bind:
4574 Res = ActOnOpenMPProcBindClause(
4575 static_cast<OpenMPProcBindClauseKind>(Argument), ArgumentLoc, StartLoc,
4580 case OMPC_num_threads:
4585 case OMPC_firstprivate:
4586 case OMPC_lastprivate:
4588 case OMPC_reduction:
4592 case OMPC_copyprivate:
4596 case OMPC_mergeable:
4597 case OMPC_threadprivate:
4606 llvm_unreachable("Clause is not allowed.");
4611 OMPClause *Sema::ActOnOpenMPDefaultClause(OpenMPDefaultClauseKind Kind,
4612 SourceLocation KindKwLoc,
4613 SourceLocation StartLoc,
4614 SourceLocation LParenLoc,
4615 SourceLocation EndLoc) {
4616 if (Kind == OMPC_DEFAULT_unknown) {
4618 static_assert(OMPC_DEFAULT_unknown > 0,
4619 "OMPC_DEFAULT_unknown not greater than 0");
4620 std::string Sep(", ");
4621 for (unsigned i = 0; i < OMPC_DEFAULT_unknown; ++i) {
4623 Values += getOpenMPSimpleClauseTypeName(OMPC_default, i);
4626 case OMPC_DEFAULT_unknown - 2:
4629 case OMPC_DEFAULT_unknown - 1:
4636 Diag(KindKwLoc, diag::err_omp_unexpected_clause_value)
4637 << Values << getOpenMPClauseName(OMPC_default);
4641 case OMPC_DEFAULT_none:
4642 DSAStack->setDefaultDSANone(KindKwLoc);
4644 case OMPC_DEFAULT_shared:
4645 DSAStack->setDefaultDSAShared(KindKwLoc);
4647 case OMPC_DEFAULT_unknown:
4648 llvm_unreachable("Clause kind is not allowed.");
4651 return new (Context)
4652 OMPDefaultClause(Kind, KindKwLoc, StartLoc, LParenLoc, EndLoc);
4655 OMPClause *Sema::ActOnOpenMPProcBindClause(OpenMPProcBindClauseKind Kind,
4656 SourceLocation KindKwLoc,
4657 SourceLocation StartLoc,
4658 SourceLocation LParenLoc,
4659 SourceLocation EndLoc) {
4660 if (Kind == OMPC_PROC_BIND_unknown) {
4662 std::string Sep(", ");
4663 for (unsigned i = 0; i < OMPC_PROC_BIND_unknown; ++i) {
4665 Values += getOpenMPSimpleClauseTypeName(OMPC_proc_bind, i);
4668 case OMPC_PROC_BIND_unknown - 2:
4671 case OMPC_PROC_BIND_unknown - 1:
4678 Diag(KindKwLoc, diag::err_omp_unexpected_clause_value)
4679 << Values << getOpenMPClauseName(OMPC_proc_bind);
4682 return new (Context)
4683 OMPProcBindClause(Kind, KindKwLoc, StartLoc, LParenLoc, EndLoc);
4686 OMPClause *Sema::ActOnOpenMPSingleExprWithArgClause(
4687 OpenMPClauseKind Kind, unsigned Argument, Expr *Expr,
4688 SourceLocation StartLoc, SourceLocation LParenLoc,
4689 SourceLocation ArgumentLoc, SourceLocation CommaLoc,
4690 SourceLocation EndLoc) {
4691 OMPClause *Res = nullptr;
4694 Res = ActOnOpenMPScheduleClause(
4695 static_cast<OpenMPScheduleClauseKind>(Argument), Expr, StartLoc,
4696 LParenLoc, ArgumentLoc, CommaLoc, EndLoc);
4700 case OMPC_num_threads:
4704 case OMPC_proc_bind:
4706 case OMPC_firstprivate:
4707 case OMPC_lastprivate:
4709 case OMPC_reduction:
4713 case OMPC_copyprivate:
4717 case OMPC_mergeable:
4718 case OMPC_threadprivate:
4727 llvm_unreachable("Clause is not allowed.");
4732 OMPClause *Sema::ActOnOpenMPScheduleClause(
4733 OpenMPScheduleClauseKind Kind, Expr *ChunkSize, SourceLocation StartLoc,
4734 SourceLocation LParenLoc, SourceLocation KindLoc, SourceLocation CommaLoc,
4735 SourceLocation EndLoc) {
4736 if (Kind == OMPC_SCHEDULE_unknown) {
4738 std::string Sep(", ");
4739 for (unsigned i = 0; i < OMPC_SCHEDULE_unknown; ++i) {
4741 Values += getOpenMPSimpleClauseTypeName(OMPC_schedule, i);
4744 case OMPC_SCHEDULE_unknown - 2:
4747 case OMPC_SCHEDULE_unknown - 1:
4754 Diag(KindLoc, diag::err_omp_unexpected_clause_value)
4755 << Values << getOpenMPClauseName(OMPC_schedule);
4758 Expr *ValExpr = ChunkSize;
4759 Expr *HelperValExpr = nullptr;
4761 if (!ChunkSize->isValueDependent() && !ChunkSize->isTypeDependent() &&
4762 !ChunkSize->isInstantiationDependent() &&
4763 !ChunkSize->containsUnexpandedParameterPack()) {
4764 SourceLocation ChunkSizeLoc = ChunkSize->getLocStart();
4766 PerformOpenMPImplicitIntegerConversion(ChunkSizeLoc, ChunkSize);
4767 if (Val.isInvalid())
4770 ValExpr = Val.get();
4772 // OpenMP [2.7.1, Restrictions]
4773 // chunk_size must be a loop invariant integer expression with a positive
4775 llvm::APSInt Result;
4776 if (ValExpr->isIntegerConstantExpr(Result, Context)) {
4777 if (Result.isSigned() && !Result.isStrictlyPositive()) {
4778 Diag(ChunkSizeLoc, diag::err_omp_negative_expression_in_clause)
4779 << "schedule" << ChunkSize->getSourceRange();
4782 } else if (isParallelOrTaskRegion(DSAStack->getCurrentDirective())) {
4783 auto *ImpVar = buildVarDecl(*this, ChunkSize->getExprLoc(),
4784 ChunkSize->getType(), ".chunk.");
4785 auto *ImpVarRef = buildDeclRefExpr(*this, ImpVar, ChunkSize->getType(),
4786 ChunkSize->getExprLoc(),
4787 /*RefersToCapture=*/true);
4788 HelperValExpr = ImpVarRef;
4793 return new (Context) OMPScheduleClause(StartLoc, LParenLoc, KindLoc, CommaLoc,
4794 EndLoc, Kind, ValExpr, HelperValExpr);
4797 OMPClause *Sema::ActOnOpenMPClause(OpenMPClauseKind Kind,
4798 SourceLocation StartLoc,
4799 SourceLocation EndLoc) {
4800 OMPClause *Res = nullptr;
4803 Res = ActOnOpenMPOrderedClause(StartLoc, EndLoc);
4806 Res = ActOnOpenMPNowaitClause(StartLoc, EndLoc);
4809 Res = ActOnOpenMPUntiedClause(StartLoc, EndLoc);
4811 case OMPC_mergeable:
4812 Res = ActOnOpenMPMergeableClause(StartLoc, EndLoc);
4815 Res = ActOnOpenMPReadClause(StartLoc, EndLoc);
4818 Res = ActOnOpenMPWriteClause(StartLoc, EndLoc);
4821 Res = ActOnOpenMPUpdateClause(StartLoc, EndLoc);
4824 Res = ActOnOpenMPCaptureClause(StartLoc, EndLoc);
4827 Res = ActOnOpenMPSeqCstClause(StartLoc, EndLoc);
4831 case OMPC_num_threads:
4836 case OMPC_firstprivate:
4837 case OMPC_lastprivate:
4839 case OMPC_reduction:
4843 case OMPC_copyprivate:
4845 case OMPC_proc_bind:
4846 case OMPC_threadprivate:
4850 llvm_unreachable("Clause is not allowed.");
4855 OMPClause *Sema::ActOnOpenMPOrderedClause(SourceLocation StartLoc,
4856 SourceLocation EndLoc) {
4857 DSAStack->setOrderedRegion();
4858 return new (Context) OMPOrderedClause(StartLoc, EndLoc);
4861 OMPClause *Sema::ActOnOpenMPNowaitClause(SourceLocation StartLoc,
4862 SourceLocation EndLoc) {
4863 DSAStack->setNowaitRegion();
4864 return new (Context) OMPNowaitClause(StartLoc, EndLoc);
4867 OMPClause *Sema::ActOnOpenMPUntiedClause(SourceLocation StartLoc,
4868 SourceLocation EndLoc) {
4869 return new (Context) OMPUntiedClause(StartLoc, EndLoc);
4872 OMPClause *Sema::ActOnOpenMPMergeableClause(SourceLocation StartLoc,
4873 SourceLocation EndLoc) {
4874 return new (Context) OMPMergeableClause(StartLoc, EndLoc);
4877 OMPClause *Sema::ActOnOpenMPReadClause(SourceLocation StartLoc,
4878 SourceLocation EndLoc) {
4879 return new (Context) OMPReadClause(StartLoc, EndLoc);
4882 OMPClause *Sema::ActOnOpenMPWriteClause(SourceLocation StartLoc,
4883 SourceLocation EndLoc) {
4884 return new (Context) OMPWriteClause(StartLoc, EndLoc);
4887 OMPClause *Sema::ActOnOpenMPUpdateClause(SourceLocation StartLoc,
4888 SourceLocation EndLoc) {
4889 return new (Context) OMPUpdateClause(StartLoc, EndLoc);
4892 OMPClause *Sema::ActOnOpenMPCaptureClause(SourceLocation StartLoc,
4893 SourceLocation EndLoc) {
4894 return new (Context) OMPCaptureClause(StartLoc, EndLoc);
4897 OMPClause *Sema::ActOnOpenMPSeqCstClause(SourceLocation StartLoc,
4898 SourceLocation EndLoc) {
4899 return new (Context) OMPSeqCstClause(StartLoc, EndLoc);
4902 OMPClause *Sema::ActOnOpenMPVarListClause(
4903 OpenMPClauseKind Kind, ArrayRef<Expr *> VarList, Expr *TailExpr,
4904 SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation ColonLoc,
4905 SourceLocation EndLoc, CXXScopeSpec &ReductionIdScopeSpec,
4906 const DeclarationNameInfo &ReductionId, OpenMPDependClauseKind DepKind,
4907 SourceLocation DepLoc) {
4908 OMPClause *Res = nullptr;
4911 Res = ActOnOpenMPPrivateClause(VarList, StartLoc, LParenLoc, EndLoc);
4913 case OMPC_firstprivate:
4914 Res = ActOnOpenMPFirstprivateClause(VarList, StartLoc, LParenLoc, EndLoc);
4916 case OMPC_lastprivate:
4917 Res = ActOnOpenMPLastprivateClause(VarList, StartLoc, LParenLoc, EndLoc);
4920 Res = ActOnOpenMPSharedClause(VarList, StartLoc, LParenLoc, EndLoc);
4922 case OMPC_reduction:
4923 Res = ActOnOpenMPReductionClause(VarList, StartLoc, LParenLoc, ColonLoc,
4924 EndLoc, ReductionIdScopeSpec, ReductionId);
4927 Res = ActOnOpenMPLinearClause(VarList, TailExpr, StartLoc, LParenLoc,
4931 Res = ActOnOpenMPAlignedClause(VarList, TailExpr, StartLoc, LParenLoc,
4935 Res = ActOnOpenMPCopyinClause(VarList, StartLoc, LParenLoc, EndLoc);
4937 case OMPC_copyprivate:
4938 Res = ActOnOpenMPCopyprivateClause(VarList, StartLoc, LParenLoc, EndLoc);
4941 Res = ActOnOpenMPFlushClause(VarList, StartLoc, LParenLoc, EndLoc);
4944 Res = ActOnOpenMPDependClause(DepKind, DepLoc, ColonLoc, VarList, StartLoc,
4949 case OMPC_num_threads:
4953 case OMPC_proc_bind:
4958 case OMPC_mergeable:
4959 case OMPC_threadprivate:
4966 llvm_unreachable("Clause is not allowed.");
4971 OMPClause *Sema::ActOnOpenMPPrivateClause(ArrayRef<Expr *> VarList,
4972 SourceLocation StartLoc,
4973 SourceLocation LParenLoc,
4974 SourceLocation EndLoc) {
4975 SmallVector<Expr *, 8> Vars;
4976 SmallVector<Expr *, 8> PrivateCopies;
4977 for (auto &RefExpr : VarList) {
4978 assert(RefExpr && "NULL expr in OpenMP private clause.");
4979 if (isa<DependentScopeDeclRefExpr>(RefExpr)) {
4980 // It will be analyzed later.
4981 Vars.push_back(RefExpr);
4982 PrivateCopies.push_back(nullptr);
4986 SourceLocation ELoc = RefExpr->getExprLoc();
4987 // OpenMP [2.1, C/C++]
4988 // A list item is a variable name.
4989 // OpenMP [2.9.3.3, Restrictions, p.1]
4990 // A variable that is part of another variable (as an array or
4991 // structure element) cannot appear in a private clause.
4992 DeclRefExpr *DE = dyn_cast_or_null<DeclRefExpr>(RefExpr);
4993 if (!DE || !isa<VarDecl>(DE->getDecl())) {
4994 Diag(ELoc, diag::err_omp_expected_var_name) << RefExpr->getSourceRange();
4997 Decl *D = DE->getDecl();
4998 VarDecl *VD = cast<VarDecl>(D);
5000 QualType Type = VD->getType();
5001 if (Type->isDependentType() || Type->isInstantiationDependentType()) {
5002 // It will be analyzed later.
5004 PrivateCopies.push_back(nullptr);
5008 // OpenMP [2.9.3.3, Restrictions, C/C++, p.3]
5009 // A variable that appears in a private clause must not have an incomplete
5010 // type or a reference type.
5011 if (RequireCompleteType(ELoc, Type,
5012 diag::err_omp_private_incomplete_type)) {
5015 if (Type->isReferenceType()) {
5016 Diag(ELoc, diag::err_omp_clause_ref_type_arg)
5017 << getOpenMPClauseName(OMPC_private) << Type;
5019 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
5020 Diag(VD->getLocation(),
5021 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
5026 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
5028 // Variables with the predetermined data-sharing attributes may not be
5029 // listed in data-sharing attributes clauses, except for the cases
5030 // listed below. For these exceptions only, listing a predetermined
5031 // variable in a data-sharing attribute clause is allowed and overrides
5032 // the variable's predetermined data-sharing attributes.
5033 DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(VD, false);
5034 if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_private) {
5035 Diag(ELoc, diag::err_omp_wrong_dsa) << getOpenMPClauseName(DVar.CKind)
5036 << getOpenMPClauseName(OMPC_private);
5037 ReportOriginalDSA(*this, DSAStack, VD, DVar);
5041 // Variably modified types are not supported for tasks.
5042 if (!Type->isAnyPointerType() && Type->isVariablyModifiedType() &&
5043 DSAStack->getCurrentDirective() == OMPD_task) {
5044 Diag(ELoc, diag::err_omp_variably_modified_type_not_supported)
5045 << getOpenMPClauseName(OMPC_private) << Type
5046 << getOpenMPDirectiveName(DSAStack->getCurrentDirective());
5048 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
5049 Diag(VD->getLocation(),
5050 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
5055 // OpenMP [2.9.3.3, Restrictions, C/C++, p.1]
5056 // A variable of class type (or array thereof) that appears in a private
5057 // clause requires an accessible, unambiguous default constructor for the
5059 // Generate helper private variable and initialize it with the default
5060 // value. The address of the original variable is replaced by the address of
5061 // the new private variable in CodeGen. This new variable is not added to
5062 // IdResolver, so the code in the OpenMP region uses original variable for
5063 // proper diagnostics.
5064 Type = Type.getUnqualifiedType();
5065 auto VDPrivate = buildVarDecl(*this, DE->getExprLoc(), Type, VD->getName());
5066 ActOnUninitializedDecl(VDPrivate, /*TypeMayContainAuto=*/false);
5067 if (VDPrivate->isInvalidDecl())
5069 auto VDPrivateRefExpr = buildDeclRefExpr(
5070 *this, VDPrivate, DE->getType().getUnqualifiedType(), DE->getExprLoc());
5072 DSAStack->addDSA(VD, DE, OMPC_private);
5074 PrivateCopies.push_back(VDPrivateRefExpr);
5080 return OMPPrivateClause::Create(Context, StartLoc, LParenLoc, EndLoc, Vars,
5085 class DiagsUninitializedSeveretyRAII {
5087 DiagnosticsEngine &Diags;
5088 SourceLocation SavedLoc;
5092 DiagsUninitializedSeveretyRAII(DiagnosticsEngine &Diags, SourceLocation Loc,
5094 : Diags(Diags), SavedLoc(Loc), IsIgnored(IsIgnored) {
5096 Diags.setSeverity(/*Diag*/ diag::warn_uninit_self_reference_in_init,
5097 /*Map*/ diag::Severity::Ignored, Loc);
5100 ~DiagsUninitializedSeveretyRAII() {
5102 Diags.popMappings(SavedLoc);
5107 OMPClause *Sema::ActOnOpenMPFirstprivateClause(ArrayRef<Expr *> VarList,
5108 SourceLocation StartLoc,
5109 SourceLocation LParenLoc,
5110 SourceLocation EndLoc) {
5111 SmallVector<Expr *, 8> Vars;
5112 SmallVector<Expr *, 8> PrivateCopies;
5113 SmallVector<Expr *, 8> Inits;
5114 bool IsImplicitClause =
5115 StartLoc.isInvalid() && LParenLoc.isInvalid() && EndLoc.isInvalid();
5116 auto ImplicitClauseLoc = DSAStack->getConstructLoc();
5118 for (auto &RefExpr : VarList) {
5119 assert(RefExpr && "NULL expr in OpenMP firstprivate clause.");
5120 if (isa<DependentScopeDeclRefExpr>(RefExpr)) {
5121 // It will be analyzed later.
5122 Vars.push_back(RefExpr);
5123 PrivateCopies.push_back(nullptr);
5124 Inits.push_back(nullptr);
5128 SourceLocation ELoc =
5129 IsImplicitClause ? ImplicitClauseLoc : RefExpr->getExprLoc();
5130 // OpenMP [2.1, C/C++]
5131 // A list item is a variable name.
5132 // OpenMP [2.9.3.3, Restrictions, p.1]
5133 // A variable that is part of another variable (as an array or
5134 // structure element) cannot appear in a private clause.
5135 DeclRefExpr *DE = dyn_cast_or_null<DeclRefExpr>(RefExpr);
5136 if (!DE || !isa<VarDecl>(DE->getDecl())) {
5137 Diag(ELoc, diag::err_omp_expected_var_name) << RefExpr->getSourceRange();
5140 Decl *D = DE->getDecl();
5141 VarDecl *VD = cast<VarDecl>(D);
5143 QualType Type = VD->getType();
5144 if (Type->isDependentType() || Type->isInstantiationDependentType()) {
5145 // It will be analyzed later.
5147 PrivateCopies.push_back(nullptr);
5148 Inits.push_back(nullptr);
5152 // OpenMP [2.9.3.3, Restrictions, C/C++, p.3]
5153 // A variable that appears in a private clause must not have an incomplete
5154 // type or a reference type.
5155 if (RequireCompleteType(ELoc, Type,
5156 diag::err_omp_firstprivate_incomplete_type)) {
5159 if (Type->isReferenceType()) {
5160 if (IsImplicitClause) {
5161 Diag(ImplicitClauseLoc,
5162 diag::err_omp_task_predetermined_firstprivate_ref_type_arg)
5164 Diag(RefExpr->getExprLoc(), diag::note_used_here);
5166 Diag(ELoc, diag::err_omp_clause_ref_type_arg)
5167 << getOpenMPClauseName(OMPC_firstprivate) << Type;
5170 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
5171 Diag(VD->getLocation(),
5172 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
5177 // OpenMP [2.9.3.4, Restrictions, C/C++, p.1]
5178 // A variable of class type (or array thereof) that appears in a private
5179 // clause requires an accessible, unambiguous copy constructor for the
5181 auto ElemType = Context.getBaseElementType(Type).getNonReferenceType();
5183 // If an implicit firstprivate variable found it was checked already.
5184 if (!IsImplicitClause) {
5185 DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(VD, false);
5186 bool IsConstant = ElemType.isConstant(Context);
5187 // OpenMP [2.4.13, Data-sharing Attribute Clauses]
5188 // A list item that specifies a given variable may not appear in more
5189 // than one clause on the same directive, except that a variable may be
5190 // specified in both firstprivate and lastprivate clauses.
5191 if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_firstprivate &&
5192 DVar.CKind != OMPC_lastprivate && DVar.RefExpr) {
5193 Diag(ELoc, diag::err_omp_wrong_dsa)
5194 << getOpenMPClauseName(DVar.CKind)
5195 << getOpenMPClauseName(OMPC_firstprivate);
5196 ReportOriginalDSA(*this, DSAStack, VD, DVar);
5200 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
5202 // Variables with the predetermined data-sharing attributes may not be
5203 // listed in data-sharing attributes clauses, except for the cases
5204 // listed below. For these exceptions only, listing a predetermined
5205 // variable in a data-sharing attribute clause is allowed and overrides
5206 // the variable's predetermined data-sharing attributes.
5207 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
5208 // in a Construct, C/C++, p.2]
5209 // Variables with const-qualified type having no mutable member may be
5210 // listed in a firstprivate clause, even if they are static data members.
5211 if (!(IsConstant || VD->isStaticDataMember()) && !DVar.RefExpr &&
5212 DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_shared) {
5213 Diag(ELoc, diag::err_omp_wrong_dsa)
5214 << getOpenMPClauseName(DVar.CKind)
5215 << getOpenMPClauseName(OMPC_firstprivate);
5216 ReportOriginalDSA(*this, DSAStack, VD, DVar);
5220 OpenMPDirectiveKind CurrDir = DSAStack->getCurrentDirective();
5221 // OpenMP [2.9.3.4, Restrictions, p.2]
5222 // A list item that is private within a parallel region must not appear
5223 // in a firstprivate clause on a worksharing construct if any of the
5224 // worksharing regions arising from the worksharing construct ever bind
5225 // to any of the parallel regions arising from the parallel construct.
5226 if (isOpenMPWorksharingDirective(CurrDir) &&
5227 !isOpenMPParallelDirective(CurrDir)) {
5228 DVar = DSAStack->getImplicitDSA(VD, true);
5229 if (DVar.CKind != OMPC_shared &&
5230 (isOpenMPParallelDirective(DVar.DKind) ||
5231 DVar.DKind == OMPD_unknown)) {
5232 Diag(ELoc, diag::err_omp_required_access)
5233 << getOpenMPClauseName(OMPC_firstprivate)
5234 << getOpenMPClauseName(OMPC_shared);
5235 ReportOriginalDSA(*this, DSAStack, VD, DVar);
5239 // OpenMP [2.9.3.4, Restrictions, p.3]
5240 // A list item that appears in a reduction clause of a parallel construct
5241 // must not appear in a firstprivate clause on a worksharing or task
5242 // construct if any of the worksharing or task regions arising from the
5243 // worksharing or task construct ever bind to any of the parallel regions
5244 // arising from the parallel construct.
5245 // OpenMP [2.9.3.4, Restrictions, p.4]
5246 // A list item that appears in a reduction clause in worksharing
5247 // construct must not appear in a firstprivate clause in a task construct
5248 // encountered during execution of any of the worksharing regions arising
5249 // from the worksharing construct.
5250 if (CurrDir == OMPD_task) {
5252 DSAStack->hasInnermostDSA(VD, MatchesAnyClause(OMPC_reduction),
5253 [](OpenMPDirectiveKind K) -> bool {
5254 return isOpenMPParallelDirective(K) ||
5255 isOpenMPWorksharingDirective(K);
5258 if (DVar.CKind == OMPC_reduction &&
5259 (isOpenMPParallelDirective(DVar.DKind) ||
5260 isOpenMPWorksharingDirective(DVar.DKind))) {
5261 Diag(ELoc, diag::err_omp_parallel_reduction_in_task_firstprivate)
5262 << getOpenMPDirectiveName(DVar.DKind);
5263 ReportOriginalDSA(*this, DSAStack, VD, DVar);
5269 // Variably modified types are not supported for tasks.
5270 if (!Type->isAnyPointerType() && Type->isVariablyModifiedType() &&
5271 DSAStack->getCurrentDirective() == OMPD_task) {
5272 Diag(ELoc, diag::err_omp_variably_modified_type_not_supported)
5273 << getOpenMPClauseName(OMPC_firstprivate) << Type
5274 << getOpenMPDirectiveName(DSAStack->getCurrentDirective());
5276 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
5277 Diag(VD->getLocation(),
5278 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
5283 Type = Type.getUnqualifiedType();
5284 auto VDPrivate = buildVarDecl(*this, ELoc, Type, VD->getName());
5285 // Generate helper private variable and initialize it with the value of the
5286 // original variable. The address of the original variable is replaced by
5287 // the address of the new private variable in the CodeGen. This new variable
5288 // is not added to IdResolver, so the code in the OpenMP region uses
5289 // original variable for proper diagnostics and variable capturing.
5290 Expr *VDInitRefExpr = nullptr;
5291 // For arrays generate initializer for single element and replace it by the
5292 // original array element in CodeGen.
5293 if (Type->isArrayType()) {
5295 buildVarDecl(*this, DE->getExprLoc(), ElemType, VD->getName());
5296 VDInitRefExpr = buildDeclRefExpr(*this, VDInit, ElemType, ELoc);
5297 auto Init = DefaultLvalueConversion(VDInitRefExpr).get();
5298 ElemType = ElemType.getUnqualifiedType();
5299 auto *VDInitTemp = buildVarDecl(*this, DE->getLocStart(), ElemType,
5300 ".firstprivate.temp");
5301 InitializedEntity Entity =
5302 InitializedEntity::InitializeVariable(VDInitTemp);
5303 InitializationKind Kind = InitializationKind::CreateCopy(ELoc, ELoc);
5305 InitializationSequence InitSeq(*this, Entity, Kind, Init);
5306 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Init);
5307 if (Result.isInvalid())
5308 VDPrivate->setInvalidDecl();
5310 VDPrivate->setInit(Result.getAs<Expr>());
5313 buildVarDecl(*this, DE->getLocStart(), Type, ".firstprivate.temp");
5315 buildDeclRefExpr(*this, VDInit, DE->getType(), DE->getExprLoc());
5316 AddInitializerToDecl(VDPrivate,
5317 DefaultLvalueConversion(VDInitRefExpr).get(),
5318 /*DirectInit=*/false, /*TypeMayContainAuto=*/false);
5320 if (VDPrivate->isInvalidDecl()) {
5321 if (IsImplicitClause) {
5322 Diag(DE->getExprLoc(),
5323 diag::note_omp_task_predetermined_firstprivate_here);
5327 CurContext->addDecl(VDPrivate);
5328 auto VDPrivateRefExpr = buildDeclRefExpr(
5329 *this, VDPrivate, DE->getType().getUnqualifiedType(), DE->getExprLoc());
5330 DSAStack->addDSA(VD, DE, OMPC_firstprivate);
5332 PrivateCopies.push_back(VDPrivateRefExpr);
5333 Inits.push_back(VDInitRefExpr);
5339 return OMPFirstprivateClause::Create(Context, StartLoc, LParenLoc, EndLoc,
5340 Vars, PrivateCopies, Inits);
5343 OMPClause *Sema::ActOnOpenMPLastprivateClause(ArrayRef<Expr *> VarList,
5344 SourceLocation StartLoc,
5345 SourceLocation LParenLoc,
5346 SourceLocation EndLoc) {
5347 SmallVector<Expr *, 8> Vars;
5348 SmallVector<Expr *, 8> SrcExprs;
5349 SmallVector<Expr *, 8> DstExprs;
5350 SmallVector<Expr *, 8> AssignmentOps;
5351 for (auto &RefExpr : VarList) {
5352 assert(RefExpr && "NULL expr in OpenMP lastprivate clause.");
5353 if (isa<DependentScopeDeclRefExpr>(RefExpr)) {
5354 // It will be analyzed later.
5355 Vars.push_back(RefExpr);
5356 SrcExprs.push_back(nullptr);
5357 DstExprs.push_back(nullptr);
5358 AssignmentOps.push_back(nullptr);
5362 SourceLocation ELoc = RefExpr->getExprLoc();
5363 // OpenMP [2.1, C/C++]
5364 // A list item is a variable name.
5365 // OpenMP [2.14.3.5, Restrictions, p.1]
5366 // A variable that is part of another variable (as an array or structure
5367 // element) cannot appear in a lastprivate clause.
5368 DeclRefExpr *DE = dyn_cast_or_null<DeclRefExpr>(RefExpr);
5369 if (!DE || !isa<VarDecl>(DE->getDecl())) {
5370 Diag(ELoc, diag::err_omp_expected_var_name) << RefExpr->getSourceRange();
5373 Decl *D = DE->getDecl();
5374 VarDecl *VD = cast<VarDecl>(D);
5376 QualType Type = VD->getType();
5377 if (Type->isDependentType() || Type->isInstantiationDependentType()) {
5378 // It will be analyzed later.
5380 SrcExprs.push_back(nullptr);
5381 DstExprs.push_back(nullptr);
5382 AssignmentOps.push_back(nullptr);
5386 // OpenMP [2.14.3.5, Restrictions, C/C++, p.2]
5387 // A variable that appears in a lastprivate clause must not have an
5388 // incomplete type or a reference type.
5389 if (RequireCompleteType(ELoc, Type,
5390 diag::err_omp_lastprivate_incomplete_type)) {
5393 if (Type->isReferenceType()) {
5394 Diag(ELoc, diag::err_omp_clause_ref_type_arg)
5395 << getOpenMPClauseName(OMPC_lastprivate) << Type;
5397 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
5398 Diag(VD->getLocation(),
5399 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
5404 // OpenMP [2.14.1.1, Data-sharing Attribute Rules for Variables Referenced
5406 // Variables with the predetermined data-sharing attributes may not be
5407 // listed in data-sharing attributes clauses, except for the cases
5409 DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(VD, false);
5410 if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_lastprivate &&
5411 DVar.CKind != OMPC_firstprivate &&
5412 (DVar.CKind != OMPC_private || DVar.RefExpr != nullptr)) {
5413 Diag(ELoc, diag::err_omp_wrong_dsa)
5414 << getOpenMPClauseName(DVar.CKind)
5415 << getOpenMPClauseName(OMPC_lastprivate);
5416 ReportOriginalDSA(*this, DSAStack, VD, DVar);
5420 OpenMPDirectiveKind CurrDir = DSAStack->getCurrentDirective();
5421 // OpenMP [2.14.3.5, Restrictions, p.2]
5422 // A list item that is private within a parallel region, or that appears in
5423 // the reduction clause of a parallel construct, must not appear in a
5424 // lastprivate clause on a worksharing construct if any of the corresponding
5425 // worksharing regions ever binds to any of the corresponding parallel
5427 DSAStackTy::DSAVarData TopDVar = DVar;
5428 if (isOpenMPWorksharingDirective(CurrDir) &&
5429 !isOpenMPParallelDirective(CurrDir)) {
5430 DVar = DSAStack->getImplicitDSA(VD, true);
5431 if (DVar.CKind != OMPC_shared) {
5432 Diag(ELoc, diag::err_omp_required_access)
5433 << getOpenMPClauseName(OMPC_lastprivate)
5434 << getOpenMPClauseName(OMPC_shared);
5435 ReportOriginalDSA(*this, DSAStack, VD, DVar);
5439 // OpenMP [2.14.3.5, Restrictions, C++, p.1,2]
5440 // A variable of class type (or array thereof) that appears in a
5441 // lastprivate clause requires an accessible, unambiguous default
5442 // constructor for the class type, unless the list item is also specified
5443 // in a firstprivate clause.
5444 // A variable of class type (or array thereof) that appears in a
5445 // lastprivate clause requires an accessible, unambiguous copy assignment
5446 // operator for the class type.
5447 Type = Context.getBaseElementType(Type).getNonReferenceType();
5448 auto *SrcVD = buildVarDecl(*this, DE->getLocStart(),
5449 Type.getUnqualifiedType(), ".lastprivate.src");
5450 auto *PseudoSrcExpr = buildDeclRefExpr(
5451 *this, SrcVD, Type.getUnqualifiedType(), DE->getExprLoc());
5453 buildVarDecl(*this, DE->getLocStart(), Type, ".lastprivate.dst");
5454 auto *PseudoDstExpr =
5455 buildDeclRefExpr(*this, DstVD, Type, DE->getExprLoc());
5456 // For arrays generate assignment operation for single element and replace
5457 // it by the original array element in CodeGen.
5458 auto AssignmentOp = BuildBinOp(/*S=*/nullptr, DE->getExprLoc(), BO_Assign,
5459 PseudoDstExpr, PseudoSrcExpr);
5460 if (AssignmentOp.isInvalid())
5462 AssignmentOp = ActOnFinishFullExpr(AssignmentOp.get(), DE->getExprLoc(),
5463 /*DiscardedValue=*/true);
5464 if (AssignmentOp.isInvalid())
5467 if (TopDVar.CKind != OMPC_firstprivate)
5468 DSAStack->addDSA(VD, DE, OMPC_lastprivate);
5470 SrcExprs.push_back(PseudoSrcExpr);
5471 DstExprs.push_back(PseudoDstExpr);
5472 AssignmentOps.push_back(AssignmentOp.get());
5478 return OMPLastprivateClause::Create(Context, StartLoc, LParenLoc, EndLoc,
5479 Vars, SrcExprs, DstExprs, AssignmentOps);
5482 OMPClause *Sema::ActOnOpenMPSharedClause(ArrayRef<Expr *> VarList,
5483 SourceLocation StartLoc,
5484 SourceLocation LParenLoc,
5485 SourceLocation EndLoc) {
5486 SmallVector<Expr *, 8> Vars;
5487 for (auto &RefExpr : VarList) {
5488 assert(RefExpr && "NULL expr in OpenMP shared clause.");
5489 if (isa<DependentScopeDeclRefExpr>(RefExpr)) {
5490 // It will be analyzed later.
5491 Vars.push_back(RefExpr);
5495 SourceLocation ELoc = RefExpr->getExprLoc();
5496 // OpenMP [2.1, C/C++]
5497 // A list item is a variable name.
5498 // OpenMP [2.14.3.2, Restrictions, p.1]
5499 // A variable that is part of another variable (as an array or structure
5500 // element) cannot appear in a shared unless it is a static data member
5502 DeclRefExpr *DE = dyn_cast<DeclRefExpr>(RefExpr);
5503 if (!DE || !isa<VarDecl>(DE->getDecl())) {
5504 Diag(ELoc, diag::err_omp_expected_var_name) << RefExpr->getSourceRange();
5507 Decl *D = DE->getDecl();
5508 VarDecl *VD = cast<VarDecl>(D);
5510 QualType Type = VD->getType();
5511 if (Type->isDependentType() || Type->isInstantiationDependentType()) {
5512 // It will be analyzed later.
5517 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
5519 // Variables with the predetermined data-sharing attributes may not be
5520 // listed in data-sharing attributes clauses, except for the cases
5521 // listed below. For these exceptions only, listing a predetermined
5522 // variable in a data-sharing attribute clause is allowed and overrides
5523 // the variable's predetermined data-sharing attributes.
5524 DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(VD, false);
5525 if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_shared &&
5527 Diag(ELoc, diag::err_omp_wrong_dsa) << getOpenMPClauseName(DVar.CKind)
5528 << getOpenMPClauseName(OMPC_shared);
5529 ReportOriginalDSA(*this, DSAStack, VD, DVar);
5533 DSAStack->addDSA(VD, DE, OMPC_shared);
5540 return OMPSharedClause::Create(Context, StartLoc, LParenLoc, EndLoc, Vars);
5544 class DSARefChecker : public StmtVisitor<DSARefChecker, bool> {
5548 bool VisitDeclRefExpr(DeclRefExpr *E) {
5549 if (VarDecl *VD = dyn_cast<VarDecl>(E->getDecl())) {
5550 DSAStackTy::DSAVarData DVar = Stack->getTopDSA(VD, false);
5551 if (DVar.CKind == OMPC_shared && !DVar.RefExpr)
5553 if (DVar.CKind != OMPC_unknown)
5555 DSAStackTy::DSAVarData DVarPrivate =
5556 Stack->hasDSA(VD, isOpenMPPrivate, MatchesAlways(), false);
5557 if (DVarPrivate.CKind != OMPC_unknown)
5563 bool VisitStmt(Stmt *S) {
5564 for (auto Child : S->children()) {
5565 if (Child && Visit(Child))
5570 explicit DSARefChecker(DSAStackTy *S) : Stack(S) {}
5574 OMPClause *Sema::ActOnOpenMPReductionClause(
5575 ArrayRef<Expr *> VarList, SourceLocation StartLoc, SourceLocation LParenLoc,
5576 SourceLocation ColonLoc, SourceLocation EndLoc,
5577 CXXScopeSpec &ReductionIdScopeSpec,
5578 const DeclarationNameInfo &ReductionId) {
5579 // TODO: Allow scope specification search when 'declare reduction' is
5581 assert(ReductionIdScopeSpec.isEmpty() &&
5582 "No support for scoped reduction identifiers yet.");
5584 auto DN = ReductionId.getName();
5585 auto OOK = DN.getCXXOverloadedOperator();
5586 BinaryOperatorKind BOK = BO_Comma;
5588 // OpenMP [2.14.3.6, reduction clause]
5590 // reduction-identifier is either an identifier or one of the following
5591 // operators: +, -, *, &, |, ^, && and ||
5593 // reduction-identifier is either an id-expression or one of the following
5594 // operators: +, -, *, &, |, ^, && and ||
5595 // FIXME: Only 'min' and 'max' identifiers are supported for now.
5622 case OO_Array_Delete:
5631 case OO_GreaterEqual:
5636 case OO_PercentEqual:
5641 case OO_GreaterGreater:
5642 case OO_LessLessEqual:
5643 case OO_GreaterGreaterEqual:
5645 case OO_ExclaimEqual:
5653 case OO_Conditional:
5654 case NUM_OVERLOADED_OPERATORS:
5655 llvm_unreachable("Unexpected reduction identifier");
5657 if (auto II = DN.getAsIdentifierInfo()) {
5658 if (II->isStr("max"))
5660 else if (II->isStr("min"))
5665 SourceRange ReductionIdRange;
5666 if (ReductionIdScopeSpec.isValid()) {
5667 ReductionIdRange.setBegin(ReductionIdScopeSpec.getBeginLoc());
5669 ReductionIdRange.setEnd(ReductionId.getEndLoc());
5670 if (BOK == BO_Comma) {
5671 // Not allowed reduction identifier is found.
5672 Diag(ReductionId.getLocStart(), diag::err_omp_unknown_reduction_identifier)
5673 << ReductionIdRange;
5677 SmallVector<Expr *, 8> Vars;
5678 SmallVector<Expr *, 8> LHSs;
5679 SmallVector<Expr *, 8> RHSs;
5680 SmallVector<Expr *, 8> ReductionOps;
5681 for (auto RefExpr : VarList) {
5682 assert(RefExpr && "nullptr expr in OpenMP reduction clause.");
5683 if (isa<DependentScopeDeclRefExpr>(RefExpr)) {
5684 // It will be analyzed later.
5685 Vars.push_back(RefExpr);
5686 LHSs.push_back(nullptr);
5687 RHSs.push_back(nullptr);
5688 ReductionOps.push_back(nullptr);
5692 if (RefExpr->isTypeDependent() || RefExpr->isValueDependent() ||
5693 RefExpr->isInstantiationDependent() ||
5694 RefExpr->containsUnexpandedParameterPack()) {
5695 // It will be analyzed later.
5696 Vars.push_back(RefExpr);
5697 LHSs.push_back(nullptr);
5698 RHSs.push_back(nullptr);
5699 ReductionOps.push_back(nullptr);
5703 auto ELoc = RefExpr->getExprLoc();
5704 auto ERange = RefExpr->getSourceRange();
5705 // OpenMP [2.1, C/C++]
5706 // A list item is a variable or array section, subject to the restrictions
5707 // specified in Section 2.4 on page 42 and in each of the sections
5708 // describing clauses and directives for which a list appears.
5709 // OpenMP [2.14.3.3, Restrictions, p.1]
5710 // A variable that is part of another variable (as an array or
5711 // structure element) cannot appear in a private clause.
5712 auto DE = dyn_cast<DeclRefExpr>(RefExpr);
5713 if (!DE || !isa<VarDecl>(DE->getDecl())) {
5714 Diag(ELoc, diag::err_omp_expected_var_name) << ERange;
5717 auto D = DE->getDecl();
5718 auto VD = cast<VarDecl>(D);
5719 auto Type = VD->getType();
5720 // OpenMP [2.9.3.3, Restrictions, C/C++, p.3]
5721 // A variable that appears in a private clause must not have an incomplete
5722 // type or a reference type.
5723 if (RequireCompleteType(ELoc, Type,
5724 diag::err_omp_reduction_incomplete_type))
5726 // OpenMP [2.14.3.6, reduction clause, Restrictions]
5727 // Arrays may not appear in a reduction clause.
5728 if (Type.getNonReferenceType()->isArrayType()) {
5729 Diag(ELoc, diag::err_omp_reduction_type_array) << Type << ERange;
5731 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
5732 Diag(VD->getLocation(),
5733 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
5737 // OpenMP [2.14.3.6, reduction clause, Restrictions]
5738 // A list item that appears in a reduction clause must not be
5740 if (Type.getNonReferenceType().isConstant(Context)) {
5741 Diag(ELoc, diag::err_omp_const_variable)
5742 << getOpenMPClauseName(OMPC_reduction) << Type << ERange;
5744 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
5745 Diag(VD->getLocation(),
5746 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
5750 // OpenMP [2.9.3.6, Restrictions, C/C++, p.4]
5751 // If a list-item is a reference type then it must bind to the same object
5752 // for all threads of the team.
5753 VarDecl *VDDef = VD->getDefinition();
5754 if (Type->isReferenceType() && VDDef) {
5755 DSARefChecker Check(DSAStack);
5756 if (Check.Visit(VDDef->getInit())) {
5757 Diag(ELoc, diag::err_omp_reduction_ref_type_arg) << ERange;
5758 Diag(VDDef->getLocation(), diag::note_defined_here) << VDDef;
5762 // OpenMP [2.14.3.6, reduction clause, Restrictions]
5763 // The type of a list item that appears in a reduction clause must be valid
5764 // for the reduction-identifier. For a max or min reduction in C, the type
5765 // of the list item must be an allowed arithmetic data type: char, int,
5766 // float, double, or _Bool, possibly modified with long, short, signed, or
5767 // unsigned. For a max or min reduction in C++, the type of the list item
5768 // must be an allowed arithmetic data type: char, wchar_t, int, float,
5769 // double, or bool, possibly modified with long, short, signed, or unsigned.
5770 if ((BOK == BO_GT || BOK == BO_LT) &&
5771 !(Type->isScalarType() ||
5772 (getLangOpts().CPlusPlus && Type->isArithmeticType()))) {
5773 Diag(ELoc, diag::err_omp_clause_not_arithmetic_type_arg)
5774 << getLangOpts().CPlusPlus;
5776 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
5777 Diag(VD->getLocation(),
5778 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
5782 if ((BOK == BO_OrAssign || BOK == BO_AndAssign || BOK == BO_XorAssign) &&
5783 !getLangOpts().CPlusPlus && Type->isFloatingType()) {
5784 Diag(ELoc, diag::err_omp_clause_floating_type_arg);
5786 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
5787 Diag(VD->getLocation(),
5788 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
5792 // OpenMP [2.14.1.1, Data-sharing Attribute Rules for Variables Referenced
5794 // Variables with the predetermined data-sharing attributes may not be
5795 // listed in data-sharing attributes clauses, except for the cases
5796 // listed below. For these exceptions only, listing a predetermined
5797 // variable in a data-sharing attribute clause is allowed and overrides
5798 // the variable's predetermined data-sharing attributes.
5799 // OpenMP [2.14.3.6, Restrictions, p.3]
5800 // Any number of reduction clauses can be specified on the directive,
5801 // but a list item can appear only once in the reduction clauses for that
5803 DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(VD, false);
5804 if (DVar.CKind == OMPC_reduction) {
5805 Diag(ELoc, diag::err_omp_once_referenced)
5806 << getOpenMPClauseName(OMPC_reduction);
5808 Diag(DVar.RefExpr->getExprLoc(), diag::note_omp_referenced);
5810 } else if (DVar.CKind != OMPC_unknown) {
5811 Diag(ELoc, diag::err_omp_wrong_dsa)
5812 << getOpenMPClauseName(DVar.CKind)
5813 << getOpenMPClauseName(OMPC_reduction);
5814 ReportOriginalDSA(*this, DSAStack, VD, DVar);
5818 // OpenMP [2.14.3.6, Restrictions, p.1]
5819 // A list item that appears in a reduction clause of a worksharing
5820 // construct must be shared in the parallel regions to which any of the
5821 // worksharing regions arising from the worksharing construct bind.
5822 OpenMPDirectiveKind CurrDir = DSAStack->getCurrentDirective();
5823 if (isOpenMPWorksharingDirective(CurrDir) &&
5824 !isOpenMPParallelDirective(CurrDir)) {
5825 DVar = DSAStack->getImplicitDSA(VD, true);
5826 if (DVar.CKind != OMPC_shared) {
5827 Diag(ELoc, diag::err_omp_required_access)
5828 << getOpenMPClauseName(OMPC_reduction)
5829 << getOpenMPClauseName(OMPC_shared);
5830 ReportOriginalDSA(*this, DSAStack, VD, DVar);
5834 Type = Type.getNonLValueExprType(Context).getUnqualifiedType();
5835 auto *LHSVD = buildVarDecl(*this, ELoc, Type, ".reduction.lhs");
5836 auto *RHSVD = buildVarDecl(*this, ELoc, Type, VD->getName());
5837 // Add initializer for private variable.
5838 Expr *Init = nullptr;
5844 // '+', '-', '^', '|', '||' reduction ops - initializer is '0'.
5845 if (Type->isScalarType() || Type->isAnyComplexType()) {
5846 Init = ActOnIntegerConstant(ELoc, /*Val=*/0).get();
5851 if (Type->isScalarType() || Type->isAnyComplexType()) {
5852 // '*' and '&&' reduction ops - initializer is '1'.
5853 Init = ActOnIntegerConstant(ELoc, /*Val=*/1).get();
5857 // '&' reduction op - initializer is '~0'.
5858 QualType OrigType = Type;
5859 if (auto *ComplexTy = OrigType->getAs<ComplexType>()) {
5860 Type = ComplexTy->getElementType();
5862 if (Type->isRealFloatingType()) {
5863 llvm::APFloat InitValue =
5864 llvm::APFloat::getAllOnesValue(Context.getTypeSize(Type),
5866 Init = FloatingLiteral::Create(Context, InitValue, /*isexact=*/true,
5868 } else if (Type->isScalarType()) {
5869 auto Size = Context.getTypeSize(Type);
5870 QualType IntTy = Context.getIntTypeForBitwidth(Size, /*Signed=*/0);
5871 llvm::APInt InitValue = llvm::APInt::getAllOnesValue(Size);
5872 Init = IntegerLiteral::Create(Context, InitValue, IntTy, ELoc);
5874 if (Init && OrigType->isAnyComplexType()) {
5875 // Init = 0xFFFF + 0xFFFFi;
5876 auto *Im = new (Context) ImaginaryLiteral(Init, OrigType);
5877 Init = CreateBuiltinBinOp(ELoc, BO_Add, Init, Im).get();
5884 // 'min' reduction op - initializer is 'Largest representable number in
5885 // the reduction list item type'.
5886 // 'max' reduction op - initializer is 'Least representable number in
5887 // the reduction list item type'.
5888 if (Type->isIntegerType() || Type->isPointerType()) {
5889 bool IsSigned = Type->hasSignedIntegerRepresentation();
5890 auto Size = Context.getTypeSize(Type);
5892 Context.getIntTypeForBitwidth(Size, /*Signed=*/IsSigned);
5893 llvm::APInt InitValue =
5895 ? IsSigned ? llvm::APInt::getSignedMinValue(Size)
5896 : llvm::APInt::getMinValue(Size)
5897 : IsSigned ? llvm::APInt::getSignedMaxValue(Size)
5898 : llvm::APInt::getMaxValue(Size);
5899 Init = IntegerLiteral::Create(Context, InitValue, IntTy, ELoc);
5900 if (Type->isPointerType()) {
5901 // Cast to pointer type.
5902 auto CastExpr = BuildCStyleCastExpr(
5903 SourceLocation(), Context.getTrivialTypeSourceInfo(Type, ELoc),
5904 SourceLocation(), Init);
5905 if (CastExpr.isInvalid())
5907 Init = CastExpr.get();
5909 } else if (Type->isRealFloatingType()) {
5910 llvm::APFloat InitValue = llvm::APFloat::getLargest(
5911 Context.getFloatTypeSemantics(Type), BOK != BO_LT);
5912 Init = FloatingLiteral::Create(Context, InitValue, /*isexact=*/true,
5940 llvm_unreachable("Unexpected reduction operation");
5943 AddInitializerToDecl(RHSVD, Init, /*DirectInit=*/false,
5944 /*TypeMayContainAuto=*/false);
5946 ActOnUninitializedDecl(RHSVD, /*TypeMayContainAuto=*/false);
5948 if (!RHSVD->hasInit()) {
5949 Diag(ELoc, diag::err_omp_reduction_id_not_compatible) << Type
5950 << ReductionIdRange;
5952 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
5953 Diag(VD->getLocation(),
5954 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
5958 auto *LHSDRE = buildDeclRefExpr(*this, LHSVD, Type, ELoc);
5959 auto *RHSDRE = buildDeclRefExpr(*this, RHSVD, Type, ELoc);
5960 ExprResult ReductionOp =
5961 BuildBinOp(DSAStack->getCurScope(), ReductionId.getLocStart(), BOK,
5963 if (ReductionOp.isUsable()) {
5964 if (BOK != BO_LT && BOK != BO_GT) {
5966 BuildBinOp(DSAStack->getCurScope(), ReductionId.getLocStart(),
5967 BO_Assign, LHSDRE, ReductionOp.get());
5969 auto *ConditionalOp = new (Context) ConditionalOperator(
5970 ReductionOp.get(), SourceLocation(), LHSDRE, SourceLocation(),
5971 RHSDRE, Type, VK_LValue, OK_Ordinary);
5973 BuildBinOp(DSAStack->getCurScope(), ReductionId.getLocStart(),
5974 BO_Assign, LHSDRE, ConditionalOp);
5976 if (ReductionOp.isUsable()) {
5977 ReductionOp = ActOnFinishFullExpr(ReductionOp.get());
5980 if (ReductionOp.isInvalid())
5983 DSAStack->addDSA(VD, DE, OMPC_reduction);
5985 LHSs.push_back(LHSDRE);
5986 RHSs.push_back(RHSDRE);
5987 ReductionOps.push_back(ReductionOp.get());
5993 return OMPReductionClause::Create(
5994 Context, StartLoc, LParenLoc, ColonLoc, EndLoc, Vars,
5995 ReductionIdScopeSpec.getWithLocInContext(Context), ReductionId, LHSs,
5996 RHSs, ReductionOps);
5999 OMPClause *Sema::ActOnOpenMPLinearClause(ArrayRef<Expr *> VarList, Expr *Step,
6000 SourceLocation StartLoc,
6001 SourceLocation LParenLoc,
6002 SourceLocation ColonLoc,
6003 SourceLocation EndLoc) {
6004 SmallVector<Expr *, 8> Vars;
6005 SmallVector<Expr *, 8> Inits;
6006 for (auto &RefExpr : VarList) {
6007 assert(RefExpr && "NULL expr in OpenMP linear clause.");
6008 if (isa<DependentScopeDeclRefExpr>(RefExpr)) {
6009 // It will be analyzed later.
6010 Vars.push_back(RefExpr);
6011 Inits.push_back(nullptr);
6015 // OpenMP [2.14.3.7, linear clause]
6016 // A list item that appears in a linear clause is subject to the private
6017 // clause semantics described in Section 2.14.3.3 on page 159 except as
6018 // noted. In addition, the value of the new list item on each iteration
6019 // of the associated loop(s) corresponds to the value of the original
6020 // list item before entering the construct plus the logical number of
6021 // the iteration times linear-step.
6023 SourceLocation ELoc = RefExpr->getExprLoc();
6024 // OpenMP [2.1, C/C++]
6025 // A list item is a variable name.
6026 // OpenMP [2.14.3.3, Restrictions, p.1]
6027 // A variable that is part of another variable (as an array or
6028 // structure element) cannot appear in a private clause.
6029 DeclRefExpr *DE = dyn_cast<DeclRefExpr>(RefExpr);
6030 if (!DE || !isa<VarDecl>(DE->getDecl())) {
6031 Diag(ELoc, diag::err_omp_expected_var_name) << RefExpr->getSourceRange();
6035 VarDecl *VD = cast<VarDecl>(DE->getDecl());
6037 // OpenMP [2.14.3.7, linear clause]
6038 // A list-item cannot appear in more than one linear clause.
6039 // A list-item that appears in a linear clause cannot appear in any
6040 // other data-sharing attribute clause.
6041 DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(VD, false);
6043 Diag(ELoc, diag::err_omp_wrong_dsa) << getOpenMPClauseName(DVar.CKind)
6044 << getOpenMPClauseName(OMPC_linear);
6045 ReportOriginalDSA(*this, DSAStack, VD, DVar);
6049 QualType QType = VD->getType();
6050 if (QType->isDependentType() || QType->isInstantiationDependentType()) {
6051 // It will be analyzed later.
6053 Inits.push_back(nullptr);
6057 // A variable must not have an incomplete type or a reference type.
6058 if (RequireCompleteType(ELoc, QType,
6059 diag::err_omp_linear_incomplete_type)) {
6062 if (QType->isReferenceType()) {
6063 Diag(ELoc, diag::err_omp_clause_ref_type_arg)
6064 << getOpenMPClauseName(OMPC_linear) << QType;
6066 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
6067 Diag(VD->getLocation(),
6068 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
6073 // A list item must not be const-qualified.
6074 if (QType.isConstant(Context)) {
6075 Diag(ELoc, diag::err_omp_const_variable)
6076 << getOpenMPClauseName(OMPC_linear);
6078 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
6079 Diag(VD->getLocation(),
6080 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
6085 // A list item must be of integral or pointer type.
6086 QType = QType.getUnqualifiedType().getCanonicalType();
6087 const Type *Ty = QType.getTypePtrOrNull();
6088 if (!Ty || (!Ty->isDependentType() && !Ty->isIntegralType(Context) &&
6089 !Ty->isPointerType())) {
6090 Diag(ELoc, diag::err_omp_linear_expected_int_or_ptr) << QType;
6092 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
6093 Diag(VD->getLocation(),
6094 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
6099 // Build var to save initial value.
6100 VarDecl *Init = buildVarDecl(*this, ELoc, QType, ".linear.start");
6101 AddInitializerToDecl(Init, DefaultLvalueConversion(DE).get(),
6102 /*DirectInit*/ false, /*TypeMayContainAuto*/ false);
6103 auto InitRef = buildDeclRefExpr(
6104 *this, Init, DE->getType().getUnqualifiedType(), DE->getExprLoc());
6105 DSAStack->addDSA(VD, DE, OMPC_linear);
6107 Inits.push_back(InitRef);
6113 Expr *StepExpr = Step;
6114 Expr *CalcStepExpr = nullptr;
6115 if (Step && !Step->isValueDependent() && !Step->isTypeDependent() &&
6116 !Step->isInstantiationDependent() &&
6117 !Step->containsUnexpandedParameterPack()) {
6118 SourceLocation StepLoc = Step->getLocStart();
6119 ExprResult Val = PerformOpenMPImplicitIntegerConversion(StepLoc, Step);
6120 if (Val.isInvalid())
6122 StepExpr = Val.get();
6124 // Build var to save the step value.
6126 buildVarDecl(*this, StepLoc, StepExpr->getType(), ".linear.step");
6127 ExprResult SaveRef =
6128 buildDeclRefExpr(*this, SaveVar, StepExpr->getType(), StepLoc);
6129 ExprResult CalcStep =
6130 BuildBinOp(CurScope, StepLoc, BO_Assign, SaveRef.get(), StepExpr);
6132 // Warn about zero linear step (it would be probably better specified as
6133 // making corresponding variables 'const').
6134 llvm::APSInt Result;
6135 bool IsConstant = StepExpr->isIntegerConstantExpr(Result, Context);
6136 if (IsConstant && !Result.isNegative() && !Result.isStrictlyPositive())
6137 Diag(StepLoc, diag::warn_omp_linear_step_zero) << Vars[0]
6138 << (Vars.size() > 1);
6139 if (!IsConstant && CalcStep.isUsable()) {
6140 // Calculate the step beforehand instead of doing this on each iteration.
6141 // (This is not used if the number of iterations may be kfold-ed).
6142 CalcStepExpr = CalcStep.get();
6146 return OMPLinearClause::Create(Context, StartLoc, LParenLoc, ColonLoc, EndLoc,
6147 Vars, Inits, StepExpr, CalcStepExpr);
6150 static bool FinishOpenMPLinearClause(OMPLinearClause &Clause, DeclRefExpr *IV,
6151 Expr *NumIterations, Sema &SemaRef,
6153 // Walk the vars and build update/final expressions for the CodeGen.
6154 SmallVector<Expr *, 8> Updates;
6155 SmallVector<Expr *, 8> Finals;
6156 Expr *Step = Clause.getStep();
6157 Expr *CalcStep = Clause.getCalcStep();
6158 // OpenMP [2.14.3.7, linear clause]
6159 // If linear-step is not specified it is assumed to be 1.
6160 if (Step == nullptr)
6161 Step = SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get();
6163 Step = cast<BinaryOperator>(CalcStep)->getLHS();
6164 bool HasErrors = false;
6165 auto CurInit = Clause.inits().begin();
6166 for (auto &RefExpr : Clause.varlists()) {
6167 Expr *InitExpr = *CurInit;
6169 // Build privatized reference to the current linear var.
6170 auto DE = cast<DeclRefExpr>(RefExpr);
6172 buildDeclRefExpr(SemaRef, cast<VarDecl>(DE->getDecl()),
6173 DE->getType().getUnqualifiedType(), DE->getExprLoc(),
6174 /*RefersToCapture=*/true);
6176 // Build update: Var = InitExpr + IV * Step
6178 BuildCounterUpdate(SemaRef, S, RefExpr->getExprLoc(), PrivateRef,
6179 InitExpr, IV, Step, /* Subtract */ false);
6180 Update = SemaRef.ActOnFinishFullExpr(Update.get());
6182 // Build final: Var = InitExpr + NumIterations * Step
6184 BuildCounterUpdate(SemaRef, S, RefExpr->getExprLoc(), PrivateRef,
6185 InitExpr, NumIterations, Step, /* Subtract */ false);
6186 Final = SemaRef.ActOnFinishFullExpr(Final.get());
6187 if (!Update.isUsable() || !Final.isUsable()) {
6188 Updates.push_back(nullptr);
6189 Finals.push_back(nullptr);
6192 Updates.push_back(Update.get());
6193 Finals.push_back(Final.get());
6197 Clause.setUpdates(Updates);
6198 Clause.setFinals(Finals);
6202 OMPClause *Sema::ActOnOpenMPAlignedClause(
6203 ArrayRef<Expr *> VarList, Expr *Alignment, SourceLocation StartLoc,
6204 SourceLocation LParenLoc, SourceLocation ColonLoc, SourceLocation EndLoc) {
6206 SmallVector<Expr *, 8> Vars;
6207 for (auto &RefExpr : VarList) {
6208 assert(RefExpr && "NULL expr in OpenMP aligned clause.");
6209 if (isa<DependentScopeDeclRefExpr>(RefExpr)) {
6210 // It will be analyzed later.
6211 Vars.push_back(RefExpr);
6215 SourceLocation ELoc = RefExpr->getExprLoc();
6216 // OpenMP [2.1, C/C++]
6217 // A list item is a variable name.
6218 DeclRefExpr *DE = dyn_cast<DeclRefExpr>(RefExpr);
6219 if (!DE || !isa<VarDecl>(DE->getDecl())) {
6220 Diag(ELoc, diag::err_omp_expected_var_name) << RefExpr->getSourceRange();
6224 VarDecl *VD = cast<VarDecl>(DE->getDecl());
6226 // OpenMP [2.8.1, simd construct, Restrictions]
6227 // The type of list items appearing in the aligned clause must be
6228 // array, pointer, reference to array, or reference to pointer.
6229 QualType QType = VD->getType();
6230 QType = QType.getNonReferenceType().getUnqualifiedType().getCanonicalType();
6231 const Type *Ty = QType.getTypePtrOrNull();
6232 if (!Ty || (!Ty->isDependentType() && !Ty->isArrayType() &&
6233 !Ty->isPointerType())) {
6234 Diag(ELoc, diag::err_omp_aligned_expected_array_or_ptr)
6235 << QType << getLangOpts().CPlusPlus << RefExpr->getSourceRange();
6237 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
6238 Diag(VD->getLocation(),
6239 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
6244 // OpenMP [2.8.1, simd construct, Restrictions]
6245 // A list-item cannot appear in more than one aligned clause.
6246 if (DeclRefExpr *PrevRef = DSAStack->addUniqueAligned(VD, DE)) {
6247 Diag(ELoc, diag::err_omp_aligned_twice) << RefExpr->getSourceRange();
6248 Diag(PrevRef->getExprLoc(), diag::note_omp_explicit_dsa)
6249 << getOpenMPClauseName(OMPC_aligned);
6256 // OpenMP [2.8.1, simd construct, Description]
6257 // The parameter of the aligned clause, alignment, must be a constant
6258 // positive integer expression.
6259 // If no optional parameter is specified, implementation-defined default
6260 // alignments for SIMD instructions on the target platforms are assumed.
6261 if (Alignment != nullptr) {
6262 ExprResult AlignResult =
6263 VerifyPositiveIntegerConstantInClause(Alignment, OMPC_aligned);
6264 if (AlignResult.isInvalid())
6266 Alignment = AlignResult.get();
6271 return OMPAlignedClause::Create(Context, StartLoc, LParenLoc, ColonLoc,
6272 EndLoc, Vars, Alignment);
6275 OMPClause *Sema::ActOnOpenMPCopyinClause(ArrayRef<Expr *> VarList,
6276 SourceLocation StartLoc,
6277 SourceLocation LParenLoc,
6278 SourceLocation EndLoc) {
6279 SmallVector<Expr *, 8> Vars;
6280 SmallVector<Expr *, 8> SrcExprs;
6281 SmallVector<Expr *, 8> DstExprs;
6282 SmallVector<Expr *, 8> AssignmentOps;
6283 for (auto &RefExpr : VarList) {
6284 assert(RefExpr && "NULL expr in OpenMP copyin clause.");
6285 if (isa<DependentScopeDeclRefExpr>(RefExpr)) {
6286 // It will be analyzed later.
6287 Vars.push_back(RefExpr);
6288 SrcExprs.push_back(nullptr);
6289 DstExprs.push_back(nullptr);
6290 AssignmentOps.push_back(nullptr);
6294 SourceLocation ELoc = RefExpr->getExprLoc();
6295 // OpenMP [2.1, C/C++]
6296 // A list item is a variable name.
6297 // OpenMP [2.14.4.1, Restrictions, p.1]
6298 // A list item that appears in a copyin clause must be threadprivate.
6299 DeclRefExpr *DE = dyn_cast<DeclRefExpr>(RefExpr);
6300 if (!DE || !isa<VarDecl>(DE->getDecl())) {
6301 Diag(ELoc, diag::err_omp_expected_var_name) << RefExpr->getSourceRange();
6305 Decl *D = DE->getDecl();
6306 VarDecl *VD = cast<VarDecl>(D);
6308 QualType Type = VD->getType();
6309 if (Type->isDependentType() || Type->isInstantiationDependentType()) {
6310 // It will be analyzed later.
6312 SrcExprs.push_back(nullptr);
6313 DstExprs.push_back(nullptr);
6314 AssignmentOps.push_back(nullptr);
6318 // OpenMP [2.14.4.1, Restrictions, C/C++, p.1]
6319 // A list item that appears in a copyin clause must be threadprivate.
6320 if (!DSAStack->isThreadPrivate(VD)) {
6321 Diag(ELoc, diag::err_omp_required_access)
6322 << getOpenMPClauseName(OMPC_copyin)
6323 << getOpenMPDirectiveName(OMPD_threadprivate);
6327 // OpenMP [2.14.4.1, Restrictions, C/C++, p.2]
6328 // A variable of class type (or array thereof) that appears in a
6329 // copyin clause requires an accessible, unambiguous copy assignment
6330 // operator for the class type.
6331 auto ElemType = Context.getBaseElementType(Type).getNonReferenceType();
6332 auto *SrcVD = buildVarDecl(*this, DE->getLocStart(),
6333 ElemType.getUnqualifiedType(), ".copyin.src");
6334 auto *PseudoSrcExpr = buildDeclRefExpr(
6335 *this, SrcVD, ElemType.getUnqualifiedType(), DE->getExprLoc());
6337 buildVarDecl(*this, DE->getLocStart(), ElemType, ".copyin.dst");
6338 auto *PseudoDstExpr =
6339 buildDeclRefExpr(*this, DstVD, ElemType, DE->getExprLoc());
6340 // For arrays generate assignment operation for single element and replace
6341 // it by the original array element in CodeGen.
6342 auto AssignmentOp = BuildBinOp(/*S=*/nullptr, DE->getExprLoc(), BO_Assign,
6343 PseudoDstExpr, PseudoSrcExpr);
6344 if (AssignmentOp.isInvalid())
6346 AssignmentOp = ActOnFinishFullExpr(AssignmentOp.get(), DE->getExprLoc(),
6347 /*DiscardedValue=*/true);
6348 if (AssignmentOp.isInvalid())
6351 DSAStack->addDSA(VD, DE, OMPC_copyin);
6353 SrcExprs.push_back(PseudoSrcExpr);
6354 DstExprs.push_back(PseudoDstExpr);
6355 AssignmentOps.push_back(AssignmentOp.get());
6361 return OMPCopyinClause::Create(Context, StartLoc, LParenLoc, EndLoc, Vars,
6362 SrcExprs, DstExprs, AssignmentOps);
6365 OMPClause *Sema::ActOnOpenMPCopyprivateClause(ArrayRef<Expr *> VarList,
6366 SourceLocation StartLoc,
6367 SourceLocation LParenLoc,
6368 SourceLocation EndLoc) {
6369 SmallVector<Expr *, 8> Vars;
6370 SmallVector<Expr *, 8> SrcExprs;
6371 SmallVector<Expr *, 8> DstExprs;
6372 SmallVector<Expr *, 8> AssignmentOps;
6373 for (auto &RefExpr : VarList) {
6374 assert(RefExpr && "NULL expr in OpenMP copyprivate clause.");
6375 if (isa<DependentScopeDeclRefExpr>(RefExpr)) {
6376 // It will be analyzed later.
6377 Vars.push_back(RefExpr);
6378 SrcExprs.push_back(nullptr);
6379 DstExprs.push_back(nullptr);
6380 AssignmentOps.push_back(nullptr);
6384 SourceLocation ELoc = RefExpr->getExprLoc();
6385 // OpenMP [2.1, C/C++]
6386 // A list item is a variable name.
6387 // OpenMP [2.14.4.1, Restrictions, p.1]
6388 // A list item that appears in a copyin clause must be threadprivate.
6389 DeclRefExpr *DE = dyn_cast<DeclRefExpr>(RefExpr);
6390 if (!DE || !isa<VarDecl>(DE->getDecl())) {
6391 Diag(ELoc, diag::err_omp_expected_var_name) << RefExpr->getSourceRange();
6395 Decl *D = DE->getDecl();
6396 VarDecl *VD = cast<VarDecl>(D);
6398 QualType Type = VD->getType();
6399 if (Type->isDependentType() || Type->isInstantiationDependentType()) {
6400 // It will be analyzed later.
6402 SrcExprs.push_back(nullptr);
6403 DstExprs.push_back(nullptr);
6404 AssignmentOps.push_back(nullptr);
6408 // OpenMP [2.14.4.2, Restrictions, p.2]
6409 // A list item that appears in a copyprivate clause may not appear in a
6410 // private or firstprivate clause on the single construct.
6411 if (!DSAStack->isThreadPrivate(VD)) {
6412 auto DVar = DSAStack->getTopDSA(VD, false);
6413 if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_copyprivate &&
6415 Diag(ELoc, diag::err_omp_wrong_dsa)
6416 << getOpenMPClauseName(DVar.CKind)
6417 << getOpenMPClauseName(OMPC_copyprivate);
6418 ReportOriginalDSA(*this, DSAStack, VD, DVar);
6422 // OpenMP [2.11.4.2, Restrictions, p.1]
6423 // All list items that appear in a copyprivate clause must be either
6424 // threadprivate or private in the enclosing context.
6425 if (DVar.CKind == OMPC_unknown) {
6426 DVar = DSAStack->getImplicitDSA(VD, false);
6427 if (DVar.CKind == OMPC_shared) {
6428 Diag(ELoc, diag::err_omp_required_access)
6429 << getOpenMPClauseName(OMPC_copyprivate)
6430 << "threadprivate or private in the enclosing context";
6431 ReportOriginalDSA(*this, DSAStack, VD, DVar);
6437 // Variably modified types are not supported.
6438 if (!Type->isAnyPointerType() && Type->isVariablyModifiedType()) {
6439 Diag(ELoc, diag::err_omp_variably_modified_type_not_supported)
6440 << getOpenMPClauseName(OMPC_copyprivate) << Type
6441 << getOpenMPDirectiveName(DSAStack->getCurrentDirective());
6443 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
6444 Diag(VD->getLocation(),
6445 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
6450 // OpenMP [2.14.4.1, Restrictions, C/C++, p.2]
6451 // A variable of class type (or array thereof) that appears in a
6452 // copyin clause requires an accessible, unambiguous copy assignment
6453 // operator for the class type.
6454 Type = Context.getBaseElementType(Type).getUnqualifiedType();
6456 buildVarDecl(*this, DE->getLocStart(), Type, ".copyprivate.src");
6457 auto *PseudoSrcExpr =
6458 buildDeclRefExpr(*this, SrcVD, Type, DE->getExprLoc());
6460 buildVarDecl(*this, DE->getLocStart(), Type, ".copyprivate.dst");
6461 auto *PseudoDstExpr =
6462 buildDeclRefExpr(*this, DstVD, Type, DE->getExprLoc());
6463 auto AssignmentOp = BuildBinOp(/*S=*/nullptr, DE->getExprLoc(), BO_Assign,
6464 PseudoDstExpr, PseudoSrcExpr);
6465 if (AssignmentOp.isInvalid())
6467 AssignmentOp = ActOnFinishFullExpr(AssignmentOp.get(), DE->getExprLoc(),
6468 /*DiscardedValue=*/true);
6469 if (AssignmentOp.isInvalid())
6472 // No need to mark vars as copyprivate, they are already threadprivate or
6473 // implicitly private.
6475 SrcExprs.push_back(PseudoSrcExpr);
6476 DstExprs.push_back(PseudoDstExpr);
6477 AssignmentOps.push_back(AssignmentOp.get());
6483 return OMPCopyprivateClause::Create(Context, StartLoc, LParenLoc, EndLoc,
6484 Vars, SrcExprs, DstExprs, AssignmentOps);
6487 OMPClause *Sema::ActOnOpenMPFlushClause(ArrayRef<Expr *> VarList,
6488 SourceLocation StartLoc,
6489 SourceLocation LParenLoc,
6490 SourceLocation EndLoc) {
6491 if (VarList.empty())
6494 return OMPFlushClause::Create(Context, StartLoc, LParenLoc, EndLoc, VarList);
6498 Sema::ActOnOpenMPDependClause(OpenMPDependClauseKind DepKind,
6499 SourceLocation DepLoc, SourceLocation ColonLoc,
6500 ArrayRef<Expr *> VarList, SourceLocation StartLoc,
6501 SourceLocation LParenLoc, SourceLocation EndLoc) {
6502 if (DepKind == OMPC_DEPEND_unknown) {
6504 std::string Sep(", ");
6505 for (unsigned i = 0; i < OMPC_DEPEND_unknown; ++i) {
6507 Values += getOpenMPSimpleClauseTypeName(OMPC_depend, i);
6510 case OMPC_DEPEND_unknown - 2:
6513 case OMPC_DEPEND_unknown - 1:
6520 Diag(DepLoc, diag::err_omp_unexpected_clause_value)
6521 << Values << getOpenMPClauseName(OMPC_depend);
6524 SmallVector<Expr *, 8> Vars;
6525 for (auto &RefExpr : VarList) {
6526 assert(RefExpr && "NULL expr in OpenMP shared clause.");
6527 if (isa<DependentScopeDeclRefExpr>(RefExpr)) {
6528 // It will be analyzed later.
6529 Vars.push_back(RefExpr);
6533 SourceLocation ELoc = RefExpr->getExprLoc();
6534 // OpenMP [2.11.1.1, Restrictions, p.3]
6535 // A variable that is part of another variable (such as a field of a
6536 // structure) but is not an array element or an array section cannot appear
6537 // in a depend clause.
6538 auto *SimpleExpr = RefExpr->IgnoreParenCasts();
6539 DeclRefExpr *DE = dyn_cast<DeclRefExpr>(SimpleExpr);
6540 ArraySubscriptExpr *ASE = dyn_cast<ArraySubscriptExpr>(SimpleExpr);
6541 if (!RefExpr->IgnoreParenImpCasts()->isLValue() || (!ASE && !DE) ||
6542 (DE && !isa<VarDecl>(DE->getDecl())) ||
6543 (ASE && !ASE->getBase()->getType()->isAnyPointerType() &&
6544 !ASE->getBase()->getType()->isArrayType())) {
6545 Diag(ELoc, diag::err_omp_expected_var_name_or_array_item)
6546 << RefExpr->getSourceRange();
6550 Vars.push_back(RefExpr->IgnoreParenImpCasts());
6556 return OMPDependClause::Create(Context, StartLoc, LParenLoc, EndLoc, DepKind,
6557 DepLoc, ColonLoc, Vars);