1 //===--- SemaOpenMP.cpp - Semantic Analysis for OpenMP constructs ---------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 /// \brief This file implements semantic analysis for OpenMP directives and
13 //===----------------------------------------------------------------------===//
15 #include "TreeTransform.h"
16 #include "clang/AST/ASTContext.h"
17 #include "clang/AST/ASTMutationListener.h"
18 #include "clang/AST/Decl.h"
19 #include "clang/AST/DeclCXX.h"
20 #include "clang/AST/DeclOpenMP.h"
21 #include "clang/AST/StmtCXX.h"
22 #include "clang/AST/StmtOpenMP.h"
23 #include "clang/AST/StmtVisitor.h"
24 #include "clang/Basic/OpenMPKinds.h"
25 #include "clang/Basic/TargetInfo.h"
26 #include "clang/Lex/Preprocessor.h"
27 #include "clang/Sema/Initialization.h"
28 #include "clang/Sema/Lookup.h"
29 #include "clang/Sema/Scope.h"
30 #include "clang/Sema/ScopeInfo.h"
31 #include "clang/Sema/SemaInternal.h"
32 using namespace clang;
34 //===----------------------------------------------------------------------===//
35 // Stack of data-sharing attributes for variables
36 //===----------------------------------------------------------------------===//
39 /// \brief Default data sharing attributes, which can be applied to directive.
40 enum DefaultDataSharingAttributes {
41 DSA_unspecified = 0, /// \brief Data sharing attribute not specified.
42 DSA_none = 1 << 0, /// \brief Default data sharing attribute 'none'.
43 DSA_shared = 1 << 1 /// \brief Default data sharing attribute 'shared'.
46 template <class T> struct MatchesAny {
47 explicit MatchesAny(ArrayRef<T> Arr) : Arr(std::move(Arr)) {}
48 bool operator()(T Kind) {
49 for (auto KindEl : Arr)
58 struct MatchesAlways {
60 template <class T> bool operator()(T) { return true; }
63 typedef MatchesAny<OpenMPClauseKind> MatchesAnyClause;
64 typedef MatchesAny<OpenMPDirectiveKind> MatchesAnyDirective;
66 /// \brief Stack for tracking declarations used in OpenMP directives and
67 /// clauses and their data-sharing attributes.
71 OpenMPDirectiveKind DKind;
72 OpenMPClauseKind CKind;
74 SourceLocation ImplicitDSALoc;
76 : DKind(OMPD_unknown), CKind(OMPC_unknown), RefExpr(nullptr),
87 OpenMPClauseKind Attributes;
90 typedef llvm::SmallDenseMap<VarDecl *, DSAInfo, 64> DeclSAMapTy;
91 typedef llvm::SmallDenseMap<VarDecl *, DeclRefExpr *, 64> AlignedMapTy;
92 typedef llvm::DenseMap<VarDecl *, unsigned> LoopControlVariablesMapTy;
93 typedef llvm::SmallDenseMap<VarDecl *, MapInfo, 64> MappedDeclsTy;
94 typedef llvm::StringMap<std::pair<OMPCriticalDirective *, llvm::APSInt>>
98 DeclSAMapTy SharingMap;
99 AlignedMapTy AlignedMap;
100 MappedDeclsTy MappedDecls;
101 LoopControlVariablesMapTy LCVMap;
102 DefaultDataSharingAttributes DefaultAttr;
103 SourceLocation DefaultAttrLoc;
104 OpenMPDirectiveKind Directive;
105 DeclarationNameInfo DirectiveName;
107 SourceLocation ConstructLoc;
108 /// \brief first argument (Expr *) contains optional argument of the
109 /// 'ordered' clause, the second one is true if the regions has 'ordered'
110 /// clause, false otherwise.
111 llvm::PointerIntPair<Expr *, 1, bool> OrderedRegion;
114 unsigned AssociatedLoops;
115 SourceLocation InnerTeamsRegionLoc;
116 SharingMapTy(OpenMPDirectiveKind DKind, DeclarationNameInfo Name,
117 Scope *CurScope, SourceLocation Loc)
118 : SharingMap(), AlignedMap(), LCVMap(), DefaultAttr(DSA_unspecified),
119 Directive(DKind), DirectiveName(std::move(Name)), CurScope(CurScope),
120 ConstructLoc(Loc), OrderedRegion(), NowaitRegion(false),
121 CancelRegion(false), AssociatedLoops(1), InnerTeamsRegionLoc() {}
123 : SharingMap(), AlignedMap(), LCVMap(), DefaultAttr(DSA_unspecified),
124 Directive(OMPD_unknown), DirectiveName(), CurScope(nullptr),
125 ConstructLoc(), OrderedRegion(), NowaitRegion(false),
126 CancelRegion(false), AssociatedLoops(1), InnerTeamsRegionLoc() {}
129 typedef SmallVector<SharingMapTy, 64> StackTy;
131 /// \brief Stack of used declaration and their data-sharing attributes.
133 /// \brief true, if check for DSA must be from parent directive, false, if
134 /// from current directive.
135 OpenMPClauseKind ClauseKindMode;
138 CriticalsWithHintsTy Criticals;
140 typedef SmallVector<SharingMapTy, 8>::reverse_iterator reverse_iterator;
142 DSAVarData getDSA(StackTy::reverse_iterator Iter, VarDecl *D);
144 /// \brief Checks if the variable is a local for OpenMP region.
145 bool isOpenMPLocal(VarDecl *D, StackTy::reverse_iterator Iter);
148 explicit DSAStackTy(Sema &S)
149 : Stack(1), ClauseKindMode(OMPC_unknown), SemaRef(S),
150 ForceCapturing(false) {}
152 bool isClauseParsingMode() const { return ClauseKindMode != OMPC_unknown; }
153 void setClauseParsingMode(OpenMPClauseKind K) { ClauseKindMode = K; }
155 bool isForceVarCapturing() const { return ForceCapturing; }
156 void setForceVarCapturing(bool V) { ForceCapturing = V; }
158 void push(OpenMPDirectiveKind DKind, const DeclarationNameInfo &DirName,
159 Scope *CurScope, SourceLocation Loc) {
160 Stack.push_back(SharingMapTy(DKind, DirName, CurScope, Loc));
161 Stack.back().DefaultAttrLoc = Loc;
165 assert(Stack.size() > 1 && "Data-sharing attributes stack is empty!");
169 void addCriticalWithHint(OMPCriticalDirective *D, llvm::APSInt Hint) {
170 Criticals[D->getDirectiveName().getAsString()] = std::make_pair(D, Hint);
172 const std::pair<OMPCriticalDirective *, llvm::APSInt>
173 getCriticalWithHint(const DeclarationNameInfo &Name) const {
174 auto I = Criticals.find(Name.getAsString());
175 if (I != Criticals.end())
177 return std::make_pair(nullptr, llvm::APSInt());
179 /// \brief If 'aligned' declaration for given variable \a D was not seen yet,
180 /// add it and return NULL; otherwise return previous occurrence's expression
182 DeclRefExpr *addUniqueAligned(VarDecl *D, DeclRefExpr *NewDE);
184 /// \brief Register specified variable as loop control variable.
185 void addLoopControlVariable(VarDecl *D);
186 /// \brief Check if the specified variable is a loop control variable for
188 /// \return The index of the loop control variable in the list of associated
189 /// for-loops (from outer to inner).
190 unsigned isLoopControlVariable(VarDecl *D);
191 /// \brief Check if the specified variable is a loop control variable for
193 /// \return The index of the loop control variable in the list of associated
194 /// for-loops (from outer to inner).
195 unsigned isParentLoopControlVariable(VarDecl *D);
196 /// \brief Get the loop control variable for the I-th loop (or nullptr) in
197 /// parent directive.
198 VarDecl *getParentLoopControlVariable(unsigned I);
200 /// \brief Adds explicit data sharing attribute to the specified declaration.
201 void addDSA(VarDecl *D, DeclRefExpr *E, OpenMPClauseKind A);
203 /// \brief Returns data sharing attributes from top of the stack for the
204 /// specified declaration.
205 DSAVarData getTopDSA(VarDecl *D, bool FromParent);
206 /// \brief Returns data-sharing attributes for the specified declaration.
207 DSAVarData getImplicitDSA(VarDecl *D, bool FromParent);
208 /// \brief Checks if the specified variables has data-sharing attributes which
209 /// match specified \a CPred predicate in any directive which matches \a DPred
211 template <class ClausesPredicate, class DirectivesPredicate>
212 DSAVarData hasDSA(VarDecl *D, ClausesPredicate CPred,
213 DirectivesPredicate DPred, bool FromParent);
214 /// \brief Checks if the specified variables has data-sharing attributes which
215 /// match specified \a CPred predicate in any innermost directive which
216 /// matches \a DPred predicate.
217 template <class ClausesPredicate, class DirectivesPredicate>
218 DSAVarData hasInnermostDSA(VarDecl *D, ClausesPredicate CPred,
219 DirectivesPredicate DPred,
221 /// \brief Checks if the specified variables has explicit data-sharing
222 /// attributes which match specified \a CPred predicate at the specified
224 bool hasExplicitDSA(VarDecl *D,
225 const llvm::function_ref<bool(OpenMPClauseKind)> &CPred,
228 /// \brief Returns true if the directive at level \Level matches in the
229 /// specified \a DPred predicate.
230 bool hasExplicitDirective(
231 const llvm::function_ref<bool(OpenMPDirectiveKind)> &DPred,
234 /// \brief Finds a directive which matches specified \a DPred predicate.
235 template <class NamedDirectivesPredicate>
236 bool hasDirective(NamedDirectivesPredicate DPred, bool FromParent);
238 /// \brief Returns currently analyzed directive.
239 OpenMPDirectiveKind getCurrentDirective() const {
240 return Stack.back().Directive;
242 /// \brief Returns parent directive.
243 OpenMPDirectiveKind getParentDirective() const {
244 if (Stack.size() > 2)
245 return Stack[Stack.size() - 2].Directive;
248 /// \brief Return the directive associated with the provided scope.
249 OpenMPDirectiveKind getDirectiveForScope(const Scope *S) const;
251 /// \brief Set default data sharing attribute to none.
252 void setDefaultDSANone(SourceLocation Loc) {
253 Stack.back().DefaultAttr = DSA_none;
254 Stack.back().DefaultAttrLoc = Loc;
256 /// \brief Set default data sharing attribute to shared.
257 void setDefaultDSAShared(SourceLocation Loc) {
258 Stack.back().DefaultAttr = DSA_shared;
259 Stack.back().DefaultAttrLoc = Loc;
262 DefaultDataSharingAttributes getDefaultDSA() const {
263 return Stack.back().DefaultAttr;
265 SourceLocation getDefaultDSALocation() const {
266 return Stack.back().DefaultAttrLoc;
269 /// \brief Checks if the specified variable is a threadprivate.
270 bool isThreadPrivate(VarDecl *D) {
271 DSAVarData DVar = getTopDSA(D, false);
272 return isOpenMPThreadPrivate(DVar.CKind);
275 /// \brief Marks current region as ordered (it has an 'ordered' clause).
276 void setOrderedRegion(bool IsOrdered, Expr *Param) {
277 Stack.back().OrderedRegion.setInt(IsOrdered);
278 Stack.back().OrderedRegion.setPointer(Param);
280 /// \brief Returns true, if parent region is ordered (has associated
281 /// 'ordered' clause), false - otherwise.
282 bool isParentOrderedRegion() const {
283 if (Stack.size() > 2)
284 return Stack[Stack.size() - 2].OrderedRegion.getInt();
287 /// \brief Returns optional parameter for the ordered region.
288 Expr *getParentOrderedRegionParam() const {
289 if (Stack.size() > 2)
290 return Stack[Stack.size() - 2].OrderedRegion.getPointer();
293 /// \brief Marks current region as nowait (it has a 'nowait' clause).
294 void setNowaitRegion(bool IsNowait = true) {
295 Stack.back().NowaitRegion = IsNowait;
297 /// \brief Returns true, if parent region is nowait (has associated
298 /// 'nowait' clause), false - otherwise.
299 bool isParentNowaitRegion() const {
300 if (Stack.size() > 2)
301 return Stack[Stack.size() - 2].NowaitRegion;
304 /// \brief Marks parent region as cancel region.
305 void setParentCancelRegion(bool Cancel = true) {
306 if (Stack.size() > 2)
307 Stack[Stack.size() - 2].CancelRegion =
308 Stack[Stack.size() - 2].CancelRegion || Cancel;
310 /// \brief Return true if current region has inner cancel construct.
311 bool isCancelRegion() const {
312 return Stack.back().CancelRegion;
315 /// \brief Set collapse value for the region.
316 void setAssociatedLoops(unsigned Val) { Stack.back().AssociatedLoops = Val; }
317 /// \brief Return collapse value for region.
318 unsigned getAssociatedLoops() const { return Stack.back().AssociatedLoops; }
320 /// \brief Marks current target region as one with closely nested teams
322 void setParentTeamsRegionLoc(SourceLocation TeamsRegionLoc) {
323 if (Stack.size() > 2)
324 Stack[Stack.size() - 2].InnerTeamsRegionLoc = TeamsRegionLoc;
326 /// \brief Returns true, if current region has closely nested teams region.
327 bool hasInnerTeamsRegion() const {
328 return getInnerTeamsRegionLoc().isValid();
330 /// \brief Returns location of the nested teams region (if any).
331 SourceLocation getInnerTeamsRegionLoc() const {
332 if (Stack.size() > 1)
333 return Stack.back().InnerTeamsRegionLoc;
334 return SourceLocation();
337 Scope *getCurScope() const { return Stack.back().CurScope; }
338 Scope *getCurScope() { return Stack.back().CurScope; }
339 SourceLocation getConstructLoc() { return Stack.back().ConstructLoc; }
341 MapInfo getMapInfoForVar(VarDecl *VD) {
343 for (auto Cnt = Stack.size() - 1; Cnt > 0; --Cnt) {
344 if (Stack[Cnt].MappedDecls.count(VD)) {
345 VarMI = Stack[Cnt].MappedDecls[VD];
352 void addMapInfoForVar(VarDecl *VD, MapInfo MI) {
353 if (Stack.size() > 1) {
354 Stack.back().MappedDecls[VD] = MI;
358 MapInfo IsMappedInCurrentRegion(VarDecl *VD) {
359 assert(Stack.size() > 1 && "Target level is 0");
361 if (Stack.size() > 1 && Stack.back().MappedDecls.count(VD)) {
362 VarMI = Stack.back().MappedDecls[VD];
367 bool isParallelOrTaskRegion(OpenMPDirectiveKind DKind) {
368 return isOpenMPParallelDirective(DKind) || DKind == OMPD_task ||
369 isOpenMPTeamsDirective(DKind) || DKind == OMPD_unknown ||
370 isOpenMPTaskLoopDirective(DKind);
374 DSAStackTy::DSAVarData DSAStackTy::getDSA(StackTy::reverse_iterator Iter,
376 D = D->getCanonicalDecl();
378 if (Iter == std::prev(Stack.rend())) {
379 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
380 // in a region but not in construct]
381 // File-scope or namespace-scope variables referenced in called routines
382 // in the region are shared unless they appear in a threadprivate
384 if (!D->isFunctionOrMethodVarDecl() && !isa<ParmVarDecl>(D))
385 DVar.CKind = OMPC_shared;
387 // OpenMP [2.9.1.2, Data-sharing Attribute Rules for Variables Referenced
388 // in a region but not in construct]
389 // Variables with static storage duration that are declared in called
390 // routines in the region are shared.
391 if (D->hasGlobalStorage())
392 DVar.CKind = OMPC_shared;
397 DVar.DKind = Iter->Directive;
398 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
399 // in a Construct, C/C++, predetermined, p.1]
400 // Variables with automatic storage duration that are declared in a scope
401 // inside the construct are private.
402 if (isOpenMPLocal(D, Iter) && D->isLocalVarDecl() &&
403 (D->getStorageClass() == SC_Auto || D->getStorageClass() == SC_None)) {
404 DVar.CKind = OMPC_private;
408 // Explicitly specified attributes and local variables with predetermined
410 if (Iter->SharingMap.count(D)) {
411 DVar.RefExpr = Iter->SharingMap[D].RefExpr;
412 DVar.CKind = Iter->SharingMap[D].Attributes;
413 DVar.ImplicitDSALoc = Iter->DefaultAttrLoc;
417 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
418 // in a Construct, C/C++, implicitly determined, p.1]
419 // In a parallel or task construct, the data-sharing attributes of these
420 // variables are determined by the default clause, if present.
421 switch (Iter->DefaultAttr) {
423 DVar.CKind = OMPC_shared;
424 DVar.ImplicitDSALoc = Iter->DefaultAttrLoc;
428 case DSA_unspecified:
429 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
430 // in a Construct, implicitly determined, p.2]
431 // In a parallel construct, if no default clause is present, these
432 // variables are shared.
433 DVar.ImplicitDSALoc = Iter->DefaultAttrLoc;
434 if (isOpenMPParallelDirective(DVar.DKind) ||
435 isOpenMPTeamsDirective(DVar.DKind)) {
436 DVar.CKind = OMPC_shared;
440 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
441 // in a Construct, implicitly determined, p.4]
442 // In a task construct, if no default clause is present, a variable that in
443 // the enclosing context is determined to be shared by all implicit tasks
444 // bound to the current team is shared.
445 if (DVar.DKind == OMPD_task) {
447 for (StackTy::reverse_iterator I = std::next(Iter), EE = Stack.rend();
449 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables
451 // in a Construct, implicitly determined, p.6]
452 // In a task construct, if no default clause is present, a variable
453 // whose data-sharing attribute is not determined by the rules above is
455 DVarTemp = getDSA(I, D);
456 if (DVarTemp.CKind != OMPC_shared) {
457 DVar.RefExpr = nullptr;
458 DVar.DKind = OMPD_task;
459 DVar.CKind = OMPC_firstprivate;
462 if (isParallelOrTaskRegion(I->Directive))
465 DVar.DKind = OMPD_task;
467 (DVarTemp.CKind == OMPC_unknown) ? OMPC_firstprivate : OMPC_shared;
471 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
472 // in a Construct, implicitly determined, p.3]
473 // For constructs other than task, if no default clause is present, these
474 // variables inherit their data-sharing attributes from the enclosing
476 return getDSA(std::next(Iter), D);
479 DeclRefExpr *DSAStackTy::addUniqueAligned(VarDecl *D, DeclRefExpr *NewDE) {
480 assert(Stack.size() > 1 && "Data sharing attributes stack is empty");
481 D = D->getCanonicalDecl();
482 auto It = Stack.back().AlignedMap.find(D);
483 if (It == Stack.back().AlignedMap.end()) {
484 assert(NewDE && "Unexpected nullptr expr to be added into aligned map");
485 Stack.back().AlignedMap[D] = NewDE;
488 assert(It->second && "Unexpected nullptr expr in the aligned map");
494 void DSAStackTy::addLoopControlVariable(VarDecl *D) {
495 assert(Stack.size() > 1 && "Data-sharing attributes stack is empty");
496 D = D->getCanonicalDecl();
497 Stack.back().LCVMap.insert(std::make_pair(D, Stack.back().LCVMap.size() + 1));
500 unsigned DSAStackTy::isLoopControlVariable(VarDecl *D) {
501 assert(Stack.size() > 1 && "Data-sharing attributes stack is empty");
502 D = D->getCanonicalDecl();
503 return Stack.back().LCVMap.count(D) > 0 ? Stack.back().LCVMap[D] : 0;
506 unsigned DSAStackTy::isParentLoopControlVariable(VarDecl *D) {
507 assert(Stack.size() > 2 && "Data-sharing attributes stack is empty");
508 D = D->getCanonicalDecl();
509 return Stack[Stack.size() - 2].LCVMap.count(D) > 0
510 ? Stack[Stack.size() - 2].LCVMap[D]
514 VarDecl *DSAStackTy::getParentLoopControlVariable(unsigned I) {
515 assert(Stack.size() > 2 && "Data-sharing attributes stack is empty");
516 if (Stack[Stack.size() - 2].LCVMap.size() < I)
518 for (auto &Pair : Stack[Stack.size() - 2].LCVMap) {
519 if (Pair.second == I)
525 void DSAStackTy::addDSA(VarDecl *D, DeclRefExpr *E, OpenMPClauseKind A) {
526 D = D->getCanonicalDecl();
527 if (A == OMPC_threadprivate) {
528 Stack[0].SharingMap[D].Attributes = A;
529 Stack[0].SharingMap[D].RefExpr = E;
531 assert(Stack.size() > 1 && "Data-sharing attributes stack is empty");
532 Stack.back().SharingMap[D].Attributes = A;
533 Stack.back().SharingMap[D].RefExpr = E;
537 bool DSAStackTy::isOpenMPLocal(VarDecl *D, StackTy::reverse_iterator Iter) {
538 D = D->getCanonicalDecl();
539 if (Stack.size() > 2) {
540 reverse_iterator I = Iter, E = std::prev(Stack.rend());
541 Scope *TopScope = nullptr;
542 while (I != E && !isParallelOrTaskRegion(I->Directive)) {
547 TopScope = I->CurScope ? I->CurScope->getParent() : nullptr;
548 Scope *CurScope = getCurScope();
549 while (CurScope != TopScope && !CurScope->isDeclScope(D)) {
550 CurScope = CurScope->getParent();
552 return CurScope != TopScope;
557 /// \brief Build a variable declaration for OpenMP loop iteration variable.
558 static VarDecl *buildVarDecl(Sema &SemaRef, SourceLocation Loc, QualType Type,
559 StringRef Name, const AttrVec *Attrs = nullptr) {
560 DeclContext *DC = SemaRef.CurContext;
561 IdentifierInfo *II = &SemaRef.PP.getIdentifierTable().get(Name);
562 TypeSourceInfo *TInfo = SemaRef.Context.getTrivialTypeSourceInfo(Type, Loc);
564 VarDecl::Create(SemaRef.Context, DC, Loc, Loc, II, Type, TInfo, SC_None);
566 for (specific_attr_iterator<AlignedAttr> I(Attrs->begin()), E(Attrs->end());
574 static DeclRefExpr *buildDeclRefExpr(Sema &S, VarDecl *D, QualType Ty,
576 bool RefersToCapture = false) {
578 D->markUsed(S.Context);
579 return DeclRefExpr::Create(S.getASTContext(), NestedNameSpecifierLoc(),
580 SourceLocation(), D, RefersToCapture, Loc, Ty,
584 DSAStackTy::DSAVarData DSAStackTy::getTopDSA(VarDecl *D, bool FromParent) {
585 D = D->getCanonicalDecl();
588 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
589 // in a Construct, C/C++, predetermined, p.1]
590 // Variables appearing in threadprivate directives are threadprivate.
591 if ((D->getTLSKind() != VarDecl::TLS_None &&
592 !(D->hasAttr<OMPThreadPrivateDeclAttr>() &&
593 SemaRef.getLangOpts().OpenMPUseTLS &&
594 SemaRef.getASTContext().getTargetInfo().isTLSSupported())) ||
595 (D->getStorageClass() == SC_Register && D->hasAttr<AsmLabelAttr>() &&
596 !D->isLocalVarDecl())) {
597 addDSA(D, buildDeclRefExpr(SemaRef, D, D->getType().getNonReferenceType(),
601 if (Stack[0].SharingMap.count(D)) {
602 DVar.RefExpr = Stack[0].SharingMap[D].RefExpr;
603 DVar.CKind = OMPC_threadprivate;
607 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
608 // in a Construct, C/C++, predetermined, p.4]
609 // Static data members are shared.
610 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
611 // in a Construct, C/C++, predetermined, p.7]
612 // Variables with static storage duration that are declared in a scope
613 // inside the construct are shared.
614 if (D->isStaticDataMember()) {
615 DSAVarData DVarTemp =
616 hasDSA(D, isOpenMPPrivate, MatchesAlways(), FromParent);
617 if (DVarTemp.CKind != OMPC_unknown && DVarTemp.RefExpr)
620 DVar.CKind = OMPC_shared;
624 QualType Type = D->getType().getNonReferenceType().getCanonicalType();
625 bool IsConstant = Type.isConstant(SemaRef.getASTContext());
626 Type = SemaRef.getASTContext().getBaseElementType(Type);
627 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
628 // in a Construct, C/C++, predetermined, p.6]
629 // Variables with const qualified type having no mutable member are
632 SemaRef.getLangOpts().CPlusPlus ? Type->getAsCXXRecordDecl() : nullptr;
633 if (auto *CTSD = dyn_cast_or_null<ClassTemplateSpecializationDecl>(RD))
634 if (auto *CTD = CTSD->getSpecializedTemplate())
635 RD = CTD->getTemplatedDecl();
637 !(SemaRef.getLangOpts().CPlusPlus && RD && RD->hasMutableFields())) {
638 // Variables with const-qualified type having no mutable member may be
639 // listed in a firstprivate clause, even if they are static data members.
640 DSAVarData DVarTemp = hasDSA(D, MatchesAnyClause(OMPC_firstprivate),
641 MatchesAlways(), FromParent);
642 if (DVarTemp.CKind == OMPC_firstprivate && DVarTemp.RefExpr)
645 DVar.CKind = OMPC_shared;
649 // Explicitly specified attributes and local variables with predetermined
651 auto StartI = std::next(Stack.rbegin());
652 auto EndI = std::prev(Stack.rend());
653 if (FromParent && StartI != EndI) {
654 StartI = std::next(StartI);
656 auto I = std::prev(StartI);
657 if (I->SharingMap.count(D)) {
658 DVar.RefExpr = I->SharingMap[D].RefExpr;
659 DVar.CKind = I->SharingMap[D].Attributes;
660 DVar.ImplicitDSALoc = I->DefaultAttrLoc;
666 DSAStackTy::DSAVarData DSAStackTy::getImplicitDSA(VarDecl *D, bool FromParent) {
667 D = D->getCanonicalDecl();
668 auto StartI = Stack.rbegin();
669 auto EndI = std::prev(Stack.rend());
670 if (FromParent && StartI != EndI) {
671 StartI = std::next(StartI);
673 return getDSA(StartI, D);
676 template <class ClausesPredicate, class DirectivesPredicate>
677 DSAStackTy::DSAVarData DSAStackTy::hasDSA(VarDecl *D, ClausesPredicate CPred,
678 DirectivesPredicate DPred,
680 D = D->getCanonicalDecl();
681 auto StartI = std::next(Stack.rbegin());
682 auto EndI = std::prev(Stack.rend());
683 if (FromParent && StartI != EndI) {
684 StartI = std::next(StartI);
686 for (auto I = StartI, EE = EndI; I != EE; ++I) {
687 if (!DPred(I->Directive) && !isParallelOrTaskRegion(I->Directive))
689 DSAVarData DVar = getDSA(I, D);
690 if (CPred(DVar.CKind))
696 template <class ClausesPredicate, class DirectivesPredicate>
697 DSAStackTy::DSAVarData
698 DSAStackTy::hasInnermostDSA(VarDecl *D, ClausesPredicate CPred,
699 DirectivesPredicate DPred, bool FromParent) {
700 D = D->getCanonicalDecl();
701 auto StartI = std::next(Stack.rbegin());
702 auto EndI = std::prev(Stack.rend());
703 if (FromParent && StartI != EndI) {
704 StartI = std::next(StartI);
706 for (auto I = StartI, EE = EndI; I != EE; ++I) {
707 if (!DPred(I->Directive))
709 DSAVarData DVar = getDSA(I, D);
710 if (CPred(DVar.CKind))
717 bool DSAStackTy::hasExplicitDSA(
718 VarDecl *D, const llvm::function_ref<bool(OpenMPClauseKind)> &CPred,
720 if (CPred(ClauseKindMode))
722 if (isClauseParsingMode())
724 D = D->getCanonicalDecl();
725 auto StartI = Stack.rbegin();
726 auto EndI = std::prev(Stack.rend());
727 if (std::distance(StartI, EndI) <= (int)Level)
729 std::advance(StartI, Level);
730 return (StartI->SharingMap.count(D) > 0) && StartI->SharingMap[D].RefExpr &&
731 CPred(StartI->SharingMap[D].Attributes);
734 bool DSAStackTy::hasExplicitDirective(
735 const llvm::function_ref<bool(OpenMPDirectiveKind)> &DPred,
737 if (isClauseParsingMode())
739 auto StartI = Stack.rbegin();
740 auto EndI = std::prev(Stack.rend());
741 if (std::distance(StartI, EndI) <= (int)Level)
743 std::advance(StartI, Level);
744 return DPred(StartI->Directive);
747 template <class NamedDirectivesPredicate>
748 bool DSAStackTy::hasDirective(NamedDirectivesPredicate DPred, bool FromParent) {
749 auto StartI = std::next(Stack.rbegin());
750 auto EndI = std::prev(Stack.rend());
751 if (FromParent && StartI != EndI) {
752 StartI = std::next(StartI);
754 for (auto I = StartI, EE = EndI; I != EE; ++I) {
755 if (DPred(I->Directive, I->DirectiveName, I->ConstructLoc))
761 OpenMPDirectiveKind DSAStackTy::getDirectiveForScope(const Scope *S) const {
762 for (auto I = Stack.rbegin(), EE = Stack.rend(); I != EE; ++I)
763 if (I->CurScope == S)
768 void Sema::InitDataSharingAttributesStack() {
769 VarDataSharingAttributesStack = new DSAStackTy(*this);
772 #define DSAStack static_cast<DSAStackTy *>(VarDataSharingAttributesStack)
774 bool Sema::IsOpenMPCapturedByRef(VarDecl *VD,
775 const CapturedRegionScopeInfo *RSI) {
776 assert(LangOpts.OpenMP && "OpenMP is not allowed");
778 auto &Ctx = getASTContext();
781 // Find the directive that is associated with the provided scope.
782 auto DKind = DSAStack->getDirectiveForScope(RSI->TheScope);
783 auto Ty = VD->getType();
785 if (isOpenMPTargetDirective(DKind)) {
786 // This table summarizes how a given variable should be passed to the device
787 // given its type and the clauses where it appears. This table is based on
788 // the description in OpenMP 4.5 [2.10.4, target Construct] and
789 // OpenMP 4.5 [2.15.5, Data-mapping Attribute Rules and Clauses].
791 // =========================================================================
792 // | type | defaultmap | pvt | first | is_device_ptr | map | res. |
793 // | |(tofrom:scalar)| | pvt | | | |
794 // =========================================================================
795 // | scl | | | | - | | bycopy|
796 // | scl | | - | x | - | - | bycopy|
797 // | scl | | x | - | - | - | null |
798 // | scl | x | | | - | | byref |
799 // | scl | x | - | x | - | - | bycopy|
800 // | scl | x | x | - | - | - | null |
801 // | scl | | - | - | - | x | byref |
802 // | scl | x | - | - | - | x | byref |
804 // | agg | n.a. | | | - | | byref |
805 // | agg | n.a. | - | x | - | - | byref |
806 // | agg | n.a. | x | - | - | - | null |
807 // | agg | n.a. | - | - | - | x | byref |
808 // | agg | n.a. | - | - | - | x[] | byref |
810 // | ptr | n.a. | | | - | | bycopy|
811 // | ptr | n.a. | - | x | - | - | bycopy|
812 // | ptr | n.a. | x | - | - | - | null |
813 // | ptr | n.a. | - | - | - | x | byref |
814 // | ptr | n.a. | - | - | - | x[] | bycopy|
815 // | ptr | n.a. | - | - | x | | bycopy|
816 // | ptr | n.a. | - | - | x | x | bycopy|
817 // | ptr | n.a. | - | - | x | x[] | bycopy|
818 // =========================================================================
824 // - - invalid in this combination
825 // [] - mapped with an array section
826 // byref - should be mapped by reference
827 // byval - should be mapped by value
828 // null - initialize a local variable to null on the device
831 // - All scalar declarations that show up in a map clause have to be passed
832 // by reference, because they may have been mapped in the enclosing data
834 // - If the scalar value does not fit the size of uintptr, it has to be
835 // passed by reference, regardless the result in the table above.
836 // - For pointers mapped by value that have either an implicit map or an
837 // array section, the runtime library may pass the NULL value to the
838 // device instead of the value passed to it by the compiler.
840 // FIXME: Right now, only implicit maps are implemented. Properly mapping
841 // values requires having the map, private, and firstprivate clauses SEMA
842 // and parsing in place, which we don't yet.
844 if (Ty->isReferenceType())
845 Ty = Ty->castAs<ReferenceType>()->getPointeeType();
846 IsByRef = !Ty->isScalarType();
849 // When passing data by value, we need to make sure it fits the uintptr size
850 // and alignment, because the runtime library only deals with uintptr types.
851 // If it does not fit the uintptr size, we need to pass the data by reference
854 (Ctx.getTypeSizeInChars(Ty) >
855 Ctx.getTypeSizeInChars(Ctx.getUIntPtrType()) ||
856 Ctx.getDeclAlign(VD) > Ctx.getTypeAlignInChars(Ctx.getUIntPtrType())))
862 bool Sema::IsOpenMPCapturedVar(VarDecl *VD) {
863 assert(LangOpts.OpenMP && "OpenMP is not allowed");
864 VD = VD->getCanonicalDecl();
866 // If we are attempting to capture a global variable in a directive with
867 // 'target' we return true so that this global is also mapped to the device.
869 // FIXME: If the declaration is enclosed in a 'declare target' directive,
870 // then it should not be captured. Therefore, an extra check has to be
871 // inserted here once support for 'declare target' is added.
873 if (!VD->hasLocalStorage()) {
874 if (DSAStack->getCurrentDirective() == OMPD_target &&
875 !DSAStack->isClauseParsingMode()) {
878 if (DSAStack->getCurScope() &&
879 DSAStack->hasDirective(
880 [](OpenMPDirectiveKind K, const DeclarationNameInfo &DNI,
881 SourceLocation Loc) -> bool {
882 return isOpenMPTargetDirective(K);
889 if (DSAStack->getCurrentDirective() != OMPD_unknown &&
890 (!DSAStack->isClauseParsingMode() ||
891 DSAStack->getParentDirective() != OMPD_unknown)) {
892 if (DSAStack->isLoopControlVariable(VD) ||
893 (VD->hasLocalStorage() &&
894 isParallelOrTaskRegion(DSAStack->getCurrentDirective())) ||
895 DSAStack->isForceVarCapturing())
897 auto DVarPrivate = DSAStack->getTopDSA(VD, DSAStack->isClauseParsingMode());
898 if (DVarPrivate.CKind != OMPC_unknown && isOpenMPPrivate(DVarPrivate.CKind))
900 DVarPrivate = DSAStack->hasDSA(VD, isOpenMPPrivate, MatchesAlways(),
901 DSAStack->isClauseParsingMode());
902 return DVarPrivate.CKind != OMPC_unknown;
907 bool Sema::isOpenMPPrivateVar(VarDecl *VD, unsigned Level) {
908 assert(LangOpts.OpenMP && "OpenMP is not allowed");
909 return DSAStack->hasExplicitDSA(
910 VD, [](OpenMPClauseKind K) -> bool { return K == OMPC_private; }, Level);
913 bool Sema::isOpenMPTargetCapturedVar(VarDecl *VD, unsigned Level) {
914 assert(LangOpts.OpenMP && "OpenMP is not allowed");
915 // Return true if the current level is no longer enclosed in a target region.
917 return !VD->hasLocalStorage() &&
918 DSAStack->hasExplicitDirective(isOpenMPTargetDirective, Level);
921 void Sema::DestroyDataSharingAttributesStack() { delete DSAStack; }
923 void Sema::StartOpenMPDSABlock(OpenMPDirectiveKind DKind,
924 const DeclarationNameInfo &DirName,
925 Scope *CurScope, SourceLocation Loc) {
926 DSAStack->push(DKind, DirName, CurScope, Loc);
927 PushExpressionEvaluationContext(PotentiallyEvaluated);
930 void Sema::StartOpenMPClause(OpenMPClauseKind K) {
931 DSAStack->setClauseParsingMode(K);
934 void Sema::EndOpenMPClause() {
935 DSAStack->setClauseParsingMode(/*K=*/OMPC_unknown);
938 void Sema::EndOpenMPDSABlock(Stmt *CurDirective) {
939 // OpenMP [2.14.3.5, Restrictions, C/C++, p.1]
940 // A variable of class type (or array thereof) that appears in a lastprivate
941 // clause requires an accessible, unambiguous default constructor for the
942 // class type, unless the list item is also specified in a firstprivate
944 if (auto D = dyn_cast_or_null<OMPExecutableDirective>(CurDirective)) {
945 for (auto *C : D->clauses()) {
946 if (auto *Clause = dyn_cast<OMPLastprivateClause>(C)) {
947 SmallVector<Expr *, 8> PrivateCopies;
948 for (auto *DE : Clause->varlists()) {
949 if (DE->isValueDependent() || DE->isTypeDependent()) {
950 PrivateCopies.push_back(nullptr);
953 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(DE)->getDecl());
954 QualType Type = VD->getType().getNonReferenceType();
955 auto DVar = DSAStack->getTopDSA(VD, false);
956 if (DVar.CKind == OMPC_lastprivate) {
957 // Generate helper private variable and initialize it with the
958 // default value. The address of the original variable is replaced
959 // by the address of the new private variable in CodeGen. This new
960 // variable is not added to IdResolver, so the code in the OpenMP
961 // region uses original variable for proper diagnostics.
962 auto *VDPrivate = buildVarDecl(
963 *this, DE->getExprLoc(), Type.getUnqualifiedType(),
964 VD->getName(), VD->hasAttrs() ? &VD->getAttrs() : nullptr);
965 ActOnUninitializedDecl(VDPrivate, /*TypeMayContainAuto=*/false);
966 if (VDPrivate->isInvalidDecl())
968 PrivateCopies.push_back(buildDeclRefExpr(
969 *this, VDPrivate, DE->getType(), DE->getExprLoc()));
971 // The variable is also a firstprivate, so initialization sequence
972 // for private copy is generated already.
973 PrivateCopies.push_back(nullptr);
976 // Set initializers to private copies if no errors were found.
977 if (PrivateCopies.size() == Clause->varlist_size()) {
978 Clause->setPrivateCopies(PrivateCopies);
985 DiscardCleanupsInEvaluationContext();
986 PopExpressionEvaluationContext();
989 static bool FinishOpenMPLinearClause(OMPLinearClause &Clause, DeclRefExpr *IV,
990 Expr *NumIterations, Sema &SemaRef,
995 class VarDeclFilterCCC : public CorrectionCandidateCallback {
1000 explicit VarDeclFilterCCC(Sema &S) : SemaRef(S) {}
1001 bool ValidateCandidate(const TypoCorrection &Candidate) override {
1002 NamedDecl *ND = Candidate.getCorrectionDecl();
1003 if (VarDecl *VD = dyn_cast_or_null<VarDecl>(ND)) {
1004 return VD->hasGlobalStorage() &&
1005 SemaRef.isDeclInScope(ND, SemaRef.getCurLexicalContext(),
1006 SemaRef.getCurScope());
1013 ExprResult Sema::ActOnOpenMPIdExpression(Scope *CurScope,
1014 CXXScopeSpec &ScopeSpec,
1015 const DeclarationNameInfo &Id) {
1016 LookupResult Lookup(*this, Id, LookupOrdinaryName);
1017 LookupParsedName(Lookup, CurScope, &ScopeSpec, true);
1019 if (Lookup.isAmbiguous())
1023 if (!Lookup.isSingleResult()) {
1024 if (TypoCorrection Corrected = CorrectTypo(
1025 Id, LookupOrdinaryName, CurScope, nullptr,
1026 llvm::make_unique<VarDeclFilterCCC>(*this), CTK_ErrorRecovery)) {
1027 diagnoseTypo(Corrected,
1028 PDiag(Lookup.empty()
1029 ? diag::err_undeclared_var_use_suggest
1030 : diag::err_omp_expected_var_arg_suggest)
1032 VD = Corrected.getCorrectionDeclAs<VarDecl>();
1034 Diag(Id.getLoc(), Lookup.empty() ? diag::err_undeclared_var_use
1035 : diag::err_omp_expected_var_arg)
1040 if (!(VD = Lookup.getAsSingle<VarDecl>())) {
1041 Diag(Id.getLoc(), diag::err_omp_expected_var_arg) << Id.getName();
1042 Diag(Lookup.getFoundDecl()->getLocation(), diag::note_declared_at);
1046 Lookup.suppressDiagnostics();
1048 // OpenMP [2.9.2, Syntax, C/C++]
1049 // Variables must be file-scope, namespace-scope, or static block-scope.
1050 if (!VD->hasGlobalStorage()) {
1051 Diag(Id.getLoc(), diag::err_omp_global_var_arg)
1052 << getOpenMPDirectiveName(OMPD_threadprivate) << !VD->isStaticLocal();
1054 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
1055 Diag(VD->getLocation(),
1056 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
1061 VarDecl *CanonicalVD = VD->getCanonicalDecl();
1062 NamedDecl *ND = cast<NamedDecl>(CanonicalVD);
1063 // OpenMP [2.9.2, Restrictions, C/C++, p.2]
1064 // A threadprivate directive for file-scope variables must appear outside
1065 // any definition or declaration.
1066 if (CanonicalVD->getDeclContext()->isTranslationUnit() &&
1067 !getCurLexicalContext()->isTranslationUnit()) {
1068 Diag(Id.getLoc(), diag::err_omp_var_scope)
1069 << getOpenMPDirectiveName(OMPD_threadprivate) << VD;
1071 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
1072 Diag(VD->getLocation(),
1073 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
1077 // OpenMP [2.9.2, Restrictions, C/C++, p.3]
1078 // A threadprivate directive for static class member variables must appear
1079 // in the class definition, in the same scope in which the member
1080 // variables are declared.
1081 if (CanonicalVD->isStaticDataMember() &&
1082 !CanonicalVD->getDeclContext()->Equals(getCurLexicalContext())) {
1083 Diag(Id.getLoc(), diag::err_omp_var_scope)
1084 << getOpenMPDirectiveName(OMPD_threadprivate) << VD;
1086 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
1087 Diag(VD->getLocation(),
1088 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
1092 // OpenMP [2.9.2, Restrictions, C/C++, p.4]
1093 // A threadprivate directive for namespace-scope variables must appear
1094 // outside any definition or declaration other than the namespace
1095 // definition itself.
1096 if (CanonicalVD->getDeclContext()->isNamespace() &&
1097 (!getCurLexicalContext()->isFileContext() ||
1098 !getCurLexicalContext()->Encloses(CanonicalVD->getDeclContext()))) {
1099 Diag(Id.getLoc(), diag::err_omp_var_scope)
1100 << getOpenMPDirectiveName(OMPD_threadprivate) << VD;
1102 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
1103 Diag(VD->getLocation(),
1104 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
1108 // OpenMP [2.9.2, Restrictions, C/C++, p.6]
1109 // A threadprivate directive for static block-scope variables must appear
1110 // in the scope of the variable and not in a nested scope.
1111 if (CanonicalVD->isStaticLocal() && CurScope &&
1112 !isDeclInScope(ND, getCurLexicalContext(), CurScope)) {
1113 Diag(Id.getLoc(), diag::err_omp_var_scope)
1114 << getOpenMPDirectiveName(OMPD_threadprivate) << VD;
1116 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
1117 Diag(VD->getLocation(),
1118 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
1123 // OpenMP [2.9.2, Restrictions, C/C++, p.2-6]
1124 // A threadprivate directive must lexically precede all references to any
1125 // of the variables in its list.
1126 if (VD->isUsed() && !DSAStack->isThreadPrivate(VD)) {
1127 Diag(Id.getLoc(), diag::err_omp_var_used)
1128 << getOpenMPDirectiveName(OMPD_threadprivate) << VD;
1132 QualType ExprType = VD->getType().getNonReferenceType();
1133 ExprResult DE = buildDeclRefExpr(*this, VD, ExprType, Id.getLoc());
1137 Sema::DeclGroupPtrTy
1138 Sema::ActOnOpenMPThreadprivateDirective(SourceLocation Loc,
1139 ArrayRef<Expr *> VarList) {
1140 if (OMPThreadPrivateDecl *D = CheckOMPThreadPrivateDecl(Loc, VarList)) {
1141 CurContext->addDecl(D);
1142 return DeclGroupPtrTy::make(DeclGroupRef(D));
1144 return DeclGroupPtrTy();
1148 class LocalVarRefChecker : public ConstStmtVisitor<LocalVarRefChecker, bool> {
1152 bool VisitDeclRefExpr(const DeclRefExpr *E) {
1153 if (auto VD = dyn_cast<VarDecl>(E->getDecl())) {
1154 if (VD->hasLocalStorage()) {
1155 SemaRef.Diag(E->getLocStart(),
1156 diag::err_omp_local_var_in_threadprivate_init)
1157 << E->getSourceRange();
1158 SemaRef.Diag(VD->getLocation(), diag::note_defined_here)
1159 << VD << VD->getSourceRange();
1165 bool VisitStmt(const Stmt *S) {
1166 for (auto Child : S->children()) {
1167 if (Child && Visit(Child))
1172 explicit LocalVarRefChecker(Sema &SemaRef) : SemaRef(SemaRef) {}
1176 OMPThreadPrivateDecl *
1177 Sema::CheckOMPThreadPrivateDecl(SourceLocation Loc, ArrayRef<Expr *> VarList) {
1178 SmallVector<Expr *, 8> Vars;
1179 for (auto &RefExpr : VarList) {
1180 DeclRefExpr *DE = cast<DeclRefExpr>(RefExpr);
1181 VarDecl *VD = cast<VarDecl>(DE->getDecl());
1182 SourceLocation ILoc = DE->getExprLoc();
1184 QualType QType = VD->getType();
1185 if (QType->isDependentType() || QType->isInstantiationDependentType()) {
1186 // It will be analyzed later.
1191 // OpenMP [2.9.2, Restrictions, C/C++, p.10]
1192 // A threadprivate variable must not have an incomplete type.
1193 if (RequireCompleteType(ILoc, VD->getType(),
1194 diag::err_omp_threadprivate_incomplete_type)) {
1198 // OpenMP [2.9.2, Restrictions, C/C++, p.10]
1199 // A threadprivate variable must not have a reference type.
1200 if (VD->getType()->isReferenceType()) {
1201 Diag(ILoc, diag::err_omp_ref_type_arg)
1202 << getOpenMPDirectiveName(OMPD_threadprivate) << VD->getType();
1204 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
1205 Diag(VD->getLocation(),
1206 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
1211 // Check if this is a TLS variable. If TLS is not being supported, produce
1212 // the corresponding diagnostic.
1213 if ((VD->getTLSKind() != VarDecl::TLS_None &&
1214 !(VD->hasAttr<OMPThreadPrivateDeclAttr>() &&
1215 getLangOpts().OpenMPUseTLS &&
1216 getASTContext().getTargetInfo().isTLSSupported())) ||
1217 (VD->getStorageClass() == SC_Register && VD->hasAttr<AsmLabelAttr>() &&
1218 !VD->isLocalVarDecl())) {
1219 Diag(ILoc, diag::err_omp_var_thread_local)
1220 << VD << ((VD->getTLSKind() != VarDecl::TLS_None) ? 0 : 1);
1222 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
1223 Diag(VD->getLocation(),
1224 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
1229 // Check if initial value of threadprivate variable reference variable with
1230 // local storage (it is not supported by runtime).
1231 if (auto Init = VD->getAnyInitializer()) {
1232 LocalVarRefChecker Checker(*this);
1233 if (Checker.Visit(Init))
1237 Vars.push_back(RefExpr);
1238 DSAStack->addDSA(VD, DE, OMPC_threadprivate);
1239 VD->addAttr(OMPThreadPrivateDeclAttr::CreateImplicit(
1240 Context, SourceRange(Loc, Loc)));
1241 if (auto *ML = Context.getASTMutationListener())
1242 ML->DeclarationMarkedOpenMPThreadPrivate(VD);
1244 OMPThreadPrivateDecl *D = nullptr;
1245 if (!Vars.empty()) {
1246 D = OMPThreadPrivateDecl::Create(Context, getCurLexicalContext(), Loc,
1248 D->setAccess(AS_public);
1253 static void ReportOriginalDSA(Sema &SemaRef, DSAStackTy *Stack,
1254 const VarDecl *VD, DSAStackTy::DSAVarData DVar,
1255 bool IsLoopIterVar = false) {
1257 SemaRef.Diag(DVar.RefExpr->getExprLoc(), diag::note_omp_explicit_dsa)
1258 << getOpenMPClauseName(DVar.CKind);
1262 PDSA_StaticMemberShared,
1263 PDSA_StaticLocalVarShared,
1264 PDSA_LoopIterVarPrivate,
1265 PDSA_LoopIterVarLinear,
1266 PDSA_LoopIterVarLastprivate,
1267 PDSA_ConstVarShared,
1268 PDSA_GlobalVarShared,
1269 PDSA_TaskVarFirstprivate,
1270 PDSA_LocalVarPrivate,
1272 } Reason = PDSA_Implicit;
1273 bool ReportHint = false;
1274 auto ReportLoc = VD->getLocation();
1275 if (IsLoopIterVar) {
1276 if (DVar.CKind == OMPC_private)
1277 Reason = PDSA_LoopIterVarPrivate;
1278 else if (DVar.CKind == OMPC_lastprivate)
1279 Reason = PDSA_LoopIterVarLastprivate;
1281 Reason = PDSA_LoopIterVarLinear;
1282 } else if (DVar.DKind == OMPD_task && DVar.CKind == OMPC_firstprivate) {
1283 Reason = PDSA_TaskVarFirstprivate;
1284 ReportLoc = DVar.ImplicitDSALoc;
1285 } else if (VD->isStaticLocal())
1286 Reason = PDSA_StaticLocalVarShared;
1287 else if (VD->isStaticDataMember())
1288 Reason = PDSA_StaticMemberShared;
1289 else if (VD->isFileVarDecl())
1290 Reason = PDSA_GlobalVarShared;
1291 else if (VD->getType().isConstant(SemaRef.getASTContext()))
1292 Reason = PDSA_ConstVarShared;
1293 else if (VD->isLocalVarDecl() && DVar.CKind == OMPC_private) {
1295 Reason = PDSA_LocalVarPrivate;
1297 if (Reason != PDSA_Implicit) {
1298 SemaRef.Diag(ReportLoc, diag::note_omp_predetermined_dsa)
1299 << Reason << ReportHint
1300 << getOpenMPDirectiveName(Stack->getCurrentDirective());
1301 } else if (DVar.ImplicitDSALoc.isValid()) {
1302 SemaRef.Diag(DVar.ImplicitDSALoc, diag::note_omp_implicit_dsa)
1303 << getOpenMPClauseName(DVar.CKind);
1308 class DSAAttrChecker : public StmtVisitor<DSAAttrChecker, void> {
1313 llvm::SmallVector<Expr *, 8> ImplicitFirstprivate;
1314 llvm::DenseMap<VarDecl *, Expr *> VarsWithInheritedDSA;
1317 void VisitDeclRefExpr(DeclRefExpr *E) {
1318 if (auto *VD = dyn_cast<VarDecl>(E->getDecl())) {
1319 // Skip internally declared variables.
1320 if (VD->isLocalVarDecl() && !CS->capturesVariable(VD))
1323 auto DVar = Stack->getTopDSA(VD, false);
1324 // Check if the variable has explicit DSA set and stop analysis if it so.
1325 if (DVar.RefExpr) return;
1327 auto ELoc = E->getExprLoc();
1328 auto DKind = Stack->getCurrentDirective();
1329 // The default(none) clause requires that each variable that is referenced
1330 // in the construct, and does not have a predetermined data-sharing
1331 // attribute, must have its data-sharing attribute explicitly determined
1332 // by being listed in a data-sharing attribute clause.
1333 if (DVar.CKind == OMPC_unknown && Stack->getDefaultDSA() == DSA_none &&
1334 isParallelOrTaskRegion(DKind) &&
1335 VarsWithInheritedDSA.count(VD) == 0) {
1336 VarsWithInheritedDSA[VD] = E;
1340 // OpenMP [2.9.3.6, Restrictions, p.2]
1341 // A list item that appears in a reduction clause of the innermost
1342 // enclosing worksharing or parallel construct may not be accessed in an
1344 DVar = Stack->hasInnermostDSA(VD, MatchesAnyClause(OMPC_reduction),
1345 [](OpenMPDirectiveKind K) -> bool {
1346 return isOpenMPParallelDirective(K) ||
1347 isOpenMPWorksharingDirective(K) ||
1348 isOpenMPTeamsDirective(K);
1351 if (DKind == OMPD_task && DVar.CKind == OMPC_reduction) {
1353 SemaRef.Diag(ELoc, diag::err_omp_reduction_in_task);
1354 ReportOriginalDSA(SemaRef, Stack, VD, DVar);
1358 // Define implicit data-sharing attributes for task.
1359 DVar = Stack->getImplicitDSA(VD, false);
1360 if (DKind == OMPD_task && DVar.CKind != OMPC_shared)
1361 ImplicitFirstprivate.push_back(E);
1364 void VisitOMPExecutableDirective(OMPExecutableDirective *S) {
1365 for (auto *C : S->clauses()) {
1366 // Skip analysis of arguments of implicitly defined firstprivate clause
1367 // for task directives.
1368 if (C && (!isa<OMPFirstprivateClause>(C) || C->getLocStart().isValid()))
1369 for (auto *CC : C->children()) {
1375 void VisitStmt(Stmt *S) {
1376 for (auto *C : S->children()) {
1377 if (C && !isa<OMPExecutableDirective>(C))
1382 bool isErrorFound() { return ErrorFound; }
1383 ArrayRef<Expr *> getImplicitFirstprivate() { return ImplicitFirstprivate; }
1384 llvm::DenseMap<VarDecl *, Expr *> &getVarsWithInheritedDSA() {
1385 return VarsWithInheritedDSA;
1388 DSAAttrChecker(DSAStackTy *S, Sema &SemaRef, CapturedStmt *CS)
1389 : Stack(S), SemaRef(SemaRef), ErrorFound(false), CS(CS) {}
1393 void Sema::ActOnOpenMPRegionStart(OpenMPDirectiveKind DKind, Scope *CurScope) {
1395 case OMPD_parallel: {
1396 QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1);
1397 QualType KmpInt32PtrTy =
1398 Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
1399 Sema::CapturedParamNameType Params[] = {
1400 std::make_pair(".global_tid.", KmpInt32PtrTy),
1401 std::make_pair(".bound_tid.", KmpInt32PtrTy),
1402 std::make_pair(StringRef(), QualType()) // __context with shared vars
1404 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
1409 Sema::CapturedParamNameType Params[] = {
1410 std::make_pair(StringRef(), QualType()) // __context with shared vars
1412 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
1417 Sema::CapturedParamNameType Params[] = {
1418 std::make_pair(StringRef(), QualType()) // __context with shared vars
1420 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
1424 case OMPD_for_simd: {
1425 Sema::CapturedParamNameType Params[] = {
1426 std::make_pair(StringRef(), QualType()) // __context with shared vars
1428 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
1432 case OMPD_sections: {
1433 Sema::CapturedParamNameType Params[] = {
1434 std::make_pair(StringRef(), QualType()) // __context with shared vars
1436 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
1440 case OMPD_section: {
1441 Sema::CapturedParamNameType Params[] = {
1442 std::make_pair(StringRef(), QualType()) // __context with shared vars
1444 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
1449 Sema::CapturedParamNameType Params[] = {
1450 std::make_pair(StringRef(), QualType()) // __context with shared vars
1452 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
1457 Sema::CapturedParamNameType Params[] = {
1458 std::make_pair(StringRef(), QualType()) // __context with shared vars
1460 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
1464 case OMPD_critical: {
1465 Sema::CapturedParamNameType Params[] = {
1466 std::make_pair(StringRef(), QualType()) // __context with shared vars
1468 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
1472 case OMPD_parallel_for: {
1473 QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1);
1474 QualType KmpInt32PtrTy =
1475 Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
1476 Sema::CapturedParamNameType Params[] = {
1477 std::make_pair(".global_tid.", KmpInt32PtrTy),
1478 std::make_pair(".bound_tid.", KmpInt32PtrTy),
1479 std::make_pair(StringRef(), QualType()) // __context with shared vars
1481 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
1485 case OMPD_parallel_for_simd: {
1486 QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1);
1487 QualType KmpInt32PtrTy =
1488 Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
1489 Sema::CapturedParamNameType Params[] = {
1490 std::make_pair(".global_tid.", KmpInt32PtrTy),
1491 std::make_pair(".bound_tid.", KmpInt32PtrTy),
1492 std::make_pair(StringRef(), QualType()) // __context with shared vars
1494 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
1498 case OMPD_parallel_sections: {
1499 QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1);
1500 QualType KmpInt32PtrTy =
1501 Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
1502 Sema::CapturedParamNameType Params[] = {
1503 std::make_pair(".global_tid.", KmpInt32PtrTy),
1504 std::make_pair(".bound_tid.", KmpInt32PtrTy),
1505 std::make_pair(StringRef(), QualType()) // __context with shared vars
1507 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
1512 QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1);
1513 QualType Args[] = {Context.VoidPtrTy.withConst().withRestrict()};
1514 FunctionProtoType::ExtProtoInfo EPI;
1515 EPI.Variadic = true;
1516 QualType CopyFnType = Context.getFunctionType(Context.VoidTy, Args, EPI);
1517 Sema::CapturedParamNameType Params[] = {
1518 std::make_pair(".global_tid.", KmpInt32Ty),
1519 std::make_pair(".part_id.", KmpInt32Ty),
1520 std::make_pair(".privates.",
1521 Context.VoidPtrTy.withConst().withRestrict()),
1524 Context.getPointerType(CopyFnType).withConst().withRestrict()),
1525 std::make_pair(StringRef(), QualType()) // __context with shared vars
1527 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
1529 // Mark this captured region as inlined, because we don't use outlined
1530 // function directly.
1531 getCurCapturedRegion()->TheCapturedDecl->addAttr(
1532 AlwaysInlineAttr::CreateImplicit(
1533 Context, AlwaysInlineAttr::Keyword_forceinline, SourceRange()));
1536 case OMPD_ordered: {
1537 Sema::CapturedParamNameType Params[] = {
1538 std::make_pair(StringRef(), QualType()) // __context with shared vars
1540 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
1545 Sema::CapturedParamNameType Params[] = {
1546 std::make_pair(StringRef(), QualType()) // __context with shared vars
1548 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
1552 case OMPD_target_data:
1554 Sema::CapturedParamNameType Params[] = {
1555 std::make_pair(StringRef(), QualType()) // __context with shared vars
1557 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
1562 QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1);
1563 QualType KmpInt32PtrTy =
1564 Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
1565 Sema::CapturedParamNameType Params[] = {
1566 std::make_pair(".global_tid.", KmpInt32PtrTy),
1567 std::make_pair(".bound_tid.", KmpInt32PtrTy),
1568 std::make_pair(StringRef(), QualType()) // __context with shared vars
1570 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
1574 case OMPD_taskgroup: {
1575 Sema::CapturedParamNameType Params[] = {
1576 std::make_pair(StringRef(), QualType()) // __context with shared vars
1578 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
1582 case OMPD_taskloop: {
1583 Sema::CapturedParamNameType Params[] = {
1584 std::make_pair(StringRef(), QualType()) // __context with shared vars
1586 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
1590 case OMPD_taskloop_simd: {
1591 Sema::CapturedParamNameType Params[] = {
1592 std::make_pair(StringRef(), QualType()) // __context with shared vars
1594 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
1598 case OMPD_distribute: {
1599 Sema::CapturedParamNameType Params[] = {
1600 std::make_pair(StringRef(), QualType()) // __context with shared vars
1602 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
1606 case OMPD_threadprivate:
1607 case OMPD_taskyield:
1610 case OMPD_cancellation_point:
1613 llvm_unreachable("OpenMP Directive is not allowed");
1615 llvm_unreachable("Unknown OpenMP directive");
1619 StmtResult Sema::ActOnOpenMPRegionEnd(StmtResult S,
1620 ArrayRef<OMPClause *> Clauses) {
1621 if (!S.isUsable()) {
1622 ActOnCapturedRegionError();
1626 OMPOrderedClause *OC = nullptr;
1627 OMPScheduleClause *SC = nullptr;
1628 SmallVector<OMPLinearClause *, 4> LCs;
1629 // This is required for proper codegen.
1630 for (auto *Clause : Clauses) {
1631 if (isOpenMPPrivate(Clause->getClauseKind()) ||
1632 Clause->getClauseKind() == OMPC_copyprivate ||
1633 (getLangOpts().OpenMPUseTLS &&
1634 getASTContext().getTargetInfo().isTLSSupported() &&
1635 Clause->getClauseKind() == OMPC_copyin)) {
1636 DSAStack->setForceVarCapturing(Clause->getClauseKind() == OMPC_copyin);
1637 // Mark all variables in private list clauses as used in inner region.
1638 for (auto *VarRef : Clause->children()) {
1639 if (auto *E = cast_or_null<Expr>(VarRef)) {
1640 MarkDeclarationsReferencedInExpr(E);
1643 DSAStack->setForceVarCapturing(/*V=*/false);
1644 } else if (isParallelOrTaskRegion(DSAStack->getCurrentDirective()) &&
1645 Clause->getClauseKind() == OMPC_schedule) {
1646 // Mark all variables in private list clauses as used in inner region.
1647 // Required for proper codegen of combined directives.
1648 // TODO: add processing for other clauses.
1649 if (auto *E = cast_or_null<Expr>(
1650 cast<OMPScheduleClause>(Clause)->getHelperChunkSize()))
1651 MarkDeclarationsReferencedInExpr(E);
1653 if (Clause->getClauseKind() == OMPC_schedule)
1654 SC = cast<OMPScheduleClause>(Clause);
1655 else if (Clause->getClauseKind() == OMPC_ordered)
1656 OC = cast<OMPOrderedClause>(Clause);
1657 else if (Clause->getClauseKind() == OMPC_linear)
1658 LCs.push_back(cast<OMPLinearClause>(Clause));
1660 bool ErrorFound = false;
1661 // OpenMP, 2.7.1 Loop Construct, Restrictions
1662 // The nonmonotonic modifier cannot be specified if an ordered clause is
1665 (SC->getFirstScheduleModifier() == OMPC_SCHEDULE_MODIFIER_nonmonotonic ||
1666 SC->getSecondScheduleModifier() ==
1667 OMPC_SCHEDULE_MODIFIER_nonmonotonic) &&
1669 Diag(SC->getFirstScheduleModifier() == OMPC_SCHEDULE_MODIFIER_nonmonotonic
1670 ? SC->getFirstScheduleModifierLoc()
1671 : SC->getSecondScheduleModifierLoc(),
1672 diag::err_omp_schedule_nonmonotonic_ordered)
1673 << SourceRange(OC->getLocStart(), OC->getLocEnd());
1676 if (!LCs.empty() && OC && OC->getNumForLoops()) {
1677 for (auto *C : LCs) {
1678 Diag(C->getLocStart(), diag::err_omp_linear_ordered)
1679 << SourceRange(OC->getLocStart(), OC->getLocEnd());
1684 ActOnCapturedRegionError();
1687 return ActOnCapturedRegionEnd(S.get());
1690 static bool CheckNestingOfRegions(Sema &SemaRef, DSAStackTy *Stack,
1691 OpenMPDirectiveKind CurrentRegion,
1692 const DeclarationNameInfo &CurrentName,
1693 OpenMPDirectiveKind CancelRegion,
1694 SourceLocation StartLoc) {
1695 // Allowed nesting of constructs
1696 // +------------------+-----------------+------------------------------------+
1697 // | Parent directive | Child directive | Closely (!), No-Closely(+), Both(*)|
1698 // +------------------+-----------------+------------------------------------+
1699 // | parallel | parallel | * |
1700 // | parallel | for | * |
1701 // | parallel | for simd | * |
1702 // | parallel | master | * |
1703 // | parallel | critical | * |
1704 // | parallel | simd | * |
1705 // | parallel | sections | * |
1706 // | parallel | section | + |
1707 // | parallel | single | * |
1708 // | parallel | parallel for | * |
1709 // | parallel |parallel for simd| * |
1710 // | parallel |parallel sections| * |
1711 // | parallel | task | * |
1712 // | parallel | taskyield | * |
1713 // | parallel | barrier | * |
1714 // | parallel | taskwait | * |
1715 // | parallel | taskgroup | * |
1716 // | parallel | flush | * |
1717 // | parallel | ordered | + |
1718 // | parallel | atomic | * |
1719 // | parallel | target | * |
1720 // | parallel | teams | + |
1721 // | parallel | cancellation | |
1723 // | parallel | cancel | ! |
1724 // | parallel | taskloop | * |
1725 // | parallel | taskloop simd | * |
1726 // | parallel | distribute | |
1727 // +------------------+-----------------+------------------------------------+
1728 // | for | parallel | * |
1729 // | for | for | + |
1730 // | for | for simd | + |
1731 // | for | master | + |
1732 // | for | critical | * |
1733 // | for | simd | * |
1734 // | for | sections | + |
1735 // | for | section | + |
1736 // | for | single | + |
1737 // | for | parallel for | * |
1738 // | for |parallel for simd| * |
1739 // | for |parallel sections| * |
1740 // | for | task | * |
1741 // | for | taskyield | * |
1742 // | for | barrier | + |
1743 // | for | taskwait | * |
1744 // | for | taskgroup | * |
1745 // | for | flush | * |
1746 // | for | ordered | * (if construct is ordered) |
1747 // | for | atomic | * |
1748 // | for | target | * |
1749 // | for | teams | + |
1750 // | for | cancellation | |
1752 // | for | cancel | ! |
1753 // | for | taskloop | * |
1754 // | for | taskloop simd | * |
1755 // | for | distribute | |
1756 // +------------------+-----------------+------------------------------------+
1757 // | master | parallel | * |
1758 // | master | for | + |
1759 // | master | for simd | + |
1760 // | master | master | * |
1761 // | master | critical | * |
1762 // | master | simd | * |
1763 // | master | sections | + |
1764 // | master | section | + |
1765 // | master | single | + |
1766 // | master | parallel for | * |
1767 // | master |parallel for simd| * |
1768 // | master |parallel sections| * |
1769 // | master | task | * |
1770 // | master | taskyield | * |
1771 // | master | barrier | + |
1772 // | master | taskwait | * |
1773 // | master | taskgroup | * |
1774 // | master | flush | * |
1775 // | master | ordered | + |
1776 // | master | atomic | * |
1777 // | master | target | * |
1778 // | master | teams | + |
1779 // | master | cancellation | |
1781 // | master | cancel | |
1782 // | master | taskloop | * |
1783 // | master | taskloop simd | * |
1784 // | master | distribute | |
1785 // +------------------+-----------------+------------------------------------+
1786 // | critical | parallel | * |
1787 // | critical | for | + |
1788 // | critical | for simd | + |
1789 // | critical | master | * |
1790 // | critical | critical | * (should have different names) |
1791 // | critical | simd | * |
1792 // | critical | sections | + |
1793 // | critical | section | + |
1794 // | critical | single | + |
1795 // | critical | parallel for | * |
1796 // | critical |parallel for simd| * |
1797 // | critical |parallel sections| * |
1798 // | critical | task | * |
1799 // | critical | taskyield | * |
1800 // | critical | barrier | + |
1801 // | critical | taskwait | * |
1802 // | critical | taskgroup | * |
1803 // | critical | ordered | + |
1804 // | critical | atomic | * |
1805 // | critical | target | * |
1806 // | critical | teams | + |
1807 // | critical | cancellation | |
1809 // | critical | cancel | |
1810 // | critical | taskloop | * |
1811 // | critical | taskloop simd | * |
1812 // | critical | distribute | |
1813 // +------------------+-----------------+------------------------------------+
1814 // | simd | parallel | |
1816 // | simd | for simd | |
1817 // | simd | master | |
1818 // | simd | critical | |
1819 // | simd | simd | |
1820 // | simd | sections | |
1821 // | simd | section | |
1822 // | simd | single | |
1823 // | simd | parallel for | |
1824 // | simd |parallel for simd| |
1825 // | simd |parallel sections| |
1826 // | simd | task | |
1827 // | simd | taskyield | |
1828 // | simd | barrier | |
1829 // | simd | taskwait | |
1830 // | simd | taskgroup | |
1831 // | simd | flush | |
1832 // | simd | ordered | + (with simd clause) |
1833 // | simd | atomic | |
1834 // | simd | target | |
1835 // | simd | teams | |
1836 // | simd | cancellation | |
1838 // | simd | cancel | |
1839 // | simd | taskloop | |
1840 // | simd | taskloop simd | |
1841 // | simd | distribute | |
1842 // +------------------+-----------------+------------------------------------+
1843 // | for simd | parallel | |
1844 // | for simd | for | |
1845 // | for simd | for simd | |
1846 // | for simd | master | |
1847 // | for simd | critical | |
1848 // | for simd | simd | |
1849 // | for simd | sections | |
1850 // | for simd | section | |
1851 // | for simd | single | |
1852 // | for simd | parallel for | |
1853 // | for simd |parallel for simd| |
1854 // | for simd |parallel sections| |
1855 // | for simd | task | |
1856 // | for simd | taskyield | |
1857 // | for simd | barrier | |
1858 // | for simd | taskwait | |
1859 // | for simd | taskgroup | |
1860 // | for simd | flush | |
1861 // | for simd | ordered | + (with simd clause) |
1862 // | for simd | atomic | |
1863 // | for simd | target | |
1864 // | for simd | teams | |
1865 // | for simd | cancellation | |
1867 // | for simd | cancel | |
1868 // | for simd | taskloop | |
1869 // | for simd | taskloop simd | |
1870 // | for simd | distribute | |
1871 // +------------------+-----------------+------------------------------------+
1872 // | parallel for simd| parallel | |
1873 // | parallel for simd| for | |
1874 // | parallel for simd| for simd | |
1875 // | parallel for simd| master | |
1876 // | parallel for simd| critical | |
1877 // | parallel for simd| simd | |
1878 // | parallel for simd| sections | |
1879 // | parallel for simd| section | |
1880 // | parallel for simd| single | |
1881 // | parallel for simd| parallel for | |
1882 // | parallel for simd|parallel for simd| |
1883 // | parallel for simd|parallel sections| |
1884 // | parallel for simd| task | |
1885 // | parallel for simd| taskyield | |
1886 // | parallel for simd| barrier | |
1887 // | parallel for simd| taskwait | |
1888 // | parallel for simd| taskgroup | |
1889 // | parallel for simd| flush | |
1890 // | parallel for simd| ordered | + (with simd clause) |
1891 // | parallel for simd| atomic | |
1892 // | parallel for simd| target | |
1893 // | parallel for simd| teams | |
1894 // | parallel for simd| cancellation | |
1896 // | parallel for simd| cancel | |
1897 // | parallel for simd| taskloop | |
1898 // | parallel for simd| taskloop simd | |
1899 // | parallel for simd| distribute | |
1900 // +------------------+-----------------+------------------------------------+
1901 // | sections | parallel | * |
1902 // | sections | for | + |
1903 // | sections | for simd | + |
1904 // | sections | master | + |
1905 // | sections | critical | * |
1906 // | sections | simd | * |
1907 // | sections | sections | + |
1908 // | sections | section | * |
1909 // | sections | single | + |
1910 // | sections | parallel for | * |
1911 // | sections |parallel for simd| * |
1912 // | sections |parallel sections| * |
1913 // | sections | task | * |
1914 // | sections | taskyield | * |
1915 // | sections | barrier | + |
1916 // | sections | taskwait | * |
1917 // | sections | taskgroup | * |
1918 // | sections | flush | * |
1919 // | sections | ordered | + |
1920 // | sections | atomic | * |
1921 // | sections | target | * |
1922 // | sections | teams | + |
1923 // | sections | cancellation | |
1925 // | sections | cancel | ! |
1926 // | sections | taskloop | * |
1927 // | sections | taskloop simd | * |
1928 // | sections | distribute | |
1929 // +------------------+-----------------+------------------------------------+
1930 // | section | parallel | * |
1931 // | section | for | + |
1932 // | section | for simd | + |
1933 // | section | master | + |
1934 // | section | critical | * |
1935 // | section | simd | * |
1936 // | section | sections | + |
1937 // | section | section | + |
1938 // | section | single | + |
1939 // | section | parallel for | * |
1940 // | section |parallel for simd| * |
1941 // | section |parallel sections| * |
1942 // | section | task | * |
1943 // | section | taskyield | * |
1944 // | section | barrier | + |
1945 // | section | taskwait | * |
1946 // | section | taskgroup | * |
1947 // | section | flush | * |
1948 // | section | ordered | + |
1949 // | section | atomic | * |
1950 // | section | target | * |
1951 // | section | teams | + |
1952 // | section | cancellation | |
1954 // | section | cancel | ! |
1955 // | section | taskloop | * |
1956 // | section | taskloop simd | * |
1957 // | section | distribute | |
1958 // +------------------+-----------------+------------------------------------+
1959 // | single | parallel | * |
1960 // | single | for | + |
1961 // | single | for simd | + |
1962 // | single | master | + |
1963 // | single | critical | * |
1964 // | single | simd | * |
1965 // | single | sections | + |
1966 // | single | section | + |
1967 // | single | single | + |
1968 // | single | parallel for | * |
1969 // | single |parallel for simd| * |
1970 // | single |parallel sections| * |
1971 // | single | task | * |
1972 // | single | taskyield | * |
1973 // | single | barrier | + |
1974 // | single | taskwait | * |
1975 // | single | taskgroup | * |
1976 // | single | flush | * |
1977 // | single | ordered | + |
1978 // | single | atomic | * |
1979 // | single | target | * |
1980 // | single | teams | + |
1981 // | single | cancellation | |
1983 // | single | cancel | |
1984 // | single | taskloop | * |
1985 // | single | taskloop simd | * |
1986 // | single | distribute | |
1987 // +------------------+-----------------+------------------------------------+
1988 // | parallel for | parallel | * |
1989 // | parallel for | for | + |
1990 // | parallel for | for simd | + |
1991 // | parallel for | master | + |
1992 // | parallel for | critical | * |
1993 // | parallel for | simd | * |
1994 // | parallel for | sections | + |
1995 // | parallel for | section | + |
1996 // | parallel for | single | + |
1997 // | parallel for | parallel for | * |
1998 // | parallel for |parallel for simd| * |
1999 // | parallel for |parallel sections| * |
2000 // | parallel for | task | * |
2001 // | parallel for | taskyield | * |
2002 // | parallel for | barrier | + |
2003 // | parallel for | taskwait | * |
2004 // | parallel for | taskgroup | * |
2005 // | parallel for | flush | * |
2006 // | parallel for | ordered | * (if construct is ordered) |
2007 // | parallel for | atomic | * |
2008 // | parallel for | target | * |
2009 // | parallel for | teams | + |
2010 // | parallel for | cancellation | |
2012 // | parallel for | cancel | ! |
2013 // | parallel for | taskloop | * |
2014 // | parallel for | taskloop simd | * |
2015 // | parallel for | distribute | |
2016 // +------------------+-----------------+------------------------------------+
2017 // | parallel sections| parallel | * |
2018 // | parallel sections| for | + |
2019 // | parallel sections| for simd | + |
2020 // | parallel sections| master | + |
2021 // | parallel sections| critical | + |
2022 // | parallel sections| simd | * |
2023 // | parallel sections| sections | + |
2024 // | parallel sections| section | * |
2025 // | parallel sections| single | + |
2026 // | parallel sections| parallel for | * |
2027 // | parallel sections|parallel for simd| * |
2028 // | parallel sections|parallel sections| * |
2029 // | parallel sections| task | * |
2030 // | parallel sections| taskyield | * |
2031 // | parallel sections| barrier | + |
2032 // | parallel sections| taskwait | * |
2033 // | parallel sections| taskgroup | * |
2034 // | parallel sections| flush | * |
2035 // | parallel sections| ordered | + |
2036 // | parallel sections| atomic | * |
2037 // | parallel sections| target | * |
2038 // | parallel sections| teams | + |
2039 // | parallel sections| cancellation | |
2041 // | parallel sections| cancel | ! |
2042 // | parallel sections| taskloop | * |
2043 // | parallel sections| taskloop simd | * |
2044 // | parallel sections| distribute | |
2045 // +------------------+-----------------+------------------------------------+
2046 // | task | parallel | * |
2047 // | task | for | + |
2048 // | task | for simd | + |
2049 // | task | master | + |
2050 // | task | critical | * |
2051 // | task | simd | * |
2052 // | task | sections | + |
2053 // | task | section | + |
2054 // | task | single | + |
2055 // | task | parallel for | * |
2056 // | task |parallel for simd| * |
2057 // | task |parallel sections| * |
2058 // | task | task | * |
2059 // | task | taskyield | * |
2060 // | task | barrier | + |
2061 // | task | taskwait | * |
2062 // | task | taskgroup | * |
2063 // | task | flush | * |
2064 // | task | ordered | + |
2065 // | task | atomic | * |
2066 // | task | target | * |
2067 // | task | teams | + |
2068 // | task | cancellation | |
2070 // | task | cancel | ! |
2071 // | task | taskloop | * |
2072 // | task | taskloop simd | * |
2073 // | task | distribute | |
2074 // +------------------+-----------------+------------------------------------+
2075 // | ordered | parallel | * |
2076 // | ordered | for | + |
2077 // | ordered | for simd | + |
2078 // | ordered | master | * |
2079 // | ordered | critical | * |
2080 // | ordered | simd | * |
2081 // | ordered | sections | + |
2082 // | ordered | section | + |
2083 // | ordered | single | + |
2084 // | ordered | parallel for | * |
2085 // | ordered |parallel for simd| * |
2086 // | ordered |parallel sections| * |
2087 // | ordered | task | * |
2088 // | ordered | taskyield | * |
2089 // | ordered | barrier | + |
2090 // | ordered | taskwait | * |
2091 // | ordered | taskgroup | * |
2092 // | ordered | flush | * |
2093 // | ordered | ordered | + |
2094 // | ordered | atomic | * |
2095 // | ordered | target | * |
2096 // | ordered | teams | + |
2097 // | ordered | cancellation | |
2099 // | ordered | cancel | |
2100 // | ordered | taskloop | * |
2101 // | ordered | taskloop simd | * |
2102 // | ordered | distribute | |
2103 // +------------------+-----------------+------------------------------------+
2104 // | atomic | parallel | |
2105 // | atomic | for | |
2106 // | atomic | for simd | |
2107 // | atomic | master | |
2108 // | atomic | critical | |
2109 // | atomic | simd | |
2110 // | atomic | sections | |
2111 // | atomic | section | |
2112 // | atomic | single | |
2113 // | atomic | parallel for | |
2114 // | atomic |parallel for simd| |
2115 // | atomic |parallel sections| |
2116 // | atomic | task | |
2117 // | atomic | taskyield | |
2118 // | atomic | barrier | |
2119 // | atomic | taskwait | |
2120 // | atomic | taskgroup | |
2121 // | atomic | flush | |
2122 // | atomic | ordered | |
2123 // | atomic | atomic | |
2124 // | atomic | target | |
2125 // | atomic | teams | |
2126 // | atomic | cancellation | |
2128 // | atomic | cancel | |
2129 // | atomic | taskloop | |
2130 // | atomic | taskloop simd | |
2131 // | atomic | distribute | |
2132 // +------------------+-----------------+------------------------------------+
2133 // | target | parallel | * |
2134 // | target | for | * |
2135 // | target | for simd | * |
2136 // | target | master | * |
2137 // | target | critical | * |
2138 // | target | simd | * |
2139 // | target | sections | * |
2140 // | target | section | * |
2141 // | target | single | * |
2142 // | target | parallel for | * |
2143 // | target |parallel for simd| * |
2144 // | target |parallel sections| * |
2145 // | target | task | * |
2146 // | target | taskyield | * |
2147 // | target | barrier | * |
2148 // | target | taskwait | * |
2149 // | target | taskgroup | * |
2150 // | target | flush | * |
2151 // | target | ordered | * |
2152 // | target | atomic | * |
2153 // | target | target | * |
2154 // | target | teams | * |
2155 // | target | cancellation | |
2157 // | target | cancel | |
2158 // | target | taskloop | * |
2159 // | target | taskloop simd | * |
2160 // | target | distribute | |
2161 // +------------------+-----------------+------------------------------------+
2162 // | teams | parallel | * |
2163 // | teams | for | + |
2164 // | teams | for simd | + |
2165 // | teams | master | + |
2166 // | teams | critical | + |
2167 // | teams | simd | + |
2168 // | teams | sections | + |
2169 // | teams | section | + |
2170 // | teams | single | + |
2171 // | teams | parallel for | * |
2172 // | teams |parallel for simd| * |
2173 // | teams |parallel sections| * |
2174 // | teams | task | + |
2175 // | teams | taskyield | + |
2176 // | teams | barrier | + |
2177 // | teams | taskwait | + |
2178 // | teams | taskgroup | + |
2179 // | teams | flush | + |
2180 // | teams | ordered | + |
2181 // | teams | atomic | + |
2182 // | teams | target | + |
2183 // | teams | teams | + |
2184 // | teams | cancellation | |
2186 // | teams | cancel | |
2187 // | teams | taskloop | + |
2188 // | teams | taskloop simd | + |
2189 // | teams | distribute | ! |
2190 // +------------------+-----------------+------------------------------------+
2191 // | taskloop | parallel | * |
2192 // | taskloop | for | + |
2193 // | taskloop | for simd | + |
2194 // | taskloop | master | + |
2195 // | taskloop | critical | * |
2196 // | taskloop | simd | * |
2197 // | taskloop | sections | + |
2198 // | taskloop | section | + |
2199 // | taskloop | single | + |
2200 // | taskloop | parallel for | * |
2201 // | taskloop |parallel for simd| * |
2202 // | taskloop |parallel sections| * |
2203 // | taskloop | task | * |
2204 // | taskloop | taskyield | * |
2205 // | taskloop | barrier | + |
2206 // | taskloop | taskwait | * |
2207 // | taskloop | taskgroup | * |
2208 // | taskloop | flush | * |
2209 // | taskloop | ordered | + |
2210 // | taskloop | atomic | * |
2211 // | taskloop | target | * |
2212 // | taskloop | teams | + |
2213 // | taskloop | cancellation | |
2215 // | taskloop | cancel | |
2216 // | taskloop | taskloop | * |
2217 // | taskloop | distribute | |
2218 // +------------------+-----------------+------------------------------------+
2219 // | taskloop simd | parallel | |
2220 // | taskloop simd | for | |
2221 // | taskloop simd | for simd | |
2222 // | taskloop simd | master | |
2223 // | taskloop simd | critical | |
2224 // | taskloop simd | simd | |
2225 // | taskloop simd | sections | |
2226 // | taskloop simd | section | |
2227 // | taskloop simd | single | |
2228 // | taskloop simd | parallel for | |
2229 // | taskloop simd |parallel for simd| |
2230 // | taskloop simd |parallel sections| |
2231 // | taskloop simd | task | |
2232 // | taskloop simd | taskyield | |
2233 // | taskloop simd | barrier | |
2234 // | taskloop simd | taskwait | |
2235 // | taskloop simd | taskgroup | |
2236 // | taskloop simd | flush | |
2237 // | taskloop simd | ordered | + (with simd clause) |
2238 // | taskloop simd | atomic | |
2239 // | taskloop simd | target | |
2240 // | taskloop simd | teams | |
2241 // | taskloop simd | cancellation | |
2243 // | taskloop simd | cancel | |
2244 // | taskloop simd | taskloop | |
2245 // | taskloop simd | taskloop simd | |
2246 // | taskloop simd | distribute | |
2247 // +------------------+-----------------+------------------------------------+
2248 // | distribute | parallel | * |
2249 // | distribute | for | * |
2250 // | distribute | for simd | * |
2251 // | distribute | master | * |
2252 // | distribute | critical | * |
2253 // | distribute | simd | * |
2254 // | distribute | sections | * |
2255 // | distribute | section | * |
2256 // | distribute | single | * |
2257 // | distribute | parallel for | * |
2258 // | distribute |parallel for simd| * |
2259 // | distribute |parallel sections| * |
2260 // | distribute | task | * |
2261 // | distribute | taskyield | * |
2262 // | distribute | barrier | * |
2263 // | distribute | taskwait | * |
2264 // | distribute | taskgroup | * |
2265 // | distribute | flush | * |
2266 // | distribute | ordered | + |
2267 // | distribute | atomic | * |
2268 // | distribute | target | |
2269 // | distribute | teams | |
2270 // | distribute | cancellation | + |
2272 // | distribute | cancel | + |
2273 // | distribute | taskloop | * |
2274 // | distribute | taskloop simd | * |
2275 // | distribute | distribute | |
2276 // +------------------+-----------------+------------------------------------+
2277 if (Stack->getCurScope()) {
2278 auto ParentRegion = Stack->getParentDirective();
2279 bool NestingProhibited = false;
2280 bool CloseNesting = true;
2283 ShouldBeInParallelRegion,
2284 ShouldBeInOrderedRegion,
2285 ShouldBeInTargetRegion,
2286 ShouldBeInTeamsRegion
2287 } Recommend = NoRecommend;
2288 if (isOpenMPSimdDirective(ParentRegion) && CurrentRegion != OMPD_ordered) {
2289 // OpenMP [2.16, Nesting of Regions]
2290 // OpenMP constructs may not be nested inside a simd region.
2291 // OpenMP [2.8.1,simd Construct, Restrictions]
2292 // An ordered construct with the simd clause is the only OpenMP construct
2293 // that can appear in the simd region.
2294 SemaRef.Diag(StartLoc, diag::err_omp_prohibited_region_simd);
2297 if (ParentRegion == OMPD_atomic) {
2298 // OpenMP [2.16, Nesting of Regions]
2299 // OpenMP constructs may not be nested inside an atomic region.
2300 SemaRef.Diag(StartLoc, diag::err_omp_prohibited_region_atomic);
2303 if (CurrentRegion == OMPD_section) {
2304 // OpenMP [2.7.2, sections Construct, Restrictions]
2305 // Orphaned section directives are prohibited. That is, the section
2306 // directives must appear within the sections construct and must not be
2307 // encountered elsewhere in the sections region.
2308 if (ParentRegion != OMPD_sections &&
2309 ParentRegion != OMPD_parallel_sections) {
2310 SemaRef.Diag(StartLoc, diag::err_omp_orphaned_section_directive)
2311 << (ParentRegion != OMPD_unknown)
2312 << getOpenMPDirectiveName(ParentRegion);
2317 // Allow some constructs to be orphaned (they could be used in functions,
2318 // called from OpenMP regions with the required preconditions).
2319 if (ParentRegion == OMPD_unknown)
2321 if (CurrentRegion == OMPD_cancellation_point ||
2322 CurrentRegion == OMPD_cancel) {
2323 // OpenMP [2.16, Nesting of Regions]
2324 // A cancellation point construct for which construct-type-clause is
2325 // taskgroup must be nested inside a task construct. A cancellation
2326 // point construct for which construct-type-clause is not taskgroup must
2327 // be closely nested inside an OpenMP construct that matches the type
2328 // specified in construct-type-clause.
2329 // A cancel construct for which construct-type-clause is taskgroup must be
2330 // nested inside a task construct. A cancel construct for which
2331 // construct-type-clause is not taskgroup must be closely nested inside an
2332 // OpenMP construct that matches the type specified in
2333 // construct-type-clause.
2335 !((CancelRegion == OMPD_parallel && ParentRegion == OMPD_parallel) ||
2336 (CancelRegion == OMPD_for &&
2337 (ParentRegion == OMPD_for || ParentRegion == OMPD_parallel_for)) ||
2338 (CancelRegion == OMPD_taskgroup && ParentRegion == OMPD_task) ||
2339 (CancelRegion == OMPD_sections &&
2340 (ParentRegion == OMPD_section || ParentRegion == OMPD_sections ||
2341 ParentRegion == OMPD_parallel_sections)));
2342 } else if (CurrentRegion == OMPD_master) {
2343 // OpenMP [2.16, Nesting of Regions]
2344 // A master region may not be closely nested inside a worksharing,
2345 // atomic, or explicit task region.
2346 NestingProhibited = isOpenMPWorksharingDirective(ParentRegion) ||
2347 ParentRegion == OMPD_task ||
2348 isOpenMPTaskLoopDirective(ParentRegion);
2349 } else if (CurrentRegion == OMPD_critical && CurrentName.getName()) {
2350 // OpenMP [2.16, Nesting of Regions]
2351 // A critical region may not be nested (closely or otherwise) inside a
2352 // critical region with the same name. Note that this restriction is not
2353 // sufficient to prevent deadlock.
2354 SourceLocation PreviousCriticalLoc;
2356 Stack->hasDirective([CurrentName, &PreviousCriticalLoc](
2357 OpenMPDirectiveKind K,
2358 const DeclarationNameInfo &DNI,
2361 if (K == OMPD_critical &&
2362 DNI.getName() == CurrentName.getName()) {
2363 PreviousCriticalLoc = Loc;
2368 false /* skip top directive */);
2370 SemaRef.Diag(StartLoc,
2371 diag::err_omp_prohibited_region_critical_same_name)
2372 << CurrentName.getName();
2373 if (PreviousCriticalLoc.isValid())
2374 SemaRef.Diag(PreviousCriticalLoc,
2375 diag::note_omp_previous_critical_region);
2378 } else if (CurrentRegion == OMPD_barrier) {
2379 // OpenMP [2.16, Nesting of Regions]
2380 // A barrier region may not be closely nested inside a worksharing,
2381 // explicit task, critical, ordered, atomic, or master region.
2383 isOpenMPWorksharingDirective(ParentRegion) ||
2384 ParentRegion == OMPD_task || ParentRegion == OMPD_master ||
2385 ParentRegion == OMPD_critical || ParentRegion == OMPD_ordered ||
2386 isOpenMPTaskLoopDirective(ParentRegion);
2387 } else if (isOpenMPWorksharingDirective(CurrentRegion) &&
2388 !isOpenMPParallelDirective(CurrentRegion)) {
2389 // OpenMP [2.16, Nesting of Regions]
2390 // A worksharing region may not be closely nested inside a worksharing,
2391 // explicit task, critical, ordered, atomic, or master region.
2393 isOpenMPWorksharingDirective(ParentRegion) ||
2394 ParentRegion == OMPD_task || ParentRegion == OMPD_master ||
2395 ParentRegion == OMPD_critical || ParentRegion == OMPD_ordered ||
2396 isOpenMPTaskLoopDirective(ParentRegion);
2397 Recommend = ShouldBeInParallelRegion;
2398 } else if (CurrentRegion == OMPD_ordered) {
2399 // OpenMP [2.16, Nesting of Regions]
2400 // An ordered region may not be closely nested inside a critical,
2401 // atomic, or explicit task region.
2402 // An ordered region must be closely nested inside a loop region (or
2403 // parallel loop region) with an ordered clause.
2404 // OpenMP [2.8.1,simd Construct, Restrictions]
2405 // An ordered construct with the simd clause is the only OpenMP construct
2406 // that can appear in the simd region.
2407 NestingProhibited = ParentRegion == OMPD_critical ||
2408 ParentRegion == OMPD_task ||
2409 isOpenMPTaskLoopDirective(ParentRegion) ||
2410 !(isOpenMPSimdDirective(ParentRegion) ||
2411 Stack->isParentOrderedRegion());
2412 Recommend = ShouldBeInOrderedRegion;
2413 } else if (isOpenMPTeamsDirective(CurrentRegion)) {
2414 // OpenMP [2.16, Nesting of Regions]
2415 // If specified, a teams construct must be contained within a target
2417 NestingProhibited = ParentRegion != OMPD_target;
2418 Recommend = ShouldBeInTargetRegion;
2419 Stack->setParentTeamsRegionLoc(Stack->getConstructLoc());
2421 if (!NestingProhibited && isOpenMPTeamsDirective(ParentRegion)) {
2422 // OpenMP [2.16, Nesting of Regions]
2423 // distribute, parallel, parallel sections, parallel workshare, and the
2424 // parallel loop and parallel loop SIMD constructs are the only OpenMP
2425 // constructs that can be closely nested in the teams region.
2426 NestingProhibited = !isOpenMPParallelDirective(CurrentRegion) &&
2427 !isOpenMPDistributeDirective(CurrentRegion);
2428 Recommend = ShouldBeInParallelRegion;
2430 if (!NestingProhibited && isOpenMPDistributeDirective(CurrentRegion)) {
2431 // OpenMP 4.5 [2.17 Nesting of Regions]
2432 // The region associated with the distribute construct must be strictly
2433 // nested inside a teams region
2434 NestingProhibited = !isOpenMPTeamsDirective(ParentRegion);
2435 Recommend = ShouldBeInTeamsRegion;
2437 if (NestingProhibited) {
2438 SemaRef.Diag(StartLoc, diag::err_omp_prohibited_region)
2439 << CloseNesting << getOpenMPDirectiveName(ParentRegion) << Recommend
2440 << getOpenMPDirectiveName(CurrentRegion);
2447 static bool checkIfClauses(Sema &S, OpenMPDirectiveKind Kind,
2448 ArrayRef<OMPClause *> Clauses,
2449 ArrayRef<OpenMPDirectiveKind> AllowedNameModifiers) {
2450 bool ErrorFound = false;
2451 unsigned NamedModifiersNumber = 0;
2452 SmallVector<const OMPIfClause *, OMPC_unknown + 1> FoundNameModifiers(
2454 SmallVector<SourceLocation, 4> NameModifierLoc;
2455 for (const auto *C : Clauses) {
2456 if (const auto *IC = dyn_cast_or_null<OMPIfClause>(C)) {
2457 // At most one if clause without a directive-name-modifier can appear on
2459 OpenMPDirectiveKind CurNM = IC->getNameModifier();
2460 if (FoundNameModifiers[CurNM]) {
2461 S.Diag(C->getLocStart(), diag::err_omp_more_one_clause)
2462 << getOpenMPDirectiveName(Kind) << getOpenMPClauseName(OMPC_if)
2463 << (CurNM != OMPD_unknown) << getOpenMPDirectiveName(CurNM);
2465 } else if (CurNM != OMPD_unknown) {
2466 NameModifierLoc.push_back(IC->getNameModifierLoc());
2467 ++NamedModifiersNumber;
2469 FoundNameModifiers[CurNM] = IC;
2470 if (CurNM == OMPD_unknown)
2472 // Check if the specified name modifier is allowed for the current
2474 // At most one if clause with the particular directive-name-modifier can
2475 // appear on the directive.
2476 bool MatchFound = false;
2477 for (auto NM : AllowedNameModifiers) {
2484 S.Diag(IC->getNameModifierLoc(),
2485 diag::err_omp_wrong_if_directive_name_modifier)
2486 << getOpenMPDirectiveName(CurNM) << getOpenMPDirectiveName(Kind);
2491 // If any if clause on the directive includes a directive-name-modifier then
2492 // all if clauses on the directive must include a directive-name-modifier.
2493 if (FoundNameModifiers[OMPD_unknown] && NamedModifiersNumber > 0) {
2494 if (NamedModifiersNumber == AllowedNameModifiers.size()) {
2495 S.Diag(FoundNameModifiers[OMPD_unknown]->getLocStart(),
2496 diag::err_omp_no_more_if_clause);
2499 std::string Sep(", ");
2500 unsigned AllowedCnt = 0;
2501 unsigned TotalAllowedNum =
2502 AllowedNameModifiers.size() - NamedModifiersNumber;
2503 for (unsigned Cnt = 0, End = AllowedNameModifiers.size(); Cnt < End;
2505 OpenMPDirectiveKind NM = AllowedNameModifiers[Cnt];
2506 if (!FoundNameModifiers[NM]) {
2508 Values += getOpenMPDirectiveName(NM);
2510 if (AllowedCnt + 2 == TotalAllowedNum)
2512 else if (AllowedCnt + 1 != TotalAllowedNum)
2517 S.Diag(FoundNameModifiers[OMPD_unknown]->getCondition()->getLocStart(),
2518 diag::err_omp_unnamed_if_clause)
2519 << (TotalAllowedNum > 1) << Values;
2521 for (auto Loc : NameModifierLoc) {
2522 S.Diag(Loc, diag::note_omp_previous_named_if_clause);
2529 StmtResult Sema::ActOnOpenMPExecutableDirective(
2530 OpenMPDirectiveKind Kind, const DeclarationNameInfo &DirName,
2531 OpenMPDirectiveKind CancelRegion, ArrayRef<OMPClause *> Clauses,
2532 Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc) {
2533 StmtResult Res = StmtError();
2534 if (CheckNestingOfRegions(*this, DSAStack, Kind, DirName, CancelRegion,
2538 llvm::SmallVector<OMPClause *, 8> ClausesWithImplicit;
2539 llvm::DenseMap<VarDecl *, Expr *> VarsWithInheritedDSA;
2540 bool ErrorFound = false;
2541 ClausesWithImplicit.append(Clauses.begin(), Clauses.end());
2543 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
2545 // Check default data sharing attributes for referenced variables.
2546 DSAAttrChecker DSAChecker(DSAStack, *this, cast<CapturedStmt>(AStmt));
2547 DSAChecker.Visit(cast<CapturedStmt>(AStmt)->getCapturedStmt());
2548 if (DSAChecker.isErrorFound())
2550 // Generate list of implicitly defined firstprivate variables.
2551 VarsWithInheritedDSA = DSAChecker.getVarsWithInheritedDSA();
2553 if (!DSAChecker.getImplicitFirstprivate().empty()) {
2554 if (OMPClause *Implicit = ActOnOpenMPFirstprivateClause(
2555 DSAChecker.getImplicitFirstprivate(), SourceLocation(),
2556 SourceLocation(), SourceLocation())) {
2557 ClausesWithImplicit.push_back(Implicit);
2558 ErrorFound = cast<OMPFirstprivateClause>(Implicit)->varlist_size() !=
2559 DSAChecker.getImplicitFirstprivate().size();
2565 llvm::SmallVector<OpenMPDirectiveKind, 4> AllowedNameModifiers;
2568 Res = ActOnOpenMPParallelDirective(ClausesWithImplicit, AStmt, StartLoc,
2570 AllowedNameModifiers.push_back(OMPD_parallel);
2573 Res = ActOnOpenMPSimdDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc,
2574 VarsWithInheritedDSA);
2577 Res = ActOnOpenMPForDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc,
2578 VarsWithInheritedDSA);
2581 Res = ActOnOpenMPForSimdDirective(ClausesWithImplicit, AStmt, StartLoc,
2582 EndLoc, VarsWithInheritedDSA);
2585 Res = ActOnOpenMPSectionsDirective(ClausesWithImplicit, AStmt, StartLoc,
2589 assert(ClausesWithImplicit.empty() &&
2590 "No clauses are allowed for 'omp section' directive");
2591 Res = ActOnOpenMPSectionDirective(AStmt, StartLoc, EndLoc);
2594 Res = ActOnOpenMPSingleDirective(ClausesWithImplicit, AStmt, StartLoc,
2598 assert(ClausesWithImplicit.empty() &&
2599 "No clauses are allowed for 'omp master' directive");
2600 Res = ActOnOpenMPMasterDirective(AStmt, StartLoc, EndLoc);
2603 Res = ActOnOpenMPCriticalDirective(DirName, ClausesWithImplicit, AStmt,
2606 case OMPD_parallel_for:
2607 Res = ActOnOpenMPParallelForDirective(ClausesWithImplicit, AStmt, StartLoc,
2608 EndLoc, VarsWithInheritedDSA);
2609 AllowedNameModifiers.push_back(OMPD_parallel);
2611 case OMPD_parallel_for_simd:
2612 Res = ActOnOpenMPParallelForSimdDirective(
2613 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
2614 AllowedNameModifiers.push_back(OMPD_parallel);
2616 case OMPD_parallel_sections:
2617 Res = ActOnOpenMPParallelSectionsDirective(ClausesWithImplicit, AStmt,
2619 AllowedNameModifiers.push_back(OMPD_parallel);
2623 ActOnOpenMPTaskDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc);
2624 AllowedNameModifiers.push_back(OMPD_task);
2626 case OMPD_taskyield:
2627 assert(ClausesWithImplicit.empty() &&
2628 "No clauses are allowed for 'omp taskyield' directive");
2629 assert(AStmt == nullptr &&
2630 "No associated statement allowed for 'omp taskyield' directive");
2631 Res = ActOnOpenMPTaskyieldDirective(StartLoc, EndLoc);
2634 assert(ClausesWithImplicit.empty() &&
2635 "No clauses are allowed for 'omp barrier' directive");
2636 assert(AStmt == nullptr &&
2637 "No associated statement allowed for 'omp barrier' directive");
2638 Res = ActOnOpenMPBarrierDirective(StartLoc, EndLoc);
2641 assert(ClausesWithImplicit.empty() &&
2642 "No clauses are allowed for 'omp taskwait' directive");
2643 assert(AStmt == nullptr &&
2644 "No associated statement allowed for 'omp taskwait' directive");
2645 Res = ActOnOpenMPTaskwaitDirective(StartLoc, EndLoc);
2647 case OMPD_taskgroup:
2648 assert(ClausesWithImplicit.empty() &&
2649 "No clauses are allowed for 'omp taskgroup' directive");
2650 Res = ActOnOpenMPTaskgroupDirective(AStmt, StartLoc, EndLoc);
2653 assert(AStmt == nullptr &&
2654 "No associated statement allowed for 'omp flush' directive");
2655 Res = ActOnOpenMPFlushDirective(ClausesWithImplicit, StartLoc, EndLoc);
2658 Res = ActOnOpenMPOrderedDirective(ClausesWithImplicit, AStmt, StartLoc,
2662 Res = ActOnOpenMPAtomicDirective(ClausesWithImplicit, AStmt, StartLoc,
2667 ActOnOpenMPTeamsDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc);
2670 Res = ActOnOpenMPTargetDirective(ClausesWithImplicit, AStmt, StartLoc,
2672 AllowedNameModifiers.push_back(OMPD_target);
2674 case OMPD_cancellation_point:
2675 assert(ClausesWithImplicit.empty() &&
2676 "No clauses are allowed for 'omp cancellation point' directive");
2677 assert(AStmt == nullptr && "No associated statement allowed for 'omp "
2678 "cancellation point' directive");
2679 Res = ActOnOpenMPCancellationPointDirective(StartLoc, EndLoc, CancelRegion);
2682 assert(AStmt == nullptr &&
2683 "No associated statement allowed for 'omp cancel' directive");
2684 Res = ActOnOpenMPCancelDirective(ClausesWithImplicit, StartLoc, EndLoc,
2686 AllowedNameModifiers.push_back(OMPD_cancel);
2688 case OMPD_target_data:
2689 Res = ActOnOpenMPTargetDataDirective(ClausesWithImplicit, AStmt, StartLoc,
2691 AllowedNameModifiers.push_back(OMPD_target_data);
2694 Res = ActOnOpenMPTaskLoopDirective(ClausesWithImplicit, AStmt, StartLoc,
2695 EndLoc, VarsWithInheritedDSA);
2696 AllowedNameModifiers.push_back(OMPD_taskloop);
2698 case OMPD_taskloop_simd:
2699 Res = ActOnOpenMPTaskLoopSimdDirective(ClausesWithImplicit, AStmt, StartLoc,
2700 EndLoc, VarsWithInheritedDSA);
2701 AllowedNameModifiers.push_back(OMPD_taskloop);
2703 case OMPD_distribute:
2704 Res = ActOnOpenMPDistributeDirective(ClausesWithImplicit, AStmt, StartLoc,
2705 EndLoc, VarsWithInheritedDSA);
2707 case OMPD_threadprivate:
2708 llvm_unreachable("OpenMP Directive is not allowed");
2710 llvm_unreachable("Unknown OpenMP directive");
2713 for (auto P : VarsWithInheritedDSA) {
2714 Diag(P.second->getExprLoc(), diag::err_omp_no_dsa_for_variable)
2715 << P.first << P.second->getSourceRange();
2717 ErrorFound = !VarsWithInheritedDSA.empty() || ErrorFound;
2719 if (!AllowedNameModifiers.empty())
2720 ErrorFound = checkIfClauses(*this, Kind, Clauses, AllowedNameModifiers) ||
2728 StmtResult Sema::ActOnOpenMPParallelDirective(ArrayRef<OMPClause *> Clauses,
2730 SourceLocation StartLoc,
2731 SourceLocation EndLoc) {
2735 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
2736 // 1.2.2 OpenMP Language Terminology
2737 // Structured block - An executable statement with a single entry at the
2738 // top and a single exit at the bottom.
2739 // The point of exit cannot be a branch out of the structured block.
2740 // longjmp() and throw() must not violate the entry/exit criteria.
2741 CS->getCapturedDecl()->setNothrow();
2743 getCurFunction()->setHasBranchProtectedScope();
2745 return OMPParallelDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt,
2746 DSAStack->isCancelRegion());
2750 /// \brief Helper class for checking canonical form of the OpenMP loops and
2751 /// extracting iteration space of each loop in the loop nest, that will be used
2752 /// for IR generation.
2753 class OpenMPIterationSpaceChecker {
2754 /// \brief Reference to Sema.
2756 /// \brief A location for diagnostics (when there is no some better location).
2757 SourceLocation DefaultLoc;
2758 /// \brief A location for diagnostics (when increment is not compatible).
2759 SourceLocation ConditionLoc;
2760 /// \brief A source location for referring to loop init later.
2761 SourceRange InitSrcRange;
2762 /// \brief A source location for referring to condition later.
2763 SourceRange ConditionSrcRange;
2764 /// \brief A source location for referring to increment later.
2765 SourceRange IncrementSrcRange;
2766 /// \brief Loop variable.
2768 /// \brief Reference to loop variable.
2769 DeclRefExpr *VarRef;
2770 /// \brief Lower bound (initializer for the var).
2772 /// \brief Upper bound.
2774 /// \brief Loop step (increment).
2776 /// \brief This flag is true when condition is one of:
2782 /// \brief This flag is true when condition is strict ( < or > ).
2783 bool TestIsStrictOp;
2784 /// \brief This flag is true when step is subtracted on each iteration.
2788 OpenMPIterationSpaceChecker(Sema &SemaRef, SourceLocation DefaultLoc)
2789 : SemaRef(SemaRef), DefaultLoc(DefaultLoc), ConditionLoc(DefaultLoc),
2790 InitSrcRange(SourceRange()), ConditionSrcRange(SourceRange()),
2791 IncrementSrcRange(SourceRange()), Var(nullptr), VarRef(nullptr),
2792 LB(nullptr), UB(nullptr), Step(nullptr), TestIsLessOp(false),
2793 TestIsStrictOp(false), SubtractStep(false) {}
2794 /// \brief Check init-expr for canonical loop form and save loop counter
2795 /// variable - #Var and its initialization value - #LB.
2796 bool CheckInit(Stmt *S, bool EmitDiags = true);
2797 /// \brief Check test-expr for canonical form, save upper-bound (#UB), flags
2798 /// for less/greater and for strict/non-strict comparison.
2799 bool CheckCond(Expr *S);
2800 /// \brief Check incr-expr for canonical loop form and return true if it
2801 /// does not conform, otherwise save loop step (#Step).
2802 bool CheckInc(Expr *S);
2803 /// \brief Return the loop counter variable.
2804 VarDecl *GetLoopVar() const { return Var; }
2805 /// \brief Return the reference expression to loop counter variable.
2806 DeclRefExpr *GetLoopVarRefExpr() const { return VarRef; }
2807 /// \brief Source range of the loop init.
2808 SourceRange GetInitSrcRange() const { return InitSrcRange; }
2809 /// \brief Source range of the loop condition.
2810 SourceRange GetConditionSrcRange() const { return ConditionSrcRange; }
2811 /// \brief Source range of the loop increment.
2812 SourceRange GetIncrementSrcRange() const { return IncrementSrcRange; }
2813 /// \brief True if the step should be subtracted.
2814 bool ShouldSubtractStep() const { return SubtractStep; }
2815 /// \brief Build the expression to calculate the number of iterations.
2816 Expr *BuildNumIterations(Scope *S, const bool LimitedType) const;
2817 /// \brief Build the precondition expression for the loops.
2818 Expr *BuildPreCond(Scope *S, Expr *Cond) const;
2819 /// \brief Build reference expression to the counter be used for codegen.
2820 Expr *BuildCounterVar() const;
2821 /// \brief Build reference expression to the private counter be used for
2823 Expr *BuildPrivateCounterVar() const;
2824 /// \brief Build initization of the counter be used for codegen.
2825 Expr *BuildCounterInit() const;
2826 /// \brief Build step of the counter be used for codegen.
2827 Expr *BuildCounterStep() const;
2828 /// \brief Return true if any expression is dependent.
2829 bool Dependent() const;
2832 /// \brief Check the right-hand side of an assignment in the increment
2834 bool CheckIncRHS(Expr *RHS);
2835 /// \brief Helper to set loop counter variable and its initializer.
2836 bool SetVarAndLB(VarDecl *NewVar, DeclRefExpr *NewVarRefExpr, Expr *NewLB);
2837 /// \brief Helper to set upper bound.
2838 bool SetUB(Expr *NewUB, bool LessOp, bool StrictOp, SourceRange SR,
2840 /// \brief Helper to set loop increment.
2841 bool SetStep(Expr *NewStep, bool Subtract);
2844 bool OpenMPIterationSpaceChecker::Dependent() const {
2846 assert(!LB && !UB && !Step);
2849 return Var->getType()->isDependentType() || (LB && LB->isValueDependent()) ||
2850 (UB && UB->isValueDependent()) || (Step && Step->isValueDependent());
2853 template <typename T>
2854 static T *getExprAsWritten(T *E) {
2855 if (auto *ExprTemp = dyn_cast<ExprWithCleanups>(E))
2856 E = ExprTemp->getSubExpr();
2858 if (auto *MTE = dyn_cast<MaterializeTemporaryExpr>(E))
2859 E = MTE->GetTemporaryExpr();
2861 while (auto *Binder = dyn_cast<CXXBindTemporaryExpr>(E))
2862 E = Binder->getSubExpr();
2864 if (auto *ICE = dyn_cast<ImplicitCastExpr>(E))
2865 E = ICE->getSubExprAsWritten();
2866 return E->IgnoreParens();
2869 bool OpenMPIterationSpaceChecker::SetVarAndLB(VarDecl *NewVar,
2870 DeclRefExpr *NewVarRefExpr,
2872 // State consistency checking to ensure correct usage.
2873 assert(Var == nullptr && LB == nullptr && VarRef == nullptr &&
2874 UB == nullptr && Step == nullptr && !TestIsLessOp && !TestIsStrictOp);
2875 if (!NewVar || !NewLB)
2878 VarRef = NewVarRefExpr;
2879 if (auto *CE = dyn_cast_or_null<CXXConstructExpr>(NewLB))
2880 if (const CXXConstructorDecl *Ctor = CE->getConstructor())
2881 if ((Ctor->isCopyOrMoveConstructor() ||
2882 Ctor->isConvertingConstructor(/*AllowExplicit=*/false)) &&
2883 CE->getNumArgs() > 0 && CE->getArg(0) != nullptr)
2884 NewLB = CE->getArg(0)->IgnoreParenImpCasts();
2889 bool OpenMPIterationSpaceChecker::SetUB(Expr *NewUB, bool LessOp, bool StrictOp,
2890 SourceRange SR, SourceLocation SL) {
2891 // State consistency checking to ensure correct usage.
2892 assert(Var != nullptr && LB != nullptr && UB == nullptr && Step == nullptr &&
2893 !TestIsLessOp && !TestIsStrictOp);
2897 TestIsLessOp = LessOp;
2898 TestIsStrictOp = StrictOp;
2899 ConditionSrcRange = SR;
2904 bool OpenMPIterationSpaceChecker::SetStep(Expr *NewStep, bool Subtract) {
2905 // State consistency checking to ensure correct usage.
2906 assert(Var != nullptr && LB != nullptr && Step == nullptr);
2909 if (!NewStep->isValueDependent()) {
2910 // Check that the step is integer expression.
2911 SourceLocation StepLoc = NewStep->getLocStart();
2913 SemaRef.PerformOpenMPImplicitIntegerConversion(StepLoc, NewStep);
2914 if (Val.isInvalid())
2916 NewStep = Val.get();
2918 // OpenMP [2.6, Canonical Loop Form, Restrictions]
2919 // If test-expr is of form var relational-op b and relational-op is < or
2920 // <= then incr-expr must cause var to increase on each iteration of the
2921 // loop. If test-expr is of form var relational-op b and relational-op is
2922 // > or >= then incr-expr must cause var to decrease on each iteration of
2924 // If test-expr is of form b relational-op var and relational-op is < or
2925 // <= then incr-expr must cause var to decrease on each iteration of the
2926 // loop. If test-expr is of form b relational-op var and relational-op is
2927 // > or >= then incr-expr must cause var to increase on each iteration of
2929 llvm::APSInt Result;
2930 bool IsConstant = NewStep->isIntegerConstantExpr(Result, SemaRef.Context);
2931 bool IsUnsigned = !NewStep->getType()->hasSignedIntegerRepresentation();
2933 IsConstant && Result.isSigned() && (Subtract != Result.isNegative());
2935 IsConstant && Result.isSigned() && (Subtract == Result.isNegative());
2936 bool IsConstZero = IsConstant && !Result.getBoolValue();
2937 if (UB && (IsConstZero ||
2938 (TestIsLessOp ? (IsConstNeg || (IsUnsigned && Subtract))
2939 : (IsConstPos || (IsUnsigned && !Subtract))))) {
2940 SemaRef.Diag(NewStep->getExprLoc(),
2941 diag::err_omp_loop_incr_not_compatible)
2942 << Var << TestIsLessOp << NewStep->getSourceRange();
2943 SemaRef.Diag(ConditionLoc,
2944 diag::note_omp_loop_cond_requres_compatible_incr)
2945 << TestIsLessOp << ConditionSrcRange;
2948 if (TestIsLessOp == Subtract) {
2949 NewStep = SemaRef.CreateBuiltinUnaryOp(NewStep->getExprLoc(), UO_Minus,
2951 Subtract = !Subtract;
2956 SubtractStep = Subtract;
2960 bool OpenMPIterationSpaceChecker::CheckInit(Stmt *S, bool EmitDiags) {
2961 // Check init-expr for canonical loop form and save loop counter
2962 // variable - #Var and its initialization value - #LB.
2963 // OpenMP [2.6] Canonical loop form. init-expr may be one of the following:
2965 // integer-type var = lb
2966 // random-access-iterator-type var = lb
2967 // pointer-type var = lb
2971 SemaRef.Diag(DefaultLoc, diag::err_omp_loop_not_canonical_init);
2975 InitSrcRange = S->getSourceRange();
2976 if (Expr *E = dyn_cast<Expr>(S))
2977 S = E->IgnoreParens();
2978 if (auto BO = dyn_cast<BinaryOperator>(S)) {
2979 if (BO->getOpcode() == BO_Assign)
2980 if (auto DRE = dyn_cast<DeclRefExpr>(BO->getLHS()->IgnoreParens()))
2981 return SetVarAndLB(dyn_cast<VarDecl>(DRE->getDecl()), DRE,
2983 } else if (auto DS = dyn_cast<DeclStmt>(S)) {
2984 if (DS->isSingleDecl()) {
2985 if (auto Var = dyn_cast_or_null<VarDecl>(DS->getSingleDecl())) {
2986 if (Var->hasInit() && !Var->getType()->isReferenceType()) {
2987 // Accept non-canonical init form here but emit ext. warning.
2988 if (Var->getInitStyle() != VarDecl::CInit && EmitDiags)
2989 SemaRef.Diag(S->getLocStart(),
2990 diag::ext_omp_loop_not_canonical_init)
2991 << S->getSourceRange();
2992 return SetVarAndLB(Var, nullptr, Var->getInit());
2996 } else if (auto CE = dyn_cast<CXXOperatorCallExpr>(S))
2997 if (CE->getOperator() == OO_Equal)
2998 if (auto DRE = dyn_cast<DeclRefExpr>(CE->getArg(0)))
2999 return SetVarAndLB(dyn_cast<VarDecl>(DRE->getDecl()), DRE,
3003 SemaRef.Diag(S->getLocStart(), diag::err_omp_loop_not_canonical_init)
3004 << S->getSourceRange();
3009 /// \brief Ignore parenthesizes, implicit casts, copy constructor and return the
3010 /// variable (which may be the loop variable) if possible.
3011 static const VarDecl *GetInitVarDecl(const Expr *E) {
3014 E = getExprAsWritten(E);
3015 if (auto *CE = dyn_cast_or_null<CXXConstructExpr>(E))
3016 if (const CXXConstructorDecl *Ctor = CE->getConstructor())
3017 if ((Ctor->isCopyOrMoveConstructor() ||
3018 Ctor->isConvertingConstructor(/*AllowExplicit=*/false)) &&
3019 CE->getNumArgs() > 0 && CE->getArg(0) != nullptr)
3020 E = CE->getArg(0)->IgnoreParenImpCasts();
3021 auto DRE = dyn_cast_or_null<DeclRefExpr>(E);
3024 return dyn_cast<VarDecl>(DRE->getDecl());
3027 bool OpenMPIterationSpaceChecker::CheckCond(Expr *S) {
3028 // Check test-expr for canonical form, save upper-bound UB, flags for
3029 // less/greater and for strict/non-strict comparison.
3030 // OpenMP [2.6] Canonical loop form. Test-expr may be one of the following:
3031 // var relational-op b
3032 // b relational-op var
3035 SemaRef.Diag(DefaultLoc, diag::err_omp_loop_not_canonical_cond) << Var;
3038 S = getExprAsWritten(S);
3039 SourceLocation CondLoc = S->getLocStart();
3040 if (auto BO = dyn_cast<BinaryOperator>(S)) {
3041 if (BO->isRelationalOp()) {
3042 if (GetInitVarDecl(BO->getLHS()) == Var)
3043 return SetUB(BO->getRHS(),
3044 (BO->getOpcode() == BO_LT || BO->getOpcode() == BO_LE),
3045 (BO->getOpcode() == BO_LT || BO->getOpcode() == BO_GT),
3046 BO->getSourceRange(), BO->getOperatorLoc());
3047 if (GetInitVarDecl(BO->getRHS()) == Var)
3048 return SetUB(BO->getLHS(),
3049 (BO->getOpcode() == BO_GT || BO->getOpcode() == BO_GE),
3050 (BO->getOpcode() == BO_LT || BO->getOpcode() == BO_GT),
3051 BO->getSourceRange(), BO->getOperatorLoc());
3053 } else if (auto CE = dyn_cast<CXXOperatorCallExpr>(S)) {
3054 if (CE->getNumArgs() == 2) {
3055 auto Op = CE->getOperator();
3058 case OO_GreaterEqual:
3061 if (GetInitVarDecl(CE->getArg(0)) == Var)
3062 return SetUB(CE->getArg(1), Op == OO_Less || Op == OO_LessEqual,
3063 Op == OO_Less || Op == OO_Greater, CE->getSourceRange(),
3064 CE->getOperatorLoc());
3065 if (GetInitVarDecl(CE->getArg(1)) == Var)
3066 return SetUB(CE->getArg(0), Op == OO_Greater || Op == OO_GreaterEqual,
3067 Op == OO_Less || Op == OO_Greater, CE->getSourceRange(),
3068 CE->getOperatorLoc());
3075 SemaRef.Diag(CondLoc, diag::err_omp_loop_not_canonical_cond)
3076 << S->getSourceRange() << Var;
3080 bool OpenMPIterationSpaceChecker::CheckIncRHS(Expr *RHS) {
3081 // RHS of canonical loop form increment can be:
3086 RHS = RHS->IgnoreParenImpCasts();
3087 if (auto BO = dyn_cast<BinaryOperator>(RHS)) {
3088 if (BO->isAdditiveOp()) {
3089 bool IsAdd = BO->getOpcode() == BO_Add;
3090 if (GetInitVarDecl(BO->getLHS()) == Var)
3091 return SetStep(BO->getRHS(), !IsAdd);
3092 if (IsAdd && GetInitVarDecl(BO->getRHS()) == Var)
3093 return SetStep(BO->getLHS(), false);
3095 } else if (auto CE = dyn_cast<CXXOperatorCallExpr>(RHS)) {
3096 bool IsAdd = CE->getOperator() == OO_Plus;
3097 if ((IsAdd || CE->getOperator() == OO_Minus) && CE->getNumArgs() == 2) {
3098 if (GetInitVarDecl(CE->getArg(0)) == Var)
3099 return SetStep(CE->getArg(1), !IsAdd);
3100 if (IsAdd && GetInitVarDecl(CE->getArg(1)) == Var)
3101 return SetStep(CE->getArg(0), false);
3104 SemaRef.Diag(RHS->getLocStart(), diag::err_omp_loop_not_canonical_incr)
3105 << RHS->getSourceRange() << Var;
3109 bool OpenMPIterationSpaceChecker::CheckInc(Expr *S) {
3110 // Check incr-expr for canonical loop form and return true if it
3111 // does not conform.
3112 // OpenMP [2.6] Canonical loop form. Test-expr may be one of the following:
3124 SemaRef.Diag(DefaultLoc, diag::err_omp_loop_not_canonical_incr) << Var;
3127 IncrementSrcRange = S->getSourceRange();
3128 S = S->IgnoreParens();
3129 if (auto UO = dyn_cast<UnaryOperator>(S)) {
3130 if (UO->isIncrementDecrementOp() && GetInitVarDecl(UO->getSubExpr()) == Var)
3132 SemaRef.ActOnIntegerConstant(UO->getLocStart(),
3133 (UO->isDecrementOp() ? -1 : 1)).get(),
3135 } else if (auto BO = dyn_cast<BinaryOperator>(S)) {
3136 switch (BO->getOpcode()) {
3139 if (GetInitVarDecl(BO->getLHS()) == Var)
3140 return SetStep(BO->getRHS(), BO->getOpcode() == BO_SubAssign);
3143 if (GetInitVarDecl(BO->getLHS()) == Var)
3144 return CheckIncRHS(BO->getRHS());
3149 } else if (auto CE = dyn_cast<CXXOperatorCallExpr>(S)) {
3150 switch (CE->getOperator()) {
3153 if (GetInitVarDecl(CE->getArg(0)) == Var)
3155 SemaRef.ActOnIntegerConstant(
3157 ((CE->getOperator() == OO_MinusMinus) ? -1 : 1)).get(),
3162 if (GetInitVarDecl(CE->getArg(0)) == Var)
3163 return SetStep(CE->getArg(1), CE->getOperator() == OO_MinusEqual);
3166 if (GetInitVarDecl(CE->getArg(0)) == Var)
3167 return CheckIncRHS(CE->getArg(1));
3173 SemaRef.Diag(S->getLocStart(), diag::err_omp_loop_not_canonical_incr)
3174 << S->getSourceRange() << Var;
3179 // Transform variables declared in GNU statement expressions to new ones to
3180 // avoid crash on codegen.
3181 class TransformToNewDefs : public TreeTransform<TransformToNewDefs> {
3182 typedef TreeTransform<TransformToNewDefs> BaseTransform;
3185 TransformToNewDefs(Sema &SemaRef) : BaseTransform(SemaRef) {}
3187 Decl *TransformDefinition(SourceLocation Loc, Decl *D) {
3188 if (auto *VD = cast<VarDecl>(D))
3189 if (!isa<ParmVarDecl>(D) && !isa<VarTemplateSpecializationDecl>(D) &&
3190 !isa<ImplicitParamDecl>(D)) {
3191 auto *NewVD = VarDecl::Create(
3192 SemaRef.Context, VD->getDeclContext(), VD->getLocStart(),
3193 VD->getLocation(), VD->getIdentifier(), VD->getType(),
3194 VD->getTypeSourceInfo(), VD->getStorageClass());
3195 NewVD->setTSCSpec(VD->getTSCSpec());
3196 NewVD->setInit(VD->getInit());
3197 NewVD->setInitStyle(VD->getInitStyle());
3198 NewVD->setExceptionVariable(VD->isExceptionVariable());
3199 NewVD->setNRVOVariable(VD->isNRVOVariable());
3200 NewVD->setCXXForRangeDecl(VD->isInExternCXXContext());
3201 NewVD->setConstexpr(VD->isConstexpr());
3202 NewVD->setInitCapture(VD->isInitCapture());
3203 NewVD->setPreviousDeclInSameBlockScope(
3204 VD->isPreviousDeclInSameBlockScope());
3205 VD->getDeclContext()->addHiddenDecl(NewVD);
3207 NewVD->setAttrs(VD->getAttrs());
3208 transformedLocalDecl(VD, NewVD);
3211 return BaseTransform::TransformDefinition(Loc, D);
3214 ExprResult TransformDeclRefExpr(DeclRefExpr *E) {
3215 if (auto *NewD = TransformDecl(E->getExprLoc(), E->getDecl()))
3216 if (E->getDecl() != NewD) {
3217 NewD->setReferenced();
3218 NewD->markUsed(SemaRef.Context);
3219 return DeclRefExpr::Create(
3220 SemaRef.Context, E->getQualifierLoc(), E->getTemplateKeywordLoc(),
3221 cast<ValueDecl>(NewD), E->refersToEnclosingVariableOrCapture(),
3222 E->getNameInfo(), E->getType(), E->getValueKind());
3224 return BaseTransform::TransformDeclRefExpr(E);
3229 /// \brief Build the expression to calculate the number of iterations.
3231 OpenMPIterationSpaceChecker::BuildNumIterations(Scope *S,
3232 const bool LimitedType) const {
3233 TransformToNewDefs Transform(SemaRef);
3235 auto VarType = Var->getType().getNonReferenceType();
3236 if (VarType->isIntegerType() || VarType->isPointerType() ||
3237 SemaRef.getLangOpts().CPlusPlus) {
3239 auto *UBExpr = TestIsLessOp ? UB : LB;
3240 auto *LBExpr = TestIsLessOp ? LB : UB;
3241 Expr *Upper = Transform.TransformExpr(UBExpr).get();
3242 Expr *Lower = Transform.TransformExpr(LBExpr).get();
3243 if (!Upper || !Lower)
3245 Upper = SemaRef.PerformImplicitConversion(Upper, UBExpr->getType(),
3246 Sema::AA_Converting,
3247 /*AllowExplicit=*/true)
3249 Lower = SemaRef.PerformImplicitConversion(Lower, LBExpr->getType(),
3250 Sema::AA_Converting,
3251 /*AllowExplicit=*/true)
3253 if (!Upper || !Lower)
3256 Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Sub, Upper, Lower);
3258 if (!Diff.isUsable() && VarType->getAsCXXRecordDecl()) {
3259 // BuildBinOp already emitted error, this one is to point user to upper
3260 // and lower bound, and to tell what is passed to 'operator-'.
3261 SemaRef.Diag(Upper->getLocStart(), diag::err_omp_loop_diff_cxx)
3262 << Upper->getSourceRange() << Lower->getSourceRange();
3267 if (!Diff.isUsable())
3270 // Upper - Lower [- 1]
3272 Diff = SemaRef.BuildBinOp(
3273 S, DefaultLoc, BO_Sub, Diff.get(),
3274 SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get());
3275 if (!Diff.isUsable())
3278 // Upper - Lower [- 1] + Step
3279 auto NewStep = Transform.TransformExpr(Step->IgnoreImplicit());
3280 if (NewStep.isInvalid())
3282 NewStep = SemaRef.PerformImplicitConversion(
3283 NewStep.get(), Step->IgnoreImplicit()->getType(), Sema::AA_Converting,
3284 /*AllowExplicit=*/true);
3285 if (NewStep.isInvalid())
3287 Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Add, Diff.get(), NewStep.get());
3288 if (!Diff.isUsable())
3291 // Parentheses (for dumping/debugging purposes only).
3292 Diff = SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, Diff.get());
3293 if (!Diff.isUsable())
3296 // (Upper - Lower [- 1] + Step) / Step
3297 NewStep = Transform.TransformExpr(Step->IgnoreImplicit());
3298 if (NewStep.isInvalid())
3300 NewStep = SemaRef.PerformImplicitConversion(
3301 NewStep.get(), Step->IgnoreImplicit()->getType(), Sema::AA_Converting,
3302 /*AllowExplicit=*/true);
3303 if (NewStep.isInvalid())
3305 Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Div, Diff.get(), NewStep.get());
3306 if (!Diff.isUsable())
3309 // OpenMP runtime requires 32-bit or 64-bit loop variables.
3310 QualType Type = Diff.get()->getType();
3311 auto &C = SemaRef.Context;
3312 bool UseVarType = VarType->hasIntegerRepresentation() &&
3313 C.getTypeSize(Type) > C.getTypeSize(VarType);
3314 if (!Type->isIntegerType() || UseVarType) {
3316 UseVarType ? C.getTypeSize(VarType) : C.getTypeSize(Type);
3317 bool IsSigned = UseVarType ? VarType->hasSignedIntegerRepresentation()
3318 : Type->hasSignedIntegerRepresentation();
3319 Type = C.getIntTypeForBitwidth(NewSize, IsSigned);
3320 Diff = SemaRef.PerformImplicitConversion(
3321 Diff.get(), Type, Sema::AA_Converting, /*AllowExplicit=*/true);
3322 if (!Diff.isUsable())
3326 unsigned NewSize = (C.getTypeSize(Type) > 32) ? 64 : 32;
3327 if (NewSize != C.getTypeSize(Type)) {
3328 if (NewSize < C.getTypeSize(Type)) {
3329 assert(NewSize == 64 && "incorrect loop var size");
3330 SemaRef.Diag(DefaultLoc, diag::warn_omp_loop_64_bit_var)
3331 << InitSrcRange << ConditionSrcRange;
3333 QualType NewType = C.getIntTypeForBitwidth(
3334 NewSize, Type->hasSignedIntegerRepresentation() ||
3335 C.getTypeSize(Type) < NewSize);
3336 Diff = SemaRef.PerformImplicitConversion(Diff.get(), NewType,
3337 Sema::AA_Converting, true);
3338 if (!Diff.isUsable())
3346 Expr *OpenMPIterationSpaceChecker::BuildPreCond(Scope *S, Expr *Cond) const {
3347 // Try to build LB <op> UB, where <op> is <, >, <=, or >=.
3348 bool Suppress = SemaRef.getDiagnostics().getSuppressAllDiagnostics();
3349 SemaRef.getDiagnostics().setSuppressAllDiagnostics(/*Val=*/true);
3350 TransformToNewDefs Transform(SemaRef);
3352 auto NewLB = Transform.TransformExpr(LB);
3353 auto NewUB = Transform.TransformExpr(UB);
3354 if (NewLB.isInvalid() || NewUB.isInvalid())
3356 NewLB = SemaRef.PerformImplicitConversion(NewLB.get(), LB->getType(),
3357 Sema::AA_Converting,
3358 /*AllowExplicit=*/true);
3359 NewUB = SemaRef.PerformImplicitConversion(NewUB.get(), UB->getType(),
3360 Sema::AA_Converting,
3361 /*AllowExplicit=*/true);
3362 if (NewLB.isInvalid() || NewUB.isInvalid())
3364 auto CondExpr = SemaRef.BuildBinOp(
3365 S, DefaultLoc, TestIsLessOp ? (TestIsStrictOp ? BO_LT : BO_LE)
3366 : (TestIsStrictOp ? BO_GT : BO_GE),
3367 NewLB.get(), NewUB.get());
3368 if (CondExpr.isUsable()) {
3369 CondExpr = SemaRef.PerformImplicitConversion(
3370 CondExpr.get(), SemaRef.Context.BoolTy, /*Action=*/Sema::AA_Casting,
3371 /*AllowExplicit=*/true);
3373 SemaRef.getDiagnostics().setSuppressAllDiagnostics(Suppress);
3374 // Otherwise use original loop conditon and evaluate it in runtime.
3375 return CondExpr.isUsable() ? CondExpr.get() : Cond;
3378 /// \brief Build reference expression to the counter be used for codegen.
3379 Expr *OpenMPIterationSpaceChecker::BuildCounterVar() const {
3380 return buildDeclRefExpr(SemaRef, Var, Var->getType().getNonReferenceType(),
3384 Expr *OpenMPIterationSpaceChecker::BuildPrivateCounterVar() const {
3385 if (Var && !Var->isInvalidDecl()) {
3386 auto Type = Var->getType().getNonReferenceType();
3388 buildVarDecl(SemaRef, DefaultLoc, Type, Var->getName(),
3389 Var->hasAttrs() ? &Var->getAttrs() : nullptr);
3390 if (PrivateVar->isInvalidDecl())
3392 return buildDeclRefExpr(SemaRef, PrivateVar, Type, DefaultLoc);
3397 /// \brief Build initization of the counter be used for codegen.
3398 Expr *OpenMPIterationSpaceChecker::BuildCounterInit() const { return LB; }
3400 /// \brief Build step of the counter be used for codegen.
3401 Expr *OpenMPIterationSpaceChecker::BuildCounterStep() const { return Step; }
3403 /// \brief Iteration space of a single for loop.
3404 struct LoopIterationSpace {
3405 /// \brief Condition of the loop.
3407 /// \brief This expression calculates the number of iterations in the loop.
3408 /// It is always possible to calculate it before starting the loop.
3409 Expr *NumIterations;
3410 /// \brief The loop counter variable.
3412 /// \brief Private loop counter variable.
3413 Expr *PrivateCounterVar;
3414 /// \brief This is initializer for the initial value of #CounterVar.
3416 /// \brief This is step for the #CounterVar used to generate its update:
3417 /// #CounterVar = #CounterInit + #CounterStep * CurrentIteration.
3419 /// \brief Should step be subtracted?
3421 /// \brief Source range of the loop init.
3422 SourceRange InitSrcRange;
3423 /// \brief Source range of the loop condition.
3424 SourceRange CondSrcRange;
3425 /// \brief Source range of the loop increment.
3426 SourceRange IncSrcRange;
3431 void Sema::ActOnOpenMPLoopInitialization(SourceLocation ForLoc, Stmt *Init) {
3432 assert(getLangOpts().OpenMP && "OpenMP is not active.");
3433 assert(Init && "Expected loop in canonical form.");
3434 unsigned AssociatedLoops = DSAStack->getAssociatedLoops();
3435 if (AssociatedLoops > 0 &&
3436 isOpenMPLoopDirective(DSAStack->getCurrentDirective())) {
3437 OpenMPIterationSpaceChecker ISC(*this, ForLoc);
3438 if (!ISC.CheckInit(Init, /*EmitDiags=*/false))
3439 DSAStack->addLoopControlVariable(ISC.GetLoopVar());
3440 DSAStack->setAssociatedLoops(AssociatedLoops - 1);
3444 /// \brief Called on a for stmt to check and extract its iteration space
3445 /// for further processing (such as collapsing).
3446 static bool CheckOpenMPIterationSpace(
3447 OpenMPDirectiveKind DKind, Stmt *S, Sema &SemaRef, DSAStackTy &DSA,
3448 unsigned CurrentNestedLoopCount, unsigned NestedLoopCount,
3449 Expr *CollapseLoopCountExpr, Expr *OrderedLoopCountExpr,
3450 llvm::DenseMap<VarDecl *, Expr *> &VarsWithImplicitDSA,
3451 LoopIterationSpace &ResultIterSpace) {
3452 // OpenMP [2.6, Canonical Loop Form]
3453 // for (init-expr; test-expr; incr-expr) structured-block
3454 auto For = dyn_cast_or_null<ForStmt>(S);
3456 SemaRef.Diag(S->getLocStart(), diag::err_omp_not_for)
3457 << (CollapseLoopCountExpr != nullptr || OrderedLoopCountExpr != nullptr)
3458 << getOpenMPDirectiveName(DKind) << NestedLoopCount
3459 << (CurrentNestedLoopCount > 0) << CurrentNestedLoopCount;
3460 if (NestedLoopCount > 1) {
3461 if (CollapseLoopCountExpr && OrderedLoopCountExpr)
3462 SemaRef.Diag(DSA.getConstructLoc(),
3463 diag::note_omp_collapse_ordered_expr)
3464 << 2 << CollapseLoopCountExpr->getSourceRange()
3465 << OrderedLoopCountExpr->getSourceRange();
3466 else if (CollapseLoopCountExpr)
3467 SemaRef.Diag(CollapseLoopCountExpr->getExprLoc(),
3468 diag::note_omp_collapse_ordered_expr)
3469 << 0 << CollapseLoopCountExpr->getSourceRange();
3471 SemaRef.Diag(OrderedLoopCountExpr->getExprLoc(),
3472 diag::note_omp_collapse_ordered_expr)
3473 << 1 << OrderedLoopCountExpr->getSourceRange();
3477 assert(For->getBody());
3479 OpenMPIterationSpaceChecker ISC(SemaRef, For->getForLoc());
3482 auto Init = For->getInit();
3483 if (ISC.CheckInit(Init)) {
3487 bool HasErrors = false;
3489 // Check loop variable's type.
3490 auto Var = ISC.GetLoopVar();
3492 // OpenMP [2.6, Canonical Loop Form]
3493 // Var is one of the following:
3494 // A variable of signed or unsigned integer type.
3495 // For C++, a variable of a random access iterator type.
3496 // For C, a variable of a pointer type.
3497 auto VarType = Var->getType().getNonReferenceType();
3498 if (!VarType->isDependentType() && !VarType->isIntegerType() &&
3499 !VarType->isPointerType() &&
3500 !(SemaRef.getLangOpts().CPlusPlus && VarType->isOverloadableType())) {
3501 SemaRef.Diag(Init->getLocStart(), diag::err_omp_loop_variable_type)
3502 << SemaRef.getLangOpts().CPlusPlus;
3506 // OpenMP, 2.14.1.1 Data-sharing Attribute Rules for Variables Referenced in a
3508 // The loop iteration variable(s) in the associated for-loop(s) of a for or
3509 // parallel for construct is (are) private.
3510 // The loop iteration variable in the associated for-loop of a simd construct
3511 // with just one associated for-loop is linear with a constant-linear-step
3512 // that is the increment of the associated for-loop.
3513 // Exclude loop var from the list of variables with implicitly defined data
3514 // sharing attributes.
3515 VarsWithImplicitDSA.erase(Var);
3517 // OpenMP [2.14.1.1, Data-sharing Attribute Rules for Variables Referenced in
3518 // a Construct, C/C++].
3519 // The loop iteration variable in the associated for-loop of a simd construct
3520 // with just one associated for-loop may be listed in a linear clause with a
3521 // constant-linear-step that is the increment of the associated for-loop.
3522 // The loop iteration variable(s) in the associated for-loop(s) of a for or
3523 // parallel for construct may be listed in a private or lastprivate clause.
3524 DSAStackTy::DSAVarData DVar = DSA.getTopDSA(Var, false);
3525 auto LoopVarRefExpr = ISC.GetLoopVarRefExpr();
3526 // If LoopVarRefExpr is nullptr it means the corresponding loop variable is
3527 // declared in the loop and it is predetermined as a private.
3528 auto PredeterminedCKind =
3529 isOpenMPSimdDirective(DKind)
3530 ? ((NestedLoopCount == 1) ? OMPC_linear : OMPC_lastprivate)
3532 if (((isOpenMPSimdDirective(DKind) && DVar.CKind != OMPC_unknown &&
3533 DVar.CKind != PredeterminedCKind) ||
3534 ((isOpenMPWorksharingDirective(DKind) || DKind == OMPD_taskloop ||
3535 isOpenMPDistributeDirective(DKind)) &&
3536 !isOpenMPSimdDirective(DKind) && DVar.CKind != OMPC_unknown &&
3537 DVar.CKind != OMPC_private && DVar.CKind != OMPC_lastprivate)) &&
3538 (DVar.CKind != OMPC_private || DVar.RefExpr != nullptr)) {
3539 SemaRef.Diag(Init->getLocStart(), diag::err_omp_loop_var_dsa)
3540 << getOpenMPClauseName(DVar.CKind) << getOpenMPDirectiveName(DKind)
3541 << getOpenMPClauseName(PredeterminedCKind);
3542 if (DVar.RefExpr == nullptr)
3543 DVar.CKind = PredeterminedCKind;
3544 ReportOriginalDSA(SemaRef, &DSA, Var, DVar, /*IsLoopIterVar=*/true);
3546 } else if (LoopVarRefExpr != nullptr) {
3547 // Make the loop iteration variable private (for worksharing constructs),
3548 // linear (for simd directives with the only one associated loop) or
3549 // lastprivate (for simd directives with several collapsed or ordered
3551 if (DVar.CKind == OMPC_unknown)
3552 DVar = DSA.hasDSA(Var, isOpenMPPrivate, MatchesAlways(),
3553 /*FromParent=*/false);
3554 DSA.addDSA(Var, LoopVarRefExpr, PredeterminedCKind);
3557 assert(isOpenMPLoopDirective(DKind) && "DSA for non-loop vars");
3560 HasErrors |= ISC.CheckCond(For->getCond());
3563 HasErrors |= ISC.CheckInc(For->getInc());
3565 if (ISC.Dependent() || SemaRef.CurContext->isDependentContext() || HasErrors)
3568 // Build the loop's iteration space representation.
3569 ResultIterSpace.PreCond = ISC.BuildPreCond(DSA.getCurScope(), For->getCond());
3570 ResultIterSpace.NumIterations = ISC.BuildNumIterations(
3571 DSA.getCurScope(), (isOpenMPWorksharingDirective(DKind) ||
3572 isOpenMPTaskLoopDirective(DKind) ||
3573 isOpenMPDistributeDirective(DKind)));
3574 ResultIterSpace.CounterVar = ISC.BuildCounterVar();
3575 ResultIterSpace.PrivateCounterVar = ISC.BuildPrivateCounterVar();
3576 ResultIterSpace.CounterInit = ISC.BuildCounterInit();
3577 ResultIterSpace.CounterStep = ISC.BuildCounterStep();
3578 ResultIterSpace.InitSrcRange = ISC.GetInitSrcRange();
3579 ResultIterSpace.CondSrcRange = ISC.GetConditionSrcRange();
3580 ResultIterSpace.IncSrcRange = ISC.GetIncrementSrcRange();
3581 ResultIterSpace.Subtract = ISC.ShouldSubtractStep();
3583 HasErrors |= (ResultIterSpace.PreCond == nullptr ||
3584 ResultIterSpace.NumIterations == nullptr ||
3585 ResultIterSpace.CounterVar == nullptr ||
3586 ResultIterSpace.PrivateCounterVar == nullptr ||
3587 ResultIterSpace.CounterInit == nullptr ||
3588 ResultIterSpace.CounterStep == nullptr);
3593 /// \brief Build 'VarRef = Start.
3594 static ExprResult BuildCounterInit(Sema &SemaRef, Scope *S, SourceLocation Loc,
3595 ExprResult VarRef, ExprResult Start) {
3596 TransformToNewDefs Transform(SemaRef);
3597 // Build 'VarRef = Start.
3598 auto NewStart = Transform.TransformExpr(Start.get()->IgnoreImplicit());
3599 if (NewStart.isInvalid())
3601 NewStart = SemaRef.PerformImplicitConversion(
3602 NewStart.get(), Start.get()->IgnoreImplicit()->getType(),
3603 Sema::AA_Converting,
3604 /*AllowExplicit=*/true);
3605 if (NewStart.isInvalid())
3607 NewStart = SemaRef.PerformImplicitConversion(
3608 NewStart.get(), VarRef.get()->getType(), Sema::AA_Converting,
3609 /*AllowExplicit=*/true);
3610 if (!NewStart.isUsable())
3614 SemaRef.BuildBinOp(S, Loc, BO_Assign, VarRef.get(), NewStart.get());
3618 /// \brief Build 'VarRef = Start + Iter * Step'.
3619 static ExprResult BuildCounterUpdate(Sema &SemaRef, Scope *S,
3620 SourceLocation Loc, ExprResult VarRef,
3621 ExprResult Start, ExprResult Iter,
3622 ExprResult Step, bool Subtract) {
3623 // Add parentheses (for debugging purposes only).
3624 Iter = SemaRef.ActOnParenExpr(Loc, Loc, Iter.get());
3625 if (!VarRef.isUsable() || !Start.isUsable() || !Iter.isUsable() ||
3629 TransformToNewDefs Transform(SemaRef);
3630 auto NewStep = Transform.TransformExpr(Step.get()->IgnoreImplicit());
3631 if (NewStep.isInvalid())
3633 NewStep = SemaRef.PerformImplicitConversion(
3634 NewStep.get(), Step.get()->IgnoreImplicit()->getType(),
3635 Sema::AA_Converting,
3636 /*AllowExplicit=*/true);
3637 if (NewStep.isInvalid())
3640 SemaRef.BuildBinOp(S, Loc, BO_Mul, Iter.get(), NewStep.get());
3641 if (!Update.isUsable())
3644 // Build 'VarRef = Start + Iter * Step'.
3645 auto NewStart = Transform.TransformExpr(Start.get()->IgnoreImplicit());
3646 if (NewStart.isInvalid())
3648 NewStart = SemaRef.PerformImplicitConversion(
3649 NewStart.get(), Start.get()->IgnoreImplicit()->getType(),
3650 Sema::AA_Converting,
3651 /*AllowExplicit=*/true);
3652 if (NewStart.isInvalid())
3654 Update = SemaRef.BuildBinOp(S, Loc, (Subtract ? BO_Sub : BO_Add),
3655 NewStart.get(), Update.get());
3656 if (!Update.isUsable())
3659 Update = SemaRef.PerformImplicitConversion(
3660 Update.get(), VarRef.get()->getType(), Sema::AA_Converting, true);
3661 if (!Update.isUsable())
3664 Update = SemaRef.BuildBinOp(S, Loc, BO_Assign, VarRef.get(), Update.get());
3668 /// \brief Convert integer expression \a E to make it have at least \a Bits
3670 static ExprResult WidenIterationCount(unsigned Bits, Expr *E,
3674 auto &C = SemaRef.Context;
3675 QualType OldType = E->getType();
3676 unsigned HasBits = C.getTypeSize(OldType);
3677 if (HasBits >= Bits)
3678 return ExprResult(E);
3679 // OK to convert to signed, because new type has more bits than old.
3680 QualType NewType = C.getIntTypeForBitwidth(Bits, /* Signed */ true);
3681 return SemaRef.PerformImplicitConversion(E, NewType, Sema::AA_Converting,
3685 /// \brief Check if the given expression \a E is a constant integer that fits
3686 /// into \a Bits bits.
3687 static bool FitsInto(unsigned Bits, bool Signed, Expr *E, Sema &SemaRef) {
3690 llvm::APSInt Result;
3691 if (E->isIntegerConstantExpr(Result, SemaRef.Context))
3692 return Signed ? Result.isSignedIntN(Bits) : Result.isIntN(Bits);
3696 /// \brief Called on a for stmt to check itself and nested loops (if any).
3697 /// \return Returns 0 if one of the collapsed stmts is not canonical for loop,
3698 /// number of collapsed loops otherwise.
3700 CheckOpenMPLoop(OpenMPDirectiveKind DKind, Expr *CollapseLoopCountExpr,
3701 Expr *OrderedLoopCountExpr, Stmt *AStmt, Sema &SemaRef,
3703 llvm::DenseMap<VarDecl *, Expr *> &VarsWithImplicitDSA,
3704 OMPLoopDirective::HelperExprs &Built) {
3705 unsigned NestedLoopCount = 1;
3706 if (CollapseLoopCountExpr) {
3707 // Found 'collapse' clause - calculate collapse number.
3708 llvm::APSInt Result;
3709 if (CollapseLoopCountExpr->EvaluateAsInt(Result, SemaRef.getASTContext()))
3710 NestedLoopCount = Result.getLimitedValue();
3712 if (OrderedLoopCountExpr) {
3713 // Found 'ordered' clause - calculate collapse number.
3714 llvm::APSInt Result;
3715 if (OrderedLoopCountExpr->EvaluateAsInt(Result, SemaRef.getASTContext())) {
3716 if (Result.getLimitedValue() < NestedLoopCount) {
3717 SemaRef.Diag(OrderedLoopCountExpr->getExprLoc(),
3718 diag::err_omp_wrong_ordered_loop_count)
3719 << OrderedLoopCountExpr->getSourceRange();
3720 SemaRef.Diag(CollapseLoopCountExpr->getExprLoc(),
3721 diag::note_collapse_loop_count)
3722 << CollapseLoopCountExpr->getSourceRange();
3724 NestedLoopCount = Result.getLimitedValue();
3727 // This is helper routine for loop directives (e.g., 'for', 'simd',
3728 // 'for simd', etc.).
3729 SmallVector<LoopIterationSpace, 4> IterSpaces;
3730 IterSpaces.resize(NestedLoopCount);
3731 Stmt *CurStmt = AStmt->IgnoreContainers(/* IgnoreCaptured */ true);
3732 for (unsigned Cnt = 0; Cnt < NestedLoopCount; ++Cnt) {
3733 if (CheckOpenMPIterationSpace(DKind, CurStmt, SemaRef, DSA, Cnt,
3734 NestedLoopCount, CollapseLoopCountExpr,
3735 OrderedLoopCountExpr, VarsWithImplicitDSA,
3738 // Move on to the next nested for loop, or to the loop body.
3739 // OpenMP [2.8.1, simd construct, Restrictions]
3740 // All loops associated with the construct must be perfectly nested; that
3741 // is, there must be no intervening code nor any OpenMP directive between
3743 CurStmt = cast<ForStmt>(CurStmt)->getBody()->IgnoreContainers();
3746 Built.clear(/* size */ NestedLoopCount);
3748 if (SemaRef.CurContext->isDependentContext())
3749 return NestedLoopCount;
3751 // An example of what is generated for the following code:
3753 // #pragma omp simd collapse(2) ordered(2)
3754 // for (i = 0; i < NI; ++i)
3755 // for (k = 0; k < NK; ++k)
3756 // for (j = J0; j < NJ; j+=2) {
3760 // We generate the code below.
3761 // Note: the loop body may be outlined in CodeGen.
3762 // Note: some counters may be C++ classes, operator- is used to find number of
3763 // iterations and operator+= to calculate counter value.
3764 // Note: decltype(NumIterations) must be integer type (in 'omp for', only i32
3765 // or i64 is currently supported).
3767 // #define NumIterations (NI * ((NJ - J0 - 1 + 2) / 2))
3768 // for (int[32|64]_t IV = 0; IV < NumIterations; ++IV ) {
3769 // .local.i = IV / ((NJ - J0 - 1 + 2) / 2);
3770 // .local.j = J0 + (IV % ((NJ - J0 - 1 + 2) / 2)) * 2;
3771 // // similar updates for vars in clauses (e.g. 'linear')
3772 // <loop body (using local i and j)>
3774 // i = NI; // assign final values of counters
3778 // Last iteration number is (I1 * I2 * ... In) - 1, where I1, I2 ... In are
3779 // the iteration counts of the collapsed for loops.
3780 // Precondition tests if there is at least one iteration (all conditions are
3782 auto PreCond = ExprResult(IterSpaces[0].PreCond);
3783 auto N0 = IterSpaces[0].NumIterations;
3784 ExprResult LastIteration32 = WidenIterationCount(
3785 32 /* Bits */, SemaRef.PerformImplicitConversion(
3786 N0->IgnoreImpCasts(), N0->getType(),
3787 Sema::AA_Converting, /*AllowExplicit=*/true)
3790 ExprResult LastIteration64 = WidenIterationCount(
3791 64 /* Bits */, SemaRef.PerformImplicitConversion(
3792 N0->IgnoreImpCasts(), N0->getType(),
3793 Sema::AA_Converting, /*AllowExplicit=*/true)
3797 if (!LastIteration32.isUsable() || !LastIteration64.isUsable())
3798 return NestedLoopCount;
3800 auto &C = SemaRef.Context;
3801 bool AllCountsNeedLessThan32Bits = C.getTypeSize(N0->getType()) < 32;
3803 Scope *CurScope = DSA.getCurScope();
3804 for (unsigned Cnt = 1; Cnt < NestedLoopCount; ++Cnt) {
3805 if (PreCond.isUsable()) {
3806 PreCond = SemaRef.BuildBinOp(CurScope, SourceLocation(), BO_LAnd,
3807 PreCond.get(), IterSpaces[Cnt].PreCond);
3809 auto N = IterSpaces[Cnt].NumIterations;
3810 AllCountsNeedLessThan32Bits &= C.getTypeSize(N->getType()) < 32;
3811 if (LastIteration32.isUsable())
3812 LastIteration32 = SemaRef.BuildBinOp(
3813 CurScope, SourceLocation(), BO_Mul, LastIteration32.get(),
3814 SemaRef.PerformImplicitConversion(N->IgnoreImpCasts(), N->getType(),
3815 Sema::AA_Converting,
3816 /*AllowExplicit=*/true)
3818 if (LastIteration64.isUsable())
3819 LastIteration64 = SemaRef.BuildBinOp(
3820 CurScope, SourceLocation(), BO_Mul, LastIteration64.get(),
3821 SemaRef.PerformImplicitConversion(N->IgnoreImpCasts(), N->getType(),
3822 Sema::AA_Converting,
3823 /*AllowExplicit=*/true)
3827 // Choose either the 32-bit or 64-bit version.
3828 ExprResult LastIteration = LastIteration64;
3829 if (LastIteration32.isUsable() &&
3830 C.getTypeSize(LastIteration32.get()->getType()) == 32 &&
3831 (AllCountsNeedLessThan32Bits || NestedLoopCount == 1 ||
3834 LastIteration32.get()->getType()->hasSignedIntegerRepresentation(),
3835 LastIteration64.get(), SemaRef)))
3836 LastIteration = LastIteration32;
3838 if (!LastIteration.isUsable())
3841 // Save the number of iterations.
3842 ExprResult NumIterations = LastIteration;
3844 LastIteration = SemaRef.BuildBinOp(
3845 CurScope, SourceLocation(), BO_Sub, LastIteration.get(),
3846 SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get());
3847 if (!LastIteration.isUsable())
3851 // Calculate the last iteration number beforehand instead of doing this on
3852 // each iteration. Do not do this if the number of iterations may be kfold-ed.
3853 llvm::APSInt Result;
3855 LastIteration.get()->isIntegerConstantExpr(Result, SemaRef.Context);
3856 ExprResult CalcLastIteration;
3858 SourceLocation SaveLoc;
3860 buildVarDecl(SemaRef, SaveLoc, LastIteration.get()->getType(),
3861 ".omp.last.iteration");
3862 ExprResult SaveRef = buildDeclRefExpr(
3863 SemaRef, SaveVar, LastIteration.get()->getType(), SaveLoc);
3864 CalcLastIteration = SemaRef.BuildBinOp(CurScope, SaveLoc, BO_Assign,
3865 SaveRef.get(), LastIteration.get());
3866 LastIteration = SaveRef;
3868 // Prepare SaveRef + 1.
3869 NumIterations = SemaRef.BuildBinOp(
3870 CurScope, SaveLoc, BO_Add, SaveRef.get(),
3871 SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get());
3872 if (!NumIterations.isUsable())
3876 SourceLocation InitLoc = IterSpaces[0].InitSrcRange.getBegin();
3878 QualType VType = LastIteration.get()->getType();
3879 // Build variables passed into runtime, nesessary for worksharing directives.
3880 ExprResult LB, UB, IL, ST, EUB;
3881 if (isOpenMPWorksharingDirective(DKind) || isOpenMPTaskLoopDirective(DKind) ||
3882 isOpenMPDistributeDirective(DKind)) {
3883 // Lower bound variable, initialized with zero.
3884 VarDecl *LBDecl = buildVarDecl(SemaRef, InitLoc, VType, ".omp.lb");
3885 LB = buildDeclRefExpr(SemaRef, LBDecl, VType, InitLoc);
3886 SemaRef.AddInitializerToDecl(
3887 LBDecl, SemaRef.ActOnIntegerConstant(InitLoc, 0).get(),
3888 /*DirectInit*/ false, /*TypeMayContainAuto*/ false);
3890 // Upper bound variable, initialized with last iteration number.
3891 VarDecl *UBDecl = buildVarDecl(SemaRef, InitLoc, VType, ".omp.ub");
3892 UB = buildDeclRefExpr(SemaRef, UBDecl, VType, InitLoc);
3893 SemaRef.AddInitializerToDecl(UBDecl, LastIteration.get(),
3894 /*DirectInit*/ false,
3895 /*TypeMayContainAuto*/ false);
3897 // A 32-bit variable-flag where runtime returns 1 for the last iteration.
3898 // This will be used to implement clause 'lastprivate'.
3899 QualType Int32Ty = SemaRef.Context.getIntTypeForBitwidth(32, true);
3900 VarDecl *ILDecl = buildVarDecl(SemaRef, InitLoc, Int32Ty, ".omp.is_last");
3901 IL = buildDeclRefExpr(SemaRef, ILDecl, Int32Ty, InitLoc);
3902 SemaRef.AddInitializerToDecl(
3903 ILDecl, SemaRef.ActOnIntegerConstant(InitLoc, 0).get(),
3904 /*DirectInit*/ false, /*TypeMayContainAuto*/ false);
3906 // Stride variable returned by runtime (we initialize it to 1 by default).
3907 VarDecl *STDecl = buildVarDecl(SemaRef, InitLoc, VType, ".omp.stride");
3908 ST = buildDeclRefExpr(SemaRef, STDecl, VType, InitLoc);
3909 SemaRef.AddInitializerToDecl(
3910 STDecl, SemaRef.ActOnIntegerConstant(InitLoc, 1).get(),
3911 /*DirectInit*/ false, /*TypeMayContainAuto*/ false);
3913 // Build expression: UB = min(UB, LastIteration)
3914 // It is nesessary for CodeGen of directives with static scheduling.
3915 ExprResult IsUBGreater = SemaRef.BuildBinOp(CurScope, InitLoc, BO_GT,
3916 UB.get(), LastIteration.get());
3917 ExprResult CondOp = SemaRef.ActOnConditionalOp(
3918 InitLoc, InitLoc, IsUBGreater.get(), LastIteration.get(), UB.get());
3919 EUB = SemaRef.BuildBinOp(CurScope, InitLoc, BO_Assign, UB.get(),
3921 EUB = SemaRef.ActOnFinishFullExpr(EUB.get());
3924 // Build the iteration variable and its initialization before loop.
3928 VarDecl *IVDecl = buildVarDecl(SemaRef, InitLoc, VType, ".omp.iv");
3929 IV = buildDeclRefExpr(SemaRef, IVDecl, VType, InitLoc);
3930 Expr *RHS = (isOpenMPWorksharingDirective(DKind) ||
3931 isOpenMPTaskLoopDirective(DKind) ||
3932 isOpenMPDistributeDirective(DKind))
3934 : SemaRef.ActOnIntegerConstant(SourceLocation(), 0).get();
3935 Init = SemaRef.BuildBinOp(CurScope, InitLoc, BO_Assign, IV.get(), RHS);
3936 Init = SemaRef.ActOnFinishFullExpr(Init.get());
3939 // Loop condition (IV < NumIterations) or (IV <= UB) for worksharing loops.
3940 SourceLocation CondLoc;
3942 (isOpenMPWorksharingDirective(DKind) ||
3943 isOpenMPTaskLoopDirective(DKind) || isOpenMPDistributeDirective(DKind))
3944 ? SemaRef.BuildBinOp(CurScope, CondLoc, BO_LE, IV.get(), UB.get())
3945 : SemaRef.BuildBinOp(CurScope, CondLoc, BO_LT, IV.get(),
3946 NumIterations.get());
3948 // Loop increment (IV = IV + 1)
3949 SourceLocation IncLoc;
3951 SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, IV.get(),
3952 SemaRef.ActOnIntegerConstant(IncLoc, 1).get());
3953 if (!Inc.isUsable())
3955 Inc = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, IV.get(), Inc.get());
3956 Inc = SemaRef.ActOnFinishFullExpr(Inc.get());
3957 if (!Inc.isUsable())
3960 // Increments for worksharing loops (LB = LB + ST; UB = UB + ST).
3961 // Used for directives with static scheduling.
3962 ExprResult NextLB, NextUB;
3963 if (isOpenMPWorksharingDirective(DKind) || isOpenMPTaskLoopDirective(DKind) ||
3964 isOpenMPDistributeDirective(DKind)) {
3966 NextLB = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, LB.get(), ST.get());
3967 if (!NextLB.isUsable())
3971 SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, LB.get(), NextLB.get());
3972 NextLB = SemaRef.ActOnFinishFullExpr(NextLB.get());
3973 if (!NextLB.isUsable())
3976 NextUB = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, UB.get(), ST.get());
3977 if (!NextUB.isUsable())
3981 SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, UB.get(), NextUB.get());
3982 NextUB = SemaRef.ActOnFinishFullExpr(NextUB.get());
3983 if (!NextUB.isUsable())
3987 // Build updates and final values of the loop counters.
3988 bool HasErrors = false;
3989 Built.Counters.resize(NestedLoopCount);
3990 Built.Inits.resize(NestedLoopCount);
3991 Built.Updates.resize(NestedLoopCount);
3992 Built.Finals.resize(NestedLoopCount);
3995 // Go from inner nested loop to outer.
3996 for (int Cnt = NestedLoopCount - 1; Cnt >= 0; --Cnt) {
3997 LoopIterationSpace &IS = IterSpaces[Cnt];
3998 SourceLocation UpdLoc = IS.IncSrcRange.getBegin();
3999 // Build: Iter = (IV / Div) % IS.NumIters
4000 // where Div is product of previous iterations' IS.NumIters.
4002 if (Div.isUsable()) {
4004 SemaRef.BuildBinOp(CurScope, UpdLoc, BO_Div, IV.get(), Div.get());
4007 assert((Cnt == (int)NestedLoopCount - 1) &&
4008 "unusable div expected on first iteration only");
4011 if (Cnt != 0 && Iter.isUsable())
4012 Iter = SemaRef.BuildBinOp(CurScope, UpdLoc, BO_Rem, Iter.get(),
4014 if (!Iter.isUsable()) {
4019 // Build update: IS.CounterVar(Private) = IS.Start + Iter * IS.Step
4020 auto *CounterVar = buildDeclRefExpr(
4021 SemaRef, cast<VarDecl>(cast<DeclRefExpr>(IS.CounterVar)->getDecl()),
4022 IS.CounterVar->getType(), IS.CounterVar->getExprLoc(),
4023 /*RefersToCapture=*/true);
4024 ExprResult Init = BuildCounterInit(SemaRef, CurScope, UpdLoc, CounterVar,
4026 if (!Init.isUsable()) {
4031 BuildCounterUpdate(SemaRef, CurScope, UpdLoc, CounterVar,
4032 IS.CounterInit, Iter, IS.CounterStep, IS.Subtract);
4033 if (!Update.isUsable()) {
4038 // Build final: IS.CounterVar = IS.Start + IS.NumIters * IS.Step
4039 ExprResult Final = BuildCounterUpdate(
4040 SemaRef, CurScope, UpdLoc, CounterVar, IS.CounterInit,
4041 IS.NumIterations, IS.CounterStep, IS.Subtract);
4042 if (!Final.isUsable()) {
4047 // Build Div for the next iteration: Div <- Div * IS.NumIters
4050 Div = IS.NumIterations;
4052 Div = SemaRef.BuildBinOp(CurScope, UpdLoc, BO_Mul, Div.get(),
4055 // Add parentheses (for debugging purposes only).
4057 Div = SemaRef.ActOnParenExpr(UpdLoc, UpdLoc, Div.get());
4058 if (!Div.isUsable()) {
4063 if (!Update.isUsable() || !Final.isUsable()) {
4068 Built.Counters[Cnt] = IS.CounterVar;
4069 Built.PrivateCounters[Cnt] = IS.PrivateCounterVar;
4070 Built.Inits[Cnt] = Init.get();
4071 Built.Updates[Cnt] = Update.get();
4072 Built.Finals[Cnt] = Final.get();
4080 Built.IterationVarRef = IV.get();
4081 Built.LastIteration = LastIteration.get();
4082 Built.NumIterations = NumIterations.get();
4083 Built.CalcLastIteration =
4084 SemaRef.ActOnFinishFullExpr(CalcLastIteration.get()).get();
4085 Built.PreCond = PreCond.get();
4086 Built.Cond = Cond.get();
4087 Built.Init = Init.get();
4088 Built.Inc = Inc.get();
4089 Built.LB = LB.get();
4090 Built.UB = UB.get();
4091 Built.IL = IL.get();
4092 Built.ST = ST.get();
4093 Built.EUB = EUB.get();
4094 Built.NLB = NextLB.get();
4095 Built.NUB = NextUB.get();
4097 return NestedLoopCount;
4100 static Expr *getCollapseNumberExpr(ArrayRef<OMPClause *> Clauses) {
4101 auto CollapseClauses =
4102 OMPExecutableDirective::getClausesOfKind<OMPCollapseClause>(Clauses);
4103 if (CollapseClauses.begin() != CollapseClauses.end())
4104 return (*CollapseClauses.begin())->getNumForLoops();
4108 static Expr *getOrderedNumberExpr(ArrayRef<OMPClause *> Clauses) {
4109 auto OrderedClauses =
4110 OMPExecutableDirective::getClausesOfKind<OMPOrderedClause>(Clauses);
4111 if (OrderedClauses.begin() != OrderedClauses.end())
4112 return (*OrderedClauses.begin())->getNumForLoops();
4116 static bool checkSimdlenSafelenValues(Sema &S, const Expr *Simdlen,
4117 const Expr *Safelen) {
4118 llvm::APSInt SimdlenRes, SafelenRes;
4119 if (Simdlen->isValueDependent() || Simdlen->isTypeDependent() ||
4120 Simdlen->isInstantiationDependent() ||
4121 Simdlen->containsUnexpandedParameterPack())
4123 if (Safelen->isValueDependent() || Safelen->isTypeDependent() ||
4124 Safelen->isInstantiationDependent() ||
4125 Safelen->containsUnexpandedParameterPack())
4127 Simdlen->EvaluateAsInt(SimdlenRes, S.Context);
4128 Safelen->EvaluateAsInt(SafelenRes, S.Context);
4129 // OpenMP 4.1 [2.8.1, simd Construct, Restrictions]
4130 // If both simdlen and safelen clauses are specified, the value of the simdlen
4131 // parameter must be less than or equal to the value of the safelen parameter.
4132 if (SimdlenRes > SafelenRes) {
4133 S.Diag(Simdlen->getExprLoc(), diag::err_omp_wrong_simdlen_safelen_values)
4134 << Simdlen->getSourceRange() << Safelen->getSourceRange();
4140 StmtResult Sema::ActOnOpenMPSimdDirective(
4141 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
4142 SourceLocation EndLoc,
4143 llvm::DenseMap<VarDecl *, Expr *> &VarsWithImplicitDSA) {
4147 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
4148 OMPLoopDirective::HelperExprs B;
4149 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
4150 // define the nested loops number.
4151 unsigned NestedLoopCount = CheckOpenMPLoop(
4152 OMPD_simd, getCollapseNumberExpr(Clauses), getOrderedNumberExpr(Clauses),
4153 AStmt, *this, *DSAStack, VarsWithImplicitDSA, B);
4154 if (NestedLoopCount == 0)
4157 assert((CurContext->isDependentContext() || B.builtAll()) &&
4158 "omp simd loop exprs were not built");
4160 if (!CurContext->isDependentContext()) {
4161 // Finalize the clauses that need pre-built expressions for CodeGen.
4162 for (auto C : Clauses) {
4163 if (auto LC = dyn_cast<OMPLinearClause>(C))
4164 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
4165 B.NumIterations, *this, CurScope))
4170 // OpenMP 4.1 [2.8.1, simd Construct, Restrictions]
4171 // If both simdlen and safelen clauses are specified, the value of the simdlen
4172 // parameter must be less than or equal to the value of the safelen parameter.
4173 OMPSafelenClause *Safelen = nullptr;
4174 OMPSimdlenClause *Simdlen = nullptr;
4175 for (auto *Clause : Clauses) {
4176 if (Clause->getClauseKind() == OMPC_safelen)
4177 Safelen = cast<OMPSafelenClause>(Clause);
4178 else if (Clause->getClauseKind() == OMPC_simdlen)
4179 Simdlen = cast<OMPSimdlenClause>(Clause);
4180 if (Safelen && Simdlen)
4183 if (Simdlen && Safelen &&
4184 checkSimdlenSafelenValues(*this, Simdlen->getSimdlen(),
4185 Safelen->getSafelen()))
4188 getCurFunction()->setHasBranchProtectedScope();
4189 return OMPSimdDirective::Create(Context, StartLoc, EndLoc, NestedLoopCount,
4193 StmtResult Sema::ActOnOpenMPForDirective(
4194 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
4195 SourceLocation EndLoc,
4196 llvm::DenseMap<VarDecl *, Expr *> &VarsWithImplicitDSA) {
4200 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
4201 OMPLoopDirective::HelperExprs B;
4202 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
4203 // define the nested loops number.
4204 unsigned NestedLoopCount = CheckOpenMPLoop(
4205 OMPD_for, getCollapseNumberExpr(Clauses), getOrderedNumberExpr(Clauses),
4206 AStmt, *this, *DSAStack, VarsWithImplicitDSA, B);
4207 if (NestedLoopCount == 0)
4210 assert((CurContext->isDependentContext() || B.builtAll()) &&
4211 "omp for loop exprs were not built");
4213 if (!CurContext->isDependentContext()) {
4214 // Finalize the clauses that need pre-built expressions for CodeGen.
4215 for (auto C : Clauses) {
4216 if (auto LC = dyn_cast<OMPLinearClause>(C))
4217 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
4218 B.NumIterations, *this, CurScope))
4223 getCurFunction()->setHasBranchProtectedScope();
4224 return OMPForDirective::Create(Context, StartLoc, EndLoc, NestedLoopCount,
4225 Clauses, AStmt, B, DSAStack->isCancelRegion());
4228 StmtResult Sema::ActOnOpenMPForSimdDirective(
4229 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
4230 SourceLocation EndLoc,
4231 llvm::DenseMap<VarDecl *, Expr *> &VarsWithImplicitDSA) {
4235 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
4236 OMPLoopDirective::HelperExprs B;
4237 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
4238 // define the nested loops number.
4239 unsigned NestedLoopCount =
4240 CheckOpenMPLoop(OMPD_for_simd, getCollapseNumberExpr(Clauses),
4241 getOrderedNumberExpr(Clauses), AStmt, *this, *DSAStack,
4242 VarsWithImplicitDSA, B);
4243 if (NestedLoopCount == 0)
4246 assert((CurContext->isDependentContext() || B.builtAll()) &&
4247 "omp for simd loop exprs were not built");
4249 if (!CurContext->isDependentContext()) {
4250 // Finalize the clauses that need pre-built expressions for CodeGen.
4251 for (auto C : Clauses) {
4252 if (auto LC = dyn_cast<OMPLinearClause>(C))
4253 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
4254 B.NumIterations, *this, CurScope))
4259 // OpenMP 4.1 [2.8.1, simd Construct, Restrictions]
4260 // If both simdlen and safelen clauses are specified, the value of the simdlen
4261 // parameter must be less than or equal to the value of the safelen parameter.
4262 OMPSafelenClause *Safelen = nullptr;
4263 OMPSimdlenClause *Simdlen = nullptr;
4264 for (auto *Clause : Clauses) {
4265 if (Clause->getClauseKind() == OMPC_safelen)
4266 Safelen = cast<OMPSafelenClause>(Clause);
4267 else if (Clause->getClauseKind() == OMPC_simdlen)
4268 Simdlen = cast<OMPSimdlenClause>(Clause);
4269 if (Safelen && Simdlen)
4272 if (Simdlen && Safelen &&
4273 checkSimdlenSafelenValues(*this, Simdlen->getSimdlen(),
4274 Safelen->getSafelen()))
4277 getCurFunction()->setHasBranchProtectedScope();
4278 return OMPForSimdDirective::Create(Context, StartLoc, EndLoc, NestedLoopCount,
4282 StmtResult Sema::ActOnOpenMPSectionsDirective(ArrayRef<OMPClause *> Clauses,
4284 SourceLocation StartLoc,
4285 SourceLocation EndLoc) {
4289 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
4290 auto BaseStmt = AStmt;
4291 while (CapturedStmt *CS = dyn_cast_or_null<CapturedStmt>(BaseStmt))
4292 BaseStmt = CS->getCapturedStmt();
4293 if (auto C = dyn_cast_or_null<CompoundStmt>(BaseStmt)) {
4294 auto S = C->children();
4295 if (S.begin() == S.end())
4297 // All associated statements must be '#pragma omp section' except for
4299 for (Stmt *SectionStmt : llvm::make_range(std::next(S.begin()), S.end())) {
4300 if (!SectionStmt || !isa<OMPSectionDirective>(SectionStmt)) {
4302 Diag(SectionStmt->getLocStart(),
4303 diag::err_omp_sections_substmt_not_section);
4306 cast<OMPSectionDirective>(SectionStmt)
4307 ->setHasCancel(DSAStack->isCancelRegion());
4310 Diag(AStmt->getLocStart(), diag::err_omp_sections_not_compound_stmt);
4314 getCurFunction()->setHasBranchProtectedScope();
4316 return OMPSectionsDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt,
4317 DSAStack->isCancelRegion());
4320 StmtResult Sema::ActOnOpenMPSectionDirective(Stmt *AStmt,
4321 SourceLocation StartLoc,
4322 SourceLocation EndLoc) {
4326 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
4328 getCurFunction()->setHasBranchProtectedScope();
4329 DSAStack->setParentCancelRegion(DSAStack->isCancelRegion());
4331 return OMPSectionDirective::Create(Context, StartLoc, EndLoc, AStmt,
4332 DSAStack->isCancelRegion());
4335 StmtResult Sema::ActOnOpenMPSingleDirective(ArrayRef<OMPClause *> Clauses,
4337 SourceLocation StartLoc,
4338 SourceLocation EndLoc) {
4342 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
4344 getCurFunction()->setHasBranchProtectedScope();
4346 // OpenMP [2.7.3, single Construct, Restrictions]
4347 // The copyprivate clause must not be used with the nowait clause.
4348 OMPClause *Nowait = nullptr;
4349 OMPClause *Copyprivate = nullptr;
4350 for (auto *Clause : Clauses) {
4351 if (Clause->getClauseKind() == OMPC_nowait)
4353 else if (Clause->getClauseKind() == OMPC_copyprivate)
4354 Copyprivate = Clause;
4355 if (Copyprivate && Nowait) {
4356 Diag(Copyprivate->getLocStart(),
4357 diag::err_omp_single_copyprivate_with_nowait);
4358 Diag(Nowait->getLocStart(), diag::note_omp_nowait_clause_here);
4363 return OMPSingleDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt);
4366 StmtResult Sema::ActOnOpenMPMasterDirective(Stmt *AStmt,
4367 SourceLocation StartLoc,
4368 SourceLocation EndLoc) {
4372 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
4374 getCurFunction()->setHasBranchProtectedScope();
4376 return OMPMasterDirective::Create(Context, StartLoc, EndLoc, AStmt);
4379 StmtResult Sema::ActOnOpenMPCriticalDirective(
4380 const DeclarationNameInfo &DirName, ArrayRef<OMPClause *> Clauses,
4381 Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc) {
4385 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
4387 bool ErrorFound = false;
4389 SourceLocation HintLoc;
4390 bool DependentHint = false;
4391 for (auto *C : Clauses) {
4392 if (C->getClauseKind() == OMPC_hint) {
4393 if (!DirName.getName()) {
4394 Diag(C->getLocStart(), diag::err_omp_hint_clause_no_name);
4397 Expr *E = cast<OMPHintClause>(C)->getHint();
4398 if (E->isTypeDependent() || E->isValueDependent() ||
4399 E->isInstantiationDependent())
4400 DependentHint = true;
4402 Hint = E->EvaluateKnownConstInt(Context);
4403 HintLoc = C->getLocStart();
4409 auto Pair = DSAStack->getCriticalWithHint(DirName);
4410 if (Pair.first && DirName.getName() && !DependentHint) {
4411 if (llvm::APSInt::compareValues(Hint, Pair.second) != 0) {
4412 Diag(StartLoc, diag::err_omp_critical_with_hint);
4413 if (HintLoc.isValid()) {
4414 Diag(HintLoc, diag::note_omp_critical_hint_here)
4415 << 0 << Hint.toString(/*Radix=*/10, /*Signed=*/false);
4417 Diag(StartLoc, diag::note_omp_critical_no_hint) << 0;
4418 if (auto *C = Pair.first->getSingleClause<OMPHintClause>()) {
4419 Diag(C->getLocStart(), diag::note_omp_critical_hint_here)
4421 << C->getHint()->EvaluateKnownConstInt(Context).toString(
4422 /*Radix=*/10, /*Signed=*/false);
4424 Diag(Pair.first->getLocStart(), diag::note_omp_critical_no_hint) << 1;
4428 getCurFunction()->setHasBranchProtectedScope();
4430 auto *Dir = OMPCriticalDirective::Create(Context, DirName, StartLoc, EndLoc,
4432 if (!Pair.first && DirName.getName() && !DependentHint)
4433 DSAStack->addCriticalWithHint(Dir, Hint);
4437 StmtResult Sema::ActOnOpenMPParallelForDirective(
4438 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
4439 SourceLocation EndLoc,
4440 llvm::DenseMap<VarDecl *, Expr *> &VarsWithImplicitDSA) {
4444 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
4445 // 1.2.2 OpenMP Language Terminology
4446 // Structured block - An executable statement with a single entry at the
4447 // top and a single exit at the bottom.
4448 // The point of exit cannot be a branch out of the structured block.
4449 // longjmp() and throw() must not violate the entry/exit criteria.
4450 CS->getCapturedDecl()->setNothrow();
4452 OMPLoopDirective::HelperExprs B;
4453 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
4454 // define the nested loops number.
4455 unsigned NestedLoopCount =
4456 CheckOpenMPLoop(OMPD_parallel_for, getCollapseNumberExpr(Clauses),
4457 getOrderedNumberExpr(Clauses), AStmt, *this, *DSAStack,
4458 VarsWithImplicitDSA, B);
4459 if (NestedLoopCount == 0)
4462 assert((CurContext->isDependentContext() || B.builtAll()) &&
4463 "omp parallel for loop exprs were not built");
4465 if (!CurContext->isDependentContext()) {
4466 // Finalize the clauses that need pre-built expressions for CodeGen.
4467 for (auto C : Clauses) {
4468 if (auto LC = dyn_cast<OMPLinearClause>(C))
4469 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
4470 B.NumIterations, *this, CurScope))
4475 getCurFunction()->setHasBranchProtectedScope();
4476 return OMPParallelForDirective::Create(Context, StartLoc, EndLoc,
4477 NestedLoopCount, Clauses, AStmt, B,
4478 DSAStack->isCancelRegion());
4481 StmtResult Sema::ActOnOpenMPParallelForSimdDirective(
4482 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
4483 SourceLocation EndLoc,
4484 llvm::DenseMap<VarDecl *, Expr *> &VarsWithImplicitDSA) {
4488 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
4489 // 1.2.2 OpenMP Language Terminology
4490 // Structured block - An executable statement with a single entry at the
4491 // top and a single exit at the bottom.
4492 // The point of exit cannot be a branch out of the structured block.
4493 // longjmp() and throw() must not violate the entry/exit criteria.
4494 CS->getCapturedDecl()->setNothrow();
4496 OMPLoopDirective::HelperExprs B;
4497 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
4498 // define the nested loops number.
4499 unsigned NestedLoopCount =
4500 CheckOpenMPLoop(OMPD_parallel_for_simd, getCollapseNumberExpr(Clauses),
4501 getOrderedNumberExpr(Clauses), AStmt, *this, *DSAStack,
4502 VarsWithImplicitDSA, B);
4503 if (NestedLoopCount == 0)
4506 if (!CurContext->isDependentContext()) {
4507 // Finalize the clauses that need pre-built expressions for CodeGen.
4508 for (auto C : Clauses) {
4509 if (auto LC = dyn_cast<OMPLinearClause>(C))
4510 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
4511 B.NumIterations, *this, CurScope))
4516 // OpenMP 4.1 [2.8.1, simd Construct, Restrictions]
4517 // If both simdlen and safelen clauses are specified, the value of the simdlen
4518 // parameter must be less than or equal to the value of the safelen parameter.
4519 OMPSafelenClause *Safelen = nullptr;
4520 OMPSimdlenClause *Simdlen = nullptr;
4521 for (auto *Clause : Clauses) {
4522 if (Clause->getClauseKind() == OMPC_safelen)
4523 Safelen = cast<OMPSafelenClause>(Clause);
4524 else if (Clause->getClauseKind() == OMPC_simdlen)
4525 Simdlen = cast<OMPSimdlenClause>(Clause);
4526 if (Safelen && Simdlen)
4529 if (Simdlen && Safelen &&
4530 checkSimdlenSafelenValues(*this, Simdlen->getSimdlen(),
4531 Safelen->getSafelen()))
4534 getCurFunction()->setHasBranchProtectedScope();
4535 return OMPParallelForSimdDirective::Create(
4536 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
4540 Sema::ActOnOpenMPParallelSectionsDirective(ArrayRef<OMPClause *> Clauses,
4541 Stmt *AStmt, SourceLocation StartLoc,
4542 SourceLocation EndLoc) {
4546 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
4547 auto BaseStmt = AStmt;
4548 while (CapturedStmt *CS = dyn_cast_or_null<CapturedStmt>(BaseStmt))
4549 BaseStmt = CS->getCapturedStmt();
4550 if (auto C = dyn_cast_or_null<CompoundStmt>(BaseStmt)) {
4551 auto S = C->children();
4552 if (S.begin() == S.end())
4554 // All associated statements must be '#pragma omp section' except for
4556 for (Stmt *SectionStmt : llvm::make_range(std::next(S.begin()), S.end())) {
4557 if (!SectionStmt || !isa<OMPSectionDirective>(SectionStmt)) {
4559 Diag(SectionStmt->getLocStart(),
4560 diag::err_omp_parallel_sections_substmt_not_section);
4563 cast<OMPSectionDirective>(SectionStmt)
4564 ->setHasCancel(DSAStack->isCancelRegion());
4567 Diag(AStmt->getLocStart(),
4568 diag::err_omp_parallel_sections_not_compound_stmt);
4572 getCurFunction()->setHasBranchProtectedScope();
4574 return OMPParallelSectionsDirective::Create(
4575 Context, StartLoc, EndLoc, Clauses, AStmt, DSAStack->isCancelRegion());
4578 StmtResult Sema::ActOnOpenMPTaskDirective(ArrayRef<OMPClause *> Clauses,
4579 Stmt *AStmt, SourceLocation StartLoc,
4580 SourceLocation EndLoc) {
4584 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
4585 // 1.2.2 OpenMP Language Terminology
4586 // Structured block - An executable statement with a single entry at the
4587 // top and a single exit at the bottom.
4588 // The point of exit cannot be a branch out of the structured block.
4589 // longjmp() and throw() must not violate the entry/exit criteria.
4590 CS->getCapturedDecl()->setNothrow();
4592 getCurFunction()->setHasBranchProtectedScope();
4594 return OMPTaskDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt,
4595 DSAStack->isCancelRegion());
4598 StmtResult Sema::ActOnOpenMPTaskyieldDirective(SourceLocation StartLoc,
4599 SourceLocation EndLoc) {
4600 return OMPTaskyieldDirective::Create(Context, StartLoc, EndLoc);
4603 StmtResult Sema::ActOnOpenMPBarrierDirective(SourceLocation StartLoc,
4604 SourceLocation EndLoc) {
4605 return OMPBarrierDirective::Create(Context, StartLoc, EndLoc);
4608 StmtResult Sema::ActOnOpenMPTaskwaitDirective(SourceLocation StartLoc,
4609 SourceLocation EndLoc) {
4610 return OMPTaskwaitDirective::Create(Context, StartLoc, EndLoc);
4613 StmtResult Sema::ActOnOpenMPTaskgroupDirective(Stmt *AStmt,
4614 SourceLocation StartLoc,
4615 SourceLocation EndLoc) {
4619 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
4621 getCurFunction()->setHasBranchProtectedScope();
4623 return OMPTaskgroupDirective::Create(Context, StartLoc, EndLoc, AStmt);
4626 StmtResult Sema::ActOnOpenMPFlushDirective(ArrayRef<OMPClause *> Clauses,
4627 SourceLocation StartLoc,
4628 SourceLocation EndLoc) {
4629 assert(Clauses.size() <= 1 && "Extra clauses in flush directive");
4630 return OMPFlushDirective::Create(Context, StartLoc, EndLoc, Clauses);
4633 StmtResult Sema::ActOnOpenMPOrderedDirective(ArrayRef<OMPClause *> Clauses,
4635 SourceLocation StartLoc,
4636 SourceLocation EndLoc) {
4637 OMPClause *DependFound = nullptr;
4638 OMPClause *DependSourceClause = nullptr;
4639 OMPClause *DependSinkClause = nullptr;
4640 bool ErrorFound = false;
4641 OMPThreadsClause *TC = nullptr;
4642 OMPSIMDClause *SC = nullptr;
4643 for (auto *C : Clauses) {
4644 if (auto *DC = dyn_cast<OMPDependClause>(C)) {
4646 if (DC->getDependencyKind() == OMPC_DEPEND_source) {
4647 if (DependSourceClause) {
4648 Diag(C->getLocStart(), diag::err_omp_more_one_clause)
4649 << getOpenMPDirectiveName(OMPD_ordered)
4650 << getOpenMPClauseName(OMPC_depend) << 2;
4653 DependSourceClause = C;
4654 if (DependSinkClause) {
4655 Diag(C->getLocStart(), diag::err_omp_depend_sink_source_not_allowed)
4659 } else if (DC->getDependencyKind() == OMPC_DEPEND_sink) {
4660 if (DependSourceClause) {
4661 Diag(C->getLocStart(), diag::err_omp_depend_sink_source_not_allowed)
4665 DependSinkClause = C;
4667 } else if (C->getClauseKind() == OMPC_threads)
4668 TC = cast<OMPThreadsClause>(C);
4669 else if (C->getClauseKind() == OMPC_simd)
4670 SC = cast<OMPSIMDClause>(C);
4672 if (!ErrorFound && !SC &&
4673 isOpenMPSimdDirective(DSAStack->getParentDirective())) {
4674 // OpenMP [2.8.1,simd Construct, Restrictions]
4675 // An ordered construct with the simd clause is the only OpenMP construct
4676 // that can appear in the simd region.
4677 Diag(StartLoc, diag::err_omp_prohibited_region_simd);
4679 } else if (DependFound && (TC || SC)) {
4680 Diag(DependFound->getLocStart(), diag::err_omp_depend_clause_thread_simd)
4681 << getOpenMPClauseName(TC ? TC->getClauseKind() : SC->getClauseKind());
4683 } else if (DependFound && !DSAStack->getParentOrderedRegionParam()) {
4684 Diag(DependFound->getLocStart(),
4685 diag::err_omp_ordered_directive_without_param);
4687 } else if (TC || Clauses.empty()) {
4688 if (auto *Param = DSAStack->getParentOrderedRegionParam()) {
4689 SourceLocation ErrLoc = TC ? TC->getLocStart() : StartLoc;
4690 Diag(ErrLoc, diag::err_omp_ordered_directive_with_param)
4692 Diag(Param->getLocStart(), diag::note_omp_ordered_param);
4696 if ((!AStmt && !DependFound) || ErrorFound)
4700 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
4702 getCurFunction()->setHasBranchProtectedScope();
4705 return OMPOrderedDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt);
4709 /// \brief Helper class for checking expression in 'omp atomic [update]'
4711 class OpenMPAtomicUpdateChecker {
4712 /// \brief Error results for atomic update expressions.
4713 enum ExprAnalysisErrorCode {
4714 /// \brief A statement is not an expression statement.
4716 /// \brief Expression is not builtin binary or unary operation.
4717 NotABinaryOrUnaryExpression,
4718 /// \brief Unary operation is not post-/pre- increment/decrement operation.
4719 NotAnUnaryIncDecExpression,
4720 /// \brief An expression is not of scalar type.
4722 /// \brief A binary operation is not an assignment operation.
4724 /// \brief RHS part of the binary operation is not a binary expression.
4725 NotABinaryExpression,
4726 /// \brief RHS part is not additive/multiplicative/shift/biwise binary
4729 /// \brief RHS binary operation does not have reference to the updated LHS
4731 NotAnUpdateExpression,
4732 /// \brief No errors is found.
4735 /// \brief Reference to Sema.
4737 /// \brief A location for note diagnostics (when error is found).
4738 SourceLocation NoteLoc;
4739 /// \brief 'x' lvalue part of the source atomic expression.
4741 /// \brief 'expr' rvalue part of the source atomic expression.
4743 /// \brief Helper expression of the form
4744 /// 'OpaqueValueExpr(x) binop OpaqueValueExpr(expr)' or
4745 /// 'OpaqueValueExpr(expr) binop OpaqueValueExpr(x)'.
4747 /// \brief Is 'x' a LHS in a RHS part of full update expression. It is
4748 /// important for non-associative operations.
4749 bool IsXLHSInRHSPart;
4750 BinaryOperatorKind Op;
4751 SourceLocation OpLoc;
4752 /// \brief true if the source expression is a postfix unary operation, false
4753 /// if it is a prefix unary operation.
4754 bool IsPostfixUpdate;
4757 OpenMPAtomicUpdateChecker(Sema &SemaRef)
4758 : SemaRef(SemaRef), X(nullptr), E(nullptr), UpdateExpr(nullptr),
4759 IsXLHSInRHSPart(false), Op(BO_PtrMemD), IsPostfixUpdate(false) {}
4760 /// \brief Check specified statement that it is suitable for 'atomic update'
4761 /// constructs and extract 'x', 'expr' and Operation from the original
4762 /// expression. If DiagId and NoteId == 0, then only check is performed
4763 /// without error notification.
4764 /// \param DiagId Diagnostic which should be emitted if error is found.
4765 /// \param NoteId Diagnostic note for the main error message.
4766 /// \return true if statement is not an update expression, false otherwise.
4767 bool checkStatement(Stmt *S, unsigned DiagId = 0, unsigned NoteId = 0);
4768 /// \brief Return the 'x' lvalue part of the source atomic expression.
4769 Expr *getX() const { return X; }
4770 /// \brief Return the 'expr' rvalue part of the source atomic expression.
4771 Expr *getExpr() const { return E; }
4772 /// \brief Return the update expression used in calculation of the updated
4773 /// value. Always has form 'OpaqueValueExpr(x) binop OpaqueValueExpr(expr)' or
4774 /// 'OpaqueValueExpr(expr) binop OpaqueValueExpr(x)'.
4775 Expr *getUpdateExpr() const { return UpdateExpr; }
4776 /// \brief Return true if 'x' is LHS in RHS part of full update expression,
4777 /// false otherwise.
4778 bool isXLHSInRHSPart() const { return IsXLHSInRHSPart; }
4780 /// \brief true if the source expression is a postfix unary operation, false
4781 /// if it is a prefix unary operation.
4782 bool isPostfixUpdate() const { return IsPostfixUpdate; }
4785 bool checkBinaryOperation(BinaryOperator *AtomicBinOp, unsigned DiagId = 0,
4786 unsigned NoteId = 0);
4790 bool OpenMPAtomicUpdateChecker::checkBinaryOperation(
4791 BinaryOperator *AtomicBinOp, unsigned DiagId, unsigned NoteId) {
4792 ExprAnalysisErrorCode ErrorFound = NoError;
4793 SourceLocation ErrorLoc, NoteLoc;
4794 SourceRange ErrorRange, NoteRange;
4795 // Allowed constructs are:
4796 // x = x binop expr;
4797 // x = expr binop x;
4798 if (AtomicBinOp->getOpcode() == BO_Assign) {
4799 X = AtomicBinOp->getLHS();
4800 if (auto *AtomicInnerBinOp = dyn_cast<BinaryOperator>(
4801 AtomicBinOp->getRHS()->IgnoreParenImpCasts())) {
4802 if (AtomicInnerBinOp->isMultiplicativeOp() ||
4803 AtomicInnerBinOp->isAdditiveOp() || AtomicInnerBinOp->isShiftOp() ||
4804 AtomicInnerBinOp->isBitwiseOp()) {
4805 Op = AtomicInnerBinOp->getOpcode();
4806 OpLoc = AtomicInnerBinOp->getOperatorLoc();
4807 auto *LHS = AtomicInnerBinOp->getLHS();
4808 auto *RHS = AtomicInnerBinOp->getRHS();
4809 llvm::FoldingSetNodeID XId, LHSId, RHSId;
4810 X->IgnoreParenImpCasts()->Profile(XId, SemaRef.getASTContext(),
4811 /*Canonical=*/true);
4812 LHS->IgnoreParenImpCasts()->Profile(LHSId, SemaRef.getASTContext(),
4813 /*Canonical=*/true);
4814 RHS->IgnoreParenImpCasts()->Profile(RHSId, SemaRef.getASTContext(),
4815 /*Canonical=*/true);
4818 IsXLHSInRHSPart = true;
4819 } else if (XId == RHSId) {
4821 IsXLHSInRHSPart = false;
4823 ErrorLoc = AtomicInnerBinOp->getExprLoc();
4824 ErrorRange = AtomicInnerBinOp->getSourceRange();
4825 NoteLoc = X->getExprLoc();
4826 NoteRange = X->getSourceRange();
4827 ErrorFound = NotAnUpdateExpression;
4830 ErrorLoc = AtomicInnerBinOp->getExprLoc();
4831 ErrorRange = AtomicInnerBinOp->getSourceRange();
4832 NoteLoc = AtomicInnerBinOp->getOperatorLoc();
4833 NoteRange = SourceRange(NoteLoc, NoteLoc);
4834 ErrorFound = NotABinaryOperator;
4837 NoteLoc = ErrorLoc = AtomicBinOp->getRHS()->getExprLoc();
4838 NoteRange = ErrorRange = AtomicBinOp->getRHS()->getSourceRange();
4839 ErrorFound = NotABinaryExpression;
4842 ErrorLoc = AtomicBinOp->getExprLoc();
4843 ErrorRange = AtomicBinOp->getSourceRange();
4844 NoteLoc = AtomicBinOp->getOperatorLoc();
4845 NoteRange = SourceRange(NoteLoc, NoteLoc);
4846 ErrorFound = NotAnAssignmentOp;
4848 if (ErrorFound != NoError && DiagId != 0 && NoteId != 0) {
4849 SemaRef.Diag(ErrorLoc, DiagId) << ErrorRange;
4850 SemaRef.Diag(NoteLoc, NoteId) << ErrorFound << NoteRange;
4852 } else if (SemaRef.CurContext->isDependentContext())
4853 E = X = UpdateExpr = nullptr;
4854 return ErrorFound != NoError;
4857 bool OpenMPAtomicUpdateChecker::checkStatement(Stmt *S, unsigned DiagId,
4859 ExprAnalysisErrorCode ErrorFound = NoError;
4860 SourceLocation ErrorLoc, NoteLoc;
4861 SourceRange ErrorRange, NoteRange;
4862 // Allowed constructs are:
4868 // x = x binop expr;
4869 // x = expr binop x;
4870 if (auto *AtomicBody = dyn_cast<Expr>(S)) {
4871 AtomicBody = AtomicBody->IgnoreParenImpCasts();
4872 if (AtomicBody->getType()->isScalarType() ||
4873 AtomicBody->isInstantiationDependent()) {
4874 if (auto *AtomicCompAssignOp = dyn_cast<CompoundAssignOperator>(
4875 AtomicBody->IgnoreParenImpCasts())) {
4876 // Check for Compound Assignment Operation
4877 Op = BinaryOperator::getOpForCompoundAssignment(
4878 AtomicCompAssignOp->getOpcode());
4879 OpLoc = AtomicCompAssignOp->getOperatorLoc();
4880 E = AtomicCompAssignOp->getRHS();
4881 X = AtomicCompAssignOp->getLHS();
4882 IsXLHSInRHSPart = true;
4883 } else if (auto *AtomicBinOp = dyn_cast<BinaryOperator>(
4884 AtomicBody->IgnoreParenImpCasts())) {
4885 // Check for Binary Operation
4886 if(checkBinaryOperation(AtomicBinOp, DiagId, NoteId))
4888 } else if (auto *AtomicUnaryOp =
4889 dyn_cast<UnaryOperator>(AtomicBody->IgnoreParenImpCasts())) {
4890 // Check for Unary Operation
4891 if (AtomicUnaryOp->isIncrementDecrementOp()) {
4892 IsPostfixUpdate = AtomicUnaryOp->isPostfix();
4893 Op = AtomicUnaryOp->isIncrementOp() ? BO_Add : BO_Sub;
4894 OpLoc = AtomicUnaryOp->getOperatorLoc();
4895 X = AtomicUnaryOp->getSubExpr();
4896 E = SemaRef.ActOnIntegerConstant(OpLoc, /*uint64_t Val=*/1).get();
4897 IsXLHSInRHSPart = true;
4899 ErrorFound = NotAnUnaryIncDecExpression;
4900 ErrorLoc = AtomicUnaryOp->getExprLoc();
4901 ErrorRange = AtomicUnaryOp->getSourceRange();
4902 NoteLoc = AtomicUnaryOp->getOperatorLoc();
4903 NoteRange = SourceRange(NoteLoc, NoteLoc);
4905 } else if (!AtomicBody->isInstantiationDependent()) {
4906 ErrorFound = NotABinaryOrUnaryExpression;
4907 NoteLoc = ErrorLoc = AtomicBody->getExprLoc();
4908 NoteRange = ErrorRange = AtomicBody->getSourceRange();
4911 ErrorFound = NotAScalarType;
4912 NoteLoc = ErrorLoc = AtomicBody->getLocStart();
4913 NoteRange = ErrorRange = SourceRange(NoteLoc, NoteLoc);
4916 ErrorFound = NotAnExpression;
4917 NoteLoc = ErrorLoc = S->getLocStart();
4918 NoteRange = ErrorRange = SourceRange(NoteLoc, NoteLoc);
4920 if (ErrorFound != NoError && DiagId != 0 && NoteId != 0) {
4921 SemaRef.Diag(ErrorLoc, DiagId) << ErrorRange;
4922 SemaRef.Diag(NoteLoc, NoteId) << ErrorFound << NoteRange;
4924 } else if (SemaRef.CurContext->isDependentContext())
4925 E = X = UpdateExpr = nullptr;
4926 if (ErrorFound == NoError && E && X) {
4927 // Build an update expression of form 'OpaqueValueExpr(x) binop
4928 // OpaqueValueExpr(expr)' or 'OpaqueValueExpr(expr) binop
4929 // OpaqueValueExpr(x)' and then cast it to the type of the 'x' expression.
4930 auto *OVEX = new (SemaRef.getASTContext())
4931 OpaqueValueExpr(X->getExprLoc(), X->getType(), VK_RValue);
4932 auto *OVEExpr = new (SemaRef.getASTContext())
4933 OpaqueValueExpr(E->getExprLoc(), E->getType(), VK_RValue);
4935 SemaRef.CreateBuiltinBinOp(OpLoc, Op, IsXLHSInRHSPart ? OVEX : OVEExpr,
4936 IsXLHSInRHSPart ? OVEExpr : OVEX);
4937 if (Update.isInvalid())
4939 Update = SemaRef.PerformImplicitConversion(Update.get(), X->getType(),
4941 if (Update.isInvalid())
4943 UpdateExpr = Update.get();
4945 return ErrorFound != NoError;
4948 StmtResult Sema::ActOnOpenMPAtomicDirective(ArrayRef<OMPClause *> Clauses,
4950 SourceLocation StartLoc,
4951 SourceLocation EndLoc) {
4955 auto CS = cast<CapturedStmt>(AStmt);
4956 // 1.2.2 OpenMP Language Terminology
4957 // Structured block - An executable statement with a single entry at the
4958 // top and a single exit at the bottom.
4959 // The point of exit cannot be a branch out of the structured block.
4960 // longjmp() and throw() must not violate the entry/exit criteria.
4961 OpenMPClauseKind AtomicKind = OMPC_unknown;
4962 SourceLocation AtomicKindLoc;
4963 for (auto *C : Clauses) {
4964 if (C->getClauseKind() == OMPC_read || C->getClauseKind() == OMPC_write ||
4965 C->getClauseKind() == OMPC_update ||
4966 C->getClauseKind() == OMPC_capture) {
4967 if (AtomicKind != OMPC_unknown) {
4968 Diag(C->getLocStart(), diag::err_omp_atomic_several_clauses)
4969 << SourceRange(C->getLocStart(), C->getLocEnd());
4970 Diag(AtomicKindLoc, diag::note_omp_atomic_previous_clause)
4971 << getOpenMPClauseName(AtomicKind);
4973 AtomicKind = C->getClauseKind();
4974 AtomicKindLoc = C->getLocStart();
4979 auto Body = CS->getCapturedStmt();
4980 if (auto *EWC = dyn_cast<ExprWithCleanups>(Body))
4981 Body = EWC->getSubExpr();
4987 bool IsXLHSInRHSPart = false;
4988 bool IsPostfixUpdate = false;
4989 // OpenMP [2.12.6, atomic Construct]
4990 // In the next expressions:
4991 // * x and v (as applicable) are both l-value expressions with scalar type.
4992 // * During the execution of an atomic region, multiple syntactic
4993 // occurrences of x must designate the same storage location.
4994 // * Neither of v and expr (as applicable) may access the storage location
4996 // * Neither of x and expr (as applicable) may access the storage location
4998 // * expr is an expression with scalar type.
4999 // * binop is one of +, *, -, /, &, ^, |, <<, or >>.
5000 // * binop, binop=, ++, and -- are not overloaded operators.
5001 // * The expression x binop expr must be numerically equivalent to x binop
5002 // (expr). This requirement is satisfied if the operators in expr have
5003 // precedence greater than binop, or by using parentheses around expr or
5004 // subexpressions of expr.
5005 // * The expression expr binop x must be numerically equivalent to (expr)
5006 // binop x. This requirement is satisfied if the operators in expr have
5007 // precedence equal to or greater than binop, or by using parentheses around
5008 // expr or subexpressions of expr.
5009 // * For forms that allow multiple occurrences of x, the number of times
5010 // that x is evaluated is unspecified.
5011 if (AtomicKind == OMPC_read) {
5018 } ErrorFound = NoError;
5019 SourceLocation ErrorLoc, NoteLoc;
5020 SourceRange ErrorRange, NoteRange;
5021 // If clause is read:
5023 if (auto AtomicBody = dyn_cast<Expr>(Body)) {
5025 dyn_cast<BinaryOperator>(AtomicBody->IgnoreParenImpCasts());
5026 if (AtomicBinOp && AtomicBinOp->getOpcode() == BO_Assign) {
5027 X = AtomicBinOp->getRHS()->IgnoreParenImpCasts();
5028 V = AtomicBinOp->getLHS()->IgnoreParenImpCasts();
5029 if ((X->isInstantiationDependent() || X->getType()->isScalarType()) &&
5030 (V->isInstantiationDependent() || V->getType()->isScalarType())) {
5031 if (!X->isLValue() || !V->isLValue()) {
5032 auto NotLValueExpr = X->isLValue() ? V : X;
5033 ErrorFound = NotAnLValue;
5034 ErrorLoc = AtomicBinOp->getExprLoc();
5035 ErrorRange = AtomicBinOp->getSourceRange();
5036 NoteLoc = NotLValueExpr->getExprLoc();
5037 NoteRange = NotLValueExpr->getSourceRange();
5039 } else if (!X->isInstantiationDependent() ||
5040 !V->isInstantiationDependent()) {
5041 auto NotScalarExpr =
5042 (X->isInstantiationDependent() || X->getType()->isScalarType())
5045 ErrorFound = NotAScalarType;
5046 ErrorLoc = AtomicBinOp->getExprLoc();
5047 ErrorRange = AtomicBinOp->getSourceRange();
5048 NoteLoc = NotScalarExpr->getExprLoc();
5049 NoteRange = NotScalarExpr->getSourceRange();
5051 } else if (!AtomicBody->isInstantiationDependent()) {
5052 ErrorFound = NotAnAssignmentOp;
5053 ErrorLoc = AtomicBody->getExprLoc();
5054 ErrorRange = AtomicBody->getSourceRange();
5055 NoteLoc = AtomicBinOp ? AtomicBinOp->getOperatorLoc()
5056 : AtomicBody->getExprLoc();
5057 NoteRange = AtomicBinOp ? AtomicBinOp->getSourceRange()
5058 : AtomicBody->getSourceRange();
5061 ErrorFound = NotAnExpression;
5062 NoteLoc = ErrorLoc = Body->getLocStart();
5063 NoteRange = ErrorRange = SourceRange(NoteLoc, NoteLoc);
5065 if (ErrorFound != NoError) {
5066 Diag(ErrorLoc, diag::err_omp_atomic_read_not_expression_statement)
5068 Diag(NoteLoc, diag::note_omp_atomic_read_write) << ErrorFound
5071 } else if (CurContext->isDependentContext())
5073 } else if (AtomicKind == OMPC_write) {
5080 } ErrorFound = NoError;
5081 SourceLocation ErrorLoc, NoteLoc;
5082 SourceRange ErrorRange, NoteRange;
5083 // If clause is write:
5085 if (auto AtomicBody = dyn_cast<Expr>(Body)) {
5087 dyn_cast<BinaryOperator>(AtomicBody->IgnoreParenImpCasts());
5088 if (AtomicBinOp && AtomicBinOp->getOpcode() == BO_Assign) {
5089 X = AtomicBinOp->getLHS();
5090 E = AtomicBinOp->getRHS();
5091 if ((X->isInstantiationDependent() || X->getType()->isScalarType()) &&
5092 (E->isInstantiationDependent() || E->getType()->isScalarType())) {
5093 if (!X->isLValue()) {
5094 ErrorFound = NotAnLValue;
5095 ErrorLoc = AtomicBinOp->getExprLoc();
5096 ErrorRange = AtomicBinOp->getSourceRange();
5097 NoteLoc = X->getExprLoc();
5098 NoteRange = X->getSourceRange();
5100 } else if (!X->isInstantiationDependent() ||
5101 !E->isInstantiationDependent()) {
5102 auto NotScalarExpr =
5103 (X->isInstantiationDependent() || X->getType()->isScalarType())
5106 ErrorFound = NotAScalarType;
5107 ErrorLoc = AtomicBinOp->getExprLoc();
5108 ErrorRange = AtomicBinOp->getSourceRange();
5109 NoteLoc = NotScalarExpr->getExprLoc();
5110 NoteRange = NotScalarExpr->getSourceRange();
5112 } else if (!AtomicBody->isInstantiationDependent()) {
5113 ErrorFound = NotAnAssignmentOp;
5114 ErrorLoc = AtomicBody->getExprLoc();
5115 ErrorRange = AtomicBody->getSourceRange();
5116 NoteLoc = AtomicBinOp ? AtomicBinOp->getOperatorLoc()
5117 : AtomicBody->getExprLoc();
5118 NoteRange = AtomicBinOp ? AtomicBinOp->getSourceRange()
5119 : AtomicBody->getSourceRange();
5122 ErrorFound = NotAnExpression;
5123 NoteLoc = ErrorLoc = Body->getLocStart();
5124 NoteRange = ErrorRange = SourceRange(NoteLoc, NoteLoc);
5126 if (ErrorFound != NoError) {
5127 Diag(ErrorLoc, diag::err_omp_atomic_write_not_expression_statement)
5129 Diag(NoteLoc, diag::note_omp_atomic_read_write) << ErrorFound
5132 } else if (CurContext->isDependentContext())
5134 } else if (AtomicKind == OMPC_update || AtomicKind == OMPC_unknown) {
5135 // If clause is update:
5141 // x = x binop expr;
5142 // x = expr binop x;
5143 OpenMPAtomicUpdateChecker Checker(*this);
5144 if (Checker.checkStatement(
5145 Body, (AtomicKind == OMPC_update)
5146 ? diag::err_omp_atomic_update_not_expression_statement
5147 : diag::err_omp_atomic_not_expression_statement,
5148 diag::note_omp_atomic_update))
5150 if (!CurContext->isDependentContext()) {
5151 E = Checker.getExpr();
5153 UE = Checker.getUpdateExpr();
5154 IsXLHSInRHSPart = Checker.isXLHSInRHSPart();
5156 } else if (AtomicKind == OMPC_capture) {
5159 NotACompoundStatement,
5160 NotTwoSubstatements,
5161 NotASpecificExpression,
5163 } ErrorFound = NoError;
5164 SourceLocation ErrorLoc, NoteLoc;
5165 SourceRange ErrorRange, NoteRange;
5166 if (auto *AtomicBody = dyn_cast<Expr>(Body)) {
5167 // If clause is a capture:
5172 // v = x binop= expr;
5173 // v = x = x binop expr;
5174 // v = x = expr binop x;
5176 dyn_cast<BinaryOperator>(AtomicBody->IgnoreParenImpCasts());
5177 if (AtomicBinOp && AtomicBinOp->getOpcode() == BO_Assign) {
5178 V = AtomicBinOp->getLHS();
5179 Body = AtomicBinOp->getRHS()->IgnoreParenImpCasts();
5180 OpenMPAtomicUpdateChecker Checker(*this);
5181 if (Checker.checkStatement(
5182 Body, diag::err_omp_atomic_capture_not_expression_statement,
5183 diag::note_omp_atomic_update))
5185 E = Checker.getExpr();
5187 UE = Checker.getUpdateExpr();
5188 IsXLHSInRHSPart = Checker.isXLHSInRHSPart();
5189 IsPostfixUpdate = Checker.isPostfixUpdate();
5190 } else if (!AtomicBody->isInstantiationDependent()) {
5191 ErrorLoc = AtomicBody->getExprLoc();
5192 ErrorRange = AtomicBody->getSourceRange();
5193 NoteLoc = AtomicBinOp ? AtomicBinOp->getOperatorLoc()
5194 : AtomicBody->getExprLoc();
5195 NoteRange = AtomicBinOp ? AtomicBinOp->getSourceRange()
5196 : AtomicBody->getSourceRange();
5197 ErrorFound = NotAnAssignmentOp;
5199 if (ErrorFound != NoError) {
5200 Diag(ErrorLoc, diag::err_omp_atomic_capture_not_expression_statement)
5202 Diag(NoteLoc, diag::note_omp_atomic_capture) << ErrorFound << NoteRange;
5204 } else if (CurContext->isDependentContext()) {
5205 UE = V = E = X = nullptr;
5208 // If clause is a capture:
5209 // { v = x; x = expr; }
5214 // { v = x; x binop= expr; }
5215 // { v = x; x = x binop expr; }
5216 // { v = x; x = expr binop x; }
5221 // { x binop= expr; v = x; }
5222 // { x = x binop expr; v = x; }
5223 // { x = expr binop x; v = x; }
5224 if (auto *CS = dyn_cast<CompoundStmt>(Body)) {
5225 // Check that this is { expr1; expr2; }
5226 if (CS->size() == 2) {
5227 auto *First = CS->body_front();
5228 auto *Second = CS->body_back();
5229 if (auto *EWC = dyn_cast<ExprWithCleanups>(First))
5230 First = EWC->getSubExpr()->IgnoreParenImpCasts();
5231 if (auto *EWC = dyn_cast<ExprWithCleanups>(Second))
5232 Second = EWC->getSubExpr()->IgnoreParenImpCasts();
5233 // Need to find what subexpression is 'v' and what is 'x'.
5234 OpenMPAtomicUpdateChecker Checker(*this);
5235 bool IsUpdateExprFound = !Checker.checkStatement(Second);
5236 BinaryOperator *BinOp = nullptr;
5237 if (IsUpdateExprFound) {
5238 BinOp = dyn_cast<BinaryOperator>(First);
5239 IsUpdateExprFound = BinOp && BinOp->getOpcode() == BO_Assign;
5241 if (IsUpdateExprFound && !CurContext->isDependentContext()) {
5246 // { v = x; x binop= expr; }
5247 // { v = x; x = x binop expr; }
5248 // { v = x; x = expr binop x; }
5249 // Check that the first expression has form v = x.
5250 auto *PossibleX = BinOp->getRHS()->IgnoreParenImpCasts();
5251 llvm::FoldingSetNodeID XId, PossibleXId;
5252 Checker.getX()->Profile(XId, Context, /*Canonical=*/true);
5253 PossibleX->Profile(PossibleXId, Context, /*Canonical=*/true);
5254 IsUpdateExprFound = XId == PossibleXId;
5255 if (IsUpdateExprFound) {
5256 V = BinOp->getLHS();
5258 E = Checker.getExpr();
5259 UE = Checker.getUpdateExpr();
5260 IsXLHSInRHSPart = Checker.isXLHSInRHSPart();
5261 IsPostfixUpdate = true;
5264 if (!IsUpdateExprFound) {
5265 IsUpdateExprFound = !Checker.checkStatement(First);
5267 if (IsUpdateExprFound) {
5268 BinOp = dyn_cast<BinaryOperator>(Second);
5269 IsUpdateExprFound = BinOp && BinOp->getOpcode() == BO_Assign;
5271 if (IsUpdateExprFound && !CurContext->isDependentContext()) {
5276 // { x binop= expr; v = x; }
5277 // { x = x binop expr; v = x; }
5278 // { x = expr binop x; v = x; }
5279 // Check that the second expression has form v = x.
5280 auto *PossibleX = BinOp->getRHS()->IgnoreParenImpCasts();
5281 llvm::FoldingSetNodeID XId, PossibleXId;
5282 Checker.getX()->Profile(XId, Context, /*Canonical=*/true);
5283 PossibleX->Profile(PossibleXId, Context, /*Canonical=*/true);
5284 IsUpdateExprFound = XId == PossibleXId;
5285 if (IsUpdateExprFound) {
5286 V = BinOp->getLHS();
5288 E = Checker.getExpr();
5289 UE = Checker.getUpdateExpr();
5290 IsXLHSInRHSPart = Checker.isXLHSInRHSPart();
5291 IsPostfixUpdate = false;
5295 if (!IsUpdateExprFound) {
5296 // { v = x; x = expr; }
5297 auto *FirstExpr = dyn_cast<Expr>(First);
5298 auto *SecondExpr = dyn_cast<Expr>(Second);
5299 if (!FirstExpr || !SecondExpr ||
5300 !(FirstExpr->isInstantiationDependent() ||
5301 SecondExpr->isInstantiationDependent())) {
5302 auto *FirstBinOp = dyn_cast<BinaryOperator>(First);
5303 if (!FirstBinOp || FirstBinOp->getOpcode() != BO_Assign) {
5304 ErrorFound = NotAnAssignmentOp;
5305 NoteLoc = ErrorLoc = FirstBinOp ? FirstBinOp->getOperatorLoc()
5306 : First->getLocStart();
5307 NoteRange = ErrorRange = FirstBinOp
5308 ? FirstBinOp->getSourceRange()
5309 : SourceRange(ErrorLoc, ErrorLoc);
5311 auto *SecondBinOp = dyn_cast<BinaryOperator>(Second);
5312 if (!SecondBinOp || SecondBinOp->getOpcode() != BO_Assign) {
5313 ErrorFound = NotAnAssignmentOp;
5314 NoteLoc = ErrorLoc = SecondBinOp
5315 ? SecondBinOp->getOperatorLoc()
5316 : Second->getLocStart();
5317 NoteRange = ErrorRange =
5318 SecondBinOp ? SecondBinOp->getSourceRange()
5319 : SourceRange(ErrorLoc, ErrorLoc);
5321 auto *PossibleXRHSInFirst =
5322 FirstBinOp->getRHS()->IgnoreParenImpCasts();
5323 auto *PossibleXLHSInSecond =
5324 SecondBinOp->getLHS()->IgnoreParenImpCasts();
5325 llvm::FoldingSetNodeID X1Id, X2Id;
5326 PossibleXRHSInFirst->Profile(X1Id, Context,
5327 /*Canonical=*/true);
5328 PossibleXLHSInSecond->Profile(X2Id, Context,
5329 /*Canonical=*/true);
5330 IsUpdateExprFound = X1Id == X2Id;
5331 if (IsUpdateExprFound) {
5332 V = FirstBinOp->getLHS();
5333 X = SecondBinOp->getLHS();
5334 E = SecondBinOp->getRHS();
5336 IsXLHSInRHSPart = false;
5337 IsPostfixUpdate = true;
5339 ErrorFound = NotASpecificExpression;
5340 ErrorLoc = FirstBinOp->getExprLoc();
5341 ErrorRange = FirstBinOp->getSourceRange();
5342 NoteLoc = SecondBinOp->getLHS()->getExprLoc();
5343 NoteRange = SecondBinOp->getRHS()->getSourceRange();
5350 NoteLoc = ErrorLoc = Body->getLocStart();
5351 NoteRange = ErrorRange =
5352 SourceRange(Body->getLocStart(), Body->getLocStart());
5353 ErrorFound = NotTwoSubstatements;
5356 NoteLoc = ErrorLoc = Body->getLocStart();
5357 NoteRange = ErrorRange =
5358 SourceRange(Body->getLocStart(), Body->getLocStart());
5359 ErrorFound = NotACompoundStatement;
5361 if (ErrorFound != NoError) {
5362 Diag(ErrorLoc, diag::err_omp_atomic_capture_not_compound_statement)
5364 Diag(NoteLoc, diag::note_omp_atomic_capture) << ErrorFound << NoteRange;
5366 } else if (CurContext->isDependentContext()) {
5367 UE = V = E = X = nullptr;
5372 getCurFunction()->setHasBranchProtectedScope();
5374 return OMPAtomicDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt,
5375 X, V, E, UE, IsXLHSInRHSPart,
5379 StmtResult Sema::ActOnOpenMPTargetDirective(ArrayRef<OMPClause *> Clauses,
5381 SourceLocation StartLoc,
5382 SourceLocation EndLoc) {
5386 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
5387 // 1.2.2 OpenMP Language Terminology
5388 // Structured block - An executable statement with a single entry at the
5389 // top and a single exit at the bottom.
5390 // The point of exit cannot be a branch out of the structured block.
5391 // longjmp() and throw() must not violate the entry/exit criteria.
5392 CS->getCapturedDecl()->setNothrow();
5394 // OpenMP [2.16, Nesting of Regions]
5395 // If specified, a teams construct must be contained within a target
5396 // construct. That target construct must contain no statements or directives
5397 // outside of the teams construct.
5398 if (DSAStack->hasInnerTeamsRegion()) {
5399 auto S = AStmt->IgnoreContainers(/*IgnoreCaptured*/ true);
5400 bool OMPTeamsFound = true;
5401 if (auto *CS = dyn_cast<CompoundStmt>(S)) {
5402 auto I = CS->body_begin();
5403 while (I != CS->body_end()) {
5404 auto OED = dyn_cast<OMPExecutableDirective>(*I);
5405 if (!OED || !isOpenMPTeamsDirective(OED->getDirectiveKind())) {
5406 OMPTeamsFound = false;
5411 assert(I != CS->body_end() && "Not found statement");
5414 if (!OMPTeamsFound) {
5415 Diag(StartLoc, diag::err_omp_target_contains_not_only_teams);
5416 Diag(DSAStack->getInnerTeamsRegionLoc(),
5417 diag::note_omp_nested_teams_construct_here);
5418 Diag(S->getLocStart(), diag::note_omp_nested_statement_here)
5419 << isa<OMPExecutableDirective>(S);
5424 getCurFunction()->setHasBranchProtectedScope();
5426 return OMPTargetDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt);
5429 StmtResult Sema::ActOnOpenMPTargetDataDirective(ArrayRef<OMPClause *> Clauses,
5431 SourceLocation StartLoc,
5432 SourceLocation EndLoc) {
5436 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
5438 getCurFunction()->setHasBranchProtectedScope();
5440 return OMPTargetDataDirective::Create(Context, StartLoc, EndLoc, Clauses,
5444 StmtResult Sema::ActOnOpenMPTeamsDirective(ArrayRef<OMPClause *> Clauses,
5445 Stmt *AStmt, SourceLocation StartLoc,
5446 SourceLocation EndLoc) {
5450 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
5451 // 1.2.2 OpenMP Language Terminology
5452 // Structured block - An executable statement with a single entry at the
5453 // top and a single exit at the bottom.
5454 // The point of exit cannot be a branch out of the structured block.
5455 // longjmp() and throw() must not violate the entry/exit criteria.
5456 CS->getCapturedDecl()->setNothrow();
5458 getCurFunction()->setHasBranchProtectedScope();
5460 return OMPTeamsDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt);
5464 Sema::ActOnOpenMPCancellationPointDirective(SourceLocation StartLoc,
5465 SourceLocation EndLoc,
5466 OpenMPDirectiveKind CancelRegion) {
5467 if (CancelRegion != OMPD_parallel && CancelRegion != OMPD_for &&
5468 CancelRegion != OMPD_sections && CancelRegion != OMPD_taskgroup) {
5469 Diag(StartLoc, diag::err_omp_wrong_cancel_region)
5470 << getOpenMPDirectiveName(CancelRegion);
5473 if (DSAStack->isParentNowaitRegion()) {
5474 Diag(StartLoc, diag::err_omp_parent_cancel_region_nowait) << 0;
5477 if (DSAStack->isParentOrderedRegion()) {
5478 Diag(StartLoc, diag::err_omp_parent_cancel_region_ordered) << 0;
5481 return OMPCancellationPointDirective::Create(Context, StartLoc, EndLoc,
5485 StmtResult Sema::ActOnOpenMPCancelDirective(ArrayRef<OMPClause *> Clauses,
5486 SourceLocation StartLoc,
5487 SourceLocation EndLoc,
5488 OpenMPDirectiveKind CancelRegion) {
5489 if (CancelRegion != OMPD_parallel && CancelRegion != OMPD_for &&
5490 CancelRegion != OMPD_sections && CancelRegion != OMPD_taskgroup) {
5491 Diag(StartLoc, diag::err_omp_wrong_cancel_region)
5492 << getOpenMPDirectiveName(CancelRegion);
5495 if (DSAStack->isParentNowaitRegion()) {
5496 Diag(StartLoc, diag::err_omp_parent_cancel_region_nowait) << 1;
5499 if (DSAStack->isParentOrderedRegion()) {
5500 Diag(StartLoc, diag::err_omp_parent_cancel_region_ordered) << 1;
5503 DSAStack->setParentCancelRegion(/*Cancel=*/true);
5504 return OMPCancelDirective::Create(Context, StartLoc, EndLoc, Clauses,
5508 static bool checkGrainsizeNumTasksClauses(Sema &S,
5509 ArrayRef<OMPClause *> Clauses) {
5510 OMPClause *PrevClause = nullptr;
5511 bool ErrorFound = false;
5512 for (auto *C : Clauses) {
5513 if (C->getClauseKind() == OMPC_grainsize ||
5514 C->getClauseKind() == OMPC_num_tasks) {
5517 else if (PrevClause->getClauseKind() != C->getClauseKind()) {
5518 S.Diag(C->getLocStart(),
5519 diag::err_omp_grainsize_num_tasks_mutually_exclusive)
5520 << getOpenMPClauseName(C->getClauseKind())
5521 << getOpenMPClauseName(PrevClause->getClauseKind());
5522 S.Diag(PrevClause->getLocStart(),
5523 diag::note_omp_previous_grainsize_num_tasks)
5524 << getOpenMPClauseName(PrevClause->getClauseKind());
5532 StmtResult Sema::ActOnOpenMPTaskLoopDirective(
5533 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
5534 SourceLocation EndLoc,
5535 llvm::DenseMap<VarDecl *, Expr *> &VarsWithImplicitDSA) {
5539 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
5540 OMPLoopDirective::HelperExprs B;
5541 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
5542 // define the nested loops number.
5543 unsigned NestedLoopCount =
5544 CheckOpenMPLoop(OMPD_taskloop, getCollapseNumberExpr(Clauses),
5545 /*OrderedLoopCountExpr=*/nullptr, AStmt, *this, *DSAStack,
5546 VarsWithImplicitDSA, B);
5547 if (NestedLoopCount == 0)
5550 assert((CurContext->isDependentContext() || B.builtAll()) &&
5551 "omp for loop exprs were not built");
5553 // OpenMP, [2.9.2 taskloop Construct, Restrictions]
5554 // The grainsize clause and num_tasks clause are mutually exclusive and may
5555 // not appear on the same taskloop directive.
5556 if (checkGrainsizeNumTasksClauses(*this, Clauses))
5559 getCurFunction()->setHasBranchProtectedScope();
5560 return OMPTaskLoopDirective::Create(Context, StartLoc, EndLoc,
5561 NestedLoopCount, Clauses, AStmt, B);
5564 StmtResult Sema::ActOnOpenMPTaskLoopSimdDirective(
5565 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
5566 SourceLocation EndLoc,
5567 llvm::DenseMap<VarDecl *, Expr *> &VarsWithImplicitDSA) {
5571 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
5572 OMPLoopDirective::HelperExprs B;
5573 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
5574 // define the nested loops number.
5575 unsigned NestedLoopCount =
5576 CheckOpenMPLoop(OMPD_taskloop_simd, getCollapseNumberExpr(Clauses),
5577 /*OrderedLoopCountExpr=*/nullptr, AStmt, *this, *DSAStack,
5578 VarsWithImplicitDSA, B);
5579 if (NestedLoopCount == 0)
5582 assert((CurContext->isDependentContext() || B.builtAll()) &&
5583 "omp for loop exprs were not built");
5585 // OpenMP, [2.9.2 taskloop Construct, Restrictions]
5586 // The grainsize clause and num_tasks clause are mutually exclusive and may
5587 // not appear on the same taskloop directive.
5588 if (checkGrainsizeNumTasksClauses(*this, Clauses))
5591 getCurFunction()->setHasBranchProtectedScope();
5592 return OMPTaskLoopSimdDirective::Create(Context, StartLoc, EndLoc,
5593 NestedLoopCount, Clauses, AStmt, B);
5596 StmtResult Sema::ActOnOpenMPDistributeDirective(
5597 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
5598 SourceLocation EndLoc,
5599 llvm::DenseMap<VarDecl *, Expr *> &VarsWithImplicitDSA) {
5603 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
5604 OMPLoopDirective::HelperExprs B;
5605 // In presence of clause 'collapse' with number of loops, it will
5606 // define the nested loops number.
5607 unsigned NestedLoopCount =
5608 CheckOpenMPLoop(OMPD_distribute, getCollapseNumberExpr(Clauses),
5609 nullptr /*ordered not a clause on distribute*/, AStmt,
5610 *this, *DSAStack, VarsWithImplicitDSA, B);
5611 if (NestedLoopCount == 0)
5614 assert((CurContext->isDependentContext() || B.builtAll()) &&
5615 "omp for loop exprs were not built");
5617 getCurFunction()->setHasBranchProtectedScope();
5618 return OMPDistributeDirective::Create(Context, StartLoc, EndLoc,
5619 NestedLoopCount, Clauses, AStmt, B);
5622 OMPClause *Sema::ActOnOpenMPSingleExprClause(OpenMPClauseKind Kind, Expr *Expr,
5623 SourceLocation StartLoc,
5624 SourceLocation LParenLoc,
5625 SourceLocation EndLoc) {
5626 OMPClause *Res = nullptr;
5629 Res = ActOnOpenMPFinalClause(Expr, StartLoc, LParenLoc, EndLoc);
5631 case OMPC_num_threads:
5632 Res = ActOnOpenMPNumThreadsClause(Expr, StartLoc, LParenLoc, EndLoc);
5635 Res = ActOnOpenMPSafelenClause(Expr, StartLoc, LParenLoc, EndLoc);
5638 Res = ActOnOpenMPSimdlenClause(Expr, StartLoc, LParenLoc, EndLoc);
5641 Res = ActOnOpenMPCollapseClause(Expr, StartLoc, LParenLoc, EndLoc);
5644 Res = ActOnOpenMPOrderedClause(StartLoc, EndLoc, LParenLoc, Expr);
5647 Res = ActOnOpenMPDeviceClause(Expr, StartLoc, LParenLoc, EndLoc);
5649 case OMPC_num_teams:
5650 Res = ActOnOpenMPNumTeamsClause(Expr, StartLoc, LParenLoc, EndLoc);
5652 case OMPC_thread_limit:
5653 Res = ActOnOpenMPThreadLimitClause(Expr, StartLoc, LParenLoc, EndLoc);
5656 Res = ActOnOpenMPPriorityClause(Expr, StartLoc, LParenLoc, EndLoc);
5658 case OMPC_grainsize:
5659 Res = ActOnOpenMPGrainsizeClause(Expr, StartLoc, LParenLoc, EndLoc);
5661 case OMPC_num_tasks:
5662 Res = ActOnOpenMPNumTasksClause(Expr, StartLoc, LParenLoc, EndLoc);
5665 Res = ActOnOpenMPHintClause(Expr, StartLoc, LParenLoc, EndLoc);
5669 case OMPC_proc_bind:
5672 case OMPC_firstprivate:
5673 case OMPC_lastprivate:
5675 case OMPC_reduction:
5679 case OMPC_copyprivate:
5682 case OMPC_mergeable:
5683 case OMPC_threadprivate:
5696 llvm_unreachable("Clause is not allowed.");
5701 OMPClause *Sema::ActOnOpenMPIfClause(OpenMPDirectiveKind NameModifier,
5702 Expr *Condition, SourceLocation StartLoc,
5703 SourceLocation LParenLoc,
5704 SourceLocation NameModifierLoc,
5705 SourceLocation ColonLoc,
5706 SourceLocation EndLoc) {
5707 Expr *ValExpr = Condition;
5708 if (!Condition->isValueDependent() && !Condition->isTypeDependent() &&
5709 !Condition->isInstantiationDependent() &&
5710 !Condition->containsUnexpandedParameterPack()) {
5711 ExprResult Val = ActOnBooleanCondition(DSAStack->getCurScope(),
5712 Condition->getExprLoc(), Condition);
5713 if (Val.isInvalid())
5716 ValExpr = Val.get();
5719 return new (Context) OMPIfClause(NameModifier, ValExpr, StartLoc, LParenLoc,
5720 NameModifierLoc, ColonLoc, EndLoc);
5723 OMPClause *Sema::ActOnOpenMPFinalClause(Expr *Condition,
5724 SourceLocation StartLoc,
5725 SourceLocation LParenLoc,
5726 SourceLocation EndLoc) {
5727 Expr *ValExpr = Condition;
5728 if (!Condition->isValueDependent() && !Condition->isTypeDependent() &&
5729 !Condition->isInstantiationDependent() &&
5730 !Condition->containsUnexpandedParameterPack()) {
5731 ExprResult Val = ActOnBooleanCondition(DSAStack->getCurScope(),
5732 Condition->getExprLoc(), Condition);
5733 if (Val.isInvalid())
5736 ValExpr = Val.get();
5739 return new (Context) OMPFinalClause(ValExpr, StartLoc, LParenLoc, EndLoc);
5741 ExprResult Sema::PerformOpenMPImplicitIntegerConversion(SourceLocation Loc,
5746 class IntConvertDiagnoser : public ICEConvertDiagnoser {
5748 IntConvertDiagnoser()
5749 : ICEConvertDiagnoser(/*AllowScopedEnumerations*/ false, false, true) {}
5750 SemaDiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc,
5751 QualType T) override {
5752 return S.Diag(Loc, diag::err_omp_not_integral) << T;
5754 SemaDiagnosticBuilder diagnoseIncomplete(Sema &S, SourceLocation Loc,
5755 QualType T) override {
5756 return S.Diag(Loc, diag::err_omp_incomplete_type) << T;
5758 SemaDiagnosticBuilder diagnoseExplicitConv(Sema &S, SourceLocation Loc,
5760 QualType ConvTy) override {
5761 return S.Diag(Loc, diag::err_omp_explicit_conversion) << T << ConvTy;
5763 SemaDiagnosticBuilder noteExplicitConv(Sema &S, CXXConversionDecl *Conv,
5764 QualType ConvTy) override {
5765 return S.Diag(Conv->getLocation(), diag::note_omp_conversion_here)
5766 << ConvTy->isEnumeralType() << ConvTy;
5768 SemaDiagnosticBuilder diagnoseAmbiguous(Sema &S, SourceLocation Loc,
5769 QualType T) override {
5770 return S.Diag(Loc, diag::err_omp_ambiguous_conversion) << T;
5772 SemaDiagnosticBuilder noteAmbiguous(Sema &S, CXXConversionDecl *Conv,
5773 QualType ConvTy) override {
5774 return S.Diag(Conv->getLocation(), diag::note_omp_conversion_here)
5775 << ConvTy->isEnumeralType() << ConvTy;
5777 SemaDiagnosticBuilder diagnoseConversion(Sema &, SourceLocation, QualType,
5778 QualType) override {
5779 llvm_unreachable("conversion functions are permitted");
5782 return PerformContextualImplicitConversion(Loc, Op, ConvertDiagnoser);
5785 static bool IsNonNegativeIntegerValue(Expr *&ValExpr, Sema &SemaRef,
5786 OpenMPClauseKind CKind,
5787 bool StrictlyPositive) {
5788 if (!ValExpr->isTypeDependent() && !ValExpr->isValueDependent() &&
5789 !ValExpr->isInstantiationDependent()) {
5790 SourceLocation Loc = ValExpr->getExprLoc();
5792 SemaRef.PerformOpenMPImplicitIntegerConversion(Loc, ValExpr);
5793 if (Value.isInvalid())
5796 ValExpr = Value.get();
5797 // The expression must evaluate to a non-negative integer value.
5798 llvm::APSInt Result;
5799 if (ValExpr->isIntegerConstantExpr(Result, SemaRef.Context) &&
5800 Result.isSigned() &&
5801 !((!StrictlyPositive && Result.isNonNegative()) ||
5802 (StrictlyPositive && Result.isStrictlyPositive()))) {
5803 SemaRef.Diag(Loc, diag::err_omp_negative_expression_in_clause)
5804 << getOpenMPClauseName(CKind) << (StrictlyPositive ? 1 : 0)
5805 << ValExpr->getSourceRange();
5812 OMPClause *Sema::ActOnOpenMPNumThreadsClause(Expr *NumThreads,
5813 SourceLocation StartLoc,
5814 SourceLocation LParenLoc,
5815 SourceLocation EndLoc) {
5816 Expr *ValExpr = NumThreads;
5818 // OpenMP [2.5, Restrictions]
5819 // The num_threads expression must evaluate to a positive integer value.
5820 if (!IsNonNegativeIntegerValue(ValExpr, *this, OMPC_num_threads,
5821 /*StrictlyPositive=*/true))
5824 return new (Context)
5825 OMPNumThreadsClause(ValExpr, StartLoc, LParenLoc, EndLoc);
5828 ExprResult Sema::VerifyPositiveIntegerConstantInClause(Expr *E,
5829 OpenMPClauseKind CKind,
5830 bool StrictlyPositive) {
5833 if (E->isValueDependent() || E->isTypeDependent() ||
5834 E->isInstantiationDependent() || E->containsUnexpandedParameterPack())
5836 llvm::APSInt Result;
5837 ExprResult ICE = VerifyIntegerConstantExpression(E, &Result);
5838 if (ICE.isInvalid())
5840 if ((StrictlyPositive && !Result.isStrictlyPositive()) ||
5841 (!StrictlyPositive && !Result.isNonNegative())) {
5842 Diag(E->getExprLoc(), diag::err_omp_negative_expression_in_clause)
5843 << getOpenMPClauseName(CKind) << (StrictlyPositive ? 1 : 0)
5844 << E->getSourceRange();
5847 if (CKind == OMPC_aligned && !Result.isPowerOf2()) {
5848 Diag(E->getExprLoc(), diag::warn_omp_alignment_not_power_of_two)
5849 << E->getSourceRange();
5852 if (CKind == OMPC_collapse && DSAStack->getAssociatedLoops() == 1)
5853 DSAStack->setAssociatedLoops(Result.getExtValue());
5854 else if (CKind == OMPC_ordered)
5855 DSAStack->setAssociatedLoops(Result.getExtValue());
5859 OMPClause *Sema::ActOnOpenMPSafelenClause(Expr *Len, SourceLocation StartLoc,
5860 SourceLocation LParenLoc,
5861 SourceLocation EndLoc) {
5862 // OpenMP [2.8.1, simd construct, Description]
5863 // The parameter of the safelen clause must be a constant
5864 // positive integer expression.
5865 ExprResult Safelen = VerifyPositiveIntegerConstantInClause(Len, OMPC_safelen);
5866 if (Safelen.isInvalid())
5868 return new (Context)
5869 OMPSafelenClause(Safelen.get(), StartLoc, LParenLoc, EndLoc);
5872 OMPClause *Sema::ActOnOpenMPSimdlenClause(Expr *Len, SourceLocation StartLoc,
5873 SourceLocation LParenLoc,
5874 SourceLocation EndLoc) {
5875 // OpenMP [2.8.1, simd construct, Description]
5876 // The parameter of the simdlen clause must be a constant
5877 // positive integer expression.
5878 ExprResult Simdlen = VerifyPositiveIntegerConstantInClause(Len, OMPC_simdlen);
5879 if (Simdlen.isInvalid())
5881 return new (Context)
5882 OMPSimdlenClause(Simdlen.get(), StartLoc, LParenLoc, EndLoc);
5885 OMPClause *Sema::ActOnOpenMPCollapseClause(Expr *NumForLoops,
5886 SourceLocation StartLoc,
5887 SourceLocation LParenLoc,
5888 SourceLocation EndLoc) {
5889 // OpenMP [2.7.1, loop construct, Description]
5890 // OpenMP [2.8.1, simd construct, Description]
5891 // OpenMP [2.9.6, distribute construct, Description]
5892 // The parameter of the collapse clause must be a constant
5893 // positive integer expression.
5894 ExprResult NumForLoopsResult =
5895 VerifyPositiveIntegerConstantInClause(NumForLoops, OMPC_collapse);
5896 if (NumForLoopsResult.isInvalid())
5898 return new (Context)
5899 OMPCollapseClause(NumForLoopsResult.get(), StartLoc, LParenLoc, EndLoc);
5902 OMPClause *Sema::ActOnOpenMPOrderedClause(SourceLocation StartLoc,
5903 SourceLocation EndLoc,
5904 SourceLocation LParenLoc,
5905 Expr *NumForLoops) {
5906 // OpenMP [2.7.1, loop construct, Description]
5907 // OpenMP [2.8.1, simd construct, Description]
5908 // OpenMP [2.9.6, distribute construct, Description]
5909 // The parameter of the ordered clause must be a constant
5910 // positive integer expression if any.
5911 if (NumForLoops && LParenLoc.isValid()) {
5912 ExprResult NumForLoopsResult =
5913 VerifyPositiveIntegerConstantInClause(NumForLoops, OMPC_ordered);
5914 if (NumForLoopsResult.isInvalid())
5916 NumForLoops = NumForLoopsResult.get();
5918 NumForLoops = nullptr;
5919 DSAStack->setOrderedRegion(/*IsOrdered=*/true, NumForLoops);
5920 return new (Context)
5921 OMPOrderedClause(NumForLoops, StartLoc, LParenLoc, EndLoc);
5924 OMPClause *Sema::ActOnOpenMPSimpleClause(
5925 OpenMPClauseKind Kind, unsigned Argument, SourceLocation ArgumentLoc,
5926 SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc) {
5927 OMPClause *Res = nullptr;
5931 ActOnOpenMPDefaultClause(static_cast<OpenMPDefaultClauseKind>(Argument),
5932 ArgumentLoc, StartLoc, LParenLoc, EndLoc);
5934 case OMPC_proc_bind:
5935 Res = ActOnOpenMPProcBindClause(
5936 static_cast<OpenMPProcBindClauseKind>(Argument), ArgumentLoc, StartLoc,
5941 case OMPC_num_threads:
5947 case OMPC_firstprivate:
5948 case OMPC_lastprivate:
5950 case OMPC_reduction:
5954 case OMPC_copyprivate:
5958 case OMPC_mergeable:
5959 case OMPC_threadprivate:
5971 case OMPC_num_teams:
5972 case OMPC_thread_limit:
5974 case OMPC_grainsize:
5976 case OMPC_num_tasks:
5979 llvm_unreachable("Clause is not allowed.");
5985 getListOfPossibleValues(OpenMPClauseKind K, unsigned First, unsigned Last,
5986 ArrayRef<unsigned> Exclude = llvm::None) {
5988 unsigned Bound = Last >= 2 ? Last - 2 : 0;
5989 unsigned Skipped = Exclude.size();
5990 auto S = Exclude.begin(), E = Exclude.end();
5991 for (unsigned i = First; i < Last; ++i) {
5992 if (std::find(S, E, i) != E) {
5997 Values += getOpenMPSimpleClauseTypeName(K, i);
5999 if (i == Bound - Skipped)
6001 else if (i != Bound + 1 - Skipped)
6007 OMPClause *Sema::ActOnOpenMPDefaultClause(OpenMPDefaultClauseKind Kind,
6008 SourceLocation KindKwLoc,
6009 SourceLocation StartLoc,
6010 SourceLocation LParenLoc,
6011 SourceLocation EndLoc) {
6012 if (Kind == OMPC_DEFAULT_unknown) {
6013 static_assert(OMPC_DEFAULT_unknown > 0,
6014 "OMPC_DEFAULT_unknown not greater than 0");
6015 Diag(KindKwLoc, diag::err_omp_unexpected_clause_value)
6016 << getListOfPossibleValues(OMPC_default, /*First=*/0,
6017 /*Last=*/OMPC_DEFAULT_unknown)
6018 << getOpenMPClauseName(OMPC_default);
6022 case OMPC_DEFAULT_none:
6023 DSAStack->setDefaultDSANone(KindKwLoc);
6025 case OMPC_DEFAULT_shared:
6026 DSAStack->setDefaultDSAShared(KindKwLoc);
6028 case OMPC_DEFAULT_unknown:
6029 llvm_unreachable("Clause kind is not allowed.");
6032 return new (Context)
6033 OMPDefaultClause(Kind, KindKwLoc, StartLoc, LParenLoc, EndLoc);
6036 OMPClause *Sema::ActOnOpenMPProcBindClause(OpenMPProcBindClauseKind Kind,
6037 SourceLocation KindKwLoc,
6038 SourceLocation StartLoc,
6039 SourceLocation LParenLoc,
6040 SourceLocation EndLoc) {
6041 if (Kind == OMPC_PROC_BIND_unknown) {
6042 Diag(KindKwLoc, diag::err_omp_unexpected_clause_value)
6043 << getListOfPossibleValues(OMPC_proc_bind, /*First=*/0,
6044 /*Last=*/OMPC_PROC_BIND_unknown)
6045 << getOpenMPClauseName(OMPC_proc_bind);
6048 return new (Context)
6049 OMPProcBindClause(Kind, KindKwLoc, StartLoc, LParenLoc, EndLoc);
6052 OMPClause *Sema::ActOnOpenMPSingleExprWithArgClause(
6053 OpenMPClauseKind Kind, ArrayRef<unsigned> Argument, Expr *Expr,
6054 SourceLocation StartLoc, SourceLocation LParenLoc,
6055 ArrayRef<SourceLocation> ArgumentLoc, SourceLocation DelimLoc,
6056 SourceLocation EndLoc) {
6057 OMPClause *Res = nullptr;
6060 enum { Modifier1, Modifier2, ScheduleKind, NumberOfElements };
6061 assert(Argument.size() == NumberOfElements &&
6062 ArgumentLoc.size() == NumberOfElements);
6063 Res = ActOnOpenMPScheduleClause(
6064 static_cast<OpenMPScheduleClauseModifier>(Argument[Modifier1]),
6065 static_cast<OpenMPScheduleClauseModifier>(Argument[Modifier2]),
6066 static_cast<OpenMPScheduleClauseKind>(Argument[ScheduleKind]), Expr,
6067 StartLoc, LParenLoc, ArgumentLoc[Modifier1], ArgumentLoc[Modifier2],
6068 ArgumentLoc[ScheduleKind], DelimLoc, EndLoc);
6071 assert(Argument.size() == 1 && ArgumentLoc.size() == 1);
6072 Res = ActOnOpenMPIfClause(static_cast<OpenMPDirectiveKind>(Argument.back()),
6073 Expr, StartLoc, LParenLoc, ArgumentLoc.back(),
6077 case OMPC_num_threads:
6082 case OMPC_proc_bind:
6084 case OMPC_firstprivate:
6085 case OMPC_lastprivate:
6087 case OMPC_reduction:
6091 case OMPC_copyprivate:
6095 case OMPC_mergeable:
6096 case OMPC_threadprivate:
6108 case OMPC_num_teams:
6109 case OMPC_thread_limit:
6111 case OMPC_grainsize:
6113 case OMPC_num_tasks:
6116 llvm_unreachable("Clause is not allowed.");
6121 static bool checkScheduleModifiers(Sema &S, OpenMPScheduleClauseModifier M1,
6122 OpenMPScheduleClauseModifier M2,
6123 SourceLocation M1Loc, SourceLocation M2Loc) {
6124 if (M1 == OMPC_SCHEDULE_MODIFIER_unknown && M1Loc.isValid()) {
6125 SmallVector<unsigned, 2> Excluded;
6126 if (M2 != OMPC_SCHEDULE_MODIFIER_unknown)
6127 Excluded.push_back(M2);
6128 if (M2 == OMPC_SCHEDULE_MODIFIER_nonmonotonic)
6129 Excluded.push_back(OMPC_SCHEDULE_MODIFIER_monotonic);
6130 if (M2 == OMPC_SCHEDULE_MODIFIER_monotonic)
6131 Excluded.push_back(OMPC_SCHEDULE_MODIFIER_nonmonotonic);
6132 S.Diag(M1Loc, diag::err_omp_unexpected_clause_value)
6133 << getListOfPossibleValues(OMPC_schedule,
6134 /*First=*/OMPC_SCHEDULE_MODIFIER_unknown + 1,
6135 /*Last=*/OMPC_SCHEDULE_MODIFIER_last,
6137 << getOpenMPClauseName(OMPC_schedule);
6143 OMPClause *Sema::ActOnOpenMPScheduleClause(
6144 OpenMPScheduleClauseModifier M1, OpenMPScheduleClauseModifier M2,
6145 OpenMPScheduleClauseKind Kind, Expr *ChunkSize, SourceLocation StartLoc,
6146 SourceLocation LParenLoc, SourceLocation M1Loc, SourceLocation M2Loc,
6147 SourceLocation KindLoc, SourceLocation CommaLoc, SourceLocation EndLoc) {
6148 if (checkScheduleModifiers(*this, M1, M2, M1Loc, M2Loc) ||
6149 checkScheduleModifiers(*this, M2, M1, M2Loc, M1Loc))
6151 // OpenMP, 2.7.1, Loop Construct, Restrictions
6152 // Either the monotonic modifier or the nonmonotonic modifier can be specified
6154 if ((M1 == M2 && M1 != OMPC_SCHEDULE_MODIFIER_unknown) ||
6155 (M1 == OMPC_SCHEDULE_MODIFIER_monotonic &&
6156 M2 == OMPC_SCHEDULE_MODIFIER_nonmonotonic) ||
6157 (M1 == OMPC_SCHEDULE_MODIFIER_nonmonotonic &&
6158 M2 == OMPC_SCHEDULE_MODIFIER_monotonic)) {
6159 Diag(M2Loc, diag::err_omp_unexpected_schedule_modifier)
6160 << getOpenMPSimpleClauseTypeName(OMPC_schedule, M2)
6161 << getOpenMPSimpleClauseTypeName(OMPC_schedule, M1);
6164 if (Kind == OMPC_SCHEDULE_unknown) {
6166 if (M1Loc.isInvalid() && M2Loc.isInvalid()) {
6167 unsigned Exclude[] = {OMPC_SCHEDULE_unknown};
6168 Values = getListOfPossibleValues(OMPC_schedule, /*First=*/0,
6169 /*Last=*/OMPC_SCHEDULE_MODIFIER_last,
6172 Values = getListOfPossibleValues(OMPC_schedule, /*First=*/0,
6173 /*Last=*/OMPC_SCHEDULE_unknown);
6175 Diag(KindLoc, diag::err_omp_unexpected_clause_value)
6176 << Values << getOpenMPClauseName(OMPC_schedule);
6179 // OpenMP, 2.7.1, Loop Construct, Restrictions
6180 // The nonmonotonic modifier can only be specified with schedule(dynamic) or
6181 // schedule(guided).
6182 if ((M1 == OMPC_SCHEDULE_MODIFIER_nonmonotonic ||
6183 M2 == OMPC_SCHEDULE_MODIFIER_nonmonotonic) &&
6184 Kind != OMPC_SCHEDULE_dynamic && Kind != OMPC_SCHEDULE_guided) {
6185 Diag(M1 == OMPC_SCHEDULE_MODIFIER_nonmonotonic ? M1Loc : M2Loc,
6186 diag::err_omp_schedule_nonmonotonic_static);
6189 Expr *ValExpr = ChunkSize;
6190 Expr *HelperValExpr = nullptr;
6192 if (!ChunkSize->isValueDependent() && !ChunkSize->isTypeDependent() &&
6193 !ChunkSize->isInstantiationDependent() &&
6194 !ChunkSize->containsUnexpandedParameterPack()) {
6195 SourceLocation ChunkSizeLoc = ChunkSize->getLocStart();
6197 PerformOpenMPImplicitIntegerConversion(ChunkSizeLoc, ChunkSize);
6198 if (Val.isInvalid())
6201 ValExpr = Val.get();
6203 // OpenMP [2.7.1, Restrictions]
6204 // chunk_size must be a loop invariant integer expression with a positive
6206 llvm::APSInt Result;
6207 if (ValExpr->isIntegerConstantExpr(Result, Context)) {
6208 if (Result.isSigned() && !Result.isStrictlyPositive()) {
6209 Diag(ChunkSizeLoc, diag::err_omp_negative_expression_in_clause)
6210 << "schedule" << 1 << ChunkSize->getSourceRange();
6213 } else if (isParallelOrTaskRegion(DSAStack->getCurrentDirective())) {
6214 auto *ImpVar = buildVarDecl(*this, ChunkSize->getExprLoc(),
6215 ChunkSize->getType(), ".chunk.");
6216 auto *ImpVarRef = buildDeclRefExpr(*this, ImpVar, ChunkSize->getType(),
6217 ChunkSize->getExprLoc(),
6218 /*RefersToCapture=*/true);
6219 HelperValExpr = ImpVarRef;
6224 return new (Context)
6225 OMPScheduleClause(StartLoc, LParenLoc, KindLoc, CommaLoc, EndLoc, Kind,
6226 ValExpr, HelperValExpr, M1, M1Loc, M2, M2Loc);
6229 OMPClause *Sema::ActOnOpenMPClause(OpenMPClauseKind Kind,
6230 SourceLocation StartLoc,
6231 SourceLocation EndLoc) {
6232 OMPClause *Res = nullptr;
6235 Res = ActOnOpenMPOrderedClause(StartLoc, EndLoc);
6238 Res = ActOnOpenMPNowaitClause(StartLoc, EndLoc);
6241 Res = ActOnOpenMPUntiedClause(StartLoc, EndLoc);
6243 case OMPC_mergeable:
6244 Res = ActOnOpenMPMergeableClause(StartLoc, EndLoc);
6247 Res = ActOnOpenMPReadClause(StartLoc, EndLoc);
6250 Res = ActOnOpenMPWriteClause(StartLoc, EndLoc);
6253 Res = ActOnOpenMPUpdateClause(StartLoc, EndLoc);
6256 Res = ActOnOpenMPCaptureClause(StartLoc, EndLoc);
6259 Res = ActOnOpenMPSeqCstClause(StartLoc, EndLoc);
6262 Res = ActOnOpenMPThreadsClause(StartLoc, EndLoc);
6265 Res = ActOnOpenMPSIMDClause(StartLoc, EndLoc);
6268 Res = ActOnOpenMPNogroupClause(StartLoc, EndLoc);
6272 case OMPC_num_threads:
6278 case OMPC_firstprivate:
6279 case OMPC_lastprivate:
6281 case OMPC_reduction:
6285 case OMPC_copyprivate:
6287 case OMPC_proc_bind:
6288 case OMPC_threadprivate:
6293 case OMPC_num_teams:
6294 case OMPC_thread_limit:
6296 case OMPC_grainsize:
6297 case OMPC_num_tasks:
6300 llvm_unreachable("Clause is not allowed.");
6305 OMPClause *Sema::ActOnOpenMPNowaitClause(SourceLocation StartLoc,
6306 SourceLocation EndLoc) {
6307 DSAStack->setNowaitRegion();
6308 return new (Context) OMPNowaitClause(StartLoc, EndLoc);
6311 OMPClause *Sema::ActOnOpenMPUntiedClause(SourceLocation StartLoc,
6312 SourceLocation EndLoc) {
6313 return new (Context) OMPUntiedClause(StartLoc, EndLoc);
6316 OMPClause *Sema::ActOnOpenMPMergeableClause(SourceLocation StartLoc,
6317 SourceLocation EndLoc) {
6318 return new (Context) OMPMergeableClause(StartLoc, EndLoc);
6321 OMPClause *Sema::ActOnOpenMPReadClause(SourceLocation StartLoc,
6322 SourceLocation EndLoc) {
6323 return new (Context) OMPReadClause(StartLoc, EndLoc);
6326 OMPClause *Sema::ActOnOpenMPWriteClause(SourceLocation StartLoc,
6327 SourceLocation EndLoc) {
6328 return new (Context) OMPWriteClause(StartLoc, EndLoc);
6331 OMPClause *Sema::ActOnOpenMPUpdateClause(SourceLocation StartLoc,
6332 SourceLocation EndLoc) {
6333 return new (Context) OMPUpdateClause(StartLoc, EndLoc);
6336 OMPClause *Sema::ActOnOpenMPCaptureClause(SourceLocation StartLoc,
6337 SourceLocation EndLoc) {
6338 return new (Context) OMPCaptureClause(StartLoc, EndLoc);
6341 OMPClause *Sema::ActOnOpenMPSeqCstClause(SourceLocation StartLoc,
6342 SourceLocation EndLoc) {
6343 return new (Context) OMPSeqCstClause(StartLoc, EndLoc);
6346 OMPClause *Sema::ActOnOpenMPThreadsClause(SourceLocation StartLoc,
6347 SourceLocation EndLoc) {
6348 return new (Context) OMPThreadsClause(StartLoc, EndLoc);
6351 OMPClause *Sema::ActOnOpenMPSIMDClause(SourceLocation StartLoc,
6352 SourceLocation EndLoc) {
6353 return new (Context) OMPSIMDClause(StartLoc, EndLoc);
6356 OMPClause *Sema::ActOnOpenMPNogroupClause(SourceLocation StartLoc,
6357 SourceLocation EndLoc) {
6358 return new (Context) OMPNogroupClause(StartLoc, EndLoc);
6361 OMPClause *Sema::ActOnOpenMPVarListClause(
6362 OpenMPClauseKind Kind, ArrayRef<Expr *> VarList, Expr *TailExpr,
6363 SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation ColonLoc,
6364 SourceLocation EndLoc, CXXScopeSpec &ReductionIdScopeSpec,
6365 const DeclarationNameInfo &ReductionId, OpenMPDependClauseKind DepKind,
6366 OpenMPLinearClauseKind LinKind, OpenMPMapClauseKind MapTypeModifier,
6367 OpenMPMapClauseKind MapType, SourceLocation DepLinMapLoc) {
6368 OMPClause *Res = nullptr;
6371 Res = ActOnOpenMPPrivateClause(VarList, StartLoc, LParenLoc, EndLoc);
6373 case OMPC_firstprivate:
6374 Res = ActOnOpenMPFirstprivateClause(VarList, StartLoc, LParenLoc, EndLoc);
6376 case OMPC_lastprivate:
6377 Res = ActOnOpenMPLastprivateClause(VarList, StartLoc, LParenLoc, EndLoc);
6380 Res = ActOnOpenMPSharedClause(VarList, StartLoc, LParenLoc, EndLoc);
6382 case OMPC_reduction:
6383 Res = ActOnOpenMPReductionClause(VarList, StartLoc, LParenLoc, ColonLoc,
6384 EndLoc, ReductionIdScopeSpec, ReductionId);
6387 Res = ActOnOpenMPLinearClause(VarList, TailExpr, StartLoc, LParenLoc,
6388 LinKind, DepLinMapLoc, ColonLoc, EndLoc);
6391 Res = ActOnOpenMPAlignedClause(VarList, TailExpr, StartLoc, LParenLoc,
6395 Res = ActOnOpenMPCopyinClause(VarList, StartLoc, LParenLoc, EndLoc);
6397 case OMPC_copyprivate:
6398 Res = ActOnOpenMPCopyprivateClause(VarList, StartLoc, LParenLoc, EndLoc);
6401 Res = ActOnOpenMPFlushClause(VarList, StartLoc, LParenLoc, EndLoc);
6404 Res = ActOnOpenMPDependClause(DepKind, DepLinMapLoc, ColonLoc, VarList,
6405 StartLoc, LParenLoc, EndLoc);
6408 Res = ActOnOpenMPMapClause(MapTypeModifier, MapType, DepLinMapLoc, ColonLoc,
6409 VarList, StartLoc, LParenLoc, EndLoc);
6413 case OMPC_num_threads:
6418 case OMPC_proc_bind:
6423 case OMPC_mergeable:
6424 case OMPC_threadprivate:
6433 case OMPC_num_teams:
6434 case OMPC_thread_limit:
6436 case OMPC_grainsize:
6438 case OMPC_num_tasks:
6441 llvm_unreachable("Clause is not allowed.");
6446 OMPClause *Sema::ActOnOpenMPPrivateClause(ArrayRef<Expr *> VarList,
6447 SourceLocation StartLoc,
6448 SourceLocation LParenLoc,
6449 SourceLocation EndLoc) {
6450 SmallVector<Expr *, 8> Vars;
6451 SmallVector<Expr *, 8> PrivateCopies;
6452 for (auto &RefExpr : VarList) {
6453 assert(RefExpr && "NULL expr in OpenMP private clause.");
6454 if (isa<DependentScopeDeclRefExpr>(RefExpr)) {
6455 // It will be analyzed later.
6456 Vars.push_back(RefExpr);
6457 PrivateCopies.push_back(nullptr);
6461 SourceLocation ELoc = RefExpr->getExprLoc();
6462 // OpenMP [2.1, C/C++]
6463 // A list item is a variable name.
6464 // OpenMP [2.9.3.3, Restrictions, p.1]
6465 // A variable that is part of another variable (as an array or
6466 // structure element) cannot appear in a private clause.
6467 DeclRefExpr *DE = dyn_cast_or_null<DeclRefExpr>(RefExpr);
6468 if (!DE || !isa<VarDecl>(DE->getDecl())) {
6469 Diag(ELoc, diag::err_omp_expected_var_name) << RefExpr->getSourceRange();
6472 Decl *D = DE->getDecl();
6473 VarDecl *VD = cast<VarDecl>(D);
6475 QualType Type = VD->getType();
6476 if (Type->isDependentType() || Type->isInstantiationDependentType()) {
6477 // It will be analyzed later.
6479 PrivateCopies.push_back(nullptr);
6483 // OpenMP [2.9.3.3, Restrictions, C/C++, p.3]
6484 // A variable that appears in a private clause must not have an incomplete
6485 // type or a reference type.
6486 if (RequireCompleteType(ELoc, Type,
6487 diag::err_omp_private_incomplete_type)) {
6490 Type = Type.getNonReferenceType();
6492 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
6494 // Variables with the predetermined data-sharing attributes may not be
6495 // listed in data-sharing attributes clauses, except for the cases
6496 // listed below. For these exceptions only, listing a predetermined
6497 // variable in a data-sharing attribute clause is allowed and overrides
6498 // the variable's predetermined data-sharing attributes.
6499 DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(VD, false);
6500 if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_private) {
6501 Diag(ELoc, diag::err_omp_wrong_dsa) << getOpenMPClauseName(DVar.CKind)
6502 << getOpenMPClauseName(OMPC_private);
6503 ReportOriginalDSA(*this, DSAStack, VD, DVar);
6507 // Variably modified types are not supported for tasks.
6508 if (!Type->isAnyPointerType() && Type->isVariablyModifiedType() &&
6509 DSAStack->getCurrentDirective() == OMPD_task) {
6510 Diag(ELoc, diag::err_omp_variably_modified_type_not_supported)
6511 << getOpenMPClauseName(OMPC_private) << Type
6512 << getOpenMPDirectiveName(DSAStack->getCurrentDirective());
6514 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
6515 Diag(VD->getLocation(),
6516 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
6521 // OpenMP [2.9.3.3, Restrictions, C/C++, p.1]
6522 // A variable of class type (or array thereof) that appears in a private
6523 // clause requires an accessible, unambiguous default constructor for the
6525 // Generate helper private variable and initialize it with the default
6526 // value. The address of the original variable is replaced by the address of
6527 // the new private variable in CodeGen. This new variable is not added to
6528 // IdResolver, so the code in the OpenMP region uses original variable for
6529 // proper diagnostics.
6530 Type = Type.getUnqualifiedType();
6531 auto VDPrivate = buildVarDecl(*this, DE->getExprLoc(), Type, VD->getName(),
6532 VD->hasAttrs() ? &VD->getAttrs() : nullptr);
6533 ActOnUninitializedDecl(VDPrivate, /*TypeMayContainAuto=*/false);
6534 if (VDPrivate->isInvalidDecl())
6536 auto VDPrivateRefExpr = buildDeclRefExpr(
6537 *this, VDPrivate, DE->getType().getUnqualifiedType(), DE->getExprLoc());
6539 DSAStack->addDSA(VD, DE, OMPC_private);
6541 PrivateCopies.push_back(VDPrivateRefExpr);
6547 return OMPPrivateClause::Create(Context, StartLoc, LParenLoc, EndLoc, Vars,
6552 class DiagsUninitializedSeveretyRAII {
6554 DiagnosticsEngine &Diags;
6555 SourceLocation SavedLoc;
6559 DiagsUninitializedSeveretyRAII(DiagnosticsEngine &Diags, SourceLocation Loc,
6561 : Diags(Diags), SavedLoc(Loc), IsIgnored(IsIgnored) {
6563 Diags.setSeverity(/*Diag*/ diag::warn_uninit_self_reference_in_init,
6564 /*Map*/ diag::Severity::Ignored, Loc);
6567 ~DiagsUninitializedSeveretyRAII() {
6569 Diags.popMappings(SavedLoc);
6574 OMPClause *Sema::ActOnOpenMPFirstprivateClause(ArrayRef<Expr *> VarList,
6575 SourceLocation StartLoc,
6576 SourceLocation LParenLoc,
6577 SourceLocation EndLoc) {
6578 SmallVector<Expr *, 8> Vars;
6579 SmallVector<Expr *, 8> PrivateCopies;
6580 SmallVector<Expr *, 8> Inits;
6581 bool IsImplicitClause =
6582 StartLoc.isInvalid() && LParenLoc.isInvalid() && EndLoc.isInvalid();
6583 auto ImplicitClauseLoc = DSAStack->getConstructLoc();
6585 for (auto &RefExpr : VarList) {
6586 assert(RefExpr && "NULL expr in OpenMP firstprivate clause.");
6587 if (isa<DependentScopeDeclRefExpr>(RefExpr)) {
6588 // It will be analyzed later.
6589 Vars.push_back(RefExpr);
6590 PrivateCopies.push_back(nullptr);
6591 Inits.push_back(nullptr);
6595 SourceLocation ELoc =
6596 IsImplicitClause ? ImplicitClauseLoc : RefExpr->getExprLoc();
6597 // OpenMP [2.1, C/C++]
6598 // A list item is a variable name.
6599 // OpenMP [2.9.3.3, Restrictions, p.1]
6600 // A variable that is part of another variable (as an array or
6601 // structure element) cannot appear in a private clause.
6602 DeclRefExpr *DE = dyn_cast_or_null<DeclRefExpr>(RefExpr);
6603 if (!DE || !isa<VarDecl>(DE->getDecl())) {
6604 Diag(ELoc, diag::err_omp_expected_var_name) << RefExpr->getSourceRange();
6607 Decl *D = DE->getDecl();
6608 VarDecl *VD = cast<VarDecl>(D);
6610 QualType Type = VD->getType();
6611 if (Type->isDependentType() || Type->isInstantiationDependentType()) {
6612 // It will be analyzed later.
6614 PrivateCopies.push_back(nullptr);
6615 Inits.push_back(nullptr);
6619 // OpenMP [2.9.3.3, Restrictions, C/C++, p.3]
6620 // A variable that appears in a private clause must not have an incomplete
6621 // type or a reference type.
6622 if (RequireCompleteType(ELoc, Type,
6623 diag::err_omp_firstprivate_incomplete_type)) {
6626 Type = Type.getNonReferenceType();
6628 // OpenMP [2.9.3.4, Restrictions, C/C++, p.1]
6629 // A variable of class type (or array thereof) that appears in a private
6630 // clause requires an accessible, unambiguous copy constructor for the
6632 auto ElemType = Context.getBaseElementType(Type).getNonReferenceType();
6634 // If an implicit firstprivate variable found it was checked already.
6635 if (!IsImplicitClause) {
6636 DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(VD, false);
6637 bool IsConstant = ElemType.isConstant(Context);
6638 // OpenMP [2.4.13, Data-sharing Attribute Clauses]
6639 // A list item that specifies a given variable may not appear in more
6640 // than one clause on the same directive, except that a variable may be
6641 // specified in both firstprivate and lastprivate clauses.
6642 if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_firstprivate &&
6643 DVar.CKind != OMPC_lastprivate && DVar.RefExpr) {
6644 Diag(ELoc, diag::err_omp_wrong_dsa)
6645 << getOpenMPClauseName(DVar.CKind)
6646 << getOpenMPClauseName(OMPC_firstprivate);
6647 ReportOriginalDSA(*this, DSAStack, VD, DVar);
6651 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
6653 // Variables with the predetermined data-sharing attributes may not be
6654 // listed in data-sharing attributes clauses, except for the cases
6655 // listed below. For these exceptions only, listing a predetermined
6656 // variable in a data-sharing attribute clause is allowed and overrides
6657 // the variable's predetermined data-sharing attributes.
6658 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
6659 // in a Construct, C/C++, p.2]
6660 // Variables with const-qualified type having no mutable member may be
6661 // listed in a firstprivate clause, even if they are static data members.
6662 if (!(IsConstant || VD->isStaticDataMember()) && !DVar.RefExpr &&
6663 DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_shared) {
6664 Diag(ELoc, diag::err_omp_wrong_dsa)
6665 << getOpenMPClauseName(DVar.CKind)
6666 << getOpenMPClauseName(OMPC_firstprivate);
6667 ReportOriginalDSA(*this, DSAStack, VD, DVar);
6671 OpenMPDirectiveKind CurrDir = DSAStack->getCurrentDirective();
6672 // OpenMP [2.9.3.4, Restrictions, p.2]
6673 // A list item that is private within a parallel region must not appear
6674 // in a firstprivate clause on a worksharing construct if any of the
6675 // worksharing regions arising from the worksharing construct ever bind
6676 // to any of the parallel regions arising from the parallel construct.
6677 if (isOpenMPWorksharingDirective(CurrDir) &&
6678 !isOpenMPParallelDirective(CurrDir)) {
6679 DVar = DSAStack->getImplicitDSA(VD, true);
6680 if (DVar.CKind != OMPC_shared &&
6681 (isOpenMPParallelDirective(DVar.DKind) ||
6682 DVar.DKind == OMPD_unknown)) {
6683 Diag(ELoc, diag::err_omp_required_access)
6684 << getOpenMPClauseName(OMPC_firstprivate)
6685 << getOpenMPClauseName(OMPC_shared);
6686 ReportOriginalDSA(*this, DSAStack, VD, DVar);
6690 // OpenMP [2.9.3.4, Restrictions, p.3]
6691 // A list item that appears in a reduction clause of a parallel construct
6692 // must not appear in a firstprivate clause on a worksharing or task
6693 // construct if any of the worksharing or task regions arising from the
6694 // worksharing or task construct ever bind to any of the parallel regions
6695 // arising from the parallel construct.
6696 // OpenMP [2.9.3.4, Restrictions, p.4]
6697 // A list item that appears in a reduction clause in worksharing
6698 // construct must not appear in a firstprivate clause in a task construct
6699 // encountered during execution of any of the worksharing regions arising
6700 // from the worksharing construct.
6701 if (CurrDir == OMPD_task) {
6703 DSAStack->hasInnermostDSA(VD, MatchesAnyClause(OMPC_reduction),
6704 [](OpenMPDirectiveKind K) -> bool {
6705 return isOpenMPParallelDirective(K) ||
6706 isOpenMPWorksharingDirective(K);
6709 if (DVar.CKind == OMPC_reduction &&
6710 (isOpenMPParallelDirective(DVar.DKind) ||
6711 isOpenMPWorksharingDirective(DVar.DKind))) {
6712 Diag(ELoc, diag::err_omp_parallel_reduction_in_task_firstprivate)
6713 << getOpenMPDirectiveName(DVar.DKind);
6714 ReportOriginalDSA(*this, DSAStack, VD, DVar);
6719 // OpenMP 4.5 [2.15.3.4, Restrictions, p.3]
6720 // A list item that is private within a teams region must not appear in a
6721 // firstprivate clause on a distribute construct if any of the distribute
6722 // regions arising from the distribute construct ever bind to any of the
6723 // teams regions arising from the teams construct.
6724 // OpenMP 4.5 [2.15.3.4, Restrictions, p.3]
6725 // A list item that appears in a reduction clause of a teams construct
6726 // must not appear in a firstprivate clause on a distribute construct if
6727 // any of the distribute regions arising from the distribute construct
6728 // ever bind to any of the teams regions arising from the teams construct.
6729 // OpenMP 4.5 [2.10.8, Distribute Construct, p.3]
6730 // A list item may appear in a firstprivate or lastprivate clause but not
6732 if (CurrDir == OMPD_distribute) {
6733 DVar = DSAStack->hasInnermostDSA(VD, MatchesAnyClause(OMPC_private),
6734 [](OpenMPDirectiveKind K) -> bool {
6735 return isOpenMPTeamsDirective(K);
6738 if (DVar.CKind == OMPC_private && isOpenMPTeamsDirective(DVar.DKind)) {
6739 Diag(ELoc, diag::err_omp_firstprivate_distribute_private_teams);
6740 ReportOriginalDSA(*this, DSAStack, VD, DVar);
6743 DVar = DSAStack->hasInnermostDSA(VD, MatchesAnyClause(OMPC_reduction),
6744 [](OpenMPDirectiveKind K) -> bool {
6745 return isOpenMPTeamsDirective(K);
6748 if (DVar.CKind == OMPC_reduction &&
6749 isOpenMPTeamsDirective(DVar.DKind)) {
6750 Diag(ELoc, diag::err_omp_firstprivate_distribute_in_teams_reduction);
6751 ReportOriginalDSA(*this, DSAStack, VD, DVar);
6754 DVar = DSAStack->getTopDSA(VD, false);
6755 if (DVar.CKind == OMPC_lastprivate) {
6756 Diag(ELoc, diag::err_omp_firstprivate_and_lastprivate_in_distribute);
6757 ReportOriginalDSA(*this, DSAStack, VD, DVar);
6763 // Variably modified types are not supported for tasks.
6764 if (!Type->isAnyPointerType() && Type->isVariablyModifiedType() &&
6765 DSAStack->getCurrentDirective() == OMPD_task) {
6766 Diag(ELoc, diag::err_omp_variably_modified_type_not_supported)
6767 << getOpenMPClauseName(OMPC_firstprivate) << Type
6768 << getOpenMPDirectiveName(DSAStack->getCurrentDirective());
6770 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
6771 Diag(VD->getLocation(),
6772 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
6777 Type = Type.getUnqualifiedType();
6778 auto VDPrivate = buildVarDecl(*this, ELoc, Type, VD->getName(),
6779 VD->hasAttrs() ? &VD->getAttrs() : nullptr);
6780 // Generate helper private variable and initialize it with the value of the
6781 // original variable. The address of the original variable is replaced by
6782 // the address of the new private variable in the CodeGen. This new variable
6783 // is not added to IdResolver, so the code in the OpenMP region uses
6784 // original variable for proper diagnostics and variable capturing.
6785 Expr *VDInitRefExpr = nullptr;
6786 // For arrays generate initializer for single element and replace it by the
6787 // original array element in CodeGen.
6788 if (Type->isArrayType()) {
6790 buildVarDecl(*this, DE->getExprLoc(), ElemType, VD->getName());
6791 VDInitRefExpr = buildDeclRefExpr(*this, VDInit, ElemType, ELoc);
6792 auto Init = DefaultLvalueConversion(VDInitRefExpr).get();
6793 ElemType = ElemType.getUnqualifiedType();
6794 auto *VDInitTemp = buildVarDecl(*this, DE->getLocStart(), ElemType,
6795 ".firstprivate.temp");
6796 InitializedEntity Entity =
6797 InitializedEntity::InitializeVariable(VDInitTemp);
6798 InitializationKind Kind = InitializationKind::CreateCopy(ELoc, ELoc);
6800 InitializationSequence InitSeq(*this, Entity, Kind, Init);
6801 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Init);
6802 if (Result.isInvalid())
6803 VDPrivate->setInvalidDecl();
6805 VDPrivate->setInit(Result.getAs<Expr>());
6806 // Remove temp variable declaration.
6807 Context.Deallocate(VDInitTemp);
6810 buildVarDecl(*this, DE->getLocStart(), Type, ".firstprivate.temp");
6812 buildDeclRefExpr(*this, VDInit, DE->getType(), DE->getExprLoc());
6813 AddInitializerToDecl(VDPrivate,
6814 DefaultLvalueConversion(VDInitRefExpr).get(),
6815 /*DirectInit=*/false, /*TypeMayContainAuto=*/false);
6817 if (VDPrivate->isInvalidDecl()) {
6818 if (IsImplicitClause) {
6819 Diag(DE->getExprLoc(),
6820 diag::note_omp_task_predetermined_firstprivate_here);
6824 CurContext->addDecl(VDPrivate);
6825 auto VDPrivateRefExpr = buildDeclRefExpr(
6826 *this, VDPrivate, DE->getType().getUnqualifiedType(), DE->getExprLoc());
6827 DSAStack->addDSA(VD, DE, OMPC_firstprivate);
6829 PrivateCopies.push_back(VDPrivateRefExpr);
6830 Inits.push_back(VDInitRefExpr);
6836 return OMPFirstprivateClause::Create(Context, StartLoc, LParenLoc, EndLoc,
6837 Vars, PrivateCopies, Inits);
6840 OMPClause *Sema::ActOnOpenMPLastprivateClause(ArrayRef<Expr *> VarList,
6841 SourceLocation StartLoc,
6842 SourceLocation LParenLoc,
6843 SourceLocation EndLoc) {
6844 SmallVector<Expr *, 8> Vars;
6845 SmallVector<Expr *, 8> SrcExprs;
6846 SmallVector<Expr *, 8> DstExprs;
6847 SmallVector<Expr *, 8> AssignmentOps;
6848 for (auto &RefExpr : VarList) {
6849 assert(RefExpr && "NULL expr in OpenMP lastprivate clause.");
6850 if (isa<DependentScopeDeclRefExpr>(RefExpr)) {
6851 // It will be analyzed later.
6852 Vars.push_back(RefExpr);
6853 SrcExprs.push_back(nullptr);
6854 DstExprs.push_back(nullptr);
6855 AssignmentOps.push_back(nullptr);
6859 SourceLocation ELoc = RefExpr->getExprLoc();
6860 // OpenMP [2.1, C/C++]
6861 // A list item is a variable name.
6862 // OpenMP [2.14.3.5, Restrictions, p.1]
6863 // A variable that is part of another variable (as an array or structure
6864 // element) cannot appear in a lastprivate clause.
6865 DeclRefExpr *DE = dyn_cast_or_null<DeclRefExpr>(RefExpr);
6866 if (!DE || !isa<VarDecl>(DE->getDecl())) {
6867 Diag(ELoc, diag::err_omp_expected_var_name) << RefExpr->getSourceRange();
6870 Decl *D = DE->getDecl();
6871 VarDecl *VD = cast<VarDecl>(D);
6873 QualType Type = VD->getType();
6874 if (Type->isDependentType() || Type->isInstantiationDependentType()) {
6875 // It will be analyzed later.
6877 SrcExprs.push_back(nullptr);
6878 DstExprs.push_back(nullptr);
6879 AssignmentOps.push_back(nullptr);
6883 // OpenMP [2.14.3.5, Restrictions, C/C++, p.2]
6884 // A variable that appears in a lastprivate clause must not have an
6885 // incomplete type or a reference type.
6886 if (RequireCompleteType(ELoc, Type,
6887 diag::err_omp_lastprivate_incomplete_type)) {
6890 Type = Type.getNonReferenceType();
6892 // OpenMP [2.14.1.1, Data-sharing Attribute Rules for Variables Referenced
6894 // Variables with the predetermined data-sharing attributes may not be
6895 // listed in data-sharing attributes clauses, except for the cases
6897 DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(VD, false);
6898 if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_lastprivate &&
6899 DVar.CKind != OMPC_firstprivate &&
6900 (DVar.CKind != OMPC_private || DVar.RefExpr != nullptr)) {
6901 Diag(ELoc, diag::err_omp_wrong_dsa)
6902 << getOpenMPClauseName(DVar.CKind)
6903 << getOpenMPClauseName(OMPC_lastprivate);
6904 ReportOriginalDSA(*this, DSAStack, VD, DVar);
6908 OpenMPDirectiveKind CurrDir = DSAStack->getCurrentDirective();
6909 // OpenMP [2.14.3.5, Restrictions, p.2]
6910 // A list item that is private within a parallel region, or that appears in
6911 // the reduction clause of a parallel construct, must not appear in a
6912 // lastprivate clause on a worksharing construct if any of the corresponding
6913 // worksharing regions ever binds to any of the corresponding parallel
6915 DSAStackTy::DSAVarData TopDVar = DVar;
6916 if (isOpenMPWorksharingDirective(CurrDir) &&
6917 !isOpenMPParallelDirective(CurrDir)) {
6918 DVar = DSAStack->getImplicitDSA(VD, true);
6919 if (DVar.CKind != OMPC_shared) {
6920 Diag(ELoc, diag::err_omp_required_access)
6921 << getOpenMPClauseName(OMPC_lastprivate)
6922 << getOpenMPClauseName(OMPC_shared);
6923 ReportOriginalDSA(*this, DSAStack, VD, DVar);
6927 // OpenMP [2.14.3.5, Restrictions, C++, p.1,2]
6928 // A variable of class type (or array thereof) that appears in a
6929 // lastprivate clause requires an accessible, unambiguous default
6930 // constructor for the class type, unless the list item is also specified
6931 // in a firstprivate clause.
6932 // A variable of class type (or array thereof) that appears in a
6933 // lastprivate clause requires an accessible, unambiguous copy assignment
6934 // operator for the class type.
6935 Type = Context.getBaseElementType(Type).getNonReferenceType();
6936 auto *SrcVD = buildVarDecl(*this, DE->getLocStart(),
6937 Type.getUnqualifiedType(), ".lastprivate.src",
6938 VD->hasAttrs() ? &VD->getAttrs() : nullptr);
6939 auto *PseudoSrcExpr = buildDeclRefExpr(
6940 *this, SrcVD, Type.getUnqualifiedType(), DE->getExprLoc());
6942 buildVarDecl(*this, DE->getLocStart(), Type, ".lastprivate.dst",
6943 VD->hasAttrs() ? &VD->getAttrs() : nullptr);
6944 auto *PseudoDstExpr =
6945 buildDeclRefExpr(*this, DstVD, Type, DE->getExprLoc());
6946 // For arrays generate assignment operation for single element and replace
6947 // it by the original array element in CodeGen.
6948 auto AssignmentOp = BuildBinOp(/*S=*/nullptr, DE->getExprLoc(), BO_Assign,
6949 PseudoDstExpr, PseudoSrcExpr);
6950 if (AssignmentOp.isInvalid())
6952 AssignmentOp = ActOnFinishFullExpr(AssignmentOp.get(), DE->getExprLoc(),
6953 /*DiscardedValue=*/true);
6954 if (AssignmentOp.isInvalid())
6957 // OpenMP 4.5 [2.10.8, Distribute Construct, p.3]
6958 // A list item may appear in a firstprivate or lastprivate clause but not
6960 if (CurrDir == OMPD_distribute) {
6961 DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(VD, false);
6962 if (DVar.CKind == OMPC_firstprivate) {
6963 Diag(ELoc, diag::err_omp_firstprivate_and_lastprivate_in_distribute);
6964 ReportOriginalDSA(*this, DSAStack, VD, DVar);
6969 if (TopDVar.CKind != OMPC_firstprivate)
6970 DSAStack->addDSA(VD, DE, OMPC_lastprivate);
6972 SrcExprs.push_back(PseudoSrcExpr);
6973 DstExprs.push_back(PseudoDstExpr);
6974 AssignmentOps.push_back(AssignmentOp.get());
6980 return OMPLastprivateClause::Create(Context, StartLoc, LParenLoc, EndLoc,
6981 Vars, SrcExprs, DstExprs, AssignmentOps);
6984 OMPClause *Sema::ActOnOpenMPSharedClause(ArrayRef<Expr *> VarList,
6985 SourceLocation StartLoc,
6986 SourceLocation LParenLoc,
6987 SourceLocation EndLoc) {
6988 SmallVector<Expr *, 8> Vars;
6989 for (auto &RefExpr : VarList) {
6990 assert(RefExpr && "NULL expr in OpenMP shared clause.");
6991 if (isa<DependentScopeDeclRefExpr>(RefExpr)) {
6992 // It will be analyzed later.
6993 Vars.push_back(RefExpr);
6997 SourceLocation ELoc = RefExpr->getExprLoc();
6998 // OpenMP [2.1, C/C++]
6999 // A list item is a variable name.
7000 // OpenMP [2.14.3.2, Restrictions, p.1]
7001 // A variable that is part of another variable (as an array or structure
7002 // element) cannot appear in a shared unless it is a static data member
7004 DeclRefExpr *DE = dyn_cast<DeclRefExpr>(RefExpr);
7005 if (!DE || !isa<VarDecl>(DE->getDecl())) {
7006 Diag(ELoc, diag::err_omp_expected_var_name) << RefExpr->getSourceRange();
7009 Decl *D = DE->getDecl();
7010 VarDecl *VD = cast<VarDecl>(D);
7012 QualType Type = VD->getType();
7013 if (Type->isDependentType() || Type->isInstantiationDependentType()) {
7014 // It will be analyzed later.
7019 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
7021 // Variables with the predetermined data-sharing attributes may not be
7022 // listed in data-sharing attributes clauses, except for the cases
7023 // listed below. For these exceptions only, listing a predetermined
7024 // variable in a data-sharing attribute clause is allowed and overrides
7025 // the variable's predetermined data-sharing attributes.
7026 DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(VD, false);
7027 if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_shared &&
7029 Diag(ELoc, diag::err_omp_wrong_dsa) << getOpenMPClauseName(DVar.CKind)
7030 << getOpenMPClauseName(OMPC_shared);
7031 ReportOriginalDSA(*this, DSAStack, VD, DVar);
7035 DSAStack->addDSA(VD, DE, OMPC_shared);
7042 return OMPSharedClause::Create(Context, StartLoc, LParenLoc, EndLoc, Vars);
7046 class DSARefChecker : public StmtVisitor<DSARefChecker, bool> {
7050 bool VisitDeclRefExpr(DeclRefExpr *E) {
7051 if (VarDecl *VD = dyn_cast<VarDecl>(E->getDecl())) {
7052 DSAStackTy::DSAVarData DVar = Stack->getTopDSA(VD, false);
7053 if (DVar.CKind == OMPC_shared && !DVar.RefExpr)
7055 if (DVar.CKind != OMPC_unknown)
7057 DSAStackTy::DSAVarData DVarPrivate =
7058 Stack->hasDSA(VD, isOpenMPPrivate, MatchesAlways(), false);
7059 if (DVarPrivate.CKind != OMPC_unknown)
7065 bool VisitStmt(Stmt *S) {
7066 for (auto Child : S->children()) {
7067 if (Child && Visit(Child))
7072 explicit DSARefChecker(DSAStackTy *S) : Stack(S) {}
7076 OMPClause *Sema::ActOnOpenMPReductionClause(
7077 ArrayRef<Expr *> VarList, SourceLocation StartLoc, SourceLocation LParenLoc,
7078 SourceLocation ColonLoc, SourceLocation EndLoc,
7079 CXXScopeSpec &ReductionIdScopeSpec,
7080 const DeclarationNameInfo &ReductionId) {
7081 // TODO: Allow scope specification search when 'declare reduction' is
7083 assert(ReductionIdScopeSpec.isEmpty() &&
7084 "No support for scoped reduction identifiers yet.");
7086 auto DN = ReductionId.getName();
7087 auto OOK = DN.getCXXOverloadedOperator();
7088 BinaryOperatorKind BOK = BO_Comma;
7090 // OpenMP [2.14.3.6, reduction clause]
7092 // reduction-identifier is either an identifier or one of the following
7093 // operators: +, -, *, &, |, ^, && and ||
7095 // reduction-identifier is either an id-expression or one of the following
7096 // operators: +, -, *, &, |, ^, && and ||
7097 // FIXME: Only 'min' and 'max' identifiers are supported for now.
7124 case OO_Array_Delete:
7133 case OO_GreaterEqual:
7138 case OO_PercentEqual:
7143 case OO_GreaterGreater:
7144 case OO_LessLessEqual:
7145 case OO_GreaterGreaterEqual:
7147 case OO_ExclaimEqual:
7155 case OO_Conditional:
7157 case NUM_OVERLOADED_OPERATORS:
7158 llvm_unreachable("Unexpected reduction identifier");
7160 if (auto II = DN.getAsIdentifierInfo()) {
7161 if (II->isStr("max"))
7163 else if (II->isStr("min"))
7168 SourceRange ReductionIdRange;
7169 if (ReductionIdScopeSpec.isValid()) {
7170 ReductionIdRange.setBegin(ReductionIdScopeSpec.getBeginLoc());
7172 ReductionIdRange.setEnd(ReductionId.getEndLoc());
7173 if (BOK == BO_Comma) {
7174 // Not allowed reduction identifier is found.
7175 Diag(ReductionId.getLocStart(), diag::err_omp_unknown_reduction_identifier)
7176 << ReductionIdRange;
7180 SmallVector<Expr *, 8> Vars;
7181 SmallVector<Expr *, 8> Privates;
7182 SmallVector<Expr *, 8> LHSs;
7183 SmallVector<Expr *, 8> RHSs;
7184 SmallVector<Expr *, 8> ReductionOps;
7185 for (auto RefExpr : VarList) {
7186 assert(RefExpr && "nullptr expr in OpenMP reduction clause.");
7187 if (isa<DependentScopeDeclRefExpr>(RefExpr)) {
7188 // It will be analyzed later.
7189 Vars.push_back(RefExpr);
7190 Privates.push_back(nullptr);
7191 LHSs.push_back(nullptr);
7192 RHSs.push_back(nullptr);
7193 ReductionOps.push_back(nullptr);
7197 if (RefExpr->isTypeDependent() || RefExpr->isValueDependent() ||
7198 RefExpr->isInstantiationDependent() ||
7199 RefExpr->containsUnexpandedParameterPack()) {
7200 // It will be analyzed later.
7201 Vars.push_back(RefExpr);
7202 Privates.push_back(nullptr);
7203 LHSs.push_back(nullptr);
7204 RHSs.push_back(nullptr);
7205 ReductionOps.push_back(nullptr);
7209 auto ELoc = RefExpr->getExprLoc();
7210 auto ERange = RefExpr->getSourceRange();
7211 // OpenMP [2.1, C/C++]
7212 // A list item is a variable or array section, subject to the restrictions
7213 // specified in Section 2.4 on page 42 and in each of the sections
7214 // describing clauses and directives for which a list appears.
7215 // OpenMP [2.14.3.3, Restrictions, p.1]
7216 // A variable that is part of another variable (as an array or
7217 // structure element) cannot appear in a private clause.
7218 auto *DE = dyn_cast<DeclRefExpr>(RefExpr);
7219 auto *ASE = dyn_cast<ArraySubscriptExpr>(RefExpr);
7220 auto *OASE = dyn_cast<OMPArraySectionExpr>(RefExpr);
7221 if (!ASE && !OASE && (!DE || !isa<VarDecl>(DE->getDecl()))) {
7222 Diag(ELoc, diag::err_omp_expected_var_name_or_array_item) << ERange;
7226 VarDecl *VD = nullptr;
7228 auto D = DE->getDecl();
7229 VD = cast<VarDecl>(D);
7230 Type = VD->getType();
7232 Type = ASE->getType();
7233 auto *Base = ASE->getBase()->IgnoreParenImpCasts();
7234 while (auto *TempASE = dyn_cast<ArraySubscriptExpr>(Base))
7235 Base = TempASE->getBase()->IgnoreParenImpCasts();
7236 DE = dyn_cast<DeclRefExpr>(Base);
7238 VD = dyn_cast<VarDecl>(DE->getDecl());
7240 Diag(Base->getExprLoc(), diag::err_omp_expected_base_var_name)
7241 << 0 << Base->getSourceRange();
7245 auto BaseType = OMPArraySectionExpr::getBaseOriginalType(OASE->getBase());
7246 if (auto *ATy = BaseType->getAsArrayTypeUnsafe())
7247 Type = ATy->getElementType();
7249 Type = BaseType->getPointeeType();
7250 auto *Base = OASE->getBase()->IgnoreParenImpCasts();
7251 while (auto *TempOASE = dyn_cast<OMPArraySectionExpr>(Base))
7252 Base = TempOASE->getBase()->IgnoreParenImpCasts();
7253 while (auto *TempASE = dyn_cast<ArraySubscriptExpr>(Base))
7254 Base = TempASE->getBase()->IgnoreParenImpCasts();
7255 DE = dyn_cast<DeclRefExpr>(Base);
7257 VD = dyn_cast<VarDecl>(DE->getDecl());
7259 Diag(Base->getExprLoc(), diag::err_omp_expected_base_var_name)
7260 << 1 << Base->getSourceRange();
7265 // OpenMP [2.9.3.3, Restrictions, C/C++, p.3]
7266 // A variable that appears in a private clause must not have an incomplete
7267 // type or a reference type.
7268 if (RequireCompleteType(ELoc, Type,
7269 diag::err_omp_reduction_incomplete_type))
7271 // OpenMP [2.14.3.6, reduction clause, Restrictions]
7272 // Arrays may not appear in a reduction clause.
7273 if (Type.getNonReferenceType()->isArrayType()) {
7274 Diag(ELoc, diag::err_omp_reduction_type_array) << Type << ERange;
7275 if (!ASE && !OASE) {
7276 bool IsDecl = VD->isThisDeclarationADefinition(Context) ==
7277 VarDecl::DeclarationOnly;
7278 Diag(VD->getLocation(),
7279 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
7284 // OpenMP [2.14.3.6, reduction clause, Restrictions]
7285 // A list item that appears in a reduction clause must not be
7287 if (Type.getNonReferenceType().isConstant(Context)) {
7288 Diag(ELoc, diag::err_omp_const_reduction_list_item)
7289 << getOpenMPClauseName(OMPC_reduction) << Type << ERange;
7290 if (!ASE && !OASE) {
7291 bool IsDecl = VD->isThisDeclarationADefinition(Context) ==
7292 VarDecl::DeclarationOnly;
7293 Diag(VD->getLocation(),
7294 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
7299 // OpenMP [2.9.3.6, Restrictions, C/C++, p.4]
7300 // If a list-item is a reference type then it must bind to the same object
7301 // for all threads of the team.
7302 if (!ASE && !OASE) {
7303 VarDecl *VDDef = VD->getDefinition();
7304 if (Type->isReferenceType() && VDDef) {
7305 DSARefChecker Check(DSAStack);
7306 if (Check.Visit(VDDef->getInit())) {
7307 Diag(ELoc, diag::err_omp_reduction_ref_type_arg) << ERange;
7308 Diag(VDDef->getLocation(), diag::note_defined_here) << VDDef;
7313 // OpenMP [2.14.3.6, reduction clause, Restrictions]
7314 // The type of a list item that appears in a reduction clause must be valid
7315 // for the reduction-identifier. For a max or min reduction in C, the type
7316 // of the list item must be an allowed arithmetic data type: char, int,
7317 // float, double, or _Bool, possibly modified with long, short, signed, or
7318 // unsigned. For a max or min reduction in C++, the type of the list item
7319 // must be an allowed arithmetic data type: char, wchar_t, int, float,
7320 // double, or bool, possibly modified with long, short, signed, or unsigned.
7321 if ((BOK == BO_GT || BOK == BO_LT) &&
7322 !(Type->isScalarType() ||
7323 (getLangOpts().CPlusPlus && Type->isArithmeticType()))) {
7324 Diag(ELoc, diag::err_omp_clause_not_arithmetic_type_arg)
7325 << getLangOpts().CPlusPlus;
7326 if (!ASE && !OASE) {
7327 bool IsDecl = VD->isThisDeclarationADefinition(Context) ==
7328 VarDecl::DeclarationOnly;
7329 Diag(VD->getLocation(),
7330 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
7335 if ((BOK == BO_OrAssign || BOK == BO_AndAssign || BOK == BO_XorAssign) &&
7336 !getLangOpts().CPlusPlus && Type->isFloatingType()) {
7337 Diag(ELoc, diag::err_omp_clause_floating_type_arg);
7338 if (!ASE && !OASE) {
7339 bool IsDecl = VD->isThisDeclarationADefinition(Context) ==
7340 VarDecl::DeclarationOnly;
7341 Diag(VD->getLocation(),
7342 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
7347 // OpenMP [2.14.1.1, Data-sharing Attribute Rules for Variables Referenced
7349 // Variables with the predetermined data-sharing attributes may not be
7350 // listed in data-sharing attributes clauses, except for the cases
7351 // listed below. For these exceptions only, listing a predetermined
7352 // variable in a data-sharing attribute clause is allowed and overrides
7353 // the variable's predetermined data-sharing attributes.
7354 // OpenMP [2.14.3.6, Restrictions, p.3]
7355 // Any number of reduction clauses can be specified on the directive,
7356 // but a list item can appear only once in the reduction clauses for that
7358 DSAStackTy::DSAVarData DVar;
7359 DVar = DSAStack->getTopDSA(VD, false);
7360 if (DVar.CKind == OMPC_reduction) {
7361 Diag(ELoc, diag::err_omp_once_referenced)
7362 << getOpenMPClauseName(OMPC_reduction);
7364 Diag(DVar.RefExpr->getExprLoc(), diag::note_omp_referenced);
7366 } else if (DVar.CKind != OMPC_unknown) {
7367 Diag(ELoc, diag::err_omp_wrong_dsa)
7368 << getOpenMPClauseName(DVar.CKind)
7369 << getOpenMPClauseName(OMPC_reduction);
7370 ReportOriginalDSA(*this, DSAStack, VD, DVar);
7374 // OpenMP [2.14.3.6, Restrictions, p.1]
7375 // A list item that appears in a reduction clause of a worksharing
7376 // construct must be shared in the parallel regions to which any of the
7377 // worksharing regions arising from the worksharing construct bind.
7378 OpenMPDirectiveKind CurrDir = DSAStack->getCurrentDirective();
7379 if (isOpenMPWorksharingDirective(CurrDir) &&
7380 !isOpenMPParallelDirective(CurrDir)) {
7381 DVar = DSAStack->getImplicitDSA(VD, true);
7382 if (DVar.CKind != OMPC_shared) {
7383 Diag(ELoc, diag::err_omp_required_access)
7384 << getOpenMPClauseName(OMPC_reduction)
7385 << getOpenMPClauseName(OMPC_shared);
7386 ReportOriginalDSA(*this, DSAStack, VD, DVar);
7391 Type = Type.getNonLValueExprType(Context).getUnqualifiedType();
7392 auto *LHSVD = buildVarDecl(*this, ELoc, Type, ".reduction.lhs",
7393 VD->hasAttrs() ? &VD->getAttrs() : nullptr);
7394 auto *RHSVD = buildVarDecl(*this, ELoc, Type, VD->getName(),
7395 VD->hasAttrs() ? &VD->getAttrs() : nullptr);
7396 auto PrivateTy = Type;
7398 // For array sections only:
7399 // Create pseudo array type for private copy. The size for this array will
7400 // be generated during codegen.
7401 // For array subscripts or single variables Private Ty is the same as Type
7402 // (type of the variable or single array element).
7403 PrivateTy = Context.getVariableArrayType(
7404 Type, new (Context) OpaqueValueExpr(SourceLocation(),
7405 Context.getSizeType(), VK_RValue),
7406 ArrayType::Normal, /*IndexTypeQuals=*/0, SourceRange());
7409 auto *PrivateVD = buildVarDecl(*this, ELoc, PrivateTy, VD->getName(),
7410 VD->hasAttrs() ? &VD->getAttrs() : nullptr);
7411 // Add initializer for private variable.
7412 Expr *Init = nullptr;
7418 // '+', '-', '^', '|', '||' reduction ops - initializer is '0'.
7419 if (Type->isScalarType() || Type->isAnyComplexType()) {
7420 Init = ActOnIntegerConstant(ELoc, /*Val=*/0).get();
7425 if (Type->isScalarType() || Type->isAnyComplexType()) {
7426 // '*' and '&&' reduction ops - initializer is '1'.
7427 Init = ActOnIntegerConstant(ELoc, /*Val=*/1).get();
7431 // '&' reduction op - initializer is '~0'.
7432 QualType OrigType = Type;
7433 if (auto *ComplexTy = OrigType->getAs<ComplexType>()) {
7434 Type = ComplexTy->getElementType();
7436 if (Type->isRealFloatingType()) {
7437 llvm::APFloat InitValue =
7438 llvm::APFloat::getAllOnesValue(Context.getTypeSize(Type),
7440 Init = FloatingLiteral::Create(Context, InitValue, /*isexact=*/true,
7442 } else if (Type->isScalarType()) {
7443 auto Size = Context.getTypeSize(Type);
7444 QualType IntTy = Context.getIntTypeForBitwidth(Size, /*Signed=*/0);
7445 llvm::APInt InitValue = llvm::APInt::getAllOnesValue(Size);
7446 Init = IntegerLiteral::Create(Context, InitValue, IntTy, ELoc);
7448 if (Init && OrigType->isAnyComplexType()) {
7449 // Init = 0xFFFF + 0xFFFFi;
7450 auto *Im = new (Context) ImaginaryLiteral(Init, OrigType);
7451 Init = CreateBuiltinBinOp(ELoc, BO_Add, Init, Im).get();
7458 // 'min' reduction op - initializer is 'Largest representable number in
7459 // the reduction list item type'.
7460 // 'max' reduction op - initializer is 'Least representable number in
7461 // the reduction list item type'.
7462 if (Type->isIntegerType() || Type->isPointerType()) {
7463 bool IsSigned = Type->hasSignedIntegerRepresentation();
7464 auto Size = Context.getTypeSize(Type);
7466 Context.getIntTypeForBitwidth(Size, /*Signed=*/IsSigned);
7467 llvm::APInt InitValue =
7469 ? IsSigned ? llvm::APInt::getSignedMinValue(Size)
7470 : llvm::APInt::getMinValue(Size)
7471 : IsSigned ? llvm::APInt::getSignedMaxValue(Size)
7472 : llvm::APInt::getMaxValue(Size);
7473 Init = IntegerLiteral::Create(Context, InitValue, IntTy, ELoc);
7474 if (Type->isPointerType()) {
7475 // Cast to pointer type.
7476 auto CastExpr = BuildCStyleCastExpr(
7477 SourceLocation(), Context.getTrivialTypeSourceInfo(Type, ELoc),
7478 SourceLocation(), Init);
7479 if (CastExpr.isInvalid())
7481 Init = CastExpr.get();
7483 } else if (Type->isRealFloatingType()) {
7484 llvm::APFloat InitValue = llvm::APFloat::getLargest(
7485 Context.getFloatTypeSemantics(Type), BOK != BO_LT);
7486 Init = FloatingLiteral::Create(Context, InitValue, /*isexact=*/true,
7514 llvm_unreachable("Unexpected reduction operation");
7517 AddInitializerToDecl(RHSVD, Init, /*DirectInit=*/false,
7518 /*TypeMayContainAuto=*/false);
7520 ActOnUninitializedDecl(RHSVD, /*TypeMayContainAuto=*/false);
7521 if (!RHSVD->hasInit()) {
7522 Diag(ELoc, diag::err_omp_reduction_id_not_compatible) << Type
7523 << ReductionIdRange;
7525 bool IsDecl = VD->isThisDeclarationADefinition(Context) ==
7526 VarDecl::DeclarationOnly;
7527 Diag(VD->getLocation(),
7528 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
7533 // Store initializer for single element in private copy. Will be used during
7535 PrivateVD->setInit(RHSVD->getInit());
7536 PrivateVD->setInitStyle(RHSVD->getInitStyle());
7537 auto *LHSDRE = buildDeclRefExpr(*this, LHSVD, Type, ELoc);
7538 auto *RHSDRE = buildDeclRefExpr(*this, RHSVD, Type, ELoc);
7539 auto *PrivateDRE = buildDeclRefExpr(*this, PrivateVD, PrivateTy, ELoc);
7540 ExprResult ReductionOp =
7541 BuildBinOp(DSAStack->getCurScope(), ReductionId.getLocStart(), BOK,
7543 if (ReductionOp.isUsable()) {
7544 if (BOK != BO_LT && BOK != BO_GT) {
7546 BuildBinOp(DSAStack->getCurScope(), ReductionId.getLocStart(),
7547 BO_Assign, LHSDRE, ReductionOp.get());
7549 auto *ConditionalOp = new (Context) ConditionalOperator(
7550 ReductionOp.get(), SourceLocation(), LHSDRE, SourceLocation(),
7551 RHSDRE, Type, VK_LValue, OK_Ordinary);
7553 BuildBinOp(DSAStack->getCurScope(), ReductionId.getLocStart(),
7554 BO_Assign, LHSDRE, ConditionalOp);
7556 ReductionOp = ActOnFinishFullExpr(ReductionOp.get());
7558 if (ReductionOp.isInvalid())
7561 DSAStack->addDSA(VD, DE, OMPC_reduction);
7562 Vars.push_back(RefExpr);
7563 Privates.push_back(PrivateDRE);
7564 LHSs.push_back(LHSDRE);
7565 RHSs.push_back(RHSDRE);
7566 ReductionOps.push_back(ReductionOp.get());
7572 return OMPReductionClause::Create(
7573 Context, StartLoc, LParenLoc, ColonLoc, EndLoc, Vars,
7574 ReductionIdScopeSpec.getWithLocInContext(Context), ReductionId, Privates,
7575 LHSs, RHSs, ReductionOps);
7578 OMPClause *Sema::ActOnOpenMPLinearClause(
7579 ArrayRef<Expr *> VarList, Expr *Step, SourceLocation StartLoc,
7580 SourceLocation LParenLoc, OpenMPLinearClauseKind LinKind,
7581 SourceLocation LinLoc, SourceLocation ColonLoc, SourceLocation EndLoc) {
7582 SmallVector<Expr *, 8> Vars;
7583 SmallVector<Expr *, 8> Privates;
7584 SmallVector<Expr *, 8> Inits;
7585 if ((!LangOpts.CPlusPlus && LinKind != OMPC_LINEAR_val) ||
7586 LinKind == OMPC_LINEAR_unknown) {
7587 Diag(LinLoc, diag::err_omp_wrong_linear_modifier) << LangOpts.CPlusPlus;
7588 LinKind = OMPC_LINEAR_val;
7590 for (auto &RefExpr : VarList) {
7591 assert(RefExpr && "NULL expr in OpenMP linear clause.");
7592 if (isa<DependentScopeDeclRefExpr>(RefExpr)) {
7593 // It will be analyzed later.
7594 Vars.push_back(RefExpr);
7595 Privates.push_back(nullptr);
7596 Inits.push_back(nullptr);
7600 // OpenMP [2.14.3.7, linear clause]
7601 // A list item that appears in a linear clause is subject to the private
7602 // clause semantics described in Section 2.14.3.3 on page 159 except as
7603 // noted. In addition, the value of the new list item on each iteration
7604 // of the associated loop(s) corresponds to the value of the original
7605 // list item before entering the construct plus the logical number of
7606 // the iteration times linear-step.
7608 SourceLocation ELoc = RefExpr->getExprLoc();
7609 // OpenMP [2.1, C/C++]
7610 // A list item is a variable name.
7611 // OpenMP [2.14.3.3, Restrictions, p.1]
7612 // A variable that is part of another variable (as an array or
7613 // structure element) cannot appear in a private clause.
7614 DeclRefExpr *DE = dyn_cast<DeclRefExpr>(RefExpr);
7615 if (!DE || !isa<VarDecl>(DE->getDecl())) {
7616 Diag(ELoc, diag::err_omp_expected_var_name) << RefExpr->getSourceRange();
7620 VarDecl *VD = cast<VarDecl>(DE->getDecl());
7622 // OpenMP [2.14.3.7, linear clause]
7623 // A list-item cannot appear in more than one linear clause.
7624 // A list-item that appears in a linear clause cannot appear in any
7625 // other data-sharing attribute clause.
7626 DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(VD, false);
7628 Diag(ELoc, diag::err_omp_wrong_dsa) << getOpenMPClauseName(DVar.CKind)
7629 << getOpenMPClauseName(OMPC_linear);
7630 ReportOriginalDSA(*this, DSAStack, VD, DVar);
7634 QualType QType = VD->getType();
7635 if (QType->isDependentType() || QType->isInstantiationDependentType()) {
7636 // It will be analyzed later.
7638 Privates.push_back(nullptr);
7639 Inits.push_back(nullptr);
7643 // A variable must not have an incomplete type or a reference type.
7644 if (RequireCompleteType(ELoc, QType,
7645 diag::err_omp_linear_incomplete_type)) {
7648 if ((LinKind == OMPC_LINEAR_uval || LinKind == OMPC_LINEAR_ref) &&
7649 !QType->isReferenceType()) {
7650 Diag(ELoc, diag::err_omp_wrong_linear_modifier_non_reference)
7651 << QType << getOpenMPSimpleClauseTypeName(OMPC_linear, LinKind);
7654 QType = QType.getNonReferenceType();
7656 // A list item must not be const-qualified.
7657 if (QType.isConstant(Context)) {
7658 Diag(ELoc, diag::err_omp_const_variable)
7659 << getOpenMPClauseName(OMPC_linear);
7661 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
7662 Diag(VD->getLocation(),
7663 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
7668 // A list item must be of integral or pointer type.
7669 QType = QType.getUnqualifiedType().getCanonicalType();
7670 const Type *Ty = QType.getTypePtrOrNull();
7671 if (!Ty || (!Ty->isDependentType() && !Ty->isIntegralType(Context) &&
7672 !Ty->isPointerType())) {
7673 Diag(ELoc, diag::err_omp_linear_expected_int_or_ptr) << QType;
7675 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
7676 Diag(VD->getLocation(),
7677 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
7682 // Build private copy of original var.
7683 auto *Private = buildVarDecl(*this, ELoc, QType, VD->getName(),
7684 VD->hasAttrs() ? &VD->getAttrs() : nullptr);
7685 auto *PrivateRef = buildDeclRefExpr(
7686 *this, Private, DE->getType().getUnqualifiedType(), DE->getExprLoc());
7687 // Build var to save initial value.
7688 VarDecl *Init = buildVarDecl(*this, ELoc, QType, ".linear.start");
7690 if (LinKind == OMPC_LINEAR_uval)
7691 InitExpr = VD->getInit();
7694 AddInitializerToDecl(Init, DefaultLvalueConversion(InitExpr).get(),
7695 /*DirectInit*/ false, /*TypeMayContainAuto*/ false);
7696 auto InitRef = buildDeclRefExpr(
7697 *this, Init, DE->getType().getUnqualifiedType(), DE->getExprLoc());
7698 DSAStack->addDSA(VD, DE, OMPC_linear);
7700 Privates.push_back(PrivateRef);
7701 Inits.push_back(InitRef);
7707 Expr *StepExpr = Step;
7708 Expr *CalcStepExpr = nullptr;
7709 if (Step && !Step->isValueDependent() && !Step->isTypeDependent() &&
7710 !Step->isInstantiationDependent() &&
7711 !Step->containsUnexpandedParameterPack()) {
7712 SourceLocation StepLoc = Step->getLocStart();
7713 ExprResult Val = PerformOpenMPImplicitIntegerConversion(StepLoc, Step);
7714 if (Val.isInvalid())
7716 StepExpr = Val.get();
7718 // Build var to save the step value.
7720 buildVarDecl(*this, StepLoc, StepExpr->getType(), ".linear.step");
7721 ExprResult SaveRef =
7722 buildDeclRefExpr(*this, SaveVar, StepExpr->getType(), StepLoc);
7723 ExprResult CalcStep =
7724 BuildBinOp(CurScope, StepLoc, BO_Assign, SaveRef.get(), StepExpr);
7725 CalcStep = ActOnFinishFullExpr(CalcStep.get());
7727 // Warn about zero linear step (it would be probably better specified as
7728 // making corresponding variables 'const').
7729 llvm::APSInt Result;
7730 bool IsConstant = StepExpr->isIntegerConstantExpr(Result, Context);
7731 if (IsConstant && !Result.isNegative() && !Result.isStrictlyPositive())
7732 Diag(StepLoc, diag::warn_omp_linear_step_zero) << Vars[0]
7733 << (Vars.size() > 1);
7734 if (!IsConstant && CalcStep.isUsable()) {
7735 // Calculate the step beforehand instead of doing this on each iteration.
7736 // (This is not used if the number of iterations may be kfold-ed).
7737 CalcStepExpr = CalcStep.get();
7741 return OMPLinearClause::Create(Context, StartLoc, LParenLoc, LinKind, LinLoc,
7742 ColonLoc, EndLoc, Vars, Privates, Inits,
7743 StepExpr, CalcStepExpr);
7746 static bool FinishOpenMPLinearClause(OMPLinearClause &Clause, DeclRefExpr *IV,
7747 Expr *NumIterations, Sema &SemaRef,
7749 // Walk the vars and build update/final expressions for the CodeGen.
7750 SmallVector<Expr *, 8> Updates;
7751 SmallVector<Expr *, 8> Finals;
7752 Expr *Step = Clause.getStep();
7753 Expr *CalcStep = Clause.getCalcStep();
7754 // OpenMP [2.14.3.7, linear clause]
7755 // If linear-step is not specified it is assumed to be 1.
7756 if (Step == nullptr)
7757 Step = SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get();
7759 Step = cast<BinaryOperator>(CalcStep)->getLHS();
7760 bool HasErrors = false;
7761 auto CurInit = Clause.inits().begin();
7762 auto CurPrivate = Clause.privates().begin();
7763 auto LinKind = Clause.getModifier();
7764 for (auto &RefExpr : Clause.varlists()) {
7765 Expr *InitExpr = *CurInit;
7767 // Build privatized reference to the current linear var.
7768 auto DE = cast<DeclRefExpr>(RefExpr);
7770 if (LinKind == OMPC_LINEAR_uval)
7771 CapturedRef = cast<VarDecl>(DE->getDecl())->getInit();
7774 buildDeclRefExpr(SemaRef, cast<VarDecl>(DE->getDecl()),
7775 DE->getType().getUnqualifiedType(), DE->getExprLoc(),
7776 /*RefersToCapture=*/true);
7778 // Build update: Var = InitExpr + IV * Step
7780 BuildCounterUpdate(SemaRef, S, RefExpr->getExprLoc(), *CurPrivate,
7781 InitExpr, IV, Step, /* Subtract */ false);
7782 Update = SemaRef.ActOnFinishFullExpr(Update.get(), DE->getLocStart(),
7783 /*DiscardedValue=*/true);
7785 // Build final: Var = InitExpr + NumIterations * Step
7787 BuildCounterUpdate(SemaRef, S, RefExpr->getExprLoc(), CapturedRef,
7788 InitExpr, NumIterations, Step, /* Subtract */ false);
7789 Final = SemaRef.ActOnFinishFullExpr(Final.get(), DE->getLocStart(),
7790 /*DiscardedValue=*/true);
7791 if (!Update.isUsable() || !Final.isUsable()) {
7792 Updates.push_back(nullptr);
7793 Finals.push_back(nullptr);
7796 Updates.push_back(Update.get());
7797 Finals.push_back(Final.get());
7799 ++CurInit, ++CurPrivate;
7801 Clause.setUpdates(Updates);
7802 Clause.setFinals(Finals);
7806 OMPClause *Sema::ActOnOpenMPAlignedClause(
7807 ArrayRef<Expr *> VarList, Expr *Alignment, SourceLocation StartLoc,
7808 SourceLocation LParenLoc, SourceLocation ColonLoc, SourceLocation EndLoc) {
7810 SmallVector<Expr *, 8> Vars;
7811 for (auto &RefExpr : VarList) {
7812 assert(RefExpr && "NULL expr in OpenMP aligned clause.");
7813 if (isa<DependentScopeDeclRefExpr>(RefExpr)) {
7814 // It will be analyzed later.
7815 Vars.push_back(RefExpr);
7819 SourceLocation ELoc = RefExpr->getExprLoc();
7820 // OpenMP [2.1, C/C++]
7821 // A list item is a variable name.
7822 DeclRefExpr *DE = dyn_cast<DeclRefExpr>(RefExpr);
7823 if (!DE || !isa<VarDecl>(DE->getDecl())) {
7824 Diag(ELoc, diag::err_omp_expected_var_name) << RefExpr->getSourceRange();
7828 VarDecl *VD = cast<VarDecl>(DE->getDecl());
7830 // OpenMP [2.8.1, simd construct, Restrictions]
7831 // The type of list items appearing in the aligned clause must be
7832 // array, pointer, reference to array, or reference to pointer.
7833 QualType QType = VD->getType();
7834 QType = QType.getNonReferenceType().getUnqualifiedType().getCanonicalType();
7835 const Type *Ty = QType.getTypePtrOrNull();
7836 if (!Ty || (!Ty->isDependentType() && !Ty->isArrayType() &&
7837 !Ty->isPointerType())) {
7838 Diag(ELoc, diag::err_omp_aligned_expected_array_or_ptr)
7839 << QType << getLangOpts().CPlusPlus << RefExpr->getSourceRange();
7841 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
7842 Diag(VD->getLocation(),
7843 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
7848 // OpenMP [2.8.1, simd construct, Restrictions]
7849 // A list-item cannot appear in more than one aligned clause.
7850 if (DeclRefExpr *PrevRef = DSAStack->addUniqueAligned(VD, DE)) {
7851 Diag(ELoc, diag::err_omp_aligned_twice) << RefExpr->getSourceRange();
7852 Diag(PrevRef->getExprLoc(), diag::note_omp_explicit_dsa)
7853 << getOpenMPClauseName(OMPC_aligned);
7860 // OpenMP [2.8.1, simd construct, Description]
7861 // The parameter of the aligned clause, alignment, must be a constant
7862 // positive integer expression.
7863 // If no optional parameter is specified, implementation-defined default
7864 // alignments for SIMD instructions on the target platforms are assumed.
7865 if (Alignment != nullptr) {
7866 ExprResult AlignResult =
7867 VerifyPositiveIntegerConstantInClause(Alignment, OMPC_aligned);
7868 if (AlignResult.isInvalid())
7870 Alignment = AlignResult.get();
7875 return OMPAlignedClause::Create(Context, StartLoc, LParenLoc, ColonLoc,
7876 EndLoc, Vars, Alignment);
7879 OMPClause *Sema::ActOnOpenMPCopyinClause(ArrayRef<Expr *> VarList,
7880 SourceLocation StartLoc,
7881 SourceLocation LParenLoc,
7882 SourceLocation EndLoc) {
7883 SmallVector<Expr *, 8> Vars;
7884 SmallVector<Expr *, 8> SrcExprs;
7885 SmallVector<Expr *, 8> DstExprs;
7886 SmallVector<Expr *, 8> AssignmentOps;
7887 for (auto &RefExpr : VarList) {
7888 assert(RefExpr && "NULL expr in OpenMP copyin clause.");
7889 if (isa<DependentScopeDeclRefExpr>(RefExpr)) {
7890 // It will be analyzed later.
7891 Vars.push_back(RefExpr);
7892 SrcExprs.push_back(nullptr);
7893 DstExprs.push_back(nullptr);
7894 AssignmentOps.push_back(nullptr);
7898 SourceLocation ELoc = RefExpr->getExprLoc();
7899 // OpenMP [2.1, C/C++]
7900 // A list item is a variable name.
7901 // OpenMP [2.14.4.1, Restrictions, p.1]
7902 // A list item that appears in a copyin clause must be threadprivate.
7903 DeclRefExpr *DE = dyn_cast<DeclRefExpr>(RefExpr);
7904 if (!DE || !isa<VarDecl>(DE->getDecl())) {
7905 Diag(ELoc, diag::err_omp_expected_var_name) << RefExpr->getSourceRange();
7909 Decl *D = DE->getDecl();
7910 VarDecl *VD = cast<VarDecl>(D);
7912 QualType Type = VD->getType();
7913 if (Type->isDependentType() || Type->isInstantiationDependentType()) {
7914 // It will be analyzed later.
7916 SrcExprs.push_back(nullptr);
7917 DstExprs.push_back(nullptr);
7918 AssignmentOps.push_back(nullptr);
7922 // OpenMP [2.14.4.1, Restrictions, C/C++, p.1]
7923 // A list item that appears in a copyin clause must be threadprivate.
7924 if (!DSAStack->isThreadPrivate(VD)) {
7925 Diag(ELoc, diag::err_omp_required_access)
7926 << getOpenMPClauseName(OMPC_copyin)
7927 << getOpenMPDirectiveName(OMPD_threadprivate);
7931 // OpenMP [2.14.4.1, Restrictions, C/C++, p.2]
7932 // A variable of class type (or array thereof) that appears in a
7933 // copyin clause requires an accessible, unambiguous copy assignment
7934 // operator for the class type.
7935 auto ElemType = Context.getBaseElementType(Type).getNonReferenceType();
7937 buildVarDecl(*this, DE->getLocStart(), ElemType.getUnqualifiedType(),
7938 ".copyin.src", VD->hasAttrs() ? &VD->getAttrs() : nullptr);
7939 auto *PseudoSrcExpr = buildDeclRefExpr(
7940 *this, SrcVD, ElemType.getUnqualifiedType(), DE->getExprLoc());
7942 buildVarDecl(*this, DE->getLocStart(), ElemType, ".copyin.dst",
7943 VD->hasAttrs() ? &VD->getAttrs() : nullptr);
7944 auto *PseudoDstExpr =
7945 buildDeclRefExpr(*this, DstVD, ElemType, DE->getExprLoc());
7946 // For arrays generate assignment operation for single element and replace
7947 // it by the original array element in CodeGen.
7948 auto AssignmentOp = BuildBinOp(/*S=*/nullptr, DE->getExprLoc(), BO_Assign,
7949 PseudoDstExpr, PseudoSrcExpr);
7950 if (AssignmentOp.isInvalid())
7952 AssignmentOp = ActOnFinishFullExpr(AssignmentOp.get(), DE->getExprLoc(),
7953 /*DiscardedValue=*/true);
7954 if (AssignmentOp.isInvalid())
7957 DSAStack->addDSA(VD, DE, OMPC_copyin);
7959 SrcExprs.push_back(PseudoSrcExpr);
7960 DstExprs.push_back(PseudoDstExpr);
7961 AssignmentOps.push_back(AssignmentOp.get());
7967 return OMPCopyinClause::Create(Context, StartLoc, LParenLoc, EndLoc, Vars,
7968 SrcExprs, DstExprs, AssignmentOps);
7971 OMPClause *Sema::ActOnOpenMPCopyprivateClause(ArrayRef<Expr *> VarList,
7972 SourceLocation StartLoc,
7973 SourceLocation LParenLoc,
7974 SourceLocation EndLoc) {
7975 SmallVector<Expr *, 8> Vars;
7976 SmallVector<Expr *, 8> SrcExprs;
7977 SmallVector<Expr *, 8> DstExprs;
7978 SmallVector<Expr *, 8> AssignmentOps;
7979 for (auto &RefExpr : VarList) {
7980 assert(RefExpr && "NULL expr in OpenMP copyprivate clause.");
7981 if (isa<DependentScopeDeclRefExpr>(RefExpr)) {
7982 // It will be analyzed later.
7983 Vars.push_back(RefExpr);
7984 SrcExprs.push_back(nullptr);
7985 DstExprs.push_back(nullptr);
7986 AssignmentOps.push_back(nullptr);
7990 SourceLocation ELoc = RefExpr->getExprLoc();
7991 // OpenMP [2.1, C/C++]
7992 // A list item is a variable name.
7993 // OpenMP [2.14.4.1, Restrictions, p.1]
7994 // A list item that appears in a copyin clause must be threadprivate.
7995 DeclRefExpr *DE = dyn_cast<DeclRefExpr>(RefExpr);
7996 if (!DE || !isa<VarDecl>(DE->getDecl())) {
7997 Diag(ELoc, diag::err_omp_expected_var_name) << RefExpr->getSourceRange();
8001 Decl *D = DE->getDecl();
8002 VarDecl *VD = cast<VarDecl>(D);
8004 QualType Type = VD->getType();
8005 if (Type->isDependentType() || Type->isInstantiationDependentType()) {
8006 // It will be analyzed later.
8008 SrcExprs.push_back(nullptr);
8009 DstExprs.push_back(nullptr);
8010 AssignmentOps.push_back(nullptr);
8014 // OpenMP [2.14.4.2, Restrictions, p.2]
8015 // A list item that appears in a copyprivate clause may not appear in a
8016 // private or firstprivate clause on the single construct.
8017 if (!DSAStack->isThreadPrivate(VD)) {
8018 auto DVar = DSAStack->getTopDSA(VD, false);
8019 if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_copyprivate &&
8021 Diag(ELoc, diag::err_omp_wrong_dsa)
8022 << getOpenMPClauseName(DVar.CKind)
8023 << getOpenMPClauseName(OMPC_copyprivate);
8024 ReportOriginalDSA(*this, DSAStack, VD, DVar);
8028 // OpenMP [2.11.4.2, Restrictions, p.1]
8029 // All list items that appear in a copyprivate clause must be either
8030 // threadprivate or private in the enclosing context.
8031 if (DVar.CKind == OMPC_unknown) {
8032 DVar = DSAStack->getImplicitDSA(VD, false);
8033 if (DVar.CKind == OMPC_shared) {
8034 Diag(ELoc, diag::err_omp_required_access)
8035 << getOpenMPClauseName(OMPC_copyprivate)
8036 << "threadprivate or private in the enclosing context";
8037 ReportOriginalDSA(*this, DSAStack, VD, DVar);
8043 // Variably modified types are not supported.
8044 if (!Type->isAnyPointerType() && Type->isVariablyModifiedType()) {
8045 Diag(ELoc, diag::err_omp_variably_modified_type_not_supported)
8046 << getOpenMPClauseName(OMPC_copyprivate) << Type
8047 << getOpenMPDirectiveName(DSAStack->getCurrentDirective());
8049 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
8050 Diag(VD->getLocation(),
8051 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
8056 // OpenMP [2.14.4.1, Restrictions, C/C++, p.2]
8057 // A variable of class type (or array thereof) that appears in a
8058 // copyin clause requires an accessible, unambiguous copy assignment
8059 // operator for the class type.
8060 Type = Context.getBaseElementType(Type.getNonReferenceType())
8061 .getUnqualifiedType();
8063 buildVarDecl(*this, DE->getLocStart(), Type, ".copyprivate.src",
8064 VD->hasAttrs() ? &VD->getAttrs() : nullptr);
8065 auto *PseudoSrcExpr =
8066 buildDeclRefExpr(*this, SrcVD, Type, DE->getExprLoc());
8068 buildVarDecl(*this, DE->getLocStart(), Type, ".copyprivate.dst",
8069 VD->hasAttrs() ? &VD->getAttrs() : nullptr);
8070 auto *PseudoDstExpr =
8071 buildDeclRefExpr(*this, DstVD, Type, DE->getExprLoc());
8072 auto AssignmentOp = BuildBinOp(/*S=*/nullptr, DE->getExprLoc(), BO_Assign,
8073 PseudoDstExpr, PseudoSrcExpr);
8074 if (AssignmentOp.isInvalid())
8076 AssignmentOp = ActOnFinishFullExpr(AssignmentOp.get(), DE->getExprLoc(),
8077 /*DiscardedValue=*/true);
8078 if (AssignmentOp.isInvalid())
8081 // No need to mark vars as copyprivate, they are already threadprivate or
8082 // implicitly private.
8084 SrcExprs.push_back(PseudoSrcExpr);
8085 DstExprs.push_back(PseudoDstExpr);
8086 AssignmentOps.push_back(AssignmentOp.get());
8092 return OMPCopyprivateClause::Create(Context, StartLoc, LParenLoc, EndLoc,
8093 Vars, SrcExprs, DstExprs, AssignmentOps);
8096 OMPClause *Sema::ActOnOpenMPFlushClause(ArrayRef<Expr *> VarList,
8097 SourceLocation StartLoc,
8098 SourceLocation LParenLoc,
8099 SourceLocation EndLoc) {
8100 if (VarList.empty())
8103 return OMPFlushClause::Create(Context, StartLoc, LParenLoc, EndLoc, VarList);
8107 Sema::ActOnOpenMPDependClause(OpenMPDependClauseKind DepKind,
8108 SourceLocation DepLoc, SourceLocation ColonLoc,
8109 ArrayRef<Expr *> VarList, SourceLocation StartLoc,
8110 SourceLocation LParenLoc, SourceLocation EndLoc) {
8111 if (DSAStack->getCurrentDirective() == OMPD_ordered &&
8112 DepKind != OMPC_DEPEND_source && DepKind != OMPC_DEPEND_sink) {
8113 Diag(DepLoc, diag::err_omp_unexpected_clause_value)
8114 << "'source' or 'sink'" << getOpenMPClauseName(OMPC_depend);
8117 if (DSAStack->getCurrentDirective() != OMPD_ordered &&
8118 (DepKind == OMPC_DEPEND_unknown || DepKind == OMPC_DEPEND_source ||
8119 DepKind == OMPC_DEPEND_sink)) {
8120 unsigned Except[] = {OMPC_DEPEND_source, OMPC_DEPEND_sink};
8121 Diag(DepLoc, diag::err_omp_unexpected_clause_value)
8122 << getListOfPossibleValues(OMPC_depend, /*First=*/0,
8123 /*Last=*/OMPC_DEPEND_unknown, Except)
8124 << getOpenMPClauseName(OMPC_depend);
8127 SmallVector<Expr *, 8> Vars;
8128 llvm::APSInt DepCounter(/*BitWidth=*/32);
8129 llvm::APSInt TotalDepCount(/*BitWidth=*/32);
8130 if (DepKind == OMPC_DEPEND_sink) {
8131 if (auto *OrderedCountExpr = DSAStack->getParentOrderedRegionParam()) {
8132 TotalDepCount = OrderedCountExpr->EvaluateKnownConstInt(Context);
8133 TotalDepCount.setIsUnsigned(/*Val=*/true);
8136 if ((DepKind != OMPC_DEPEND_sink && DepKind != OMPC_DEPEND_source) ||
8137 DSAStack->getParentOrderedRegionParam()) {
8138 for (auto &RefExpr : VarList) {
8139 assert(RefExpr && "NULL expr in OpenMP shared clause.");
8140 if (isa<DependentScopeDeclRefExpr>(RefExpr) ||
8141 (DepKind == OMPC_DEPEND_sink && CurContext->isDependentContext())) {
8142 // It will be analyzed later.
8143 Vars.push_back(RefExpr);
8147 SourceLocation ELoc = RefExpr->getExprLoc();
8148 auto *SimpleExpr = RefExpr->IgnoreParenCasts();
8149 if (DepKind == OMPC_DEPEND_sink) {
8150 if (DepCounter >= TotalDepCount) {
8151 Diag(ELoc, diag::err_omp_depend_sink_unexpected_expr);
8155 // OpenMP [2.13.9, Summary]
8156 // depend(dependence-type : vec), where dependence-type is:
8157 // 'sink' and where vec is the iteration vector, which has the form:
8158 // x1 [+- d1], x2 [+- d2 ], . . . , xn [+- dn]
8159 // where n is the value specified by the ordered clause in the loop
8160 // directive, xi denotes the loop iteration variable of the i-th nested
8161 // loop associated with the loop directive, and di is a constant
8162 // non-negative integer.
8163 SimpleExpr = SimpleExpr->IgnoreImplicit();
8164 auto *DE = dyn_cast<DeclRefExpr>(SimpleExpr);
8166 OverloadedOperatorKind OOK = OO_None;
8167 SourceLocation OOLoc;
8169 if (auto *BO = dyn_cast<BinaryOperator>(SimpleExpr)) {
8170 OOK = BinaryOperator::getOverloadedOperator(BO->getOpcode());
8171 OOLoc = BO->getOperatorLoc();
8172 LHS = BO->getLHS()->IgnoreParenImpCasts();
8173 RHS = BO->getRHS()->IgnoreParenImpCasts();
8174 } else if (auto *OCE = dyn_cast<CXXOperatorCallExpr>(SimpleExpr)) {
8175 OOK = OCE->getOperator();
8176 OOLoc = OCE->getOperatorLoc();
8177 LHS = OCE->getArg(/*Arg=*/0)->IgnoreParenImpCasts();
8178 RHS = OCE->getArg(/*Arg=*/1)->IgnoreParenImpCasts();
8179 } else if (auto *MCE = dyn_cast<CXXMemberCallExpr>(SimpleExpr)) {
8180 OOK = MCE->getMethodDecl()
8183 .getCXXOverloadedOperator();
8184 OOLoc = MCE->getCallee()->getExprLoc();
8185 LHS = MCE->getImplicitObjectArgument()->IgnoreParenImpCasts();
8186 RHS = MCE->getArg(/*Arg=*/0)->IgnoreParenImpCasts();
8188 Diag(ELoc, diag::err_omp_depend_sink_wrong_expr);
8191 DE = dyn_cast<DeclRefExpr>(LHS);
8193 Diag(LHS->getExprLoc(),
8194 diag::err_omp_depend_sink_expected_loop_iteration)
8195 << DSAStack->getParentLoopControlVariable(
8196 DepCounter.getZExtValue());
8199 if (OOK != OO_Plus && OOK != OO_Minus) {
8200 Diag(OOLoc, diag::err_omp_depend_sink_expected_plus_minus);
8203 ExprResult Res = VerifyPositiveIntegerConstantInClause(
8204 RHS, OMPC_depend, /*StrictlyPositive=*/false);
8205 if (Res.isInvalid())
8208 auto *VD = dyn_cast<VarDecl>(DE->getDecl());
8209 if (!CurContext->isDependentContext() &&
8210 DSAStack->getParentOrderedRegionParam() &&
8211 (!VD || DepCounter != DSAStack->isParentLoopControlVariable(VD))) {
8212 Diag(DE->getExprLoc(),
8213 diag::err_omp_depend_sink_expected_loop_iteration)
8214 << DSAStack->getParentLoopControlVariable(
8215 DepCounter.getZExtValue());
8219 // OpenMP [2.11.1.1, Restrictions, p.3]
8220 // A variable that is part of another variable (such as a field of a
8221 // structure) but is not an array element or an array section cannot
8222 // appear in a depend clause.
8223 auto *DE = dyn_cast<DeclRefExpr>(SimpleExpr);
8224 auto *ASE = dyn_cast<ArraySubscriptExpr>(SimpleExpr);
8225 auto *OASE = dyn_cast<OMPArraySectionExpr>(SimpleExpr);
8226 if (!RefExpr->IgnoreParenImpCasts()->isLValue() ||
8227 (!ASE && !DE && !OASE) || (DE && !isa<VarDecl>(DE->getDecl())) ||
8228 (ASE && !ASE->getBase()->getType()->isAnyPointerType() &&
8229 !ASE->getBase()->getType()->isArrayType())) {
8230 Diag(ELoc, diag::err_omp_expected_var_name_or_array_item)
8231 << RefExpr->getSourceRange();
8236 Vars.push_back(RefExpr->IgnoreParenImpCasts());
8239 if (!CurContext->isDependentContext() && DepKind == OMPC_DEPEND_sink &&
8240 TotalDepCount > VarList.size() &&
8241 DSAStack->getParentOrderedRegionParam()) {
8242 Diag(EndLoc, diag::err_omp_depend_sink_expected_loop_iteration)
8243 << DSAStack->getParentLoopControlVariable(VarList.size() + 1);
8245 if (DepKind != OMPC_DEPEND_source && DepKind != OMPC_DEPEND_sink &&
8250 return OMPDependClause::Create(Context, StartLoc, LParenLoc, EndLoc, DepKind,
8251 DepLoc, ColonLoc, Vars);
8254 OMPClause *Sema::ActOnOpenMPDeviceClause(Expr *Device, SourceLocation StartLoc,
8255 SourceLocation LParenLoc,
8256 SourceLocation EndLoc) {
8257 Expr *ValExpr = Device;
8259 // OpenMP [2.9.1, Restrictions]
8260 // The device expression must evaluate to a non-negative integer value.
8261 if (!IsNonNegativeIntegerValue(ValExpr, *this, OMPC_device,
8262 /*StrictlyPositive=*/false))
8265 return new (Context) OMPDeviceClause(ValExpr, StartLoc, LParenLoc, EndLoc);
8268 static bool IsCXXRecordForMappable(Sema &SemaRef, SourceLocation Loc,
8269 DSAStackTy *Stack, CXXRecordDecl *RD) {
8270 if (!RD || RD->isInvalidDecl())
8273 if (auto *CTSD = dyn_cast<ClassTemplateSpecializationDecl>(RD))
8274 if (auto *CTD = CTSD->getSpecializedTemplate())
8275 RD = CTD->getTemplatedDecl();
8276 auto QTy = SemaRef.Context.getRecordType(RD);
8277 if (RD->isDynamicClass()) {
8278 SemaRef.Diag(Loc, diag::err_omp_not_mappable_type) << QTy;
8279 SemaRef.Diag(RD->getLocation(), diag::note_omp_polymorphic_in_target);
8283 bool IsCorrect = true;
8284 for (auto *I : DC->decls()) {
8286 if (auto *MD = dyn_cast<CXXMethodDecl>(I)) {
8287 if (MD->isStatic()) {
8288 SemaRef.Diag(Loc, diag::err_omp_not_mappable_type) << QTy;
8289 SemaRef.Diag(MD->getLocation(),
8290 diag::note_omp_static_member_in_target);
8293 } else if (auto *VD = dyn_cast<VarDecl>(I)) {
8294 if (VD->isStaticDataMember()) {
8295 SemaRef.Diag(Loc, diag::err_omp_not_mappable_type) << QTy;
8296 SemaRef.Diag(VD->getLocation(),
8297 diag::note_omp_static_member_in_target);
8304 for (auto &I : RD->bases()) {
8305 if (!IsCXXRecordForMappable(SemaRef, I.getLocStart(), Stack,
8306 I.getType()->getAsCXXRecordDecl()))
8312 static bool CheckTypeMappable(SourceLocation SL, SourceRange SR, Sema &SemaRef,
8313 DSAStackTy *Stack, QualType QTy) {
8315 if (QTy->isIncompleteType(&ND)) {
8316 SemaRef.Diag(SL, diag::err_incomplete_type) << QTy << SR;
8318 } else if (CXXRecordDecl *RD = dyn_cast_or_null<CXXRecordDecl>(ND)) {
8319 if (!RD->isInvalidDecl() &&
8320 !IsCXXRecordForMappable(SemaRef, SL, Stack, RD))
8326 OMPClause *Sema::ActOnOpenMPMapClause(
8327 OpenMPMapClauseKind MapTypeModifier, OpenMPMapClauseKind MapType,
8328 SourceLocation MapLoc, SourceLocation ColonLoc, ArrayRef<Expr *> VarList,
8329 SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc) {
8330 SmallVector<Expr *, 4> Vars;
8332 for (auto &RE : VarList) {
8333 assert(RE && "Null expr in omp map");
8334 if (isa<DependentScopeDeclRefExpr>(RE)) {
8335 // It will be analyzed later.
8339 SourceLocation ELoc = RE->getExprLoc();
8341 // OpenMP [2.14.5, Restrictions]
8342 // A variable that is part of another variable (such as field of a
8343 // structure) but is not an array element or an array section cannot appear
8345 auto *VE = RE->IgnoreParenLValueCasts();
8347 if (VE->isValueDependent() || VE->isTypeDependent() ||
8348 VE->isInstantiationDependent() ||
8349 VE->containsUnexpandedParameterPack()) {
8350 // It will be analyzed later.
8355 auto *SimpleExpr = RE->IgnoreParenCasts();
8356 auto *DE = dyn_cast<DeclRefExpr>(SimpleExpr);
8357 auto *ASE = dyn_cast<ArraySubscriptExpr>(SimpleExpr);
8358 auto *OASE = dyn_cast<OMPArraySectionExpr>(SimpleExpr);
8360 if (!RE->IgnoreParenImpCasts()->isLValue() ||
8361 (!OASE && !ASE && !DE) ||
8362 (DE && !isa<VarDecl>(DE->getDecl())) ||
8363 (ASE && !ASE->getBase()->getType()->isAnyPointerType() &&
8364 !ASE->getBase()->getType()->isArrayType())) {
8365 Diag(ELoc, diag::err_omp_expected_var_name_or_array_item)
8366 << RE->getSourceRange();
8374 auto *B = ASE->getBase()->IgnoreParenCasts();
8375 D = dyn_cast<DeclRefExpr>(B)->getDecl();
8377 auto *B = OASE->getBase();
8378 D = dyn_cast<DeclRefExpr>(B)->getDecl();
8380 assert(D && "Null decl on map clause.");
8381 auto *VD = cast<VarDecl>(D);
8383 // OpenMP [2.14.5, Restrictions, p.8]
8384 // threadprivate variables cannot appear in a map clause.
8385 if (DSAStack->isThreadPrivate(VD)) {
8386 auto DVar = DSAStack->getTopDSA(VD, false);
8387 Diag(ELoc, diag::err_omp_threadprivate_in_map);
8388 ReportOriginalDSA(*this, DSAStack, VD, DVar);
8392 // OpenMP [2.14.5, Restrictions, p.2]
8393 // At most one list item can be an array item derived from a given variable
8394 // in map clauses of the same construct.
8395 // OpenMP [2.14.5, Restrictions, p.3]
8396 // List items of map clauses in the same construct must not share original
8398 // OpenMP [2.14.5, Restrictions, C/C++, p.2]
8399 // A variable for which the type is pointer, reference to array, or
8400 // reference to pointer and an array section derived from that variable
8401 // must not appear as list items of map clauses of the same construct.
8402 DSAStackTy::MapInfo MI = DSAStack->IsMappedInCurrentRegion(VD);
8404 Diag(ELoc, diag::err_omp_map_shared_storage) << ELoc;
8405 Diag(MI.RefExpr->getExprLoc(), diag::note_used_here)
8406 << MI.RefExpr->getSourceRange();
8410 // OpenMP [2.14.5, Restrictions, C/C++, p.3,4]
8411 // A variable for which the type is pointer, reference to array, or
8412 // reference to pointer must not appear as a list item if the enclosing
8413 // device data environment already contains an array section derived from
8415 // An array section derived from a variable for which the type is pointer,
8416 // reference to array, or reference to pointer must not appear as a list
8417 // item if the enclosing device data environment already contains that
8419 QualType Type = VD->getType();
8420 MI = DSAStack->getMapInfoForVar(VD);
8421 if (MI.RefExpr && (isa<DeclRefExpr>(MI.RefExpr->IgnoreParenLValueCasts()) !=
8422 isa<DeclRefExpr>(VE)) &&
8423 (Type->isPointerType() || Type->isReferenceType())) {
8424 Diag(ELoc, diag::err_omp_map_shared_storage) << ELoc;
8425 Diag(MI.RefExpr->getExprLoc(), diag::note_used_here)
8426 << MI.RefExpr->getSourceRange();
8430 // OpenMP [2.14.5, Restrictions, C/C++, p.7]
8431 // A list item must have a mappable type.
8432 if (!CheckTypeMappable(VE->getExprLoc(), VE->getSourceRange(), *this,
8438 DSAStack->addMapInfoForVar(VD, MI);
8443 return OMPMapClause::Create(Context, StartLoc, LParenLoc, EndLoc, Vars,
8444 MapTypeModifier, MapType, MapLoc);
8447 OMPClause *Sema::ActOnOpenMPNumTeamsClause(Expr *NumTeams,
8448 SourceLocation StartLoc,
8449 SourceLocation LParenLoc,
8450 SourceLocation EndLoc) {
8451 Expr *ValExpr = NumTeams;
8453 // OpenMP [teams Constrcut, Restrictions]
8454 // The num_teams expression must evaluate to a positive integer value.
8455 if (!IsNonNegativeIntegerValue(ValExpr, *this, OMPC_num_teams,
8456 /*StrictlyPositive=*/true))
8459 return new (Context) OMPNumTeamsClause(ValExpr, StartLoc, LParenLoc, EndLoc);
8462 OMPClause *Sema::ActOnOpenMPThreadLimitClause(Expr *ThreadLimit,
8463 SourceLocation StartLoc,
8464 SourceLocation LParenLoc,
8465 SourceLocation EndLoc) {
8466 Expr *ValExpr = ThreadLimit;
8468 // OpenMP [teams Constrcut, Restrictions]
8469 // The thread_limit expression must evaluate to a positive integer value.
8470 if (!IsNonNegativeIntegerValue(ValExpr, *this, OMPC_thread_limit,
8471 /*StrictlyPositive=*/true))
8474 return new (Context) OMPThreadLimitClause(ValExpr, StartLoc, LParenLoc,
8478 OMPClause *Sema::ActOnOpenMPPriorityClause(Expr *Priority,
8479 SourceLocation StartLoc,
8480 SourceLocation LParenLoc,
8481 SourceLocation EndLoc) {
8482 Expr *ValExpr = Priority;
8484 // OpenMP [2.9.1, task Constrcut]
8485 // The priority-value is a non-negative numerical scalar expression.
8486 if (!IsNonNegativeIntegerValue(ValExpr, *this, OMPC_priority,
8487 /*StrictlyPositive=*/false))
8490 return new (Context) OMPPriorityClause(ValExpr, StartLoc, LParenLoc, EndLoc);
8493 OMPClause *Sema::ActOnOpenMPGrainsizeClause(Expr *Grainsize,
8494 SourceLocation StartLoc,
8495 SourceLocation LParenLoc,
8496 SourceLocation EndLoc) {
8497 Expr *ValExpr = Grainsize;
8499 // OpenMP [2.9.2, taskloop Constrcut]
8500 // The parameter of the grainsize clause must be a positive integer
8502 if (!IsNonNegativeIntegerValue(ValExpr, *this, OMPC_grainsize,
8503 /*StrictlyPositive=*/true))
8506 return new (Context) OMPGrainsizeClause(ValExpr, StartLoc, LParenLoc, EndLoc);
8509 OMPClause *Sema::ActOnOpenMPNumTasksClause(Expr *NumTasks,
8510 SourceLocation StartLoc,
8511 SourceLocation LParenLoc,
8512 SourceLocation EndLoc) {
8513 Expr *ValExpr = NumTasks;
8515 // OpenMP [2.9.2, taskloop Constrcut]
8516 // The parameter of the num_tasks clause must be a positive integer
8518 if (!IsNonNegativeIntegerValue(ValExpr, *this, OMPC_num_tasks,
8519 /*StrictlyPositive=*/true))
8522 return new (Context) OMPNumTasksClause(ValExpr, StartLoc, LParenLoc, EndLoc);
8525 OMPClause *Sema::ActOnOpenMPHintClause(Expr *Hint, SourceLocation StartLoc,
8526 SourceLocation LParenLoc,
8527 SourceLocation EndLoc) {
8528 // OpenMP [2.13.2, critical construct, Description]
8529 // ... where hint-expression is an integer constant expression that evaluates
8530 // to a valid lock hint.
8531 ExprResult HintExpr = VerifyPositiveIntegerConstantInClause(Hint, OMPC_hint);
8532 if (HintExpr.isInvalid())
8534 return new (Context)
8535 OMPHintClause(HintExpr.get(), StartLoc, LParenLoc, EndLoc);