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/CXXInheritance.h"
19 #include "clang/AST/Decl.h"
20 #include "clang/AST/DeclCXX.h"
21 #include "clang/AST/DeclOpenMP.h"
22 #include "clang/AST/StmtCXX.h"
23 #include "clang/AST/StmtOpenMP.h"
24 #include "clang/AST/StmtVisitor.h"
25 #include "clang/AST/TypeOrdering.h"
26 #include "clang/Basic/OpenMPKinds.h"
27 #include "clang/Basic/TargetInfo.h"
28 #include "clang/Lex/Preprocessor.h"
29 #include "clang/Sema/Initialization.h"
30 #include "clang/Sema/Lookup.h"
31 #include "clang/Sema/Scope.h"
32 #include "clang/Sema/ScopeInfo.h"
33 #include "clang/Sema/SemaInternal.h"
34 using namespace clang;
36 //===----------------------------------------------------------------------===//
37 // Stack of data-sharing attributes for variables
38 //===----------------------------------------------------------------------===//
41 /// \brief Default data sharing attributes, which can be applied to directive.
42 enum DefaultDataSharingAttributes {
43 DSA_unspecified = 0, /// \brief Data sharing attribute not specified.
44 DSA_none = 1 << 0, /// \brief Default data sharing attribute 'none'.
45 DSA_shared = 1 << 1 /// \brief Default data sharing attribute 'shared'.
48 /// \brief Stack for tracking declarations used in OpenMP directives and
49 /// clauses and their data-sharing attributes.
50 class DSAStackTy final {
52 struct DSAVarData final {
53 OpenMPDirectiveKind DKind = OMPD_unknown;
54 OpenMPClauseKind CKind = OMPC_unknown;
55 Expr *RefExpr = nullptr;
56 DeclRefExpr *PrivateCopy = nullptr;
57 SourceLocation ImplicitDSALoc;
60 typedef llvm::SmallVector<std::pair<Expr *, OverloadedOperatorKind>, 4>
64 struct DSAInfo final {
65 OpenMPClauseKind Attributes = OMPC_unknown;
66 /// Pointer to a reference expression and a flag which shows that the
67 /// variable is marked as lastprivate(true) or not (false).
68 llvm::PointerIntPair<Expr *, 1, bool> RefExpr;
69 DeclRefExpr *PrivateCopy = nullptr;
71 typedef llvm::DenseMap<ValueDecl *, DSAInfo> DeclSAMapTy;
72 typedef llvm::DenseMap<ValueDecl *, Expr *> AlignedMapTy;
73 typedef std::pair<unsigned, VarDecl *> LCDeclInfo;
74 typedef llvm::DenseMap<ValueDecl *, LCDeclInfo> LoopControlVariablesMapTy;
75 /// Struct that associates a component with the clause kind where they are
77 struct MappedExprComponentTy {
78 OMPClauseMappableExprCommon::MappableExprComponentLists Components;
79 OpenMPClauseKind Kind = OMPC_unknown;
81 typedef llvm::DenseMap<ValueDecl *, MappedExprComponentTy>
82 MappedExprComponentsTy;
83 typedef llvm::StringMap<std::pair<OMPCriticalDirective *, llvm::APSInt>>
85 typedef llvm::DenseMap<OMPDependClause *, OperatorOffsetTy>
88 struct SharingMapTy final {
89 DeclSAMapTy SharingMap;
90 AlignedMapTy AlignedMap;
91 MappedExprComponentsTy MappedExprComponents;
92 LoopControlVariablesMapTy LCVMap;
93 DefaultDataSharingAttributes DefaultAttr = DSA_unspecified;
94 SourceLocation DefaultAttrLoc;
95 OpenMPDirectiveKind Directive = OMPD_unknown;
96 DeclarationNameInfo DirectiveName;
97 Scope *CurScope = nullptr;
98 SourceLocation ConstructLoc;
99 /// Set of 'depend' clauses with 'sink|source' dependence kind. Required to
100 /// get the data (loop counters etc.) about enclosing loop-based construct.
101 /// This data is required during codegen.
102 DoacrossDependMapTy DoacrossDepends;
103 /// \brief first argument (Expr *) contains optional argument of the
104 /// 'ordered' clause, the second one is true if the regions has 'ordered'
105 /// clause, false otherwise.
106 llvm::PointerIntPair<Expr *, 1, bool> OrderedRegion;
107 bool NowaitRegion = false;
108 bool CancelRegion = false;
109 unsigned AssociatedLoops = 1;
110 SourceLocation InnerTeamsRegionLoc;
111 SharingMapTy(OpenMPDirectiveKind DKind, DeclarationNameInfo Name,
112 Scope *CurScope, SourceLocation Loc)
113 : Directive(DKind), DirectiveName(Name), CurScope(CurScope),
118 typedef SmallVector<SharingMapTy, 4> StackTy;
120 /// \brief Stack of used declaration and their data-sharing attributes.
121 DeclSAMapTy Threadprivates;
122 const FunctionScopeInfo *CurrentNonCapturingFunctionScope = nullptr;
123 SmallVector<std::pair<StackTy, const FunctionScopeInfo *>, 4> Stack;
124 /// \brief true, if check for DSA must be from parent directive, false, if
125 /// from current directive.
126 OpenMPClauseKind ClauseKindMode = OMPC_unknown;
128 bool ForceCapturing = false;
129 CriticalsWithHintsTy Criticals;
131 typedef SmallVector<SharingMapTy, 8>::reverse_iterator reverse_iterator;
133 DSAVarData getDSA(StackTy::reverse_iterator &Iter, ValueDecl *D);
135 /// \brief Checks if the variable is a local for OpenMP region.
136 bool isOpenMPLocal(VarDecl *D, StackTy::reverse_iterator Iter);
138 bool isStackEmpty() const {
139 return Stack.empty() ||
140 Stack.back().second != CurrentNonCapturingFunctionScope ||
141 Stack.back().first.empty();
145 explicit DSAStackTy(Sema &S) : SemaRef(S) {}
147 bool isClauseParsingMode() const { return ClauseKindMode != OMPC_unknown; }
148 void setClauseParsingMode(OpenMPClauseKind K) { ClauseKindMode = K; }
150 bool isForceVarCapturing() const { return ForceCapturing; }
151 void setForceVarCapturing(bool V) { ForceCapturing = V; }
153 void push(OpenMPDirectiveKind DKind, const DeclarationNameInfo &DirName,
154 Scope *CurScope, SourceLocation Loc) {
156 Stack.back().second != CurrentNonCapturingFunctionScope)
157 Stack.emplace_back(StackTy(), CurrentNonCapturingFunctionScope);
158 Stack.back().first.emplace_back(DKind, DirName, CurScope, Loc);
159 Stack.back().first.back().DefaultAttrLoc = Loc;
163 assert(!Stack.back().first.empty() &&
164 "Data-sharing attributes stack is empty!");
165 Stack.back().first.pop_back();
168 /// Start new OpenMP region stack in new non-capturing function.
169 void pushFunction() {
170 const FunctionScopeInfo *CurFnScope = SemaRef.getCurFunction();
171 assert(!isa<CapturingScopeInfo>(CurFnScope));
172 CurrentNonCapturingFunctionScope = CurFnScope;
174 /// Pop region stack for non-capturing function.
175 void popFunction(const FunctionScopeInfo *OldFSI) {
176 if (!Stack.empty() && Stack.back().second == OldFSI) {
177 assert(Stack.back().first.empty());
180 CurrentNonCapturingFunctionScope = nullptr;
181 for (const FunctionScopeInfo *FSI : llvm::reverse(SemaRef.FunctionScopes)) {
182 if (!isa<CapturingScopeInfo>(FSI)) {
183 CurrentNonCapturingFunctionScope = FSI;
189 void addCriticalWithHint(OMPCriticalDirective *D, llvm::APSInt Hint) {
190 Criticals[D->getDirectiveName().getAsString()] = std::make_pair(D, Hint);
192 const std::pair<OMPCriticalDirective *, llvm::APSInt>
193 getCriticalWithHint(const DeclarationNameInfo &Name) const {
194 auto I = Criticals.find(Name.getAsString());
195 if (I != Criticals.end())
197 return std::make_pair(nullptr, llvm::APSInt());
199 /// \brief If 'aligned' declaration for given variable \a D was not seen yet,
200 /// add it and return NULL; otherwise return previous occurrence's expression
202 Expr *addUniqueAligned(ValueDecl *D, Expr *NewDE);
204 /// \brief Register specified variable as loop control variable.
205 void addLoopControlVariable(ValueDecl *D, VarDecl *Capture);
206 /// \brief Check if the specified variable is a loop control variable for
208 /// \return The index of the loop control variable in the list of associated
209 /// for-loops (from outer to inner).
210 LCDeclInfo isLoopControlVariable(ValueDecl *D);
211 /// \brief Check if the specified variable is a loop control variable for
213 /// \return The index of the loop control variable in the list of associated
214 /// for-loops (from outer to inner).
215 LCDeclInfo isParentLoopControlVariable(ValueDecl *D);
216 /// \brief Get the loop control variable for the I-th loop (or nullptr) in
217 /// parent directive.
218 ValueDecl *getParentLoopControlVariable(unsigned I);
220 /// \brief Adds explicit data sharing attribute to the specified declaration.
221 void addDSA(ValueDecl *D, Expr *E, OpenMPClauseKind A,
222 DeclRefExpr *PrivateCopy = nullptr);
224 /// \brief Returns data sharing attributes from top of the stack for the
225 /// specified declaration.
226 DSAVarData getTopDSA(ValueDecl *D, bool FromParent);
227 /// \brief Returns data-sharing attributes for the specified declaration.
228 DSAVarData getImplicitDSA(ValueDecl *D, bool FromParent);
229 /// \brief Checks if the specified variables has data-sharing attributes which
230 /// match specified \a CPred predicate in any directive which matches \a DPred
232 DSAVarData hasDSA(ValueDecl *D,
233 const llvm::function_ref<bool(OpenMPClauseKind)> &CPred,
234 const llvm::function_ref<bool(OpenMPDirectiveKind)> &DPred,
236 /// \brief Checks if the specified variables has data-sharing attributes which
237 /// match specified \a CPred predicate in any innermost directive which
238 /// matches \a DPred predicate.
240 hasInnermostDSA(ValueDecl *D,
241 const llvm::function_ref<bool(OpenMPClauseKind)> &CPred,
242 const llvm::function_ref<bool(OpenMPDirectiveKind)> &DPred,
244 /// \brief Checks if the specified variables has explicit data-sharing
245 /// attributes which match specified \a CPred predicate at the specified
247 bool hasExplicitDSA(ValueDecl *D,
248 const llvm::function_ref<bool(OpenMPClauseKind)> &CPred,
249 unsigned Level, bool NotLastprivate = false);
251 /// \brief Returns true if the directive at level \Level matches in the
252 /// specified \a DPred predicate.
253 bool hasExplicitDirective(
254 const llvm::function_ref<bool(OpenMPDirectiveKind)> &DPred,
257 /// \brief Finds a directive which matches specified \a DPred predicate.
258 bool hasDirective(const llvm::function_ref<bool(OpenMPDirectiveKind,
259 const DeclarationNameInfo &,
260 SourceLocation)> &DPred,
263 /// \brief Returns currently analyzed directive.
264 OpenMPDirectiveKind getCurrentDirective() const {
265 return isStackEmpty() ? OMPD_unknown : Stack.back().first.back().Directive;
267 /// \brief Returns parent directive.
268 OpenMPDirectiveKind getParentDirective() const {
269 if (isStackEmpty() || Stack.back().first.size() == 1)
271 return std::next(Stack.back().first.rbegin())->Directive;
274 /// \brief Set default data sharing attribute to none.
275 void setDefaultDSANone(SourceLocation Loc) {
276 assert(!isStackEmpty());
277 Stack.back().first.back().DefaultAttr = DSA_none;
278 Stack.back().first.back().DefaultAttrLoc = Loc;
280 /// \brief Set default data sharing attribute to shared.
281 void setDefaultDSAShared(SourceLocation Loc) {
282 assert(!isStackEmpty());
283 Stack.back().first.back().DefaultAttr = DSA_shared;
284 Stack.back().first.back().DefaultAttrLoc = Loc;
287 DefaultDataSharingAttributes getDefaultDSA() const {
288 return isStackEmpty() ? DSA_unspecified
289 : Stack.back().first.back().DefaultAttr;
291 SourceLocation getDefaultDSALocation() const {
292 return isStackEmpty() ? SourceLocation()
293 : Stack.back().first.back().DefaultAttrLoc;
296 /// \brief Checks if the specified variable is a threadprivate.
297 bool isThreadPrivate(VarDecl *D) {
298 DSAVarData DVar = getTopDSA(D, false);
299 return isOpenMPThreadPrivate(DVar.CKind);
302 /// \brief Marks current region as ordered (it has an 'ordered' clause).
303 void setOrderedRegion(bool IsOrdered, Expr *Param) {
304 assert(!isStackEmpty());
305 Stack.back().first.back().OrderedRegion.setInt(IsOrdered);
306 Stack.back().first.back().OrderedRegion.setPointer(Param);
308 /// \brief Returns true, if parent region is ordered (has associated
309 /// 'ordered' clause), false - otherwise.
310 bool isParentOrderedRegion() const {
311 if (isStackEmpty() || Stack.back().first.size() == 1)
313 return std::next(Stack.back().first.rbegin())->OrderedRegion.getInt();
315 /// \brief Returns optional parameter for the ordered region.
316 Expr *getParentOrderedRegionParam() const {
317 if (isStackEmpty() || Stack.back().first.size() == 1)
319 return std::next(Stack.back().first.rbegin())->OrderedRegion.getPointer();
321 /// \brief Marks current region as nowait (it has a 'nowait' clause).
322 void setNowaitRegion(bool IsNowait = true) {
323 assert(!isStackEmpty());
324 Stack.back().first.back().NowaitRegion = IsNowait;
326 /// \brief Returns true, if parent region is nowait (has associated
327 /// 'nowait' clause), false - otherwise.
328 bool isParentNowaitRegion() const {
329 if (isStackEmpty() || Stack.back().first.size() == 1)
331 return std::next(Stack.back().first.rbegin())->NowaitRegion;
333 /// \brief Marks parent region as cancel region.
334 void setParentCancelRegion(bool Cancel = true) {
335 if (!isStackEmpty() && Stack.back().first.size() > 1) {
336 auto &StackElemRef = *std::next(Stack.back().first.rbegin());
337 StackElemRef.CancelRegion |= StackElemRef.CancelRegion || Cancel;
340 /// \brief Return true if current region has inner cancel construct.
341 bool isCancelRegion() const {
342 return isStackEmpty() ? false : Stack.back().first.back().CancelRegion;
345 /// \brief Set collapse value for the region.
346 void setAssociatedLoops(unsigned Val) {
347 assert(!isStackEmpty());
348 Stack.back().first.back().AssociatedLoops = Val;
350 /// \brief Return collapse value for region.
351 unsigned getAssociatedLoops() const {
352 return isStackEmpty() ? 0 : Stack.back().first.back().AssociatedLoops;
355 /// \brief Marks current target region as one with closely nested teams
357 void setParentTeamsRegionLoc(SourceLocation TeamsRegionLoc) {
358 if (!isStackEmpty() && Stack.back().first.size() > 1) {
359 std::next(Stack.back().first.rbegin())->InnerTeamsRegionLoc =
363 /// \brief Returns true, if current region has closely nested teams region.
364 bool hasInnerTeamsRegion() const {
365 return getInnerTeamsRegionLoc().isValid();
367 /// \brief Returns location of the nested teams region (if any).
368 SourceLocation getInnerTeamsRegionLoc() const {
369 return isStackEmpty() ? SourceLocation()
370 : Stack.back().first.back().InnerTeamsRegionLoc;
373 Scope *getCurScope() const {
374 return isStackEmpty() ? nullptr : Stack.back().first.back().CurScope;
376 Scope *getCurScope() {
377 return isStackEmpty() ? nullptr : Stack.back().first.back().CurScope;
379 SourceLocation getConstructLoc() {
380 return isStackEmpty() ? SourceLocation()
381 : Stack.back().first.back().ConstructLoc;
384 /// Do the check specified in \a Check to all component lists and return true
385 /// if any issue is found.
386 bool checkMappableExprComponentListsForDecl(
387 ValueDecl *VD, bool CurrentRegionOnly,
388 const llvm::function_ref<
389 bool(OMPClauseMappableExprCommon::MappableExprComponentListRef,
390 OpenMPClauseKind)> &Check) {
393 auto SI = Stack.back().first.rbegin();
394 auto SE = Stack.back().first.rend();
399 if (CurrentRegionOnly) {
405 for (; SI != SE; ++SI) {
406 auto MI = SI->MappedExprComponents.find(VD);
407 if (MI != SI->MappedExprComponents.end())
408 for (auto &L : MI->second.Components)
409 if (Check(L, MI->second.Kind))
415 /// Create a new mappable expression component list associated with a given
416 /// declaration and initialize it with the provided list of components.
417 void addMappableExpressionComponents(
419 OMPClauseMappableExprCommon::MappableExprComponentListRef Components,
420 OpenMPClauseKind WhereFoundClauseKind) {
421 assert(!isStackEmpty() &&
422 "Not expecting to retrieve components from a empty stack!");
423 auto &MEC = Stack.back().first.back().MappedExprComponents[VD];
424 // Create new entry and append the new components there.
425 MEC.Components.resize(MEC.Components.size() + 1);
426 MEC.Components.back().append(Components.begin(), Components.end());
427 MEC.Kind = WhereFoundClauseKind;
430 unsigned getNestingLevel() const {
431 assert(!isStackEmpty());
432 return Stack.back().first.size() - 1;
434 void addDoacrossDependClause(OMPDependClause *C, OperatorOffsetTy &OpsOffs) {
435 assert(!isStackEmpty() && Stack.back().first.size() > 1);
436 auto &StackElem = *std::next(Stack.back().first.rbegin());
437 assert(isOpenMPWorksharingDirective(StackElem.Directive));
438 StackElem.DoacrossDepends.insert({C, OpsOffs});
440 llvm::iterator_range<DoacrossDependMapTy::const_iterator>
441 getDoacrossDependClauses() const {
442 assert(!isStackEmpty());
443 auto &StackElem = Stack.back().first.back();
444 if (isOpenMPWorksharingDirective(StackElem.Directive)) {
445 auto &Ref = StackElem.DoacrossDepends;
446 return llvm::make_range(Ref.begin(), Ref.end());
448 return llvm::make_range(StackElem.DoacrossDepends.end(),
449 StackElem.DoacrossDepends.end());
452 bool isParallelOrTaskRegion(OpenMPDirectiveKind DKind) {
453 return isOpenMPParallelDirective(DKind) || isOpenMPTaskingDirective(DKind) ||
454 isOpenMPTeamsDirective(DKind) || DKind == OMPD_unknown;
458 static ValueDecl *getCanonicalDecl(ValueDecl *D) {
459 auto *VD = dyn_cast<VarDecl>(D);
460 auto *FD = dyn_cast<FieldDecl>(D);
462 VD = VD->getCanonicalDecl();
466 FD = FD->getCanonicalDecl();
472 DSAStackTy::DSAVarData DSAStackTy::getDSA(StackTy::reverse_iterator &Iter,
474 D = getCanonicalDecl(D);
475 auto *VD = dyn_cast<VarDecl>(D);
476 auto *FD = dyn_cast<FieldDecl>(D);
478 if (isStackEmpty() || Iter == Stack.back().first.rend()) {
479 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
480 // in a region but not in construct]
481 // File-scope or namespace-scope variables referenced in called routines
482 // in the region are shared unless they appear in a threadprivate
484 if (VD && !VD->isFunctionOrMethodVarDecl() && !isa<ParmVarDecl>(D))
485 DVar.CKind = OMPC_shared;
487 // OpenMP [2.9.1.2, Data-sharing Attribute Rules for Variables Referenced
488 // in a region but not in construct]
489 // Variables with static storage duration that are declared in called
490 // routines in the region are shared.
491 if (VD && VD->hasGlobalStorage())
492 DVar.CKind = OMPC_shared;
494 // Non-static data members are shared by default.
496 DVar.CKind = OMPC_shared;
501 DVar.DKind = Iter->Directive;
502 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
503 // in a Construct, C/C++, predetermined, p.1]
504 // Variables with automatic storage duration that are declared in a scope
505 // inside the construct are private.
506 if (VD && isOpenMPLocal(VD, Iter) && VD->isLocalVarDecl() &&
507 (VD->getStorageClass() == SC_Auto || VD->getStorageClass() == SC_None)) {
508 DVar.CKind = OMPC_private;
512 // Explicitly specified attributes and local variables with predetermined
514 if (Iter->SharingMap.count(D)) {
515 DVar.RefExpr = Iter->SharingMap[D].RefExpr.getPointer();
516 DVar.PrivateCopy = Iter->SharingMap[D].PrivateCopy;
517 DVar.CKind = Iter->SharingMap[D].Attributes;
518 DVar.ImplicitDSALoc = Iter->DefaultAttrLoc;
522 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
523 // in a Construct, C/C++, implicitly determined, p.1]
524 // In a parallel or task construct, the data-sharing attributes of these
525 // variables are determined by the default clause, if present.
526 switch (Iter->DefaultAttr) {
528 DVar.CKind = OMPC_shared;
529 DVar.ImplicitDSALoc = Iter->DefaultAttrLoc;
533 case DSA_unspecified:
534 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
535 // in a Construct, implicitly determined, p.2]
536 // In a parallel construct, if no default clause is present, these
537 // variables are shared.
538 DVar.ImplicitDSALoc = Iter->DefaultAttrLoc;
539 if (isOpenMPParallelDirective(DVar.DKind) ||
540 isOpenMPTeamsDirective(DVar.DKind)) {
541 DVar.CKind = OMPC_shared;
545 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
546 // in a Construct, implicitly determined, p.4]
547 // In a task construct, if no default clause is present, a variable that in
548 // the enclosing context is determined to be shared by all implicit tasks
549 // bound to the current team is shared.
550 if (isOpenMPTaskingDirective(DVar.DKind)) {
552 auto I = Iter, E = Stack.back().first.rend();
555 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables
556 // Referenced in a Construct, implicitly determined, p.6]
557 // In a task construct, if no default clause is present, a variable
558 // whose data-sharing attribute is not determined by the rules above is
560 DVarTemp = getDSA(I, D);
561 if (DVarTemp.CKind != OMPC_shared) {
562 DVar.RefExpr = nullptr;
563 DVar.CKind = OMPC_firstprivate;
566 } while (I != E && !isParallelOrTaskRegion(I->Directive));
568 (DVarTemp.CKind == OMPC_unknown) ? OMPC_firstprivate : OMPC_shared;
572 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
573 // in a Construct, implicitly determined, p.3]
574 // For constructs other than task, if no default clause is present, these
575 // variables inherit their data-sharing attributes from the enclosing
577 return getDSA(++Iter, D);
580 Expr *DSAStackTy::addUniqueAligned(ValueDecl *D, Expr *NewDE) {
581 assert(!isStackEmpty() && "Data sharing attributes stack is empty");
582 D = getCanonicalDecl(D);
583 auto &StackElem = Stack.back().first.back();
584 auto It = StackElem.AlignedMap.find(D);
585 if (It == StackElem.AlignedMap.end()) {
586 assert(NewDE && "Unexpected nullptr expr to be added into aligned map");
587 StackElem.AlignedMap[D] = NewDE;
590 assert(It->second && "Unexpected nullptr expr in the aligned map");
596 void DSAStackTy::addLoopControlVariable(ValueDecl *D, VarDecl *Capture) {
597 assert(!isStackEmpty() && "Data-sharing attributes stack is empty");
598 D = getCanonicalDecl(D);
599 auto &StackElem = Stack.back().first.back();
600 StackElem.LCVMap.insert(
601 {D, LCDeclInfo(StackElem.LCVMap.size() + 1, Capture)});
604 DSAStackTy::LCDeclInfo DSAStackTy::isLoopControlVariable(ValueDecl *D) {
605 assert(!isStackEmpty() && "Data-sharing attributes stack is empty");
606 D = getCanonicalDecl(D);
607 auto &StackElem = Stack.back().first.back();
608 auto It = StackElem.LCVMap.find(D);
609 if (It != StackElem.LCVMap.end())
614 DSAStackTy::LCDeclInfo DSAStackTy::isParentLoopControlVariable(ValueDecl *D) {
615 assert(!isStackEmpty() && Stack.back().first.size() > 1 &&
616 "Data-sharing attributes stack is empty");
617 D = getCanonicalDecl(D);
618 auto &StackElem = *std::next(Stack.back().first.rbegin());
619 auto It = StackElem.LCVMap.find(D);
620 if (It != StackElem.LCVMap.end())
625 ValueDecl *DSAStackTy::getParentLoopControlVariable(unsigned I) {
626 assert(!isStackEmpty() && Stack.back().first.size() > 1 &&
627 "Data-sharing attributes stack is empty");
628 auto &StackElem = *std::next(Stack.back().first.rbegin());
629 if (StackElem.LCVMap.size() < I)
631 for (auto &Pair : StackElem.LCVMap)
632 if (Pair.second.first == I)
637 void DSAStackTy::addDSA(ValueDecl *D, Expr *E, OpenMPClauseKind A,
638 DeclRefExpr *PrivateCopy) {
639 D = getCanonicalDecl(D);
640 if (A == OMPC_threadprivate) {
641 auto &Data = Threadprivates[D];
643 Data.RefExpr.setPointer(E);
644 Data.PrivateCopy = nullptr;
646 assert(!isStackEmpty() && "Data-sharing attributes stack is empty");
647 auto &Data = Stack.back().first.back().SharingMap[D];
648 assert(Data.Attributes == OMPC_unknown || (A == Data.Attributes) ||
649 (A == OMPC_firstprivate && Data.Attributes == OMPC_lastprivate) ||
650 (A == OMPC_lastprivate && Data.Attributes == OMPC_firstprivate) ||
651 (isLoopControlVariable(D).first && A == OMPC_private));
652 if (A == OMPC_lastprivate && Data.Attributes == OMPC_firstprivate) {
653 Data.RefExpr.setInt(/*IntVal=*/true);
656 const bool IsLastprivate =
657 A == OMPC_lastprivate || Data.Attributes == OMPC_lastprivate;
659 Data.RefExpr.setPointerAndInt(E, IsLastprivate);
660 Data.PrivateCopy = PrivateCopy;
662 auto &Data = Stack.back().first.back().SharingMap[PrivateCopy->getDecl()];
664 Data.RefExpr.setPointerAndInt(PrivateCopy, IsLastprivate);
665 Data.PrivateCopy = nullptr;
670 bool DSAStackTy::isOpenMPLocal(VarDecl *D, StackTy::reverse_iterator Iter) {
671 D = D->getCanonicalDecl();
672 if (!isStackEmpty() && Stack.back().first.size() > 1) {
673 reverse_iterator I = Iter, E = Stack.back().first.rend();
674 Scope *TopScope = nullptr;
675 while (I != E && !isParallelOrTaskRegion(I->Directive))
679 TopScope = I->CurScope ? I->CurScope->getParent() : nullptr;
680 Scope *CurScope = getCurScope();
681 while (CurScope != TopScope && !CurScope->isDeclScope(D))
682 CurScope = CurScope->getParent();
683 return CurScope != TopScope;
688 /// \brief Build a variable declaration for OpenMP loop iteration variable.
689 static VarDecl *buildVarDecl(Sema &SemaRef, SourceLocation Loc, QualType Type,
690 StringRef Name, const AttrVec *Attrs = nullptr) {
691 DeclContext *DC = SemaRef.CurContext;
692 IdentifierInfo *II = &SemaRef.PP.getIdentifierTable().get(Name);
693 TypeSourceInfo *TInfo = SemaRef.Context.getTrivialTypeSourceInfo(Type, Loc);
695 VarDecl::Create(SemaRef.Context, DC, Loc, Loc, II, Type, TInfo, SC_None);
697 for (specific_attr_iterator<AlignedAttr> I(Attrs->begin()), E(Attrs->end());
705 static DeclRefExpr *buildDeclRefExpr(Sema &S, VarDecl *D, QualType Ty,
707 bool RefersToCapture = false) {
709 D->markUsed(S.Context);
710 return DeclRefExpr::Create(S.getASTContext(), NestedNameSpecifierLoc(),
711 SourceLocation(), D, RefersToCapture, Loc, Ty,
715 DSAStackTy::DSAVarData DSAStackTy::getTopDSA(ValueDecl *D, bool FromParent) {
716 D = getCanonicalDecl(D);
719 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
720 // in a Construct, C/C++, predetermined, p.1]
721 // Variables appearing in threadprivate directives are threadprivate.
722 auto *VD = dyn_cast<VarDecl>(D);
723 if ((VD && VD->getTLSKind() != VarDecl::TLS_None &&
724 !(VD->hasAttr<OMPThreadPrivateDeclAttr>() &&
725 SemaRef.getLangOpts().OpenMPUseTLS &&
726 SemaRef.getASTContext().getTargetInfo().isTLSSupported())) ||
727 (VD && VD->getStorageClass() == SC_Register &&
728 VD->hasAttr<AsmLabelAttr>() && !VD->isLocalVarDecl())) {
729 addDSA(D, buildDeclRefExpr(SemaRef, VD, D->getType().getNonReferenceType(),
733 auto TI = Threadprivates.find(D);
734 if (TI != Threadprivates.end()) {
735 DVar.RefExpr = TI->getSecond().RefExpr.getPointer();
736 DVar.CKind = OMPC_threadprivate;
741 // Not in OpenMP execution region and top scope was already checked.
744 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
745 // in a Construct, C/C++, predetermined, p.4]
746 // Static data members are shared.
747 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
748 // in a Construct, C/C++, predetermined, p.7]
749 // Variables with static storage duration that are declared in a scope
750 // inside the construct are shared.
751 auto &&MatchesAlways = [](OpenMPDirectiveKind) -> bool { return true; };
752 if (VD && VD->isStaticDataMember()) {
753 DSAVarData DVarTemp = hasDSA(D, isOpenMPPrivate, MatchesAlways, FromParent);
754 if (DVarTemp.CKind != OMPC_unknown && DVarTemp.RefExpr)
757 DVar.CKind = OMPC_shared;
761 QualType Type = D->getType().getNonReferenceType().getCanonicalType();
762 bool IsConstant = Type.isConstant(SemaRef.getASTContext());
763 Type = SemaRef.getASTContext().getBaseElementType(Type);
764 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
765 // in a Construct, C/C++, predetermined, p.6]
766 // Variables with const qualified type having no mutable member are
769 SemaRef.getLangOpts().CPlusPlus ? Type->getAsCXXRecordDecl() : nullptr;
770 if (auto *CTSD = dyn_cast_or_null<ClassTemplateSpecializationDecl>(RD))
771 if (auto *CTD = CTSD->getSpecializedTemplate())
772 RD = CTD->getTemplatedDecl();
774 !(SemaRef.getLangOpts().CPlusPlus && RD && RD->hasDefinition() &&
775 RD->hasMutableFields())) {
776 // Variables with const-qualified type having no mutable member may be
777 // listed in a firstprivate clause, even if they are static data members.
778 DSAVarData DVarTemp = hasDSA(
779 D, [](OpenMPClauseKind C) -> bool { return C == OMPC_firstprivate; },
780 MatchesAlways, FromParent);
781 if (DVarTemp.CKind == OMPC_firstprivate && DVarTemp.RefExpr)
784 DVar.CKind = OMPC_shared;
788 // Explicitly specified attributes and local variables with predetermined
790 auto StartI = std::next(Stack.back().first.rbegin());
791 auto EndI = Stack.back().first.rend();
792 if (FromParent && StartI != EndI)
793 StartI = std::next(StartI);
794 auto I = std::prev(StartI);
795 if (I->SharingMap.count(D)) {
796 DVar.RefExpr = I->SharingMap[D].RefExpr.getPointer();
797 DVar.PrivateCopy = I->SharingMap[D].PrivateCopy;
798 DVar.CKind = I->SharingMap[D].Attributes;
799 DVar.ImplicitDSALoc = I->DefaultAttrLoc;
805 DSAStackTy::DSAVarData DSAStackTy::getImplicitDSA(ValueDecl *D,
807 if (isStackEmpty()) {
808 StackTy::reverse_iterator I;
811 D = getCanonicalDecl(D);
812 auto StartI = Stack.back().first.rbegin();
813 auto EndI = Stack.back().first.rend();
814 if (FromParent && StartI != EndI)
815 StartI = std::next(StartI);
816 return getDSA(StartI, D);
819 DSAStackTy::DSAVarData
820 DSAStackTy::hasDSA(ValueDecl *D,
821 const llvm::function_ref<bool(OpenMPClauseKind)> &CPred,
822 const llvm::function_ref<bool(OpenMPDirectiveKind)> &DPred,
826 D = getCanonicalDecl(D);
827 auto StartI = std::next(Stack.back().first.rbegin());
828 auto EndI = Stack.back().first.rend();
829 if (FromParent && StartI != EndI)
830 StartI = std::next(StartI);
833 auto I = std::prev(StartI);
836 if (!DPred(I->Directive) && !isParallelOrTaskRegion(I->Directive))
838 DSAVarData DVar = getDSA(I, D);
839 if (CPred(DVar.CKind))
845 DSAStackTy::DSAVarData DSAStackTy::hasInnermostDSA(
846 ValueDecl *D, const llvm::function_ref<bool(OpenMPClauseKind)> &CPred,
847 const llvm::function_ref<bool(OpenMPDirectiveKind)> &DPred,
851 D = getCanonicalDecl(D);
852 auto StartI = std::next(Stack.back().first.rbegin());
853 auto EndI = Stack.back().first.rend();
854 if (FromParent && StartI != EndI)
855 StartI = std::next(StartI);
856 if (StartI == EndI || !DPred(StartI->Directive))
858 DSAVarData DVar = getDSA(StartI, D);
859 return CPred(DVar.CKind) ? DVar : DSAVarData();
862 bool DSAStackTy::hasExplicitDSA(
863 ValueDecl *D, const llvm::function_ref<bool(OpenMPClauseKind)> &CPred,
864 unsigned Level, bool NotLastprivate) {
865 if (CPred(ClauseKindMode))
869 D = getCanonicalDecl(D);
870 auto StartI = Stack.back().first.begin();
871 auto EndI = Stack.back().first.end();
872 if (std::distance(StartI, EndI) <= (int)Level)
874 std::advance(StartI, Level);
875 return (StartI->SharingMap.count(D) > 0) &&
876 StartI->SharingMap[D].RefExpr.getPointer() &&
877 CPred(StartI->SharingMap[D].Attributes) &&
878 (!NotLastprivate || !StartI->SharingMap[D].RefExpr.getInt());
881 bool DSAStackTy::hasExplicitDirective(
882 const llvm::function_ref<bool(OpenMPDirectiveKind)> &DPred,
886 auto StartI = Stack.back().first.begin();
887 auto EndI = Stack.back().first.end();
888 if (std::distance(StartI, EndI) <= (int)Level)
890 std::advance(StartI, Level);
891 return DPred(StartI->Directive);
894 bool DSAStackTy::hasDirective(
895 const llvm::function_ref<bool(OpenMPDirectiveKind,
896 const DeclarationNameInfo &, SourceLocation)>
899 // We look only in the enclosing region.
902 auto StartI = std::next(Stack.back().first.rbegin());
903 auto EndI = Stack.back().first.rend();
904 if (FromParent && StartI != EndI)
905 StartI = std::next(StartI);
906 for (auto I = StartI, EE = EndI; I != EE; ++I) {
907 if (DPred(I->Directive, I->DirectiveName, I->ConstructLoc))
913 void Sema::InitDataSharingAttributesStack() {
914 VarDataSharingAttributesStack = new DSAStackTy(*this);
917 #define DSAStack static_cast<DSAStackTy *>(VarDataSharingAttributesStack)
919 void Sema::pushOpenMPFunctionRegion() {
920 DSAStack->pushFunction();
923 void Sema::popOpenMPFunctionRegion(const FunctionScopeInfo *OldFSI) {
924 DSAStack->popFunction(OldFSI);
927 bool Sema::IsOpenMPCapturedByRef(ValueDecl *D, unsigned Level) {
928 assert(LangOpts.OpenMP && "OpenMP is not allowed");
930 auto &Ctx = getASTContext();
933 // Find the directive that is associated with the provided scope.
934 auto Ty = D->getType();
936 if (DSAStack->hasExplicitDirective(isOpenMPTargetExecutionDirective, Level)) {
937 // This table summarizes how a given variable should be passed to the device
938 // given its type and the clauses where it appears. This table is based on
939 // the description in OpenMP 4.5 [2.10.4, target Construct] and
940 // OpenMP 4.5 [2.15.5, Data-mapping Attribute Rules and Clauses].
942 // =========================================================================
943 // | type | defaultmap | pvt | first | is_device_ptr | map | res. |
944 // | |(tofrom:scalar)| | pvt | | | |
945 // =========================================================================
946 // | scl | | | | - | | bycopy|
947 // | scl | | - | x | - | - | bycopy|
948 // | scl | | x | - | - | - | null |
949 // | scl | x | | | - | | byref |
950 // | scl | x | - | x | - | - | bycopy|
951 // | scl | x | x | - | - | - | null |
952 // | scl | | - | - | - | x | byref |
953 // | scl | x | - | - | - | x | byref |
955 // | agg | n.a. | | | - | | byref |
956 // | agg | n.a. | - | x | - | - | byref |
957 // | agg | n.a. | x | - | - | - | null |
958 // | agg | n.a. | - | - | - | x | byref |
959 // | agg | n.a. | - | - | - | x[] | byref |
961 // | ptr | n.a. | | | - | | bycopy|
962 // | ptr | n.a. | - | x | - | - | bycopy|
963 // | ptr | n.a. | x | - | - | - | null |
964 // | ptr | n.a. | - | - | - | x | byref |
965 // | ptr | n.a. | - | - | - | x[] | bycopy|
966 // | ptr | n.a. | - | - | x | | bycopy|
967 // | ptr | n.a. | - | - | x | x | bycopy|
968 // | ptr | n.a. | - | - | x | x[] | bycopy|
969 // =========================================================================
975 // - - invalid in this combination
976 // [] - mapped with an array section
977 // byref - should be mapped by reference
978 // byval - should be mapped by value
979 // null - initialize a local variable to null on the device
982 // - All scalar declarations that show up in a map clause have to be passed
983 // by reference, because they may have been mapped in the enclosing data
985 // - If the scalar value does not fit the size of uintptr, it has to be
986 // passed by reference, regardless the result in the table above.
987 // - For pointers mapped by value that have either an implicit map or an
988 // array section, the runtime library may pass the NULL value to the
989 // device instead of the value passed to it by the compiler.
991 if (Ty->isReferenceType())
992 Ty = Ty->castAs<ReferenceType>()->getPointeeType();
994 // Locate map clauses and see if the variable being captured is referred to
995 // in any of those clauses. Here we only care about variables, not fields,
996 // because fields are part of aggregates.
997 bool IsVariableUsedInMapClause = false;
998 bool IsVariableAssociatedWithSection = false;
1000 DSAStack->checkMappableExprComponentListsForDecl(
1001 D, /*CurrentRegionOnly=*/true,
1002 [&](OMPClauseMappableExprCommon::MappableExprComponentListRef
1004 OpenMPClauseKind WhereFoundClauseKind) {
1005 // Only the map clause information influences how a variable is
1006 // captured. E.g. is_device_ptr does not require changing the default
1008 if (WhereFoundClauseKind != OMPC_map)
1011 auto EI = MapExprComponents.rbegin();
1012 auto EE = MapExprComponents.rend();
1014 assert(EI != EE && "Invalid map expression!");
1016 if (isa<DeclRefExpr>(EI->getAssociatedExpression()))
1017 IsVariableUsedInMapClause |= EI->getAssociatedDeclaration() == D;
1023 if (isa<ArraySubscriptExpr>(EI->getAssociatedExpression()) ||
1024 isa<OMPArraySectionExpr>(EI->getAssociatedExpression()) ||
1025 isa<MemberExpr>(EI->getAssociatedExpression())) {
1026 IsVariableAssociatedWithSection = true;
1027 // There is nothing more we need to know about this variable.
1031 // Keep looking for more map info.
1035 if (IsVariableUsedInMapClause) {
1036 // If variable is identified in a map clause it is always captured by
1037 // reference except if it is a pointer that is dereferenced somehow.
1038 IsByRef = !(Ty->isPointerType() && IsVariableAssociatedWithSection);
1040 // By default, all the data that has a scalar type is mapped by copy.
1041 IsByRef = !Ty->isScalarType();
1045 if (IsByRef && Ty.getNonReferenceType()->isScalarType()) {
1046 IsByRef = !DSAStack->hasExplicitDSA(
1047 D, [](OpenMPClauseKind K) -> bool { return K == OMPC_firstprivate; },
1048 Level, /*NotLastprivate=*/true);
1051 // When passing data by copy, we need to make sure it fits the uintptr size
1052 // and alignment, because the runtime library only deals with uintptr types.
1053 // If it does not fit the uintptr size, we need to pass the data by reference
1056 (Ctx.getTypeSizeInChars(Ty) >
1057 Ctx.getTypeSizeInChars(Ctx.getUIntPtrType()) ||
1058 Ctx.getDeclAlign(D) > Ctx.getTypeAlignInChars(Ctx.getUIntPtrType()))) {
1065 unsigned Sema::getOpenMPNestingLevel() const {
1066 assert(getLangOpts().OpenMP);
1067 return DSAStack->getNestingLevel();
1070 VarDecl *Sema::IsOpenMPCapturedDecl(ValueDecl *D) {
1071 assert(LangOpts.OpenMP && "OpenMP is not allowed");
1072 D = getCanonicalDecl(D);
1074 // If we are attempting to capture a global variable in a directive with
1075 // 'target' we return true so that this global is also mapped to the device.
1077 // FIXME: If the declaration is enclosed in a 'declare target' directive,
1078 // then it should not be captured. Therefore, an extra check has to be
1079 // inserted here once support for 'declare target' is added.
1081 auto *VD = dyn_cast<VarDecl>(D);
1082 if (VD && !VD->hasLocalStorage()) {
1083 if (DSAStack->getCurrentDirective() == OMPD_target &&
1084 !DSAStack->isClauseParsingMode())
1086 if (DSAStack->hasDirective(
1087 [](OpenMPDirectiveKind K, const DeclarationNameInfo &,
1088 SourceLocation) -> bool {
1089 return isOpenMPTargetExecutionDirective(K);
1095 if (DSAStack->getCurrentDirective() != OMPD_unknown &&
1096 (!DSAStack->isClauseParsingMode() ||
1097 DSAStack->getParentDirective() != OMPD_unknown)) {
1098 auto &&Info = DSAStack->isLoopControlVariable(D);
1100 (VD && VD->hasLocalStorage() &&
1101 isParallelOrTaskRegion(DSAStack->getCurrentDirective())) ||
1102 (VD && DSAStack->isForceVarCapturing()))
1103 return VD ? VD : Info.second;
1104 auto DVarPrivate = DSAStack->getTopDSA(D, DSAStack->isClauseParsingMode());
1105 if (DVarPrivate.CKind != OMPC_unknown && isOpenMPPrivate(DVarPrivate.CKind))
1106 return VD ? VD : cast<VarDecl>(DVarPrivate.PrivateCopy->getDecl());
1107 DVarPrivate = DSAStack->hasDSA(
1108 D, isOpenMPPrivate, [](OpenMPDirectiveKind) -> bool { return true; },
1109 DSAStack->isClauseParsingMode());
1110 if (DVarPrivate.CKind != OMPC_unknown)
1111 return VD ? VD : cast<VarDecl>(DVarPrivate.PrivateCopy->getDecl());
1116 bool Sema::isOpenMPPrivateDecl(ValueDecl *D, unsigned Level) {
1117 assert(LangOpts.OpenMP && "OpenMP is not allowed");
1118 return DSAStack->hasExplicitDSA(
1119 D, [](OpenMPClauseKind K) -> bool { return K == OMPC_private; }, Level);
1122 bool Sema::isOpenMPTargetCapturedDecl(ValueDecl *D, unsigned Level) {
1123 assert(LangOpts.OpenMP && "OpenMP is not allowed");
1124 // Return true if the current level is no longer enclosed in a target region.
1126 auto *VD = dyn_cast<VarDecl>(D);
1127 return VD && !VD->hasLocalStorage() &&
1128 DSAStack->hasExplicitDirective(isOpenMPTargetExecutionDirective,
1132 void Sema::DestroyDataSharingAttributesStack() { delete DSAStack; }
1134 void Sema::StartOpenMPDSABlock(OpenMPDirectiveKind DKind,
1135 const DeclarationNameInfo &DirName,
1136 Scope *CurScope, SourceLocation Loc) {
1137 DSAStack->push(DKind, DirName, CurScope, Loc);
1138 PushExpressionEvaluationContext(
1139 ExpressionEvaluationContext::PotentiallyEvaluated);
1142 void Sema::StartOpenMPClause(OpenMPClauseKind K) {
1143 DSAStack->setClauseParsingMode(K);
1146 void Sema::EndOpenMPClause() {
1147 DSAStack->setClauseParsingMode(/*K=*/OMPC_unknown);
1150 void Sema::EndOpenMPDSABlock(Stmt *CurDirective) {
1151 // OpenMP [2.14.3.5, Restrictions, C/C++, p.1]
1152 // A variable of class type (or array thereof) that appears in a lastprivate
1153 // clause requires an accessible, unambiguous default constructor for the
1154 // class type, unless the list item is also specified in a firstprivate
1156 if (auto *D = dyn_cast_or_null<OMPExecutableDirective>(CurDirective)) {
1157 for (auto *C : D->clauses()) {
1158 if (auto *Clause = dyn_cast<OMPLastprivateClause>(C)) {
1159 SmallVector<Expr *, 8> PrivateCopies;
1160 for (auto *DE : Clause->varlists()) {
1161 if (DE->isValueDependent() || DE->isTypeDependent()) {
1162 PrivateCopies.push_back(nullptr);
1165 auto *DRE = cast<DeclRefExpr>(DE->IgnoreParens());
1166 VarDecl *VD = cast<VarDecl>(DRE->getDecl());
1167 QualType Type = VD->getType().getNonReferenceType();
1168 auto DVar = DSAStack->getTopDSA(VD, false);
1169 if (DVar.CKind == OMPC_lastprivate) {
1170 // Generate helper private variable and initialize it with the
1171 // default value. The address of the original variable is replaced
1172 // by the address of the new private variable in CodeGen. This new
1173 // variable is not added to IdResolver, so the code in the OpenMP
1174 // region uses original variable for proper diagnostics.
1175 auto *VDPrivate = buildVarDecl(
1176 *this, DE->getExprLoc(), Type.getUnqualifiedType(),
1177 VD->getName(), VD->hasAttrs() ? &VD->getAttrs() : nullptr);
1178 ActOnUninitializedDecl(VDPrivate);
1179 if (VDPrivate->isInvalidDecl())
1181 PrivateCopies.push_back(buildDeclRefExpr(
1182 *this, VDPrivate, DE->getType(), DE->getExprLoc()));
1184 // The variable is also a firstprivate, so initialization sequence
1185 // for private copy is generated already.
1186 PrivateCopies.push_back(nullptr);
1189 // Set initializers to private copies if no errors were found.
1190 if (PrivateCopies.size() == Clause->varlist_size())
1191 Clause->setPrivateCopies(PrivateCopies);
1197 DiscardCleanupsInEvaluationContext();
1198 PopExpressionEvaluationContext();
1201 static bool FinishOpenMPLinearClause(OMPLinearClause &Clause, DeclRefExpr *IV,
1202 Expr *NumIterations, Sema &SemaRef,
1203 Scope *S, DSAStackTy *Stack);
1207 class VarDeclFilterCCC : public CorrectionCandidateCallback {
1212 explicit VarDeclFilterCCC(Sema &S) : SemaRef(S) {}
1213 bool ValidateCandidate(const TypoCorrection &Candidate) override {
1214 NamedDecl *ND = Candidate.getCorrectionDecl();
1215 if (auto *VD = dyn_cast_or_null<VarDecl>(ND)) {
1216 return VD->hasGlobalStorage() &&
1217 SemaRef.isDeclInScope(ND, SemaRef.getCurLexicalContext(),
1218 SemaRef.getCurScope());
1224 class VarOrFuncDeclFilterCCC : public CorrectionCandidateCallback {
1229 explicit VarOrFuncDeclFilterCCC(Sema &S) : SemaRef(S) {}
1230 bool ValidateCandidate(const TypoCorrection &Candidate) override {
1231 NamedDecl *ND = Candidate.getCorrectionDecl();
1232 if (isa<VarDecl>(ND) || isa<FunctionDecl>(ND)) {
1233 return SemaRef.isDeclInScope(ND, SemaRef.getCurLexicalContext(),
1234 SemaRef.getCurScope());
1242 ExprResult Sema::ActOnOpenMPIdExpression(Scope *CurScope,
1243 CXXScopeSpec &ScopeSpec,
1244 const DeclarationNameInfo &Id) {
1245 LookupResult Lookup(*this, Id, LookupOrdinaryName);
1246 LookupParsedName(Lookup, CurScope, &ScopeSpec, true);
1248 if (Lookup.isAmbiguous())
1252 if (!Lookup.isSingleResult()) {
1253 if (TypoCorrection Corrected = CorrectTypo(
1254 Id, LookupOrdinaryName, CurScope, nullptr,
1255 llvm::make_unique<VarDeclFilterCCC>(*this), CTK_ErrorRecovery)) {
1256 diagnoseTypo(Corrected,
1257 PDiag(Lookup.empty()
1258 ? diag::err_undeclared_var_use_suggest
1259 : diag::err_omp_expected_var_arg_suggest)
1261 VD = Corrected.getCorrectionDeclAs<VarDecl>();
1263 Diag(Id.getLoc(), Lookup.empty() ? diag::err_undeclared_var_use
1264 : diag::err_omp_expected_var_arg)
1269 if (!(VD = Lookup.getAsSingle<VarDecl>())) {
1270 Diag(Id.getLoc(), diag::err_omp_expected_var_arg) << Id.getName();
1271 Diag(Lookup.getFoundDecl()->getLocation(), diag::note_declared_at);
1275 Lookup.suppressDiagnostics();
1277 // OpenMP [2.9.2, Syntax, C/C++]
1278 // Variables must be file-scope, namespace-scope, or static block-scope.
1279 if (!VD->hasGlobalStorage()) {
1280 Diag(Id.getLoc(), diag::err_omp_global_var_arg)
1281 << getOpenMPDirectiveName(OMPD_threadprivate) << !VD->isStaticLocal();
1283 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
1284 Diag(VD->getLocation(),
1285 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
1290 VarDecl *CanonicalVD = VD->getCanonicalDecl();
1291 NamedDecl *ND = cast<NamedDecl>(CanonicalVD);
1292 // OpenMP [2.9.2, Restrictions, C/C++, p.2]
1293 // A threadprivate directive for file-scope variables must appear outside
1294 // any definition or declaration.
1295 if (CanonicalVD->getDeclContext()->isTranslationUnit() &&
1296 !getCurLexicalContext()->isTranslationUnit()) {
1297 Diag(Id.getLoc(), diag::err_omp_var_scope)
1298 << getOpenMPDirectiveName(OMPD_threadprivate) << VD;
1300 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
1301 Diag(VD->getLocation(),
1302 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
1306 // OpenMP [2.9.2, Restrictions, C/C++, p.3]
1307 // A threadprivate directive for static class member variables must appear
1308 // in the class definition, in the same scope in which the member
1309 // variables are declared.
1310 if (CanonicalVD->isStaticDataMember() &&
1311 !CanonicalVD->getDeclContext()->Equals(getCurLexicalContext())) {
1312 Diag(Id.getLoc(), diag::err_omp_var_scope)
1313 << getOpenMPDirectiveName(OMPD_threadprivate) << VD;
1315 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
1316 Diag(VD->getLocation(),
1317 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
1321 // OpenMP [2.9.2, Restrictions, C/C++, p.4]
1322 // A threadprivate directive for namespace-scope variables must appear
1323 // outside any definition or declaration other than the namespace
1324 // definition itself.
1325 if (CanonicalVD->getDeclContext()->isNamespace() &&
1326 (!getCurLexicalContext()->isFileContext() ||
1327 !getCurLexicalContext()->Encloses(CanonicalVD->getDeclContext()))) {
1328 Diag(Id.getLoc(), diag::err_omp_var_scope)
1329 << getOpenMPDirectiveName(OMPD_threadprivate) << VD;
1331 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
1332 Diag(VD->getLocation(),
1333 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
1337 // OpenMP [2.9.2, Restrictions, C/C++, p.6]
1338 // A threadprivate directive for static block-scope variables must appear
1339 // in the scope of the variable and not in a nested scope.
1340 if (CanonicalVD->isStaticLocal() && CurScope &&
1341 !isDeclInScope(ND, getCurLexicalContext(), CurScope)) {
1342 Diag(Id.getLoc(), diag::err_omp_var_scope)
1343 << getOpenMPDirectiveName(OMPD_threadprivate) << VD;
1345 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
1346 Diag(VD->getLocation(),
1347 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
1352 // OpenMP [2.9.2, Restrictions, C/C++, p.2-6]
1353 // A threadprivate directive must lexically precede all references to any
1354 // of the variables in its list.
1355 if (VD->isUsed() && !DSAStack->isThreadPrivate(VD)) {
1356 Diag(Id.getLoc(), diag::err_omp_var_used)
1357 << getOpenMPDirectiveName(OMPD_threadprivate) << VD;
1361 QualType ExprType = VD->getType().getNonReferenceType();
1362 return DeclRefExpr::Create(Context, NestedNameSpecifierLoc(),
1363 SourceLocation(), VD,
1364 /*RefersToEnclosingVariableOrCapture=*/false,
1365 Id.getLoc(), ExprType, VK_LValue);
1368 Sema::DeclGroupPtrTy
1369 Sema::ActOnOpenMPThreadprivateDirective(SourceLocation Loc,
1370 ArrayRef<Expr *> VarList) {
1371 if (OMPThreadPrivateDecl *D = CheckOMPThreadPrivateDecl(Loc, VarList)) {
1372 CurContext->addDecl(D);
1373 return DeclGroupPtrTy::make(DeclGroupRef(D));
1379 class LocalVarRefChecker : public ConstStmtVisitor<LocalVarRefChecker, bool> {
1383 bool VisitDeclRefExpr(const DeclRefExpr *E) {
1384 if (auto *VD = dyn_cast<VarDecl>(E->getDecl())) {
1385 if (VD->hasLocalStorage()) {
1386 SemaRef.Diag(E->getLocStart(),
1387 diag::err_omp_local_var_in_threadprivate_init)
1388 << E->getSourceRange();
1389 SemaRef.Diag(VD->getLocation(), diag::note_defined_here)
1390 << VD << VD->getSourceRange();
1396 bool VisitStmt(const Stmt *S) {
1397 for (auto Child : S->children()) {
1398 if (Child && Visit(Child))
1403 explicit LocalVarRefChecker(Sema &SemaRef) : SemaRef(SemaRef) {}
1407 OMPThreadPrivateDecl *
1408 Sema::CheckOMPThreadPrivateDecl(SourceLocation Loc, ArrayRef<Expr *> VarList) {
1409 SmallVector<Expr *, 8> Vars;
1410 for (auto &RefExpr : VarList) {
1411 DeclRefExpr *DE = cast<DeclRefExpr>(RefExpr);
1412 VarDecl *VD = cast<VarDecl>(DE->getDecl());
1413 SourceLocation ILoc = DE->getExprLoc();
1415 // Mark variable as used.
1416 VD->setReferenced();
1417 VD->markUsed(Context);
1419 QualType QType = VD->getType();
1420 if (QType->isDependentType() || QType->isInstantiationDependentType()) {
1421 // It will be analyzed later.
1426 // OpenMP [2.9.2, Restrictions, C/C++, p.10]
1427 // A threadprivate variable must not have an incomplete type.
1428 if (RequireCompleteType(ILoc, VD->getType(),
1429 diag::err_omp_threadprivate_incomplete_type)) {
1433 // OpenMP [2.9.2, Restrictions, C/C++, p.10]
1434 // A threadprivate variable must not have a reference type.
1435 if (VD->getType()->isReferenceType()) {
1436 Diag(ILoc, diag::err_omp_ref_type_arg)
1437 << getOpenMPDirectiveName(OMPD_threadprivate) << VD->getType();
1439 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
1440 Diag(VD->getLocation(),
1441 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
1446 // Check if this is a TLS variable. If TLS is not being supported, produce
1447 // the corresponding diagnostic.
1448 if ((VD->getTLSKind() != VarDecl::TLS_None &&
1449 !(VD->hasAttr<OMPThreadPrivateDeclAttr>() &&
1450 getLangOpts().OpenMPUseTLS &&
1451 getASTContext().getTargetInfo().isTLSSupported())) ||
1452 (VD->getStorageClass() == SC_Register && VD->hasAttr<AsmLabelAttr>() &&
1453 !VD->isLocalVarDecl())) {
1454 Diag(ILoc, diag::err_omp_var_thread_local)
1455 << VD << ((VD->getTLSKind() != VarDecl::TLS_None) ? 0 : 1);
1457 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
1458 Diag(VD->getLocation(),
1459 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
1464 // Check if initial value of threadprivate variable reference variable with
1465 // local storage (it is not supported by runtime).
1466 if (auto Init = VD->getAnyInitializer()) {
1467 LocalVarRefChecker Checker(*this);
1468 if (Checker.Visit(Init))
1472 Vars.push_back(RefExpr);
1473 DSAStack->addDSA(VD, DE, OMPC_threadprivate);
1474 VD->addAttr(OMPThreadPrivateDeclAttr::CreateImplicit(
1475 Context, SourceRange(Loc, Loc)));
1476 if (auto *ML = Context.getASTMutationListener())
1477 ML->DeclarationMarkedOpenMPThreadPrivate(VD);
1479 OMPThreadPrivateDecl *D = nullptr;
1480 if (!Vars.empty()) {
1481 D = OMPThreadPrivateDecl::Create(Context, getCurLexicalContext(), Loc,
1483 D->setAccess(AS_public);
1488 static void ReportOriginalDSA(Sema &SemaRef, DSAStackTy *Stack,
1489 const ValueDecl *D, DSAStackTy::DSAVarData DVar,
1490 bool IsLoopIterVar = false) {
1492 SemaRef.Diag(DVar.RefExpr->getExprLoc(), diag::note_omp_explicit_dsa)
1493 << getOpenMPClauseName(DVar.CKind);
1497 PDSA_StaticMemberShared,
1498 PDSA_StaticLocalVarShared,
1499 PDSA_LoopIterVarPrivate,
1500 PDSA_LoopIterVarLinear,
1501 PDSA_LoopIterVarLastprivate,
1502 PDSA_ConstVarShared,
1503 PDSA_GlobalVarShared,
1504 PDSA_TaskVarFirstprivate,
1505 PDSA_LocalVarPrivate,
1507 } Reason = PDSA_Implicit;
1508 bool ReportHint = false;
1509 auto ReportLoc = D->getLocation();
1510 auto *VD = dyn_cast<VarDecl>(D);
1511 if (IsLoopIterVar) {
1512 if (DVar.CKind == OMPC_private)
1513 Reason = PDSA_LoopIterVarPrivate;
1514 else if (DVar.CKind == OMPC_lastprivate)
1515 Reason = PDSA_LoopIterVarLastprivate;
1517 Reason = PDSA_LoopIterVarLinear;
1518 } else if (isOpenMPTaskingDirective(DVar.DKind) &&
1519 DVar.CKind == OMPC_firstprivate) {
1520 Reason = PDSA_TaskVarFirstprivate;
1521 ReportLoc = DVar.ImplicitDSALoc;
1522 } else if (VD && VD->isStaticLocal())
1523 Reason = PDSA_StaticLocalVarShared;
1524 else if (VD && VD->isStaticDataMember())
1525 Reason = PDSA_StaticMemberShared;
1526 else if (VD && VD->isFileVarDecl())
1527 Reason = PDSA_GlobalVarShared;
1528 else if (D->getType().isConstant(SemaRef.getASTContext()))
1529 Reason = PDSA_ConstVarShared;
1530 else if (VD && VD->isLocalVarDecl() && DVar.CKind == OMPC_private) {
1532 Reason = PDSA_LocalVarPrivate;
1534 if (Reason != PDSA_Implicit) {
1535 SemaRef.Diag(ReportLoc, diag::note_omp_predetermined_dsa)
1536 << Reason << ReportHint
1537 << getOpenMPDirectiveName(Stack->getCurrentDirective());
1538 } else if (DVar.ImplicitDSALoc.isValid()) {
1539 SemaRef.Diag(DVar.ImplicitDSALoc, diag::note_omp_implicit_dsa)
1540 << getOpenMPClauseName(DVar.CKind);
1545 class DSAAttrChecker : public StmtVisitor<DSAAttrChecker, void> {
1550 llvm::SmallVector<Expr *, 8> ImplicitFirstprivate;
1551 llvm::DenseMap<ValueDecl *, Expr *> VarsWithInheritedDSA;
1554 void VisitDeclRefExpr(DeclRefExpr *E) {
1555 if (E->isTypeDependent() || E->isValueDependent() ||
1556 E->containsUnexpandedParameterPack() || E->isInstantiationDependent())
1558 if (auto *VD = dyn_cast<VarDecl>(E->getDecl())) {
1559 // Skip internally declared variables.
1560 if (VD->isLocalVarDecl() && !CS->capturesVariable(VD))
1563 auto DVar = Stack->getTopDSA(VD, false);
1564 // Check if the variable has explicit DSA set and stop analysis if it so.
1568 auto ELoc = E->getExprLoc();
1569 auto DKind = Stack->getCurrentDirective();
1570 // The default(none) clause requires that each variable that is referenced
1571 // in the construct, and does not have a predetermined data-sharing
1572 // attribute, must have its data-sharing attribute explicitly determined
1573 // by being listed in a data-sharing attribute clause.
1574 if (DVar.CKind == OMPC_unknown && Stack->getDefaultDSA() == DSA_none &&
1575 isParallelOrTaskRegion(DKind) &&
1576 VarsWithInheritedDSA.count(VD) == 0) {
1577 VarsWithInheritedDSA[VD] = E;
1581 // OpenMP [2.9.3.6, Restrictions, p.2]
1582 // A list item that appears in a reduction clause of the innermost
1583 // enclosing worksharing or parallel construct may not be accessed in an
1585 DVar = Stack->hasInnermostDSA(
1586 VD, [](OpenMPClauseKind C) -> bool { return C == OMPC_reduction; },
1587 [](OpenMPDirectiveKind K) -> bool {
1588 return isOpenMPParallelDirective(K) ||
1589 isOpenMPWorksharingDirective(K) || isOpenMPTeamsDirective(K);
1592 if (isOpenMPTaskingDirective(DKind) && DVar.CKind == OMPC_reduction) {
1594 SemaRef.Diag(ELoc, diag::err_omp_reduction_in_task);
1595 ReportOriginalDSA(SemaRef, Stack, VD, DVar);
1599 // Define implicit data-sharing attributes for task.
1600 DVar = Stack->getImplicitDSA(VD, false);
1601 if (isOpenMPTaskingDirective(DKind) && DVar.CKind != OMPC_shared &&
1602 !Stack->isLoopControlVariable(VD).first)
1603 ImplicitFirstprivate.push_back(E);
1606 void VisitMemberExpr(MemberExpr *E) {
1607 if (E->isTypeDependent() || E->isValueDependent() ||
1608 E->containsUnexpandedParameterPack() || E->isInstantiationDependent())
1610 if (isa<CXXThisExpr>(E->getBase()->IgnoreParens())) {
1611 if (auto *FD = dyn_cast<FieldDecl>(E->getMemberDecl())) {
1612 auto DVar = Stack->getTopDSA(FD, false);
1613 // Check if the variable has explicit DSA set and stop analysis if it
1618 auto ELoc = E->getExprLoc();
1619 auto DKind = Stack->getCurrentDirective();
1620 // OpenMP [2.9.3.6, Restrictions, p.2]
1621 // A list item that appears in a reduction clause of the innermost
1622 // enclosing worksharing or parallel construct may not be accessed in
1623 // an explicit task.
1624 DVar = Stack->hasInnermostDSA(
1625 FD, [](OpenMPClauseKind C) -> bool { return C == OMPC_reduction; },
1626 [](OpenMPDirectiveKind K) -> bool {
1627 return isOpenMPParallelDirective(K) ||
1628 isOpenMPWorksharingDirective(K) ||
1629 isOpenMPTeamsDirective(K);
1632 if (isOpenMPTaskingDirective(DKind) && DVar.CKind == OMPC_reduction) {
1634 SemaRef.Diag(ELoc, diag::err_omp_reduction_in_task);
1635 ReportOriginalDSA(SemaRef, Stack, FD, DVar);
1639 // Define implicit data-sharing attributes for task.
1640 DVar = Stack->getImplicitDSA(FD, false);
1641 if (isOpenMPTaskingDirective(DKind) && DVar.CKind != OMPC_shared &&
1642 !Stack->isLoopControlVariable(FD).first)
1643 ImplicitFirstprivate.push_back(E);
1646 Visit(E->getBase());
1648 void VisitOMPExecutableDirective(OMPExecutableDirective *S) {
1649 for (auto *C : S->clauses()) {
1650 // Skip analysis of arguments of implicitly defined firstprivate clause
1651 // for task directives.
1652 if (C && (!isa<OMPFirstprivateClause>(C) || C->getLocStart().isValid()))
1653 for (auto *CC : C->children()) {
1659 void VisitStmt(Stmt *S) {
1660 for (auto *C : S->children()) {
1661 if (C && !isa<OMPExecutableDirective>(C))
1666 bool isErrorFound() { return ErrorFound; }
1667 ArrayRef<Expr *> getImplicitFirstprivate() { return ImplicitFirstprivate; }
1668 llvm::DenseMap<ValueDecl *, Expr *> &getVarsWithInheritedDSA() {
1669 return VarsWithInheritedDSA;
1672 DSAAttrChecker(DSAStackTy *S, Sema &SemaRef, CapturedStmt *CS)
1673 : Stack(S), SemaRef(SemaRef), ErrorFound(false), CS(CS) {}
1677 void Sema::ActOnOpenMPRegionStart(OpenMPDirectiveKind DKind, Scope *CurScope) {
1680 case OMPD_parallel_for:
1681 case OMPD_parallel_for_simd:
1682 case OMPD_parallel_sections:
1684 QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1);
1685 QualType KmpInt32PtrTy =
1686 Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
1687 Sema::CapturedParamNameType Params[] = {
1688 std::make_pair(".global_tid.", KmpInt32PtrTy),
1689 std::make_pair(".bound_tid.", KmpInt32PtrTy),
1690 std::make_pair(StringRef(), QualType()) // __context with shared vars
1692 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
1696 case OMPD_target_teams:
1697 case OMPD_target_parallel: {
1698 Sema::CapturedParamNameType ParamsTarget[] = {
1699 std::make_pair(StringRef(), QualType()) // __context with shared vars
1701 // Start a captured region for 'target' with no implicit parameters.
1702 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
1704 QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1);
1705 QualType KmpInt32PtrTy =
1706 Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
1707 Sema::CapturedParamNameType ParamsTeamsOrParallel[] = {
1708 std::make_pair(".global_tid.", KmpInt32PtrTy),
1709 std::make_pair(".bound_tid.", KmpInt32PtrTy),
1710 std::make_pair(StringRef(), QualType()) // __context with shared vars
1712 // Start a captured region for 'teams' or 'parallel'. Both regions have
1713 // the same implicit parameters.
1714 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
1715 ParamsTeamsOrParallel);
1726 case OMPD_taskgroup:
1727 case OMPD_distribute:
1730 case OMPD_target_data:
1732 case OMPD_target_parallel_for:
1733 case OMPD_target_parallel_for_simd:
1734 case OMPD_target_simd: {
1735 Sema::CapturedParamNameType Params[] = {
1736 std::make_pair(StringRef(), QualType()) // __context with shared vars
1738 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
1743 QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1);
1744 QualType Args[] = {Context.VoidPtrTy.withConst().withRestrict()};
1745 FunctionProtoType::ExtProtoInfo EPI;
1746 EPI.Variadic = true;
1747 QualType CopyFnType = Context.getFunctionType(Context.VoidTy, Args, EPI);
1748 Sema::CapturedParamNameType Params[] = {
1749 std::make_pair(".global_tid.", KmpInt32Ty),
1750 std::make_pair(".part_id.", Context.getPointerType(KmpInt32Ty)),
1751 std::make_pair(".privates.", Context.VoidPtrTy.withConst()),
1752 std::make_pair(".copy_fn.",
1753 Context.getPointerType(CopyFnType).withConst()),
1754 std::make_pair(".task_t.", Context.VoidPtrTy.withConst()),
1755 std::make_pair(StringRef(), QualType()) // __context with shared vars
1757 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
1759 // Mark this captured region as inlined, because we don't use outlined
1760 // function directly.
1761 getCurCapturedRegion()->TheCapturedDecl->addAttr(
1762 AlwaysInlineAttr::CreateImplicit(
1763 Context, AlwaysInlineAttr::Keyword_forceinline, SourceRange()));
1767 case OMPD_taskloop_simd: {
1768 QualType KmpInt32Ty =
1769 Context.getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/1);
1770 QualType KmpUInt64Ty =
1771 Context.getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/0);
1772 QualType KmpInt64Ty =
1773 Context.getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/1);
1774 QualType Args[] = {Context.VoidPtrTy.withConst().withRestrict()};
1775 FunctionProtoType::ExtProtoInfo EPI;
1776 EPI.Variadic = true;
1777 QualType CopyFnType = Context.getFunctionType(Context.VoidTy, Args, EPI);
1778 Sema::CapturedParamNameType Params[] = {
1779 std::make_pair(".global_tid.", KmpInt32Ty),
1780 std::make_pair(".part_id.", Context.getPointerType(KmpInt32Ty)),
1781 std::make_pair(".privates.",
1782 Context.VoidPtrTy.withConst().withRestrict()),
1785 Context.getPointerType(CopyFnType).withConst().withRestrict()),
1786 std::make_pair(".task_t.", Context.VoidPtrTy.withConst()),
1787 std::make_pair(".lb.", KmpUInt64Ty),
1788 std::make_pair(".ub.", KmpUInt64Ty), std::make_pair(".st.", KmpInt64Ty),
1789 std::make_pair(".liter.", KmpInt32Ty),
1790 std::make_pair(StringRef(), QualType()) // __context with shared vars
1792 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
1794 // Mark this captured region as inlined, because we don't use outlined
1795 // function directly.
1796 getCurCapturedRegion()->TheCapturedDecl->addAttr(
1797 AlwaysInlineAttr::CreateImplicit(
1798 Context, AlwaysInlineAttr::Keyword_forceinline, SourceRange()));
1801 case OMPD_distribute_parallel_for_simd:
1802 case OMPD_distribute_simd:
1803 case OMPD_distribute_parallel_for:
1804 case OMPD_teams_distribute:
1805 case OMPD_teams_distribute_simd:
1806 case OMPD_teams_distribute_parallel_for_simd:
1807 case OMPD_teams_distribute_parallel_for:
1808 case OMPD_target_teams_distribute:
1809 case OMPD_target_teams_distribute_parallel_for:
1810 case OMPD_target_teams_distribute_parallel_for_simd:
1811 case OMPD_target_teams_distribute_simd: {
1812 QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1);
1813 QualType KmpInt32PtrTy =
1814 Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
1815 Sema::CapturedParamNameType Params[] = {
1816 std::make_pair(".global_tid.", KmpInt32PtrTy),
1817 std::make_pair(".bound_tid.", KmpInt32PtrTy),
1818 std::make_pair(".previous.lb.", Context.getSizeType()),
1819 std::make_pair(".previous.ub.", Context.getSizeType()),
1820 std::make_pair(StringRef(), QualType()) // __context with shared vars
1822 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
1826 case OMPD_threadprivate:
1827 case OMPD_taskyield:
1830 case OMPD_cancellation_point:
1833 case OMPD_target_enter_data:
1834 case OMPD_target_exit_data:
1835 case OMPD_declare_reduction:
1836 case OMPD_declare_simd:
1837 case OMPD_declare_target:
1838 case OMPD_end_declare_target:
1839 case OMPD_target_update:
1840 llvm_unreachable("OpenMP Directive is not allowed");
1842 llvm_unreachable("Unknown OpenMP directive");
1846 int Sema::getOpenMPCaptureLevels(OpenMPDirectiveKind DKind) {
1847 SmallVector<OpenMPDirectiveKind, 4> CaptureRegions;
1848 getOpenMPCaptureRegions(CaptureRegions, DKind);
1849 return CaptureRegions.size();
1852 static OMPCapturedExprDecl *buildCaptureDecl(Sema &S, IdentifierInfo *Id,
1853 Expr *CaptureExpr, bool WithInit,
1854 bool AsExpression) {
1855 assert(CaptureExpr);
1856 ASTContext &C = S.getASTContext();
1857 Expr *Init = AsExpression ? CaptureExpr : CaptureExpr->IgnoreImpCasts();
1858 QualType Ty = Init->getType();
1859 if (CaptureExpr->getObjectKind() == OK_Ordinary && CaptureExpr->isGLValue()) {
1860 if (S.getLangOpts().CPlusPlus)
1861 Ty = C.getLValueReferenceType(Ty);
1863 Ty = C.getPointerType(Ty);
1865 S.CreateBuiltinUnaryOp(CaptureExpr->getExprLoc(), UO_AddrOf, Init);
1866 if (!Res.isUsable())
1872 auto *CED = OMPCapturedExprDecl::Create(C, S.CurContext, Id, Ty,
1873 CaptureExpr->getLocStart());
1875 CED->addAttr(OMPCaptureNoInitAttr::CreateImplicit(C, SourceRange()));
1876 S.CurContext->addHiddenDecl(CED);
1877 S.AddInitializerToDecl(CED, Init, /*DirectInit=*/false);
1881 static DeclRefExpr *buildCapture(Sema &S, ValueDecl *D, Expr *CaptureExpr,
1883 OMPCapturedExprDecl *CD;
1884 if (auto *VD = S.IsOpenMPCapturedDecl(D))
1885 CD = cast<OMPCapturedExprDecl>(VD);
1887 CD = buildCaptureDecl(S, D->getIdentifier(), CaptureExpr, WithInit,
1888 /*AsExpression=*/false);
1889 return buildDeclRefExpr(S, CD, CD->getType().getNonReferenceType(),
1890 CaptureExpr->getExprLoc());
1893 static ExprResult buildCapture(Sema &S, Expr *CaptureExpr, DeclRefExpr *&Ref) {
1896 buildCaptureDecl(S, &S.getASTContext().Idents.get(".capture_expr."),
1897 CaptureExpr, /*WithInit=*/true, /*AsExpression=*/true);
1898 Ref = buildDeclRefExpr(S, CD, CD->getType().getNonReferenceType(),
1899 CaptureExpr->getExprLoc());
1901 ExprResult Res = Ref;
1902 if (!S.getLangOpts().CPlusPlus &&
1903 CaptureExpr->getObjectKind() == OK_Ordinary && CaptureExpr->isGLValue() &&
1904 Ref->getType()->isPointerType())
1905 Res = S.CreateBuiltinUnaryOp(CaptureExpr->getExprLoc(), UO_Deref, Ref);
1906 if (!Res.isUsable())
1908 return CaptureExpr->isGLValue() ? Res : S.DefaultLvalueConversion(Res.get());
1912 // OpenMP directives parsed in this section are represented as a
1913 // CapturedStatement with an associated statement. If a syntax error
1914 // is detected during the parsing of the associated statement, the
1915 // compiler must abort processing and close the CapturedStatement.
1917 // Combined directives such as 'target parallel' have more than one
1918 // nested CapturedStatements. This RAII ensures that we unwind out
1919 // of all the nested CapturedStatements when an error is found.
1920 class CaptureRegionUnwinderRAII {
1924 OpenMPDirectiveKind DKind;
1927 CaptureRegionUnwinderRAII(Sema &S, bool &ErrorFound,
1928 OpenMPDirectiveKind DKind)
1929 : S(S), ErrorFound(ErrorFound), DKind(DKind) {}
1930 ~CaptureRegionUnwinderRAII() {
1932 int ThisCaptureLevel = S.getOpenMPCaptureLevels(DKind);
1933 while (--ThisCaptureLevel >= 0)
1934 S.ActOnCapturedRegionError();
1940 StmtResult Sema::ActOnOpenMPRegionEnd(StmtResult S,
1941 ArrayRef<OMPClause *> Clauses) {
1942 bool ErrorFound = false;
1943 CaptureRegionUnwinderRAII CaptureRegionUnwinder(
1944 *this, ErrorFound, DSAStack->getCurrentDirective());
1945 if (!S.isUsable()) {
1950 OMPOrderedClause *OC = nullptr;
1951 OMPScheduleClause *SC = nullptr;
1952 SmallVector<OMPLinearClause *, 4> LCs;
1953 SmallVector<OMPClauseWithPreInit *, 8> PICs;
1954 // This is required for proper codegen.
1955 for (auto *Clause : Clauses) {
1956 if (isOpenMPPrivate(Clause->getClauseKind()) ||
1957 Clause->getClauseKind() == OMPC_copyprivate ||
1958 (getLangOpts().OpenMPUseTLS &&
1959 getASTContext().getTargetInfo().isTLSSupported() &&
1960 Clause->getClauseKind() == OMPC_copyin)) {
1961 DSAStack->setForceVarCapturing(Clause->getClauseKind() == OMPC_copyin);
1962 // Mark all variables in private list clauses as used in inner region.
1963 for (auto *VarRef : Clause->children()) {
1964 if (auto *E = cast_or_null<Expr>(VarRef)) {
1965 MarkDeclarationsReferencedInExpr(E);
1968 DSAStack->setForceVarCapturing(/*V=*/false);
1969 } else if (isParallelOrTaskRegion(DSAStack->getCurrentDirective())) {
1970 if (auto *C = OMPClauseWithPreInit::get(Clause))
1972 if (auto *C = OMPClauseWithPostUpdate::get(Clause)) {
1973 if (auto *E = C->getPostUpdateExpr())
1974 MarkDeclarationsReferencedInExpr(E);
1977 if (Clause->getClauseKind() == OMPC_schedule)
1978 SC = cast<OMPScheduleClause>(Clause);
1979 else if (Clause->getClauseKind() == OMPC_ordered)
1980 OC = cast<OMPOrderedClause>(Clause);
1981 else if (Clause->getClauseKind() == OMPC_linear)
1982 LCs.push_back(cast<OMPLinearClause>(Clause));
1984 // OpenMP, 2.7.1 Loop Construct, Restrictions
1985 // The nonmonotonic modifier cannot be specified if an ordered clause is
1988 (SC->getFirstScheduleModifier() == OMPC_SCHEDULE_MODIFIER_nonmonotonic ||
1989 SC->getSecondScheduleModifier() ==
1990 OMPC_SCHEDULE_MODIFIER_nonmonotonic) &&
1992 Diag(SC->getFirstScheduleModifier() == OMPC_SCHEDULE_MODIFIER_nonmonotonic
1993 ? SC->getFirstScheduleModifierLoc()
1994 : SC->getSecondScheduleModifierLoc(),
1995 diag::err_omp_schedule_nonmonotonic_ordered)
1996 << SourceRange(OC->getLocStart(), OC->getLocEnd());
1999 if (!LCs.empty() && OC && OC->getNumForLoops()) {
2000 for (auto *C : LCs) {
2001 Diag(C->getLocStart(), diag::err_omp_linear_ordered)
2002 << SourceRange(OC->getLocStart(), OC->getLocEnd());
2006 if (isOpenMPWorksharingDirective(DSAStack->getCurrentDirective()) &&
2007 isOpenMPSimdDirective(DSAStack->getCurrentDirective()) && OC &&
2008 OC->getNumForLoops()) {
2009 Diag(OC->getLocStart(), diag::err_omp_ordered_simd)
2010 << getOpenMPDirectiveName(DSAStack->getCurrentDirective());
2017 SmallVector<OpenMPDirectiveKind, 4> CaptureRegions;
2018 getOpenMPCaptureRegions(CaptureRegions, DSAStack->getCurrentDirective());
2019 for (auto ThisCaptureRegion : llvm::reverse(CaptureRegions)) {
2020 // Mark all variables in private list clauses as used in inner region.
2021 // Required for proper codegen of combined directives.
2022 // TODO: add processing for other clauses.
2023 if (isParallelOrTaskRegion(DSAStack->getCurrentDirective())) {
2024 for (auto *C : PICs) {
2025 OpenMPDirectiveKind CaptureRegion = C->getCaptureRegion();
2026 // Find the particular capture region for the clause if the
2027 // directive is a combined one with multiple capture regions.
2028 // If the directive is not a combined one, the capture region
2029 // associated with the clause is OMPD_unknown and is generated
2031 if (CaptureRegion == ThisCaptureRegion ||
2032 CaptureRegion == OMPD_unknown) {
2033 if (auto *DS = cast_or_null<DeclStmt>(C->getPreInitStmt())) {
2034 for (auto *D : DS->decls())
2035 MarkVariableReferenced(D->getLocation(), cast<VarDecl>(D));
2040 SR = ActOnCapturedRegionEnd(SR.get());
2045 static bool checkCancelRegion(Sema &SemaRef, OpenMPDirectiveKind CurrentRegion,
2046 OpenMPDirectiveKind CancelRegion,
2047 SourceLocation StartLoc) {
2048 // CancelRegion is only needed for cancel and cancellation_point.
2049 if (CurrentRegion != OMPD_cancel && CurrentRegion != OMPD_cancellation_point)
2052 if (CancelRegion == OMPD_parallel || CancelRegion == OMPD_for ||
2053 CancelRegion == OMPD_sections || CancelRegion == OMPD_taskgroup)
2056 SemaRef.Diag(StartLoc, diag::err_omp_wrong_cancel_region)
2057 << getOpenMPDirectiveName(CancelRegion);
2061 static bool checkNestingOfRegions(Sema &SemaRef, DSAStackTy *Stack,
2062 OpenMPDirectiveKind CurrentRegion,
2063 const DeclarationNameInfo &CurrentName,
2064 OpenMPDirectiveKind CancelRegion,
2065 SourceLocation StartLoc) {
2066 if (Stack->getCurScope()) {
2067 auto ParentRegion = Stack->getParentDirective();
2068 auto OffendingRegion = ParentRegion;
2069 bool NestingProhibited = false;
2070 bool CloseNesting = true;
2071 bool OrphanSeen = false;
2074 ShouldBeInParallelRegion,
2075 ShouldBeInOrderedRegion,
2076 ShouldBeInTargetRegion,
2077 ShouldBeInTeamsRegion
2078 } Recommend = NoRecommend;
2079 if (isOpenMPSimdDirective(ParentRegion) && CurrentRegion != OMPD_ordered) {
2080 // OpenMP [2.16, Nesting of Regions]
2081 // OpenMP constructs may not be nested inside a simd region.
2082 // OpenMP [2.8.1,simd Construct, Restrictions]
2083 // An ordered construct with the simd clause is the only OpenMP
2084 // construct that can appear in the simd region.
2085 // Allowing a SIMD construct nested in another SIMD construct is an
2086 // extension. The OpenMP 4.5 spec does not allow it. Issue a warning
2088 SemaRef.Diag(StartLoc, (CurrentRegion != OMPD_simd)
2089 ? diag::err_omp_prohibited_region_simd
2090 : diag::warn_omp_nesting_simd);
2091 return CurrentRegion != OMPD_simd;
2093 if (ParentRegion == OMPD_atomic) {
2094 // OpenMP [2.16, Nesting of Regions]
2095 // OpenMP constructs may not be nested inside an atomic region.
2096 SemaRef.Diag(StartLoc, diag::err_omp_prohibited_region_atomic);
2099 if (CurrentRegion == OMPD_section) {
2100 // OpenMP [2.7.2, sections Construct, Restrictions]
2101 // Orphaned section directives are prohibited. That is, the section
2102 // directives must appear within the sections construct and must not be
2103 // encountered elsewhere in the sections region.
2104 if (ParentRegion != OMPD_sections &&
2105 ParentRegion != OMPD_parallel_sections) {
2106 SemaRef.Diag(StartLoc, diag::err_omp_orphaned_section_directive)
2107 << (ParentRegion != OMPD_unknown)
2108 << getOpenMPDirectiveName(ParentRegion);
2113 // Allow some constructs (except teams) to be orphaned (they could be
2114 // used in functions, called from OpenMP regions with the required
2116 if (ParentRegion == OMPD_unknown &&
2117 !isOpenMPNestingTeamsDirective(CurrentRegion))
2119 if (CurrentRegion == OMPD_cancellation_point ||
2120 CurrentRegion == OMPD_cancel) {
2121 // OpenMP [2.16, Nesting of Regions]
2122 // A cancellation point construct for which construct-type-clause is
2123 // taskgroup must be nested inside a task construct. A cancellation
2124 // point construct for which construct-type-clause is not taskgroup must
2125 // be closely nested inside an OpenMP construct that matches the type
2126 // specified in construct-type-clause.
2127 // A cancel construct for which construct-type-clause is taskgroup must be
2128 // nested inside a task construct. A cancel construct for which
2129 // construct-type-clause is not taskgroup must be closely nested inside an
2130 // OpenMP construct that matches the type specified in
2131 // construct-type-clause.
2133 !((CancelRegion == OMPD_parallel &&
2134 (ParentRegion == OMPD_parallel ||
2135 ParentRegion == OMPD_target_parallel)) ||
2136 (CancelRegion == OMPD_for &&
2137 (ParentRegion == OMPD_for || ParentRegion == OMPD_parallel_for ||
2138 ParentRegion == OMPD_target_parallel_for)) ||
2139 (CancelRegion == OMPD_taskgroup && ParentRegion == OMPD_task) ||
2140 (CancelRegion == OMPD_sections &&
2141 (ParentRegion == OMPD_section || ParentRegion == OMPD_sections ||
2142 ParentRegion == OMPD_parallel_sections)));
2143 } else if (CurrentRegion == OMPD_master) {
2144 // OpenMP [2.16, Nesting of Regions]
2145 // A master region may not be closely nested inside a worksharing,
2146 // atomic, or explicit task region.
2147 NestingProhibited = isOpenMPWorksharingDirective(ParentRegion) ||
2148 isOpenMPTaskingDirective(ParentRegion);
2149 } else if (CurrentRegion == OMPD_critical && CurrentName.getName()) {
2150 // OpenMP [2.16, Nesting of Regions]
2151 // A critical region may not be nested (closely or otherwise) inside a
2152 // critical region with the same name. Note that this restriction is not
2153 // sufficient to prevent deadlock.
2154 SourceLocation PreviousCriticalLoc;
2155 bool DeadLock = Stack->hasDirective(
2156 [CurrentName, &PreviousCriticalLoc](OpenMPDirectiveKind K,
2157 const DeclarationNameInfo &DNI,
2158 SourceLocation Loc) -> bool {
2159 if (K == OMPD_critical && DNI.getName() == CurrentName.getName()) {
2160 PreviousCriticalLoc = Loc;
2165 false /* skip top directive */);
2167 SemaRef.Diag(StartLoc,
2168 diag::err_omp_prohibited_region_critical_same_name)
2169 << CurrentName.getName();
2170 if (PreviousCriticalLoc.isValid())
2171 SemaRef.Diag(PreviousCriticalLoc,
2172 diag::note_omp_previous_critical_region);
2175 } else if (CurrentRegion == OMPD_barrier) {
2176 // OpenMP [2.16, Nesting of Regions]
2177 // A barrier region may not be closely nested inside a worksharing,
2178 // explicit task, critical, ordered, atomic, or master region.
2179 NestingProhibited = isOpenMPWorksharingDirective(ParentRegion) ||
2180 isOpenMPTaskingDirective(ParentRegion) ||
2181 ParentRegion == OMPD_master ||
2182 ParentRegion == OMPD_critical ||
2183 ParentRegion == OMPD_ordered;
2184 } else if (isOpenMPWorksharingDirective(CurrentRegion) &&
2185 !isOpenMPParallelDirective(CurrentRegion) &&
2186 !isOpenMPTeamsDirective(CurrentRegion)) {
2187 // OpenMP [2.16, Nesting of Regions]
2188 // A worksharing region may not be closely nested inside a worksharing,
2189 // explicit task, critical, ordered, atomic, or master region.
2190 NestingProhibited = isOpenMPWorksharingDirective(ParentRegion) ||
2191 isOpenMPTaskingDirective(ParentRegion) ||
2192 ParentRegion == OMPD_master ||
2193 ParentRegion == OMPD_critical ||
2194 ParentRegion == OMPD_ordered;
2195 Recommend = ShouldBeInParallelRegion;
2196 } else if (CurrentRegion == OMPD_ordered) {
2197 // OpenMP [2.16, Nesting of Regions]
2198 // An ordered region may not be closely nested inside a critical,
2199 // atomic, or explicit task region.
2200 // An ordered region must be closely nested inside a loop region (or
2201 // parallel loop region) with an ordered clause.
2202 // OpenMP [2.8.1,simd Construct, Restrictions]
2203 // An ordered construct with the simd clause is the only OpenMP construct
2204 // that can appear in the simd region.
2205 NestingProhibited = ParentRegion == OMPD_critical ||
2206 isOpenMPTaskingDirective(ParentRegion) ||
2207 !(isOpenMPSimdDirective(ParentRegion) ||
2208 Stack->isParentOrderedRegion());
2209 Recommend = ShouldBeInOrderedRegion;
2210 } else if (isOpenMPNestingTeamsDirective(CurrentRegion)) {
2211 // OpenMP [2.16, Nesting of Regions]
2212 // If specified, a teams construct must be contained within a target
2214 NestingProhibited = ParentRegion != OMPD_target;
2215 OrphanSeen = ParentRegion == OMPD_unknown;
2216 Recommend = ShouldBeInTargetRegion;
2217 Stack->setParentTeamsRegionLoc(Stack->getConstructLoc());
2219 if (!NestingProhibited &&
2220 !isOpenMPTargetExecutionDirective(CurrentRegion) &&
2221 !isOpenMPTargetDataManagementDirective(CurrentRegion) &&
2222 (ParentRegion == OMPD_teams || ParentRegion == OMPD_target_teams)) {
2223 // OpenMP [2.16, Nesting of Regions]
2224 // distribute, parallel, parallel sections, parallel workshare, and the
2225 // parallel loop and parallel loop SIMD constructs are the only OpenMP
2226 // constructs that can be closely nested in the teams region.
2227 NestingProhibited = !isOpenMPParallelDirective(CurrentRegion) &&
2228 !isOpenMPDistributeDirective(CurrentRegion);
2229 Recommend = ShouldBeInParallelRegion;
2231 if (!NestingProhibited &&
2232 isOpenMPNestingDistributeDirective(CurrentRegion)) {
2233 // OpenMP 4.5 [2.17 Nesting of Regions]
2234 // The region associated with the distribute construct must be strictly
2235 // nested inside a teams region
2237 (ParentRegion != OMPD_teams && ParentRegion != OMPD_target_teams);
2238 Recommend = ShouldBeInTeamsRegion;
2240 if (!NestingProhibited &&
2241 (isOpenMPTargetExecutionDirective(CurrentRegion) ||
2242 isOpenMPTargetDataManagementDirective(CurrentRegion))) {
2243 // OpenMP 4.5 [2.17 Nesting of Regions]
2244 // If a target, target update, target data, target enter data, or
2245 // target exit data construct is encountered during execution of a
2246 // target region, the behavior is unspecified.
2247 NestingProhibited = Stack->hasDirective(
2248 [&OffendingRegion](OpenMPDirectiveKind K, const DeclarationNameInfo &,
2249 SourceLocation) -> bool {
2250 if (isOpenMPTargetExecutionDirective(K)) {
2251 OffendingRegion = K;
2256 false /* don't skip top directive */);
2257 CloseNesting = false;
2259 if (NestingProhibited) {
2261 SemaRef.Diag(StartLoc, diag::err_omp_orphaned_device_directive)
2262 << getOpenMPDirectiveName(CurrentRegion) << Recommend;
2264 SemaRef.Diag(StartLoc, diag::err_omp_prohibited_region)
2265 << CloseNesting << getOpenMPDirectiveName(OffendingRegion)
2266 << Recommend << getOpenMPDirectiveName(CurrentRegion);
2274 static bool checkIfClauses(Sema &S, OpenMPDirectiveKind Kind,
2275 ArrayRef<OMPClause *> Clauses,
2276 ArrayRef<OpenMPDirectiveKind> AllowedNameModifiers) {
2277 bool ErrorFound = false;
2278 unsigned NamedModifiersNumber = 0;
2279 SmallVector<const OMPIfClause *, OMPC_unknown + 1> FoundNameModifiers(
2281 SmallVector<SourceLocation, 4> NameModifierLoc;
2282 for (const auto *C : Clauses) {
2283 if (const auto *IC = dyn_cast_or_null<OMPIfClause>(C)) {
2284 // At most one if clause without a directive-name-modifier can appear on
2286 OpenMPDirectiveKind CurNM = IC->getNameModifier();
2287 if (FoundNameModifiers[CurNM]) {
2288 S.Diag(C->getLocStart(), diag::err_omp_more_one_clause)
2289 << getOpenMPDirectiveName(Kind) << getOpenMPClauseName(OMPC_if)
2290 << (CurNM != OMPD_unknown) << getOpenMPDirectiveName(CurNM);
2292 } else if (CurNM != OMPD_unknown) {
2293 NameModifierLoc.push_back(IC->getNameModifierLoc());
2294 ++NamedModifiersNumber;
2296 FoundNameModifiers[CurNM] = IC;
2297 if (CurNM == OMPD_unknown)
2299 // Check if the specified name modifier is allowed for the current
2301 // At most one if clause with the particular directive-name-modifier can
2302 // appear on the directive.
2303 bool MatchFound = false;
2304 for (auto NM : AllowedNameModifiers) {
2311 S.Diag(IC->getNameModifierLoc(),
2312 diag::err_omp_wrong_if_directive_name_modifier)
2313 << getOpenMPDirectiveName(CurNM) << getOpenMPDirectiveName(Kind);
2318 // If any if clause on the directive includes a directive-name-modifier then
2319 // all if clauses on the directive must include a directive-name-modifier.
2320 if (FoundNameModifiers[OMPD_unknown] && NamedModifiersNumber > 0) {
2321 if (NamedModifiersNumber == AllowedNameModifiers.size()) {
2322 S.Diag(FoundNameModifiers[OMPD_unknown]->getLocStart(),
2323 diag::err_omp_no_more_if_clause);
2326 std::string Sep(", ");
2327 unsigned AllowedCnt = 0;
2328 unsigned TotalAllowedNum =
2329 AllowedNameModifiers.size() - NamedModifiersNumber;
2330 for (unsigned Cnt = 0, End = AllowedNameModifiers.size(); Cnt < End;
2332 OpenMPDirectiveKind NM = AllowedNameModifiers[Cnt];
2333 if (!FoundNameModifiers[NM]) {
2335 Values += getOpenMPDirectiveName(NM);
2337 if (AllowedCnt + 2 == TotalAllowedNum)
2339 else if (AllowedCnt + 1 != TotalAllowedNum)
2344 S.Diag(FoundNameModifiers[OMPD_unknown]->getCondition()->getLocStart(),
2345 diag::err_omp_unnamed_if_clause)
2346 << (TotalAllowedNum > 1) << Values;
2348 for (auto Loc : NameModifierLoc) {
2349 S.Diag(Loc, diag::note_omp_previous_named_if_clause);
2356 StmtResult Sema::ActOnOpenMPExecutableDirective(
2357 OpenMPDirectiveKind Kind, const DeclarationNameInfo &DirName,
2358 OpenMPDirectiveKind CancelRegion, ArrayRef<OMPClause *> Clauses,
2359 Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc) {
2360 StmtResult Res = StmtError();
2361 // First check CancelRegion which is then used in checkNestingOfRegions.
2362 if (checkCancelRegion(*this, Kind, CancelRegion, StartLoc) ||
2363 checkNestingOfRegions(*this, DSAStack, Kind, DirName, CancelRegion,
2367 llvm::SmallVector<OMPClause *, 8> ClausesWithImplicit;
2368 llvm::DenseMap<ValueDecl *, Expr *> VarsWithInheritedDSA;
2369 bool ErrorFound = false;
2370 ClausesWithImplicit.append(Clauses.begin(), Clauses.end());
2372 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
2374 // Check default data sharing attributes for referenced variables.
2375 DSAAttrChecker DSAChecker(DSAStack, *this, cast<CapturedStmt>(AStmt));
2376 int ThisCaptureLevel = getOpenMPCaptureLevels(Kind);
2378 while (--ThisCaptureLevel >= 0)
2379 S = cast<CapturedStmt>(S)->getCapturedStmt();
2380 DSAChecker.Visit(S);
2381 if (DSAChecker.isErrorFound())
2383 // Generate list of implicitly defined firstprivate variables.
2384 VarsWithInheritedDSA = DSAChecker.getVarsWithInheritedDSA();
2386 if (!DSAChecker.getImplicitFirstprivate().empty()) {
2387 if (OMPClause *Implicit = ActOnOpenMPFirstprivateClause(
2388 DSAChecker.getImplicitFirstprivate(), SourceLocation(),
2389 SourceLocation(), SourceLocation())) {
2390 ClausesWithImplicit.push_back(Implicit);
2391 ErrorFound = cast<OMPFirstprivateClause>(Implicit)->varlist_size() !=
2392 DSAChecker.getImplicitFirstprivate().size();
2398 llvm::SmallVector<OpenMPDirectiveKind, 4> AllowedNameModifiers;
2401 Res = ActOnOpenMPParallelDirective(ClausesWithImplicit, AStmt, StartLoc,
2403 AllowedNameModifiers.push_back(OMPD_parallel);
2406 Res = ActOnOpenMPSimdDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc,
2407 VarsWithInheritedDSA);
2410 Res = ActOnOpenMPForDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc,
2411 VarsWithInheritedDSA);
2414 Res = ActOnOpenMPForSimdDirective(ClausesWithImplicit, AStmt, StartLoc,
2415 EndLoc, VarsWithInheritedDSA);
2418 Res = ActOnOpenMPSectionsDirective(ClausesWithImplicit, AStmt, StartLoc,
2422 assert(ClausesWithImplicit.empty() &&
2423 "No clauses are allowed for 'omp section' directive");
2424 Res = ActOnOpenMPSectionDirective(AStmt, StartLoc, EndLoc);
2427 Res = ActOnOpenMPSingleDirective(ClausesWithImplicit, AStmt, StartLoc,
2431 assert(ClausesWithImplicit.empty() &&
2432 "No clauses are allowed for 'omp master' directive");
2433 Res = ActOnOpenMPMasterDirective(AStmt, StartLoc, EndLoc);
2436 Res = ActOnOpenMPCriticalDirective(DirName, ClausesWithImplicit, AStmt,
2439 case OMPD_parallel_for:
2440 Res = ActOnOpenMPParallelForDirective(ClausesWithImplicit, AStmt, StartLoc,
2441 EndLoc, VarsWithInheritedDSA);
2442 AllowedNameModifiers.push_back(OMPD_parallel);
2444 case OMPD_parallel_for_simd:
2445 Res = ActOnOpenMPParallelForSimdDirective(
2446 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
2447 AllowedNameModifiers.push_back(OMPD_parallel);
2449 case OMPD_parallel_sections:
2450 Res = ActOnOpenMPParallelSectionsDirective(ClausesWithImplicit, AStmt,
2452 AllowedNameModifiers.push_back(OMPD_parallel);
2456 ActOnOpenMPTaskDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc);
2457 AllowedNameModifiers.push_back(OMPD_task);
2459 case OMPD_taskyield:
2460 assert(ClausesWithImplicit.empty() &&
2461 "No clauses are allowed for 'omp taskyield' directive");
2462 assert(AStmt == nullptr &&
2463 "No associated statement allowed for 'omp taskyield' directive");
2464 Res = ActOnOpenMPTaskyieldDirective(StartLoc, EndLoc);
2467 assert(ClausesWithImplicit.empty() &&
2468 "No clauses are allowed for 'omp barrier' directive");
2469 assert(AStmt == nullptr &&
2470 "No associated statement allowed for 'omp barrier' directive");
2471 Res = ActOnOpenMPBarrierDirective(StartLoc, EndLoc);
2474 assert(ClausesWithImplicit.empty() &&
2475 "No clauses are allowed for 'omp taskwait' directive");
2476 assert(AStmt == nullptr &&
2477 "No associated statement allowed for 'omp taskwait' directive");
2478 Res = ActOnOpenMPTaskwaitDirective(StartLoc, EndLoc);
2480 case OMPD_taskgroup:
2481 assert(ClausesWithImplicit.empty() &&
2482 "No clauses are allowed for 'omp taskgroup' directive");
2483 Res = ActOnOpenMPTaskgroupDirective(AStmt, StartLoc, EndLoc);
2486 assert(AStmt == nullptr &&
2487 "No associated statement allowed for 'omp flush' directive");
2488 Res = ActOnOpenMPFlushDirective(ClausesWithImplicit, StartLoc, EndLoc);
2491 Res = ActOnOpenMPOrderedDirective(ClausesWithImplicit, AStmt, StartLoc,
2495 Res = ActOnOpenMPAtomicDirective(ClausesWithImplicit, AStmt, StartLoc,
2500 ActOnOpenMPTeamsDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc);
2503 Res = ActOnOpenMPTargetDirective(ClausesWithImplicit, AStmt, StartLoc,
2505 AllowedNameModifiers.push_back(OMPD_target);
2507 case OMPD_target_parallel:
2508 Res = ActOnOpenMPTargetParallelDirective(ClausesWithImplicit, AStmt,
2510 AllowedNameModifiers.push_back(OMPD_target);
2511 AllowedNameModifiers.push_back(OMPD_parallel);
2513 case OMPD_target_parallel_for:
2514 Res = ActOnOpenMPTargetParallelForDirective(
2515 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
2516 AllowedNameModifiers.push_back(OMPD_target);
2517 AllowedNameModifiers.push_back(OMPD_parallel);
2519 case OMPD_cancellation_point:
2520 assert(ClausesWithImplicit.empty() &&
2521 "No clauses are allowed for 'omp cancellation point' directive");
2522 assert(AStmt == nullptr && "No associated statement allowed for 'omp "
2523 "cancellation point' directive");
2524 Res = ActOnOpenMPCancellationPointDirective(StartLoc, EndLoc, CancelRegion);
2527 assert(AStmt == nullptr &&
2528 "No associated statement allowed for 'omp cancel' directive");
2529 Res = ActOnOpenMPCancelDirective(ClausesWithImplicit, StartLoc, EndLoc,
2531 AllowedNameModifiers.push_back(OMPD_cancel);
2533 case OMPD_target_data:
2534 Res = ActOnOpenMPTargetDataDirective(ClausesWithImplicit, AStmt, StartLoc,
2536 AllowedNameModifiers.push_back(OMPD_target_data);
2538 case OMPD_target_enter_data:
2539 Res = ActOnOpenMPTargetEnterDataDirective(ClausesWithImplicit, StartLoc,
2541 AllowedNameModifiers.push_back(OMPD_target_enter_data);
2543 case OMPD_target_exit_data:
2544 Res = ActOnOpenMPTargetExitDataDirective(ClausesWithImplicit, StartLoc,
2546 AllowedNameModifiers.push_back(OMPD_target_exit_data);
2549 Res = ActOnOpenMPTaskLoopDirective(ClausesWithImplicit, AStmt, StartLoc,
2550 EndLoc, VarsWithInheritedDSA);
2551 AllowedNameModifiers.push_back(OMPD_taskloop);
2553 case OMPD_taskloop_simd:
2554 Res = ActOnOpenMPTaskLoopSimdDirective(ClausesWithImplicit, AStmt, StartLoc,
2555 EndLoc, VarsWithInheritedDSA);
2556 AllowedNameModifiers.push_back(OMPD_taskloop);
2558 case OMPD_distribute:
2559 Res = ActOnOpenMPDistributeDirective(ClausesWithImplicit, AStmt, StartLoc,
2560 EndLoc, VarsWithInheritedDSA);
2562 case OMPD_target_update:
2563 assert(!AStmt && "Statement is not allowed for target update");
2565 ActOnOpenMPTargetUpdateDirective(ClausesWithImplicit, StartLoc, EndLoc);
2566 AllowedNameModifiers.push_back(OMPD_target_update);
2568 case OMPD_distribute_parallel_for:
2569 Res = ActOnOpenMPDistributeParallelForDirective(
2570 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
2571 AllowedNameModifiers.push_back(OMPD_parallel);
2573 case OMPD_distribute_parallel_for_simd:
2574 Res = ActOnOpenMPDistributeParallelForSimdDirective(
2575 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
2576 AllowedNameModifiers.push_back(OMPD_parallel);
2578 case OMPD_distribute_simd:
2579 Res = ActOnOpenMPDistributeSimdDirective(
2580 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
2582 case OMPD_target_parallel_for_simd:
2583 Res = ActOnOpenMPTargetParallelForSimdDirective(
2584 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
2585 AllowedNameModifiers.push_back(OMPD_target);
2586 AllowedNameModifiers.push_back(OMPD_parallel);
2588 case OMPD_target_simd:
2589 Res = ActOnOpenMPTargetSimdDirective(ClausesWithImplicit, AStmt, StartLoc,
2590 EndLoc, VarsWithInheritedDSA);
2591 AllowedNameModifiers.push_back(OMPD_target);
2593 case OMPD_teams_distribute:
2594 Res = ActOnOpenMPTeamsDistributeDirective(
2595 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
2597 case OMPD_teams_distribute_simd:
2598 Res = ActOnOpenMPTeamsDistributeSimdDirective(
2599 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
2601 case OMPD_teams_distribute_parallel_for_simd:
2602 Res = ActOnOpenMPTeamsDistributeParallelForSimdDirective(
2603 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
2604 AllowedNameModifiers.push_back(OMPD_parallel);
2606 case OMPD_teams_distribute_parallel_for:
2607 Res = ActOnOpenMPTeamsDistributeParallelForDirective(
2608 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
2609 AllowedNameModifiers.push_back(OMPD_parallel);
2611 case OMPD_target_teams:
2612 Res = ActOnOpenMPTargetTeamsDirective(ClausesWithImplicit, AStmt, StartLoc,
2614 AllowedNameModifiers.push_back(OMPD_target);
2616 case OMPD_target_teams_distribute:
2617 Res = ActOnOpenMPTargetTeamsDistributeDirective(
2618 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
2619 AllowedNameModifiers.push_back(OMPD_target);
2621 case OMPD_target_teams_distribute_parallel_for:
2622 Res = ActOnOpenMPTargetTeamsDistributeParallelForDirective(
2623 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
2624 AllowedNameModifiers.push_back(OMPD_target);
2625 AllowedNameModifiers.push_back(OMPD_parallel);
2627 case OMPD_target_teams_distribute_parallel_for_simd:
2628 Res = ActOnOpenMPTargetTeamsDistributeParallelForSimdDirective(
2629 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
2630 AllowedNameModifiers.push_back(OMPD_target);
2631 AllowedNameModifiers.push_back(OMPD_parallel);
2633 case OMPD_target_teams_distribute_simd:
2634 Res = ActOnOpenMPTargetTeamsDistributeSimdDirective(
2635 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
2636 AllowedNameModifiers.push_back(OMPD_target);
2638 case OMPD_declare_target:
2639 case OMPD_end_declare_target:
2640 case OMPD_threadprivate:
2641 case OMPD_declare_reduction:
2642 case OMPD_declare_simd:
2643 llvm_unreachable("OpenMP Directive is not allowed");
2645 llvm_unreachable("Unknown OpenMP directive");
2648 for (auto P : VarsWithInheritedDSA) {
2649 Diag(P.second->getExprLoc(), diag::err_omp_no_dsa_for_variable)
2650 << P.first << P.second->getSourceRange();
2652 ErrorFound = !VarsWithInheritedDSA.empty() || ErrorFound;
2654 if (!AllowedNameModifiers.empty())
2655 ErrorFound = checkIfClauses(*this, Kind, Clauses, AllowedNameModifiers) ||
2663 Sema::DeclGroupPtrTy Sema::ActOnOpenMPDeclareSimdDirective(
2664 DeclGroupPtrTy DG, OMPDeclareSimdDeclAttr::BranchStateTy BS, Expr *Simdlen,
2665 ArrayRef<Expr *> Uniforms, ArrayRef<Expr *> Aligneds,
2666 ArrayRef<Expr *> Alignments, ArrayRef<Expr *> Linears,
2667 ArrayRef<unsigned> LinModifiers, ArrayRef<Expr *> Steps, SourceRange SR) {
2668 assert(Aligneds.size() == Alignments.size());
2669 assert(Linears.size() == LinModifiers.size());
2670 assert(Linears.size() == Steps.size());
2671 if (!DG || DG.get().isNull())
2672 return DeclGroupPtrTy();
2674 if (!DG.get().isSingleDecl()) {
2675 Diag(SR.getBegin(), diag::err_omp_single_decl_in_declare_simd);
2678 auto *ADecl = DG.get().getSingleDecl();
2679 if (auto *FTD = dyn_cast<FunctionTemplateDecl>(ADecl))
2680 ADecl = FTD->getTemplatedDecl();
2682 auto *FD = dyn_cast<FunctionDecl>(ADecl);
2684 Diag(ADecl->getLocation(), diag::err_omp_function_expected);
2685 return DeclGroupPtrTy();
2688 // OpenMP [2.8.2, declare simd construct, Description]
2689 // The parameter of the simdlen clause must be a constant positive integer
2693 SL = VerifyPositiveIntegerConstantInClause(Simdlen, OMPC_simdlen);
2694 // OpenMP [2.8.2, declare simd construct, Description]
2695 // The special this pointer can be used as if was one of the arguments to the
2696 // function in any of the linear, aligned, or uniform clauses.
2697 // The uniform clause declares one or more arguments to have an invariant
2698 // value for all concurrent invocations of the function in the execution of a
2699 // single SIMD loop.
2700 llvm::DenseMap<Decl *, Expr *> UniformedArgs;
2701 Expr *UniformedLinearThis = nullptr;
2702 for (auto *E : Uniforms) {
2703 E = E->IgnoreParenImpCasts();
2704 if (auto *DRE = dyn_cast<DeclRefExpr>(E))
2705 if (auto *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl()))
2706 if (FD->getNumParams() > PVD->getFunctionScopeIndex() &&
2707 FD->getParamDecl(PVD->getFunctionScopeIndex())
2708 ->getCanonicalDecl() == PVD->getCanonicalDecl()) {
2709 UniformedArgs.insert(std::make_pair(PVD->getCanonicalDecl(), E));
2712 if (isa<CXXThisExpr>(E)) {
2713 UniformedLinearThis = E;
2716 Diag(E->getExprLoc(), diag::err_omp_param_or_this_in_clause)
2717 << FD->getDeclName() << (isa<CXXMethodDecl>(ADecl) ? 1 : 0);
2719 // OpenMP [2.8.2, declare simd construct, Description]
2720 // The aligned clause declares that the object to which each list item points
2721 // is aligned to the number of bytes expressed in the optional parameter of
2722 // the aligned clause.
2723 // The special this pointer can be used as if was one of the arguments to the
2724 // function in any of the linear, aligned, or uniform clauses.
2725 // The type of list items appearing in the aligned clause must be array,
2726 // pointer, reference to array, or reference to pointer.
2727 llvm::DenseMap<Decl *, Expr *> AlignedArgs;
2728 Expr *AlignedThis = nullptr;
2729 for (auto *E : Aligneds) {
2730 E = E->IgnoreParenImpCasts();
2731 if (auto *DRE = dyn_cast<DeclRefExpr>(E))
2732 if (auto *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl())) {
2733 auto *CanonPVD = PVD->getCanonicalDecl();
2734 if (FD->getNumParams() > PVD->getFunctionScopeIndex() &&
2735 FD->getParamDecl(PVD->getFunctionScopeIndex())
2736 ->getCanonicalDecl() == CanonPVD) {
2737 // OpenMP [2.8.1, simd construct, Restrictions]
2738 // A list-item cannot appear in more than one aligned clause.
2739 if (AlignedArgs.count(CanonPVD) > 0) {
2740 Diag(E->getExprLoc(), diag::err_omp_aligned_twice)
2741 << 1 << E->getSourceRange();
2742 Diag(AlignedArgs[CanonPVD]->getExprLoc(),
2743 diag::note_omp_explicit_dsa)
2744 << getOpenMPClauseName(OMPC_aligned);
2747 AlignedArgs[CanonPVD] = E;
2748 QualType QTy = PVD->getType()
2749 .getNonReferenceType()
2750 .getUnqualifiedType()
2751 .getCanonicalType();
2752 const Type *Ty = QTy.getTypePtrOrNull();
2753 if (!Ty || (!Ty->isArrayType() && !Ty->isPointerType())) {
2754 Diag(E->getExprLoc(), diag::err_omp_aligned_expected_array_or_ptr)
2755 << QTy << getLangOpts().CPlusPlus << E->getSourceRange();
2756 Diag(PVD->getLocation(), diag::note_previous_decl) << PVD;
2761 if (isa<CXXThisExpr>(E)) {
2763 Diag(E->getExprLoc(), diag::err_omp_aligned_twice)
2764 << 2 << E->getSourceRange();
2765 Diag(AlignedThis->getExprLoc(), diag::note_omp_explicit_dsa)
2766 << getOpenMPClauseName(OMPC_aligned);
2771 Diag(E->getExprLoc(), diag::err_omp_param_or_this_in_clause)
2772 << FD->getDeclName() << (isa<CXXMethodDecl>(ADecl) ? 1 : 0);
2774 // The optional parameter of the aligned clause, alignment, must be a constant
2775 // positive integer expression. If no optional parameter is specified,
2776 // implementation-defined default alignments for SIMD instructions on the
2777 // target platforms are assumed.
2778 SmallVector<Expr *, 4> NewAligns;
2779 for (auto *E : Alignments) {
2782 Align = VerifyPositiveIntegerConstantInClause(E, OMPC_aligned);
2783 NewAligns.push_back(Align.get());
2785 // OpenMP [2.8.2, declare simd construct, Description]
2786 // The linear clause declares one or more list items to be private to a SIMD
2787 // lane and to have a linear relationship with respect to the iteration space
2789 // The special this pointer can be used as if was one of the arguments to the
2790 // function in any of the linear, aligned, or uniform clauses.
2791 // When a linear-step expression is specified in a linear clause it must be
2792 // either a constant integer expression or an integer-typed parameter that is
2793 // specified in a uniform clause on the directive.
2794 llvm::DenseMap<Decl *, Expr *> LinearArgs;
2795 const bool IsUniformedThis = UniformedLinearThis != nullptr;
2796 auto MI = LinModifiers.begin();
2797 for (auto *E : Linears) {
2798 auto LinKind = static_cast<OpenMPLinearClauseKind>(*MI);
2800 E = E->IgnoreParenImpCasts();
2801 if (auto *DRE = dyn_cast<DeclRefExpr>(E))
2802 if (auto *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl())) {
2803 auto *CanonPVD = PVD->getCanonicalDecl();
2804 if (FD->getNumParams() > PVD->getFunctionScopeIndex() &&
2805 FD->getParamDecl(PVD->getFunctionScopeIndex())
2806 ->getCanonicalDecl() == CanonPVD) {
2807 // OpenMP [2.15.3.7, linear Clause, Restrictions]
2808 // A list-item cannot appear in more than one linear clause.
2809 if (LinearArgs.count(CanonPVD) > 0) {
2810 Diag(E->getExprLoc(), diag::err_omp_wrong_dsa)
2811 << getOpenMPClauseName(OMPC_linear)
2812 << getOpenMPClauseName(OMPC_linear) << E->getSourceRange();
2813 Diag(LinearArgs[CanonPVD]->getExprLoc(),
2814 diag::note_omp_explicit_dsa)
2815 << getOpenMPClauseName(OMPC_linear);
2818 // Each argument can appear in at most one uniform or linear clause.
2819 if (UniformedArgs.count(CanonPVD) > 0) {
2820 Diag(E->getExprLoc(), diag::err_omp_wrong_dsa)
2821 << getOpenMPClauseName(OMPC_linear)
2822 << getOpenMPClauseName(OMPC_uniform) << E->getSourceRange();
2823 Diag(UniformedArgs[CanonPVD]->getExprLoc(),
2824 diag::note_omp_explicit_dsa)
2825 << getOpenMPClauseName(OMPC_uniform);
2828 LinearArgs[CanonPVD] = E;
2829 if (E->isValueDependent() || E->isTypeDependent() ||
2830 E->isInstantiationDependent() ||
2831 E->containsUnexpandedParameterPack())
2833 (void)CheckOpenMPLinearDecl(CanonPVD, E->getExprLoc(), LinKind,
2834 PVD->getOriginalType());
2838 if (isa<CXXThisExpr>(E)) {
2839 if (UniformedLinearThis) {
2840 Diag(E->getExprLoc(), diag::err_omp_wrong_dsa)
2841 << getOpenMPClauseName(OMPC_linear)
2842 << getOpenMPClauseName(IsUniformedThis ? OMPC_uniform : OMPC_linear)
2843 << E->getSourceRange();
2844 Diag(UniformedLinearThis->getExprLoc(), diag::note_omp_explicit_dsa)
2845 << getOpenMPClauseName(IsUniformedThis ? OMPC_uniform
2849 UniformedLinearThis = E;
2850 if (E->isValueDependent() || E->isTypeDependent() ||
2851 E->isInstantiationDependent() || E->containsUnexpandedParameterPack())
2853 (void)CheckOpenMPLinearDecl(/*D=*/nullptr, E->getExprLoc(), LinKind,
2857 Diag(E->getExprLoc(), diag::err_omp_param_or_this_in_clause)
2858 << FD->getDeclName() << (isa<CXXMethodDecl>(ADecl) ? 1 : 0);
2860 Expr *Step = nullptr;
2861 Expr *NewStep = nullptr;
2862 SmallVector<Expr *, 4> NewSteps;
2863 for (auto *E : Steps) {
2864 // Skip the same step expression, it was checked already.
2865 if (Step == E || !E) {
2866 NewSteps.push_back(E ? NewStep : nullptr);
2870 if (auto *DRE = dyn_cast<DeclRefExpr>(Step))
2871 if (auto *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl())) {
2872 auto *CanonPVD = PVD->getCanonicalDecl();
2873 if (UniformedArgs.count(CanonPVD) == 0) {
2874 Diag(Step->getExprLoc(), diag::err_omp_expected_uniform_param)
2875 << Step->getSourceRange();
2876 } else if (E->isValueDependent() || E->isTypeDependent() ||
2877 E->isInstantiationDependent() ||
2878 E->containsUnexpandedParameterPack() ||
2879 CanonPVD->getType()->hasIntegerRepresentation())
2880 NewSteps.push_back(Step);
2882 Diag(Step->getExprLoc(), diag::err_omp_expected_int_param)
2883 << Step->getSourceRange();
2888 if (Step && !Step->isValueDependent() && !Step->isTypeDependent() &&
2889 !Step->isInstantiationDependent() &&
2890 !Step->containsUnexpandedParameterPack()) {
2891 NewStep = PerformOpenMPImplicitIntegerConversion(Step->getExprLoc(), Step)
2894 NewStep = VerifyIntegerConstantExpression(NewStep).get();
2896 NewSteps.push_back(NewStep);
2898 auto *NewAttr = OMPDeclareSimdDeclAttr::CreateImplicit(
2899 Context, BS, SL.get(), const_cast<Expr **>(Uniforms.data()),
2900 Uniforms.size(), const_cast<Expr **>(Aligneds.data()), Aligneds.size(),
2901 const_cast<Expr **>(NewAligns.data()), NewAligns.size(),
2902 const_cast<Expr **>(Linears.data()), Linears.size(),
2903 const_cast<unsigned *>(LinModifiers.data()), LinModifiers.size(),
2904 NewSteps.data(), NewSteps.size(), SR);
2905 ADecl->addAttr(NewAttr);
2906 return ConvertDeclToDeclGroup(ADecl);
2909 StmtResult Sema::ActOnOpenMPParallelDirective(ArrayRef<OMPClause *> Clauses,
2911 SourceLocation StartLoc,
2912 SourceLocation EndLoc) {
2916 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
2917 // 1.2.2 OpenMP Language Terminology
2918 // Structured block - An executable statement with a single entry at the
2919 // top and a single exit at the bottom.
2920 // The point of exit cannot be a branch out of the structured block.
2921 // longjmp() and throw() must not violate the entry/exit criteria.
2922 CS->getCapturedDecl()->setNothrow();
2924 getCurFunction()->setHasBranchProtectedScope();
2926 return OMPParallelDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt,
2927 DSAStack->isCancelRegion());
2931 /// \brief Helper class for checking canonical form of the OpenMP loops and
2932 /// extracting iteration space of each loop in the loop nest, that will be used
2933 /// for IR generation.
2934 class OpenMPIterationSpaceChecker {
2935 /// \brief Reference to Sema.
2937 /// \brief A location for diagnostics (when there is no some better location).
2938 SourceLocation DefaultLoc;
2939 /// \brief A location for diagnostics (when increment is not compatible).
2940 SourceLocation ConditionLoc;
2941 /// \brief A source location for referring to loop init later.
2942 SourceRange InitSrcRange;
2943 /// \brief A source location for referring to condition later.
2944 SourceRange ConditionSrcRange;
2945 /// \brief A source location for referring to increment later.
2946 SourceRange IncrementSrcRange;
2947 /// \brief Loop variable.
2948 ValueDecl *LCDecl = nullptr;
2949 /// \brief Reference to loop variable.
2950 Expr *LCRef = nullptr;
2951 /// \brief Lower bound (initializer for the var).
2953 /// \brief Upper bound.
2955 /// \brief Loop step (increment).
2956 Expr *Step = nullptr;
2957 /// \brief This flag is true when condition is one of:
2962 bool TestIsLessOp = false;
2963 /// \brief This flag is true when condition is strict ( < or > ).
2964 bool TestIsStrictOp = false;
2965 /// \brief This flag is true when step is subtracted on each iteration.
2966 bool SubtractStep = false;
2969 OpenMPIterationSpaceChecker(Sema &SemaRef, SourceLocation DefaultLoc)
2970 : SemaRef(SemaRef), DefaultLoc(DefaultLoc), ConditionLoc(DefaultLoc) {}
2971 /// \brief Check init-expr for canonical loop form and save loop counter
2972 /// variable - #Var and its initialization value - #LB.
2973 bool CheckInit(Stmt *S, bool EmitDiags = true);
2974 /// \brief Check test-expr for canonical form, save upper-bound (#UB), flags
2975 /// for less/greater and for strict/non-strict comparison.
2976 bool CheckCond(Expr *S);
2977 /// \brief Check incr-expr for canonical loop form and return true if it
2978 /// does not conform, otherwise save loop step (#Step).
2979 bool CheckInc(Expr *S);
2980 /// \brief Return the loop counter variable.
2981 ValueDecl *GetLoopDecl() const { return LCDecl; }
2982 /// \brief Return the reference expression to loop counter variable.
2983 Expr *GetLoopDeclRefExpr() const { return LCRef; }
2984 /// \brief Source range of the loop init.
2985 SourceRange GetInitSrcRange() const { return InitSrcRange; }
2986 /// \brief Source range of the loop condition.
2987 SourceRange GetConditionSrcRange() const { return ConditionSrcRange; }
2988 /// \brief Source range of the loop increment.
2989 SourceRange GetIncrementSrcRange() const { return IncrementSrcRange; }
2990 /// \brief True if the step should be subtracted.
2991 bool ShouldSubtractStep() const { return SubtractStep; }
2992 /// \brief Build the expression to calculate the number of iterations.
2994 BuildNumIterations(Scope *S, const bool LimitedType,
2995 llvm::MapVector<Expr *, DeclRefExpr *> &Captures) const;
2996 /// \brief Build the precondition expression for the loops.
2997 Expr *BuildPreCond(Scope *S, Expr *Cond,
2998 llvm::MapVector<Expr *, DeclRefExpr *> &Captures) const;
2999 /// \brief Build reference expression to the counter be used for codegen.
3000 DeclRefExpr *BuildCounterVar(llvm::MapVector<Expr *, DeclRefExpr *> &Captures,
3001 DSAStackTy &DSA) const;
3002 /// \brief Build reference expression to the private counter be used for
3004 Expr *BuildPrivateCounterVar() const;
3005 /// \brief Build initialization of the counter be used for codegen.
3006 Expr *BuildCounterInit() const;
3007 /// \brief Build step of the counter be used for codegen.
3008 Expr *BuildCounterStep() const;
3009 /// \brief Return true if any expression is dependent.
3010 bool Dependent() const;
3013 /// \brief Check the right-hand side of an assignment in the increment
3015 bool CheckIncRHS(Expr *RHS);
3016 /// \brief Helper to set loop counter variable and its initializer.
3017 bool SetLCDeclAndLB(ValueDecl *NewLCDecl, Expr *NewDeclRefExpr, Expr *NewLB);
3018 /// \brief Helper to set upper bound.
3019 bool SetUB(Expr *NewUB, bool LessOp, bool StrictOp, SourceRange SR,
3021 /// \brief Helper to set loop increment.
3022 bool SetStep(Expr *NewStep, bool Subtract);
3025 bool OpenMPIterationSpaceChecker::Dependent() const {
3027 assert(!LB && !UB && !Step);
3030 return LCDecl->getType()->isDependentType() ||
3031 (LB && LB->isValueDependent()) || (UB && UB->isValueDependent()) ||
3032 (Step && Step->isValueDependent());
3035 static Expr *getExprAsWritten(Expr *E) {
3036 if (auto *ExprTemp = dyn_cast<ExprWithCleanups>(E))
3037 E = ExprTemp->getSubExpr();
3039 if (auto *MTE = dyn_cast<MaterializeTemporaryExpr>(E))
3040 E = MTE->GetTemporaryExpr();
3042 while (auto *Binder = dyn_cast<CXXBindTemporaryExpr>(E))
3043 E = Binder->getSubExpr();
3045 if (auto *ICE = dyn_cast<ImplicitCastExpr>(E))
3046 E = ICE->getSubExprAsWritten();
3047 return E->IgnoreParens();
3050 bool OpenMPIterationSpaceChecker::SetLCDeclAndLB(ValueDecl *NewLCDecl,
3053 // State consistency checking to ensure correct usage.
3054 assert(LCDecl == nullptr && LB == nullptr && LCRef == nullptr &&
3055 UB == nullptr && Step == nullptr && !TestIsLessOp && !TestIsStrictOp);
3056 if (!NewLCDecl || !NewLB)
3058 LCDecl = getCanonicalDecl(NewLCDecl);
3059 LCRef = NewLCRefExpr;
3060 if (auto *CE = dyn_cast_or_null<CXXConstructExpr>(NewLB))
3061 if (const CXXConstructorDecl *Ctor = CE->getConstructor())
3062 if ((Ctor->isCopyOrMoveConstructor() ||
3063 Ctor->isConvertingConstructor(/*AllowExplicit=*/false)) &&
3064 CE->getNumArgs() > 0 && CE->getArg(0) != nullptr)
3065 NewLB = CE->getArg(0)->IgnoreParenImpCasts();
3070 bool OpenMPIterationSpaceChecker::SetUB(Expr *NewUB, bool LessOp, bool StrictOp,
3071 SourceRange SR, SourceLocation SL) {
3072 // State consistency checking to ensure correct usage.
3073 assert(LCDecl != nullptr && LB != nullptr && UB == nullptr &&
3074 Step == nullptr && !TestIsLessOp && !TestIsStrictOp);
3078 TestIsLessOp = LessOp;
3079 TestIsStrictOp = StrictOp;
3080 ConditionSrcRange = SR;
3085 bool OpenMPIterationSpaceChecker::SetStep(Expr *NewStep, bool Subtract) {
3086 // State consistency checking to ensure correct usage.
3087 assert(LCDecl != nullptr && LB != nullptr && Step == nullptr);
3090 if (!NewStep->isValueDependent()) {
3091 // Check that the step is integer expression.
3092 SourceLocation StepLoc = NewStep->getLocStart();
3094 SemaRef.PerformOpenMPImplicitIntegerConversion(StepLoc, NewStep);
3095 if (Val.isInvalid())
3097 NewStep = Val.get();
3099 // OpenMP [2.6, Canonical Loop Form, Restrictions]
3100 // If test-expr is of form var relational-op b and relational-op is < or
3101 // <= then incr-expr must cause var to increase on each iteration of the
3102 // loop. If test-expr is of form var relational-op b and relational-op is
3103 // > or >= then incr-expr must cause var to decrease on each iteration of
3105 // If test-expr is of form b relational-op var and relational-op is < or
3106 // <= then incr-expr must cause var to decrease on each iteration of the
3107 // loop. If test-expr is of form b relational-op var and relational-op is
3108 // > or >= then incr-expr must cause var to increase on each iteration of
3110 llvm::APSInt Result;
3111 bool IsConstant = NewStep->isIntegerConstantExpr(Result, SemaRef.Context);
3112 bool IsUnsigned = !NewStep->getType()->hasSignedIntegerRepresentation();
3114 IsConstant && Result.isSigned() && (Subtract != Result.isNegative());
3116 IsConstant && Result.isSigned() && (Subtract == Result.isNegative());
3117 bool IsConstZero = IsConstant && !Result.getBoolValue();
3118 if (UB && (IsConstZero ||
3119 (TestIsLessOp ? (IsConstNeg || (IsUnsigned && Subtract))
3120 : (IsConstPos || (IsUnsigned && !Subtract))))) {
3121 SemaRef.Diag(NewStep->getExprLoc(),
3122 diag::err_omp_loop_incr_not_compatible)
3123 << LCDecl << TestIsLessOp << NewStep->getSourceRange();
3124 SemaRef.Diag(ConditionLoc,
3125 diag::note_omp_loop_cond_requres_compatible_incr)
3126 << TestIsLessOp << ConditionSrcRange;
3129 if (TestIsLessOp == Subtract) {
3131 SemaRef.CreateBuiltinUnaryOp(NewStep->getExprLoc(), UO_Minus, NewStep)
3133 Subtract = !Subtract;
3138 SubtractStep = Subtract;
3142 bool OpenMPIterationSpaceChecker::CheckInit(Stmt *S, bool EmitDiags) {
3143 // Check init-expr for canonical loop form and save loop counter
3144 // variable - #Var and its initialization value - #LB.
3145 // OpenMP [2.6] Canonical loop form. init-expr may be one of the following:
3147 // integer-type var = lb
3148 // random-access-iterator-type var = lb
3149 // pointer-type var = lb
3153 SemaRef.Diag(DefaultLoc, diag::err_omp_loop_not_canonical_init);
3157 if (auto *ExprTemp = dyn_cast<ExprWithCleanups>(S))
3158 if (!ExprTemp->cleanupsHaveSideEffects())
3159 S = ExprTemp->getSubExpr();
3161 InitSrcRange = S->getSourceRange();
3162 if (Expr *E = dyn_cast<Expr>(S))
3163 S = E->IgnoreParens();
3164 if (auto *BO = dyn_cast<BinaryOperator>(S)) {
3165 if (BO->getOpcode() == BO_Assign) {
3166 auto *LHS = BO->getLHS()->IgnoreParens();
3167 if (auto *DRE = dyn_cast<DeclRefExpr>(LHS)) {
3168 if (auto *CED = dyn_cast<OMPCapturedExprDecl>(DRE->getDecl()))
3169 if (auto *ME = dyn_cast<MemberExpr>(getExprAsWritten(CED->getInit())))
3170 return SetLCDeclAndLB(ME->getMemberDecl(), ME, BO->getRHS());
3171 return SetLCDeclAndLB(DRE->getDecl(), DRE, BO->getRHS());
3173 if (auto *ME = dyn_cast<MemberExpr>(LHS)) {
3174 if (ME->isArrow() &&
3175 isa<CXXThisExpr>(ME->getBase()->IgnoreParenImpCasts()))
3176 return SetLCDeclAndLB(ME->getMemberDecl(), ME, BO->getRHS());
3179 } else if (auto *DS = dyn_cast<DeclStmt>(S)) {
3180 if (DS->isSingleDecl()) {
3181 if (auto *Var = dyn_cast_or_null<VarDecl>(DS->getSingleDecl())) {
3182 if (Var->hasInit() && !Var->getType()->isReferenceType()) {
3183 // Accept non-canonical init form here but emit ext. warning.
3184 if (Var->getInitStyle() != VarDecl::CInit && EmitDiags)
3185 SemaRef.Diag(S->getLocStart(),
3186 diag::ext_omp_loop_not_canonical_init)
3187 << S->getSourceRange();
3188 return SetLCDeclAndLB(Var, nullptr, Var->getInit());
3192 } else if (auto *CE = dyn_cast<CXXOperatorCallExpr>(S)) {
3193 if (CE->getOperator() == OO_Equal) {
3194 auto *LHS = CE->getArg(0);
3195 if (auto *DRE = dyn_cast<DeclRefExpr>(LHS)) {
3196 if (auto *CED = dyn_cast<OMPCapturedExprDecl>(DRE->getDecl()))
3197 if (auto *ME = dyn_cast<MemberExpr>(getExprAsWritten(CED->getInit())))
3198 return SetLCDeclAndLB(ME->getMemberDecl(), ME, BO->getRHS());
3199 return SetLCDeclAndLB(DRE->getDecl(), DRE, CE->getArg(1));
3201 if (auto *ME = dyn_cast<MemberExpr>(LHS)) {
3202 if (ME->isArrow() &&
3203 isa<CXXThisExpr>(ME->getBase()->IgnoreParenImpCasts()))
3204 return SetLCDeclAndLB(ME->getMemberDecl(), ME, BO->getRHS());
3209 if (Dependent() || SemaRef.CurContext->isDependentContext())
3212 SemaRef.Diag(S->getLocStart(), diag::err_omp_loop_not_canonical_init)
3213 << S->getSourceRange();
3218 /// \brief Ignore parenthesizes, implicit casts, copy constructor and return the
3219 /// variable (which may be the loop variable) if possible.
3220 static const ValueDecl *GetInitLCDecl(Expr *E) {
3223 E = getExprAsWritten(E);
3224 if (auto *CE = dyn_cast_or_null<CXXConstructExpr>(E))
3225 if (const CXXConstructorDecl *Ctor = CE->getConstructor())
3226 if ((Ctor->isCopyOrMoveConstructor() ||
3227 Ctor->isConvertingConstructor(/*AllowExplicit=*/false)) &&
3228 CE->getNumArgs() > 0 && CE->getArg(0) != nullptr)
3229 E = CE->getArg(0)->IgnoreParenImpCasts();
3230 if (auto *DRE = dyn_cast_or_null<DeclRefExpr>(E)) {
3231 if (auto *VD = dyn_cast<VarDecl>(DRE->getDecl())) {
3232 if (auto *CED = dyn_cast<OMPCapturedExprDecl>(VD))
3233 if (auto *ME = dyn_cast<MemberExpr>(getExprAsWritten(CED->getInit())))
3234 return getCanonicalDecl(ME->getMemberDecl());
3235 return getCanonicalDecl(VD);
3238 if (auto *ME = dyn_cast_or_null<MemberExpr>(E))
3239 if (ME->isArrow() && isa<CXXThisExpr>(ME->getBase()->IgnoreParenImpCasts()))
3240 return getCanonicalDecl(ME->getMemberDecl());
3244 bool OpenMPIterationSpaceChecker::CheckCond(Expr *S) {
3245 // Check test-expr for canonical form, save upper-bound UB, flags for
3246 // less/greater and for strict/non-strict comparison.
3247 // OpenMP [2.6] Canonical loop form. Test-expr may be one of the following:
3248 // var relational-op b
3249 // b relational-op var
3252 SemaRef.Diag(DefaultLoc, diag::err_omp_loop_not_canonical_cond) << LCDecl;
3255 S = getExprAsWritten(S);
3256 SourceLocation CondLoc = S->getLocStart();
3257 if (auto *BO = dyn_cast<BinaryOperator>(S)) {
3258 if (BO->isRelationalOp()) {
3259 if (GetInitLCDecl(BO->getLHS()) == LCDecl)
3260 return SetUB(BO->getRHS(),
3261 (BO->getOpcode() == BO_LT || BO->getOpcode() == BO_LE),
3262 (BO->getOpcode() == BO_LT || BO->getOpcode() == BO_GT),
3263 BO->getSourceRange(), BO->getOperatorLoc());
3264 if (GetInitLCDecl(BO->getRHS()) == LCDecl)
3265 return SetUB(BO->getLHS(),
3266 (BO->getOpcode() == BO_GT || BO->getOpcode() == BO_GE),
3267 (BO->getOpcode() == BO_LT || BO->getOpcode() == BO_GT),
3268 BO->getSourceRange(), BO->getOperatorLoc());
3270 } else if (auto *CE = dyn_cast<CXXOperatorCallExpr>(S)) {
3271 if (CE->getNumArgs() == 2) {
3272 auto Op = CE->getOperator();
3275 case OO_GreaterEqual:
3278 if (GetInitLCDecl(CE->getArg(0)) == LCDecl)
3279 return SetUB(CE->getArg(1), Op == OO_Less || Op == OO_LessEqual,
3280 Op == OO_Less || Op == OO_Greater, CE->getSourceRange(),
3281 CE->getOperatorLoc());
3282 if (GetInitLCDecl(CE->getArg(1)) == LCDecl)
3283 return SetUB(CE->getArg(0), Op == OO_Greater || Op == OO_GreaterEqual,
3284 Op == OO_Less || Op == OO_Greater, CE->getSourceRange(),
3285 CE->getOperatorLoc());
3292 if (Dependent() || SemaRef.CurContext->isDependentContext())
3294 SemaRef.Diag(CondLoc, diag::err_omp_loop_not_canonical_cond)
3295 << S->getSourceRange() << LCDecl;
3299 bool OpenMPIterationSpaceChecker::CheckIncRHS(Expr *RHS) {
3300 // RHS of canonical loop form increment can be:
3305 RHS = RHS->IgnoreParenImpCasts();
3306 if (auto *BO = dyn_cast<BinaryOperator>(RHS)) {
3307 if (BO->isAdditiveOp()) {
3308 bool IsAdd = BO->getOpcode() == BO_Add;
3309 if (GetInitLCDecl(BO->getLHS()) == LCDecl)
3310 return SetStep(BO->getRHS(), !IsAdd);
3311 if (IsAdd && GetInitLCDecl(BO->getRHS()) == LCDecl)
3312 return SetStep(BO->getLHS(), false);
3314 } else if (auto *CE = dyn_cast<CXXOperatorCallExpr>(RHS)) {
3315 bool IsAdd = CE->getOperator() == OO_Plus;
3316 if ((IsAdd || CE->getOperator() == OO_Minus) && CE->getNumArgs() == 2) {
3317 if (GetInitLCDecl(CE->getArg(0)) == LCDecl)
3318 return SetStep(CE->getArg(1), !IsAdd);
3319 if (IsAdd && GetInitLCDecl(CE->getArg(1)) == LCDecl)
3320 return SetStep(CE->getArg(0), false);
3323 if (Dependent() || SemaRef.CurContext->isDependentContext())
3325 SemaRef.Diag(RHS->getLocStart(), diag::err_omp_loop_not_canonical_incr)
3326 << RHS->getSourceRange() << LCDecl;
3330 bool OpenMPIterationSpaceChecker::CheckInc(Expr *S) {
3331 // Check incr-expr for canonical loop form and return true if it
3332 // does not conform.
3333 // OpenMP [2.6] Canonical loop form. Test-expr may be one of the following:
3345 SemaRef.Diag(DefaultLoc, diag::err_omp_loop_not_canonical_incr) << LCDecl;
3348 if (auto *ExprTemp = dyn_cast<ExprWithCleanups>(S))
3349 if (!ExprTemp->cleanupsHaveSideEffects())
3350 S = ExprTemp->getSubExpr();
3352 IncrementSrcRange = S->getSourceRange();
3353 S = S->IgnoreParens();
3354 if (auto *UO = dyn_cast<UnaryOperator>(S)) {
3355 if (UO->isIncrementDecrementOp() &&
3356 GetInitLCDecl(UO->getSubExpr()) == LCDecl)
3357 return SetStep(SemaRef
3358 .ActOnIntegerConstant(UO->getLocStart(),
3359 (UO->isDecrementOp() ? -1 : 1))
3362 } else if (auto *BO = dyn_cast<BinaryOperator>(S)) {
3363 switch (BO->getOpcode()) {
3366 if (GetInitLCDecl(BO->getLHS()) == LCDecl)
3367 return SetStep(BO->getRHS(), BO->getOpcode() == BO_SubAssign);
3370 if (GetInitLCDecl(BO->getLHS()) == LCDecl)
3371 return CheckIncRHS(BO->getRHS());
3376 } else if (auto *CE = dyn_cast<CXXOperatorCallExpr>(S)) {
3377 switch (CE->getOperator()) {
3380 if (GetInitLCDecl(CE->getArg(0)) == LCDecl)
3381 return SetStep(SemaRef
3382 .ActOnIntegerConstant(
3384 ((CE->getOperator() == OO_MinusMinus) ? -1 : 1))
3390 if (GetInitLCDecl(CE->getArg(0)) == LCDecl)
3391 return SetStep(CE->getArg(1), CE->getOperator() == OO_MinusEqual);
3394 if (GetInitLCDecl(CE->getArg(0)) == LCDecl)
3395 return CheckIncRHS(CE->getArg(1));
3401 if (Dependent() || SemaRef.CurContext->isDependentContext())
3403 SemaRef.Diag(S->getLocStart(), diag::err_omp_loop_not_canonical_incr)
3404 << S->getSourceRange() << LCDecl;
3409 tryBuildCapture(Sema &SemaRef, Expr *Capture,
3410 llvm::MapVector<Expr *, DeclRefExpr *> &Captures) {
3411 if (SemaRef.CurContext->isDependentContext())
3412 return ExprResult(Capture);
3413 if (Capture->isEvaluatable(SemaRef.Context, Expr::SE_AllowSideEffects))
3414 return SemaRef.PerformImplicitConversion(
3415 Capture->IgnoreImpCasts(), Capture->getType(), Sema::AA_Converting,
3416 /*AllowExplicit=*/true);
3417 auto I = Captures.find(Capture);
3418 if (I != Captures.end())
3419 return buildCapture(SemaRef, Capture, I->second);
3420 DeclRefExpr *Ref = nullptr;
3421 ExprResult Res = buildCapture(SemaRef, Capture, Ref);
3422 Captures[Capture] = Ref;
3426 /// \brief Build the expression to calculate the number of iterations.
3427 Expr *OpenMPIterationSpaceChecker::BuildNumIterations(
3428 Scope *S, const bool LimitedType,
3429 llvm::MapVector<Expr *, DeclRefExpr *> &Captures) const {
3431 auto VarType = LCDecl->getType().getNonReferenceType();
3432 if (VarType->isIntegerType() || VarType->isPointerType() ||
3433 SemaRef.getLangOpts().CPlusPlus) {
3435 auto *UBExpr = TestIsLessOp ? UB : LB;
3436 auto *LBExpr = TestIsLessOp ? LB : UB;
3437 Expr *Upper = tryBuildCapture(SemaRef, UBExpr, Captures).get();
3438 Expr *Lower = tryBuildCapture(SemaRef, LBExpr, Captures).get();
3439 if (!Upper || !Lower)
3442 Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Sub, Upper, Lower);
3444 if (!Diff.isUsable() && VarType->getAsCXXRecordDecl()) {
3445 // BuildBinOp already emitted error, this one is to point user to upper
3446 // and lower bound, and to tell what is passed to 'operator-'.
3447 SemaRef.Diag(Upper->getLocStart(), diag::err_omp_loop_diff_cxx)
3448 << Upper->getSourceRange() << Lower->getSourceRange();
3453 if (!Diff.isUsable())
3456 // Upper - Lower [- 1]
3458 Diff = SemaRef.BuildBinOp(
3459 S, DefaultLoc, BO_Sub, Diff.get(),
3460 SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get());
3461 if (!Diff.isUsable())
3464 // Upper - Lower [- 1] + Step
3465 auto NewStep = tryBuildCapture(SemaRef, Step, Captures);
3466 if (!NewStep.isUsable())
3468 Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Add, Diff.get(), NewStep.get());
3469 if (!Diff.isUsable())
3472 // Parentheses (for dumping/debugging purposes only).
3473 Diff = SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, Diff.get());
3474 if (!Diff.isUsable())
3477 // (Upper - Lower [- 1] + Step) / Step
3478 Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Div, Diff.get(), NewStep.get());
3479 if (!Diff.isUsable())
3482 // OpenMP runtime requires 32-bit or 64-bit loop variables.
3483 QualType Type = Diff.get()->getType();
3484 auto &C = SemaRef.Context;
3485 bool UseVarType = VarType->hasIntegerRepresentation() &&
3486 C.getTypeSize(Type) > C.getTypeSize(VarType);
3487 if (!Type->isIntegerType() || UseVarType) {
3489 UseVarType ? C.getTypeSize(VarType) : C.getTypeSize(Type);
3490 bool IsSigned = UseVarType ? VarType->hasSignedIntegerRepresentation()
3491 : Type->hasSignedIntegerRepresentation();
3492 Type = C.getIntTypeForBitwidth(NewSize, IsSigned);
3493 if (!SemaRef.Context.hasSameType(Diff.get()->getType(), Type)) {
3494 Diff = SemaRef.PerformImplicitConversion(
3495 Diff.get(), Type, Sema::AA_Converting, /*AllowExplicit=*/true);
3496 if (!Diff.isUsable())
3501 unsigned NewSize = (C.getTypeSize(Type) > 32) ? 64 : 32;
3502 if (NewSize != C.getTypeSize(Type)) {
3503 if (NewSize < C.getTypeSize(Type)) {
3504 assert(NewSize == 64 && "incorrect loop var size");
3505 SemaRef.Diag(DefaultLoc, diag::warn_omp_loop_64_bit_var)
3506 << InitSrcRange << ConditionSrcRange;
3508 QualType NewType = C.getIntTypeForBitwidth(
3509 NewSize, Type->hasSignedIntegerRepresentation() ||
3510 C.getTypeSize(Type) < NewSize);
3511 if (!SemaRef.Context.hasSameType(Diff.get()->getType(), NewType)) {
3512 Diff = SemaRef.PerformImplicitConversion(Diff.get(), NewType,
3513 Sema::AA_Converting, true);
3514 if (!Diff.isUsable())
3523 Expr *OpenMPIterationSpaceChecker::BuildPreCond(
3524 Scope *S, Expr *Cond,
3525 llvm::MapVector<Expr *, DeclRefExpr *> &Captures) const {
3526 // Try to build LB <op> UB, where <op> is <, >, <=, or >=.
3527 bool Suppress = SemaRef.getDiagnostics().getSuppressAllDiagnostics();
3528 SemaRef.getDiagnostics().setSuppressAllDiagnostics(/*Val=*/true);
3530 auto NewLB = tryBuildCapture(SemaRef, LB, Captures);
3531 auto NewUB = tryBuildCapture(SemaRef, UB, Captures);
3532 if (!NewLB.isUsable() || !NewUB.isUsable())
3535 auto CondExpr = SemaRef.BuildBinOp(
3536 S, DefaultLoc, TestIsLessOp ? (TestIsStrictOp ? BO_LT : BO_LE)
3537 : (TestIsStrictOp ? BO_GT : BO_GE),
3538 NewLB.get(), NewUB.get());
3539 if (CondExpr.isUsable()) {
3540 if (!SemaRef.Context.hasSameUnqualifiedType(CondExpr.get()->getType(),
3541 SemaRef.Context.BoolTy))
3542 CondExpr = SemaRef.PerformImplicitConversion(
3543 CondExpr.get(), SemaRef.Context.BoolTy, /*Action=*/Sema::AA_Casting,
3544 /*AllowExplicit=*/true);
3546 SemaRef.getDiagnostics().setSuppressAllDiagnostics(Suppress);
3547 // Otherwise use original loop conditon and evaluate it in runtime.
3548 return CondExpr.isUsable() ? CondExpr.get() : Cond;
3551 /// \brief Build reference expression to the counter be used for codegen.
3552 DeclRefExpr *OpenMPIterationSpaceChecker::BuildCounterVar(
3553 llvm::MapVector<Expr *, DeclRefExpr *> &Captures, DSAStackTy &DSA) const {
3554 auto *VD = dyn_cast<VarDecl>(LCDecl);
3556 VD = SemaRef.IsOpenMPCapturedDecl(LCDecl);
3557 auto *Ref = buildDeclRefExpr(
3558 SemaRef, VD, VD->getType().getNonReferenceType(), DefaultLoc);
3559 DSAStackTy::DSAVarData Data = DSA.getTopDSA(LCDecl, /*FromParent=*/false);
3560 // If the loop control decl is explicitly marked as private, do not mark it
3561 // as captured again.
3562 if (!isOpenMPPrivate(Data.CKind) || !Data.RefExpr)
3563 Captures.insert(std::make_pair(LCRef, Ref));
3566 return buildDeclRefExpr(SemaRef, VD, VD->getType().getNonReferenceType(),
3570 Expr *OpenMPIterationSpaceChecker::BuildPrivateCounterVar() const {
3571 if (LCDecl && !LCDecl->isInvalidDecl()) {
3572 auto Type = LCDecl->getType().getNonReferenceType();
3574 buildVarDecl(SemaRef, DefaultLoc, Type, LCDecl->getName(),
3575 LCDecl->hasAttrs() ? &LCDecl->getAttrs() : nullptr);
3576 if (PrivateVar->isInvalidDecl())
3578 return buildDeclRefExpr(SemaRef, PrivateVar, Type, DefaultLoc);
3583 /// \brief Build initialization of the counter to be used for codegen.
3584 Expr *OpenMPIterationSpaceChecker::BuildCounterInit() const { return LB; }
3586 /// \brief Build step of the counter be used for codegen.
3587 Expr *OpenMPIterationSpaceChecker::BuildCounterStep() const { return Step; }
3589 /// \brief Iteration space of a single for loop.
3590 struct LoopIterationSpace final {
3591 /// \brief Condition of the loop.
3592 Expr *PreCond = nullptr;
3593 /// \brief This expression calculates the number of iterations in the loop.
3594 /// It is always possible to calculate it before starting the loop.
3595 Expr *NumIterations = nullptr;
3596 /// \brief The loop counter variable.
3597 Expr *CounterVar = nullptr;
3598 /// \brief Private loop counter variable.
3599 Expr *PrivateCounterVar = nullptr;
3600 /// \brief This is initializer for the initial value of #CounterVar.
3601 Expr *CounterInit = nullptr;
3602 /// \brief This is step for the #CounterVar used to generate its update:
3603 /// #CounterVar = #CounterInit + #CounterStep * CurrentIteration.
3604 Expr *CounterStep = nullptr;
3605 /// \brief Should step be subtracted?
3606 bool Subtract = false;
3607 /// \brief Source range of the loop init.
3608 SourceRange InitSrcRange;
3609 /// \brief Source range of the loop condition.
3610 SourceRange CondSrcRange;
3611 /// \brief Source range of the loop increment.
3612 SourceRange IncSrcRange;
3617 void Sema::ActOnOpenMPLoopInitialization(SourceLocation ForLoc, Stmt *Init) {
3618 assert(getLangOpts().OpenMP && "OpenMP is not active.");
3619 assert(Init && "Expected loop in canonical form.");
3620 unsigned AssociatedLoops = DSAStack->getAssociatedLoops();
3621 if (AssociatedLoops > 0 &&
3622 isOpenMPLoopDirective(DSAStack->getCurrentDirective())) {
3623 OpenMPIterationSpaceChecker ISC(*this, ForLoc);
3624 if (!ISC.CheckInit(Init, /*EmitDiags=*/false)) {
3625 if (auto *D = ISC.GetLoopDecl()) {
3626 auto *VD = dyn_cast<VarDecl>(D);
3628 if (auto *Private = IsOpenMPCapturedDecl(D))
3631 auto *Ref = buildCapture(*this, D, ISC.GetLoopDeclRefExpr(),
3632 /*WithInit=*/false);
3633 VD = cast<VarDecl>(Ref->getDecl());
3636 DSAStack->addLoopControlVariable(D, VD);
3639 DSAStack->setAssociatedLoops(AssociatedLoops - 1);
3643 /// \brief Called on a for stmt to check and extract its iteration space
3644 /// for further processing (such as collapsing).
3645 static bool CheckOpenMPIterationSpace(
3646 OpenMPDirectiveKind DKind, Stmt *S, Sema &SemaRef, DSAStackTy &DSA,
3647 unsigned CurrentNestedLoopCount, unsigned NestedLoopCount,
3648 Expr *CollapseLoopCountExpr, Expr *OrderedLoopCountExpr,
3649 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA,
3650 LoopIterationSpace &ResultIterSpace,
3651 llvm::MapVector<Expr *, DeclRefExpr *> &Captures) {
3652 // OpenMP [2.6, Canonical Loop Form]
3653 // for (init-expr; test-expr; incr-expr) structured-block
3654 auto *For = dyn_cast_or_null<ForStmt>(S);
3656 SemaRef.Diag(S->getLocStart(), diag::err_omp_not_for)
3657 << (CollapseLoopCountExpr != nullptr || OrderedLoopCountExpr != nullptr)
3658 << getOpenMPDirectiveName(DKind) << NestedLoopCount
3659 << (CurrentNestedLoopCount > 0) << CurrentNestedLoopCount;
3660 if (NestedLoopCount > 1) {
3661 if (CollapseLoopCountExpr && OrderedLoopCountExpr)
3662 SemaRef.Diag(DSA.getConstructLoc(),
3663 diag::note_omp_collapse_ordered_expr)
3664 << 2 << CollapseLoopCountExpr->getSourceRange()
3665 << OrderedLoopCountExpr->getSourceRange();
3666 else if (CollapseLoopCountExpr)
3667 SemaRef.Diag(CollapseLoopCountExpr->getExprLoc(),
3668 diag::note_omp_collapse_ordered_expr)
3669 << 0 << CollapseLoopCountExpr->getSourceRange();
3671 SemaRef.Diag(OrderedLoopCountExpr->getExprLoc(),
3672 diag::note_omp_collapse_ordered_expr)
3673 << 1 << OrderedLoopCountExpr->getSourceRange();
3677 assert(For->getBody());
3679 OpenMPIterationSpaceChecker ISC(SemaRef, For->getForLoc());
3682 auto Init = For->getInit();
3683 if (ISC.CheckInit(Init))
3686 bool HasErrors = false;
3688 // Check loop variable's type.
3689 if (auto *LCDecl = ISC.GetLoopDecl()) {
3690 auto *LoopDeclRefExpr = ISC.GetLoopDeclRefExpr();
3692 // OpenMP [2.6, Canonical Loop Form]
3693 // Var is one of the following:
3694 // A variable of signed or unsigned integer type.
3695 // For C++, a variable of a random access iterator type.
3696 // For C, a variable of a pointer type.
3697 auto VarType = LCDecl->getType().getNonReferenceType();
3698 if (!VarType->isDependentType() && !VarType->isIntegerType() &&
3699 !VarType->isPointerType() &&
3700 !(SemaRef.getLangOpts().CPlusPlus && VarType->isOverloadableType())) {
3701 SemaRef.Diag(Init->getLocStart(), diag::err_omp_loop_variable_type)
3702 << SemaRef.getLangOpts().CPlusPlus;
3706 // OpenMP, 2.14.1.1 Data-sharing Attribute Rules for Variables Referenced in
3708 // The loop iteration variable(s) in the associated for-loop(s) of a for or
3709 // parallel for construct is (are) private.
3710 // The loop iteration variable in the associated for-loop of a simd
3711 // construct with just one associated for-loop is linear with a
3712 // constant-linear-step that is the increment of the associated for-loop.
3713 // Exclude loop var from the list of variables with implicitly defined data
3714 // sharing attributes.
3715 VarsWithImplicitDSA.erase(LCDecl);
3717 // OpenMP [2.14.1.1, Data-sharing Attribute Rules for Variables Referenced
3718 // in a Construct, C/C++].
3719 // The loop iteration variable in the associated for-loop of a simd
3720 // construct with just one associated for-loop may be listed in a linear
3721 // clause with a constant-linear-step that is the increment of the
3722 // associated for-loop.
3723 // The loop iteration variable(s) in the associated for-loop(s) of a for or
3724 // parallel for construct may be listed in a private or lastprivate clause.
3725 DSAStackTy::DSAVarData DVar = DSA.getTopDSA(LCDecl, false);
3726 // If LoopVarRefExpr is nullptr it means the corresponding loop variable is
3727 // declared in the loop and it is predetermined as a private.
3728 auto PredeterminedCKind =
3729 isOpenMPSimdDirective(DKind)
3730 ? ((NestedLoopCount == 1) ? OMPC_linear : OMPC_lastprivate)
3732 if (((isOpenMPSimdDirective(DKind) && DVar.CKind != OMPC_unknown &&
3733 DVar.CKind != PredeterminedCKind) ||
3734 ((isOpenMPWorksharingDirective(DKind) || DKind == OMPD_taskloop ||
3735 isOpenMPDistributeDirective(DKind)) &&
3736 !isOpenMPSimdDirective(DKind) && DVar.CKind != OMPC_unknown &&
3737 DVar.CKind != OMPC_private && DVar.CKind != OMPC_lastprivate)) &&
3738 (DVar.CKind != OMPC_private || DVar.RefExpr != nullptr)) {
3739 SemaRef.Diag(Init->getLocStart(), diag::err_omp_loop_var_dsa)
3740 << getOpenMPClauseName(DVar.CKind) << getOpenMPDirectiveName(DKind)
3741 << getOpenMPClauseName(PredeterminedCKind);
3742 if (DVar.RefExpr == nullptr)
3743 DVar.CKind = PredeterminedCKind;
3744 ReportOriginalDSA(SemaRef, &DSA, LCDecl, DVar, /*IsLoopIterVar=*/true);
3746 } else if (LoopDeclRefExpr != nullptr) {
3747 // Make the loop iteration variable private (for worksharing constructs),
3748 // linear (for simd directives with the only one associated loop) or
3749 // lastprivate (for simd directives with several collapsed or ordered
3751 if (DVar.CKind == OMPC_unknown)
3752 DVar = DSA.hasDSA(LCDecl, isOpenMPPrivate,
3753 [](OpenMPDirectiveKind) -> bool { return true; },
3754 /*FromParent=*/false);
3755 DSA.addDSA(LCDecl, LoopDeclRefExpr, PredeterminedCKind);
3758 assert(isOpenMPLoopDirective(DKind) && "DSA for non-loop vars");
3761 HasErrors |= ISC.CheckCond(For->getCond());
3764 HasErrors |= ISC.CheckInc(For->getInc());
3767 if (ISC.Dependent() || SemaRef.CurContext->isDependentContext() || HasErrors)
3770 // Build the loop's iteration space representation.
3771 ResultIterSpace.PreCond =
3772 ISC.BuildPreCond(DSA.getCurScope(), For->getCond(), Captures);
3773 ResultIterSpace.NumIterations = ISC.BuildNumIterations(
3775 (isOpenMPWorksharingDirective(DKind) ||
3776 isOpenMPTaskLoopDirective(DKind) || isOpenMPDistributeDirective(DKind)),
3778 ResultIterSpace.CounterVar = ISC.BuildCounterVar(Captures, DSA);
3779 ResultIterSpace.PrivateCounterVar = ISC.BuildPrivateCounterVar();
3780 ResultIterSpace.CounterInit = ISC.BuildCounterInit();
3781 ResultIterSpace.CounterStep = ISC.BuildCounterStep();
3782 ResultIterSpace.InitSrcRange = ISC.GetInitSrcRange();
3783 ResultIterSpace.CondSrcRange = ISC.GetConditionSrcRange();
3784 ResultIterSpace.IncSrcRange = ISC.GetIncrementSrcRange();
3785 ResultIterSpace.Subtract = ISC.ShouldSubtractStep();
3787 HasErrors |= (ResultIterSpace.PreCond == nullptr ||
3788 ResultIterSpace.NumIterations == nullptr ||
3789 ResultIterSpace.CounterVar == nullptr ||
3790 ResultIterSpace.PrivateCounterVar == nullptr ||
3791 ResultIterSpace.CounterInit == nullptr ||
3792 ResultIterSpace.CounterStep == nullptr);
3797 /// \brief Build 'VarRef = Start.
3799 BuildCounterInit(Sema &SemaRef, Scope *S, SourceLocation Loc, ExprResult VarRef,
3801 llvm::MapVector<Expr *, DeclRefExpr *> &Captures) {
3802 // Build 'VarRef = Start.
3803 auto NewStart = tryBuildCapture(SemaRef, Start.get(), Captures);
3804 if (!NewStart.isUsable())
3806 if (!SemaRef.Context.hasSameType(NewStart.get()->getType(),
3807 VarRef.get()->getType())) {
3808 NewStart = SemaRef.PerformImplicitConversion(
3809 NewStart.get(), VarRef.get()->getType(), Sema::AA_Converting,
3810 /*AllowExplicit=*/true);
3811 if (!NewStart.isUsable())
3816 SemaRef.BuildBinOp(S, Loc, BO_Assign, VarRef.get(), NewStart.get());
3820 /// \brief Build 'VarRef = Start + Iter * Step'.
3822 BuildCounterUpdate(Sema &SemaRef, Scope *S, SourceLocation Loc,
3823 ExprResult VarRef, ExprResult Start, ExprResult Iter,
3824 ExprResult Step, bool Subtract,
3825 llvm::MapVector<Expr *, DeclRefExpr *> *Captures = nullptr) {
3826 // Add parentheses (for debugging purposes only).
3827 Iter = SemaRef.ActOnParenExpr(Loc, Loc, Iter.get());
3828 if (!VarRef.isUsable() || !Start.isUsable() || !Iter.isUsable() ||
3832 ExprResult NewStep = Step;
3834 NewStep = tryBuildCapture(SemaRef, Step.get(), *Captures);
3835 if (NewStep.isInvalid())
3838 SemaRef.BuildBinOp(S, Loc, BO_Mul, Iter.get(), NewStep.get());
3839 if (!Update.isUsable())
3842 // Try to build 'VarRef = Start, VarRef (+|-)= Iter * Step' or
3843 // 'VarRef = Start (+|-) Iter * Step'.
3844 ExprResult NewStart = Start;
3846 NewStart = tryBuildCapture(SemaRef, Start.get(), *Captures);
3847 if (NewStart.isInvalid())
3850 // First attempt: try to build 'VarRef = Start, VarRef += Iter * Step'.
3851 ExprResult SavedUpdate = Update;
3852 ExprResult UpdateVal;
3853 if (VarRef.get()->getType()->isOverloadableType() ||
3854 NewStart.get()->getType()->isOverloadableType() ||
3855 Update.get()->getType()->isOverloadableType()) {
3856 bool Suppress = SemaRef.getDiagnostics().getSuppressAllDiagnostics();
3857 SemaRef.getDiagnostics().setSuppressAllDiagnostics(/*Val=*/true);
3859 SemaRef.BuildBinOp(S, Loc, BO_Assign, VarRef.get(), NewStart.get());
3860 if (Update.isUsable()) {
3862 SemaRef.BuildBinOp(S, Loc, Subtract ? BO_SubAssign : BO_AddAssign,
3863 VarRef.get(), SavedUpdate.get());
3864 if (UpdateVal.isUsable()) {
3865 Update = SemaRef.CreateBuiltinBinOp(Loc, BO_Comma, Update.get(),
3869 SemaRef.getDiagnostics().setSuppressAllDiagnostics(Suppress);
3872 // Second attempt: try to build 'VarRef = Start (+|-) Iter * Step'.
3873 if (!Update.isUsable() || !UpdateVal.isUsable()) {
3874 Update = SemaRef.BuildBinOp(S, Loc, Subtract ? BO_Sub : BO_Add,
3875 NewStart.get(), SavedUpdate.get());
3876 if (!Update.isUsable())
3879 if (!SemaRef.Context.hasSameType(Update.get()->getType(),
3880 VarRef.get()->getType())) {
3881 Update = SemaRef.PerformImplicitConversion(
3882 Update.get(), VarRef.get()->getType(), Sema::AA_Converting, true);
3883 if (!Update.isUsable())
3887 Update = SemaRef.BuildBinOp(S, Loc, BO_Assign, VarRef.get(), Update.get());
3892 /// \brief Convert integer expression \a E to make it have at least \a Bits
3894 static ExprResult WidenIterationCount(unsigned Bits, Expr *E, Sema &SemaRef) {
3897 auto &C = SemaRef.Context;
3898 QualType OldType = E->getType();
3899 unsigned HasBits = C.getTypeSize(OldType);
3900 if (HasBits >= Bits)
3901 return ExprResult(E);
3902 // OK to convert to signed, because new type has more bits than old.
3903 QualType NewType = C.getIntTypeForBitwidth(Bits, /* Signed */ true);
3904 return SemaRef.PerformImplicitConversion(E, NewType, Sema::AA_Converting,
3908 /// \brief Check if the given expression \a E is a constant integer that fits
3909 /// into \a Bits bits.
3910 static bool FitsInto(unsigned Bits, bool Signed, Expr *E, Sema &SemaRef) {
3913 llvm::APSInt Result;
3914 if (E->isIntegerConstantExpr(Result, SemaRef.Context))
3915 return Signed ? Result.isSignedIntN(Bits) : Result.isIntN(Bits);
3919 /// Build preinits statement for the given declarations.
3920 static Stmt *buildPreInits(ASTContext &Context,
3921 SmallVectorImpl<Decl *> &PreInits) {
3922 if (!PreInits.empty()) {
3923 return new (Context) DeclStmt(
3924 DeclGroupRef::Create(Context, PreInits.begin(), PreInits.size()),
3925 SourceLocation(), SourceLocation());
3930 /// Build preinits statement for the given declarations.
3931 static Stmt *buildPreInits(ASTContext &Context,
3932 llvm::MapVector<Expr *, DeclRefExpr *> &Captures) {
3933 if (!Captures.empty()) {
3934 SmallVector<Decl *, 16> PreInits;
3935 for (auto &Pair : Captures)
3936 PreInits.push_back(Pair.second->getDecl());
3937 return buildPreInits(Context, PreInits);
3942 /// Build postupdate expression for the given list of postupdates expressions.
3943 static Expr *buildPostUpdate(Sema &S, ArrayRef<Expr *> PostUpdates) {
3944 Expr *PostUpdate = nullptr;
3945 if (!PostUpdates.empty()) {
3946 for (auto *E : PostUpdates) {
3947 Expr *ConvE = S.BuildCStyleCastExpr(
3949 S.Context.getTrivialTypeSourceInfo(S.Context.VoidTy),
3952 PostUpdate = PostUpdate
3953 ? S.CreateBuiltinBinOp(ConvE->getExprLoc(), BO_Comma,
3962 /// \brief Called on a for stmt to check itself and nested loops (if any).
3963 /// \return Returns 0 if one of the collapsed stmts is not canonical for loop,
3964 /// number of collapsed loops otherwise.
3966 CheckOpenMPLoop(OpenMPDirectiveKind DKind, Expr *CollapseLoopCountExpr,
3967 Expr *OrderedLoopCountExpr, Stmt *AStmt, Sema &SemaRef,
3969 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA,
3970 OMPLoopDirective::HelperExprs &Built) {
3971 unsigned NestedLoopCount = 1;
3972 if (CollapseLoopCountExpr) {
3973 // Found 'collapse' clause - calculate collapse number.
3974 llvm::APSInt Result;
3975 if (CollapseLoopCountExpr->EvaluateAsInt(Result, SemaRef.getASTContext()))
3976 NestedLoopCount = Result.getLimitedValue();
3978 if (OrderedLoopCountExpr) {
3979 // Found 'ordered' clause - calculate collapse number.
3980 llvm::APSInt Result;
3981 if (OrderedLoopCountExpr->EvaluateAsInt(Result, SemaRef.getASTContext())) {
3982 if (Result.getLimitedValue() < NestedLoopCount) {
3983 SemaRef.Diag(OrderedLoopCountExpr->getExprLoc(),
3984 diag::err_omp_wrong_ordered_loop_count)
3985 << OrderedLoopCountExpr->getSourceRange();
3986 SemaRef.Diag(CollapseLoopCountExpr->getExprLoc(),
3987 diag::note_collapse_loop_count)
3988 << CollapseLoopCountExpr->getSourceRange();
3990 NestedLoopCount = Result.getLimitedValue();
3993 // This is helper routine for loop directives (e.g., 'for', 'simd',
3994 // 'for simd', etc.).
3995 llvm::MapVector<Expr *, DeclRefExpr *> Captures;
3996 SmallVector<LoopIterationSpace, 4> IterSpaces;
3997 IterSpaces.resize(NestedLoopCount);
3998 Stmt *CurStmt = AStmt->IgnoreContainers(/* IgnoreCaptured */ true);
3999 for (unsigned Cnt = 0; Cnt < NestedLoopCount; ++Cnt) {
4000 if (CheckOpenMPIterationSpace(DKind, CurStmt, SemaRef, DSA, Cnt,
4001 NestedLoopCount, CollapseLoopCountExpr,
4002 OrderedLoopCountExpr, VarsWithImplicitDSA,
4003 IterSpaces[Cnt], Captures))
4005 // Move on to the next nested for loop, or to the loop body.
4006 // OpenMP [2.8.1, simd construct, Restrictions]
4007 // All loops associated with the construct must be perfectly nested; that
4008 // is, there must be no intervening code nor any OpenMP directive between
4010 CurStmt = cast<ForStmt>(CurStmt)->getBody()->IgnoreContainers();
4013 Built.clear(/* size */ NestedLoopCount);
4015 if (SemaRef.CurContext->isDependentContext())
4016 return NestedLoopCount;
4018 // An example of what is generated for the following code:
4020 // #pragma omp simd collapse(2) ordered(2)
4021 // for (i = 0; i < NI; ++i)
4022 // for (k = 0; k < NK; ++k)
4023 // for (j = J0; j < NJ; j+=2) {
4027 // We generate the code below.
4028 // Note: the loop body may be outlined in CodeGen.
4029 // Note: some counters may be C++ classes, operator- is used to find number of
4030 // iterations and operator+= to calculate counter value.
4031 // Note: decltype(NumIterations) must be integer type (in 'omp for', only i32
4032 // or i64 is currently supported).
4034 // #define NumIterations (NI * ((NJ - J0 - 1 + 2) / 2))
4035 // for (int[32|64]_t IV = 0; IV < NumIterations; ++IV ) {
4036 // .local.i = IV / ((NJ - J0 - 1 + 2) / 2);
4037 // .local.j = J0 + (IV % ((NJ - J0 - 1 + 2) / 2)) * 2;
4038 // // similar updates for vars in clauses (e.g. 'linear')
4039 // <loop body (using local i and j)>
4041 // i = NI; // assign final values of counters
4045 // Last iteration number is (I1 * I2 * ... In) - 1, where I1, I2 ... In are
4046 // the iteration counts of the collapsed for loops.
4047 // Precondition tests if there is at least one iteration (all conditions are
4049 auto PreCond = ExprResult(IterSpaces[0].PreCond);
4050 auto N0 = IterSpaces[0].NumIterations;
4051 ExprResult LastIteration32 = WidenIterationCount(
4052 32 /* Bits */, SemaRef
4053 .PerformImplicitConversion(
4054 N0->IgnoreImpCasts(), N0->getType(),
4055 Sema::AA_Converting, /*AllowExplicit=*/true)
4058 ExprResult LastIteration64 = WidenIterationCount(
4059 64 /* Bits */, SemaRef
4060 .PerformImplicitConversion(
4061 N0->IgnoreImpCasts(), N0->getType(),
4062 Sema::AA_Converting, /*AllowExplicit=*/true)
4066 if (!LastIteration32.isUsable() || !LastIteration64.isUsable())
4067 return NestedLoopCount;
4069 auto &C = SemaRef.Context;
4070 bool AllCountsNeedLessThan32Bits = C.getTypeSize(N0->getType()) < 32;
4072 Scope *CurScope = DSA.getCurScope();
4073 for (unsigned Cnt = 1; Cnt < NestedLoopCount; ++Cnt) {
4074 if (PreCond.isUsable()) {
4076 SemaRef.BuildBinOp(CurScope, PreCond.get()->getExprLoc(), BO_LAnd,
4077 PreCond.get(), IterSpaces[Cnt].PreCond);
4079 auto N = IterSpaces[Cnt].NumIterations;
4080 SourceLocation Loc = N->getExprLoc();
4081 AllCountsNeedLessThan32Bits &= C.getTypeSize(N->getType()) < 32;
4082 if (LastIteration32.isUsable())
4083 LastIteration32 = SemaRef.BuildBinOp(
4084 CurScope, Loc, BO_Mul, LastIteration32.get(),
4086 .PerformImplicitConversion(N->IgnoreImpCasts(), N->getType(),
4087 Sema::AA_Converting,
4088 /*AllowExplicit=*/true)
4090 if (LastIteration64.isUsable())
4091 LastIteration64 = SemaRef.BuildBinOp(
4092 CurScope, Loc, BO_Mul, LastIteration64.get(),
4094 .PerformImplicitConversion(N->IgnoreImpCasts(), N->getType(),
4095 Sema::AA_Converting,
4096 /*AllowExplicit=*/true)
4100 // Choose either the 32-bit or 64-bit version.
4101 ExprResult LastIteration = LastIteration64;
4102 if (LastIteration32.isUsable() &&
4103 C.getTypeSize(LastIteration32.get()->getType()) == 32 &&
4104 (AllCountsNeedLessThan32Bits || NestedLoopCount == 1 ||
4107 LastIteration32.get()->getType()->hasSignedIntegerRepresentation(),
4108 LastIteration64.get(), SemaRef)))
4109 LastIteration = LastIteration32;
4110 QualType VType = LastIteration.get()->getType();
4111 QualType RealVType = VType;
4112 QualType StrideVType = VType;
4113 if (isOpenMPTaskLoopDirective(DKind)) {
4115 SemaRef.Context.getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/0);
4117 SemaRef.Context.getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/1);
4120 if (!LastIteration.isUsable())
4123 // Save the number of iterations.
4124 ExprResult NumIterations = LastIteration;
4126 LastIteration = SemaRef.BuildBinOp(
4127 CurScope, LastIteration.get()->getExprLoc(), BO_Sub,
4128 LastIteration.get(),
4129 SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get());
4130 if (!LastIteration.isUsable())
4134 // Calculate the last iteration number beforehand instead of doing this on
4135 // each iteration. Do not do this if the number of iterations may be kfold-ed.
4136 llvm::APSInt Result;
4138 LastIteration.get()->isIntegerConstantExpr(Result, SemaRef.Context);
4139 ExprResult CalcLastIteration;
4141 ExprResult SaveRef =
4142 tryBuildCapture(SemaRef, LastIteration.get(), Captures);
4143 LastIteration = SaveRef;
4145 // Prepare SaveRef + 1.
4146 NumIterations = SemaRef.BuildBinOp(
4147 CurScope, SaveRef.get()->getExprLoc(), BO_Add, SaveRef.get(),
4148 SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get());
4149 if (!NumIterations.isUsable())
4153 SourceLocation InitLoc = IterSpaces[0].InitSrcRange.getBegin();
4155 // Build variables passed into runtime, necessary for worksharing directives.
4156 ExprResult LB, UB, IL, ST, EUB, CombLB, CombUB, PrevLB, PrevUB, CombEUB;
4157 if (isOpenMPWorksharingDirective(DKind) || isOpenMPTaskLoopDirective(DKind) ||
4158 isOpenMPDistributeDirective(DKind)) {
4159 // Lower bound variable, initialized with zero.
4160 VarDecl *LBDecl = buildVarDecl(SemaRef, InitLoc, VType, ".omp.lb");
4161 LB = buildDeclRefExpr(SemaRef, LBDecl, VType, InitLoc);
4162 SemaRef.AddInitializerToDecl(LBDecl,
4163 SemaRef.ActOnIntegerConstant(InitLoc, 0).get(),
4164 /*DirectInit*/ false);
4166 // Upper bound variable, initialized with last iteration number.
4167 VarDecl *UBDecl = buildVarDecl(SemaRef, InitLoc, VType, ".omp.ub");
4168 UB = buildDeclRefExpr(SemaRef, UBDecl, VType, InitLoc);
4169 SemaRef.AddInitializerToDecl(UBDecl, LastIteration.get(),
4170 /*DirectInit*/ false);
4172 // A 32-bit variable-flag where runtime returns 1 for the last iteration.
4173 // This will be used to implement clause 'lastprivate'.
4174 QualType Int32Ty = SemaRef.Context.getIntTypeForBitwidth(32, true);
4175 VarDecl *ILDecl = buildVarDecl(SemaRef, InitLoc, Int32Ty, ".omp.is_last");
4176 IL = buildDeclRefExpr(SemaRef, ILDecl, Int32Ty, InitLoc);
4177 SemaRef.AddInitializerToDecl(ILDecl,
4178 SemaRef.ActOnIntegerConstant(InitLoc, 0).get(),
4179 /*DirectInit*/ false);
4181 // Stride variable returned by runtime (we initialize it to 1 by default).
4183 buildVarDecl(SemaRef, InitLoc, StrideVType, ".omp.stride");
4184 ST = buildDeclRefExpr(SemaRef, STDecl, StrideVType, InitLoc);
4185 SemaRef.AddInitializerToDecl(STDecl,
4186 SemaRef.ActOnIntegerConstant(InitLoc, 1).get(),
4187 /*DirectInit*/ false);
4189 // Build expression: UB = min(UB, LastIteration)
4190 // It is necessary for CodeGen of directives with static scheduling.
4191 ExprResult IsUBGreater = SemaRef.BuildBinOp(CurScope, InitLoc, BO_GT,
4192 UB.get(), LastIteration.get());
4193 ExprResult CondOp = SemaRef.ActOnConditionalOp(
4194 InitLoc, InitLoc, IsUBGreater.get(), LastIteration.get(), UB.get());
4195 EUB = SemaRef.BuildBinOp(CurScope, InitLoc, BO_Assign, UB.get(),
4197 EUB = SemaRef.ActOnFinishFullExpr(EUB.get());
4199 // If we have a combined directive that combines 'distribute', 'for' or
4200 // 'simd' we need to be able to access the bounds of the schedule of the
4201 // enclosing region. E.g. in 'distribute parallel for' the bounds obtained
4202 // by scheduling 'distribute' have to be passed to the schedule of 'for'.
4203 if (isOpenMPLoopBoundSharingDirective(DKind)) {
4205 // Lower bound variable, initialized with zero.
4206 VarDecl *CombLBDecl =
4207 buildVarDecl(SemaRef, InitLoc, VType, ".omp.comb.lb");
4208 CombLB = buildDeclRefExpr(SemaRef, CombLBDecl, VType, InitLoc);
4209 SemaRef.AddInitializerToDecl(
4210 CombLBDecl, SemaRef.ActOnIntegerConstant(InitLoc, 0).get(),
4211 /*DirectInit*/ false);
4213 // Upper bound variable, initialized with last iteration number.
4214 VarDecl *CombUBDecl =
4215 buildVarDecl(SemaRef, InitLoc, VType, ".omp.comb.ub");
4216 CombUB = buildDeclRefExpr(SemaRef, CombUBDecl, VType, InitLoc);
4217 SemaRef.AddInitializerToDecl(CombUBDecl, LastIteration.get(),
4218 /*DirectInit*/ false);
4220 ExprResult CombIsUBGreater = SemaRef.BuildBinOp(
4221 CurScope, InitLoc, BO_GT, CombUB.get(), LastIteration.get());
4222 ExprResult CombCondOp =
4223 SemaRef.ActOnConditionalOp(InitLoc, InitLoc, CombIsUBGreater.get(),
4224 LastIteration.get(), CombUB.get());
4225 CombEUB = SemaRef.BuildBinOp(CurScope, InitLoc, BO_Assign, CombUB.get(),
4227 CombEUB = SemaRef.ActOnFinishFullExpr(CombEUB.get());
4229 auto *CD = cast<CapturedStmt>(AStmt)->getCapturedDecl();
4230 // We expect to have at least 2 more parameters than the 'parallel'
4231 // directive does - the lower and upper bounds of the previous schedule.
4232 assert(CD->getNumParams() >= 4 &&
4233 "Unexpected number of parameters in loop combined directive");
4235 // Set the proper type for the bounds given what we learned from the
4237 auto *PrevLBDecl = CD->getParam(/*PrevLB=*/2);
4238 auto *PrevUBDecl = CD->getParam(/*PrevUB=*/3);
4240 // Previous lower and upper bounds are obtained from the region
4243 buildDeclRefExpr(SemaRef, PrevLBDecl, PrevLBDecl->getType(), InitLoc);
4245 buildDeclRefExpr(SemaRef, PrevUBDecl, PrevUBDecl->getType(), InitLoc);
4249 // Build the iteration variable and its initialization before loop.
4251 ExprResult Init, CombInit;
4253 VarDecl *IVDecl = buildVarDecl(SemaRef, InitLoc, RealVType, ".omp.iv");
4254 IV = buildDeclRefExpr(SemaRef, IVDecl, RealVType, InitLoc);
4256 (isOpenMPWorksharingDirective(DKind) ||
4257 isOpenMPTaskLoopDirective(DKind) || isOpenMPDistributeDirective(DKind))
4259 : SemaRef.ActOnIntegerConstant(SourceLocation(), 0).get();
4260 Init = SemaRef.BuildBinOp(CurScope, InitLoc, BO_Assign, IV.get(), RHS);
4261 Init = SemaRef.ActOnFinishFullExpr(Init.get());
4263 if (isOpenMPLoopBoundSharingDirective(DKind)) {
4265 (isOpenMPWorksharingDirective(DKind) ||
4266 isOpenMPTaskLoopDirective(DKind) ||
4267 isOpenMPDistributeDirective(DKind))
4269 : SemaRef.ActOnIntegerConstant(SourceLocation(), 0).get();
4271 SemaRef.BuildBinOp(CurScope, InitLoc, BO_Assign, IV.get(), CombRHS);
4272 CombInit = SemaRef.ActOnFinishFullExpr(CombInit.get());
4276 // Loop condition (IV < NumIterations) or (IV <= UB) for worksharing loops.
4277 SourceLocation CondLoc;
4279 (isOpenMPWorksharingDirective(DKind) ||
4280 isOpenMPTaskLoopDirective(DKind) || isOpenMPDistributeDirective(DKind))
4281 ? SemaRef.BuildBinOp(CurScope, CondLoc, BO_LE, IV.get(), UB.get())
4282 : SemaRef.BuildBinOp(CurScope, CondLoc, BO_LT, IV.get(),
4283 NumIterations.get());
4284 ExprResult CombCond;
4285 if (isOpenMPLoopBoundSharingDirective(DKind)) {
4287 SemaRef.BuildBinOp(CurScope, CondLoc, BO_LE, IV.get(), CombUB.get());
4289 // Loop increment (IV = IV + 1)
4290 SourceLocation IncLoc;
4292 SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, IV.get(),
4293 SemaRef.ActOnIntegerConstant(IncLoc, 1).get());
4294 if (!Inc.isUsable())
4296 Inc = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, IV.get(), Inc.get());
4297 Inc = SemaRef.ActOnFinishFullExpr(Inc.get());
4298 if (!Inc.isUsable())
4301 // Increments for worksharing loops (LB = LB + ST; UB = UB + ST).
4302 // Used for directives with static scheduling.
4303 // In combined construct, add combined version that use CombLB and CombUB
4304 // base variables for the update
4305 ExprResult NextLB, NextUB, CombNextLB, CombNextUB;
4306 if (isOpenMPWorksharingDirective(DKind) || isOpenMPTaskLoopDirective(DKind) ||
4307 isOpenMPDistributeDirective(DKind)) {
4309 NextLB = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, LB.get(), ST.get());
4310 if (!NextLB.isUsable())
4314 SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, LB.get(), NextLB.get());
4315 NextLB = SemaRef.ActOnFinishFullExpr(NextLB.get());
4316 if (!NextLB.isUsable())
4319 NextUB = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, UB.get(), ST.get());
4320 if (!NextUB.isUsable())
4324 SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, UB.get(), NextUB.get());
4325 NextUB = SemaRef.ActOnFinishFullExpr(NextUB.get());
4326 if (!NextUB.isUsable())
4328 if (isOpenMPLoopBoundSharingDirective(DKind)) {
4330 SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, CombLB.get(), ST.get());
4331 if (!NextLB.isUsable())
4334 CombNextLB = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, CombLB.get(),
4336 CombNextLB = SemaRef.ActOnFinishFullExpr(CombNextLB.get());
4337 if (!CombNextLB.isUsable())
4341 SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, CombUB.get(), ST.get());
4342 if (!CombNextUB.isUsable())
4345 CombNextUB = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, CombUB.get(),
4347 CombNextUB = SemaRef.ActOnFinishFullExpr(CombNextUB.get());
4348 if (!CombNextUB.isUsable())
4353 // Create increment expression for distribute loop when combined in a same
4354 // directive with for as IV = IV + ST; ensure upper bound expression based
4355 // on PrevUB instead of NumIterations - used to implement 'for' when found
4356 // in combination with 'distribute', like in 'distribute parallel for'
4357 SourceLocation DistIncLoc;
4358 ExprResult DistCond, DistInc, PrevEUB;
4359 if (isOpenMPLoopBoundSharingDirective(DKind)) {
4360 DistCond = SemaRef.BuildBinOp(CurScope, CondLoc, BO_LE, IV.get(), UB.get());
4361 assert(DistCond.isUsable() && "distribute cond expr was not built");
4364 SemaRef.BuildBinOp(CurScope, DistIncLoc, BO_Add, IV.get(), ST.get());
4365 assert(DistInc.isUsable() && "distribute inc expr was not built");
4366 DistInc = SemaRef.BuildBinOp(CurScope, DistIncLoc, BO_Assign, IV.get(),
4368 DistInc = SemaRef.ActOnFinishFullExpr(DistInc.get());
4369 assert(DistInc.isUsable() && "distribute inc expr was not built");
4371 // Build expression: UB = min(UB, prevUB) for #for in composite or combined
4373 SourceLocation DistEUBLoc;
4374 ExprResult IsUBGreater =
4375 SemaRef.BuildBinOp(CurScope, DistEUBLoc, BO_GT, UB.get(), PrevUB.get());
4376 ExprResult CondOp = SemaRef.ActOnConditionalOp(
4377 DistEUBLoc, DistEUBLoc, IsUBGreater.get(), PrevUB.get(), UB.get());
4378 PrevEUB = SemaRef.BuildBinOp(CurScope, DistIncLoc, BO_Assign, UB.get(),
4380 PrevEUB = SemaRef.ActOnFinishFullExpr(PrevEUB.get());
4383 // Build updates and final values of the loop counters.
4384 bool HasErrors = false;
4385 Built.Counters.resize(NestedLoopCount);
4386 Built.Inits.resize(NestedLoopCount);
4387 Built.Updates.resize(NestedLoopCount);
4388 Built.Finals.resize(NestedLoopCount);
4389 SmallVector<Expr *, 4> LoopMultipliers;
4392 // Go from inner nested loop to outer.
4393 for (int Cnt = NestedLoopCount - 1; Cnt >= 0; --Cnt) {
4394 LoopIterationSpace &IS = IterSpaces[Cnt];
4395 SourceLocation UpdLoc = IS.IncSrcRange.getBegin();
4396 // Build: Iter = (IV / Div) % IS.NumIters
4397 // where Div is product of previous iterations' IS.NumIters.
4399 if (Div.isUsable()) {
4401 SemaRef.BuildBinOp(CurScope, UpdLoc, BO_Div, IV.get(), Div.get());
4404 assert((Cnt == (int)NestedLoopCount - 1) &&
4405 "unusable div expected on first iteration only");
4408 if (Cnt != 0 && Iter.isUsable())
4409 Iter = SemaRef.BuildBinOp(CurScope, UpdLoc, BO_Rem, Iter.get(),
4411 if (!Iter.isUsable()) {
4416 // Build update: IS.CounterVar(Private) = IS.Start + Iter * IS.Step
4417 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(IS.CounterVar)->getDecl());
4418 auto *CounterVar = buildDeclRefExpr(SemaRef, VD, IS.CounterVar->getType(),
4419 IS.CounterVar->getExprLoc(),
4420 /*RefersToCapture=*/true);
4421 ExprResult Init = BuildCounterInit(SemaRef, CurScope, UpdLoc, CounterVar,
4422 IS.CounterInit, Captures);
4423 if (!Init.isUsable()) {
4427 ExprResult Update = BuildCounterUpdate(
4428 SemaRef, CurScope, UpdLoc, CounterVar, IS.CounterInit, Iter,
4429 IS.CounterStep, IS.Subtract, &Captures);
4430 if (!Update.isUsable()) {
4435 // Build final: IS.CounterVar = IS.Start + IS.NumIters * IS.Step
4436 ExprResult Final = BuildCounterUpdate(
4437 SemaRef, CurScope, UpdLoc, CounterVar, IS.CounterInit,
4438 IS.NumIterations, IS.CounterStep, IS.Subtract, &Captures);
4439 if (!Final.isUsable()) {
4444 // Build Div for the next iteration: Div <- Div * IS.NumIters
4447 Div = IS.NumIterations;
4449 Div = SemaRef.BuildBinOp(CurScope, UpdLoc, BO_Mul, Div.get(),
4452 // Add parentheses (for debugging purposes only).
4454 Div = tryBuildCapture(SemaRef, Div.get(), Captures);
4455 if (!Div.isUsable()) {
4459 LoopMultipliers.push_back(Div.get());
4461 if (!Update.isUsable() || !Final.isUsable()) {
4466 Built.Counters[Cnt] = IS.CounterVar;
4467 Built.PrivateCounters[Cnt] = IS.PrivateCounterVar;
4468 Built.Inits[Cnt] = Init.get();
4469 Built.Updates[Cnt] = Update.get();
4470 Built.Finals[Cnt] = Final.get();
4478 Built.IterationVarRef = IV.get();
4479 Built.LastIteration = LastIteration.get();
4480 Built.NumIterations = NumIterations.get();
4481 Built.CalcLastIteration =
4482 SemaRef.ActOnFinishFullExpr(CalcLastIteration.get()).get();
4483 Built.PreCond = PreCond.get();
4484 Built.PreInits = buildPreInits(C, Captures);
4485 Built.Cond = Cond.get();
4486 Built.Init = Init.get();
4487 Built.Inc = Inc.get();
4488 Built.LB = LB.get();
4489 Built.UB = UB.get();
4490 Built.IL = IL.get();
4491 Built.ST = ST.get();
4492 Built.EUB = EUB.get();
4493 Built.NLB = NextLB.get();
4494 Built.NUB = NextUB.get();
4495 Built.PrevLB = PrevLB.get();
4496 Built.PrevUB = PrevUB.get();
4497 Built.DistInc = DistInc.get();
4498 Built.PrevEUB = PrevEUB.get();
4499 Built.DistCombinedFields.LB = CombLB.get();
4500 Built.DistCombinedFields.UB = CombUB.get();
4501 Built.DistCombinedFields.EUB = CombEUB.get();
4502 Built.DistCombinedFields.Init = CombInit.get();
4503 Built.DistCombinedFields.Cond = CombCond.get();
4504 Built.DistCombinedFields.NLB = CombNextLB.get();
4505 Built.DistCombinedFields.NUB = CombNextUB.get();
4507 Expr *CounterVal = SemaRef.DefaultLvalueConversion(IV.get()).get();
4508 // Fill data for doacross depend clauses.
4509 for (auto Pair : DSA.getDoacrossDependClauses()) {
4510 if (Pair.first->getDependencyKind() == OMPC_DEPEND_source)
4511 Pair.first->setCounterValue(CounterVal);
4513 if (NestedLoopCount != Pair.second.size() ||
4514 NestedLoopCount != LoopMultipliers.size() + 1) {
4515 // Erroneous case - clause has some problems.
4516 Pair.first->setCounterValue(CounterVal);
4519 assert(Pair.first->getDependencyKind() == OMPC_DEPEND_sink);
4520 auto I = Pair.second.rbegin();
4521 auto IS = IterSpaces.rbegin();
4522 auto ILM = LoopMultipliers.rbegin();
4523 Expr *UpCounterVal = CounterVal;
4524 Expr *Multiplier = nullptr;
4525 for (int Cnt = NestedLoopCount - 1; Cnt >= 0; --Cnt) {
4527 assert(IS->CounterStep);
4528 Expr *NormalizedOffset =
4530 .BuildBinOp(CurScope, I->first->getExprLoc(), BO_Div,
4531 I->first, IS->CounterStep)
4536 .BuildBinOp(CurScope, I->first->getExprLoc(), BO_Mul,
4537 NormalizedOffset, Multiplier)
4540 assert(I->second == OO_Plus || I->second == OO_Minus);
4541 BinaryOperatorKind BOK = (I->second == OO_Plus) ? BO_Add : BO_Sub;
4542 UpCounterVal = SemaRef
4543 .BuildBinOp(CurScope, I->first->getExprLoc(), BOK,
4544 UpCounterVal, NormalizedOffset)
4552 Pair.first->setCounterValue(UpCounterVal);
4556 return NestedLoopCount;
4559 static Expr *getCollapseNumberExpr(ArrayRef<OMPClause *> Clauses) {
4560 auto CollapseClauses =
4561 OMPExecutableDirective::getClausesOfKind<OMPCollapseClause>(Clauses);
4562 if (CollapseClauses.begin() != CollapseClauses.end())
4563 return (*CollapseClauses.begin())->getNumForLoops();
4567 static Expr *getOrderedNumberExpr(ArrayRef<OMPClause *> Clauses) {
4568 auto OrderedClauses =
4569 OMPExecutableDirective::getClausesOfKind<OMPOrderedClause>(Clauses);
4570 if (OrderedClauses.begin() != OrderedClauses.end())
4571 return (*OrderedClauses.begin())->getNumForLoops();
4575 static bool checkSimdlenSafelenSpecified(Sema &S,
4576 const ArrayRef<OMPClause *> Clauses) {
4577 OMPSafelenClause *Safelen = nullptr;
4578 OMPSimdlenClause *Simdlen = nullptr;
4580 for (auto *Clause : Clauses) {
4581 if (Clause->getClauseKind() == OMPC_safelen)
4582 Safelen = cast<OMPSafelenClause>(Clause);
4583 else if (Clause->getClauseKind() == OMPC_simdlen)
4584 Simdlen = cast<OMPSimdlenClause>(Clause);
4585 if (Safelen && Simdlen)
4589 if (Simdlen && Safelen) {
4590 llvm::APSInt SimdlenRes, SafelenRes;
4591 auto SimdlenLength = Simdlen->getSimdlen();
4592 auto SafelenLength = Safelen->getSafelen();
4593 if (SimdlenLength->isValueDependent() || SimdlenLength->isTypeDependent() ||
4594 SimdlenLength->isInstantiationDependent() ||
4595 SimdlenLength->containsUnexpandedParameterPack())
4597 if (SafelenLength->isValueDependent() || SafelenLength->isTypeDependent() ||
4598 SafelenLength->isInstantiationDependent() ||
4599 SafelenLength->containsUnexpandedParameterPack())
4601 SimdlenLength->EvaluateAsInt(SimdlenRes, S.Context);
4602 SafelenLength->EvaluateAsInt(SafelenRes, S.Context);
4603 // OpenMP 4.5 [2.8.1, simd Construct, Restrictions]
4604 // If both simdlen and safelen clauses are specified, the value of the
4605 // simdlen parameter must be less than or equal to the value of the safelen
4607 if (SimdlenRes > SafelenRes) {
4608 S.Diag(SimdlenLength->getExprLoc(),
4609 diag::err_omp_wrong_simdlen_safelen_values)
4610 << SimdlenLength->getSourceRange() << SafelenLength->getSourceRange();
4617 StmtResult Sema::ActOnOpenMPSimdDirective(
4618 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
4619 SourceLocation EndLoc,
4620 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
4624 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
4625 OMPLoopDirective::HelperExprs B;
4626 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
4627 // define the nested loops number.
4628 unsigned NestedLoopCount = CheckOpenMPLoop(
4629 OMPD_simd, getCollapseNumberExpr(Clauses), getOrderedNumberExpr(Clauses),
4630 AStmt, *this, *DSAStack, VarsWithImplicitDSA, B);
4631 if (NestedLoopCount == 0)
4634 assert((CurContext->isDependentContext() || B.builtAll()) &&
4635 "omp simd loop exprs were not built");
4637 if (!CurContext->isDependentContext()) {
4638 // Finalize the clauses that need pre-built expressions for CodeGen.
4639 for (auto C : Clauses) {
4640 if (auto *LC = dyn_cast<OMPLinearClause>(C))
4641 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
4642 B.NumIterations, *this, CurScope,
4648 if (checkSimdlenSafelenSpecified(*this, Clauses))
4651 getCurFunction()->setHasBranchProtectedScope();
4652 return OMPSimdDirective::Create(Context, StartLoc, EndLoc, NestedLoopCount,
4656 StmtResult Sema::ActOnOpenMPForDirective(
4657 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
4658 SourceLocation EndLoc,
4659 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
4663 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
4664 OMPLoopDirective::HelperExprs B;
4665 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
4666 // define the nested loops number.
4667 unsigned NestedLoopCount = CheckOpenMPLoop(
4668 OMPD_for, getCollapseNumberExpr(Clauses), getOrderedNumberExpr(Clauses),
4669 AStmt, *this, *DSAStack, VarsWithImplicitDSA, B);
4670 if (NestedLoopCount == 0)
4673 assert((CurContext->isDependentContext() || B.builtAll()) &&
4674 "omp for loop exprs were not built");
4676 if (!CurContext->isDependentContext()) {
4677 // Finalize the clauses that need pre-built expressions for CodeGen.
4678 for (auto C : Clauses) {
4679 if (auto *LC = dyn_cast<OMPLinearClause>(C))
4680 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
4681 B.NumIterations, *this, CurScope,
4687 getCurFunction()->setHasBranchProtectedScope();
4688 return OMPForDirective::Create(Context, StartLoc, EndLoc, NestedLoopCount,
4689 Clauses, AStmt, B, DSAStack->isCancelRegion());
4692 StmtResult Sema::ActOnOpenMPForSimdDirective(
4693 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
4694 SourceLocation EndLoc,
4695 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
4699 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
4700 OMPLoopDirective::HelperExprs B;
4701 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
4702 // define the nested loops number.
4703 unsigned NestedLoopCount =
4704 CheckOpenMPLoop(OMPD_for_simd, getCollapseNumberExpr(Clauses),
4705 getOrderedNumberExpr(Clauses), AStmt, *this, *DSAStack,
4706 VarsWithImplicitDSA, B);
4707 if (NestedLoopCount == 0)
4710 assert((CurContext->isDependentContext() || B.builtAll()) &&
4711 "omp for simd loop exprs were not built");
4713 if (!CurContext->isDependentContext()) {
4714 // Finalize the clauses that need pre-built expressions for CodeGen.
4715 for (auto C : Clauses) {
4716 if (auto *LC = dyn_cast<OMPLinearClause>(C))
4717 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
4718 B.NumIterations, *this, CurScope,
4724 if (checkSimdlenSafelenSpecified(*this, Clauses))
4727 getCurFunction()->setHasBranchProtectedScope();
4728 return OMPForSimdDirective::Create(Context, StartLoc, EndLoc, NestedLoopCount,
4732 StmtResult Sema::ActOnOpenMPSectionsDirective(ArrayRef<OMPClause *> Clauses,
4734 SourceLocation StartLoc,
4735 SourceLocation EndLoc) {
4739 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
4740 auto BaseStmt = AStmt;
4741 while (auto *CS = dyn_cast_or_null<CapturedStmt>(BaseStmt))
4742 BaseStmt = CS->getCapturedStmt();
4743 if (auto *C = dyn_cast_or_null<CompoundStmt>(BaseStmt)) {
4744 auto S = C->children();
4745 if (S.begin() == S.end())
4747 // All associated statements must be '#pragma omp section' except for
4749 for (Stmt *SectionStmt : llvm::make_range(std::next(S.begin()), S.end())) {
4750 if (!SectionStmt || !isa<OMPSectionDirective>(SectionStmt)) {
4752 Diag(SectionStmt->getLocStart(),
4753 diag::err_omp_sections_substmt_not_section);
4756 cast<OMPSectionDirective>(SectionStmt)
4757 ->setHasCancel(DSAStack->isCancelRegion());
4760 Diag(AStmt->getLocStart(), diag::err_omp_sections_not_compound_stmt);
4764 getCurFunction()->setHasBranchProtectedScope();
4766 return OMPSectionsDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt,
4767 DSAStack->isCancelRegion());
4770 StmtResult Sema::ActOnOpenMPSectionDirective(Stmt *AStmt,
4771 SourceLocation StartLoc,
4772 SourceLocation EndLoc) {
4776 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
4778 getCurFunction()->setHasBranchProtectedScope();
4779 DSAStack->setParentCancelRegion(DSAStack->isCancelRegion());
4781 return OMPSectionDirective::Create(Context, StartLoc, EndLoc, AStmt,
4782 DSAStack->isCancelRegion());
4785 StmtResult Sema::ActOnOpenMPSingleDirective(ArrayRef<OMPClause *> Clauses,
4787 SourceLocation StartLoc,
4788 SourceLocation EndLoc) {
4792 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
4794 getCurFunction()->setHasBranchProtectedScope();
4796 // OpenMP [2.7.3, single Construct, Restrictions]
4797 // The copyprivate clause must not be used with the nowait clause.
4798 OMPClause *Nowait = nullptr;
4799 OMPClause *Copyprivate = nullptr;
4800 for (auto *Clause : Clauses) {
4801 if (Clause->getClauseKind() == OMPC_nowait)
4803 else if (Clause->getClauseKind() == OMPC_copyprivate)
4804 Copyprivate = Clause;
4805 if (Copyprivate && Nowait) {
4806 Diag(Copyprivate->getLocStart(),
4807 diag::err_omp_single_copyprivate_with_nowait);
4808 Diag(Nowait->getLocStart(), diag::note_omp_nowait_clause_here);
4813 return OMPSingleDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt);
4816 StmtResult Sema::ActOnOpenMPMasterDirective(Stmt *AStmt,
4817 SourceLocation StartLoc,
4818 SourceLocation EndLoc) {
4822 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
4824 getCurFunction()->setHasBranchProtectedScope();
4826 return OMPMasterDirective::Create(Context, StartLoc, EndLoc, AStmt);
4829 StmtResult Sema::ActOnOpenMPCriticalDirective(
4830 const DeclarationNameInfo &DirName, ArrayRef<OMPClause *> Clauses,
4831 Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc) {
4835 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
4837 bool ErrorFound = false;
4839 SourceLocation HintLoc;
4840 bool DependentHint = false;
4841 for (auto *C : Clauses) {
4842 if (C->getClauseKind() == OMPC_hint) {
4843 if (!DirName.getName()) {
4844 Diag(C->getLocStart(), diag::err_omp_hint_clause_no_name);
4847 Expr *E = cast<OMPHintClause>(C)->getHint();
4848 if (E->isTypeDependent() || E->isValueDependent() ||
4849 E->isInstantiationDependent())
4850 DependentHint = true;
4852 Hint = E->EvaluateKnownConstInt(Context);
4853 HintLoc = C->getLocStart();
4859 auto Pair = DSAStack->getCriticalWithHint(DirName);
4860 if (Pair.first && DirName.getName() && !DependentHint) {
4861 if (llvm::APSInt::compareValues(Hint, Pair.second) != 0) {
4862 Diag(StartLoc, diag::err_omp_critical_with_hint);
4863 if (HintLoc.isValid()) {
4864 Diag(HintLoc, diag::note_omp_critical_hint_here)
4865 << 0 << Hint.toString(/*Radix=*/10, /*Signed=*/false);
4867 Diag(StartLoc, diag::note_omp_critical_no_hint) << 0;
4868 if (auto *C = Pair.first->getSingleClause<OMPHintClause>()) {
4869 Diag(C->getLocStart(), diag::note_omp_critical_hint_here)
4871 << C->getHint()->EvaluateKnownConstInt(Context).toString(
4872 /*Radix=*/10, /*Signed=*/false);
4874 Diag(Pair.first->getLocStart(), diag::note_omp_critical_no_hint) << 1;
4878 getCurFunction()->setHasBranchProtectedScope();
4880 auto *Dir = OMPCriticalDirective::Create(Context, DirName, StartLoc, EndLoc,
4882 if (!Pair.first && DirName.getName() && !DependentHint)
4883 DSAStack->addCriticalWithHint(Dir, Hint);
4887 StmtResult Sema::ActOnOpenMPParallelForDirective(
4888 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
4889 SourceLocation EndLoc,
4890 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
4894 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
4895 // 1.2.2 OpenMP Language Terminology
4896 // Structured block - An executable statement with a single entry at the
4897 // top and a single exit at the bottom.
4898 // The point of exit cannot be a branch out of the structured block.
4899 // longjmp() and throw() must not violate the entry/exit criteria.
4900 CS->getCapturedDecl()->setNothrow();
4902 OMPLoopDirective::HelperExprs B;
4903 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
4904 // define the nested loops number.
4905 unsigned NestedLoopCount =
4906 CheckOpenMPLoop(OMPD_parallel_for, getCollapseNumberExpr(Clauses),
4907 getOrderedNumberExpr(Clauses), AStmt, *this, *DSAStack,
4908 VarsWithImplicitDSA, B);
4909 if (NestedLoopCount == 0)
4912 assert((CurContext->isDependentContext() || B.builtAll()) &&
4913 "omp parallel for loop exprs were not built");
4915 if (!CurContext->isDependentContext()) {
4916 // Finalize the clauses that need pre-built expressions for CodeGen.
4917 for (auto C : Clauses) {
4918 if (auto *LC = dyn_cast<OMPLinearClause>(C))
4919 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
4920 B.NumIterations, *this, CurScope,
4926 getCurFunction()->setHasBranchProtectedScope();
4927 return OMPParallelForDirective::Create(Context, StartLoc, EndLoc,
4928 NestedLoopCount, Clauses, AStmt, B,
4929 DSAStack->isCancelRegion());
4932 StmtResult Sema::ActOnOpenMPParallelForSimdDirective(
4933 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
4934 SourceLocation EndLoc,
4935 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
4939 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
4940 // 1.2.2 OpenMP Language Terminology
4941 // Structured block - An executable statement with a single entry at the
4942 // top and a single exit at the bottom.
4943 // The point of exit cannot be a branch out of the structured block.
4944 // longjmp() and throw() must not violate the entry/exit criteria.
4945 CS->getCapturedDecl()->setNothrow();
4947 OMPLoopDirective::HelperExprs B;
4948 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
4949 // define the nested loops number.
4950 unsigned NestedLoopCount =
4951 CheckOpenMPLoop(OMPD_parallel_for_simd, getCollapseNumberExpr(Clauses),
4952 getOrderedNumberExpr(Clauses), AStmt, *this, *DSAStack,
4953 VarsWithImplicitDSA, B);
4954 if (NestedLoopCount == 0)
4957 if (!CurContext->isDependentContext()) {
4958 // Finalize the clauses that need pre-built expressions for CodeGen.
4959 for (auto C : Clauses) {
4960 if (auto *LC = dyn_cast<OMPLinearClause>(C))
4961 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
4962 B.NumIterations, *this, CurScope,
4968 if (checkSimdlenSafelenSpecified(*this, Clauses))
4971 getCurFunction()->setHasBranchProtectedScope();
4972 return OMPParallelForSimdDirective::Create(
4973 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
4977 Sema::ActOnOpenMPParallelSectionsDirective(ArrayRef<OMPClause *> Clauses,
4978 Stmt *AStmt, SourceLocation StartLoc,
4979 SourceLocation EndLoc) {
4983 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
4984 auto BaseStmt = AStmt;
4985 while (auto *CS = dyn_cast_or_null<CapturedStmt>(BaseStmt))
4986 BaseStmt = CS->getCapturedStmt();
4987 if (auto *C = dyn_cast_or_null<CompoundStmt>(BaseStmt)) {
4988 auto S = C->children();
4989 if (S.begin() == S.end())
4991 // All associated statements must be '#pragma omp section' except for
4993 for (Stmt *SectionStmt : llvm::make_range(std::next(S.begin()), S.end())) {
4994 if (!SectionStmt || !isa<OMPSectionDirective>(SectionStmt)) {
4996 Diag(SectionStmt->getLocStart(),
4997 diag::err_omp_parallel_sections_substmt_not_section);
5000 cast<OMPSectionDirective>(SectionStmt)
5001 ->setHasCancel(DSAStack->isCancelRegion());
5004 Diag(AStmt->getLocStart(),
5005 diag::err_omp_parallel_sections_not_compound_stmt);
5009 getCurFunction()->setHasBranchProtectedScope();
5011 return OMPParallelSectionsDirective::Create(
5012 Context, StartLoc, EndLoc, Clauses, AStmt, DSAStack->isCancelRegion());
5015 StmtResult Sema::ActOnOpenMPTaskDirective(ArrayRef<OMPClause *> Clauses,
5016 Stmt *AStmt, SourceLocation StartLoc,
5017 SourceLocation EndLoc) {
5021 auto *CS = cast<CapturedStmt>(AStmt);
5022 // 1.2.2 OpenMP Language Terminology
5023 // Structured block - An executable statement with a single entry at the
5024 // top and a single exit at the bottom.
5025 // The point of exit cannot be a branch out of the structured block.
5026 // longjmp() and throw() must not violate the entry/exit criteria.
5027 CS->getCapturedDecl()->setNothrow();
5029 getCurFunction()->setHasBranchProtectedScope();
5031 return OMPTaskDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt,
5032 DSAStack->isCancelRegion());
5035 StmtResult Sema::ActOnOpenMPTaskyieldDirective(SourceLocation StartLoc,
5036 SourceLocation EndLoc) {
5037 return OMPTaskyieldDirective::Create(Context, StartLoc, EndLoc);
5040 StmtResult Sema::ActOnOpenMPBarrierDirective(SourceLocation StartLoc,
5041 SourceLocation EndLoc) {
5042 return OMPBarrierDirective::Create(Context, StartLoc, EndLoc);
5045 StmtResult Sema::ActOnOpenMPTaskwaitDirective(SourceLocation StartLoc,
5046 SourceLocation EndLoc) {
5047 return OMPTaskwaitDirective::Create(Context, StartLoc, EndLoc);
5050 StmtResult Sema::ActOnOpenMPTaskgroupDirective(Stmt *AStmt,
5051 SourceLocation StartLoc,
5052 SourceLocation EndLoc) {
5056 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
5058 getCurFunction()->setHasBranchProtectedScope();
5060 return OMPTaskgroupDirective::Create(Context, StartLoc, EndLoc, AStmt);
5063 StmtResult Sema::ActOnOpenMPFlushDirective(ArrayRef<OMPClause *> Clauses,
5064 SourceLocation StartLoc,
5065 SourceLocation EndLoc) {
5066 assert(Clauses.size() <= 1 && "Extra clauses in flush directive");
5067 return OMPFlushDirective::Create(Context, StartLoc, EndLoc, Clauses);
5070 StmtResult Sema::ActOnOpenMPOrderedDirective(ArrayRef<OMPClause *> Clauses,
5072 SourceLocation StartLoc,
5073 SourceLocation EndLoc) {
5074 OMPClause *DependFound = nullptr;
5075 OMPClause *DependSourceClause = nullptr;
5076 OMPClause *DependSinkClause = nullptr;
5077 bool ErrorFound = false;
5078 OMPThreadsClause *TC = nullptr;
5079 OMPSIMDClause *SC = nullptr;
5080 for (auto *C : Clauses) {
5081 if (auto *DC = dyn_cast<OMPDependClause>(C)) {
5083 if (DC->getDependencyKind() == OMPC_DEPEND_source) {
5084 if (DependSourceClause) {
5085 Diag(C->getLocStart(), diag::err_omp_more_one_clause)
5086 << getOpenMPDirectiveName(OMPD_ordered)
5087 << getOpenMPClauseName(OMPC_depend) << 2;
5090 DependSourceClause = C;
5091 if (DependSinkClause) {
5092 Diag(C->getLocStart(), diag::err_omp_depend_sink_source_not_allowed)
5096 } else if (DC->getDependencyKind() == OMPC_DEPEND_sink) {
5097 if (DependSourceClause) {
5098 Diag(C->getLocStart(), diag::err_omp_depend_sink_source_not_allowed)
5102 DependSinkClause = C;
5104 } else if (C->getClauseKind() == OMPC_threads)
5105 TC = cast<OMPThreadsClause>(C);
5106 else if (C->getClauseKind() == OMPC_simd)
5107 SC = cast<OMPSIMDClause>(C);
5109 if (!ErrorFound && !SC &&
5110 isOpenMPSimdDirective(DSAStack->getParentDirective())) {
5111 // OpenMP [2.8.1,simd Construct, Restrictions]
5112 // An ordered construct with the simd clause is the only OpenMP construct
5113 // that can appear in the simd region.
5114 Diag(StartLoc, diag::err_omp_prohibited_region_simd);
5116 } else if (DependFound && (TC || SC)) {
5117 Diag(DependFound->getLocStart(), diag::err_omp_depend_clause_thread_simd)
5118 << getOpenMPClauseName(TC ? TC->getClauseKind() : SC->getClauseKind());
5120 } else if (DependFound && !DSAStack->getParentOrderedRegionParam()) {
5121 Diag(DependFound->getLocStart(),
5122 diag::err_omp_ordered_directive_without_param);
5124 } else if (TC || Clauses.empty()) {
5125 if (auto *Param = DSAStack->getParentOrderedRegionParam()) {
5126 SourceLocation ErrLoc = TC ? TC->getLocStart() : StartLoc;
5127 Diag(ErrLoc, diag::err_omp_ordered_directive_with_param)
5129 Diag(Param->getLocStart(), diag::note_omp_ordered_param);
5133 if ((!AStmt && !DependFound) || ErrorFound)
5137 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
5139 getCurFunction()->setHasBranchProtectedScope();
5142 return OMPOrderedDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt);
5146 /// \brief Helper class for checking expression in 'omp atomic [update]'
5148 class OpenMPAtomicUpdateChecker {
5149 /// \brief Error results for atomic update expressions.
5150 enum ExprAnalysisErrorCode {
5151 /// \brief A statement is not an expression statement.
5153 /// \brief Expression is not builtin binary or unary operation.
5154 NotABinaryOrUnaryExpression,
5155 /// \brief Unary operation is not post-/pre- increment/decrement operation.
5156 NotAnUnaryIncDecExpression,
5157 /// \brief An expression is not of scalar type.
5159 /// \brief A binary operation is not an assignment operation.
5161 /// \brief RHS part of the binary operation is not a binary expression.
5162 NotABinaryExpression,
5163 /// \brief RHS part is not additive/multiplicative/shift/biwise binary
5166 /// \brief RHS binary operation does not have reference to the updated LHS
5168 NotAnUpdateExpression,
5169 /// \brief No errors is found.
5172 /// \brief Reference to Sema.
5174 /// \brief A location for note diagnostics (when error is found).
5175 SourceLocation NoteLoc;
5176 /// \brief 'x' lvalue part of the source atomic expression.
5178 /// \brief 'expr' rvalue part of the source atomic expression.
5180 /// \brief Helper expression of the form
5181 /// 'OpaqueValueExpr(x) binop OpaqueValueExpr(expr)' or
5182 /// 'OpaqueValueExpr(expr) binop OpaqueValueExpr(x)'.
5184 /// \brief Is 'x' a LHS in a RHS part of full update expression. It is
5185 /// important for non-associative operations.
5186 bool IsXLHSInRHSPart;
5187 BinaryOperatorKind Op;
5188 SourceLocation OpLoc;
5189 /// \brief true if the source expression is a postfix unary operation, false
5190 /// if it is a prefix unary operation.
5191 bool IsPostfixUpdate;
5194 OpenMPAtomicUpdateChecker(Sema &SemaRef)
5195 : SemaRef(SemaRef), X(nullptr), E(nullptr), UpdateExpr(nullptr),
5196 IsXLHSInRHSPart(false), Op(BO_PtrMemD), IsPostfixUpdate(false) {}
5197 /// \brief Check specified statement that it is suitable for 'atomic update'
5198 /// constructs and extract 'x', 'expr' and Operation from the original
5199 /// expression. If DiagId and NoteId == 0, then only check is performed
5200 /// without error notification.
5201 /// \param DiagId Diagnostic which should be emitted if error is found.
5202 /// \param NoteId Diagnostic note for the main error message.
5203 /// \return true if statement is not an update expression, false otherwise.
5204 bool checkStatement(Stmt *S, unsigned DiagId = 0, unsigned NoteId = 0);
5205 /// \brief Return the 'x' lvalue part of the source atomic expression.
5206 Expr *getX() const { return X; }
5207 /// \brief Return the 'expr' rvalue part of the source atomic expression.
5208 Expr *getExpr() const { return E; }
5209 /// \brief Return the update expression used in calculation of the updated
5210 /// value. Always has form 'OpaqueValueExpr(x) binop OpaqueValueExpr(expr)' or
5211 /// 'OpaqueValueExpr(expr) binop OpaqueValueExpr(x)'.
5212 Expr *getUpdateExpr() const { return UpdateExpr; }
5213 /// \brief Return true if 'x' is LHS in RHS part of full update expression,
5214 /// false otherwise.
5215 bool isXLHSInRHSPart() const { return IsXLHSInRHSPart; }
5217 /// \brief true if the source expression is a postfix unary operation, false
5218 /// if it is a prefix unary operation.
5219 bool isPostfixUpdate() const { return IsPostfixUpdate; }
5222 bool checkBinaryOperation(BinaryOperator *AtomicBinOp, unsigned DiagId = 0,
5223 unsigned NoteId = 0);
5227 bool OpenMPAtomicUpdateChecker::checkBinaryOperation(
5228 BinaryOperator *AtomicBinOp, unsigned DiagId, unsigned NoteId) {
5229 ExprAnalysisErrorCode ErrorFound = NoError;
5230 SourceLocation ErrorLoc, NoteLoc;
5231 SourceRange ErrorRange, NoteRange;
5232 // Allowed constructs are:
5233 // x = x binop expr;
5234 // x = expr binop x;
5235 if (AtomicBinOp->getOpcode() == BO_Assign) {
5236 X = AtomicBinOp->getLHS();
5237 if (auto *AtomicInnerBinOp = dyn_cast<BinaryOperator>(
5238 AtomicBinOp->getRHS()->IgnoreParenImpCasts())) {
5239 if (AtomicInnerBinOp->isMultiplicativeOp() ||
5240 AtomicInnerBinOp->isAdditiveOp() || AtomicInnerBinOp->isShiftOp() ||
5241 AtomicInnerBinOp->isBitwiseOp()) {
5242 Op = AtomicInnerBinOp->getOpcode();
5243 OpLoc = AtomicInnerBinOp->getOperatorLoc();
5244 auto *LHS = AtomicInnerBinOp->getLHS();
5245 auto *RHS = AtomicInnerBinOp->getRHS();
5246 llvm::FoldingSetNodeID XId, LHSId, RHSId;
5247 X->IgnoreParenImpCasts()->Profile(XId, SemaRef.getASTContext(),
5248 /*Canonical=*/true);
5249 LHS->IgnoreParenImpCasts()->Profile(LHSId, SemaRef.getASTContext(),
5250 /*Canonical=*/true);
5251 RHS->IgnoreParenImpCasts()->Profile(RHSId, SemaRef.getASTContext(),
5252 /*Canonical=*/true);
5255 IsXLHSInRHSPart = true;
5256 } else if (XId == RHSId) {
5258 IsXLHSInRHSPart = false;
5260 ErrorLoc = AtomicInnerBinOp->getExprLoc();
5261 ErrorRange = AtomicInnerBinOp->getSourceRange();
5262 NoteLoc = X->getExprLoc();
5263 NoteRange = X->getSourceRange();
5264 ErrorFound = NotAnUpdateExpression;
5267 ErrorLoc = AtomicInnerBinOp->getExprLoc();
5268 ErrorRange = AtomicInnerBinOp->getSourceRange();
5269 NoteLoc = AtomicInnerBinOp->getOperatorLoc();
5270 NoteRange = SourceRange(NoteLoc, NoteLoc);
5271 ErrorFound = NotABinaryOperator;
5274 NoteLoc = ErrorLoc = AtomicBinOp->getRHS()->getExprLoc();
5275 NoteRange = ErrorRange = AtomicBinOp->getRHS()->getSourceRange();
5276 ErrorFound = NotABinaryExpression;
5279 ErrorLoc = AtomicBinOp->getExprLoc();
5280 ErrorRange = AtomicBinOp->getSourceRange();
5281 NoteLoc = AtomicBinOp->getOperatorLoc();
5282 NoteRange = SourceRange(NoteLoc, NoteLoc);
5283 ErrorFound = NotAnAssignmentOp;
5285 if (ErrorFound != NoError && DiagId != 0 && NoteId != 0) {
5286 SemaRef.Diag(ErrorLoc, DiagId) << ErrorRange;
5287 SemaRef.Diag(NoteLoc, NoteId) << ErrorFound << NoteRange;
5289 } else if (SemaRef.CurContext->isDependentContext())
5290 E = X = UpdateExpr = nullptr;
5291 return ErrorFound != NoError;
5294 bool OpenMPAtomicUpdateChecker::checkStatement(Stmt *S, unsigned DiagId,
5296 ExprAnalysisErrorCode ErrorFound = NoError;
5297 SourceLocation ErrorLoc, NoteLoc;
5298 SourceRange ErrorRange, NoteRange;
5299 // Allowed constructs are:
5305 // x = x binop expr;
5306 // x = expr binop x;
5307 if (auto *AtomicBody = dyn_cast<Expr>(S)) {
5308 AtomicBody = AtomicBody->IgnoreParenImpCasts();
5309 if (AtomicBody->getType()->isScalarType() ||
5310 AtomicBody->isInstantiationDependent()) {
5311 if (auto *AtomicCompAssignOp = dyn_cast<CompoundAssignOperator>(
5312 AtomicBody->IgnoreParenImpCasts())) {
5313 // Check for Compound Assignment Operation
5314 Op = BinaryOperator::getOpForCompoundAssignment(
5315 AtomicCompAssignOp->getOpcode());
5316 OpLoc = AtomicCompAssignOp->getOperatorLoc();
5317 E = AtomicCompAssignOp->getRHS();
5318 X = AtomicCompAssignOp->getLHS()->IgnoreParens();
5319 IsXLHSInRHSPart = true;
5320 } else if (auto *AtomicBinOp = dyn_cast<BinaryOperator>(
5321 AtomicBody->IgnoreParenImpCasts())) {
5322 // Check for Binary Operation
5323 if (checkBinaryOperation(AtomicBinOp, DiagId, NoteId))
5325 } else if (auto *AtomicUnaryOp = dyn_cast<UnaryOperator>(
5326 AtomicBody->IgnoreParenImpCasts())) {
5327 // Check for Unary Operation
5328 if (AtomicUnaryOp->isIncrementDecrementOp()) {
5329 IsPostfixUpdate = AtomicUnaryOp->isPostfix();
5330 Op = AtomicUnaryOp->isIncrementOp() ? BO_Add : BO_Sub;
5331 OpLoc = AtomicUnaryOp->getOperatorLoc();
5332 X = AtomicUnaryOp->getSubExpr()->IgnoreParens();
5333 E = SemaRef.ActOnIntegerConstant(OpLoc, /*uint64_t Val=*/1).get();
5334 IsXLHSInRHSPart = true;
5336 ErrorFound = NotAnUnaryIncDecExpression;
5337 ErrorLoc = AtomicUnaryOp->getExprLoc();
5338 ErrorRange = AtomicUnaryOp->getSourceRange();
5339 NoteLoc = AtomicUnaryOp->getOperatorLoc();
5340 NoteRange = SourceRange(NoteLoc, NoteLoc);
5342 } else if (!AtomicBody->isInstantiationDependent()) {
5343 ErrorFound = NotABinaryOrUnaryExpression;
5344 NoteLoc = ErrorLoc = AtomicBody->getExprLoc();
5345 NoteRange = ErrorRange = AtomicBody->getSourceRange();
5348 ErrorFound = NotAScalarType;
5349 NoteLoc = ErrorLoc = AtomicBody->getLocStart();
5350 NoteRange = ErrorRange = SourceRange(NoteLoc, NoteLoc);
5353 ErrorFound = NotAnExpression;
5354 NoteLoc = ErrorLoc = S->getLocStart();
5355 NoteRange = ErrorRange = SourceRange(NoteLoc, NoteLoc);
5357 if (ErrorFound != NoError && DiagId != 0 && NoteId != 0) {
5358 SemaRef.Diag(ErrorLoc, DiagId) << ErrorRange;
5359 SemaRef.Diag(NoteLoc, NoteId) << ErrorFound << NoteRange;
5361 } else if (SemaRef.CurContext->isDependentContext())
5362 E = X = UpdateExpr = nullptr;
5363 if (ErrorFound == NoError && E && X) {
5364 // Build an update expression of form 'OpaqueValueExpr(x) binop
5365 // OpaqueValueExpr(expr)' or 'OpaqueValueExpr(expr) binop
5366 // OpaqueValueExpr(x)' and then cast it to the type of the 'x' expression.
5367 auto *OVEX = new (SemaRef.getASTContext())
5368 OpaqueValueExpr(X->getExprLoc(), X->getType(), VK_RValue);
5369 auto *OVEExpr = new (SemaRef.getASTContext())
5370 OpaqueValueExpr(E->getExprLoc(), E->getType(), VK_RValue);
5372 SemaRef.CreateBuiltinBinOp(OpLoc, Op, IsXLHSInRHSPart ? OVEX : OVEExpr,
5373 IsXLHSInRHSPart ? OVEExpr : OVEX);
5374 if (Update.isInvalid())
5376 Update = SemaRef.PerformImplicitConversion(Update.get(), X->getType(),
5378 if (Update.isInvalid())
5380 UpdateExpr = Update.get();
5382 return ErrorFound != NoError;
5385 StmtResult Sema::ActOnOpenMPAtomicDirective(ArrayRef<OMPClause *> Clauses,
5387 SourceLocation StartLoc,
5388 SourceLocation EndLoc) {
5392 auto *CS = cast<CapturedStmt>(AStmt);
5393 // 1.2.2 OpenMP Language Terminology
5394 // Structured block - An executable statement with a single entry at the
5395 // top and a single exit at the bottom.
5396 // The point of exit cannot be a branch out of the structured block.
5397 // longjmp() and throw() must not violate the entry/exit criteria.
5398 OpenMPClauseKind AtomicKind = OMPC_unknown;
5399 SourceLocation AtomicKindLoc;
5400 for (auto *C : Clauses) {
5401 if (C->getClauseKind() == OMPC_read || C->getClauseKind() == OMPC_write ||
5402 C->getClauseKind() == OMPC_update ||
5403 C->getClauseKind() == OMPC_capture) {
5404 if (AtomicKind != OMPC_unknown) {
5405 Diag(C->getLocStart(), diag::err_omp_atomic_several_clauses)
5406 << SourceRange(C->getLocStart(), C->getLocEnd());
5407 Diag(AtomicKindLoc, diag::note_omp_atomic_previous_clause)
5408 << getOpenMPClauseName(AtomicKind);
5410 AtomicKind = C->getClauseKind();
5411 AtomicKindLoc = C->getLocStart();
5416 auto Body = CS->getCapturedStmt();
5417 if (auto *EWC = dyn_cast<ExprWithCleanups>(Body))
5418 Body = EWC->getSubExpr();
5424 bool IsXLHSInRHSPart = false;
5425 bool IsPostfixUpdate = false;
5426 // OpenMP [2.12.6, atomic Construct]
5427 // In the next expressions:
5428 // * x and v (as applicable) are both l-value expressions with scalar type.
5429 // * During the execution of an atomic region, multiple syntactic
5430 // occurrences of x must designate the same storage location.
5431 // * Neither of v and expr (as applicable) may access the storage location
5433 // * Neither of x and expr (as applicable) may access the storage location
5435 // * expr is an expression with scalar type.
5436 // * binop is one of +, *, -, /, &, ^, |, <<, or >>.
5437 // * binop, binop=, ++, and -- are not overloaded operators.
5438 // * The expression x binop expr must be numerically equivalent to x binop
5439 // (expr). This requirement is satisfied if the operators in expr have
5440 // precedence greater than binop, or by using parentheses around expr or
5441 // subexpressions of expr.
5442 // * The expression expr binop x must be numerically equivalent to (expr)
5443 // binop x. This requirement is satisfied if the operators in expr have
5444 // precedence equal to or greater than binop, or by using parentheses around
5445 // expr or subexpressions of expr.
5446 // * For forms that allow multiple occurrences of x, the number of times
5447 // that x is evaluated is unspecified.
5448 if (AtomicKind == OMPC_read) {
5455 } ErrorFound = NoError;
5456 SourceLocation ErrorLoc, NoteLoc;
5457 SourceRange ErrorRange, NoteRange;
5458 // If clause is read:
5460 if (auto *AtomicBody = dyn_cast<Expr>(Body)) {
5462 dyn_cast<BinaryOperator>(AtomicBody->IgnoreParenImpCasts());
5463 if (AtomicBinOp && AtomicBinOp->getOpcode() == BO_Assign) {
5464 X = AtomicBinOp->getRHS()->IgnoreParenImpCasts();
5465 V = AtomicBinOp->getLHS()->IgnoreParenImpCasts();
5466 if ((X->isInstantiationDependent() || X->getType()->isScalarType()) &&
5467 (V->isInstantiationDependent() || V->getType()->isScalarType())) {
5468 if (!X->isLValue() || !V->isLValue()) {
5469 auto NotLValueExpr = X->isLValue() ? V : X;
5470 ErrorFound = NotAnLValue;
5471 ErrorLoc = AtomicBinOp->getExprLoc();
5472 ErrorRange = AtomicBinOp->getSourceRange();
5473 NoteLoc = NotLValueExpr->getExprLoc();
5474 NoteRange = NotLValueExpr->getSourceRange();
5476 } else if (!X->isInstantiationDependent() ||
5477 !V->isInstantiationDependent()) {
5478 auto NotScalarExpr =
5479 (X->isInstantiationDependent() || X->getType()->isScalarType())
5482 ErrorFound = NotAScalarType;
5483 ErrorLoc = AtomicBinOp->getExprLoc();
5484 ErrorRange = AtomicBinOp->getSourceRange();
5485 NoteLoc = NotScalarExpr->getExprLoc();
5486 NoteRange = NotScalarExpr->getSourceRange();
5488 } else if (!AtomicBody->isInstantiationDependent()) {
5489 ErrorFound = NotAnAssignmentOp;
5490 ErrorLoc = AtomicBody->getExprLoc();
5491 ErrorRange = AtomicBody->getSourceRange();
5492 NoteLoc = AtomicBinOp ? AtomicBinOp->getOperatorLoc()
5493 : AtomicBody->getExprLoc();
5494 NoteRange = AtomicBinOp ? AtomicBinOp->getSourceRange()
5495 : AtomicBody->getSourceRange();
5498 ErrorFound = NotAnExpression;
5499 NoteLoc = ErrorLoc = Body->getLocStart();
5500 NoteRange = ErrorRange = SourceRange(NoteLoc, NoteLoc);
5502 if (ErrorFound != NoError) {
5503 Diag(ErrorLoc, diag::err_omp_atomic_read_not_expression_statement)
5505 Diag(NoteLoc, diag::note_omp_atomic_read_write) << ErrorFound
5508 } else if (CurContext->isDependentContext())
5510 } else if (AtomicKind == OMPC_write) {
5517 } ErrorFound = NoError;
5518 SourceLocation ErrorLoc, NoteLoc;
5519 SourceRange ErrorRange, NoteRange;
5520 // If clause is write:
5522 if (auto *AtomicBody = dyn_cast<Expr>(Body)) {
5524 dyn_cast<BinaryOperator>(AtomicBody->IgnoreParenImpCasts());
5525 if (AtomicBinOp && AtomicBinOp->getOpcode() == BO_Assign) {
5526 X = AtomicBinOp->getLHS();
5527 E = AtomicBinOp->getRHS();
5528 if ((X->isInstantiationDependent() || X->getType()->isScalarType()) &&
5529 (E->isInstantiationDependent() || E->getType()->isScalarType())) {
5530 if (!X->isLValue()) {
5531 ErrorFound = NotAnLValue;
5532 ErrorLoc = AtomicBinOp->getExprLoc();
5533 ErrorRange = AtomicBinOp->getSourceRange();
5534 NoteLoc = X->getExprLoc();
5535 NoteRange = X->getSourceRange();
5537 } else if (!X->isInstantiationDependent() ||
5538 !E->isInstantiationDependent()) {
5539 auto NotScalarExpr =
5540 (X->isInstantiationDependent() || X->getType()->isScalarType())
5543 ErrorFound = NotAScalarType;
5544 ErrorLoc = AtomicBinOp->getExprLoc();
5545 ErrorRange = AtomicBinOp->getSourceRange();
5546 NoteLoc = NotScalarExpr->getExprLoc();
5547 NoteRange = NotScalarExpr->getSourceRange();
5549 } else if (!AtomicBody->isInstantiationDependent()) {
5550 ErrorFound = NotAnAssignmentOp;
5551 ErrorLoc = AtomicBody->getExprLoc();
5552 ErrorRange = AtomicBody->getSourceRange();
5553 NoteLoc = AtomicBinOp ? AtomicBinOp->getOperatorLoc()
5554 : AtomicBody->getExprLoc();
5555 NoteRange = AtomicBinOp ? AtomicBinOp->getSourceRange()
5556 : AtomicBody->getSourceRange();
5559 ErrorFound = NotAnExpression;
5560 NoteLoc = ErrorLoc = Body->getLocStart();
5561 NoteRange = ErrorRange = SourceRange(NoteLoc, NoteLoc);
5563 if (ErrorFound != NoError) {
5564 Diag(ErrorLoc, diag::err_omp_atomic_write_not_expression_statement)
5566 Diag(NoteLoc, diag::note_omp_atomic_read_write) << ErrorFound
5569 } else if (CurContext->isDependentContext())
5571 } else if (AtomicKind == OMPC_update || AtomicKind == OMPC_unknown) {
5572 // If clause is update:
5578 // x = x binop expr;
5579 // x = expr binop x;
5580 OpenMPAtomicUpdateChecker Checker(*this);
5581 if (Checker.checkStatement(
5582 Body, (AtomicKind == OMPC_update)
5583 ? diag::err_omp_atomic_update_not_expression_statement
5584 : diag::err_omp_atomic_not_expression_statement,
5585 diag::note_omp_atomic_update))
5587 if (!CurContext->isDependentContext()) {
5588 E = Checker.getExpr();
5590 UE = Checker.getUpdateExpr();
5591 IsXLHSInRHSPart = Checker.isXLHSInRHSPart();
5593 } else if (AtomicKind == OMPC_capture) {
5596 NotACompoundStatement,
5597 NotTwoSubstatements,
5598 NotASpecificExpression,
5600 } ErrorFound = NoError;
5601 SourceLocation ErrorLoc, NoteLoc;
5602 SourceRange ErrorRange, NoteRange;
5603 if (auto *AtomicBody = dyn_cast<Expr>(Body)) {
5604 // If clause is a capture:
5609 // v = x binop= expr;
5610 // v = x = x binop expr;
5611 // v = x = expr binop x;
5613 dyn_cast<BinaryOperator>(AtomicBody->IgnoreParenImpCasts());
5614 if (AtomicBinOp && AtomicBinOp->getOpcode() == BO_Assign) {
5615 V = AtomicBinOp->getLHS();
5616 Body = AtomicBinOp->getRHS()->IgnoreParenImpCasts();
5617 OpenMPAtomicUpdateChecker Checker(*this);
5618 if (Checker.checkStatement(
5619 Body, diag::err_omp_atomic_capture_not_expression_statement,
5620 diag::note_omp_atomic_update))
5622 E = Checker.getExpr();
5624 UE = Checker.getUpdateExpr();
5625 IsXLHSInRHSPart = Checker.isXLHSInRHSPart();
5626 IsPostfixUpdate = Checker.isPostfixUpdate();
5627 } else if (!AtomicBody->isInstantiationDependent()) {
5628 ErrorLoc = AtomicBody->getExprLoc();
5629 ErrorRange = AtomicBody->getSourceRange();
5630 NoteLoc = AtomicBinOp ? AtomicBinOp->getOperatorLoc()
5631 : AtomicBody->getExprLoc();
5632 NoteRange = AtomicBinOp ? AtomicBinOp->getSourceRange()
5633 : AtomicBody->getSourceRange();
5634 ErrorFound = NotAnAssignmentOp;
5636 if (ErrorFound != NoError) {
5637 Diag(ErrorLoc, diag::err_omp_atomic_capture_not_expression_statement)
5639 Diag(NoteLoc, diag::note_omp_atomic_capture) << ErrorFound << NoteRange;
5641 } else if (CurContext->isDependentContext()) {
5642 UE = V = E = X = nullptr;
5645 // If clause is a capture:
5646 // { v = x; x = expr; }
5651 // { v = x; x binop= expr; }
5652 // { v = x; x = x binop expr; }
5653 // { v = x; x = expr binop x; }
5658 // { x binop= expr; v = x; }
5659 // { x = x binop expr; v = x; }
5660 // { x = expr binop x; v = x; }
5661 if (auto *CS = dyn_cast<CompoundStmt>(Body)) {
5662 // Check that this is { expr1; expr2; }
5663 if (CS->size() == 2) {
5664 auto *First = CS->body_front();
5665 auto *Second = CS->body_back();
5666 if (auto *EWC = dyn_cast<ExprWithCleanups>(First))
5667 First = EWC->getSubExpr()->IgnoreParenImpCasts();
5668 if (auto *EWC = dyn_cast<ExprWithCleanups>(Second))
5669 Second = EWC->getSubExpr()->IgnoreParenImpCasts();
5670 // Need to find what subexpression is 'v' and what is 'x'.
5671 OpenMPAtomicUpdateChecker Checker(*this);
5672 bool IsUpdateExprFound = !Checker.checkStatement(Second);
5673 BinaryOperator *BinOp = nullptr;
5674 if (IsUpdateExprFound) {
5675 BinOp = dyn_cast<BinaryOperator>(First);
5676 IsUpdateExprFound = BinOp && BinOp->getOpcode() == BO_Assign;
5678 if (IsUpdateExprFound && !CurContext->isDependentContext()) {
5683 // { v = x; x binop= expr; }
5684 // { v = x; x = x binop expr; }
5685 // { v = x; x = expr binop x; }
5686 // Check that the first expression has form v = x.
5687 auto *PossibleX = BinOp->getRHS()->IgnoreParenImpCasts();
5688 llvm::FoldingSetNodeID XId, PossibleXId;
5689 Checker.getX()->Profile(XId, Context, /*Canonical=*/true);
5690 PossibleX->Profile(PossibleXId, Context, /*Canonical=*/true);
5691 IsUpdateExprFound = XId == PossibleXId;
5692 if (IsUpdateExprFound) {
5693 V = BinOp->getLHS();
5695 E = Checker.getExpr();
5696 UE = Checker.getUpdateExpr();
5697 IsXLHSInRHSPart = Checker.isXLHSInRHSPart();
5698 IsPostfixUpdate = true;
5701 if (!IsUpdateExprFound) {
5702 IsUpdateExprFound = !Checker.checkStatement(First);
5704 if (IsUpdateExprFound) {
5705 BinOp = dyn_cast<BinaryOperator>(Second);
5706 IsUpdateExprFound = BinOp && BinOp->getOpcode() == BO_Assign;
5708 if (IsUpdateExprFound && !CurContext->isDependentContext()) {
5713 // { x binop= expr; v = x; }
5714 // { x = x binop expr; v = x; }
5715 // { x = expr binop x; v = x; }
5716 // Check that the second expression has form v = x.
5717 auto *PossibleX = BinOp->getRHS()->IgnoreParenImpCasts();
5718 llvm::FoldingSetNodeID XId, PossibleXId;
5719 Checker.getX()->Profile(XId, Context, /*Canonical=*/true);
5720 PossibleX->Profile(PossibleXId, Context, /*Canonical=*/true);
5721 IsUpdateExprFound = XId == PossibleXId;
5722 if (IsUpdateExprFound) {
5723 V = BinOp->getLHS();
5725 E = Checker.getExpr();
5726 UE = Checker.getUpdateExpr();
5727 IsXLHSInRHSPart = Checker.isXLHSInRHSPart();
5728 IsPostfixUpdate = false;
5732 if (!IsUpdateExprFound) {
5733 // { v = x; x = expr; }
5734 auto *FirstExpr = dyn_cast<Expr>(First);
5735 auto *SecondExpr = dyn_cast<Expr>(Second);
5736 if (!FirstExpr || !SecondExpr ||
5737 !(FirstExpr->isInstantiationDependent() ||
5738 SecondExpr->isInstantiationDependent())) {
5739 auto *FirstBinOp = dyn_cast<BinaryOperator>(First);
5740 if (!FirstBinOp || FirstBinOp->getOpcode() != BO_Assign) {
5741 ErrorFound = NotAnAssignmentOp;
5742 NoteLoc = ErrorLoc = FirstBinOp ? FirstBinOp->getOperatorLoc()
5743 : First->getLocStart();
5744 NoteRange = ErrorRange = FirstBinOp
5745 ? FirstBinOp->getSourceRange()
5746 : SourceRange(ErrorLoc, ErrorLoc);
5748 auto *SecondBinOp = dyn_cast<BinaryOperator>(Second);
5749 if (!SecondBinOp || SecondBinOp->getOpcode() != BO_Assign) {
5750 ErrorFound = NotAnAssignmentOp;
5751 NoteLoc = ErrorLoc = SecondBinOp
5752 ? SecondBinOp->getOperatorLoc()
5753 : Second->getLocStart();
5754 NoteRange = ErrorRange =
5755 SecondBinOp ? SecondBinOp->getSourceRange()
5756 : SourceRange(ErrorLoc, ErrorLoc);
5758 auto *PossibleXRHSInFirst =
5759 FirstBinOp->getRHS()->IgnoreParenImpCasts();
5760 auto *PossibleXLHSInSecond =
5761 SecondBinOp->getLHS()->IgnoreParenImpCasts();
5762 llvm::FoldingSetNodeID X1Id, X2Id;
5763 PossibleXRHSInFirst->Profile(X1Id, Context,
5764 /*Canonical=*/true);
5765 PossibleXLHSInSecond->Profile(X2Id, Context,
5766 /*Canonical=*/true);
5767 IsUpdateExprFound = X1Id == X2Id;
5768 if (IsUpdateExprFound) {
5769 V = FirstBinOp->getLHS();
5770 X = SecondBinOp->getLHS();
5771 E = SecondBinOp->getRHS();
5773 IsXLHSInRHSPart = false;
5774 IsPostfixUpdate = true;
5776 ErrorFound = NotASpecificExpression;
5777 ErrorLoc = FirstBinOp->getExprLoc();
5778 ErrorRange = FirstBinOp->getSourceRange();
5779 NoteLoc = SecondBinOp->getLHS()->getExprLoc();
5780 NoteRange = SecondBinOp->getRHS()->getSourceRange();
5787 NoteLoc = ErrorLoc = Body->getLocStart();
5788 NoteRange = ErrorRange =
5789 SourceRange(Body->getLocStart(), Body->getLocStart());
5790 ErrorFound = NotTwoSubstatements;
5793 NoteLoc = ErrorLoc = Body->getLocStart();
5794 NoteRange = ErrorRange =
5795 SourceRange(Body->getLocStart(), Body->getLocStart());
5796 ErrorFound = NotACompoundStatement;
5798 if (ErrorFound != NoError) {
5799 Diag(ErrorLoc, diag::err_omp_atomic_capture_not_compound_statement)
5801 Diag(NoteLoc, diag::note_omp_atomic_capture) << ErrorFound << NoteRange;
5803 } else if (CurContext->isDependentContext()) {
5804 UE = V = E = X = nullptr;
5809 getCurFunction()->setHasBranchProtectedScope();
5811 return OMPAtomicDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt,
5812 X, V, E, UE, IsXLHSInRHSPart,
5816 StmtResult Sema::ActOnOpenMPTargetDirective(ArrayRef<OMPClause *> Clauses,
5818 SourceLocation StartLoc,
5819 SourceLocation EndLoc) {
5823 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
5824 // 1.2.2 OpenMP Language Terminology
5825 // Structured block - An executable statement with a single entry at the
5826 // top and a single exit at the bottom.
5827 // The point of exit cannot be a branch out of the structured block.
5828 // longjmp() and throw() must not violate the entry/exit criteria.
5829 CS->getCapturedDecl()->setNothrow();
5831 // OpenMP [2.16, Nesting of Regions]
5832 // If specified, a teams construct must be contained within a target
5833 // construct. That target construct must contain no statements or directives
5834 // outside of the teams construct.
5835 if (DSAStack->hasInnerTeamsRegion()) {
5836 auto S = AStmt->IgnoreContainers(/*IgnoreCaptured*/ true);
5837 bool OMPTeamsFound = true;
5838 if (auto *CS = dyn_cast<CompoundStmt>(S)) {
5839 auto I = CS->body_begin();
5840 while (I != CS->body_end()) {
5841 auto *OED = dyn_cast<OMPExecutableDirective>(*I);
5842 if (!OED || !isOpenMPTeamsDirective(OED->getDirectiveKind())) {
5843 OMPTeamsFound = false;
5848 assert(I != CS->body_end() && "Not found statement");
5851 auto *OED = dyn_cast<OMPExecutableDirective>(S);
5852 OMPTeamsFound = OED && isOpenMPTeamsDirective(OED->getDirectiveKind());
5854 if (!OMPTeamsFound) {
5855 Diag(StartLoc, diag::err_omp_target_contains_not_only_teams);
5856 Diag(DSAStack->getInnerTeamsRegionLoc(),
5857 diag::note_omp_nested_teams_construct_here);
5858 Diag(S->getLocStart(), diag::note_omp_nested_statement_here)
5859 << isa<OMPExecutableDirective>(S);
5864 getCurFunction()->setHasBranchProtectedScope();
5866 return OMPTargetDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt);
5870 Sema::ActOnOpenMPTargetParallelDirective(ArrayRef<OMPClause *> Clauses,
5871 Stmt *AStmt, SourceLocation StartLoc,
5872 SourceLocation EndLoc) {
5876 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
5877 // 1.2.2 OpenMP Language Terminology
5878 // Structured block - An executable statement with a single entry at the
5879 // top and a single exit at the bottom.
5880 // The point of exit cannot be a branch out of the structured block.
5881 // longjmp() and throw() must not violate the entry/exit criteria.
5882 CS->getCapturedDecl()->setNothrow();
5884 getCurFunction()->setHasBranchProtectedScope();
5886 return OMPTargetParallelDirective::Create(Context, StartLoc, EndLoc, Clauses,
5890 StmtResult Sema::ActOnOpenMPTargetParallelForDirective(
5891 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
5892 SourceLocation EndLoc,
5893 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
5897 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
5898 // 1.2.2 OpenMP Language Terminology
5899 // Structured block - An executable statement with a single entry at the
5900 // top and a single exit at the bottom.
5901 // The point of exit cannot be a branch out of the structured block.
5902 // longjmp() and throw() must not violate the entry/exit criteria.
5903 CS->getCapturedDecl()->setNothrow();
5905 OMPLoopDirective::HelperExprs B;
5906 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
5907 // define the nested loops number.
5908 unsigned NestedLoopCount =
5909 CheckOpenMPLoop(OMPD_target_parallel_for, getCollapseNumberExpr(Clauses),
5910 getOrderedNumberExpr(Clauses), AStmt, *this, *DSAStack,
5911 VarsWithImplicitDSA, B);
5912 if (NestedLoopCount == 0)
5915 assert((CurContext->isDependentContext() || B.builtAll()) &&
5916 "omp target parallel for loop exprs were not built");
5918 if (!CurContext->isDependentContext()) {
5919 // Finalize the clauses that need pre-built expressions for CodeGen.
5920 for (auto C : Clauses) {
5921 if (auto *LC = dyn_cast<OMPLinearClause>(C))
5922 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
5923 B.NumIterations, *this, CurScope,
5929 getCurFunction()->setHasBranchProtectedScope();
5930 return OMPTargetParallelForDirective::Create(Context, StartLoc, EndLoc,
5931 NestedLoopCount, Clauses, AStmt,
5932 B, DSAStack->isCancelRegion());
5935 /// \brief Check for existence of a map clause in the list of clauses.
5936 static bool HasMapClause(ArrayRef<OMPClause *> Clauses) {
5937 for (ArrayRef<OMPClause *>::iterator I = Clauses.begin(), E = Clauses.end();
5939 if (*I != nullptr && (*I)->getClauseKind() == OMPC_map) {
5947 StmtResult Sema::ActOnOpenMPTargetDataDirective(ArrayRef<OMPClause *> Clauses,
5949 SourceLocation StartLoc,
5950 SourceLocation EndLoc) {
5954 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
5956 // OpenMP [2.10.1, Restrictions, p. 97]
5957 // At least one map clause must appear on the directive.
5958 if (!HasMapClause(Clauses)) {
5959 Diag(StartLoc, diag::err_omp_no_map_for_directive)
5960 << getOpenMPDirectiveName(OMPD_target_data);
5964 getCurFunction()->setHasBranchProtectedScope();
5966 return OMPTargetDataDirective::Create(Context, StartLoc, EndLoc, Clauses,
5971 Sema::ActOnOpenMPTargetEnterDataDirective(ArrayRef<OMPClause *> Clauses,
5972 SourceLocation StartLoc,
5973 SourceLocation EndLoc) {
5974 // OpenMP [2.10.2, Restrictions, p. 99]
5975 // At least one map clause must appear on the directive.
5976 if (!HasMapClause(Clauses)) {
5977 Diag(StartLoc, diag::err_omp_no_map_for_directive)
5978 << getOpenMPDirectiveName(OMPD_target_enter_data);
5982 return OMPTargetEnterDataDirective::Create(Context, StartLoc, EndLoc,
5987 Sema::ActOnOpenMPTargetExitDataDirective(ArrayRef<OMPClause *> Clauses,
5988 SourceLocation StartLoc,
5989 SourceLocation EndLoc) {
5990 // OpenMP [2.10.3, Restrictions, p. 102]
5991 // At least one map clause must appear on the directive.
5992 if (!HasMapClause(Clauses)) {
5993 Diag(StartLoc, diag::err_omp_no_map_for_directive)
5994 << getOpenMPDirectiveName(OMPD_target_exit_data);
5998 return OMPTargetExitDataDirective::Create(Context, StartLoc, EndLoc, Clauses);
6001 StmtResult Sema::ActOnOpenMPTargetUpdateDirective(ArrayRef<OMPClause *> Clauses,
6002 SourceLocation StartLoc,
6003 SourceLocation EndLoc) {
6004 bool seenMotionClause = false;
6005 for (auto *C : Clauses) {
6006 if (C->getClauseKind() == OMPC_to || C->getClauseKind() == OMPC_from)
6007 seenMotionClause = true;
6009 if (!seenMotionClause) {
6010 Diag(StartLoc, diag::err_omp_at_least_one_motion_clause_required);
6013 return OMPTargetUpdateDirective::Create(Context, StartLoc, EndLoc, Clauses);
6016 StmtResult Sema::ActOnOpenMPTeamsDirective(ArrayRef<OMPClause *> Clauses,
6017 Stmt *AStmt, SourceLocation StartLoc,
6018 SourceLocation EndLoc) {
6022 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
6023 // 1.2.2 OpenMP Language Terminology
6024 // Structured block - An executable statement with a single entry at the
6025 // top and a single exit at the bottom.
6026 // The point of exit cannot be a branch out of the structured block.
6027 // longjmp() and throw() must not violate the entry/exit criteria.
6028 CS->getCapturedDecl()->setNothrow();
6030 getCurFunction()->setHasBranchProtectedScope();
6032 return OMPTeamsDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt);
6036 Sema::ActOnOpenMPCancellationPointDirective(SourceLocation StartLoc,
6037 SourceLocation EndLoc,
6038 OpenMPDirectiveKind CancelRegion) {
6039 if (DSAStack->isParentNowaitRegion()) {
6040 Diag(StartLoc, diag::err_omp_parent_cancel_region_nowait) << 0;
6043 if (DSAStack->isParentOrderedRegion()) {
6044 Diag(StartLoc, diag::err_omp_parent_cancel_region_ordered) << 0;
6047 return OMPCancellationPointDirective::Create(Context, StartLoc, EndLoc,
6051 StmtResult Sema::ActOnOpenMPCancelDirective(ArrayRef<OMPClause *> Clauses,
6052 SourceLocation StartLoc,
6053 SourceLocation EndLoc,
6054 OpenMPDirectiveKind CancelRegion) {
6055 if (DSAStack->isParentNowaitRegion()) {
6056 Diag(StartLoc, diag::err_omp_parent_cancel_region_nowait) << 1;
6059 if (DSAStack->isParentOrderedRegion()) {
6060 Diag(StartLoc, diag::err_omp_parent_cancel_region_ordered) << 1;
6063 DSAStack->setParentCancelRegion(/*Cancel=*/true);
6064 return OMPCancelDirective::Create(Context, StartLoc, EndLoc, Clauses,
6068 static bool checkGrainsizeNumTasksClauses(Sema &S,
6069 ArrayRef<OMPClause *> Clauses) {
6070 OMPClause *PrevClause = nullptr;
6071 bool ErrorFound = false;
6072 for (auto *C : Clauses) {
6073 if (C->getClauseKind() == OMPC_grainsize ||
6074 C->getClauseKind() == OMPC_num_tasks) {
6077 else if (PrevClause->getClauseKind() != C->getClauseKind()) {
6078 S.Diag(C->getLocStart(),
6079 diag::err_omp_grainsize_num_tasks_mutually_exclusive)
6080 << getOpenMPClauseName(C->getClauseKind())
6081 << getOpenMPClauseName(PrevClause->getClauseKind());
6082 S.Diag(PrevClause->getLocStart(),
6083 diag::note_omp_previous_grainsize_num_tasks)
6084 << getOpenMPClauseName(PrevClause->getClauseKind());
6092 StmtResult Sema::ActOnOpenMPTaskLoopDirective(
6093 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
6094 SourceLocation EndLoc,
6095 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
6099 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
6100 OMPLoopDirective::HelperExprs B;
6101 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
6102 // define the nested loops number.
6103 unsigned NestedLoopCount =
6104 CheckOpenMPLoop(OMPD_taskloop, getCollapseNumberExpr(Clauses),
6105 /*OrderedLoopCountExpr=*/nullptr, AStmt, *this, *DSAStack,
6106 VarsWithImplicitDSA, B);
6107 if (NestedLoopCount == 0)
6110 assert((CurContext->isDependentContext() || B.builtAll()) &&
6111 "omp for loop exprs were not built");
6113 // OpenMP, [2.9.2 taskloop Construct, Restrictions]
6114 // The grainsize clause and num_tasks clause are mutually exclusive and may
6115 // not appear on the same taskloop directive.
6116 if (checkGrainsizeNumTasksClauses(*this, Clauses))
6119 getCurFunction()->setHasBranchProtectedScope();
6120 return OMPTaskLoopDirective::Create(Context, StartLoc, EndLoc,
6121 NestedLoopCount, Clauses, AStmt, B);
6124 StmtResult Sema::ActOnOpenMPTaskLoopSimdDirective(
6125 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
6126 SourceLocation EndLoc,
6127 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
6131 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
6132 OMPLoopDirective::HelperExprs B;
6133 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
6134 // define the nested loops number.
6135 unsigned NestedLoopCount =
6136 CheckOpenMPLoop(OMPD_taskloop_simd, getCollapseNumberExpr(Clauses),
6137 /*OrderedLoopCountExpr=*/nullptr, AStmt, *this, *DSAStack,
6138 VarsWithImplicitDSA, B);
6139 if (NestedLoopCount == 0)
6142 assert((CurContext->isDependentContext() || B.builtAll()) &&
6143 "omp for loop exprs were not built");
6145 if (!CurContext->isDependentContext()) {
6146 // Finalize the clauses that need pre-built expressions for CodeGen.
6147 for (auto C : Clauses) {
6148 if (auto *LC = dyn_cast<OMPLinearClause>(C))
6149 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
6150 B.NumIterations, *this, CurScope,
6156 // OpenMP, [2.9.2 taskloop Construct, Restrictions]
6157 // The grainsize clause and num_tasks clause are mutually exclusive and may
6158 // not appear on the same taskloop directive.
6159 if (checkGrainsizeNumTasksClauses(*this, Clauses))
6162 getCurFunction()->setHasBranchProtectedScope();
6163 return OMPTaskLoopSimdDirective::Create(Context, StartLoc, EndLoc,
6164 NestedLoopCount, Clauses, AStmt, B);
6167 StmtResult Sema::ActOnOpenMPDistributeDirective(
6168 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
6169 SourceLocation EndLoc,
6170 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
6174 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
6175 OMPLoopDirective::HelperExprs B;
6176 // In presence of clause 'collapse' with number of loops, it will
6177 // define the nested loops number.
6178 unsigned NestedLoopCount =
6179 CheckOpenMPLoop(OMPD_distribute, getCollapseNumberExpr(Clauses),
6180 nullptr /*ordered not a clause on distribute*/, AStmt,
6181 *this, *DSAStack, VarsWithImplicitDSA, B);
6182 if (NestedLoopCount == 0)
6185 assert((CurContext->isDependentContext() || B.builtAll()) &&
6186 "omp for loop exprs were not built");
6188 getCurFunction()->setHasBranchProtectedScope();
6189 return OMPDistributeDirective::Create(Context, StartLoc, EndLoc,
6190 NestedLoopCount, Clauses, AStmt, B);
6193 StmtResult Sema::ActOnOpenMPDistributeParallelForDirective(
6194 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
6195 SourceLocation EndLoc,
6196 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
6200 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
6201 // 1.2.2 OpenMP Language Terminology
6202 // Structured block - An executable statement with a single entry at the
6203 // top and a single exit at the bottom.
6204 // The point of exit cannot be a branch out of the structured block.
6205 // longjmp() and throw() must not violate the entry/exit criteria.
6206 CS->getCapturedDecl()->setNothrow();
6208 OMPLoopDirective::HelperExprs B;
6209 // In presence of clause 'collapse' with number of loops, it will
6210 // define the nested loops number.
6211 unsigned NestedLoopCount = CheckOpenMPLoop(
6212 OMPD_distribute_parallel_for, getCollapseNumberExpr(Clauses),
6213 nullptr /*ordered not a clause on distribute*/, AStmt, *this, *DSAStack,
6214 VarsWithImplicitDSA, B);
6215 if (NestedLoopCount == 0)
6218 assert((CurContext->isDependentContext() || B.builtAll()) &&
6219 "omp for loop exprs were not built");
6221 getCurFunction()->setHasBranchProtectedScope();
6222 return OMPDistributeParallelForDirective::Create(
6223 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
6226 StmtResult Sema::ActOnOpenMPDistributeParallelForSimdDirective(
6227 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
6228 SourceLocation EndLoc,
6229 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
6233 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
6234 // 1.2.2 OpenMP Language Terminology
6235 // Structured block - An executable statement with a single entry at the
6236 // top and a single exit at the bottom.
6237 // The point of exit cannot be a branch out of the structured block.
6238 // longjmp() and throw() must not violate the entry/exit criteria.
6239 CS->getCapturedDecl()->setNothrow();
6241 OMPLoopDirective::HelperExprs B;
6242 // In presence of clause 'collapse' with number of loops, it will
6243 // define the nested loops number.
6244 unsigned NestedLoopCount = CheckOpenMPLoop(
6245 OMPD_distribute_parallel_for_simd, getCollapseNumberExpr(Clauses),
6246 nullptr /*ordered not a clause on distribute*/, AStmt, *this, *DSAStack,
6247 VarsWithImplicitDSA, B);
6248 if (NestedLoopCount == 0)
6251 assert((CurContext->isDependentContext() || B.builtAll()) &&
6252 "omp for loop exprs were not built");
6254 if (checkSimdlenSafelenSpecified(*this, Clauses))
6257 getCurFunction()->setHasBranchProtectedScope();
6258 return OMPDistributeParallelForSimdDirective::Create(
6259 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
6262 StmtResult Sema::ActOnOpenMPDistributeSimdDirective(
6263 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
6264 SourceLocation EndLoc,
6265 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
6269 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
6270 // 1.2.2 OpenMP Language Terminology
6271 // Structured block - An executable statement with a single entry at the
6272 // top and a single exit at the bottom.
6273 // The point of exit cannot be a branch out of the structured block.
6274 // longjmp() and throw() must not violate the entry/exit criteria.
6275 CS->getCapturedDecl()->setNothrow();
6277 OMPLoopDirective::HelperExprs B;
6278 // In presence of clause 'collapse' with number of loops, it will
6279 // define the nested loops number.
6280 unsigned NestedLoopCount =
6281 CheckOpenMPLoop(OMPD_distribute_simd, getCollapseNumberExpr(Clauses),
6282 nullptr /*ordered not a clause on distribute*/, AStmt,
6283 *this, *DSAStack, VarsWithImplicitDSA, B);
6284 if (NestedLoopCount == 0)
6287 assert((CurContext->isDependentContext() || B.builtAll()) &&
6288 "omp for loop exprs were not built");
6290 if (checkSimdlenSafelenSpecified(*this, Clauses))
6293 getCurFunction()->setHasBranchProtectedScope();
6294 return OMPDistributeSimdDirective::Create(Context, StartLoc, EndLoc,
6295 NestedLoopCount, Clauses, AStmt, B);
6298 StmtResult Sema::ActOnOpenMPTargetParallelForSimdDirective(
6299 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
6300 SourceLocation EndLoc,
6301 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
6305 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
6306 // 1.2.2 OpenMP Language Terminology
6307 // Structured block - An executable statement with a single entry at the
6308 // top and a single exit at the bottom.
6309 // The point of exit cannot be a branch out of the structured block.
6310 // longjmp() and throw() must not violate the entry/exit criteria.
6311 CS->getCapturedDecl()->setNothrow();
6313 OMPLoopDirective::HelperExprs B;
6314 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
6315 // define the nested loops number.
6316 unsigned NestedLoopCount = CheckOpenMPLoop(
6317 OMPD_target_parallel_for_simd, getCollapseNumberExpr(Clauses),
6318 getOrderedNumberExpr(Clauses), AStmt, *this, *DSAStack,
6319 VarsWithImplicitDSA, B);
6320 if (NestedLoopCount == 0)
6323 assert((CurContext->isDependentContext() || B.builtAll()) &&
6324 "omp target parallel for simd loop exprs were not built");
6326 if (!CurContext->isDependentContext()) {
6327 // Finalize the clauses that need pre-built expressions for CodeGen.
6328 for (auto C : Clauses) {
6329 if (auto *LC = dyn_cast<OMPLinearClause>(C))
6330 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
6331 B.NumIterations, *this, CurScope,
6336 if (checkSimdlenSafelenSpecified(*this, Clauses))
6339 getCurFunction()->setHasBranchProtectedScope();
6340 return OMPTargetParallelForSimdDirective::Create(
6341 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
6344 StmtResult Sema::ActOnOpenMPTargetSimdDirective(
6345 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
6346 SourceLocation EndLoc,
6347 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
6351 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
6352 // 1.2.2 OpenMP Language Terminology
6353 // Structured block - An executable statement with a single entry at the
6354 // top and a single exit at the bottom.
6355 // The point of exit cannot be a branch out of the structured block.
6356 // longjmp() and throw() must not violate the entry/exit criteria.
6357 CS->getCapturedDecl()->setNothrow();
6359 OMPLoopDirective::HelperExprs B;
6360 // In presence of clause 'collapse' with number of loops, it will define the
6361 // nested loops number.
6362 unsigned NestedLoopCount =
6363 CheckOpenMPLoop(OMPD_target_simd, getCollapseNumberExpr(Clauses),
6364 getOrderedNumberExpr(Clauses), AStmt, *this, *DSAStack,
6365 VarsWithImplicitDSA, B);
6366 if (NestedLoopCount == 0)
6369 assert((CurContext->isDependentContext() || B.builtAll()) &&
6370 "omp target simd loop exprs were not built");
6372 if (!CurContext->isDependentContext()) {
6373 // Finalize the clauses that need pre-built expressions for CodeGen.
6374 for (auto C : Clauses) {
6375 if (auto *LC = dyn_cast<OMPLinearClause>(C))
6376 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
6377 B.NumIterations, *this, CurScope,
6383 if (checkSimdlenSafelenSpecified(*this, Clauses))
6386 getCurFunction()->setHasBranchProtectedScope();
6387 return OMPTargetSimdDirective::Create(Context, StartLoc, EndLoc,
6388 NestedLoopCount, Clauses, AStmt, B);
6391 StmtResult Sema::ActOnOpenMPTeamsDistributeDirective(
6392 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
6393 SourceLocation EndLoc,
6394 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
6398 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
6399 // 1.2.2 OpenMP Language Terminology
6400 // Structured block - An executable statement with a single entry at the
6401 // top and a single exit at the bottom.
6402 // The point of exit cannot be a branch out of the structured block.
6403 // longjmp() and throw() must not violate the entry/exit criteria.
6404 CS->getCapturedDecl()->setNothrow();
6406 OMPLoopDirective::HelperExprs B;
6407 // In presence of clause 'collapse' with number of loops, it will
6408 // define the nested loops number.
6409 unsigned NestedLoopCount =
6410 CheckOpenMPLoop(OMPD_teams_distribute, getCollapseNumberExpr(Clauses),
6411 nullptr /*ordered not a clause on distribute*/, AStmt,
6412 *this, *DSAStack, VarsWithImplicitDSA, B);
6413 if (NestedLoopCount == 0)
6416 assert((CurContext->isDependentContext() || B.builtAll()) &&
6417 "omp teams distribute loop exprs were not built");
6419 getCurFunction()->setHasBranchProtectedScope();
6420 return OMPTeamsDistributeDirective::Create(
6421 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
6424 StmtResult Sema::ActOnOpenMPTeamsDistributeSimdDirective(
6425 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
6426 SourceLocation EndLoc,
6427 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
6431 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
6432 // 1.2.2 OpenMP Language Terminology
6433 // Structured block - An executable statement with a single entry at the
6434 // top and a single exit at the bottom.
6435 // The point of exit cannot be a branch out of the structured block.
6436 // longjmp() and throw() must not violate the entry/exit criteria.
6437 CS->getCapturedDecl()->setNothrow();
6439 OMPLoopDirective::HelperExprs B;
6440 // In presence of clause 'collapse' with number of loops, it will
6441 // define the nested loops number.
6442 unsigned NestedLoopCount = CheckOpenMPLoop(
6443 OMPD_teams_distribute_simd, getCollapseNumberExpr(Clauses),
6444 nullptr /*ordered not a clause on distribute*/, AStmt, *this, *DSAStack,
6445 VarsWithImplicitDSA, B);
6447 if (NestedLoopCount == 0)
6450 assert((CurContext->isDependentContext() || B.builtAll()) &&
6451 "omp teams distribute simd loop exprs were not built");
6453 if (!CurContext->isDependentContext()) {
6454 // Finalize the clauses that need pre-built expressions for CodeGen.
6455 for (auto C : Clauses) {
6456 if (auto *LC = dyn_cast<OMPLinearClause>(C))
6457 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
6458 B.NumIterations, *this, CurScope,
6464 if (checkSimdlenSafelenSpecified(*this, Clauses))
6467 getCurFunction()->setHasBranchProtectedScope();
6468 return OMPTeamsDistributeSimdDirective::Create(
6469 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
6472 StmtResult Sema::ActOnOpenMPTeamsDistributeParallelForSimdDirective(
6473 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
6474 SourceLocation EndLoc,
6475 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
6479 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
6480 // 1.2.2 OpenMP Language Terminology
6481 // Structured block - An executable statement with a single entry at the
6482 // top and a single exit at the bottom.
6483 // The point of exit cannot be a branch out of the structured block.
6484 // longjmp() and throw() must not violate the entry/exit criteria.
6485 CS->getCapturedDecl()->setNothrow();
6487 OMPLoopDirective::HelperExprs B;
6488 // In presence of clause 'collapse' with number of loops, it will
6489 // define the nested loops number.
6490 auto NestedLoopCount = CheckOpenMPLoop(
6491 OMPD_teams_distribute_parallel_for_simd, getCollapseNumberExpr(Clauses),
6492 nullptr /*ordered not a clause on distribute*/, AStmt, *this, *DSAStack,
6493 VarsWithImplicitDSA, B);
6495 if (NestedLoopCount == 0)
6498 assert((CurContext->isDependentContext() || B.builtAll()) &&
6499 "omp for loop exprs were not built");
6501 if (!CurContext->isDependentContext()) {
6502 // Finalize the clauses that need pre-built expressions for CodeGen.
6503 for (auto C : Clauses) {
6504 if (auto *LC = dyn_cast<OMPLinearClause>(C))
6505 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
6506 B.NumIterations, *this, CurScope,
6512 if (checkSimdlenSafelenSpecified(*this, Clauses))
6515 getCurFunction()->setHasBranchProtectedScope();
6516 return OMPTeamsDistributeParallelForSimdDirective::Create(
6517 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
6520 StmtResult Sema::ActOnOpenMPTeamsDistributeParallelForDirective(
6521 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
6522 SourceLocation EndLoc,
6523 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
6527 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
6528 // 1.2.2 OpenMP Language Terminology
6529 // Structured block - An executable statement with a single entry at the
6530 // top and a single exit at the bottom.
6531 // The point of exit cannot be a branch out of the structured block.
6532 // longjmp() and throw() must not violate the entry/exit criteria.
6533 CS->getCapturedDecl()->setNothrow();
6535 OMPLoopDirective::HelperExprs B;
6536 // In presence of clause 'collapse' with number of loops, it will
6537 // define the nested loops number.
6538 unsigned NestedLoopCount = CheckOpenMPLoop(
6539 OMPD_teams_distribute_parallel_for, getCollapseNumberExpr(Clauses),
6540 nullptr /*ordered not a clause on distribute*/, AStmt, *this, *DSAStack,
6541 VarsWithImplicitDSA, B);
6543 if (NestedLoopCount == 0)
6546 assert((CurContext->isDependentContext() || B.builtAll()) &&
6547 "omp for loop exprs were not built");
6549 if (!CurContext->isDependentContext()) {
6550 // Finalize the clauses that need pre-built expressions for CodeGen.
6551 for (auto C : Clauses) {
6552 if (auto *LC = dyn_cast<OMPLinearClause>(C))
6553 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
6554 B.NumIterations, *this, CurScope,
6560 getCurFunction()->setHasBranchProtectedScope();
6561 return OMPTeamsDistributeParallelForDirective::Create(
6562 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
6565 StmtResult Sema::ActOnOpenMPTargetTeamsDirective(ArrayRef<OMPClause *> Clauses,
6567 SourceLocation StartLoc,
6568 SourceLocation EndLoc) {
6572 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
6573 // 1.2.2 OpenMP Language Terminology
6574 // Structured block - An executable statement with a single entry at the
6575 // top and a single exit at the bottom.
6576 // The point of exit cannot be a branch out of the structured block.
6577 // longjmp() and throw() must not violate the entry/exit criteria.
6578 CS->getCapturedDecl()->setNothrow();
6580 getCurFunction()->setHasBranchProtectedScope();
6582 return OMPTargetTeamsDirective::Create(Context, StartLoc, EndLoc, Clauses,
6586 StmtResult Sema::ActOnOpenMPTargetTeamsDistributeDirective(
6587 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
6588 SourceLocation EndLoc,
6589 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
6593 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
6594 // 1.2.2 OpenMP Language Terminology
6595 // Structured block - An executable statement with a single entry at the
6596 // top and a single exit at the bottom.
6597 // The point of exit cannot be a branch out of the structured block.
6598 // longjmp() and throw() must not violate the entry/exit criteria.
6599 CS->getCapturedDecl()->setNothrow();
6601 OMPLoopDirective::HelperExprs B;
6602 // In presence of clause 'collapse' with number of loops, it will
6603 // define the nested loops number.
6604 auto NestedLoopCount = CheckOpenMPLoop(
6605 OMPD_target_teams_distribute,
6606 getCollapseNumberExpr(Clauses),
6607 nullptr /*ordered not a clause on distribute*/, AStmt, *this, *DSAStack,
6608 VarsWithImplicitDSA, B);
6609 if (NestedLoopCount == 0)
6612 assert((CurContext->isDependentContext() || B.builtAll()) &&
6613 "omp target teams distribute loop exprs were not built");
6615 getCurFunction()->setHasBranchProtectedScope();
6616 return OMPTargetTeamsDistributeDirective::Create(
6617 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
6620 StmtResult Sema::ActOnOpenMPTargetTeamsDistributeParallelForDirective(
6621 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
6622 SourceLocation EndLoc,
6623 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
6627 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
6628 // 1.2.2 OpenMP Language Terminology
6629 // Structured block - An executable statement with a single entry at the
6630 // top and a single exit at the bottom.
6631 // The point of exit cannot be a branch out of the structured block.
6632 // longjmp() and throw() must not violate the entry/exit criteria.
6633 CS->getCapturedDecl()->setNothrow();
6635 OMPLoopDirective::HelperExprs B;
6636 // In presence of clause 'collapse' with number of loops, it will
6637 // define the nested loops number.
6638 auto NestedLoopCount = CheckOpenMPLoop(
6639 OMPD_target_teams_distribute_parallel_for,
6640 getCollapseNumberExpr(Clauses),
6641 nullptr /*ordered not a clause on distribute*/, AStmt, *this, *DSAStack,
6642 VarsWithImplicitDSA, B);
6643 if (NestedLoopCount == 0)
6646 assert((CurContext->isDependentContext() || B.builtAll()) &&
6647 "omp target teams distribute parallel for loop exprs were not built");
6649 if (!CurContext->isDependentContext()) {
6650 // Finalize the clauses that need pre-built expressions for CodeGen.
6651 for (auto C : Clauses) {
6652 if (auto *LC = dyn_cast<OMPLinearClause>(C))
6653 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
6654 B.NumIterations, *this, CurScope,
6660 getCurFunction()->setHasBranchProtectedScope();
6661 return OMPTargetTeamsDistributeParallelForDirective::Create(
6662 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
6665 StmtResult Sema::ActOnOpenMPTargetTeamsDistributeParallelForSimdDirective(
6666 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
6667 SourceLocation EndLoc,
6668 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
6672 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
6673 // 1.2.2 OpenMP Language Terminology
6674 // Structured block - An executable statement with a single entry at the
6675 // top and a single exit at the bottom.
6676 // The point of exit cannot be a branch out of the structured block.
6677 // longjmp() and throw() must not violate the entry/exit criteria.
6678 CS->getCapturedDecl()->setNothrow();
6680 OMPLoopDirective::HelperExprs B;
6681 // In presence of clause 'collapse' with number of loops, it will
6682 // define the nested loops number.
6683 auto NestedLoopCount = CheckOpenMPLoop(
6684 OMPD_target_teams_distribute_parallel_for_simd,
6685 getCollapseNumberExpr(Clauses),
6686 nullptr /*ordered not a clause on distribute*/, AStmt, *this, *DSAStack,
6687 VarsWithImplicitDSA, B);
6688 if (NestedLoopCount == 0)
6691 assert((CurContext->isDependentContext() || B.builtAll()) &&
6692 "omp target teams distribute parallel for simd loop exprs were not "
6695 if (!CurContext->isDependentContext()) {
6696 // Finalize the clauses that need pre-built expressions for CodeGen.
6697 for (auto C : Clauses) {
6698 if (auto *LC = dyn_cast<OMPLinearClause>(C))
6699 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
6700 B.NumIterations, *this, CurScope,
6706 getCurFunction()->setHasBranchProtectedScope();
6707 return OMPTargetTeamsDistributeParallelForSimdDirective::Create(
6708 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
6711 StmtResult Sema::ActOnOpenMPTargetTeamsDistributeSimdDirective(
6712 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
6713 SourceLocation EndLoc,
6714 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
6718 auto *CS = cast<CapturedStmt>(AStmt);
6719 // 1.2.2 OpenMP Language Terminology
6720 // Structured block - An executable statement with a single entry at the
6721 // top and a single exit at the bottom.
6722 // The point of exit cannot be a branch out of the structured block.
6723 // longjmp() and throw() must not violate the entry/exit criteria.
6724 CS->getCapturedDecl()->setNothrow();
6726 OMPLoopDirective::HelperExprs B;
6727 // In presence of clause 'collapse' with number of loops, it will
6728 // define the nested loops number.
6729 auto NestedLoopCount = CheckOpenMPLoop(
6730 OMPD_target_teams_distribute_simd, getCollapseNumberExpr(Clauses),
6731 nullptr /*ordered not a clause on distribute*/, AStmt, *this, *DSAStack,
6732 VarsWithImplicitDSA, B);
6733 if (NestedLoopCount == 0)
6736 assert((CurContext->isDependentContext() || B.builtAll()) &&
6737 "omp target teams distribute simd loop exprs were not built");
6739 getCurFunction()->setHasBranchProtectedScope();
6740 return OMPTargetTeamsDistributeSimdDirective::Create(
6741 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
6744 OMPClause *Sema::ActOnOpenMPSingleExprClause(OpenMPClauseKind Kind, Expr *Expr,
6745 SourceLocation StartLoc,
6746 SourceLocation LParenLoc,
6747 SourceLocation EndLoc) {
6748 OMPClause *Res = nullptr;
6751 Res = ActOnOpenMPFinalClause(Expr, StartLoc, LParenLoc, EndLoc);
6753 case OMPC_num_threads:
6754 Res = ActOnOpenMPNumThreadsClause(Expr, StartLoc, LParenLoc, EndLoc);
6757 Res = ActOnOpenMPSafelenClause(Expr, StartLoc, LParenLoc, EndLoc);
6760 Res = ActOnOpenMPSimdlenClause(Expr, StartLoc, LParenLoc, EndLoc);
6763 Res = ActOnOpenMPCollapseClause(Expr, StartLoc, LParenLoc, EndLoc);
6766 Res = ActOnOpenMPOrderedClause(StartLoc, EndLoc, LParenLoc, Expr);
6769 Res = ActOnOpenMPDeviceClause(Expr, StartLoc, LParenLoc, EndLoc);
6771 case OMPC_num_teams:
6772 Res = ActOnOpenMPNumTeamsClause(Expr, StartLoc, LParenLoc, EndLoc);
6774 case OMPC_thread_limit:
6775 Res = ActOnOpenMPThreadLimitClause(Expr, StartLoc, LParenLoc, EndLoc);
6778 Res = ActOnOpenMPPriorityClause(Expr, StartLoc, LParenLoc, EndLoc);
6780 case OMPC_grainsize:
6781 Res = ActOnOpenMPGrainsizeClause(Expr, StartLoc, LParenLoc, EndLoc);
6783 case OMPC_num_tasks:
6784 Res = ActOnOpenMPNumTasksClause(Expr, StartLoc, LParenLoc, EndLoc);
6787 Res = ActOnOpenMPHintClause(Expr, StartLoc, LParenLoc, EndLoc);
6791 case OMPC_proc_bind:
6794 case OMPC_firstprivate:
6795 case OMPC_lastprivate:
6797 case OMPC_reduction:
6801 case OMPC_copyprivate:
6804 case OMPC_mergeable:
6805 case OMPC_threadprivate:
6817 case OMPC_dist_schedule:
6818 case OMPC_defaultmap:
6823 case OMPC_use_device_ptr:
6824 case OMPC_is_device_ptr:
6825 llvm_unreachable("Clause is not allowed.");
6830 // An OpenMP directive such as 'target parallel' has two captured regions:
6831 // for the 'target' and 'parallel' respectively. This function returns
6832 // the region in which to capture expressions associated with a clause.
6833 // A return value of OMPD_unknown signifies that the expression should not
6835 static OpenMPDirectiveKind getOpenMPCaptureRegionForClause(
6836 OpenMPDirectiveKind DKind, OpenMPClauseKind CKind,
6837 OpenMPDirectiveKind NameModifier = OMPD_unknown) {
6838 OpenMPDirectiveKind CaptureRegion = OMPD_unknown;
6843 case OMPD_target_parallel:
6844 // If this clause applies to the nested 'parallel' region, capture within
6845 // the 'target' region, otherwise do not capture.
6846 if (NameModifier == OMPD_unknown || NameModifier == OMPD_parallel)
6847 CaptureRegion = OMPD_target;
6851 case OMPD_parallel_sections:
6852 case OMPD_parallel_for:
6853 case OMPD_parallel_for_simd:
6855 case OMPD_target_simd:
6856 case OMPD_target_parallel_for:
6857 case OMPD_target_parallel_for_simd:
6858 case OMPD_target_teams:
6859 case OMPD_target_teams_distribute:
6860 case OMPD_target_teams_distribute_simd:
6861 case OMPD_target_teams_distribute_parallel_for:
6862 case OMPD_target_teams_distribute_parallel_for_simd:
6863 case OMPD_teams_distribute_parallel_for:
6864 case OMPD_teams_distribute_parallel_for_simd:
6865 case OMPD_distribute_parallel_for:
6866 case OMPD_distribute_parallel_for_simd:
6869 case OMPD_taskloop_simd:
6870 case OMPD_target_data:
6871 case OMPD_target_enter_data:
6872 case OMPD_target_exit_data:
6873 case OMPD_target_update:
6874 // Do not capture if-clause expressions.
6876 case OMPD_threadprivate:
6877 case OMPD_taskyield:
6880 case OMPD_cancellation_point:
6882 case OMPD_declare_reduction:
6883 case OMPD_declare_simd:
6884 case OMPD_declare_target:
6885 case OMPD_end_declare_target:
6895 case OMPD_taskgroup:
6896 case OMPD_distribute:
6899 case OMPD_distribute_simd:
6900 case OMPD_teams_distribute:
6901 case OMPD_teams_distribute_simd:
6902 llvm_unreachable("Unexpected OpenMP directive with if-clause");
6904 llvm_unreachable("Unknown OpenMP directive");
6907 case OMPC_num_threads:
6909 case OMPD_target_parallel:
6910 CaptureRegion = OMPD_target;
6914 case OMPD_parallel_sections:
6915 case OMPD_parallel_for:
6916 case OMPD_parallel_for_simd:
6918 case OMPD_target_simd:
6919 case OMPD_target_parallel_for:
6920 case OMPD_target_parallel_for_simd:
6921 case OMPD_target_teams:
6922 case OMPD_target_teams_distribute:
6923 case OMPD_target_teams_distribute_simd:
6924 case OMPD_target_teams_distribute_parallel_for:
6925 case OMPD_target_teams_distribute_parallel_for_simd:
6926 case OMPD_teams_distribute_parallel_for:
6927 case OMPD_teams_distribute_parallel_for_simd:
6928 case OMPD_distribute_parallel_for:
6929 case OMPD_distribute_parallel_for_simd:
6932 case OMPD_taskloop_simd:
6933 case OMPD_target_data:
6934 case OMPD_target_enter_data:
6935 case OMPD_target_exit_data:
6936 case OMPD_target_update:
6937 // Do not capture num_threads-clause expressions.
6939 case OMPD_threadprivate:
6940 case OMPD_taskyield:
6943 case OMPD_cancellation_point:
6945 case OMPD_declare_reduction:
6946 case OMPD_declare_simd:
6947 case OMPD_declare_target:
6948 case OMPD_end_declare_target:
6958 case OMPD_taskgroup:
6959 case OMPD_distribute:
6962 case OMPD_distribute_simd:
6963 case OMPD_teams_distribute:
6964 case OMPD_teams_distribute_simd:
6965 llvm_unreachable("Unexpected OpenMP directive with num_threads-clause");
6967 llvm_unreachable("Unknown OpenMP directive");
6970 case OMPC_num_teams:
6972 case OMPD_target_teams:
6973 CaptureRegion = OMPD_target;
6977 case OMPD_parallel_sections:
6978 case OMPD_parallel_for:
6979 case OMPD_parallel_for_simd:
6981 case OMPD_target_simd:
6982 case OMPD_target_parallel:
6983 case OMPD_target_parallel_for:
6984 case OMPD_target_parallel_for_simd:
6985 case OMPD_target_teams_distribute:
6986 case OMPD_target_teams_distribute_simd:
6987 case OMPD_target_teams_distribute_parallel_for:
6988 case OMPD_target_teams_distribute_parallel_for_simd:
6989 case OMPD_teams_distribute_parallel_for:
6990 case OMPD_teams_distribute_parallel_for_simd:
6991 case OMPD_distribute_parallel_for:
6992 case OMPD_distribute_parallel_for_simd:
6995 case OMPD_taskloop_simd:
6996 case OMPD_target_data:
6997 case OMPD_target_enter_data:
6998 case OMPD_target_exit_data:
6999 case OMPD_target_update:
7001 case OMPD_teams_distribute:
7002 case OMPD_teams_distribute_simd:
7003 // Do not capture num_teams-clause expressions.
7005 case OMPD_threadprivate:
7006 case OMPD_taskyield:
7009 case OMPD_cancellation_point:
7011 case OMPD_declare_reduction:
7012 case OMPD_declare_simd:
7013 case OMPD_declare_target:
7014 case OMPD_end_declare_target:
7023 case OMPD_taskgroup:
7024 case OMPD_distribute:
7027 case OMPD_distribute_simd:
7028 llvm_unreachable("Unexpected OpenMP directive with num_teams-clause");
7030 llvm_unreachable("Unknown OpenMP directive");
7033 case OMPC_thread_limit:
7035 case OMPD_target_teams:
7036 CaptureRegion = OMPD_target;
7040 case OMPD_parallel_sections:
7041 case OMPD_parallel_for:
7042 case OMPD_parallel_for_simd:
7044 case OMPD_target_simd:
7045 case OMPD_target_parallel:
7046 case OMPD_target_parallel_for:
7047 case OMPD_target_parallel_for_simd:
7048 case OMPD_target_teams_distribute:
7049 case OMPD_target_teams_distribute_simd:
7050 case OMPD_target_teams_distribute_parallel_for:
7051 case OMPD_target_teams_distribute_parallel_for_simd:
7052 case OMPD_teams_distribute_parallel_for:
7053 case OMPD_teams_distribute_parallel_for_simd:
7054 case OMPD_distribute_parallel_for:
7055 case OMPD_distribute_parallel_for_simd:
7058 case OMPD_taskloop_simd:
7059 case OMPD_target_data:
7060 case OMPD_target_enter_data:
7061 case OMPD_target_exit_data:
7062 case OMPD_target_update:
7064 case OMPD_teams_distribute:
7065 case OMPD_teams_distribute_simd:
7066 // Do not capture thread_limit-clause expressions.
7068 case OMPD_threadprivate:
7069 case OMPD_taskyield:
7072 case OMPD_cancellation_point:
7074 case OMPD_declare_reduction:
7075 case OMPD_declare_simd:
7076 case OMPD_declare_target:
7077 case OMPD_end_declare_target:
7086 case OMPD_taskgroup:
7087 case OMPD_distribute:
7090 case OMPD_distribute_simd:
7091 llvm_unreachable("Unexpected OpenMP directive with thread_limit-clause");
7093 llvm_unreachable("Unknown OpenMP directive");
7097 case OMPC_dist_schedule:
7098 case OMPC_firstprivate:
7099 case OMPC_lastprivate:
7100 case OMPC_reduction:
7103 case OMPC_proc_bind:
7112 case OMPC_copyprivate:
7116 case OMPC_mergeable:
7117 case OMPC_threadprivate:
7130 case OMPC_grainsize:
7132 case OMPC_num_tasks:
7134 case OMPC_defaultmap:
7139 case OMPC_use_device_ptr:
7140 case OMPC_is_device_ptr:
7141 llvm_unreachable("Unexpected OpenMP clause.");
7143 return CaptureRegion;
7146 OMPClause *Sema::ActOnOpenMPIfClause(OpenMPDirectiveKind NameModifier,
7147 Expr *Condition, SourceLocation StartLoc,
7148 SourceLocation LParenLoc,
7149 SourceLocation NameModifierLoc,
7150 SourceLocation ColonLoc,
7151 SourceLocation EndLoc) {
7152 Expr *ValExpr = Condition;
7153 Stmt *HelperValStmt = nullptr;
7154 OpenMPDirectiveKind CaptureRegion = OMPD_unknown;
7155 if (!Condition->isValueDependent() && !Condition->isTypeDependent() &&
7156 !Condition->isInstantiationDependent() &&
7157 !Condition->containsUnexpandedParameterPack()) {
7158 ExprResult Val = CheckBooleanCondition(StartLoc, Condition);
7159 if (Val.isInvalid())
7162 ValExpr = MakeFullExpr(Val.get()).get();
7164 OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective();
7166 getOpenMPCaptureRegionForClause(DKind, OMPC_if, NameModifier);
7167 if (CaptureRegion != OMPD_unknown) {
7168 llvm::MapVector<Expr *, DeclRefExpr *> Captures;
7169 ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
7170 HelperValStmt = buildPreInits(Context, Captures);
7174 return new (Context)
7175 OMPIfClause(NameModifier, ValExpr, HelperValStmt, CaptureRegion, StartLoc,
7176 LParenLoc, NameModifierLoc, ColonLoc, EndLoc);
7179 OMPClause *Sema::ActOnOpenMPFinalClause(Expr *Condition,
7180 SourceLocation StartLoc,
7181 SourceLocation LParenLoc,
7182 SourceLocation EndLoc) {
7183 Expr *ValExpr = Condition;
7184 if (!Condition->isValueDependent() && !Condition->isTypeDependent() &&
7185 !Condition->isInstantiationDependent() &&
7186 !Condition->containsUnexpandedParameterPack()) {
7187 ExprResult Val = CheckBooleanCondition(StartLoc, Condition);
7188 if (Val.isInvalid())
7191 ValExpr = MakeFullExpr(Val.get()).get();
7194 return new (Context) OMPFinalClause(ValExpr, StartLoc, LParenLoc, EndLoc);
7196 ExprResult Sema::PerformOpenMPImplicitIntegerConversion(SourceLocation Loc,
7201 class IntConvertDiagnoser : public ICEConvertDiagnoser {
7203 IntConvertDiagnoser()
7204 : ICEConvertDiagnoser(/*AllowScopedEnumerations*/ false, false, true) {}
7205 SemaDiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc,
7206 QualType T) override {
7207 return S.Diag(Loc, diag::err_omp_not_integral) << T;
7209 SemaDiagnosticBuilder diagnoseIncomplete(Sema &S, SourceLocation Loc,
7210 QualType T) override {
7211 return S.Diag(Loc, diag::err_omp_incomplete_type) << T;
7213 SemaDiagnosticBuilder diagnoseExplicitConv(Sema &S, SourceLocation Loc,
7215 QualType ConvTy) override {
7216 return S.Diag(Loc, diag::err_omp_explicit_conversion) << T << ConvTy;
7218 SemaDiagnosticBuilder noteExplicitConv(Sema &S, CXXConversionDecl *Conv,
7219 QualType ConvTy) override {
7220 return S.Diag(Conv->getLocation(), diag::note_omp_conversion_here)
7221 << ConvTy->isEnumeralType() << ConvTy;
7223 SemaDiagnosticBuilder diagnoseAmbiguous(Sema &S, SourceLocation Loc,
7224 QualType T) override {
7225 return S.Diag(Loc, diag::err_omp_ambiguous_conversion) << T;
7227 SemaDiagnosticBuilder noteAmbiguous(Sema &S, CXXConversionDecl *Conv,
7228 QualType ConvTy) override {
7229 return S.Diag(Conv->getLocation(), diag::note_omp_conversion_here)
7230 << ConvTy->isEnumeralType() << ConvTy;
7232 SemaDiagnosticBuilder diagnoseConversion(Sema &, SourceLocation, QualType,
7233 QualType) override {
7234 llvm_unreachable("conversion functions are permitted");
7237 return PerformContextualImplicitConversion(Loc, Op, ConvertDiagnoser);
7240 static bool IsNonNegativeIntegerValue(Expr *&ValExpr, Sema &SemaRef,
7241 OpenMPClauseKind CKind,
7242 bool StrictlyPositive) {
7243 if (!ValExpr->isTypeDependent() && !ValExpr->isValueDependent() &&
7244 !ValExpr->isInstantiationDependent()) {
7245 SourceLocation Loc = ValExpr->getExprLoc();
7247 SemaRef.PerformOpenMPImplicitIntegerConversion(Loc, ValExpr);
7248 if (Value.isInvalid())
7251 ValExpr = Value.get();
7252 // The expression must evaluate to a non-negative integer value.
7253 llvm::APSInt Result;
7254 if (ValExpr->isIntegerConstantExpr(Result, SemaRef.Context) &&
7255 Result.isSigned() &&
7256 !((!StrictlyPositive && Result.isNonNegative()) ||
7257 (StrictlyPositive && Result.isStrictlyPositive()))) {
7258 SemaRef.Diag(Loc, diag::err_omp_negative_expression_in_clause)
7259 << getOpenMPClauseName(CKind) << (StrictlyPositive ? 1 : 0)
7260 << ValExpr->getSourceRange();
7267 OMPClause *Sema::ActOnOpenMPNumThreadsClause(Expr *NumThreads,
7268 SourceLocation StartLoc,
7269 SourceLocation LParenLoc,
7270 SourceLocation EndLoc) {
7271 Expr *ValExpr = NumThreads;
7272 Stmt *HelperValStmt = nullptr;
7273 OpenMPDirectiveKind CaptureRegion = OMPD_unknown;
7275 // OpenMP [2.5, Restrictions]
7276 // The num_threads expression must evaluate to a positive integer value.
7277 if (!IsNonNegativeIntegerValue(ValExpr, *this, OMPC_num_threads,
7278 /*StrictlyPositive=*/true))
7281 OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective();
7282 CaptureRegion = getOpenMPCaptureRegionForClause(DKind, OMPC_num_threads);
7283 if (CaptureRegion != OMPD_unknown) {
7284 llvm::MapVector<Expr *, DeclRefExpr *> Captures;
7285 ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
7286 HelperValStmt = buildPreInits(Context, Captures);
7289 return new (Context) OMPNumThreadsClause(
7290 ValExpr, HelperValStmt, CaptureRegion, StartLoc, LParenLoc, EndLoc);
7293 ExprResult Sema::VerifyPositiveIntegerConstantInClause(Expr *E,
7294 OpenMPClauseKind CKind,
7295 bool StrictlyPositive) {
7298 if (E->isValueDependent() || E->isTypeDependent() ||
7299 E->isInstantiationDependent() || E->containsUnexpandedParameterPack())
7301 llvm::APSInt Result;
7302 ExprResult ICE = VerifyIntegerConstantExpression(E, &Result);
7303 if (ICE.isInvalid())
7305 if ((StrictlyPositive && !Result.isStrictlyPositive()) ||
7306 (!StrictlyPositive && !Result.isNonNegative())) {
7307 Diag(E->getExprLoc(), diag::err_omp_negative_expression_in_clause)
7308 << getOpenMPClauseName(CKind) << (StrictlyPositive ? 1 : 0)
7309 << E->getSourceRange();
7312 if (CKind == OMPC_aligned && !Result.isPowerOf2()) {
7313 Diag(E->getExprLoc(), diag::warn_omp_alignment_not_power_of_two)
7314 << E->getSourceRange();
7317 if (CKind == OMPC_collapse && DSAStack->getAssociatedLoops() == 1)
7318 DSAStack->setAssociatedLoops(Result.getExtValue());
7319 else if (CKind == OMPC_ordered)
7320 DSAStack->setAssociatedLoops(Result.getExtValue());
7324 OMPClause *Sema::ActOnOpenMPSafelenClause(Expr *Len, SourceLocation StartLoc,
7325 SourceLocation LParenLoc,
7326 SourceLocation EndLoc) {
7327 // OpenMP [2.8.1, simd construct, Description]
7328 // The parameter of the safelen clause must be a constant
7329 // positive integer expression.
7330 ExprResult Safelen = VerifyPositiveIntegerConstantInClause(Len, OMPC_safelen);
7331 if (Safelen.isInvalid())
7333 return new (Context)
7334 OMPSafelenClause(Safelen.get(), StartLoc, LParenLoc, EndLoc);
7337 OMPClause *Sema::ActOnOpenMPSimdlenClause(Expr *Len, SourceLocation StartLoc,
7338 SourceLocation LParenLoc,
7339 SourceLocation EndLoc) {
7340 // OpenMP [2.8.1, simd construct, Description]
7341 // The parameter of the simdlen clause must be a constant
7342 // positive integer expression.
7343 ExprResult Simdlen = VerifyPositiveIntegerConstantInClause(Len, OMPC_simdlen);
7344 if (Simdlen.isInvalid())
7346 return new (Context)
7347 OMPSimdlenClause(Simdlen.get(), StartLoc, LParenLoc, EndLoc);
7350 OMPClause *Sema::ActOnOpenMPCollapseClause(Expr *NumForLoops,
7351 SourceLocation StartLoc,
7352 SourceLocation LParenLoc,
7353 SourceLocation EndLoc) {
7354 // OpenMP [2.7.1, loop construct, Description]
7355 // OpenMP [2.8.1, simd construct, Description]
7356 // OpenMP [2.9.6, distribute construct, Description]
7357 // The parameter of the collapse clause must be a constant
7358 // positive integer expression.
7359 ExprResult NumForLoopsResult =
7360 VerifyPositiveIntegerConstantInClause(NumForLoops, OMPC_collapse);
7361 if (NumForLoopsResult.isInvalid())
7363 return new (Context)
7364 OMPCollapseClause(NumForLoopsResult.get(), StartLoc, LParenLoc, EndLoc);
7367 OMPClause *Sema::ActOnOpenMPOrderedClause(SourceLocation StartLoc,
7368 SourceLocation EndLoc,
7369 SourceLocation LParenLoc,
7370 Expr *NumForLoops) {
7371 // OpenMP [2.7.1, loop construct, Description]
7372 // OpenMP [2.8.1, simd construct, Description]
7373 // OpenMP [2.9.6, distribute construct, Description]
7374 // The parameter of the ordered clause must be a constant
7375 // positive integer expression if any.
7376 if (NumForLoops && LParenLoc.isValid()) {
7377 ExprResult NumForLoopsResult =
7378 VerifyPositiveIntegerConstantInClause(NumForLoops, OMPC_ordered);
7379 if (NumForLoopsResult.isInvalid())
7381 NumForLoops = NumForLoopsResult.get();
7383 NumForLoops = nullptr;
7384 DSAStack->setOrderedRegion(/*IsOrdered=*/true, NumForLoops);
7385 return new (Context)
7386 OMPOrderedClause(NumForLoops, StartLoc, LParenLoc, EndLoc);
7389 OMPClause *Sema::ActOnOpenMPSimpleClause(
7390 OpenMPClauseKind Kind, unsigned Argument, SourceLocation ArgumentLoc,
7391 SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc) {
7392 OMPClause *Res = nullptr;
7396 ActOnOpenMPDefaultClause(static_cast<OpenMPDefaultClauseKind>(Argument),
7397 ArgumentLoc, StartLoc, LParenLoc, EndLoc);
7399 case OMPC_proc_bind:
7400 Res = ActOnOpenMPProcBindClause(
7401 static_cast<OpenMPProcBindClauseKind>(Argument), ArgumentLoc, StartLoc,
7406 case OMPC_num_threads:
7412 case OMPC_firstprivate:
7413 case OMPC_lastprivate:
7415 case OMPC_reduction:
7419 case OMPC_copyprivate:
7423 case OMPC_mergeable:
7424 case OMPC_threadprivate:
7436 case OMPC_num_teams:
7437 case OMPC_thread_limit:
7439 case OMPC_grainsize:
7441 case OMPC_num_tasks:
7443 case OMPC_dist_schedule:
7444 case OMPC_defaultmap:
7449 case OMPC_use_device_ptr:
7450 case OMPC_is_device_ptr:
7451 llvm_unreachable("Clause is not allowed.");
7457 getListOfPossibleValues(OpenMPClauseKind K, unsigned First, unsigned Last,
7458 ArrayRef<unsigned> Exclude = llvm::None) {
7460 unsigned Bound = Last >= 2 ? Last - 2 : 0;
7461 unsigned Skipped = Exclude.size();
7462 auto S = Exclude.begin(), E = Exclude.end();
7463 for (unsigned i = First; i < Last; ++i) {
7464 if (std::find(S, E, i) != E) {
7469 Values += getOpenMPSimpleClauseTypeName(K, i);
7471 if (i == Bound - Skipped)
7473 else if (i != Bound + 1 - Skipped)
7479 OMPClause *Sema::ActOnOpenMPDefaultClause(OpenMPDefaultClauseKind Kind,
7480 SourceLocation KindKwLoc,
7481 SourceLocation StartLoc,
7482 SourceLocation LParenLoc,
7483 SourceLocation EndLoc) {
7484 if (Kind == OMPC_DEFAULT_unknown) {
7485 static_assert(OMPC_DEFAULT_unknown > 0,
7486 "OMPC_DEFAULT_unknown not greater than 0");
7487 Diag(KindKwLoc, diag::err_omp_unexpected_clause_value)
7488 << getListOfPossibleValues(OMPC_default, /*First=*/0,
7489 /*Last=*/OMPC_DEFAULT_unknown)
7490 << getOpenMPClauseName(OMPC_default);
7494 case OMPC_DEFAULT_none:
7495 DSAStack->setDefaultDSANone(KindKwLoc);
7497 case OMPC_DEFAULT_shared:
7498 DSAStack->setDefaultDSAShared(KindKwLoc);
7500 case OMPC_DEFAULT_unknown:
7501 llvm_unreachable("Clause kind is not allowed.");
7504 return new (Context)
7505 OMPDefaultClause(Kind, KindKwLoc, StartLoc, LParenLoc, EndLoc);
7508 OMPClause *Sema::ActOnOpenMPProcBindClause(OpenMPProcBindClauseKind Kind,
7509 SourceLocation KindKwLoc,
7510 SourceLocation StartLoc,
7511 SourceLocation LParenLoc,
7512 SourceLocation EndLoc) {
7513 if (Kind == OMPC_PROC_BIND_unknown) {
7514 Diag(KindKwLoc, diag::err_omp_unexpected_clause_value)
7515 << getListOfPossibleValues(OMPC_proc_bind, /*First=*/0,
7516 /*Last=*/OMPC_PROC_BIND_unknown)
7517 << getOpenMPClauseName(OMPC_proc_bind);
7520 return new (Context)
7521 OMPProcBindClause(Kind, KindKwLoc, StartLoc, LParenLoc, EndLoc);
7524 OMPClause *Sema::ActOnOpenMPSingleExprWithArgClause(
7525 OpenMPClauseKind Kind, ArrayRef<unsigned> Argument, Expr *Expr,
7526 SourceLocation StartLoc, SourceLocation LParenLoc,
7527 ArrayRef<SourceLocation> ArgumentLoc, SourceLocation DelimLoc,
7528 SourceLocation EndLoc) {
7529 OMPClause *Res = nullptr;
7532 enum { Modifier1, Modifier2, ScheduleKind, NumberOfElements };
7533 assert(Argument.size() == NumberOfElements &&
7534 ArgumentLoc.size() == NumberOfElements);
7535 Res = ActOnOpenMPScheduleClause(
7536 static_cast<OpenMPScheduleClauseModifier>(Argument[Modifier1]),
7537 static_cast<OpenMPScheduleClauseModifier>(Argument[Modifier2]),
7538 static_cast<OpenMPScheduleClauseKind>(Argument[ScheduleKind]), Expr,
7539 StartLoc, LParenLoc, ArgumentLoc[Modifier1], ArgumentLoc[Modifier2],
7540 ArgumentLoc[ScheduleKind], DelimLoc, EndLoc);
7543 assert(Argument.size() == 1 && ArgumentLoc.size() == 1);
7544 Res = ActOnOpenMPIfClause(static_cast<OpenMPDirectiveKind>(Argument.back()),
7545 Expr, StartLoc, LParenLoc, ArgumentLoc.back(),
7548 case OMPC_dist_schedule:
7549 Res = ActOnOpenMPDistScheduleClause(
7550 static_cast<OpenMPDistScheduleClauseKind>(Argument.back()), Expr,
7551 StartLoc, LParenLoc, ArgumentLoc.back(), DelimLoc, EndLoc);
7553 case OMPC_defaultmap:
7554 enum { Modifier, DefaultmapKind };
7555 Res = ActOnOpenMPDefaultmapClause(
7556 static_cast<OpenMPDefaultmapClauseModifier>(Argument[Modifier]),
7557 static_cast<OpenMPDefaultmapClauseKind>(Argument[DefaultmapKind]),
7558 StartLoc, LParenLoc, ArgumentLoc[Modifier], ArgumentLoc[DefaultmapKind],
7562 case OMPC_num_threads:
7567 case OMPC_proc_bind:
7569 case OMPC_firstprivate:
7570 case OMPC_lastprivate:
7572 case OMPC_reduction:
7576 case OMPC_copyprivate:
7580 case OMPC_mergeable:
7581 case OMPC_threadprivate:
7593 case OMPC_num_teams:
7594 case OMPC_thread_limit:
7596 case OMPC_grainsize:
7598 case OMPC_num_tasks:
7604 case OMPC_use_device_ptr:
7605 case OMPC_is_device_ptr:
7606 llvm_unreachable("Clause is not allowed.");
7611 static bool checkScheduleModifiers(Sema &S, OpenMPScheduleClauseModifier M1,
7612 OpenMPScheduleClauseModifier M2,
7613 SourceLocation M1Loc, SourceLocation M2Loc) {
7614 if (M1 == OMPC_SCHEDULE_MODIFIER_unknown && M1Loc.isValid()) {
7615 SmallVector<unsigned, 2> Excluded;
7616 if (M2 != OMPC_SCHEDULE_MODIFIER_unknown)
7617 Excluded.push_back(M2);
7618 if (M2 == OMPC_SCHEDULE_MODIFIER_nonmonotonic)
7619 Excluded.push_back(OMPC_SCHEDULE_MODIFIER_monotonic);
7620 if (M2 == OMPC_SCHEDULE_MODIFIER_monotonic)
7621 Excluded.push_back(OMPC_SCHEDULE_MODIFIER_nonmonotonic);
7622 S.Diag(M1Loc, diag::err_omp_unexpected_clause_value)
7623 << getListOfPossibleValues(OMPC_schedule,
7624 /*First=*/OMPC_SCHEDULE_MODIFIER_unknown + 1,
7625 /*Last=*/OMPC_SCHEDULE_MODIFIER_last,
7627 << getOpenMPClauseName(OMPC_schedule);
7633 OMPClause *Sema::ActOnOpenMPScheduleClause(
7634 OpenMPScheduleClauseModifier M1, OpenMPScheduleClauseModifier M2,
7635 OpenMPScheduleClauseKind Kind, Expr *ChunkSize, SourceLocation StartLoc,
7636 SourceLocation LParenLoc, SourceLocation M1Loc, SourceLocation M2Loc,
7637 SourceLocation KindLoc, SourceLocation CommaLoc, SourceLocation EndLoc) {
7638 if (checkScheduleModifiers(*this, M1, M2, M1Loc, M2Loc) ||
7639 checkScheduleModifiers(*this, M2, M1, M2Loc, M1Loc))
7641 // OpenMP, 2.7.1, Loop Construct, Restrictions
7642 // Either the monotonic modifier or the nonmonotonic modifier can be specified
7644 if ((M1 == M2 && M1 != OMPC_SCHEDULE_MODIFIER_unknown) ||
7645 (M1 == OMPC_SCHEDULE_MODIFIER_monotonic &&
7646 M2 == OMPC_SCHEDULE_MODIFIER_nonmonotonic) ||
7647 (M1 == OMPC_SCHEDULE_MODIFIER_nonmonotonic &&
7648 M2 == OMPC_SCHEDULE_MODIFIER_monotonic)) {
7649 Diag(M2Loc, diag::err_omp_unexpected_schedule_modifier)
7650 << getOpenMPSimpleClauseTypeName(OMPC_schedule, M2)
7651 << getOpenMPSimpleClauseTypeName(OMPC_schedule, M1);
7654 if (Kind == OMPC_SCHEDULE_unknown) {
7656 if (M1Loc.isInvalid() && M2Loc.isInvalid()) {
7657 unsigned Exclude[] = {OMPC_SCHEDULE_unknown};
7658 Values = getListOfPossibleValues(OMPC_schedule, /*First=*/0,
7659 /*Last=*/OMPC_SCHEDULE_MODIFIER_last,
7662 Values = getListOfPossibleValues(OMPC_schedule, /*First=*/0,
7663 /*Last=*/OMPC_SCHEDULE_unknown);
7665 Diag(KindLoc, diag::err_omp_unexpected_clause_value)
7666 << Values << getOpenMPClauseName(OMPC_schedule);
7669 // OpenMP, 2.7.1, Loop Construct, Restrictions
7670 // The nonmonotonic modifier can only be specified with schedule(dynamic) or
7671 // schedule(guided).
7672 if ((M1 == OMPC_SCHEDULE_MODIFIER_nonmonotonic ||
7673 M2 == OMPC_SCHEDULE_MODIFIER_nonmonotonic) &&
7674 Kind != OMPC_SCHEDULE_dynamic && Kind != OMPC_SCHEDULE_guided) {
7675 Diag(M1 == OMPC_SCHEDULE_MODIFIER_nonmonotonic ? M1Loc : M2Loc,
7676 diag::err_omp_schedule_nonmonotonic_static);
7679 Expr *ValExpr = ChunkSize;
7680 Stmt *HelperValStmt = nullptr;
7682 if (!ChunkSize->isValueDependent() && !ChunkSize->isTypeDependent() &&
7683 !ChunkSize->isInstantiationDependent() &&
7684 !ChunkSize->containsUnexpandedParameterPack()) {
7685 SourceLocation ChunkSizeLoc = ChunkSize->getLocStart();
7687 PerformOpenMPImplicitIntegerConversion(ChunkSizeLoc, ChunkSize);
7688 if (Val.isInvalid())
7691 ValExpr = Val.get();
7693 // OpenMP [2.7.1, Restrictions]
7694 // chunk_size must be a loop invariant integer expression with a positive
7696 llvm::APSInt Result;
7697 if (ValExpr->isIntegerConstantExpr(Result, Context)) {
7698 if (Result.isSigned() && !Result.isStrictlyPositive()) {
7699 Diag(ChunkSizeLoc, diag::err_omp_negative_expression_in_clause)
7700 << "schedule" << 1 << ChunkSize->getSourceRange();
7703 } else if (isParallelOrTaskRegion(DSAStack->getCurrentDirective()) &&
7704 !CurContext->isDependentContext()) {
7705 llvm::MapVector<Expr *, DeclRefExpr *> Captures;
7706 ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
7707 HelperValStmt = buildPreInits(Context, Captures);
7712 return new (Context)
7713 OMPScheduleClause(StartLoc, LParenLoc, KindLoc, CommaLoc, EndLoc, Kind,
7714 ValExpr, HelperValStmt, M1, M1Loc, M2, M2Loc);
7717 OMPClause *Sema::ActOnOpenMPClause(OpenMPClauseKind Kind,
7718 SourceLocation StartLoc,
7719 SourceLocation EndLoc) {
7720 OMPClause *Res = nullptr;
7723 Res = ActOnOpenMPOrderedClause(StartLoc, EndLoc);
7726 Res = ActOnOpenMPNowaitClause(StartLoc, EndLoc);
7729 Res = ActOnOpenMPUntiedClause(StartLoc, EndLoc);
7731 case OMPC_mergeable:
7732 Res = ActOnOpenMPMergeableClause(StartLoc, EndLoc);
7735 Res = ActOnOpenMPReadClause(StartLoc, EndLoc);
7738 Res = ActOnOpenMPWriteClause(StartLoc, EndLoc);
7741 Res = ActOnOpenMPUpdateClause(StartLoc, EndLoc);
7744 Res = ActOnOpenMPCaptureClause(StartLoc, EndLoc);
7747 Res = ActOnOpenMPSeqCstClause(StartLoc, EndLoc);
7750 Res = ActOnOpenMPThreadsClause(StartLoc, EndLoc);
7753 Res = ActOnOpenMPSIMDClause(StartLoc, EndLoc);
7756 Res = ActOnOpenMPNogroupClause(StartLoc, EndLoc);
7760 case OMPC_num_threads:
7766 case OMPC_firstprivate:
7767 case OMPC_lastprivate:
7769 case OMPC_reduction:
7773 case OMPC_copyprivate:
7775 case OMPC_proc_bind:
7776 case OMPC_threadprivate:
7781 case OMPC_num_teams:
7782 case OMPC_thread_limit:
7784 case OMPC_grainsize:
7785 case OMPC_num_tasks:
7787 case OMPC_dist_schedule:
7788 case OMPC_defaultmap:
7793 case OMPC_use_device_ptr:
7794 case OMPC_is_device_ptr:
7795 llvm_unreachable("Clause is not allowed.");
7800 OMPClause *Sema::ActOnOpenMPNowaitClause(SourceLocation StartLoc,
7801 SourceLocation EndLoc) {
7802 DSAStack->setNowaitRegion();
7803 return new (Context) OMPNowaitClause(StartLoc, EndLoc);
7806 OMPClause *Sema::ActOnOpenMPUntiedClause(SourceLocation StartLoc,
7807 SourceLocation EndLoc) {
7808 return new (Context) OMPUntiedClause(StartLoc, EndLoc);
7811 OMPClause *Sema::ActOnOpenMPMergeableClause(SourceLocation StartLoc,
7812 SourceLocation EndLoc) {
7813 return new (Context) OMPMergeableClause(StartLoc, EndLoc);
7816 OMPClause *Sema::ActOnOpenMPReadClause(SourceLocation StartLoc,
7817 SourceLocation EndLoc) {
7818 return new (Context) OMPReadClause(StartLoc, EndLoc);
7821 OMPClause *Sema::ActOnOpenMPWriteClause(SourceLocation StartLoc,
7822 SourceLocation EndLoc) {
7823 return new (Context) OMPWriteClause(StartLoc, EndLoc);
7826 OMPClause *Sema::ActOnOpenMPUpdateClause(SourceLocation StartLoc,
7827 SourceLocation EndLoc) {
7828 return new (Context) OMPUpdateClause(StartLoc, EndLoc);
7831 OMPClause *Sema::ActOnOpenMPCaptureClause(SourceLocation StartLoc,
7832 SourceLocation EndLoc) {
7833 return new (Context) OMPCaptureClause(StartLoc, EndLoc);
7836 OMPClause *Sema::ActOnOpenMPSeqCstClause(SourceLocation StartLoc,
7837 SourceLocation EndLoc) {
7838 return new (Context) OMPSeqCstClause(StartLoc, EndLoc);
7841 OMPClause *Sema::ActOnOpenMPThreadsClause(SourceLocation StartLoc,
7842 SourceLocation EndLoc) {
7843 return new (Context) OMPThreadsClause(StartLoc, EndLoc);
7846 OMPClause *Sema::ActOnOpenMPSIMDClause(SourceLocation StartLoc,
7847 SourceLocation EndLoc) {
7848 return new (Context) OMPSIMDClause(StartLoc, EndLoc);
7851 OMPClause *Sema::ActOnOpenMPNogroupClause(SourceLocation StartLoc,
7852 SourceLocation EndLoc) {
7853 return new (Context) OMPNogroupClause(StartLoc, EndLoc);
7856 OMPClause *Sema::ActOnOpenMPVarListClause(
7857 OpenMPClauseKind Kind, ArrayRef<Expr *> VarList, Expr *TailExpr,
7858 SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation ColonLoc,
7859 SourceLocation EndLoc, CXXScopeSpec &ReductionIdScopeSpec,
7860 const DeclarationNameInfo &ReductionId, OpenMPDependClauseKind DepKind,
7861 OpenMPLinearClauseKind LinKind, OpenMPMapClauseKind MapTypeModifier,
7862 OpenMPMapClauseKind MapType, bool IsMapTypeImplicit,
7863 SourceLocation DepLinMapLoc) {
7864 OMPClause *Res = nullptr;
7867 Res = ActOnOpenMPPrivateClause(VarList, StartLoc, LParenLoc, EndLoc);
7869 case OMPC_firstprivate:
7870 Res = ActOnOpenMPFirstprivateClause(VarList, StartLoc, LParenLoc, EndLoc);
7872 case OMPC_lastprivate:
7873 Res = ActOnOpenMPLastprivateClause(VarList, StartLoc, LParenLoc, EndLoc);
7876 Res = ActOnOpenMPSharedClause(VarList, StartLoc, LParenLoc, EndLoc);
7878 case OMPC_reduction:
7879 Res = ActOnOpenMPReductionClause(VarList, StartLoc, LParenLoc, ColonLoc,
7880 EndLoc, ReductionIdScopeSpec, ReductionId);
7883 Res = ActOnOpenMPLinearClause(VarList, TailExpr, StartLoc, LParenLoc,
7884 LinKind, DepLinMapLoc, ColonLoc, EndLoc);
7887 Res = ActOnOpenMPAlignedClause(VarList, TailExpr, StartLoc, LParenLoc,
7891 Res = ActOnOpenMPCopyinClause(VarList, StartLoc, LParenLoc, EndLoc);
7893 case OMPC_copyprivate:
7894 Res = ActOnOpenMPCopyprivateClause(VarList, StartLoc, LParenLoc, EndLoc);
7897 Res = ActOnOpenMPFlushClause(VarList, StartLoc, LParenLoc, EndLoc);
7900 Res = ActOnOpenMPDependClause(DepKind, DepLinMapLoc, ColonLoc, VarList,
7901 StartLoc, LParenLoc, EndLoc);
7904 Res = ActOnOpenMPMapClause(MapTypeModifier, MapType, IsMapTypeImplicit,
7905 DepLinMapLoc, ColonLoc, VarList, StartLoc,
7909 Res = ActOnOpenMPToClause(VarList, StartLoc, LParenLoc, EndLoc);
7912 Res = ActOnOpenMPFromClause(VarList, StartLoc, LParenLoc, EndLoc);
7914 case OMPC_use_device_ptr:
7915 Res = ActOnOpenMPUseDevicePtrClause(VarList, StartLoc, LParenLoc, EndLoc);
7917 case OMPC_is_device_ptr:
7918 Res = ActOnOpenMPIsDevicePtrClause(VarList, StartLoc, LParenLoc, EndLoc);
7922 case OMPC_num_threads:
7927 case OMPC_proc_bind:
7932 case OMPC_mergeable:
7933 case OMPC_threadprivate:
7942 case OMPC_num_teams:
7943 case OMPC_thread_limit:
7945 case OMPC_grainsize:
7947 case OMPC_num_tasks:
7949 case OMPC_dist_schedule:
7950 case OMPC_defaultmap:
7953 llvm_unreachable("Clause is not allowed.");
7958 ExprResult Sema::getOpenMPCapturedExpr(VarDecl *Capture, ExprValueKind VK,
7959 ExprObjectKind OK, SourceLocation Loc) {
7960 ExprResult Res = BuildDeclRefExpr(
7961 Capture, Capture->getType().getNonReferenceType(), VK_LValue, Loc);
7962 if (!Res.isUsable())
7964 if (OK == OK_Ordinary && !getLangOpts().CPlusPlus) {
7965 Res = CreateBuiltinUnaryOp(Loc, UO_Deref, Res.get());
7966 if (!Res.isUsable())
7969 if (VK != VK_LValue && Res.get()->isGLValue()) {
7970 Res = DefaultLvalueConversion(Res.get());
7971 if (!Res.isUsable())
7977 static std::pair<ValueDecl *, bool>
7978 getPrivateItem(Sema &S, Expr *&RefExpr, SourceLocation &ELoc,
7979 SourceRange &ERange, bool AllowArraySection = false) {
7980 if (RefExpr->isTypeDependent() || RefExpr->isValueDependent() ||
7981 RefExpr->containsUnexpandedParameterPack())
7982 return std::make_pair(nullptr, true);
7984 // OpenMP [3.1, C/C++]
7985 // A list item is a variable name.
7986 // OpenMP [2.9.3.3, Restrictions, p.1]
7987 // A variable that is part of another variable (as an array or
7988 // structure element) cannot appear in a private clause.
7989 RefExpr = RefExpr->IgnoreParens();
7994 } IsArrayExpr = NoArrayExpr;
7995 if (AllowArraySection) {
7996 if (auto *ASE = dyn_cast_or_null<ArraySubscriptExpr>(RefExpr)) {
7997 auto *Base = ASE->getBase()->IgnoreParenImpCasts();
7998 while (auto *TempASE = dyn_cast<ArraySubscriptExpr>(Base))
7999 Base = TempASE->getBase()->IgnoreParenImpCasts();
8001 IsArrayExpr = ArraySubscript;
8002 } else if (auto *OASE = dyn_cast_or_null<OMPArraySectionExpr>(RefExpr)) {
8003 auto *Base = OASE->getBase()->IgnoreParenImpCasts();
8004 while (auto *TempOASE = dyn_cast<OMPArraySectionExpr>(Base))
8005 Base = TempOASE->getBase()->IgnoreParenImpCasts();
8006 while (auto *TempASE = dyn_cast<ArraySubscriptExpr>(Base))
8007 Base = TempASE->getBase()->IgnoreParenImpCasts();
8009 IsArrayExpr = OMPArraySection;
8012 ELoc = RefExpr->getExprLoc();
8013 ERange = RefExpr->getSourceRange();
8014 RefExpr = RefExpr->IgnoreParenImpCasts();
8015 auto *DE = dyn_cast_or_null<DeclRefExpr>(RefExpr);
8016 auto *ME = dyn_cast_or_null<MemberExpr>(RefExpr);
8017 if ((!DE || !isa<VarDecl>(DE->getDecl())) &&
8018 (S.getCurrentThisType().isNull() || !ME ||
8019 !isa<CXXThisExpr>(ME->getBase()->IgnoreParenImpCasts()) ||
8020 !isa<FieldDecl>(ME->getMemberDecl()))) {
8021 if (IsArrayExpr != NoArrayExpr)
8022 S.Diag(ELoc, diag::err_omp_expected_base_var_name) << IsArrayExpr
8027 ? diag::err_omp_expected_var_name_member_expr_or_array_item
8028 : diag::err_omp_expected_var_name_member_expr)
8029 << (S.getCurrentThisType().isNull() ? 0 : 1) << ERange;
8031 return std::make_pair(nullptr, false);
8033 return std::make_pair(DE ? DE->getDecl() : ME->getMemberDecl(), false);
8036 OMPClause *Sema::ActOnOpenMPPrivateClause(ArrayRef<Expr *> VarList,
8037 SourceLocation StartLoc,
8038 SourceLocation LParenLoc,
8039 SourceLocation EndLoc) {
8040 SmallVector<Expr *, 8> Vars;
8041 SmallVector<Expr *, 8> PrivateCopies;
8042 for (auto &RefExpr : VarList) {
8043 assert(RefExpr && "NULL expr in OpenMP private clause.");
8044 SourceLocation ELoc;
8046 Expr *SimpleRefExpr = RefExpr;
8047 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
8049 // It will be analyzed later.
8050 Vars.push_back(RefExpr);
8051 PrivateCopies.push_back(nullptr);
8053 ValueDecl *D = Res.first;
8057 QualType Type = D->getType();
8058 auto *VD = dyn_cast<VarDecl>(D);
8060 // OpenMP [2.9.3.3, Restrictions, C/C++, p.3]
8061 // A variable that appears in a private clause must not have an incomplete
8062 // type or a reference type.
8063 if (RequireCompleteType(ELoc, Type, diag::err_omp_private_incomplete_type))
8065 Type = Type.getNonReferenceType();
8067 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
8069 // Variables with the predetermined data-sharing attributes may not be
8070 // listed in data-sharing attributes clauses, except for the cases
8071 // listed below. For these exceptions only, listing a predetermined
8072 // variable in a data-sharing attribute clause is allowed and overrides
8073 // the variable's predetermined data-sharing attributes.
8074 DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, false);
8075 if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_private) {
8076 Diag(ELoc, diag::err_omp_wrong_dsa) << getOpenMPClauseName(DVar.CKind)
8077 << getOpenMPClauseName(OMPC_private);
8078 ReportOriginalDSA(*this, DSAStack, D, DVar);
8082 auto CurrDir = DSAStack->getCurrentDirective();
8083 // Variably modified types are not supported for tasks.
8084 if (!Type->isAnyPointerType() && Type->isVariablyModifiedType() &&
8085 isOpenMPTaskingDirective(CurrDir)) {
8086 Diag(ELoc, diag::err_omp_variably_modified_type_not_supported)
8087 << getOpenMPClauseName(OMPC_private) << Type
8088 << getOpenMPDirectiveName(CurrDir);
8091 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
8092 Diag(D->getLocation(),
8093 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
8098 // OpenMP 4.5 [2.15.5.1, Restrictions, p.3]
8099 // A list item cannot appear in both a map clause and a data-sharing
8100 // attribute clause on the same construct
8101 if (CurrDir == OMPD_target || CurrDir == OMPD_target_parallel ||
8102 CurrDir == OMPD_target_teams ||
8103 CurrDir == OMPD_target_teams_distribute ||
8104 CurrDir == OMPD_target_teams_distribute_parallel_for ||
8105 CurrDir == OMPD_target_teams_distribute_parallel_for_simd ||
8106 CurrDir == OMPD_target_teams_distribute_simd ||
8107 CurrDir == OMPD_target_parallel_for_simd ||
8108 CurrDir == OMPD_target_parallel_for) {
8109 OpenMPClauseKind ConflictKind;
8110 if (DSAStack->checkMappableExprComponentListsForDecl(
8111 VD, /*CurrentRegionOnly=*/true,
8112 [&](OMPClauseMappableExprCommon::MappableExprComponentListRef,
8113 OpenMPClauseKind WhereFoundClauseKind) -> bool {
8114 ConflictKind = WhereFoundClauseKind;
8117 Diag(ELoc, diag::err_omp_variable_in_given_clause_and_dsa)
8118 << getOpenMPClauseName(OMPC_private)
8119 << getOpenMPClauseName(ConflictKind)
8120 << getOpenMPDirectiveName(CurrDir);
8121 ReportOriginalDSA(*this, DSAStack, D, DVar);
8126 // OpenMP [2.9.3.3, Restrictions, C/C++, p.1]
8127 // A variable of class type (or array thereof) that appears in a private
8128 // clause requires an accessible, unambiguous default constructor for the
8130 // Generate helper private variable and initialize it with the default
8131 // value. The address of the original variable is replaced by the address of
8132 // the new private variable in CodeGen. This new variable is not added to
8133 // IdResolver, so the code in the OpenMP region uses original variable for
8134 // proper diagnostics.
8135 Type = Type.getUnqualifiedType();
8136 auto VDPrivate = buildVarDecl(*this, ELoc, Type, D->getName(),
8137 D->hasAttrs() ? &D->getAttrs() : nullptr);
8138 ActOnUninitializedDecl(VDPrivate);
8139 if (VDPrivate->isInvalidDecl())
8141 auto VDPrivateRefExpr = buildDeclRefExpr(
8142 *this, VDPrivate, RefExpr->getType().getUnqualifiedType(), ELoc);
8144 DeclRefExpr *Ref = nullptr;
8145 if (!VD && !CurContext->isDependentContext())
8146 Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/false);
8147 DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_private, Ref);
8148 Vars.push_back((VD || CurContext->isDependentContext())
8149 ? RefExpr->IgnoreParens()
8151 PrivateCopies.push_back(VDPrivateRefExpr);
8157 return OMPPrivateClause::Create(Context, StartLoc, LParenLoc, EndLoc, Vars,
8162 class DiagsUninitializedSeveretyRAII {
8164 DiagnosticsEngine &Diags;
8165 SourceLocation SavedLoc;
8169 DiagsUninitializedSeveretyRAII(DiagnosticsEngine &Diags, SourceLocation Loc,
8171 : Diags(Diags), SavedLoc(Loc), IsIgnored(IsIgnored) {
8173 Diags.setSeverity(/*Diag*/ diag::warn_uninit_self_reference_in_init,
8174 /*Map*/ diag::Severity::Ignored, Loc);
8177 ~DiagsUninitializedSeveretyRAII() {
8179 Diags.popMappings(SavedLoc);
8184 OMPClause *Sema::ActOnOpenMPFirstprivateClause(ArrayRef<Expr *> VarList,
8185 SourceLocation StartLoc,
8186 SourceLocation LParenLoc,
8187 SourceLocation EndLoc) {
8188 SmallVector<Expr *, 8> Vars;
8189 SmallVector<Expr *, 8> PrivateCopies;
8190 SmallVector<Expr *, 8> Inits;
8191 SmallVector<Decl *, 4> ExprCaptures;
8192 bool IsImplicitClause =
8193 StartLoc.isInvalid() && LParenLoc.isInvalid() && EndLoc.isInvalid();
8194 auto ImplicitClauseLoc = DSAStack->getConstructLoc();
8196 for (auto &RefExpr : VarList) {
8197 assert(RefExpr && "NULL expr in OpenMP firstprivate clause.");
8198 SourceLocation ELoc;
8200 Expr *SimpleRefExpr = RefExpr;
8201 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
8203 // It will be analyzed later.
8204 Vars.push_back(RefExpr);
8205 PrivateCopies.push_back(nullptr);
8206 Inits.push_back(nullptr);
8208 ValueDecl *D = Res.first;
8212 ELoc = IsImplicitClause ? ImplicitClauseLoc : ELoc;
8213 QualType Type = D->getType();
8214 auto *VD = dyn_cast<VarDecl>(D);
8216 // OpenMP [2.9.3.3, Restrictions, C/C++, p.3]
8217 // A variable that appears in a private clause must not have an incomplete
8218 // type or a reference type.
8219 if (RequireCompleteType(ELoc, Type,
8220 diag::err_omp_firstprivate_incomplete_type))
8222 Type = Type.getNonReferenceType();
8224 // OpenMP [2.9.3.4, Restrictions, C/C++, p.1]
8225 // A variable of class type (or array thereof) that appears in a private
8226 // clause requires an accessible, unambiguous copy constructor for the
8228 auto ElemType = Context.getBaseElementType(Type).getNonReferenceType();
8230 // If an implicit firstprivate variable found it was checked already.
8231 DSAStackTy::DSAVarData TopDVar;
8232 if (!IsImplicitClause) {
8233 DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, false);
8235 bool IsConstant = ElemType.isConstant(Context);
8236 // OpenMP [2.4.13, Data-sharing Attribute Clauses]
8237 // A list item that specifies a given variable may not appear in more
8238 // than one clause on the same directive, except that a variable may be
8239 // specified in both firstprivate and lastprivate clauses.
8240 if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_firstprivate &&
8241 DVar.CKind != OMPC_lastprivate && DVar.RefExpr) {
8242 Diag(ELoc, diag::err_omp_wrong_dsa)
8243 << getOpenMPClauseName(DVar.CKind)
8244 << getOpenMPClauseName(OMPC_firstprivate);
8245 ReportOriginalDSA(*this, DSAStack, D, DVar);
8249 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
8251 // Variables with the predetermined data-sharing attributes may not be
8252 // listed in data-sharing attributes clauses, except for the cases
8253 // listed below. For these exceptions only, listing a predetermined
8254 // variable in a data-sharing attribute clause is allowed and overrides
8255 // the variable's predetermined data-sharing attributes.
8256 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
8257 // in a Construct, C/C++, p.2]
8258 // Variables with const-qualified type having no mutable member may be
8259 // listed in a firstprivate clause, even if they are static data members.
8260 if (!(IsConstant || (VD && VD->isStaticDataMember())) && !DVar.RefExpr &&
8261 DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_shared) {
8262 Diag(ELoc, diag::err_omp_wrong_dsa)
8263 << getOpenMPClauseName(DVar.CKind)
8264 << getOpenMPClauseName(OMPC_firstprivate);
8265 ReportOriginalDSA(*this, DSAStack, D, DVar);
8269 OpenMPDirectiveKind CurrDir = DSAStack->getCurrentDirective();
8270 // OpenMP [2.9.3.4, Restrictions, p.2]
8271 // A list item that is private within a parallel region must not appear
8272 // in a firstprivate clause on a worksharing construct if any of the
8273 // worksharing regions arising from the worksharing construct ever bind
8274 // to any of the parallel regions arising from the parallel construct.
8275 if (isOpenMPWorksharingDirective(CurrDir) &&
8276 !isOpenMPParallelDirective(CurrDir) &&
8277 !isOpenMPTeamsDirective(CurrDir)) {
8278 DVar = DSAStack->getImplicitDSA(D, true);
8279 if (DVar.CKind != OMPC_shared &&
8280 (isOpenMPParallelDirective(DVar.DKind) ||
8281 DVar.DKind == OMPD_unknown)) {
8282 Diag(ELoc, diag::err_omp_required_access)
8283 << getOpenMPClauseName(OMPC_firstprivate)
8284 << getOpenMPClauseName(OMPC_shared);
8285 ReportOriginalDSA(*this, DSAStack, D, DVar);
8289 // OpenMP [2.9.3.4, Restrictions, p.3]
8290 // A list item that appears in a reduction clause of a parallel construct
8291 // must not appear in a firstprivate clause on a worksharing or task
8292 // construct if any of the worksharing or task regions arising from the
8293 // worksharing or task construct ever bind to any of the parallel regions
8294 // arising from the parallel construct.
8295 // OpenMP [2.9.3.4, Restrictions, p.4]
8296 // A list item that appears in a reduction clause in worksharing
8297 // construct must not appear in a firstprivate clause in a task construct
8298 // encountered during execution of any of the worksharing regions arising
8299 // from the worksharing construct.
8300 if (isOpenMPTaskingDirective(CurrDir)) {
8301 DVar = DSAStack->hasInnermostDSA(
8302 D, [](OpenMPClauseKind C) -> bool { return C == OMPC_reduction; },
8303 [](OpenMPDirectiveKind K) -> bool {
8304 return isOpenMPParallelDirective(K) ||
8305 isOpenMPWorksharingDirective(K);
8308 if (DVar.CKind == OMPC_reduction &&
8309 (isOpenMPParallelDirective(DVar.DKind) ||
8310 isOpenMPWorksharingDirective(DVar.DKind))) {
8311 Diag(ELoc, diag::err_omp_parallel_reduction_in_task_firstprivate)
8312 << getOpenMPDirectiveName(DVar.DKind);
8313 ReportOriginalDSA(*this, DSAStack, D, DVar);
8318 // OpenMP 4.5 [2.15.3.4, Restrictions, p.3]
8319 // A list item that is private within a teams region must not appear in a
8320 // firstprivate clause on a distribute construct if any of the distribute
8321 // regions arising from the distribute construct ever bind to any of the
8322 // teams regions arising from the teams construct.
8323 // OpenMP 4.5 [2.15.3.4, Restrictions, p.3]
8324 // A list item that appears in a reduction clause of a teams construct
8325 // must not appear in a firstprivate clause on a distribute construct if
8326 // any of the distribute regions arising from the distribute construct
8327 // ever bind to any of the teams regions arising from the teams construct.
8328 // OpenMP 4.5 [2.10.8, Distribute Construct, p.3]
8329 // A list item may appear in a firstprivate or lastprivate clause but not
8331 if (CurrDir == OMPD_distribute) {
8332 DVar = DSAStack->hasInnermostDSA(
8333 D, [](OpenMPClauseKind C) -> bool { return C == OMPC_private; },
8334 [](OpenMPDirectiveKind K) -> bool {
8335 return isOpenMPTeamsDirective(K);
8338 if (DVar.CKind == OMPC_private && isOpenMPTeamsDirective(DVar.DKind)) {
8339 Diag(ELoc, diag::err_omp_firstprivate_distribute_private_teams);
8340 ReportOriginalDSA(*this, DSAStack, D, DVar);
8343 DVar = DSAStack->hasInnermostDSA(
8344 D, [](OpenMPClauseKind C) -> bool { return C == OMPC_reduction; },
8345 [](OpenMPDirectiveKind K) -> bool {
8346 return isOpenMPTeamsDirective(K);
8349 if (DVar.CKind == OMPC_reduction &&
8350 isOpenMPTeamsDirective(DVar.DKind)) {
8351 Diag(ELoc, diag::err_omp_firstprivate_distribute_in_teams_reduction);
8352 ReportOriginalDSA(*this, DSAStack, D, DVar);
8355 DVar = DSAStack->getTopDSA(D, false);
8356 if (DVar.CKind == OMPC_lastprivate) {
8357 Diag(ELoc, diag::err_omp_firstprivate_and_lastprivate_in_distribute);
8358 ReportOriginalDSA(*this, DSAStack, D, DVar);
8362 // OpenMP 4.5 [2.15.5.1, Restrictions, p.3]
8363 // A list item cannot appear in both a map clause and a data-sharing
8364 // attribute clause on the same construct
8365 if (CurrDir == OMPD_target || CurrDir == OMPD_target_parallel ||
8366 CurrDir == OMPD_target_teams ||
8367 CurrDir == OMPD_target_teams_distribute ||
8368 CurrDir == OMPD_target_teams_distribute_parallel_for ||
8369 CurrDir == OMPD_target_teams_distribute_parallel_for_simd ||
8370 CurrDir == OMPD_target_teams_distribute_simd ||
8371 CurrDir == OMPD_target_parallel_for_simd ||
8372 CurrDir == OMPD_target_parallel_for) {
8373 OpenMPClauseKind ConflictKind;
8374 if (DSAStack->checkMappableExprComponentListsForDecl(
8375 VD, /*CurrentRegionOnly=*/true,
8376 [&](OMPClauseMappableExprCommon::MappableExprComponentListRef,
8377 OpenMPClauseKind WhereFoundClauseKind) -> bool {
8378 ConflictKind = WhereFoundClauseKind;
8381 Diag(ELoc, diag::err_omp_variable_in_given_clause_and_dsa)
8382 << getOpenMPClauseName(OMPC_firstprivate)
8383 << getOpenMPClauseName(ConflictKind)
8384 << getOpenMPDirectiveName(DSAStack->getCurrentDirective());
8385 ReportOriginalDSA(*this, DSAStack, D, DVar);
8391 // Variably modified types are not supported for tasks.
8392 if (!Type->isAnyPointerType() && Type->isVariablyModifiedType() &&
8393 isOpenMPTaskingDirective(DSAStack->getCurrentDirective())) {
8394 Diag(ELoc, diag::err_omp_variably_modified_type_not_supported)
8395 << getOpenMPClauseName(OMPC_firstprivate) << Type
8396 << getOpenMPDirectiveName(DSAStack->getCurrentDirective());
8399 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
8400 Diag(D->getLocation(),
8401 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
8406 Type = Type.getUnqualifiedType();
8407 auto VDPrivate = buildVarDecl(*this, ELoc, Type, D->getName(),
8408 D->hasAttrs() ? &D->getAttrs() : nullptr);
8409 // Generate helper private variable and initialize it with the value of the
8410 // original variable. The address of the original variable is replaced by
8411 // the address of the new private variable in the CodeGen. This new variable
8412 // is not added to IdResolver, so the code in the OpenMP region uses
8413 // original variable for proper diagnostics and variable capturing.
8414 Expr *VDInitRefExpr = nullptr;
8415 // For arrays generate initializer for single element and replace it by the
8416 // original array element in CodeGen.
8417 if (Type->isArrayType()) {
8419 buildVarDecl(*this, RefExpr->getExprLoc(), ElemType, D->getName());
8420 VDInitRefExpr = buildDeclRefExpr(*this, VDInit, ElemType, ELoc);
8421 auto Init = DefaultLvalueConversion(VDInitRefExpr).get();
8422 ElemType = ElemType.getUnqualifiedType();
8423 auto *VDInitTemp = buildVarDecl(*this, RefExpr->getExprLoc(), ElemType,
8424 ".firstprivate.temp");
8425 InitializedEntity Entity =
8426 InitializedEntity::InitializeVariable(VDInitTemp);
8427 InitializationKind Kind = InitializationKind::CreateCopy(ELoc, ELoc);
8429 InitializationSequence InitSeq(*this, Entity, Kind, Init);
8430 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Init);
8431 if (Result.isInvalid())
8432 VDPrivate->setInvalidDecl();
8434 VDPrivate->setInit(Result.getAs<Expr>());
8435 // Remove temp variable declaration.
8436 Context.Deallocate(VDInitTemp);
8438 auto *VDInit = buildVarDecl(*this, RefExpr->getExprLoc(), Type,
8439 ".firstprivate.temp");
8440 VDInitRefExpr = buildDeclRefExpr(*this, VDInit, RefExpr->getType(),
8441 RefExpr->getExprLoc());
8442 AddInitializerToDecl(VDPrivate,
8443 DefaultLvalueConversion(VDInitRefExpr).get(),
8444 /*DirectInit=*/false);
8446 if (VDPrivate->isInvalidDecl()) {
8447 if (IsImplicitClause) {
8448 Diag(RefExpr->getExprLoc(),
8449 diag::note_omp_task_predetermined_firstprivate_here);
8453 CurContext->addDecl(VDPrivate);
8454 auto VDPrivateRefExpr = buildDeclRefExpr(
8455 *this, VDPrivate, RefExpr->getType().getUnqualifiedType(),
8456 RefExpr->getExprLoc());
8457 DeclRefExpr *Ref = nullptr;
8458 if (!VD && !CurContext->isDependentContext()) {
8459 if (TopDVar.CKind == OMPC_lastprivate)
8460 Ref = TopDVar.PrivateCopy;
8462 Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/true);
8463 if (!IsOpenMPCapturedDecl(D))
8464 ExprCaptures.push_back(Ref->getDecl());
8467 DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_firstprivate, Ref);
8468 Vars.push_back((VD || CurContext->isDependentContext())
8469 ? RefExpr->IgnoreParens()
8471 PrivateCopies.push_back(VDPrivateRefExpr);
8472 Inits.push_back(VDInitRefExpr);
8478 return OMPFirstprivateClause::Create(Context, StartLoc, LParenLoc, EndLoc,
8479 Vars, PrivateCopies, Inits,
8480 buildPreInits(Context, ExprCaptures));
8483 OMPClause *Sema::ActOnOpenMPLastprivateClause(ArrayRef<Expr *> VarList,
8484 SourceLocation StartLoc,
8485 SourceLocation LParenLoc,
8486 SourceLocation EndLoc) {
8487 SmallVector<Expr *, 8> Vars;
8488 SmallVector<Expr *, 8> SrcExprs;
8489 SmallVector<Expr *, 8> DstExprs;
8490 SmallVector<Expr *, 8> AssignmentOps;
8491 SmallVector<Decl *, 4> ExprCaptures;
8492 SmallVector<Expr *, 4> ExprPostUpdates;
8493 for (auto &RefExpr : VarList) {
8494 assert(RefExpr && "NULL expr in OpenMP lastprivate clause.");
8495 SourceLocation ELoc;
8497 Expr *SimpleRefExpr = RefExpr;
8498 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
8500 // It will be analyzed later.
8501 Vars.push_back(RefExpr);
8502 SrcExprs.push_back(nullptr);
8503 DstExprs.push_back(nullptr);
8504 AssignmentOps.push_back(nullptr);
8506 ValueDecl *D = Res.first;
8510 QualType Type = D->getType();
8511 auto *VD = dyn_cast<VarDecl>(D);
8513 // OpenMP [2.14.3.5, Restrictions, C/C++, p.2]
8514 // A variable that appears in a lastprivate clause must not have an
8515 // incomplete type or a reference type.
8516 if (RequireCompleteType(ELoc, Type,
8517 diag::err_omp_lastprivate_incomplete_type))
8519 Type = Type.getNonReferenceType();
8521 // OpenMP [2.14.1.1, Data-sharing Attribute Rules for Variables Referenced
8523 // Variables with the predetermined data-sharing attributes may not be
8524 // listed in data-sharing attributes clauses, except for the cases
8526 DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, false);
8527 if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_lastprivate &&
8528 DVar.CKind != OMPC_firstprivate &&
8529 (DVar.CKind != OMPC_private || DVar.RefExpr != nullptr)) {
8530 Diag(ELoc, diag::err_omp_wrong_dsa)
8531 << getOpenMPClauseName(DVar.CKind)
8532 << getOpenMPClauseName(OMPC_lastprivate);
8533 ReportOriginalDSA(*this, DSAStack, D, DVar);
8537 OpenMPDirectiveKind CurrDir = DSAStack->getCurrentDirective();
8538 // OpenMP [2.14.3.5, Restrictions, p.2]
8539 // A list item that is private within a parallel region, or that appears in
8540 // the reduction clause of a parallel construct, must not appear in a
8541 // lastprivate clause on a worksharing construct if any of the corresponding
8542 // worksharing regions ever binds to any of the corresponding parallel
8544 DSAStackTy::DSAVarData TopDVar = DVar;
8545 if (isOpenMPWorksharingDirective(CurrDir) &&
8546 !isOpenMPParallelDirective(CurrDir) &&
8547 !isOpenMPTeamsDirective(CurrDir)) {
8548 DVar = DSAStack->getImplicitDSA(D, true);
8549 if (DVar.CKind != OMPC_shared) {
8550 Diag(ELoc, diag::err_omp_required_access)
8551 << getOpenMPClauseName(OMPC_lastprivate)
8552 << getOpenMPClauseName(OMPC_shared);
8553 ReportOriginalDSA(*this, DSAStack, D, DVar);
8558 // OpenMP 4.5 [2.10.8, Distribute Construct, p.3]
8559 // A list item may appear in a firstprivate or lastprivate clause but not
8561 if (CurrDir == OMPD_distribute) {
8562 DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, false);
8563 if (DVar.CKind == OMPC_firstprivate) {
8564 Diag(ELoc, diag::err_omp_firstprivate_and_lastprivate_in_distribute);
8565 ReportOriginalDSA(*this, DSAStack, D, DVar);
8570 // OpenMP [2.14.3.5, Restrictions, C++, p.1,2]
8571 // A variable of class type (or array thereof) that appears in a
8572 // lastprivate clause requires an accessible, unambiguous default
8573 // constructor for the class type, unless the list item is also specified
8574 // in a firstprivate clause.
8575 // A variable of class type (or array thereof) that appears in a
8576 // lastprivate clause requires an accessible, unambiguous copy assignment
8577 // operator for the class type.
8578 Type = Context.getBaseElementType(Type).getNonReferenceType();
8579 auto *SrcVD = buildVarDecl(*this, ERange.getBegin(),
8580 Type.getUnqualifiedType(), ".lastprivate.src",
8581 D->hasAttrs() ? &D->getAttrs() : nullptr);
8582 auto *PseudoSrcExpr =
8583 buildDeclRefExpr(*this, SrcVD, Type.getUnqualifiedType(), ELoc);
8585 buildVarDecl(*this, ERange.getBegin(), Type, ".lastprivate.dst",
8586 D->hasAttrs() ? &D->getAttrs() : nullptr);
8587 auto *PseudoDstExpr = buildDeclRefExpr(*this, DstVD, Type, ELoc);
8588 // For arrays generate assignment operation for single element and replace
8589 // it by the original array element in CodeGen.
8590 auto AssignmentOp = BuildBinOp(/*S=*/nullptr, ELoc, BO_Assign,
8591 PseudoDstExpr, PseudoSrcExpr);
8592 if (AssignmentOp.isInvalid())
8594 AssignmentOp = ActOnFinishFullExpr(AssignmentOp.get(), ELoc,
8595 /*DiscardedValue=*/true);
8596 if (AssignmentOp.isInvalid())
8599 DeclRefExpr *Ref = nullptr;
8600 if (!VD && !CurContext->isDependentContext()) {
8601 if (TopDVar.CKind == OMPC_firstprivate)
8602 Ref = TopDVar.PrivateCopy;
8604 Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/false);
8605 if (!IsOpenMPCapturedDecl(D))
8606 ExprCaptures.push_back(Ref->getDecl());
8608 if (TopDVar.CKind == OMPC_firstprivate ||
8609 (!IsOpenMPCapturedDecl(D) &&
8610 Ref->getDecl()->hasAttr<OMPCaptureNoInitAttr>())) {
8611 ExprResult RefRes = DefaultLvalueConversion(Ref);
8612 if (!RefRes.isUsable())
8614 ExprResult PostUpdateRes =
8615 BuildBinOp(DSAStack->getCurScope(), ELoc, BO_Assign, SimpleRefExpr,
8617 if (!PostUpdateRes.isUsable())
8619 ExprPostUpdates.push_back(
8620 IgnoredValueConversions(PostUpdateRes.get()).get());
8623 DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_lastprivate, Ref);
8624 Vars.push_back((VD || CurContext->isDependentContext())
8625 ? RefExpr->IgnoreParens()
8627 SrcExprs.push_back(PseudoSrcExpr);
8628 DstExprs.push_back(PseudoDstExpr);
8629 AssignmentOps.push_back(AssignmentOp.get());
8635 return OMPLastprivateClause::Create(Context, StartLoc, LParenLoc, EndLoc,
8636 Vars, SrcExprs, DstExprs, AssignmentOps,
8637 buildPreInits(Context, ExprCaptures),
8638 buildPostUpdate(*this, ExprPostUpdates));
8641 OMPClause *Sema::ActOnOpenMPSharedClause(ArrayRef<Expr *> VarList,
8642 SourceLocation StartLoc,
8643 SourceLocation LParenLoc,
8644 SourceLocation EndLoc) {
8645 SmallVector<Expr *, 8> Vars;
8646 for (auto &RefExpr : VarList) {
8647 assert(RefExpr && "NULL expr in OpenMP lastprivate clause.");
8648 SourceLocation ELoc;
8650 Expr *SimpleRefExpr = RefExpr;
8651 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
8653 // It will be analyzed later.
8654 Vars.push_back(RefExpr);
8656 ValueDecl *D = Res.first;
8660 auto *VD = dyn_cast<VarDecl>(D);
8661 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
8663 // Variables with the predetermined data-sharing attributes may not be
8664 // listed in data-sharing attributes clauses, except for the cases
8665 // listed below. For these exceptions only, listing a predetermined
8666 // variable in a data-sharing attribute clause is allowed and overrides
8667 // the variable's predetermined data-sharing attributes.
8668 DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, false);
8669 if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_shared &&
8671 Diag(ELoc, diag::err_omp_wrong_dsa) << getOpenMPClauseName(DVar.CKind)
8672 << getOpenMPClauseName(OMPC_shared);
8673 ReportOriginalDSA(*this, DSAStack, D, DVar);
8677 DeclRefExpr *Ref = nullptr;
8678 if (!VD && IsOpenMPCapturedDecl(D) && !CurContext->isDependentContext())
8679 Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/true);
8680 DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_shared, Ref);
8681 Vars.push_back((VD || !Ref || CurContext->isDependentContext())
8682 ? RefExpr->IgnoreParens()
8689 return OMPSharedClause::Create(Context, StartLoc, LParenLoc, EndLoc, Vars);
8693 class DSARefChecker : public StmtVisitor<DSARefChecker, bool> {
8697 bool VisitDeclRefExpr(DeclRefExpr *E) {
8698 if (VarDecl *VD = dyn_cast<VarDecl>(E->getDecl())) {
8699 DSAStackTy::DSAVarData DVar = Stack->getTopDSA(VD, false);
8700 if (DVar.CKind == OMPC_shared && !DVar.RefExpr)
8702 if (DVar.CKind != OMPC_unknown)
8704 DSAStackTy::DSAVarData DVarPrivate = Stack->hasDSA(
8705 VD, isOpenMPPrivate, [](OpenMPDirectiveKind) -> bool { return true; },
8707 if (DVarPrivate.CKind != OMPC_unknown)
8713 bool VisitStmt(Stmt *S) {
8714 for (auto Child : S->children()) {
8715 if (Child && Visit(Child))
8720 explicit DSARefChecker(DSAStackTy *S) : Stack(S) {}
8725 // Transform MemberExpression for specified FieldDecl of current class to
8726 // DeclRefExpr to specified OMPCapturedExprDecl.
8727 class TransformExprToCaptures : public TreeTransform<TransformExprToCaptures> {
8728 typedef TreeTransform<TransformExprToCaptures> BaseTransform;
8730 DeclRefExpr *CapturedExpr;
8733 TransformExprToCaptures(Sema &SemaRef, ValueDecl *FieldDecl)
8734 : BaseTransform(SemaRef), Field(FieldDecl), CapturedExpr(nullptr) {}
8736 ExprResult TransformMemberExpr(MemberExpr *E) {
8737 if (isa<CXXThisExpr>(E->getBase()->IgnoreParenImpCasts()) &&
8738 E->getMemberDecl() == Field) {
8739 CapturedExpr = buildCapture(SemaRef, Field, E, /*WithInit=*/false);
8740 return CapturedExpr;
8742 return BaseTransform::TransformMemberExpr(E);
8744 DeclRefExpr *getCapturedExpr() { return CapturedExpr; }
8748 template <typename T>
8749 static T filterLookupForUDR(SmallVectorImpl<UnresolvedSet<8>> &Lookups,
8750 const llvm::function_ref<T(ValueDecl *)> &Gen) {
8751 for (auto &Set : Lookups) {
8752 for (auto *D : Set) {
8753 if (auto Res = Gen(cast<ValueDecl>(D)))
8761 buildDeclareReductionRef(Sema &SemaRef, SourceLocation Loc, SourceRange Range,
8762 Scope *S, CXXScopeSpec &ReductionIdScopeSpec,
8763 const DeclarationNameInfo &ReductionId, QualType Ty,
8764 CXXCastPath &BasePath, Expr *UnresolvedReduction) {
8765 if (ReductionIdScopeSpec.isInvalid())
8767 SmallVector<UnresolvedSet<8>, 4> Lookups;
8769 LookupResult Lookup(SemaRef, ReductionId, Sema::LookupOMPReductionName);
8770 Lookup.suppressDiagnostics();
8771 while (S && SemaRef.LookupParsedName(Lookup, S, &ReductionIdScopeSpec)) {
8772 auto *D = Lookup.getRepresentativeDecl();
8775 } while (S && !S->isDeclScope(D));
8778 Lookups.push_back(UnresolvedSet<8>());
8779 Lookups.back().append(Lookup.begin(), Lookup.end());
8782 } else if (auto *ULE =
8783 cast_or_null<UnresolvedLookupExpr>(UnresolvedReduction)) {
8784 Lookups.push_back(UnresolvedSet<8>());
8785 Decl *PrevD = nullptr;
8786 for (auto *D : ULE->decls()) {
8788 Lookups.push_back(UnresolvedSet<8>());
8789 else if (auto *DRD = cast<OMPDeclareReductionDecl>(D))
8790 Lookups.back().addDecl(DRD);
8794 if (Ty->isDependentType() || Ty->isInstantiationDependentType() ||
8795 Ty->containsUnexpandedParameterPack() ||
8796 filterLookupForUDR<bool>(Lookups, [](ValueDecl *D) -> bool {
8797 return !D->isInvalidDecl() &&
8798 (D->getType()->isDependentType() ||
8799 D->getType()->isInstantiationDependentType() ||
8800 D->getType()->containsUnexpandedParameterPack());
8802 UnresolvedSet<8> ResSet;
8803 for (auto &Set : Lookups) {
8804 ResSet.append(Set.begin(), Set.end());
8805 // The last item marks the end of all declarations at the specified scope.
8806 ResSet.addDecl(Set[Set.size() - 1]);
8808 return UnresolvedLookupExpr::Create(
8809 SemaRef.Context, /*NamingClass=*/nullptr,
8810 ReductionIdScopeSpec.getWithLocInContext(SemaRef.Context), ReductionId,
8811 /*ADL=*/true, /*Overloaded=*/true, ResSet.begin(), ResSet.end());
8813 if (auto *VD = filterLookupForUDR<ValueDecl *>(
8814 Lookups, [&SemaRef, Ty](ValueDecl *D) -> ValueDecl * {
8815 if (!D->isInvalidDecl() &&
8816 SemaRef.Context.hasSameType(D->getType(), Ty))
8820 return SemaRef.BuildDeclRefExpr(VD, Ty, VK_LValue, Loc);
8821 if (auto *VD = filterLookupForUDR<ValueDecl *>(
8822 Lookups, [&SemaRef, Ty, Loc](ValueDecl *D) -> ValueDecl * {
8823 if (!D->isInvalidDecl() &&
8824 SemaRef.IsDerivedFrom(Loc, Ty, D->getType()) &&
8825 !Ty.isMoreQualifiedThan(D->getType()))
8829 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
8830 /*DetectVirtual=*/false);
8831 if (SemaRef.IsDerivedFrom(Loc, Ty, VD->getType(), Paths)) {
8832 if (!Paths.isAmbiguous(SemaRef.Context.getCanonicalType(
8833 VD->getType().getUnqualifiedType()))) {
8834 if (SemaRef.CheckBaseClassAccess(Loc, VD->getType(), Ty, Paths.front(),
8836 Sema::AR_inaccessible) {
8837 SemaRef.BuildBasePathArray(Paths, BasePath);
8838 return SemaRef.BuildDeclRefExpr(VD, Ty, VK_LValue, Loc);
8843 if (ReductionIdScopeSpec.isSet()) {
8844 SemaRef.Diag(Loc, diag::err_omp_not_resolved_reduction_identifier) << Range;
8850 OMPClause *Sema::ActOnOpenMPReductionClause(
8851 ArrayRef<Expr *> VarList, SourceLocation StartLoc, SourceLocation LParenLoc,
8852 SourceLocation ColonLoc, SourceLocation EndLoc,
8853 CXXScopeSpec &ReductionIdScopeSpec, const DeclarationNameInfo &ReductionId,
8854 ArrayRef<Expr *> UnresolvedReductions) {
8855 auto DN = ReductionId.getName();
8856 auto OOK = DN.getCXXOverloadedOperator();
8857 BinaryOperatorKind BOK = BO_Comma;
8859 // OpenMP [2.14.3.6, reduction clause]
8861 // reduction-identifier is either an identifier or one of the following
8862 // operators: +, -, *, &, |, ^, && and ||
8864 // reduction-identifier is either an id-expression or one of the following
8865 // operators: +, -, *, &, |, ^, && and ||
8866 // FIXME: Only 'min' and 'max' identifiers are supported for now.
8893 case OO_Array_Delete:
8902 case OO_GreaterEqual:
8907 case OO_PercentEqual:
8912 case OO_GreaterGreater:
8913 case OO_LessLessEqual:
8914 case OO_GreaterGreaterEqual:
8916 case OO_ExclaimEqual:
8924 case OO_Conditional:
8926 case NUM_OVERLOADED_OPERATORS:
8927 llvm_unreachable("Unexpected reduction identifier");
8929 if (auto II = DN.getAsIdentifierInfo()) {
8930 if (II->isStr("max"))
8932 else if (II->isStr("min"))
8937 SourceRange ReductionIdRange;
8938 if (ReductionIdScopeSpec.isValid())
8939 ReductionIdRange.setBegin(ReductionIdScopeSpec.getBeginLoc());
8940 ReductionIdRange.setEnd(ReductionId.getEndLoc());
8942 SmallVector<Expr *, 8> Vars;
8943 SmallVector<Expr *, 8> Privates;
8944 SmallVector<Expr *, 8> LHSs;
8945 SmallVector<Expr *, 8> RHSs;
8946 SmallVector<Expr *, 8> ReductionOps;
8947 SmallVector<Decl *, 4> ExprCaptures;
8948 SmallVector<Expr *, 4> ExprPostUpdates;
8949 auto IR = UnresolvedReductions.begin(), ER = UnresolvedReductions.end();
8950 bool FirstIter = true;
8951 for (auto RefExpr : VarList) {
8952 assert(RefExpr && "nullptr expr in OpenMP reduction clause.");
8953 // OpenMP [2.1, C/C++]
8954 // A list item is a variable or array section, subject to the restrictions
8955 // specified in Section 2.4 on page 42 and in each of the sections
8956 // describing clauses and directives for which a list appears.
8957 // OpenMP [2.14.3.3, Restrictions, p.1]
8958 // A variable that is part of another variable (as an array or
8959 // structure element) cannot appear in a private clause.
8960 if (!FirstIter && IR != ER)
8963 SourceLocation ELoc;
8965 Expr *SimpleRefExpr = RefExpr;
8966 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange,
8967 /*AllowArraySection=*/true);
8969 // It will be analyzed later.
8970 Vars.push_back(RefExpr);
8971 Privates.push_back(nullptr);
8972 LHSs.push_back(nullptr);
8973 RHSs.push_back(nullptr);
8974 // Try to find 'declare reduction' corresponding construct before using
8975 // builtin/overloaded operators.
8976 QualType Type = Context.DependentTy;
8977 CXXCastPath BasePath;
8978 ExprResult DeclareReductionRef = buildDeclareReductionRef(
8979 *this, ELoc, ERange, DSAStack->getCurScope(), ReductionIdScopeSpec,
8980 ReductionId, Type, BasePath, IR == ER ? nullptr : *IR);
8981 if (CurContext->isDependentContext() &&
8982 (DeclareReductionRef.isUnset() ||
8983 isa<UnresolvedLookupExpr>(DeclareReductionRef.get())))
8984 ReductionOps.push_back(DeclareReductionRef.get());
8986 ReductionOps.push_back(nullptr);
8988 ValueDecl *D = Res.first;
8993 auto *ASE = dyn_cast<ArraySubscriptExpr>(RefExpr->IgnoreParens());
8994 auto *OASE = dyn_cast<OMPArraySectionExpr>(RefExpr->IgnoreParens());
8996 Type = ASE->getType().getNonReferenceType();
8998 auto BaseType = OMPArraySectionExpr::getBaseOriginalType(OASE->getBase());
8999 if (auto *ATy = BaseType->getAsArrayTypeUnsafe())
9000 Type = ATy->getElementType();
9002 Type = BaseType->getPointeeType();
9003 Type = Type.getNonReferenceType();
9005 Type = Context.getBaseElementType(D->getType().getNonReferenceType());
9006 auto *VD = dyn_cast<VarDecl>(D);
9008 // OpenMP [2.9.3.3, Restrictions, C/C++, p.3]
9009 // A variable that appears in a private clause must not have an incomplete
9010 // type or a reference type.
9011 if (RequireCompleteType(ELoc, Type,
9012 diag::err_omp_reduction_incomplete_type))
9014 // OpenMP [2.14.3.6, reduction clause, Restrictions]
9015 // A list item that appears in a reduction clause must not be
9017 if (Type.getNonReferenceType().isConstant(Context)) {
9018 Diag(ELoc, diag::err_omp_const_reduction_list_item)
9019 << getOpenMPClauseName(OMPC_reduction) << Type << ERange;
9020 if (!ASE && !OASE) {
9021 bool IsDecl = !VD ||
9022 VD->isThisDeclarationADefinition(Context) ==
9023 VarDecl::DeclarationOnly;
9024 Diag(D->getLocation(),
9025 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
9030 // OpenMP [2.9.3.6, Restrictions, C/C++, p.4]
9031 // If a list-item is a reference type then it must bind to the same object
9032 // for all threads of the team.
9033 if (!ASE && !OASE && VD) {
9034 VarDecl *VDDef = VD->getDefinition();
9035 if (VD->getType()->isReferenceType() && VDDef && VDDef->hasInit()) {
9036 DSARefChecker Check(DSAStack);
9037 if (Check.Visit(VDDef->getInit())) {
9038 Diag(ELoc, diag::err_omp_reduction_ref_type_arg) << ERange;
9039 Diag(VDDef->getLocation(), diag::note_defined_here) << VDDef;
9045 // OpenMP [2.14.1.1, Data-sharing Attribute Rules for Variables Referenced
9047 // Variables with the predetermined data-sharing attributes may not be
9048 // listed in data-sharing attributes clauses, except for the cases
9049 // listed below. For these exceptions only, listing a predetermined
9050 // variable in a data-sharing attribute clause is allowed and overrides
9051 // the variable's predetermined data-sharing attributes.
9052 // OpenMP [2.14.3.6, Restrictions, p.3]
9053 // Any number of reduction clauses can be specified on the directive,
9054 // but a list item can appear only once in the reduction clauses for that
9056 DSAStackTy::DSAVarData DVar;
9057 DVar = DSAStack->getTopDSA(D, false);
9058 if (DVar.CKind == OMPC_reduction) {
9059 Diag(ELoc, diag::err_omp_once_referenced)
9060 << getOpenMPClauseName(OMPC_reduction);
9062 Diag(DVar.RefExpr->getExprLoc(), diag::note_omp_referenced);
9063 } else if (DVar.CKind != OMPC_unknown) {
9064 Diag(ELoc, diag::err_omp_wrong_dsa)
9065 << getOpenMPClauseName(DVar.CKind)
9066 << getOpenMPClauseName(OMPC_reduction);
9067 ReportOriginalDSA(*this, DSAStack, D, DVar);
9071 // OpenMP [2.14.3.6, Restrictions, p.1]
9072 // A list item that appears in a reduction clause of a worksharing
9073 // construct must be shared in the parallel regions to which any of the
9074 // worksharing regions arising from the worksharing construct bind.
9075 OpenMPDirectiveKind CurrDir = DSAStack->getCurrentDirective();
9076 if (isOpenMPWorksharingDirective(CurrDir) &&
9077 !isOpenMPParallelDirective(CurrDir) &&
9078 !isOpenMPTeamsDirective(CurrDir)) {
9079 DVar = DSAStack->getImplicitDSA(D, true);
9080 if (DVar.CKind != OMPC_shared) {
9081 Diag(ELoc, diag::err_omp_required_access)
9082 << getOpenMPClauseName(OMPC_reduction)
9083 << getOpenMPClauseName(OMPC_shared);
9084 ReportOriginalDSA(*this, DSAStack, D, DVar);
9089 // Try to find 'declare reduction' corresponding construct before using
9090 // builtin/overloaded operators.
9091 CXXCastPath BasePath;
9092 ExprResult DeclareReductionRef = buildDeclareReductionRef(
9093 *this, ELoc, ERange, DSAStack->getCurScope(), ReductionIdScopeSpec,
9094 ReductionId, Type, BasePath, IR == ER ? nullptr : *IR);
9095 if (DeclareReductionRef.isInvalid())
9097 if (CurContext->isDependentContext() &&
9098 (DeclareReductionRef.isUnset() ||
9099 isa<UnresolvedLookupExpr>(DeclareReductionRef.get()))) {
9100 Vars.push_back(RefExpr);
9101 Privates.push_back(nullptr);
9102 LHSs.push_back(nullptr);
9103 RHSs.push_back(nullptr);
9104 ReductionOps.push_back(DeclareReductionRef.get());
9107 if (BOK == BO_Comma && DeclareReductionRef.isUnset()) {
9108 // Not allowed reduction identifier is found.
9109 Diag(ReductionId.getLocStart(),
9110 diag::err_omp_unknown_reduction_identifier)
9111 << Type << ReductionIdRange;
9115 // OpenMP [2.14.3.6, reduction clause, Restrictions]
9116 // The type of a list item that appears in a reduction clause must be valid
9117 // for the reduction-identifier. For a max or min reduction in C, the type
9118 // of the list item must be an allowed arithmetic data type: char, int,
9119 // float, double, or _Bool, possibly modified with long, short, signed, or
9120 // unsigned. For a max or min reduction in C++, the type of the list item
9121 // must be an allowed arithmetic data type: char, wchar_t, int, float,
9122 // double, or bool, possibly modified with long, short, signed, or unsigned.
9123 if (DeclareReductionRef.isUnset()) {
9124 if ((BOK == BO_GT || BOK == BO_LT) &&
9125 !(Type->isScalarType() ||
9126 (getLangOpts().CPlusPlus && Type->isArithmeticType()))) {
9127 Diag(ELoc, diag::err_omp_clause_not_arithmetic_type_arg)
9128 << getLangOpts().CPlusPlus;
9129 if (!ASE && !OASE) {
9130 bool IsDecl = !VD ||
9131 VD->isThisDeclarationADefinition(Context) ==
9132 VarDecl::DeclarationOnly;
9133 Diag(D->getLocation(),
9134 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
9139 if ((BOK == BO_OrAssign || BOK == BO_AndAssign || BOK == BO_XorAssign) &&
9140 !getLangOpts().CPlusPlus && Type->isFloatingType()) {
9141 Diag(ELoc, diag::err_omp_clause_floating_type_arg);
9142 if (!ASE && !OASE) {
9143 bool IsDecl = !VD ||
9144 VD->isThisDeclarationADefinition(Context) ==
9145 VarDecl::DeclarationOnly;
9146 Diag(D->getLocation(),
9147 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
9154 Type = Type.getNonLValueExprType(Context).getUnqualifiedType();
9155 auto *LHSVD = buildVarDecl(*this, ELoc, Type, ".reduction.lhs",
9156 D->hasAttrs() ? &D->getAttrs() : nullptr);
9157 auto *RHSVD = buildVarDecl(*this, ELoc, Type, D->getName(),
9158 D->hasAttrs() ? &D->getAttrs() : nullptr);
9159 auto PrivateTy = Type;
9162 D->getType().getNonReferenceType()->isVariablyModifiedType())) {
9163 // For arrays/array sections only:
9164 // Create pseudo array type for private copy. The size for this array will
9165 // be generated during codegen.
9166 // For array subscripts or single variables Private Ty is the same as Type
9167 // (type of the variable or single array element).
9168 PrivateTy = Context.getVariableArrayType(
9169 Type, new (Context) OpaqueValueExpr(SourceLocation(),
9170 Context.getSizeType(), VK_RValue),
9171 ArrayType::Normal, /*IndexTypeQuals=*/0, SourceRange());
9172 } else if (!ASE && !OASE &&
9173 Context.getAsArrayType(D->getType().getNonReferenceType()))
9174 PrivateTy = D->getType().getNonReferenceType();
9176 auto *PrivateVD = buildVarDecl(*this, ELoc, PrivateTy, D->getName(),
9177 D->hasAttrs() ? &D->getAttrs() : nullptr);
9178 // Add initializer for private variable.
9179 Expr *Init = nullptr;
9180 auto *LHSDRE = buildDeclRefExpr(*this, LHSVD, Type, ELoc);
9181 auto *RHSDRE = buildDeclRefExpr(*this, RHSVD, Type, ELoc);
9182 if (DeclareReductionRef.isUsable()) {
9183 auto *DRDRef = DeclareReductionRef.getAs<DeclRefExpr>();
9184 auto *DRD = cast<OMPDeclareReductionDecl>(DRDRef->getDecl());
9185 if (DRD->getInitializer()) {
9187 RHSVD->setInit(DRDRef);
9188 RHSVD->setInitStyle(VarDecl::CallInit);
9196 // '+', '-', '^', '|', '||' reduction ops - initializer is '0'.
9197 if (Type->isScalarType() || Type->isAnyComplexType())
9198 Init = ActOnIntegerConstant(ELoc, /*Val=*/0).get();
9202 if (Type->isScalarType() || Type->isAnyComplexType()) {
9203 // '*' and '&&' reduction ops - initializer is '1'.
9204 Init = ActOnIntegerConstant(ELoc, /*Val=*/1).get();
9208 // '&' reduction op - initializer is '~0'.
9209 QualType OrigType = Type;
9210 if (auto *ComplexTy = OrigType->getAs<ComplexType>())
9211 Type = ComplexTy->getElementType();
9212 if (Type->isRealFloatingType()) {
9213 llvm::APFloat InitValue =
9214 llvm::APFloat::getAllOnesValue(Context.getTypeSize(Type),
9216 Init = FloatingLiteral::Create(Context, InitValue, /*isexact=*/true,
9218 } else if (Type->isScalarType()) {
9219 auto Size = Context.getTypeSize(Type);
9220 QualType IntTy = Context.getIntTypeForBitwidth(Size, /*Signed=*/0);
9221 llvm::APInt InitValue = llvm::APInt::getAllOnesValue(Size);
9222 Init = IntegerLiteral::Create(Context, InitValue, IntTy, ELoc);
9224 if (Init && OrigType->isAnyComplexType()) {
9225 // Init = 0xFFFF + 0xFFFFi;
9226 auto *Im = new (Context) ImaginaryLiteral(Init, OrigType);
9227 Init = CreateBuiltinBinOp(ELoc, BO_Add, Init, Im).get();
9234 // 'min' reduction op - initializer is 'Largest representable number in
9235 // the reduction list item type'.
9236 // 'max' reduction op - initializer is 'Least representable number in
9237 // the reduction list item type'.
9238 if (Type->isIntegerType() || Type->isPointerType()) {
9239 bool IsSigned = Type->hasSignedIntegerRepresentation();
9240 auto Size = Context.getTypeSize(Type);
9242 Context.getIntTypeForBitwidth(Size, /*Signed=*/IsSigned);
9243 llvm::APInt InitValue =
9245 ? IsSigned ? llvm::APInt::getSignedMinValue(Size)
9246 : llvm::APInt::getMinValue(Size)
9247 : IsSigned ? llvm::APInt::getSignedMaxValue(Size)
9248 : llvm::APInt::getMaxValue(Size);
9249 Init = IntegerLiteral::Create(Context, InitValue, IntTy, ELoc);
9250 if (Type->isPointerType()) {
9251 // Cast to pointer type.
9252 auto CastExpr = BuildCStyleCastExpr(
9253 SourceLocation(), Context.getTrivialTypeSourceInfo(Type, ELoc),
9254 SourceLocation(), Init);
9255 if (CastExpr.isInvalid())
9257 Init = CastExpr.get();
9259 } else if (Type->isRealFloatingType()) {
9260 llvm::APFloat InitValue = llvm::APFloat::getLargest(
9261 Context.getFloatTypeSemantics(Type), BOK != BO_LT);
9262 Init = FloatingLiteral::Create(Context, InitValue, /*isexact=*/true,
9290 llvm_unreachable("Unexpected reduction operation");
9293 if (Init && DeclareReductionRef.isUnset()) {
9294 AddInitializerToDecl(RHSVD, Init, /*DirectInit=*/false);
9296 ActOnUninitializedDecl(RHSVD);
9297 if (RHSVD->isInvalidDecl())
9299 if (!RHSVD->hasInit() && DeclareReductionRef.isUnset()) {
9300 Diag(ELoc, diag::err_omp_reduction_id_not_compatible) << Type
9301 << ReductionIdRange;
9304 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
9305 Diag(D->getLocation(),
9306 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
9310 // Store initializer for single element in private copy. Will be used during
9312 PrivateVD->setInit(RHSVD->getInit());
9313 PrivateVD->setInitStyle(RHSVD->getInitStyle());
9314 auto *PrivateDRE = buildDeclRefExpr(*this, PrivateVD, PrivateTy, ELoc);
9315 ExprResult ReductionOp;
9316 if (DeclareReductionRef.isUsable()) {
9317 QualType RedTy = DeclareReductionRef.get()->getType();
9318 QualType PtrRedTy = Context.getPointerType(RedTy);
9319 ExprResult LHS = CreateBuiltinUnaryOp(ELoc, UO_AddrOf, LHSDRE);
9320 ExprResult RHS = CreateBuiltinUnaryOp(ELoc, UO_AddrOf, RHSDRE);
9321 if (!BasePath.empty()) {
9322 LHS = DefaultLvalueConversion(LHS.get());
9323 RHS = DefaultLvalueConversion(RHS.get());
9324 LHS = ImplicitCastExpr::Create(Context, PtrRedTy,
9325 CK_UncheckedDerivedToBase, LHS.get(),
9326 &BasePath, LHS.get()->getValueKind());
9327 RHS = ImplicitCastExpr::Create(Context, PtrRedTy,
9328 CK_UncheckedDerivedToBase, RHS.get(),
9329 &BasePath, RHS.get()->getValueKind());
9331 FunctionProtoType::ExtProtoInfo EPI;
9332 QualType Params[] = {PtrRedTy, PtrRedTy};
9333 QualType FnTy = Context.getFunctionType(Context.VoidTy, Params, EPI);
9334 auto *OVE = new (Context) OpaqueValueExpr(
9335 ELoc, Context.getPointerType(FnTy), VK_RValue, OK_Ordinary,
9336 DefaultLvalueConversion(DeclareReductionRef.get()).get());
9337 Expr *Args[] = {LHS.get(), RHS.get()};
9338 ReductionOp = new (Context)
9339 CallExpr(Context, OVE, Args, Context.VoidTy, VK_RValue, ELoc);
9341 ReductionOp = BuildBinOp(DSAStack->getCurScope(),
9342 ReductionId.getLocStart(), BOK, LHSDRE, RHSDRE);
9343 if (ReductionOp.isUsable()) {
9344 if (BOK != BO_LT && BOK != BO_GT) {
9346 BuildBinOp(DSAStack->getCurScope(), ReductionId.getLocStart(),
9347 BO_Assign, LHSDRE, ReductionOp.get());
9349 auto *ConditionalOp = new (Context) ConditionalOperator(
9350 ReductionOp.get(), SourceLocation(), LHSDRE, SourceLocation(),
9351 RHSDRE, Type, VK_LValue, OK_Ordinary);
9353 BuildBinOp(DSAStack->getCurScope(), ReductionId.getLocStart(),
9354 BO_Assign, LHSDRE, ConditionalOp);
9356 ReductionOp = ActOnFinishFullExpr(ReductionOp.get());
9358 if (ReductionOp.isInvalid())
9362 DeclRefExpr *Ref = nullptr;
9363 Expr *VarsExpr = RefExpr->IgnoreParens();
9364 if (!VD && !CurContext->isDependentContext()) {
9366 TransformExprToCaptures RebuildToCapture(*this, D);
9368 RebuildToCapture.TransformExpr(RefExpr->IgnoreParens()).get();
9369 Ref = RebuildToCapture.getCapturedExpr();
9372 buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/false);
9374 if (!IsOpenMPCapturedDecl(D)) {
9375 ExprCaptures.push_back(Ref->getDecl());
9376 if (Ref->getDecl()->hasAttr<OMPCaptureNoInitAttr>()) {
9377 ExprResult RefRes = DefaultLvalueConversion(Ref);
9378 if (!RefRes.isUsable())
9380 ExprResult PostUpdateRes =
9381 BuildBinOp(DSAStack->getCurScope(), ELoc, BO_Assign,
9382 SimpleRefExpr, RefRes.get());
9383 if (!PostUpdateRes.isUsable())
9385 ExprPostUpdates.push_back(
9386 IgnoredValueConversions(PostUpdateRes.get()).get());
9390 DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_reduction, Ref);
9391 Vars.push_back(VarsExpr);
9392 Privates.push_back(PrivateDRE);
9393 LHSs.push_back(LHSDRE);
9394 RHSs.push_back(RHSDRE);
9395 ReductionOps.push_back(ReductionOp.get());
9401 return OMPReductionClause::Create(
9402 Context, StartLoc, LParenLoc, ColonLoc, EndLoc, Vars,
9403 ReductionIdScopeSpec.getWithLocInContext(Context), ReductionId, Privates,
9404 LHSs, RHSs, ReductionOps, buildPreInits(Context, ExprCaptures),
9405 buildPostUpdate(*this, ExprPostUpdates));
9408 bool Sema::CheckOpenMPLinearModifier(OpenMPLinearClauseKind LinKind,
9409 SourceLocation LinLoc) {
9410 if ((!LangOpts.CPlusPlus && LinKind != OMPC_LINEAR_val) ||
9411 LinKind == OMPC_LINEAR_unknown) {
9412 Diag(LinLoc, diag::err_omp_wrong_linear_modifier) << LangOpts.CPlusPlus;
9418 bool Sema::CheckOpenMPLinearDecl(ValueDecl *D, SourceLocation ELoc,
9419 OpenMPLinearClauseKind LinKind,
9421 auto *VD = dyn_cast_or_null<VarDecl>(D);
9422 // A variable must not have an incomplete type or a reference type.
9423 if (RequireCompleteType(ELoc, Type, diag::err_omp_linear_incomplete_type))
9425 if ((LinKind == OMPC_LINEAR_uval || LinKind == OMPC_LINEAR_ref) &&
9426 !Type->isReferenceType()) {
9427 Diag(ELoc, diag::err_omp_wrong_linear_modifier_non_reference)
9428 << Type << getOpenMPSimpleClauseTypeName(OMPC_linear, LinKind);
9431 Type = Type.getNonReferenceType();
9433 // A list item must not be const-qualified.
9434 if (Type.isConstant(Context)) {
9435 Diag(ELoc, diag::err_omp_const_variable)
9436 << getOpenMPClauseName(OMPC_linear);
9440 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
9441 Diag(D->getLocation(),
9442 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
9448 // A list item must be of integral or pointer type.
9449 Type = Type.getUnqualifiedType().getCanonicalType();
9450 const auto *Ty = Type.getTypePtrOrNull();
9451 if (!Ty || (!Ty->isDependentType() && !Ty->isIntegralType(Context) &&
9452 !Ty->isPointerType())) {
9453 Diag(ELoc, diag::err_omp_linear_expected_int_or_ptr) << Type;
9457 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
9458 Diag(D->getLocation(),
9459 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
9467 OMPClause *Sema::ActOnOpenMPLinearClause(
9468 ArrayRef<Expr *> VarList, Expr *Step, SourceLocation StartLoc,
9469 SourceLocation LParenLoc, OpenMPLinearClauseKind LinKind,
9470 SourceLocation LinLoc, SourceLocation ColonLoc, SourceLocation EndLoc) {
9471 SmallVector<Expr *, 8> Vars;
9472 SmallVector<Expr *, 8> Privates;
9473 SmallVector<Expr *, 8> Inits;
9474 SmallVector<Decl *, 4> ExprCaptures;
9475 SmallVector<Expr *, 4> ExprPostUpdates;
9476 if (CheckOpenMPLinearModifier(LinKind, LinLoc))
9477 LinKind = OMPC_LINEAR_val;
9478 for (auto &RefExpr : VarList) {
9479 assert(RefExpr && "NULL expr in OpenMP linear clause.");
9480 SourceLocation ELoc;
9482 Expr *SimpleRefExpr = RefExpr;
9483 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange,
9484 /*AllowArraySection=*/false);
9486 // It will be analyzed later.
9487 Vars.push_back(RefExpr);
9488 Privates.push_back(nullptr);
9489 Inits.push_back(nullptr);
9491 ValueDecl *D = Res.first;
9495 QualType Type = D->getType();
9496 auto *VD = dyn_cast<VarDecl>(D);
9498 // OpenMP [2.14.3.7, linear clause]
9499 // A list-item cannot appear in more than one linear clause.
9500 // A list-item that appears in a linear clause cannot appear in any
9501 // other data-sharing attribute clause.
9502 DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, false);
9504 Diag(ELoc, diag::err_omp_wrong_dsa) << getOpenMPClauseName(DVar.CKind)
9505 << getOpenMPClauseName(OMPC_linear);
9506 ReportOriginalDSA(*this, DSAStack, D, DVar);
9510 if (CheckOpenMPLinearDecl(D, ELoc, LinKind, Type))
9512 Type = Type.getNonReferenceType().getUnqualifiedType().getCanonicalType();
9514 // Build private copy of original var.
9515 auto *Private = buildVarDecl(*this, ELoc, Type, D->getName(),
9516 D->hasAttrs() ? &D->getAttrs() : nullptr);
9517 auto *PrivateRef = buildDeclRefExpr(*this, Private, Type, ELoc);
9518 // Build var to save initial value.
9519 VarDecl *Init = buildVarDecl(*this, ELoc, Type, ".linear.start");
9521 DeclRefExpr *Ref = nullptr;
9522 if (!VD && !CurContext->isDependentContext()) {
9523 Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/false);
9524 if (!IsOpenMPCapturedDecl(D)) {
9525 ExprCaptures.push_back(Ref->getDecl());
9526 if (Ref->getDecl()->hasAttr<OMPCaptureNoInitAttr>()) {
9527 ExprResult RefRes = DefaultLvalueConversion(Ref);
9528 if (!RefRes.isUsable())
9530 ExprResult PostUpdateRes =
9531 BuildBinOp(DSAStack->getCurScope(), ELoc, BO_Assign,
9532 SimpleRefExpr, RefRes.get());
9533 if (!PostUpdateRes.isUsable())
9535 ExprPostUpdates.push_back(
9536 IgnoredValueConversions(PostUpdateRes.get()).get());
9540 if (LinKind == OMPC_LINEAR_uval)
9541 InitExpr = VD ? VD->getInit() : SimpleRefExpr;
9543 InitExpr = VD ? SimpleRefExpr : Ref;
9544 AddInitializerToDecl(Init, DefaultLvalueConversion(InitExpr).get(),
9545 /*DirectInit=*/false);
9546 auto InitRef = buildDeclRefExpr(*this, Init, Type, ELoc);
9548 DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_linear, Ref);
9549 Vars.push_back((VD || CurContext->isDependentContext())
9550 ? RefExpr->IgnoreParens()
9552 Privates.push_back(PrivateRef);
9553 Inits.push_back(InitRef);
9559 Expr *StepExpr = Step;
9560 Expr *CalcStepExpr = nullptr;
9561 if (Step && !Step->isValueDependent() && !Step->isTypeDependent() &&
9562 !Step->isInstantiationDependent() &&
9563 !Step->containsUnexpandedParameterPack()) {
9564 SourceLocation StepLoc = Step->getLocStart();
9565 ExprResult Val = PerformOpenMPImplicitIntegerConversion(StepLoc, Step);
9566 if (Val.isInvalid())
9568 StepExpr = Val.get();
9570 // Build var to save the step value.
9572 buildVarDecl(*this, StepLoc, StepExpr->getType(), ".linear.step");
9573 ExprResult SaveRef =
9574 buildDeclRefExpr(*this, SaveVar, StepExpr->getType(), StepLoc);
9575 ExprResult CalcStep =
9576 BuildBinOp(CurScope, StepLoc, BO_Assign, SaveRef.get(), StepExpr);
9577 CalcStep = ActOnFinishFullExpr(CalcStep.get());
9579 // Warn about zero linear step (it would be probably better specified as
9580 // making corresponding variables 'const').
9581 llvm::APSInt Result;
9582 bool IsConstant = StepExpr->isIntegerConstantExpr(Result, Context);
9583 if (IsConstant && !Result.isNegative() && !Result.isStrictlyPositive())
9584 Diag(StepLoc, diag::warn_omp_linear_step_zero) << Vars[0]
9585 << (Vars.size() > 1);
9586 if (!IsConstant && CalcStep.isUsable()) {
9587 // Calculate the step beforehand instead of doing this on each iteration.
9588 // (This is not used if the number of iterations may be kfold-ed).
9589 CalcStepExpr = CalcStep.get();
9593 return OMPLinearClause::Create(Context, StartLoc, LParenLoc, LinKind, LinLoc,
9594 ColonLoc, EndLoc, Vars, Privates, Inits,
9595 StepExpr, CalcStepExpr,
9596 buildPreInits(Context, ExprCaptures),
9597 buildPostUpdate(*this, ExprPostUpdates));
9600 static bool FinishOpenMPLinearClause(OMPLinearClause &Clause, DeclRefExpr *IV,
9601 Expr *NumIterations, Sema &SemaRef,
9602 Scope *S, DSAStackTy *Stack) {
9603 // Walk the vars and build update/final expressions for the CodeGen.
9604 SmallVector<Expr *, 8> Updates;
9605 SmallVector<Expr *, 8> Finals;
9606 Expr *Step = Clause.getStep();
9607 Expr *CalcStep = Clause.getCalcStep();
9608 // OpenMP [2.14.3.7, linear clause]
9609 // If linear-step is not specified it is assumed to be 1.
9610 if (Step == nullptr)
9611 Step = SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get();
9612 else if (CalcStep) {
9613 Step = cast<BinaryOperator>(CalcStep)->getLHS();
9615 bool HasErrors = false;
9616 auto CurInit = Clause.inits().begin();
9617 auto CurPrivate = Clause.privates().begin();
9618 auto LinKind = Clause.getModifier();
9619 for (auto &RefExpr : Clause.varlists()) {
9620 SourceLocation ELoc;
9622 Expr *SimpleRefExpr = RefExpr;
9623 auto Res = getPrivateItem(SemaRef, SimpleRefExpr, ELoc, ERange,
9624 /*AllowArraySection=*/false);
9625 ValueDecl *D = Res.first;
9626 if (Res.second || !D) {
9627 Updates.push_back(nullptr);
9628 Finals.push_back(nullptr);
9632 if (auto *CED = dyn_cast<OMPCapturedExprDecl>(D)) {
9633 D = cast<MemberExpr>(CED->getInit()->IgnoreParenImpCasts())
9636 auto &&Info = Stack->isLoopControlVariable(D);
9637 Expr *InitExpr = *CurInit;
9639 // Build privatized reference to the current linear var.
9640 auto *DE = cast<DeclRefExpr>(SimpleRefExpr);
9642 if (LinKind == OMPC_LINEAR_uval)
9643 CapturedRef = cast<VarDecl>(DE->getDecl())->getInit();
9646 buildDeclRefExpr(SemaRef, cast<VarDecl>(DE->getDecl()),
9647 DE->getType().getUnqualifiedType(), DE->getExprLoc(),
9648 /*RefersToCapture=*/true);
9650 // Build update: Var = InitExpr + IV * Step
9654 BuildCounterUpdate(SemaRef, S, RefExpr->getExprLoc(), *CurPrivate,
9655 InitExpr, IV, Step, /* Subtract */ false);
9657 Update = *CurPrivate;
9658 Update = SemaRef.ActOnFinishFullExpr(Update.get(), DE->getLocStart(),
9659 /*DiscardedValue=*/true);
9661 // Build final: Var = InitExpr + NumIterations * Step
9664 Final = BuildCounterUpdate(SemaRef, S, RefExpr->getExprLoc(), CapturedRef,
9665 InitExpr, NumIterations, Step,
9666 /* Subtract */ false);
9668 Final = *CurPrivate;
9669 Final = SemaRef.ActOnFinishFullExpr(Final.get(), DE->getLocStart(),
9670 /*DiscardedValue=*/true);
9672 if (!Update.isUsable() || !Final.isUsable()) {
9673 Updates.push_back(nullptr);
9674 Finals.push_back(nullptr);
9677 Updates.push_back(Update.get());
9678 Finals.push_back(Final.get());
9683 Clause.setUpdates(Updates);
9684 Clause.setFinals(Finals);
9688 OMPClause *Sema::ActOnOpenMPAlignedClause(
9689 ArrayRef<Expr *> VarList, Expr *Alignment, SourceLocation StartLoc,
9690 SourceLocation LParenLoc, SourceLocation ColonLoc, SourceLocation EndLoc) {
9692 SmallVector<Expr *, 8> Vars;
9693 for (auto &RefExpr : VarList) {
9694 assert(RefExpr && "NULL expr in OpenMP linear clause.");
9695 SourceLocation ELoc;
9697 Expr *SimpleRefExpr = RefExpr;
9698 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange,
9699 /*AllowArraySection=*/false);
9701 // It will be analyzed later.
9702 Vars.push_back(RefExpr);
9704 ValueDecl *D = Res.first;
9708 QualType QType = D->getType();
9709 auto *VD = dyn_cast<VarDecl>(D);
9711 // OpenMP [2.8.1, simd construct, Restrictions]
9712 // The type of list items appearing in the aligned clause must be
9713 // array, pointer, reference to array, or reference to pointer.
9714 QType = QType.getNonReferenceType().getUnqualifiedType().getCanonicalType();
9715 const Type *Ty = QType.getTypePtrOrNull();
9716 if (!Ty || (!Ty->isArrayType() && !Ty->isPointerType())) {
9717 Diag(ELoc, diag::err_omp_aligned_expected_array_or_ptr)
9718 << QType << getLangOpts().CPlusPlus << ERange;
9721 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
9722 Diag(D->getLocation(),
9723 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
9728 // OpenMP [2.8.1, simd construct, Restrictions]
9729 // A list-item cannot appear in more than one aligned clause.
9730 if (Expr *PrevRef = DSAStack->addUniqueAligned(D, SimpleRefExpr)) {
9731 Diag(ELoc, diag::err_omp_aligned_twice) << 0 << ERange;
9732 Diag(PrevRef->getExprLoc(), diag::note_omp_explicit_dsa)
9733 << getOpenMPClauseName(OMPC_aligned);
9737 DeclRefExpr *Ref = nullptr;
9738 if (!VD && IsOpenMPCapturedDecl(D))
9739 Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/true);
9740 Vars.push_back(DefaultFunctionArrayConversion(
9741 (VD || !Ref) ? RefExpr->IgnoreParens() : Ref)
9745 // OpenMP [2.8.1, simd construct, Description]
9746 // The parameter of the aligned clause, alignment, must be a constant
9747 // positive integer expression.
9748 // If no optional parameter is specified, implementation-defined default
9749 // alignments for SIMD instructions on the target platforms are assumed.
9750 if (Alignment != nullptr) {
9751 ExprResult AlignResult =
9752 VerifyPositiveIntegerConstantInClause(Alignment, OMPC_aligned);
9753 if (AlignResult.isInvalid())
9755 Alignment = AlignResult.get();
9760 return OMPAlignedClause::Create(Context, StartLoc, LParenLoc, ColonLoc,
9761 EndLoc, Vars, Alignment);
9764 OMPClause *Sema::ActOnOpenMPCopyinClause(ArrayRef<Expr *> VarList,
9765 SourceLocation StartLoc,
9766 SourceLocation LParenLoc,
9767 SourceLocation EndLoc) {
9768 SmallVector<Expr *, 8> Vars;
9769 SmallVector<Expr *, 8> SrcExprs;
9770 SmallVector<Expr *, 8> DstExprs;
9771 SmallVector<Expr *, 8> AssignmentOps;
9772 for (auto &RefExpr : VarList) {
9773 assert(RefExpr && "NULL expr in OpenMP copyin clause.");
9774 if (isa<DependentScopeDeclRefExpr>(RefExpr)) {
9775 // It will be analyzed later.
9776 Vars.push_back(RefExpr);
9777 SrcExprs.push_back(nullptr);
9778 DstExprs.push_back(nullptr);
9779 AssignmentOps.push_back(nullptr);
9783 SourceLocation ELoc = RefExpr->getExprLoc();
9784 // OpenMP [2.1, C/C++]
9785 // A list item is a variable name.
9786 // OpenMP [2.14.4.1, Restrictions, p.1]
9787 // A list item that appears in a copyin clause must be threadprivate.
9788 DeclRefExpr *DE = dyn_cast<DeclRefExpr>(RefExpr);
9789 if (!DE || !isa<VarDecl>(DE->getDecl())) {
9790 Diag(ELoc, diag::err_omp_expected_var_name_member_expr)
9791 << 0 << RefExpr->getSourceRange();
9795 Decl *D = DE->getDecl();
9796 VarDecl *VD = cast<VarDecl>(D);
9798 QualType Type = VD->getType();
9799 if (Type->isDependentType() || Type->isInstantiationDependentType()) {
9800 // It will be analyzed later.
9802 SrcExprs.push_back(nullptr);
9803 DstExprs.push_back(nullptr);
9804 AssignmentOps.push_back(nullptr);
9808 // OpenMP [2.14.4.1, Restrictions, C/C++, p.1]
9809 // A list item that appears in a copyin clause must be threadprivate.
9810 if (!DSAStack->isThreadPrivate(VD)) {
9811 Diag(ELoc, diag::err_omp_required_access)
9812 << getOpenMPClauseName(OMPC_copyin)
9813 << getOpenMPDirectiveName(OMPD_threadprivate);
9817 // OpenMP [2.14.4.1, Restrictions, C/C++, p.2]
9818 // A variable of class type (or array thereof) that appears in a
9819 // copyin clause requires an accessible, unambiguous copy assignment
9820 // operator for the class type.
9821 auto ElemType = Context.getBaseElementType(Type).getNonReferenceType();
9823 buildVarDecl(*this, DE->getLocStart(), ElemType.getUnqualifiedType(),
9824 ".copyin.src", VD->hasAttrs() ? &VD->getAttrs() : nullptr);
9825 auto *PseudoSrcExpr = buildDeclRefExpr(
9826 *this, SrcVD, ElemType.getUnqualifiedType(), DE->getExprLoc());
9828 buildVarDecl(*this, DE->getLocStart(), ElemType, ".copyin.dst",
9829 VD->hasAttrs() ? &VD->getAttrs() : nullptr);
9830 auto *PseudoDstExpr =
9831 buildDeclRefExpr(*this, DstVD, ElemType, DE->getExprLoc());
9832 // For arrays generate assignment operation for single element and replace
9833 // it by the original array element in CodeGen.
9834 auto AssignmentOp = BuildBinOp(/*S=*/nullptr, DE->getExprLoc(), BO_Assign,
9835 PseudoDstExpr, PseudoSrcExpr);
9836 if (AssignmentOp.isInvalid())
9838 AssignmentOp = ActOnFinishFullExpr(AssignmentOp.get(), DE->getExprLoc(),
9839 /*DiscardedValue=*/true);
9840 if (AssignmentOp.isInvalid())
9843 DSAStack->addDSA(VD, DE, OMPC_copyin);
9845 SrcExprs.push_back(PseudoSrcExpr);
9846 DstExprs.push_back(PseudoDstExpr);
9847 AssignmentOps.push_back(AssignmentOp.get());
9853 return OMPCopyinClause::Create(Context, StartLoc, LParenLoc, EndLoc, Vars,
9854 SrcExprs, DstExprs, AssignmentOps);
9857 OMPClause *Sema::ActOnOpenMPCopyprivateClause(ArrayRef<Expr *> VarList,
9858 SourceLocation StartLoc,
9859 SourceLocation LParenLoc,
9860 SourceLocation EndLoc) {
9861 SmallVector<Expr *, 8> Vars;
9862 SmallVector<Expr *, 8> SrcExprs;
9863 SmallVector<Expr *, 8> DstExprs;
9864 SmallVector<Expr *, 8> AssignmentOps;
9865 for (auto &RefExpr : VarList) {
9866 assert(RefExpr && "NULL expr in OpenMP linear clause.");
9867 SourceLocation ELoc;
9869 Expr *SimpleRefExpr = RefExpr;
9870 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange,
9871 /*AllowArraySection=*/false);
9873 // It will be analyzed later.
9874 Vars.push_back(RefExpr);
9875 SrcExprs.push_back(nullptr);
9876 DstExprs.push_back(nullptr);
9877 AssignmentOps.push_back(nullptr);
9879 ValueDecl *D = Res.first;
9883 QualType Type = D->getType();
9884 auto *VD = dyn_cast<VarDecl>(D);
9886 // OpenMP [2.14.4.2, Restrictions, p.2]
9887 // A list item that appears in a copyprivate clause may not appear in a
9888 // private or firstprivate clause on the single construct.
9889 if (!VD || !DSAStack->isThreadPrivate(VD)) {
9890 auto DVar = DSAStack->getTopDSA(D, false);
9891 if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_copyprivate &&
9893 Diag(ELoc, diag::err_omp_wrong_dsa)
9894 << getOpenMPClauseName(DVar.CKind)
9895 << getOpenMPClauseName(OMPC_copyprivate);
9896 ReportOriginalDSA(*this, DSAStack, D, DVar);
9900 // OpenMP [2.11.4.2, Restrictions, p.1]
9901 // All list items that appear in a copyprivate clause must be either
9902 // threadprivate or private in the enclosing context.
9903 if (DVar.CKind == OMPC_unknown) {
9904 DVar = DSAStack->getImplicitDSA(D, false);
9905 if (DVar.CKind == OMPC_shared) {
9906 Diag(ELoc, diag::err_omp_required_access)
9907 << getOpenMPClauseName(OMPC_copyprivate)
9908 << "threadprivate or private in the enclosing context";
9909 ReportOriginalDSA(*this, DSAStack, D, DVar);
9915 // Variably modified types are not supported.
9916 if (!Type->isAnyPointerType() && Type->isVariablyModifiedType()) {
9917 Diag(ELoc, diag::err_omp_variably_modified_type_not_supported)
9918 << getOpenMPClauseName(OMPC_copyprivate) << Type
9919 << getOpenMPDirectiveName(DSAStack->getCurrentDirective());
9922 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
9923 Diag(D->getLocation(),
9924 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
9929 // OpenMP [2.14.4.1, Restrictions, C/C++, p.2]
9930 // A variable of class type (or array thereof) that appears in a
9931 // copyin clause requires an accessible, unambiguous copy assignment
9932 // operator for the class type.
9933 Type = Context.getBaseElementType(Type.getNonReferenceType())
9934 .getUnqualifiedType();
9936 buildVarDecl(*this, RefExpr->getLocStart(), Type, ".copyprivate.src",
9937 D->hasAttrs() ? &D->getAttrs() : nullptr);
9938 auto *PseudoSrcExpr = buildDeclRefExpr(*this, SrcVD, Type, ELoc);
9940 buildVarDecl(*this, RefExpr->getLocStart(), Type, ".copyprivate.dst",
9941 D->hasAttrs() ? &D->getAttrs() : nullptr);
9942 auto *PseudoDstExpr = buildDeclRefExpr(*this, DstVD, Type, ELoc);
9943 auto AssignmentOp = BuildBinOp(DSAStack->getCurScope(), ELoc, BO_Assign,
9944 PseudoDstExpr, PseudoSrcExpr);
9945 if (AssignmentOp.isInvalid())
9947 AssignmentOp = ActOnFinishFullExpr(AssignmentOp.get(), ELoc,
9948 /*DiscardedValue=*/true);
9949 if (AssignmentOp.isInvalid())
9952 // No need to mark vars as copyprivate, they are already threadprivate or
9953 // implicitly private.
9954 assert(VD || IsOpenMPCapturedDecl(D));
9956 VD ? RefExpr->IgnoreParens()
9957 : buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/false));
9958 SrcExprs.push_back(PseudoSrcExpr);
9959 DstExprs.push_back(PseudoDstExpr);
9960 AssignmentOps.push_back(AssignmentOp.get());
9966 return OMPCopyprivateClause::Create(Context, StartLoc, LParenLoc, EndLoc,
9967 Vars, SrcExprs, DstExprs, AssignmentOps);
9970 OMPClause *Sema::ActOnOpenMPFlushClause(ArrayRef<Expr *> VarList,
9971 SourceLocation StartLoc,
9972 SourceLocation LParenLoc,
9973 SourceLocation EndLoc) {
9974 if (VarList.empty())
9977 return OMPFlushClause::Create(Context, StartLoc, LParenLoc, EndLoc, VarList);
9981 Sema::ActOnOpenMPDependClause(OpenMPDependClauseKind DepKind,
9982 SourceLocation DepLoc, SourceLocation ColonLoc,
9983 ArrayRef<Expr *> VarList, SourceLocation StartLoc,
9984 SourceLocation LParenLoc, SourceLocation EndLoc) {
9985 if (DSAStack->getCurrentDirective() == OMPD_ordered &&
9986 DepKind != OMPC_DEPEND_source && DepKind != OMPC_DEPEND_sink) {
9987 Diag(DepLoc, diag::err_omp_unexpected_clause_value)
9988 << "'source' or 'sink'" << getOpenMPClauseName(OMPC_depend);
9991 if (DSAStack->getCurrentDirective() != OMPD_ordered &&
9992 (DepKind == OMPC_DEPEND_unknown || DepKind == OMPC_DEPEND_source ||
9993 DepKind == OMPC_DEPEND_sink)) {
9994 unsigned Except[] = {OMPC_DEPEND_source, OMPC_DEPEND_sink};
9995 Diag(DepLoc, diag::err_omp_unexpected_clause_value)
9996 << getListOfPossibleValues(OMPC_depend, /*First=*/0,
9997 /*Last=*/OMPC_DEPEND_unknown, Except)
9998 << getOpenMPClauseName(OMPC_depend);
10001 SmallVector<Expr *, 8> Vars;
10002 DSAStackTy::OperatorOffsetTy OpsOffs;
10003 llvm::APSInt DepCounter(/*BitWidth=*/32);
10004 llvm::APSInt TotalDepCount(/*BitWidth=*/32);
10005 if (DepKind == OMPC_DEPEND_sink) {
10006 if (auto *OrderedCountExpr = DSAStack->getParentOrderedRegionParam()) {
10007 TotalDepCount = OrderedCountExpr->EvaluateKnownConstInt(Context);
10008 TotalDepCount.setIsUnsigned(/*Val=*/true);
10011 if ((DepKind != OMPC_DEPEND_sink && DepKind != OMPC_DEPEND_source) ||
10012 DSAStack->getParentOrderedRegionParam()) {
10013 for (auto &RefExpr : VarList) {
10014 assert(RefExpr && "NULL expr in OpenMP shared clause.");
10015 if (isa<DependentScopeDeclRefExpr>(RefExpr)) {
10016 // It will be analyzed later.
10017 Vars.push_back(RefExpr);
10021 SourceLocation ELoc = RefExpr->getExprLoc();
10022 auto *SimpleExpr = RefExpr->IgnoreParenCasts();
10023 if (DepKind == OMPC_DEPEND_sink) {
10024 if (DepCounter >= TotalDepCount) {
10025 Diag(ELoc, diag::err_omp_depend_sink_unexpected_expr);
10029 // OpenMP [2.13.9, Summary]
10030 // depend(dependence-type : vec), where dependence-type is:
10031 // 'sink' and where vec is the iteration vector, which has the form:
10032 // x1 [+- d1], x2 [+- d2 ], . . . , xn [+- dn]
10033 // where n is the value specified by the ordered clause in the loop
10034 // directive, xi denotes the loop iteration variable of the i-th nested
10035 // loop associated with the loop directive, and di is a constant
10036 // non-negative integer.
10037 if (CurContext->isDependentContext()) {
10038 // It will be analyzed later.
10039 Vars.push_back(RefExpr);
10042 SimpleExpr = SimpleExpr->IgnoreImplicit();
10043 OverloadedOperatorKind OOK = OO_None;
10044 SourceLocation OOLoc;
10045 Expr *LHS = SimpleExpr;
10046 Expr *RHS = nullptr;
10047 if (auto *BO = dyn_cast<BinaryOperator>(SimpleExpr)) {
10048 OOK = BinaryOperator::getOverloadedOperator(BO->getOpcode());
10049 OOLoc = BO->getOperatorLoc();
10050 LHS = BO->getLHS()->IgnoreParenImpCasts();
10051 RHS = BO->getRHS()->IgnoreParenImpCasts();
10052 } else if (auto *OCE = dyn_cast<CXXOperatorCallExpr>(SimpleExpr)) {
10053 OOK = OCE->getOperator();
10054 OOLoc = OCE->getOperatorLoc();
10055 LHS = OCE->getArg(/*Arg=*/0)->IgnoreParenImpCasts();
10056 RHS = OCE->getArg(/*Arg=*/1)->IgnoreParenImpCasts();
10057 } else if (auto *MCE = dyn_cast<CXXMemberCallExpr>(SimpleExpr)) {
10058 OOK = MCE->getMethodDecl()
10061 .getCXXOverloadedOperator();
10062 OOLoc = MCE->getCallee()->getExprLoc();
10063 LHS = MCE->getImplicitObjectArgument()->IgnoreParenImpCasts();
10064 RHS = MCE->getArg(/*Arg=*/0)->IgnoreParenImpCasts();
10066 SourceLocation ELoc;
10067 SourceRange ERange;
10068 auto Res = getPrivateItem(*this, LHS, ELoc, ERange,
10069 /*AllowArraySection=*/false);
10071 // It will be analyzed later.
10072 Vars.push_back(RefExpr);
10074 ValueDecl *D = Res.first;
10078 if (OOK != OO_Plus && OOK != OO_Minus && (RHS || OOK != OO_None)) {
10079 Diag(OOLoc, diag::err_omp_depend_sink_expected_plus_minus);
10083 ExprResult RHSRes = VerifyPositiveIntegerConstantInClause(
10084 RHS, OMPC_depend, /*StrictlyPositive=*/false);
10085 if (RHSRes.isInvalid())
10088 if (!CurContext->isDependentContext() &&
10089 DSAStack->getParentOrderedRegionParam() &&
10090 DepCounter != DSAStack->isParentLoopControlVariable(D).first) {
10091 Diag(ELoc, diag::err_omp_depend_sink_expected_loop_iteration)
10092 << DSAStack->getParentLoopControlVariable(
10093 DepCounter.getZExtValue());
10096 OpsOffs.push_back({RHS, OOK});
10098 // OpenMP [2.11.1.1, Restrictions, p.3]
10099 // A variable that is part of another variable (such as a field of a
10100 // structure) but is not an array element or an array section cannot
10101 // appear in a depend clause.
10102 auto *DE = dyn_cast<DeclRefExpr>(SimpleExpr);
10103 auto *ASE = dyn_cast<ArraySubscriptExpr>(SimpleExpr);
10104 auto *OASE = dyn_cast<OMPArraySectionExpr>(SimpleExpr);
10105 if (!RefExpr->IgnoreParenImpCasts()->isLValue() ||
10106 (!ASE && !DE && !OASE) || (DE && !isa<VarDecl>(DE->getDecl())) ||
10110 .getNonReferenceType()
10111 ->isPointerType() &&
10112 !ASE->getBase()->getType().getNonReferenceType()->isArrayType())) {
10113 Diag(ELoc, diag::err_omp_expected_var_name_member_expr_or_array_item)
10114 << 0 << RefExpr->getSourceRange();
10118 Vars.push_back(RefExpr->IgnoreParenImpCasts());
10121 if (!CurContext->isDependentContext() && DepKind == OMPC_DEPEND_sink &&
10122 TotalDepCount > VarList.size() &&
10123 DSAStack->getParentOrderedRegionParam()) {
10124 Diag(EndLoc, diag::err_omp_depend_sink_expected_loop_iteration)
10125 << DSAStack->getParentLoopControlVariable(VarList.size() + 1);
10127 if (DepKind != OMPC_DEPEND_source && DepKind != OMPC_DEPEND_sink &&
10131 auto *C = OMPDependClause::Create(Context, StartLoc, LParenLoc, EndLoc,
10132 DepKind, DepLoc, ColonLoc, Vars);
10133 if (DepKind == OMPC_DEPEND_sink || DepKind == OMPC_DEPEND_source)
10134 DSAStack->addDoacrossDependClause(C, OpsOffs);
10138 OMPClause *Sema::ActOnOpenMPDeviceClause(Expr *Device, SourceLocation StartLoc,
10139 SourceLocation LParenLoc,
10140 SourceLocation EndLoc) {
10141 Expr *ValExpr = Device;
10143 // OpenMP [2.9.1, Restrictions]
10144 // The device expression must evaluate to a non-negative integer value.
10145 if (!IsNonNegativeIntegerValue(ValExpr, *this, OMPC_device,
10146 /*StrictlyPositive=*/false))
10149 return new (Context) OMPDeviceClause(ValExpr, StartLoc, LParenLoc, EndLoc);
10152 static bool IsCXXRecordForMappable(Sema &SemaRef, SourceLocation Loc,
10153 DSAStackTy *Stack, CXXRecordDecl *RD) {
10154 if (!RD || RD->isInvalidDecl())
10157 auto QTy = SemaRef.Context.getRecordType(RD);
10158 if (RD->isDynamicClass()) {
10159 SemaRef.Diag(Loc, diag::err_omp_not_mappable_type) << QTy;
10160 SemaRef.Diag(RD->getLocation(), diag::note_omp_polymorphic_in_target);
10164 bool IsCorrect = true;
10165 for (auto *I : DC->decls()) {
10167 if (auto *MD = dyn_cast<CXXMethodDecl>(I)) {
10168 if (MD->isStatic()) {
10169 SemaRef.Diag(Loc, diag::err_omp_not_mappable_type) << QTy;
10170 SemaRef.Diag(MD->getLocation(),
10171 diag::note_omp_static_member_in_target);
10174 } else if (auto *VD = dyn_cast<VarDecl>(I)) {
10175 if (VD->isStaticDataMember()) {
10176 SemaRef.Diag(Loc, diag::err_omp_not_mappable_type) << QTy;
10177 SemaRef.Diag(VD->getLocation(),
10178 diag::note_omp_static_member_in_target);
10185 for (auto &I : RD->bases()) {
10186 if (!IsCXXRecordForMappable(SemaRef, I.getLocStart(), Stack,
10187 I.getType()->getAsCXXRecordDecl()))
10193 static bool CheckTypeMappable(SourceLocation SL, SourceRange SR, Sema &SemaRef,
10194 DSAStackTy *Stack, QualType QTy) {
10196 if (QTy->isIncompleteType(&ND)) {
10197 SemaRef.Diag(SL, diag::err_incomplete_type) << QTy << SR;
10199 } else if (CXXRecordDecl *RD = dyn_cast_or_null<CXXRecordDecl>(ND)) {
10200 if (!RD->isInvalidDecl() && !IsCXXRecordForMappable(SemaRef, SL, Stack, RD))
10206 /// \brief Return true if it can be proven that the provided array expression
10207 /// (array section or array subscript) does NOT specify the whole size of the
10208 /// array whose base type is \a BaseQTy.
10209 static bool CheckArrayExpressionDoesNotReferToWholeSize(Sema &SemaRef,
10211 QualType BaseQTy) {
10212 auto *OASE = dyn_cast<OMPArraySectionExpr>(E);
10214 // If this is an array subscript, it refers to the whole size if the size of
10215 // the dimension is constant and equals 1. Also, an array section assumes the
10216 // format of an array subscript if no colon is used.
10217 if (isa<ArraySubscriptExpr>(E) || (OASE && OASE->getColonLoc().isInvalid())) {
10218 if (auto *ATy = dyn_cast<ConstantArrayType>(BaseQTy.getTypePtr()))
10219 return ATy->getSize().getSExtValue() != 1;
10220 // Size can't be evaluated statically.
10224 assert(OASE && "Expecting array section if not an array subscript.");
10225 auto *LowerBound = OASE->getLowerBound();
10226 auto *Length = OASE->getLength();
10228 // If there is a lower bound that does not evaluates to zero, we are not
10229 // covering the whole dimension.
10231 llvm::APSInt ConstLowerBound;
10232 if (!LowerBound->EvaluateAsInt(ConstLowerBound, SemaRef.getASTContext()))
10233 return false; // Can't get the integer value as a constant.
10234 if (ConstLowerBound.getSExtValue())
10238 // If we don't have a length we covering the whole dimension.
10242 // If the base is a pointer, we don't have a way to get the size of the
10244 if (BaseQTy->isPointerType())
10247 // We can only check if the length is the same as the size of the dimension
10248 // if we have a constant array.
10249 auto *CATy = dyn_cast<ConstantArrayType>(BaseQTy.getTypePtr());
10253 llvm::APSInt ConstLength;
10254 if (!Length->EvaluateAsInt(ConstLength, SemaRef.getASTContext()))
10255 return false; // Can't get the integer value as a constant.
10257 return CATy->getSize().getSExtValue() != ConstLength.getSExtValue();
10260 // Return true if it can be proven that the provided array expression (array
10261 // section or array subscript) does NOT specify a single element of the array
10262 // whose base type is \a BaseQTy.
10263 static bool CheckArrayExpressionDoesNotReferToUnitySize(Sema &SemaRef,
10265 QualType BaseQTy) {
10266 auto *OASE = dyn_cast<OMPArraySectionExpr>(E);
10268 // An array subscript always refer to a single element. Also, an array section
10269 // assumes the format of an array subscript if no colon is used.
10270 if (isa<ArraySubscriptExpr>(E) || (OASE && OASE->getColonLoc().isInvalid()))
10273 assert(OASE && "Expecting array section if not an array subscript.");
10274 auto *Length = OASE->getLength();
10276 // If we don't have a length we have to check if the array has unitary size
10277 // for this dimension. Also, we should always expect a length if the base type
10280 if (auto *ATy = dyn_cast<ConstantArrayType>(BaseQTy.getTypePtr()))
10281 return ATy->getSize().getSExtValue() != 1;
10282 // We cannot assume anything.
10286 // Check if the length evaluates to 1.
10287 llvm::APSInt ConstLength;
10288 if (!Length->EvaluateAsInt(ConstLength, SemaRef.getASTContext()))
10289 return false; // Can't get the integer value as a constant.
10291 return ConstLength.getSExtValue() != 1;
10294 // Return the expression of the base of the mappable expression or null if it
10295 // cannot be determined and do all the necessary checks to see if the expression
10296 // is valid as a standalone mappable expression. In the process, record all the
10297 // components of the expression.
10298 static Expr *CheckMapClauseExpressionBase(
10299 Sema &SemaRef, Expr *E,
10300 OMPClauseMappableExprCommon::MappableExprComponentList &CurComponents,
10301 OpenMPClauseKind CKind) {
10302 SourceLocation ELoc = E->getExprLoc();
10303 SourceRange ERange = E->getSourceRange();
10305 // The base of elements of list in a map clause have to be either:
10306 // - a reference to variable or field.
10307 // - a member expression.
10308 // - an array expression.
10310 // E.g. if we have the expression 'r.S.Arr[:12]', we want to retrieve the
10311 // reference to 'r'.
10318 // #pragma omp target map (S.Arr[:12]);
10322 // We want to retrieve the member expression 'this->S';
10324 Expr *RelevantExpr = nullptr;
10326 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.2]
10327 // If a list item is an array section, it must specify contiguous storage.
10329 // For this restriction it is sufficient that we make sure only references
10330 // to variables or fields and array expressions, and that no array sections
10331 // exist except in the rightmost expression (unless they cover the whole
10332 // dimension of the array). E.g. these would be invalid:
10334 // r.ArrS[3:5].Arr[6:7]
10338 // but these would be valid:
10339 // r.ArrS[3].Arr[6:7]
10343 bool AllowUnitySizeArraySection = true;
10344 bool AllowWholeSizeArraySection = true;
10346 while (!RelevantExpr) {
10347 E = E->IgnoreParenImpCasts();
10349 if (auto *CurE = dyn_cast<DeclRefExpr>(E)) {
10350 if (!isa<VarDecl>(CurE->getDecl()))
10353 RelevantExpr = CurE;
10355 // If we got a reference to a declaration, we should not expect any array
10356 // section before that.
10357 AllowUnitySizeArraySection = false;
10358 AllowWholeSizeArraySection = false;
10360 // Record the component.
10361 CurComponents.push_back(OMPClauseMappableExprCommon::MappableComponent(
10362 CurE, CurE->getDecl()));
10366 if (auto *CurE = dyn_cast<MemberExpr>(E)) {
10367 auto *BaseE = CurE->getBase()->IgnoreParenImpCasts();
10369 if (isa<CXXThisExpr>(BaseE))
10370 // We found a base expression: this->Val.
10371 RelevantExpr = CurE;
10375 if (!isa<FieldDecl>(CurE->getMemberDecl())) {
10376 SemaRef.Diag(ELoc, diag::err_omp_expected_access_to_data_field)
10377 << CurE->getSourceRange();
10381 auto *FD = cast<FieldDecl>(CurE->getMemberDecl());
10383 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C/C++, p.3]
10384 // A bit-field cannot appear in a map clause.
10386 if (FD->isBitField()) {
10387 SemaRef.Diag(ELoc, diag::err_omp_bit_fields_forbidden_in_clause)
10388 << CurE->getSourceRange() << getOpenMPClauseName(CKind);
10392 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C++, p.1]
10393 // If the type of a list item is a reference to a type T then the type
10394 // will be considered to be T for all purposes of this clause.
10395 QualType CurType = BaseE->getType().getNonReferenceType();
10397 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C/C++, p.2]
10398 // A list item cannot be a variable that is a member of a structure with
10401 if (auto *RT = CurType->getAs<RecordType>())
10402 if (RT->isUnionType()) {
10403 SemaRef.Diag(ELoc, diag::err_omp_union_type_not_allowed)
10404 << CurE->getSourceRange();
10408 // If we got a member expression, we should not expect any array section
10411 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.7]
10412 // If a list item is an element of a structure, only the rightmost symbol
10413 // of the variable reference can be an array section.
10415 AllowUnitySizeArraySection = false;
10416 AllowWholeSizeArraySection = false;
10418 // Record the component.
10419 CurComponents.push_back(
10420 OMPClauseMappableExprCommon::MappableComponent(CurE, FD));
10424 if (auto *CurE = dyn_cast<ArraySubscriptExpr>(E)) {
10425 E = CurE->getBase()->IgnoreParenImpCasts();
10427 if (!E->getType()->isAnyPointerType() && !E->getType()->isArrayType()) {
10428 SemaRef.Diag(ELoc, diag::err_omp_expected_base_var_name)
10429 << 0 << CurE->getSourceRange();
10433 // If we got an array subscript that express the whole dimension we
10434 // can have any array expressions before. If it only expressing part of
10435 // the dimension, we can only have unitary-size array expressions.
10436 if (CheckArrayExpressionDoesNotReferToWholeSize(SemaRef, CurE,
10438 AllowWholeSizeArraySection = false;
10440 // Record the component - we don't have any declaration associated.
10441 CurComponents.push_back(
10442 OMPClauseMappableExprCommon::MappableComponent(CurE, nullptr));
10446 if (auto *CurE = dyn_cast<OMPArraySectionExpr>(E)) {
10447 E = CurE->getBase()->IgnoreParenImpCasts();
10450 OMPArraySectionExpr::getBaseOriginalType(E).getCanonicalType();
10452 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C++, p.1]
10453 // If the type of a list item is a reference to a type T then the type
10454 // will be considered to be T for all purposes of this clause.
10455 if (CurType->isReferenceType())
10456 CurType = CurType->getPointeeType();
10458 bool IsPointer = CurType->isAnyPointerType();
10460 if (!IsPointer && !CurType->isArrayType()) {
10461 SemaRef.Diag(ELoc, diag::err_omp_expected_base_var_name)
10462 << 0 << CurE->getSourceRange();
10467 CheckArrayExpressionDoesNotReferToWholeSize(SemaRef, CurE, CurType);
10469 CheckArrayExpressionDoesNotReferToUnitySize(SemaRef, CurE, CurType);
10471 if (AllowWholeSizeArraySection) {
10472 // Any array section is currently allowed. Allowing a whole size array
10473 // section implies allowing a unity array section as well.
10475 // If this array section refers to the whole dimension we can still
10476 // accept other array sections before this one, except if the base is a
10477 // pointer. Otherwise, only unitary sections are accepted.
10478 if (NotWhole || IsPointer)
10479 AllowWholeSizeArraySection = false;
10480 } else if (AllowUnitySizeArraySection && NotUnity) {
10481 // A unity or whole array section is not allowed and that is not
10482 // compatible with the properties of the current array section.
10484 ELoc, diag::err_array_section_does_not_specify_contiguous_storage)
10485 << CurE->getSourceRange();
10489 // Record the component - we don't have any declaration associated.
10490 CurComponents.push_back(
10491 OMPClauseMappableExprCommon::MappableComponent(CurE, nullptr));
10495 // If nothing else worked, this is not a valid map clause expression.
10497 diag::err_omp_expected_named_var_member_or_array_expression)
10502 return RelevantExpr;
10505 // Return true if expression E associated with value VD has conflicts with other
10506 // map information.
10507 static bool CheckMapConflicts(
10508 Sema &SemaRef, DSAStackTy *DSAS, ValueDecl *VD, Expr *E,
10509 bool CurrentRegionOnly,
10510 OMPClauseMappableExprCommon::MappableExprComponentListRef CurComponents,
10511 OpenMPClauseKind CKind) {
10513 SourceLocation ELoc = E->getExprLoc();
10514 SourceRange ERange = E->getSourceRange();
10516 // In order to easily check the conflicts we need to match each component of
10517 // the expression under test with the components of the expressions that are
10518 // already in the stack.
10520 assert(!CurComponents.empty() && "Map clause expression with no components!");
10521 assert(CurComponents.back().getAssociatedDeclaration() == VD &&
10522 "Map clause expression with unexpected base!");
10524 // Variables to help detecting enclosing problems in data environment nests.
10525 bool IsEnclosedByDataEnvironmentExpr = false;
10526 const Expr *EnclosingExpr = nullptr;
10528 bool FoundError = DSAS->checkMappableExprComponentListsForDecl(
10529 VD, CurrentRegionOnly,
10530 [&](OMPClauseMappableExprCommon::MappableExprComponentListRef
10532 OpenMPClauseKind) -> bool {
10534 assert(!StackComponents.empty() &&
10535 "Map clause expression with no components!");
10536 assert(StackComponents.back().getAssociatedDeclaration() == VD &&
10537 "Map clause expression with unexpected base!");
10539 // The whole expression in the stack.
10540 auto *RE = StackComponents.front().getAssociatedExpression();
10542 // Expressions must start from the same base. Here we detect at which
10543 // point both expressions diverge from each other and see if we can
10544 // detect if the memory referred to both expressions is contiguous and
10546 auto CI = CurComponents.rbegin();
10547 auto CE = CurComponents.rend();
10548 auto SI = StackComponents.rbegin();
10549 auto SE = StackComponents.rend();
10550 for (; CI != CE && SI != SE; ++CI, ++SI) {
10552 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.3]
10553 // At most one list item can be an array item derived from a given
10554 // variable in map clauses of the same construct.
10555 if (CurrentRegionOnly &&
10556 (isa<ArraySubscriptExpr>(CI->getAssociatedExpression()) ||
10557 isa<OMPArraySectionExpr>(CI->getAssociatedExpression())) &&
10558 (isa<ArraySubscriptExpr>(SI->getAssociatedExpression()) ||
10559 isa<OMPArraySectionExpr>(SI->getAssociatedExpression()))) {
10560 SemaRef.Diag(CI->getAssociatedExpression()->getExprLoc(),
10561 diag::err_omp_multiple_array_items_in_map_clause)
10562 << CI->getAssociatedExpression()->getSourceRange();
10563 SemaRef.Diag(SI->getAssociatedExpression()->getExprLoc(),
10564 diag::note_used_here)
10565 << SI->getAssociatedExpression()->getSourceRange();
10569 // Do both expressions have the same kind?
10570 if (CI->getAssociatedExpression()->getStmtClass() !=
10571 SI->getAssociatedExpression()->getStmtClass())
10574 // Are we dealing with different variables/fields?
10575 if (CI->getAssociatedDeclaration() != SI->getAssociatedDeclaration())
10578 // Check if the extra components of the expressions in the enclosing
10579 // data environment are redundant for the current base declaration.
10580 // If they are, the maps completely overlap, which is legal.
10581 for (; SI != SE; ++SI) {
10584 dyn_cast<ArraySubscriptExpr>(SI->getAssociatedExpression())) {
10585 Type = ASE->getBase()->IgnoreParenImpCasts()->getType();
10586 } else if (auto *OASE = dyn_cast<OMPArraySectionExpr>(
10587 SI->getAssociatedExpression())) {
10588 auto *E = OASE->getBase()->IgnoreParenImpCasts();
10590 OMPArraySectionExpr::getBaseOriginalType(E).getCanonicalType();
10592 if (Type.isNull() || Type->isAnyPointerType() ||
10593 CheckArrayExpressionDoesNotReferToWholeSize(
10594 SemaRef, SI->getAssociatedExpression(), Type))
10598 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.4]
10599 // List items of map clauses in the same construct must not share
10600 // original storage.
10602 // If the expressions are exactly the same or one is a subset of the
10603 // other, it means they are sharing storage.
10604 if (CI == CE && SI == SE) {
10605 if (CurrentRegionOnly) {
10606 if (CKind == OMPC_map)
10607 SemaRef.Diag(ELoc, diag::err_omp_map_shared_storage) << ERange;
10609 assert(CKind == OMPC_to || CKind == OMPC_from);
10610 SemaRef.Diag(ELoc, diag::err_omp_once_referenced_in_target_update)
10613 SemaRef.Diag(RE->getExprLoc(), diag::note_used_here)
10614 << RE->getSourceRange();
10617 // If we find the same expression in the enclosing data environment,
10619 IsEnclosedByDataEnvironmentExpr = true;
10624 QualType DerivedType =
10625 std::prev(CI)->getAssociatedDeclaration()->getType();
10626 SourceLocation DerivedLoc =
10627 std::prev(CI)->getAssociatedExpression()->getExprLoc();
10629 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C++, p.1]
10630 // If the type of a list item is a reference to a type T then the type
10631 // will be considered to be T for all purposes of this clause.
10632 DerivedType = DerivedType.getNonReferenceType();
10634 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C/C++, p.1]
10635 // A variable for which the type is pointer and an array section
10636 // derived from that variable must not appear as list items of map
10637 // clauses of the same construct.
10639 // Also, cover one of the cases in:
10640 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.5]
10641 // If any part of the original storage of a list item has corresponding
10642 // storage in the device data environment, all of the original storage
10643 // must have corresponding storage in the device data environment.
10645 if (DerivedType->isAnyPointerType()) {
10646 if (CI == CE || SI == SE) {
10649 diag::err_omp_pointer_mapped_along_with_derived_section)
10652 assert(CI != CE && SI != SE);
10653 SemaRef.Diag(DerivedLoc, diag::err_omp_same_pointer_derreferenced)
10656 SemaRef.Diag(RE->getExprLoc(), diag::note_used_here)
10657 << RE->getSourceRange();
10661 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.4]
10662 // List items of map clauses in the same construct must not share
10663 // original storage.
10665 // An expression is a subset of the other.
10666 if (CurrentRegionOnly && (CI == CE || SI == SE)) {
10667 if (CKind == OMPC_map)
10668 SemaRef.Diag(ELoc, diag::err_omp_map_shared_storage) << ERange;
10670 assert(CKind == OMPC_to || CKind == OMPC_from);
10671 SemaRef.Diag(ELoc, diag::err_omp_once_referenced_in_target_update)
10674 SemaRef.Diag(RE->getExprLoc(), diag::note_used_here)
10675 << RE->getSourceRange();
10679 // The current expression uses the same base as other expression in the
10680 // data environment but does not contain it completely.
10681 if (!CurrentRegionOnly && SI != SE)
10682 EnclosingExpr = RE;
10684 // The current expression is a subset of the expression in the data
10686 IsEnclosedByDataEnvironmentExpr |=
10687 (!CurrentRegionOnly && CI != CE && SI == SE);
10692 if (CurrentRegionOnly)
10695 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.5]
10696 // If any part of the original storage of a list item has corresponding
10697 // storage in the device data environment, all of the original storage must
10698 // have corresponding storage in the device data environment.
10699 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.6]
10700 // If a list item is an element of a structure, and a different element of
10701 // the structure has a corresponding list item in the device data environment
10702 // prior to a task encountering the construct associated with the map clause,
10703 // then the list item must also have a corresponding list item in the device
10704 // data environment prior to the task encountering the construct.
10706 if (EnclosingExpr && !IsEnclosedByDataEnvironmentExpr) {
10708 diag::err_omp_original_storage_is_shared_and_does_not_contain)
10710 SemaRef.Diag(EnclosingExpr->getExprLoc(), diag::note_used_here)
10711 << EnclosingExpr->getSourceRange();
10719 // Utility struct that gathers all the related lists associated with a mappable
10721 struct MappableVarListInfo final {
10722 // The list of expressions.
10723 ArrayRef<Expr *> VarList;
10724 // The list of processed expressions.
10725 SmallVector<Expr *, 16> ProcessedVarList;
10726 // The mappble components for each expression.
10727 OMPClauseMappableExprCommon::MappableExprComponentLists VarComponents;
10728 // The base declaration of the variable.
10729 SmallVector<ValueDecl *, 16> VarBaseDeclarations;
10731 MappableVarListInfo(ArrayRef<Expr *> VarList) : VarList(VarList) {
10732 // We have a list of components and base declarations for each entry in the
10734 VarComponents.reserve(VarList.size());
10735 VarBaseDeclarations.reserve(VarList.size());
10740 // Check the validity of the provided variable list for the provided clause kind
10741 // \a CKind. In the check process the valid expressions, and mappable expression
10742 // components and variables are extracted and used to fill \a Vars,
10743 // \a ClauseComponents, and \a ClauseBaseDeclarations. \a MapType and
10744 // \a IsMapTypeImplicit are expected to be valid if the clause kind is 'map'.
10746 checkMappableExpressionList(Sema &SemaRef, DSAStackTy *DSAS,
10747 OpenMPClauseKind CKind, MappableVarListInfo &MVLI,
10748 SourceLocation StartLoc,
10749 OpenMPMapClauseKind MapType = OMPC_MAP_unknown,
10750 bool IsMapTypeImplicit = false) {
10751 // We only expect mappable expressions in 'to', 'from', and 'map' clauses.
10752 assert((CKind == OMPC_map || CKind == OMPC_to || CKind == OMPC_from) &&
10753 "Unexpected clause kind with mappable expressions!");
10755 // Keep track of the mappable components and base declarations in this clause.
10756 // Each entry in the list is going to have a list of components associated. We
10757 // record each set of the components so that we can build the clause later on.
10758 // In the end we should have the same amount of declarations and component
10761 for (auto &RE : MVLI.VarList) {
10762 assert(RE && "Null expr in omp to/from/map clause");
10763 SourceLocation ELoc = RE->getExprLoc();
10765 auto *VE = RE->IgnoreParenLValueCasts();
10767 if (VE->isValueDependent() || VE->isTypeDependent() ||
10768 VE->isInstantiationDependent() ||
10769 VE->containsUnexpandedParameterPack()) {
10770 // We can only analyze this information once the missing information is
10772 MVLI.ProcessedVarList.push_back(RE);
10776 auto *SimpleExpr = RE->IgnoreParenCasts();
10778 if (!RE->IgnoreParenImpCasts()->isLValue()) {
10780 diag::err_omp_expected_named_var_member_or_array_expression)
10781 << RE->getSourceRange();
10785 OMPClauseMappableExprCommon::MappableExprComponentList CurComponents;
10786 ValueDecl *CurDeclaration = nullptr;
10788 // Obtain the array or member expression bases if required. Also, fill the
10789 // components array with all the components identified in the process.
10791 CheckMapClauseExpressionBase(SemaRef, SimpleExpr, CurComponents, CKind);
10795 assert(!CurComponents.empty() &&
10796 "Invalid mappable expression information.");
10798 // For the following checks, we rely on the base declaration which is
10799 // expected to be associated with the last component. The declaration is
10800 // expected to be a variable or a field (if 'this' is being mapped).
10801 CurDeclaration = CurComponents.back().getAssociatedDeclaration();
10802 assert(CurDeclaration && "Null decl on map clause.");
10804 CurDeclaration->isCanonicalDecl() &&
10805 "Expecting components to have associated only canonical declarations.");
10807 auto *VD = dyn_cast<VarDecl>(CurDeclaration);
10808 auto *FD = dyn_cast<FieldDecl>(CurDeclaration);
10810 assert((VD || FD) && "Only variables or fields are expected here!");
10813 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.10]
10814 // threadprivate variables cannot appear in a map clause.
10815 // OpenMP 4.5 [2.10.5, target update Construct]
10816 // threadprivate variables cannot appear in a from clause.
10817 if (VD && DSAS->isThreadPrivate(VD)) {
10818 auto DVar = DSAS->getTopDSA(VD, false);
10819 SemaRef.Diag(ELoc, diag::err_omp_threadprivate_in_clause)
10820 << getOpenMPClauseName(CKind);
10821 ReportOriginalDSA(SemaRef, DSAS, VD, DVar);
10825 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.9]
10826 // A list item cannot appear in both a map clause and a data-sharing
10827 // attribute clause on the same construct.
10829 // Check conflicts with other map clause expressions. We check the conflicts
10830 // with the current construct separately from the enclosing data
10831 // environment, because the restrictions are different. We only have to
10832 // check conflicts across regions for the map clauses.
10833 if (CheckMapConflicts(SemaRef, DSAS, CurDeclaration, SimpleExpr,
10834 /*CurrentRegionOnly=*/true, CurComponents, CKind))
10836 if (CKind == OMPC_map &&
10837 CheckMapConflicts(SemaRef, DSAS, CurDeclaration, SimpleExpr,
10838 /*CurrentRegionOnly=*/false, CurComponents, CKind))
10841 // OpenMP 4.5 [2.10.5, target update Construct]
10842 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C++, p.1]
10843 // If the type of a list item is a reference to a type T then the type will
10844 // be considered to be T for all purposes of this clause.
10845 QualType Type = CurDeclaration->getType().getNonReferenceType();
10847 // OpenMP 4.5 [2.10.5, target update Construct, Restrictions, p.4]
10848 // A list item in a to or from clause must have a mappable type.
10849 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.9]
10850 // A list item must have a mappable type.
10851 if (!CheckTypeMappable(VE->getExprLoc(), VE->getSourceRange(), SemaRef,
10855 if (CKind == OMPC_map) {
10856 // target enter data
10857 // OpenMP [2.10.2, Restrictions, p. 99]
10858 // A map-type must be specified in all map clauses and must be either
10860 OpenMPDirectiveKind DKind = DSAS->getCurrentDirective();
10861 if (DKind == OMPD_target_enter_data &&
10862 !(MapType == OMPC_MAP_to || MapType == OMPC_MAP_alloc)) {
10863 SemaRef.Diag(StartLoc, diag::err_omp_invalid_map_type_for_directive)
10864 << (IsMapTypeImplicit ? 1 : 0)
10865 << getOpenMPSimpleClauseTypeName(OMPC_map, MapType)
10866 << getOpenMPDirectiveName(DKind);
10870 // target exit_data
10871 // OpenMP [2.10.3, Restrictions, p. 102]
10872 // A map-type must be specified in all map clauses and must be either
10873 // from, release, or delete.
10874 if (DKind == OMPD_target_exit_data &&
10875 !(MapType == OMPC_MAP_from || MapType == OMPC_MAP_release ||
10876 MapType == OMPC_MAP_delete)) {
10877 SemaRef.Diag(StartLoc, diag::err_omp_invalid_map_type_for_directive)
10878 << (IsMapTypeImplicit ? 1 : 0)
10879 << getOpenMPSimpleClauseTypeName(OMPC_map, MapType)
10880 << getOpenMPDirectiveName(DKind);
10884 // OpenMP 4.5 [2.15.5.1, Restrictions, p.3]
10885 // A list item cannot appear in both a map clause and a data-sharing
10886 // attribute clause on the same construct
10887 if ((DKind == OMPD_target || DKind == OMPD_target_teams ||
10888 DKind == OMPD_target_teams_distribute ||
10889 DKind == OMPD_target_teams_distribute_parallel_for ||
10890 DKind == OMPD_target_teams_distribute_parallel_for_simd ||
10891 DKind == OMPD_target_teams_distribute_simd) && VD) {
10892 auto DVar = DSAS->getTopDSA(VD, false);
10893 if (isOpenMPPrivate(DVar.CKind)) {
10894 SemaRef.Diag(ELoc, diag::err_omp_variable_in_given_clause_and_dsa)
10895 << getOpenMPClauseName(DVar.CKind)
10896 << getOpenMPClauseName(OMPC_map)
10897 << getOpenMPDirectiveName(DSAS->getCurrentDirective());
10898 ReportOriginalDSA(SemaRef, DSAS, CurDeclaration, DVar);
10904 // Save the current expression.
10905 MVLI.ProcessedVarList.push_back(RE);
10907 // Store the components in the stack so that they can be used to check
10908 // against other clauses later on.
10909 DSAS->addMappableExpressionComponents(CurDeclaration, CurComponents,
10910 /*WhereFoundClauseKind=*/OMPC_map);
10912 // Save the components and declaration to create the clause. For purposes of
10913 // the clause creation, any component list that has has base 'this' uses
10914 // null as base declaration.
10915 MVLI.VarComponents.resize(MVLI.VarComponents.size() + 1);
10916 MVLI.VarComponents.back().append(CurComponents.begin(),
10917 CurComponents.end());
10918 MVLI.VarBaseDeclarations.push_back(isa<MemberExpr>(BE) ? nullptr
10924 Sema::ActOnOpenMPMapClause(OpenMPMapClauseKind MapTypeModifier,
10925 OpenMPMapClauseKind MapType, bool IsMapTypeImplicit,
10926 SourceLocation MapLoc, SourceLocation ColonLoc,
10927 ArrayRef<Expr *> VarList, SourceLocation StartLoc,
10928 SourceLocation LParenLoc, SourceLocation EndLoc) {
10929 MappableVarListInfo MVLI(VarList);
10930 checkMappableExpressionList(*this, DSAStack, OMPC_map, MVLI, StartLoc,
10931 MapType, IsMapTypeImplicit);
10933 // We need to produce a map clause even if we don't have variables so that
10934 // other diagnostics related with non-existing map clauses are accurate.
10935 return OMPMapClause::Create(Context, StartLoc, LParenLoc, EndLoc,
10936 MVLI.ProcessedVarList, MVLI.VarBaseDeclarations,
10937 MVLI.VarComponents, MapTypeModifier, MapType,
10938 IsMapTypeImplicit, MapLoc);
10941 QualType Sema::ActOnOpenMPDeclareReductionType(SourceLocation TyLoc,
10942 TypeResult ParsedType) {
10943 assert(ParsedType.isUsable());
10945 QualType ReductionType = GetTypeFromParser(ParsedType.get());
10946 if (ReductionType.isNull())
10949 // [OpenMP 4.0], 2.15 declare reduction Directive, Restrictions, C\C++
10950 // A type name in a declare reduction directive cannot be a function type, an
10951 // array type, a reference type, or a type qualified with const, volatile or
10953 if (ReductionType.hasQualifiers()) {
10954 Diag(TyLoc, diag::err_omp_reduction_wrong_type) << 0;
10958 if (ReductionType->isFunctionType()) {
10959 Diag(TyLoc, diag::err_omp_reduction_wrong_type) << 1;
10962 if (ReductionType->isReferenceType()) {
10963 Diag(TyLoc, diag::err_omp_reduction_wrong_type) << 2;
10966 if (ReductionType->isArrayType()) {
10967 Diag(TyLoc, diag::err_omp_reduction_wrong_type) << 3;
10970 return ReductionType;
10973 Sema::DeclGroupPtrTy Sema::ActOnOpenMPDeclareReductionDirectiveStart(
10974 Scope *S, DeclContext *DC, DeclarationName Name,
10975 ArrayRef<std::pair<QualType, SourceLocation>> ReductionTypes,
10976 AccessSpecifier AS, Decl *PrevDeclInScope) {
10977 SmallVector<Decl *, 8> Decls;
10978 Decls.reserve(ReductionTypes.size());
10980 LookupResult Lookup(*this, Name, SourceLocation(), LookupOMPReductionName,
10982 // [OpenMP 4.0], 2.15 declare reduction Directive, Restrictions
10983 // A reduction-identifier may not be re-declared in the current scope for the
10984 // same type or for a type that is compatible according to the base language
10986 llvm::DenseMap<QualType, SourceLocation> PreviousRedeclTypes;
10987 OMPDeclareReductionDecl *PrevDRD = nullptr;
10988 bool InCompoundScope = true;
10989 if (S != nullptr) {
10990 // Find previous declaration with the same name not referenced in other
10992 FunctionScopeInfo *ParentFn = getEnclosingFunction();
10994 (ParentFn != nullptr) && !ParentFn->CompoundScopes.empty();
10995 LookupName(Lookup, S);
10996 FilterLookupForScope(Lookup, DC, S, /*ConsiderLinkage=*/false,
10997 /*AllowInlineNamespace=*/false);
10998 llvm::DenseMap<OMPDeclareReductionDecl *, bool> UsedAsPrevious;
10999 auto Filter = Lookup.makeFilter();
11000 while (Filter.hasNext()) {
11001 auto *PrevDecl = cast<OMPDeclareReductionDecl>(Filter.next());
11002 if (InCompoundScope) {
11003 auto I = UsedAsPrevious.find(PrevDecl);
11004 if (I == UsedAsPrevious.end())
11005 UsedAsPrevious[PrevDecl] = false;
11006 if (auto *D = PrevDecl->getPrevDeclInScope())
11007 UsedAsPrevious[D] = true;
11009 PreviousRedeclTypes[PrevDecl->getType().getCanonicalType()] =
11010 PrevDecl->getLocation();
11013 if (InCompoundScope) {
11014 for (auto &PrevData : UsedAsPrevious) {
11015 if (!PrevData.second) {
11016 PrevDRD = PrevData.first;
11021 } else if (PrevDeclInScope != nullptr) {
11022 auto *PrevDRDInScope = PrevDRD =
11023 cast<OMPDeclareReductionDecl>(PrevDeclInScope);
11025 PreviousRedeclTypes[PrevDRDInScope->getType().getCanonicalType()] =
11026 PrevDRDInScope->getLocation();
11027 PrevDRDInScope = PrevDRDInScope->getPrevDeclInScope();
11028 } while (PrevDRDInScope != nullptr);
11030 for (auto &TyData : ReductionTypes) {
11031 auto I = PreviousRedeclTypes.find(TyData.first.getCanonicalType());
11032 bool Invalid = false;
11033 if (I != PreviousRedeclTypes.end()) {
11034 Diag(TyData.second, diag::err_omp_declare_reduction_redefinition)
11036 Diag(I->second, diag::note_previous_definition);
11039 PreviousRedeclTypes[TyData.first.getCanonicalType()] = TyData.second;
11040 auto *DRD = OMPDeclareReductionDecl::Create(Context, DC, TyData.second,
11041 Name, TyData.first, PrevDRD);
11043 DRD->setAccess(AS);
11044 Decls.push_back(DRD);
11046 DRD->setInvalidDecl();
11051 return DeclGroupPtrTy::make(
11052 DeclGroupRef::Create(Context, Decls.begin(), Decls.size()));
11055 void Sema::ActOnOpenMPDeclareReductionCombinerStart(Scope *S, Decl *D) {
11056 auto *DRD = cast<OMPDeclareReductionDecl>(D);
11058 // Enter new function scope.
11059 PushFunctionScope();
11060 getCurFunction()->setHasBranchProtectedScope();
11061 getCurFunction()->setHasOMPDeclareReductionCombiner();
11064 PushDeclContext(S, DRD);
11068 PushExpressionEvaluationContext(
11069 ExpressionEvaluationContext::PotentiallyEvaluated);
11071 QualType ReductionType = DRD->getType();
11072 // Create 'T* omp_parm;T omp_in;'. All references to 'omp_in' will
11073 // be replaced by '*omp_parm' during codegen. This required because 'omp_in'
11074 // uses semantics of argument handles by value, but it should be passed by
11075 // reference. C lang does not support references, so pass all parameters as
11077 // Create 'T omp_in;' variable.
11079 buildVarDecl(*this, D->getLocation(), ReductionType, "omp_in");
11080 // Create 'T* omp_parm;T omp_out;'. All references to 'omp_out' will
11081 // be replaced by '*omp_parm' during codegen. This required because 'omp_out'
11082 // uses semantics of argument handles by value, but it should be passed by
11083 // reference. C lang does not support references, so pass all parameters as
11085 // Create 'T omp_out;' variable.
11087 buildVarDecl(*this, D->getLocation(), ReductionType, "omp_out");
11088 if (S != nullptr) {
11089 PushOnScopeChains(OmpInParm, S);
11090 PushOnScopeChains(OmpOutParm, S);
11092 DRD->addDecl(OmpInParm);
11093 DRD->addDecl(OmpOutParm);
11097 void Sema::ActOnOpenMPDeclareReductionCombinerEnd(Decl *D, Expr *Combiner) {
11098 auto *DRD = cast<OMPDeclareReductionDecl>(D);
11099 DiscardCleanupsInEvaluationContext();
11100 PopExpressionEvaluationContext();
11103 PopFunctionScopeInfo();
11105 if (Combiner != nullptr)
11106 DRD->setCombiner(Combiner);
11108 DRD->setInvalidDecl();
11111 void Sema::ActOnOpenMPDeclareReductionInitializerStart(Scope *S, Decl *D) {
11112 auto *DRD = cast<OMPDeclareReductionDecl>(D);
11114 // Enter new function scope.
11115 PushFunctionScope();
11116 getCurFunction()->setHasBranchProtectedScope();
11119 PushDeclContext(S, DRD);
11123 PushExpressionEvaluationContext(
11124 ExpressionEvaluationContext::PotentiallyEvaluated);
11126 QualType ReductionType = DRD->getType();
11127 // Create 'T* omp_parm;T omp_priv;'. All references to 'omp_priv' will
11128 // be replaced by '*omp_parm' during codegen. This required because 'omp_priv'
11129 // uses semantics of argument handles by value, but it should be passed by
11130 // reference. C lang does not support references, so pass all parameters as
11132 // Create 'T omp_priv;' variable.
11133 auto *OmpPrivParm =
11134 buildVarDecl(*this, D->getLocation(), ReductionType, "omp_priv");
11135 // Create 'T* omp_parm;T omp_orig;'. All references to 'omp_orig' will
11136 // be replaced by '*omp_parm' during codegen. This required because 'omp_orig'
11137 // uses semantics of argument handles by value, but it should be passed by
11138 // reference. C lang does not support references, so pass all parameters as
11140 // Create 'T omp_orig;' variable.
11141 auto *OmpOrigParm =
11142 buildVarDecl(*this, D->getLocation(), ReductionType, "omp_orig");
11143 if (S != nullptr) {
11144 PushOnScopeChains(OmpPrivParm, S);
11145 PushOnScopeChains(OmpOrigParm, S);
11147 DRD->addDecl(OmpPrivParm);
11148 DRD->addDecl(OmpOrigParm);
11152 void Sema::ActOnOpenMPDeclareReductionInitializerEnd(Decl *D,
11153 Expr *Initializer) {
11154 auto *DRD = cast<OMPDeclareReductionDecl>(D);
11155 DiscardCleanupsInEvaluationContext();
11156 PopExpressionEvaluationContext();
11159 PopFunctionScopeInfo();
11161 if (Initializer != nullptr)
11162 DRD->setInitializer(Initializer);
11164 DRD->setInvalidDecl();
11167 Sema::DeclGroupPtrTy Sema::ActOnOpenMPDeclareReductionDirectiveEnd(
11168 Scope *S, DeclGroupPtrTy DeclReductions, bool IsValid) {
11169 for (auto *D : DeclReductions.get()) {
11171 auto *DRD = cast<OMPDeclareReductionDecl>(D);
11173 PushOnScopeChains(DRD, S, /*AddToContext=*/false);
11175 D->setInvalidDecl();
11177 return DeclReductions;
11180 OMPClause *Sema::ActOnOpenMPNumTeamsClause(Expr *NumTeams,
11181 SourceLocation StartLoc,
11182 SourceLocation LParenLoc,
11183 SourceLocation EndLoc) {
11184 Expr *ValExpr = NumTeams;
11185 Stmt *HelperValStmt = nullptr;
11186 OpenMPDirectiveKind CaptureRegion = OMPD_unknown;
11188 // OpenMP [teams Constrcut, Restrictions]
11189 // The num_teams expression must evaluate to a positive integer value.
11190 if (!IsNonNegativeIntegerValue(ValExpr, *this, OMPC_num_teams,
11191 /*StrictlyPositive=*/true))
11194 OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective();
11195 CaptureRegion = getOpenMPCaptureRegionForClause(DKind, OMPC_num_teams);
11196 if (CaptureRegion != OMPD_unknown) {
11197 llvm::MapVector<Expr *, DeclRefExpr *> Captures;
11198 ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
11199 HelperValStmt = buildPreInits(Context, Captures);
11202 return new (Context) OMPNumTeamsClause(ValExpr, HelperValStmt, CaptureRegion,
11203 StartLoc, LParenLoc, EndLoc);
11206 OMPClause *Sema::ActOnOpenMPThreadLimitClause(Expr *ThreadLimit,
11207 SourceLocation StartLoc,
11208 SourceLocation LParenLoc,
11209 SourceLocation EndLoc) {
11210 Expr *ValExpr = ThreadLimit;
11211 Stmt *HelperValStmt = nullptr;
11212 OpenMPDirectiveKind CaptureRegion = OMPD_unknown;
11214 // OpenMP [teams Constrcut, Restrictions]
11215 // The thread_limit expression must evaluate to a positive integer value.
11216 if (!IsNonNegativeIntegerValue(ValExpr, *this, OMPC_thread_limit,
11217 /*StrictlyPositive=*/true))
11220 OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective();
11221 CaptureRegion = getOpenMPCaptureRegionForClause(DKind, OMPC_thread_limit);
11222 if (CaptureRegion != OMPD_unknown) {
11223 llvm::MapVector<Expr *, DeclRefExpr *> Captures;
11224 ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
11225 HelperValStmt = buildPreInits(Context, Captures);
11228 return new (Context) OMPThreadLimitClause(
11229 ValExpr, HelperValStmt, CaptureRegion, StartLoc, LParenLoc, EndLoc);
11232 OMPClause *Sema::ActOnOpenMPPriorityClause(Expr *Priority,
11233 SourceLocation StartLoc,
11234 SourceLocation LParenLoc,
11235 SourceLocation EndLoc) {
11236 Expr *ValExpr = Priority;
11238 // OpenMP [2.9.1, task Constrcut]
11239 // The priority-value is a non-negative numerical scalar expression.
11240 if (!IsNonNegativeIntegerValue(ValExpr, *this, OMPC_priority,
11241 /*StrictlyPositive=*/false))
11244 return new (Context) OMPPriorityClause(ValExpr, StartLoc, LParenLoc, EndLoc);
11247 OMPClause *Sema::ActOnOpenMPGrainsizeClause(Expr *Grainsize,
11248 SourceLocation StartLoc,
11249 SourceLocation LParenLoc,
11250 SourceLocation EndLoc) {
11251 Expr *ValExpr = Grainsize;
11253 // OpenMP [2.9.2, taskloop Constrcut]
11254 // The parameter of the grainsize clause must be a positive integer
11256 if (!IsNonNegativeIntegerValue(ValExpr, *this, OMPC_grainsize,
11257 /*StrictlyPositive=*/true))
11260 return new (Context) OMPGrainsizeClause(ValExpr, StartLoc, LParenLoc, EndLoc);
11263 OMPClause *Sema::ActOnOpenMPNumTasksClause(Expr *NumTasks,
11264 SourceLocation StartLoc,
11265 SourceLocation LParenLoc,
11266 SourceLocation EndLoc) {
11267 Expr *ValExpr = NumTasks;
11269 // OpenMP [2.9.2, taskloop Constrcut]
11270 // The parameter of the num_tasks clause must be a positive integer
11272 if (!IsNonNegativeIntegerValue(ValExpr, *this, OMPC_num_tasks,
11273 /*StrictlyPositive=*/true))
11276 return new (Context) OMPNumTasksClause(ValExpr, StartLoc, LParenLoc, EndLoc);
11279 OMPClause *Sema::ActOnOpenMPHintClause(Expr *Hint, SourceLocation StartLoc,
11280 SourceLocation LParenLoc,
11281 SourceLocation EndLoc) {
11282 // OpenMP [2.13.2, critical construct, Description]
11283 // ... where hint-expression is an integer constant expression that evaluates
11284 // to a valid lock hint.
11285 ExprResult HintExpr = VerifyPositiveIntegerConstantInClause(Hint, OMPC_hint);
11286 if (HintExpr.isInvalid())
11288 return new (Context)
11289 OMPHintClause(HintExpr.get(), StartLoc, LParenLoc, EndLoc);
11292 OMPClause *Sema::ActOnOpenMPDistScheduleClause(
11293 OpenMPDistScheduleClauseKind Kind, Expr *ChunkSize, SourceLocation StartLoc,
11294 SourceLocation LParenLoc, SourceLocation KindLoc, SourceLocation CommaLoc,
11295 SourceLocation EndLoc) {
11296 if (Kind == OMPC_DIST_SCHEDULE_unknown) {
11297 std::string Values;
11299 Values += getOpenMPSimpleClauseTypeName(OMPC_dist_schedule, 0);
11301 Diag(KindLoc, diag::err_omp_unexpected_clause_value)
11302 << Values << getOpenMPClauseName(OMPC_dist_schedule);
11305 Expr *ValExpr = ChunkSize;
11306 Stmt *HelperValStmt = nullptr;
11308 if (!ChunkSize->isValueDependent() && !ChunkSize->isTypeDependent() &&
11309 !ChunkSize->isInstantiationDependent() &&
11310 !ChunkSize->containsUnexpandedParameterPack()) {
11311 SourceLocation ChunkSizeLoc = ChunkSize->getLocStart();
11313 PerformOpenMPImplicitIntegerConversion(ChunkSizeLoc, ChunkSize);
11314 if (Val.isInvalid())
11317 ValExpr = Val.get();
11319 // OpenMP [2.7.1, Restrictions]
11320 // chunk_size must be a loop invariant integer expression with a positive
11322 llvm::APSInt Result;
11323 if (ValExpr->isIntegerConstantExpr(Result, Context)) {
11324 if (Result.isSigned() && !Result.isStrictlyPositive()) {
11325 Diag(ChunkSizeLoc, diag::err_omp_negative_expression_in_clause)
11326 << "dist_schedule" << ChunkSize->getSourceRange();
11329 } else if (isParallelOrTaskRegion(DSAStack->getCurrentDirective()) &&
11330 !CurContext->isDependentContext()) {
11331 llvm::MapVector<Expr *, DeclRefExpr *> Captures;
11332 ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
11333 HelperValStmt = buildPreInits(Context, Captures);
11338 return new (Context)
11339 OMPDistScheduleClause(StartLoc, LParenLoc, KindLoc, CommaLoc, EndLoc,
11340 Kind, ValExpr, HelperValStmt);
11343 OMPClause *Sema::ActOnOpenMPDefaultmapClause(
11344 OpenMPDefaultmapClauseModifier M, OpenMPDefaultmapClauseKind Kind,
11345 SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation MLoc,
11346 SourceLocation KindLoc, SourceLocation EndLoc) {
11347 // OpenMP 4.5 only supports 'defaultmap(tofrom: scalar)'
11348 if (M != OMPC_DEFAULTMAP_MODIFIER_tofrom || Kind != OMPC_DEFAULTMAP_scalar) {
11350 SourceLocation Loc;
11352 if (M != OMPC_DEFAULTMAP_MODIFIER_tofrom) {
11353 Value += getOpenMPSimpleClauseTypeName(OMPC_defaultmap,
11354 OMPC_DEFAULTMAP_MODIFIER_tofrom);
11357 Value += getOpenMPSimpleClauseTypeName(OMPC_defaultmap,
11358 OMPC_DEFAULTMAP_scalar);
11362 Diag(Loc, diag::err_omp_unexpected_clause_value)
11363 << Value << getOpenMPClauseName(OMPC_defaultmap);
11367 return new (Context)
11368 OMPDefaultmapClause(StartLoc, LParenLoc, MLoc, KindLoc, EndLoc, Kind, M);
11371 bool Sema::ActOnStartOpenMPDeclareTargetDirective(SourceLocation Loc) {
11372 DeclContext *CurLexicalContext = getCurLexicalContext();
11373 if (!CurLexicalContext->isFileContext() &&
11374 !CurLexicalContext->isExternCContext() &&
11375 !CurLexicalContext->isExternCXXContext()) {
11376 Diag(Loc, diag::err_omp_region_not_file_context);
11379 if (IsInOpenMPDeclareTargetContext) {
11380 Diag(Loc, diag::err_omp_enclosed_declare_target);
11384 IsInOpenMPDeclareTargetContext = true;
11388 void Sema::ActOnFinishOpenMPDeclareTargetDirective() {
11389 assert(IsInOpenMPDeclareTargetContext &&
11390 "Unexpected ActOnFinishOpenMPDeclareTargetDirective");
11392 IsInOpenMPDeclareTargetContext = false;
11395 void Sema::ActOnOpenMPDeclareTargetName(Scope *CurScope,
11396 CXXScopeSpec &ScopeSpec,
11397 const DeclarationNameInfo &Id,
11398 OMPDeclareTargetDeclAttr::MapTypeTy MT,
11399 NamedDeclSetType &SameDirectiveDecls) {
11400 LookupResult Lookup(*this, Id, LookupOrdinaryName);
11401 LookupParsedName(Lookup, CurScope, &ScopeSpec, true);
11403 if (Lookup.isAmbiguous())
11405 Lookup.suppressDiagnostics();
11407 if (!Lookup.isSingleResult()) {
11408 if (TypoCorrection Corrected =
11409 CorrectTypo(Id, LookupOrdinaryName, CurScope, nullptr,
11410 llvm::make_unique<VarOrFuncDeclFilterCCC>(*this),
11411 CTK_ErrorRecovery)) {
11412 diagnoseTypo(Corrected, PDiag(diag::err_undeclared_var_use_suggest)
11414 checkDeclIsAllowedInOpenMPTarget(nullptr, Corrected.getCorrectionDecl());
11418 Diag(Id.getLoc(), diag::err_undeclared_var_use) << Id.getName();
11422 NamedDecl *ND = Lookup.getAsSingle<NamedDecl>();
11423 if (isa<VarDecl>(ND) || isa<FunctionDecl>(ND)) {
11424 if (!SameDirectiveDecls.insert(cast<NamedDecl>(ND->getCanonicalDecl())))
11425 Diag(Id.getLoc(), diag::err_omp_declare_target_multiple) << Id.getName();
11427 if (!ND->hasAttr<OMPDeclareTargetDeclAttr>()) {
11428 Attr *A = OMPDeclareTargetDeclAttr::CreateImplicit(Context, MT);
11430 if (ASTMutationListener *ML = Context.getASTMutationListener())
11431 ML->DeclarationMarkedOpenMPDeclareTarget(ND, A);
11432 checkDeclIsAllowedInOpenMPTarget(nullptr, ND);
11433 } else if (ND->getAttr<OMPDeclareTargetDeclAttr>()->getMapType() != MT) {
11434 Diag(Id.getLoc(), diag::err_omp_declare_target_to_and_link)
11438 Diag(Id.getLoc(), diag::err_omp_invalid_target_decl) << Id.getName();
11441 static void checkDeclInTargetContext(SourceLocation SL, SourceRange SR,
11442 Sema &SemaRef, Decl *D) {
11445 Decl *LD = nullptr;
11446 if (isa<TagDecl>(D)) {
11447 LD = cast<TagDecl>(D)->getDefinition();
11448 } else if (isa<VarDecl>(D)) {
11449 LD = cast<VarDecl>(D)->getDefinition();
11451 // If this is an implicit variable that is legal and we do not need to do
11453 if (cast<VarDecl>(D)->isImplicit()) {
11454 Attr *A = OMPDeclareTargetDeclAttr::CreateImplicit(
11455 SemaRef.Context, OMPDeclareTargetDeclAttr::MT_To);
11457 if (ASTMutationListener *ML = SemaRef.Context.getASTMutationListener())
11458 ML->DeclarationMarkedOpenMPDeclareTarget(D, A);
11462 } else if (isa<FunctionDecl>(D)) {
11463 const FunctionDecl *FD = nullptr;
11464 if (cast<FunctionDecl>(D)->hasBody(FD))
11465 LD = const_cast<FunctionDecl *>(FD);
11467 // If the definition is associated with the current declaration in the
11468 // target region (it can be e.g. a lambda) that is legal and we do not need
11469 // to do anything else.
11471 Attr *A = OMPDeclareTargetDeclAttr::CreateImplicit(
11472 SemaRef.Context, OMPDeclareTargetDeclAttr::MT_To);
11474 if (ASTMutationListener *ML = SemaRef.Context.getASTMutationListener())
11475 ML->DeclarationMarkedOpenMPDeclareTarget(D, A);
11481 if (LD && !LD->hasAttr<OMPDeclareTargetDeclAttr>() &&
11482 (isa<VarDecl>(LD) || isa<FunctionDecl>(LD))) {
11483 // Outlined declaration is not declared target.
11484 if (LD->isOutOfLine()) {
11485 SemaRef.Diag(LD->getLocation(), diag::warn_omp_not_in_target_context);
11486 SemaRef.Diag(SL, diag::note_used_here) << SR;
11488 DeclContext *DC = LD->getDeclContext();
11490 if (isa<FunctionDecl>(DC) &&
11491 cast<FunctionDecl>(DC)->hasAttr<OMPDeclareTargetDeclAttr>())
11493 DC = DC->getParent();
11498 // Is not declared in target context.
11499 SemaRef.Diag(LD->getLocation(), diag::warn_omp_not_in_target_context);
11500 SemaRef.Diag(SL, diag::note_used_here) << SR;
11502 // Mark decl as declared target to prevent further diagnostic.
11503 Attr *A = OMPDeclareTargetDeclAttr::CreateImplicit(
11504 SemaRef.Context, OMPDeclareTargetDeclAttr::MT_To);
11506 if (ASTMutationListener *ML = SemaRef.Context.getASTMutationListener())
11507 ML->DeclarationMarkedOpenMPDeclareTarget(D, A);
11511 static bool checkValueDeclInTarget(SourceLocation SL, SourceRange SR,
11512 Sema &SemaRef, DSAStackTy *Stack,
11514 if (VD->hasAttr<OMPDeclareTargetDeclAttr>())
11516 if (!CheckTypeMappable(SL, SR, SemaRef, Stack, VD->getType()))
11521 void Sema::checkDeclIsAllowedInOpenMPTarget(Expr *E, Decl *D) {
11522 if (!D || D->isInvalidDecl())
11524 SourceRange SR = E ? E->getSourceRange() : D->getSourceRange();
11525 SourceLocation SL = E ? E->getLocStart() : D->getLocation();
11526 // 2.10.6: threadprivate variable cannot appear in a declare target directive.
11527 if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
11528 if (DSAStack->isThreadPrivate(VD)) {
11529 Diag(SL, diag::err_omp_threadprivate_in_target);
11530 ReportOriginalDSA(*this, DSAStack, VD, DSAStack->getTopDSA(VD, false));
11534 if (ValueDecl *VD = dyn_cast<ValueDecl>(D)) {
11535 // Problem if any with var declared with incomplete type will be reported
11536 // as normal, so no need to check it here.
11537 if ((E || !VD->getType()->isIncompleteType()) &&
11538 !checkValueDeclInTarget(SL, SR, *this, DSAStack, VD)) {
11539 // Mark decl as declared target to prevent further diagnostic.
11540 if (isa<VarDecl>(VD) || isa<FunctionDecl>(VD)) {
11541 Attr *A = OMPDeclareTargetDeclAttr::CreateImplicit(
11542 Context, OMPDeclareTargetDeclAttr::MT_To);
11544 if (ASTMutationListener *ML = Context.getASTMutationListener())
11545 ML->DeclarationMarkedOpenMPDeclareTarget(VD, A);
11551 // Checking declaration inside declare target region.
11552 if (!D->hasAttr<OMPDeclareTargetDeclAttr>() &&
11553 (isa<VarDecl>(D) || isa<FunctionDecl>(D))) {
11554 Attr *A = OMPDeclareTargetDeclAttr::CreateImplicit(
11555 Context, OMPDeclareTargetDeclAttr::MT_To);
11557 if (ASTMutationListener *ML = Context.getASTMutationListener())
11558 ML->DeclarationMarkedOpenMPDeclareTarget(D, A);
11562 checkDeclInTargetContext(E->getExprLoc(), E->getSourceRange(), *this, D);
11565 OMPClause *Sema::ActOnOpenMPToClause(ArrayRef<Expr *> VarList,
11566 SourceLocation StartLoc,
11567 SourceLocation LParenLoc,
11568 SourceLocation EndLoc) {
11569 MappableVarListInfo MVLI(VarList);
11570 checkMappableExpressionList(*this, DSAStack, OMPC_to, MVLI, StartLoc);
11571 if (MVLI.ProcessedVarList.empty())
11574 return OMPToClause::Create(Context, StartLoc, LParenLoc, EndLoc,
11575 MVLI.ProcessedVarList, MVLI.VarBaseDeclarations,
11576 MVLI.VarComponents);
11579 OMPClause *Sema::ActOnOpenMPFromClause(ArrayRef<Expr *> VarList,
11580 SourceLocation StartLoc,
11581 SourceLocation LParenLoc,
11582 SourceLocation EndLoc) {
11583 MappableVarListInfo MVLI(VarList);
11584 checkMappableExpressionList(*this, DSAStack, OMPC_from, MVLI, StartLoc);
11585 if (MVLI.ProcessedVarList.empty())
11588 return OMPFromClause::Create(Context, StartLoc, LParenLoc, EndLoc,
11589 MVLI.ProcessedVarList, MVLI.VarBaseDeclarations,
11590 MVLI.VarComponents);
11593 OMPClause *Sema::ActOnOpenMPUseDevicePtrClause(ArrayRef<Expr *> VarList,
11594 SourceLocation StartLoc,
11595 SourceLocation LParenLoc,
11596 SourceLocation EndLoc) {
11597 MappableVarListInfo MVLI(VarList);
11598 SmallVector<Expr *, 8> PrivateCopies;
11599 SmallVector<Expr *, 8> Inits;
11601 for (auto &RefExpr : VarList) {
11602 assert(RefExpr && "NULL expr in OpenMP use_device_ptr clause.");
11603 SourceLocation ELoc;
11604 SourceRange ERange;
11605 Expr *SimpleRefExpr = RefExpr;
11606 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
11608 // It will be analyzed later.
11609 MVLI.ProcessedVarList.push_back(RefExpr);
11610 PrivateCopies.push_back(nullptr);
11611 Inits.push_back(nullptr);
11613 ValueDecl *D = Res.first;
11617 QualType Type = D->getType();
11618 Type = Type.getNonReferenceType().getUnqualifiedType();
11620 auto *VD = dyn_cast<VarDecl>(D);
11622 // Item should be a pointer or reference to pointer.
11623 if (!Type->isPointerType()) {
11624 Diag(ELoc, diag::err_omp_usedeviceptr_not_a_pointer)
11625 << 0 << RefExpr->getSourceRange();
11629 // Build the private variable and the expression that refers to it.
11630 auto VDPrivate = buildVarDecl(*this, ELoc, Type, D->getName(),
11631 D->hasAttrs() ? &D->getAttrs() : nullptr);
11632 if (VDPrivate->isInvalidDecl())
11635 CurContext->addDecl(VDPrivate);
11636 auto VDPrivateRefExpr = buildDeclRefExpr(
11637 *this, VDPrivate, RefExpr->getType().getUnqualifiedType(), ELoc);
11639 // Add temporary variable to initialize the private copy of the pointer.
11641 buildVarDecl(*this, RefExpr->getExprLoc(), Type, ".devptr.temp");
11642 auto *VDInitRefExpr = buildDeclRefExpr(*this, VDInit, RefExpr->getType(),
11643 RefExpr->getExprLoc());
11644 AddInitializerToDecl(VDPrivate,
11645 DefaultLvalueConversion(VDInitRefExpr).get(),
11646 /*DirectInit=*/false);
11648 // If required, build a capture to implement the privatization initialized
11649 // with the current list item value.
11650 DeclRefExpr *Ref = nullptr;
11652 Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/true);
11653 MVLI.ProcessedVarList.push_back(VD ? RefExpr->IgnoreParens() : Ref);
11654 PrivateCopies.push_back(VDPrivateRefExpr);
11655 Inits.push_back(VDInitRefExpr);
11657 // We need to add a data sharing attribute for this variable to make sure it
11658 // is correctly captured. A variable that shows up in a use_device_ptr has
11659 // similar properties of a first private variable.
11660 DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_firstprivate, Ref);
11662 // Create a mappable component for the list item. List items in this clause
11663 // only need a component.
11664 MVLI.VarBaseDeclarations.push_back(D);
11665 MVLI.VarComponents.resize(MVLI.VarComponents.size() + 1);
11666 MVLI.VarComponents.back().push_back(
11667 OMPClauseMappableExprCommon::MappableComponent(SimpleRefExpr, D));
11670 if (MVLI.ProcessedVarList.empty())
11673 return OMPUseDevicePtrClause::Create(
11674 Context, StartLoc, LParenLoc, EndLoc, MVLI.ProcessedVarList,
11675 PrivateCopies, Inits, MVLI.VarBaseDeclarations, MVLI.VarComponents);
11678 OMPClause *Sema::ActOnOpenMPIsDevicePtrClause(ArrayRef<Expr *> VarList,
11679 SourceLocation StartLoc,
11680 SourceLocation LParenLoc,
11681 SourceLocation EndLoc) {
11682 MappableVarListInfo MVLI(VarList);
11683 for (auto &RefExpr : VarList) {
11684 assert(RefExpr && "NULL expr in OpenMP is_device_ptr clause.");
11685 SourceLocation ELoc;
11686 SourceRange ERange;
11687 Expr *SimpleRefExpr = RefExpr;
11688 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
11690 // It will be analyzed later.
11691 MVLI.ProcessedVarList.push_back(RefExpr);
11693 ValueDecl *D = Res.first;
11697 QualType Type = D->getType();
11698 // item should be a pointer or array or reference to pointer or array
11699 if (!Type.getNonReferenceType()->isPointerType() &&
11700 !Type.getNonReferenceType()->isArrayType()) {
11701 Diag(ELoc, diag::err_omp_argument_type_isdeviceptr)
11702 << 0 << RefExpr->getSourceRange();
11706 // Check if the declaration in the clause does not show up in any data
11707 // sharing attribute.
11708 auto DVar = DSAStack->getTopDSA(D, false);
11709 if (isOpenMPPrivate(DVar.CKind)) {
11710 Diag(ELoc, diag::err_omp_variable_in_given_clause_and_dsa)
11711 << getOpenMPClauseName(DVar.CKind)
11712 << getOpenMPClauseName(OMPC_is_device_ptr)
11713 << getOpenMPDirectiveName(DSAStack->getCurrentDirective());
11714 ReportOriginalDSA(*this, DSAStack, D, DVar);
11718 Expr *ConflictExpr;
11719 if (DSAStack->checkMappableExprComponentListsForDecl(
11720 D, /*CurrentRegionOnly=*/true,
11722 OMPClauseMappableExprCommon::MappableExprComponentListRef R,
11723 OpenMPClauseKind) -> bool {
11724 ConflictExpr = R.front().getAssociatedExpression();
11727 Diag(ELoc, diag::err_omp_map_shared_storage) << RefExpr->getSourceRange();
11728 Diag(ConflictExpr->getExprLoc(), diag::note_used_here)
11729 << ConflictExpr->getSourceRange();
11733 // Store the components in the stack so that they can be used to check
11734 // against other clauses later on.
11735 OMPClauseMappableExprCommon::MappableComponent MC(SimpleRefExpr, D);
11736 DSAStack->addMappableExpressionComponents(
11737 D, MC, /*WhereFoundClauseKind=*/OMPC_is_device_ptr);
11739 // Record the expression we've just processed.
11740 MVLI.ProcessedVarList.push_back(SimpleRefExpr);
11742 // Create a mappable component for the list item. List items in this clause
11743 // only need a component. We use a null declaration to signal fields in
11745 assert((isa<DeclRefExpr>(SimpleRefExpr) ||
11746 isa<CXXThisExpr>(cast<MemberExpr>(SimpleRefExpr)->getBase())) &&
11747 "Unexpected device pointer expression!");
11748 MVLI.VarBaseDeclarations.push_back(
11749 isa<DeclRefExpr>(SimpleRefExpr) ? D : nullptr);
11750 MVLI.VarComponents.resize(MVLI.VarComponents.size() + 1);
11751 MVLI.VarComponents.back().push_back(MC);
11754 if (MVLI.ProcessedVarList.empty())
11757 return OMPIsDevicePtrClause::Create(
11758 Context, StartLoc, LParenLoc, EndLoc, MVLI.ProcessedVarList,
11759 MVLI.VarBaseDeclarations, MVLI.VarComponents);