HELLO·Android
系统源代码
IT资讯
技术文章
我的收藏
注册
登录
-
我收藏的文章
创建代码块
我的代码块
我的账号
Android 10
|
10.0.0_r6
下载
查看原文件
收藏
根目录
external
clang
lib
Sema
SemaOpenMP.cpp
//===--- SemaOpenMP.cpp - Semantic Analysis for OpenMP constructs ---------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// /// \file /// \brief This file implements semantic analysis for OpenMP directives and /// clauses. /// //===----------------------------------------------------------------------===// #include "TreeTransform.h" #include "clang/AST/ASTContext.h" #include "clang/AST/ASTMutationListener.h" #include "clang/AST/CXXInheritance.h" #include "clang/AST/Decl.h" #include "clang/AST/DeclCXX.h" #include "clang/AST/DeclOpenMP.h" #include "clang/AST/StmtCXX.h" #include "clang/AST/StmtOpenMP.h" #include "clang/AST/StmtVisitor.h" #include "clang/AST/TypeOrdering.h" #include "clang/Basic/OpenMPKinds.h" #include "clang/Basic/TargetInfo.h" #include "clang/Lex/Preprocessor.h" #include "clang/Sema/Initialization.h" #include "clang/Sema/Lookup.h" #include "clang/Sema/Scope.h" #include "clang/Sema/ScopeInfo.h" #include "clang/Sema/SemaInternal.h" using namespace clang; //===----------------------------------------------------------------------===// // Stack of data-sharing attributes for variables //===----------------------------------------------------------------------===// namespace { /// \brief Default data sharing attributes, which can be applied to directive. enum DefaultDataSharingAttributes { DSA_unspecified = 0, /// \brief Data sharing attribute not specified. DSA_none = 1 << 0, /// \brief Default data sharing attribute 'none'. DSA_shared = 1 << 1 /// \brief Default data sharing attribute 'shared'. }; /// \brief Stack for tracking declarations used in OpenMP directives and /// clauses and their data-sharing attributes. class DSAStackTy final { public: struct DSAVarData final { OpenMPDirectiveKind DKind = OMPD_unknown; OpenMPClauseKind CKind = OMPC_unknown; Expr *RefExpr = nullptr; DeclRefExpr *PrivateCopy = nullptr; SourceLocation ImplicitDSALoc; DSAVarData() {} }; typedef llvm::SmallVector
, 4> OperatorOffsetTy; private: struct DSAInfo final { OpenMPClauseKind Attributes = OMPC_unknown; /// Pointer to a reference expression and a flag which shows that the /// variable is marked as lastprivate(true) or not (false). llvm::PointerIntPair
RefExpr; DeclRefExpr *PrivateCopy = nullptr; }; typedef llvm::DenseMap
DeclSAMapTy; typedef llvm::DenseMap
AlignedMapTy; typedef std::pair
LCDeclInfo; typedef llvm::DenseMap
LoopControlVariablesMapTy; typedef llvm::DenseMap< ValueDecl *, OMPClauseMappableExprCommon::MappableExprComponentLists> MappedExprComponentsTy; typedef llvm::StringMap
> CriticalsWithHintsTy; typedef llvm::DenseMap
DoacrossDependMapTy; struct SharingMapTy final { DeclSAMapTy SharingMap; AlignedMapTy AlignedMap; MappedExprComponentsTy MappedExprComponents; LoopControlVariablesMapTy LCVMap; DefaultDataSharingAttributes DefaultAttr = DSA_unspecified; SourceLocation DefaultAttrLoc; OpenMPDirectiveKind Directive = OMPD_unknown; DeclarationNameInfo DirectiveName; Scope *CurScope = nullptr; SourceLocation ConstructLoc; /// Set of 'depend' clauses with 'sink|source' dependence kind. Required to /// get the data (loop counters etc.) about enclosing loop-based construct. /// This data is required during codegen. DoacrossDependMapTy DoacrossDepends; /// \brief first argument (Expr *) contains optional argument of the /// 'ordered' clause, the second one is true if the regions has 'ordered' /// clause, false otherwise. llvm::PointerIntPair
OrderedRegion; bool NowaitRegion = false; bool CancelRegion = false; unsigned AssociatedLoops = 1; SourceLocation InnerTeamsRegionLoc; SharingMapTy(OpenMPDirectiveKind DKind, DeclarationNameInfo Name, Scope *CurScope, SourceLocation Loc) : Directive(DKind), DirectiveName(Name), CurScope(CurScope), ConstructLoc(Loc) {} SharingMapTy() {} }; typedef SmallVector
StackTy; /// \brief Stack of used declaration and their data-sharing attributes. StackTy Stack; /// \brief true, if check for DSA must be from parent directive, false, if /// from current directive. OpenMPClauseKind ClauseKindMode = OMPC_unknown; Sema &SemaRef; bool ForceCapturing = false; CriticalsWithHintsTy Criticals; typedef SmallVector
::reverse_iterator reverse_iterator; DSAVarData getDSA(StackTy::reverse_iterator& Iter, ValueDecl *D); /// \brief Checks if the variable is a local for OpenMP region. bool isOpenMPLocal(VarDecl *D, StackTy::reverse_iterator Iter); public: explicit DSAStackTy(Sema &S) : Stack(1), SemaRef(S) {} bool isClauseParsingMode() const { return ClauseKindMode != OMPC_unknown; } void setClauseParsingMode(OpenMPClauseKind K) { ClauseKindMode = K; } bool isForceVarCapturing() const { return ForceCapturing; } void setForceVarCapturing(bool V) { ForceCapturing = V; } void push(OpenMPDirectiveKind DKind, const DeclarationNameInfo &DirName, Scope *CurScope, SourceLocation Loc) { Stack.push_back(SharingMapTy(DKind, DirName, CurScope, Loc)); Stack.back().DefaultAttrLoc = Loc; } void pop() { assert(Stack.size() > 1 && "Data-sharing attributes stack is empty!"); Stack.pop_back(); } void addCriticalWithHint(OMPCriticalDirective *D, llvm::APSInt Hint) { Criticals[D->getDirectiveName().getAsString()] = std::make_pair(D, Hint); } const std::pair
getCriticalWithHint(const DeclarationNameInfo &Name) const { auto I = Criticals.find(Name.getAsString()); if (I != Criticals.end()) return I->second; return std::make_pair(nullptr, llvm::APSInt()); } /// \brief If 'aligned' declaration for given variable \a D was not seen yet, /// add it and return NULL; otherwise return previous occurrence's expression /// for diagnostics. Expr *addUniqueAligned(ValueDecl *D, Expr *NewDE); /// \brief Register specified variable as loop control variable. void addLoopControlVariable(ValueDecl *D, VarDecl *Capture); /// \brief Check if the specified variable is a loop control variable for /// current region. /// \return The index of the loop control variable in the list of associated /// for-loops (from outer to inner). LCDeclInfo isLoopControlVariable(ValueDecl *D); /// \brief Check if the specified variable is a loop control variable for /// parent region. /// \return The index of the loop control variable in the list of associated /// for-loops (from outer to inner). LCDeclInfo isParentLoopControlVariable(ValueDecl *D); /// \brief Get the loop control variable for the I-th loop (or nullptr) in /// parent directive. ValueDecl *getParentLoopControlVariable(unsigned I); /// \brief Adds explicit data sharing attribute to the specified declaration. void addDSA(ValueDecl *D, Expr *E, OpenMPClauseKind A, DeclRefExpr *PrivateCopy = nullptr); /// \brief Returns data sharing attributes from top of the stack for the /// specified declaration. DSAVarData getTopDSA(ValueDecl *D, bool FromParent); /// \brief Returns data-sharing attributes for the specified declaration. DSAVarData getImplicitDSA(ValueDecl *D, bool FromParent); /// \brief Checks if the specified variables has data-sharing attributes which /// match specified \a CPred predicate in any directive which matches \a DPred /// predicate. DSAVarData hasDSA(ValueDecl *D, const llvm::function_ref
&CPred, const llvm::function_ref
&DPred, bool FromParent); /// \brief Checks if the specified variables has data-sharing attributes which /// match specified \a CPred predicate in any innermost directive which /// matches \a DPred predicate. DSAVarData hasInnermostDSA(ValueDecl *D, const llvm::function_ref
&CPred, const llvm::function_ref
&DPred, bool FromParent); /// \brief Checks if the specified variables has explicit data-sharing /// attributes which match specified \a CPred predicate at the specified /// OpenMP region. bool hasExplicitDSA(ValueDecl *D, const llvm::function_ref
&CPred, unsigned Level, bool NotLastprivate = false); /// \brief Returns true if the directive at level \Level matches in the /// specified \a DPred predicate. bool hasExplicitDirective( const llvm::function_ref
&DPred, unsigned Level); /// \brief Finds a directive which matches specified \a DPred predicate. bool hasDirective(const llvm::function_ref
&DPred, bool FromParent); /// \brief Returns currently analyzed directive. OpenMPDirectiveKind getCurrentDirective() const { return Stack.back().Directive; } /// \brief Returns parent directive. OpenMPDirectiveKind getParentDirective() const { if (Stack.size() > 2) return Stack[Stack.size() - 2].Directive; return OMPD_unknown; } /// \brief Set default data sharing attribute to none. void setDefaultDSANone(SourceLocation Loc) { Stack.back().DefaultAttr = DSA_none; Stack.back().DefaultAttrLoc = Loc; } /// \brief Set default data sharing attribute to shared. void setDefaultDSAShared(SourceLocation Loc) { Stack.back().DefaultAttr = DSA_shared; Stack.back().DefaultAttrLoc = Loc; } DefaultDataSharingAttributes getDefaultDSA() const { return Stack.back().DefaultAttr; } SourceLocation getDefaultDSALocation() const { return Stack.back().DefaultAttrLoc; } /// \brief Checks if the specified variable is a threadprivate. bool isThreadPrivate(VarDecl *D) { DSAVarData DVar = getTopDSA(D, false); return isOpenMPThreadPrivate(DVar.CKind); } /// \brief Marks current region as ordered (it has an 'ordered' clause). void setOrderedRegion(bool IsOrdered, Expr *Param) { Stack.back().OrderedRegion.setInt(IsOrdered); Stack.back().OrderedRegion.setPointer(Param); } /// \brief Returns true, if parent region is ordered (has associated /// 'ordered' clause), false - otherwise. bool isParentOrderedRegion() const { if (Stack.size() > 2) return Stack[Stack.size() - 2].OrderedRegion.getInt(); return false; } /// \brief Returns optional parameter for the ordered region. Expr *getParentOrderedRegionParam() const { if (Stack.size() > 2) return Stack[Stack.size() - 2].OrderedRegion.getPointer(); return nullptr; } /// \brief Marks current region as nowait (it has a 'nowait' clause). void setNowaitRegion(bool IsNowait = true) { Stack.back().NowaitRegion = IsNowait; } /// \brief Returns true, if parent region is nowait (has associated /// 'nowait' clause), false - otherwise. bool isParentNowaitRegion() const { if (Stack.size() > 2) return Stack[Stack.size() - 2].NowaitRegion; return false; } /// \brief Marks parent region as cancel region. void setParentCancelRegion(bool Cancel = true) { if (Stack.size() > 2) Stack[Stack.size() - 2].CancelRegion = Stack[Stack.size() - 2].CancelRegion || Cancel; } /// \brief Return true if current region has inner cancel construct. bool isCancelRegion() const { return Stack.back().CancelRegion; } /// \brief Set collapse value for the region. void setAssociatedLoops(unsigned Val) { Stack.back().AssociatedLoops = Val; } /// \brief Return collapse value for region. unsigned getAssociatedLoops() const { return Stack.back().AssociatedLoops; } /// \brief Marks current target region as one with closely nested teams /// region. void setParentTeamsRegionLoc(SourceLocation TeamsRegionLoc) { if (Stack.size() > 2) Stack[Stack.size() - 2].InnerTeamsRegionLoc = TeamsRegionLoc; } /// \brief Returns true, if current region has closely nested teams region. bool hasInnerTeamsRegion() const { return getInnerTeamsRegionLoc().isValid(); } /// \brief Returns location of the nested teams region (if any). SourceLocation getInnerTeamsRegionLoc() const { if (Stack.size() > 1) return Stack.back().InnerTeamsRegionLoc; return SourceLocation(); } Scope *getCurScope() const { return Stack.back().CurScope; } Scope *getCurScope() { return Stack.back().CurScope; } SourceLocation getConstructLoc() { return Stack.back().ConstructLoc; } // Do the check specified in \a Check to all component lists and return true // if any issue is found. bool checkMappableExprComponentListsForDecl( ValueDecl *VD, bool CurrentRegionOnly, const llvm::function_ref
&Check) { auto SI = Stack.rbegin(); auto SE = Stack.rend(); if (SI == SE) return false; if (CurrentRegionOnly) { SE = std::next(SI); } else { ++SI; } for (; SI != SE; ++SI) { auto MI = SI->MappedExprComponents.find(VD); if (MI != SI->MappedExprComponents.end()) for (auto &L : MI->second) if (Check(L)) return true; } return false; } // Create a new mappable expression component list associated with a given // declaration and initialize it with the provided list of components. void addMappableExpressionComponents( ValueDecl *VD, OMPClauseMappableExprCommon::MappableExprComponentListRef Components) { assert(Stack.size() > 1 && "Not expecting to retrieve components from a empty stack!"); auto &MEC = Stack.back().MappedExprComponents[VD]; // Create new entry and append the new components there. MEC.resize(MEC.size() + 1); MEC.back().append(Components.begin(), Components.end()); } unsigned getNestingLevel() const { assert(Stack.size() > 1); return Stack.size() - 2; } void addDoacrossDependClause(OMPDependClause *C, OperatorOffsetTy &OpsOffs) { assert(Stack.size() > 2); assert(isOpenMPWorksharingDirective(Stack[Stack.size() - 2].Directive)); Stack[Stack.size() - 2].DoacrossDepends.insert({C, OpsOffs}); } llvm::iterator_range
getDoacrossDependClauses() const { assert(Stack.size() > 1); if (isOpenMPWorksharingDirective(Stack[Stack.size() - 1].Directive)) { auto &Ref = Stack[Stack.size() - 1].DoacrossDepends; return llvm::make_range(Ref.begin(), Ref.end()); } return llvm::make_range(Stack[0].DoacrossDepends.end(), Stack[0].DoacrossDepends.end()); } }; bool isParallelOrTaskRegion(OpenMPDirectiveKind DKind) { return isOpenMPParallelDirective(DKind) || isOpenMPTaskingDirective(DKind) || isOpenMPTeamsDirective(DKind) || DKind == OMPD_unknown; } } // namespace static ValueDecl *getCanonicalDecl(ValueDecl *D) { auto *VD = dyn_cast
(D); auto *FD = dyn_cast
(D); if (VD != nullptr) { VD = VD->getCanonicalDecl(); D = VD; } else { assert(FD); FD = FD->getCanonicalDecl(); D = FD; } return D; } DSAStackTy::DSAVarData DSAStackTy::getDSA(StackTy::reverse_iterator& Iter, ValueDecl *D) { D = getCanonicalDecl(D); auto *VD = dyn_cast
(D); auto *FD = dyn_cast
(D); DSAVarData DVar; if (Iter == std::prev(Stack.rend())) { // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced // in a region but not in construct] // File-scope or namespace-scope variables referenced in called routines // in the region are shared unless they appear in a threadprivate // directive. if (VD && !VD->isFunctionOrMethodVarDecl() && !isa
(D)) DVar.CKind = OMPC_shared; // OpenMP [2.9.1.2, Data-sharing Attribute Rules for Variables Referenced // in a region but not in construct] // Variables with static storage duration that are declared in called // routines in the region are shared. if (VD && VD->hasGlobalStorage()) DVar.CKind = OMPC_shared; // Non-static data members are shared by default. if (FD) DVar.CKind = OMPC_shared; return DVar; } DVar.DKind = Iter->Directive; // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced // in a Construct, C/C++, predetermined, p.1] // Variables with automatic storage duration that are declared in a scope // inside the construct are private. if (VD && isOpenMPLocal(VD, Iter) && VD->isLocalVarDecl() && (VD->getStorageClass() == SC_Auto || VD->getStorageClass() == SC_None)) { DVar.CKind = OMPC_private; return DVar; } // Explicitly specified attributes and local variables with predetermined // attributes. if (Iter->SharingMap.count(D)) { DVar.RefExpr = Iter->SharingMap[D].RefExpr.getPointer(); DVar.PrivateCopy = Iter->SharingMap[D].PrivateCopy; DVar.CKind = Iter->SharingMap[D].Attributes; DVar.ImplicitDSALoc = Iter->DefaultAttrLoc; return DVar; } // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced // in a Construct, C/C++, implicitly determined, p.1] // In a parallel or task construct, the data-sharing attributes of these // variables are determined by the default clause, if present. switch (Iter->DefaultAttr) { case DSA_shared: DVar.CKind = OMPC_shared; DVar.ImplicitDSALoc = Iter->DefaultAttrLoc; return DVar; case DSA_none: return DVar; case DSA_unspecified: // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced // in a Construct, implicitly determined, p.2] // In a parallel construct, if no default clause is present, these // variables are shared. DVar.ImplicitDSALoc = Iter->DefaultAttrLoc; if (isOpenMPParallelDirective(DVar.DKind) || isOpenMPTeamsDirective(DVar.DKind)) { DVar.CKind = OMPC_shared; return DVar; } // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced // in a Construct, implicitly determined, p.4] // In a task construct, if no default clause is present, a variable that in // the enclosing context is determined to be shared by all implicit tasks // bound to the current team is shared. if (isOpenMPTaskingDirective(DVar.DKind)) { DSAVarData DVarTemp; for (StackTy::reverse_iterator I = std::next(Iter), EE = Stack.rend(); I != EE; ++I) { // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables // Referenced in a Construct, implicitly determined, p.6] // In a task construct, if no default clause is present, a variable // whose data-sharing attribute is not determined by the rules above is // firstprivate. DVarTemp = getDSA(I, D); if (DVarTemp.CKind != OMPC_shared) { DVar.RefExpr = nullptr; DVar.CKind = OMPC_firstprivate; return DVar; } if (isParallelOrTaskRegion(I->Directive)) break; } DVar.CKind = (DVarTemp.CKind == OMPC_unknown) ? OMPC_firstprivate : OMPC_shared; return DVar; } } // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced // in a Construct, implicitly determined, p.3] // For constructs other than task, if no default clause is present, these // variables inherit their data-sharing attributes from the enclosing // context. return getDSA(++Iter, D); } Expr *DSAStackTy::addUniqueAligned(ValueDecl *D, Expr *NewDE) { assert(Stack.size() > 1 && "Data sharing attributes stack is empty"); D = getCanonicalDecl(D); auto It = Stack.back().AlignedMap.find(D); if (It == Stack.back().AlignedMap.end()) { assert(NewDE && "Unexpected nullptr expr to be added into aligned map"); Stack.back().AlignedMap[D] = NewDE; return nullptr; } else { assert(It->second && "Unexpected nullptr expr in the aligned map"); return It->second; } return nullptr; } void DSAStackTy::addLoopControlVariable(ValueDecl *D, VarDecl *Capture) { assert(Stack.size() > 1 && "Data-sharing attributes stack is empty"); D = getCanonicalDecl(D); Stack.back().LCVMap.insert( std::make_pair(D, LCDeclInfo(Stack.back().LCVMap.size() + 1, Capture))); } DSAStackTy::LCDeclInfo DSAStackTy::isLoopControlVariable(ValueDecl *D) { assert(Stack.size() > 1 && "Data-sharing attributes stack is empty"); D = getCanonicalDecl(D); return Stack.back().LCVMap.count(D) > 0 ? Stack.back().LCVMap[D] : LCDeclInfo(0, nullptr); } DSAStackTy::LCDeclInfo DSAStackTy::isParentLoopControlVariable(ValueDecl *D) { assert(Stack.size() > 2 && "Data-sharing attributes stack is empty"); D = getCanonicalDecl(D); return Stack[Stack.size() - 2].LCVMap.count(D) > 0 ? Stack[Stack.size() - 2].LCVMap[D] : LCDeclInfo(0, nullptr); } ValueDecl *DSAStackTy::getParentLoopControlVariable(unsigned I) { assert(Stack.size() > 2 && "Data-sharing attributes stack is empty"); if (Stack[Stack.size() - 2].LCVMap.size() < I) return nullptr; for (auto &Pair : Stack[Stack.size() - 2].LCVMap) { if (Pair.second.first == I) return Pair.first; } return nullptr; } void DSAStackTy::addDSA(ValueDecl *D, Expr *E, OpenMPClauseKind A, DeclRefExpr *PrivateCopy) { D = getCanonicalDecl(D); if (A == OMPC_threadprivate) { auto &Data = Stack[0].SharingMap[D]; Data.Attributes = A; Data.RefExpr.setPointer(E); Data.PrivateCopy = nullptr; } else { assert(Stack.size() > 1 && "Data-sharing attributes stack is empty"); auto &Data = Stack.back().SharingMap[D]; assert(Data.Attributes == OMPC_unknown || (A == Data.Attributes) || (A == OMPC_firstprivate && Data.Attributes == OMPC_lastprivate) || (A == OMPC_lastprivate && Data.Attributes == OMPC_firstprivate) || (isLoopControlVariable(D).first && A == OMPC_private)); if (A == OMPC_lastprivate && Data.Attributes == OMPC_firstprivate) { Data.RefExpr.setInt(/*IntVal=*/true); return; } const bool IsLastprivate = A == OMPC_lastprivate || Data.Attributes == OMPC_lastprivate; Data.Attributes = A; Data.RefExpr.setPointerAndInt(E, IsLastprivate); Data.PrivateCopy = PrivateCopy; if (PrivateCopy) { auto &Data = Stack.back().SharingMap[PrivateCopy->getDecl()]; Data.Attributes = A; Data.RefExpr.setPointerAndInt(PrivateCopy, IsLastprivate); Data.PrivateCopy = nullptr; } } } bool DSAStackTy::isOpenMPLocal(VarDecl *D, StackTy::reverse_iterator Iter) { D = D->getCanonicalDecl(); if (Stack.size() > 2) { reverse_iterator I = Iter, E = std::prev(Stack.rend()); Scope *TopScope = nullptr; while (I != E && !isParallelOrTaskRegion(I->Directive)) { ++I; } if (I == E) return false; TopScope = I->CurScope ? I->CurScope->getParent() : nullptr; Scope *CurScope = getCurScope(); while (CurScope != TopScope && !CurScope->isDeclScope(D)) { CurScope = CurScope->getParent(); } return CurScope != TopScope; } return false; } /// \brief Build a variable declaration for OpenMP loop iteration variable. static VarDecl *buildVarDecl(Sema &SemaRef, SourceLocation Loc, QualType Type, StringRef Name, const AttrVec *Attrs = nullptr) { DeclContext *DC = SemaRef.CurContext; IdentifierInfo *II = &SemaRef.PP.getIdentifierTable().get(Name); TypeSourceInfo *TInfo = SemaRef.Context.getTrivialTypeSourceInfo(Type, Loc); VarDecl *Decl = VarDecl::Create(SemaRef.Context, DC, Loc, Loc, II, Type, TInfo, SC_None); if (Attrs) { for (specific_attr_iterator
I(Attrs->begin()), E(Attrs->end()); I != E; ++I) Decl->addAttr(*I); } Decl->setImplicit(); return Decl; } static DeclRefExpr *buildDeclRefExpr(Sema &S, VarDecl *D, QualType Ty, SourceLocation Loc, bool RefersToCapture = false) { D->setReferenced(); D->markUsed(S.Context); return DeclRefExpr::Create(S.getASTContext(), NestedNameSpecifierLoc(), SourceLocation(), D, RefersToCapture, Loc, Ty, VK_LValue); } DSAStackTy::DSAVarData DSAStackTy::getTopDSA(ValueDecl *D, bool FromParent) { D = getCanonicalDecl(D); DSAVarData DVar; // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced // in a Construct, C/C++, predetermined, p.1] // Variables appearing in threadprivate directives are threadprivate. auto *VD = dyn_cast
(D); if ((VD && VD->getTLSKind() != VarDecl::TLS_None && !(VD->hasAttr
() && SemaRef.getLangOpts().OpenMPUseTLS && SemaRef.getASTContext().getTargetInfo().isTLSSupported())) || (VD && VD->getStorageClass() == SC_Register && VD->hasAttr
() && !VD->isLocalVarDecl())) { addDSA(D, buildDeclRefExpr(SemaRef, VD, D->getType().getNonReferenceType(), D->getLocation()), OMPC_threadprivate); } if (Stack[0].SharingMap.count(D)) { DVar.RefExpr = Stack[0].SharingMap[D].RefExpr.getPointer(); DVar.CKind = OMPC_threadprivate; return DVar; } if (Stack.size() == 1) { // Not in OpenMP execution region and top scope was already checked. return DVar; } // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced // in a Construct, C/C++, predetermined, p.4] // Static data members are shared. // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced // in a Construct, C/C++, predetermined, p.7] // Variables with static storage duration that are declared in a scope // inside the construct are shared. auto &&MatchesAlways = [](OpenMPDirectiveKind) -> bool { return true; }; if (VD && VD->isStaticDataMember()) { DSAVarData DVarTemp = hasDSA(D, isOpenMPPrivate, MatchesAlways, FromParent); if (DVarTemp.CKind != OMPC_unknown && DVarTemp.RefExpr) return DVar; DVar.CKind = OMPC_shared; return DVar; } QualType Type = D->getType().getNonReferenceType().getCanonicalType(); bool IsConstant = Type.isConstant(SemaRef.getASTContext()); Type = SemaRef.getASTContext().getBaseElementType(Type); // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced // in a Construct, C/C++, predetermined, p.6] // Variables with const qualified type having no mutable member are // shared. CXXRecordDecl *RD = SemaRef.getLangOpts().CPlusPlus ? Type->getAsCXXRecordDecl() : nullptr; if (auto *CTSD = dyn_cast_or_null
(RD)) if (auto *CTD = CTSD->getSpecializedTemplate()) RD = CTD->getTemplatedDecl(); if (IsConstant && !(SemaRef.getLangOpts().CPlusPlus && RD && RD->hasDefinition() && RD->hasMutableFields())) { // Variables with const-qualified type having no mutable member may be // listed in a firstprivate clause, even if they are static data members. DSAVarData DVarTemp = hasDSA( D, [](OpenMPClauseKind C) -> bool { return C == OMPC_firstprivate; }, MatchesAlways, FromParent); if (DVarTemp.CKind == OMPC_firstprivate && DVarTemp.RefExpr) return DVar; DVar.CKind = OMPC_shared; return DVar; } // Explicitly specified attributes and local variables with predetermined // attributes. auto StartI = std::next(Stack.rbegin()); auto EndI = std::prev(Stack.rend()); if (FromParent && StartI != EndI) { StartI = std::next(StartI); } auto I = std::prev(StartI); if (I->SharingMap.count(D)) { DVar.RefExpr = I->SharingMap[D].RefExpr.getPointer(); DVar.PrivateCopy = I->SharingMap[D].PrivateCopy; DVar.CKind = I->SharingMap[D].Attributes; DVar.ImplicitDSALoc = I->DefaultAttrLoc; } return DVar; } DSAStackTy::DSAVarData DSAStackTy::getImplicitDSA(ValueDecl *D, bool FromParent) { D = getCanonicalDecl(D); auto StartI = Stack.rbegin(); auto EndI = std::prev(Stack.rend()); if (FromParent && StartI != EndI) { StartI = std::next(StartI); } return getDSA(StartI, D); } DSAStackTy::DSAVarData DSAStackTy::hasDSA(ValueDecl *D, const llvm::function_ref
&CPred, const llvm::function_ref
&DPred, bool FromParent) { D = getCanonicalDecl(D); auto StartI = std::next(Stack.rbegin()); auto EndI = Stack.rend(); if (FromParent && StartI != EndI) { StartI = std::next(StartI); } for (auto I = StartI, EE = EndI; I != EE; ++I) { if (!DPred(I->Directive) && !isParallelOrTaskRegion(I->Directive)) continue; DSAVarData DVar = getDSA(I, D); if (CPred(DVar.CKind)) return DVar; } return DSAVarData(); } DSAStackTy::DSAVarData DSAStackTy::hasInnermostDSA( ValueDecl *D, const llvm::function_ref
&CPred, const llvm::function_ref
&DPred, bool FromParent) { D = getCanonicalDecl(D); auto StartI = std::next(Stack.rbegin()); auto EndI = Stack.rend(); if (FromParent && StartI != EndI) { StartI = std::next(StartI); } for (auto I = StartI, EE = EndI; I != EE; ++I) { if (!DPred(I->Directive)) break; DSAVarData DVar = getDSA(I, D); if (CPred(DVar.CKind)) return DVar; return DSAVarData(); } return DSAVarData(); } bool DSAStackTy::hasExplicitDSA( ValueDecl *D, const llvm::function_ref
&CPred, unsigned Level, bool NotLastprivate) { if (CPred(ClauseKindMode)) return true; D = getCanonicalDecl(D); auto StartI = std::next(Stack.begin()); auto EndI = Stack.end(); if (std::distance(StartI, EndI) <= (int)Level) return false; std::advance(StartI, Level); return (StartI->SharingMap.count(D) > 0) && StartI->SharingMap[D].RefExpr.getPointer() && CPred(StartI->SharingMap[D].Attributes) && (!NotLastprivate || !StartI->SharingMap[D].RefExpr.getInt()); } bool DSAStackTy::hasExplicitDirective( const llvm::function_ref
&DPred, unsigned Level) { auto StartI = std::next(Stack.begin()); auto EndI = Stack.end(); if (std::distance(StartI, EndI) <= (int)Level) return false; std::advance(StartI, Level); return DPred(StartI->Directive); } bool DSAStackTy::hasDirective( const llvm::function_ref
&DPred, bool FromParent) { // We look only in the enclosing region. if (Stack.size() < 2) return false; auto StartI = std::next(Stack.rbegin()); auto EndI = std::prev(Stack.rend()); if (FromParent && StartI != EndI) { StartI = std::next(StartI); } for (auto I = StartI, EE = EndI; I != EE; ++I) { if (DPred(I->Directive, I->DirectiveName, I->ConstructLoc)) return true; } return false; } void Sema::InitDataSharingAttributesStack() { VarDataSharingAttributesStack = new DSAStackTy(*this); } #define DSAStack static_cast
(VarDataSharingAttributesStack) bool Sema::IsOpenMPCapturedByRef(ValueDecl *D, unsigned Level) { assert(LangOpts.OpenMP && "OpenMP is not allowed"); auto &Ctx = getASTContext(); bool IsByRef = true; // Find the directive that is associated with the provided scope. auto Ty = D->getType(); if (DSAStack->hasExplicitDirective(isOpenMPTargetExecutionDirective, Level)) { // This table summarizes how a given variable should be passed to the device // given its type and the clauses where it appears. This table is based on // the description in OpenMP 4.5 [2.10.4, target Construct] and // OpenMP 4.5 [2.15.5, Data-mapping Attribute Rules and Clauses]. // // ========================================================================= // | type | defaultmap | pvt | first | is_device_ptr | map | res. | // | |(tofrom:scalar)| | pvt | | | | // ========================================================================= // | scl | | | | - | | bycopy| // | scl | | - | x | - | - | bycopy| // | scl | | x | - | - | - | null | // | scl | x | | | - | | byref | // | scl | x | - | x | - | - | bycopy| // | scl | x | x | - | - | - | null | // | scl | | - | - | - | x | byref | // | scl | x | - | - | - | x | byref | // // | agg | n.a. | | | - | | byref | // | agg | n.a. | - | x | - | - | byref | // | agg | n.a. | x | - | - | - | null | // | agg | n.a. | - | - | - | x | byref | // | agg | n.a. | - | - | - | x[] | byref | // // | ptr | n.a. | | | - | | bycopy| // | ptr | n.a. | - | x | - | - | bycopy| // | ptr | n.a. | x | - | - | - | null | // | ptr | n.a. | - | - | - | x | byref | // | ptr | n.a. | - | - | - | x[] | bycopy| // | ptr | n.a. | - | - | x | | bycopy| // | ptr | n.a. | - | - | x | x | bycopy| // | ptr | n.a. | - | - | x | x[] | bycopy| // ========================================================================= // Legend: // scl - scalar // ptr - pointer // agg - aggregate // x - applies // - - invalid in this combination // [] - mapped with an array section // byref - should be mapped by reference // byval - should be mapped by value // null - initialize a local variable to null on the device // // Observations: // - All scalar declarations that show up in a map clause have to be passed // by reference, because they may have been mapped in the enclosing data // environment. // - If the scalar value does not fit the size of uintptr, it has to be // passed by reference, regardless the result in the table above. // - For pointers mapped by value that have either an implicit map or an // array section, the runtime library may pass the NULL value to the // device instead of the value passed to it by the compiler. if (Ty->isReferenceType()) Ty = Ty->castAs
()->getPointeeType(); // Locate map clauses and see if the variable being captured is referred to // in any of those clauses. Here we only care about variables, not fields, // because fields are part of aggregates. bool IsVariableUsedInMapClause = false; bool IsVariableAssociatedWithSection = false; DSAStack->checkMappableExprComponentListsForDecl( D, /*CurrentRegionOnly=*/true, [&](OMPClauseMappableExprCommon::MappableExprComponentListRef MapExprComponents) { auto EI = MapExprComponents.rbegin(); auto EE = MapExprComponents.rend(); assert(EI != EE && "Invalid map expression!"); if (isa
(EI->getAssociatedExpression())) IsVariableUsedInMapClause |= EI->getAssociatedDeclaration() == D; ++EI; if (EI == EE) return false; if (isa
(EI->getAssociatedExpression()) || isa
(EI->getAssociatedExpression()) || isa
(EI->getAssociatedExpression())) { IsVariableAssociatedWithSection = true; // There is nothing more we need to know about this variable. return true; } // Keep looking for more map info. return false; }); if (IsVariableUsedInMapClause) { // If variable is identified in a map clause it is always captured by // reference except if it is a pointer that is dereferenced somehow. IsByRef = !(Ty->isPointerType() && IsVariableAssociatedWithSection); } else { // By default, all the data that has a scalar type is mapped by copy. IsByRef = !Ty->isScalarType(); } } if (IsByRef && Ty.getNonReferenceType()->isScalarType()) { IsByRef = !DSAStack->hasExplicitDSA( D, [](OpenMPClauseKind K) -> bool { return K == OMPC_firstprivate; }, Level, /*NotLastprivate=*/true); } // When passing data by copy, we need to make sure it fits the uintptr size // and alignment, because the runtime library only deals with uintptr types. // If it does not fit the uintptr size, we need to pass the data by reference // instead. if (!IsByRef && (Ctx.getTypeSizeInChars(Ty) > Ctx.getTypeSizeInChars(Ctx.getUIntPtrType()) || Ctx.getDeclAlign(D) > Ctx.getTypeAlignInChars(Ctx.getUIntPtrType()))) { IsByRef = true; } return IsByRef; } unsigned Sema::getOpenMPNestingLevel() const { assert(getLangOpts().OpenMP); return DSAStack->getNestingLevel(); } VarDecl *Sema::IsOpenMPCapturedDecl(ValueDecl *D) { assert(LangOpts.OpenMP && "OpenMP is not allowed"); D = getCanonicalDecl(D); // If we are attempting to capture a global variable in a directive with // 'target' we return true so that this global is also mapped to the device. // // FIXME: If the declaration is enclosed in a 'declare target' directive, // then it should not be captured. Therefore, an extra check has to be // inserted here once support for 'declare target' is added. // auto *VD = dyn_cast
(D); if (VD && !VD->hasLocalStorage()) { if (DSAStack->getCurrentDirective() == OMPD_target && !DSAStack->isClauseParsingMode()) return VD; if (DSAStack->hasDirective( [](OpenMPDirectiveKind K, const DeclarationNameInfo &, SourceLocation) -> bool { return isOpenMPTargetExecutionDirective(K); }, false)) return VD; } if (DSAStack->getCurrentDirective() != OMPD_unknown && (!DSAStack->isClauseParsingMode() || DSAStack->getParentDirective() != OMPD_unknown)) { auto &&Info = DSAStack->isLoopControlVariable(D); if (Info.first || (VD && VD->hasLocalStorage() && isParallelOrTaskRegion(DSAStack->getCurrentDirective())) || (VD && DSAStack->isForceVarCapturing())) return VD ? VD : Info.second; auto DVarPrivate = DSAStack->getTopDSA(D, DSAStack->isClauseParsingMode()); if (DVarPrivate.CKind != OMPC_unknown && isOpenMPPrivate(DVarPrivate.CKind)) return VD ? VD : cast
(DVarPrivate.PrivateCopy->getDecl()); DVarPrivate = DSAStack->hasDSA( D, isOpenMPPrivate, [](OpenMPDirectiveKind) -> bool { return true; }, DSAStack->isClauseParsingMode()); if (DVarPrivate.CKind != OMPC_unknown) return VD ? VD : cast
(DVarPrivate.PrivateCopy->getDecl()); } return nullptr; } bool Sema::isOpenMPPrivateDecl(ValueDecl *D, unsigned Level) { assert(LangOpts.OpenMP && "OpenMP is not allowed"); return DSAStack->hasExplicitDSA( D, [](OpenMPClauseKind K) -> bool { return K == OMPC_private; }, Level); } bool Sema::isOpenMPTargetCapturedDecl(ValueDecl *D, unsigned Level) { assert(LangOpts.OpenMP && "OpenMP is not allowed"); // Return true if the current level is no longer enclosed in a target region. auto *VD = dyn_cast
(D); return VD && !VD->hasLocalStorage() && DSAStack->hasExplicitDirective(isOpenMPTargetExecutionDirective, Level); } void Sema::DestroyDataSharingAttributesStack() { delete DSAStack; } void Sema::StartOpenMPDSABlock(OpenMPDirectiveKind DKind, const DeclarationNameInfo &DirName, Scope *CurScope, SourceLocation Loc) { DSAStack->push(DKind, DirName, CurScope, Loc); PushExpressionEvaluationContext(PotentiallyEvaluated); } void Sema::StartOpenMPClause(OpenMPClauseKind K) { DSAStack->setClauseParsingMode(K); } void Sema::EndOpenMPClause() { DSAStack->setClauseParsingMode(/*K=*/OMPC_unknown); } void Sema::EndOpenMPDSABlock(Stmt *CurDirective) { // OpenMP [2.14.3.5, Restrictions, C/C++, p.1] // A variable of class type (or array thereof) that appears in a lastprivate // clause requires an accessible, unambiguous default constructor for the // class type, unless the list item is also specified in a firstprivate // clause. if (auto D = dyn_cast_or_null
(CurDirective)) { for (auto *C : D->clauses()) { if (auto *Clause = dyn_cast
(C)) { SmallVector
PrivateCopies; for (auto *DE : Clause->varlists()) { if (DE->isValueDependent() || DE->isTypeDependent()) { PrivateCopies.push_back(nullptr); continue; } auto *DRE = cast
(DE->IgnoreParens()); VarDecl *VD = cast
(DRE->getDecl()); QualType Type = VD->getType().getNonReferenceType(); auto DVar = DSAStack->getTopDSA(VD, false); if (DVar.CKind == OMPC_lastprivate) { // Generate helper private variable and initialize it with the // default value. The address of the original variable is replaced // by the address of the new private variable in CodeGen. This new // variable is not added to IdResolver, so the code in the OpenMP // region uses original variable for proper diagnostics. auto *VDPrivate = buildVarDecl( *this, DE->getExprLoc(), Type.getUnqualifiedType(), VD->getName(), VD->hasAttrs() ? &VD->getAttrs() : nullptr); ActOnUninitializedDecl(VDPrivate, /*TypeMayContainAuto=*/false); if (VDPrivate->isInvalidDecl()) continue; PrivateCopies.push_back(buildDeclRefExpr( *this, VDPrivate, DE->getType(), DE->getExprLoc())); } else { // The variable is also a firstprivate, so initialization sequence // for private copy is generated already. PrivateCopies.push_back(nullptr); } } // Set initializers to private copies if no errors were found. if (PrivateCopies.size() == Clause->varlist_size()) Clause->setPrivateCopies(PrivateCopies); } } } DSAStack->pop(); DiscardCleanupsInEvaluationContext(); PopExpressionEvaluationContext(); } static bool FinishOpenMPLinearClause(OMPLinearClause &Clause, DeclRefExpr *IV, Expr *NumIterations, Sema &SemaRef, Scope *S, DSAStackTy *Stack); namespace { class VarDeclFilterCCC : public CorrectionCandidateCallback { private: Sema &SemaRef; public: explicit VarDeclFilterCCC(Sema &S) : SemaRef(S) {} bool ValidateCandidate(const TypoCorrection &Candidate) override { NamedDecl *ND = Candidate.getCorrectionDecl(); if (VarDecl *VD = dyn_cast_or_null
(ND)) { return VD->hasGlobalStorage() && SemaRef.isDeclInScope(ND, SemaRef.getCurLexicalContext(), SemaRef.getCurScope()); } return false; } }; class VarOrFuncDeclFilterCCC : public CorrectionCandidateCallback { private: Sema &SemaRef; public: explicit VarOrFuncDeclFilterCCC(Sema &S) : SemaRef(S) {} bool ValidateCandidate(const TypoCorrection &Candidate) override { NamedDecl *ND = Candidate.getCorrectionDecl(); if (isa
(ND) || isa
(ND)) { return SemaRef.isDeclInScope(ND, SemaRef.getCurLexicalContext(), SemaRef.getCurScope()); } return false; } }; } // namespace ExprResult Sema::ActOnOpenMPIdExpression(Scope *CurScope, CXXScopeSpec &ScopeSpec, const DeclarationNameInfo &Id) { LookupResult Lookup(*this, Id, LookupOrdinaryName); LookupParsedName(Lookup, CurScope, &ScopeSpec, true); if (Lookup.isAmbiguous()) return ExprError(); VarDecl *VD; if (!Lookup.isSingleResult()) { if (TypoCorrection Corrected = CorrectTypo( Id, LookupOrdinaryName, CurScope, nullptr, llvm::make_unique
(*this), CTK_ErrorRecovery)) { diagnoseTypo(Corrected, PDiag(Lookup.empty() ? diag::err_undeclared_var_use_suggest : diag::err_omp_expected_var_arg_suggest) << Id.getName()); VD = Corrected.getCorrectionDeclAs
(); } else { Diag(Id.getLoc(), Lookup.empty() ? diag::err_undeclared_var_use : diag::err_omp_expected_var_arg) << Id.getName(); return ExprError(); } } else { if (!(VD = Lookup.getAsSingle
())) { Diag(Id.getLoc(), diag::err_omp_expected_var_arg) << Id.getName(); Diag(Lookup.getFoundDecl()->getLocation(), diag::note_declared_at); return ExprError(); } } Lookup.suppressDiagnostics(); // OpenMP [2.9.2, Syntax, C/C++] // Variables must be file-scope, namespace-scope, or static block-scope. if (!VD->hasGlobalStorage()) { Diag(Id.getLoc(), diag::err_omp_global_var_arg) << getOpenMPDirectiveName(OMPD_threadprivate) << !VD->isStaticLocal(); bool IsDecl = VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly; Diag(VD->getLocation(), IsDecl ? diag::note_previous_decl : diag::note_defined_here) << VD; return ExprError(); } VarDecl *CanonicalVD = VD->getCanonicalDecl(); NamedDecl *ND = cast
(CanonicalVD); // OpenMP [2.9.2, Restrictions, C/C++, p.2] // A threadprivate directive for file-scope variables must appear outside // any definition or declaration. if (CanonicalVD->getDeclContext()->isTranslationUnit() && !getCurLexicalContext()->isTranslationUnit()) { Diag(Id.getLoc(), diag::err_omp_var_scope) << getOpenMPDirectiveName(OMPD_threadprivate) << VD; bool IsDecl = VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly; Diag(VD->getLocation(), IsDecl ? diag::note_previous_decl : diag::note_defined_here) << VD; return ExprError(); } // OpenMP [2.9.2, Restrictions, C/C++, p.3] // A threadprivate directive for static class member variables must appear // in the class definition, in the same scope in which the member // variables are declared. if (CanonicalVD->isStaticDataMember() && !CanonicalVD->getDeclContext()->Equals(getCurLexicalContext())) { Diag(Id.getLoc(), diag::err_omp_var_scope) << getOpenMPDirectiveName(OMPD_threadprivate) << VD; bool IsDecl = VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly; Diag(VD->getLocation(), IsDecl ? diag::note_previous_decl : diag::note_defined_here) << VD; return ExprError(); } // OpenMP [2.9.2, Restrictions, C/C++, p.4] // A threadprivate directive for namespace-scope variables must appear // outside any definition or declaration other than the namespace // definition itself. if (CanonicalVD->getDeclContext()->isNamespace() && (!getCurLexicalContext()->isFileContext() || !getCurLexicalContext()->Encloses(CanonicalVD->getDeclContext()))) { Diag(Id.getLoc(), diag::err_omp_var_scope) << getOpenMPDirectiveName(OMPD_threadprivate) << VD; bool IsDecl = VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly; Diag(VD->getLocation(), IsDecl ? diag::note_previous_decl : diag::note_defined_here) << VD; return ExprError(); } // OpenMP [2.9.2, Restrictions, C/C++, p.6] // A threadprivate directive for static block-scope variables must appear // in the scope of the variable and not in a nested scope. if (CanonicalVD->isStaticLocal() && CurScope && !isDeclInScope(ND, getCurLexicalContext(), CurScope)) { Diag(Id.getLoc(), diag::err_omp_var_scope) << getOpenMPDirectiveName(OMPD_threadprivate) << VD; bool IsDecl = VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly; Diag(VD->getLocation(), IsDecl ? diag::note_previous_decl : diag::note_defined_here) << VD; return ExprError(); } // OpenMP [2.9.2, Restrictions, C/C++, p.2-6] // A threadprivate directive must lexically precede all references to any // of the variables in its list. if (VD->isUsed() && !DSAStack->isThreadPrivate(VD)) { Diag(Id.getLoc(), diag::err_omp_var_used) << getOpenMPDirectiveName(OMPD_threadprivate) << VD; return ExprError(); } QualType ExprType = VD->getType().getNonReferenceType(); return DeclRefExpr::Create(Context, NestedNameSpecifierLoc(), SourceLocation(), VD, /*RefersToEnclosingVariableOrCapture=*/false, Id.getLoc(), ExprType, VK_LValue); } Sema::DeclGroupPtrTy Sema::ActOnOpenMPThreadprivateDirective(SourceLocation Loc, ArrayRef
VarList) { if (OMPThreadPrivateDecl *D = CheckOMPThreadPrivateDecl(Loc, VarList)) { CurContext->addDecl(D); return DeclGroupPtrTy::make(DeclGroupRef(D)); } return nullptr; } namespace { class LocalVarRefChecker : public ConstStmtVisitor
{ Sema &SemaRef; public: bool VisitDeclRefExpr(const DeclRefExpr *E) { if (auto VD = dyn_cast
(E->getDecl())) { if (VD->hasLocalStorage()) { SemaRef.Diag(E->getLocStart(), diag::err_omp_local_var_in_threadprivate_init) << E->getSourceRange(); SemaRef.Diag(VD->getLocation(), diag::note_defined_here) << VD << VD->getSourceRange(); return true; } } return false; } bool VisitStmt(const Stmt *S) { for (auto Child : S->children()) { if (Child && Visit(Child)) return true; } return false; } explicit LocalVarRefChecker(Sema &SemaRef) : SemaRef(SemaRef) {} }; } // namespace OMPThreadPrivateDecl * Sema::CheckOMPThreadPrivateDecl(SourceLocation Loc, ArrayRef
VarList) { SmallVector
Vars; for (auto &RefExpr : VarList) { DeclRefExpr *DE = cast
(RefExpr); VarDecl *VD = cast
(DE->getDecl()); SourceLocation ILoc = DE->getExprLoc(); // Mark variable as used. VD->setReferenced(); VD->markUsed(Context); QualType QType = VD->getType(); if (QType->isDependentType() || QType->isInstantiationDependentType()) { // It will be analyzed later. Vars.push_back(DE); continue; } // OpenMP [2.9.2, Restrictions, C/C++, p.10] // A threadprivate variable must not have an incomplete type. if (RequireCompleteType(ILoc, VD->getType(), diag::err_omp_threadprivate_incomplete_type)) { continue; } // OpenMP [2.9.2, Restrictions, C/C++, p.10] // A threadprivate variable must not have a reference type. if (VD->getType()->isReferenceType()) { Diag(ILoc, diag::err_omp_ref_type_arg) << getOpenMPDirectiveName(OMPD_threadprivate) << VD->getType(); bool IsDecl = VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly; Diag(VD->getLocation(), IsDecl ? diag::note_previous_decl : diag::note_defined_here) << VD; continue; } // Check if this is a TLS variable. If TLS is not being supported, produce // the corresponding diagnostic. if ((VD->getTLSKind() != VarDecl::TLS_None && !(VD->hasAttr
() && getLangOpts().OpenMPUseTLS && getASTContext().getTargetInfo().isTLSSupported())) || (VD->getStorageClass() == SC_Register && VD->hasAttr
() && !VD->isLocalVarDecl())) { Diag(ILoc, diag::err_omp_var_thread_local) << VD << ((VD->getTLSKind() != VarDecl::TLS_None) ? 0 : 1); bool IsDecl = VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly; Diag(VD->getLocation(), IsDecl ? diag::note_previous_decl : diag::note_defined_here) << VD; continue; } // Check if initial value of threadprivate variable reference variable with // local storage (it is not supported by runtime). if (auto Init = VD->getAnyInitializer()) { LocalVarRefChecker Checker(*this); if (Checker.Visit(Init)) continue; } Vars.push_back(RefExpr); DSAStack->addDSA(VD, DE, OMPC_threadprivate); VD->addAttr(OMPThreadPrivateDeclAttr::CreateImplicit( Context, SourceRange(Loc, Loc))); if (auto *ML = Context.getASTMutationListener()) ML->DeclarationMarkedOpenMPThreadPrivate(VD); } OMPThreadPrivateDecl *D = nullptr; if (!Vars.empty()) { D = OMPThreadPrivateDecl::Create(Context, getCurLexicalContext(), Loc, Vars); D->setAccess(AS_public); } return D; } static void ReportOriginalDSA(Sema &SemaRef, DSAStackTy *Stack, const ValueDecl *D, DSAStackTy::DSAVarData DVar, bool IsLoopIterVar = false) { if (DVar.RefExpr) { SemaRef.Diag(DVar.RefExpr->getExprLoc(), diag::note_omp_explicit_dsa) << getOpenMPClauseName(DVar.CKind); return; } enum { PDSA_StaticMemberShared, PDSA_StaticLocalVarShared, PDSA_LoopIterVarPrivate, PDSA_LoopIterVarLinear, PDSA_LoopIterVarLastprivate, PDSA_ConstVarShared, PDSA_GlobalVarShared, PDSA_TaskVarFirstprivate, PDSA_LocalVarPrivate, PDSA_Implicit } Reason = PDSA_Implicit; bool ReportHint = false; auto ReportLoc = D->getLocation(); auto *VD = dyn_cast
(D); if (IsLoopIterVar) { if (DVar.CKind == OMPC_private) Reason = PDSA_LoopIterVarPrivate; else if (DVar.CKind == OMPC_lastprivate) Reason = PDSA_LoopIterVarLastprivate; else Reason = PDSA_LoopIterVarLinear; } else if (isOpenMPTaskingDirective(DVar.DKind) && DVar.CKind == OMPC_firstprivate) { Reason = PDSA_TaskVarFirstprivate; ReportLoc = DVar.ImplicitDSALoc; } else if (VD && VD->isStaticLocal()) Reason = PDSA_StaticLocalVarShared; else if (VD && VD->isStaticDataMember()) Reason = PDSA_StaticMemberShared; else if (VD && VD->isFileVarDecl()) Reason = PDSA_GlobalVarShared; else if (D->getType().isConstant(SemaRef.getASTContext())) Reason = PDSA_ConstVarShared; else if (VD && VD->isLocalVarDecl() && DVar.CKind == OMPC_private) { ReportHint = true; Reason = PDSA_LocalVarPrivate; } if (Reason != PDSA_Implicit) { SemaRef.Diag(ReportLoc, diag::note_omp_predetermined_dsa) << Reason << ReportHint << getOpenMPDirectiveName(Stack->getCurrentDirective()); } else if (DVar.ImplicitDSALoc.isValid()) { SemaRef.Diag(DVar.ImplicitDSALoc, diag::note_omp_implicit_dsa) << getOpenMPClauseName(DVar.CKind); } } namespace { class DSAAttrChecker : public StmtVisitor
{ DSAStackTy *Stack; Sema &SemaRef; bool ErrorFound; CapturedStmt *CS; llvm::SmallVector
ImplicitFirstprivate; llvm::DenseMap
VarsWithInheritedDSA; public: void VisitDeclRefExpr(DeclRefExpr *E) { if (E->isTypeDependent() || E->isValueDependent() || E->containsUnexpandedParameterPack() || E->isInstantiationDependent()) return; if (auto *VD = dyn_cast
(E->getDecl())) { // Skip internally declared variables. if (VD->isLocalVarDecl() && !CS->capturesVariable(VD)) return; auto DVar = Stack->getTopDSA(VD, false); // Check if the variable has explicit DSA set and stop analysis if it so. if (DVar.RefExpr) return; auto ELoc = E->getExprLoc(); auto DKind = Stack->getCurrentDirective(); // The default(none) clause requires that each variable that is referenced // in the construct, and does not have a predetermined data-sharing // attribute, must have its data-sharing attribute explicitly determined // by being listed in a data-sharing attribute clause. if (DVar.CKind == OMPC_unknown && Stack->getDefaultDSA() == DSA_none && isParallelOrTaskRegion(DKind) && VarsWithInheritedDSA.count(VD) == 0) { VarsWithInheritedDSA[VD] = E; return; } // OpenMP [2.9.3.6, Restrictions, p.2] // A list item that appears in a reduction clause of the innermost // enclosing worksharing or parallel construct may not be accessed in an // explicit task. DVar = Stack->hasInnermostDSA( VD, [](OpenMPClauseKind C) -> bool { return C == OMPC_reduction; }, [](OpenMPDirectiveKind K) -> bool { return isOpenMPParallelDirective(K) || isOpenMPWorksharingDirective(K) || isOpenMPTeamsDirective(K); }, false); if (isOpenMPTaskingDirective(DKind) && DVar.CKind == OMPC_reduction) { ErrorFound = true; SemaRef.Diag(ELoc, diag::err_omp_reduction_in_task); ReportOriginalDSA(SemaRef, Stack, VD, DVar); return; } // Define implicit data-sharing attributes for task. DVar = Stack->getImplicitDSA(VD, false); if (isOpenMPTaskingDirective(DKind) && DVar.CKind != OMPC_shared && !Stack->isLoopControlVariable(VD).first) ImplicitFirstprivate.push_back(E); } } void VisitMemberExpr(MemberExpr *E) { if (E->isTypeDependent() || E->isValueDependent() || E->containsUnexpandedParameterPack() || E->isInstantiationDependent()) return; if (isa
(E->getBase()->IgnoreParens())) { if (auto *FD = dyn_cast
(E->getMemberDecl())) { auto DVar = Stack->getTopDSA(FD, false); // Check if the variable has explicit DSA set and stop analysis if it // so. if (DVar.RefExpr) return; auto ELoc = E->getExprLoc(); auto DKind = Stack->getCurrentDirective(); // OpenMP [2.9.3.6, Restrictions, p.2] // A list item that appears in a reduction clause of the innermost // enclosing worksharing or parallel construct may not be accessed in // an explicit task. DVar = Stack->hasInnermostDSA( FD, [](OpenMPClauseKind C) -> bool { return C == OMPC_reduction; }, [](OpenMPDirectiveKind K) -> bool { return isOpenMPParallelDirective(K) || isOpenMPWorksharingDirective(K) || isOpenMPTeamsDirective(K); }, false); if (isOpenMPTaskingDirective(DKind) && DVar.CKind == OMPC_reduction) { ErrorFound = true; SemaRef.Diag(ELoc, diag::err_omp_reduction_in_task); ReportOriginalDSA(SemaRef, Stack, FD, DVar); return; } // Define implicit data-sharing attributes for task. DVar = Stack->getImplicitDSA(FD, false); if (isOpenMPTaskingDirective(DKind) && DVar.CKind != OMPC_shared && !Stack->isLoopControlVariable(FD).first) ImplicitFirstprivate.push_back(E); } } } void VisitOMPExecutableDirective(OMPExecutableDirective *S) { for (auto *C : S->clauses()) { // Skip analysis of arguments of implicitly defined firstprivate clause // for task directives. if (C && (!isa
(C) || C->getLocStart().isValid())) for (auto *CC : C->children()) { if (CC) Visit(CC); } } } void VisitStmt(Stmt *S) { for (auto *C : S->children()) { if (C && !isa
(C)) Visit(C); } } bool isErrorFound() { return ErrorFound; } ArrayRef
getImplicitFirstprivate() { return ImplicitFirstprivate; } llvm::DenseMap
&getVarsWithInheritedDSA() { return VarsWithInheritedDSA; } DSAAttrChecker(DSAStackTy *S, Sema &SemaRef, CapturedStmt *CS) : Stack(S), SemaRef(SemaRef), ErrorFound(false), CS(CS) {} }; } // namespace void Sema::ActOnOpenMPRegionStart(OpenMPDirectiveKind DKind, Scope *CurScope) { switch (DKind) { case OMPD_parallel: case OMPD_parallel_for: case OMPD_parallel_for_simd: case OMPD_parallel_sections: case OMPD_teams: { QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1); QualType KmpInt32PtrTy = Context.getPointerType(KmpInt32Ty).withConst().withRestrict(); Sema::CapturedParamNameType Params[] = { std::make_pair(".global_tid.", KmpInt32PtrTy), std::make_pair(".bound_tid.", KmpInt32PtrTy), std::make_pair(StringRef(), QualType()) // __context with shared vars }; ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP, Params); break; } case OMPD_simd: case OMPD_for: case OMPD_for_simd: case OMPD_sections: case OMPD_section: case OMPD_single: case OMPD_master: case OMPD_critical: case OMPD_taskgroup: case OMPD_distribute: case OMPD_ordered: case OMPD_atomic: case OMPD_target_data: case OMPD_target: case OMPD_target_parallel: case OMPD_target_parallel_for: case OMPD_target_parallel_for_simd: { Sema::CapturedParamNameType Params[] = { std::make_pair(StringRef(), QualType()) // __context with shared vars }; ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP, Params); break; } case OMPD_task: { QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1); QualType Args[] = {Context.VoidPtrTy.withConst().withRestrict()}; FunctionProtoType::ExtProtoInfo EPI; EPI.Variadic = true; QualType CopyFnType = Context.getFunctionType(Context.VoidTy, Args, EPI); Sema::CapturedParamNameType Params[] = { std::make_pair(".global_tid.", KmpInt32Ty), std::make_pair(".part_id.", Context.getPointerType(KmpInt32Ty)), std::make_pair(".privates.", Context.VoidPtrTy.withConst()), std::make_pair(".copy_fn.", Context.getPointerType(CopyFnType).withConst()), std::make_pair(".task_t.", Context.VoidPtrTy.withConst()), std::make_pair(StringRef(), QualType()) // __context with shared vars }; ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP, Params); // Mark this captured region as inlined, because we don't use outlined // function directly. getCurCapturedRegion()->TheCapturedDecl->addAttr( AlwaysInlineAttr::CreateImplicit( Context, AlwaysInlineAttr::Keyword_forceinline, SourceRange())); break; } case OMPD_taskloop: case OMPD_taskloop_simd: { QualType KmpInt32Ty = Context.getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/1); QualType KmpUInt64Ty = Context.getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/0); QualType KmpInt64Ty = Context.getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/1); QualType Args[] = {Context.VoidPtrTy.withConst().withRestrict()}; FunctionProtoType::ExtProtoInfo EPI; EPI.Variadic = true; QualType CopyFnType = Context.getFunctionType(Context.VoidTy, Args, EPI); Sema::CapturedParamNameType Params[] = { std::make_pair(".global_tid.", KmpInt32Ty), std::make_pair(".part_id.", Context.getPointerType(KmpInt32Ty)), std::make_pair(".privates.", Context.VoidPtrTy.withConst().withRestrict()), std::make_pair( ".copy_fn.", Context.getPointerType(CopyFnType).withConst().withRestrict()), std::make_pair(".task_t.", Context.VoidPtrTy.withConst()), std::make_pair(".lb.", KmpUInt64Ty), std::make_pair(".ub.", KmpUInt64Ty), std::make_pair(".st.", KmpInt64Ty), std::make_pair(".liter.", KmpInt32Ty), std::make_pair(StringRef(), QualType()) // __context with shared vars }; ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP, Params); // Mark this captured region as inlined, because we don't use outlined // function directly. getCurCapturedRegion()->TheCapturedDecl->addAttr( AlwaysInlineAttr::CreateImplicit( Context, AlwaysInlineAttr::Keyword_forceinline, SourceRange())); break; } case OMPD_distribute_parallel_for_simd: case OMPD_distribute_simd: case OMPD_distribute_parallel_for: { QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1); QualType KmpInt32PtrTy = Context.getPointerType(KmpInt32Ty).withConst().withRestrict(); Sema::CapturedParamNameType Params[] = { std::make_pair(".global_tid.", KmpInt32PtrTy), std::make_pair(".bound_tid.", KmpInt32PtrTy), std::make_pair(".previous.lb.", Context.getSizeType()), std::make_pair(".previous.ub.", Context.getSizeType()), std::make_pair(StringRef(), QualType()) // __context with shared vars }; ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP, Params); break; } case OMPD_threadprivate: case OMPD_taskyield: case OMPD_barrier: case OMPD_taskwait: case OMPD_cancellation_point: case OMPD_cancel: case OMPD_flush: case OMPD_target_enter_data: case OMPD_target_exit_data: case OMPD_declare_reduction: case OMPD_declare_simd: case OMPD_declare_target: case OMPD_end_declare_target: case OMPD_target_update: llvm_unreachable("OpenMP Directive is not allowed"); case OMPD_unknown: llvm_unreachable("Unknown OpenMP directive"); } } static OMPCapturedExprDecl *buildCaptureDecl(Sema &S, IdentifierInfo *Id, Expr *CaptureExpr, bool WithInit, bool AsExpression) { assert(CaptureExpr); ASTContext &C = S.getASTContext(); Expr *Init = AsExpression ? CaptureExpr : CaptureExpr->IgnoreImpCasts(); QualType Ty = Init->getType(); if (CaptureExpr->getObjectKind() == OK_Ordinary && CaptureExpr->isGLValue()) { if (S.getLangOpts().CPlusPlus) Ty = C.getLValueReferenceType(Ty); else { Ty = C.getPointerType(Ty); ExprResult Res = S.CreateBuiltinUnaryOp(CaptureExpr->getExprLoc(), UO_AddrOf, Init); if (!Res.isUsable()) return nullptr; Init = Res.get(); } WithInit = true; } auto *CED = OMPCapturedExprDecl::Create(C, S.CurContext, Id, Ty); if (!WithInit) CED->addAttr(OMPCaptureNoInitAttr::CreateImplicit(C, SourceRange())); S.CurContext->addHiddenDecl(CED); S.AddInitializerToDecl(CED, Init, /*DirectInit=*/false, /*TypeMayContainAuto=*/true); return CED; } static DeclRefExpr *buildCapture(Sema &S, ValueDecl *D, Expr *CaptureExpr, bool WithInit) { OMPCapturedExprDecl *CD; if (auto *VD = S.IsOpenMPCapturedDecl(D)) CD = cast
(VD); else CD = buildCaptureDecl(S, D->getIdentifier(), CaptureExpr, WithInit, /*AsExpression=*/false); return buildDeclRefExpr(S, CD, CD->getType().getNonReferenceType(), CaptureExpr->getExprLoc()); } static ExprResult buildCapture(Sema &S, Expr *CaptureExpr, DeclRefExpr *&Ref) { if (!Ref) { auto *CD = buildCaptureDecl(S, &S.getASTContext().Idents.get(".capture_expr."), CaptureExpr, /*WithInit=*/true, /*AsExpression=*/true); Ref = buildDeclRefExpr(S, CD, CD->getType().getNonReferenceType(), CaptureExpr->getExprLoc()); } ExprResult Res = Ref; if (!S.getLangOpts().CPlusPlus && CaptureExpr->getObjectKind() == OK_Ordinary && CaptureExpr->isGLValue() && Ref->getType()->isPointerType()) Res = S.CreateBuiltinUnaryOp(CaptureExpr->getExprLoc(), UO_Deref, Ref); if (!Res.isUsable()) return ExprError(); return CaptureExpr->isGLValue() ? Res : S.DefaultLvalueConversion(Res.get()); } StmtResult Sema::ActOnOpenMPRegionEnd(StmtResult S, ArrayRef
Clauses) { if (!S.isUsable()) { ActOnCapturedRegionError(); return StmtError(); } OMPOrderedClause *OC = nullptr; OMPScheduleClause *SC = nullptr; SmallVector
LCs; // This is required for proper codegen. for (auto *Clause : Clauses) { if (isOpenMPPrivate(Clause->getClauseKind()) || Clause->getClauseKind() == OMPC_copyprivate || (getLangOpts().OpenMPUseTLS && getASTContext().getTargetInfo().isTLSSupported() && Clause->getClauseKind() == OMPC_copyin)) { DSAStack->setForceVarCapturing(Clause->getClauseKind() == OMPC_copyin); // Mark all variables in private list clauses as used in inner region. for (auto *VarRef : Clause->children()) { if (auto *E = cast_or_null
(VarRef)) { MarkDeclarationsReferencedInExpr(E); } } DSAStack->setForceVarCapturing(/*V=*/false); } else if (isParallelOrTaskRegion(DSAStack->getCurrentDirective())) { // Mark all variables in private list clauses as used in inner region. // Required for proper codegen of combined directives. // TODO: add processing for other clauses. if (auto *C = OMPClauseWithPreInit::get(Clause)) { if (auto *DS = cast_or_null
(C->getPreInitStmt())) { for (auto *D : DS->decls()) MarkVariableReferenced(D->getLocation(), cast
(D)); } } if (auto *C = OMPClauseWithPostUpdate::get(Clause)) { if (auto *E = C->getPostUpdateExpr()) MarkDeclarationsReferencedInExpr(E); } } if (Clause->getClauseKind() == OMPC_schedule) SC = cast
(Clause); else if (Clause->getClauseKind() == OMPC_ordered) OC = cast
(Clause); else if (Clause->getClauseKind() == OMPC_linear) LCs.push_back(cast
(Clause)); } bool ErrorFound = false; // OpenMP, 2.7.1 Loop Construct, Restrictions // The nonmonotonic modifier cannot be specified if an ordered clause is // specified. if (SC && (SC->getFirstScheduleModifier() == OMPC_SCHEDULE_MODIFIER_nonmonotonic || SC->getSecondScheduleModifier() == OMPC_SCHEDULE_MODIFIER_nonmonotonic) && OC) { Diag(SC->getFirstScheduleModifier() == OMPC_SCHEDULE_MODIFIER_nonmonotonic ? SC->getFirstScheduleModifierLoc() : SC->getSecondScheduleModifierLoc(), diag::err_omp_schedule_nonmonotonic_ordered) << SourceRange(OC->getLocStart(), OC->getLocEnd()); ErrorFound = true; } if (!LCs.empty() && OC && OC->getNumForLoops()) { for (auto *C : LCs) { Diag(C->getLocStart(), diag::err_omp_linear_ordered) << SourceRange(OC->getLocStart(), OC->getLocEnd()); } ErrorFound = true; } if (isOpenMPWorksharingDirective(DSAStack->getCurrentDirective()) && isOpenMPSimdDirective(DSAStack->getCurrentDirective()) && OC && OC->getNumForLoops()) { Diag(OC->getLocStart(), diag::err_omp_ordered_simd) << getOpenMPDirectiveName(DSAStack->getCurrentDirective()); ErrorFound = true; } if (ErrorFound) { ActOnCapturedRegionError(); return StmtError(); } return ActOnCapturedRegionEnd(S.get()); } static bool CheckNestingOfRegions(Sema &SemaRef, DSAStackTy *Stack, OpenMPDirectiveKind CurrentRegion, const DeclarationNameInfo &CurrentName, OpenMPDirectiveKind CancelRegion, SourceLocation StartLoc) { // Allowed nesting of constructs // +------------------+-----------------+------------------------------------+ // | Parent directive | Child directive | Closely (!), No-Closely(+), Both(*)| // +------------------+-----------------+------------------------------------+ // | parallel | parallel | * | // | parallel | for | * | // | parallel | for simd | * | // | parallel | master | * | // | parallel | critical | * | // | parallel | simd | * | // | parallel | sections | * | // | parallel | section | + | // | parallel | single | * | // | parallel | parallel for | * | // | parallel |parallel for simd| * | // | parallel |parallel sections| * | // | parallel | task | * | // | parallel | taskyield | * | // | parallel | barrier | * | // | parallel | taskwait | * | // | parallel | taskgroup | * | // | parallel | flush | * | // | parallel | ordered | + | // | parallel | atomic | * | // | parallel | target | * | // | parallel | target parallel | * | // | parallel | target parallel | * | // | | for | | // | parallel | target enter | * | // | | data | | // | parallel | target exit | * | // | | data | | // | parallel | teams | + | // | parallel | cancellation | | // | | point | ! | // | parallel | cancel | ! | // | parallel | taskloop | * | // | parallel | taskloop simd | * | // | parallel | distribute | + | // | parallel | distribute | + | // | | parallel for | | // | parallel | distribute | + | // | |parallel for simd| | // | parallel | distribute simd | + | // +------------------+-----------------+------------------------------------+ // | for | parallel | * | // | for | for | + | // | for | for simd | + | // | for | master | + | // | for | critical | * | // | for | simd | * | // | for | sections | + | // | for | section | + | // | for | single | + | // | for | parallel for | * | // | for |parallel for simd| * | // | for |parallel sections| * | // | for | task | * | // | for | taskyield | * | // | for | barrier | + | // | for | taskwait | * | // | for | taskgroup | * | // | for | flush | * | // | for | ordered | * (if construct is ordered) | // | for | atomic | * | // | for | target | * | // | for | target parallel | * | // | for | target parallel | * | // | | for | | // | for | target enter | * | // | | data | | // | for | target exit | * | // | | data | | // | for | teams | + | // | for | cancellation | | // | | point | ! | // | for | cancel | ! | // | for | taskloop | * | // | for | taskloop simd | * | // | for | distribute | + | // | for | distribute | + | // | | parallel for | | // | for | distribute | + | // | |parallel for simd| | // | for | distribute simd | + | // | for | target parallel | + | // | | for simd | | // +------------------+-----------------+------------------------------------+ // | master | parallel | * | // | master | for | + | // | master | for simd | + | // | master | master | * | // | master | critical | * | // | master | simd | * | // | master | sections | + | // | master | section | + | // | master | single | + | // | master | parallel for | * | // | master |parallel for simd| * | // | master |parallel sections| * | // | master | task | * | // | master | taskyield | * | // | master | barrier | + | // | master | taskwait | * | // | master | taskgroup | * | // | master | flush | * | // | master | ordered | + | // | master | atomic | * | // | master | target | * | // | master | target parallel | * | // | master | target parallel | * | // | | for | | // | master | target enter | * | // | | data | | // | master | target exit | * | // | | data | | // | master | teams | + | // | master | cancellation | | // | | point | | // | master | cancel | | // | master | taskloop | * | // | master | taskloop simd | * | // | master | distribute | + | // | master | distribute | + | // | | parallel for | | // | master | distribute | + | // | |parallel for simd| | // | master | distribute simd | + | // | master | target parallel | + | // | | for simd | | // +------------------+-----------------+------------------------------------+ // | critical | parallel | * | // | critical | for | + | // | critical | for simd | + | // | critical | master | * | // | critical | critical | * (should have different names) | // | critical | simd | * | // | critical | sections | + | // | critical | section | + | // | critical | single | + | // | critical | parallel for | * | // | critical |parallel for simd| * | // | critical |parallel sections| * | // | critical | task | * | // | critical | taskyield | * | // | critical | barrier | + | // | critical | taskwait | * | // | critical | taskgroup | * | // | critical | ordered | + | // | critical | atomic | * | // | critical | target | * | // | critical | target parallel | * | // | critical | target parallel | * | // | | for | | // | critical | target enter | * | // | | data | | // | critical | target exit | * | // | | data | | // | critical | teams | + | // | critical | cancellation | | // | | point | | // | critical | cancel | | // | critical | taskloop | * | // | critical | taskloop simd | * | // | critical | distribute | + | // | critical | distribute | + | // | | parallel for | | // | critical | distribute | + | // | |parallel for simd| | // | critical | distribute simd | + | // | critical | target parallel | + | // | | for simd | | // +------------------+-----------------+------------------------------------+ // | simd | parallel | | // | simd | for | | // | simd | for simd | | // | simd | master | | // | simd | critical | | // | simd | simd | * | // | simd | sections | | // | simd | section | | // | simd | single | | // | simd | parallel for | | // | simd |parallel for simd| | // | simd |parallel sections| | // | simd | task | | // | simd | taskyield | | // | simd | barrier | | // | simd | taskwait | | // | simd | taskgroup | | // | simd | flush | | // | simd | ordered | + (with simd clause) | // | simd | atomic | | // | simd | target | | // | simd | target parallel | | // | simd | target parallel | | // | | for | | // | simd | target enter | | // | | data | | // | simd | target exit | | // | | data | | // | simd | teams | | // | simd | cancellation | | // | | point | | // | simd | cancel | | // | simd | taskloop | | // | simd | taskloop simd | | // | simd | distribute | | // | simd | distribute | | // | | parallel for | | // | simd | distribute | | // | |parallel for simd| | // | simd | distribute simd | | // | simd | target parallel | | // | | for simd | | // +------------------+-----------------+------------------------------------+ // | for simd | parallel | | // | for simd | for | | // | for simd | for simd | | // | for simd | master | | // | for simd | critical | | // | for simd | simd | * | // | for simd | sections | | // | for simd | section | | // | for simd | single | | // | for simd | parallel for | | // | for simd |parallel for simd| | // | for simd |parallel sections| | // | for simd | task | | // | for simd | taskyield | | // | for simd | barrier | | // | for simd | taskwait | | // | for simd | taskgroup | | // | for simd | flush | | // | for simd | ordered | + (with simd clause) | // | for simd | atomic | | // | for simd | target | | // | for simd | target parallel | | // | for simd | target parallel | | // | | for | | // | for simd | target enter | | // | | data | | // | for simd | target exit | | // | | data | | // | for simd | teams | | // | for simd | cancellation | | // | | point | | // | for simd | cancel | | // | for simd | taskloop | | // | for simd | taskloop simd | | // | for simd | distribute | | // | for simd | distribute | | // | | parallel for | | // | for simd | distribute | | // | |parallel for simd| | // | for simd | distribute simd | | // | for simd | target parallel | | // | | for simd | | // +------------------+-----------------+------------------------------------+ // | parallel for simd| parallel | | // | parallel for simd| for | | // | parallel for simd| for simd | | // | parallel for simd| master | | // | parallel for simd| critical | | // | parallel for simd| simd | * | // | parallel for simd| sections | | // | parallel for simd| section | | // | parallel for simd| single | | // | parallel for simd| parallel for | | // | parallel for simd|parallel for simd| | // | parallel for simd|parallel sections| | // | parallel for simd| task | | // | parallel for simd| taskyield | | // | parallel for simd| barrier | | // | parallel for simd| taskwait | | // | parallel for simd| taskgroup | | // | parallel for simd| flush | | // | parallel for simd| ordered | + (with simd clause) | // | parallel for simd| atomic | | // | parallel for simd| target | | // | parallel for simd| target parallel | | // | parallel for simd| target parallel | | // | | for | | // | parallel for simd| target enter | | // | | data | | // | parallel for simd| target exit | | // | | data | | // | parallel for simd| teams | | // | parallel for simd| cancellation | | // | | point | | // | parallel for simd| cancel | | // | parallel for simd| taskloop | | // | parallel for simd| taskloop simd | | // | parallel for simd| distribute | | // | parallel for simd| distribute | | // | | parallel for | | // | parallel for simd| distribute | | // | |parallel for simd| | // | parallel for simd| distribute simd | | // | | for simd | | // +------------------+-----------------+------------------------------------+ // | sections | parallel | * | // | sections | for | + | // | sections | for simd | + | // | sections | master | + | // | sections | critical | * | // | sections | simd | * | // | sections | sections | + | // | sections | section | * | // | sections | single | + | // | sections | parallel for | * | // | sections |parallel for simd| * | // | sections |parallel sections| * | // | sections | task | * | // | sections | taskyield | * | // | sections | barrier | + | // | sections | taskwait | * | // | sections | taskgroup | * | // | sections | flush | * | // | sections | ordered | + | // | sections | atomic | * | // | sections | target | * | // | sections | target parallel | * | // | sections | target parallel | * | // | | for | | // | sections | target enter | * | // | | data | | // | sections | target exit | * | // | | data | | // | sections | teams | + | // | sections | cancellation | | // | | point | ! | // | sections | cancel | ! | // | sections | taskloop | * | // | sections | taskloop simd | * | // | sections | distribute | + | // | sections | distribute | + | // | | parallel for | | // | sections | distribute | + | // | |parallel for simd| | // | sections | distribute simd | + | // | sections | target parallel | + | // | | for simd | | // +------------------+-----------------+------------------------------------+ // | section | parallel | * | // | section | for | + | // | section | for simd | + | // | section | master | + | // | section | critical | * | // | section | simd | * | // | section | sections | + | // | section | section | + | // | section | single | + | // | section | parallel for | * | // | section |parallel for simd| * | // | section |parallel sections| * | // | section | task | * | // | section | taskyield | * | // | section | barrier | + | // | section | taskwait | * | // | section | taskgroup | * | // | section | flush | * | // | section | ordered | + | // | section | atomic | * | // | section | target | * | // | section | target parallel | * | // | section | target parallel | * | // | | for | | // | section | target enter | * | // | | data | | // | section | target exit | * | // | | data | | // | section | teams | + | // | section | cancellation | | // | | point | ! | // | section | cancel | ! | // | section | taskloop | * | // | section | taskloop simd | * | // | section | distribute | + | // | section | distribute | + | // | | parallel for | | // | section | distribute | + | // | |parallel for simd| | // | section | distribute simd | + | // | section | target parallel | + | // | | for simd | | // +------------------+-----------------+------------------------------------+ // | single | parallel | * | // | single | for | + | // | single | for simd | + | // | single | master | + | // | single | critical | * | // | single | simd | * | // | single | sections | + | // | single | section | + | // | single | single | + | // | single | parallel for | * | // | single |parallel for simd| * | // | single |parallel sections| * | // | single | task | * | // | single | taskyield | * | // | single | barrier | + | // | single | taskwait | * | // | single | taskgroup | * | // | single | flush | * | // | single | ordered | + | // | single | atomic | * | // | single | target | * | // | single | target parallel | * | // | single | target parallel | * | // | | for | | // | single | target enter | * | // | | data | | // | single | target exit | * | // | | data | | // | single | teams | + | // | single | cancellation | | // | | point | | // | single | cancel | | // | single | taskloop | * | // | single | taskloop simd | * | // | single | distribute | + | // | single | distribute | + | // | | parallel for | | // | single | distribute | + | // | |parallel for simd| | // | single | distribute simd | + | // | single | target parallel | + | // | | for simd | | // +------------------+-----------------+------------------------------------+ // | parallel for | parallel | * | // | parallel for | for | + | // | parallel for | for simd | + | // | parallel for | master | + | // | parallel for | critical | * | // | parallel for | simd | * | // | parallel for | sections | + | // | parallel for | section | + | // | parallel for | single | + | // | parallel for | parallel for | * | // | parallel for |parallel for simd| * | // | parallel for |parallel sections| * | // | parallel for | task | * | // | parallel for | taskyield | * | // | parallel for | barrier | + | // | parallel for | taskwait | * | // | parallel for | taskgroup | * | // | parallel for | flush | * | // | parallel for | ordered | * (if construct is ordered) | // | parallel for | atomic | * | // | parallel for | target | * | // | parallel for | target parallel | * | // | parallel for | target parallel | * | // | | for | | // | parallel for | target enter | * | // | | data | | // | parallel for | target exit | * | // | | data | | // | parallel for | teams | + | // | parallel for | cancellation | | // | | point | ! | // | parallel for | cancel | ! | // | parallel for | taskloop | * | // | parallel for | taskloop simd | * | // | parallel for | distribute | + | // | parallel for | distribute | + | // | | parallel for | | // | parallel for | distribute | + | // | |parallel for simd| | // | parallel for | distribute simd | + | // | parallel for | target parallel | + | // | | for simd | | // +------------------+-----------------+------------------------------------+ // | parallel sections| parallel | * | // | parallel sections| for | + | // | parallel sections| for simd | + | // | parallel sections| master | + | // | parallel sections| critical | + | // | parallel sections| simd | * | // | parallel sections| sections | + | // | parallel sections| section | * | // | parallel sections| single | + | // | parallel sections| parallel for | * | // | parallel sections|parallel for simd| * | // | parallel sections|parallel sections| * | // | parallel sections| task | * | // | parallel sections| taskyield | * | // | parallel sections| barrier | + | // | parallel sections| taskwait | * | // | parallel sections| taskgroup | * | // | parallel sections| flush | * | // | parallel sections| ordered | + | // | parallel sections| atomic | * | // | parallel sections| target | * | // | parallel sections| target parallel | * | // | parallel sections| target parallel | * | // | | for | | // | parallel sections| target enter | * | // | | data | | // | parallel sections| target exit | * | // | | data | | // | parallel sections| teams | + | // | parallel sections| cancellation | | // | | point | ! | // | parallel sections| cancel | ! | // | parallel sections| taskloop | * | // | parallel sections| taskloop simd | * | // | parallel sections| distribute | + | // | parallel sections| distribute | + | // | | parallel for | | // | parallel sections| distribute | + | // | |parallel for simd| | // | parallel sections| distribute simd | + | // | parallel sections| target parallel | + | // | | for simd | | // +------------------+-----------------+------------------------------------+ // | task | parallel | * | // | task | for | + | // | task | for simd | + | // | task | master | + | // | task | critical | * | // | task | simd | * | // | task | sections | + | // | task | section | + | // | task | single | + | // | task | parallel for | * | // | task |parallel for simd| * | // | task |parallel sections| * | // | task | task | * | // | task | taskyield | * | // | task | barrier | + | // | task | taskwait | * | // | task | taskgroup | * | // | task | flush | * | // | task | ordered | + | // | task | atomic | * | // | task | target | * | // | task | target parallel | * | // | task | target parallel | * | // | | for | | // | task | target enter | * | // | | data | | // | task | target exit | * | // | | data | | // | task | teams | + | // | task | cancellation | | // | | point | ! | // | task | cancel | ! | // | task | taskloop | * | // | task | taskloop simd | * | // | task | distribute | + | // | task | distribute | + | // | | parallel for | | // | task | distribute | + | // | |parallel for simd| | // | task | distribute simd | + | // | task | target parallel | + | // | | for simd | | // +------------------+-----------------+------------------------------------+ // | ordered | parallel | * | // | ordered | for | + | // | ordered | for simd | + | // | ordered | master | * | // | ordered | critical | * | // | ordered | simd | * | // | ordered | sections | + | // | ordered | section | + | // | ordered | single | + | // | ordered | parallel for | * | // | ordered |parallel for simd| * | // | ordered |parallel sections| * | // | ordered | task | * | // | ordered | taskyield | * | // | ordered | barrier | + | // | ordered | taskwait | * | // | ordered | taskgroup | * | // | ordered | flush | * | // | ordered | ordered | + | // | ordered | atomic | * | // | ordered | target | * | // | ordered | target parallel | * | // | ordered | target parallel | * | // | | for | | // | ordered | target enter | * | // | | data | | // | ordered | target exit | * | // | | data | | // | ordered | teams | + | // | ordered | cancellation | | // | | point | | // | ordered | cancel | | // | ordered | taskloop | * | // | ordered | taskloop simd | * | // | ordered | distribute | + | // | ordered | distribute | + | // | | parallel for | | // | ordered | distribute | + | // | |parallel for simd| | // | ordered | distribute simd | + | // | ordered | target parallel | + | // | | for simd | | // +------------------+-----------------+------------------------------------+ // | atomic | parallel | | // | atomic | for | | // | atomic | for simd | | // | atomic | master | | // | atomic | critical | | // | atomic | simd | | // | atomic | sections | | // | atomic | section | | // | atomic | single | | // | atomic | parallel for | | // | atomic |parallel for simd| | // | atomic |parallel sections| | // | atomic | task | | // | atomic | taskyield | | // | atomic | barrier | | // | atomic | taskwait | | // | atomic | taskgroup | | // | atomic | flush | | // | atomic | ordered | | // | atomic | atomic | | // | atomic | target | | // | atomic | target parallel | | // | atomic | target parallel | | // | | for | | // | atomic | target enter | | // | | data | | // | atomic | target exit | | // | | data | | // | atomic | teams | | // | atomic | cancellation | | // | | point | | // | atomic | cancel | | // | atomic | taskloop | | // | atomic | taskloop simd | | // | atomic | distribute | | // | atomic | distribute | | // | | parallel for | | // | atomic | distribute | | // | |parallel for simd| | // | atomic | distribute simd | | // | atomic | target parallel | | // | | for simd | | // +------------------+-----------------+------------------------------------+ // | target | parallel | * | // | target | for | * | // | target | for simd | * | // | target | master | * | // | target | critical | * | // | target | simd | * | // | target | sections | * | // | target | section | * | // | target | single | * | // | target | parallel for | * | // | target |parallel for simd| * | // | target |parallel sections| * | // | target | task | * | // | target | taskyield | * | // | target | barrier | * | // | target | taskwait | * | // | target | taskgroup | * | // | target | flush | * | // | target | ordered | * | // | target | atomic | * | // | target | target | | // | target | target parallel | | // | target | target parallel | | // | | for | | // | target | target enter | | // | | data | | // | target | target exit | | // | | data | | // | target | teams | * | // | target | cancellation | | // | | point | | // | target | cancel | | // | target | taskloop | * | // | target | taskloop simd | * | // | target | distribute | + | // | target | distribute | + | // | | parallel for | | // | target | distribute | + | // | |parallel for simd| | // | target | distribute simd | + | // | target | target parallel | | // | | for simd | | // +------------------+-----------------+------------------------------------+ // | target parallel | parallel | * | // | target parallel | for | * | // | target parallel | for simd | * | // | target parallel | master | * | // | target parallel | critical | * | // | target parallel | simd | * | // | target parallel | sections | * | // | target parallel | section | * | // | target parallel | single | * | // | target parallel | parallel for | * | // | target parallel |parallel for simd| * | // | target parallel |parallel sections| * | // | target parallel | task | * | // | target parallel | taskyield | * | // | target parallel | barrier | * | // | target parallel | taskwait | * | // | target parallel | taskgroup | * | // | target parallel | flush | * | // | target parallel | ordered | * | // | target parallel | atomic | * | // | target parallel | target | | // | target parallel | target parallel | | // | target parallel | target parallel | | // | | for | | // | target parallel | target enter | | // | | data | | // | target parallel | target exit | | // | | data | | // | target parallel | teams | | // | target parallel | cancellation | | // | | point | ! | // | target parallel | cancel | ! | // | target parallel | taskloop | * | // | target parallel | taskloop simd | * | // | target parallel | distribute | | // | target parallel | distribute | | // | | parallel for | | // | target parallel | distribute | | // | |parallel for simd| | // | target parallel | distribute simd | | // | target parallel | target parallel | | // | | for simd | | // +------------------+-----------------+------------------------------------+ // | target parallel | parallel | * | // | for | | | // | target parallel | for | * | // | for | | | // | target parallel | for simd | * | // | for | | | // | target parallel | master | * | // | for | | | // | target parallel | critical | * | // | for | | | // | target parallel | simd | * | // | for | | | // | target parallel | sections | * | // | for | | | // | target parallel | section | * | // | for | | | // | target parallel | single | * | // | for | | | // | target parallel | parallel for | * | // | for | | | // | target parallel |parallel for simd| * | // | for | | | // | target parallel |parallel sections| * | // | for | | | // | target parallel | task | * | // | for | | | // | target parallel | taskyield | * | // | for | | | // | target parallel | barrier | * | // | for | | | // | target parallel | taskwait | * | // | for | | | // | target parallel | taskgroup | * | // | for | | | // | target parallel | flush | * | // | for | | | // | target parallel | ordered | * | // | for | | | // | target parallel | atomic | * | // | for | | | // | target parallel | target | | // | for | | | // | target parallel | target parallel | | // | for | | | // | target parallel | target parallel | | // | for | for | | // | target parallel | target enter | | // | for | data | | // | target parallel | target exit | | // | for | data | | // | target parallel | teams | | // | for | | | // | target parallel | cancellation | | // | for | point | ! | // | target parallel | cancel | ! | // | for | | | // | target parallel | taskloop | * | // | for | | | // | target parallel | taskloop simd | * | // | for | | | // | target parallel | distribute | | // | for | | | // | target parallel | distribute | | // | for | parallel for | | // | target parallel | distribute | | // | for |parallel for simd| | // | target parallel | distribute simd | | // | for | | | // | target parallel | target parallel | | // | for | for simd | | // +------------------+-----------------+------------------------------------+ // | teams | parallel | * | // | teams | for | + | // | teams | for simd | + | // | teams | master | + | // | teams | critical | + | // | teams | simd | + | // | teams | sections | + | // | teams | section | + | // | teams | single | + | // | teams | parallel for | * | // | teams |parallel for simd| * | // | teams |parallel sections| * | // | teams | task | + | // | teams | taskyield | + | // | teams | barrier | + | // | teams | taskwait | + | // | teams | taskgroup | + | // | teams | flush | + | // | teams | ordered | + | // | teams | atomic | + | // | teams | target | + | // | teams | target parallel | + | // | teams | target parallel | + | // | | for | | // | teams | target enter | + | // | | data | | // | teams | target exit | + | // | | data | | // | teams | teams | + | // | teams | cancellation | | // | | point | | // | teams | cancel | | // | teams | taskloop | + | // | teams | taskloop simd | + | // | teams | distribute | ! | // | teams | distribute | ! | // | | parallel for | | // | teams | distribute | ! | // | |parallel for simd| | // | teams | distribute simd | ! | // | teams | target parallel | + | // | | for simd | | // +------------------+-----------------+------------------------------------+ // | taskloop | parallel | * | // | taskloop | for | + | // | taskloop | for simd | + | // | taskloop | master | + | // | taskloop | critical | * | // | taskloop | simd | * | // | taskloop | sections | + | // | taskloop | section | + | // | taskloop | single | + | // | taskloop | parallel for | * | // | taskloop |parallel for simd| * | // | taskloop |parallel sections| * | // | taskloop | task | * | // | taskloop | taskyield | * | // | taskloop | barrier | + | // | taskloop | taskwait | * | // | taskloop | taskgroup | * | // | taskloop | flush | * | // | taskloop | ordered | + | // | taskloop | atomic | * | // | taskloop | target | * | // | taskloop | target parallel | * | // | taskloop | target parallel | * | // | | for | | // | taskloop | target enter | * | // | | data | | // | taskloop | target exit | * | // | | data | | // | taskloop | teams | + | // | taskloop | cancellation | | // | | point | | // | taskloop | cancel | | // | taskloop | taskloop | * | // | taskloop | distribute | + | // | taskloop | distribute | + | // | | parallel for | | // | taskloop | distribute | + | // | |parallel for simd| | // | taskloop | distribute simd | + | // | taskloop | target parallel | * | // | | for simd | | // +------------------+-----------------+------------------------------------+ // | taskloop simd | parallel | | // | taskloop simd | for | | // | taskloop simd | for simd | | // | taskloop simd | master | | // | taskloop simd | critical | | // | taskloop simd | simd | * | // | taskloop simd | sections | | // | taskloop simd | section | | // | taskloop simd | single | | // | taskloop simd | parallel for | | // | taskloop simd |parallel for simd| | // | taskloop simd |parallel sections| | // | taskloop simd | task | | // | taskloop simd | taskyield | | // | taskloop simd | barrier | | // | taskloop simd | taskwait | | // | taskloop simd | taskgroup | | // | taskloop simd | flush | | // | taskloop simd | ordered | + (with simd clause) | // | taskloop simd | atomic | | // | taskloop simd | target | | // | taskloop simd | target parallel | | // | taskloop simd | target parallel | | // | | for | | // | taskloop simd | target enter | | // | | data | | // | taskloop simd | target exit | | // | | data | | // | taskloop simd | teams | | // | taskloop simd | cancellation | | // | | point | | // | taskloop simd | cancel | | // | taskloop simd | taskloop | | // | taskloop simd | taskloop simd | | // | taskloop simd | distribute | | // | taskloop simd | distribute | | // | | parallel for | | // | taskloop simd | distribute | | // | |parallel for simd| | // | taskloop simd | distribute simd | | // | taskloop simd | target parallel | | // | | for simd | | // +------------------+-----------------+------------------------------------+ // | distribute | parallel | * | // | distribute | for | * | // | distribute | for simd | * | // | distribute | master | * | // | distribute | critical | * | // | distribute | simd | * | // | distribute | sections | * | // | distribute | section | * | // | distribute | single | * | // | distribute | parallel for | * | // | distribute |parallel for simd| * | // | distribute |parallel sections| * | // | distribute | task | * | // | distribute | taskyield | * | // | distribute | barrier | * | // | distribute | taskwait | * | // | distribute | taskgroup | * | // | distribute | flush | * | // | distribute | ordered | + | // | distribute | atomic | * | // | distribute | target | | // | distribute | target parallel | | // | distribute | target parallel | | // | | for | | // | distribute | target enter | | // | | data | | // | distribute | target exit | | // | | data | | // | distribute | teams | | // | distribute | cancellation | + | // | | point | | // | distribute | cancel | + | // | distribute | taskloop | * | // | distribute | taskloop simd | * | // | distribute | distribute | | // | distribute | distribute | | // | | parallel for | | // | distribute | distribute | | // | |parallel for simd| | // | distribute | distribute simd | | // | distribute | target parallel | | // | | for simd | | // +------------------+-----------------+------------------------------------+ // | distribute | parallel | * | // | parallel for | | | // | distribute | for | * | // | parallel for | | | // | distribute | for simd | * | // | parallel for | | | // | distribute | master | * | // | parallel for | | | // | distribute | critical | * | // | parallel for | | | // | distribute | simd | * | // | parallel for | | | // | distribute | sections | * | // | parallel for | | | // | distribute | section | * | // | parallel for | | | // | distribute | single | * | // | parallel for | | | // | distribute | parallel for | * | // | parallel for | | | // | distribute |parallel for simd| * | // | parallel for | | | // | distribute |parallel sections| * | // | parallel for | | | // | distribute | task | * | // | parallel for | | | // | parallel for | | | // | distribute | taskyield | * | // | parallel for | | | // | distribute | barrier | * | // | parallel for | | | // | distribute | taskwait | * | // | parallel for | | | // | distribute | taskgroup | * | // | parallel for | | | // | distribute | flush | * | // | parallel for | | | // | distribute | ordered | + | // | parallel for | | | // | distribute | atomic | * | // | parallel for | | | // | distribute | target | | // | parallel for | | | // | distribute | target parallel | | // | parallel for | | | // | distribute | target parallel | | // | parallel for | for | | // | distribute | target enter | | // | parallel for | data | | // | distribute | target exit | | // | parallel for | data | | // | distribute | teams | | // | parallel for | | | // | distribute | cancellation | + | // | parallel for | point | | // | distribute | cancel | + | // | parallel for | | | // | distribute | taskloop | * | // | parallel for | | | // | distribute | taskloop simd | * | // | parallel for | | | // | distribute | distribute | | // | parallel for | | | // | distribute | distribute | | // | parallel for | parallel for | | // | distribute | distribute | | // | parallel for |parallel for simd| | // | distribute | distribute simd | | // | parallel for | | | // | distribute | target parallel | | // | parallel for | for simd | | // +------------------+-----------------+------------------------------------+ // | distribute | parallel | * | // | parallel for simd| | | // | distribute | for | * | // | parallel for simd| | | // | distribute | for simd | * | // | parallel for simd| | | // | distribute | master | * | // | parallel for simd| | | // | distribute | critical | * | // | parallel for simd| | | // | distribute | simd | * | // | parallel for simd| | | // | distribute | sections | * | // | parallel for simd| | | // | distribute | section | * | // | parallel for simd| | | // | distribute | single | * | // | parallel for simd| | | // | distribute | parallel for | * | // | parallel for simd| | | // | distribute |parallel for simd| * | // | parallel for simd| | | // | distribute |parallel sections| * | // | parallel for simd| | | // | distribute | task | * | // | parallel for simd| | | // | distribute | taskyield | * | // | parallel for simd| | | // | distribute | barrier | * | // | parallel for simd| | | // | distribute | taskwait | * | // | parallel for simd| | | // | distribute | taskgroup | * | // | parallel for simd| | | // | distribute | flush | * | // | parallel for simd| | | // | distribute | ordered | + | // | parallel for simd| | | // | distribute | atomic | * | // | parallel for simd| | | // | distribute | target | | // | parallel for simd| | | // | distribute | target parallel | | // | parallel for simd| | | // | distribute | target parallel | | // | parallel for simd| for | | // | distribute | target enter | | // | parallel for simd| data | | // | distribute | target exit | | // | parallel for simd| data | | // | distribute | teams | | // | parallel for simd| | | // | distribute | cancellation | + | // | parallel for simd| point | | // | distribute | cancel | + | // | parallel for simd| | | // | distribute | taskloop | * | // | parallel for simd| | | // | distribute | taskloop simd | * | // | parallel for simd| | | // | distribute | distribute | | // | parallel for simd| | | // | distribute | distribute | * | // | parallel for simd| parallel for | | // | distribute | distribute | * | // | parallel for simd|parallel for simd| | // | distribute | distribute simd | * | // | parallel for simd| | | // | distribute | target parallel | | // | parallel for simd| for simd | | // +------------------+-----------------+------------------------------------+ // | distribute simd | parallel | * | // | distribute simd | for | * | // | distribute simd | for simd | * | // | distribute simd | master | * | // | distribute simd | critical | * | // | distribute simd | simd | * | // | distribute simd | sections | * | // | distribute simd | section | * | // | distribute simd | single | * | // | distribute simd | parallel for | * | // | distribute simd |parallel for simd| * | // | distribute simd |parallel sections| * | // | distribute simd | task | * | // | distribute simd | taskyield | * | // | distribute simd | barrier | * | // | distribute simd | taskwait | * | // | distribute simd | taskgroup | * | // | distribute simd | flush | * | // | distribute simd | ordered | + | // | distribute simd | atomic | * | // | distribute simd | target | * | // | distribute simd | target parallel | * | // | distribute simd | target parallel | * | // | | for | | // | distribute simd | target enter | * | // | | data | | // | distribute simd | target exit | * | // | | data | | // | distribute simd | teams | * | // | distribute simd | cancellation | + | // | | point | | // | distribute simd | cancel | + | // | distribute simd | taskloop | * | // | distribute simd | taskloop simd | * | // | distribute simd | distribute | | // | distribute simd | distribute | * | // | | parallel for | | // | distribute simd | distribute | * | // | |parallel for simd| | // | distribute simd | distribute simd | * | // | distribute simd | target parallel | * | // | | for simd | | // +------------------+-----------------+------------------------------------+ // | target parallel | parallel | * | // | for simd | | | // | target parallel | for | * | // | for simd | | | // | target parallel | for simd | * | // | for simd | | | // | target parallel | master | * | // | for simd | | | // | target parallel | critical | * | // | for simd | | | // | target parallel | simd | ! | // | for simd | | | // | target parallel | sections | * | // | for simd | | | // | target parallel | section | * | // | for simd | | | // | target parallel | single | * | // | for simd | | | // | target parallel | parallel for | * | // | for simd | | | // | target parallel |parallel for simd| * | // | for simd | | | // | target parallel |parallel sections| * | // | for simd | | | // | target parallel | task | * | // | for simd | | | // | target parallel | taskyield | * | // | for simd | | | // | target parallel | barrier | * | // | for simd | | | // | target parallel | taskwait | * | // | for simd | | | // | target parallel | taskgroup | * | // | for simd | | | // | target parallel | flush | * | // | for simd | | | // | target parallel | ordered | + (with simd clause) | // | for simd | | | // | target parallel | atomic | * | // | for simd | | | // | target parallel | target | * | // | for simd | | | // | target parallel | target parallel | * | // | for simd | | | // | target parallel | target parallel | * | // | for simd | for | | // | target parallel | target enter | * | // | for simd | data | | // | target parallel | target exit | * | // | for simd | data | | // | target parallel | teams | * | // | for simd | | | // | target parallel | cancellation | * | // | for simd | point | | // | target parallel | cancel | * | // | for simd | | | // | target parallel | taskloop | * | // | for simd | | | // | target parallel | taskloop simd | * | // | for simd | | | // | target parallel | distribute | * | // | for simd | | | // | target parallel | distribute | * | // | for simd | parallel for | | // | target parallel | distribute | * | // | for simd |parallel for simd| | // | target parallel | distribute simd | * | // | for simd | | | // | target parallel | target parallel | * | // | for simd | for simd | | // +------------------+-----------------+------------------------------------+ if (Stack->getCurScope()) { auto ParentRegion = Stack->getParentDirective(); auto OffendingRegion = ParentRegion; bool NestingProhibited = false; bool CloseNesting = true; enum { NoRecommend, ShouldBeInParallelRegion, ShouldBeInOrderedRegion, ShouldBeInTargetRegion, ShouldBeInTeamsRegion } Recommend = NoRecommend; if (isOpenMPSimdDirective(ParentRegion) && CurrentRegion != OMPD_ordered) { // OpenMP [2.16, Nesting of Regions] // OpenMP constructs may not be nested inside a simd region. // OpenMP [2.8.1,simd Construct, Restrictions] // An ordered construct with the simd clause is the only OpenMP // construct that can appear in the simd region. // Allowing a SIMD consruct nested in another SIMD construct is an // extension. The OpenMP 4.5 spec does not allow it. Issue a warning // message. SemaRef.Diag(StartLoc, (CurrentRegion != OMPD_simd) ? diag::err_omp_prohibited_region_simd : diag::warn_omp_nesting_simd); return CurrentRegion != OMPD_simd; } if (ParentRegion == OMPD_atomic) { // OpenMP [2.16, Nesting of Regions] // OpenMP constructs may not be nested inside an atomic region. SemaRef.Diag(StartLoc, diag::err_omp_prohibited_region_atomic); return true; } if (CurrentRegion == OMPD_section) { // OpenMP [2.7.2, sections Construct, Restrictions] // Orphaned section directives are prohibited. That is, the section // directives must appear within the sections construct and must not be // encountered elsewhere in the sections region. if (ParentRegion != OMPD_sections && ParentRegion != OMPD_parallel_sections) { SemaRef.Diag(StartLoc, diag::err_omp_orphaned_section_directive) << (ParentRegion != OMPD_unknown) << getOpenMPDirectiveName(ParentRegion); return true; } return false; } // Allow some constructs to be orphaned (they could be used in functions, // called from OpenMP regions with the required preconditions). if (ParentRegion == OMPD_unknown) return false; if (CurrentRegion == OMPD_cancellation_point || CurrentRegion == OMPD_cancel) { // OpenMP [2.16, Nesting of Regions] // A cancellation point construct for which construct-type-clause is // taskgroup must be nested inside a task construct. A cancellation // point construct for which construct-type-clause is not taskgroup must // be closely nested inside an OpenMP construct that matches the type // specified in construct-type-clause. // A cancel construct for which construct-type-clause is taskgroup must be // nested inside a task construct. A cancel construct for which // construct-type-clause is not taskgroup must be closely nested inside an // OpenMP construct that matches the type specified in // construct-type-clause. NestingProhibited = !((CancelRegion == OMPD_parallel && (ParentRegion == OMPD_parallel || ParentRegion == OMPD_target_parallel)) || (CancelRegion == OMPD_for && (ParentRegion == OMPD_for || ParentRegion == OMPD_parallel_for || ParentRegion == OMPD_target_parallel_for)) || (CancelRegion == OMPD_taskgroup && ParentRegion == OMPD_task) || (CancelRegion == OMPD_sections && (ParentRegion == OMPD_section || ParentRegion == OMPD_sections || ParentRegion == OMPD_parallel_sections))); } else if (CurrentRegion == OMPD_master) { // OpenMP [2.16, Nesting of Regions] // A master region may not be closely nested inside a worksharing, // atomic, or explicit task region. NestingProhibited = isOpenMPWorksharingDirective(ParentRegion) || isOpenMPTaskingDirective(ParentRegion); } else if (CurrentRegion == OMPD_critical && CurrentName.getName()) { // OpenMP [2.16, Nesting of Regions] // A critical region may not be nested (closely or otherwise) inside a // critical region with the same name. Note that this restriction is not // sufficient to prevent deadlock. SourceLocation PreviousCriticalLoc; bool DeadLock = Stack->hasDirective([CurrentName, &PreviousCriticalLoc]( OpenMPDirectiveKind K, const DeclarationNameInfo &DNI, SourceLocation Loc) ->bool { if (K == OMPD_critical && DNI.getName() == CurrentName.getName()) { PreviousCriticalLoc = Loc; return true; } else return false; }, false /* skip top directive */); if (DeadLock) { SemaRef.Diag(StartLoc, diag::err_omp_prohibited_region_critical_same_name) << CurrentName.getName(); if (PreviousCriticalLoc.isValid()) SemaRef.Diag(PreviousCriticalLoc, diag::note_omp_previous_critical_region); return true; } } else if (CurrentRegion == OMPD_barrier) { // OpenMP [2.16, Nesting of Regions] // A barrier region may not be closely nested inside a worksharing, // explicit task, critical, ordered, atomic, or master region. NestingProhibited = isOpenMPWorksharingDirective(ParentRegion) || isOpenMPTaskingDirective(ParentRegion) || ParentRegion == OMPD_master || ParentRegion == OMPD_critical || ParentRegion == OMPD_ordered; } else if (isOpenMPWorksharingDirective(CurrentRegion) && !isOpenMPParallelDirective(CurrentRegion)) { // OpenMP [2.16, Nesting of Regions] // A worksharing region may not be closely nested inside a worksharing, // explicit task, critical, ordered, atomic, or master region. NestingProhibited = isOpenMPWorksharingDirective(ParentRegion) || isOpenMPTaskingDirective(ParentRegion) || ParentRegion == OMPD_master || ParentRegion == OMPD_critical || ParentRegion == OMPD_ordered; Recommend = ShouldBeInParallelRegion; } else if (CurrentRegion == OMPD_ordered) { // OpenMP [2.16, Nesting of Regions] // An ordered region may not be closely nested inside a critical, // atomic, or explicit task region. // An ordered region must be closely nested inside a loop region (or // parallel loop region) with an ordered clause. // OpenMP [2.8.1,simd Construct, Restrictions] // An ordered construct with the simd clause is the only OpenMP construct // that can appear in the simd region. NestingProhibited = ParentRegion == OMPD_critical || isOpenMPTaskingDirective(ParentRegion) || !(isOpenMPSimdDirective(ParentRegion) || Stack->isParentOrderedRegion()); Recommend = ShouldBeInOrderedRegion; } else if (isOpenMPTeamsDirective(CurrentRegion)) { // OpenMP [2.16, Nesting of Regions] // If specified, a teams construct must be contained within a target // construct. NestingProhibited = ParentRegion != OMPD_target; Recommend = ShouldBeInTargetRegion; Stack->setParentTeamsRegionLoc(Stack->getConstructLoc()); } if (!NestingProhibited && isOpenMPTeamsDirective(ParentRegion)) { // OpenMP [2.16, Nesting of Regions] // distribute, parallel, parallel sections, parallel workshare, and the // parallel loop and parallel loop SIMD constructs are the only OpenMP // constructs that can be closely nested in the teams region. NestingProhibited = !isOpenMPParallelDirective(CurrentRegion) && !isOpenMPDistributeDirective(CurrentRegion); Recommend = ShouldBeInParallelRegion; } if (!NestingProhibited && isOpenMPDistributeDirective(CurrentRegion)) { // OpenMP 4.5 [2.17 Nesting of Regions] // The region associated with the distribute construct must be strictly // nested inside a teams region NestingProhibited = !isOpenMPTeamsDirective(ParentRegion); Recommend = ShouldBeInTeamsRegion; } if (!NestingProhibited && (isOpenMPTargetExecutionDirective(CurrentRegion) || isOpenMPTargetDataManagementDirective(CurrentRegion))) { // OpenMP 4.5 [2.17 Nesting of Regions] // If a target, target update, target data, target enter data, or // target exit data construct is encountered during execution of a // target region, the behavior is unspecified. NestingProhibited = Stack->hasDirective( [&OffendingRegion](OpenMPDirectiveKind K, const DeclarationNameInfo &, SourceLocation) -> bool { if (isOpenMPTargetExecutionDirective(K)) { OffendingRegion = K; return true; } else return false; }, false /* don't skip top directive */); CloseNesting = false; } if (NestingProhibited) { SemaRef.Diag(StartLoc, diag::err_omp_prohibited_region) << CloseNesting << getOpenMPDirectiveName(OffendingRegion) << Recommend << getOpenMPDirectiveName(CurrentRegion); return true; } } return false; } static bool checkIfClauses(Sema &S, OpenMPDirectiveKind Kind, ArrayRef
Clauses, ArrayRef
AllowedNameModifiers) { bool ErrorFound = false; unsigned NamedModifiersNumber = 0; SmallVector
FoundNameModifiers( OMPD_unknown + 1); SmallVector
NameModifierLoc; for (const auto *C : Clauses) { if (const auto *IC = dyn_cast_or_null
(C)) { // At most one if clause without a directive-name-modifier can appear on // the directive. OpenMPDirectiveKind CurNM = IC->getNameModifier(); if (FoundNameModifiers[CurNM]) { S.Diag(C->getLocStart(), diag::err_omp_more_one_clause) << getOpenMPDirectiveName(Kind) << getOpenMPClauseName(OMPC_if) << (CurNM != OMPD_unknown) << getOpenMPDirectiveName(CurNM); ErrorFound = true; } else if (CurNM != OMPD_unknown) { NameModifierLoc.push_back(IC->getNameModifierLoc()); ++NamedModifiersNumber; } FoundNameModifiers[CurNM] = IC; if (CurNM == OMPD_unknown) continue; // Check if the specified name modifier is allowed for the current // directive. // At most one if clause with the particular directive-name-modifier can // appear on the directive. bool MatchFound = false; for (auto NM : AllowedNameModifiers) { if (CurNM == NM) { MatchFound = true; break; } } if (!MatchFound) { S.Diag(IC->getNameModifierLoc(), diag::err_omp_wrong_if_directive_name_modifier) << getOpenMPDirectiveName(CurNM) << getOpenMPDirectiveName(Kind); ErrorFound = true; } } } // If any if clause on the directive includes a directive-name-modifier then // all if clauses on the directive must include a directive-name-modifier. if (FoundNameModifiers[OMPD_unknown] && NamedModifiersNumber > 0) { if (NamedModifiersNumber == AllowedNameModifiers.size()) { S.Diag(FoundNameModifiers[OMPD_unknown]->getLocStart(), diag::err_omp_no_more_if_clause); } else { std::string Values; std::string Sep(", "); unsigned AllowedCnt = 0; unsigned TotalAllowedNum = AllowedNameModifiers.size() - NamedModifiersNumber; for (unsigned Cnt = 0, End = AllowedNameModifiers.size(); Cnt < End; ++Cnt) { OpenMPDirectiveKind NM = AllowedNameModifiers[Cnt]; if (!FoundNameModifiers[NM]) { Values += "'"; Values += getOpenMPDirectiveName(NM); Values += "'"; if (AllowedCnt + 2 == TotalAllowedNum) Values += " or "; else if (AllowedCnt + 1 != TotalAllowedNum) Values += Sep; ++AllowedCnt; } } S.Diag(FoundNameModifiers[OMPD_unknown]->getCondition()->getLocStart(), diag::err_omp_unnamed_if_clause) << (TotalAllowedNum > 1) << Values; } for (auto Loc : NameModifierLoc) { S.Diag(Loc, diag::note_omp_previous_named_if_clause); } ErrorFound = true; } return ErrorFound; } StmtResult Sema::ActOnOpenMPExecutableDirective( OpenMPDirectiveKind Kind, const DeclarationNameInfo &DirName, OpenMPDirectiveKind CancelRegion, ArrayRef
Clauses, Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc) { StmtResult Res = StmtError(); if (CheckNestingOfRegions(*this, DSAStack, Kind, DirName, CancelRegion, StartLoc)) return StmtError(); llvm::SmallVector
ClausesWithImplicit; llvm::DenseMap
VarsWithInheritedDSA; bool ErrorFound = false; ClausesWithImplicit.append(Clauses.begin(), Clauses.end()); if (AStmt) { assert(isa
(AStmt) && "Captured statement expected"); // Check default data sharing attributes for referenced variables. DSAAttrChecker DSAChecker(DSAStack, *this, cast
(AStmt)); DSAChecker.Visit(cast
(AStmt)->getCapturedStmt()); if (DSAChecker.isErrorFound()) return StmtError(); // Generate list of implicitly defined firstprivate variables. VarsWithInheritedDSA = DSAChecker.getVarsWithInheritedDSA(); if (!DSAChecker.getImplicitFirstprivate().empty()) { if (OMPClause *Implicit = ActOnOpenMPFirstprivateClause( DSAChecker.getImplicitFirstprivate(), SourceLocation(), SourceLocation(), SourceLocation())) { ClausesWithImplicit.push_back(Implicit); ErrorFound = cast
(Implicit)->varlist_size() != DSAChecker.getImplicitFirstprivate().size(); } else ErrorFound = true; } } llvm::SmallVector
AllowedNameModifiers; switch (Kind) { case OMPD_parallel: Res = ActOnOpenMPParallelDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc); AllowedNameModifiers.push_back(OMPD_parallel); break; case OMPD_simd: Res = ActOnOpenMPSimdDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA); break; case OMPD_for: Res = ActOnOpenMPForDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA); break; case OMPD_for_simd: Res = ActOnOpenMPForSimdDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA); break; case OMPD_sections: Res = ActOnOpenMPSectionsDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc); break; case OMPD_section: assert(ClausesWithImplicit.empty() && "No clauses are allowed for 'omp section' directive"); Res = ActOnOpenMPSectionDirective(AStmt, StartLoc, EndLoc); break; case OMPD_single: Res = ActOnOpenMPSingleDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc); break; case OMPD_master: assert(ClausesWithImplicit.empty() && "No clauses are allowed for 'omp master' directive"); Res = ActOnOpenMPMasterDirective(AStmt, StartLoc, EndLoc); break; case OMPD_critical: Res = ActOnOpenMPCriticalDirective(DirName, ClausesWithImplicit, AStmt, StartLoc, EndLoc); break; case OMPD_parallel_for: Res = ActOnOpenMPParallelForDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA); AllowedNameModifiers.push_back(OMPD_parallel); break; case OMPD_parallel_for_simd: Res = ActOnOpenMPParallelForSimdDirective( ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA); AllowedNameModifiers.push_back(OMPD_parallel); break; case OMPD_parallel_sections: Res = ActOnOpenMPParallelSectionsDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc); AllowedNameModifiers.push_back(OMPD_parallel); break; case OMPD_task: Res = ActOnOpenMPTaskDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc); AllowedNameModifiers.push_back(OMPD_task); break; case OMPD_taskyield: assert(ClausesWithImplicit.empty() && "No clauses are allowed for 'omp taskyield' directive"); assert(AStmt == nullptr && "No associated statement allowed for 'omp taskyield' directive"); Res = ActOnOpenMPTaskyieldDirective(StartLoc, EndLoc); break; case OMPD_barrier: assert(ClausesWithImplicit.empty() && "No clauses are allowed for 'omp barrier' directive"); assert(AStmt == nullptr && "No associated statement allowed for 'omp barrier' directive"); Res = ActOnOpenMPBarrierDirective(StartLoc, EndLoc); break; case OMPD_taskwait: assert(ClausesWithImplicit.empty() && "No clauses are allowed for 'omp taskwait' directive"); assert(AStmt == nullptr && "No associated statement allowed for 'omp taskwait' directive"); Res = ActOnOpenMPTaskwaitDirective(StartLoc, EndLoc); break; case OMPD_taskgroup: assert(ClausesWithImplicit.empty() && "No clauses are allowed for 'omp taskgroup' directive"); Res = ActOnOpenMPTaskgroupDirective(AStmt, StartLoc, EndLoc); break; case OMPD_flush: assert(AStmt == nullptr && "No associated statement allowed for 'omp flush' directive"); Res = ActOnOpenMPFlushDirective(ClausesWithImplicit, StartLoc, EndLoc); break; case OMPD_ordered: Res = ActOnOpenMPOrderedDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc); break; case OMPD_atomic: Res = ActOnOpenMPAtomicDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc); break; case OMPD_teams: Res = ActOnOpenMPTeamsDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc); break; case OMPD_target: Res = ActOnOpenMPTargetDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc); AllowedNameModifiers.push_back(OMPD_target); break; case OMPD_target_parallel: Res = ActOnOpenMPTargetParallelDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc); AllowedNameModifiers.push_back(OMPD_target); AllowedNameModifiers.push_back(OMPD_parallel); break; case OMPD_target_parallel_for: Res = ActOnOpenMPTargetParallelForDirective( ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA); AllowedNameModifiers.push_back(OMPD_target); AllowedNameModifiers.push_back(OMPD_parallel); break; case OMPD_cancellation_point: assert(ClausesWithImplicit.empty() && "No clauses are allowed for 'omp cancellation point' directive"); assert(AStmt == nullptr && "No associated statement allowed for 'omp " "cancellation point' directive"); Res = ActOnOpenMPCancellationPointDirective(StartLoc, EndLoc, CancelRegion); break; case OMPD_cancel: assert(AStmt == nullptr && "No associated statement allowed for 'omp cancel' directive"); Res = ActOnOpenMPCancelDirective(ClausesWithImplicit, StartLoc, EndLoc, CancelRegion); AllowedNameModifiers.push_back(OMPD_cancel); break; case OMPD_target_data: Res = ActOnOpenMPTargetDataDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc); AllowedNameModifiers.push_back(OMPD_target_data); break; case OMPD_target_enter_data: Res = ActOnOpenMPTargetEnterDataDirective(ClausesWithImplicit, StartLoc, EndLoc); AllowedNameModifiers.push_back(OMPD_target_enter_data); break; case OMPD_target_exit_data: Res = ActOnOpenMPTargetExitDataDirective(ClausesWithImplicit, StartLoc, EndLoc); AllowedNameModifiers.push_back(OMPD_target_exit_data); break; case OMPD_taskloop: Res = ActOnOpenMPTaskLoopDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA); AllowedNameModifiers.push_back(OMPD_taskloop); break; case OMPD_taskloop_simd: Res = ActOnOpenMPTaskLoopSimdDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA); AllowedNameModifiers.push_back(OMPD_taskloop); break; case OMPD_distribute: Res = ActOnOpenMPDistributeDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA); break; case OMPD_target_update: assert(!AStmt && "Statement is not allowed for target update"); Res = ActOnOpenMPTargetUpdateDirective(ClausesWithImplicit, StartLoc, EndLoc); AllowedNameModifiers.push_back(OMPD_target_update); break; case OMPD_distribute_parallel_for: Res = ActOnOpenMPDistributeParallelForDirective( ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA); AllowedNameModifiers.push_back(OMPD_parallel); break; case OMPD_distribute_parallel_for_simd: Res = ActOnOpenMPDistributeParallelForSimdDirective( ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA); AllowedNameModifiers.push_back(OMPD_parallel); break; case OMPD_distribute_simd: Res = ActOnOpenMPDistributeSimdDirective( ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA); break; case OMPD_target_parallel_for_simd: Res = ActOnOpenMPTargetParallelForSimdDirective( ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA); AllowedNameModifiers.push_back(OMPD_target); AllowedNameModifiers.push_back(OMPD_parallel); break; case OMPD_declare_target: case OMPD_end_declare_target: case OMPD_threadprivate: case OMPD_declare_reduction: case OMPD_declare_simd: llvm_unreachable("OpenMP Directive is not allowed"); case OMPD_unknown: llvm_unreachable("Unknown OpenMP directive"); } for (auto P : VarsWithInheritedDSA) { Diag(P.second->getExprLoc(), diag::err_omp_no_dsa_for_variable) << P.first << P.second->getSourceRange(); } ErrorFound = !VarsWithInheritedDSA.empty() || ErrorFound; if (!AllowedNameModifiers.empty()) ErrorFound = checkIfClauses(*this, Kind, Clauses, AllowedNameModifiers) || ErrorFound; if (ErrorFound) return StmtError(); return Res; } Sema::DeclGroupPtrTy Sema::ActOnOpenMPDeclareSimdDirective( DeclGroupPtrTy DG, OMPDeclareSimdDeclAttr::BranchStateTy BS, Expr *Simdlen, ArrayRef
Uniforms, ArrayRef
Aligneds, ArrayRef
Alignments, ArrayRef
Linears, ArrayRef
LinModifiers, ArrayRef
Steps, SourceRange SR) { assert(Aligneds.size() == Alignments.size()); assert(Linears.size() == LinModifiers.size()); assert(Linears.size() == Steps.size()); if (!DG || DG.get().isNull()) return DeclGroupPtrTy(); if (!DG.get().isSingleDecl()) { Diag(SR.getBegin(), diag::err_omp_single_decl_in_declare_simd); return DG; } auto *ADecl = DG.get().getSingleDecl(); if (auto *FTD = dyn_cast
(ADecl)) ADecl = FTD->getTemplatedDecl(); auto *FD = dyn_cast
(ADecl); if (!FD) { Diag(ADecl->getLocation(), diag::err_omp_function_expected); return DeclGroupPtrTy(); } // OpenMP [2.8.2, declare simd construct, Description] // The parameter of the simdlen clause must be a constant positive integer // expression. ExprResult SL; if (Simdlen) SL = VerifyPositiveIntegerConstantInClause(Simdlen, OMPC_simdlen); // OpenMP [2.8.2, declare simd construct, Description] // The special this pointer can be used as if was one of the arguments to the // function in any of the linear, aligned, or uniform clauses. // The uniform clause declares one or more arguments to have an invariant // value for all concurrent invocations of the function in the execution of a // single SIMD loop. llvm::DenseMap
UniformedArgs; Expr *UniformedLinearThis = nullptr; for (auto *E : Uniforms) { E = E->IgnoreParenImpCasts(); if (auto *DRE = dyn_cast
(E)) if (auto *PVD = dyn_cast
(DRE->getDecl())) if (FD->getNumParams() > PVD->getFunctionScopeIndex() && FD->getParamDecl(PVD->getFunctionScopeIndex()) ->getCanonicalDecl() == PVD->getCanonicalDecl()) { UniformedArgs.insert(std::make_pair(PVD->getCanonicalDecl(), E)); continue; } if (isa
(E)) { UniformedLinearThis = E; continue; } Diag(E->getExprLoc(), diag::err_omp_param_or_this_in_clause) << FD->getDeclName() << (isa
(ADecl) ? 1 : 0); } // OpenMP [2.8.2, declare simd construct, Description] // The aligned clause declares that the object to which each list item points // is aligned to the number of bytes expressed in the optional parameter of // the aligned clause. // The special this pointer can be used as if was one of the arguments to the // function in any of the linear, aligned, or uniform clauses. // The type of list items appearing in the aligned clause must be array, // pointer, reference to array, or reference to pointer. llvm::DenseMap
AlignedArgs; Expr *AlignedThis = nullptr; for (auto *E : Aligneds) { E = E->IgnoreParenImpCasts(); if (auto *DRE = dyn_cast
(E)) if (auto *PVD = dyn_cast
(DRE->getDecl())) { auto *CanonPVD = PVD->getCanonicalDecl(); if (FD->getNumParams() > PVD->getFunctionScopeIndex() && FD->getParamDecl(PVD->getFunctionScopeIndex()) ->getCanonicalDecl() == CanonPVD) { // OpenMP [2.8.1, simd construct, Restrictions] // A list-item cannot appear in more than one aligned clause. if (AlignedArgs.count(CanonPVD) > 0) { Diag(E->getExprLoc(), diag::err_omp_aligned_twice) << 1 << E->getSourceRange(); Diag(AlignedArgs[CanonPVD]->getExprLoc(), diag::note_omp_explicit_dsa) << getOpenMPClauseName(OMPC_aligned); continue; } AlignedArgs[CanonPVD] = E; QualType QTy = PVD->getType() .getNonReferenceType() .getUnqualifiedType() .getCanonicalType(); const Type *Ty = QTy.getTypePtrOrNull(); if (!Ty || (!Ty->isArrayType() && !Ty->isPointerType())) { Diag(E->getExprLoc(), diag::err_omp_aligned_expected_array_or_ptr) << QTy << getLangOpts().CPlusPlus << E->getSourceRange(); Diag(PVD->getLocation(), diag::note_previous_decl) << PVD; } continue; } } if (isa
(E)) { if (AlignedThis) { Diag(E->getExprLoc(), diag::err_omp_aligned_twice) << 2 << E->getSourceRange(); Diag(AlignedThis->getExprLoc(), diag::note_omp_explicit_dsa) << getOpenMPClauseName(OMPC_aligned); } AlignedThis = E; continue; } Diag(E->getExprLoc(), diag::err_omp_param_or_this_in_clause) << FD->getDeclName() << (isa
(ADecl) ? 1 : 0); } // The optional parameter of the aligned clause, alignment, must be a constant // positive integer expression. If no optional parameter is specified, // implementation-defined default alignments for SIMD instructions on the // target platforms are assumed. SmallVector
NewAligns; for (auto *E : Alignments) { ExprResult Align; if (E) Align = VerifyPositiveIntegerConstantInClause(E, OMPC_aligned); NewAligns.push_back(Align.get()); } // OpenMP [2.8.2, declare simd construct, Description] // The linear clause declares one or more list items to be private to a SIMD // lane and to have a linear relationship with respect to the iteration space // of a loop. // The special this pointer can be used as if was one of the arguments to the // function in any of the linear, aligned, or uniform clauses. // When a linear-step expression is specified in a linear clause it must be // either a constant integer expression or an integer-typed parameter that is // specified in a uniform clause on the directive. llvm::DenseMap
LinearArgs; const bool IsUniformedThis = UniformedLinearThis != nullptr; auto MI = LinModifiers.begin(); for (auto *E : Linears) { auto LinKind = static_cast
(*MI); ++MI; E = E->IgnoreParenImpCasts(); if (auto *DRE = dyn_cast
(E)) if (auto *PVD = dyn_cast
(DRE->getDecl())) { auto *CanonPVD = PVD->getCanonicalDecl(); if (FD->getNumParams() > PVD->getFunctionScopeIndex() && FD->getParamDecl(PVD->getFunctionScopeIndex()) ->getCanonicalDecl() == CanonPVD) { // OpenMP [2.15.3.7, linear Clause, Restrictions] // A list-item cannot appear in more than one linear clause. if (LinearArgs.count(CanonPVD) > 0) { Diag(E->getExprLoc(), diag::err_omp_wrong_dsa) << getOpenMPClauseName(OMPC_linear) << getOpenMPClauseName(OMPC_linear) << E->getSourceRange(); Diag(LinearArgs[CanonPVD]->getExprLoc(), diag::note_omp_explicit_dsa) << getOpenMPClauseName(OMPC_linear); continue; } // Each argument can appear in at most one uniform or linear clause. if (UniformedArgs.count(CanonPVD) > 0) { Diag(E->getExprLoc(), diag::err_omp_wrong_dsa) << getOpenMPClauseName(OMPC_linear) << getOpenMPClauseName(OMPC_uniform) << E->getSourceRange(); Diag(UniformedArgs[CanonPVD]->getExprLoc(), diag::note_omp_explicit_dsa) << getOpenMPClauseName(OMPC_uniform); continue; } LinearArgs[CanonPVD] = E; if (E->isValueDependent() || E->isTypeDependent() || E->isInstantiationDependent() || E->containsUnexpandedParameterPack()) continue; (void)CheckOpenMPLinearDecl(CanonPVD, E->getExprLoc(), LinKind, PVD->getOriginalType()); continue; } } if (isa
(E)) { if (UniformedLinearThis) { Diag(E->getExprLoc(), diag::err_omp_wrong_dsa) << getOpenMPClauseName(OMPC_linear) << getOpenMPClauseName(IsUniformedThis ? OMPC_uniform : OMPC_linear) << E->getSourceRange(); Diag(UniformedLinearThis->getExprLoc(), diag::note_omp_explicit_dsa) << getOpenMPClauseName(IsUniformedThis ? OMPC_uniform : OMPC_linear); continue; } UniformedLinearThis = E; if (E->isValueDependent() || E->isTypeDependent() || E->isInstantiationDependent() || E->containsUnexpandedParameterPack()) continue; (void)CheckOpenMPLinearDecl(/*D=*/nullptr, E->getExprLoc(), LinKind, E->getType()); continue; } Diag(E->getExprLoc(), diag::err_omp_param_or_this_in_clause) << FD->getDeclName() << (isa
(ADecl) ? 1 : 0); } Expr *Step = nullptr; Expr *NewStep = nullptr; SmallVector
NewSteps; for (auto *E : Steps) { // Skip the same step expression, it was checked already. if (Step == E || !E) { NewSteps.push_back(E ? NewStep : nullptr); continue; } Step = E; if (auto *DRE = dyn_cast
(Step)) if (auto *PVD = dyn_cast
(DRE->getDecl())) { auto *CanonPVD = PVD->getCanonicalDecl(); if (UniformedArgs.count(CanonPVD) == 0) { Diag(Step->getExprLoc(), diag::err_omp_expected_uniform_param) << Step->getSourceRange(); } else if (E->isValueDependent() || E->isTypeDependent() || E->isInstantiationDependent() || E->containsUnexpandedParameterPack() || CanonPVD->getType()->hasIntegerRepresentation()) NewSteps.push_back(Step); else { Diag(Step->getExprLoc(), diag::err_omp_expected_int_param) << Step->getSourceRange(); } continue; } NewStep = Step; if (Step && !Step->isValueDependent() && !Step->isTypeDependent() && !Step->isInstantiationDependent() && !Step->containsUnexpandedParameterPack()) { NewStep = PerformOpenMPImplicitIntegerConversion(Step->getExprLoc(), Step) .get(); if (NewStep) NewStep = VerifyIntegerConstantExpression(NewStep).get(); } NewSteps.push_back(NewStep); } auto *NewAttr = OMPDeclareSimdDeclAttr::CreateImplicit( Context, BS, SL.get(), const_cast
(Uniforms.data()), Uniforms.size(), const_cast
(Aligneds.data()), Aligneds.size(), const_cast
(NewAligns.data()), NewAligns.size(), const_cast
(Linears.data()), Linears.size(), const_cast
(LinModifiers.data()), LinModifiers.size(), NewSteps.data(), NewSteps.size(), SR); ADecl->addAttr(NewAttr); return ConvertDeclToDeclGroup(ADecl); } StmtResult Sema::ActOnOpenMPParallelDirective(ArrayRef
Clauses, Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc) { if (!AStmt) return StmtError(); CapturedStmt *CS = cast
(AStmt); // 1.2.2 OpenMP Language Terminology // Structured block - An executable statement with a single entry at the // top and a single exit at the bottom. // The point of exit cannot be a branch out of the structured block. // longjmp() and throw() must not violate the entry/exit criteria. CS->getCapturedDecl()->setNothrow(); getCurFunction()->setHasBranchProtectedScope(); return OMPParallelDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt, DSAStack->isCancelRegion()); } namespace { /// \brief Helper class for checking canonical form of the OpenMP loops and /// extracting iteration space of each loop in the loop nest, that will be used /// for IR generation. class OpenMPIterationSpaceChecker { /// \brief Reference to Sema. Sema &SemaRef; /// \brief A location for diagnostics (when there is no some better location). SourceLocation DefaultLoc; /// \brief A location for diagnostics (when increment is not compatible). SourceLocation ConditionLoc; /// \brief A source location for referring to loop init later. SourceRange InitSrcRange; /// \brief A source location for referring to condition later. SourceRange ConditionSrcRange; /// \brief A source location for referring to increment later. SourceRange IncrementSrcRange; /// \brief Loop variable. ValueDecl *LCDecl = nullptr; /// \brief Reference to loop variable. Expr *LCRef = nullptr; /// \brief Lower bound (initializer for the var). Expr *LB = nullptr; /// \brief Upper bound. Expr *UB = nullptr; /// \brief Loop step (increment). Expr *Step = nullptr; /// \brief This flag is true when condition is one of: /// Var < UB /// Var <= UB /// UB > Var /// UB >= Var bool TestIsLessOp = false; /// \brief This flag is true when condition is strict ( < or > ). bool TestIsStrictOp = false; /// \brief This flag is true when step is subtracted on each iteration. bool SubtractStep = false; public: OpenMPIterationSpaceChecker(Sema &SemaRef, SourceLocation DefaultLoc) : SemaRef(SemaRef), DefaultLoc(DefaultLoc), ConditionLoc(DefaultLoc) {} /// \brief Check init-expr for canonical loop form and save loop counter /// variable - #Var and its initialization value - #LB. bool CheckInit(Stmt *S, bool EmitDiags = true); /// \brief Check test-expr for canonical form, save upper-bound (#UB), flags /// for less/greater and for strict/non-strict comparison. bool CheckCond(Expr *S); /// \brief Check incr-expr for canonical loop form and return true if it /// does not conform, otherwise save loop step (#Step). bool CheckInc(Expr *S); /// \brief Return the loop counter variable. ValueDecl *GetLoopDecl() const { return LCDecl; } /// \brief Return the reference expression to loop counter variable. Expr *GetLoopDeclRefExpr() const { return LCRef; } /// \brief Source range of the loop init. SourceRange GetInitSrcRange() const { return InitSrcRange; } /// \brief Source range of the loop condition. SourceRange GetConditionSrcRange() const { return ConditionSrcRange; } /// \brief Source range of the loop increment. SourceRange GetIncrementSrcRange() const { return IncrementSrcRange; } /// \brief True if the step should be subtracted. bool ShouldSubtractStep() const { return SubtractStep; } /// \brief Build the expression to calculate the number of iterations. Expr * BuildNumIterations(Scope *S, const bool LimitedType, llvm::MapVector
&Captures) const; /// \brief Build the precondition expression for the loops. Expr *BuildPreCond(Scope *S, Expr *Cond, llvm::MapVector
&Captures) const; /// \brief Build reference expression to the counter be used for codegen. DeclRefExpr *BuildCounterVar(llvm::MapVector
&Captures, DSAStackTy &DSA) const; /// \brief Build reference expression to the private counter be used for /// codegen. Expr *BuildPrivateCounterVar() const; /// \brief Build initization of the counter be used for codegen. Expr *BuildCounterInit() const; /// \brief Build step of the counter be used for codegen. Expr *BuildCounterStep() const; /// \brief Return true if any expression is dependent. bool Dependent() const; private: /// \brief Check the right-hand side of an assignment in the increment /// expression. bool CheckIncRHS(Expr *RHS); /// \brief Helper to set loop counter variable and its initializer. bool SetLCDeclAndLB(ValueDecl *NewLCDecl, Expr *NewDeclRefExpr, Expr *NewLB); /// \brief Helper to set upper bound. bool SetUB(Expr *NewUB, bool LessOp, bool StrictOp, SourceRange SR, SourceLocation SL); /// \brief Helper to set loop increment. bool SetStep(Expr *NewStep, bool Subtract); }; bool OpenMPIterationSpaceChecker::Dependent() const { if (!LCDecl) { assert(!LB && !UB && !Step); return false; } return LCDecl->getType()->isDependentType() || (LB && LB->isValueDependent()) || (UB && UB->isValueDependent()) || (Step && Step->isValueDependent()); } static Expr *getExprAsWritten(Expr *E) { if (auto *ExprTemp = dyn_cast
(E)) E = ExprTemp->getSubExpr(); if (auto *MTE = dyn_cast
(E)) E = MTE->GetTemporaryExpr(); while (auto *Binder = dyn_cast
(E)) E = Binder->getSubExpr(); if (auto *ICE = dyn_cast
(E)) E = ICE->getSubExprAsWritten(); return E->IgnoreParens(); } bool OpenMPIterationSpaceChecker::SetLCDeclAndLB(ValueDecl *NewLCDecl, Expr *NewLCRefExpr, Expr *NewLB) { // State consistency checking to ensure correct usage. assert(LCDecl == nullptr && LB == nullptr && LCRef == nullptr && UB == nullptr && Step == nullptr && !TestIsLessOp && !TestIsStrictOp); if (!NewLCDecl || !NewLB) return true; LCDecl = getCanonicalDecl(NewLCDecl); LCRef = NewLCRefExpr; if (auto *CE = dyn_cast_or_null
(NewLB)) if (const CXXConstructorDecl *Ctor = CE->getConstructor()) if ((Ctor->isCopyOrMoveConstructor() || Ctor->isConvertingConstructor(/*AllowExplicit=*/false)) && CE->getNumArgs() > 0 && CE->getArg(0) != nullptr) NewLB = CE->getArg(0)->IgnoreParenImpCasts(); LB = NewLB; return false; } bool OpenMPIterationSpaceChecker::SetUB(Expr *NewUB, bool LessOp, bool StrictOp, SourceRange SR, SourceLocation SL) { // State consistency checking to ensure correct usage. assert(LCDecl != nullptr && LB != nullptr && UB == nullptr && Step == nullptr && !TestIsLessOp && !TestIsStrictOp); if (!NewUB) return true; UB = NewUB; TestIsLessOp = LessOp; TestIsStrictOp = StrictOp; ConditionSrcRange = SR; ConditionLoc = SL; return false; } bool OpenMPIterationSpaceChecker::SetStep(Expr *NewStep, bool Subtract) { // State consistency checking to ensure correct usage. assert(LCDecl != nullptr && LB != nullptr && Step == nullptr); if (!NewStep) return true; if (!NewStep->isValueDependent()) { // Check that the step is integer expression. SourceLocation StepLoc = NewStep->getLocStart(); ExprResult Val = SemaRef.PerformOpenMPImplicitIntegerConversion(StepLoc, NewStep); if (Val.isInvalid()) return true; NewStep = Val.get(); // OpenMP [2.6, Canonical Loop Form, Restrictions] // If test-expr is of form var relational-op b and relational-op is < or // <= then incr-expr must cause var to increase on each iteration of the // loop. If test-expr is of form var relational-op b and relational-op is // > or >= then incr-expr must cause var to decrease on each iteration of // the loop. // If test-expr is of form b relational-op var and relational-op is < or // <= then incr-expr must cause var to decrease on each iteration of the // loop. If test-expr is of form b relational-op var and relational-op is // > or >= then incr-expr must cause var to increase on each iteration of // the loop. llvm::APSInt Result; bool IsConstant = NewStep->isIntegerConstantExpr(Result, SemaRef.Context); bool IsUnsigned = !NewStep->getType()->hasSignedIntegerRepresentation(); bool IsConstNeg = IsConstant && Result.isSigned() && (Subtract != Result.isNegative()); bool IsConstPos = IsConstant && Result.isSigned() && (Subtract == Result.isNegative()); bool IsConstZero = IsConstant && !Result.getBoolValue(); if (UB && (IsConstZero || (TestIsLessOp ? (IsConstNeg || (IsUnsigned && Subtract)) : (IsConstPos || (IsUnsigned && !Subtract))))) { SemaRef.Diag(NewStep->getExprLoc(), diag::err_omp_loop_incr_not_compatible) << LCDecl << TestIsLessOp << NewStep->getSourceRange(); SemaRef.Diag(ConditionLoc, diag::note_omp_loop_cond_requres_compatible_incr) << TestIsLessOp << ConditionSrcRange; return true; } if (TestIsLessOp == Subtract) { NewStep = SemaRef.CreateBuiltinUnaryOp(NewStep->getExprLoc(), UO_Minus, NewStep).get(); Subtract = !Subtract; } } Step = NewStep; SubtractStep = Subtract; return false; } bool OpenMPIterationSpaceChecker::CheckInit(Stmt *S, bool EmitDiags) { // Check init-expr for canonical loop form and save loop counter // variable - #Var and its initialization value - #LB. // OpenMP [2.6] Canonical loop form. init-expr may be one of the following: // var = lb // integer-type var = lb // random-access-iterator-type var = lb // pointer-type var = lb // if (!S) { if (EmitDiags) { SemaRef.Diag(DefaultLoc, diag::err_omp_loop_not_canonical_init); } return true; } if (auto *ExprTemp = dyn_cast
(S)) if (!ExprTemp->cleanupsHaveSideEffects()) S = ExprTemp->getSubExpr(); InitSrcRange = S->getSourceRange(); if (Expr *E = dyn_cast
(S)) S = E->IgnoreParens(); if (auto BO = dyn_cast
(S)) { if (BO->getOpcode() == BO_Assign) { auto *LHS = BO->getLHS()->IgnoreParens(); if (auto *DRE = dyn_cast
(LHS)) { if (auto *CED = dyn_cast
(DRE->getDecl())) if (auto *ME = dyn_cast
(getExprAsWritten(CED->getInit()))) return SetLCDeclAndLB(ME->getMemberDecl(), ME, BO->getRHS()); return SetLCDeclAndLB(DRE->getDecl(), DRE, BO->getRHS()); } if (auto *ME = dyn_cast
(LHS)) { if (ME->isArrow() && isa
(ME->getBase()->IgnoreParenImpCasts())) return SetLCDeclAndLB(ME->getMemberDecl(), ME, BO->getRHS()); } } } else if (auto DS = dyn_cast
(S)) { if (DS->isSingleDecl()) { if (auto Var = dyn_cast_or_null
(DS->getSingleDecl())) { if (Var->hasInit() && !Var->getType()->isReferenceType()) { // Accept non-canonical init form here but emit ext. warning. if (Var->getInitStyle() != VarDecl::CInit && EmitDiags) SemaRef.Diag(S->getLocStart(), diag::ext_omp_loop_not_canonical_init) << S->getSourceRange(); return SetLCDeclAndLB(Var, nullptr, Var->getInit()); } } } } else if (auto CE = dyn_cast
(S)) { if (CE->getOperator() == OO_Equal) { auto *LHS = CE->getArg(0); if (auto DRE = dyn_cast
(LHS)) { if (auto *CED = dyn_cast
(DRE->getDecl())) if (auto *ME = dyn_cast
(getExprAsWritten(CED->getInit()))) return SetLCDeclAndLB(ME->getMemberDecl(), ME, BO->getRHS()); return SetLCDeclAndLB(DRE->getDecl(), DRE, CE->getArg(1)); } if (auto *ME = dyn_cast
(LHS)) { if (ME->isArrow() && isa
(ME->getBase()->IgnoreParenImpCasts())) return SetLCDeclAndLB(ME->getMemberDecl(), ME, BO->getRHS()); } } } if (Dependent() || SemaRef.CurContext->isDependentContext()) return false; if (EmitDiags) { SemaRef.Diag(S->getLocStart(), diag::err_omp_loop_not_canonical_init) << S->getSourceRange(); } return true; } /// \brief Ignore parenthesizes, implicit casts, copy constructor and return the /// variable (which may be the loop variable) if possible. static const ValueDecl *GetInitLCDecl(Expr *E) { if (!E) return nullptr; E = getExprAsWritten(E); if (auto *CE = dyn_cast_or_null
(E)) if (const CXXConstructorDecl *Ctor = CE->getConstructor()) if ((Ctor->isCopyOrMoveConstructor() || Ctor->isConvertingConstructor(/*AllowExplicit=*/false)) && CE->getNumArgs() > 0 && CE->getArg(0) != nullptr) E = CE->getArg(0)->IgnoreParenImpCasts(); if (auto *DRE = dyn_cast_or_null
(E)) { if (auto *VD = dyn_cast
(DRE->getDecl())) { if (auto *CED = dyn_cast
(VD)) if (auto *ME = dyn_cast
(getExprAsWritten(CED->getInit()))) return getCanonicalDecl(ME->getMemberDecl()); return getCanonicalDecl(VD); } } if (auto *ME = dyn_cast_or_null
(E)) if (ME->isArrow() && isa
(ME->getBase()->IgnoreParenImpCasts())) return getCanonicalDecl(ME->getMemberDecl()); return nullptr; } bool OpenMPIterationSpaceChecker::CheckCond(Expr *S) { // Check test-expr for canonical form, save upper-bound UB, flags for // less/greater and for strict/non-strict comparison. // OpenMP [2.6] Canonical loop form. Test-expr may be one of the following: // var relational-op b // b relational-op var // if (!S) { SemaRef.Diag(DefaultLoc, diag::err_omp_loop_not_canonical_cond) << LCDecl; return true; } S = getExprAsWritten(S); SourceLocation CondLoc = S->getLocStart(); if (auto BO = dyn_cast
(S)) { if (BO->isRelationalOp()) { if (GetInitLCDecl(BO->getLHS()) == LCDecl) return SetUB(BO->getRHS(), (BO->getOpcode() == BO_LT || BO->getOpcode() == BO_LE), (BO->getOpcode() == BO_LT || BO->getOpcode() == BO_GT), BO->getSourceRange(), BO->getOperatorLoc()); if (GetInitLCDecl(BO->getRHS()) == LCDecl) return SetUB(BO->getLHS(), (BO->getOpcode() == BO_GT || BO->getOpcode() == BO_GE), (BO->getOpcode() == BO_LT || BO->getOpcode() == BO_GT), BO->getSourceRange(), BO->getOperatorLoc()); } } else if (auto CE = dyn_cast
(S)) { if (CE->getNumArgs() == 2) { auto Op = CE->getOperator(); switch (Op) { case OO_Greater: case OO_GreaterEqual: case OO_Less: case OO_LessEqual: if (GetInitLCDecl(CE->getArg(0)) == LCDecl) return SetUB(CE->getArg(1), Op == OO_Less || Op == OO_LessEqual, Op == OO_Less || Op == OO_Greater, CE->getSourceRange(), CE->getOperatorLoc()); if (GetInitLCDecl(CE->getArg(1)) == LCDecl) return SetUB(CE->getArg(0), Op == OO_Greater || Op == OO_GreaterEqual, Op == OO_Less || Op == OO_Greater, CE->getSourceRange(), CE->getOperatorLoc()); break; default: break; } } } if (Dependent() || SemaRef.CurContext->isDependentContext()) return false; SemaRef.Diag(CondLoc, diag::err_omp_loop_not_canonical_cond) << S->getSourceRange() << LCDecl; return true; } bool OpenMPIterationSpaceChecker::CheckIncRHS(Expr *RHS) { // RHS of canonical loop form increment can be: // var + incr // incr + var // var - incr // RHS = RHS->IgnoreParenImpCasts(); if (auto BO = dyn_cast
(RHS)) { if (BO->isAdditiveOp()) { bool IsAdd = BO->getOpcode() == BO_Add; if (GetInitLCDecl(BO->getLHS()) == LCDecl) return SetStep(BO->getRHS(), !IsAdd); if (IsAdd && GetInitLCDecl(BO->getRHS()) == LCDecl) return SetStep(BO->getLHS(), false); } } else if (auto CE = dyn_cast
(RHS)) { bool IsAdd = CE->getOperator() == OO_Plus; if ((IsAdd || CE->getOperator() == OO_Minus) && CE->getNumArgs() == 2) { if (GetInitLCDecl(CE->getArg(0)) == LCDecl) return SetStep(CE->getArg(1), !IsAdd); if (IsAdd && GetInitLCDecl(CE->getArg(1)) == LCDecl) return SetStep(CE->getArg(0), false); } } if (Dependent() || SemaRef.CurContext->isDependentContext()) return false; SemaRef.Diag(RHS->getLocStart(), diag::err_omp_loop_not_canonical_incr) << RHS->getSourceRange() << LCDecl; return true; } bool OpenMPIterationSpaceChecker::CheckInc(Expr *S) { // Check incr-expr for canonical loop form and return true if it // does not conform. // OpenMP [2.6] Canonical loop form. Test-expr may be one of the following: // ++var // var++ // --var // var-- // var += incr // var -= incr // var = var + incr // var = incr + var // var = var - incr // if (!S) { SemaRef.Diag(DefaultLoc, diag::err_omp_loop_not_canonical_incr) << LCDecl; return true; } if (auto *ExprTemp = dyn_cast
(S)) if (!ExprTemp->cleanupsHaveSideEffects()) S = ExprTemp->getSubExpr(); IncrementSrcRange = S->getSourceRange(); S = S->IgnoreParens(); if (auto UO = dyn_cast
(S)) { if (UO->isIncrementDecrementOp() && GetInitLCDecl(UO->getSubExpr()) == LCDecl) return SetStep( SemaRef.ActOnIntegerConstant(UO->getLocStart(), (UO->isDecrementOp() ? -1 : 1)).get(), false); } else if (auto BO = dyn_cast
(S)) { switch (BO->getOpcode()) { case BO_AddAssign: case BO_SubAssign: if (GetInitLCDecl(BO->getLHS()) == LCDecl) return SetStep(BO->getRHS(), BO->getOpcode() == BO_SubAssign); break; case BO_Assign: if (GetInitLCDecl(BO->getLHS()) == LCDecl) return CheckIncRHS(BO->getRHS()); break; default: break; } } else if (auto CE = dyn_cast
(S)) { switch (CE->getOperator()) { case OO_PlusPlus: case OO_MinusMinus: if (GetInitLCDecl(CE->getArg(0)) == LCDecl) return SetStep( SemaRef.ActOnIntegerConstant( CE->getLocStart(), ((CE->getOperator() == OO_MinusMinus) ? -1 : 1)).get(), false); break; case OO_PlusEqual: case OO_MinusEqual: if (GetInitLCDecl(CE->getArg(0)) == LCDecl) return SetStep(CE->getArg(1), CE->getOperator() == OO_MinusEqual); break; case OO_Equal: if (GetInitLCDecl(CE->getArg(0)) == LCDecl) return CheckIncRHS(CE->getArg(1)); break; default: break; } } if (Dependent() || SemaRef.CurContext->isDependentContext()) return false; SemaRef.Diag(S->getLocStart(), diag::err_omp_loop_not_canonical_incr) << S->getSourceRange() << LCDecl; return true; } static ExprResult tryBuildCapture(Sema &SemaRef, Expr *Capture, llvm::MapVector
&Captures) { if (SemaRef.CurContext->isDependentContext()) return ExprResult(Capture); if (Capture->isEvaluatable(SemaRef.Context, Expr::SE_AllowSideEffects)) return SemaRef.PerformImplicitConversion( Capture->IgnoreImpCasts(), Capture->getType(), Sema::AA_Converting, /*AllowExplicit=*/true); auto I = Captures.find(Capture); if (I != Captures.end()) return buildCapture(SemaRef, Capture, I->second); DeclRefExpr *Ref = nullptr; ExprResult Res = buildCapture(SemaRef, Capture, Ref); Captures[Capture] = Ref; return Res; } /// \brief Build the expression to calculate the number of iterations. Expr *OpenMPIterationSpaceChecker::BuildNumIterations( Scope *S, const bool LimitedType, llvm::MapVector
&Captures) const { ExprResult Diff; auto VarType = LCDecl->getType().getNonReferenceType(); if (VarType->isIntegerType() || VarType->isPointerType() || SemaRef.getLangOpts().CPlusPlus) { // Upper - Lower auto *UBExpr = TestIsLessOp ? UB : LB; auto *LBExpr = TestIsLessOp ? LB : UB; Expr *Upper = tryBuildCapture(SemaRef, UBExpr, Captures).get(); Expr *Lower = tryBuildCapture(SemaRef, LBExpr, Captures).get(); if (!Upper || !Lower) return nullptr; Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Sub, Upper, Lower); if (!Diff.isUsable() && VarType->getAsCXXRecordDecl()) { // BuildBinOp already emitted error, this one is to point user to upper // and lower bound, and to tell what is passed to 'operator-'. SemaRef.Diag(Upper->getLocStart(), diag::err_omp_loop_diff_cxx) << Upper->getSourceRange() << Lower->getSourceRange(); return nullptr; } } if (!Diff.isUsable()) return nullptr; // Upper - Lower [- 1] if (TestIsStrictOp) Diff = SemaRef.BuildBinOp( S, DefaultLoc, BO_Sub, Diff.get(), SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get()); if (!Diff.isUsable()) return nullptr; // Upper - Lower [- 1] + Step auto NewStep = tryBuildCapture(SemaRef, Step, Captures); if (!NewStep.isUsable()) return nullptr; Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Add, Diff.get(), NewStep.get()); if (!Diff.isUsable()) return nullptr; // Parentheses (for dumping/debugging purposes only). Diff = SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, Diff.get()); if (!Diff.isUsable()) return nullptr; // (Upper - Lower [- 1] + Step) / Step Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Div, Diff.get(), NewStep.get()); if (!Diff.isUsable()) return nullptr; // OpenMP runtime requires 32-bit or 64-bit loop variables. QualType Type = Diff.get()->getType(); auto &C = SemaRef.Context; bool UseVarType = VarType->hasIntegerRepresentation() && C.getTypeSize(Type) > C.getTypeSize(VarType); if (!Type->isIntegerType() || UseVarType) { unsigned NewSize = UseVarType ? C.getTypeSize(VarType) : C.getTypeSize(Type); bool IsSigned = UseVarType ? VarType->hasSignedIntegerRepresentation() : Type->hasSignedIntegerRepresentation(); Type = C.getIntTypeForBitwidth(NewSize, IsSigned); if (!SemaRef.Context.hasSameType(Diff.get()->getType(), Type)) { Diff = SemaRef.PerformImplicitConversion( Diff.get(), Type, Sema::AA_Converting, /*AllowExplicit=*/true); if (!Diff.isUsable()) return nullptr; } } if (LimitedType) { unsigned NewSize = (C.getTypeSize(Type) > 32) ? 64 : 32; if (NewSize != C.getTypeSize(Type)) { if (NewSize < C.getTypeSize(Type)) { assert(NewSize == 64 && "incorrect loop var size"); SemaRef.Diag(DefaultLoc, diag::warn_omp_loop_64_bit_var) << InitSrcRange << ConditionSrcRange; } QualType NewType = C.getIntTypeForBitwidth( NewSize, Type->hasSignedIntegerRepresentation() || C.getTypeSize(Type) < NewSize); if (!SemaRef.Context.hasSameType(Diff.get()->getType(), NewType)) { Diff = SemaRef.PerformImplicitConversion(Diff.get(), NewType, Sema::AA_Converting, true); if (!Diff.isUsable()) return nullptr; } } } return Diff.get(); } Expr *OpenMPIterationSpaceChecker::BuildPreCond( Scope *S, Expr *Cond, llvm::MapVector
&Captures) const { // Try to build LB
UB, where
is <, >, <=, or >=. bool Suppress = SemaRef.getDiagnostics().getSuppressAllDiagnostics(); SemaRef.getDiagnostics().setSuppressAllDiagnostics(/*Val=*/true); auto NewLB = tryBuildCapture(SemaRef, LB, Captures); auto NewUB = tryBuildCapture(SemaRef, UB, Captures); if (!NewLB.isUsable() || !NewUB.isUsable()) return nullptr; auto CondExpr = SemaRef.BuildBinOp( S, DefaultLoc, TestIsLessOp ? (TestIsStrictOp ? BO_LT : BO_LE) : (TestIsStrictOp ? BO_GT : BO_GE), NewLB.get(), NewUB.get()); if (CondExpr.isUsable()) { if (!SemaRef.Context.hasSameUnqualifiedType(CondExpr.get()->getType(), SemaRef.Context.BoolTy)) CondExpr = SemaRef.PerformImplicitConversion( CondExpr.get(), SemaRef.Context.BoolTy, /*Action=*/Sema::AA_Casting, /*AllowExplicit=*/true); } SemaRef.getDiagnostics().setSuppressAllDiagnostics(Suppress); // Otherwise use original loop conditon and evaluate it in runtime. return CondExpr.isUsable() ? CondExpr.get() : Cond; } /// \brief Build reference expression to the counter be used for codegen. DeclRefExpr *OpenMPIterationSpaceChecker::BuildCounterVar( llvm::MapVector
&Captures, DSAStackTy &DSA) const { auto *VD = dyn_cast
(LCDecl); if (!VD) { VD = SemaRef.IsOpenMPCapturedDecl(LCDecl); auto *Ref = buildDeclRefExpr( SemaRef, VD, VD->getType().getNonReferenceType(), DefaultLoc); DSAStackTy::DSAVarData Data = DSA.getTopDSA(LCDecl, /*FromParent=*/false); // If the loop control decl is explicitly marked as private, do not mark it // as captured again. if (!isOpenMPPrivate(Data.CKind) || !Data.RefExpr) Captures.insert(std::make_pair(LCRef, Ref)); return Ref; } return buildDeclRefExpr(SemaRef, VD, VD->getType().getNonReferenceType(), DefaultLoc); } Expr *OpenMPIterationSpaceChecker::BuildPrivateCounterVar() const { if (LCDecl && !LCDecl->isInvalidDecl()) { auto Type = LCDecl->getType().getNonReferenceType(); auto *PrivateVar = buildVarDecl(SemaRef, DefaultLoc, Type, LCDecl->getName(), LCDecl->hasAttrs() ? &LCDecl->getAttrs() : nullptr); if (PrivateVar->isInvalidDecl()) return nullptr; return buildDeclRefExpr(SemaRef, PrivateVar, Type, DefaultLoc); } return nullptr; } /// \brief Build initization of the counter be used for codegen. Expr *OpenMPIterationSpaceChecker::BuildCounterInit() const { return LB; } /// \brief Build step of the counter be used for codegen. Expr *OpenMPIterationSpaceChecker::BuildCounterStep() const { return Step; } /// \brief Iteration space of a single for loop. struct LoopIterationSpace final { /// \brief Condition of the loop. Expr *PreCond = nullptr; /// \brief This expression calculates the number of iterations in the loop. /// It is always possible to calculate it before starting the loop. Expr *NumIterations = nullptr; /// \brief The loop counter variable. Expr *CounterVar = nullptr; /// \brief Private loop counter variable. Expr *PrivateCounterVar = nullptr; /// \brief This is initializer for the initial value of #CounterVar. Expr *CounterInit = nullptr; /// \brief This is step for the #CounterVar used to generate its update: /// #CounterVar = #CounterInit + #CounterStep * CurrentIteration. Expr *CounterStep = nullptr; /// \brief Should step be subtracted? bool Subtract = false; /// \brief Source range of the loop init. SourceRange InitSrcRange; /// \brief Source range of the loop condition. SourceRange CondSrcRange; /// \brief Source range of the loop increment. SourceRange IncSrcRange; }; } // namespace void Sema::ActOnOpenMPLoopInitialization(SourceLocation ForLoc, Stmt *Init) { assert(getLangOpts().OpenMP && "OpenMP is not active."); assert(Init && "Expected loop in canonical form."); unsigned AssociatedLoops = DSAStack->getAssociatedLoops(); if (AssociatedLoops > 0 && isOpenMPLoopDirective(DSAStack->getCurrentDirective())) { OpenMPIterationSpaceChecker ISC(*this, ForLoc); if (!ISC.CheckInit(Init, /*EmitDiags=*/false)) { if (auto *D = ISC.GetLoopDecl()) { auto *VD = dyn_cast
(D); if (!VD) { if (auto *Private = IsOpenMPCapturedDecl(D)) VD = Private; else { auto *Ref = buildCapture(*this, D, ISC.GetLoopDeclRefExpr(), /*WithInit=*/false); VD = cast
(Ref->getDecl()); } } DSAStack->addLoopControlVariable(D, VD); } } DSAStack->setAssociatedLoops(AssociatedLoops - 1); } } /// \brief Called on a for stmt to check and extract its iteration space /// for further processing (such as collapsing). static bool CheckOpenMPIterationSpace( OpenMPDirectiveKind DKind, Stmt *S, Sema &SemaRef, DSAStackTy &DSA, unsigned CurrentNestedLoopCount, unsigned NestedLoopCount, Expr *CollapseLoopCountExpr, Expr *OrderedLoopCountExpr, llvm::DenseMap
&VarsWithImplicitDSA, LoopIterationSpace &ResultIterSpace, llvm::MapVector
&Captures) { // OpenMP [2.6, Canonical Loop Form] // for (init-expr; test-expr; incr-expr) structured-block auto For = dyn_cast_or_null
(S); if (!For) { SemaRef.Diag(S->getLocStart(), diag::err_omp_not_for) << (CollapseLoopCountExpr != nullptr || OrderedLoopCountExpr != nullptr) << getOpenMPDirectiveName(DKind) << NestedLoopCount << (CurrentNestedLoopCount > 0) << CurrentNestedLoopCount; if (NestedLoopCount > 1) { if (CollapseLoopCountExpr && OrderedLoopCountExpr) SemaRef.Diag(DSA.getConstructLoc(), diag::note_omp_collapse_ordered_expr) << 2 << CollapseLoopCountExpr->getSourceRange() << OrderedLoopCountExpr->getSourceRange(); else if (CollapseLoopCountExpr) SemaRef.Diag(CollapseLoopCountExpr->getExprLoc(), diag::note_omp_collapse_ordered_expr) << 0 << CollapseLoopCountExpr->getSourceRange(); else SemaRef.Diag(OrderedLoopCountExpr->getExprLoc(), diag::note_omp_collapse_ordered_expr) << 1 << OrderedLoopCountExpr->getSourceRange(); } return true; } assert(For->getBody()); OpenMPIterationSpaceChecker ISC(SemaRef, For->getForLoc()); // Check init. auto Init = For->getInit(); if (ISC.CheckInit(Init)) return true; bool HasErrors = false; // Check loop variable's type. if (auto *LCDecl = ISC.GetLoopDecl()) { auto *LoopDeclRefExpr = ISC.GetLoopDeclRefExpr(); // OpenMP [2.6, Canonical Loop Form] // Var is one of the following: // A variable of signed or unsigned integer type. // For C++, a variable of a random access iterator type. // For C, a variable of a pointer type. auto VarType = LCDecl->getType().getNonReferenceType(); if (!VarType->isDependentType() && !VarType->isIntegerType() && !VarType->isPointerType() && !(SemaRef.getLangOpts().CPlusPlus && VarType->isOverloadableType())) { SemaRef.Diag(Init->getLocStart(), diag::err_omp_loop_variable_type) << SemaRef.getLangOpts().CPlusPlus; HasErrors = true; } // OpenMP, 2.14.1.1 Data-sharing Attribute Rules for Variables Referenced in // a Construct // The loop iteration variable(s) in the associated for-loop(s) of a for or // parallel for construct is (are) private. // The loop iteration variable in the associated for-loop of a simd // construct with just one associated for-loop is linear with a // constant-linear-step that is the increment of the associated for-loop. // Exclude loop var from the list of variables with implicitly defined data // sharing attributes. VarsWithImplicitDSA.erase(LCDecl); // OpenMP [2.14.1.1, Data-sharing Attribute Rules for Variables Referenced // in a Construct, C/C++]. // The loop iteration variable in the associated for-loop of a simd // construct with just one associated for-loop may be listed in a linear // clause with a constant-linear-step that is the increment of the // associated for-loop. // The loop iteration variable(s) in the associated for-loop(s) of a for or // parallel for construct may be listed in a private or lastprivate clause. DSAStackTy::DSAVarData DVar = DSA.getTopDSA(LCDecl, false); // If LoopVarRefExpr is nullptr it means the corresponding loop variable is // declared in the loop and it is predetermined as a private. auto PredeterminedCKind = isOpenMPSimdDirective(DKind) ? ((NestedLoopCount == 1) ? OMPC_linear : OMPC_lastprivate) : OMPC_private; if (((isOpenMPSimdDirective(DKind) && DVar.CKind != OMPC_unknown && DVar.CKind != PredeterminedCKind) || ((isOpenMPWorksharingDirective(DKind) || DKind == OMPD_taskloop || isOpenMPDistributeDirective(DKind)) && !isOpenMPSimdDirective(DKind) && DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_private && DVar.CKind != OMPC_lastprivate)) && (DVar.CKind != OMPC_private || DVar.RefExpr != nullptr)) { SemaRef.Diag(Init->getLocStart(), diag::err_omp_loop_var_dsa) << getOpenMPClauseName(DVar.CKind) << getOpenMPDirectiveName(DKind) << getOpenMPClauseName(PredeterminedCKind); if (DVar.RefExpr == nullptr) DVar.CKind = PredeterminedCKind; ReportOriginalDSA(SemaRef, &DSA, LCDecl, DVar, /*IsLoopIterVar=*/true); HasErrors = true; } else if (LoopDeclRefExpr != nullptr) { // Make the loop iteration variable private (for worksharing constructs), // linear (for simd directives with the only one associated loop) or // lastprivate (for simd directives with several collapsed or ordered // loops). if (DVar.CKind == OMPC_unknown) DVar = DSA.hasDSA(LCDecl, isOpenMPPrivate, [](OpenMPDirectiveKind) -> bool { return true; }, /*FromParent=*/false); DSA.addDSA(LCDecl, LoopDeclRefExpr, PredeterminedCKind); } assert(isOpenMPLoopDirective(DKind) && "DSA for non-loop vars"); // Check test-expr. HasErrors |= ISC.CheckCond(For->getCond()); // Check incr-expr. HasErrors |= ISC.CheckInc(For->getInc()); } if (ISC.Dependent() || SemaRef.CurContext->isDependentContext() || HasErrors) return HasErrors; // Build the loop's iteration space representation. ResultIterSpace.PreCond = ISC.BuildPreCond(DSA.getCurScope(), For->getCond(), Captures); ResultIterSpace.NumIterations = ISC.BuildNumIterations( DSA.getCurScope(), (isOpenMPWorksharingDirective(DKind) || isOpenMPTaskLoopDirective(DKind) || isOpenMPDistributeDirective(DKind)), Captures); ResultIterSpace.CounterVar = ISC.BuildCounterVar(Captures, DSA); ResultIterSpace.PrivateCounterVar = ISC.BuildPrivateCounterVar(); ResultIterSpace.CounterInit = ISC.BuildCounterInit(); ResultIterSpace.CounterStep = ISC.BuildCounterStep(); ResultIterSpace.InitSrcRange = ISC.GetInitSrcRange(); ResultIterSpace.CondSrcRange = ISC.GetConditionSrcRange(); ResultIterSpace.IncSrcRange = ISC.GetIncrementSrcRange(); ResultIterSpace.Subtract = ISC.ShouldSubtractStep(); HasErrors |= (ResultIterSpace.PreCond == nullptr || ResultIterSpace.NumIterations == nullptr || ResultIterSpace.CounterVar == nullptr || ResultIterSpace.PrivateCounterVar == nullptr || ResultIterSpace.CounterInit == nullptr || ResultIterSpace.CounterStep == nullptr); return HasErrors; } /// \brief Build 'VarRef = Start. static ExprResult BuildCounterInit(Sema &SemaRef, Scope *S, SourceLocation Loc, ExprResult VarRef, ExprResult Start, llvm::MapVector
&Captures) { // Build 'VarRef = Start. auto NewStart = tryBuildCapture(SemaRef, Start.get(), Captures); if (!NewStart.isUsable()) return ExprError(); if (!SemaRef.Context.hasSameType(NewStart.get()->getType(), VarRef.get()->getType())) { NewStart = SemaRef.PerformImplicitConversion( NewStart.get(), VarRef.get()->getType(), Sema::AA_Converting, /*AllowExplicit=*/true); if (!NewStart.isUsable()) return ExprError(); } auto Init = SemaRef.BuildBinOp(S, Loc, BO_Assign, VarRef.get(), NewStart.get()); return Init; } /// \brief Build 'VarRef = Start + Iter * Step'. static ExprResult BuildCounterUpdate(Sema &SemaRef, Scope *S, SourceLocation Loc, ExprResult VarRef, ExprResult Start, ExprResult Iter, ExprResult Step, bool Subtract, llvm::MapVector
*Captures = nullptr) { // Add parentheses (for debugging purposes only). Iter = SemaRef.ActOnParenExpr(Loc, Loc, Iter.get()); if (!VarRef.isUsable() || !Start.isUsable() || !Iter.isUsable() || !Step.isUsable()) return ExprError(); ExprResult NewStep = Step; if (Captures) NewStep = tryBuildCapture(SemaRef, Step.get(), *Captures); if (NewStep.isInvalid()) return ExprError(); ExprResult Update = SemaRef.BuildBinOp(S, Loc, BO_Mul, Iter.get(), NewStep.get()); if (!Update.isUsable()) return ExprError(); // Try to build 'VarRef = Start, VarRef (+|-)= Iter * Step' or // 'VarRef = Start (+|-) Iter * Step'. ExprResult NewStart = Start; if (Captures) NewStart = tryBuildCapture(SemaRef, Start.get(), *Captures); if (NewStart.isInvalid()) return ExprError(); // First attempt: try to build 'VarRef = Start, VarRef += Iter * Step'. ExprResult SavedUpdate = Update; ExprResult UpdateVal; if (VarRef.get()->getType()->isOverloadableType() || NewStart.get()->getType()->isOverloadableType() || Update.get()->getType()->isOverloadableType()) { bool Suppress = SemaRef.getDiagnostics().getSuppressAllDiagnostics(); SemaRef.getDiagnostics().setSuppressAllDiagnostics(/*Val=*/true); Update = SemaRef.BuildBinOp(S, Loc, BO_Assign, VarRef.get(), NewStart.get()); if (Update.isUsable()) { UpdateVal = SemaRef.BuildBinOp(S, Loc, Subtract ? BO_SubAssign : BO_AddAssign, VarRef.get(), SavedUpdate.get()); if (UpdateVal.isUsable()) { Update = SemaRef.CreateBuiltinBinOp(Loc, BO_Comma, Update.get(), UpdateVal.get()); } } SemaRef.getDiagnostics().setSuppressAllDiagnostics(Suppress); } // Second attempt: try to build 'VarRef = Start (+|-) Iter * Step'. if (!Update.isUsable() || !UpdateVal.isUsable()) { Update = SemaRef.BuildBinOp(S, Loc, Subtract ? BO_Sub : BO_Add, NewStart.get(), SavedUpdate.get()); if (!Update.isUsable()) return ExprError(); if (!SemaRef.Context.hasSameType(Update.get()->getType(), VarRef.get()->getType())) { Update = SemaRef.PerformImplicitConversion( Update.get(), VarRef.get()->getType(), Sema::AA_Converting, true); if (!Update.isUsable()) return ExprError(); } Update = SemaRef.BuildBinOp(S, Loc, BO_Assign, VarRef.get(), Update.get()); } return Update; } /// \brief Convert integer expression \a E to make it have at least \a Bits /// bits. static ExprResult WidenIterationCount(unsigned Bits, Expr *E, Sema &SemaRef) { if (E == nullptr) return ExprError(); auto &C = SemaRef.Context; QualType OldType = E->getType(); unsigned HasBits = C.getTypeSize(OldType); if (HasBits >= Bits) return ExprResult(E); // OK to convert to signed, because new type has more bits than old. QualType NewType = C.getIntTypeForBitwidth(Bits, /* Signed */ true); return SemaRef.PerformImplicitConversion(E, NewType, Sema::AA_Converting, true); } /// \brief Check if the given expression \a E is a constant integer that fits /// into \a Bits bits. static bool FitsInto(unsigned Bits, bool Signed, Expr *E, Sema &SemaRef) { if (E == nullptr) return false; llvm::APSInt Result; if (E->isIntegerConstantExpr(Result, SemaRef.Context)) return Signed ? Result.isSignedIntN(Bits) : Result.isIntN(Bits); return false; } /// Build preinits statement for the given declarations. static Stmt *buildPreInits(ASTContext &Context, SmallVectorImpl
&PreInits) { if (!PreInits.empty()) { return new (Context) DeclStmt( DeclGroupRef::Create(Context, PreInits.begin(), PreInits.size()), SourceLocation(), SourceLocation()); } return nullptr; } /// Build preinits statement for the given declarations. static Stmt *buildPreInits(ASTContext &Context, llvm::MapVector
&Captures) { if (!Captures.empty()) { SmallVector
PreInits; for (auto &Pair : Captures) PreInits.push_back(Pair.second->getDecl()); return buildPreInits(Context, PreInits); } return nullptr; } /// Build postupdate expression for the given list of postupdates expressions. static Expr *buildPostUpdate(Sema &S, ArrayRef
PostUpdates) { Expr *PostUpdate = nullptr; if (!PostUpdates.empty()) { for (auto *E : PostUpdates) { Expr *ConvE = S.BuildCStyleCastExpr( E->getExprLoc(), S.Context.getTrivialTypeSourceInfo(S.Context.VoidTy), E->getExprLoc(), E) .get(); PostUpdate = PostUpdate ? S.CreateBuiltinBinOp(ConvE->getExprLoc(), BO_Comma, PostUpdate, ConvE) .get() : ConvE; } } return PostUpdate; } /// \brief Called on a for stmt to check itself and nested loops (if any). /// \return Returns 0 if one of the collapsed stmts is not canonical for loop, /// number of collapsed loops otherwise. static unsigned CheckOpenMPLoop(OpenMPDirectiveKind DKind, Expr *CollapseLoopCountExpr, Expr *OrderedLoopCountExpr, Stmt *AStmt, Sema &SemaRef, DSAStackTy &DSA, llvm::DenseMap
&VarsWithImplicitDSA, OMPLoopDirective::HelperExprs &Built) { unsigned NestedLoopCount = 1; if (CollapseLoopCountExpr) { // Found 'collapse' clause - calculate collapse number. llvm::APSInt Result; if (CollapseLoopCountExpr->EvaluateAsInt(Result, SemaRef.getASTContext())) NestedLoopCount = Result.getLimitedValue(); } if (OrderedLoopCountExpr) { // Found 'ordered' clause - calculate collapse number. llvm::APSInt Result; if (OrderedLoopCountExpr->EvaluateAsInt(Result, SemaRef.getASTContext())) { if (Result.getLimitedValue() < NestedLoopCount) { SemaRef.Diag(OrderedLoopCountExpr->getExprLoc(), diag::err_omp_wrong_ordered_loop_count) << OrderedLoopCountExpr->getSourceRange(); SemaRef.Diag(CollapseLoopCountExpr->getExprLoc(), diag::note_collapse_loop_count) << CollapseLoopCountExpr->getSourceRange(); } NestedLoopCount = Result.getLimitedValue(); } } // This is helper routine for loop directives (e.g., 'for', 'simd', // 'for simd', etc.). llvm::MapVector
Captures; SmallVector
IterSpaces; IterSpaces.resize(NestedLoopCount); Stmt *CurStmt = AStmt->IgnoreContainers(/* IgnoreCaptured */ true); for (unsigned Cnt = 0; Cnt < NestedLoopCount; ++Cnt) { if (CheckOpenMPIterationSpace(DKind, CurStmt, SemaRef, DSA, Cnt, NestedLoopCount, CollapseLoopCountExpr, OrderedLoopCountExpr, VarsWithImplicitDSA, IterSpaces[Cnt], Captures)) return 0; // Move on to the next nested for loop, or to the loop body. // OpenMP [2.8.1, simd construct, Restrictions] // All loops associated with the construct must be perfectly nested; that // is, there must be no intervening code nor any OpenMP directive between // any two loops. CurStmt = cast
(CurStmt)->getBody()->IgnoreContainers(); } Built.clear(/* size */ NestedLoopCount); if (SemaRef.CurContext->isDependentContext()) return NestedLoopCount; // An example of what is generated for the following code: // // #pragma omp simd collapse(2) ordered(2) // for (i = 0; i < NI; ++i) // for (k = 0; k < NK; ++k) // for (j = J0; j < NJ; j+=2) { //
// } // // We generate the code below. // Note: the loop body may be outlined in CodeGen. // Note: some counters may be C++ classes, operator- is used to find number of // iterations and operator+= to calculate counter value. // Note: decltype(NumIterations) must be integer type (in 'omp for', only i32 // or i64 is currently supported). // // #define NumIterations (NI * ((NJ - J0 - 1 + 2) / 2)) // for (int[32|64]_t IV = 0; IV < NumIterations; ++IV ) { // .local.i = IV / ((NJ - J0 - 1 + 2) / 2); // .local.j = J0 + (IV % ((NJ - J0 - 1 + 2) / 2)) * 2; // // similar updates for vars in clauses (e.g. 'linear') //
// } // i = NI; // assign final values of counters // j = NJ; // // Last iteration number is (I1 * I2 * ... In) - 1, where I1, I2 ... In are // the iteration counts of the collapsed for loops. // Precondition tests if there is at least one iteration (all conditions are // true). auto PreCond = ExprResult(IterSpaces[0].PreCond); auto N0 = IterSpaces[0].NumIterations; ExprResult LastIteration32 = WidenIterationCount( 32 /* Bits */, SemaRef.PerformImplicitConversion( N0->IgnoreImpCasts(), N0->getType(), Sema::AA_Converting, /*AllowExplicit=*/true) .get(), SemaRef); ExprResult LastIteration64 = WidenIterationCount( 64 /* Bits */, SemaRef.PerformImplicitConversion( N0->IgnoreImpCasts(), N0->getType(), Sema::AA_Converting, /*AllowExplicit=*/true) .get(), SemaRef); if (!LastIteration32.isUsable() || !LastIteration64.isUsable()) return NestedLoopCount; auto &C = SemaRef.Context; bool AllCountsNeedLessThan32Bits = C.getTypeSize(N0->getType()) < 32; Scope *CurScope = DSA.getCurScope(); for (unsigned Cnt = 1; Cnt < NestedLoopCount; ++Cnt) { if (PreCond.isUsable()) { PreCond = SemaRef.BuildBinOp(CurScope, SourceLocation(), BO_LAnd, PreCond.get(), IterSpaces[Cnt].PreCond); } auto N = IterSpaces[Cnt].NumIterations; AllCountsNeedLessThan32Bits &= C.getTypeSize(N->getType()) < 32; if (LastIteration32.isUsable()) LastIteration32 = SemaRef.BuildBinOp( CurScope, SourceLocation(), BO_Mul, LastIteration32.get(), SemaRef.PerformImplicitConversion(N->IgnoreImpCasts(), N->getType(), Sema::AA_Converting, /*AllowExplicit=*/true) .get()); if (LastIteration64.isUsable()) LastIteration64 = SemaRef.BuildBinOp( CurScope, SourceLocation(), BO_Mul, LastIteration64.get(), SemaRef.PerformImplicitConversion(N->IgnoreImpCasts(), N->getType(), Sema::AA_Converting, /*AllowExplicit=*/true) .get()); } // Choose either the 32-bit or 64-bit version. ExprResult LastIteration = LastIteration64; if (LastIteration32.isUsable() && C.getTypeSize(LastIteration32.get()->getType()) == 32 && (AllCountsNeedLessThan32Bits || NestedLoopCount == 1 || FitsInto( 32 /* Bits */, LastIteration32.get()->getType()->hasSignedIntegerRepresentation(), LastIteration64.get(), SemaRef))) LastIteration = LastIteration32; QualType VType = LastIteration.get()->getType(); QualType RealVType = VType; QualType StrideVType = VType; if (isOpenMPTaskLoopDirective(DKind)) { VType = SemaRef.Context.getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/0); StrideVType = SemaRef.Context.getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/1); } if (!LastIteration.isUsable()) return 0; // Save the number of iterations. ExprResult NumIterations = LastIteration; { LastIteration = SemaRef.BuildBinOp( CurScope, SourceLocation(), BO_Sub, LastIteration.get(), SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get()); if (!LastIteration.isUsable()) return 0; } // Calculate the last iteration number beforehand instead of doing this on // each iteration. Do not do this if the number of iterations may be kfold-ed. llvm::APSInt Result; bool IsConstant = LastIteration.get()->isIntegerConstantExpr(Result, SemaRef.Context); ExprResult CalcLastIteration; if (!IsConstant) { ExprResult SaveRef = tryBuildCapture(SemaRef, LastIteration.get(), Captures); LastIteration = SaveRef; // Prepare SaveRef + 1. NumIterations = SemaRef.BuildBinOp( CurScope, SourceLocation(), BO_Add, SaveRef.get(), SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get()); if (!NumIterations.isUsable()) return 0; } SourceLocation InitLoc = IterSpaces[0].InitSrcRange.getBegin(); // Build variables passed into runtime, nesessary for worksharing directives. ExprResult LB, UB, IL, ST, EUB, PrevLB, PrevUB; if (isOpenMPWorksharingDirective(DKind) || isOpenMPTaskLoopDirective(DKind) || isOpenMPDistributeDirective(DKind)) { // Lower bound variable, initialized with zero. VarDecl *LBDecl = buildVarDecl(SemaRef, InitLoc, VType, ".omp.lb"); LB = buildDeclRefExpr(SemaRef, LBDecl, VType, InitLoc); SemaRef.AddInitializerToDecl( LBDecl, SemaRef.ActOnIntegerConstant(InitLoc, 0).get(), /*DirectInit*/ false, /*TypeMayContainAuto*/ false); // Upper bound variable, initialized with last iteration number. VarDecl *UBDecl = buildVarDecl(SemaRef, InitLoc, VType, ".omp.ub"); UB = buildDeclRefExpr(SemaRef, UBDecl, VType, InitLoc); SemaRef.AddInitializerToDecl(UBDecl, LastIteration.get(), /*DirectInit*/ false, /*TypeMayContainAuto*/ false); // A 32-bit variable-flag where runtime returns 1 for the last iteration. // This will be used to implement clause 'lastprivate'. QualType Int32Ty = SemaRef.Context.getIntTypeForBitwidth(32, true); VarDecl *ILDecl = buildVarDecl(SemaRef, InitLoc, Int32Ty, ".omp.is_last"); IL = buildDeclRefExpr(SemaRef, ILDecl, Int32Ty, InitLoc); SemaRef.AddInitializerToDecl( ILDecl, SemaRef.ActOnIntegerConstant(InitLoc, 0).get(), /*DirectInit*/ false, /*TypeMayContainAuto*/ false); // Stride variable returned by runtime (we initialize it to 1 by default). VarDecl *STDecl = buildVarDecl(SemaRef, InitLoc, StrideVType, ".omp.stride"); ST = buildDeclRefExpr(SemaRef, STDecl, StrideVType, InitLoc); SemaRef.AddInitializerToDecl( STDecl, SemaRef.ActOnIntegerConstant(InitLoc, 1).get(), /*DirectInit*/ false, /*TypeMayContainAuto*/ false); // Build expression: UB = min(UB, LastIteration) // It is nesessary for CodeGen of directives with static scheduling. ExprResult IsUBGreater = SemaRef.BuildBinOp(CurScope, InitLoc, BO_GT, UB.get(), LastIteration.get()); ExprResult CondOp = SemaRef.ActOnConditionalOp( InitLoc, InitLoc, IsUBGreater.get(), LastIteration.get(), UB.get()); EUB = SemaRef.BuildBinOp(CurScope, InitLoc, BO_Assign, UB.get(), CondOp.get()); EUB = SemaRef.ActOnFinishFullExpr(EUB.get()); // If we have a combined directive that combines 'distribute', 'for' or // 'simd' we need to be able to access the bounds of the schedule of the // enclosing region. E.g. in 'distribute parallel for' the bounds obtained // by scheduling 'distribute' have to be passed to the schedule of 'for'. if (isOpenMPLoopBoundSharingDirective(DKind)) { auto *CD = cast
(AStmt)->getCapturedDecl(); // We expect to have at least 2 more parameters than the 'parallel' // directive does - the lower and upper bounds of the previous schedule. assert(CD->getNumParams() >= 4 && "Unexpected number of parameters in loop combined directive"); // Set the proper type for the bounds given what we learned from the // enclosed loops. auto *PrevLBDecl = CD->getParam(/*PrevLB=*/2); auto *PrevUBDecl = CD->getParam(/*PrevUB=*/3); // Previous lower and upper bounds are obtained from the region // parameters. PrevLB = buildDeclRefExpr(SemaRef, PrevLBDecl, PrevLBDecl->getType(), InitLoc); PrevUB = buildDeclRefExpr(SemaRef, PrevUBDecl, PrevUBDecl->getType(), InitLoc); } } // Build the iteration variable and its initialization before loop. ExprResult IV; ExprResult Init; { VarDecl *IVDecl = buildVarDecl(SemaRef, InitLoc, RealVType, ".omp.iv"); IV = buildDeclRefExpr(SemaRef, IVDecl, RealVType, InitLoc); Expr *RHS = (isOpenMPWorksharingDirective(DKind) || isOpenMPTaskLoopDirective(DKind) || isOpenMPDistributeDirective(DKind)) ? LB.get() : SemaRef.ActOnIntegerConstant(SourceLocation(), 0).get(); Init = SemaRef.BuildBinOp(CurScope, InitLoc, BO_Assign, IV.get(), RHS); Init = SemaRef.ActOnFinishFullExpr(Init.get()); } // Loop condition (IV < NumIterations) or (IV <= UB) for worksharing loops. SourceLocation CondLoc; ExprResult Cond = (isOpenMPWorksharingDirective(DKind) || isOpenMPTaskLoopDirective(DKind) || isOpenMPDistributeDirective(DKind)) ? SemaRef.BuildBinOp(CurScope, CondLoc, BO_LE, IV.get(), UB.get()) : SemaRef.BuildBinOp(CurScope, CondLoc, BO_LT, IV.get(), NumIterations.get()); // Loop increment (IV = IV + 1) SourceLocation IncLoc; ExprResult Inc = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, IV.get(), SemaRef.ActOnIntegerConstant(IncLoc, 1).get()); if (!Inc.isUsable()) return 0; Inc = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, IV.get(), Inc.get()); Inc = SemaRef.ActOnFinishFullExpr(Inc.get()); if (!Inc.isUsable()) return 0; // Increments for worksharing loops (LB = LB + ST; UB = UB + ST). // Used for directives with static scheduling. ExprResult NextLB, NextUB; if (isOpenMPWorksharingDirective(DKind) || isOpenMPTaskLoopDirective(DKind) || isOpenMPDistributeDirective(DKind)) { // LB + ST NextLB = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, LB.get(), ST.get()); if (!NextLB.isUsable()) return 0; // LB = LB + ST NextLB = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, LB.get(), NextLB.get()); NextLB = SemaRef.ActOnFinishFullExpr(NextLB.get()); if (!NextLB.isUsable()) return 0; // UB + ST NextUB = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, UB.get(), ST.get()); if (!NextUB.isUsable()) return 0; // UB = UB + ST NextUB = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, UB.get(), NextUB.get()); NextUB = SemaRef.ActOnFinishFullExpr(NextUB.get()); if (!NextUB.isUsable()) return 0; } // Build updates and final values of the loop counters. bool HasErrors = false; Built.Counters.resize(NestedLoopCount); Built.Inits.resize(NestedLoopCount); Built.Updates.resize(NestedLoopCount); Built.Finals.resize(NestedLoopCount); SmallVector
LoopMultipliers; { ExprResult Div; // Go from inner nested loop to outer. for (int Cnt = NestedLoopCount - 1; Cnt >= 0; --Cnt) { LoopIterationSpace &IS = IterSpaces[Cnt]; SourceLocation UpdLoc = IS.IncSrcRange.getBegin(); // Build: Iter = (IV / Div) % IS.NumIters // where Div is product of previous iterations' IS.NumIters. ExprResult Iter; if (Div.isUsable()) { Iter = SemaRef.BuildBinOp(CurScope, UpdLoc, BO_Div, IV.get(), Div.get()); } else { Iter = IV; assert((Cnt == (int)NestedLoopCount - 1) && "unusable div expected on first iteration only"); } if (Cnt != 0 && Iter.isUsable()) Iter = SemaRef.BuildBinOp(CurScope, UpdLoc, BO_Rem, Iter.get(), IS.NumIterations); if (!Iter.isUsable()) { HasErrors = true; break; } // Build update: IS.CounterVar(Private) = IS.Start + Iter * IS.Step auto *VD = cast
(cast
(IS.CounterVar)->getDecl()); auto *CounterVar = buildDeclRefExpr(SemaRef, VD, IS.CounterVar->getType(), IS.CounterVar->getExprLoc(), /*RefersToCapture=*/true); ExprResult Init = BuildCounterInit(SemaRef, CurScope, UpdLoc, CounterVar, IS.CounterInit, Captures); if (!Init.isUsable()) { HasErrors = true; break; } ExprResult Update = BuildCounterUpdate( SemaRef, CurScope, UpdLoc, CounterVar, IS.CounterInit, Iter, IS.CounterStep, IS.Subtract, &Captures); if (!Update.isUsable()) { HasErrors = true; break; } // Build final: IS.CounterVar = IS.Start + IS.NumIters * IS.Step ExprResult Final = BuildCounterUpdate( SemaRef, CurScope, UpdLoc, CounterVar, IS.CounterInit, IS.NumIterations, IS.CounterStep, IS.Subtract, &Captures); if (!Final.isUsable()) { HasErrors = true; break; } // Build Div for the next iteration: Div <- Div * IS.NumIters if (Cnt != 0) { if (Div.isUnset()) Div = IS.NumIterations; else Div = SemaRef.BuildBinOp(CurScope, UpdLoc, BO_Mul, Div.get(), IS.NumIterations); // Add parentheses (for debugging purposes only). if (Div.isUsable()) Div = tryBuildCapture(SemaRef, Div.get(), Captures); if (!Div.isUsable()) { HasErrors = true; break; } LoopMultipliers.push_back(Div.get()); } if (!Update.isUsable() || !Final.isUsable()) { HasErrors = true; break; } // Save results Built.Counters[Cnt] = IS.CounterVar; Built.PrivateCounters[Cnt] = IS.PrivateCounterVar; Built.Inits[Cnt] = Init.get(); Built.Updates[Cnt] = Update.get(); Built.Finals[Cnt] = Final.get(); } } if (HasErrors) return 0; // Save results Built.IterationVarRef = IV.get(); Built.LastIteration = LastIteration.get(); Built.NumIterations = NumIterations.get(); Built.CalcLastIteration = SemaRef.ActOnFinishFullExpr(CalcLastIteration.get()).get(); Built.PreCond = PreCond.get(); Built.PreInits = buildPreInits(C, Captures); Built.Cond = Cond.get(); Built.Init = Init.get(); Built.Inc = Inc.get(); Built.LB = LB.get(); Built.UB = UB.get(); Built.IL = IL.get(); Built.ST = ST.get(); Built.EUB = EUB.get(); Built.NLB = NextLB.get(); Built.NUB = NextUB.get(); Built.PrevLB = PrevLB.get(); Built.PrevUB = PrevUB.get(); Expr *CounterVal = SemaRef.DefaultLvalueConversion(IV.get()).get(); // Fill data for doacross depend clauses. for (auto Pair : DSA.getDoacrossDependClauses()) { if (Pair.first->getDependencyKind() == OMPC_DEPEND_source) Pair.first->setCounterValue(CounterVal); else { if (NestedLoopCount != Pair.second.size() || NestedLoopCount != LoopMultipliers.size() + 1) { // Erroneous case - clause has some problems. Pair.first->setCounterValue(CounterVal); continue; } assert(Pair.first->getDependencyKind() == OMPC_DEPEND_sink); auto I = Pair.second.rbegin(); auto IS = IterSpaces.rbegin(); auto ILM = LoopMultipliers.rbegin(); Expr *UpCounterVal = CounterVal; Expr *Multiplier = nullptr; for (int Cnt = NestedLoopCount - 1; Cnt >= 0; --Cnt) { if (I->first) { assert(IS->CounterStep); Expr *NormalizedOffset = SemaRef .BuildBinOp(CurScope, I->first->getExprLoc(), BO_Div, I->first, IS->CounterStep) .get(); if (Multiplier) { NormalizedOffset = SemaRef .BuildBinOp(CurScope, I->first->getExprLoc(), BO_Mul, NormalizedOffset, Multiplier) .get(); } assert(I->second == OO_Plus || I->second == OO_Minus); BinaryOperatorKind BOK = (I->second == OO_Plus) ? BO_Add : BO_Sub; UpCounterVal = SemaRef.BuildBinOp(CurScope, I->first->getExprLoc(), BOK, UpCounterVal, NormalizedOffset).get(); } Multiplier = *ILM; ++I; ++IS; ++ILM; } Pair.first->setCounterValue(UpCounterVal); } } return NestedLoopCount; } static Expr *getCollapseNumberExpr(ArrayRef
Clauses) { auto CollapseClauses = OMPExecutableDirective::getClausesOfKind
(Clauses); if (CollapseClauses.begin() != CollapseClauses.end()) return (*CollapseClauses.begin())->getNumForLoops(); return nullptr; } static Expr *getOrderedNumberExpr(ArrayRef
Clauses) { auto OrderedClauses = OMPExecutableDirective::getClausesOfKind
(Clauses); if (OrderedClauses.begin() != OrderedClauses.end()) return (*OrderedClauses.begin())->getNumForLoops(); return nullptr; } static bool checkSimdlenSafelenValues(Sema &S, const Expr *Simdlen, const Expr *Safelen) { llvm::APSInt SimdlenRes, SafelenRes; if (Simdlen->isValueDependent() || Simdlen->isTypeDependent() || Simdlen->isInstantiationDependent() || Simdlen->containsUnexpandedParameterPack()) return false; if (Safelen->isValueDependent() || Safelen->isTypeDependent() || Safelen->isInstantiationDependent() || Safelen->containsUnexpandedParameterPack()) return false; Simdlen->EvaluateAsInt(SimdlenRes, S.Context); Safelen->EvaluateAsInt(SafelenRes, S.Context); // OpenMP 4.1 [2.8.1, simd Construct, Restrictions] // If both simdlen and safelen clauses are specified, the value of the simdlen // parameter must be less than or equal to the value of the safelen parameter. if (SimdlenRes > SafelenRes) { S.Diag(Simdlen->getExprLoc(), diag::err_omp_wrong_simdlen_safelen_values) << Simdlen->getSourceRange() << Safelen->getSourceRange(); return true; } return false; } StmtResult Sema::ActOnOpenMPSimdDirective( ArrayRef
Clauses, Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc, llvm::DenseMap
&VarsWithImplicitDSA) { if (!AStmt) return StmtError(); assert(isa
(AStmt) && "Captured statement expected"); OMPLoopDirective::HelperExprs B; // In presence of clause 'collapse' or 'ordered' with number of loops, it will // define the nested loops number. unsigned NestedLoopCount = CheckOpenMPLoop( OMPD_simd, getCollapseNumberExpr(Clauses), getOrderedNumberExpr(Clauses), AStmt, *this, *DSAStack, VarsWithImplicitDSA, B); if (NestedLoopCount == 0) return StmtError(); assert((CurContext->isDependentContext() || B.builtAll()) && "omp simd loop exprs were not built"); if (!CurContext->isDependentContext()) { // Finalize the clauses that need pre-built expressions for CodeGen. for (auto C : Clauses) { if (auto LC = dyn_cast
(C)) if (FinishOpenMPLinearClause(*LC, cast
(B.IterationVarRef), B.NumIterations, *this, CurScope, DSAStack)) return StmtError(); } } // OpenMP 4.1 [2.8.1, simd Construct, Restrictions] // If both simdlen and safelen clauses are specified, the value of the simdlen // parameter must be less than or equal to the value of the safelen parameter. OMPSafelenClause *Safelen = nullptr; OMPSimdlenClause *Simdlen = nullptr; for (auto *Clause : Clauses) { if (Clause->getClauseKind() == OMPC_safelen) Safelen = cast
(Clause); else if (Clause->getClauseKind() == OMPC_simdlen) Simdlen = cast
(Clause); if (Safelen && Simdlen) break; } if (Simdlen && Safelen && checkSimdlenSafelenValues(*this, Simdlen->getSimdlen(), Safelen->getSafelen())) return StmtError(); getCurFunction()->setHasBranchProtectedScope(); return OMPSimdDirective::Create(Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B); } StmtResult Sema::ActOnOpenMPForDirective( ArrayRef
Clauses, Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc, llvm::DenseMap
&VarsWithImplicitDSA) { if (!AStmt) return StmtError(); assert(isa
(AStmt) && "Captured statement expected"); OMPLoopDirective::HelperExprs B; // In presence of clause 'collapse' or 'ordered' with number of loops, it will // define the nested loops number. unsigned NestedLoopCount = CheckOpenMPLoop( OMPD_for, getCollapseNumberExpr(Clauses), getOrderedNumberExpr(Clauses), AStmt, *this, *DSAStack, VarsWithImplicitDSA, B); if (NestedLoopCount == 0) return StmtError(); assert((CurContext->isDependentContext() || B.builtAll()) && "omp for loop exprs were not built"); if (!CurContext->isDependentContext()) { // Finalize the clauses that need pre-built expressions for CodeGen. for (auto C : Clauses) { if (auto LC = dyn_cast
(C)) if (FinishOpenMPLinearClause(*LC, cast
(B.IterationVarRef), B.NumIterations, *this, CurScope, DSAStack)) return StmtError(); } } getCurFunction()->setHasBranchProtectedScope(); return OMPForDirective::Create(Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B, DSAStack->isCancelRegion()); } StmtResult Sema::ActOnOpenMPForSimdDirective( ArrayRef
Clauses, Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc, llvm::DenseMap
&VarsWithImplicitDSA) { if (!AStmt) return StmtError(); assert(isa
(AStmt) && "Captured statement expected"); OMPLoopDirective::HelperExprs B; // In presence of clause 'collapse' or 'ordered' with number of loops, it will // define the nested loops number. unsigned NestedLoopCount = CheckOpenMPLoop(OMPD_for_simd, getCollapseNumberExpr(Clauses), getOrderedNumberExpr(Clauses), AStmt, *this, *DSAStack, VarsWithImplicitDSA, B); if (NestedLoopCount == 0) return StmtError(); assert((CurContext->isDependentContext() || B.builtAll()) && "omp for simd loop exprs were not built"); if (!CurContext->isDependentContext()) { // Finalize the clauses that need pre-built expressions for CodeGen. for (auto C : Clauses) { if (auto LC = dyn_cast
(C)) if (FinishOpenMPLinearClause(*LC, cast
(B.IterationVarRef), B.NumIterations, *this, CurScope, DSAStack)) return StmtError(); } } // OpenMP 4.1 [2.8.1, simd Construct, Restrictions] // If both simdlen and safelen clauses are specified, the value of the simdlen // parameter must be less than or equal to the value of the safelen parameter. OMPSafelenClause *Safelen = nullptr; OMPSimdlenClause *Simdlen = nullptr; for (auto *Clause : Clauses) { if (Clause->getClauseKind() == OMPC_safelen) Safelen = cast
(Clause); else if (Clause->getClauseKind() == OMPC_simdlen) Simdlen = cast
(Clause); if (Safelen && Simdlen) break; } if (Simdlen && Safelen && checkSimdlenSafelenValues(*this, Simdlen->getSimdlen(), Safelen->getSafelen())) return StmtError(); getCurFunction()->setHasBranchProtectedScope(); return OMPForSimdDirective::Create(Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B); } StmtResult Sema::ActOnOpenMPSectionsDirective(ArrayRef
Clauses, Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc) { if (!AStmt) return StmtError(); assert(isa
(AStmt) && "Captured statement expected"); auto BaseStmt = AStmt; while (CapturedStmt *CS = dyn_cast_or_null
(BaseStmt)) BaseStmt = CS->getCapturedStmt(); if (auto C = dyn_cast_or_null
(BaseStmt)) { auto S = C->children(); if (S.begin() == S.end()) return StmtError(); // All associated statements must be '#pragma omp section' except for // the first one. for (Stmt *SectionStmt : llvm::make_range(std::next(S.begin()), S.end())) { if (!SectionStmt || !isa
(SectionStmt)) { if (SectionStmt) Diag(SectionStmt->getLocStart(), diag::err_omp_sections_substmt_not_section); return StmtError(); } cast
(SectionStmt) ->setHasCancel(DSAStack->isCancelRegion()); } } else { Diag(AStmt->getLocStart(), diag::err_omp_sections_not_compound_stmt); return StmtError(); } getCurFunction()->setHasBranchProtectedScope(); return OMPSectionsDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt, DSAStack->isCancelRegion()); } StmtResult Sema::ActOnOpenMPSectionDirective(Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc) { if (!AStmt) return StmtError(); assert(isa
(AStmt) && "Captured statement expected"); getCurFunction()->setHasBranchProtectedScope(); DSAStack->setParentCancelRegion(DSAStack->isCancelRegion()); return OMPSectionDirective::Create(Context, StartLoc, EndLoc, AStmt, DSAStack->isCancelRegion()); } StmtResult Sema::ActOnOpenMPSingleDirective(ArrayRef
Clauses, Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc) { if (!AStmt) return StmtError(); assert(isa
(AStmt) && "Captured statement expected"); getCurFunction()->setHasBranchProtectedScope(); // OpenMP [2.7.3, single Construct, Restrictions] // The copyprivate clause must not be used with the nowait clause. OMPClause *Nowait = nullptr; OMPClause *Copyprivate = nullptr; for (auto *Clause : Clauses) { if (Clause->getClauseKind() == OMPC_nowait) Nowait = Clause; else if (Clause->getClauseKind() == OMPC_copyprivate) Copyprivate = Clause; if (Copyprivate && Nowait) { Diag(Copyprivate->getLocStart(), diag::err_omp_single_copyprivate_with_nowait); Diag(Nowait->getLocStart(), diag::note_omp_nowait_clause_here); return StmtError(); } } return OMPSingleDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt); } StmtResult Sema::ActOnOpenMPMasterDirective(Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc) { if (!AStmt) return StmtError(); assert(isa
(AStmt) && "Captured statement expected"); getCurFunction()->setHasBranchProtectedScope(); return OMPMasterDirective::Create(Context, StartLoc, EndLoc, AStmt); } StmtResult Sema::ActOnOpenMPCriticalDirective( const DeclarationNameInfo &DirName, ArrayRef
Clauses, Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc) { if (!AStmt) return StmtError(); assert(isa
(AStmt) && "Captured statement expected"); bool ErrorFound = false; llvm::APSInt Hint; SourceLocation HintLoc; bool DependentHint = false; for (auto *C : Clauses) { if (C->getClauseKind() == OMPC_hint) { if (!DirName.getName()) { Diag(C->getLocStart(), diag::err_omp_hint_clause_no_name); ErrorFound = true; } Expr *E = cast
(C)->getHint(); if (E->isTypeDependent() || E->isValueDependent() || E->isInstantiationDependent()) DependentHint = true; else { Hint = E->EvaluateKnownConstInt(Context); HintLoc = C->getLocStart(); } } } if (ErrorFound) return StmtError(); auto Pair = DSAStack->getCriticalWithHint(DirName); if (Pair.first && DirName.getName() && !DependentHint) { if (llvm::APSInt::compareValues(Hint, Pair.second) != 0) { Diag(StartLoc, diag::err_omp_critical_with_hint); if (HintLoc.isValid()) { Diag(HintLoc, diag::note_omp_critical_hint_here) << 0 << Hint.toString(/*Radix=*/10, /*Signed=*/false); } else Diag(StartLoc, diag::note_omp_critical_no_hint) << 0; if (auto *C = Pair.first->getSingleClause
()) { Diag(C->getLocStart(), diag::note_omp_critical_hint_here) << 1 << C->getHint()->EvaluateKnownConstInt(Context).toString( /*Radix=*/10, /*Signed=*/false); } else Diag(Pair.first->getLocStart(), diag::note_omp_critical_no_hint) << 1; } } getCurFunction()->setHasBranchProtectedScope(); auto *Dir = OMPCriticalDirective::Create(Context, DirName, StartLoc, EndLoc, Clauses, AStmt); if (!Pair.first && DirName.getName() && !DependentHint) DSAStack->addCriticalWithHint(Dir, Hint); return Dir; } StmtResult Sema::ActOnOpenMPParallelForDirective( ArrayRef
Clauses, Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc, llvm::DenseMap
&VarsWithImplicitDSA) { if (!AStmt) return StmtError(); CapturedStmt *CS = cast
(AStmt); // 1.2.2 OpenMP Language Terminology // Structured block - An executable statement with a single entry at the // top and a single exit at the bottom. // The point of exit cannot be a branch out of the structured block. // longjmp() and throw() must not violate the entry/exit criteria. CS->getCapturedDecl()->setNothrow(); OMPLoopDirective::HelperExprs B; // In presence of clause 'collapse' or 'ordered' with number of loops, it will // define the nested loops number. unsigned NestedLoopCount = CheckOpenMPLoop(OMPD_parallel_for, getCollapseNumberExpr(Clauses), getOrderedNumberExpr(Clauses), AStmt, *this, *DSAStack, VarsWithImplicitDSA, B); if (NestedLoopCount == 0) return StmtError(); assert((CurContext->isDependentContext() || B.builtAll()) && "omp parallel for loop exprs were not built"); if (!CurContext->isDependentContext()) { // Finalize the clauses that need pre-built expressions for CodeGen. for (auto C : Clauses) { if (auto LC = dyn_cast
(C)) if (FinishOpenMPLinearClause(*LC, cast
(B.IterationVarRef), B.NumIterations, *this, CurScope, DSAStack)) return StmtError(); } } getCurFunction()->setHasBranchProtectedScope(); return OMPParallelForDirective::Create(Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B, DSAStack->isCancelRegion()); } StmtResult Sema::ActOnOpenMPParallelForSimdDirective( ArrayRef
Clauses, Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc, llvm::DenseMap
&VarsWithImplicitDSA) { if (!AStmt) return StmtError(); CapturedStmt *CS = cast
(AStmt); // 1.2.2 OpenMP Language Terminology // Structured block - An executable statement with a single entry at the // top and a single exit at the bottom. // The point of exit cannot be a branch out of the structured block. // longjmp() and throw() must not violate the entry/exit criteria. CS->getCapturedDecl()->setNothrow(); OMPLoopDirective::HelperExprs B; // In presence of clause 'collapse' or 'ordered' with number of loops, it will // define the nested loops number. unsigned NestedLoopCount = CheckOpenMPLoop(OMPD_parallel_for_simd, getCollapseNumberExpr(Clauses), getOrderedNumberExpr(Clauses), AStmt, *this, *DSAStack, VarsWithImplicitDSA, B); if (NestedLoopCount == 0) return StmtError(); if (!CurContext->isDependentContext()) { // Finalize the clauses that need pre-built expressions for CodeGen. for (auto C : Clauses) { if (auto LC = dyn_cast
(C)) if (FinishOpenMPLinearClause(*LC, cast
(B.IterationVarRef), B.NumIterations, *this, CurScope, DSAStack)) return StmtError(); } } // OpenMP 4.1 [2.8.1, simd Construct, Restrictions] // If both simdlen and safelen clauses are specified, the value of the simdlen // parameter must be less than or equal to the value of the safelen parameter. OMPSafelenClause *Safelen = nullptr; OMPSimdlenClause *Simdlen = nullptr; for (auto *Clause : Clauses) { if (Clause->getClauseKind() == OMPC_safelen) Safelen = cast
(Clause); else if (Clause->getClauseKind() == OMPC_simdlen) Simdlen = cast
(Clause); if (Safelen && Simdlen) break; } if (Simdlen && Safelen && checkSimdlenSafelenValues(*this, Simdlen->getSimdlen(), Safelen->getSafelen())) return StmtError(); getCurFunction()->setHasBranchProtectedScope(); return OMPParallelForSimdDirective::Create( Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B); } StmtResult Sema::ActOnOpenMPParallelSectionsDirective(ArrayRef