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());
1683 if (isOpenMPWorksharingDirective(DSAStack->getCurrentDirective()) &&
1684 isOpenMPSimdDirective(DSAStack->getCurrentDirective()) && OC &&
1685 OC->getNumForLoops()) {
1686 Diag(OC->getLocStart(), diag::err_omp_ordered_simd)
1687 << getOpenMPDirectiveName(DSAStack->getCurrentDirective());
1691 ActOnCapturedRegionError();
1694 return ActOnCapturedRegionEnd(S.get());
1697 static bool CheckNestingOfRegions(Sema &SemaRef, DSAStackTy *Stack,
1698 OpenMPDirectiveKind CurrentRegion,
1699 const DeclarationNameInfo &CurrentName,
1700 OpenMPDirectiveKind CancelRegion,
1701 SourceLocation StartLoc) {
1702 // Allowed nesting of constructs
1703 // +------------------+-----------------+------------------------------------+
1704 // | Parent directive | Child directive | Closely (!), No-Closely(+), Both(*)|
1705 // +------------------+-----------------+------------------------------------+
1706 // | parallel | parallel | * |
1707 // | parallel | for | * |
1708 // | parallel | for simd | * |
1709 // | parallel | master | * |
1710 // | parallel | critical | * |
1711 // | parallel | simd | * |
1712 // | parallel | sections | * |
1713 // | parallel | section | + |
1714 // | parallel | single | * |
1715 // | parallel | parallel for | * |
1716 // | parallel |parallel for simd| * |
1717 // | parallel |parallel sections| * |
1718 // | parallel | task | * |
1719 // | parallel | taskyield | * |
1720 // | parallel | barrier | * |
1721 // | parallel | taskwait | * |
1722 // | parallel | taskgroup | * |
1723 // | parallel | flush | * |
1724 // | parallel | ordered | + |
1725 // | parallel | atomic | * |
1726 // | parallel | target | * |
1727 // | parallel | teams | + |
1728 // | parallel | cancellation | |
1730 // | parallel | cancel | ! |
1731 // | parallel | taskloop | * |
1732 // | parallel | taskloop simd | * |
1733 // | parallel | distribute | |
1734 // +------------------+-----------------+------------------------------------+
1735 // | for | parallel | * |
1736 // | for | for | + |
1737 // | for | for simd | + |
1738 // | for | master | + |
1739 // | for | critical | * |
1740 // | for | simd | * |
1741 // | for | sections | + |
1742 // | for | section | + |
1743 // | for | single | + |
1744 // | for | parallel for | * |
1745 // | for |parallel for simd| * |
1746 // | for |parallel sections| * |
1747 // | for | task | * |
1748 // | for | taskyield | * |
1749 // | for | barrier | + |
1750 // | for | taskwait | * |
1751 // | for | taskgroup | * |
1752 // | for | flush | * |
1753 // | for | ordered | * (if construct is ordered) |
1754 // | for | atomic | * |
1755 // | for | target | * |
1756 // | for | teams | + |
1757 // | for | cancellation | |
1759 // | for | cancel | ! |
1760 // | for | taskloop | * |
1761 // | for | taskloop simd | * |
1762 // | for | distribute | |
1763 // +------------------+-----------------+------------------------------------+
1764 // | master | parallel | * |
1765 // | master | for | + |
1766 // | master | for simd | + |
1767 // | master | master | * |
1768 // | master | critical | * |
1769 // | master | simd | * |
1770 // | master | sections | + |
1771 // | master | section | + |
1772 // | master | single | + |
1773 // | master | parallel for | * |
1774 // | master |parallel for simd| * |
1775 // | master |parallel sections| * |
1776 // | master | task | * |
1777 // | master | taskyield | * |
1778 // | master | barrier | + |
1779 // | master | taskwait | * |
1780 // | master | taskgroup | * |
1781 // | master | flush | * |
1782 // | master | ordered | + |
1783 // | master | atomic | * |
1784 // | master | target | * |
1785 // | master | teams | + |
1786 // | master | cancellation | |
1788 // | master | cancel | |
1789 // | master | taskloop | * |
1790 // | master | taskloop simd | * |
1791 // | master | distribute | |
1792 // +------------------+-----------------+------------------------------------+
1793 // | critical | parallel | * |
1794 // | critical | for | + |
1795 // | critical | for simd | + |
1796 // | critical | master | * |
1797 // | critical | critical | * (should have different names) |
1798 // | critical | simd | * |
1799 // | critical | sections | + |
1800 // | critical | section | + |
1801 // | critical | single | + |
1802 // | critical | parallel for | * |
1803 // | critical |parallel for simd| * |
1804 // | critical |parallel sections| * |
1805 // | critical | task | * |
1806 // | critical | taskyield | * |
1807 // | critical | barrier | + |
1808 // | critical | taskwait | * |
1809 // | critical | taskgroup | * |
1810 // | critical | ordered | + |
1811 // | critical | atomic | * |
1812 // | critical | target | * |
1813 // | critical | teams | + |
1814 // | critical | cancellation | |
1816 // | critical | cancel | |
1817 // | critical | taskloop | * |
1818 // | critical | taskloop simd | * |
1819 // | critical | distribute | |
1820 // +------------------+-----------------+------------------------------------+
1821 // | simd | parallel | |
1823 // | simd | for simd | |
1824 // | simd | master | |
1825 // | simd | critical | |
1826 // | simd | simd | |
1827 // | simd | sections | |
1828 // | simd | section | |
1829 // | simd | single | |
1830 // | simd | parallel for | |
1831 // | simd |parallel for simd| |
1832 // | simd |parallel sections| |
1833 // | simd | task | |
1834 // | simd | taskyield | |
1835 // | simd | barrier | |
1836 // | simd | taskwait | |
1837 // | simd | taskgroup | |
1838 // | simd | flush | |
1839 // | simd | ordered | + (with simd clause) |
1840 // | simd | atomic | |
1841 // | simd | target | |
1842 // | simd | teams | |
1843 // | simd | cancellation | |
1845 // | simd | cancel | |
1846 // | simd | taskloop | |
1847 // | simd | taskloop simd | |
1848 // | simd | distribute | |
1849 // +------------------+-----------------+------------------------------------+
1850 // | for simd | parallel | |
1851 // | for simd | for | |
1852 // | for simd | for simd | |
1853 // | for simd | master | |
1854 // | for simd | critical | |
1855 // | for simd | simd | |
1856 // | for simd | sections | |
1857 // | for simd | section | |
1858 // | for simd | single | |
1859 // | for simd | parallel for | |
1860 // | for simd |parallel for simd| |
1861 // | for simd |parallel sections| |
1862 // | for simd | task | |
1863 // | for simd | taskyield | |
1864 // | for simd | barrier | |
1865 // | for simd | taskwait | |
1866 // | for simd | taskgroup | |
1867 // | for simd | flush | |
1868 // | for simd | ordered | + (with simd clause) |
1869 // | for simd | atomic | |
1870 // | for simd | target | |
1871 // | for simd | teams | |
1872 // | for simd | cancellation | |
1874 // | for simd | cancel | |
1875 // | for simd | taskloop | |
1876 // | for simd | taskloop simd | |
1877 // | for simd | distribute | |
1878 // +------------------+-----------------+------------------------------------+
1879 // | parallel for simd| parallel | |
1880 // | parallel for simd| for | |
1881 // | parallel for simd| for simd | |
1882 // | parallel for simd| master | |
1883 // | parallel for simd| critical | |
1884 // | parallel for simd| simd | |
1885 // | parallel for simd| sections | |
1886 // | parallel for simd| section | |
1887 // | parallel for simd| single | |
1888 // | parallel for simd| parallel for | |
1889 // | parallel for simd|parallel for simd| |
1890 // | parallel for simd|parallel sections| |
1891 // | parallel for simd| task | |
1892 // | parallel for simd| taskyield | |
1893 // | parallel for simd| barrier | |
1894 // | parallel for simd| taskwait | |
1895 // | parallel for simd| taskgroup | |
1896 // | parallel for simd| flush | |
1897 // | parallel for simd| ordered | + (with simd clause) |
1898 // | parallel for simd| atomic | |
1899 // | parallel for simd| target | |
1900 // | parallel for simd| teams | |
1901 // | parallel for simd| cancellation | |
1903 // | parallel for simd| cancel | |
1904 // | parallel for simd| taskloop | |
1905 // | parallel for simd| taskloop simd | |
1906 // | parallel for simd| distribute | |
1907 // +------------------+-----------------+------------------------------------+
1908 // | sections | parallel | * |
1909 // | sections | for | + |
1910 // | sections | for simd | + |
1911 // | sections | master | + |
1912 // | sections | critical | * |
1913 // | sections | simd | * |
1914 // | sections | sections | + |
1915 // | sections | section | * |
1916 // | sections | single | + |
1917 // | sections | parallel for | * |
1918 // | sections |parallel for simd| * |
1919 // | sections |parallel sections| * |
1920 // | sections | task | * |
1921 // | sections | taskyield | * |
1922 // | sections | barrier | + |
1923 // | sections | taskwait | * |
1924 // | sections | taskgroup | * |
1925 // | sections | flush | * |
1926 // | sections | ordered | + |
1927 // | sections | atomic | * |
1928 // | sections | target | * |
1929 // | sections | teams | + |
1930 // | sections | cancellation | |
1932 // | sections | cancel | ! |
1933 // | sections | taskloop | * |
1934 // | sections | taskloop simd | * |
1935 // | sections | distribute | |
1936 // +------------------+-----------------+------------------------------------+
1937 // | section | parallel | * |
1938 // | section | for | + |
1939 // | section | for simd | + |
1940 // | section | master | + |
1941 // | section | critical | * |
1942 // | section | simd | * |
1943 // | section | sections | + |
1944 // | section | section | + |
1945 // | section | single | + |
1946 // | section | parallel for | * |
1947 // | section |parallel for simd| * |
1948 // | section |parallel sections| * |
1949 // | section | task | * |
1950 // | section | taskyield | * |
1951 // | section | barrier | + |
1952 // | section | taskwait | * |
1953 // | section | taskgroup | * |
1954 // | section | flush | * |
1955 // | section | ordered | + |
1956 // | section | atomic | * |
1957 // | section | target | * |
1958 // | section | teams | + |
1959 // | section | cancellation | |
1961 // | section | cancel | ! |
1962 // | section | taskloop | * |
1963 // | section | taskloop simd | * |
1964 // | section | distribute | |
1965 // +------------------+-----------------+------------------------------------+
1966 // | single | parallel | * |
1967 // | single | for | + |
1968 // | single | for simd | + |
1969 // | single | master | + |
1970 // | single | critical | * |
1971 // | single | simd | * |
1972 // | single | sections | + |
1973 // | single | section | + |
1974 // | single | single | + |
1975 // | single | parallel for | * |
1976 // | single |parallel for simd| * |
1977 // | single |parallel sections| * |
1978 // | single | task | * |
1979 // | single | taskyield | * |
1980 // | single | barrier | + |
1981 // | single | taskwait | * |
1982 // | single | taskgroup | * |
1983 // | single | flush | * |
1984 // | single | ordered | + |
1985 // | single | atomic | * |
1986 // | single | target | * |
1987 // | single | teams | + |
1988 // | single | cancellation | |
1990 // | single | cancel | |
1991 // | single | taskloop | * |
1992 // | single | taskloop simd | * |
1993 // | single | distribute | |
1994 // +------------------+-----------------+------------------------------------+
1995 // | parallel for | parallel | * |
1996 // | parallel for | for | + |
1997 // | parallel for | for simd | + |
1998 // | parallel for | master | + |
1999 // | parallel for | critical | * |
2000 // | parallel for | simd | * |
2001 // | parallel for | sections | + |
2002 // | parallel for | section | + |
2003 // | parallel for | single | + |
2004 // | parallel for | parallel for | * |
2005 // | parallel for |parallel for simd| * |
2006 // | parallel for |parallel sections| * |
2007 // | parallel for | task | * |
2008 // | parallel for | taskyield | * |
2009 // | parallel for | barrier | + |
2010 // | parallel for | taskwait | * |
2011 // | parallel for | taskgroup | * |
2012 // | parallel for | flush | * |
2013 // | parallel for | ordered | * (if construct is ordered) |
2014 // | parallel for | atomic | * |
2015 // | parallel for | target | * |
2016 // | parallel for | teams | + |
2017 // | parallel for | cancellation | |
2019 // | parallel for | cancel | ! |
2020 // | parallel for | taskloop | * |
2021 // | parallel for | taskloop simd | * |
2022 // | parallel for | distribute | |
2023 // +------------------+-----------------+------------------------------------+
2024 // | parallel sections| parallel | * |
2025 // | parallel sections| for | + |
2026 // | parallel sections| for simd | + |
2027 // | parallel sections| master | + |
2028 // | parallel sections| critical | + |
2029 // | parallel sections| simd | * |
2030 // | parallel sections| sections | + |
2031 // | parallel sections| section | * |
2032 // | parallel sections| single | + |
2033 // | parallel sections| parallel for | * |
2034 // | parallel sections|parallel for simd| * |
2035 // | parallel sections|parallel sections| * |
2036 // | parallel sections| task | * |
2037 // | parallel sections| taskyield | * |
2038 // | parallel sections| barrier | + |
2039 // | parallel sections| taskwait | * |
2040 // | parallel sections| taskgroup | * |
2041 // | parallel sections| flush | * |
2042 // | parallel sections| ordered | + |
2043 // | parallel sections| atomic | * |
2044 // | parallel sections| target | * |
2045 // | parallel sections| teams | + |
2046 // | parallel sections| cancellation | |
2048 // | parallel sections| cancel | ! |
2049 // | parallel sections| taskloop | * |
2050 // | parallel sections| taskloop simd | * |
2051 // | parallel sections| distribute | |
2052 // +------------------+-----------------+------------------------------------+
2053 // | task | parallel | * |
2054 // | task | for | + |
2055 // | task | for simd | + |
2056 // | task | master | + |
2057 // | task | critical | * |
2058 // | task | simd | * |
2059 // | task | sections | + |
2060 // | task | section | + |
2061 // | task | single | + |
2062 // | task | parallel for | * |
2063 // | task |parallel for simd| * |
2064 // | task |parallel sections| * |
2065 // | task | task | * |
2066 // | task | taskyield | * |
2067 // | task | barrier | + |
2068 // | task | taskwait | * |
2069 // | task | taskgroup | * |
2070 // | task | flush | * |
2071 // | task | ordered | + |
2072 // | task | atomic | * |
2073 // | task | target | * |
2074 // | task | teams | + |
2075 // | task | cancellation | |
2077 // | task | cancel | ! |
2078 // | task | taskloop | * |
2079 // | task | taskloop simd | * |
2080 // | task | distribute | |
2081 // +------------------+-----------------+------------------------------------+
2082 // | ordered | parallel | * |
2083 // | ordered | for | + |
2084 // | ordered | for simd | + |
2085 // | ordered | master | * |
2086 // | ordered | critical | * |
2087 // | ordered | simd | * |
2088 // | ordered | sections | + |
2089 // | ordered | section | + |
2090 // | ordered | single | + |
2091 // | ordered | parallel for | * |
2092 // | ordered |parallel for simd| * |
2093 // | ordered |parallel sections| * |
2094 // | ordered | task | * |
2095 // | ordered | taskyield | * |
2096 // | ordered | barrier | + |
2097 // | ordered | taskwait | * |
2098 // | ordered | taskgroup | * |
2099 // | ordered | flush | * |
2100 // | ordered | ordered | + |
2101 // | ordered | atomic | * |
2102 // | ordered | target | * |
2103 // | ordered | teams | + |
2104 // | ordered | cancellation | |
2106 // | ordered | cancel | |
2107 // | ordered | taskloop | * |
2108 // | ordered | taskloop simd | * |
2109 // | ordered | distribute | |
2110 // +------------------+-----------------+------------------------------------+
2111 // | atomic | parallel | |
2112 // | atomic | for | |
2113 // | atomic | for simd | |
2114 // | atomic | master | |
2115 // | atomic | critical | |
2116 // | atomic | simd | |
2117 // | atomic | sections | |
2118 // | atomic | section | |
2119 // | atomic | single | |
2120 // | atomic | parallel for | |
2121 // | atomic |parallel for simd| |
2122 // | atomic |parallel sections| |
2123 // | atomic | task | |
2124 // | atomic | taskyield | |
2125 // | atomic | barrier | |
2126 // | atomic | taskwait | |
2127 // | atomic | taskgroup | |
2128 // | atomic | flush | |
2129 // | atomic | ordered | |
2130 // | atomic | atomic | |
2131 // | atomic | target | |
2132 // | atomic | teams | |
2133 // | atomic | cancellation | |
2135 // | atomic | cancel | |
2136 // | atomic | taskloop | |
2137 // | atomic | taskloop simd | |
2138 // | atomic | distribute | |
2139 // +------------------+-----------------+------------------------------------+
2140 // | target | parallel | * |
2141 // | target | for | * |
2142 // | target | for simd | * |
2143 // | target | master | * |
2144 // | target | critical | * |
2145 // | target | simd | * |
2146 // | target | sections | * |
2147 // | target | section | * |
2148 // | target | single | * |
2149 // | target | parallel for | * |
2150 // | target |parallel for simd| * |
2151 // | target |parallel sections| * |
2152 // | target | task | * |
2153 // | target | taskyield | * |
2154 // | target | barrier | * |
2155 // | target | taskwait | * |
2156 // | target | taskgroup | * |
2157 // | target | flush | * |
2158 // | target | ordered | * |
2159 // | target | atomic | * |
2160 // | target | target | * |
2161 // | target | teams | * |
2162 // | target | cancellation | |
2164 // | target | cancel | |
2165 // | target | taskloop | * |
2166 // | target | taskloop simd | * |
2167 // | target | distribute | |
2168 // +------------------+-----------------+------------------------------------+
2169 // | teams | parallel | * |
2170 // | teams | for | + |
2171 // | teams | for simd | + |
2172 // | teams | master | + |
2173 // | teams | critical | + |
2174 // | teams | simd | + |
2175 // | teams | sections | + |
2176 // | teams | section | + |
2177 // | teams | single | + |
2178 // | teams | parallel for | * |
2179 // | teams |parallel for simd| * |
2180 // | teams |parallel sections| * |
2181 // | teams | task | + |
2182 // | teams | taskyield | + |
2183 // | teams | barrier | + |
2184 // | teams | taskwait | + |
2185 // | teams | taskgroup | + |
2186 // | teams | flush | + |
2187 // | teams | ordered | + |
2188 // | teams | atomic | + |
2189 // | teams | target | + |
2190 // | teams | teams | + |
2191 // | teams | cancellation | |
2193 // | teams | cancel | |
2194 // | teams | taskloop | + |
2195 // | teams | taskloop simd | + |
2196 // | teams | distribute | ! |
2197 // +------------------+-----------------+------------------------------------+
2198 // | taskloop | parallel | * |
2199 // | taskloop | for | + |
2200 // | taskloop | for simd | + |
2201 // | taskloop | master | + |
2202 // | taskloop | critical | * |
2203 // | taskloop | simd | * |
2204 // | taskloop | sections | + |
2205 // | taskloop | section | + |
2206 // | taskloop | single | + |
2207 // | taskloop | parallel for | * |
2208 // | taskloop |parallel for simd| * |
2209 // | taskloop |parallel sections| * |
2210 // | taskloop | task | * |
2211 // | taskloop | taskyield | * |
2212 // | taskloop | barrier | + |
2213 // | taskloop | taskwait | * |
2214 // | taskloop | taskgroup | * |
2215 // | taskloop | flush | * |
2216 // | taskloop | ordered | + |
2217 // | taskloop | atomic | * |
2218 // | taskloop | target | * |
2219 // | taskloop | teams | + |
2220 // | taskloop | cancellation | |
2222 // | taskloop | cancel | |
2223 // | taskloop | taskloop | * |
2224 // | taskloop | distribute | |
2225 // +------------------+-----------------+------------------------------------+
2226 // | taskloop simd | parallel | |
2227 // | taskloop simd | for | |
2228 // | taskloop simd | for simd | |
2229 // | taskloop simd | master | |
2230 // | taskloop simd | critical | |
2231 // | taskloop simd | simd | |
2232 // | taskloop simd | sections | |
2233 // | taskloop simd | section | |
2234 // | taskloop simd | single | |
2235 // | taskloop simd | parallel for | |
2236 // | taskloop simd |parallel for simd| |
2237 // | taskloop simd |parallel sections| |
2238 // | taskloop simd | task | |
2239 // | taskloop simd | taskyield | |
2240 // | taskloop simd | barrier | |
2241 // | taskloop simd | taskwait | |
2242 // | taskloop simd | taskgroup | |
2243 // | taskloop simd | flush | |
2244 // | taskloop simd | ordered | + (with simd clause) |
2245 // | taskloop simd | atomic | |
2246 // | taskloop simd | target | |
2247 // | taskloop simd | teams | |
2248 // | taskloop simd | cancellation | |
2250 // | taskloop simd | cancel | |
2251 // | taskloop simd | taskloop | |
2252 // | taskloop simd | taskloop simd | |
2253 // | taskloop simd | distribute | |
2254 // +------------------+-----------------+------------------------------------+
2255 // | distribute | parallel | * |
2256 // | distribute | for | * |
2257 // | distribute | for simd | * |
2258 // | distribute | master | * |
2259 // | distribute | critical | * |
2260 // | distribute | simd | * |
2261 // | distribute | sections | * |
2262 // | distribute | section | * |
2263 // | distribute | single | * |
2264 // | distribute | parallel for | * |
2265 // | distribute |parallel for simd| * |
2266 // | distribute |parallel sections| * |
2267 // | distribute | task | * |
2268 // | distribute | taskyield | * |
2269 // | distribute | barrier | * |
2270 // | distribute | taskwait | * |
2271 // | distribute | taskgroup | * |
2272 // | distribute | flush | * |
2273 // | distribute | ordered | + |
2274 // | distribute | atomic | * |
2275 // | distribute | target | |
2276 // | distribute | teams | |
2277 // | distribute | cancellation | + |
2279 // | distribute | cancel | + |
2280 // | distribute | taskloop | * |
2281 // | distribute | taskloop simd | * |
2282 // | distribute | distribute | |
2283 // +------------------+-----------------+------------------------------------+
2284 if (Stack->getCurScope()) {
2285 auto ParentRegion = Stack->getParentDirective();
2286 bool NestingProhibited = false;
2287 bool CloseNesting = true;
2290 ShouldBeInParallelRegion,
2291 ShouldBeInOrderedRegion,
2292 ShouldBeInTargetRegion,
2293 ShouldBeInTeamsRegion
2294 } Recommend = NoRecommend;
2295 if (isOpenMPSimdDirective(ParentRegion) && CurrentRegion != OMPD_ordered) {
2296 // OpenMP [2.16, Nesting of Regions]
2297 // OpenMP constructs may not be nested inside a simd region.
2298 // OpenMP [2.8.1,simd Construct, Restrictions]
2299 // An ordered construct with the simd clause is the only OpenMP construct
2300 // that can appear in the simd region.
2301 SemaRef.Diag(StartLoc, diag::err_omp_prohibited_region_simd);
2304 if (ParentRegion == OMPD_atomic) {
2305 // OpenMP [2.16, Nesting of Regions]
2306 // OpenMP constructs may not be nested inside an atomic region.
2307 SemaRef.Diag(StartLoc, diag::err_omp_prohibited_region_atomic);
2310 if (CurrentRegion == OMPD_section) {
2311 // OpenMP [2.7.2, sections Construct, Restrictions]
2312 // Orphaned section directives are prohibited. That is, the section
2313 // directives must appear within the sections construct and must not be
2314 // encountered elsewhere in the sections region.
2315 if (ParentRegion != OMPD_sections &&
2316 ParentRegion != OMPD_parallel_sections) {
2317 SemaRef.Diag(StartLoc, diag::err_omp_orphaned_section_directive)
2318 << (ParentRegion != OMPD_unknown)
2319 << getOpenMPDirectiveName(ParentRegion);
2324 // Allow some constructs to be orphaned (they could be used in functions,
2325 // called from OpenMP regions with the required preconditions).
2326 if (ParentRegion == OMPD_unknown)
2328 if (CurrentRegion == OMPD_cancellation_point ||
2329 CurrentRegion == OMPD_cancel) {
2330 // OpenMP [2.16, Nesting of Regions]
2331 // A cancellation point construct for which construct-type-clause is
2332 // taskgroup must be nested inside a task construct. A cancellation
2333 // point construct for which construct-type-clause is not taskgroup must
2334 // be closely nested inside an OpenMP construct that matches the type
2335 // specified in construct-type-clause.
2336 // A cancel construct for which construct-type-clause is taskgroup must be
2337 // nested inside a task construct. A cancel construct for which
2338 // construct-type-clause is not taskgroup must be closely nested inside an
2339 // OpenMP construct that matches the type specified in
2340 // construct-type-clause.
2342 !((CancelRegion == OMPD_parallel && ParentRegion == OMPD_parallel) ||
2343 (CancelRegion == OMPD_for &&
2344 (ParentRegion == OMPD_for || ParentRegion == OMPD_parallel_for)) ||
2345 (CancelRegion == OMPD_taskgroup && ParentRegion == OMPD_task) ||
2346 (CancelRegion == OMPD_sections &&
2347 (ParentRegion == OMPD_section || ParentRegion == OMPD_sections ||
2348 ParentRegion == OMPD_parallel_sections)));
2349 } else if (CurrentRegion == OMPD_master) {
2350 // OpenMP [2.16, Nesting of Regions]
2351 // A master region may not be closely nested inside a worksharing,
2352 // atomic, or explicit task region.
2353 NestingProhibited = isOpenMPWorksharingDirective(ParentRegion) ||
2354 ParentRegion == OMPD_task ||
2355 isOpenMPTaskLoopDirective(ParentRegion);
2356 } else if (CurrentRegion == OMPD_critical && CurrentName.getName()) {
2357 // OpenMP [2.16, Nesting of Regions]
2358 // A critical region may not be nested (closely or otherwise) inside a
2359 // critical region with the same name. Note that this restriction is not
2360 // sufficient to prevent deadlock.
2361 SourceLocation PreviousCriticalLoc;
2363 Stack->hasDirective([CurrentName, &PreviousCriticalLoc](
2364 OpenMPDirectiveKind K,
2365 const DeclarationNameInfo &DNI,
2368 if (K == OMPD_critical &&
2369 DNI.getName() == CurrentName.getName()) {
2370 PreviousCriticalLoc = Loc;
2375 false /* skip top directive */);
2377 SemaRef.Diag(StartLoc,
2378 diag::err_omp_prohibited_region_critical_same_name)
2379 << CurrentName.getName();
2380 if (PreviousCriticalLoc.isValid())
2381 SemaRef.Diag(PreviousCriticalLoc,
2382 diag::note_omp_previous_critical_region);
2385 } else if (CurrentRegion == OMPD_barrier) {
2386 // OpenMP [2.16, Nesting of Regions]
2387 // A barrier region may not be closely nested inside a worksharing,
2388 // explicit task, critical, ordered, atomic, or master region.
2390 isOpenMPWorksharingDirective(ParentRegion) ||
2391 ParentRegion == OMPD_task || ParentRegion == OMPD_master ||
2392 ParentRegion == OMPD_critical || ParentRegion == OMPD_ordered ||
2393 isOpenMPTaskLoopDirective(ParentRegion);
2394 } else if (isOpenMPWorksharingDirective(CurrentRegion) &&
2395 !isOpenMPParallelDirective(CurrentRegion)) {
2396 // OpenMP [2.16, Nesting of Regions]
2397 // A worksharing region may not be closely nested inside a worksharing,
2398 // explicit task, critical, ordered, atomic, or master region.
2400 isOpenMPWorksharingDirective(ParentRegion) ||
2401 ParentRegion == OMPD_task || ParentRegion == OMPD_master ||
2402 ParentRegion == OMPD_critical || ParentRegion == OMPD_ordered ||
2403 isOpenMPTaskLoopDirective(ParentRegion);
2404 Recommend = ShouldBeInParallelRegion;
2405 } else if (CurrentRegion == OMPD_ordered) {
2406 // OpenMP [2.16, Nesting of Regions]
2407 // An ordered region may not be closely nested inside a critical,
2408 // atomic, or explicit task region.
2409 // An ordered region must be closely nested inside a loop region (or
2410 // parallel loop region) with an ordered clause.
2411 // OpenMP [2.8.1,simd Construct, Restrictions]
2412 // An ordered construct with the simd clause is the only OpenMP construct
2413 // that can appear in the simd region.
2414 NestingProhibited = ParentRegion == OMPD_critical ||
2415 ParentRegion == OMPD_task ||
2416 isOpenMPTaskLoopDirective(ParentRegion) ||
2417 !(isOpenMPSimdDirective(ParentRegion) ||
2418 Stack->isParentOrderedRegion());
2419 Recommend = ShouldBeInOrderedRegion;
2420 } else if (isOpenMPTeamsDirective(CurrentRegion)) {
2421 // OpenMP [2.16, Nesting of Regions]
2422 // If specified, a teams construct must be contained within a target
2424 NestingProhibited = ParentRegion != OMPD_target;
2425 Recommend = ShouldBeInTargetRegion;
2426 Stack->setParentTeamsRegionLoc(Stack->getConstructLoc());
2428 if (!NestingProhibited && isOpenMPTeamsDirective(ParentRegion)) {
2429 // OpenMP [2.16, Nesting of Regions]
2430 // distribute, parallel, parallel sections, parallel workshare, and the
2431 // parallel loop and parallel loop SIMD constructs are the only OpenMP
2432 // constructs that can be closely nested in the teams region.
2433 NestingProhibited = !isOpenMPParallelDirective(CurrentRegion) &&
2434 !isOpenMPDistributeDirective(CurrentRegion);
2435 Recommend = ShouldBeInParallelRegion;
2437 if (!NestingProhibited && isOpenMPDistributeDirective(CurrentRegion)) {
2438 // OpenMP 4.5 [2.17 Nesting of Regions]
2439 // The region associated with the distribute construct must be strictly
2440 // nested inside a teams region
2441 NestingProhibited = !isOpenMPTeamsDirective(ParentRegion);
2442 Recommend = ShouldBeInTeamsRegion;
2444 if (NestingProhibited) {
2445 SemaRef.Diag(StartLoc, diag::err_omp_prohibited_region)
2446 << CloseNesting << getOpenMPDirectiveName(ParentRegion) << Recommend
2447 << getOpenMPDirectiveName(CurrentRegion);
2454 static bool checkIfClauses(Sema &S, OpenMPDirectiveKind Kind,
2455 ArrayRef<OMPClause *> Clauses,
2456 ArrayRef<OpenMPDirectiveKind> AllowedNameModifiers) {
2457 bool ErrorFound = false;
2458 unsigned NamedModifiersNumber = 0;
2459 SmallVector<const OMPIfClause *, OMPC_unknown + 1> FoundNameModifiers(
2461 SmallVector<SourceLocation, 4> NameModifierLoc;
2462 for (const auto *C : Clauses) {
2463 if (const auto *IC = dyn_cast_or_null<OMPIfClause>(C)) {
2464 // At most one if clause without a directive-name-modifier can appear on
2466 OpenMPDirectiveKind CurNM = IC->getNameModifier();
2467 if (FoundNameModifiers[CurNM]) {
2468 S.Diag(C->getLocStart(), diag::err_omp_more_one_clause)
2469 << getOpenMPDirectiveName(Kind) << getOpenMPClauseName(OMPC_if)
2470 << (CurNM != OMPD_unknown) << getOpenMPDirectiveName(CurNM);
2472 } else if (CurNM != OMPD_unknown) {
2473 NameModifierLoc.push_back(IC->getNameModifierLoc());
2474 ++NamedModifiersNumber;
2476 FoundNameModifiers[CurNM] = IC;
2477 if (CurNM == OMPD_unknown)
2479 // Check if the specified name modifier is allowed for the current
2481 // At most one if clause with the particular directive-name-modifier can
2482 // appear on the directive.
2483 bool MatchFound = false;
2484 for (auto NM : AllowedNameModifiers) {
2491 S.Diag(IC->getNameModifierLoc(),
2492 diag::err_omp_wrong_if_directive_name_modifier)
2493 << getOpenMPDirectiveName(CurNM) << getOpenMPDirectiveName(Kind);
2498 // If any if clause on the directive includes a directive-name-modifier then
2499 // all if clauses on the directive must include a directive-name-modifier.
2500 if (FoundNameModifiers[OMPD_unknown] && NamedModifiersNumber > 0) {
2501 if (NamedModifiersNumber == AllowedNameModifiers.size()) {
2502 S.Diag(FoundNameModifiers[OMPD_unknown]->getLocStart(),
2503 diag::err_omp_no_more_if_clause);
2506 std::string Sep(", ");
2507 unsigned AllowedCnt = 0;
2508 unsigned TotalAllowedNum =
2509 AllowedNameModifiers.size() - NamedModifiersNumber;
2510 for (unsigned Cnt = 0, End = AllowedNameModifiers.size(); Cnt < End;
2512 OpenMPDirectiveKind NM = AllowedNameModifiers[Cnt];
2513 if (!FoundNameModifiers[NM]) {
2515 Values += getOpenMPDirectiveName(NM);
2517 if (AllowedCnt + 2 == TotalAllowedNum)
2519 else if (AllowedCnt + 1 != TotalAllowedNum)
2524 S.Diag(FoundNameModifiers[OMPD_unknown]->getCondition()->getLocStart(),
2525 diag::err_omp_unnamed_if_clause)
2526 << (TotalAllowedNum > 1) << Values;
2528 for (auto Loc : NameModifierLoc) {
2529 S.Diag(Loc, diag::note_omp_previous_named_if_clause);
2536 StmtResult Sema::ActOnOpenMPExecutableDirective(
2537 OpenMPDirectiveKind Kind, const DeclarationNameInfo &DirName,
2538 OpenMPDirectiveKind CancelRegion, ArrayRef<OMPClause *> Clauses,
2539 Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc) {
2540 StmtResult Res = StmtError();
2541 if (CheckNestingOfRegions(*this, DSAStack, Kind, DirName, CancelRegion,
2545 llvm::SmallVector<OMPClause *, 8> ClausesWithImplicit;
2546 llvm::DenseMap<VarDecl *, Expr *> VarsWithInheritedDSA;
2547 bool ErrorFound = false;
2548 ClausesWithImplicit.append(Clauses.begin(), Clauses.end());
2550 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
2552 // Check default data sharing attributes for referenced variables.
2553 DSAAttrChecker DSAChecker(DSAStack, *this, cast<CapturedStmt>(AStmt));
2554 DSAChecker.Visit(cast<CapturedStmt>(AStmt)->getCapturedStmt());
2555 if (DSAChecker.isErrorFound())
2557 // Generate list of implicitly defined firstprivate variables.
2558 VarsWithInheritedDSA = DSAChecker.getVarsWithInheritedDSA();
2560 if (!DSAChecker.getImplicitFirstprivate().empty()) {
2561 if (OMPClause *Implicit = ActOnOpenMPFirstprivateClause(
2562 DSAChecker.getImplicitFirstprivate(), SourceLocation(),
2563 SourceLocation(), SourceLocation())) {
2564 ClausesWithImplicit.push_back(Implicit);
2565 ErrorFound = cast<OMPFirstprivateClause>(Implicit)->varlist_size() !=
2566 DSAChecker.getImplicitFirstprivate().size();
2572 llvm::SmallVector<OpenMPDirectiveKind, 4> AllowedNameModifiers;
2575 Res = ActOnOpenMPParallelDirective(ClausesWithImplicit, AStmt, StartLoc,
2577 AllowedNameModifiers.push_back(OMPD_parallel);
2580 Res = ActOnOpenMPSimdDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc,
2581 VarsWithInheritedDSA);
2584 Res = ActOnOpenMPForDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc,
2585 VarsWithInheritedDSA);
2588 Res = ActOnOpenMPForSimdDirective(ClausesWithImplicit, AStmt, StartLoc,
2589 EndLoc, VarsWithInheritedDSA);
2592 Res = ActOnOpenMPSectionsDirective(ClausesWithImplicit, AStmt, StartLoc,
2596 assert(ClausesWithImplicit.empty() &&
2597 "No clauses are allowed for 'omp section' directive");
2598 Res = ActOnOpenMPSectionDirective(AStmt, StartLoc, EndLoc);
2601 Res = ActOnOpenMPSingleDirective(ClausesWithImplicit, AStmt, StartLoc,
2605 assert(ClausesWithImplicit.empty() &&
2606 "No clauses are allowed for 'omp master' directive");
2607 Res = ActOnOpenMPMasterDirective(AStmt, StartLoc, EndLoc);
2610 Res = ActOnOpenMPCriticalDirective(DirName, ClausesWithImplicit, AStmt,
2613 case OMPD_parallel_for:
2614 Res = ActOnOpenMPParallelForDirective(ClausesWithImplicit, AStmt, StartLoc,
2615 EndLoc, VarsWithInheritedDSA);
2616 AllowedNameModifiers.push_back(OMPD_parallel);
2618 case OMPD_parallel_for_simd:
2619 Res = ActOnOpenMPParallelForSimdDirective(
2620 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
2621 AllowedNameModifiers.push_back(OMPD_parallel);
2623 case OMPD_parallel_sections:
2624 Res = ActOnOpenMPParallelSectionsDirective(ClausesWithImplicit, AStmt,
2626 AllowedNameModifiers.push_back(OMPD_parallel);
2630 ActOnOpenMPTaskDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc);
2631 AllowedNameModifiers.push_back(OMPD_task);
2633 case OMPD_taskyield:
2634 assert(ClausesWithImplicit.empty() &&
2635 "No clauses are allowed for 'omp taskyield' directive");
2636 assert(AStmt == nullptr &&
2637 "No associated statement allowed for 'omp taskyield' directive");
2638 Res = ActOnOpenMPTaskyieldDirective(StartLoc, EndLoc);
2641 assert(ClausesWithImplicit.empty() &&
2642 "No clauses are allowed for 'omp barrier' directive");
2643 assert(AStmt == nullptr &&
2644 "No associated statement allowed for 'omp barrier' directive");
2645 Res = ActOnOpenMPBarrierDirective(StartLoc, EndLoc);
2648 assert(ClausesWithImplicit.empty() &&
2649 "No clauses are allowed for 'omp taskwait' directive");
2650 assert(AStmt == nullptr &&
2651 "No associated statement allowed for 'omp taskwait' directive");
2652 Res = ActOnOpenMPTaskwaitDirective(StartLoc, EndLoc);
2654 case OMPD_taskgroup:
2655 assert(ClausesWithImplicit.empty() &&
2656 "No clauses are allowed for 'omp taskgroup' directive");
2657 Res = ActOnOpenMPTaskgroupDirective(AStmt, StartLoc, EndLoc);
2660 assert(AStmt == nullptr &&
2661 "No associated statement allowed for 'omp flush' directive");
2662 Res = ActOnOpenMPFlushDirective(ClausesWithImplicit, StartLoc, EndLoc);
2665 Res = ActOnOpenMPOrderedDirective(ClausesWithImplicit, AStmt, StartLoc,
2669 Res = ActOnOpenMPAtomicDirective(ClausesWithImplicit, AStmt, StartLoc,
2674 ActOnOpenMPTeamsDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc);
2677 Res = ActOnOpenMPTargetDirective(ClausesWithImplicit, AStmt, StartLoc,
2679 AllowedNameModifiers.push_back(OMPD_target);
2681 case OMPD_cancellation_point:
2682 assert(ClausesWithImplicit.empty() &&
2683 "No clauses are allowed for 'omp cancellation point' directive");
2684 assert(AStmt == nullptr && "No associated statement allowed for 'omp "
2685 "cancellation point' directive");
2686 Res = ActOnOpenMPCancellationPointDirective(StartLoc, EndLoc, CancelRegion);
2689 assert(AStmt == nullptr &&
2690 "No associated statement allowed for 'omp cancel' directive");
2691 Res = ActOnOpenMPCancelDirective(ClausesWithImplicit, StartLoc, EndLoc,
2693 AllowedNameModifiers.push_back(OMPD_cancel);
2695 case OMPD_target_data:
2696 Res = ActOnOpenMPTargetDataDirective(ClausesWithImplicit, AStmt, StartLoc,
2698 AllowedNameModifiers.push_back(OMPD_target_data);
2701 Res = ActOnOpenMPTaskLoopDirective(ClausesWithImplicit, AStmt, StartLoc,
2702 EndLoc, VarsWithInheritedDSA);
2703 AllowedNameModifiers.push_back(OMPD_taskloop);
2705 case OMPD_taskloop_simd:
2706 Res = ActOnOpenMPTaskLoopSimdDirective(ClausesWithImplicit, AStmt, StartLoc,
2707 EndLoc, VarsWithInheritedDSA);
2708 AllowedNameModifiers.push_back(OMPD_taskloop);
2710 case OMPD_distribute:
2711 Res = ActOnOpenMPDistributeDirective(ClausesWithImplicit, AStmt, StartLoc,
2712 EndLoc, VarsWithInheritedDSA);
2714 case OMPD_threadprivate:
2715 llvm_unreachable("OpenMP Directive is not allowed");
2717 llvm_unreachable("Unknown OpenMP directive");
2720 for (auto P : VarsWithInheritedDSA) {
2721 Diag(P.second->getExprLoc(), diag::err_omp_no_dsa_for_variable)
2722 << P.first << P.second->getSourceRange();
2724 ErrorFound = !VarsWithInheritedDSA.empty() || ErrorFound;
2726 if (!AllowedNameModifiers.empty())
2727 ErrorFound = checkIfClauses(*this, Kind, Clauses, AllowedNameModifiers) ||
2735 StmtResult Sema::ActOnOpenMPParallelDirective(ArrayRef<OMPClause *> Clauses,
2737 SourceLocation StartLoc,
2738 SourceLocation EndLoc) {
2742 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
2743 // 1.2.2 OpenMP Language Terminology
2744 // Structured block - An executable statement with a single entry at the
2745 // top and a single exit at the bottom.
2746 // The point of exit cannot be a branch out of the structured block.
2747 // longjmp() and throw() must not violate the entry/exit criteria.
2748 CS->getCapturedDecl()->setNothrow();
2750 getCurFunction()->setHasBranchProtectedScope();
2752 return OMPParallelDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt,
2753 DSAStack->isCancelRegion());
2757 /// \brief Helper class for checking canonical form of the OpenMP loops and
2758 /// extracting iteration space of each loop in the loop nest, that will be used
2759 /// for IR generation.
2760 class OpenMPIterationSpaceChecker {
2761 /// \brief Reference to Sema.
2763 /// \brief A location for diagnostics (when there is no some better location).
2764 SourceLocation DefaultLoc;
2765 /// \brief A location for diagnostics (when increment is not compatible).
2766 SourceLocation ConditionLoc;
2767 /// \brief A source location for referring to loop init later.
2768 SourceRange InitSrcRange;
2769 /// \brief A source location for referring to condition later.
2770 SourceRange ConditionSrcRange;
2771 /// \brief A source location for referring to increment later.
2772 SourceRange IncrementSrcRange;
2773 /// \brief Loop variable.
2775 /// \brief Reference to loop variable.
2776 DeclRefExpr *VarRef;
2777 /// \brief Lower bound (initializer for the var).
2779 /// \brief Upper bound.
2781 /// \brief Loop step (increment).
2783 /// \brief This flag is true when condition is one of:
2789 /// \brief This flag is true when condition is strict ( < or > ).
2790 bool TestIsStrictOp;
2791 /// \brief This flag is true when step is subtracted on each iteration.
2795 OpenMPIterationSpaceChecker(Sema &SemaRef, SourceLocation DefaultLoc)
2796 : SemaRef(SemaRef), DefaultLoc(DefaultLoc), ConditionLoc(DefaultLoc),
2797 InitSrcRange(SourceRange()), ConditionSrcRange(SourceRange()),
2798 IncrementSrcRange(SourceRange()), Var(nullptr), VarRef(nullptr),
2799 LB(nullptr), UB(nullptr), Step(nullptr), TestIsLessOp(false),
2800 TestIsStrictOp(false), SubtractStep(false) {}
2801 /// \brief Check init-expr for canonical loop form and save loop counter
2802 /// variable - #Var and its initialization value - #LB.
2803 bool CheckInit(Stmt *S, bool EmitDiags = true);
2804 /// \brief Check test-expr for canonical form, save upper-bound (#UB), flags
2805 /// for less/greater and for strict/non-strict comparison.
2806 bool CheckCond(Expr *S);
2807 /// \brief Check incr-expr for canonical loop form and return true if it
2808 /// does not conform, otherwise save loop step (#Step).
2809 bool CheckInc(Expr *S);
2810 /// \brief Return the loop counter variable.
2811 VarDecl *GetLoopVar() const { return Var; }
2812 /// \brief Return the reference expression to loop counter variable.
2813 DeclRefExpr *GetLoopVarRefExpr() const { return VarRef; }
2814 /// \brief Source range of the loop init.
2815 SourceRange GetInitSrcRange() const { return InitSrcRange; }
2816 /// \brief Source range of the loop condition.
2817 SourceRange GetConditionSrcRange() const { return ConditionSrcRange; }
2818 /// \brief Source range of the loop increment.
2819 SourceRange GetIncrementSrcRange() const { return IncrementSrcRange; }
2820 /// \brief True if the step should be subtracted.
2821 bool ShouldSubtractStep() const { return SubtractStep; }
2822 /// \brief Build the expression to calculate the number of iterations.
2823 Expr *BuildNumIterations(Scope *S, const bool LimitedType) const;
2824 /// \brief Build the precondition expression for the loops.
2825 Expr *BuildPreCond(Scope *S, Expr *Cond) const;
2826 /// \brief Build reference expression to the counter be used for codegen.
2827 Expr *BuildCounterVar() const;
2828 /// \brief Build reference expression to the private counter be used for
2830 Expr *BuildPrivateCounterVar() const;
2831 /// \brief Build initization of the counter be used for codegen.
2832 Expr *BuildCounterInit() const;
2833 /// \brief Build step of the counter be used for codegen.
2834 Expr *BuildCounterStep() const;
2835 /// \brief Return true if any expression is dependent.
2836 bool Dependent() const;
2839 /// \brief Check the right-hand side of an assignment in the increment
2841 bool CheckIncRHS(Expr *RHS);
2842 /// \brief Helper to set loop counter variable and its initializer.
2843 bool SetVarAndLB(VarDecl *NewVar, DeclRefExpr *NewVarRefExpr, Expr *NewLB);
2844 /// \brief Helper to set upper bound.
2845 bool SetUB(Expr *NewUB, bool LessOp, bool StrictOp, SourceRange SR,
2847 /// \brief Helper to set loop increment.
2848 bool SetStep(Expr *NewStep, bool Subtract);
2851 bool OpenMPIterationSpaceChecker::Dependent() const {
2853 assert(!LB && !UB && !Step);
2856 return Var->getType()->isDependentType() || (LB && LB->isValueDependent()) ||
2857 (UB && UB->isValueDependent()) || (Step && Step->isValueDependent());
2860 template <typename T>
2861 static T *getExprAsWritten(T *E) {
2862 if (auto *ExprTemp = dyn_cast<ExprWithCleanups>(E))
2863 E = ExprTemp->getSubExpr();
2865 if (auto *MTE = dyn_cast<MaterializeTemporaryExpr>(E))
2866 E = MTE->GetTemporaryExpr();
2868 while (auto *Binder = dyn_cast<CXXBindTemporaryExpr>(E))
2869 E = Binder->getSubExpr();
2871 if (auto *ICE = dyn_cast<ImplicitCastExpr>(E))
2872 E = ICE->getSubExprAsWritten();
2873 return E->IgnoreParens();
2876 bool OpenMPIterationSpaceChecker::SetVarAndLB(VarDecl *NewVar,
2877 DeclRefExpr *NewVarRefExpr,
2879 // State consistency checking to ensure correct usage.
2880 assert(Var == nullptr && LB == nullptr && VarRef == nullptr &&
2881 UB == nullptr && Step == nullptr && !TestIsLessOp && !TestIsStrictOp);
2882 if (!NewVar || !NewLB)
2885 VarRef = NewVarRefExpr;
2886 if (auto *CE = dyn_cast_or_null<CXXConstructExpr>(NewLB))
2887 if (const CXXConstructorDecl *Ctor = CE->getConstructor())
2888 if ((Ctor->isCopyOrMoveConstructor() ||
2889 Ctor->isConvertingConstructor(/*AllowExplicit=*/false)) &&
2890 CE->getNumArgs() > 0 && CE->getArg(0) != nullptr)
2891 NewLB = CE->getArg(0)->IgnoreParenImpCasts();
2896 bool OpenMPIterationSpaceChecker::SetUB(Expr *NewUB, bool LessOp, bool StrictOp,
2897 SourceRange SR, SourceLocation SL) {
2898 // State consistency checking to ensure correct usage.
2899 assert(Var != nullptr && LB != nullptr && UB == nullptr && Step == nullptr &&
2900 !TestIsLessOp && !TestIsStrictOp);
2904 TestIsLessOp = LessOp;
2905 TestIsStrictOp = StrictOp;
2906 ConditionSrcRange = SR;
2911 bool OpenMPIterationSpaceChecker::SetStep(Expr *NewStep, bool Subtract) {
2912 // State consistency checking to ensure correct usage.
2913 assert(Var != nullptr && LB != nullptr && Step == nullptr);
2916 if (!NewStep->isValueDependent()) {
2917 // Check that the step is integer expression.
2918 SourceLocation StepLoc = NewStep->getLocStart();
2920 SemaRef.PerformOpenMPImplicitIntegerConversion(StepLoc, NewStep);
2921 if (Val.isInvalid())
2923 NewStep = Val.get();
2925 // OpenMP [2.6, Canonical Loop Form, Restrictions]
2926 // If test-expr is of form var relational-op b and relational-op is < or
2927 // <= then incr-expr must cause var to increase on each iteration of the
2928 // loop. If test-expr is of form var relational-op b and relational-op is
2929 // > or >= then incr-expr must cause var to decrease on each iteration of
2931 // If test-expr is of form b relational-op var and relational-op is < or
2932 // <= then incr-expr must cause var to decrease on each iteration of the
2933 // loop. If test-expr is of form b relational-op var and relational-op is
2934 // > or >= then incr-expr must cause var to increase on each iteration of
2936 llvm::APSInt Result;
2937 bool IsConstant = NewStep->isIntegerConstantExpr(Result, SemaRef.Context);
2938 bool IsUnsigned = !NewStep->getType()->hasSignedIntegerRepresentation();
2940 IsConstant && Result.isSigned() && (Subtract != Result.isNegative());
2942 IsConstant && Result.isSigned() && (Subtract == Result.isNegative());
2943 bool IsConstZero = IsConstant && !Result.getBoolValue();
2944 if (UB && (IsConstZero ||
2945 (TestIsLessOp ? (IsConstNeg || (IsUnsigned && Subtract))
2946 : (IsConstPos || (IsUnsigned && !Subtract))))) {
2947 SemaRef.Diag(NewStep->getExprLoc(),
2948 diag::err_omp_loop_incr_not_compatible)
2949 << Var << TestIsLessOp << NewStep->getSourceRange();
2950 SemaRef.Diag(ConditionLoc,
2951 diag::note_omp_loop_cond_requres_compatible_incr)
2952 << TestIsLessOp << ConditionSrcRange;
2955 if (TestIsLessOp == Subtract) {
2956 NewStep = SemaRef.CreateBuiltinUnaryOp(NewStep->getExprLoc(), UO_Minus,
2958 Subtract = !Subtract;
2963 SubtractStep = Subtract;
2967 bool OpenMPIterationSpaceChecker::CheckInit(Stmt *S, bool EmitDiags) {
2968 // Check init-expr for canonical loop form and save loop counter
2969 // variable - #Var and its initialization value - #LB.
2970 // OpenMP [2.6] Canonical loop form. init-expr may be one of the following:
2972 // integer-type var = lb
2973 // random-access-iterator-type var = lb
2974 // pointer-type var = lb
2978 SemaRef.Diag(DefaultLoc, diag::err_omp_loop_not_canonical_init);
2982 InitSrcRange = S->getSourceRange();
2983 if (Expr *E = dyn_cast<Expr>(S))
2984 S = E->IgnoreParens();
2985 if (auto BO = dyn_cast<BinaryOperator>(S)) {
2986 if (BO->getOpcode() == BO_Assign)
2987 if (auto DRE = dyn_cast<DeclRefExpr>(BO->getLHS()->IgnoreParens()))
2988 return SetVarAndLB(dyn_cast<VarDecl>(DRE->getDecl()), DRE,
2990 } else if (auto DS = dyn_cast<DeclStmt>(S)) {
2991 if (DS->isSingleDecl()) {
2992 if (auto Var = dyn_cast_or_null<VarDecl>(DS->getSingleDecl())) {
2993 if (Var->hasInit() && !Var->getType()->isReferenceType()) {
2994 // Accept non-canonical init form here but emit ext. warning.
2995 if (Var->getInitStyle() != VarDecl::CInit && EmitDiags)
2996 SemaRef.Diag(S->getLocStart(),
2997 diag::ext_omp_loop_not_canonical_init)
2998 << S->getSourceRange();
2999 return SetVarAndLB(Var, nullptr, Var->getInit());
3003 } else if (auto CE = dyn_cast<CXXOperatorCallExpr>(S))
3004 if (CE->getOperator() == OO_Equal)
3005 if (auto DRE = dyn_cast<DeclRefExpr>(CE->getArg(0)))
3006 return SetVarAndLB(dyn_cast<VarDecl>(DRE->getDecl()), DRE,
3010 SemaRef.Diag(S->getLocStart(), diag::err_omp_loop_not_canonical_init)
3011 << S->getSourceRange();
3016 /// \brief Ignore parenthesizes, implicit casts, copy constructor and return the
3017 /// variable (which may be the loop variable) if possible.
3018 static const VarDecl *GetInitVarDecl(const Expr *E) {
3021 E = getExprAsWritten(E);
3022 if (auto *CE = dyn_cast_or_null<CXXConstructExpr>(E))
3023 if (const CXXConstructorDecl *Ctor = CE->getConstructor())
3024 if ((Ctor->isCopyOrMoveConstructor() ||
3025 Ctor->isConvertingConstructor(/*AllowExplicit=*/false)) &&
3026 CE->getNumArgs() > 0 && CE->getArg(0) != nullptr)
3027 E = CE->getArg(0)->IgnoreParenImpCasts();
3028 auto DRE = dyn_cast_or_null<DeclRefExpr>(E);
3031 return dyn_cast<VarDecl>(DRE->getDecl());
3034 bool OpenMPIterationSpaceChecker::CheckCond(Expr *S) {
3035 // Check test-expr for canonical form, save upper-bound UB, flags for
3036 // less/greater and for strict/non-strict comparison.
3037 // OpenMP [2.6] Canonical loop form. Test-expr may be one of the following:
3038 // var relational-op b
3039 // b relational-op var
3042 SemaRef.Diag(DefaultLoc, diag::err_omp_loop_not_canonical_cond) << Var;
3045 S = getExprAsWritten(S);
3046 SourceLocation CondLoc = S->getLocStart();
3047 if (auto BO = dyn_cast<BinaryOperator>(S)) {
3048 if (BO->isRelationalOp()) {
3049 if (GetInitVarDecl(BO->getLHS()) == Var)
3050 return SetUB(BO->getRHS(),
3051 (BO->getOpcode() == BO_LT || BO->getOpcode() == BO_LE),
3052 (BO->getOpcode() == BO_LT || BO->getOpcode() == BO_GT),
3053 BO->getSourceRange(), BO->getOperatorLoc());
3054 if (GetInitVarDecl(BO->getRHS()) == Var)
3055 return SetUB(BO->getLHS(),
3056 (BO->getOpcode() == BO_GT || BO->getOpcode() == BO_GE),
3057 (BO->getOpcode() == BO_LT || BO->getOpcode() == BO_GT),
3058 BO->getSourceRange(), BO->getOperatorLoc());
3060 } else if (auto CE = dyn_cast<CXXOperatorCallExpr>(S)) {
3061 if (CE->getNumArgs() == 2) {
3062 auto Op = CE->getOperator();
3065 case OO_GreaterEqual:
3068 if (GetInitVarDecl(CE->getArg(0)) == Var)
3069 return SetUB(CE->getArg(1), Op == OO_Less || Op == OO_LessEqual,
3070 Op == OO_Less || Op == OO_Greater, CE->getSourceRange(),
3071 CE->getOperatorLoc());
3072 if (GetInitVarDecl(CE->getArg(1)) == Var)
3073 return SetUB(CE->getArg(0), Op == OO_Greater || Op == OO_GreaterEqual,
3074 Op == OO_Less || Op == OO_Greater, CE->getSourceRange(),
3075 CE->getOperatorLoc());
3082 SemaRef.Diag(CondLoc, diag::err_omp_loop_not_canonical_cond)
3083 << S->getSourceRange() << Var;
3087 bool OpenMPIterationSpaceChecker::CheckIncRHS(Expr *RHS) {
3088 // RHS of canonical loop form increment can be:
3093 RHS = RHS->IgnoreParenImpCasts();
3094 if (auto BO = dyn_cast<BinaryOperator>(RHS)) {
3095 if (BO->isAdditiveOp()) {
3096 bool IsAdd = BO->getOpcode() == BO_Add;
3097 if (GetInitVarDecl(BO->getLHS()) == Var)
3098 return SetStep(BO->getRHS(), !IsAdd);
3099 if (IsAdd && GetInitVarDecl(BO->getRHS()) == Var)
3100 return SetStep(BO->getLHS(), false);
3102 } else if (auto CE = dyn_cast<CXXOperatorCallExpr>(RHS)) {
3103 bool IsAdd = CE->getOperator() == OO_Plus;
3104 if ((IsAdd || CE->getOperator() == OO_Minus) && CE->getNumArgs() == 2) {
3105 if (GetInitVarDecl(CE->getArg(0)) == Var)
3106 return SetStep(CE->getArg(1), !IsAdd);
3107 if (IsAdd && GetInitVarDecl(CE->getArg(1)) == Var)
3108 return SetStep(CE->getArg(0), false);
3111 SemaRef.Diag(RHS->getLocStart(), diag::err_omp_loop_not_canonical_incr)
3112 << RHS->getSourceRange() << Var;
3116 bool OpenMPIterationSpaceChecker::CheckInc(Expr *S) {
3117 // Check incr-expr for canonical loop form and return true if it
3118 // does not conform.
3119 // OpenMP [2.6] Canonical loop form. Test-expr may be one of the following:
3131 SemaRef.Diag(DefaultLoc, diag::err_omp_loop_not_canonical_incr) << Var;
3134 IncrementSrcRange = S->getSourceRange();
3135 S = S->IgnoreParens();
3136 if (auto UO = dyn_cast<UnaryOperator>(S)) {
3137 if (UO->isIncrementDecrementOp() && GetInitVarDecl(UO->getSubExpr()) == Var)
3139 SemaRef.ActOnIntegerConstant(UO->getLocStart(),
3140 (UO->isDecrementOp() ? -1 : 1)).get(),
3142 } else if (auto BO = dyn_cast<BinaryOperator>(S)) {
3143 switch (BO->getOpcode()) {
3146 if (GetInitVarDecl(BO->getLHS()) == Var)
3147 return SetStep(BO->getRHS(), BO->getOpcode() == BO_SubAssign);
3150 if (GetInitVarDecl(BO->getLHS()) == Var)
3151 return CheckIncRHS(BO->getRHS());
3156 } else if (auto CE = dyn_cast<CXXOperatorCallExpr>(S)) {
3157 switch (CE->getOperator()) {
3160 if (GetInitVarDecl(CE->getArg(0)) == Var)
3162 SemaRef.ActOnIntegerConstant(
3164 ((CE->getOperator() == OO_MinusMinus) ? -1 : 1)).get(),
3169 if (GetInitVarDecl(CE->getArg(0)) == Var)
3170 return SetStep(CE->getArg(1), CE->getOperator() == OO_MinusEqual);
3173 if (GetInitVarDecl(CE->getArg(0)) == Var)
3174 return CheckIncRHS(CE->getArg(1));
3180 SemaRef.Diag(S->getLocStart(), diag::err_omp_loop_not_canonical_incr)
3181 << S->getSourceRange() << Var;
3186 // Transform variables declared in GNU statement expressions to new ones to
3187 // avoid crash on codegen.
3188 class TransformToNewDefs : public TreeTransform<TransformToNewDefs> {
3189 typedef TreeTransform<TransformToNewDefs> BaseTransform;
3192 TransformToNewDefs(Sema &SemaRef) : BaseTransform(SemaRef) {}
3194 Decl *TransformDefinition(SourceLocation Loc, Decl *D) {
3195 if (auto *VD = cast<VarDecl>(D))
3196 if (!isa<ParmVarDecl>(D) && !isa<VarTemplateSpecializationDecl>(D) &&
3197 !isa<ImplicitParamDecl>(D)) {
3198 auto *NewVD = VarDecl::Create(
3199 SemaRef.Context, VD->getDeclContext(), VD->getLocStart(),
3200 VD->getLocation(), VD->getIdentifier(), VD->getType(),
3201 VD->getTypeSourceInfo(), VD->getStorageClass());
3202 NewVD->setTSCSpec(VD->getTSCSpec());
3203 NewVD->setInit(VD->getInit());
3204 NewVD->setInitStyle(VD->getInitStyle());
3205 NewVD->setExceptionVariable(VD->isExceptionVariable());
3206 NewVD->setNRVOVariable(VD->isNRVOVariable());
3207 NewVD->setCXXForRangeDecl(VD->isInExternCXXContext());
3208 NewVD->setConstexpr(VD->isConstexpr());
3209 NewVD->setInitCapture(VD->isInitCapture());
3210 NewVD->setPreviousDeclInSameBlockScope(
3211 VD->isPreviousDeclInSameBlockScope());
3212 VD->getDeclContext()->addHiddenDecl(NewVD);
3214 NewVD->setAttrs(VD->getAttrs());
3215 transformedLocalDecl(VD, NewVD);
3218 return BaseTransform::TransformDefinition(Loc, D);
3221 ExprResult TransformDeclRefExpr(DeclRefExpr *E) {
3222 if (auto *NewD = TransformDecl(E->getExprLoc(), E->getDecl()))
3223 if (E->getDecl() != NewD) {
3224 NewD->setReferenced();
3225 NewD->markUsed(SemaRef.Context);
3226 return DeclRefExpr::Create(
3227 SemaRef.Context, E->getQualifierLoc(), E->getTemplateKeywordLoc(),
3228 cast<ValueDecl>(NewD), E->refersToEnclosingVariableOrCapture(),
3229 E->getNameInfo(), E->getType(), E->getValueKind());
3231 return BaseTransform::TransformDeclRefExpr(E);
3236 /// \brief Build the expression to calculate the number of iterations.
3238 OpenMPIterationSpaceChecker::BuildNumIterations(Scope *S,
3239 const bool LimitedType) const {
3240 TransformToNewDefs Transform(SemaRef);
3242 auto VarType = Var->getType().getNonReferenceType();
3243 if (VarType->isIntegerType() || VarType->isPointerType() ||
3244 SemaRef.getLangOpts().CPlusPlus) {
3246 auto *UBExpr = TestIsLessOp ? UB : LB;
3247 auto *LBExpr = TestIsLessOp ? LB : UB;
3248 Expr *Upper = Transform.TransformExpr(UBExpr).get();
3249 Expr *Lower = Transform.TransformExpr(LBExpr).get();
3250 if (!Upper || !Lower)
3252 Upper = SemaRef.PerformImplicitConversion(Upper, UBExpr->getType(),
3253 Sema::AA_Converting,
3254 /*AllowExplicit=*/true)
3256 Lower = SemaRef.PerformImplicitConversion(Lower, LBExpr->getType(),
3257 Sema::AA_Converting,
3258 /*AllowExplicit=*/true)
3260 if (!Upper || !Lower)
3263 Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Sub, Upper, Lower);
3265 if (!Diff.isUsable() && VarType->getAsCXXRecordDecl()) {
3266 // BuildBinOp already emitted error, this one is to point user to upper
3267 // and lower bound, and to tell what is passed to 'operator-'.
3268 SemaRef.Diag(Upper->getLocStart(), diag::err_omp_loop_diff_cxx)
3269 << Upper->getSourceRange() << Lower->getSourceRange();
3274 if (!Diff.isUsable())
3277 // Upper - Lower [- 1]
3279 Diff = SemaRef.BuildBinOp(
3280 S, DefaultLoc, BO_Sub, Diff.get(),
3281 SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get());
3282 if (!Diff.isUsable())
3285 // Upper - Lower [- 1] + Step
3286 auto NewStep = Transform.TransformExpr(Step->IgnoreImplicit());
3287 if (NewStep.isInvalid())
3289 NewStep = SemaRef.PerformImplicitConversion(
3290 NewStep.get(), Step->IgnoreImplicit()->getType(), Sema::AA_Converting,
3291 /*AllowExplicit=*/true);
3292 if (NewStep.isInvalid())
3294 Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Add, Diff.get(), NewStep.get());
3295 if (!Diff.isUsable())
3298 // Parentheses (for dumping/debugging purposes only).
3299 Diff = SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, Diff.get());
3300 if (!Diff.isUsable())
3303 // (Upper - Lower [- 1] + Step) / Step
3304 NewStep = Transform.TransformExpr(Step->IgnoreImplicit());
3305 if (NewStep.isInvalid())
3307 NewStep = SemaRef.PerformImplicitConversion(
3308 NewStep.get(), Step->IgnoreImplicit()->getType(), Sema::AA_Converting,
3309 /*AllowExplicit=*/true);
3310 if (NewStep.isInvalid())
3312 Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Div, Diff.get(), NewStep.get());
3313 if (!Diff.isUsable())
3316 // OpenMP runtime requires 32-bit or 64-bit loop variables.
3317 QualType Type = Diff.get()->getType();
3318 auto &C = SemaRef.Context;
3319 bool UseVarType = VarType->hasIntegerRepresentation() &&
3320 C.getTypeSize(Type) > C.getTypeSize(VarType);
3321 if (!Type->isIntegerType() || UseVarType) {
3323 UseVarType ? C.getTypeSize(VarType) : C.getTypeSize(Type);
3324 bool IsSigned = UseVarType ? VarType->hasSignedIntegerRepresentation()
3325 : Type->hasSignedIntegerRepresentation();
3326 Type = C.getIntTypeForBitwidth(NewSize, IsSigned);
3327 Diff = SemaRef.PerformImplicitConversion(
3328 Diff.get(), Type, Sema::AA_Converting, /*AllowExplicit=*/true);
3329 if (!Diff.isUsable())
3333 unsigned NewSize = (C.getTypeSize(Type) > 32) ? 64 : 32;
3334 if (NewSize != C.getTypeSize(Type)) {
3335 if (NewSize < C.getTypeSize(Type)) {
3336 assert(NewSize == 64 && "incorrect loop var size");
3337 SemaRef.Diag(DefaultLoc, diag::warn_omp_loop_64_bit_var)
3338 << InitSrcRange << ConditionSrcRange;
3340 QualType NewType = C.getIntTypeForBitwidth(
3341 NewSize, Type->hasSignedIntegerRepresentation() ||
3342 C.getTypeSize(Type) < NewSize);
3343 Diff = SemaRef.PerformImplicitConversion(Diff.get(), NewType,
3344 Sema::AA_Converting, true);
3345 if (!Diff.isUsable())
3353 Expr *OpenMPIterationSpaceChecker::BuildPreCond(Scope *S, Expr *Cond) const {
3354 // Try to build LB <op> UB, where <op> is <, >, <=, or >=.
3355 bool Suppress = SemaRef.getDiagnostics().getSuppressAllDiagnostics();
3356 SemaRef.getDiagnostics().setSuppressAllDiagnostics(/*Val=*/true);
3357 TransformToNewDefs Transform(SemaRef);
3359 auto NewLB = Transform.TransformExpr(LB);
3360 auto NewUB = Transform.TransformExpr(UB);
3361 if (NewLB.isInvalid() || NewUB.isInvalid())
3363 NewLB = SemaRef.PerformImplicitConversion(NewLB.get(), LB->getType(),
3364 Sema::AA_Converting,
3365 /*AllowExplicit=*/true);
3366 NewUB = SemaRef.PerformImplicitConversion(NewUB.get(), UB->getType(),
3367 Sema::AA_Converting,
3368 /*AllowExplicit=*/true);
3369 if (NewLB.isInvalid() || NewUB.isInvalid())
3371 auto CondExpr = SemaRef.BuildBinOp(
3372 S, DefaultLoc, TestIsLessOp ? (TestIsStrictOp ? BO_LT : BO_LE)
3373 : (TestIsStrictOp ? BO_GT : BO_GE),
3374 NewLB.get(), NewUB.get());
3375 if (CondExpr.isUsable()) {
3376 CondExpr = SemaRef.PerformImplicitConversion(
3377 CondExpr.get(), SemaRef.Context.BoolTy, /*Action=*/Sema::AA_Casting,
3378 /*AllowExplicit=*/true);
3380 SemaRef.getDiagnostics().setSuppressAllDiagnostics(Suppress);
3381 // Otherwise use original loop conditon and evaluate it in runtime.
3382 return CondExpr.isUsable() ? CondExpr.get() : Cond;
3385 /// \brief Build reference expression to the counter be used for codegen.
3386 Expr *OpenMPIterationSpaceChecker::BuildCounterVar() const {
3387 return buildDeclRefExpr(SemaRef, Var, Var->getType().getNonReferenceType(),
3391 Expr *OpenMPIterationSpaceChecker::BuildPrivateCounterVar() const {
3392 if (Var && !Var->isInvalidDecl()) {
3393 auto Type = Var->getType().getNonReferenceType();
3395 buildVarDecl(SemaRef, DefaultLoc, Type, Var->getName(),
3396 Var->hasAttrs() ? &Var->getAttrs() : nullptr);
3397 if (PrivateVar->isInvalidDecl())
3399 return buildDeclRefExpr(SemaRef, PrivateVar, Type, DefaultLoc);
3404 /// \brief Build initization of the counter be used for codegen.
3405 Expr *OpenMPIterationSpaceChecker::BuildCounterInit() const { return LB; }
3407 /// \brief Build step of the counter be used for codegen.
3408 Expr *OpenMPIterationSpaceChecker::BuildCounterStep() const { return Step; }
3410 /// \brief Iteration space of a single for loop.
3411 struct LoopIterationSpace {
3412 /// \brief Condition of the loop.
3414 /// \brief This expression calculates the number of iterations in the loop.
3415 /// It is always possible to calculate it before starting the loop.
3416 Expr *NumIterations;
3417 /// \brief The loop counter variable.
3419 /// \brief Private loop counter variable.
3420 Expr *PrivateCounterVar;
3421 /// \brief This is initializer for the initial value of #CounterVar.
3423 /// \brief This is step for the #CounterVar used to generate its update:
3424 /// #CounterVar = #CounterInit + #CounterStep * CurrentIteration.
3426 /// \brief Should step be subtracted?
3428 /// \brief Source range of the loop init.
3429 SourceRange InitSrcRange;
3430 /// \brief Source range of the loop condition.
3431 SourceRange CondSrcRange;
3432 /// \brief Source range of the loop increment.
3433 SourceRange IncSrcRange;
3438 void Sema::ActOnOpenMPLoopInitialization(SourceLocation ForLoc, Stmt *Init) {
3439 assert(getLangOpts().OpenMP && "OpenMP is not active.");
3440 assert(Init && "Expected loop in canonical form.");
3441 unsigned AssociatedLoops = DSAStack->getAssociatedLoops();
3442 if (AssociatedLoops > 0 &&
3443 isOpenMPLoopDirective(DSAStack->getCurrentDirective())) {
3444 OpenMPIterationSpaceChecker ISC(*this, ForLoc);
3445 if (!ISC.CheckInit(Init, /*EmitDiags=*/false))
3446 DSAStack->addLoopControlVariable(ISC.GetLoopVar());
3447 DSAStack->setAssociatedLoops(AssociatedLoops - 1);
3451 /// \brief Called on a for stmt to check and extract its iteration space
3452 /// for further processing (such as collapsing).
3453 static bool CheckOpenMPIterationSpace(
3454 OpenMPDirectiveKind DKind, Stmt *S, Sema &SemaRef, DSAStackTy &DSA,
3455 unsigned CurrentNestedLoopCount, unsigned NestedLoopCount,
3456 Expr *CollapseLoopCountExpr, Expr *OrderedLoopCountExpr,
3457 llvm::DenseMap<VarDecl *, Expr *> &VarsWithImplicitDSA,
3458 LoopIterationSpace &ResultIterSpace) {
3459 // OpenMP [2.6, Canonical Loop Form]
3460 // for (init-expr; test-expr; incr-expr) structured-block
3461 auto For = dyn_cast_or_null<ForStmt>(S);
3463 SemaRef.Diag(S->getLocStart(), diag::err_omp_not_for)
3464 << (CollapseLoopCountExpr != nullptr || OrderedLoopCountExpr != nullptr)
3465 << getOpenMPDirectiveName(DKind) << NestedLoopCount
3466 << (CurrentNestedLoopCount > 0) << CurrentNestedLoopCount;
3467 if (NestedLoopCount > 1) {
3468 if (CollapseLoopCountExpr && OrderedLoopCountExpr)
3469 SemaRef.Diag(DSA.getConstructLoc(),
3470 diag::note_omp_collapse_ordered_expr)
3471 << 2 << CollapseLoopCountExpr->getSourceRange()
3472 << OrderedLoopCountExpr->getSourceRange();
3473 else if (CollapseLoopCountExpr)
3474 SemaRef.Diag(CollapseLoopCountExpr->getExprLoc(),
3475 diag::note_omp_collapse_ordered_expr)
3476 << 0 << CollapseLoopCountExpr->getSourceRange();
3478 SemaRef.Diag(OrderedLoopCountExpr->getExprLoc(),
3479 diag::note_omp_collapse_ordered_expr)
3480 << 1 << OrderedLoopCountExpr->getSourceRange();
3484 assert(For->getBody());
3486 OpenMPIterationSpaceChecker ISC(SemaRef, For->getForLoc());
3489 auto Init = For->getInit();
3490 if (ISC.CheckInit(Init)) {
3494 bool HasErrors = false;
3496 // Check loop variable's type.
3497 auto Var = ISC.GetLoopVar();
3499 // OpenMP [2.6, Canonical Loop Form]
3500 // Var is one of the following:
3501 // A variable of signed or unsigned integer type.
3502 // For C++, a variable of a random access iterator type.
3503 // For C, a variable of a pointer type.
3504 auto VarType = Var->getType().getNonReferenceType();
3505 if (!VarType->isDependentType() && !VarType->isIntegerType() &&
3506 !VarType->isPointerType() &&
3507 !(SemaRef.getLangOpts().CPlusPlus && VarType->isOverloadableType())) {
3508 SemaRef.Diag(Init->getLocStart(), diag::err_omp_loop_variable_type)
3509 << SemaRef.getLangOpts().CPlusPlus;
3513 // OpenMP, 2.14.1.1 Data-sharing Attribute Rules for Variables Referenced in a
3515 // The loop iteration variable(s) in the associated for-loop(s) of a for or
3516 // parallel for construct is (are) private.
3517 // The loop iteration variable in the associated for-loop of a simd construct
3518 // with just one associated for-loop is linear with a constant-linear-step
3519 // that is the increment of the associated for-loop.
3520 // Exclude loop var from the list of variables with implicitly defined data
3521 // sharing attributes.
3522 VarsWithImplicitDSA.erase(Var);
3524 // OpenMP [2.14.1.1, Data-sharing Attribute Rules for Variables Referenced in
3525 // a Construct, C/C++].
3526 // The loop iteration variable in the associated for-loop of a simd construct
3527 // with just one associated for-loop may be listed in a linear clause with a
3528 // constant-linear-step that is the increment of the associated for-loop.
3529 // The loop iteration variable(s) in the associated for-loop(s) of a for or
3530 // parallel for construct may be listed in a private or lastprivate clause.
3531 DSAStackTy::DSAVarData DVar = DSA.getTopDSA(Var, false);
3532 auto LoopVarRefExpr = ISC.GetLoopVarRefExpr();
3533 // If LoopVarRefExpr is nullptr it means the corresponding loop variable is
3534 // declared in the loop and it is predetermined as a private.
3535 auto PredeterminedCKind =
3536 isOpenMPSimdDirective(DKind)
3537 ? ((NestedLoopCount == 1) ? OMPC_linear : OMPC_lastprivate)
3539 if (((isOpenMPSimdDirective(DKind) && DVar.CKind != OMPC_unknown &&
3540 DVar.CKind != PredeterminedCKind) ||
3541 ((isOpenMPWorksharingDirective(DKind) || DKind == OMPD_taskloop ||
3542 isOpenMPDistributeDirective(DKind)) &&
3543 !isOpenMPSimdDirective(DKind) && DVar.CKind != OMPC_unknown &&
3544 DVar.CKind != OMPC_private && DVar.CKind != OMPC_lastprivate)) &&
3545 (DVar.CKind != OMPC_private || DVar.RefExpr != nullptr)) {
3546 SemaRef.Diag(Init->getLocStart(), diag::err_omp_loop_var_dsa)
3547 << getOpenMPClauseName(DVar.CKind) << getOpenMPDirectiveName(DKind)
3548 << getOpenMPClauseName(PredeterminedCKind);
3549 if (DVar.RefExpr == nullptr)
3550 DVar.CKind = PredeterminedCKind;
3551 ReportOriginalDSA(SemaRef, &DSA, Var, DVar, /*IsLoopIterVar=*/true);
3553 } else if (LoopVarRefExpr != nullptr) {
3554 // Make the loop iteration variable private (for worksharing constructs),
3555 // linear (for simd directives with the only one associated loop) or
3556 // lastprivate (for simd directives with several collapsed or ordered
3558 if (DVar.CKind == OMPC_unknown)
3559 DVar = DSA.hasDSA(Var, isOpenMPPrivate, MatchesAlways(),
3560 /*FromParent=*/false);
3561 DSA.addDSA(Var, LoopVarRefExpr, PredeterminedCKind);
3564 assert(isOpenMPLoopDirective(DKind) && "DSA for non-loop vars");
3567 HasErrors |= ISC.CheckCond(For->getCond());
3570 HasErrors |= ISC.CheckInc(For->getInc());
3572 if (ISC.Dependent() || SemaRef.CurContext->isDependentContext() || HasErrors)
3575 // Build the loop's iteration space representation.
3576 ResultIterSpace.PreCond = ISC.BuildPreCond(DSA.getCurScope(), For->getCond());
3577 ResultIterSpace.NumIterations = ISC.BuildNumIterations(
3578 DSA.getCurScope(), (isOpenMPWorksharingDirective(DKind) ||
3579 isOpenMPTaskLoopDirective(DKind) ||
3580 isOpenMPDistributeDirective(DKind)));
3581 ResultIterSpace.CounterVar = ISC.BuildCounterVar();
3582 ResultIterSpace.PrivateCounterVar = ISC.BuildPrivateCounterVar();
3583 ResultIterSpace.CounterInit = ISC.BuildCounterInit();
3584 ResultIterSpace.CounterStep = ISC.BuildCounterStep();
3585 ResultIterSpace.InitSrcRange = ISC.GetInitSrcRange();
3586 ResultIterSpace.CondSrcRange = ISC.GetConditionSrcRange();
3587 ResultIterSpace.IncSrcRange = ISC.GetIncrementSrcRange();
3588 ResultIterSpace.Subtract = ISC.ShouldSubtractStep();
3590 HasErrors |= (ResultIterSpace.PreCond == nullptr ||
3591 ResultIterSpace.NumIterations == nullptr ||
3592 ResultIterSpace.CounterVar == nullptr ||
3593 ResultIterSpace.PrivateCounterVar == nullptr ||
3594 ResultIterSpace.CounterInit == nullptr ||
3595 ResultIterSpace.CounterStep == nullptr);
3600 /// \brief Build 'VarRef = Start.
3601 static ExprResult BuildCounterInit(Sema &SemaRef, Scope *S, SourceLocation Loc,
3602 ExprResult VarRef, ExprResult Start) {
3603 TransformToNewDefs Transform(SemaRef);
3604 // Build 'VarRef = Start.
3605 auto NewStart = Transform.TransformExpr(Start.get()->IgnoreImplicit());
3606 if (NewStart.isInvalid())
3608 NewStart = SemaRef.PerformImplicitConversion(
3609 NewStart.get(), Start.get()->IgnoreImplicit()->getType(),
3610 Sema::AA_Converting,
3611 /*AllowExplicit=*/true);
3612 if (NewStart.isInvalid())
3614 NewStart = SemaRef.PerformImplicitConversion(
3615 NewStart.get(), VarRef.get()->getType(), Sema::AA_Converting,
3616 /*AllowExplicit=*/true);
3617 if (!NewStart.isUsable())
3621 SemaRef.BuildBinOp(S, Loc, BO_Assign, VarRef.get(), NewStart.get());
3625 /// \brief Build 'VarRef = Start + Iter * Step'.
3626 static ExprResult BuildCounterUpdate(Sema &SemaRef, Scope *S,
3627 SourceLocation Loc, ExprResult VarRef,
3628 ExprResult Start, ExprResult Iter,
3629 ExprResult Step, bool Subtract) {
3630 // Add parentheses (for debugging purposes only).
3631 Iter = SemaRef.ActOnParenExpr(Loc, Loc, Iter.get());
3632 if (!VarRef.isUsable() || !Start.isUsable() || !Iter.isUsable() ||
3636 TransformToNewDefs Transform(SemaRef);
3637 auto NewStep = Transform.TransformExpr(Step.get()->IgnoreImplicit());
3638 if (NewStep.isInvalid())
3640 NewStep = SemaRef.PerformImplicitConversion(
3641 NewStep.get(), Step.get()->IgnoreImplicit()->getType(),
3642 Sema::AA_Converting,
3643 /*AllowExplicit=*/true);
3644 if (NewStep.isInvalid())
3647 SemaRef.BuildBinOp(S, Loc, BO_Mul, Iter.get(), NewStep.get());
3648 if (!Update.isUsable())
3651 // Build 'VarRef = Start + Iter * Step'.
3652 auto NewStart = Transform.TransformExpr(Start.get()->IgnoreImplicit());
3653 if (NewStart.isInvalid())
3655 NewStart = SemaRef.PerformImplicitConversion(
3656 NewStart.get(), Start.get()->IgnoreImplicit()->getType(),
3657 Sema::AA_Converting,
3658 /*AllowExplicit=*/true);
3659 if (NewStart.isInvalid())
3661 Update = SemaRef.BuildBinOp(S, Loc, (Subtract ? BO_Sub : BO_Add),
3662 NewStart.get(), Update.get());
3663 if (!Update.isUsable())
3666 Update = SemaRef.PerformImplicitConversion(
3667 Update.get(), VarRef.get()->getType(), Sema::AA_Converting, true);
3668 if (!Update.isUsable())
3671 Update = SemaRef.BuildBinOp(S, Loc, BO_Assign, VarRef.get(), Update.get());
3675 /// \brief Convert integer expression \a E to make it have at least \a Bits
3677 static ExprResult WidenIterationCount(unsigned Bits, Expr *E,
3681 auto &C = SemaRef.Context;
3682 QualType OldType = E->getType();
3683 unsigned HasBits = C.getTypeSize(OldType);
3684 if (HasBits >= Bits)
3685 return ExprResult(E);
3686 // OK to convert to signed, because new type has more bits than old.
3687 QualType NewType = C.getIntTypeForBitwidth(Bits, /* Signed */ true);
3688 return SemaRef.PerformImplicitConversion(E, NewType, Sema::AA_Converting,
3692 /// \brief Check if the given expression \a E is a constant integer that fits
3693 /// into \a Bits bits.
3694 static bool FitsInto(unsigned Bits, bool Signed, Expr *E, Sema &SemaRef) {
3697 llvm::APSInt Result;
3698 if (E->isIntegerConstantExpr(Result, SemaRef.Context))
3699 return Signed ? Result.isSignedIntN(Bits) : Result.isIntN(Bits);
3703 /// \brief Called on a for stmt to check itself and nested loops (if any).
3704 /// \return Returns 0 if one of the collapsed stmts is not canonical for loop,
3705 /// number of collapsed loops otherwise.
3707 CheckOpenMPLoop(OpenMPDirectiveKind DKind, Expr *CollapseLoopCountExpr,
3708 Expr *OrderedLoopCountExpr, Stmt *AStmt, Sema &SemaRef,
3710 llvm::DenseMap<VarDecl *, Expr *> &VarsWithImplicitDSA,
3711 OMPLoopDirective::HelperExprs &Built) {
3712 unsigned NestedLoopCount = 1;
3713 if (CollapseLoopCountExpr) {
3714 // Found 'collapse' clause - calculate collapse number.
3715 llvm::APSInt Result;
3716 if (CollapseLoopCountExpr->EvaluateAsInt(Result, SemaRef.getASTContext()))
3717 NestedLoopCount = Result.getLimitedValue();
3719 if (OrderedLoopCountExpr) {
3720 // Found 'ordered' clause - calculate collapse number.
3721 llvm::APSInt Result;
3722 if (OrderedLoopCountExpr->EvaluateAsInt(Result, SemaRef.getASTContext())) {
3723 if (Result.getLimitedValue() < NestedLoopCount) {
3724 SemaRef.Diag(OrderedLoopCountExpr->getExprLoc(),
3725 diag::err_omp_wrong_ordered_loop_count)
3726 << OrderedLoopCountExpr->getSourceRange();
3727 SemaRef.Diag(CollapseLoopCountExpr->getExprLoc(),
3728 diag::note_collapse_loop_count)
3729 << CollapseLoopCountExpr->getSourceRange();
3731 NestedLoopCount = Result.getLimitedValue();
3734 // This is helper routine for loop directives (e.g., 'for', 'simd',
3735 // 'for simd', etc.).
3736 SmallVector<LoopIterationSpace, 4> IterSpaces;
3737 IterSpaces.resize(NestedLoopCount);
3738 Stmt *CurStmt = AStmt->IgnoreContainers(/* IgnoreCaptured */ true);
3739 for (unsigned Cnt = 0; Cnt < NestedLoopCount; ++Cnt) {
3740 if (CheckOpenMPIterationSpace(DKind, CurStmt, SemaRef, DSA, Cnt,
3741 NestedLoopCount, CollapseLoopCountExpr,
3742 OrderedLoopCountExpr, VarsWithImplicitDSA,
3745 // Move on to the next nested for loop, or to the loop body.
3746 // OpenMP [2.8.1, simd construct, Restrictions]
3747 // All loops associated with the construct must be perfectly nested; that
3748 // is, there must be no intervening code nor any OpenMP directive between
3750 CurStmt = cast<ForStmt>(CurStmt)->getBody()->IgnoreContainers();
3753 Built.clear(/* size */ NestedLoopCount);
3755 if (SemaRef.CurContext->isDependentContext())
3756 return NestedLoopCount;
3758 // An example of what is generated for the following code:
3760 // #pragma omp simd collapse(2) ordered(2)
3761 // for (i = 0; i < NI; ++i)
3762 // for (k = 0; k < NK; ++k)
3763 // for (j = J0; j < NJ; j+=2) {
3767 // We generate the code below.
3768 // Note: the loop body may be outlined in CodeGen.
3769 // Note: some counters may be C++ classes, operator- is used to find number of
3770 // iterations and operator+= to calculate counter value.
3771 // Note: decltype(NumIterations) must be integer type (in 'omp for', only i32
3772 // or i64 is currently supported).
3774 // #define NumIterations (NI * ((NJ - J0 - 1 + 2) / 2))
3775 // for (int[32|64]_t IV = 0; IV < NumIterations; ++IV ) {
3776 // .local.i = IV / ((NJ - J0 - 1 + 2) / 2);
3777 // .local.j = J0 + (IV % ((NJ - J0 - 1 + 2) / 2)) * 2;
3778 // // similar updates for vars in clauses (e.g. 'linear')
3779 // <loop body (using local i and j)>
3781 // i = NI; // assign final values of counters
3785 // Last iteration number is (I1 * I2 * ... In) - 1, where I1, I2 ... In are
3786 // the iteration counts of the collapsed for loops.
3787 // Precondition tests if there is at least one iteration (all conditions are
3789 auto PreCond = ExprResult(IterSpaces[0].PreCond);
3790 auto N0 = IterSpaces[0].NumIterations;
3791 ExprResult LastIteration32 = WidenIterationCount(
3792 32 /* Bits */, SemaRef.PerformImplicitConversion(
3793 N0->IgnoreImpCasts(), N0->getType(),
3794 Sema::AA_Converting, /*AllowExplicit=*/true)
3797 ExprResult LastIteration64 = WidenIterationCount(
3798 64 /* Bits */, SemaRef.PerformImplicitConversion(
3799 N0->IgnoreImpCasts(), N0->getType(),
3800 Sema::AA_Converting, /*AllowExplicit=*/true)
3804 if (!LastIteration32.isUsable() || !LastIteration64.isUsable())
3805 return NestedLoopCount;
3807 auto &C = SemaRef.Context;
3808 bool AllCountsNeedLessThan32Bits = C.getTypeSize(N0->getType()) < 32;
3810 Scope *CurScope = DSA.getCurScope();
3811 for (unsigned Cnt = 1; Cnt < NestedLoopCount; ++Cnt) {
3812 if (PreCond.isUsable()) {
3813 PreCond = SemaRef.BuildBinOp(CurScope, SourceLocation(), BO_LAnd,
3814 PreCond.get(), IterSpaces[Cnt].PreCond);
3816 auto N = IterSpaces[Cnt].NumIterations;
3817 AllCountsNeedLessThan32Bits &= C.getTypeSize(N->getType()) < 32;
3818 if (LastIteration32.isUsable())
3819 LastIteration32 = SemaRef.BuildBinOp(
3820 CurScope, SourceLocation(), BO_Mul, LastIteration32.get(),
3821 SemaRef.PerformImplicitConversion(N->IgnoreImpCasts(), N->getType(),
3822 Sema::AA_Converting,
3823 /*AllowExplicit=*/true)
3825 if (LastIteration64.isUsable())
3826 LastIteration64 = SemaRef.BuildBinOp(
3827 CurScope, SourceLocation(), BO_Mul, LastIteration64.get(),
3828 SemaRef.PerformImplicitConversion(N->IgnoreImpCasts(), N->getType(),
3829 Sema::AA_Converting,
3830 /*AllowExplicit=*/true)
3834 // Choose either the 32-bit or 64-bit version.
3835 ExprResult LastIteration = LastIteration64;
3836 if (LastIteration32.isUsable() &&
3837 C.getTypeSize(LastIteration32.get()->getType()) == 32 &&
3838 (AllCountsNeedLessThan32Bits || NestedLoopCount == 1 ||
3841 LastIteration32.get()->getType()->hasSignedIntegerRepresentation(),
3842 LastIteration64.get(), SemaRef)))
3843 LastIteration = LastIteration32;
3845 if (!LastIteration.isUsable())
3848 // Save the number of iterations.
3849 ExprResult NumIterations = LastIteration;
3851 LastIteration = SemaRef.BuildBinOp(
3852 CurScope, SourceLocation(), BO_Sub, LastIteration.get(),
3853 SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get());
3854 if (!LastIteration.isUsable())
3858 // Calculate the last iteration number beforehand instead of doing this on
3859 // each iteration. Do not do this if the number of iterations may be kfold-ed.
3860 llvm::APSInt Result;
3862 LastIteration.get()->isIntegerConstantExpr(Result, SemaRef.Context);
3863 ExprResult CalcLastIteration;
3865 SourceLocation SaveLoc;
3867 buildVarDecl(SemaRef, SaveLoc, LastIteration.get()->getType(),
3868 ".omp.last.iteration");
3869 ExprResult SaveRef = buildDeclRefExpr(
3870 SemaRef, SaveVar, LastIteration.get()->getType(), SaveLoc);
3871 CalcLastIteration = SemaRef.BuildBinOp(CurScope, SaveLoc, BO_Assign,
3872 SaveRef.get(), LastIteration.get());
3873 LastIteration = SaveRef;
3875 // Prepare SaveRef + 1.
3876 NumIterations = SemaRef.BuildBinOp(
3877 CurScope, SaveLoc, BO_Add, SaveRef.get(),
3878 SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get());
3879 if (!NumIterations.isUsable())
3883 SourceLocation InitLoc = IterSpaces[0].InitSrcRange.getBegin();
3885 QualType VType = LastIteration.get()->getType();
3886 // Build variables passed into runtime, nesessary for worksharing directives.
3887 ExprResult LB, UB, IL, ST, EUB;
3888 if (isOpenMPWorksharingDirective(DKind) || isOpenMPTaskLoopDirective(DKind) ||
3889 isOpenMPDistributeDirective(DKind)) {
3890 // Lower bound variable, initialized with zero.
3891 VarDecl *LBDecl = buildVarDecl(SemaRef, InitLoc, VType, ".omp.lb");
3892 LB = buildDeclRefExpr(SemaRef, LBDecl, VType, InitLoc);
3893 SemaRef.AddInitializerToDecl(
3894 LBDecl, SemaRef.ActOnIntegerConstant(InitLoc, 0).get(),
3895 /*DirectInit*/ false, /*TypeMayContainAuto*/ false);
3897 // Upper bound variable, initialized with last iteration number.
3898 VarDecl *UBDecl = buildVarDecl(SemaRef, InitLoc, VType, ".omp.ub");
3899 UB = buildDeclRefExpr(SemaRef, UBDecl, VType, InitLoc);
3900 SemaRef.AddInitializerToDecl(UBDecl, LastIteration.get(),
3901 /*DirectInit*/ false,
3902 /*TypeMayContainAuto*/ false);
3904 // A 32-bit variable-flag where runtime returns 1 for the last iteration.
3905 // This will be used to implement clause 'lastprivate'.
3906 QualType Int32Ty = SemaRef.Context.getIntTypeForBitwidth(32, true);
3907 VarDecl *ILDecl = buildVarDecl(SemaRef, InitLoc, Int32Ty, ".omp.is_last");
3908 IL = buildDeclRefExpr(SemaRef, ILDecl, Int32Ty, InitLoc);
3909 SemaRef.AddInitializerToDecl(
3910 ILDecl, SemaRef.ActOnIntegerConstant(InitLoc, 0).get(),
3911 /*DirectInit*/ false, /*TypeMayContainAuto*/ false);
3913 // Stride variable returned by runtime (we initialize it to 1 by default).
3914 VarDecl *STDecl = buildVarDecl(SemaRef, InitLoc, VType, ".omp.stride");
3915 ST = buildDeclRefExpr(SemaRef, STDecl, VType, InitLoc);
3916 SemaRef.AddInitializerToDecl(
3917 STDecl, SemaRef.ActOnIntegerConstant(InitLoc, 1).get(),
3918 /*DirectInit*/ false, /*TypeMayContainAuto*/ false);
3920 // Build expression: UB = min(UB, LastIteration)
3921 // It is nesessary for CodeGen of directives with static scheduling.
3922 ExprResult IsUBGreater = SemaRef.BuildBinOp(CurScope, InitLoc, BO_GT,
3923 UB.get(), LastIteration.get());
3924 ExprResult CondOp = SemaRef.ActOnConditionalOp(
3925 InitLoc, InitLoc, IsUBGreater.get(), LastIteration.get(), UB.get());
3926 EUB = SemaRef.BuildBinOp(CurScope, InitLoc, BO_Assign, UB.get(),
3928 EUB = SemaRef.ActOnFinishFullExpr(EUB.get());
3931 // Build the iteration variable and its initialization before loop.
3935 VarDecl *IVDecl = buildVarDecl(SemaRef, InitLoc, VType, ".omp.iv");
3936 IV = buildDeclRefExpr(SemaRef, IVDecl, VType, InitLoc);
3937 Expr *RHS = (isOpenMPWorksharingDirective(DKind) ||
3938 isOpenMPTaskLoopDirective(DKind) ||
3939 isOpenMPDistributeDirective(DKind))
3941 : SemaRef.ActOnIntegerConstant(SourceLocation(), 0).get();
3942 Init = SemaRef.BuildBinOp(CurScope, InitLoc, BO_Assign, IV.get(), RHS);
3943 Init = SemaRef.ActOnFinishFullExpr(Init.get());
3946 // Loop condition (IV < NumIterations) or (IV <= UB) for worksharing loops.
3947 SourceLocation CondLoc;
3949 (isOpenMPWorksharingDirective(DKind) ||
3950 isOpenMPTaskLoopDirective(DKind) || isOpenMPDistributeDirective(DKind))
3951 ? SemaRef.BuildBinOp(CurScope, CondLoc, BO_LE, IV.get(), UB.get())
3952 : SemaRef.BuildBinOp(CurScope, CondLoc, BO_LT, IV.get(),
3953 NumIterations.get());
3955 // Loop increment (IV = IV + 1)
3956 SourceLocation IncLoc;
3958 SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, IV.get(),
3959 SemaRef.ActOnIntegerConstant(IncLoc, 1).get());
3960 if (!Inc.isUsable())
3962 Inc = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, IV.get(), Inc.get());
3963 Inc = SemaRef.ActOnFinishFullExpr(Inc.get());
3964 if (!Inc.isUsable())
3967 // Increments for worksharing loops (LB = LB + ST; UB = UB + ST).
3968 // Used for directives with static scheduling.
3969 ExprResult NextLB, NextUB;
3970 if (isOpenMPWorksharingDirective(DKind) || isOpenMPTaskLoopDirective(DKind) ||
3971 isOpenMPDistributeDirective(DKind)) {
3973 NextLB = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, LB.get(), ST.get());
3974 if (!NextLB.isUsable())
3978 SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, LB.get(), NextLB.get());
3979 NextLB = SemaRef.ActOnFinishFullExpr(NextLB.get());
3980 if (!NextLB.isUsable())
3983 NextUB = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, UB.get(), ST.get());
3984 if (!NextUB.isUsable())
3988 SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, UB.get(), NextUB.get());
3989 NextUB = SemaRef.ActOnFinishFullExpr(NextUB.get());
3990 if (!NextUB.isUsable())
3994 // Build updates and final values of the loop counters.
3995 bool HasErrors = false;
3996 Built.Counters.resize(NestedLoopCount);
3997 Built.Inits.resize(NestedLoopCount);
3998 Built.Updates.resize(NestedLoopCount);
3999 Built.Finals.resize(NestedLoopCount);
4002 // Go from inner nested loop to outer.
4003 for (int Cnt = NestedLoopCount - 1; Cnt >= 0; --Cnt) {
4004 LoopIterationSpace &IS = IterSpaces[Cnt];
4005 SourceLocation UpdLoc = IS.IncSrcRange.getBegin();
4006 // Build: Iter = (IV / Div) % IS.NumIters
4007 // where Div is product of previous iterations' IS.NumIters.
4009 if (Div.isUsable()) {
4011 SemaRef.BuildBinOp(CurScope, UpdLoc, BO_Div, IV.get(), Div.get());
4014 assert((Cnt == (int)NestedLoopCount - 1) &&
4015 "unusable div expected on first iteration only");
4018 if (Cnt != 0 && Iter.isUsable())
4019 Iter = SemaRef.BuildBinOp(CurScope, UpdLoc, BO_Rem, Iter.get(),
4021 if (!Iter.isUsable()) {
4026 // Build update: IS.CounterVar(Private) = IS.Start + Iter * IS.Step
4027 auto *CounterVar = buildDeclRefExpr(
4028 SemaRef, cast<VarDecl>(cast<DeclRefExpr>(IS.CounterVar)->getDecl()),
4029 IS.CounterVar->getType(), IS.CounterVar->getExprLoc(),
4030 /*RefersToCapture=*/true);
4031 ExprResult Init = BuildCounterInit(SemaRef, CurScope, UpdLoc, CounterVar,
4033 if (!Init.isUsable()) {
4038 BuildCounterUpdate(SemaRef, CurScope, UpdLoc, CounterVar,
4039 IS.CounterInit, Iter, IS.CounterStep, IS.Subtract);
4040 if (!Update.isUsable()) {
4045 // Build final: IS.CounterVar = IS.Start + IS.NumIters * IS.Step
4046 ExprResult Final = BuildCounterUpdate(
4047 SemaRef, CurScope, UpdLoc, CounterVar, IS.CounterInit,
4048 IS.NumIterations, IS.CounterStep, IS.Subtract);
4049 if (!Final.isUsable()) {
4054 // Build Div for the next iteration: Div <- Div * IS.NumIters
4057 Div = IS.NumIterations;
4059 Div = SemaRef.BuildBinOp(CurScope, UpdLoc, BO_Mul, Div.get(),
4062 // Add parentheses (for debugging purposes only).
4064 Div = SemaRef.ActOnParenExpr(UpdLoc, UpdLoc, Div.get());
4065 if (!Div.isUsable()) {
4070 if (!Update.isUsable() || !Final.isUsable()) {
4075 Built.Counters[Cnt] = IS.CounterVar;
4076 Built.PrivateCounters[Cnt] = IS.PrivateCounterVar;
4077 Built.Inits[Cnt] = Init.get();
4078 Built.Updates[Cnt] = Update.get();
4079 Built.Finals[Cnt] = Final.get();
4087 Built.IterationVarRef = IV.get();
4088 Built.LastIteration = LastIteration.get();
4089 Built.NumIterations = NumIterations.get();
4090 Built.CalcLastIteration =
4091 SemaRef.ActOnFinishFullExpr(CalcLastIteration.get()).get();
4092 Built.PreCond = PreCond.get();
4093 Built.Cond = Cond.get();
4094 Built.Init = Init.get();
4095 Built.Inc = Inc.get();
4096 Built.LB = LB.get();
4097 Built.UB = UB.get();
4098 Built.IL = IL.get();
4099 Built.ST = ST.get();
4100 Built.EUB = EUB.get();
4101 Built.NLB = NextLB.get();
4102 Built.NUB = NextUB.get();
4104 return NestedLoopCount;
4107 static Expr *getCollapseNumberExpr(ArrayRef<OMPClause *> Clauses) {
4108 auto CollapseClauses =
4109 OMPExecutableDirective::getClausesOfKind<OMPCollapseClause>(Clauses);
4110 if (CollapseClauses.begin() != CollapseClauses.end())
4111 return (*CollapseClauses.begin())->getNumForLoops();
4115 static Expr *getOrderedNumberExpr(ArrayRef<OMPClause *> Clauses) {
4116 auto OrderedClauses =
4117 OMPExecutableDirective::getClausesOfKind<OMPOrderedClause>(Clauses);
4118 if (OrderedClauses.begin() != OrderedClauses.end())
4119 return (*OrderedClauses.begin())->getNumForLoops();
4123 static bool checkSimdlenSafelenValues(Sema &S, const Expr *Simdlen,
4124 const Expr *Safelen) {
4125 llvm::APSInt SimdlenRes, SafelenRes;
4126 if (Simdlen->isValueDependent() || Simdlen->isTypeDependent() ||
4127 Simdlen->isInstantiationDependent() ||
4128 Simdlen->containsUnexpandedParameterPack())
4130 if (Safelen->isValueDependent() || Safelen->isTypeDependent() ||
4131 Safelen->isInstantiationDependent() ||
4132 Safelen->containsUnexpandedParameterPack())
4134 Simdlen->EvaluateAsInt(SimdlenRes, S.Context);
4135 Safelen->EvaluateAsInt(SafelenRes, S.Context);
4136 // OpenMP 4.1 [2.8.1, simd Construct, Restrictions]
4137 // If both simdlen and safelen clauses are specified, the value of the simdlen
4138 // parameter must be less than or equal to the value of the safelen parameter.
4139 if (SimdlenRes > SafelenRes) {
4140 S.Diag(Simdlen->getExprLoc(), diag::err_omp_wrong_simdlen_safelen_values)
4141 << Simdlen->getSourceRange() << Safelen->getSourceRange();
4147 StmtResult Sema::ActOnOpenMPSimdDirective(
4148 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
4149 SourceLocation EndLoc,
4150 llvm::DenseMap<VarDecl *, Expr *> &VarsWithImplicitDSA) {
4154 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
4155 OMPLoopDirective::HelperExprs B;
4156 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
4157 // define the nested loops number.
4158 unsigned NestedLoopCount = CheckOpenMPLoop(
4159 OMPD_simd, getCollapseNumberExpr(Clauses), getOrderedNumberExpr(Clauses),
4160 AStmt, *this, *DSAStack, VarsWithImplicitDSA, B);
4161 if (NestedLoopCount == 0)
4164 assert((CurContext->isDependentContext() || B.builtAll()) &&
4165 "omp simd loop exprs were not built");
4167 if (!CurContext->isDependentContext()) {
4168 // Finalize the clauses that need pre-built expressions for CodeGen.
4169 for (auto C : Clauses) {
4170 if (auto LC = dyn_cast<OMPLinearClause>(C))
4171 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
4172 B.NumIterations, *this, CurScope))
4177 // OpenMP 4.1 [2.8.1, simd Construct, Restrictions]
4178 // If both simdlen and safelen clauses are specified, the value of the simdlen
4179 // parameter must be less than or equal to the value of the safelen parameter.
4180 OMPSafelenClause *Safelen = nullptr;
4181 OMPSimdlenClause *Simdlen = nullptr;
4182 for (auto *Clause : Clauses) {
4183 if (Clause->getClauseKind() == OMPC_safelen)
4184 Safelen = cast<OMPSafelenClause>(Clause);
4185 else if (Clause->getClauseKind() == OMPC_simdlen)
4186 Simdlen = cast<OMPSimdlenClause>(Clause);
4187 if (Safelen && Simdlen)
4190 if (Simdlen && Safelen &&
4191 checkSimdlenSafelenValues(*this, Simdlen->getSimdlen(),
4192 Safelen->getSafelen()))
4195 getCurFunction()->setHasBranchProtectedScope();
4196 return OMPSimdDirective::Create(Context, StartLoc, EndLoc, NestedLoopCount,
4200 StmtResult Sema::ActOnOpenMPForDirective(
4201 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
4202 SourceLocation EndLoc,
4203 llvm::DenseMap<VarDecl *, Expr *> &VarsWithImplicitDSA) {
4207 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
4208 OMPLoopDirective::HelperExprs B;
4209 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
4210 // define the nested loops number.
4211 unsigned NestedLoopCount = CheckOpenMPLoop(
4212 OMPD_for, getCollapseNumberExpr(Clauses), getOrderedNumberExpr(Clauses),
4213 AStmt, *this, *DSAStack, VarsWithImplicitDSA, B);
4214 if (NestedLoopCount == 0)
4217 assert((CurContext->isDependentContext() || B.builtAll()) &&
4218 "omp for loop exprs were not built");
4220 if (!CurContext->isDependentContext()) {
4221 // Finalize the clauses that need pre-built expressions for CodeGen.
4222 for (auto C : Clauses) {
4223 if (auto LC = dyn_cast<OMPLinearClause>(C))
4224 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
4225 B.NumIterations, *this, CurScope))
4230 getCurFunction()->setHasBranchProtectedScope();
4231 return OMPForDirective::Create(Context, StartLoc, EndLoc, NestedLoopCount,
4232 Clauses, AStmt, B, DSAStack->isCancelRegion());
4235 StmtResult Sema::ActOnOpenMPForSimdDirective(
4236 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
4237 SourceLocation EndLoc,
4238 llvm::DenseMap<VarDecl *, Expr *> &VarsWithImplicitDSA) {
4242 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
4243 OMPLoopDirective::HelperExprs B;
4244 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
4245 // define the nested loops number.
4246 unsigned NestedLoopCount =
4247 CheckOpenMPLoop(OMPD_for_simd, getCollapseNumberExpr(Clauses),
4248 getOrderedNumberExpr(Clauses), AStmt, *this, *DSAStack,
4249 VarsWithImplicitDSA, B);
4250 if (NestedLoopCount == 0)
4253 assert((CurContext->isDependentContext() || B.builtAll()) &&
4254 "omp for simd loop exprs were not built");
4256 if (!CurContext->isDependentContext()) {
4257 // Finalize the clauses that need pre-built expressions for CodeGen.
4258 for (auto C : Clauses) {
4259 if (auto LC = dyn_cast<OMPLinearClause>(C))
4260 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
4261 B.NumIterations, *this, CurScope))
4266 // OpenMP 4.1 [2.8.1, simd Construct, Restrictions]
4267 // If both simdlen and safelen clauses are specified, the value of the simdlen
4268 // parameter must be less than or equal to the value of the safelen parameter.
4269 OMPSafelenClause *Safelen = nullptr;
4270 OMPSimdlenClause *Simdlen = nullptr;
4271 for (auto *Clause : Clauses) {
4272 if (Clause->getClauseKind() == OMPC_safelen)
4273 Safelen = cast<OMPSafelenClause>(Clause);
4274 else if (Clause->getClauseKind() == OMPC_simdlen)
4275 Simdlen = cast<OMPSimdlenClause>(Clause);
4276 if (Safelen && Simdlen)
4279 if (Simdlen && Safelen &&
4280 checkSimdlenSafelenValues(*this, Simdlen->getSimdlen(),
4281 Safelen->getSafelen()))
4284 getCurFunction()->setHasBranchProtectedScope();
4285 return OMPForSimdDirective::Create(Context, StartLoc, EndLoc, NestedLoopCount,
4289 StmtResult Sema::ActOnOpenMPSectionsDirective(ArrayRef<OMPClause *> Clauses,
4291 SourceLocation StartLoc,
4292 SourceLocation EndLoc) {
4296 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
4297 auto BaseStmt = AStmt;
4298 while (CapturedStmt *CS = dyn_cast_or_null<CapturedStmt>(BaseStmt))
4299 BaseStmt = CS->getCapturedStmt();
4300 if (auto C = dyn_cast_or_null<CompoundStmt>(BaseStmt)) {
4301 auto S = C->children();
4302 if (S.begin() == S.end())
4304 // All associated statements must be '#pragma omp section' except for
4306 for (Stmt *SectionStmt : llvm::make_range(std::next(S.begin()), S.end())) {
4307 if (!SectionStmt || !isa<OMPSectionDirective>(SectionStmt)) {
4309 Diag(SectionStmt->getLocStart(),
4310 diag::err_omp_sections_substmt_not_section);
4313 cast<OMPSectionDirective>(SectionStmt)
4314 ->setHasCancel(DSAStack->isCancelRegion());
4317 Diag(AStmt->getLocStart(), diag::err_omp_sections_not_compound_stmt);
4321 getCurFunction()->setHasBranchProtectedScope();
4323 return OMPSectionsDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt,
4324 DSAStack->isCancelRegion());
4327 StmtResult Sema::ActOnOpenMPSectionDirective(Stmt *AStmt,
4328 SourceLocation StartLoc,
4329 SourceLocation EndLoc) {
4333 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
4335 getCurFunction()->setHasBranchProtectedScope();
4336 DSAStack->setParentCancelRegion(DSAStack->isCancelRegion());
4338 return OMPSectionDirective::Create(Context, StartLoc, EndLoc, AStmt,
4339 DSAStack->isCancelRegion());
4342 StmtResult Sema::ActOnOpenMPSingleDirective(ArrayRef<OMPClause *> Clauses,
4344 SourceLocation StartLoc,
4345 SourceLocation EndLoc) {
4349 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
4351 getCurFunction()->setHasBranchProtectedScope();
4353 // OpenMP [2.7.3, single Construct, Restrictions]
4354 // The copyprivate clause must not be used with the nowait clause.
4355 OMPClause *Nowait = nullptr;
4356 OMPClause *Copyprivate = nullptr;
4357 for (auto *Clause : Clauses) {
4358 if (Clause->getClauseKind() == OMPC_nowait)
4360 else if (Clause->getClauseKind() == OMPC_copyprivate)
4361 Copyprivate = Clause;
4362 if (Copyprivate && Nowait) {
4363 Diag(Copyprivate->getLocStart(),
4364 diag::err_omp_single_copyprivate_with_nowait);
4365 Diag(Nowait->getLocStart(), diag::note_omp_nowait_clause_here);
4370 return OMPSingleDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt);
4373 StmtResult Sema::ActOnOpenMPMasterDirective(Stmt *AStmt,
4374 SourceLocation StartLoc,
4375 SourceLocation EndLoc) {
4379 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
4381 getCurFunction()->setHasBranchProtectedScope();
4383 return OMPMasterDirective::Create(Context, StartLoc, EndLoc, AStmt);
4386 StmtResult Sema::ActOnOpenMPCriticalDirective(
4387 const DeclarationNameInfo &DirName, ArrayRef<OMPClause *> Clauses,
4388 Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc) {
4392 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
4394 bool ErrorFound = false;
4396 SourceLocation HintLoc;
4397 bool DependentHint = false;
4398 for (auto *C : Clauses) {
4399 if (C->getClauseKind() == OMPC_hint) {
4400 if (!DirName.getName()) {
4401 Diag(C->getLocStart(), diag::err_omp_hint_clause_no_name);
4404 Expr *E = cast<OMPHintClause>(C)->getHint();
4405 if (E->isTypeDependent() || E->isValueDependent() ||
4406 E->isInstantiationDependent())
4407 DependentHint = true;
4409 Hint = E->EvaluateKnownConstInt(Context);
4410 HintLoc = C->getLocStart();
4416 auto Pair = DSAStack->getCriticalWithHint(DirName);
4417 if (Pair.first && DirName.getName() && !DependentHint) {
4418 if (llvm::APSInt::compareValues(Hint, Pair.second) != 0) {
4419 Diag(StartLoc, diag::err_omp_critical_with_hint);
4420 if (HintLoc.isValid()) {
4421 Diag(HintLoc, diag::note_omp_critical_hint_here)
4422 << 0 << Hint.toString(/*Radix=*/10, /*Signed=*/false);
4424 Diag(StartLoc, diag::note_omp_critical_no_hint) << 0;
4425 if (auto *C = Pair.first->getSingleClause<OMPHintClause>()) {
4426 Diag(C->getLocStart(), diag::note_omp_critical_hint_here)
4428 << C->getHint()->EvaluateKnownConstInt(Context).toString(
4429 /*Radix=*/10, /*Signed=*/false);
4431 Diag(Pair.first->getLocStart(), diag::note_omp_critical_no_hint) << 1;
4435 getCurFunction()->setHasBranchProtectedScope();
4437 auto *Dir = OMPCriticalDirective::Create(Context, DirName, StartLoc, EndLoc,
4439 if (!Pair.first && DirName.getName() && !DependentHint)
4440 DSAStack->addCriticalWithHint(Dir, Hint);
4444 StmtResult Sema::ActOnOpenMPParallelForDirective(
4445 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
4446 SourceLocation EndLoc,
4447 llvm::DenseMap<VarDecl *, Expr *> &VarsWithImplicitDSA) {
4451 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
4452 // 1.2.2 OpenMP Language Terminology
4453 // Structured block - An executable statement with a single entry at the
4454 // top and a single exit at the bottom.
4455 // The point of exit cannot be a branch out of the structured block.
4456 // longjmp() and throw() must not violate the entry/exit criteria.
4457 CS->getCapturedDecl()->setNothrow();
4459 OMPLoopDirective::HelperExprs B;
4460 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
4461 // define the nested loops number.
4462 unsigned NestedLoopCount =
4463 CheckOpenMPLoop(OMPD_parallel_for, getCollapseNumberExpr(Clauses),
4464 getOrderedNumberExpr(Clauses), AStmt, *this, *DSAStack,
4465 VarsWithImplicitDSA, B);
4466 if (NestedLoopCount == 0)
4469 assert((CurContext->isDependentContext() || B.builtAll()) &&
4470 "omp parallel for loop exprs were not built");
4472 if (!CurContext->isDependentContext()) {
4473 // Finalize the clauses that need pre-built expressions for CodeGen.
4474 for (auto C : Clauses) {
4475 if (auto LC = dyn_cast<OMPLinearClause>(C))
4476 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
4477 B.NumIterations, *this, CurScope))
4482 getCurFunction()->setHasBranchProtectedScope();
4483 return OMPParallelForDirective::Create(Context, StartLoc, EndLoc,
4484 NestedLoopCount, Clauses, AStmt, B,
4485 DSAStack->isCancelRegion());
4488 StmtResult Sema::ActOnOpenMPParallelForSimdDirective(
4489 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
4490 SourceLocation EndLoc,
4491 llvm::DenseMap<VarDecl *, Expr *> &VarsWithImplicitDSA) {
4495 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
4496 // 1.2.2 OpenMP Language Terminology
4497 // Structured block - An executable statement with a single entry at the
4498 // top and a single exit at the bottom.
4499 // The point of exit cannot be a branch out of the structured block.
4500 // longjmp() and throw() must not violate the entry/exit criteria.
4501 CS->getCapturedDecl()->setNothrow();
4503 OMPLoopDirective::HelperExprs B;
4504 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
4505 // define the nested loops number.
4506 unsigned NestedLoopCount =
4507 CheckOpenMPLoop(OMPD_parallel_for_simd, getCollapseNumberExpr(Clauses),
4508 getOrderedNumberExpr(Clauses), AStmt, *this, *DSAStack,
4509 VarsWithImplicitDSA, B);
4510 if (NestedLoopCount == 0)
4513 if (!CurContext->isDependentContext()) {
4514 // Finalize the clauses that need pre-built expressions for CodeGen.
4515 for (auto C : Clauses) {
4516 if (auto LC = dyn_cast<OMPLinearClause>(C))
4517 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
4518 B.NumIterations, *this, CurScope))
4523 // OpenMP 4.1 [2.8.1, simd Construct, Restrictions]
4524 // If both simdlen and safelen clauses are specified, the value of the simdlen
4525 // parameter must be less than or equal to the value of the safelen parameter.
4526 OMPSafelenClause *Safelen = nullptr;
4527 OMPSimdlenClause *Simdlen = nullptr;
4528 for (auto *Clause : Clauses) {
4529 if (Clause->getClauseKind() == OMPC_safelen)
4530 Safelen = cast<OMPSafelenClause>(Clause);
4531 else if (Clause->getClauseKind() == OMPC_simdlen)
4532 Simdlen = cast<OMPSimdlenClause>(Clause);
4533 if (Safelen && Simdlen)
4536 if (Simdlen && Safelen &&
4537 checkSimdlenSafelenValues(*this, Simdlen->getSimdlen(),
4538 Safelen->getSafelen()))
4541 getCurFunction()->setHasBranchProtectedScope();
4542 return OMPParallelForSimdDirective::Create(
4543 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
4547 Sema::ActOnOpenMPParallelSectionsDirective(ArrayRef<OMPClause *> Clauses,
4548 Stmt *AStmt, SourceLocation StartLoc,
4549 SourceLocation EndLoc) {
4553 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
4554 auto BaseStmt = AStmt;
4555 while (CapturedStmt *CS = dyn_cast_or_null<CapturedStmt>(BaseStmt))
4556 BaseStmt = CS->getCapturedStmt();
4557 if (auto C = dyn_cast_or_null<CompoundStmt>(BaseStmt)) {
4558 auto S = C->children();
4559 if (S.begin() == S.end())
4561 // All associated statements must be '#pragma omp section' except for
4563 for (Stmt *SectionStmt : llvm::make_range(std::next(S.begin()), S.end())) {
4564 if (!SectionStmt || !isa<OMPSectionDirective>(SectionStmt)) {
4566 Diag(SectionStmt->getLocStart(),
4567 diag::err_omp_parallel_sections_substmt_not_section);
4570 cast<OMPSectionDirective>(SectionStmt)
4571 ->setHasCancel(DSAStack->isCancelRegion());
4574 Diag(AStmt->getLocStart(),
4575 diag::err_omp_parallel_sections_not_compound_stmt);
4579 getCurFunction()->setHasBranchProtectedScope();
4581 return OMPParallelSectionsDirective::Create(
4582 Context, StartLoc, EndLoc, Clauses, AStmt, DSAStack->isCancelRegion());
4585 StmtResult Sema::ActOnOpenMPTaskDirective(ArrayRef<OMPClause *> Clauses,
4586 Stmt *AStmt, SourceLocation StartLoc,
4587 SourceLocation EndLoc) {
4591 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
4592 // 1.2.2 OpenMP Language Terminology
4593 // Structured block - An executable statement with a single entry at the
4594 // top and a single exit at the bottom.
4595 // The point of exit cannot be a branch out of the structured block.
4596 // longjmp() and throw() must not violate the entry/exit criteria.
4597 CS->getCapturedDecl()->setNothrow();
4599 getCurFunction()->setHasBranchProtectedScope();
4601 return OMPTaskDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt,
4602 DSAStack->isCancelRegion());
4605 StmtResult Sema::ActOnOpenMPTaskyieldDirective(SourceLocation StartLoc,
4606 SourceLocation EndLoc) {
4607 return OMPTaskyieldDirective::Create(Context, StartLoc, EndLoc);
4610 StmtResult Sema::ActOnOpenMPBarrierDirective(SourceLocation StartLoc,
4611 SourceLocation EndLoc) {
4612 return OMPBarrierDirective::Create(Context, StartLoc, EndLoc);
4615 StmtResult Sema::ActOnOpenMPTaskwaitDirective(SourceLocation StartLoc,
4616 SourceLocation EndLoc) {
4617 return OMPTaskwaitDirective::Create(Context, StartLoc, EndLoc);
4620 StmtResult Sema::ActOnOpenMPTaskgroupDirective(Stmt *AStmt,
4621 SourceLocation StartLoc,
4622 SourceLocation EndLoc) {
4626 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
4628 getCurFunction()->setHasBranchProtectedScope();
4630 return OMPTaskgroupDirective::Create(Context, StartLoc, EndLoc, AStmt);
4633 StmtResult Sema::ActOnOpenMPFlushDirective(ArrayRef<OMPClause *> Clauses,
4634 SourceLocation StartLoc,
4635 SourceLocation EndLoc) {
4636 assert(Clauses.size() <= 1 && "Extra clauses in flush directive");
4637 return OMPFlushDirective::Create(Context, StartLoc, EndLoc, Clauses);
4640 StmtResult Sema::ActOnOpenMPOrderedDirective(ArrayRef<OMPClause *> Clauses,
4642 SourceLocation StartLoc,
4643 SourceLocation EndLoc) {
4644 OMPClause *DependFound = nullptr;
4645 OMPClause *DependSourceClause = nullptr;
4646 OMPClause *DependSinkClause = nullptr;
4647 bool ErrorFound = false;
4648 OMPThreadsClause *TC = nullptr;
4649 OMPSIMDClause *SC = nullptr;
4650 for (auto *C : Clauses) {
4651 if (auto *DC = dyn_cast<OMPDependClause>(C)) {
4653 if (DC->getDependencyKind() == OMPC_DEPEND_source) {
4654 if (DependSourceClause) {
4655 Diag(C->getLocStart(), diag::err_omp_more_one_clause)
4656 << getOpenMPDirectiveName(OMPD_ordered)
4657 << getOpenMPClauseName(OMPC_depend) << 2;
4660 DependSourceClause = C;
4661 if (DependSinkClause) {
4662 Diag(C->getLocStart(), diag::err_omp_depend_sink_source_not_allowed)
4666 } else if (DC->getDependencyKind() == OMPC_DEPEND_sink) {
4667 if (DependSourceClause) {
4668 Diag(C->getLocStart(), diag::err_omp_depend_sink_source_not_allowed)
4672 DependSinkClause = C;
4674 } else if (C->getClauseKind() == OMPC_threads)
4675 TC = cast<OMPThreadsClause>(C);
4676 else if (C->getClauseKind() == OMPC_simd)
4677 SC = cast<OMPSIMDClause>(C);
4679 if (!ErrorFound && !SC &&
4680 isOpenMPSimdDirective(DSAStack->getParentDirective())) {
4681 // OpenMP [2.8.1,simd Construct, Restrictions]
4682 // An ordered construct with the simd clause is the only OpenMP construct
4683 // that can appear in the simd region.
4684 Diag(StartLoc, diag::err_omp_prohibited_region_simd);
4686 } else if (DependFound && (TC || SC)) {
4687 Diag(DependFound->getLocStart(), diag::err_omp_depend_clause_thread_simd)
4688 << getOpenMPClauseName(TC ? TC->getClauseKind() : SC->getClauseKind());
4690 } else if (DependFound && !DSAStack->getParentOrderedRegionParam()) {
4691 Diag(DependFound->getLocStart(),
4692 diag::err_omp_ordered_directive_without_param);
4694 } else if (TC || Clauses.empty()) {
4695 if (auto *Param = DSAStack->getParentOrderedRegionParam()) {
4696 SourceLocation ErrLoc = TC ? TC->getLocStart() : StartLoc;
4697 Diag(ErrLoc, diag::err_omp_ordered_directive_with_param)
4699 Diag(Param->getLocStart(), diag::note_omp_ordered_param);
4703 if ((!AStmt && !DependFound) || ErrorFound)
4707 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
4709 getCurFunction()->setHasBranchProtectedScope();
4712 return OMPOrderedDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt);
4716 /// \brief Helper class for checking expression in 'omp atomic [update]'
4718 class OpenMPAtomicUpdateChecker {
4719 /// \brief Error results for atomic update expressions.
4720 enum ExprAnalysisErrorCode {
4721 /// \brief A statement is not an expression statement.
4723 /// \brief Expression is not builtin binary or unary operation.
4724 NotABinaryOrUnaryExpression,
4725 /// \brief Unary operation is not post-/pre- increment/decrement operation.
4726 NotAnUnaryIncDecExpression,
4727 /// \brief An expression is not of scalar type.
4729 /// \brief A binary operation is not an assignment operation.
4731 /// \brief RHS part of the binary operation is not a binary expression.
4732 NotABinaryExpression,
4733 /// \brief RHS part is not additive/multiplicative/shift/biwise binary
4736 /// \brief RHS binary operation does not have reference to the updated LHS
4738 NotAnUpdateExpression,
4739 /// \brief No errors is found.
4742 /// \brief Reference to Sema.
4744 /// \brief A location for note diagnostics (when error is found).
4745 SourceLocation NoteLoc;
4746 /// \brief 'x' lvalue part of the source atomic expression.
4748 /// \brief 'expr' rvalue part of the source atomic expression.
4750 /// \brief Helper expression of the form
4751 /// 'OpaqueValueExpr(x) binop OpaqueValueExpr(expr)' or
4752 /// 'OpaqueValueExpr(expr) binop OpaqueValueExpr(x)'.
4754 /// \brief Is 'x' a LHS in a RHS part of full update expression. It is
4755 /// important for non-associative operations.
4756 bool IsXLHSInRHSPart;
4757 BinaryOperatorKind Op;
4758 SourceLocation OpLoc;
4759 /// \brief true if the source expression is a postfix unary operation, false
4760 /// if it is a prefix unary operation.
4761 bool IsPostfixUpdate;
4764 OpenMPAtomicUpdateChecker(Sema &SemaRef)
4765 : SemaRef(SemaRef), X(nullptr), E(nullptr), UpdateExpr(nullptr),
4766 IsXLHSInRHSPart(false), Op(BO_PtrMemD), IsPostfixUpdate(false) {}
4767 /// \brief Check specified statement that it is suitable for 'atomic update'
4768 /// constructs and extract 'x', 'expr' and Operation from the original
4769 /// expression. If DiagId and NoteId == 0, then only check is performed
4770 /// without error notification.
4771 /// \param DiagId Diagnostic which should be emitted if error is found.
4772 /// \param NoteId Diagnostic note for the main error message.
4773 /// \return true if statement is not an update expression, false otherwise.
4774 bool checkStatement(Stmt *S, unsigned DiagId = 0, unsigned NoteId = 0);
4775 /// \brief Return the 'x' lvalue part of the source atomic expression.
4776 Expr *getX() const { return X; }
4777 /// \brief Return the 'expr' rvalue part of the source atomic expression.
4778 Expr *getExpr() const { return E; }
4779 /// \brief Return the update expression used in calculation of the updated
4780 /// value. Always has form 'OpaqueValueExpr(x) binop OpaqueValueExpr(expr)' or
4781 /// 'OpaqueValueExpr(expr) binop OpaqueValueExpr(x)'.
4782 Expr *getUpdateExpr() const { return UpdateExpr; }
4783 /// \brief Return true if 'x' is LHS in RHS part of full update expression,
4784 /// false otherwise.
4785 bool isXLHSInRHSPart() const { return IsXLHSInRHSPart; }
4787 /// \brief true if the source expression is a postfix unary operation, false
4788 /// if it is a prefix unary operation.
4789 bool isPostfixUpdate() const { return IsPostfixUpdate; }
4792 bool checkBinaryOperation(BinaryOperator *AtomicBinOp, unsigned DiagId = 0,
4793 unsigned NoteId = 0);
4797 bool OpenMPAtomicUpdateChecker::checkBinaryOperation(
4798 BinaryOperator *AtomicBinOp, unsigned DiagId, unsigned NoteId) {
4799 ExprAnalysisErrorCode ErrorFound = NoError;
4800 SourceLocation ErrorLoc, NoteLoc;
4801 SourceRange ErrorRange, NoteRange;
4802 // Allowed constructs are:
4803 // x = x binop expr;
4804 // x = expr binop x;
4805 if (AtomicBinOp->getOpcode() == BO_Assign) {
4806 X = AtomicBinOp->getLHS();
4807 if (auto *AtomicInnerBinOp = dyn_cast<BinaryOperator>(
4808 AtomicBinOp->getRHS()->IgnoreParenImpCasts())) {
4809 if (AtomicInnerBinOp->isMultiplicativeOp() ||
4810 AtomicInnerBinOp->isAdditiveOp() || AtomicInnerBinOp->isShiftOp() ||
4811 AtomicInnerBinOp->isBitwiseOp()) {
4812 Op = AtomicInnerBinOp->getOpcode();
4813 OpLoc = AtomicInnerBinOp->getOperatorLoc();
4814 auto *LHS = AtomicInnerBinOp->getLHS();
4815 auto *RHS = AtomicInnerBinOp->getRHS();
4816 llvm::FoldingSetNodeID XId, LHSId, RHSId;
4817 X->IgnoreParenImpCasts()->Profile(XId, SemaRef.getASTContext(),
4818 /*Canonical=*/true);
4819 LHS->IgnoreParenImpCasts()->Profile(LHSId, SemaRef.getASTContext(),
4820 /*Canonical=*/true);
4821 RHS->IgnoreParenImpCasts()->Profile(RHSId, SemaRef.getASTContext(),
4822 /*Canonical=*/true);
4825 IsXLHSInRHSPart = true;
4826 } else if (XId == RHSId) {
4828 IsXLHSInRHSPart = false;
4830 ErrorLoc = AtomicInnerBinOp->getExprLoc();
4831 ErrorRange = AtomicInnerBinOp->getSourceRange();
4832 NoteLoc = X->getExprLoc();
4833 NoteRange = X->getSourceRange();
4834 ErrorFound = NotAnUpdateExpression;
4837 ErrorLoc = AtomicInnerBinOp->getExprLoc();
4838 ErrorRange = AtomicInnerBinOp->getSourceRange();
4839 NoteLoc = AtomicInnerBinOp->getOperatorLoc();
4840 NoteRange = SourceRange(NoteLoc, NoteLoc);
4841 ErrorFound = NotABinaryOperator;
4844 NoteLoc = ErrorLoc = AtomicBinOp->getRHS()->getExprLoc();
4845 NoteRange = ErrorRange = AtomicBinOp->getRHS()->getSourceRange();
4846 ErrorFound = NotABinaryExpression;
4849 ErrorLoc = AtomicBinOp->getExprLoc();
4850 ErrorRange = AtomicBinOp->getSourceRange();
4851 NoteLoc = AtomicBinOp->getOperatorLoc();
4852 NoteRange = SourceRange(NoteLoc, NoteLoc);
4853 ErrorFound = NotAnAssignmentOp;
4855 if (ErrorFound != NoError && DiagId != 0 && NoteId != 0) {
4856 SemaRef.Diag(ErrorLoc, DiagId) << ErrorRange;
4857 SemaRef.Diag(NoteLoc, NoteId) << ErrorFound << NoteRange;
4859 } else if (SemaRef.CurContext->isDependentContext())
4860 E = X = UpdateExpr = nullptr;
4861 return ErrorFound != NoError;
4864 bool OpenMPAtomicUpdateChecker::checkStatement(Stmt *S, unsigned DiagId,
4866 ExprAnalysisErrorCode ErrorFound = NoError;
4867 SourceLocation ErrorLoc, NoteLoc;
4868 SourceRange ErrorRange, NoteRange;
4869 // Allowed constructs are:
4875 // x = x binop expr;
4876 // x = expr binop x;
4877 if (auto *AtomicBody = dyn_cast<Expr>(S)) {
4878 AtomicBody = AtomicBody->IgnoreParenImpCasts();
4879 if (AtomicBody->getType()->isScalarType() ||
4880 AtomicBody->isInstantiationDependent()) {
4881 if (auto *AtomicCompAssignOp = dyn_cast<CompoundAssignOperator>(
4882 AtomicBody->IgnoreParenImpCasts())) {
4883 // Check for Compound Assignment Operation
4884 Op = BinaryOperator::getOpForCompoundAssignment(
4885 AtomicCompAssignOp->getOpcode());
4886 OpLoc = AtomicCompAssignOp->getOperatorLoc();
4887 E = AtomicCompAssignOp->getRHS();
4888 X = AtomicCompAssignOp->getLHS();
4889 IsXLHSInRHSPart = true;
4890 } else if (auto *AtomicBinOp = dyn_cast<BinaryOperator>(
4891 AtomicBody->IgnoreParenImpCasts())) {
4892 // Check for Binary Operation
4893 if(checkBinaryOperation(AtomicBinOp, DiagId, NoteId))
4895 } else if (auto *AtomicUnaryOp =
4896 dyn_cast<UnaryOperator>(AtomicBody->IgnoreParenImpCasts())) {
4897 // Check for Unary Operation
4898 if (AtomicUnaryOp->isIncrementDecrementOp()) {
4899 IsPostfixUpdate = AtomicUnaryOp->isPostfix();
4900 Op = AtomicUnaryOp->isIncrementOp() ? BO_Add : BO_Sub;
4901 OpLoc = AtomicUnaryOp->getOperatorLoc();
4902 X = AtomicUnaryOp->getSubExpr();
4903 E = SemaRef.ActOnIntegerConstant(OpLoc, /*uint64_t Val=*/1).get();
4904 IsXLHSInRHSPart = true;
4906 ErrorFound = NotAnUnaryIncDecExpression;
4907 ErrorLoc = AtomicUnaryOp->getExprLoc();
4908 ErrorRange = AtomicUnaryOp->getSourceRange();
4909 NoteLoc = AtomicUnaryOp->getOperatorLoc();
4910 NoteRange = SourceRange(NoteLoc, NoteLoc);
4912 } else if (!AtomicBody->isInstantiationDependent()) {
4913 ErrorFound = NotABinaryOrUnaryExpression;
4914 NoteLoc = ErrorLoc = AtomicBody->getExprLoc();
4915 NoteRange = ErrorRange = AtomicBody->getSourceRange();
4918 ErrorFound = NotAScalarType;
4919 NoteLoc = ErrorLoc = AtomicBody->getLocStart();
4920 NoteRange = ErrorRange = SourceRange(NoteLoc, NoteLoc);
4923 ErrorFound = NotAnExpression;
4924 NoteLoc = ErrorLoc = S->getLocStart();
4925 NoteRange = ErrorRange = SourceRange(NoteLoc, NoteLoc);
4927 if (ErrorFound != NoError && DiagId != 0 && NoteId != 0) {
4928 SemaRef.Diag(ErrorLoc, DiagId) << ErrorRange;
4929 SemaRef.Diag(NoteLoc, NoteId) << ErrorFound << NoteRange;
4931 } else if (SemaRef.CurContext->isDependentContext())
4932 E = X = UpdateExpr = nullptr;
4933 if (ErrorFound == NoError && E && X) {
4934 // Build an update expression of form 'OpaqueValueExpr(x) binop
4935 // OpaqueValueExpr(expr)' or 'OpaqueValueExpr(expr) binop
4936 // OpaqueValueExpr(x)' and then cast it to the type of the 'x' expression.
4937 auto *OVEX = new (SemaRef.getASTContext())
4938 OpaqueValueExpr(X->getExprLoc(), X->getType(), VK_RValue);
4939 auto *OVEExpr = new (SemaRef.getASTContext())
4940 OpaqueValueExpr(E->getExprLoc(), E->getType(), VK_RValue);
4942 SemaRef.CreateBuiltinBinOp(OpLoc, Op, IsXLHSInRHSPart ? OVEX : OVEExpr,
4943 IsXLHSInRHSPart ? OVEExpr : OVEX);
4944 if (Update.isInvalid())
4946 Update = SemaRef.PerformImplicitConversion(Update.get(), X->getType(),
4948 if (Update.isInvalid())
4950 UpdateExpr = Update.get();
4952 return ErrorFound != NoError;
4955 StmtResult Sema::ActOnOpenMPAtomicDirective(ArrayRef<OMPClause *> Clauses,
4957 SourceLocation StartLoc,
4958 SourceLocation EndLoc) {
4962 auto CS = cast<CapturedStmt>(AStmt);
4963 // 1.2.2 OpenMP Language Terminology
4964 // Structured block - An executable statement with a single entry at the
4965 // top and a single exit at the bottom.
4966 // The point of exit cannot be a branch out of the structured block.
4967 // longjmp() and throw() must not violate the entry/exit criteria.
4968 OpenMPClauseKind AtomicKind = OMPC_unknown;
4969 SourceLocation AtomicKindLoc;
4970 for (auto *C : Clauses) {
4971 if (C->getClauseKind() == OMPC_read || C->getClauseKind() == OMPC_write ||
4972 C->getClauseKind() == OMPC_update ||
4973 C->getClauseKind() == OMPC_capture) {
4974 if (AtomicKind != OMPC_unknown) {
4975 Diag(C->getLocStart(), diag::err_omp_atomic_several_clauses)
4976 << SourceRange(C->getLocStart(), C->getLocEnd());
4977 Diag(AtomicKindLoc, diag::note_omp_atomic_previous_clause)
4978 << getOpenMPClauseName(AtomicKind);
4980 AtomicKind = C->getClauseKind();
4981 AtomicKindLoc = C->getLocStart();
4986 auto Body = CS->getCapturedStmt();
4987 if (auto *EWC = dyn_cast<ExprWithCleanups>(Body))
4988 Body = EWC->getSubExpr();
4994 bool IsXLHSInRHSPart = false;
4995 bool IsPostfixUpdate = false;
4996 // OpenMP [2.12.6, atomic Construct]
4997 // In the next expressions:
4998 // * x and v (as applicable) are both l-value expressions with scalar type.
4999 // * During the execution of an atomic region, multiple syntactic
5000 // occurrences of x must designate the same storage location.
5001 // * Neither of v and expr (as applicable) may access the storage location
5003 // * Neither of x and expr (as applicable) may access the storage location
5005 // * expr is an expression with scalar type.
5006 // * binop is one of +, *, -, /, &, ^, |, <<, or >>.
5007 // * binop, binop=, ++, and -- are not overloaded operators.
5008 // * The expression x binop expr must be numerically equivalent to x binop
5009 // (expr). This requirement is satisfied if the operators in expr have
5010 // precedence greater than binop, or by using parentheses around expr or
5011 // subexpressions of expr.
5012 // * The expression expr binop x must be numerically equivalent to (expr)
5013 // binop x. This requirement is satisfied if the operators in expr have
5014 // precedence equal to or greater than binop, or by using parentheses around
5015 // expr or subexpressions of expr.
5016 // * For forms that allow multiple occurrences of x, the number of times
5017 // that x is evaluated is unspecified.
5018 if (AtomicKind == OMPC_read) {
5025 } ErrorFound = NoError;
5026 SourceLocation ErrorLoc, NoteLoc;
5027 SourceRange ErrorRange, NoteRange;
5028 // If clause is read:
5030 if (auto AtomicBody = dyn_cast<Expr>(Body)) {
5032 dyn_cast<BinaryOperator>(AtomicBody->IgnoreParenImpCasts());
5033 if (AtomicBinOp && AtomicBinOp->getOpcode() == BO_Assign) {
5034 X = AtomicBinOp->getRHS()->IgnoreParenImpCasts();
5035 V = AtomicBinOp->getLHS()->IgnoreParenImpCasts();
5036 if ((X->isInstantiationDependent() || X->getType()->isScalarType()) &&
5037 (V->isInstantiationDependent() || V->getType()->isScalarType())) {
5038 if (!X->isLValue() || !V->isLValue()) {
5039 auto NotLValueExpr = X->isLValue() ? V : X;
5040 ErrorFound = NotAnLValue;
5041 ErrorLoc = AtomicBinOp->getExprLoc();
5042 ErrorRange = AtomicBinOp->getSourceRange();
5043 NoteLoc = NotLValueExpr->getExprLoc();
5044 NoteRange = NotLValueExpr->getSourceRange();
5046 } else if (!X->isInstantiationDependent() ||
5047 !V->isInstantiationDependent()) {
5048 auto NotScalarExpr =
5049 (X->isInstantiationDependent() || X->getType()->isScalarType())
5052 ErrorFound = NotAScalarType;
5053 ErrorLoc = AtomicBinOp->getExprLoc();
5054 ErrorRange = AtomicBinOp->getSourceRange();
5055 NoteLoc = NotScalarExpr->getExprLoc();
5056 NoteRange = NotScalarExpr->getSourceRange();
5058 } else if (!AtomicBody->isInstantiationDependent()) {
5059 ErrorFound = NotAnAssignmentOp;
5060 ErrorLoc = AtomicBody->getExprLoc();
5061 ErrorRange = AtomicBody->getSourceRange();
5062 NoteLoc = AtomicBinOp ? AtomicBinOp->getOperatorLoc()
5063 : AtomicBody->getExprLoc();
5064 NoteRange = AtomicBinOp ? AtomicBinOp->getSourceRange()
5065 : AtomicBody->getSourceRange();
5068 ErrorFound = NotAnExpression;
5069 NoteLoc = ErrorLoc = Body->getLocStart();
5070 NoteRange = ErrorRange = SourceRange(NoteLoc, NoteLoc);
5072 if (ErrorFound != NoError) {
5073 Diag(ErrorLoc, diag::err_omp_atomic_read_not_expression_statement)
5075 Diag(NoteLoc, diag::note_omp_atomic_read_write) << ErrorFound
5078 } else if (CurContext->isDependentContext())
5080 } else if (AtomicKind == OMPC_write) {
5087 } ErrorFound = NoError;
5088 SourceLocation ErrorLoc, NoteLoc;
5089 SourceRange ErrorRange, NoteRange;
5090 // If clause is write:
5092 if (auto AtomicBody = dyn_cast<Expr>(Body)) {
5094 dyn_cast<BinaryOperator>(AtomicBody->IgnoreParenImpCasts());
5095 if (AtomicBinOp && AtomicBinOp->getOpcode() == BO_Assign) {
5096 X = AtomicBinOp->getLHS();
5097 E = AtomicBinOp->getRHS();
5098 if ((X->isInstantiationDependent() || X->getType()->isScalarType()) &&
5099 (E->isInstantiationDependent() || E->getType()->isScalarType())) {
5100 if (!X->isLValue()) {
5101 ErrorFound = NotAnLValue;
5102 ErrorLoc = AtomicBinOp->getExprLoc();
5103 ErrorRange = AtomicBinOp->getSourceRange();
5104 NoteLoc = X->getExprLoc();
5105 NoteRange = X->getSourceRange();
5107 } else if (!X->isInstantiationDependent() ||
5108 !E->isInstantiationDependent()) {
5109 auto NotScalarExpr =
5110 (X->isInstantiationDependent() || X->getType()->isScalarType())
5113 ErrorFound = NotAScalarType;
5114 ErrorLoc = AtomicBinOp->getExprLoc();
5115 ErrorRange = AtomicBinOp->getSourceRange();
5116 NoteLoc = NotScalarExpr->getExprLoc();
5117 NoteRange = NotScalarExpr->getSourceRange();
5119 } else if (!AtomicBody->isInstantiationDependent()) {
5120 ErrorFound = NotAnAssignmentOp;
5121 ErrorLoc = AtomicBody->getExprLoc();
5122 ErrorRange = AtomicBody->getSourceRange();
5123 NoteLoc = AtomicBinOp ? AtomicBinOp->getOperatorLoc()
5124 : AtomicBody->getExprLoc();
5125 NoteRange = AtomicBinOp ? AtomicBinOp->getSourceRange()
5126 : AtomicBody->getSourceRange();
5129 ErrorFound = NotAnExpression;
5130 NoteLoc = ErrorLoc = Body->getLocStart();
5131 NoteRange = ErrorRange = SourceRange(NoteLoc, NoteLoc);
5133 if (ErrorFound != NoError) {
5134 Diag(ErrorLoc, diag::err_omp_atomic_write_not_expression_statement)
5136 Diag(NoteLoc, diag::note_omp_atomic_read_write) << ErrorFound
5139 } else if (CurContext->isDependentContext())
5141 } else if (AtomicKind == OMPC_update || AtomicKind == OMPC_unknown) {
5142 // If clause is update:
5148 // x = x binop expr;
5149 // x = expr binop x;
5150 OpenMPAtomicUpdateChecker Checker(*this);
5151 if (Checker.checkStatement(
5152 Body, (AtomicKind == OMPC_update)
5153 ? diag::err_omp_atomic_update_not_expression_statement
5154 : diag::err_omp_atomic_not_expression_statement,
5155 diag::note_omp_atomic_update))
5157 if (!CurContext->isDependentContext()) {
5158 E = Checker.getExpr();
5160 UE = Checker.getUpdateExpr();
5161 IsXLHSInRHSPart = Checker.isXLHSInRHSPart();
5163 } else if (AtomicKind == OMPC_capture) {
5166 NotACompoundStatement,
5167 NotTwoSubstatements,
5168 NotASpecificExpression,
5170 } ErrorFound = NoError;
5171 SourceLocation ErrorLoc, NoteLoc;
5172 SourceRange ErrorRange, NoteRange;
5173 if (auto *AtomicBody = dyn_cast<Expr>(Body)) {
5174 // If clause is a capture:
5179 // v = x binop= expr;
5180 // v = x = x binop expr;
5181 // v = x = expr binop x;
5183 dyn_cast<BinaryOperator>(AtomicBody->IgnoreParenImpCasts());
5184 if (AtomicBinOp && AtomicBinOp->getOpcode() == BO_Assign) {
5185 V = AtomicBinOp->getLHS();
5186 Body = AtomicBinOp->getRHS()->IgnoreParenImpCasts();
5187 OpenMPAtomicUpdateChecker Checker(*this);
5188 if (Checker.checkStatement(
5189 Body, diag::err_omp_atomic_capture_not_expression_statement,
5190 diag::note_omp_atomic_update))
5192 E = Checker.getExpr();
5194 UE = Checker.getUpdateExpr();
5195 IsXLHSInRHSPart = Checker.isXLHSInRHSPart();
5196 IsPostfixUpdate = Checker.isPostfixUpdate();
5197 } else if (!AtomicBody->isInstantiationDependent()) {
5198 ErrorLoc = AtomicBody->getExprLoc();
5199 ErrorRange = AtomicBody->getSourceRange();
5200 NoteLoc = AtomicBinOp ? AtomicBinOp->getOperatorLoc()
5201 : AtomicBody->getExprLoc();
5202 NoteRange = AtomicBinOp ? AtomicBinOp->getSourceRange()
5203 : AtomicBody->getSourceRange();
5204 ErrorFound = NotAnAssignmentOp;
5206 if (ErrorFound != NoError) {
5207 Diag(ErrorLoc, diag::err_omp_atomic_capture_not_expression_statement)
5209 Diag(NoteLoc, diag::note_omp_atomic_capture) << ErrorFound << NoteRange;
5211 } else if (CurContext->isDependentContext()) {
5212 UE = V = E = X = nullptr;
5215 // If clause is a capture:
5216 // { v = x; x = expr; }
5221 // { v = x; x binop= expr; }
5222 // { v = x; x = x binop expr; }
5223 // { v = x; x = expr binop x; }
5228 // { x binop= expr; v = x; }
5229 // { x = x binop expr; v = x; }
5230 // { x = expr binop x; v = x; }
5231 if (auto *CS = dyn_cast<CompoundStmt>(Body)) {
5232 // Check that this is { expr1; expr2; }
5233 if (CS->size() == 2) {
5234 auto *First = CS->body_front();
5235 auto *Second = CS->body_back();
5236 if (auto *EWC = dyn_cast<ExprWithCleanups>(First))
5237 First = EWC->getSubExpr()->IgnoreParenImpCasts();
5238 if (auto *EWC = dyn_cast<ExprWithCleanups>(Second))
5239 Second = EWC->getSubExpr()->IgnoreParenImpCasts();
5240 // Need to find what subexpression is 'v' and what is 'x'.
5241 OpenMPAtomicUpdateChecker Checker(*this);
5242 bool IsUpdateExprFound = !Checker.checkStatement(Second);
5243 BinaryOperator *BinOp = nullptr;
5244 if (IsUpdateExprFound) {
5245 BinOp = dyn_cast<BinaryOperator>(First);
5246 IsUpdateExprFound = BinOp && BinOp->getOpcode() == BO_Assign;
5248 if (IsUpdateExprFound && !CurContext->isDependentContext()) {
5253 // { v = x; x binop= expr; }
5254 // { v = x; x = x binop expr; }
5255 // { v = x; x = expr binop x; }
5256 // Check that the first expression has form v = x.
5257 auto *PossibleX = BinOp->getRHS()->IgnoreParenImpCasts();
5258 llvm::FoldingSetNodeID XId, PossibleXId;
5259 Checker.getX()->Profile(XId, Context, /*Canonical=*/true);
5260 PossibleX->Profile(PossibleXId, Context, /*Canonical=*/true);
5261 IsUpdateExprFound = XId == PossibleXId;
5262 if (IsUpdateExprFound) {
5263 V = BinOp->getLHS();
5265 E = Checker.getExpr();
5266 UE = Checker.getUpdateExpr();
5267 IsXLHSInRHSPart = Checker.isXLHSInRHSPart();
5268 IsPostfixUpdate = true;
5271 if (!IsUpdateExprFound) {
5272 IsUpdateExprFound = !Checker.checkStatement(First);
5274 if (IsUpdateExprFound) {
5275 BinOp = dyn_cast<BinaryOperator>(Second);
5276 IsUpdateExprFound = BinOp && BinOp->getOpcode() == BO_Assign;
5278 if (IsUpdateExprFound && !CurContext->isDependentContext()) {
5283 // { x binop= expr; v = x; }
5284 // { x = x binop expr; v = x; }
5285 // { x = expr binop x; v = x; }
5286 // Check that the second expression has form v = x.
5287 auto *PossibleX = BinOp->getRHS()->IgnoreParenImpCasts();
5288 llvm::FoldingSetNodeID XId, PossibleXId;
5289 Checker.getX()->Profile(XId, Context, /*Canonical=*/true);
5290 PossibleX->Profile(PossibleXId, Context, /*Canonical=*/true);
5291 IsUpdateExprFound = XId == PossibleXId;
5292 if (IsUpdateExprFound) {
5293 V = BinOp->getLHS();
5295 E = Checker.getExpr();
5296 UE = Checker.getUpdateExpr();
5297 IsXLHSInRHSPart = Checker.isXLHSInRHSPart();
5298 IsPostfixUpdate = false;
5302 if (!IsUpdateExprFound) {
5303 // { v = x; x = expr; }
5304 auto *FirstExpr = dyn_cast<Expr>(First);
5305 auto *SecondExpr = dyn_cast<Expr>(Second);
5306 if (!FirstExpr || !SecondExpr ||
5307 !(FirstExpr->isInstantiationDependent() ||
5308 SecondExpr->isInstantiationDependent())) {
5309 auto *FirstBinOp = dyn_cast<BinaryOperator>(First);
5310 if (!FirstBinOp || FirstBinOp->getOpcode() != BO_Assign) {
5311 ErrorFound = NotAnAssignmentOp;
5312 NoteLoc = ErrorLoc = FirstBinOp ? FirstBinOp->getOperatorLoc()
5313 : First->getLocStart();
5314 NoteRange = ErrorRange = FirstBinOp
5315 ? FirstBinOp->getSourceRange()
5316 : SourceRange(ErrorLoc, ErrorLoc);
5318 auto *SecondBinOp = dyn_cast<BinaryOperator>(Second);
5319 if (!SecondBinOp || SecondBinOp->getOpcode() != BO_Assign) {
5320 ErrorFound = NotAnAssignmentOp;
5321 NoteLoc = ErrorLoc = SecondBinOp
5322 ? SecondBinOp->getOperatorLoc()
5323 : Second->getLocStart();
5324 NoteRange = ErrorRange =
5325 SecondBinOp ? SecondBinOp->getSourceRange()
5326 : SourceRange(ErrorLoc, ErrorLoc);
5328 auto *PossibleXRHSInFirst =
5329 FirstBinOp->getRHS()->IgnoreParenImpCasts();
5330 auto *PossibleXLHSInSecond =
5331 SecondBinOp->getLHS()->IgnoreParenImpCasts();
5332 llvm::FoldingSetNodeID X1Id, X2Id;
5333 PossibleXRHSInFirst->Profile(X1Id, Context,
5334 /*Canonical=*/true);
5335 PossibleXLHSInSecond->Profile(X2Id, Context,
5336 /*Canonical=*/true);
5337 IsUpdateExprFound = X1Id == X2Id;
5338 if (IsUpdateExprFound) {
5339 V = FirstBinOp->getLHS();
5340 X = SecondBinOp->getLHS();
5341 E = SecondBinOp->getRHS();
5343 IsXLHSInRHSPart = false;
5344 IsPostfixUpdate = true;
5346 ErrorFound = NotASpecificExpression;
5347 ErrorLoc = FirstBinOp->getExprLoc();
5348 ErrorRange = FirstBinOp->getSourceRange();
5349 NoteLoc = SecondBinOp->getLHS()->getExprLoc();
5350 NoteRange = SecondBinOp->getRHS()->getSourceRange();
5357 NoteLoc = ErrorLoc = Body->getLocStart();
5358 NoteRange = ErrorRange =
5359 SourceRange(Body->getLocStart(), Body->getLocStart());
5360 ErrorFound = NotTwoSubstatements;
5363 NoteLoc = ErrorLoc = Body->getLocStart();
5364 NoteRange = ErrorRange =
5365 SourceRange(Body->getLocStart(), Body->getLocStart());
5366 ErrorFound = NotACompoundStatement;
5368 if (ErrorFound != NoError) {
5369 Diag(ErrorLoc, diag::err_omp_atomic_capture_not_compound_statement)
5371 Diag(NoteLoc, diag::note_omp_atomic_capture) << ErrorFound << NoteRange;
5373 } else if (CurContext->isDependentContext()) {
5374 UE = V = E = X = nullptr;
5379 getCurFunction()->setHasBranchProtectedScope();
5381 return OMPAtomicDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt,
5382 X, V, E, UE, IsXLHSInRHSPart,
5386 StmtResult Sema::ActOnOpenMPTargetDirective(ArrayRef<OMPClause *> Clauses,
5388 SourceLocation StartLoc,
5389 SourceLocation EndLoc) {
5393 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
5394 // 1.2.2 OpenMP Language Terminology
5395 // Structured block - An executable statement with a single entry at the
5396 // top and a single exit at the bottom.
5397 // The point of exit cannot be a branch out of the structured block.
5398 // longjmp() and throw() must not violate the entry/exit criteria.
5399 CS->getCapturedDecl()->setNothrow();
5401 // OpenMP [2.16, Nesting of Regions]
5402 // If specified, a teams construct must be contained within a target
5403 // construct. That target construct must contain no statements or directives
5404 // outside of the teams construct.
5405 if (DSAStack->hasInnerTeamsRegion()) {
5406 auto S = AStmt->IgnoreContainers(/*IgnoreCaptured*/ true);
5407 bool OMPTeamsFound = true;
5408 if (auto *CS = dyn_cast<CompoundStmt>(S)) {
5409 auto I = CS->body_begin();
5410 while (I != CS->body_end()) {
5411 auto OED = dyn_cast<OMPExecutableDirective>(*I);
5412 if (!OED || !isOpenMPTeamsDirective(OED->getDirectiveKind())) {
5413 OMPTeamsFound = false;
5418 assert(I != CS->body_end() && "Not found statement");
5421 if (!OMPTeamsFound) {
5422 Diag(StartLoc, diag::err_omp_target_contains_not_only_teams);
5423 Diag(DSAStack->getInnerTeamsRegionLoc(),
5424 diag::note_omp_nested_teams_construct_here);
5425 Diag(S->getLocStart(), diag::note_omp_nested_statement_here)
5426 << isa<OMPExecutableDirective>(S);
5431 getCurFunction()->setHasBranchProtectedScope();
5433 return OMPTargetDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt);
5436 StmtResult Sema::ActOnOpenMPTargetDataDirective(ArrayRef<OMPClause *> Clauses,
5438 SourceLocation StartLoc,
5439 SourceLocation EndLoc) {
5443 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
5445 getCurFunction()->setHasBranchProtectedScope();
5447 return OMPTargetDataDirective::Create(Context, StartLoc, EndLoc, Clauses,
5451 StmtResult Sema::ActOnOpenMPTeamsDirective(ArrayRef<OMPClause *> Clauses,
5452 Stmt *AStmt, SourceLocation StartLoc,
5453 SourceLocation EndLoc) {
5457 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
5458 // 1.2.2 OpenMP Language Terminology
5459 // Structured block - An executable statement with a single entry at the
5460 // top and a single exit at the bottom.
5461 // The point of exit cannot be a branch out of the structured block.
5462 // longjmp() and throw() must not violate the entry/exit criteria.
5463 CS->getCapturedDecl()->setNothrow();
5465 getCurFunction()->setHasBranchProtectedScope();
5467 return OMPTeamsDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt);
5471 Sema::ActOnOpenMPCancellationPointDirective(SourceLocation StartLoc,
5472 SourceLocation EndLoc,
5473 OpenMPDirectiveKind CancelRegion) {
5474 if (CancelRegion != OMPD_parallel && CancelRegion != OMPD_for &&
5475 CancelRegion != OMPD_sections && CancelRegion != OMPD_taskgroup) {
5476 Diag(StartLoc, diag::err_omp_wrong_cancel_region)
5477 << getOpenMPDirectiveName(CancelRegion);
5480 if (DSAStack->isParentNowaitRegion()) {
5481 Diag(StartLoc, diag::err_omp_parent_cancel_region_nowait) << 0;
5484 if (DSAStack->isParentOrderedRegion()) {
5485 Diag(StartLoc, diag::err_omp_parent_cancel_region_ordered) << 0;
5488 return OMPCancellationPointDirective::Create(Context, StartLoc, EndLoc,
5492 StmtResult Sema::ActOnOpenMPCancelDirective(ArrayRef<OMPClause *> Clauses,
5493 SourceLocation StartLoc,
5494 SourceLocation EndLoc,
5495 OpenMPDirectiveKind CancelRegion) {
5496 if (CancelRegion != OMPD_parallel && CancelRegion != OMPD_for &&
5497 CancelRegion != OMPD_sections && CancelRegion != OMPD_taskgroup) {
5498 Diag(StartLoc, diag::err_omp_wrong_cancel_region)
5499 << getOpenMPDirectiveName(CancelRegion);
5502 if (DSAStack->isParentNowaitRegion()) {
5503 Diag(StartLoc, diag::err_omp_parent_cancel_region_nowait) << 1;
5506 if (DSAStack->isParentOrderedRegion()) {
5507 Diag(StartLoc, diag::err_omp_parent_cancel_region_ordered) << 1;
5510 DSAStack->setParentCancelRegion(/*Cancel=*/true);
5511 return OMPCancelDirective::Create(Context, StartLoc, EndLoc, Clauses,
5515 static bool checkGrainsizeNumTasksClauses(Sema &S,
5516 ArrayRef<OMPClause *> Clauses) {
5517 OMPClause *PrevClause = nullptr;
5518 bool ErrorFound = false;
5519 for (auto *C : Clauses) {
5520 if (C->getClauseKind() == OMPC_grainsize ||
5521 C->getClauseKind() == OMPC_num_tasks) {
5524 else if (PrevClause->getClauseKind() != C->getClauseKind()) {
5525 S.Diag(C->getLocStart(),
5526 diag::err_omp_grainsize_num_tasks_mutually_exclusive)
5527 << getOpenMPClauseName(C->getClauseKind())
5528 << getOpenMPClauseName(PrevClause->getClauseKind());
5529 S.Diag(PrevClause->getLocStart(),
5530 diag::note_omp_previous_grainsize_num_tasks)
5531 << getOpenMPClauseName(PrevClause->getClauseKind());
5539 StmtResult Sema::ActOnOpenMPTaskLoopDirective(
5540 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
5541 SourceLocation EndLoc,
5542 llvm::DenseMap<VarDecl *, Expr *> &VarsWithImplicitDSA) {
5546 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
5547 OMPLoopDirective::HelperExprs B;
5548 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
5549 // define the nested loops number.
5550 unsigned NestedLoopCount =
5551 CheckOpenMPLoop(OMPD_taskloop, getCollapseNumberExpr(Clauses),
5552 /*OrderedLoopCountExpr=*/nullptr, AStmt, *this, *DSAStack,
5553 VarsWithImplicitDSA, B);
5554 if (NestedLoopCount == 0)
5557 assert((CurContext->isDependentContext() || B.builtAll()) &&
5558 "omp for loop exprs were not built");
5560 // OpenMP, [2.9.2 taskloop Construct, Restrictions]
5561 // The grainsize clause and num_tasks clause are mutually exclusive and may
5562 // not appear on the same taskloop directive.
5563 if (checkGrainsizeNumTasksClauses(*this, Clauses))
5566 getCurFunction()->setHasBranchProtectedScope();
5567 return OMPTaskLoopDirective::Create(Context, StartLoc, EndLoc,
5568 NestedLoopCount, Clauses, AStmt, B);
5571 StmtResult Sema::ActOnOpenMPTaskLoopSimdDirective(
5572 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
5573 SourceLocation EndLoc,
5574 llvm::DenseMap<VarDecl *, Expr *> &VarsWithImplicitDSA) {
5578 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
5579 OMPLoopDirective::HelperExprs B;
5580 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
5581 // define the nested loops number.
5582 unsigned NestedLoopCount =
5583 CheckOpenMPLoop(OMPD_taskloop_simd, getCollapseNumberExpr(Clauses),
5584 /*OrderedLoopCountExpr=*/nullptr, AStmt, *this, *DSAStack,
5585 VarsWithImplicitDSA, B);
5586 if (NestedLoopCount == 0)
5589 assert((CurContext->isDependentContext() || B.builtAll()) &&
5590 "omp for loop exprs were not built");
5592 // OpenMP, [2.9.2 taskloop Construct, Restrictions]
5593 // The grainsize clause and num_tasks clause are mutually exclusive and may
5594 // not appear on the same taskloop directive.
5595 if (checkGrainsizeNumTasksClauses(*this, Clauses))
5598 getCurFunction()->setHasBranchProtectedScope();
5599 return OMPTaskLoopSimdDirective::Create(Context, StartLoc, EndLoc,
5600 NestedLoopCount, Clauses, AStmt, B);
5603 StmtResult Sema::ActOnOpenMPDistributeDirective(
5604 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
5605 SourceLocation EndLoc,
5606 llvm::DenseMap<VarDecl *, Expr *> &VarsWithImplicitDSA) {
5610 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
5611 OMPLoopDirective::HelperExprs B;
5612 // In presence of clause 'collapse' with number of loops, it will
5613 // define the nested loops number.
5614 unsigned NestedLoopCount =
5615 CheckOpenMPLoop(OMPD_distribute, getCollapseNumberExpr(Clauses),
5616 nullptr /*ordered not a clause on distribute*/, AStmt,
5617 *this, *DSAStack, VarsWithImplicitDSA, B);
5618 if (NestedLoopCount == 0)
5621 assert((CurContext->isDependentContext() || B.builtAll()) &&
5622 "omp for loop exprs were not built");
5624 getCurFunction()->setHasBranchProtectedScope();
5625 return OMPDistributeDirective::Create(Context, StartLoc, EndLoc,
5626 NestedLoopCount, Clauses, AStmt, B);
5629 OMPClause *Sema::ActOnOpenMPSingleExprClause(OpenMPClauseKind Kind, Expr *Expr,
5630 SourceLocation StartLoc,
5631 SourceLocation LParenLoc,
5632 SourceLocation EndLoc) {
5633 OMPClause *Res = nullptr;
5636 Res = ActOnOpenMPFinalClause(Expr, StartLoc, LParenLoc, EndLoc);
5638 case OMPC_num_threads:
5639 Res = ActOnOpenMPNumThreadsClause(Expr, StartLoc, LParenLoc, EndLoc);
5642 Res = ActOnOpenMPSafelenClause(Expr, StartLoc, LParenLoc, EndLoc);
5645 Res = ActOnOpenMPSimdlenClause(Expr, StartLoc, LParenLoc, EndLoc);
5648 Res = ActOnOpenMPCollapseClause(Expr, StartLoc, LParenLoc, EndLoc);
5651 Res = ActOnOpenMPOrderedClause(StartLoc, EndLoc, LParenLoc, Expr);
5654 Res = ActOnOpenMPDeviceClause(Expr, StartLoc, LParenLoc, EndLoc);
5656 case OMPC_num_teams:
5657 Res = ActOnOpenMPNumTeamsClause(Expr, StartLoc, LParenLoc, EndLoc);
5659 case OMPC_thread_limit:
5660 Res = ActOnOpenMPThreadLimitClause(Expr, StartLoc, LParenLoc, EndLoc);
5663 Res = ActOnOpenMPPriorityClause(Expr, StartLoc, LParenLoc, EndLoc);
5665 case OMPC_grainsize:
5666 Res = ActOnOpenMPGrainsizeClause(Expr, StartLoc, LParenLoc, EndLoc);
5668 case OMPC_num_tasks:
5669 Res = ActOnOpenMPNumTasksClause(Expr, StartLoc, LParenLoc, EndLoc);
5672 Res = ActOnOpenMPHintClause(Expr, StartLoc, LParenLoc, EndLoc);
5676 case OMPC_proc_bind:
5679 case OMPC_firstprivate:
5680 case OMPC_lastprivate:
5682 case OMPC_reduction:
5686 case OMPC_copyprivate:
5689 case OMPC_mergeable:
5690 case OMPC_threadprivate:
5703 llvm_unreachable("Clause is not allowed.");
5708 OMPClause *Sema::ActOnOpenMPIfClause(OpenMPDirectiveKind NameModifier,
5709 Expr *Condition, SourceLocation StartLoc,
5710 SourceLocation LParenLoc,
5711 SourceLocation NameModifierLoc,
5712 SourceLocation ColonLoc,
5713 SourceLocation EndLoc) {
5714 Expr *ValExpr = Condition;
5715 if (!Condition->isValueDependent() && !Condition->isTypeDependent() &&
5716 !Condition->isInstantiationDependent() &&
5717 !Condition->containsUnexpandedParameterPack()) {
5718 ExprResult Val = ActOnBooleanCondition(DSAStack->getCurScope(),
5719 Condition->getExprLoc(), Condition);
5720 if (Val.isInvalid())
5723 ValExpr = Val.get();
5726 return new (Context) OMPIfClause(NameModifier, ValExpr, StartLoc, LParenLoc,
5727 NameModifierLoc, ColonLoc, EndLoc);
5730 OMPClause *Sema::ActOnOpenMPFinalClause(Expr *Condition,
5731 SourceLocation StartLoc,
5732 SourceLocation LParenLoc,
5733 SourceLocation EndLoc) {
5734 Expr *ValExpr = Condition;
5735 if (!Condition->isValueDependent() && !Condition->isTypeDependent() &&
5736 !Condition->isInstantiationDependent() &&
5737 !Condition->containsUnexpandedParameterPack()) {
5738 ExprResult Val = ActOnBooleanCondition(DSAStack->getCurScope(),
5739 Condition->getExprLoc(), Condition);
5740 if (Val.isInvalid())
5743 ValExpr = Val.get();
5746 return new (Context) OMPFinalClause(ValExpr, StartLoc, LParenLoc, EndLoc);
5748 ExprResult Sema::PerformOpenMPImplicitIntegerConversion(SourceLocation Loc,
5753 class IntConvertDiagnoser : public ICEConvertDiagnoser {
5755 IntConvertDiagnoser()
5756 : ICEConvertDiagnoser(/*AllowScopedEnumerations*/ false, false, true) {}
5757 SemaDiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc,
5758 QualType T) override {
5759 return S.Diag(Loc, diag::err_omp_not_integral) << T;
5761 SemaDiagnosticBuilder diagnoseIncomplete(Sema &S, SourceLocation Loc,
5762 QualType T) override {
5763 return S.Diag(Loc, diag::err_omp_incomplete_type) << T;
5765 SemaDiagnosticBuilder diagnoseExplicitConv(Sema &S, SourceLocation Loc,
5767 QualType ConvTy) override {
5768 return S.Diag(Loc, diag::err_omp_explicit_conversion) << T << ConvTy;
5770 SemaDiagnosticBuilder noteExplicitConv(Sema &S, CXXConversionDecl *Conv,
5771 QualType ConvTy) override {
5772 return S.Diag(Conv->getLocation(), diag::note_omp_conversion_here)
5773 << ConvTy->isEnumeralType() << ConvTy;
5775 SemaDiagnosticBuilder diagnoseAmbiguous(Sema &S, SourceLocation Loc,
5776 QualType T) override {
5777 return S.Diag(Loc, diag::err_omp_ambiguous_conversion) << T;
5779 SemaDiagnosticBuilder noteAmbiguous(Sema &S, CXXConversionDecl *Conv,
5780 QualType ConvTy) override {
5781 return S.Diag(Conv->getLocation(), diag::note_omp_conversion_here)
5782 << ConvTy->isEnumeralType() << ConvTy;
5784 SemaDiagnosticBuilder diagnoseConversion(Sema &, SourceLocation, QualType,
5785 QualType) override {
5786 llvm_unreachable("conversion functions are permitted");
5789 return PerformContextualImplicitConversion(Loc, Op, ConvertDiagnoser);
5792 static bool IsNonNegativeIntegerValue(Expr *&ValExpr, Sema &SemaRef,
5793 OpenMPClauseKind CKind,
5794 bool StrictlyPositive) {
5795 if (!ValExpr->isTypeDependent() && !ValExpr->isValueDependent() &&
5796 !ValExpr->isInstantiationDependent()) {
5797 SourceLocation Loc = ValExpr->getExprLoc();
5799 SemaRef.PerformOpenMPImplicitIntegerConversion(Loc, ValExpr);
5800 if (Value.isInvalid())
5803 ValExpr = Value.get();
5804 // The expression must evaluate to a non-negative integer value.
5805 llvm::APSInt Result;
5806 if (ValExpr->isIntegerConstantExpr(Result, SemaRef.Context) &&
5807 Result.isSigned() &&
5808 !((!StrictlyPositive && Result.isNonNegative()) ||
5809 (StrictlyPositive && Result.isStrictlyPositive()))) {
5810 SemaRef.Diag(Loc, diag::err_omp_negative_expression_in_clause)
5811 << getOpenMPClauseName(CKind) << (StrictlyPositive ? 1 : 0)
5812 << ValExpr->getSourceRange();
5819 OMPClause *Sema::ActOnOpenMPNumThreadsClause(Expr *NumThreads,
5820 SourceLocation StartLoc,
5821 SourceLocation LParenLoc,
5822 SourceLocation EndLoc) {
5823 Expr *ValExpr = NumThreads;
5825 // OpenMP [2.5, Restrictions]
5826 // The num_threads expression must evaluate to a positive integer value.
5827 if (!IsNonNegativeIntegerValue(ValExpr, *this, OMPC_num_threads,
5828 /*StrictlyPositive=*/true))
5831 return new (Context)
5832 OMPNumThreadsClause(ValExpr, StartLoc, LParenLoc, EndLoc);
5835 ExprResult Sema::VerifyPositiveIntegerConstantInClause(Expr *E,
5836 OpenMPClauseKind CKind,
5837 bool StrictlyPositive) {
5840 if (E->isValueDependent() || E->isTypeDependent() ||
5841 E->isInstantiationDependent() || E->containsUnexpandedParameterPack())
5843 llvm::APSInt Result;
5844 ExprResult ICE = VerifyIntegerConstantExpression(E, &Result);
5845 if (ICE.isInvalid())
5847 if ((StrictlyPositive && !Result.isStrictlyPositive()) ||
5848 (!StrictlyPositive && !Result.isNonNegative())) {
5849 Diag(E->getExprLoc(), diag::err_omp_negative_expression_in_clause)
5850 << getOpenMPClauseName(CKind) << (StrictlyPositive ? 1 : 0)
5851 << E->getSourceRange();
5854 if (CKind == OMPC_aligned && !Result.isPowerOf2()) {
5855 Diag(E->getExprLoc(), diag::warn_omp_alignment_not_power_of_two)
5856 << E->getSourceRange();
5859 if (CKind == OMPC_collapse && DSAStack->getAssociatedLoops() == 1)
5860 DSAStack->setAssociatedLoops(Result.getExtValue());
5861 else if (CKind == OMPC_ordered)
5862 DSAStack->setAssociatedLoops(Result.getExtValue());
5866 OMPClause *Sema::ActOnOpenMPSafelenClause(Expr *Len, SourceLocation StartLoc,
5867 SourceLocation LParenLoc,
5868 SourceLocation EndLoc) {
5869 // OpenMP [2.8.1, simd construct, Description]
5870 // The parameter of the safelen clause must be a constant
5871 // positive integer expression.
5872 ExprResult Safelen = VerifyPositiveIntegerConstantInClause(Len, OMPC_safelen);
5873 if (Safelen.isInvalid())
5875 return new (Context)
5876 OMPSafelenClause(Safelen.get(), StartLoc, LParenLoc, EndLoc);
5879 OMPClause *Sema::ActOnOpenMPSimdlenClause(Expr *Len, SourceLocation StartLoc,
5880 SourceLocation LParenLoc,
5881 SourceLocation EndLoc) {
5882 // OpenMP [2.8.1, simd construct, Description]
5883 // The parameter of the simdlen clause must be a constant
5884 // positive integer expression.
5885 ExprResult Simdlen = VerifyPositiveIntegerConstantInClause(Len, OMPC_simdlen);
5886 if (Simdlen.isInvalid())
5888 return new (Context)
5889 OMPSimdlenClause(Simdlen.get(), StartLoc, LParenLoc, EndLoc);
5892 OMPClause *Sema::ActOnOpenMPCollapseClause(Expr *NumForLoops,
5893 SourceLocation StartLoc,
5894 SourceLocation LParenLoc,
5895 SourceLocation EndLoc) {
5896 // OpenMP [2.7.1, loop construct, Description]
5897 // OpenMP [2.8.1, simd construct, Description]
5898 // OpenMP [2.9.6, distribute construct, Description]
5899 // The parameter of the collapse clause must be a constant
5900 // positive integer expression.
5901 ExprResult NumForLoopsResult =
5902 VerifyPositiveIntegerConstantInClause(NumForLoops, OMPC_collapse);
5903 if (NumForLoopsResult.isInvalid())
5905 return new (Context)
5906 OMPCollapseClause(NumForLoopsResult.get(), StartLoc, LParenLoc, EndLoc);
5909 OMPClause *Sema::ActOnOpenMPOrderedClause(SourceLocation StartLoc,
5910 SourceLocation EndLoc,
5911 SourceLocation LParenLoc,
5912 Expr *NumForLoops) {
5913 // OpenMP [2.7.1, loop construct, Description]
5914 // OpenMP [2.8.1, simd construct, Description]
5915 // OpenMP [2.9.6, distribute construct, Description]
5916 // The parameter of the ordered clause must be a constant
5917 // positive integer expression if any.
5918 if (NumForLoops && LParenLoc.isValid()) {
5919 ExprResult NumForLoopsResult =
5920 VerifyPositiveIntegerConstantInClause(NumForLoops, OMPC_ordered);
5921 if (NumForLoopsResult.isInvalid())
5923 NumForLoops = NumForLoopsResult.get();
5925 NumForLoops = nullptr;
5926 DSAStack->setOrderedRegion(/*IsOrdered=*/true, NumForLoops);
5927 return new (Context)
5928 OMPOrderedClause(NumForLoops, StartLoc, LParenLoc, EndLoc);
5931 OMPClause *Sema::ActOnOpenMPSimpleClause(
5932 OpenMPClauseKind Kind, unsigned Argument, SourceLocation ArgumentLoc,
5933 SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc) {
5934 OMPClause *Res = nullptr;
5938 ActOnOpenMPDefaultClause(static_cast<OpenMPDefaultClauseKind>(Argument),
5939 ArgumentLoc, StartLoc, LParenLoc, EndLoc);
5941 case OMPC_proc_bind:
5942 Res = ActOnOpenMPProcBindClause(
5943 static_cast<OpenMPProcBindClauseKind>(Argument), ArgumentLoc, StartLoc,
5948 case OMPC_num_threads:
5954 case OMPC_firstprivate:
5955 case OMPC_lastprivate:
5957 case OMPC_reduction:
5961 case OMPC_copyprivate:
5965 case OMPC_mergeable:
5966 case OMPC_threadprivate:
5978 case OMPC_num_teams:
5979 case OMPC_thread_limit:
5981 case OMPC_grainsize:
5983 case OMPC_num_tasks:
5986 llvm_unreachable("Clause is not allowed.");
5992 getListOfPossibleValues(OpenMPClauseKind K, unsigned First, unsigned Last,
5993 ArrayRef<unsigned> Exclude = llvm::None) {
5995 unsigned Bound = Last >= 2 ? Last - 2 : 0;
5996 unsigned Skipped = Exclude.size();
5997 auto S = Exclude.begin(), E = Exclude.end();
5998 for (unsigned i = First; i < Last; ++i) {
5999 if (std::find(S, E, i) != E) {
6004 Values += getOpenMPSimpleClauseTypeName(K, i);
6006 if (i == Bound - Skipped)
6008 else if (i != Bound + 1 - Skipped)
6014 OMPClause *Sema::ActOnOpenMPDefaultClause(OpenMPDefaultClauseKind Kind,
6015 SourceLocation KindKwLoc,
6016 SourceLocation StartLoc,
6017 SourceLocation LParenLoc,
6018 SourceLocation EndLoc) {
6019 if (Kind == OMPC_DEFAULT_unknown) {
6020 static_assert(OMPC_DEFAULT_unknown > 0,
6021 "OMPC_DEFAULT_unknown not greater than 0");
6022 Diag(KindKwLoc, diag::err_omp_unexpected_clause_value)
6023 << getListOfPossibleValues(OMPC_default, /*First=*/0,
6024 /*Last=*/OMPC_DEFAULT_unknown)
6025 << getOpenMPClauseName(OMPC_default);
6029 case OMPC_DEFAULT_none:
6030 DSAStack->setDefaultDSANone(KindKwLoc);
6032 case OMPC_DEFAULT_shared:
6033 DSAStack->setDefaultDSAShared(KindKwLoc);
6035 case OMPC_DEFAULT_unknown:
6036 llvm_unreachable("Clause kind is not allowed.");
6039 return new (Context)
6040 OMPDefaultClause(Kind, KindKwLoc, StartLoc, LParenLoc, EndLoc);
6043 OMPClause *Sema::ActOnOpenMPProcBindClause(OpenMPProcBindClauseKind Kind,
6044 SourceLocation KindKwLoc,
6045 SourceLocation StartLoc,
6046 SourceLocation LParenLoc,
6047 SourceLocation EndLoc) {
6048 if (Kind == OMPC_PROC_BIND_unknown) {
6049 Diag(KindKwLoc, diag::err_omp_unexpected_clause_value)
6050 << getListOfPossibleValues(OMPC_proc_bind, /*First=*/0,
6051 /*Last=*/OMPC_PROC_BIND_unknown)
6052 << getOpenMPClauseName(OMPC_proc_bind);
6055 return new (Context)
6056 OMPProcBindClause(Kind, KindKwLoc, StartLoc, LParenLoc, EndLoc);
6059 OMPClause *Sema::ActOnOpenMPSingleExprWithArgClause(
6060 OpenMPClauseKind Kind, ArrayRef<unsigned> Argument, Expr *Expr,
6061 SourceLocation StartLoc, SourceLocation LParenLoc,
6062 ArrayRef<SourceLocation> ArgumentLoc, SourceLocation DelimLoc,
6063 SourceLocation EndLoc) {
6064 OMPClause *Res = nullptr;
6067 enum { Modifier1, Modifier2, ScheduleKind, NumberOfElements };
6068 assert(Argument.size() == NumberOfElements &&
6069 ArgumentLoc.size() == NumberOfElements);
6070 Res = ActOnOpenMPScheduleClause(
6071 static_cast<OpenMPScheduleClauseModifier>(Argument[Modifier1]),
6072 static_cast<OpenMPScheduleClauseModifier>(Argument[Modifier2]),
6073 static_cast<OpenMPScheduleClauseKind>(Argument[ScheduleKind]), Expr,
6074 StartLoc, LParenLoc, ArgumentLoc[Modifier1], ArgumentLoc[Modifier2],
6075 ArgumentLoc[ScheduleKind], DelimLoc, EndLoc);
6078 assert(Argument.size() == 1 && ArgumentLoc.size() == 1);
6079 Res = ActOnOpenMPIfClause(static_cast<OpenMPDirectiveKind>(Argument.back()),
6080 Expr, StartLoc, LParenLoc, ArgumentLoc.back(),
6084 case OMPC_num_threads:
6089 case OMPC_proc_bind:
6091 case OMPC_firstprivate:
6092 case OMPC_lastprivate:
6094 case OMPC_reduction:
6098 case OMPC_copyprivate:
6102 case OMPC_mergeable:
6103 case OMPC_threadprivate:
6115 case OMPC_num_teams:
6116 case OMPC_thread_limit:
6118 case OMPC_grainsize:
6120 case OMPC_num_tasks:
6123 llvm_unreachable("Clause is not allowed.");
6128 static bool checkScheduleModifiers(Sema &S, OpenMPScheduleClauseModifier M1,
6129 OpenMPScheduleClauseModifier M2,
6130 SourceLocation M1Loc, SourceLocation M2Loc) {
6131 if (M1 == OMPC_SCHEDULE_MODIFIER_unknown && M1Loc.isValid()) {
6132 SmallVector<unsigned, 2> Excluded;
6133 if (M2 != OMPC_SCHEDULE_MODIFIER_unknown)
6134 Excluded.push_back(M2);
6135 if (M2 == OMPC_SCHEDULE_MODIFIER_nonmonotonic)
6136 Excluded.push_back(OMPC_SCHEDULE_MODIFIER_monotonic);
6137 if (M2 == OMPC_SCHEDULE_MODIFIER_monotonic)
6138 Excluded.push_back(OMPC_SCHEDULE_MODIFIER_nonmonotonic);
6139 S.Diag(M1Loc, diag::err_omp_unexpected_clause_value)
6140 << getListOfPossibleValues(OMPC_schedule,
6141 /*First=*/OMPC_SCHEDULE_MODIFIER_unknown + 1,
6142 /*Last=*/OMPC_SCHEDULE_MODIFIER_last,
6144 << getOpenMPClauseName(OMPC_schedule);
6150 OMPClause *Sema::ActOnOpenMPScheduleClause(
6151 OpenMPScheduleClauseModifier M1, OpenMPScheduleClauseModifier M2,
6152 OpenMPScheduleClauseKind Kind, Expr *ChunkSize, SourceLocation StartLoc,
6153 SourceLocation LParenLoc, SourceLocation M1Loc, SourceLocation M2Loc,
6154 SourceLocation KindLoc, SourceLocation CommaLoc, SourceLocation EndLoc) {
6155 if (checkScheduleModifiers(*this, M1, M2, M1Loc, M2Loc) ||
6156 checkScheduleModifiers(*this, M2, M1, M2Loc, M1Loc))
6158 // OpenMP, 2.7.1, Loop Construct, Restrictions
6159 // Either the monotonic modifier or the nonmonotonic modifier can be specified
6161 if ((M1 == M2 && M1 != OMPC_SCHEDULE_MODIFIER_unknown) ||
6162 (M1 == OMPC_SCHEDULE_MODIFIER_monotonic &&
6163 M2 == OMPC_SCHEDULE_MODIFIER_nonmonotonic) ||
6164 (M1 == OMPC_SCHEDULE_MODIFIER_nonmonotonic &&
6165 M2 == OMPC_SCHEDULE_MODIFIER_monotonic)) {
6166 Diag(M2Loc, diag::err_omp_unexpected_schedule_modifier)
6167 << getOpenMPSimpleClauseTypeName(OMPC_schedule, M2)
6168 << getOpenMPSimpleClauseTypeName(OMPC_schedule, M1);
6171 if (Kind == OMPC_SCHEDULE_unknown) {
6173 if (M1Loc.isInvalid() && M2Loc.isInvalid()) {
6174 unsigned Exclude[] = {OMPC_SCHEDULE_unknown};
6175 Values = getListOfPossibleValues(OMPC_schedule, /*First=*/0,
6176 /*Last=*/OMPC_SCHEDULE_MODIFIER_last,
6179 Values = getListOfPossibleValues(OMPC_schedule, /*First=*/0,
6180 /*Last=*/OMPC_SCHEDULE_unknown);
6182 Diag(KindLoc, diag::err_omp_unexpected_clause_value)
6183 << Values << getOpenMPClauseName(OMPC_schedule);
6186 // OpenMP, 2.7.1, Loop Construct, Restrictions
6187 // The nonmonotonic modifier can only be specified with schedule(dynamic) or
6188 // schedule(guided).
6189 if ((M1 == OMPC_SCHEDULE_MODIFIER_nonmonotonic ||
6190 M2 == OMPC_SCHEDULE_MODIFIER_nonmonotonic) &&
6191 Kind != OMPC_SCHEDULE_dynamic && Kind != OMPC_SCHEDULE_guided) {
6192 Diag(M1 == OMPC_SCHEDULE_MODIFIER_nonmonotonic ? M1Loc : M2Loc,
6193 diag::err_omp_schedule_nonmonotonic_static);
6196 Expr *ValExpr = ChunkSize;
6197 Expr *HelperValExpr = nullptr;
6199 if (!ChunkSize->isValueDependent() && !ChunkSize->isTypeDependent() &&
6200 !ChunkSize->isInstantiationDependent() &&
6201 !ChunkSize->containsUnexpandedParameterPack()) {
6202 SourceLocation ChunkSizeLoc = ChunkSize->getLocStart();
6204 PerformOpenMPImplicitIntegerConversion(ChunkSizeLoc, ChunkSize);
6205 if (Val.isInvalid())
6208 ValExpr = Val.get();
6210 // OpenMP [2.7.1, Restrictions]
6211 // chunk_size must be a loop invariant integer expression with a positive
6213 llvm::APSInt Result;
6214 if (ValExpr->isIntegerConstantExpr(Result, Context)) {
6215 if (Result.isSigned() && !Result.isStrictlyPositive()) {
6216 Diag(ChunkSizeLoc, diag::err_omp_negative_expression_in_clause)
6217 << "schedule" << 1 << ChunkSize->getSourceRange();
6220 } else if (isParallelOrTaskRegion(DSAStack->getCurrentDirective())) {
6221 auto *ImpVar = buildVarDecl(*this, ChunkSize->getExprLoc(),
6222 ChunkSize->getType(), ".chunk.");
6223 auto *ImpVarRef = buildDeclRefExpr(*this, ImpVar, ChunkSize->getType(),
6224 ChunkSize->getExprLoc(),
6225 /*RefersToCapture=*/true);
6226 HelperValExpr = ImpVarRef;
6231 return new (Context)
6232 OMPScheduleClause(StartLoc, LParenLoc, KindLoc, CommaLoc, EndLoc, Kind,
6233 ValExpr, HelperValExpr, M1, M1Loc, M2, M2Loc);
6236 OMPClause *Sema::ActOnOpenMPClause(OpenMPClauseKind Kind,
6237 SourceLocation StartLoc,
6238 SourceLocation EndLoc) {
6239 OMPClause *Res = nullptr;
6242 Res = ActOnOpenMPOrderedClause(StartLoc, EndLoc);
6245 Res = ActOnOpenMPNowaitClause(StartLoc, EndLoc);
6248 Res = ActOnOpenMPUntiedClause(StartLoc, EndLoc);
6250 case OMPC_mergeable:
6251 Res = ActOnOpenMPMergeableClause(StartLoc, EndLoc);
6254 Res = ActOnOpenMPReadClause(StartLoc, EndLoc);
6257 Res = ActOnOpenMPWriteClause(StartLoc, EndLoc);
6260 Res = ActOnOpenMPUpdateClause(StartLoc, EndLoc);
6263 Res = ActOnOpenMPCaptureClause(StartLoc, EndLoc);
6266 Res = ActOnOpenMPSeqCstClause(StartLoc, EndLoc);
6269 Res = ActOnOpenMPThreadsClause(StartLoc, EndLoc);
6272 Res = ActOnOpenMPSIMDClause(StartLoc, EndLoc);
6275 Res = ActOnOpenMPNogroupClause(StartLoc, EndLoc);
6279 case OMPC_num_threads:
6285 case OMPC_firstprivate:
6286 case OMPC_lastprivate:
6288 case OMPC_reduction:
6292 case OMPC_copyprivate:
6294 case OMPC_proc_bind:
6295 case OMPC_threadprivate:
6300 case OMPC_num_teams:
6301 case OMPC_thread_limit:
6303 case OMPC_grainsize:
6304 case OMPC_num_tasks:
6307 llvm_unreachable("Clause is not allowed.");
6312 OMPClause *Sema::ActOnOpenMPNowaitClause(SourceLocation StartLoc,
6313 SourceLocation EndLoc) {
6314 DSAStack->setNowaitRegion();
6315 return new (Context) OMPNowaitClause(StartLoc, EndLoc);
6318 OMPClause *Sema::ActOnOpenMPUntiedClause(SourceLocation StartLoc,
6319 SourceLocation EndLoc) {
6320 return new (Context) OMPUntiedClause(StartLoc, EndLoc);
6323 OMPClause *Sema::ActOnOpenMPMergeableClause(SourceLocation StartLoc,
6324 SourceLocation EndLoc) {
6325 return new (Context) OMPMergeableClause(StartLoc, EndLoc);
6328 OMPClause *Sema::ActOnOpenMPReadClause(SourceLocation StartLoc,
6329 SourceLocation EndLoc) {
6330 return new (Context) OMPReadClause(StartLoc, EndLoc);
6333 OMPClause *Sema::ActOnOpenMPWriteClause(SourceLocation StartLoc,
6334 SourceLocation EndLoc) {
6335 return new (Context) OMPWriteClause(StartLoc, EndLoc);
6338 OMPClause *Sema::ActOnOpenMPUpdateClause(SourceLocation StartLoc,
6339 SourceLocation EndLoc) {
6340 return new (Context) OMPUpdateClause(StartLoc, EndLoc);
6343 OMPClause *Sema::ActOnOpenMPCaptureClause(SourceLocation StartLoc,
6344 SourceLocation EndLoc) {
6345 return new (Context) OMPCaptureClause(StartLoc, EndLoc);
6348 OMPClause *Sema::ActOnOpenMPSeqCstClause(SourceLocation StartLoc,
6349 SourceLocation EndLoc) {
6350 return new (Context) OMPSeqCstClause(StartLoc, EndLoc);
6353 OMPClause *Sema::ActOnOpenMPThreadsClause(SourceLocation StartLoc,
6354 SourceLocation EndLoc) {
6355 return new (Context) OMPThreadsClause(StartLoc, EndLoc);
6358 OMPClause *Sema::ActOnOpenMPSIMDClause(SourceLocation StartLoc,
6359 SourceLocation EndLoc) {
6360 return new (Context) OMPSIMDClause(StartLoc, EndLoc);
6363 OMPClause *Sema::ActOnOpenMPNogroupClause(SourceLocation StartLoc,
6364 SourceLocation EndLoc) {
6365 return new (Context) OMPNogroupClause(StartLoc, EndLoc);
6368 OMPClause *Sema::ActOnOpenMPVarListClause(
6369 OpenMPClauseKind Kind, ArrayRef<Expr *> VarList, Expr *TailExpr,
6370 SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation ColonLoc,
6371 SourceLocation EndLoc, CXXScopeSpec &ReductionIdScopeSpec,
6372 const DeclarationNameInfo &ReductionId, OpenMPDependClauseKind DepKind,
6373 OpenMPLinearClauseKind LinKind, OpenMPMapClauseKind MapTypeModifier,
6374 OpenMPMapClauseKind MapType, SourceLocation DepLinMapLoc) {
6375 OMPClause *Res = nullptr;
6378 Res = ActOnOpenMPPrivateClause(VarList, StartLoc, LParenLoc, EndLoc);
6380 case OMPC_firstprivate:
6381 Res = ActOnOpenMPFirstprivateClause(VarList, StartLoc, LParenLoc, EndLoc);
6383 case OMPC_lastprivate:
6384 Res = ActOnOpenMPLastprivateClause(VarList, StartLoc, LParenLoc, EndLoc);
6387 Res = ActOnOpenMPSharedClause(VarList, StartLoc, LParenLoc, EndLoc);
6389 case OMPC_reduction:
6390 Res = ActOnOpenMPReductionClause(VarList, StartLoc, LParenLoc, ColonLoc,
6391 EndLoc, ReductionIdScopeSpec, ReductionId);
6394 Res = ActOnOpenMPLinearClause(VarList, TailExpr, StartLoc, LParenLoc,
6395 LinKind, DepLinMapLoc, ColonLoc, EndLoc);
6398 Res = ActOnOpenMPAlignedClause(VarList, TailExpr, StartLoc, LParenLoc,
6402 Res = ActOnOpenMPCopyinClause(VarList, StartLoc, LParenLoc, EndLoc);
6404 case OMPC_copyprivate:
6405 Res = ActOnOpenMPCopyprivateClause(VarList, StartLoc, LParenLoc, EndLoc);
6408 Res = ActOnOpenMPFlushClause(VarList, StartLoc, LParenLoc, EndLoc);
6411 Res = ActOnOpenMPDependClause(DepKind, DepLinMapLoc, ColonLoc, VarList,
6412 StartLoc, LParenLoc, EndLoc);
6415 Res = ActOnOpenMPMapClause(MapTypeModifier, MapType, DepLinMapLoc, ColonLoc,
6416 VarList, StartLoc, LParenLoc, EndLoc);
6420 case OMPC_num_threads:
6425 case OMPC_proc_bind:
6430 case OMPC_mergeable:
6431 case OMPC_threadprivate:
6440 case OMPC_num_teams:
6441 case OMPC_thread_limit:
6443 case OMPC_grainsize:
6445 case OMPC_num_tasks:
6448 llvm_unreachable("Clause is not allowed.");
6453 OMPClause *Sema::ActOnOpenMPPrivateClause(ArrayRef<Expr *> VarList,
6454 SourceLocation StartLoc,
6455 SourceLocation LParenLoc,
6456 SourceLocation EndLoc) {
6457 SmallVector<Expr *, 8> Vars;
6458 SmallVector<Expr *, 8> PrivateCopies;
6459 for (auto &RefExpr : VarList) {
6460 assert(RefExpr && "NULL expr in OpenMP private clause.");
6461 if (isa<DependentScopeDeclRefExpr>(RefExpr)) {
6462 // It will be analyzed later.
6463 Vars.push_back(RefExpr);
6464 PrivateCopies.push_back(nullptr);
6468 SourceLocation ELoc = RefExpr->getExprLoc();
6469 // OpenMP [2.1, C/C++]
6470 // A list item is a variable name.
6471 // OpenMP [2.9.3.3, Restrictions, p.1]
6472 // A variable that is part of another variable (as an array or
6473 // structure element) cannot appear in a private clause.
6474 DeclRefExpr *DE = dyn_cast_or_null<DeclRefExpr>(RefExpr);
6475 if (!DE || !isa<VarDecl>(DE->getDecl())) {
6476 Diag(ELoc, diag::err_omp_expected_var_name) << RefExpr->getSourceRange();
6479 Decl *D = DE->getDecl();
6480 VarDecl *VD = cast<VarDecl>(D);
6482 QualType Type = VD->getType();
6483 if (Type->isDependentType() || Type->isInstantiationDependentType()) {
6484 // It will be analyzed later.
6486 PrivateCopies.push_back(nullptr);
6490 // OpenMP [2.9.3.3, Restrictions, C/C++, p.3]
6491 // A variable that appears in a private clause must not have an incomplete
6492 // type or a reference type.
6493 if (RequireCompleteType(ELoc, Type,
6494 diag::err_omp_private_incomplete_type)) {
6497 Type = Type.getNonReferenceType();
6499 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
6501 // Variables with the predetermined data-sharing attributes may not be
6502 // listed in data-sharing attributes clauses, except for the cases
6503 // listed below. For these exceptions only, listing a predetermined
6504 // variable in a data-sharing attribute clause is allowed and overrides
6505 // the variable's predetermined data-sharing attributes.
6506 DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(VD, false);
6507 if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_private) {
6508 Diag(ELoc, diag::err_omp_wrong_dsa) << getOpenMPClauseName(DVar.CKind)
6509 << getOpenMPClauseName(OMPC_private);
6510 ReportOriginalDSA(*this, DSAStack, VD, DVar);
6514 // Variably modified types are not supported for tasks.
6515 if (!Type->isAnyPointerType() && Type->isVariablyModifiedType() &&
6516 DSAStack->getCurrentDirective() == OMPD_task) {
6517 Diag(ELoc, diag::err_omp_variably_modified_type_not_supported)
6518 << getOpenMPClauseName(OMPC_private) << Type
6519 << getOpenMPDirectiveName(DSAStack->getCurrentDirective());
6521 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
6522 Diag(VD->getLocation(),
6523 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
6528 // OpenMP [2.9.3.3, Restrictions, C/C++, p.1]
6529 // A variable of class type (or array thereof) that appears in a private
6530 // clause requires an accessible, unambiguous default constructor for the
6532 // Generate helper private variable and initialize it with the default
6533 // value. The address of the original variable is replaced by the address of
6534 // the new private variable in CodeGen. This new variable is not added to
6535 // IdResolver, so the code in the OpenMP region uses original variable for
6536 // proper diagnostics.
6537 Type = Type.getUnqualifiedType();
6538 auto VDPrivate = buildVarDecl(*this, DE->getExprLoc(), Type, VD->getName(),
6539 VD->hasAttrs() ? &VD->getAttrs() : nullptr);
6540 ActOnUninitializedDecl(VDPrivate, /*TypeMayContainAuto=*/false);
6541 if (VDPrivate->isInvalidDecl())
6543 auto VDPrivateRefExpr = buildDeclRefExpr(
6544 *this, VDPrivate, DE->getType().getUnqualifiedType(), DE->getExprLoc());
6546 DSAStack->addDSA(VD, DE, OMPC_private);
6548 PrivateCopies.push_back(VDPrivateRefExpr);
6554 return OMPPrivateClause::Create(Context, StartLoc, LParenLoc, EndLoc, Vars,
6559 class DiagsUninitializedSeveretyRAII {
6561 DiagnosticsEngine &Diags;
6562 SourceLocation SavedLoc;
6566 DiagsUninitializedSeveretyRAII(DiagnosticsEngine &Diags, SourceLocation Loc,
6568 : Diags(Diags), SavedLoc(Loc), IsIgnored(IsIgnored) {
6570 Diags.setSeverity(/*Diag*/ diag::warn_uninit_self_reference_in_init,
6571 /*Map*/ diag::Severity::Ignored, Loc);
6574 ~DiagsUninitializedSeveretyRAII() {
6576 Diags.popMappings(SavedLoc);
6581 OMPClause *Sema::ActOnOpenMPFirstprivateClause(ArrayRef<Expr *> VarList,
6582 SourceLocation StartLoc,
6583 SourceLocation LParenLoc,
6584 SourceLocation EndLoc) {
6585 SmallVector<Expr *, 8> Vars;
6586 SmallVector<Expr *, 8> PrivateCopies;
6587 SmallVector<Expr *, 8> Inits;
6588 bool IsImplicitClause =
6589 StartLoc.isInvalid() && LParenLoc.isInvalid() && EndLoc.isInvalid();
6590 auto ImplicitClauseLoc = DSAStack->getConstructLoc();
6592 for (auto &RefExpr : VarList) {
6593 assert(RefExpr && "NULL expr in OpenMP firstprivate clause.");
6594 if (isa<DependentScopeDeclRefExpr>(RefExpr)) {
6595 // It will be analyzed later.
6596 Vars.push_back(RefExpr);
6597 PrivateCopies.push_back(nullptr);
6598 Inits.push_back(nullptr);
6602 SourceLocation ELoc =
6603 IsImplicitClause ? ImplicitClauseLoc : RefExpr->getExprLoc();
6604 // OpenMP [2.1, C/C++]
6605 // A list item is a variable name.
6606 // OpenMP [2.9.3.3, Restrictions, p.1]
6607 // A variable that is part of another variable (as an array or
6608 // structure element) cannot appear in a private clause.
6609 DeclRefExpr *DE = dyn_cast_or_null<DeclRefExpr>(RefExpr);
6610 if (!DE || !isa<VarDecl>(DE->getDecl())) {
6611 Diag(ELoc, diag::err_omp_expected_var_name) << RefExpr->getSourceRange();
6614 Decl *D = DE->getDecl();
6615 VarDecl *VD = cast<VarDecl>(D);
6617 QualType Type = VD->getType();
6618 if (Type->isDependentType() || Type->isInstantiationDependentType()) {
6619 // It will be analyzed later.
6621 PrivateCopies.push_back(nullptr);
6622 Inits.push_back(nullptr);
6626 // OpenMP [2.9.3.3, Restrictions, C/C++, p.3]
6627 // A variable that appears in a private clause must not have an incomplete
6628 // type or a reference type.
6629 if (RequireCompleteType(ELoc, Type,
6630 diag::err_omp_firstprivate_incomplete_type)) {
6633 Type = Type.getNonReferenceType();
6635 // OpenMP [2.9.3.4, Restrictions, C/C++, p.1]
6636 // A variable of class type (or array thereof) that appears in a private
6637 // clause requires an accessible, unambiguous copy constructor for the
6639 auto ElemType = Context.getBaseElementType(Type).getNonReferenceType();
6641 // If an implicit firstprivate variable found it was checked already.
6642 if (!IsImplicitClause) {
6643 DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(VD, false);
6644 bool IsConstant = ElemType.isConstant(Context);
6645 // OpenMP [2.4.13, Data-sharing Attribute Clauses]
6646 // A list item that specifies a given variable may not appear in more
6647 // than one clause on the same directive, except that a variable may be
6648 // specified in both firstprivate and lastprivate clauses.
6649 if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_firstprivate &&
6650 DVar.CKind != OMPC_lastprivate && DVar.RefExpr) {
6651 Diag(ELoc, diag::err_omp_wrong_dsa)
6652 << getOpenMPClauseName(DVar.CKind)
6653 << getOpenMPClauseName(OMPC_firstprivate);
6654 ReportOriginalDSA(*this, DSAStack, VD, DVar);
6658 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
6660 // Variables with the predetermined data-sharing attributes may not be
6661 // listed in data-sharing attributes clauses, except for the cases
6662 // listed below. For these exceptions only, listing a predetermined
6663 // variable in a data-sharing attribute clause is allowed and overrides
6664 // the variable's predetermined data-sharing attributes.
6665 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
6666 // in a Construct, C/C++, p.2]
6667 // Variables with const-qualified type having no mutable member may be
6668 // listed in a firstprivate clause, even if they are static data members.
6669 if (!(IsConstant || VD->isStaticDataMember()) && !DVar.RefExpr &&
6670 DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_shared) {
6671 Diag(ELoc, diag::err_omp_wrong_dsa)
6672 << getOpenMPClauseName(DVar.CKind)
6673 << getOpenMPClauseName(OMPC_firstprivate);
6674 ReportOriginalDSA(*this, DSAStack, VD, DVar);
6678 OpenMPDirectiveKind CurrDir = DSAStack->getCurrentDirective();
6679 // OpenMP [2.9.3.4, Restrictions, p.2]
6680 // A list item that is private within a parallel region must not appear
6681 // in a firstprivate clause on a worksharing construct if any of the
6682 // worksharing regions arising from the worksharing construct ever bind
6683 // to any of the parallel regions arising from the parallel construct.
6684 if (isOpenMPWorksharingDirective(CurrDir) &&
6685 !isOpenMPParallelDirective(CurrDir)) {
6686 DVar = DSAStack->getImplicitDSA(VD, true);
6687 if (DVar.CKind != OMPC_shared &&
6688 (isOpenMPParallelDirective(DVar.DKind) ||
6689 DVar.DKind == OMPD_unknown)) {
6690 Diag(ELoc, diag::err_omp_required_access)
6691 << getOpenMPClauseName(OMPC_firstprivate)
6692 << getOpenMPClauseName(OMPC_shared);
6693 ReportOriginalDSA(*this, DSAStack, VD, DVar);
6697 // OpenMP [2.9.3.4, Restrictions, p.3]
6698 // A list item that appears in a reduction clause of a parallel construct
6699 // must not appear in a firstprivate clause on a worksharing or task
6700 // construct if any of the worksharing or task regions arising from the
6701 // worksharing or task construct ever bind to any of the parallel regions
6702 // arising from the parallel construct.
6703 // OpenMP [2.9.3.4, Restrictions, p.4]
6704 // A list item that appears in a reduction clause in worksharing
6705 // construct must not appear in a firstprivate clause in a task construct
6706 // encountered during execution of any of the worksharing regions arising
6707 // from the worksharing construct.
6708 if (CurrDir == OMPD_task) {
6710 DSAStack->hasInnermostDSA(VD, MatchesAnyClause(OMPC_reduction),
6711 [](OpenMPDirectiveKind K) -> bool {
6712 return isOpenMPParallelDirective(K) ||
6713 isOpenMPWorksharingDirective(K);
6716 if (DVar.CKind == OMPC_reduction &&
6717 (isOpenMPParallelDirective(DVar.DKind) ||
6718 isOpenMPWorksharingDirective(DVar.DKind))) {
6719 Diag(ELoc, diag::err_omp_parallel_reduction_in_task_firstprivate)
6720 << getOpenMPDirectiveName(DVar.DKind);
6721 ReportOriginalDSA(*this, DSAStack, VD, DVar);
6726 // OpenMP 4.5 [2.15.3.4, Restrictions, p.3]
6727 // A list item that is private within a teams region must not appear in a
6728 // firstprivate clause on a distribute construct if any of the distribute
6729 // regions arising from the distribute construct ever bind to any of the
6730 // teams regions arising from the teams construct.
6731 // OpenMP 4.5 [2.15.3.4, Restrictions, p.3]
6732 // A list item that appears in a reduction clause of a teams construct
6733 // must not appear in a firstprivate clause on a distribute construct if
6734 // any of the distribute regions arising from the distribute construct
6735 // ever bind to any of the teams regions arising from the teams construct.
6736 // OpenMP 4.5 [2.10.8, Distribute Construct, p.3]
6737 // A list item may appear in a firstprivate or lastprivate clause but not
6739 if (CurrDir == OMPD_distribute) {
6740 DVar = DSAStack->hasInnermostDSA(VD, MatchesAnyClause(OMPC_private),
6741 [](OpenMPDirectiveKind K) -> bool {
6742 return isOpenMPTeamsDirective(K);
6745 if (DVar.CKind == OMPC_private && isOpenMPTeamsDirective(DVar.DKind)) {
6746 Diag(ELoc, diag::err_omp_firstprivate_distribute_private_teams);
6747 ReportOriginalDSA(*this, DSAStack, VD, DVar);
6750 DVar = DSAStack->hasInnermostDSA(VD, MatchesAnyClause(OMPC_reduction),
6751 [](OpenMPDirectiveKind K) -> bool {
6752 return isOpenMPTeamsDirective(K);
6755 if (DVar.CKind == OMPC_reduction &&
6756 isOpenMPTeamsDirective(DVar.DKind)) {
6757 Diag(ELoc, diag::err_omp_firstprivate_distribute_in_teams_reduction);
6758 ReportOriginalDSA(*this, DSAStack, VD, DVar);
6761 DVar = DSAStack->getTopDSA(VD, false);
6762 if (DVar.CKind == OMPC_lastprivate) {
6763 Diag(ELoc, diag::err_omp_firstprivate_and_lastprivate_in_distribute);
6764 ReportOriginalDSA(*this, DSAStack, VD, DVar);
6770 // Variably modified types are not supported for tasks.
6771 if (!Type->isAnyPointerType() && Type->isVariablyModifiedType() &&
6772 DSAStack->getCurrentDirective() == OMPD_task) {
6773 Diag(ELoc, diag::err_omp_variably_modified_type_not_supported)
6774 << getOpenMPClauseName(OMPC_firstprivate) << Type
6775 << getOpenMPDirectiveName(DSAStack->getCurrentDirective());
6777 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
6778 Diag(VD->getLocation(),
6779 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
6784 Type = Type.getUnqualifiedType();
6785 auto VDPrivate = buildVarDecl(*this, ELoc, Type, VD->getName(),
6786 VD->hasAttrs() ? &VD->getAttrs() : nullptr);
6787 // Generate helper private variable and initialize it with the value of the
6788 // original variable. The address of the original variable is replaced by
6789 // the address of the new private variable in the CodeGen. This new variable
6790 // is not added to IdResolver, so the code in the OpenMP region uses
6791 // original variable for proper diagnostics and variable capturing.
6792 Expr *VDInitRefExpr = nullptr;
6793 // For arrays generate initializer for single element and replace it by the
6794 // original array element in CodeGen.
6795 if (Type->isArrayType()) {
6797 buildVarDecl(*this, DE->getExprLoc(), ElemType, VD->getName());
6798 VDInitRefExpr = buildDeclRefExpr(*this, VDInit, ElemType, ELoc);
6799 auto Init = DefaultLvalueConversion(VDInitRefExpr).get();
6800 ElemType = ElemType.getUnqualifiedType();
6801 auto *VDInitTemp = buildVarDecl(*this, DE->getLocStart(), ElemType,
6802 ".firstprivate.temp");
6803 InitializedEntity Entity =
6804 InitializedEntity::InitializeVariable(VDInitTemp);
6805 InitializationKind Kind = InitializationKind::CreateCopy(ELoc, ELoc);
6807 InitializationSequence InitSeq(*this, Entity, Kind, Init);
6808 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Init);
6809 if (Result.isInvalid())
6810 VDPrivate->setInvalidDecl();
6812 VDPrivate->setInit(Result.getAs<Expr>());
6813 // Remove temp variable declaration.
6814 Context.Deallocate(VDInitTemp);
6817 buildVarDecl(*this, DE->getLocStart(), Type, ".firstprivate.temp");
6819 buildDeclRefExpr(*this, VDInit, DE->getType(), DE->getExprLoc());
6820 AddInitializerToDecl(VDPrivate,
6821 DefaultLvalueConversion(VDInitRefExpr).get(),
6822 /*DirectInit=*/false, /*TypeMayContainAuto=*/false);
6824 if (VDPrivate->isInvalidDecl()) {
6825 if (IsImplicitClause) {
6826 Diag(DE->getExprLoc(),
6827 diag::note_omp_task_predetermined_firstprivate_here);
6831 CurContext->addDecl(VDPrivate);
6832 auto VDPrivateRefExpr = buildDeclRefExpr(
6833 *this, VDPrivate, DE->getType().getUnqualifiedType(), DE->getExprLoc());
6834 DSAStack->addDSA(VD, DE, OMPC_firstprivate);
6836 PrivateCopies.push_back(VDPrivateRefExpr);
6837 Inits.push_back(VDInitRefExpr);
6843 return OMPFirstprivateClause::Create(Context, StartLoc, LParenLoc, EndLoc,
6844 Vars, PrivateCopies, Inits);
6847 OMPClause *Sema::ActOnOpenMPLastprivateClause(ArrayRef<Expr *> VarList,
6848 SourceLocation StartLoc,
6849 SourceLocation LParenLoc,
6850 SourceLocation EndLoc) {
6851 SmallVector<Expr *, 8> Vars;
6852 SmallVector<Expr *, 8> SrcExprs;
6853 SmallVector<Expr *, 8> DstExprs;
6854 SmallVector<Expr *, 8> AssignmentOps;
6855 for (auto &RefExpr : VarList) {
6856 assert(RefExpr && "NULL expr in OpenMP lastprivate clause.");
6857 if (isa<DependentScopeDeclRefExpr>(RefExpr)) {
6858 // It will be analyzed later.
6859 Vars.push_back(RefExpr);
6860 SrcExprs.push_back(nullptr);
6861 DstExprs.push_back(nullptr);
6862 AssignmentOps.push_back(nullptr);
6866 SourceLocation ELoc = RefExpr->getExprLoc();
6867 // OpenMP [2.1, C/C++]
6868 // A list item is a variable name.
6869 // OpenMP [2.14.3.5, Restrictions, p.1]
6870 // A variable that is part of another variable (as an array or structure
6871 // element) cannot appear in a lastprivate clause.
6872 DeclRefExpr *DE = dyn_cast_or_null<DeclRefExpr>(RefExpr);
6873 if (!DE || !isa<VarDecl>(DE->getDecl())) {
6874 Diag(ELoc, diag::err_omp_expected_var_name) << RefExpr->getSourceRange();
6877 Decl *D = DE->getDecl();
6878 VarDecl *VD = cast<VarDecl>(D);
6880 QualType Type = VD->getType();
6881 if (Type->isDependentType() || Type->isInstantiationDependentType()) {
6882 // It will be analyzed later.
6884 SrcExprs.push_back(nullptr);
6885 DstExprs.push_back(nullptr);
6886 AssignmentOps.push_back(nullptr);
6890 // OpenMP [2.14.3.5, Restrictions, C/C++, p.2]
6891 // A variable that appears in a lastprivate clause must not have an
6892 // incomplete type or a reference type.
6893 if (RequireCompleteType(ELoc, Type,
6894 diag::err_omp_lastprivate_incomplete_type)) {
6897 Type = Type.getNonReferenceType();
6899 // OpenMP [2.14.1.1, Data-sharing Attribute Rules for Variables Referenced
6901 // Variables with the predetermined data-sharing attributes may not be
6902 // listed in data-sharing attributes clauses, except for the cases
6904 DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(VD, false);
6905 if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_lastprivate &&
6906 DVar.CKind != OMPC_firstprivate &&
6907 (DVar.CKind != OMPC_private || DVar.RefExpr != nullptr)) {
6908 Diag(ELoc, diag::err_omp_wrong_dsa)
6909 << getOpenMPClauseName(DVar.CKind)
6910 << getOpenMPClauseName(OMPC_lastprivate);
6911 ReportOriginalDSA(*this, DSAStack, VD, DVar);
6915 OpenMPDirectiveKind CurrDir = DSAStack->getCurrentDirective();
6916 // OpenMP [2.14.3.5, Restrictions, p.2]
6917 // A list item that is private within a parallel region, or that appears in
6918 // the reduction clause of a parallel construct, must not appear in a
6919 // lastprivate clause on a worksharing construct if any of the corresponding
6920 // worksharing regions ever binds to any of the corresponding parallel
6922 DSAStackTy::DSAVarData TopDVar = DVar;
6923 if (isOpenMPWorksharingDirective(CurrDir) &&
6924 !isOpenMPParallelDirective(CurrDir)) {
6925 DVar = DSAStack->getImplicitDSA(VD, true);
6926 if (DVar.CKind != OMPC_shared) {
6927 Diag(ELoc, diag::err_omp_required_access)
6928 << getOpenMPClauseName(OMPC_lastprivate)
6929 << getOpenMPClauseName(OMPC_shared);
6930 ReportOriginalDSA(*this, DSAStack, VD, DVar);
6934 // OpenMP [2.14.3.5, Restrictions, C++, p.1,2]
6935 // A variable of class type (or array thereof) that appears in a
6936 // lastprivate clause requires an accessible, unambiguous default
6937 // constructor for the class type, unless the list item is also specified
6938 // in a firstprivate clause.
6939 // A variable of class type (or array thereof) that appears in a
6940 // lastprivate clause requires an accessible, unambiguous copy assignment
6941 // operator for the class type.
6942 Type = Context.getBaseElementType(Type).getNonReferenceType();
6943 auto *SrcVD = buildVarDecl(*this, DE->getLocStart(),
6944 Type.getUnqualifiedType(), ".lastprivate.src",
6945 VD->hasAttrs() ? &VD->getAttrs() : nullptr);
6946 auto *PseudoSrcExpr = buildDeclRefExpr(
6947 *this, SrcVD, Type.getUnqualifiedType(), DE->getExprLoc());
6949 buildVarDecl(*this, DE->getLocStart(), Type, ".lastprivate.dst",
6950 VD->hasAttrs() ? &VD->getAttrs() : nullptr);
6951 auto *PseudoDstExpr =
6952 buildDeclRefExpr(*this, DstVD, Type, DE->getExprLoc());
6953 // For arrays generate assignment operation for single element and replace
6954 // it by the original array element in CodeGen.
6955 auto AssignmentOp = BuildBinOp(/*S=*/nullptr, DE->getExprLoc(), BO_Assign,
6956 PseudoDstExpr, PseudoSrcExpr);
6957 if (AssignmentOp.isInvalid())
6959 AssignmentOp = ActOnFinishFullExpr(AssignmentOp.get(), DE->getExprLoc(),
6960 /*DiscardedValue=*/true);
6961 if (AssignmentOp.isInvalid())
6964 // OpenMP 4.5 [2.10.8, Distribute Construct, p.3]
6965 // A list item may appear in a firstprivate or lastprivate clause but not
6967 if (CurrDir == OMPD_distribute) {
6968 DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(VD, false);
6969 if (DVar.CKind == OMPC_firstprivate) {
6970 Diag(ELoc, diag::err_omp_firstprivate_and_lastprivate_in_distribute);
6971 ReportOriginalDSA(*this, DSAStack, VD, DVar);
6976 if (TopDVar.CKind != OMPC_firstprivate)
6977 DSAStack->addDSA(VD, DE, OMPC_lastprivate);
6979 SrcExprs.push_back(PseudoSrcExpr);
6980 DstExprs.push_back(PseudoDstExpr);
6981 AssignmentOps.push_back(AssignmentOp.get());
6987 return OMPLastprivateClause::Create(Context, StartLoc, LParenLoc, EndLoc,
6988 Vars, SrcExprs, DstExprs, AssignmentOps);
6991 OMPClause *Sema::ActOnOpenMPSharedClause(ArrayRef<Expr *> VarList,
6992 SourceLocation StartLoc,
6993 SourceLocation LParenLoc,
6994 SourceLocation EndLoc) {
6995 SmallVector<Expr *, 8> Vars;
6996 for (auto &RefExpr : VarList) {
6997 assert(RefExpr && "NULL expr in OpenMP shared clause.");
6998 if (isa<DependentScopeDeclRefExpr>(RefExpr)) {
6999 // It will be analyzed later.
7000 Vars.push_back(RefExpr);
7004 SourceLocation ELoc = RefExpr->getExprLoc();
7005 // OpenMP [2.1, C/C++]
7006 // A list item is a variable name.
7007 // OpenMP [2.14.3.2, Restrictions, p.1]
7008 // A variable that is part of another variable (as an array or structure
7009 // element) cannot appear in a shared unless it is a static data member
7011 DeclRefExpr *DE = dyn_cast<DeclRefExpr>(RefExpr);
7012 if (!DE || !isa<VarDecl>(DE->getDecl())) {
7013 Diag(ELoc, diag::err_omp_expected_var_name) << RefExpr->getSourceRange();
7016 Decl *D = DE->getDecl();
7017 VarDecl *VD = cast<VarDecl>(D);
7019 QualType Type = VD->getType();
7020 if (Type->isDependentType() || Type->isInstantiationDependentType()) {
7021 // It will be analyzed later.
7026 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
7028 // Variables with the predetermined data-sharing attributes may not be
7029 // listed in data-sharing attributes clauses, except for the cases
7030 // listed below. For these exceptions only, listing a predetermined
7031 // variable in a data-sharing attribute clause is allowed and overrides
7032 // the variable's predetermined data-sharing attributes.
7033 DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(VD, false);
7034 if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_shared &&
7036 Diag(ELoc, diag::err_omp_wrong_dsa) << getOpenMPClauseName(DVar.CKind)
7037 << getOpenMPClauseName(OMPC_shared);
7038 ReportOriginalDSA(*this, DSAStack, VD, DVar);
7042 DSAStack->addDSA(VD, DE, OMPC_shared);
7049 return OMPSharedClause::Create(Context, StartLoc, LParenLoc, EndLoc, Vars);
7053 class DSARefChecker : public StmtVisitor<DSARefChecker, bool> {
7057 bool VisitDeclRefExpr(DeclRefExpr *E) {
7058 if (VarDecl *VD = dyn_cast<VarDecl>(E->getDecl())) {
7059 DSAStackTy::DSAVarData DVar = Stack->getTopDSA(VD, false);
7060 if (DVar.CKind == OMPC_shared && !DVar.RefExpr)
7062 if (DVar.CKind != OMPC_unknown)
7064 DSAStackTy::DSAVarData DVarPrivate =
7065 Stack->hasDSA(VD, isOpenMPPrivate, MatchesAlways(), false);
7066 if (DVarPrivate.CKind != OMPC_unknown)
7072 bool VisitStmt(Stmt *S) {
7073 for (auto Child : S->children()) {
7074 if (Child && Visit(Child))
7079 explicit DSARefChecker(DSAStackTy *S) : Stack(S) {}
7083 OMPClause *Sema::ActOnOpenMPReductionClause(
7084 ArrayRef<Expr *> VarList, SourceLocation StartLoc, SourceLocation LParenLoc,
7085 SourceLocation ColonLoc, SourceLocation EndLoc,
7086 CXXScopeSpec &ReductionIdScopeSpec,
7087 const DeclarationNameInfo &ReductionId) {
7088 // TODO: Allow scope specification search when 'declare reduction' is
7090 assert(ReductionIdScopeSpec.isEmpty() &&
7091 "No support for scoped reduction identifiers yet.");
7093 auto DN = ReductionId.getName();
7094 auto OOK = DN.getCXXOverloadedOperator();
7095 BinaryOperatorKind BOK = BO_Comma;
7097 // OpenMP [2.14.3.6, reduction clause]
7099 // reduction-identifier is either an identifier or one of the following
7100 // operators: +, -, *, &, |, ^, && and ||
7102 // reduction-identifier is either an id-expression or one of the following
7103 // operators: +, -, *, &, |, ^, && and ||
7104 // FIXME: Only 'min' and 'max' identifiers are supported for now.
7131 case OO_Array_Delete:
7140 case OO_GreaterEqual:
7145 case OO_PercentEqual:
7150 case OO_GreaterGreater:
7151 case OO_LessLessEqual:
7152 case OO_GreaterGreaterEqual:
7154 case OO_ExclaimEqual:
7162 case OO_Conditional:
7164 case NUM_OVERLOADED_OPERATORS:
7165 llvm_unreachable("Unexpected reduction identifier");
7167 if (auto II = DN.getAsIdentifierInfo()) {
7168 if (II->isStr("max"))
7170 else if (II->isStr("min"))
7175 SourceRange ReductionIdRange;
7176 if (ReductionIdScopeSpec.isValid()) {
7177 ReductionIdRange.setBegin(ReductionIdScopeSpec.getBeginLoc());
7179 ReductionIdRange.setEnd(ReductionId.getEndLoc());
7180 if (BOK == BO_Comma) {
7181 // Not allowed reduction identifier is found.
7182 Diag(ReductionId.getLocStart(), diag::err_omp_unknown_reduction_identifier)
7183 << ReductionIdRange;
7187 SmallVector<Expr *, 8> Vars;
7188 SmallVector<Expr *, 8> Privates;
7189 SmallVector<Expr *, 8> LHSs;
7190 SmallVector<Expr *, 8> RHSs;
7191 SmallVector<Expr *, 8> ReductionOps;
7192 for (auto RefExpr : VarList) {
7193 assert(RefExpr && "nullptr expr in OpenMP reduction clause.");
7194 if (isa<DependentScopeDeclRefExpr>(RefExpr)) {
7195 // It will be analyzed later.
7196 Vars.push_back(RefExpr);
7197 Privates.push_back(nullptr);
7198 LHSs.push_back(nullptr);
7199 RHSs.push_back(nullptr);
7200 ReductionOps.push_back(nullptr);
7204 if (RefExpr->isTypeDependent() || RefExpr->isValueDependent() ||
7205 RefExpr->isInstantiationDependent() ||
7206 RefExpr->containsUnexpandedParameterPack()) {
7207 // It will be analyzed later.
7208 Vars.push_back(RefExpr);
7209 Privates.push_back(nullptr);
7210 LHSs.push_back(nullptr);
7211 RHSs.push_back(nullptr);
7212 ReductionOps.push_back(nullptr);
7216 auto ELoc = RefExpr->getExprLoc();
7217 auto ERange = RefExpr->getSourceRange();
7218 // OpenMP [2.1, C/C++]
7219 // A list item is a variable or array section, subject to the restrictions
7220 // specified in Section 2.4 on page 42 and in each of the sections
7221 // describing clauses and directives for which a list appears.
7222 // OpenMP [2.14.3.3, Restrictions, p.1]
7223 // A variable that is part of another variable (as an array or
7224 // structure element) cannot appear in a private clause.
7225 auto *DE = dyn_cast<DeclRefExpr>(RefExpr);
7226 auto *ASE = dyn_cast<ArraySubscriptExpr>(RefExpr);
7227 auto *OASE = dyn_cast<OMPArraySectionExpr>(RefExpr);
7228 if (!ASE && !OASE && (!DE || !isa<VarDecl>(DE->getDecl()))) {
7229 Diag(ELoc, diag::err_omp_expected_var_name_or_array_item) << ERange;
7233 VarDecl *VD = nullptr;
7235 auto D = DE->getDecl();
7236 VD = cast<VarDecl>(D);
7237 Type = VD->getType();
7239 Type = ASE->getType();
7240 auto *Base = ASE->getBase()->IgnoreParenImpCasts();
7241 while (auto *TempASE = dyn_cast<ArraySubscriptExpr>(Base))
7242 Base = TempASE->getBase()->IgnoreParenImpCasts();
7243 DE = dyn_cast<DeclRefExpr>(Base);
7245 VD = dyn_cast<VarDecl>(DE->getDecl());
7247 Diag(Base->getExprLoc(), diag::err_omp_expected_base_var_name)
7248 << 0 << Base->getSourceRange();
7252 auto BaseType = OMPArraySectionExpr::getBaseOriginalType(OASE->getBase());
7253 if (auto *ATy = BaseType->getAsArrayTypeUnsafe())
7254 Type = ATy->getElementType();
7256 Type = BaseType->getPointeeType();
7257 auto *Base = OASE->getBase()->IgnoreParenImpCasts();
7258 while (auto *TempOASE = dyn_cast<OMPArraySectionExpr>(Base))
7259 Base = TempOASE->getBase()->IgnoreParenImpCasts();
7260 while (auto *TempASE = dyn_cast<ArraySubscriptExpr>(Base))
7261 Base = TempASE->getBase()->IgnoreParenImpCasts();
7262 DE = dyn_cast<DeclRefExpr>(Base);
7264 VD = dyn_cast<VarDecl>(DE->getDecl());
7266 Diag(Base->getExprLoc(), diag::err_omp_expected_base_var_name)
7267 << 1 << Base->getSourceRange();
7272 // OpenMP [2.9.3.3, Restrictions, C/C++, p.3]
7273 // A variable that appears in a private clause must not have an incomplete
7274 // type or a reference type.
7275 if (RequireCompleteType(ELoc, Type,
7276 diag::err_omp_reduction_incomplete_type))
7278 // OpenMP [2.14.3.6, reduction clause, Restrictions]
7279 // Arrays may not appear in a reduction clause.
7280 if (Type.getNonReferenceType()->isArrayType()) {
7281 Diag(ELoc, diag::err_omp_reduction_type_array) << Type << ERange;
7282 if (!ASE && !OASE) {
7283 bool IsDecl = VD->isThisDeclarationADefinition(Context) ==
7284 VarDecl::DeclarationOnly;
7285 Diag(VD->getLocation(),
7286 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
7291 // OpenMP [2.14.3.6, reduction clause, Restrictions]
7292 // A list item that appears in a reduction clause must not be
7294 if (Type.getNonReferenceType().isConstant(Context)) {
7295 Diag(ELoc, diag::err_omp_const_reduction_list_item)
7296 << getOpenMPClauseName(OMPC_reduction) << Type << ERange;
7297 if (!ASE && !OASE) {
7298 bool IsDecl = VD->isThisDeclarationADefinition(Context) ==
7299 VarDecl::DeclarationOnly;
7300 Diag(VD->getLocation(),
7301 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
7306 // OpenMP [2.9.3.6, Restrictions, C/C++, p.4]
7307 // If a list-item is a reference type then it must bind to the same object
7308 // for all threads of the team.
7309 if (!ASE && !OASE) {
7310 VarDecl *VDDef = VD->getDefinition();
7311 if (Type->isReferenceType() && VDDef) {
7312 DSARefChecker Check(DSAStack);
7313 if (Check.Visit(VDDef->getInit())) {
7314 Diag(ELoc, diag::err_omp_reduction_ref_type_arg) << ERange;
7315 Diag(VDDef->getLocation(), diag::note_defined_here) << VDDef;
7320 // OpenMP [2.14.3.6, reduction clause, Restrictions]
7321 // The type of a list item that appears in a reduction clause must be valid
7322 // for the reduction-identifier. For a max or min reduction in C, the type
7323 // of the list item must be an allowed arithmetic data type: char, int,
7324 // float, double, or _Bool, possibly modified with long, short, signed, or
7325 // unsigned. For a max or min reduction in C++, the type of the list item
7326 // must be an allowed arithmetic data type: char, wchar_t, int, float,
7327 // double, or bool, possibly modified with long, short, signed, or unsigned.
7328 if ((BOK == BO_GT || BOK == BO_LT) &&
7329 !(Type->isScalarType() ||
7330 (getLangOpts().CPlusPlus && Type->isArithmeticType()))) {
7331 Diag(ELoc, diag::err_omp_clause_not_arithmetic_type_arg)
7332 << getLangOpts().CPlusPlus;
7333 if (!ASE && !OASE) {
7334 bool IsDecl = VD->isThisDeclarationADefinition(Context) ==
7335 VarDecl::DeclarationOnly;
7336 Diag(VD->getLocation(),
7337 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
7342 if ((BOK == BO_OrAssign || BOK == BO_AndAssign || BOK == BO_XorAssign) &&
7343 !getLangOpts().CPlusPlus && Type->isFloatingType()) {
7344 Diag(ELoc, diag::err_omp_clause_floating_type_arg);
7345 if (!ASE && !OASE) {
7346 bool IsDecl = VD->isThisDeclarationADefinition(Context) ==
7347 VarDecl::DeclarationOnly;
7348 Diag(VD->getLocation(),
7349 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
7354 // OpenMP [2.14.1.1, Data-sharing Attribute Rules for Variables Referenced
7356 // Variables with the predetermined data-sharing attributes may not be
7357 // listed in data-sharing attributes clauses, except for the cases
7358 // listed below. For these exceptions only, listing a predetermined
7359 // variable in a data-sharing attribute clause is allowed and overrides
7360 // the variable's predetermined data-sharing attributes.
7361 // OpenMP [2.14.3.6, Restrictions, p.3]
7362 // Any number of reduction clauses can be specified on the directive,
7363 // but a list item can appear only once in the reduction clauses for that
7365 DSAStackTy::DSAVarData DVar;
7366 DVar = DSAStack->getTopDSA(VD, false);
7367 if (DVar.CKind == OMPC_reduction) {
7368 Diag(ELoc, diag::err_omp_once_referenced)
7369 << getOpenMPClauseName(OMPC_reduction);
7371 Diag(DVar.RefExpr->getExprLoc(), diag::note_omp_referenced);
7373 } else if (DVar.CKind != OMPC_unknown) {
7374 Diag(ELoc, diag::err_omp_wrong_dsa)
7375 << getOpenMPClauseName(DVar.CKind)
7376 << getOpenMPClauseName(OMPC_reduction);
7377 ReportOriginalDSA(*this, DSAStack, VD, DVar);
7381 // OpenMP [2.14.3.6, Restrictions, p.1]
7382 // A list item that appears in a reduction clause of a worksharing
7383 // construct must be shared in the parallel regions to which any of the
7384 // worksharing regions arising from the worksharing construct bind.
7385 OpenMPDirectiveKind CurrDir = DSAStack->getCurrentDirective();
7386 if (isOpenMPWorksharingDirective(CurrDir) &&
7387 !isOpenMPParallelDirective(CurrDir)) {
7388 DVar = DSAStack->getImplicitDSA(VD, true);
7389 if (DVar.CKind != OMPC_shared) {
7390 Diag(ELoc, diag::err_omp_required_access)
7391 << getOpenMPClauseName(OMPC_reduction)
7392 << getOpenMPClauseName(OMPC_shared);
7393 ReportOriginalDSA(*this, DSAStack, VD, DVar);
7398 Type = Type.getNonLValueExprType(Context).getUnqualifiedType();
7399 auto *LHSVD = buildVarDecl(*this, ELoc, Type, ".reduction.lhs",
7400 VD->hasAttrs() ? &VD->getAttrs() : nullptr);
7401 auto *RHSVD = buildVarDecl(*this, ELoc, Type, VD->getName(),
7402 VD->hasAttrs() ? &VD->getAttrs() : nullptr);
7403 auto PrivateTy = Type;
7405 // For array sections only:
7406 // Create pseudo array type for private copy. The size for this array will
7407 // be generated during codegen.
7408 // For array subscripts or single variables Private Ty is the same as Type
7409 // (type of the variable or single array element).
7410 PrivateTy = Context.getVariableArrayType(
7411 Type, new (Context) OpaqueValueExpr(SourceLocation(),
7412 Context.getSizeType(), VK_RValue),
7413 ArrayType::Normal, /*IndexTypeQuals=*/0, SourceRange());
7416 auto *PrivateVD = buildVarDecl(*this, ELoc, PrivateTy, VD->getName(),
7417 VD->hasAttrs() ? &VD->getAttrs() : nullptr);
7418 // Add initializer for private variable.
7419 Expr *Init = nullptr;
7425 // '+', '-', '^', '|', '||' reduction ops - initializer is '0'.
7426 if (Type->isScalarType() || Type->isAnyComplexType()) {
7427 Init = ActOnIntegerConstant(ELoc, /*Val=*/0).get();
7432 if (Type->isScalarType() || Type->isAnyComplexType()) {
7433 // '*' and '&&' reduction ops - initializer is '1'.
7434 Init = ActOnIntegerConstant(ELoc, /*Val=*/1).get();
7438 // '&' reduction op - initializer is '~0'.
7439 QualType OrigType = Type;
7440 if (auto *ComplexTy = OrigType->getAs<ComplexType>()) {
7441 Type = ComplexTy->getElementType();
7443 if (Type->isRealFloatingType()) {
7444 llvm::APFloat InitValue =
7445 llvm::APFloat::getAllOnesValue(Context.getTypeSize(Type),
7447 Init = FloatingLiteral::Create(Context, InitValue, /*isexact=*/true,
7449 } else if (Type->isScalarType()) {
7450 auto Size = Context.getTypeSize(Type);
7451 QualType IntTy = Context.getIntTypeForBitwidth(Size, /*Signed=*/0);
7452 llvm::APInt InitValue = llvm::APInt::getAllOnesValue(Size);
7453 Init = IntegerLiteral::Create(Context, InitValue, IntTy, ELoc);
7455 if (Init && OrigType->isAnyComplexType()) {
7456 // Init = 0xFFFF + 0xFFFFi;
7457 auto *Im = new (Context) ImaginaryLiteral(Init, OrigType);
7458 Init = CreateBuiltinBinOp(ELoc, BO_Add, Init, Im).get();
7465 // 'min' reduction op - initializer is 'Largest representable number in
7466 // the reduction list item type'.
7467 // 'max' reduction op - initializer is 'Least representable number in
7468 // the reduction list item type'.
7469 if (Type->isIntegerType() || Type->isPointerType()) {
7470 bool IsSigned = Type->hasSignedIntegerRepresentation();
7471 auto Size = Context.getTypeSize(Type);
7473 Context.getIntTypeForBitwidth(Size, /*Signed=*/IsSigned);
7474 llvm::APInt InitValue =
7476 ? IsSigned ? llvm::APInt::getSignedMinValue(Size)
7477 : llvm::APInt::getMinValue(Size)
7478 : IsSigned ? llvm::APInt::getSignedMaxValue(Size)
7479 : llvm::APInt::getMaxValue(Size);
7480 Init = IntegerLiteral::Create(Context, InitValue, IntTy, ELoc);
7481 if (Type->isPointerType()) {
7482 // Cast to pointer type.
7483 auto CastExpr = BuildCStyleCastExpr(
7484 SourceLocation(), Context.getTrivialTypeSourceInfo(Type, ELoc),
7485 SourceLocation(), Init);
7486 if (CastExpr.isInvalid())
7488 Init = CastExpr.get();
7490 } else if (Type->isRealFloatingType()) {
7491 llvm::APFloat InitValue = llvm::APFloat::getLargest(
7492 Context.getFloatTypeSemantics(Type), BOK != BO_LT);
7493 Init = FloatingLiteral::Create(Context, InitValue, /*isexact=*/true,
7521 llvm_unreachable("Unexpected reduction operation");
7524 AddInitializerToDecl(RHSVD, Init, /*DirectInit=*/false,
7525 /*TypeMayContainAuto=*/false);
7527 ActOnUninitializedDecl(RHSVD, /*TypeMayContainAuto=*/false);
7528 if (!RHSVD->hasInit()) {
7529 Diag(ELoc, diag::err_omp_reduction_id_not_compatible) << Type
7530 << ReductionIdRange;
7532 bool IsDecl = VD->isThisDeclarationADefinition(Context) ==
7533 VarDecl::DeclarationOnly;
7534 Diag(VD->getLocation(),
7535 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
7540 // Store initializer for single element in private copy. Will be used during
7542 PrivateVD->setInit(RHSVD->getInit());
7543 PrivateVD->setInitStyle(RHSVD->getInitStyle());
7544 auto *LHSDRE = buildDeclRefExpr(*this, LHSVD, Type, ELoc);
7545 auto *RHSDRE = buildDeclRefExpr(*this, RHSVD, Type, ELoc);
7546 auto *PrivateDRE = buildDeclRefExpr(*this, PrivateVD, PrivateTy, ELoc);
7547 ExprResult ReductionOp =
7548 BuildBinOp(DSAStack->getCurScope(), ReductionId.getLocStart(), BOK,
7550 if (ReductionOp.isUsable()) {
7551 if (BOK != BO_LT && BOK != BO_GT) {
7553 BuildBinOp(DSAStack->getCurScope(), ReductionId.getLocStart(),
7554 BO_Assign, LHSDRE, ReductionOp.get());
7556 auto *ConditionalOp = new (Context) ConditionalOperator(
7557 ReductionOp.get(), SourceLocation(), LHSDRE, SourceLocation(),
7558 RHSDRE, Type, VK_LValue, OK_Ordinary);
7560 BuildBinOp(DSAStack->getCurScope(), ReductionId.getLocStart(),
7561 BO_Assign, LHSDRE, ConditionalOp);
7563 ReductionOp = ActOnFinishFullExpr(ReductionOp.get());
7565 if (ReductionOp.isInvalid())
7568 DSAStack->addDSA(VD, DE, OMPC_reduction);
7569 Vars.push_back(RefExpr);
7570 Privates.push_back(PrivateDRE);
7571 LHSs.push_back(LHSDRE);
7572 RHSs.push_back(RHSDRE);
7573 ReductionOps.push_back(ReductionOp.get());
7579 return OMPReductionClause::Create(
7580 Context, StartLoc, LParenLoc, ColonLoc, EndLoc, Vars,
7581 ReductionIdScopeSpec.getWithLocInContext(Context), ReductionId, Privates,
7582 LHSs, RHSs, ReductionOps);
7585 OMPClause *Sema::ActOnOpenMPLinearClause(
7586 ArrayRef<Expr *> VarList, Expr *Step, SourceLocation StartLoc,
7587 SourceLocation LParenLoc, OpenMPLinearClauseKind LinKind,
7588 SourceLocation LinLoc, SourceLocation ColonLoc, SourceLocation EndLoc) {
7589 SmallVector<Expr *, 8> Vars;
7590 SmallVector<Expr *, 8> Privates;
7591 SmallVector<Expr *, 8> Inits;
7592 if ((!LangOpts.CPlusPlus && LinKind != OMPC_LINEAR_val) ||
7593 LinKind == OMPC_LINEAR_unknown) {
7594 Diag(LinLoc, diag::err_omp_wrong_linear_modifier) << LangOpts.CPlusPlus;
7595 LinKind = OMPC_LINEAR_val;
7597 for (auto &RefExpr : VarList) {
7598 assert(RefExpr && "NULL expr in OpenMP linear clause.");
7599 if (isa<DependentScopeDeclRefExpr>(RefExpr)) {
7600 // It will be analyzed later.
7601 Vars.push_back(RefExpr);
7602 Privates.push_back(nullptr);
7603 Inits.push_back(nullptr);
7607 // OpenMP [2.14.3.7, linear clause]
7608 // A list item that appears in a linear clause is subject to the private
7609 // clause semantics described in Section 2.14.3.3 on page 159 except as
7610 // noted. In addition, the value of the new list item on each iteration
7611 // of the associated loop(s) corresponds to the value of the original
7612 // list item before entering the construct plus the logical number of
7613 // the iteration times linear-step.
7615 SourceLocation ELoc = RefExpr->getExprLoc();
7616 // OpenMP [2.1, C/C++]
7617 // A list item is a variable name.
7618 // OpenMP [2.14.3.3, Restrictions, p.1]
7619 // A variable that is part of another variable (as an array or
7620 // structure element) cannot appear in a private clause.
7621 DeclRefExpr *DE = dyn_cast<DeclRefExpr>(RefExpr);
7622 if (!DE || !isa<VarDecl>(DE->getDecl())) {
7623 Diag(ELoc, diag::err_omp_expected_var_name) << RefExpr->getSourceRange();
7627 VarDecl *VD = cast<VarDecl>(DE->getDecl());
7629 // OpenMP [2.14.3.7, linear clause]
7630 // A list-item cannot appear in more than one linear clause.
7631 // A list-item that appears in a linear clause cannot appear in any
7632 // other data-sharing attribute clause.
7633 DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(VD, false);
7635 Diag(ELoc, diag::err_omp_wrong_dsa) << getOpenMPClauseName(DVar.CKind)
7636 << getOpenMPClauseName(OMPC_linear);
7637 ReportOriginalDSA(*this, DSAStack, VD, DVar);
7641 QualType QType = VD->getType();
7642 if (QType->isDependentType() || QType->isInstantiationDependentType()) {
7643 // It will be analyzed later.
7645 Privates.push_back(nullptr);
7646 Inits.push_back(nullptr);
7650 // A variable must not have an incomplete type or a reference type.
7651 if (RequireCompleteType(ELoc, QType,
7652 diag::err_omp_linear_incomplete_type)) {
7655 if ((LinKind == OMPC_LINEAR_uval || LinKind == OMPC_LINEAR_ref) &&
7656 !QType->isReferenceType()) {
7657 Diag(ELoc, diag::err_omp_wrong_linear_modifier_non_reference)
7658 << QType << getOpenMPSimpleClauseTypeName(OMPC_linear, LinKind);
7661 QType = QType.getNonReferenceType();
7663 // A list item must not be const-qualified.
7664 if (QType.isConstant(Context)) {
7665 Diag(ELoc, diag::err_omp_const_variable)
7666 << getOpenMPClauseName(OMPC_linear);
7668 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
7669 Diag(VD->getLocation(),
7670 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
7675 // A list item must be of integral or pointer type.
7676 QType = QType.getUnqualifiedType().getCanonicalType();
7677 const Type *Ty = QType.getTypePtrOrNull();
7678 if (!Ty || (!Ty->isDependentType() && !Ty->isIntegralType(Context) &&
7679 !Ty->isPointerType())) {
7680 Diag(ELoc, diag::err_omp_linear_expected_int_or_ptr) << QType;
7682 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
7683 Diag(VD->getLocation(),
7684 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
7689 // Build private copy of original var.
7690 auto *Private = buildVarDecl(*this, ELoc, QType, VD->getName(),
7691 VD->hasAttrs() ? &VD->getAttrs() : nullptr);
7692 auto *PrivateRef = buildDeclRefExpr(
7693 *this, Private, DE->getType().getUnqualifiedType(), DE->getExprLoc());
7694 // Build var to save initial value.
7695 VarDecl *Init = buildVarDecl(*this, ELoc, QType, ".linear.start");
7697 if (LinKind == OMPC_LINEAR_uval)
7698 InitExpr = VD->getInit();
7701 AddInitializerToDecl(Init, DefaultLvalueConversion(InitExpr).get(),
7702 /*DirectInit*/ false, /*TypeMayContainAuto*/ false);
7703 auto InitRef = buildDeclRefExpr(
7704 *this, Init, DE->getType().getUnqualifiedType(), DE->getExprLoc());
7705 DSAStack->addDSA(VD, DE, OMPC_linear);
7707 Privates.push_back(PrivateRef);
7708 Inits.push_back(InitRef);
7714 Expr *StepExpr = Step;
7715 Expr *CalcStepExpr = nullptr;
7716 if (Step && !Step->isValueDependent() && !Step->isTypeDependent() &&
7717 !Step->isInstantiationDependent() &&
7718 !Step->containsUnexpandedParameterPack()) {
7719 SourceLocation StepLoc = Step->getLocStart();
7720 ExprResult Val = PerformOpenMPImplicitIntegerConversion(StepLoc, Step);
7721 if (Val.isInvalid())
7723 StepExpr = Val.get();
7725 // Build var to save the step value.
7727 buildVarDecl(*this, StepLoc, StepExpr->getType(), ".linear.step");
7728 ExprResult SaveRef =
7729 buildDeclRefExpr(*this, SaveVar, StepExpr->getType(), StepLoc);
7730 ExprResult CalcStep =
7731 BuildBinOp(CurScope, StepLoc, BO_Assign, SaveRef.get(), StepExpr);
7732 CalcStep = ActOnFinishFullExpr(CalcStep.get());
7734 // Warn about zero linear step (it would be probably better specified as
7735 // making corresponding variables 'const').
7736 llvm::APSInt Result;
7737 bool IsConstant = StepExpr->isIntegerConstantExpr(Result, Context);
7738 if (IsConstant && !Result.isNegative() && !Result.isStrictlyPositive())
7739 Diag(StepLoc, diag::warn_omp_linear_step_zero) << Vars[0]
7740 << (Vars.size() > 1);
7741 if (!IsConstant && CalcStep.isUsable()) {
7742 // Calculate the step beforehand instead of doing this on each iteration.
7743 // (This is not used if the number of iterations may be kfold-ed).
7744 CalcStepExpr = CalcStep.get();
7748 return OMPLinearClause::Create(Context, StartLoc, LParenLoc, LinKind, LinLoc,
7749 ColonLoc, EndLoc, Vars, Privates, Inits,
7750 StepExpr, CalcStepExpr);
7753 static bool FinishOpenMPLinearClause(OMPLinearClause &Clause, DeclRefExpr *IV,
7754 Expr *NumIterations, Sema &SemaRef,
7756 // Walk the vars and build update/final expressions for the CodeGen.
7757 SmallVector<Expr *, 8> Updates;
7758 SmallVector<Expr *, 8> Finals;
7759 Expr *Step = Clause.getStep();
7760 Expr *CalcStep = Clause.getCalcStep();
7761 // OpenMP [2.14.3.7, linear clause]
7762 // If linear-step is not specified it is assumed to be 1.
7763 if (Step == nullptr)
7764 Step = SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get();
7766 Step = cast<BinaryOperator>(CalcStep)->getLHS();
7767 bool HasErrors = false;
7768 auto CurInit = Clause.inits().begin();
7769 auto CurPrivate = Clause.privates().begin();
7770 auto LinKind = Clause.getModifier();
7771 for (auto &RefExpr : Clause.varlists()) {
7772 Expr *InitExpr = *CurInit;
7774 // Build privatized reference to the current linear var.
7775 auto DE = cast<DeclRefExpr>(RefExpr);
7777 if (LinKind == OMPC_LINEAR_uval)
7778 CapturedRef = cast<VarDecl>(DE->getDecl())->getInit();
7781 buildDeclRefExpr(SemaRef, cast<VarDecl>(DE->getDecl()),
7782 DE->getType().getUnqualifiedType(), DE->getExprLoc(),
7783 /*RefersToCapture=*/true);
7785 // Build update: Var = InitExpr + IV * Step
7787 BuildCounterUpdate(SemaRef, S, RefExpr->getExprLoc(), *CurPrivate,
7788 InitExpr, IV, Step, /* Subtract */ false);
7789 Update = SemaRef.ActOnFinishFullExpr(Update.get(), DE->getLocStart(),
7790 /*DiscardedValue=*/true);
7792 // Build final: Var = InitExpr + NumIterations * Step
7794 BuildCounterUpdate(SemaRef, S, RefExpr->getExprLoc(), CapturedRef,
7795 InitExpr, NumIterations, Step, /* Subtract */ false);
7796 Final = SemaRef.ActOnFinishFullExpr(Final.get(), DE->getLocStart(),
7797 /*DiscardedValue=*/true);
7798 if (!Update.isUsable() || !Final.isUsable()) {
7799 Updates.push_back(nullptr);
7800 Finals.push_back(nullptr);
7803 Updates.push_back(Update.get());
7804 Finals.push_back(Final.get());
7806 ++CurInit, ++CurPrivate;
7808 Clause.setUpdates(Updates);
7809 Clause.setFinals(Finals);
7813 OMPClause *Sema::ActOnOpenMPAlignedClause(
7814 ArrayRef<Expr *> VarList, Expr *Alignment, SourceLocation StartLoc,
7815 SourceLocation LParenLoc, SourceLocation ColonLoc, SourceLocation EndLoc) {
7817 SmallVector<Expr *, 8> Vars;
7818 for (auto &RefExpr : VarList) {
7819 assert(RefExpr && "NULL expr in OpenMP aligned clause.");
7820 if (isa<DependentScopeDeclRefExpr>(RefExpr)) {
7821 // It will be analyzed later.
7822 Vars.push_back(RefExpr);
7826 SourceLocation ELoc = RefExpr->getExprLoc();
7827 // OpenMP [2.1, C/C++]
7828 // A list item is a variable name.
7829 DeclRefExpr *DE = dyn_cast<DeclRefExpr>(RefExpr);
7830 if (!DE || !isa<VarDecl>(DE->getDecl())) {
7831 Diag(ELoc, diag::err_omp_expected_var_name) << RefExpr->getSourceRange();
7835 VarDecl *VD = cast<VarDecl>(DE->getDecl());
7837 // OpenMP [2.8.1, simd construct, Restrictions]
7838 // The type of list items appearing in the aligned clause must be
7839 // array, pointer, reference to array, or reference to pointer.
7840 QualType QType = VD->getType();
7841 QType = QType.getNonReferenceType().getUnqualifiedType().getCanonicalType();
7842 const Type *Ty = QType.getTypePtrOrNull();
7843 if (!Ty || (!Ty->isDependentType() && !Ty->isArrayType() &&
7844 !Ty->isPointerType())) {
7845 Diag(ELoc, diag::err_omp_aligned_expected_array_or_ptr)
7846 << QType << getLangOpts().CPlusPlus << RefExpr->getSourceRange();
7848 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
7849 Diag(VD->getLocation(),
7850 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
7855 // OpenMP [2.8.1, simd construct, Restrictions]
7856 // A list-item cannot appear in more than one aligned clause.
7857 if (DeclRefExpr *PrevRef = DSAStack->addUniqueAligned(VD, DE)) {
7858 Diag(ELoc, diag::err_omp_aligned_twice) << RefExpr->getSourceRange();
7859 Diag(PrevRef->getExprLoc(), diag::note_omp_explicit_dsa)
7860 << getOpenMPClauseName(OMPC_aligned);
7867 // OpenMP [2.8.1, simd construct, Description]
7868 // The parameter of the aligned clause, alignment, must be a constant
7869 // positive integer expression.
7870 // If no optional parameter is specified, implementation-defined default
7871 // alignments for SIMD instructions on the target platforms are assumed.
7872 if (Alignment != nullptr) {
7873 ExprResult AlignResult =
7874 VerifyPositiveIntegerConstantInClause(Alignment, OMPC_aligned);
7875 if (AlignResult.isInvalid())
7877 Alignment = AlignResult.get();
7882 return OMPAlignedClause::Create(Context, StartLoc, LParenLoc, ColonLoc,
7883 EndLoc, Vars, Alignment);
7886 OMPClause *Sema::ActOnOpenMPCopyinClause(ArrayRef<Expr *> VarList,
7887 SourceLocation StartLoc,
7888 SourceLocation LParenLoc,
7889 SourceLocation EndLoc) {
7890 SmallVector<Expr *, 8> Vars;
7891 SmallVector<Expr *, 8> SrcExprs;
7892 SmallVector<Expr *, 8> DstExprs;
7893 SmallVector<Expr *, 8> AssignmentOps;
7894 for (auto &RefExpr : VarList) {
7895 assert(RefExpr && "NULL expr in OpenMP copyin clause.");
7896 if (isa<DependentScopeDeclRefExpr>(RefExpr)) {
7897 // It will be analyzed later.
7898 Vars.push_back(RefExpr);
7899 SrcExprs.push_back(nullptr);
7900 DstExprs.push_back(nullptr);
7901 AssignmentOps.push_back(nullptr);
7905 SourceLocation ELoc = RefExpr->getExprLoc();
7906 // OpenMP [2.1, C/C++]
7907 // A list item is a variable name.
7908 // OpenMP [2.14.4.1, Restrictions, p.1]
7909 // A list item that appears in a copyin clause must be threadprivate.
7910 DeclRefExpr *DE = dyn_cast<DeclRefExpr>(RefExpr);
7911 if (!DE || !isa<VarDecl>(DE->getDecl())) {
7912 Diag(ELoc, diag::err_omp_expected_var_name) << RefExpr->getSourceRange();
7916 Decl *D = DE->getDecl();
7917 VarDecl *VD = cast<VarDecl>(D);
7919 QualType Type = VD->getType();
7920 if (Type->isDependentType() || Type->isInstantiationDependentType()) {
7921 // It will be analyzed later.
7923 SrcExprs.push_back(nullptr);
7924 DstExprs.push_back(nullptr);
7925 AssignmentOps.push_back(nullptr);
7929 // OpenMP [2.14.4.1, Restrictions, C/C++, p.1]
7930 // A list item that appears in a copyin clause must be threadprivate.
7931 if (!DSAStack->isThreadPrivate(VD)) {
7932 Diag(ELoc, diag::err_omp_required_access)
7933 << getOpenMPClauseName(OMPC_copyin)
7934 << getOpenMPDirectiveName(OMPD_threadprivate);
7938 // OpenMP [2.14.4.1, Restrictions, C/C++, p.2]
7939 // A variable of class type (or array thereof) that appears in a
7940 // copyin clause requires an accessible, unambiguous copy assignment
7941 // operator for the class type.
7942 auto ElemType = Context.getBaseElementType(Type).getNonReferenceType();
7944 buildVarDecl(*this, DE->getLocStart(), ElemType.getUnqualifiedType(),
7945 ".copyin.src", VD->hasAttrs() ? &VD->getAttrs() : nullptr);
7946 auto *PseudoSrcExpr = buildDeclRefExpr(
7947 *this, SrcVD, ElemType.getUnqualifiedType(), DE->getExprLoc());
7949 buildVarDecl(*this, DE->getLocStart(), ElemType, ".copyin.dst",
7950 VD->hasAttrs() ? &VD->getAttrs() : nullptr);
7951 auto *PseudoDstExpr =
7952 buildDeclRefExpr(*this, DstVD, ElemType, DE->getExprLoc());
7953 // For arrays generate assignment operation for single element and replace
7954 // it by the original array element in CodeGen.
7955 auto AssignmentOp = BuildBinOp(/*S=*/nullptr, DE->getExprLoc(), BO_Assign,
7956 PseudoDstExpr, PseudoSrcExpr);
7957 if (AssignmentOp.isInvalid())
7959 AssignmentOp = ActOnFinishFullExpr(AssignmentOp.get(), DE->getExprLoc(),
7960 /*DiscardedValue=*/true);
7961 if (AssignmentOp.isInvalid())
7964 DSAStack->addDSA(VD, DE, OMPC_copyin);
7966 SrcExprs.push_back(PseudoSrcExpr);
7967 DstExprs.push_back(PseudoDstExpr);
7968 AssignmentOps.push_back(AssignmentOp.get());
7974 return OMPCopyinClause::Create(Context, StartLoc, LParenLoc, EndLoc, Vars,
7975 SrcExprs, DstExprs, AssignmentOps);
7978 OMPClause *Sema::ActOnOpenMPCopyprivateClause(ArrayRef<Expr *> VarList,
7979 SourceLocation StartLoc,
7980 SourceLocation LParenLoc,
7981 SourceLocation EndLoc) {
7982 SmallVector<Expr *, 8> Vars;
7983 SmallVector<Expr *, 8> SrcExprs;
7984 SmallVector<Expr *, 8> DstExprs;
7985 SmallVector<Expr *, 8> AssignmentOps;
7986 for (auto &RefExpr : VarList) {
7987 assert(RefExpr && "NULL expr in OpenMP copyprivate clause.");
7988 if (isa<DependentScopeDeclRefExpr>(RefExpr)) {
7989 // It will be analyzed later.
7990 Vars.push_back(RefExpr);
7991 SrcExprs.push_back(nullptr);
7992 DstExprs.push_back(nullptr);
7993 AssignmentOps.push_back(nullptr);
7997 SourceLocation ELoc = RefExpr->getExprLoc();
7998 // OpenMP [2.1, C/C++]
7999 // A list item is a variable name.
8000 // OpenMP [2.14.4.1, Restrictions, p.1]
8001 // A list item that appears in a copyin clause must be threadprivate.
8002 DeclRefExpr *DE = dyn_cast<DeclRefExpr>(RefExpr);
8003 if (!DE || !isa<VarDecl>(DE->getDecl())) {
8004 Diag(ELoc, diag::err_omp_expected_var_name) << RefExpr->getSourceRange();
8008 Decl *D = DE->getDecl();
8009 VarDecl *VD = cast<VarDecl>(D);
8011 QualType Type = VD->getType();
8012 if (Type->isDependentType() || Type->isInstantiationDependentType()) {
8013 // It will be analyzed later.
8015 SrcExprs.push_back(nullptr);
8016 DstExprs.push_back(nullptr);
8017 AssignmentOps.push_back(nullptr);
8021 // OpenMP [2.14.4.2, Restrictions, p.2]
8022 // A list item that appears in a copyprivate clause may not appear in a
8023 // private or firstprivate clause on the single construct.
8024 if (!DSAStack->isThreadPrivate(VD)) {
8025 auto DVar = DSAStack->getTopDSA(VD, false);
8026 if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_copyprivate &&
8028 Diag(ELoc, diag::err_omp_wrong_dsa)
8029 << getOpenMPClauseName(DVar.CKind)
8030 << getOpenMPClauseName(OMPC_copyprivate);
8031 ReportOriginalDSA(*this, DSAStack, VD, DVar);
8035 // OpenMP [2.11.4.2, Restrictions, p.1]
8036 // All list items that appear in a copyprivate clause must be either
8037 // threadprivate or private in the enclosing context.
8038 if (DVar.CKind == OMPC_unknown) {
8039 DVar = DSAStack->getImplicitDSA(VD, false);
8040 if (DVar.CKind == OMPC_shared) {
8041 Diag(ELoc, diag::err_omp_required_access)
8042 << getOpenMPClauseName(OMPC_copyprivate)
8043 << "threadprivate or private in the enclosing context";
8044 ReportOriginalDSA(*this, DSAStack, VD, DVar);
8050 // Variably modified types are not supported.
8051 if (!Type->isAnyPointerType() && Type->isVariablyModifiedType()) {
8052 Diag(ELoc, diag::err_omp_variably_modified_type_not_supported)
8053 << getOpenMPClauseName(OMPC_copyprivate) << Type
8054 << getOpenMPDirectiveName(DSAStack->getCurrentDirective());
8056 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
8057 Diag(VD->getLocation(),
8058 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
8063 // OpenMP [2.14.4.1, Restrictions, C/C++, p.2]
8064 // A variable of class type (or array thereof) that appears in a
8065 // copyin clause requires an accessible, unambiguous copy assignment
8066 // operator for the class type.
8067 Type = Context.getBaseElementType(Type.getNonReferenceType())
8068 .getUnqualifiedType();
8070 buildVarDecl(*this, DE->getLocStart(), Type, ".copyprivate.src",
8071 VD->hasAttrs() ? &VD->getAttrs() : nullptr);
8072 auto *PseudoSrcExpr =
8073 buildDeclRefExpr(*this, SrcVD, Type, DE->getExprLoc());
8075 buildVarDecl(*this, DE->getLocStart(), Type, ".copyprivate.dst",
8076 VD->hasAttrs() ? &VD->getAttrs() : nullptr);
8077 auto *PseudoDstExpr =
8078 buildDeclRefExpr(*this, DstVD, Type, DE->getExprLoc());
8079 auto AssignmentOp = BuildBinOp(/*S=*/nullptr, DE->getExprLoc(), BO_Assign,
8080 PseudoDstExpr, PseudoSrcExpr);
8081 if (AssignmentOp.isInvalid())
8083 AssignmentOp = ActOnFinishFullExpr(AssignmentOp.get(), DE->getExprLoc(),
8084 /*DiscardedValue=*/true);
8085 if (AssignmentOp.isInvalid())
8088 // No need to mark vars as copyprivate, they are already threadprivate or
8089 // implicitly private.
8091 SrcExprs.push_back(PseudoSrcExpr);
8092 DstExprs.push_back(PseudoDstExpr);
8093 AssignmentOps.push_back(AssignmentOp.get());
8099 return OMPCopyprivateClause::Create(Context, StartLoc, LParenLoc, EndLoc,
8100 Vars, SrcExprs, DstExprs, AssignmentOps);
8103 OMPClause *Sema::ActOnOpenMPFlushClause(ArrayRef<Expr *> VarList,
8104 SourceLocation StartLoc,
8105 SourceLocation LParenLoc,
8106 SourceLocation EndLoc) {
8107 if (VarList.empty())
8110 return OMPFlushClause::Create(Context, StartLoc, LParenLoc, EndLoc, VarList);
8114 Sema::ActOnOpenMPDependClause(OpenMPDependClauseKind DepKind,
8115 SourceLocation DepLoc, SourceLocation ColonLoc,
8116 ArrayRef<Expr *> VarList, SourceLocation StartLoc,
8117 SourceLocation LParenLoc, SourceLocation EndLoc) {
8118 if (DSAStack->getCurrentDirective() == OMPD_ordered &&
8119 DepKind != OMPC_DEPEND_source && DepKind != OMPC_DEPEND_sink) {
8120 Diag(DepLoc, diag::err_omp_unexpected_clause_value)
8121 << "'source' or 'sink'" << getOpenMPClauseName(OMPC_depend);
8124 if (DSAStack->getCurrentDirective() != OMPD_ordered &&
8125 (DepKind == OMPC_DEPEND_unknown || DepKind == OMPC_DEPEND_source ||
8126 DepKind == OMPC_DEPEND_sink)) {
8127 unsigned Except[] = {OMPC_DEPEND_source, OMPC_DEPEND_sink};
8128 Diag(DepLoc, diag::err_omp_unexpected_clause_value)
8129 << getListOfPossibleValues(OMPC_depend, /*First=*/0,
8130 /*Last=*/OMPC_DEPEND_unknown, Except)
8131 << getOpenMPClauseName(OMPC_depend);
8134 SmallVector<Expr *, 8> Vars;
8135 llvm::APSInt DepCounter(/*BitWidth=*/32);
8136 llvm::APSInt TotalDepCount(/*BitWidth=*/32);
8137 if (DepKind == OMPC_DEPEND_sink) {
8138 if (auto *OrderedCountExpr = DSAStack->getParentOrderedRegionParam()) {
8139 TotalDepCount = OrderedCountExpr->EvaluateKnownConstInt(Context);
8140 TotalDepCount.setIsUnsigned(/*Val=*/true);
8143 if ((DepKind != OMPC_DEPEND_sink && DepKind != OMPC_DEPEND_source) ||
8144 DSAStack->getParentOrderedRegionParam()) {
8145 for (auto &RefExpr : VarList) {
8146 assert(RefExpr && "NULL expr in OpenMP shared clause.");
8147 if (isa<DependentScopeDeclRefExpr>(RefExpr) ||
8148 (DepKind == OMPC_DEPEND_sink && CurContext->isDependentContext())) {
8149 // It will be analyzed later.
8150 Vars.push_back(RefExpr);
8154 SourceLocation ELoc = RefExpr->getExprLoc();
8155 auto *SimpleExpr = RefExpr->IgnoreParenCasts();
8156 if (DepKind == OMPC_DEPEND_sink) {
8157 if (DepCounter >= TotalDepCount) {
8158 Diag(ELoc, diag::err_omp_depend_sink_unexpected_expr);
8162 // OpenMP [2.13.9, Summary]
8163 // depend(dependence-type : vec), where dependence-type is:
8164 // 'sink' and where vec is the iteration vector, which has the form:
8165 // x1 [+- d1], x2 [+- d2 ], . . . , xn [+- dn]
8166 // where n is the value specified by the ordered clause in the loop
8167 // directive, xi denotes the loop iteration variable of the i-th nested
8168 // loop associated with the loop directive, and di is a constant
8169 // non-negative integer.
8170 SimpleExpr = SimpleExpr->IgnoreImplicit();
8171 auto *DE = dyn_cast<DeclRefExpr>(SimpleExpr);
8173 OverloadedOperatorKind OOK = OO_None;
8174 SourceLocation OOLoc;
8176 if (auto *BO = dyn_cast<BinaryOperator>(SimpleExpr)) {
8177 OOK = BinaryOperator::getOverloadedOperator(BO->getOpcode());
8178 OOLoc = BO->getOperatorLoc();
8179 LHS = BO->getLHS()->IgnoreParenImpCasts();
8180 RHS = BO->getRHS()->IgnoreParenImpCasts();
8181 } else if (auto *OCE = dyn_cast<CXXOperatorCallExpr>(SimpleExpr)) {
8182 OOK = OCE->getOperator();
8183 OOLoc = OCE->getOperatorLoc();
8184 LHS = OCE->getArg(/*Arg=*/0)->IgnoreParenImpCasts();
8185 RHS = OCE->getArg(/*Arg=*/1)->IgnoreParenImpCasts();
8186 } else if (auto *MCE = dyn_cast<CXXMemberCallExpr>(SimpleExpr)) {
8187 OOK = MCE->getMethodDecl()
8190 .getCXXOverloadedOperator();
8191 OOLoc = MCE->getCallee()->getExprLoc();
8192 LHS = MCE->getImplicitObjectArgument()->IgnoreParenImpCasts();
8193 RHS = MCE->getArg(/*Arg=*/0)->IgnoreParenImpCasts();
8195 Diag(ELoc, diag::err_omp_depend_sink_wrong_expr);
8198 DE = dyn_cast<DeclRefExpr>(LHS);
8200 Diag(LHS->getExprLoc(),
8201 diag::err_omp_depend_sink_expected_loop_iteration)
8202 << DSAStack->getParentLoopControlVariable(
8203 DepCounter.getZExtValue());
8206 if (OOK != OO_Plus && OOK != OO_Minus) {
8207 Diag(OOLoc, diag::err_omp_depend_sink_expected_plus_minus);
8210 ExprResult Res = VerifyPositiveIntegerConstantInClause(
8211 RHS, OMPC_depend, /*StrictlyPositive=*/false);
8212 if (Res.isInvalid())
8215 auto *VD = dyn_cast<VarDecl>(DE->getDecl());
8216 if (!CurContext->isDependentContext() &&
8217 DSAStack->getParentOrderedRegionParam() &&
8218 (!VD || DepCounter != DSAStack->isParentLoopControlVariable(VD))) {
8219 Diag(DE->getExprLoc(),
8220 diag::err_omp_depend_sink_expected_loop_iteration)
8221 << DSAStack->getParentLoopControlVariable(
8222 DepCounter.getZExtValue());
8226 // OpenMP [2.11.1.1, Restrictions, p.3]
8227 // A variable that is part of another variable (such as a field of a
8228 // structure) but is not an array element or an array section cannot
8229 // appear in a depend clause.
8230 auto *DE = dyn_cast<DeclRefExpr>(SimpleExpr);
8231 auto *ASE = dyn_cast<ArraySubscriptExpr>(SimpleExpr);
8232 auto *OASE = dyn_cast<OMPArraySectionExpr>(SimpleExpr);
8233 if (!RefExpr->IgnoreParenImpCasts()->isLValue() ||
8234 (!ASE && !DE && !OASE) || (DE && !isa<VarDecl>(DE->getDecl())) ||
8235 (ASE && !ASE->getBase()->getType()->isAnyPointerType() &&
8236 !ASE->getBase()->getType()->isArrayType())) {
8237 Diag(ELoc, diag::err_omp_expected_var_name_or_array_item)
8238 << RefExpr->getSourceRange();
8243 Vars.push_back(RefExpr->IgnoreParenImpCasts());
8246 if (!CurContext->isDependentContext() && DepKind == OMPC_DEPEND_sink &&
8247 TotalDepCount > VarList.size() &&
8248 DSAStack->getParentOrderedRegionParam()) {
8249 Diag(EndLoc, diag::err_omp_depend_sink_expected_loop_iteration)
8250 << DSAStack->getParentLoopControlVariable(VarList.size() + 1);
8252 if (DepKind != OMPC_DEPEND_source && DepKind != OMPC_DEPEND_sink &&
8257 return OMPDependClause::Create(Context, StartLoc, LParenLoc, EndLoc, DepKind,
8258 DepLoc, ColonLoc, Vars);
8261 OMPClause *Sema::ActOnOpenMPDeviceClause(Expr *Device, SourceLocation StartLoc,
8262 SourceLocation LParenLoc,
8263 SourceLocation EndLoc) {
8264 Expr *ValExpr = Device;
8266 // OpenMP [2.9.1, Restrictions]
8267 // The device expression must evaluate to a non-negative integer value.
8268 if (!IsNonNegativeIntegerValue(ValExpr, *this, OMPC_device,
8269 /*StrictlyPositive=*/false))
8272 return new (Context) OMPDeviceClause(ValExpr, StartLoc, LParenLoc, EndLoc);
8275 static bool IsCXXRecordForMappable(Sema &SemaRef, SourceLocation Loc,
8276 DSAStackTy *Stack, CXXRecordDecl *RD) {
8277 if (!RD || RD->isInvalidDecl())
8280 if (auto *CTSD = dyn_cast<ClassTemplateSpecializationDecl>(RD))
8281 if (auto *CTD = CTSD->getSpecializedTemplate())
8282 RD = CTD->getTemplatedDecl();
8283 auto QTy = SemaRef.Context.getRecordType(RD);
8284 if (RD->isDynamicClass()) {
8285 SemaRef.Diag(Loc, diag::err_omp_not_mappable_type) << QTy;
8286 SemaRef.Diag(RD->getLocation(), diag::note_omp_polymorphic_in_target);
8290 bool IsCorrect = true;
8291 for (auto *I : DC->decls()) {
8293 if (auto *MD = dyn_cast<CXXMethodDecl>(I)) {
8294 if (MD->isStatic()) {
8295 SemaRef.Diag(Loc, diag::err_omp_not_mappable_type) << QTy;
8296 SemaRef.Diag(MD->getLocation(),
8297 diag::note_omp_static_member_in_target);
8300 } else if (auto *VD = dyn_cast<VarDecl>(I)) {
8301 if (VD->isStaticDataMember()) {
8302 SemaRef.Diag(Loc, diag::err_omp_not_mappable_type) << QTy;
8303 SemaRef.Diag(VD->getLocation(),
8304 diag::note_omp_static_member_in_target);
8311 for (auto &I : RD->bases()) {
8312 if (!IsCXXRecordForMappable(SemaRef, I.getLocStart(), Stack,
8313 I.getType()->getAsCXXRecordDecl()))
8319 static bool CheckTypeMappable(SourceLocation SL, SourceRange SR, Sema &SemaRef,
8320 DSAStackTy *Stack, QualType QTy) {
8322 if (QTy->isIncompleteType(&ND)) {
8323 SemaRef.Diag(SL, diag::err_incomplete_type) << QTy << SR;
8325 } else if (CXXRecordDecl *RD = dyn_cast_or_null<CXXRecordDecl>(ND)) {
8326 if (!RD->isInvalidDecl() &&
8327 !IsCXXRecordForMappable(SemaRef, SL, Stack, RD))
8333 OMPClause *Sema::ActOnOpenMPMapClause(
8334 OpenMPMapClauseKind MapTypeModifier, OpenMPMapClauseKind MapType,
8335 SourceLocation MapLoc, SourceLocation ColonLoc, ArrayRef<Expr *> VarList,
8336 SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc) {
8337 SmallVector<Expr *, 4> Vars;
8339 for (auto &RE : VarList) {
8340 assert(RE && "Null expr in omp map");
8341 if (isa<DependentScopeDeclRefExpr>(RE)) {
8342 // It will be analyzed later.
8346 SourceLocation ELoc = RE->getExprLoc();
8348 // OpenMP [2.14.5, Restrictions]
8349 // A variable that is part of another variable (such as field of a
8350 // structure) but is not an array element or an array section cannot appear
8352 auto *VE = RE->IgnoreParenLValueCasts();
8354 if (VE->isValueDependent() || VE->isTypeDependent() ||
8355 VE->isInstantiationDependent() ||
8356 VE->containsUnexpandedParameterPack()) {
8357 // It will be analyzed later.
8362 auto *SimpleExpr = RE->IgnoreParenCasts();
8363 auto *DE = dyn_cast<DeclRefExpr>(SimpleExpr);
8364 auto *ASE = dyn_cast<ArraySubscriptExpr>(SimpleExpr);
8365 auto *OASE = dyn_cast<OMPArraySectionExpr>(SimpleExpr);
8367 if (!RE->IgnoreParenImpCasts()->isLValue() ||
8368 (!OASE && !ASE && !DE) ||
8369 (DE && !isa<VarDecl>(DE->getDecl())) ||
8370 (ASE && !ASE->getBase()->getType()->isAnyPointerType() &&
8371 !ASE->getBase()->getType()->isArrayType())) {
8372 Diag(ELoc, diag::err_omp_expected_var_name_or_array_item)
8373 << RE->getSourceRange();
8381 auto *B = ASE->getBase()->IgnoreParenCasts();
8382 D = dyn_cast<DeclRefExpr>(B)->getDecl();
8384 auto *B = OASE->getBase();
8385 D = dyn_cast<DeclRefExpr>(B)->getDecl();
8387 assert(D && "Null decl on map clause.");
8388 auto *VD = cast<VarDecl>(D);
8390 // OpenMP [2.14.5, Restrictions, p.8]
8391 // threadprivate variables cannot appear in a map clause.
8392 if (DSAStack->isThreadPrivate(VD)) {
8393 auto DVar = DSAStack->getTopDSA(VD, false);
8394 Diag(ELoc, diag::err_omp_threadprivate_in_map);
8395 ReportOriginalDSA(*this, DSAStack, VD, DVar);
8399 // OpenMP [2.14.5, Restrictions, p.2]
8400 // At most one list item can be an array item derived from a given variable
8401 // in map clauses of the same construct.
8402 // OpenMP [2.14.5, Restrictions, p.3]
8403 // List items of map clauses in the same construct must not share original
8405 // OpenMP [2.14.5, Restrictions, C/C++, p.2]
8406 // A variable for which the type is pointer, reference to array, or
8407 // reference to pointer and an array section derived from that variable
8408 // must not appear as list items of map clauses of the same construct.
8409 DSAStackTy::MapInfo MI = DSAStack->IsMappedInCurrentRegion(VD);
8411 Diag(ELoc, diag::err_omp_map_shared_storage) << ELoc;
8412 Diag(MI.RefExpr->getExprLoc(), diag::note_used_here)
8413 << MI.RefExpr->getSourceRange();
8417 // OpenMP [2.14.5, Restrictions, C/C++, p.3,4]
8418 // A variable for which the type is pointer, reference to array, or
8419 // reference to pointer must not appear as a list item if the enclosing
8420 // device data environment already contains an array section derived from
8422 // An array section derived from a variable for which the type is pointer,
8423 // reference to array, or reference to pointer must not appear as a list
8424 // item if the enclosing device data environment already contains that
8426 QualType Type = VD->getType();
8427 MI = DSAStack->getMapInfoForVar(VD);
8428 if (MI.RefExpr && (isa<DeclRefExpr>(MI.RefExpr->IgnoreParenLValueCasts()) !=
8429 isa<DeclRefExpr>(VE)) &&
8430 (Type->isPointerType() || Type->isReferenceType())) {
8431 Diag(ELoc, diag::err_omp_map_shared_storage) << ELoc;
8432 Diag(MI.RefExpr->getExprLoc(), diag::note_used_here)
8433 << MI.RefExpr->getSourceRange();
8437 // OpenMP [2.14.5, Restrictions, C/C++, p.7]
8438 // A list item must have a mappable type.
8439 if (!CheckTypeMappable(VE->getExprLoc(), VE->getSourceRange(), *this,
8445 DSAStack->addMapInfoForVar(VD, MI);
8450 return OMPMapClause::Create(Context, StartLoc, LParenLoc, EndLoc, Vars,
8451 MapTypeModifier, MapType, MapLoc);
8454 OMPClause *Sema::ActOnOpenMPNumTeamsClause(Expr *NumTeams,
8455 SourceLocation StartLoc,
8456 SourceLocation LParenLoc,
8457 SourceLocation EndLoc) {
8458 Expr *ValExpr = NumTeams;
8460 // OpenMP [teams Constrcut, Restrictions]
8461 // The num_teams expression must evaluate to a positive integer value.
8462 if (!IsNonNegativeIntegerValue(ValExpr, *this, OMPC_num_teams,
8463 /*StrictlyPositive=*/true))
8466 return new (Context) OMPNumTeamsClause(ValExpr, StartLoc, LParenLoc, EndLoc);
8469 OMPClause *Sema::ActOnOpenMPThreadLimitClause(Expr *ThreadLimit,
8470 SourceLocation StartLoc,
8471 SourceLocation LParenLoc,
8472 SourceLocation EndLoc) {
8473 Expr *ValExpr = ThreadLimit;
8475 // OpenMP [teams Constrcut, Restrictions]
8476 // The thread_limit expression must evaluate to a positive integer value.
8477 if (!IsNonNegativeIntegerValue(ValExpr, *this, OMPC_thread_limit,
8478 /*StrictlyPositive=*/true))
8481 return new (Context) OMPThreadLimitClause(ValExpr, StartLoc, LParenLoc,
8485 OMPClause *Sema::ActOnOpenMPPriorityClause(Expr *Priority,
8486 SourceLocation StartLoc,
8487 SourceLocation LParenLoc,
8488 SourceLocation EndLoc) {
8489 Expr *ValExpr = Priority;
8491 // OpenMP [2.9.1, task Constrcut]
8492 // The priority-value is a non-negative numerical scalar expression.
8493 if (!IsNonNegativeIntegerValue(ValExpr, *this, OMPC_priority,
8494 /*StrictlyPositive=*/false))
8497 return new (Context) OMPPriorityClause(ValExpr, StartLoc, LParenLoc, EndLoc);
8500 OMPClause *Sema::ActOnOpenMPGrainsizeClause(Expr *Grainsize,
8501 SourceLocation StartLoc,
8502 SourceLocation LParenLoc,
8503 SourceLocation EndLoc) {
8504 Expr *ValExpr = Grainsize;
8506 // OpenMP [2.9.2, taskloop Constrcut]
8507 // The parameter of the grainsize clause must be a positive integer
8509 if (!IsNonNegativeIntegerValue(ValExpr, *this, OMPC_grainsize,
8510 /*StrictlyPositive=*/true))
8513 return new (Context) OMPGrainsizeClause(ValExpr, StartLoc, LParenLoc, EndLoc);
8516 OMPClause *Sema::ActOnOpenMPNumTasksClause(Expr *NumTasks,
8517 SourceLocation StartLoc,
8518 SourceLocation LParenLoc,
8519 SourceLocation EndLoc) {
8520 Expr *ValExpr = NumTasks;
8522 // OpenMP [2.9.2, taskloop Constrcut]
8523 // The parameter of the num_tasks clause must be a positive integer
8525 if (!IsNonNegativeIntegerValue(ValExpr, *this, OMPC_num_tasks,
8526 /*StrictlyPositive=*/true))
8529 return new (Context) OMPNumTasksClause(ValExpr, StartLoc, LParenLoc, EndLoc);
8532 OMPClause *Sema::ActOnOpenMPHintClause(Expr *Hint, SourceLocation StartLoc,
8533 SourceLocation LParenLoc,
8534 SourceLocation EndLoc) {
8535 // OpenMP [2.13.2, critical construct, Description]
8536 // ... where hint-expression is an integer constant expression that evaluates
8537 // to a valid lock hint.
8538 ExprResult HintExpr = VerifyPositiveIntegerConstantInClause(Hint, OMPC_hint);
8539 if (HintExpr.isInvalid())
8541 return new (Context)
8542 OMPHintClause(HintExpr.get(), StartLoc, LParenLoc, EndLoc);