1 //===--- SemaOpenMP.cpp - Semantic Analysis for OpenMP constructs ---------===// 2 // 3 // The LLVM Compiler Infrastructure 4 // 5 // This file is distributed under the University of Illinois Open Source 6 // License. See LICENSE.TXT for details. 7 // 8 //===----------------------------------------------------------------------===// 9 /// \file 10 /// \brief This file implements semantic analysis for OpenMP directives and 11 /// clauses. 12 /// 13 //===----------------------------------------------------------------------===// 14 15 #include "clang/AST/ASTContext.h" 16 #include "clang/AST/Decl.h" 17 #include "clang/AST/DeclCXX.h" 18 #include "clang/AST/DeclOpenMP.h" 19 #include "clang/AST/StmtCXX.h" 20 #include "clang/AST/StmtOpenMP.h" 21 #include "clang/AST/StmtVisitor.h" 22 #include "clang/Basic/OpenMPKinds.h" 23 #include "clang/Lex/Preprocessor.h" 24 #include "clang/Sema/Initialization.h" 25 #include "clang/Sema/Lookup.h" 26 #include "clang/Sema/Scope.h" 27 #include "clang/Sema/ScopeInfo.h" 28 #include "clang/Sema/SemaInternal.h" 29 using namespace clang; 30 31 //===----------------------------------------------------------------------===// 32 // Stack of data-sharing attributes for variables 33 //===----------------------------------------------------------------------===// 34 35 namespace { 36 /// \brief Default data sharing attributes, which can be applied to directive. 37 enum DefaultDataSharingAttributes { 38 DSA_unspecified = 0, /// \brief Data sharing attribute not specified. 39 DSA_none = 1 << 0, /// \brief Default data sharing attribute 'none'. 40 DSA_shared = 1 << 1 /// \brief Default data sharing attribute 'shared'. 41 }; 42 43 template <class T> struct MatchesAny { 44 explicit MatchesAny(ArrayRef<T> Arr) : Arr(std::move(Arr)) {} 45 bool operator()(T Kind) { 46 for (auto KindEl : Arr) 47 if (KindEl == Kind) 48 return true; 49 return false; 50 } 51 52 private: 53 ArrayRef<T> Arr; 54 }; 55 struct MatchesAlways { 56 MatchesAlways() {} 57 template <class T> bool operator()(T) { return true; } 58 }; 59 60 typedef MatchesAny<OpenMPClauseKind> MatchesAnyClause; 61 typedef MatchesAny<OpenMPDirectiveKind> MatchesAnyDirective; 62 63 /// \brief Stack for tracking declarations used in OpenMP directives and 64 /// clauses and their data-sharing attributes. 65 class DSAStackTy { 66 public: 67 struct DSAVarData { 68 OpenMPDirectiveKind DKind; 69 OpenMPClauseKind CKind; 70 DeclRefExpr *RefExpr; 71 SourceLocation ImplicitDSALoc; 72 DSAVarData() 73 : DKind(OMPD_unknown), CKind(OMPC_unknown), RefExpr(nullptr), 74 ImplicitDSALoc() {} 75 }; 76 77 private: 78 struct DSAInfo { 79 OpenMPClauseKind Attributes; 80 DeclRefExpr *RefExpr; 81 }; 82 typedef llvm::SmallDenseMap<VarDecl *, DSAInfo, 64> DeclSAMapTy; 83 typedef llvm::SmallDenseMap<VarDecl *, DeclRefExpr *, 64> AlignedMapTy; 84 85 struct SharingMapTy { 86 DeclSAMapTy SharingMap; 87 AlignedMapTy AlignedMap; 88 DefaultDataSharingAttributes DefaultAttr; 89 SourceLocation DefaultAttrLoc; 90 OpenMPDirectiveKind Directive; 91 DeclarationNameInfo DirectiveName; 92 Scope *CurScope; 93 SourceLocation ConstructLoc; 94 bool OrderedRegion; 95 SourceLocation InnerTeamsRegionLoc; 96 SharingMapTy(OpenMPDirectiveKind DKind, DeclarationNameInfo Name, 97 Scope *CurScope, SourceLocation Loc) 98 : SharingMap(), AlignedMap(), DefaultAttr(DSA_unspecified), 99 Directive(DKind), DirectiveName(std::move(Name)), CurScope(CurScope), 100 ConstructLoc(Loc), OrderedRegion(false), InnerTeamsRegionLoc() {} 101 SharingMapTy() 102 : SharingMap(), AlignedMap(), DefaultAttr(DSA_unspecified), 103 Directive(OMPD_unknown), DirectiveName(), CurScope(nullptr), 104 ConstructLoc(), OrderedRegion(false), InnerTeamsRegionLoc() {} 105 }; 106 107 typedef SmallVector<SharingMapTy, 64> StackTy; 108 109 /// \brief Stack of used declaration and their data-sharing attributes. 110 StackTy Stack; 111 Sema &SemaRef; 112 113 typedef SmallVector<SharingMapTy, 8>::reverse_iterator reverse_iterator; 114 115 DSAVarData getDSA(StackTy::reverse_iterator Iter, VarDecl *D); 116 117 /// \brief Checks if the variable is a local for OpenMP region. 118 bool isOpenMPLocal(VarDecl *D, StackTy::reverse_iterator Iter); 119 120 public: 121 explicit DSAStackTy(Sema &S) : Stack(1), SemaRef(S) {} 122 123 void push(OpenMPDirectiveKind DKind, const DeclarationNameInfo &DirName, 124 Scope *CurScope, SourceLocation Loc) { 125 Stack.push_back(SharingMapTy(DKind, DirName, CurScope, Loc)); 126 Stack.back().DefaultAttrLoc = Loc; 127 } 128 129 void pop() { 130 assert(Stack.size() > 1 && "Data-sharing attributes stack is empty!"); 131 Stack.pop_back(); 132 } 133 134 /// \brief If 'aligned' declaration for given variable \a D was not seen yet, 135 /// add it and return NULL; otherwise return previous occurrence's expression 136 /// for diagnostics. 137 DeclRefExpr *addUniqueAligned(VarDecl *D, DeclRefExpr *NewDE); 138 139 /// \brief Adds explicit data sharing attribute to the specified declaration. 140 void addDSA(VarDecl *D, DeclRefExpr *E, OpenMPClauseKind A); 141 142 /// \brief Returns data sharing attributes from top of the stack for the 143 /// specified declaration. 144 DSAVarData getTopDSA(VarDecl *D, bool FromParent); 145 /// \brief Returns data-sharing attributes for the specified declaration. 146 DSAVarData getImplicitDSA(VarDecl *D, bool FromParent); 147 /// \brief Checks if the specified variables has data-sharing attributes which 148 /// match specified \a CPred predicate in any directive which matches \a DPred 149 /// predicate. 150 template <class ClausesPredicate, class DirectivesPredicate> 151 DSAVarData hasDSA(VarDecl *D, ClausesPredicate CPred, 152 DirectivesPredicate DPred, bool FromParent); 153 /// \brief Checks if the specified variables has data-sharing attributes which 154 /// match specified \a CPred predicate in any innermost directive which 155 /// matches \a DPred predicate. 156 template <class ClausesPredicate, class DirectivesPredicate> 157 DSAVarData hasInnermostDSA(VarDecl *D, ClausesPredicate CPred, 158 DirectivesPredicate DPred, 159 bool FromParent); 160 /// \brief Finds a directive which matches specified \a DPred predicate. 161 template <class NamedDirectivesPredicate> 162 bool hasDirective(NamedDirectivesPredicate DPred, bool FromParent); 163 164 /// \brief Returns currently analyzed directive. 165 OpenMPDirectiveKind getCurrentDirective() const { 166 return Stack.back().Directive; 167 } 168 /// \brief Returns parent directive. 169 OpenMPDirectiveKind getParentDirective() const { 170 if (Stack.size() > 2) 171 return Stack[Stack.size() - 2].Directive; 172 return OMPD_unknown; 173 } 174 175 /// \brief Set default data sharing attribute to none. 176 void setDefaultDSANone(SourceLocation Loc) { 177 Stack.back().DefaultAttr = DSA_none; 178 Stack.back().DefaultAttrLoc = Loc; 179 } 180 /// \brief Set default data sharing attribute to shared. 181 void setDefaultDSAShared(SourceLocation Loc) { 182 Stack.back().DefaultAttr = DSA_shared; 183 Stack.back().DefaultAttrLoc = Loc; 184 } 185 186 DefaultDataSharingAttributes getDefaultDSA() const { 187 return Stack.back().DefaultAttr; 188 } 189 SourceLocation getDefaultDSALocation() const { 190 return Stack.back().DefaultAttrLoc; 191 } 192 193 /// \brief Checks if the specified variable is a threadprivate. 194 bool isThreadPrivate(VarDecl *D) { 195 DSAVarData DVar = getTopDSA(D, false); 196 return isOpenMPThreadPrivate(DVar.CKind); 197 } 198 199 /// \brief Marks current region as ordered (it has an 'ordered' clause). 200 void setOrderedRegion(bool IsOrdered = true) { 201 Stack.back().OrderedRegion = IsOrdered; 202 } 203 /// \brief Returns true, if parent region is ordered (has associated 204 /// 'ordered' clause), false - otherwise. 205 bool isParentOrderedRegion() const { 206 if (Stack.size() > 2) 207 return Stack[Stack.size() - 2].OrderedRegion; 208 return false; 209 } 210 211 /// \brief Marks current target region as one with closely nested teams 212 /// region. 213 void setParentTeamsRegionLoc(SourceLocation TeamsRegionLoc) { 214 if (Stack.size() > 2) 215 Stack[Stack.size() - 2].InnerTeamsRegionLoc = TeamsRegionLoc; 216 } 217 /// \brief Returns true, if current region has closely nested teams region. 218 bool hasInnerTeamsRegion() const { 219 return getInnerTeamsRegionLoc().isValid(); 220 } 221 /// \brief Returns location of the nested teams region (if any). 222 SourceLocation getInnerTeamsRegionLoc() const { 223 if (Stack.size() > 1) 224 return Stack.back().InnerTeamsRegionLoc; 225 return SourceLocation(); 226 } 227 228 Scope *getCurScope() const { return Stack.back().CurScope; } 229 Scope *getCurScope() { return Stack.back().CurScope; } 230 SourceLocation getConstructLoc() { return Stack.back().ConstructLoc; } 231 }; 232 bool isParallelOrTaskRegion(OpenMPDirectiveKind DKind) { 233 return isOpenMPParallelDirective(DKind) || DKind == OMPD_task || 234 isOpenMPTeamsDirective(DKind) || DKind == OMPD_unknown; 235 } 236 } // namespace 237 238 DSAStackTy::DSAVarData DSAStackTy::getDSA(StackTy::reverse_iterator Iter, 239 VarDecl *D) { 240 DSAVarData DVar; 241 if (Iter == std::prev(Stack.rend())) { 242 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced 243 // in a region but not in construct] 244 // File-scope or namespace-scope variables referenced in called routines 245 // in the region are shared unless they appear in a threadprivate 246 // directive. 247 if (!D->isFunctionOrMethodVarDecl() && !isa<ParmVarDecl>(D)) 248 DVar.CKind = OMPC_shared; 249 250 // OpenMP [2.9.1.2, Data-sharing Attribute Rules for Variables Referenced 251 // in a region but not in construct] 252 // Variables with static storage duration that are declared in called 253 // routines in the region are shared. 254 if (D->hasGlobalStorage()) 255 DVar.CKind = OMPC_shared; 256 257 return DVar; 258 } 259 260 DVar.DKind = Iter->Directive; 261 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced 262 // in a Construct, C/C++, predetermined, p.1] 263 // Variables with automatic storage duration that are declared in a scope 264 // inside the construct are private. 265 if (isOpenMPLocal(D, Iter) && D->isLocalVarDecl() && 266 (D->getStorageClass() == SC_Auto || D->getStorageClass() == SC_None)) { 267 DVar.CKind = OMPC_private; 268 return DVar; 269 } 270 271 // Explicitly specified attributes and local variables with predetermined 272 // attributes. 273 if (Iter->SharingMap.count(D)) { 274 DVar.RefExpr = Iter->SharingMap[D].RefExpr; 275 DVar.CKind = Iter->SharingMap[D].Attributes; 276 DVar.ImplicitDSALoc = Iter->DefaultAttrLoc; 277 return DVar; 278 } 279 280 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced 281 // in a Construct, C/C++, implicitly determined, p.1] 282 // In a parallel or task construct, the data-sharing attributes of these 283 // variables are determined by the default clause, if present. 284 switch (Iter->DefaultAttr) { 285 case DSA_shared: 286 DVar.CKind = OMPC_shared; 287 DVar.ImplicitDSALoc = Iter->DefaultAttrLoc; 288 return DVar; 289 case DSA_none: 290 return DVar; 291 case DSA_unspecified: 292 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced 293 // in a Construct, implicitly determined, p.2] 294 // In a parallel construct, if no default clause is present, these 295 // variables are shared. 296 DVar.ImplicitDSALoc = Iter->DefaultAttrLoc; 297 if (isOpenMPParallelDirective(DVar.DKind) || 298 isOpenMPTeamsDirective(DVar.DKind)) { 299 DVar.CKind = OMPC_shared; 300 return DVar; 301 } 302 303 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced 304 // in a Construct, implicitly determined, p.4] 305 // In a task construct, if no default clause is present, a variable that in 306 // the enclosing context is determined to be shared by all implicit tasks 307 // bound to the current team is shared. 308 if (DVar.DKind == OMPD_task) { 309 DSAVarData DVarTemp; 310 for (StackTy::reverse_iterator I = std::next(Iter), 311 EE = std::prev(Stack.rend()); 312 I != EE; ++I) { 313 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables 314 // Referenced 315 // in a Construct, implicitly determined, p.6] 316 // In a task construct, if no default clause is present, a variable 317 // whose data-sharing attribute is not determined by the rules above is 318 // firstprivate. 319 DVarTemp = getDSA(I, D); 320 if (DVarTemp.CKind != OMPC_shared) { 321 DVar.RefExpr = nullptr; 322 DVar.DKind = OMPD_task; 323 DVar.CKind = OMPC_firstprivate; 324 return DVar; 325 } 326 if (isParallelOrTaskRegion(I->Directive)) 327 break; 328 } 329 DVar.DKind = OMPD_task; 330 DVar.CKind = 331 (DVarTemp.CKind == OMPC_unknown) ? OMPC_firstprivate : OMPC_shared; 332 return DVar; 333 } 334 } 335 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced 336 // in a Construct, implicitly determined, p.3] 337 // For constructs other than task, if no default clause is present, these 338 // variables inherit their data-sharing attributes from the enclosing 339 // context. 340 return getDSA(std::next(Iter), D); 341 } 342 343 DeclRefExpr *DSAStackTy::addUniqueAligned(VarDecl *D, DeclRefExpr *NewDE) { 344 assert(Stack.size() > 1 && "Data sharing attributes stack is empty"); 345 auto It = Stack.back().AlignedMap.find(D); 346 if (It == Stack.back().AlignedMap.end()) { 347 assert(NewDE && "Unexpected nullptr expr to be added into aligned map"); 348 Stack.back().AlignedMap[D] = NewDE; 349 return nullptr; 350 } else { 351 assert(It->second && "Unexpected nullptr expr in the aligned map"); 352 return It->second; 353 } 354 return nullptr; 355 } 356 357 void DSAStackTy::addDSA(VarDecl *D, DeclRefExpr *E, OpenMPClauseKind A) { 358 if (A == OMPC_threadprivate) { 359 Stack[0].SharingMap[D].Attributes = A; 360 Stack[0].SharingMap[D].RefExpr = E; 361 } else { 362 assert(Stack.size() > 1 && "Data-sharing attributes stack is empty"); 363 Stack.back().SharingMap[D].Attributes = A; 364 Stack.back().SharingMap[D].RefExpr = E; 365 } 366 } 367 368 bool DSAStackTy::isOpenMPLocal(VarDecl *D, StackTy::reverse_iterator Iter) { 369 if (Stack.size() > 2) { 370 reverse_iterator I = Iter, E = std::prev(Stack.rend()); 371 Scope *TopScope = nullptr; 372 while (I != E && !isParallelOrTaskRegion(I->Directive)) { 373 ++I; 374 } 375 if (I == E) 376 return false; 377 TopScope = I->CurScope ? I->CurScope->getParent() : nullptr; 378 Scope *CurScope = getCurScope(); 379 while (CurScope != TopScope && !CurScope->isDeclScope(D)) { 380 CurScope = CurScope->getParent(); 381 } 382 return CurScope != TopScope; 383 } 384 return false; 385 } 386 387 DSAStackTy::DSAVarData DSAStackTy::getTopDSA(VarDecl *D, bool FromParent) { 388 DSAVarData DVar; 389 390 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced 391 // in a Construct, C/C++, predetermined, p.1] 392 // Variables appearing in threadprivate directives are threadprivate. 393 if (D->getTLSKind() != VarDecl::TLS_None) { 394 DVar.CKind = OMPC_threadprivate; 395 return DVar; 396 } 397 if (Stack[0].SharingMap.count(D)) { 398 DVar.RefExpr = Stack[0].SharingMap[D].RefExpr; 399 DVar.CKind = OMPC_threadprivate; 400 return DVar; 401 } 402 403 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced 404 // in a Construct, C/C++, predetermined, p.1] 405 // Variables with automatic storage duration that are declared in a scope 406 // inside the construct are private. 407 OpenMPDirectiveKind Kind = 408 FromParent ? getParentDirective() : getCurrentDirective(); 409 auto StartI = std::next(Stack.rbegin()); 410 auto EndI = std::prev(Stack.rend()); 411 if (FromParent && StartI != EndI) { 412 StartI = std::next(StartI); 413 } 414 if (!isParallelOrTaskRegion(Kind)) { 415 if (isOpenMPLocal(D, StartI) && 416 ((D->isLocalVarDecl() && (D->getStorageClass() == SC_Auto || 417 D->getStorageClass() == SC_None)) || 418 isa<ParmVarDecl>(D))) { 419 DVar.CKind = OMPC_private; 420 return DVar; 421 } 422 } 423 424 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced 425 // in a Construct, C/C++, predetermined, p.4] 426 // Static data members are shared. 427 if (D->isStaticDataMember()) { 428 // Variables with const-qualified type having no mutable member may be 429 // listed in a firstprivate clause, even if they are static data members. 430 DSAVarData DVarTemp = hasDSA(D, MatchesAnyClause(OMPC_firstprivate), 431 MatchesAlways(), FromParent); 432 if (DVarTemp.CKind == OMPC_firstprivate && DVarTemp.RefExpr) 433 return DVar; 434 435 DVar.CKind = OMPC_shared; 436 return DVar; 437 } 438 439 QualType Type = D->getType().getNonReferenceType().getCanonicalType(); 440 bool IsConstant = Type.isConstant(SemaRef.getASTContext()); 441 while (Type->isArrayType()) { 442 QualType ElemType = cast<ArrayType>(Type.getTypePtr())->getElementType(); 443 Type = ElemType.getNonReferenceType().getCanonicalType(); 444 } 445 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced 446 // in a Construct, C/C++, predetermined, p.6] 447 // Variables with const qualified type having no mutable member are 448 // shared. 449 CXXRecordDecl *RD = 450 SemaRef.getLangOpts().CPlusPlus ? Type->getAsCXXRecordDecl() : nullptr; 451 if (IsConstant && 452 !(SemaRef.getLangOpts().CPlusPlus && RD && RD->hasMutableFields())) { 453 // Variables with const-qualified type having no mutable member may be 454 // listed in a firstprivate clause, even if they are static data members. 455 DSAVarData DVarTemp = hasDSA(D, MatchesAnyClause(OMPC_firstprivate), 456 MatchesAlways(), FromParent); 457 if (DVarTemp.CKind == OMPC_firstprivate && DVarTemp.RefExpr) 458 return DVar; 459 460 DVar.CKind = OMPC_shared; 461 return DVar; 462 } 463 464 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced 465 // in a Construct, C/C++, predetermined, p.7] 466 // Variables with static storage duration that are declared in a scope 467 // inside the construct are shared. 468 if (D->isStaticLocal()) { 469 DVar.CKind = OMPC_shared; 470 return DVar; 471 } 472 473 // Explicitly specified attributes and local variables with predetermined 474 // attributes. 475 auto I = std::prev(StartI); 476 if (I->SharingMap.count(D)) { 477 DVar.RefExpr = I->SharingMap[D].RefExpr; 478 DVar.CKind = I->SharingMap[D].Attributes; 479 DVar.ImplicitDSALoc = I->DefaultAttrLoc; 480 } 481 482 return DVar; 483 } 484 485 DSAStackTy::DSAVarData DSAStackTy::getImplicitDSA(VarDecl *D, bool FromParent) { 486 auto StartI = Stack.rbegin(); 487 auto EndI = std::prev(Stack.rend()); 488 if (FromParent && StartI != EndI) { 489 StartI = std::next(StartI); 490 } 491 return getDSA(StartI, D); 492 } 493 494 template <class ClausesPredicate, class DirectivesPredicate> 495 DSAStackTy::DSAVarData DSAStackTy::hasDSA(VarDecl *D, ClausesPredicate CPred, 496 DirectivesPredicate DPred, 497 bool FromParent) { 498 auto StartI = std::next(Stack.rbegin()); 499 auto EndI = std::prev(Stack.rend()); 500 if (FromParent && StartI != EndI) { 501 StartI = std::next(StartI); 502 } 503 for (auto I = StartI, EE = EndI; I != EE; ++I) { 504 if (!DPred(I->Directive) && !isParallelOrTaskRegion(I->Directive)) 505 continue; 506 DSAVarData DVar = getDSA(I, D); 507 if (CPred(DVar.CKind)) 508 return DVar; 509 } 510 return DSAVarData(); 511 } 512 513 template <class ClausesPredicate, class DirectivesPredicate> 514 DSAStackTy::DSAVarData 515 DSAStackTy::hasInnermostDSA(VarDecl *D, ClausesPredicate CPred, 516 DirectivesPredicate DPred, bool FromParent) { 517 auto StartI = std::next(Stack.rbegin()); 518 auto EndI = std::prev(Stack.rend()); 519 if (FromParent && StartI != EndI) { 520 StartI = std::next(StartI); 521 } 522 for (auto I = StartI, EE = EndI; I != EE; ++I) { 523 if (!DPred(I->Directive)) 524 break; 525 DSAVarData DVar = getDSA(I, D); 526 if (CPred(DVar.CKind)) 527 return DVar; 528 return DSAVarData(); 529 } 530 return DSAVarData(); 531 } 532 533 template <class NamedDirectivesPredicate> 534 bool DSAStackTy::hasDirective(NamedDirectivesPredicate DPred, bool FromParent) { 535 auto StartI = std::next(Stack.rbegin()); 536 auto EndI = std::prev(Stack.rend()); 537 if (FromParent && StartI != EndI) { 538 StartI = std::next(StartI); 539 } 540 for (auto I = StartI, EE = EndI; I != EE; ++I) { 541 if (DPred(I->Directive, I->DirectiveName, I->ConstructLoc)) 542 return true; 543 } 544 return false; 545 } 546 547 void Sema::InitDataSharingAttributesStack() { 548 VarDataSharingAttributesStack = new DSAStackTy(*this); 549 } 550 551 #define DSAStack static_cast<DSAStackTy *>(VarDataSharingAttributesStack) 552 553 void Sema::DestroyDataSharingAttributesStack() { delete DSAStack; } 554 555 void Sema::StartOpenMPDSABlock(OpenMPDirectiveKind DKind, 556 const DeclarationNameInfo &DirName, 557 Scope *CurScope, SourceLocation Loc) { 558 DSAStack->push(DKind, DirName, CurScope, Loc); 559 PushExpressionEvaluationContext(PotentiallyEvaluated); 560 } 561 562 void Sema::EndOpenMPDSABlock(Stmt *CurDirective) { 563 // OpenMP [2.14.3.5, Restrictions, C/C++, p.1] 564 // A variable of class type (or array thereof) that appears in a lastprivate 565 // clause requires an accessible, unambiguous default constructor for the 566 // class type, unless the list item is also specified in a firstprivate 567 // clause. 568 if (auto D = dyn_cast_or_null<OMPExecutableDirective>(CurDirective)) { 569 for (auto C : D->clauses()) { 570 if (auto Clause = dyn_cast<OMPLastprivateClause>(C)) { 571 for (auto VarRef : Clause->varlists()) { 572 if (VarRef->isValueDependent() || VarRef->isTypeDependent()) 573 continue; 574 auto VD = cast<VarDecl>(cast<DeclRefExpr>(VarRef)->getDecl()); 575 auto DVar = DSAStack->getTopDSA(VD, false); 576 if (DVar.CKind == OMPC_lastprivate) { 577 SourceLocation ELoc = VarRef->getExprLoc(); 578 auto Type = VarRef->getType(); 579 if (Type->isArrayType()) 580 Type = QualType(Type->getArrayElementTypeNoTypeQual(), 0); 581 CXXRecordDecl *RD = 582 getLangOpts().CPlusPlus ? Type->getAsCXXRecordDecl() : nullptr; 583 // FIXME This code must be replaced by actual constructing of the 584 // lastprivate variable. 585 if (RD) { 586 CXXConstructorDecl *CD = LookupDefaultConstructor(RD); 587 PartialDiagnostic PD = 588 PartialDiagnostic(PartialDiagnostic::NullDiagnostic()); 589 if (!CD || 590 CheckConstructorAccess( 591 ELoc, CD, InitializedEntity::InitializeTemporary(Type), 592 CD->getAccess(), PD) == AR_inaccessible || 593 CD->isDeleted()) { 594 Diag(ELoc, diag::err_omp_required_method) 595 << getOpenMPClauseName(OMPC_lastprivate) << 0; 596 bool IsDecl = VD->isThisDeclarationADefinition(Context) == 597 VarDecl::DeclarationOnly; 598 Diag(VD->getLocation(), IsDecl ? diag::note_previous_decl 599 : diag::note_defined_here) 600 << VD; 601 Diag(RD->getLocation(), diag::note_previous_decl) << RD; 602 continue; 603 } 604 MarkFunctionReferenced(ELoc, CD); 605 DiagnoseUseOfDecl(CD, ELoc); 606 } 607 } 608 } 609 } 610 } 611 } 612 613 DSAStack->pop(); 614 DiscardCleanupsInEvaluationContext(); 615 PopExpressionEvaluationContext(); 616 } 617 618 namespace { 619 620 class VarDeclFilterCCC : public CorrectionCandidateCallback { 621 private: 622 Sema &SemaRef; 623 624 public: 625 explicit VarDeclFilterCCC(Sema &S) : SemaRef(S) {} 626 bool ValidateCandidate(const TypoCorrection &Candidate) override { 627 NamedDecl *ND = Candidate.getCorrectionDecl(); 628 if (VarDecl *VD = dyn_cast_or_null<VarDecl>(ND)) { 629 return VD->hasGlobalStorage() && 630 SemaRef.isDeclInScope(ND, SemaRef.getCurLexicalContext(), 631 SemaRef.getCurScope()); 632 } 633 return false; 634 } 635 }; 636 } // namespace 637 638 ExprResult Sema::ActOnOpenMPIdExpression(Scope *CurScope, 639 CXXScopeSpec &ScopeSpec, 640 const DeclarationNameInfo &Id) { 641 LookupResult Lookup(*this, Id, LookupOrdinaryName); 642 LookupParsedName(Lookup, CurScope, &ScopeSpec, true); 643 644 if (Lookup.isAmbiguous()) 645 return ExprError(); 646 647 VarDecl *VD; 648 if (!Lookup.isSingleResult()) { 649 if (TypoCorrection Corrected = CorrectTypo( 650 Id, LookupOrdinaryName, CurScope, nullptr, 651 llvm::make_unique<VarDeclFilterCCC>(*this), CTK_ErrorRecovery)) { 652 diagnoseTypo(Corrected, 653 PDiag(Lookup.empty() 654 ? diag::err_undeclared_var_use_suggest 655 : diag::err_omp_expected_var_arg_suggest) 656 << Id.getName()); 657 VD = Corrected.getCorrectionDeclAs<VarDecl>(); 658 } else { 659 Diag(Id.getLoc(), Lookup.empty() ? diag::err_undeclared_var_use 660 : diag::err_omp_expected_var_arg) 661 << Id.getName(); 662 return ExprError(); 663 } 664 } else { 665 if (!(VD = Lookup.getAsSingle<VarDecl>())) { 666 Diag(Id.getLoc(), diag::err_omp_expected_var_arg) << Id.getName(); 667 Diag(Lookup.getFoundDecl()->getLocation(), diag::note_declared_at); 668 return ExprError(); 669 } 670 } 671 Lookup.suppressDiagnostics(); 672 673 // OpenMP [2.9.2, Syntax, C/C++] 674 // Variables must be file-scope, namespace-scope, or static block-scope. 675 if (!VD->hasGlobalStorage()) { 676 Diag(Id.getLoc(), diag::err_omp_global_var_arg) 677 << getOpenMPDirectiveName(OMPD_threadprivate) << !VD->isStaticLocal(); 678 bool IsDecl = 679 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly; 680 Diag(VD->getLocation(), 681 IsDecl ? diag::note_previous_decl : diag::note_defined_here) 682 << VD; 683 return ExprError(); 684 } 685 686 VarDecl *CanonicalVD = VD->getCanonicalDecl(); 687 NamedDecl *ND = cast<NamedDecl>(CanonicalVD); 688 // OpenMP [2.9.2, Restrictions, C/C++, p.2] 689 // A threadprivate directive for file-scope variables must appear outside 690 // any definition or declaration. 691 if (CanonicalVD->getDeclContext()->isTranslationUnit() && 692 !getCurLexicalContext()->isTranslationUnit()) { 693 Diag(Id.getLoc(), diag::err_omp_var_scope) 694 << getOpenMPDirectiveName(OMPD_threadprivate) << VD; 695 bool IsDecl = 696 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly; 697 Diag(VD->getLocation(), 698 IsDecl ? diag::note_previous_decl : diag::note_defined_here) 699 << VD; 700 return ExprError(); 701 } 702 // OpenMP [2.9.2, Restrictions, C/C++, p.3] 703 // A threadprivate directive for static class member variables must appear 704 // in the class definition, in the same scope in which the member 705 // variables are declared. 706 if (CanonicalVD->isStaticDataMember() && 707 !CanonicalVD->getDeclContext()->Equals(getCurLexicalContext())) { 708 Diag(Id.getLoc(), diag::err_omp_var_scope) 709 << getOpenMPDirectiveName(OMPD_threadprivate) << VD; 710 bool IsDecl = 711 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly; 712 Diag(VD->getLocation(), 713 IsDecl ? diag::note_previous_decl : diag::note_defined_here) 714 << VD; 715 return ExprError(); 716 } 717 // OpenMP [2.9.2, Restrictions, C/C++, p.4] 718 // A threadprivate directive for namespace-scope variables must appear 719 // outside any definition or declaration other than the namespace 720 // definition itself. 721 if (CanonicalVD->getDeclContext()->isNamespace() && 722 (!getCurLexicalContext()->isFileContext() || 723 !getCurLexicalContext()->Encloses(CanonicalVD->getDeclContext()))) { 724 Diag(Id.getLoc(), diag::err_omp_var_scope) 725 << getOpenMPDirectiveName(OMPD_threadprivate) << VD; 726 bool IsDecl = 727 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly; 728 Diag(VD->getLocation(), 729 IsDecl ? diag::note_previous_decl : diag::note_defined_here) 730 << VD; 731 return ExprError(); 732 } 733 // OpenMP [2.9.2, Restrictions, C/C++, p.6] 734 // A threadprivate directive for static block-scope variables must appear 735 // in the scope of the variable and not in a nested scope. 736 if (CanonicalVD->isStaticLocal() && CurScope && 737 !isDeclInScope(ND, getCurLexicalContext(), CurScope)) { 738 Diag(Id.getLoc(), diag::err_omp_var_scope) 739 << getOpenMPDirectiveName(OMPD_threadprivate) << VD; 740 bool IsDecl = 741 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly; 742 Diag(VD->getLocation(), 743 IsDecl ? diag::note_previous_decl : diag::note_defined_here) 744 << VD; 745 return ExprError(); 746 } 747 748 // OpenMP [2.9.2, Restrictions, C/C++, p.2-6] 749 // A threadprivate directive must lexically precede all references to any 750 // of the variables in its list. 751 if (VD->isUsed()) { 752 Diag(Id.getLoc(), diag::err_omp_var_used) 753 << getOpenMPDirectiveName(OMPD_threadprivate) << VD; 754 return ExprError(); 755 } 756 757 QualType ExprType = VD->getType().getNonReferenceType(); 758 ExprResult DE = BuildDeclRefExpr(VD, ExprType, VK_LValue, Id.getLoc()); 759 return DE; 760 } 761 762 Sema::DeclGroupPtrTy 763 Sema::ActOnOpenMPThreadprivateDirective(SourceLocation Loc, 764 ArrayRef<Expr *> VarList) { 765 if (OMPThreadPrivateDecl *D = CheckOMPThreadPrivateDecl(Loc, VarList)) { 766 CurContext->addDecl(D); 767 return DeclGroupPtrTy::make(DeclGroupRef(D)); 768 } 769 return DeclGroupPtrTy(); 770 } 771 772 namespace { 773 class LocalVarRefChecker : public ConstStmtVisitor<LocalVarRefChecker, bool> { 774 Sema &SemaRef; 775 776 public: 777 bool VisitDeclRefExpr(const DeclRefExpr *E) { 778 if (auto VD = dyn_cast<VarDecl>(E->getDecl())) { 779 if (VD->hasLocalStorage()) { 780 SemaRef.Diag(E->getLocStart(), 781 diag::err_omp_local_var_in_threadprivate_init) 782 << E->getSourceRange(); 783 SemaRef.Diag(VD->getLocation(), diag::note_defined_here) 784 << VD << VD->getSourceRange(); 785 return true; 786 } 787 } 788 return false; 789 } 790 bool VisitStmt(const Stmt *S) { 791 for (auto Child : S->children()) { 792 if (Child && Visit(Child)) 793 return true; 794 } 795 return false; 796 } 797 explicit LocalVarRefChecker(Sema &SemaRef) : SemaRef(SemaRef) {} 798 }; 799 } // namespace 800 801 OMPThreadPrivateDecl * 802 Sema::CheckOMPThreadPrivateDecl(SourceLocation Loc, ArrayRef<Expr *> VarList) { 803 SmallVector<Expr *, 8> Vars; 804 for (auto &RefExpr : VarList) { 805 DeclRefExpr *DE = cast<DeclRefExpr>(RefExpr); 806 VarDecl *VD = cast<VarDecl>(DE->getDecl()); 807 SourceLocation ILoc = DE->getExprLoc(); 808 809 // OpenMP [2.9.2, Restrictions, C/C++, p.10] 810 // A threadprivate variable must not have an incomplete type. 811 if (RequireCompleteType(ILoc, VD->getType(), 812 diag::err_omp_threadprivate_incomplete_type)) { 813 continue; 814 } 815 816 // OpenMP [2.9.2, Restrictions, C/C++, p.10] 817 // A threadprivate variable must not have a reference type. 818 if (VD->getType()->isReferenceType()) { 819 Diag(ILoc, diag::err_omp_ref_type_arg) 820 << getOpenMPDirectiveName(OMPD_threadprivate) << VD->getType(); 821 bool IsDecl = 822 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly; 823 Diag(VD->getLocation(), 824 IsDecl ? diag::note_previous_decl : diag::note_defined_here) 825 << VD; 826 continue; 827 } 828 829 // Check if this is a TLS variable. 830 if (VD->getTLSKind()) { 831 Diag(ILoc, diag::err_omp_var_thread_local) << VD; 832 bool IsDecl = 833 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly; 834 Diag(VD->getLocation(), 835 IsDecl ? diag::note_previous_decl : diag::note_defined_here) 836 << VD; 837 continue; 838 } 839 840 // Check if initial value of threadprivate variable reference variable with 841 // local storage (it is not supported by runtime). 842 if (auto Init = VD->getAnyInitializer()) { 843 LocalVarRefChecker Checker(*this); 844 if (Checker.Visit(Init)) 845 continue; 846 } 847 848 Vars.push_back(RefExpr); 849 DSAStack->addDSA(VD, DE, OMPC_threadprivate); 850 } 851 OMPThreadPrivateDecl *D = nullptr; 852 if (!Vars.empty()) { 853 D = OMPThreadPrivateDecl::Create(Context, getCurLexicalContext(), Loc, 854 Vars); 855 D->setAccess(AS_public); 856 } 857 return D; 858 } 859 860 static void ReportOriginalDSA(Sema &SemaRef, DSAStackTy *Stack, 861 const VarDecl *VD, DSAStackTy::DSAVarData DVar, 862 bool IsLoopIterVar = false) { 863 if (DVar.RefExpr) { 864 SemaRef.Diag(DVar.RefExpr->getExprLoc(), diag::note_omp_explicit_dsa) 865 << getOpenMPClauseName(DVar.CKind); 866 return; 867 } 868 enum { 869 PDSA_StaticMemberShared, 870 PDSA_StaticLocalVarShared, 871 PDSA_LoopIterVarPrivate, 872 PDSA_LoopIterVarLinear, 873 PDSA_LoopIterVarLastprivate, 874 PDSA_ConstVarShared, 875 PDSA_GlobalVarShared, 876 PDSA_TaskVarFirstprivate, 877 PDSA_LocalVarPrivate, 878 PDSA_Implicit 879 } Reason = PDSA_Implicit; 880 bool ReportHint = false; 881 auto ReportLoc = VD->getLocation(); 882 if (IsLoopIterVar) { 883 if (DVar.CKind == OMPC_private) 884 Reason = PDSA_LoopIterVarPrivate; 885 else if (DVar.CKind == OMPC_lastprivate) 886 Reason = PDSA_LoopIterVarLastprivate; 887 else 888 Reason = PDSA_LoopIterVarLinear; 889 } else if (DVar.DKind == OMPD_task && DVar.CKind == OMPC_firstprivate) { 890 Reason = PDSA_TaskVarFirstprivate; 891 ReportLoc = DVar.ImplicitDSALoc; 892 } else if (VD->isStaticLocal()) 893 Reason = PDSA_StaticLocalVarShared; 894 else if (VD->isStaticDataMember()) 895 Reason = PDSA_StaticMemberShared; 896 else if (VD->isFileVarDecl()) 897 Reason = PDSA_GlobalVarShared; 898 else if (VD->getType().isConstant(SemaRef.getASTContext())) 899 Reason = PDSA_ConstVarShared; 900 else if (VD->isLocalVarDecl() && DVar.CKind == OMPC_private) { 901 ReportHint = true; 902 Reason = PDSA_LocalVarPrivate; 903 } 904 if (Reason != PDSA_Implicit) { 905 SemaRef.Diag(ReportLoc, diag::note_omp_predetermined_dsa) 906 << Reason << ReportHint 907 << getOpenMPDirectiveName(Stack->getCurrentDirective()); 908 } else if (DVar.ImplicitDSALoc.isValid()) { 909 SemaRef.Diag(DVar.ImplicitDSALoc, diag::note_omp_implicit_dsa) 910 << getOpenMPClauseName(DVar.CKind); 911 } 912 } 913 914 namespace { 915 class DSAAttrChecker : public StmtVisitor<DSAAttrChecker, void> { 916 DSAStackTy *Stack; 917 Sema &SemaRef; 918 bool ErrorFound; 919 CapturedStmt *CS; 920 llvm::SmallVector<Expr *, 8> ImplicitFirstprivate; 921 llvm::DenseMap<VarDecl *, Expr *> VarsWithInheritedDSA; 922 923 public: 924 void VisitDeclRefExpr(DeclRefExpr *E) { 925 if (auto *VD = dyn_cast<VarDecl>(E->getDecl())) { 926 // Skip internally declared variables. 927 if (VD->isLocalVarDecl() && !CS->capturesVariable(VD)) 928 return; 929 930 auto DVar = Stack->getTopDSA(VD, false); 931 // Check if the variable has explicit DSA set and stop analysis if it so. 932 if (DVar.RefExpr) return; 933 934 auto ELoc = E->getExprLoc(); 935 auto DKind = Stack->getCurrentDirective(); 936 // The default(none) clause requires that each variable that is referenced 937 // in the construct, and does not have a predetermined data-sharing 938 // attribute, must have its data-sharing attribute explicitly determined 939 // by being listed in a data-sharing attribute clause. 940 if (DVar.CKind == OMPC_unknown && Stack->getDefaultDSA() == DSA_none && 941 isParallelOrTaskRegion(DKind) && 942 VarsWithInheritedDSA.count(VD) == 0) { 943 VarsWithInheritedDSA[VD] = E; 944 return; 945 } 946 947 // OpenMP [2.9.3.6, Restrictions, p.2] 948 // A list item that appears in a reduction clause of the innermost 949 // enclosing worksharing or parallel construct may not be accessed in an 950 // explicit task. 951 DVar = Stack->hasInnermostDSA(VD, MatchesAnyClause(OMPC_reduction), 952 [](OpenMPDirectiveKind K) -> bool { 953 return isOpenMPParallelDirective(K) || 954 isOpenMPWorksharingDirective(K) || 955 isOpenMPTeamsDirective(K); 956 }, 957 false); 958 if (DKind == OMPD_task && DVar.CKind == OMPC_reduction) { 959 ErrorFound = true; 960 SemaRef.Diag(ELoc, diag::err_omp_reduction_in_task); 961 ReportOriginalDSA(SemaRef, Stack, VD, DVar); 962 return; 963 } 964 965 // Define implicit data-sharing attributes for task. 966 DVar = Stack->getImplicitDSA(VD, false); 967 if (DKind == OMPD_task && DVar.CKind != OMPC_shared) 968 ImplicitFirstprivate.push_back(E); 969 } 970 } 971 void VisitOMPExecutableDirective(OMPExecutableDirective *S) { 972 for (auto *C : S->clauses()) { 973 // Skip analysis of arguments of implicitly defined firstprivate clause 974 // for task directives. 975 if (C && (!isa<OMPFirstprivateClause>(C) || C->getLocStart().isValid())) 976 for (auto *CC : C->children()) { 977 if (CC) 978 Visit(CC); 979 } 980 } 981 } 982 void VisitStmt(Stmt *S) { 983 for (auto *C : S->children()) { 984 if (C && !isa<OMPExecutableDirective>(C)) 985 Visit(C); 986 } 987 } 988 989 bool isErrorFound() { return ErrorFound; } 990 ArrayRef<Expr *> getImplicitFirstprivate() { return ImplicitFirstprivate; } 991 llvm::DenseMap<VarDecl *, Expr *> &getVarsWithInheritedDSA() { 992 return VarsWithInheritedDSA; 993 } 994 995 DSAAttrChecker(DSAStackTy *S, Sema &SemaRef, CapturedStmt *CS) 996 : Stack(S), SemaRef(SemaRef), ErrorFound(false), CS(CS) {} 997 }; 998 } // namespace 999 1000 void Sema::ActOnOpenMPRegionStart(OpenMPDirectiveKind DKind, Scope *CurScope) { 1001 switch (DKind) { 1002 case OMPD_parallel: { 1003 QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1); 1004 QualType KmpInt32PtrTy = Context.getPointerType(KmpInt32Ty); 1005 Sema::CapturedParamNameType Params[] = { 1006 std::make_pair(".global_tid.", KmpInt32PtrTy), 1007 std::make_pair(".bound_tid.", KmpInt32PtrTy), 1008 std::make_pair(StringRef(), QualType()) // __context with shared vars 1009 }; 1010 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP, 1011 Params); 1012 break; 1013 } 1014 case OMPD_simd: { 1015 Sema::CapturedParamNameType Params[] = { 1016 std::make_pair(StringRef(), QualType()) // __context with shared vars 1017 }; 1018 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP, 1019 Params); 1020 break; 1021 } 1022 case OMPD_for: { 1023 Sema::CapturedParamNameType Params[] = { 1024 std::make_pair(StringRef(), QualType()) // __context with shared vars 1025 }; 1026 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP, 1027 Params); 1028 break; 1029 } 1030 case OMPD_for_simd: { 1031 Sema::CapturedParamNameType Params[] = { 1032 std::make_pair(StringRef(), QualType()) // __context with shared vars 1033 }; 1034 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP, 1035 Params); 1036 break; 1037 } 1038 case OMPD_sections: { 1039 Sema::CapturedParamNameType Params[] = { 1040 std::make_pair(StringRef(), QualType()) // __context with shared vars 1041 }; 1042 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP, 1043 Params); 1044 break; 1045 } 1046 case OMPD_section: { 1047 Sema::CapturedParamNameType Params[] = { 1048 std::make_pair(StringRef(), QualType()) // __context with shared vars 1049 }; 1050 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP, 1051 Params); 1052 break; 1053 } 1054 case OMPD_single: { 1055 Sema::CapturedParamNameType Params[] = { 1056 std::make_pair(StringRef(), QualType()) // __context with shared vars 1057 }; 1058 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP, 1059 Params); 1060 break; 1061 } 1062 case OMPD_master: { 1063 Sema::CapturedParamNameType Params[] = { 1064 std::make_pair(StringRef(), QualType()) // __context with shared vars 1065 }; 1066 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP, 1067 Params); 1068 break; 1069 } 1070 case OMPD_critical: { 1071 Sema::CapturedParamNameType Params[] = { 1072 std::make_pair(StringRef(), QualType()) // __context with shared vars 1073 }; 1074 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP, 1075 Params); 1076 break; 1077 } 1078 case OMPD_parallel_for: { 1079 QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1); 1080 QualType KmpInt32PtrTy = Context.getPointerType(KmpInt32Ty); 1081 Sema::CapturedParamNameType Params[] = { 1082 std::make_pair(".global_tid.", KmpInt32PtrTy), 1083 std::make_pair(".bound_tid.", KmpInt32PtrTy), 1084 std::make_pair(StringRef(), QualType()) // __context with shared vars 1085 }; 1086 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP, 1087 Params); 1088 break; 1089 } 1090 case OMPD_parallel_for_simd: { 1091 QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1); 1092 QualType KmpInt32PtrTy = Context.getPointerType(KmpInt32Ty); 1093 Sema::CapturedParamNameType Params[] = { 1094 std::make_pair(".global_tid.", KmpInt32PtrTy), 1095 std::make_pair(".bound_tid.", KmpInt32PtrTy), 1096 std::make_pair(StringRef(), QualType()) // __context with shared vars 1097 }; 1098 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP, 1099 Params); 1100 break; 1101 } 1102 case OMPD_parallel_sections: { 1103 Sema::CapturedParamNameType Params[] = { 1104 std::make_pair(StringRef(), QualType()) // __context with shared vars 1105 }; 1106 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP, 1107 Params); 1108 break; 1109 } 1110 case OMPD_task: { 1111 Sema::CapturedParamNameType Params[] = { 1112 std::make_pair(StringRef(), QualType()) // __context with shared vars 1113 }; 1114 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP, 1115 Params); 1116 break; 1117 } 1118 case OMPD_taskyield: { 1119 Sema::CapturedParamNameType Params[] = { 1120 std::make_pair(StringRef(), QualType()) // __context with shared vars 1121 }; 1122 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP, 1123 Params); 1124 break; 1125 } 1126 case OMPD_barrier: { 1127 Sema::CapturedParamNameType Params[] = { 1128 std::make_pair(StringRef(), QualType()) // __context with shared vars 1129 }; 1130 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP, 1131 Params); 1132 break; 1133 } 1134 case OMPD_taskwait: { 1135 Sema::CapturedParamNameType Params[] = { 1136 std::make_pair(StringRef(), QualType()) // __context with shared vars 1137 }; 1138 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP, 1139 Params); 1140 break; 1141 } 1142 case OMPD_flush: { 1143 Sema::CapturedParamNameType Params[] = { 1144 std::make_pair(StringRef(), QualType()) // __context with shared vars 1145 }; 1146 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP, 1147 Params); 1148 break; 1149 } 1150 case OMPD_ordered: { 1151 Sema::CapturedParamNameType Params[] = { 1152 std::make_pair(StringRef(), QualType()) // __context with shared vars 1153 }; 1154 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP, 1155 Params); 1156 break; 1157 } 1158 case OMPD_atomic: { 1159 Sema::CapturedParamNameType Params[] = { 1160 std::make_pair(StringRef(), QualType()) // __context with shared vars 1161 }; 1162 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP, 1163 Params); 1164 break; 1165 } 1166 case OMPD_target: { 1167 Sema::CapturedParamNameType Params[] = { 1168 std::make_pair(StringRef(), QualType()) // __context with shared vars 1169 }; 1170 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP, 1171 Params); 1172 break; 1173 } 1174 case OMPD_teams: { 1175 QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1); 1176 QualType KmpInt32PtrTy = Context.getPointerType(KmpInt32Ty); 1177 Sema::CapturedParamNameType Params[] = { 1178 std::make_pair(".global_tid.", KmpInt32PtrTy), 1179 std::make_pair(".bound_tid.", KmpInt32PtrTy), 1180 std::make_pair(StringRef(), QualType()) // __context with shared vars 1181 }; 1182 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP, 1183 Params); 1184 break; 1185 } 1186 case OMPD_threadprivate: 1187 llvm_unreachable("OpenMP Directive is not allowed"); 1188 case OMPD_unknown: 1189 llvm_unreachable("Unknown OpenMP directive"); 1190 } 1191 } 1192 1193 static bool CheckNestingOfRegions(Sema &SemaRef, DSAStackTy *Stack, 1194 OpenMPDirectiveKind CurrentRegion, 1195 const DeclarationNameInfo &CurrentName, 1196 SourceLocation StartLoc) { 1197 // Allowed nesting of constructs 1198 // +------------------+-----------------+------------------------------------+ 1199 // | Parent directive | Child directive | Closely (!), No-Closely(+), Both(*)| 1200 // +------------------+-----------------+------------------------------------+ 1201 // | parallel | parallel | * | 1202 // | parallel | for | * | 1203 // | parallel | for simd | * | 1204 // | parallel | master | * | 1205 // | parallel | critical | * | 1206 // | parallel | simd | * | 1207 // | parallel | sections | * | 1208 // | parallel | section | + | 1209 // | parallel | single | * | 1210 // | parallel | parallel for | * | 1211 // | parallel |parallel for simd| * | 1212 // | parallel |parallel sections| * | 1213 // | parallel | task | * | 1214 // | parallel | taskyield | * | 1215 // | parallel | barrier | * | 1216 // | parallel | taskwait | * | 1217 // | parallel | flush | * | 1218 // | parallel | ordered | + | 1219 // | parallel | atomic | * | 1220 // | parallel | target | * | 1221 // | parallel | teams | + | 1222 // +------------------+-----------------+------------------------------------+ 1223 // | for | parallel | * | 1224 // | for | for | + | 1225 // | for | for simd | + | 1226 // | for | master | + | 1227 // | for | critical | * | 1228 // | for | simd | * | 1229 // | for | sections | + | 1230 // | for | section | + | 1231 // | for | single | + | 1232 // | for | parallel for | * | 1233 // | for |parallel for simd| * | 1234 // | for |parallel sections| * | 1235 // | for | task | * | 1236 // | for | taskyield | * | 1237 // | for | barrier | + | 1238 // | for | taskwait | * | 1239 // | for | flush | * | 1240 // | for | ordered | * (if construct is ordered) | 1241 // | for | atomic | * | 1242 // | for | target | * | 1243 // | for | teams | + | 1244 // +------------------+-----------------+------------------------------------+ 1245 // | master | parallel | * | 1246 // | master | for | + | 1247 // | master | for simd | + | 1248 // | master | master | * | 1249 // | master | critical | * | 1250 // | master | simd | * | 1251 // | master | sections | + | 1252 // | master | section | + | 1253 // | master | single | + | 1254 // | master | parallel for | * | 1255 // | master |parallel for simd| * | 1256 // | master |parallel sections| * | 1257 // | master | task | * | 1258 // | master | taskyield | * | 1259 // | master | barrier | + | 1260 // | master | taskwait | * | 1261 // | master | flush | * | 1262 // | master | ordered | + | 1263 // | master | atomic | * | 1264 // | master | target | * | 1265 // | master | teams | + | 1266 // +------------------+-----------------+------------------------------------+ 1267 // | critical | parallel | * | 1268 // | critical | for | + | 1269 // | critical | for simd | + | 1270 // | critical | master | * | 1271 // | critical | critical | * (should have different names) | 1272 // | critical | simd | * | 1273 // | critical | sections | + | 1274 // | critical | section | + | 1275 // | critical | single | + | 1276 // | critical | parallel for | * | 1277 // | critical |parallel for simd| * | 1278 // | critical |parallel sections| * | 1279 // | critical | task | * | 1280 // | critical | taskyield | * | 1281 // | critical | barrier | + | 1282 // | critical | taskwait | * | 1283 // | critical | ordered | + | 1284 // | critical | atomic | * | 1285 // | critical | target | * | 1286 // | critical | teams | + | 1287 // +------------------+-----------------+------------------------------------+ 1288 // | simd | parallel | | 1289 // | simd | for | | 1290 // | simd | for simd | | 1291 // | simd | master | | 1292 // | simd | critical | | 1293 // | simd | simd | | 1294 // | simd | sections | | 1295 // | simd | section | | 1296 // | simd | single | | 1297 // | simd | parallel for | | 1298 // | simd |parallel for simd| | 1299 // | simd |parallel sections| | 1300 // | simd | task | | 1301 // | simd | taskyield | | 1302 // | simd | barrier | | 1303 // | simd | taskwait | | 1304 // | simd | flush | | 1305 // | simd | ordered | | 1306 // | simd | atomic | | 1307 // | simd | target | | 1308 // | simd | teams | | 1309 // +------------------+-----------------+------------------------------------+ 1310 // | for simd | parallel | | 1311 // | for simd | for | | 1312 // | for simd | for simd | | 1313 // | for simd | master | | 1314 // | for simd | critical | | 1315 // | for simd | simd | | 1316 // | for simd | sections | | 1317 // | for simd | section | | 1318 // | for simd | single | | 1319 // | for simd | parallel for | | 1320 // | for simd |parallel for simd| | 1321 // | for simd |parallel sections| | 1322 // | for simd | task | | 1323 // | for simd | taskyield | | 1324 // | for simd | barrier | | 1325 // | for simd | taskwait | | 1326 // | for simd | flush | | 1327 // | for simd | ordered | | 1328 // | for simd | atomic | | 1329 // | for simd | target | | 1330 // | for simd | teams | | 1331 // +------------------+-----------------+------------------------------------+ 1332 // | parallel for simd| parallel | | 1333 // | parallel for simd| for | | 1334 // | parallel for simd| for simd | | 1335 // | parallel for simd| master | | 1336 // | parallel for simd| critical | | 1337 // | parallel for simd| simd | | 1338 // | parallel for simd| sections | | 1339 // | parallel for simd| section | | 1340 // | parallel for simd| single | | 1341 // | parallel for simd| parallel for | | 1342 // | parallel for simd|parallel for simd| | 1343 // | parallel for simd|parallel sections| | 1344 // | parallel for simd| task | | 1345 // | parallel for simd| taskyield | | 1346 // | parallel for simd| barrier | | 1347 // | parallel for simd| taskwait | | 1348 // | parallel for simd| flush | | 1349 // | parallel for simd| ordered | | 1350 // | parallel for simd| atomic | | 1351 // | parallel for simd| target | | 1352 // | parallel for simd| teams | | 1353 // +------------------+-----------------+------------------------------------+ 1354 // | sections | parallel | * | 1355 // | sections | for | + | 1356 // | sections | for simd | + | 1357 // | sections | master | + | 1358 // | sections | critical | * | 1359 // | sections | simd | * | 1360 // | sections | sections | + | 1361 // | sections | section | * | 1362 // | sections | single | + | 1363 // | sections | parallel for | * | 1364 // | sections |parallel for simd| * | 1365 // | sections |parallel sections| * | 1366 // | sections | task | * | 1367 // | sections | taskyield | * | 1368 // | sections | barrier | + | 1369 // | sections | taskwait | * | 1370 // | sections | flush | * | 1371 // | sections | ordered | + | 1372 // | sections | atomic | * | 1373 // | sections | target | * | 1374 // | sections | teams | + | 1375 // +------------------+-----------------+------------------------------------+ 1376 // | section | parallel | * | 1377 // | section | for | + | 1378 // | section | for simd | + | 1379 // | section | master | + | 1380 // | section | critical | * | 1381 // | section | simd | * | 1382 // | section | sections | + | 1383 // | section | section | + | 1384 // | section | single | + | 1385 // | section | parallel for | * | 1386 // | section |parallel for simd| * | 1387 // | section |parallel sections| * | 1388 // | section | task | * | 1389 // | section | taskyield | * | 1390 // | section | barrier | + | 1391 // | section | taskwait | * | 1392 // | section | flush | * | 1393 // | section | ordered | + | 1394 // | section | atomic | * | 1395 // | section | target | * | 1396 // | section | teams | + | 1397 // +------------------+-----------------+------------------------------------+ 1398 // | single | parallel | * | 1399 // | single | for | + | 1400 // | single | for simd | + | 1401 // | single | master | + | 1402 // | single | critical | * | 1403 // | single | simd | * | 1404 // | single | sections | + | 1405 // | single | section | + | 1406 // | single | single | + | 1407 // | single | parallel for | * | 1408 // | single |parallel for simd| * | 1409 // | single |parallel sections| * | 1410 // | single | task | * | 1411 // | single | taskyield | * | 1412 // | single | barrier | + | 1413 // | single | taskwait | * | 1414 // | single | flush | * | 1415 // | single | ordered | + | 1416 // | single | atomic | * | 1417 // | single | target | * | 1418 // | single | teams | + | 1419 // +------------------+-----------------+------------------------------------+ 1420 // | parallel for | parallel | * | 1421 // | parallel for | for | + | 1422 // | parallel for | for simd | + | 1423 // | parallel for | master | + | 1424 // | parallel for | critical | * | 1425 // | parallel for | simd | * | 1426 // | parallel for | sections | + | 1427 // | parallel for | section | + | 1428 // | parallel for | single | + | 1429 // | parallel for | parallel for | * | 1430 // | parallel for |parallel for simd| * | 1431 // | parallel for |parallel sections| * | 1432 // | parallel for | task | * | 1433 // | parallel for | taskyield | * | 1434 // | parallel for | barrier | + | 1435 // | parallel for | taskwait | * | 1436 // | parallel for | flush | * | 1437 // | parallel for | ordered | * (if construct is ordered) | 1438 // | parallel for | atomic | * | 1439 // | parallel for | target | * | 1440 // | parallel for | teams | + | 1441 // +------------------+-----------------+------------------------------------+ 1442 // | parallel sections| parallel | * | 1443 // | parallel sections| for | + | 1444 // | parallel sections| for simd | + | 1445 // | parallel sections| master | + | 1446 // | parallel sections| critical | + | 1447 // | parallel sections| simd | * | 1448 // | parallel sections| sections | + | 1449 // | parallel sections| section | * | 1450 // | parallel sections| single | + | 1451 // | parallel sections| parallel for | * | 1452 // | parallel sections|parallel for simd| * | 1453 // | parallel sections|parallel sections| * | 1454 // | parallel sections| task | * | 1455 // | parallel sections| taskyield | * | 1456 // | parallel sections| barrier | + | 1457 // | parallel sections| taskwait | * | 1458 // | parallel sections| flush | * | 1459 // | parallel sections| ordered | + | 1460 // | parallel sections| atomic | * | 1461 // | parallel sections| target | * | 1462 // | parallel sections| teams | + | 1463 // +------------------+-----------------+------------------------------------+ 1464 // | task | parallel | * | 1465 // | task | for | + | 1466 // | task | for simd | + | 1467 // | task | master | + | 1468 // | task | critical | * | 1469 // | task | simd | * | 1470 // | task | sections | + | 1471 // | task | section | + | 1472 // | task | single | + | 1473 // | task | parallel for | * | 1474 // | task |parallel for simd| * | 1475 // | task |parallel sections| * | 1476 // | task | task | * | 1477 // | task | taskyield | * | 1478 // | task | barrier | + | 1479 // | task | taskwait | * | 1480 // | task | flush | * | 1481 // | task | ordered | + | 1482 // | task | atomic | * | 1483 // | task | target | * | 1484 // | task | teams | + | 1485 // +------------------+-----------------+------------------------------------+ 1486 // | ordered | parallel | * | 1487 // | ordered | for | + | 1488 // | ordered | for simd | + | 1489 // | ordered | master | * | 1490 // | ordered | critical | * | 1491 // | ordered | simd | * | 1492 // | ordered | sections | + | 1493 // | ordered | section | + | 1494 // | ordered | single | + | 1495 // | ordered | parallel for | * | 1496 // | ordered |parallel for simd| * | 1497 // | ordered |parallel sections| * | 1498 // | ordered | task | * | 1499 // | ordered | taskyield | * | 1500 // | ordered | barrier | + | 1501 // | ordered | taskwait | * | 1502 // | ordered | flush | * | 1503 // | ordered | ordered | + | 1504 // | ordered | atomic | * | 1505 // | ordered | target | * | 1506 // | ordered | teams | + | 1507 // +------------------+-----------------+------------------------------------+ 1508 // | atomic | parallel | | 1509 // | atomic | for | | 1510 // | atomic | for simd | | 1511 // | atomic | master | | 1512 // | atomic | critical | | 1513 // | atomic | simd | | 1514 // | atomic | sections | | 1515 // | atomic | section | | 1516 // | atomic | single | | 1517 // | atomic | parallel for | | 1518 // | atomic |parallel for simd| | 1519 // | atomic |parallel sections| | 1520 // | atomic | task | | 1521 // | atomic | taskyield | | 1522 // | atomic | barrier | | 1523 // | atomic | taskwait | | 1524 // | atomic | flush | | 1525 // | atomic | ordered | | 1526 // | atomic | atomic | | 1527 // | atomic | target | | 1528 // | atomic | teams | | 1529 // +------------------+-----------------+------------------------------------+ 1530 // | target | parallel | * | 1531 // | target | for | * | 1532 // | target | for simd | * | 1533 // | target | master | * | 1534 // | target | critical | * | 1535 // | target | simd | * | 1536 // | target | sections | * | 1537 // | target | section | * | 1538 // | target | single | * | 1539 // | target | parallel for | * | 1540 // | target |parallel for simd| * | 1541 // | target |parallel sections| * | 1542 // | target | task | * | 1543 // | target | taskyield | * | 1544 // | target | barrier | * | 1545 // | target | taskwait | * | 1546 // | target | flush | * | 1547 // | target | ordered | * | 1548 // | target | atomic | * | 1549 // | target | target | * | 1550 // | target | teams | * | 1551 // +------------------+-----------------+------------------------------------+ 1552 // | teams | parallel | * | 1553 // | teams | for | + | 1554 // | teams | for simd | + | 1555 // | teams | master | + | 1556 // | teams | critical | + | 1557 // | teams | simd | + | 1558 // | teams | sections | + | 1559 // | teams | section | + | 1560 // | teams | single | + | 1561 // | teams | parallel for | * | 1562 // | teams |parallel for simd| * | 1563 // | teams |parallel sections| * | 1564 // | teams | task | + | 1565 // | teams | taskyield | + | 1566 // | teams | barrier | + | 1567 // | teams | taskwait | + | 1568 // | teams | flush | + | 1569 // | teams | ordered | + | 1570 // | teams | atomic | + | 1571 // | teams | target | + | 1572 // | teams | teams | + | 1573 // +------------------+-----------------+------------------------------------+ 1574 if (Stack->getCurScope()) { 1575 auto ParentRegion = Stack->getParentDirective(); 1576 bool NestingProhibited = false; 1577 bool CloseNesting = true; 1578 enum { 1579 NoRecommend, 1580 ShouldBeInParallelRegion, 1581 ShouldBeInOrderedRegion, 1582 ShouldBeInTargetRegion 1583 } Recommend = NoRecommend; 1584 if (isOpenMPSimdDirective(ParentRegion)) { 1585 // OpenMP [2.16, Nesting of Regions] 1586 // OpenMP constructs may not be nested inside a simd region. 1587 SemaRef.Diag(StartLoc, diag::err_omp_prohibited_region_simd); 1588 return true; 1589 } 1590 if (ParentRegion == OMPD_atomic) { 1591 // OpenMP [2.16, Nesting of Regions] 1592 // OpenMP constructs may not be nested inside an atomic region. 1593 SemaRef.Diag(StartLoc, diag::err_omp_prohibited_region_atomic); 1594 return true; 1595 } 1596 if (CurrentRegion == OMPD_section) { 1597 // OpenMP [2.7.2, sections Construct, Restrictions] 1598 // Orphaned section directives are prohibited. That is, the section 1599 // directives must appear within the sections construct and must not be 1600 // encountered elsewhere in the sections region. 1601 if (ParentRegion != OMPD_sections && 1602 ParentRegion != OMPD_parallel_sections) { 1603 SemaRef.Diag(StartLoc, diag::err_omp_orphaned_section_directive) 1604 << (ParentRegion != OMPD_unknown) 1605 << getOpenMPDirectiveName(ParentRegion); 1606 return true; 1607 } 1608 return false; 1609 } 1610 // Allow some constructs to be orphaned (they could be used in functions, 1611 // called from OpenMP regions with the required preconditions). 1612 if (ParentRegion == OMPD_unknown) 1613 return false; 1614 if (CurrentRegion == OMPD_master) { 1615 // OpenMP [2.16, Nesting of Regions] 1616 // A master region may not be closely nested inside a worksharing, 1617 // atomic, or explicit task region. 1618 NestingProhibited = isOpenMPWorksharingDirective(ParentRegion) || 1619 ParentRegion == OMPD_task; 1620 } else if (CurrentRegion == OMPD_critical && CurrentName.getName()) { 1621 // OpenMP [2.16, Nesting of Regions] 1622 // A critical region may not be nested (closely or otherwise) inside a 1623 // critical region with the same name. Note that this restriction is not 1624 // sufficient to prevent deadlock. 1625 SourceLocation PreviousCriticalLoc; 1626 bool DeadLock = 1627 Stack->hasDirective([CurrentName, &PreviousCriticalLoc]( 1628 OpenMPDirectiveKind K, 1629 const DeclarationNameInfo &DNI, 1630 SourceLocation Loc) 1631 ->bool { 1632 if (K == OMPD_critical && 1633 DNI.getName() == CurrentName.getName()) { 1634 PreviousCriticalLoc = Loc; 1635 return true; 1636 } else 1637 return false; 1638 }, 1639 false /* skip top directive */); 1640 if (DeadLock) { 1641 SemaRef.Diag(StartLoc, 1642 diag::err_omp_prohibited_region_critical_same_name) 1643 << CurrentName.getName(); 1644 if (PreviousCriticalLoc.isValid()) 1645 SemaRef.Diag(PreviousCriticalLoc, 1646 diag::note_omp_previous_critical_region); 1647 return true; 1648 } 1649 } else if (CurrentRegion == OMPD_barrier) { 1650 // OpenMP [2.16, Nesting of Regions] 1651 // A barrier region may not be closely nested inside a worksharing, 1652 // explicit task, critical, ordered, atomic, or master region. 1653 NestingProhibited = 1654 isOpenMPWorksharingDirective(ParentRegion) || 1655 ParentRegion == OMPD_task || ParentRegion == OMPD_master || 1656 ParentRegion == OMPD_critical || ParentRegion == OMPD_ordered; 1657 } else if (isOpenMPWorksharingDirective(CurrentRegion) && 1658 !isOpenMPParallelDirective(CurrentRegion)) { 1659 // OpenMP [2.16, Nesting of Regions] 1660 // A worksharing region may not be closely nested inside a worksharing, 1661 // explicit task, critical, ordered, atomic, or master region. 1662 NestingProhibited = 1663 isOpenMPWorksharingDirective(ParentRegion) || 1664 ParentRegion == OMPD_task || ParentRegion == OMPD_master || 1665 ParentRegion == OMPD_critical || ParentRegion == OMPD_ordered; 1666 Recommend = ShouldBeInParallelRegion; 1667 } else if (CurrentRegion == OMPD_ordered) { 1668 // OpenMP [2.16, Nesting of Regions] 1669 // An ordered region may not be closely nested inside a critical, 1670 // atomic, or explicit task region. 1671 // An ordered region must be closely nested inside a loop region (or 1672 // parallel loop region) with an ordered clause. 1673 NestingProhibited = ParentRegion == OMPD_critical || 1674 ParentRegion == OMPD_task || 1675 !Stack->isParentOrderedRegion(); 1676 Recommend = ShouldBeInOrderedRegion; 1677 } else if (isOpenMPTeamsDirective(CurrentRegion)) { 1678 // OpenMP [2.16, Nesting of Regions] 1679 // If specified, a teams construct must be contained within a target 1680 // construct. 1681 NestingProhibited = ParentRegion != OMPD_target; 1682 Recommend = ShouldBeInTargetRegion; 1683 Stack->setParentTeamsRegionLoc(Stack->getConstructLoc()); 1684 } 1685 if (!NestingProhibited && isOpenMPTeamsDirective(ParentRegion)) { 1686 // OpenMP [2.16, Nesting of Regions] 1687 // distribute, parallel, parallel sections, parallel workshare, and the 1688 // parallel loop and parallel loop SIMD constructs are the only OpenMP 1689 // constructs that can be closely nested in the teams region. 1690 // TODO: add distribute directive. 1691 NestingProhibited = !isOpenMPParallelDirective(CurrentRegion); 1692 Recommend = ShouldBeInParallelRegion; 1693 } 1694 if (NestingProhibited) { 1695 SemaRef.Diag(StartLoc, diag::err_omp_prohibited_region) 1696 << CloseNesting << getOpenMPDirectiveName(ParentRegion) << Recommend 1697 << getOpenMPDirectiveName(CurrentRegion); 1698 return true; 1699 } 1700 } 1701 return false; 1702 } 1703 1704 StmtResult Sema::ActOnOpenMPExecutableDirective(OpenMPDirectiveKind Kind, 1705 const DeclarationNameInfo &DirName, 1706 ArrayRef<OMPClause *> Clauses, 1707 Stmt *AStmt, 1708 SourceLocation StartLoc, 1709 SourceLocation EndLoc) { 1710 StmtResult Res = StmtError(); 1711 if (CheckNestingOfRegions(*this, DSAStack, Kind, DirName, StartLoc)) 1712 return StmtError(); 1713 1714 llvm::SmallVector<OMPClause *, 8> ClausesWithImplicit; 1715 llvm::DenseMap<VarDecl *, Expr *> VarsWithInheritedDSA; 1716 bool ErrorFound = false; 1717 ClausesWithImplicit.append(Clauses.begin(), Clauses.end()); 1718 if (AStmt) { 1719 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected"); 1720 1721 // Check default data sharing attributes for referenced variables. 1722 DSAAttrChecker DSAChecker(DSAStack, *this, cast<CapturedStmt>(AStmt)); 1723 DSAChecker.Visit(cast<CapturedStmt>(AStmt)->getCapturedStmt()); 1724 if (DSAChecker.isErrorFound()) 1725 return StmtError(); 1726 // Generate list of implicitly defined firstprivate variables. 1727 VarsWithInheritedDSA = DSAChecker.getVarsWithInheritedDSA(); 1728 1729 if (!DSAChecker.getImplicitFirstprivate().empty()) { 1730 if (OMPClause *Implicit = ActOnOpenMPFirstprivateClause( 1731 DSAChecker.getImplicitFirstprivate(), SourceLocation(), 1732 SourceLocation(), SourceLocation())) { 1733 ClausesWithImplicit.push_back(Implicit); 1734 ErrorFound = cast<OMPFirstprivateClause>(Implicit)->varlist_size() != 1735 DSAChecker.getImplicitFirstprivate().size(); 1736 } else 1737 ErrorFound = true; 1738 } 1739 } 1740 1741 switch (Kind) { 1742 case OMPD_parallel: 1743 Res = ActOnOpenMPParallelDirective(ClausesWithImplicit, AStmt, StartLoc, 1744 EndLoc); 1745 break; 1746 case OMPD_simd: 1747 Res = ActOnOpenMPSimdDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc, 1748 VarsWithInheritedDSA); 1749 break; 1750 case OMPD_for: 1751 Res = ActOnOpenMPForDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc, 1752 VarsWithInheritedDSA); 1753 break; 1754 case OMPD_for_simd: 1755 Res = ActOnOpenMPForSimdDirective(ClausesWithImplicit, AStmt, StartLoc, 1756 EndLoc, VarsWithInheritedDSA); 1757 break; 1758 case OMPD_sections: 1759 Res = ActOnOpenMPSectionsDirective(ClausesWithImplicit, AStmt, StartLoc, 1760 EndLoc); 1761 break; 1762 case OMPD_section: 1763 assert(ClausesWithImplicit.empty() && 1764 "No clauses are allowed for 'omp section' directive"); 1765 Res = ActOnOpenMPSectionDirective(AStmt, StartLoc, EndLoc); 1766 break; 1767 case OMPD_single: 1768 Res = ActOnOpenMPSingleDirective(ClausesWithImplicit, AStmt, StartLoc, 1769 EndLoc); 1770 break; 1771 case OMPD_master: 1772 assert(ClausesWithImplicit.empty() && 1773 "No clauses are allowed for 'omp master' directive"); 1774 Res = ActOnOpenMPMasterDirective(AStmt, StartLoc, EndLoc); 1775 break; 1776 case OMPD_critical: 1777 assert(ClausesWithImplicit.empty() && 1778 "No clauses are allowed for 'omp critical' directive"); 1779 Res = ActOnOpenMPCriticalDirective(DirName, AStmt, StartLoc, EndLoc); 1780 break; 1781 case OMPD_parallel_for: 1782 Res = ActOnOpenMPParallelForDirective(ClausesWithImplicit, AStmt, StartLoc, 1783 EndLoc, VarsWithInheritedDSA); 1784 break; 1785 case OMPD_parallel_for_simd: 1786 Res = ActOnOpenMPParallelForSimdDirective( 1787 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA); 1788 break; 1789 case OMPD_parallel_sections: 1790 Res = ActOnOpenMPParallelSectionsDirective(ClausesWithImplicit, AStmt, 1791 StartLoc, EndLoc); 1792 break; 1793 case OMPD_task: 1794 Res = 1795 ActOnOpenMPTaskDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc); 1796 break; 1797 case OMPD_taskyield: 1798 assert(ClausesWithImplicit.empty() && 1799 "No clauses are allowed for 'omp taskyield' directive"); 1800 assert(AStmt == nullptr && 1801 "No associated statement allowed for 'omp taskyield' directive"); 1802 Res = ActOnOpenMPTaskyieldDirective(StartLoc, EndLoc); 1803 break; 1804 case OMPD_barrier: 1805 assert(ClausesWithImplicit.empty() && 1806 "No clauses are allowed for 'omp barrier' directive"); 1807 assert(AStmt == nullptr && 1808 "No associated statement allowed for 'omp barrier' directive"); 1809 Res = ActOnOpenMPBarrierDirective(StartLoc, EndLoc); 1810 break; 1811 case OMPD_taskwait: 1812 assert(ClausesWithImplicit.empty() && 1813 "No clauses are allowed for 'omp taskwait' directive"); 1814 assert(AStmt == nullptr && 1815 "No associated statement allowed for 'omp taskwait' directive"); 1816 Res = ActOnOpenMPTaskwaitDirective(StartLoc, EndLoc); 1817 break; 1818 case OMPD_flush: 1819 assert(AStmt == nullptr && 1820 "No associated statement allowed for 'omp flush' directive"); 1821 Res = ActOnOpenMPFlushDirective(ClausesWithImplicit, StartLoc, EndLoc); 1822 break; 1823 case OMPD_ordered: 1824 assert(ClausesWithImplicit.empty() && 1825 "No clauses are allowed for 'omp ordered' directive"); 1826 Res = ActOnOpenMPOrderedDirective(AStmt, StartLoc, EndLoc); 1827 break; 1828 case OMPD_atomic: 1829 Res = ActOnOpenMPAtomicDirective(ClausesWithImplicit, AStmt, StartLoc, 1830 EndLoc); 1831 break; 1832 case OMPD_teams: 1833 Res = 1834 ActOnOpenMPTeamsDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc); 1835 break; 1836 case OMPD_target: 1837 Res = ActOnOpenMPTargetDirective(ClausesWithImplicit, AStmt, StartLoc, 1838 EndLoc); 1839 break; 1840 case OMPD_threadprivate: 1841 llvm_unreachable("OpenMP Directive is not allowed"); 1842 case OMPD_unknown: 1843 llvm_unreachable("Unknown OpenMP directive"); 1844 } 1845 1846 for (auto P : VarsWithInheritedDSA) { 1847 Diag(P.second->getExprLoc(), diag::err_omp_no_dsa_for_variable) 1848 << P.first << P.second->getSourceRange(); 1849 } 1850 if (!VarsWithInheritedDSA.empty()) 1851 return StmtError(); 1852 1853 if (ErrorFound) 1854 return StmtError(); 1855 return Res; 1856 } 1857 1858 StmtResult Sema::ActOnOpenMPParallelDirective(ArrayRef<OMPClause *> Clauses, 1859 Stmt *AStmt, 1860 SourceLocation StartLoc, 1861 SourceLocation EndLoc) { 1862 assert(AStmt && isa<CapturedStmt>(AStmt) && "Captured statement expected"); 1863 CapturedStmt *CS = cast<CapturedStmt>(AStmt); 1864 // 1.2.2 OpenMP Language Terminology 1865 // Structured block - An executable statement with a single entry at the 1866 // top and a single exit at the bottom. 1867 // The point of exit cannot be a branch out of the structured block. 1868 // longjmp() and throw() must not violate the entry/exit criteria. 1869 CS->getCapturedDecl()->setNothrow(); 1870 1871 getCurFunction()->setHasBranchProtectedScope(); 1872 1873 return OMPParallelDirective::Create(Context, StartLoc, EndLoc, Clauses, 1874 AStmt); 1875 } 1876 1877 namespace { 1878 /// \brief Helper class for checking canonical form of the OpenMP loops and 1879 /// extracting iteration space of each loop in the loop nest, that will be used 1880 /// for IR generation. 1881 class OpenMPIterationSpaceChecker { 1882 /// \brief Reference to Sema. 1883 Sema &SemaRef; 1884 /// \brief A location for diagnostics (when there is no some better location). 1885 SourceLocation DefaultLoc; 1886 /// \brief A location for diagnostics (when increment is not compatible). 1887 SourceLocation ConditionLoc; 1888 /// \brief A source location for referring to loop init later. 1889 SourceRange InitSrcRange; 1890 /// \brief A source location for referring to condition later. 1891 SourceRange ConditionSrcRange; 1892 /// \brief A source location for referring to increment later. 1893 SourceRange IncrementSrcRange; 1894 /// \brief Loop variable. 1895 VarDecl *Var; 1896 /// \brief Reference to loop variable. 1897 DeclRefExpr *VarRef; 1898 /// \brief Lower bound (initializer for the var). 1899 Expr *LB; 1900 /// \brief Upper bound. 1901 Expr *UB; 1902 /// \brief Loop step (increment). 1903 Expr *Step; 1904 /// \brief This flag is true when condition is one of: 1905 /// Var < UB 1906 /// Var <= UB 1907 /// UB > Var 1908 /// UB >= Var 1909 bool TestIsLessOp; 1910 /// \brief This flag is true when condition is strict ( < or > ). 1911 bool TestIsStrictOp; 1912 /// \brief This flag is true when step is subtracted on each iteration. 1913 bool SubtractStep; 1914 1915 public: 1916 OpenMPIterationSpaceChecker(Sema &SemaRef, SourceLocation DefaultLoc) 1917 : SemaRef(SemaRef), DefaultLoc(DefaultLoc), ConditionLoc(DefaultLoc), 1918 InitSrcRange(SourceRange()), ConditionSrcRange(SourceRange()), 1919 IncrementSrcRange(SourceRange()), Var(nullptr), VarRef(nullptr), 1920 LB(nullptr), UB(nullptr), Step(nullptr), TestIsLessOp(false), 1921 TestIsStrictOp(false), SubtractStep(false) {} 1922 /// \brief Check init-expr for canonical loop form and save loop counter 1923 /// variable - #Var and its initialization value - #LB. 1924 bool CheckInit(Stmt *S); 1925 /// \brief Check test-expr for canonical form, save upper-bound (#UB), flags 1926 /// for less/greater and for strict/non-strict comparison. 1927 bool CheckCond(Expr *S); 1928 /// \brief Check incr-expr for canonical loop form and return true if it 1929 /// does not conform, otherwise save loop step (#Step). 1930 bool CheckInc(Expr *S); 1931 /// \brief Return the loop counter variable. 1932 VarDecl *GetLoopVar() const { return Var; } 1933 /// \brief Return the reference expression to loop counter variable. 1934 DeclRefExpr *GetLoopVarRefExpr() const { return VarRef; } 1935 /// \brief Source range of the loop init. 1936 SourceRange GetInitSrcRange() const { return InitSrcRange; } 1937 /// \brief Source range of the loop condition. 1938 SourceRange GetConditionSrcRange() const { return ConditionSrcRange; } 1939 /// \brief Source range of the loop increment. 1940 SourceRange GetIncrementSrcRange() const { return IncrementSrcRange; } 1941 /// \brief True if the step should be subtracted. 1942 bool ShouldSubtractStep() const { return SubtractStep; } 1943 /// \brief Build the expression to calculate the number of iterations. 1944 Expr *BuildNumIterations(Scope *S, const bool LimitedType) const; 1945 /// \brief Build reference expression to the counter be used for codegen. 1946 Expr *BuildCounterVar() const; 1947 /// \brief Build initization of the counter be used for codegen. 1948 Expr *BuildCounterInit() const; 1949 /// \brief Build step of the counter be used for codegen. 1950 Expr *BuildCounterStep() const; 1951 /// \brief Return true if any expression is dependent. 1952 bool Dependent() const; 1953 1954 private: 1955 /// \brief Check the right-hand side of an assignment in the increment 1956 /// expression. 1957 bool CheckIncRHS(Expr *RHS); 1958 /// \brief Helper to set loop counter variable and its initializer. 1959 bool SetVarAndLB(VarDecl *NewVar, DeclRefExpr *NewVarRefExpr, Expr *NewLB); 1960 /// \brief Helper to set upper bound. 1961 bool SetUB(Expr *NewUB, bool LessOp, bool StrictOp, const SourceRange &SR, 1962 const SourceLocation &SL); 1963 /// \brief Helper to set loop increment. 1964 bool SetStep(Expr *NewStep, bool Subtract); 1965 }; 1966 1967 bool OpenMPIterationSpaceChecker::Dependent() const { 1968 if (!Var) { 1969 assert(!LB && !UB && !Step); 1970 return false; 1971 } 1972 return Var->getType()->isDependentType() || (LB && LB->isValueDependent()) || 1973 (UB && UB->isValueDependent()) || (Step && Step->isValueDependent()); 1974 } 1975 1976 bool OpenMPIterationSpaceChecker::SetVarAndLB(VarDecl *NewVar, 1977 DeclRefExpr *NewVarRefExpr, 1978 Expr *NewLB) { 1979 // State consistency checking to ensure correct usage. 1980 assert(Var == nullptr && LB == nullptr && VarRef == nullptr && 1981 UB == nullptr && Step == nullptr && !TestIsLessOp && !TestIsStrictOp); 1982 if (!NewVar || !NewLB) 1983 return true; 1984 Var = NewVar; 1985 VarRef = NewVarRefExpr; 1986 LB = NewLB; 1987 return false; 1988 } 1989 1990 bool OpenMPIterationSpaceChecker::SetUB(Expr *NewUB, bool LessOp, bool StrictOp, 1991 const SourceRange &SR, 1992 const SourceLocation &SL) { 1993 // State consistency checking to ensure correct usage. 1994 assert(Var != nullptr && LB != nullptr && UB == nullptr && Step == nullptr && 1995 !TestIsLessOp && !TestIsStrictOp); 1996 if (!NewUB) 1997 return true; 1998 UB = NewUB; 1999 TestIsLessOp = LessOp; 2000 TestIsStrictOp = StrictOp; 2001 ConditionSrcRange = SR; 2002 ConditionLoc = SL; 2003 return false; 2004 } 2005 2006 bool OpenMPIterationSpaceChecker::SetStep(Expr *NewStep, bool Subtract) { 2007 // State consistency checking to ensure correct usage. 2008 assert(Var != nullptr && LB != nullptr && Step == nullptr); 2009 if (!NewStep) 2010 return true; 2011 if (!NewStep->isValueDependent()) { 2012 // Check that the step is integer expression. 2013 SourceLocation StepLoc = NewStep->getLocStart(); 2014 ExprResult Val = 2015 SemaRef.PerformOpenMPImplicitIntegerConversion(StepLoc, NewStep); 2016 if (Val.isInvalid()) 2017 return true; 2018 NewStep = Val.get(); 2019 2020 // OpenMP [2.6, Canonical Loop Form, Restrictions] 2021 // If test-expr is of form var relational-op b and relational-op is < or 2022 // <= then incr-expr must cause var to increase on each iteration of the 2023 // loop. If test-expr is of form var relational-op b and relational-op is 2024 // > or >= then incr-expr must cause var to decrease on each iteration of 2025 // the loop. 2026 // If test-expr is of form b relational-op var and relational-op is < or 2027 // <= then incr-expr must cause var to decrease on each iteration of the 2028 // loop. If test-expr is of form b relational-op var and relational-op is 2029 // > or >= then incr-expr must cause var to increase on each iteration of 2030 // the loop. 2031 llvm::APSInt Result; 2032 bool IsConstant = NewStep->isIntegerConstantExpr(Result, SemaRef.Context); 2033 bool IsUnsigned = !NewStep->getType()->hasSignedIntegerRepresentation(); 2034 bool IsConstNeg = 2035 IsConstant && Result.isSigned() && (Subtract != Result.isNegative()); 2036 bool IsConstPos = 2037 IsConstant && Result.isSigned() && (Subtract == Result.isNegative()); 2038 bool IsConstZero = IsConstant && !Result.getBoolValue(); 2039 if (UB && (IsConstZero || 2040 (TestIsLessOp ? (IsConstNeg || (IsUnsigned && Subtract)) 2041 : (IsConstPos || (IsUnsigned && !Subtract))))) { 2042 SemaRef.Diag(NewStep->getExprLoc(), 2043 diag::err_omp_loop_incr_not_compatible) 2044 << Var << TestIsLessOp << NewStep->getSourceRange(); 2045 SemaRef.Diag(ConditionLoc, 2046 diag::note_omp_loop_cond_requres_compatible_incr) 2047 << TestIsLessOp << ConditionSrcRange; 2048 return true; 2049 } 2050 if (TestIsLessOp == Subtract) { 2051 NewStep = SemaRef.CreateBuiltinUnaryOp(NewStep->getExprLoc(), UO_Minus, 2052 NewStep).get(); 2053 Subtract = !Subtract; 2054 } 2055 } 2056 2057 Step = NewStep; 2058 SubtractStep = Subtract; 2059 return false; 2060 } 2061 2062 bool OpenMPIterationSpaceChecker::CheckInit(Stmt *S) { 2063 // Check init-expr for canonical loop form and save loop counter 2064 // variable - #Var and its initialization value - #LB. 2065 // OpenMP [2.6] Canonical loop form. init-expr may be one of the following: 2066 // var = lb 2067 // integer-type var = lb 2068 // random-access-iterator-type var = lb 2069 // pointer-type var = lb 2070 // 2071 if (!S) { 2072 SemaRef.Diag(DefaultLoc, diag::err_omp_loop_not_canonical_init); 2073 return true; 2074 } 2075 InitSrcRange = S->getSourceRange(); 2076 if (Expr *E = dyn_cast<Expr>(S)) 2077 S = E->IgnoreParens(); 2078 if (auto BO = dyn_cast<BinaryOperator>(S)) { 2079 if (BO->getOpcode() == BO_Assign) 2080 if (auto DRE = dyn_cast<DeclRefExpr>(BO->getLHS()->IgnoreParens())) 2081 return SetVarAndLB(dyn_cast<VarDecl>(DRE->getDecl()), DRE, 2082 BO->getRHS()); 2083 } else if (auto DS = dyn_cast<DeclStmt>(S)) { 2084 if (DS->isSingleDecl()) { 2085 if (auto Var = dyn_cast_or_null<VarDecl>(DS->getSingleDecl())) { 2086 if (Var->hasInit()) { 2087 // Accept non-canonical init form here but emit ext. warning. 2088 if (Var->getInitStyle() != VarDecl::CInit) 2089 SemaRef.Diag(S->getLocStart(), 2090 diag::ext_omp_loop_not_canonical_init) 2091 << S->getSourceRange(); 2092 return SetVarAndLB(Var, nullptr, Var->getInit()); 2093 } 2094 } 2095 } 2096 } else if (auto CE = dyn_cast<CXXOperatorCallExpr>(S)) 2097 if (CE->getOperator() == OO_Equal) 2098 if (auto DRE = dyn_cast<DeclRefExpr>(CE->getArg(0))) 2099 return SetVarAndLB(dyn_cast<VarDecl>(DRE->getDecl()), DRE, 2100 CE->getArg(1)); 2101 2102 SemaRef.Diag(S->getLocStart(), diag::err_omp_loop_not_canonical_init) 2103 << S->getSourceRange(); 2104 return true; 2105 } 2106 2107 /// \brief Ignore parenthesizes, implicit casts, copy constructor and return the 2108 /// variable (which may be the loop variable) if possible. 2109 static const VarDecl *GetInitVarDecl(const Expr *E) { 2110 if (!E) 2111 return nullptr; 2112 E = E->IgnoreParenImpCasts(); 2113 if (auto *CE = dyn_cast_or_null<CXXConstructExpr>(E)) 2114 if (const CXXConstructorDecl *Ctor = CE->getConstructor()) 2115 if (Ctor->isCopyConstructor() && CE->getNumArgs() == 1 && 2116 CE->getArg(0) != nullptr) 2117 E = CE->getArg(0)->IgnoreParenImpCasts(); 2118 auto DRE = dyn_cast_or_null<DeclRefExpr>(E); 2119 if (!DRE) 2120 return nullptr; 2121 return dyn_cast<VarDecl>(DRE->getDecl()); 2122 } 2123 2124 bool OpenMPIterationSpaceChecker::CheckCond(Expr *S) { 2125 // Check test-expr for canonical form, save upper-bound UB, flags for 2126 // less/greater and for strict/non-strict comparison. 2127 // OpenMP [2.6] Canonical loop form. Test-expr may be one of the following: 2128 // var relational-op b 2129 // b relational-op var 2130 // 2131 if (!S) { 2132 SemaRef.Diag(DefaultLoc, diag::err_omp_loop_not_canonical_cond) << Var; 2133 return true; 2134 } 2135 S = S->IgnoreParenImpCasts(); 2136 SourceLocation CondLoc = S->getLocStart(); 2137 if (auto BO = dyn_cast<BinaryOperator>(S)) { 2138 if (BO->isRelationalOp()) { 2139 if (GetInitVarDecl(BO->getLHS()) == Var) 2140 return SetUB(BO->getRHS(), 2141 (BO->getOpcode() == BO_LT || BO->getOpcode() == BO_LE), 2142 (BO->getOpcode() == BO_LT || BO->getOpcode() == BO_GT), 2143 BO->getSourceRange(), BO->getOperatorLoc()); 2144 if (GetInitVarDecl(BO->getRHS()) == Var) 2145 return SetUB(BO->getLHS(), 2146 (BO->getOpcode() == BO_GT || BO->getOpcode() == BO_GE), 2147 (BO->getOpcode() == BO_LT || BO->getOpcode() == BO_GT), 2148 BO->getSourceRange(), BO->getOperatorLoc()); 2149 } 2150 } else if (auto CE = dyn_cast<CXXOperatorCallExpr>(S)) { 2151 if (CE->getNumArgs() == 2) { 2152 auto Op = CE->getOperator(); 2153 switch (Op) { 2154 case OO_Greater: 2155 case OO_GreaterEqual: 2156 case OO_Less: 2157 case OO_LessEqual: 2158 if (GetInitVarDecl(CE->getArg(0)) == Var) 2159 return SetUB(CE->getArg(1), Op == OO_Less || Op == OO_LessEqual, 2160 Op == OO_Less || Op == OO_Greater, CE->getSourceRange(), 2161 CE->getOperatorLoc()); 2162 if (GetInitVarDecl(CE->getArg(1)) == Var) 2163 return SetUB(CE->getArg(0), Op == OO_Greater || Op == OO_GreaterEqual, 2164 Op == OO_Less || Op == OO_Greater, CE->getSourceRange(), 2165 CE->getOperatorLoc()); 2166 break; 2167 default: 2168 break; 2169 } 2170 } 2171 } 2172 SemaRef.Diag(CondLoc, diag::err_omp_loop_not_canonical_cond) 2173 << S->getSourceRange() << Var; 2174 return true; 2175 } 2176 2177 bool OpenMPIterationSpaceChecker::CheckIncRHS(Expr *RHS) { 2178 // RHS of canonical loop form increment can be: 2179 // var + incr 2180 // incr + var 2181 // var - incr 2182 // 2183 RHS = RHS->IgnoreParenImpCasts(); 2184 if (auto BO = dyn_cast<BinaryOperator>(RHS)) { 2185 if (BO->isAdditiveOp()) { 2186 bool IsAdd = BO->getOpcode() == BO_Add; 2187 if (GetInitVarDecl(BO->getLHS()) == Var) 2188 return SetStep(BO->getRHS(), !IsAdd); 2189 if (IsAdd && GetInitVarDecl(BO->getRHS()) == Var) 2190 return SetStep(BO->getLHS(), false); 2191 } 2192 } else if (auto CE = dyn_cast<CXXOperatorCallExpr>(RHS)) { 2193 bool IsAdd = CE->getOperator() == OO_Plus; 2194 if ((IsAdd || CE->getOperator() == OO_Minus) && CE->getNumArgs() == 2) { 2195 if (GetInitVarDecl(CE->getArg(0)) == Var) 2196 return SetStep(CE->getArg(1), !IsAdd); 2197 if (IsAdd && GetInitVarDecl(CE->getArg(1)) == Var) 2198 return SetStep(CE->getArg(0), false); 2199 } 2200 } 2201 SemaRef.Diag(RHS->getLocStart(), diag::err_omp_loop_not_canonical_incr) 2202 << RHS->getSourceRange() << Var; 2203 return true; 2204 } 2205 2206 bool OpenMPIterationSpaceChecker::CheckInc(Expr *S) { 2207 // Check incr-expr for canonical loop form and return true if it 2208 // does not conform. 2209 // OpenMP [2.6] Canonical loop form. Test-expr may be one of the following: 2210 // ++var 2211 // var++ 2212 // --var 2213 // var-- 2214 // var += incr 2215 // var -= incr 2216 // var = var + incr 2217 // var = incr + var 2218 // var = var - incr 2219 // 2220 if (!S) { 2221 SemaRef.Diag(DefaultLoc, diag::err_omp_loop_not_canonical_incr) << Var; 2222 return true; 2223 } 2224 IncrementSrcRange = S->getSourceRange(); 2225 S = S->IgnoreParens(); 2226 if (auto UO = dyn_cast<UnaryOperator>(S)) { 2227 if (UO->isIncrementDecrementOp() && GetInitVarDecl(UO->getSubExpr()) == Var) 2228 return SetStep( 2229 SemaRef.ActOnIntegerConstant(UO->getLocStart(), 2230 (UO->isDecrementOp() ? -1 : 1)).get(), 2231 false); 2232 } else if (auto BO = dyn_cast<BinaryOperator>(S)) { 2233 switch (BO->getOpcode()) { 2234 case BO_AddAssign: 2235 case BO_SubAssign: 2236 if (GetInitVarDecl(BO->getLHS()) == Var) 2237 return SetStep(BO->getRHS(), BO->getOpcode() == BO_SubAssign); 2238 break; 2239 case BO_Assign: 2240 if (GetInitVarDecl(BO->getLHS()) == Var) 2241 return CheckIncRHS(BO->getRHS()); 2242 break; 2243 default: 2244 break; 2245 } 2246 } else if (auto CE = dyn_cast<CXXOperatorCallExpr>(S)) { 2247 switch (CE->getOperator()) { 2248 case OO_PlusPlus: 2249 case OO_MinusMinus: 2250 if (GetInitVarDecl(CE->getArg(0)) == Var) 2251 return SetStep( 2252 SemaRef.ActOnIntegerConstant( 2253 CE->getLocStart(), 2254 ((CE->getOperator() == OO_MinusMinus) ? -1 : 1)).get(), 2255 false); 2256 break; 2257 case OO_PlusEqual: 2258 case OO_MinusEqual: 2259 if (GetInitVarDecl(CE->getArg(0)) == Var) 2260 return SetStep(CE->getArg(1), CE->getOperator() == OO_MinusEqual); 2261 break; 2262 case OO_Equal: 2263 if (GetInitVarDecl(CE->getArg(0)) == Var) 2264 return CheckIncRHS(CE->getArg(1)); 2265 break; 2266 default: 2267 break; 2268 } 2269 } 2270 SemaRef.Diag(S->getLocStart(), diag::err_omp_loop_not_canonical_incr) 2271 << S->getSourceRange() << Var; 2272 return true; 2273 } 2274 2275 /// \brief Build the expression to calculate the number of iterations. 2276 Expr * 2277 OpenMPIterationSpaceChecker::BuildNumIterations(Scope *S, 2278 const bool LimitedType) const { 2279 ExprResult Diff; 2280 if (Var->getType()->isIntegerType() || Var->getType()->isPointerType() || 2281 SemaRef.getLangOpts().CPlusPlus) { 2282 // Upper - Lower 2283 Expr *Upper = TestIsLessOp ? UB : LB; 2284 Expr *Lower = TestIsLessOp ? LB : UB; 2285 2286 Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Sub, Upper, Lower); 2287 2288 if (!Diff.isUsable() && Var->getType()->getAsCXXRecordDecl()) { 2289 // BuildBinOp already emitted error, this one is to point user to upper 2290 // and lower bound, and to tell what is passed to 'operator-'. 2291 SemaRef.Diag(Upper->getLocStart(), diag::err_omp_loop_diff_cxx) 2292 << Upper->getSourceRange() << Lower->getSourceRange(); 2293 return nullptr; 2294 } 2295 } 2296 2297 if (!Diff.isUsable()) 2298 return nullptr; 2299 2300 // Upper - Lower [- 1] 2301 if (TestIsStrictOp) 2302 Diff = SemaRef.BuildBinOp( 2303 S, DefaultLoc, BO_Sub, Diff.get(), 2304 SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get()); 2305 if (!Diff.isUsable()) 2306 return nullptr; 2307 2308 // Upper - Lower [- 1] + Step 2309 Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Add, Diff.get(), 2310 Step->IgnoreImplicit()); 2311 if (!Diff.isUsable()) 2312 return nullptr; 2313 2314 // Parentheses (for dumping/debugging purposes only). 2315 Diff = SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, Diff.get()); 2316 if (!Diff.isUsable()) 2317 return nullptr; 2318 2319 // (Upper - Lower [- 1] + Step) / Step 2320 Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Div, Diff.get(), 2321 Step->IgnoreImplicit()); 2322 if (!Diff.isUsable()) 2323 return nullptr; 2324 2325 // OpenMP runtime requires 32-bit or 64-bit loop variables. 2326 if (LimitedType) { 2327 auto &C = SemaRef.Context; 2328 QualType Type = Diff.get()->getType(); 2329 unsigned NewSize = (C.getTypeSize(Type) > 32) ? 64 : 32; 2330 if (NewSize != C.getTypeSize(Type)) { 2331 if (NewSize < C.getTypeSize(Type)) { 2332 assert(NewSize == 64 && "incorrect loop var size"); 2333 SemaRef.Diag(DefaultLoc, diag::warn_omp_loop_64_bit_var) 2334 << InitSrcRange << ConditionSrcRange; 2335 } 2336 QualType NewType = C.getIntTypeForBitwidth( 2337 NewSize, Type->hasSignedIntegerRepresentation()); 2338 Diff = SemaRef.PerformImplicitConversion(Diff.get(), NewType, 2339 Sema::AA_Converting, true); 2340 if (!Diff.isUsable()) 2341 return nullptr; 2342 } 2343 } 2344 2345 return Diff.get(); 2346 } 2347 2348 /// \brief Build reference expression to the counter be used for codegen. 2349 Expr *OpenMPIterationSpaceChecker::BuildCounterVar() const { 2350 return DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(), 2351 GetIncrementSrcRange().getBegin(), Var, false, 2352 DefaultLoc, Var->getType(), VK_LValue); 2353 } 2354 2355 /// \brief Build initization of the counter be used for codegen. 2356 Expr *OpenMPIterationSpaceChecker::BuildCounterInit() const { return LB; } 2357 2358 /// \brief Build step of the counter be used for codegen. 2359 Expr *OpenMPIterationSpaceChecker::BuildCounterStep() const { return Step; } 2360 2361 /// \brief Iteration space of a single for loop. 2362 struct LoopIterationSpace { 2363 /// \brief This expression calculates the number of iterations in the loop. 2364 /// It is always possible to calculate it before starting the loop. 2365 Expr *NumIterations; 2366 /// \brief The loop counter variable. 2367 Expr *CounterVar; 2368 /// \brief This is initializer for the initial value of #CounterVar. 2369 Expr *CounterInit; 2370 /// \brief This is step for the #CounterVar used to generate its update: 2371 /// #CounterVar = #CounterInit + #CounterStep * CurrentIteration. 2372 Expr *CounterStep; 2373 /// \brief Should step be subtracted? 2374 bool Subtract; 2375 /// \brief Source range of the loop init. 2376 SourceRange InitSrcRange; 2377 /// \brief Source range of the loop condition. 2378 SourceRange CondSrcRange; 2379 /// \brief Source range of the loop increment. 2380 SourceRange IncSrcRange; 2381 }; 2382 2383 /// \brief The resulting expressions built for the OpenMP loop CodeGen for the 2384 /// whole collapsed loop nest. See class OMPLoopDirective for their description. 2385 struct BuiltLoopExprs { 2386 Expr *IterationVarRef; 2387 Expr *LastIteration; 2388 Expr *CalcLastIteration; 2389 Expr *PreCond; 2390 Expr *Cond; 2391 Expr *SeparatedCond; 2392 Expr *Init; 2393 Expr *Inc; 2394 SmallVector<Expr *, 4> Counters; 2395 SmallVector<Expr *, 4> Updates; 2396 SmallVector<Expr *, 4> Finals; 2397 2398 bool builtAll() { 2399 return IterationVarRef != nullptr && LastIteration != nullptr && 2400 PreCond != nullptr && Cond != nullptr && SeparatedCond != nullptr && 2401 Init != nullptr && Inc != nullptr; 2402 } 2403 void clear(unsigned size) { 2404 IterationVarRef = nullptr; 2405 LastIteration = nullptr; 2406 CalcLastIteration = nullptr; 2407 PreCond = nullptr; 2408 Cond = nullptr; 2409 SeparatedCond = nullptr; 2410 Init = nullptr; 2411 Inc = nullptr; 2412 Counters.resize(size); 2413 Updates.resize(size); 2414 Finals.resize(size); 2415 for (unsigned i = 0; i < size; ++i) { 2416 Counters[i] = nullptr; 2417 Updates[i] = nullptr; 2418 Finals[i] = nullptr; 2419 } 2420 } 2421 }; 2422 2423 } // namespace 2424 2425 /// \brief Called on a for stmt to check and extract its iteration space 2426 /// for further processing (such as collapsing). 2427 static bool CheckOpenMPIterationSpace( 2428 OpenMPDirectiveKind DKind, Stmt *S, Sema &SemaRef, DSAStackTy &DSA, 2429 unsigned CurrentNestedLoopCount, unsigned NestedLoopCount, 2430 Expr *NestedLoopCountExpr, 2431 llvm::DenseMap<VarDecl *, Expr *> &VarsWithImplicitDSA, 2432 LoopIterationSpace &ResultIterSpace) { 2433 // OpenMP [2.6, Canonical Loop Form] 2434 // for (init-expr; test-expr; incr-expr) structured-block 2435 auto For = dyn_cast_or_null<ForStmt>(S); 2436 if (!For) { 2437 SemaRef.Diag(S->getLocStart(), diag::err_omp_not_for) 2438 << (NestedLoopCountExpr != nullptr) << getOpenMPDirectiveName(DKind) 2439 << NestedLoopCount << (CurrentNestedLoopCount > 0) 2440 << CurrentNestedLoopCount; 2441 if (NestedLoopCount > 1) 2442 SemaRef.Diag(NestedLoopCountExpr->getExprLoc(), 2443 diag::note_omp_collapse_expr) 2444 << NestedLoopCountExpr->getSourceRange(); 2445 return true; 2446 } 2447 assert(For->getBody()); 2448 2449 OpenMPIterationSpaceChecker ISC(SemaRef, For->getForLoc()); 2450 2451 // Check init. 2452 auto Init = For->getInit(); 2453 if (ISC.CheckInit(Init)) { 2454 return true; 2455 } 2456 2457 bool HasErrors = false; 2458 2459 // Check loop variable's type. 2460 auto Var = ISC.GetLoopVar(); 2461 2462 // OpenMP [2.6, Canonical Loop Form] 2463 // Var is one of the following: 2464 // A variable of signed or unsigned integer type. 2465 // For C++, a variable of a random access iterator type. 2466 // For C, a variable of a pointer type. 2467 auto VarType = Var->getType(); 2468 if (!VarType->isDependentType() && !VarType->isIntegerType() && 2469 !VarType->isPointerType() && 2470 !(SemaRef.getLangOpts().CPlusPlus && VarType->isOverloadableType())) { 2471 SemaRef.Diag(Init->getLocStart(), diag::err_omp_loop_variable_type) 2472 << SemaRef.getLangOpts().CPlusPlus; 2473 HasErrors = true; 2474 } 2475 2476 // OpenMP, 2.14.1.1 Data-sharing Attribute Rules for Variables Referenced in a 2477 // Construct 2478 // The loop iteration variable(s) in the associated for-loop(s) of a for or 2479 // parallel for construct is (are) private. 2480 // The loop iteration variable in the associated for-loop of a simd construct 2481 // with just one associated for-loop is linear with a constant-linear-step 2482 // that is the increment of the associated for-loop. 2483 // Exclude loop var from the list of variables with implicitly defined data 2484 // sharing attributes. 2485 VarsWithImplicitDSA.erase(Var); 2486 2487 // OpenMP [2.14.1.1, Data-sharing Attribute Rules for Variables Referenced in 2488 // a Construct, C/C++]. 2489 // The loop iteration variable in the associated for-loop of a simd construct 2490 // with just one associated for-loop may be listed in a linear clause with a 2491 // constant-linear-step that is the increment of the associated for-loop. 2492 // The loop iteration variable(s) in the associated for-loop(s) of a for or 2493 // parallel for construct may be listed in a private or lastprivate clause. 2494 DSAStackTy::DSAVarData DVar = DSA.getTopDSA(Var, false); 2495 auto LoopVarRefExpr = ISC.GetLoopVarRefExpr(); 2496 // If LoopVarRefExpr is nullptr it means the corresponding loop variable is 2497 // declared in the loop and it is predetermined as a private. 2498 auto PredeterminedCKind = 2499 isOpenMPSimdDirective(DKind) 2500 ? ((NestedLoopCount == 1) ? OMPC_linear : OMPC_lastprivate) 2501 : OMPC_private; 2502 if (((isOpenMPSimdDirective(DKind) && DVar.CKind != OMPC_unknown && 2503 DVar.CKind != PredeterminedCKind) || 2504 (isOpenMPWorksharingDirective(DKind) && !isOpenMPSimdDirective(DKind) && 2505 DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_private && 2506 DVar.CKind != OMPC_lastprivate)) && 2507 (DVar.CKind != OMPC_private || DVar.RefExpr != nullptr)) { 2508 SemaRef.Diag(Init->getLocStart(), diag::err_omp_loop_var_dsa) 2509 << getOpenMPClauseName(DVar.CKind) << getOpenMPDirectiveName(DKind) 2510 << getOpenMPClauseName(PredeterminedCKind); 2511 ReportOriginalDSA(SemaRef, &DSA, Var, DVar, true); 2512 HasErrors = true; 2513 } else if (LoopVarRefExpr != nullptr) { 2514 // Make the loop iteration variable private (for worksharing constructs), 2515 // linear (for simd directives with the only one associated loop) or 2516 // lastprivate (for simd directives with several collapsed loops). 2517 DSA.addDSA(Var, LoopVarRefExpr, PredeterminedCKind); 2518 } 2519 2520 assert(isOpenMPLoopDirective(DKind) && "DSA for non-loop vars"); 2521 2522 // Check test-expr. 2523 HasErrors |= ISC.CheckCond(For->getCond()); 2524 2525 // Check incr-expr. 2526 HasErrors |= ISC.CheckInc(For->getInc()); 2527 2528 if (ISC.Dependent() || SemaRef.CurContext->isDependentContext() || HasErrors) 2529 return HasErrors; 2530 2531 // Build the loop's iteration space representation. 2532 ResultIterSpace.NumIterations = ISC.BuildNumIterations( 2533 DSA.getCurScope(), /* LimitedType */ isOpenMPWorksharingDirective(DKind)); 2534 ResultIterSpace.CounterVar = ISC.BuildCounterVar(); 2535 ResultIterSpace.CounterInit = ISC.BuildCounterInit(); 2536 ResultIterSpace.CounterStep = ISC.BuildCounterStep(); 2537 ResultIterSpace.InitSrcRange = ISC.GetInitSrcRange(); 2538 ResultIterSpace.CondSrcRange = ISC.GetConditionSrcRange(); 2539 ResultIterSpace.IncSrcRange = ISC.GetIncrementSrcRange(); 2540 ResultIterSpace.Subtract = ISC.ShouldSubtractStep(); 2541 2542 HasErrors |= (ResultIterSpace.NumIterations == nullptr || 2543 ResultIterSpace.CounterVar == nullptr || 2544 ResultIterSpace.CounterInit == nullptr || 2545 ResultIterSpace.CounterStep == nullptr); 2546 2547 return HasErrors; 2548 } 2549 2550 /// \brief Build a variable declaration for OpenMP loop iteration variable. 2551 static VarDecl *BuildVarDecl(Sema &SemaRef, SourceLocation Loc, QualType Type, 2552 StringRef Name) { 2553 DeclContext *DC = SemaRef.CurContext; 2554 IdentifierInfo *II = &SemaRef.PP.getIdentifierTable().get(Name); 2555 TypeSourceInfo *TInfo = SemaRef.Context.getTrivialTypeSourceInfo(Type, Loc); 2556 VarDecl *Decl = 2557 VarDecl::Create(SemaRef.Context, DC, Loc, Loc, II, Type, TInfo, SC_None); 2558 Decl->setImplicit(); 2559 return Decl; 2560 } 2561 2562 /// \brief Build 'VarRef = Start + Iter * Step'. 2563 static ExprResult BuildCounterUpdate(Sema &SemaRef, Scope *S, 2564 SourceLocation Loc, ExprResult VarRef, 2565 ExprResult Start, ExprResult Iter, 2566 ExprResult Step, bool Subtract) { 2567 // Add parentheses (for debugging purposes only). 2568 Iter = SemaRef.ActOnParenExpr(Loc, Loc, Iter.get()); 2569 if (!VarRef.isUsable() || !Start.isUsable() || !Iter.isUsable() || 2570 !Step.isUsable()) 2571 return ExprError(); 2572 2573 ExprResult Update = SemaRef.BuildBinOp(S, Loc, BO_Mul, Iter.get(), 2574 Step.get()->IgnoreImplicit()); 2575 if (!Update.isUsable()) 2576 return ExprError(); 2577 2578 // Build 'VarRef = Start + Iter * Step'. 2579 Update = SemaRef.BuildBinOp(S, Loc, (Subtract ? BO_Sub : BO_Add), 2580 Start.get()->IgnoreImplicit(), Update.get()); 2581 if (!Update.isUsable()) 2582 return ExprError(); 2583 2584 Update = SemaRef.PerformImplicitConversion( 2585 Update.get(), VarRef.get()->getType(), Sema::AA_Converting, true); 2586 if (!Update.isUsable()) 2587 return ExprError(); 2588 2589 Update = SemaRef.BuildBinOp(S, Loc, BO_Assign, VarRef.get(), Update.get()); 2590 return Update; 2591 } 2592 2593 /// \brief Convert integer expression \a E to make it have at least \a Bits 2594 /// bits. 2595 static ExprResult WidenIterationCount(unsigned Bits, Expr *E, 2596 Sema &SemaRef) { 2597 if (E == nullptr) 2598 return ExprError(); 2599 auto &C = SemaRef.Context; 2600 QualType OldType = E->getType(); 2601 unsigned HasBits = C.getTypeSize(OldType); 2602 if (HasBits >= Bits) 2603 return ExprResult(E); 2604 // OK to convert to signed, because new type has more bits than old. 2605 QualType NewType = C.getIntTypeForBitwidth(Bits, /* Signed */ true); 2606 return SemaRef.PerformImplicitConversion(E, NewType, Sema::AA_Converting, 2607 true); 2608 } 2609 2610 /// \brief Check if the given expression \a E is a constant integer that fits 2611 /// into \a Bits bits. 2612 static bool FitsInto(unsigned Bits, bool Signed, Expr *E, Sema &SemaRef) { 2613 if (E == nullptr) 2614 return false; 2615 llvm::APSInt Result; 2616 if (E->isIntegerConstantExpr(Result, SemaRef.Context)) 2617 return Signed ? Result.isSignedIntN(Bits) : Result.isIntN(Bits); 2618 return false; 2619 } 2620 2621 /// \brief Called on a for stmt to check itself and nested loops (if any). 2622 /// \return Returns 0 if one of the collapsed stmts is not canonical for loop, 2623 /// number of collapsed loops otherwise. 2624 static unsigned 2625 CheckOpenMPLoop(OpenMPDirectiveKind DKind, Expr *NestedLoopCountExpr, 2626 Stmt *AStmt, Sema &SemaRef, DSAStackTy &DSA, 2627 llvm::DenseMap<VarDecl *, Expr *> &VarsWithImplicitDSA, 2628 BuiltLoopExprs &Built) { 2629 unsigned NestedLoopCount = 1; 2630 if (NestedLoopCountExpr) { 2631 // Found 'collapse' clause - calculate collapse number. 2632 llvm::APSInt Result; 2633 if (NestedLoopCountExpr->EvaluateAsInt(Result, SemaRef.getASTContext())) 2634 NestedLoopCount = Result.getLimitedValue(); 2635 } 2636 // This is helper routine for loop directives (e.g., 'for', 'simd', 2637 // 'for simd', etc.). 2638 SmallVector<LoopIterationSpace, 4> IterSpaces; 2639 IterSpaces.resize(NestedLoopCount); 2640 Stmt *CurStmt = AStmt->IgnoreContainers(/* IgnoreCaptured */ true); 2641 for (unsigned Cnt = 0; Cnt < NestedLoopCount; ++Cnt) { 2642 if (CheckOpenMPIterationSpace(DKind, CurStmt, SemaRef, DSA, Cnt, 2643 NestedLoopCount, NestedLoopCountExpr, 2644 VarsWithImplicitDSA, IterSpaces[Cnt])) 2645 return 0; 2646 // Move on to the next nested for loop, or to the loop body. 2647 // OpenMP [2.8.1, simd construct, Restrictions] 2648 // All loops associated with the construct must be perfectly nested; that 2649 // is, there must be no intervening code nor any OpenMP directive between 2650 // any two loops. 2651 CurStmt = cast<ForStmt>(CurStmt)->getBody()->IgnoreContainers(); 2652 } 2653 2654 Built.clear(/* size */ NestedLoopCount); 2655 2656 if (SemaRef.CurContext->isDependentContext()) 2657 return NestedLoopCount; 2658 2659 // An example of what is generated for the following code: 2660 // 2661 // #pragma omp simd collapse(2) 2662 // for (i = 0; i < NI; ++i) 2663 // for (j = J0; j < NJ; j+=2) { 2664 // <loop body> 2665 // } 2666 // 2667 // We generate the code below. 2668 // Note: the loop body may be outlined in CodeGen. 2669 // Note: some counters may be C++ classes, operator- is used to find number of 2670 // iterations and operator+= to calculate counter value. 2671 // Note: decltype(NumIterations) must be integer type (in 'omp for', only i32 2672 // or i64 is currently supported). 2673 // 2674 // #define NumIterations (NI * ((NJ - J0 - 1 + 2) / 2)) 2675 // for (int[32|64]_t IV = 0; IV < NumIterations; ++IV ) { 2676 // .local.i = IV / ((NJ - J0 - 1 + 2) / 2); 2677 // .local.j = J0 + (IV % ((NJ - J0 - 1 + 2) / 2)) * 2; 2678 // // similar updates for vars in clauses (e.g. 'linear') 2679 // <loop body (using local i and j)> 2680 // } 2681 // i = NI; // assign final values of counters 2682 // j = NJ; 2683 // 2684 2685 // Last iteration number is (I1 * I2 * ... In) - 1, where I1, I2 ... In are 2686 // the iteration counts of the collapsed for loops. 2687 auto N0 = IterSpaces[0].NumIterations; 2688 ExprResult LastIteration32 = WidenIterationCount(32 /* Bits */, N0, SemaRef); 2689 ExprResult LastIteration64 = WidenIterationCount(64 /* Bits */, N0, SemaRef); 2690 2691 if (!LastIteration32.isUsable() || !LastIteration64.isUsable()) 2692 return NestedLoopCount; 2693 2694 auto &C = SemaRef.Context; 2695 bool AllCountsNeedLessThan32Bits = C.getTypeSize(N0->getType()) < 32; 2696 2697 Scope *CurScope = DSA.getCurScope(); 2698 for (unsigned Cnt = 1; Cnt < NestedLoopCount; ++Cnt) { 2699 auto N = IterSpaces[Cnt].NumIterations; 2700 AllCountsNeedLessThan32Bits &= C.getTypeSize(N->getType()) < 32; 2701 if (LastIteration32.isUsable()) 2702 LastIteration32 = SemaRef.BuildBinOp(CurScope, SourceLocation(), BO_Mul, 2703 LastIteration32.get(), N); 2704 if (LastIteration64.isUsable()) 2705 LastIteration64 = SemaRef.BuildBinOp(CurScope, SourceLocation(), BO_Mul, 2706 LastIteration64.get(), N); 2707 } 2708 2709 // Choose either the 32-bit or 64-bit version. 2710 ExprResult LastIteration = LastIteration64; 2711 if (LastIteration32.isUsable() && 2712 C.getTypeSize(LastIteration32.get()->getType()) == 32 && 2713 (AllCountsNeedLessThan32Bits || NestedLoopCount == 1 || 2714 FitsInto( 2715 32 /* Bits */, 2716 LastIteration32.get()->getType()->hasSignedIntegerRepresentation(), 2717 LastIteration64.get(), SemaRef))) 2718 LastIteration = LastIteration32; 2719 2720 if (!LastIteration.isUsable()) 2721 return 0; 2722 2723 // Save the number of iterations. 2724 ExprResult NumIterations = LastIteration; 2725 { 2726 LastIteration = SemaRef.BuildBinOp( 2727 CurScope, SourceLocation(), BO_Sub, LastIteration.get(), 2728 SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get()); 2729 if (!LastIteration.isUsable()) 2730 return 0; 2731 } 2732 2733 // Calculate the last iteration number beforehand instead of doing this on 2734 // each iteration. Do not do this if the number of iterations may be kfold-ed. 2735 llvm::APSInt Result; 2736 bool IsConstant = 2737 LastIteration.get()->isIntegerConstantExpr(Result, SemaRef.Context); 2738 ExprResult CalcLastIteration; 2739 if (!IsConstant) { 2740 SourceLocation SaveLoc; 2741 VarDecl *SaveVar = 2742 BuildVarDecl(SemaRef, SaveLoc, LastIteration.get()->getType(), 2743 ".omp.last.iteration"); 2744 ExprResult SaveRef = SemaRef.BuildDeclRefExpr( 2745 SaveVar, LastIteration.get()->getType(), VK_LValue, SaveLoc); 2746 CalcLastIteration = SemaRef.BuildBinOp(CurScope, SaveLoc, BO_Assign, 2747 SaveRef.get(), LastIteration.get()); 2748 LastIteration = SaveRef; 2749 2750 // Prepare SaveRef + 1. 2751 NumIterations = SemaRef.BuildBinOp( 2752 CurScope, SaveLoc, BO_Add, SaveRef.get(), 2753 SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get()); 2754 if (!NumIterations.isUsable()) 2755 return 0; 2756 } 2757 2758 SourceLocation InitLoc = IterSpaces[0].InitSrcRange.getBegin(); 2759 2760 // Precondition tests if there is at least one iteration (LastIteration > 0). 2761 ExprResult PreCond = SemaRef.BuildBinOp( 2762 CurScope, InitLoc, BO_GT, LastIteration.get(), 2763 SemaRef.ActOnIntegerConstant(SourceLocation(), 0).get()); 2764 2765 // Build the iteration variable and its initialization to zero before loop. 2766 ExprResult IV; 2767 ExprResult Init; 2768 { 2769 VarDecl *IVDecl = BuildVarDecl(SemaRef, InitLoc, 2770 LastIteration.get()->getType(), ".omp.iv"); 2771 IV = SemaRef.BuildDeclRefExpr(IVDecl, LastIteration.get()->getType(), 2772 VK_LValue, InitLoc); 2773 Init = SemaRef.BuildBinOp( 2774 CurScope, InitLoc, BO_Assign, IV.get(), 2775 SemaRef.ActOnIntegerConstant(SourceLocation(), 0).get()); 2776 } 2777 2778 // Loop condition (IV < NumIterations) 2779 SourceLocation CondLoc; 2780 ExprResult Cond = SemaRef.BuildBinOp(CurScope, CondLoc, BO_LT, IV.get(), 2781 NumIterations.get()); 2782 // Loop condition with 1 iteration separated (IV < LastIteration) 2783 ExprResult SeparatedCond = SemaRef.BuildBinOp(CurScope, CondLoc, BO_LT, 2784 IV.get(), LastIteration.get()); 2785 2786 // Loop increment (IV = IV + 1) 2787 SourceLocation IncLoc; 2788 ExprResult Inc = 2789 SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, IV.get(), 2790 SemaRef.ActOnIntegerConstant(IncLoc, 1).get()); 2791 if (!Inc.isUsable()) 2792 return 0; 2793 Inc = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, IV.get(), Inc.get()); 2794 2795 // Build updates and final values of the loop counters. 2796 bool HasErrors = false; 2797 Built.Counters.resize(NestedLoopCount); 2798 Built.Updates.resize(NestedLoopCount); 2799 Built.Finals.resize(NestedLoopCount); 2800 { 2801 ExprResult Div; 2802 // Go from inner nested loop to outer. 2803 for (int Cnt = NestedLoopCount - 1; Cnt >= 0; --Cnt) { 2804 LoopIterationSpace &IS = IterSpaces[Cnt]; 2805 SourceLocation UpdLoc = IS.IncSrcRange.getBegin(); 2806 // Build: Iter = (IV / Div) % IS.NumIters 2807 // where Div is product of previous iterations' IS.NumIters. 2808 ExprResult Iter; 2809 if (Div.isUsable()) { 2810 Iter = 2811 SemaRef.BuildBinOp(CurScope, UpdLoc, BO_Div, IV.get(), Div.get()); 2812 } else { 2813 Iter = IV; 2814 assert((Cnt == (int)NestedLoopCount - 1) && 2815 "unusable div expected on first iteration only"); 2816 } 2817 2818 if (Cnt != 0 && Iter.isUsable()) 2819 Iter = SemaRef.BuildBinOp(CurScope, UpdLoc, BO_Rem, Iter.get(), 2820 IS.NumIterations); 2821 if (!Iter.isUsable()) { 2822 HasErrors = true; 2823 break; 2824 } 2825 2826 // Build update: IS.CounterVar = IS.Start + Iter * IS.Step 2827 ExprResult Update = 2828 BuildCounterUpdate(SemaRef, CurScope, UpdLoc, IS.CounterVar, 2829 IS.CounterInit, Iter, IS.CounterStep, IS.Subtract); 2830 if (!Update.isUsable()) { 2831 HasErrors = true; 2832 break; 2833 } 2834 2835 // Build final: IS.CounterVar = IS.Start + IS.NumIters * IS.Step 2836 ExprResult Final = BuildCounterUpdate( 2837 SemaRef, CurScope, UpdLoc, IS.CounterVar, IS.CounterInit, 2838 IS.NumIterations, IS.CounterStep, IS.Subtract); 2839 if (!Final.isUsable()) { 2840 HasErrors = true; 2841 break; 2842 } 2843 2844 // Build Div for the next iteration: Div <- Div * IS.NumIters 2845 if (Cnt != 0) { 2846 if (Div.isUnset()) 2847 Div = IS.NumIterations; 2848 else 2849 Div = SemaRef.BuildBinOp(CurScope, UpdLoc, BO_Mul, Div.get(), 2850 IS.NumIterations); 2851 2852 // Add parentheses (for debugging purposes only). 2853 if (Div.isUsable()) 2854 Div = SemaRef.ActOnParenExpr(UpdLoc, UpdLoc, Div.get()); 2855 if (!Div.isUsable()) { 2856 HasErrors = true; 2857 break; 2858 } 2859 } 2860 if (!Update.isUsable() || !Final.isUsable()) { 2861 HasErrors = true; 2862 break; 2863 } 2864 // Save results 2865 Built.Counters[Cnt] = IS.CounterVar; 2866 Built.Updates[Cnt] = Update.get(); 2867 Built.Finals[Cnt] = Final.get(); 2868 } 2869 } 2870 2871 if (HasErrors) 2872 return 0; 2873 2874 // Save results 2875 Built.IterationVarRef = IV.get(); 2876 Built.LastIteration = LastIteration.get(); 2877 Built.CalcLastIteration = CalcLastIteration.get(); 2878 Built.PreCond = PreCond.get(); 2879 Built.Cond = Cond.get(); 2880 Built.SeparatedCond = SeparatedCond.get(); 2881 Built.Init = Init.get(); 2882 Built.Inc = Inc.get(); 2883 2884 return NestedLoopCount; 2885 } 2886 2887 static Expr *GetCollapseNumberExpr(ArrayRef<OMPClause *> Clauses) { 2888 auto CollapseFilter = [](const OMPClause *C) -> bool { 2889 return C->getClauseKind() == OMPC_collapse; 2890 }; 2891 OMPExecutableDirective::filtered_clause_iterator<decltype(CollapseFilter)> I( 2892 Clauses, CollapseFilter); 2893 if (I) 2894 return cast<OMPCollapseClause>(*I)->getNumForLoops(); 2895 return nullptr; 2896 } 2897 2898 StmtResult Sema::ActOnOpenMPSimdDirective( 2899 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, 2900 SourceLocation EndLoc, 2901 llvm::DenseMap<VarDecl *, Expr *> &VarsWithImplicitDSA) { 2902 BuiltLoopExprs B; 2903 // In presence of clause 'collapse', it will define the nested loops number. 2904 unsigned NestedLoopCount = 2905 CheckOpenMPLoop(OMPD_simd, GetCollapseNumberExpr(Clauses), AStmt, *this, 2906 *DSAStack, VarsWithImplicitDSA, B); 2907 if (NestedLoopCount == 0) 2908 return StmtError(); 2909 2910 assert((CurContext->isDependentContext() || B.builtAll()) && 2911 "omp simd loop exprs were not built"); 2912 2913 getCurFunction()->setHasBranchProtectedScope(); 2914 return OMPSimdDirective::Create( 2915 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, 2916 B.IterationVarRef, B.LastIteration, B.CalcLastIteration, B.PreCond, 2917 B.Cond, B.SeparatedCond, B.Init, B.Inc, B.Counters, B.Updates, B.Finals); 2918 } 2919 2920 StmtResult Sema::ActOnOpenMPForDirective( 2921 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, 2922 SourceLocation EndLoc, 2923 llvm::DenseMap<VarDecl *, Expr *> &VarsWithImplicitDSA) { 2924 BuiltLoopExprs B; 2925 // In presence of clause 'collapse', it will define the nested loops number. 2926 unsigned NestedLoopCount = 2927 CheckOpenMPLoop(OMPD_for, GetCollapseNumberExpr(Clauses), AStmt, *this, 2928 *DSAStack, VarsWithImplicitDSA, B); 2929 if (NestedLoopCount == 0) 2930 return StmtError(); 2931 2932 assert((CurContext->isDependentContext() || B.builtAll()) && 2933 "omp for loop exprs were not built"); 2934 2935 getCurFunction()->setHasBranchProtectedScope(); 2936 return OMPForDirective::Create( 2937 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, 2938 B.IterationVarRef, B.LastIteration, B.CalcLastIteration, B.PreCond, 2939 B.Cond, B.SeparatedCond, B.Init, B.Inc, B.Counters, B.Updates, B.Finals); 2940 } 2941 2942 StmtResult Sema::ActOnOpenMPForSimdDirective( 2943 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, 2944 SourceLocation EndLoc, 2945 llvm::DenseMap<VarDecl *, Expr *> &VarsWithImplicitDSA) { 2946 BuiltLoopExprs B; 2947 // In presence of clause 'collapse', it will define the nested loops number. 2948 unsigned NestedLoopCount = 2949 CheckOpenMPLoop(OMPD_for_simd, GetCollapseNumberExpr(Clauses), AStmt, 2950 *this, *DSAStack, VarsWithImplicitDSA, B); 2951 if (NestedLoopCount == 0) 2952 return StmtError(); 2953 2954 getCurFunction()->setHasBranchProtectedScope(); 2955 return OMPForSimdDirective::Create( 2956 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, 2957 B.IterationVarRef, B.LastIteration, B.CalcLastIteration, B.PreCond, 2958 B.Cond, B.SeparatedCond, B.Init, B.Inc, B.Counters, B.Updates, B.Finals); 2959 } 2960 2961 StmtResult Sema::ActOnOpenMPSectionsDirective(ArrayRef<OMPClause *> Clauses, 2962 Stmt *AStmt, 2963 SourceLocation StartLoc, 2964 SourceLocation EndLoc) { 2965 assert(AStmt && isa<CapturedStmt>(AStmt) && "Captured statement expected"); 2966 auto BaseStmt = AStmt; 2967 while (CapturedStmt *CS = dyn_cast_or_null<CapturedStmt>(BaseStmt)) 2968 BaseStmt = CS->getCapturedStmt(); 2969 if (auto C = dyn_cast_or_null<CompoundStmt>(BaseStmt)) { 2970 auto S = C->children(); 2971 if (!S) 2972 return StmtError(); 2973 // All associated statements must be '#pragma omp section' except for 2974 // the first one. 2975 for (++S; S; ++S) { 2976 auto SectionStmt = *S; 2977 if (!SectionStmt || !isa<OMPSectionDirective>(SectionStmt)) { 2978 if (SectionStmt) 2979 Diag(SectionStmt->getLocStart(), 2980 diag::err_omp_sections_substmt_not_section); 2981 return StmtError(); 2982 } 2983 } 2984 } else { 2985 Diag(AStmt->getLocStart(), diag::err_omp_sections_not_compound_stmt); 2986 return StmtError(); 2987 } 2988 2989 getCurFunction()->setHasBranchProtectedScope(); 2990 2991 return OMPSectionsDirective::Create(Context, StartLoc, EndLoc, Clauses, 2992 AStmt); 2993 } 2994 2995 StmtResult Sema::ActOnOpenMPSectionDirective(Stmt *AStmt, 2996 SourceLocation StartLoc, 2997 SourceLocation EndLoc) { 2998 assert(AStmt && isa<CapturedStmt>(AStmt) && "Captured statement expected"); 2999 3000 getCurFunction()->setHasBranchProtectedScope(); 3001 3002 return OMPSectionDirective::Create(Context, StartLoc, EndLoc, AStmt); 3003 } 3004 3005 StmtResult Sema::ActOnOpenMPSingleDirective(ArrayRef<OMPClause *> Clauses, 3006 Stmt *AStmt, 3007 SourceLocation StartLoc, 3008 SourceLocation EndLoc) { 3009 assert(AStmt && isa<CapturedStmt>(AStmt) && "Captured statement expected"); 3010 3011 getCurFunction()->setHasBranchProtectedScope(); 3012 3013 return OMPSingleDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt); 3014 } 3015 3016 StmtResult Sema::ActOnOpenMPMasterDirective(Stmt *AStmt, 3017 SourceLocation StartLoc, 3018 SourceLocation EndLoc) { 3019 assert(AStmt && isa<CapturedStmt>(AStmt) && "Captured statement expected"); 3020 3021 getCurFunction()->setHasBranchProtectedScope(); 3022 3023 return OMPMasterDirective::Create(Context, StartLoc, EndLoc, AStmt); 3024 } 3025 3026 StmtResult 3027 Sema::ActOnOpenMPCriticalDirective(const DeclarationNameInfo &DirName, 3028 Stmt *AStmt, SourceLocation StartLoc, 3029 SourceLocation EndLoc) { 3030 assert(AStmt && isa<CapturedStmt>(AStmt) && "Captured statement expected"); 3031 3032 getCurFunction()->setHasBranchProtectedScope(); 3033 3034 return OMPCriticalDirective::Create(Context, DirName, StartLoc, EndLoc, 3035 AStmt); 3036 } 3037 3038 StmtResult Sema::ActOnOpenMPParallelForDirective( 3039 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, 3040 SourceLocation EndLoc, 3041 llvm::DenseMap<VarDecl *, Expr *> &VarsWithImplicitDSA) { 3042 assert(AStmt && isa<CapturedStmt>(AStmt) && "Captured statement expected"); 3043 CapturedStmt *CS = cast<CapturedStmt>(AStmt); 3044 // 1.2.2 OpenMP Language Terminology 3045 // Structured block - An executable statement with a single entry at the 3046 // top and a single exit at the bottom. 3047 // The point of exit cannot be a branch out of the structured block. 3048 // longjmp() and throw() must not violate the entry/exit criteria. 3049 CS->getCapturedDecl()->setNothrow(); 3050 3051 BuiltLoopExprs B; 3052 // In presence of clause 'collapse', it will define the nested loops number. 3053 unsigned NestedLoopCount = 3054 CheckOpenMPLoop(OMPD_parallel_for, GetCollapseNumberExpr(Clauses), AStmt, 3055 *this, *DSAStack, VarsWithImplicitDSA, B); 3056 if (NestedLoopCount == 0) 3057 return StmtError(); 3058 3059 assert((CurContext->isDependentContext() || B.builtAll()) && 3060 "omp parallel for loop exprs were not built"); 3061 3062 getCurFunction()->setHasBranchProtectedScope(); 3063 return OMPParallelForDirective::Create( 3064 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, 3065 B.IterationVarRef, B.LastIteration, B.CalcLastIteration, B.PreCond, 3066 B.Cond, B.SeparatedCond, B.Init, B.Inc, B.Counters, B.Updates, B.Finals); 3067 } 3068 3069 StmtResult Sema::ActOnOpenMPParallelForSimdDirective( 3070 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, 3071 SourceLocation EndLoc, 3072 llvm::DenseMap<VarDecl *, Expr *> &VarsWithImplicitDSA) { 3073 assert(AStmt && isa<CapturedStmt>(AStmt) && "Captured statement expected"); 3074 CapturedStmt *CS = cast<CapturedStmt>(AStmt); 3075 // 1.2.2 OpenMP Language Terminology 3076 // Structured block - An executable statement with a single entry at the 3077 // top and a single exit at the bottom. 3078 // The point of exit cannot be a branch out of the structured block. 3079 // longjmp() and throw() must not violate the entry/exit criteria. 3080 CS->getCapturedDecl()->setNothrow(); 3081 3082 BuiltLoopExprs B; 3083 // In presence of clause 'collapse', it will define the nested loops number. 3084 unsigned NestedLoopCount = 3085 CheckOpenMPLoop(OMPD_parallel_for_simd, GetCollapseNumberExpr(Clauses), 3086 AStmt, *this, *DSAStack, VarsWithImplicitDSA, B); 3087 if (NestedLoopCount == 0) 3088 return StmtError(); 3089 3090 getCurFunction()->setHasBranchProtectedScope(); 3091 return OMPParallelForSimdDirective::Create( 3092 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, 3093 B.IterationVarRef, B.LastIteration, B.CalcLastIteration, B.PreCond, 3094 B.Cond, B.SeparatedCond, B.Init, B.Inc, B.Counters, B.Updates, B.Finals); 3095 } 3096 3097 StmtResult 3098 Sema::ActOnOpenMPParallelSectionsDirective(ArrayRef<OMPClause *> Clauses, 3099 Stmt *AStmt, SourceLocation StartLoc, 3100 SourceLocation EndLoc) { 3101 assert(AStmt && isa<CapturedStmt>(AStmt) && "Captured statement expected"); 3102 auto BaseStmt = AStmt; 3103 while (CapturedStmt *CS = dyn_cast_or_null<CapturedStmt>(BaseStmt)) 3104 BaseStmt = CS->getCapturedStmt(); 3105 if (auto C = dyn_cast_or_null<CompoundStmt>(BaseStmt)) { 3106 auto S = C->children(); 3107 if (!S) 3108 return StmtError(); 3109 // All associated statements must be '#pragma omp section' except for 3110 // the first one. 3111 for (++S; S; ++S) { 3112 auto SectionStmt = *S; 3113 if (!SectionStmt || !isa<OMPSectionDirective>(SectionStmt)) { 3114 if (SectionStmt) 3115 Diag(SectionStmt->getLocStart(), 3116 diag::err_omp_parallel_sections_substmt_not_section); 3117 return StmtError(); 3118 } 3119 } 3120 } else { 3121 Diag(AStmt->getLocStart(), 3122 diag::err_omp_parallel_sections_not_compound_stmt); 3123 return StmtError(); 3124 } 3125 3126 getCurFunction()->setHasBranchProtectedScope(); 3127 3128 return OMPParallelSectionsDirective::Create(Context, StartLoc, EndLoc, 3129 Clauses, AStmt); 3130 } 3131 3132 StmtResult Sema::ActOnOpenMPTaskDirective(ArrayRef<OMPClause *> Clauses, 3133 Stmt *AStmt, SourceLocation StartLoc, 3134 SourceLocation EndLoc) { 3135 assert(AStmt && isa<CapturedStmt>(AStmt) && "Captured statement expected"); 3136 CapturedStmt *CS = cast<CapturedStmt>(AStmt); 3137 // 1.2.2 OpenMP Language Terminology 3138 // Structured block - An executable statement with a single entry at the 3139 // top and a single exit at the bottom. 3140 // The point of exit cannot be a branch out of the structured block. 3141 // longjmp() and throw() must not violate the entry/exit criteria. 3142 CS->getCapturedDecl()->setNothrow(); 3143 3144 getCurFunction()->setHasBranchProtectedScope(); 3145 3146 return OMPTaskDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt); 3147 } 3148 3149 StmtResult Sema::ActOnOpenMPTaskyieldDirective(SourceLocation StartLoc, 3150 SourceLocation EndLoc) { 3151 return OMPTaskyieldDirective::Create(Context, StartLoc, EndLoc); 3152 } 3153 3154 StmtResult Sema::ActOnOpenMPBarrierDirective(SourceLocation StartLoc, 3155 SourceLocation EndLoc) { 3156 return OMPBarrierDirective::Create(Context, StartLoc, EndLoc); 3157 } 3158 3159 StmtResult Sema::ActOnOpenMPTaskwaitDirective(SourceLocation StartLoc, 3160 SourceLocation EndLoc) { 3161 return OMPTaskwaitDirective::Create(Context, StartLoc, EndLoc); 3162 } 3163 3164 StmtResult Sema::ActOnOpenMPFlushDirective(ArrayRef<OMPClause *> Clauses, 3165 SourceLocation StartLoc, 3166 SourceLocation EndLoc) { 3167 assert(Clauses.size() <= 1 && "Extra clauses in flush directive"); 3168 return OMPFlushDirective::Create(Context, StartLoc, EndLoc, Clauses); 3169 } 3170 3171 StmtResult Sema::ActOnOpenMPOrderedDirective(Stmt *AStmt, 3172 SourceLocation StartLoc, 3173 SourceLocation EndLoc) { 3174 assert(AStmt && isa<CapturedStmt>(AStmt) && "Captured statement expected"); 3175 3176 getCurFunction()->setHasBranchProtectedScope(); 3177 3178 return OMPOrderedDirective::Create(Context, StartLoc, EndLoc, AStmt); 3179 } 3180 3181 StmtResult Sema::ActOnOpenMPAtomicDirective(ArrayRef<OMPClause *> Clauses, 3182 Stmt *AStmt, 3183 SourceLocation StartLoc, 3184 SourceLocation EndLoc) { 3185 assert(AStmt && isa<CapturedStmt>(AStmt) && "Captured statement expected"); 3186 auto CS = cast<CapturedStmt>(AStmt); 3187 // 1.2.2 OpenMP Language Terminology 3188 // Structured block - An executable statement with a single entry at the 3189 // top and a single exit at the bottom. 3190 // The point of exit cannot be a branch out of the structured block. 3191 // longjmp() and throw() must not violate the entry/exit criteria. 3192 // TODO further analysis of associated statements and clauses. 3193 OpenMPClauseKind AtomicKind = OMPC_unknown; 3194 SourceLocation AtomicKindLoc; 3195 for (auto *C : Clauses) { 3196 if (C->getClauseKind() == OMPC_read || C->getClauseKind() == OMPC_write || 3197 C->getClauseKind() == OMPC_update || 3198 C->getClauseKind() == OMPC_capture) { 3199 if (AtomicKind != OMPC_unknown) { 3200 Diag(C->getLocStart(), diag::err_omp_atomic_several_clauses) 3201 << SourceRange(C->getLocStart(), C->getLocEnd()); 3202 Diag(AtomicKindLoc, diag::note_omp_atomic_previous_clause) 3203 << getOpenMPClauseName(AtomicKind); 3204 } else { 3205 AtomicKind = C->getClauseKind(); 3206 AtomicKindLoc = C->getLocStart(); 3207 } 3208 } 3209 } 3210 auto Body = CS->getCapturedStmt(); 3211 if (AtomicKind == OMPC_read) { 3212 if (!isa<Expr>(Body)) { 3213 Diag(Body->getLocStart(), 3214 diag::err_omp_atomic_read_not_expression_statement); 3215 return StmtError(); 3216 } 3217 } else if (AtomicKind == OMPC_write) { 3218 if (!isa<Expr>(Body)) { 3219 Diag(Body->getLocStart(), 3220 diag::err_omp_atomic_write_not_expression_statement); 3221 return StmtError(); 3222 } 3223 } else if (AtomicKind == OMPC_update || AtomicKind == OMPC_unknown) { 3224 if (!isa<Expr>(Body)) { 3225 Diag(Body->getLocStart(), 3226 diag::err_omp_atomic_update_not_expression_statement) 3227 << (AtomicKind == OMPC_update); 3228 return StmtError(); 3229 } 3230 } else if (AtomicKind == OMPC_capture) { 3231 if (isa<Expr>(Body) && !isa<BinaryOperator>(Body)) { 3232 Diag(Body->getLocStart(), 3233 diag::err_omp_atomic_capture_not_expression_statement); 3234 return StmtError(); 3235 } else if (!isa<Expr>(Body) && !isa<CompoundStmt>(Body)) { 3236 Diag(Body->getLocStart(), 3237 diag::err_omp_atomic_capture_not_compound_statement); 3238 return StmtError(); 3239 } 3240 } 3241 3242 getCurFunction()->setHasBranchProtectedScope(); 3243 3244 return OMPAtomicDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt); 3245 } 3246 3247 StmtResult Sema::ActOnOpenMPTargetDirective(ArrayRef<OMPClause *> Clauses, 3248 Stmt *AStmt, 3249 SourceLocation StartLoc, 3250 SourceLocation EndLoc) { 3251 assert(AStmt && isa<CapturedStmt>(AStmt) && "Captured statement expected"); 3252 3253 // OpenMP [2.16, Nesting of Regions] 3254 // If specified, a teams construct must be contained within a target 3255 // construct. That target construct must contain no statements or directives 3256 // outside of the teams construct. 3257 if (DSAStack->hasInnerTeamsRegion()) { 3258 auto S = AStmt->IgnoreContainers(/*IgnoreCaptured*/ true); 3259 bool OMPTeamsFound = true; 3260 if (auto *CS = dyn_cast<CompoundStmt>(S)) { 3261 auto I = CS->body_begin(); 3262 while (I != CS->body_end()) { 3263 auto OED = dyn_cast<OMPExecutableDirective>(*I); 3264 if (!OED || !isOpenMPTeamsDirective(OED->getDirectiveKind())) { 3265 OMPTeamsFound = false; 3266 break; 3267 } 3268 ++I; 3269 } 3270 assert(I != CS->body_end() && "Not found statement"); 3271 S = *I; 3272 } 3273 if (!OMPTeamsFound) { 3274 Diag(StartLoc, diag::err_omp_target_contains_not_only_teams); 3275 Diag(DSAStack->getInnerTeamsRegionLoc(), 3276 diag::note_omp_nested_teams_construct_here); 3277 Diag(S->getLocStart(), diag::note_omp_nested_statement_here) 3278 << isa<OMPExecutableDirective>(S); 3279 return StmtError(); 3280 } 3281 } 3282 3283 getCurFunction()->setHasBranchProtectedScope(); 3284 3285 return OMPTargetDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt); 3286 } 3287 3288 StmtResult Sema::ActOnOpenMPTeamsDirective(ArrayRef<OMPClause *> Clauses, 3289 Stmt *AStmt, SourceLocation StartLoc, 3290 SourceLocation EndLoc) { 3291 assert(AStmt && isa<CapturedStmt>(AStmt) && "Captured statement expected"); 3292 CapturedStmt *CS = cast<CapturedStmt>(AStmt); 3293 // 1.2.2 OpenMP Language Terminology 3294 // Structured block - An executable statement with a single entry at the 3295 // top and a single exit at the bottom. 3296 // The point of exit cannot be a branch out of the structured block. 3297 // longjmp() and throw() must not violate the entry/exit criteria. 3298 CS->getCapturedDecl()->setNothrow(); 3299 3300 getCurFunction()->setHasBranchProtectedScope(); 3301 3302 return OMPTeamsDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt); 3303 } 3304 3305 OMPClause *Sema::ActOnOpenMPSingleExprClause(OpenMPClauseKind Kind, Expr *Expr, 3306 SourceLocation StartLoc, 3307 SourceLocation LParenLoc, 3308 SourceLocation EndLoc) { 3309 OMPClause *Res = nullptr; 3310 switch (Kind) { 3311 case OMPC_if: 3312 Res = ActOnOpenMPIfClause(Expr, StartLoc, LParenLoc, EndLoc); 3313 break; 3314 case OMPC_final: 3315 Res = ActOnOpenMPFinalClause(Expr, StartLoc, LParenLoc, EndLoc); 3316 break; 3317 case OMPC_num_threads: 3318 Res = ActOnOpenMPNumThreadsClause(Expr, StartLoc, LParenLoc, EndLoc); 3319 break; 3320 case OMPC_safelen: 3321 Res = ActOnOpenMPSafelenClause(Expr, StartLoc, LParenLoc, EndLoc); 3322 break; 3323 case OMPC_collapse: 3324 Res = ActOnOpenMPCollapseClause(Expr, StartLoc, LParenLoc, EndLoc); 3325 break; 3326 case OMPC_default: 3327 case OMPC_proc_bind: 3328 case OMPC_schedule: 3329 case OMPC_private: 3330 case OMPC_firstprivate: 3331 case OMPC_lastprivate: 3332 case OMPC_shared: 3333 case OMPC_reduction: 3334 case OMPC_linear: 3335 case OMPC_aligned: 3336 case OMPC_copyin: 3337 case OMPC_copyprivate: 3338 case OMPC_ordered: 3339 case OMPC_nowait: 3340 case OMPC_untied: 3341 case OMPC_mergeable: 3342 case OMPC_threadprivate: 3343 case OMPC_flush: 3344 case OMPC_read: 3345 case OMPC_write: 3346 case OMPC_update: 3347 case OMPC_capture: 3348 case OMPC_seq_cst: 3349 case OMPC_unknown: 3350 llvm_unreachable("Clause is not allowed."); 3351 } 3352 return Res; 3353 } 3354 3355 OMPClause *Sema::ActOnOpenMPIfClause(Expr *Condition, SourceLocation StartLoc, 3356 SourceLocation LParenLoc, 3357 SourceLocation EndLoc) { 3358 Expr *ValExpr = Condition; 3359 if (!Condition->isValueDependent() && !Condition->isTypeDependent() && 3360 !Condition->isInstantiationDependent() && 3361 !Condition->containsUnexpandedParameterPack()) { 3362 ExprResult Val = ActOnBooleanCondition(DSAStack->getCurScope(), 3363 Condition->getExprLoc(), Condition); 3364 if (Val.isInvalid()) 3365 return nullptr; 3366 3367 ValExpr = Val.get(); 3368 } 3369 3370 return new (Context) OMPIfClause(ValExpr, StartLoc, LParenLoc, EndLoc); 3371 } 3372 3373 OMPClause *Sema::ActOnOpenMPFinalClause(Expr *Condition, 3374 SourceLocation StartLoc, 3375 SourceLocation LParenLoc, 3376 SourceLocation EndLoc) { 3377 Expr *ValExpr = Condition; 3378 if (!Condition->isValueDependent() && !Condition->isTypeDependent() && 3379 !Condition->isInstantiationDependent() && 3380 !Condition->containsUnexpandedParameterPack()) { 3381 ExprResult Val = ActOnBooleanCondition(DSAStack->getCurScope(), 3382 Condition->getExprLoc(), Condition); 3383 if (Val.isInvalid()) 3384 return nullptr; 3385 3386 ValExpr = Val.get(); 3387 } 3388 3389 return new (Context) OMPFinalClause(ValExpr, StartLoc, LParenLoc, EndLoc); 3390 } 3391 ExprResult Sema::PerformOpenMPImplicitIntegerConversion(SourceLocation Loc, 3392 Expr *Op) { 3393 if (!Op) 3394 return ExprError(); 3395 3396 class IntConvertDiagnoser : public ICEConvertDiagnoser { 3397 public: 3398 IntConvertDiagnoser() 3399 : ICEConvertDiagnoser(/*AllowScopedEnumerations*/ false, false, true) {} 3400 SemaDiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc, 3401 QualType T) override { 3402 return S.Diag(Loc, diag::err_omp_not_integral) << T; 3403 } 3404 SemaDiagnosticBuilder diagnoseIncomplete(Sema &S, SourceLocation Loc, 3405 QualType T) override { 3406 return S.Diag(Loc, diag::err_omp_incomplete_type) << T; 3407 } 3408 SemaDiagnosticBuilder diagnoseExplicitConv(Sema &S, SourceLocation Loc, 3409 QualType T, 3410 QualType ConvTy) override { 3411 return S.Diag(Loc, diag::err_omp_explicit_conversion) << T << ConvTy; 3412 } 3413 SemaDiagnosticBuilder noteExplicitConv(Sema &S, CXXConversionDecl *Conv, 3414 QualType ConvTy) override { 3415 return S.Diag(Conv->getLocation(), diag::note_omp_conversion_here) 3416 << ConvTy->isEnumeralType() << ConvTy; 3417 } 3418 SemaDiagnosticBuilder diagnoseAmbiguous(Sema &S, SourceLocation Loc, 3419 QualType T) override { 3420 return S.Diag(Loc, diag::err_omp_ambiguous_conversion) << T; 3421 } 3422 SemaDiagnosticBuilder noteAmbiguous(Sema &S, CXXConversionDecl *Conv, 3423 QualType ConvTy) override { 3424 return S.Diag(Conv->getLocation(), diag::note_omp_conversion_here) 3425 << ConvTy->isEnumeralType() << ConvTy; 3426 } 3427 SemaDiagnosticBuilder diagnoseConversion(Sema &, SourceLocation, QualType, 3428 QualType) override { 3429 llvm_unreachable("conversion functions are permitted"); 3430 } 3431 } ConvertDiagnoser; 3432 return PerformContextualImplicitConversion(Loc, Op, ConvertDiagnoser); 3433 } 3434 3435 OMPClause *Sema::ActOnOpenMPNumThreadsClause(Expr *NumThreads, 3436 SourceLocation StartLoc, 3437 SourceLocation LParenLoc, 3438 SourceLocation EndLoc) { 3439 Expr *ValExpr = NumThreads; 3440 if (!NumThreads->isValueDependent() && !NumThreads->isTypeDependent() && 3441 !NumThreads->containsUnexpandedParameterPack()) { 3442 SourceLocation NumThreadsLoc = NumThreads->getLocStart(); 3443 ExprResult Val = 3444 PerformOpenMPImplicitIntegerConversion(NumThreadsLoc, NumThreads); 3445 if (Val.isInvalid()) 3446 return nullptr; 3447 3448 ValExpr = Val.get(); 3449 3450 // OpenMP [2.5, Restrictions] 3451 // The num_threads expression must evaluate to a positive integer value. 3452 llvm::APSInt Result; 3453 if (ValExpr->isIntegerConstantExpr(Result, Context) && Result.isSigned() && 3454 !Result.isStrictlyPositive()) { 3455 Diag(NumThreadsLoc, diag::err_omp_negative_expression_in_clause) 3456 << "num_threads" << NumThreads->getSourceRange(); 3457 return nullptr; 3458 } 3459 } 3460 3461 return new (Context) 3462 OMPNumThreadsClause(ValExpr, StartLoc, LParenLoc, EndLoc); 3463 } 3464 3465 ExprResult Sema::VerifyPositiveIntegerConstantInClause(Expr *E, 3466 OpenMPClauseKind CKind) { 3467 if (!E) 3468 return ExprError(); 3469 if (E->isValueDependent() || E->isTypeDependent() || 3470 E->isInstantiationDependent() || E->containsUnexpandedParameterPack()) 3471 return E; 3472 llvm::APSInt Result; 3473 ExprResult ICE = VerifyIntegerConstantExpression(E, &Result); 3474 if (ICE.isInvalid()) 3475 return ExprError(); 3476 if (!Result.isStrictlyPositive()) { 3477 Diag(E->getExprLoc(), diag::err_omp_negative_expression_in_clause) 3478 << getOpenMPClauseName(CKind) << E->getSourceRange(); 3479 return ExprError(); 3480 } 3481 if (CKind == OMPC_aligned && !Result.isPowerOf2()) { 3482 Diag(E->getExprLoc(), diag::warn_omp_alignment_not_power_of_two) 3483 << E->getSourceRange(); 3484 return ExprError(); 3485 } 3486 return ICE; 3487 } 3488 3489 OMPClause *Sema::ActOnOpenMPSafelenClause(Expr *Len, SourceLocation StartLoc, 3490 SourceLocation LParenLoc, 3491 SourceLocation EndLoc) { 3492 // OpenMP [2.8.1, simd construct, Description] 3493 // The parameter of the safelen clause must be a constant 3494 // positive integer expression. 3495 ExprResult Safelen = VerifyPositiveIntegerConstantInClause(Len, OMPC_safelen); 3496 if (Safelen.isInvalid()) 3497 return nullptr; 3498 return new (Context) 3499 OMPSafelenClause(Safelen.get(), StartLoc, LParenLoc, EndLoc); 3500 } 3501 3502 OMPClause *Sema::ActOnOpenMPCollapseClause(Expr *NumForLoops, 3503 SourceLocation StartLoc, 3504 SourceLocation LParenLoc, 3505 SourceLocation EndLoc) { 3506 // OpenMP [2.7.1, loop construct, Description] 3507 // OpenMP [2.8.1, simd construct, Description] 3508 // OpenMP [2.9.6, distribute construct, Description] 3509 // The parameter of the collapse clause must be a constant 3510 // positive integer expression. 3511 ExprResult NumForLoopsResult = 3512 VerifyPositiveIntegerConstantInClause(NumForLoops, OMPC_collapse); 3513 if (NumForLoopsResult.isInvalid()) 3514 return nullptr; 3515 return new (Context) 3516 OMPCollapseClause(NumForLoopsResult.get(), StartLoc, LParenLoc, EndLoc); 3517 } 3518 3519 OMPClause *Sema::ActOnOpenMPSimpleClause( 3520 OpenMPClauseKind Kind, unsigned Argument, SourceLocation ArgumentLoc, 3521 SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc) { 3522 OMPClause *Res = nullptr; 3523 switch (Kind) { 3524 case OMPC_default: 3525 Res = 3526 ActOnOpenMPDefaultClause(static_cast<OpenMPDefaultClauseKind>(Argument), 3527 ArgumentLoc, StartLoc, LParenLoc, EndLoc); 3528 break; 3529 case OMPC_proc_bind: 3530 Res = ActOnOpenMPProcBindClause( 3531 static_cast<OpenMPProcBindClauseKind>(Argument), ArgumentLoc, StartLoc, 3532 LParenLoc, EndLoc); 3533 break; 3534 case OMPC_if: 3535 case OMPC_final: 3536 case OMPC_num_threads: 3537 case OMPC_safelen: 3538 case OMPC_collapse: 3539 case OMPC_schedule: 3540 case OMPC_private: 3541 case OMPC_firstprivate: 3542 case OMPC_lastprivate: 3543 case OMPC_shared: 3544 case OMPC_reduction: 3545 case OMPC_linear: 3546 case OMPC_aligned: 3547 case OMPC_copyin: 3548 case OMPC_copyprivate: 3549 case OMPC_ordered: 3550 case OMPC_nowait: 3551 case OMPC_untied: 3552 case OMPC_mergeable: 3553 case OMPC_threadprivate: 3554 case OMPC_flush: 3555 case OMPC_read: 3556 case OMPC_write: 3557 case OMPC_update: 3558 case OMPC_capture: 3559 case OMPC_seq_cst: 3560 case OMPC_unknown: 3561 llvm_unreachable("Clause is not allowed."); 3562 } 3563 return Res; 3564 } 3565 3566 OMPClause *Sema::ActOnOpenMPDefaultClause(OpenMPDefaultClauseKind Kind, 3567 SourceLocation KindKwLoc, 3568 SourceLocation StartLoc, 3569 SourceLocation LParenLoc, 3570 SourceLocation EndLoc) { 3571 if (Kind == OMPC_DEFAULT_unknown) { 3572 std::string Values; 3573 static_assert(OMPC_DEFAULT_unknown > 0, 3574 "OMPC_DEFAULT_unknown not greater than 0"); 3575 std::string Sep(", "); 3576 for (unsigned i = 0; i < OMPC_DEFAULT_unknown; ++i) { 3577 Values += "'"; 3578 Values += getOpenMPSimpleClauseTypeName(OMPC_default, i); 3579 Values += "'"; 3580 switch (i) { 3581 case OMPC_DEFAULT_unknown - 2: 3582 Values += " or "; 3583 break; 3584 case OMPC_DEFAULT_unknown - 1: 3585 break; 3586 default: 3587 Values += Sep; 3588 break; 3589 } 3590 } 3591 Diag(KindKwLoc, diag::err_omp_unexpected_clause_value) 3592 << Values << getOpenMPClauseName(OMPC_default); 3593 return nullptr; 3594 } 3595 switch (Kind) { 3596 case OMPC_DEFAULT_none: 3597 DSAStack->setDefaultDSANone(KindKwLoc); 3598 break; 3599 case OMPC_DEFAULT_shared: 3600 DSAStack->setDefaultDSAShared(KindKwLoc); 3601 break; 3602 case OMPC_DEFAULT_unknown: 3603 llvm_unreachable("Clause kind is not allowed."); 3604 break; 3605 } 3606 return new (Context) 3607 OMPDefaultClause(Kind, KindKwLoc, StartLoc, LParenLoc, EndLoc); 3608 } 3609 3610 OMPClause *Sema::ActOnOpenMPProcBindClause(OpenMPProcBindClauseKind Kind, 3611 SourceLocation KindKwLoc, 3612 SourceLocation StartLoc, 3613 SourceLocation LParenLoc, 3614 SourceLocation EndLoc) { 3615 if (Kind == OMPC_PROC_BIND_unknown) { 3616 std::string Values; 3617 std::string Sep(", "); 3618 for (unsigned i = 0; i < OMPC_PROC_BIND_unknown; ++i) { 3619 Values += "'"; 3620 Values += getOpenMPSimpleClauseTypeName(OMPC_proc_bind, i); 3621 Values += "'"; 3622 switch (i) { 3623 case OMPC_PROC_BIND_unknown - 2: 3624 Values += " or "; 3625 break; 3626 case OMPC_PROC_BIND_unknown - 1: 3627 break; 3628 default: 3629 Values += Sep; 3630 break; 3631 } 3632 } 3633 Diag(KindKwLoc, diag::err_omp_unexpected_clause_value) 3634 << Values << getOpenMPClauseName(OMPC_proc_bind); 3635 return nullptr; 3636 } 3637 return new (Context) 3638 OMPProcBindClause(Kind, KindKwLoc, StartLoc, LParenLoc, EndLoc); 3639 } 3640 3641 OMPClause *Sema::ActOnOpenMPSingleExprWithArgClause( 3642 OpenMPClauseKind Kind, unsigned Argument, Expr *Expr, 3643 SourceLocation StartLoc, SourceLocation LParenLoc, 3644 SourceLocation ArgumentLoc, SourceLocation CommaLoc, 3645 SourceLocation EndLoc) { 3646 OMPClause *Res = nullptr; 3647 switch (Kind) { 3648 case OMPC_schedule: 3649 Res = ActOnOpenMPScheduleClause( 3650 static_cast<OpenMPScheduleClauseKind>(Argument), Expr, StartLoc, 3651 LParenLoc, ArgumentLoc, CommaLoc, EndLoc); 3652 break; 3653 case OMPC_if: 3654 case OMPC_final: 3655 case OMPC_num_threads: 3656 case OMPC_safelen: 3657 case OMPC_collapse: 3658 case OMPC_default: 3659 case OMPC_proc_bind: 3660 case OMPC_private: 3661 case OMPC_firstprivate: 3662 case OMPC_lastprivate: 3663 case OMPC_shared: 3664 case OMPC_reduction: 3665 case OMPC_linear: 3666 case OMPC_aligned: 3667 case OMPC_copyin: 3668 case OMPC_copyprivate: 3669 case OMPC_ordered: 3670 case OMPC_nowait: 3671 case OMPC_untied: 3672 case OMPC_mergeable: 3673 case OMPC_threadprivate: 3674 case OMPC_flush: 3675 case OMPC_read: 3676 case OMPC_write: 3677 case OMPC_update: 3678 case OMPC_capture: 3679 case OMPC_seq_cst: 3680 case OMPC_unknown: 3681 llvm_unreachable("Clause is not allowed."); 3682 } 3683 return Res; 3684 } 3685 3686 OMPClause *Sema::ActOnOpenMPScheduleClause( 3687 OpenMPScheduleClauseKind Kind, Expr *ChunkSize, SourceLocation StartLoc, 3688 SourceLocation LParenLoc, SourceLocation KindLoc, SourceLocation CommaLoc, 3689 SourceLocation EndLoc) { 3690 if (Kind == OMPC_SCHEDULE_unknown) { 3691 std::string Values; 3692 std::string Sep(", "); 3693 for (unsigned i = 0; i < OMPC_SCHEDULE_unknown; ++i) { 3694 Values += "'"; 3695 Values += getOpenMPSimpleClauseTypeName(OMPC_schedule, i); 3696 Values += "'"; 3697 switch (i) { 3698 case OMPC_SCHEDULE_unknown - 2: 3699 Values += " or "; 3700 break; 3701 case OMPC_SCHEDULE_unknown - 1: 3702 break; 3703 default: 3704 Values += Sep; 3705 break; 3706 } 3707 } 3708 Diag(KindLoc, diag::err_omp_unexpected_clause_value) 3709 << Values << getOpenMPClauseName(OMPC_schedule); 3710 return nullptr; 3711 } 3712 Expr *ValExpr = ChunkSize; 3713 if (ChunkSize) { 3714 if (!ChunkSize->isValueDependent() && !ChunkSize->isTypeDependent() && 3715 !ChunkSize->isInstantiationDependent() && 3716 !ChunkSize->containsUnexpandedParameterPack()) { 3717 SourceLocation ChunkSizeLoc = ChunkSize->getLocStart(); 3718 ExprResult Val = 3719 PerformOpenMPImplicitIntegerConversion(ChunkSizeLoc, ChunkSize); 3720 if (Val.isInvalid()) 3721 return nullptr; 3722 3723 ValExpr = Val.get(); 3724 3725 // OpenMP [2.7.1, Restrictions] 3726 // chunk_size must be a loop invariant integer expression with a positive 3727 // value. 3728 llvm::APSInt Result; 3729 if (ValExpr->isIntegerConstantExpr(Result, Context) && 3730 Result.isSigned() && !Result.isStrictlyPositive()) { 3731 Diag(ChunkSizeLoc, diag::err_omp_negative_expression_in_clause) 3732 << "schedule" << ChunkSize->getSourceRange(); 3733 return nullptr; 3734 } 3735 } 3736 } 3737 3738 return new (Context) OMPScheduleClause(StartLoc, LParenLoc, KindLoc, CommaLoc, 3739 EndLoc, Kind, ValExpr); 3740 } 3741 3742 OMPClause *Sema::ActOnOpenMPClause(OpenMPClauseKind Kind, 3743 SourceLocation StartLoc, 3744 SourceLocation EndLoc) { 3745 OMPClause *Res = nullptr; 3746 switch (Kind) { 3747 case OMPC_ordered: 3748 Res = ActOnOpenMPOrderedClause(StartLoc, EndLoc); 3749 break; 3750 case OMPC_nowait: 3751 Res = ActOnOpenMPNowaitClause(StartLoc, EndLoc); 3752 break; 3753 case OMPC_untied: 3754 Res = ActOnOpenMPUntiedClause(StartLoc, EndLoc); 3755 break; 3756 case OMPC_mergeable: 3757 Res = ActOnOpenMPMergeableClause(StartLoc, EndLoc); 3758 break; 3759 case OMPC_read: 3760 Res = ActOnOpenMPReadClause(StartLoc, EndLoc); 3761 break; 3762 case OMPC_write: 3763 Res = ActOnOpenMPWriteClause(StartLoc, EndLoc); 3764 break; 3765 case OMPC_update: 3766 Res = ActOnOpenMPUpdateClause(StartLoc, EndLoc); 3767 break; 3768 case OMPC_capture: 3769 Res = ActOnOpenMPCaptureClause(StartLoc, EndLoc); 3770 break; 3771 case OMPC_seq_cst: 3772 Res = ActOnOpenMPSeqCstClause(StartLoc, EndLoc); 3773 break; 3774 case OMPC_if: 3775 case OMPC_final: 3776 case OMPC_num_threads: 3777 case OMPC_safelen: 3778 case OMPC_collapse: 3779 case OMPC_schedule: 3780 case OMPC_private: 3781 case OMPC_firstprivate: 3782 case OMPC_lastprivate: 3783 case OMPC_shared: 3784 case OMPC_reduction: 3785 case OMPC_linear: 3786 case OMPC_aligned: 3787 case OMPC_copyin: 3788 case OMPC_copyprivate: 3789 case OMPC_default: 3790 case OMPC_proc_bind: 3791 case OMPC_threadprivate: 3792 case OMPC_flush: 3793 case OMPC_unknown: 3794 llvm_unreachable("Clause is not allowed."); 3795 } 3796 return Res; 3797 } 3798 3799 OMPClause *Sema::ActOnOpenMPOrderedClause(SourceLocation StartLoc, 3800 SourceLocation EndLoc) { 3801 DSAStack->setOrderedRegion(); 3802 return new (Context) OMPOrderedClause(StartLoc, EndLoc); 3803 } 3804 3805 OMPClause *Sema::ActOnOpenMPNowaitClause(SourceLocation StartLoc, 3806 SourceLocation EndLoc) { 3807 return new (Context) OMPNowaitClause(StartLoc, EndLoc); 3808 } 3809 3810 OMPClause *Sema::ActOnOpenMPUntiedClause(SourceLocation StartLoc, 3811 SourceLocation EndLoc) { 3812 return new (Context) OMPUntiedClause(StartLoc, EndLoc); 3813 } 3814 3815 OMPClause *Sema::ActOnOpenMPMergeableClause(SourceLocation StartLoc, 3816 SourceLocation EndLoc) { 3817 return new (Context) OMPMergeableClause(StartLoc, EndLoc); 3818 } 3819 3820 OMPClause *Sema::ActOnOpenMPReadClause(SourceLocation StartLoc, 3821 SourceLocation EndLoc) { 3822 return new (Context) OMPReadClause(StartLoc, EndLoc); 3823 } 3824 3825 OMPClause *Sema::ActOnOpenMPWriteClause(SourceLocation StartLoc, 3826 SourceLocation EndLoc) { 3827 return new (Context) OMPWriteClause(StartLoc, EndLoc); 3828 } 3829 3830 OMPClause *Sema::ActOnOpenMPUpdateClause(SourceLocation StartLoc, 3831 SourceLocation EndLoc) { 3832 return new (Context) OMPUpdateClause(StartLoc, EndLoc); 3833 } 3834 3835 OMPClause *Sema::ActOnOpenMPCaptureClause(SourceLocation StartLoc, 3836 SourceLocation EndLoc) { 3837 return new (Context) OMPCaptureClause(StartLoc, EndLoc); 3838 } 3839 3840 OMPClause *Sema::ActOnOpenMPSeqCstClause(SourceLocation StartLoc, 3841 SourceLocation EndLoc) { 3842 return new (Context) OMPSeqCstClause(StartLoc, EndLoc); 3843 } 3844 3845 OMPClause *Sema::ActOnOpenMPVarListClause( 3846 OpenMPClauseKind Kind, ArrayRef<Expr *> VarList, Expr *TailExpr, 3847 SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation ColonLoc, 3848 SourceLocation EndLoc, CXXScopeSpec &ReductionIdScopeSpec, 3849 const DeclarationNameInfo &ReductionId) { 3850 OMPClause *Res = nullptr; 3851 switch (Kind) { 3852 case OMPC_private: 3853 Res = ActOnOpenMPPrivateClause(VarList, StartLoc, LParenLoc, EndLoc); 3854 break; 3855 case OMPC_firstprivate: 3856 Res = ActOnOpenMPFirstprivateClause(VarList, StartLoc, LParenLoc, EndLoc); 3857 break; 3858 case OMPC_lastprivate: 3859 Res = ActOnOpenMPLastprivateClause(VarList, StartLoc, LParenLoc, EndLoc); 3860 break; 3861 case OMPC_shared: 3862 Res = ActOnOpenMPSharedClause(VarList, StartLoc, LParenLoc, EndLoc); 3863 break; 3864 case OMPC_reduction: 3865 Res = ActOnOpenMPReductionClause(VarList, StartLoc, LParenLoc, ColonLoc, 3866 EndLoc, ReductionIdScopeSpec, ReductionId); 3867 break; 3868 case OMPC_linear: 3869 Res = ActOnOpenMPLinearClause(VarList, TailExpr, StartLoc, LParenLoc, 3870 ColonLoc, EndLoc); 3871 break; 3872 case OMPC_aligned: 3873 Res = ActOnOpenMPAlignedClause(VarList, TailExpr, StartLoc, LParenLoc, 3874 ColonLoc, EndLoc); 3875 break; 3876 case OMPC_copyin: 3877 Res = ActOnOpenMPCopyinClause(VarList, StartLoc, LParenLoc, EndLoc); 3878 break; 3879 case OMPC_copyprivate: 3880 Res = ActOnOpenMPCopyprivateClause(VarList, StartLoc, LParenLoc, EndLoc); 3881 break; 3882 case OMPC_flush: 3883 Res = ActOnOpenMPFlushClause(VarList, StartLoc, LParenLoc, EndLoc); 3884 break; 3885 case OMPC_if: 3886 case OMPC_final: 3887 case OMPC_num_threads: 3888 case OMPC_safelen: 3889 case OMPC_collapse: 3890 case OMPC_default: 3891 case OMPC_proc_bind: 3892 case OMPC_schedule: 3893 case OMPC_ordered: 3894 case OMPC_nowait: 3895 case OMPC_untied: 3896 case OMPC_mergeable: 3897 case OMPC_threadprivate: 3898 case OMPC_read: 3899 case OMPC_write: 3900 case OMPC_update: 3901 case OMPC_capture: 3902 case OMPC_seq_cst: 3903 case OMPC_unknown: 3904 llvm_unreachable("Clause is not allowed."); 3905 } 3906 return Res; 3907 } 3908 3909 OMPClause *Sema::ActOnOpenMPPrivateClause(ArrayRef<Expr *> VarList, 3910 SourceLocation StartLoc, 3911 SourceLocation LParenLoc, 3912 SourceLocation EndLoc) { 3913 SmallVector<Expr *, 8> Vars; 3914 SmallVector<Expr *, 8> PrivateCopies; 3915 for (auto &RefExpr : VarList) { 3916 assert(RefExpr && "NULL expr in OpenMP private clause."); 3917 if (isa<DependentScopeDeclRefExpr>(RefExpr)) { 3918 // It will be analyzed later. 3919 Vars.push_back(RefExpr); 3920 PrivateCopies.push_back(nullptr); 3921 continue; 3922 } 3923 3924 SourceLocation ELoc = RefExpr->getExprLoc(); 3925 // OpenMP [2.1, C/C++] 3926 // A list item is a variable name. 3927 // OpenMP [2.9.3.3, Restrictions, p.1] 3928 // A variable that is part of another variable (as an array or 3929 // structure element) cannot appear in a private clause. 3930 DeclRefExpr *DE = dyn_cast_or_null<DeclRefExpr>(RefExpr); 3931 if (!DE || !isa<VarDecl>(DE->getDecl())) { 3932 Diag(ELoc, diag::err_omp_expected_var_name) << RefExpr->getSourceRange(); 3933 continue; 3934 } 3935 Decl *D = DE->getDecl(); 3936 VarDecl *VD = cast<VarDecl>(D); 3937 3938 QualType Type = VD->getType(); 3939 if (Type->isDependentType() || Type->isInstantiationDependentType()) { 3940 // It will be analyzed later. 3941 Vars.push_back(DE); 3942 PrivateCopies.push_back(nullptr); 3943 continue; 3944 } 3945 3946 // OpenMP [2.9.3.3, Restrictions, C/C++, p.3] 3947 // A variable that appears in a private clause must not have an incomplete 3948 // type or a reference type. 3949 if (RequireCompleteType(ELoc, Type, 3950 diag::err_omp_private_incomplete_type)) { 3951 continue; 3952 } 3953 if (Type->isReferenceType()) { 3954 Diag(ELoc, diag::err_omp_clause_ref_type_arg) 3955 << getOpenMPClauseName(OMPC_private) << Type; 3956 bool IsDecl = 3957 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly; 3958 Diag(VD->getLocation(), 3959 IsDecl ? diag::note_previous_decl : diag::note_defined_here) 3960 << VD; 3961 continue; 3962 } 3963 3964 // OpenMP [2.9.3.3, Restrictions, C/C++, p.1] 3965 // A variable of class type (or array thereof) that appears in a private 3966 // clause requires an accessible, unambiguous default constructor for the 3967 // class type. 3968 while (Type->isArrayType()) { 3969 Type = cast<ArrayType>(Type.getTypePtr())->getElementType(); 3970 } 3971 3972 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced 3973 // in a Construct] 3974 // Variables with the predetermined data-sharing attributes may not be 3975 // listed in data-sharing attributes clauses, except for the cases 3976 // listed below. For these exceptions only, listing a predetermined 3977 // variable in a data-sharing attribute clause is allowed and overrides 3978 // the variable's predetermined data-sharing attributes. 3979 DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(VD, false); 3980 if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_private) { 3981 Diag(ELoc, diag::err_omp_wrong_dsa) << getOpenMPClauseName(DVar.CKind) 3982 << getOpenMPClauseName(OMPC_private); 3983 ReportOriginalDSA(*this, DSAStack, VD, DVar); 3984 continue; 3985 } 3986 3987 // Generate helper private variable and initialize it with the default 3988 // value. The address of the original variable is replaced by the address of 3989 // the new private variable in CodeGen. This new variable is not added to 3990 // IdResolver, so the code in the OpenMP region uses original variable for 3991 // proper diagnostics. 3992 auto VDPrivate = 3993 VarDecl::Create(Context, CurContext, DE->getLocStart(), 3994 DE->getExprLoc(), VD->getIdentifier(), VD->getType(), 3995 VD->getTypeSourceInfo(), /*S*/ SC_Auto); 3996 ActOnUninitializedDecl(VDPrivate, /*TypeMayContainAuto*/ false); 3997 if (VDPrivate->isInvalidDecl()) 3998 continue; 3999 CurContext->addDecl(VDPrivate); 4000 auto VDPrivateRefExpr = DeclRefExpr::Create( 4001 Context, /*QualifierLoc*/ NestedNameSpecifierLoc(), 4002 /*TemplateKWLoc*/ SourceLocation(), VDPrivate, 4003 /*isEnclosingLocal*/ false, /*NameLoc*/ SourceLocation(), DE->getType(), 4004 /*VK*/ VK_LValue); 4005 4006 DSAStack->addDSA(VD, DE, OMPC_private); 4007 Vars.push_back(DE); 4008 PrivateCopies.push_back(VDPrivateRefExpr); 4009 } 4010 4011 if (Vars.empty()) 4012 return nullptr; 4013 4014 return OMPPrivateClause::Create(Context, StartLoc, LParenLoc, EndLoc, Vars, 4015 PrivateCopies); 4016 } 4017 4018 namespace { 4019 class DiagsUninitializedSeveretyRAII { 4020 private: 4021 DiagnosticsEngine &Diags; 4022 SourceLocation SavedLoc; 4023 bool IsIgnored; 4024 4025 public: 4026 DiagsUninitializedSeveretyRAII(DiagnosticsEngine &Diags, SourceLocation Loc, 4027 bool IsIgnored) 4028 : Diags(Diags), SavedLoc(Loc), IsIgnored(IsIgnored) { 4029 if (!IsIgnored) { 4030 Diags.setSeverity(/*Diag*/ diag::warn_uninit_self_reference_in_init, 4031 /*Map*/ diag::Severity::Ignored, Loc); 4032 } 4033 } 4034 ~DiagsUninitializedSeveretyRAII() { 4035 if (!IsIgnored) 4036 Diags.popMappings(SavedLoc); 4037 } 4038 }; 4039 } 4040 4041 OMPClause *Sema::ActOnOpenMPFirstprivateClause(ArrayRef<Expr *> VarList, 4042 SourceLocation StartLoc, 4043 SourceLocation LParenLoc, 4044 SourceLocation EndLoc) { 4045 SmallVector<Expr *, 8> Vars; 4046 SmallVector<Expr *, 8> PrivateCopies; 4047 SmallVector<Expr *, 8> Inits; 4048 bool IsImplicitClause = 4049 StartLoc.isInvalid() && LParenLoc.isInvalid() && EndLoc.isInvalid(); 4050 auto ImplicitClauseLoc = DSAStack->getConstructLoc(); 4051 4052 for (auto &RefExpr : VarList) { 4053 assert(RefExpr && "NULL expr in OpenMP firstprivate clause."); 4054 if (isa<DependentScopeDeclRefExpr>(RefExpr)) { 4055 // It will be analyzed later. 4056 Vars.push_back(RefExpr); 4057 PrivateCopies.push_back(nullptr); 4058 Inits.push_back(nullptr); 4059 continue; 4060 } 4061 4062 SourceLocation ELoc = 4063 IsImplicitClause ? ImplicitClauseLoc : RefExpr->getExprLoc(); 4064 // OpenMP [2.1, C/C++] 4065 // A list item is a variable name. 4066 // OpenMP [2.9.3.3, Restrictions, p.1] 4067 // A variable that is part of another variable (as an array or 4068 // structure element) cannot appear in a private clause. 4069 DeclRefExpr *DE = dyn_cast_or_null<DeclRefExpr>(RefExpr); 4070 if (!DE || !isa<VarDecl>(DE->getDecl())) { 4071 Diag(ELoc, diag::err_omp_expected_var_name) << RefExpr->getSourceRange(); 4072 continue; 4073 } 4074 Decl *D = DE->getDecl(); 4075 VarDecl *VD = cast<VarDecl>(D); 4076 4077 QualType Type = VD->getType(); 4078 if (Type->isDependentType() || Type->isInstantiationDependentType()) { 4079 // It will be analyzed later. 4080 Vars.push_back(DE); 4081 PrivateCopies.push_back(nullptr); 4082 Inits.push_back(nullptr); 4083 continue; 4084 } 4085 4086 // OpenMP [2.9.3.3, Restrictions, C/C++, p.3] 4087 // A variable that appears in a private clause must not have an incomplete 4088 // type or a reference type. 4089 if (RequireCompleteType(ELoc, Type, 4090 diag::err_omp_firstprivate_incomplete_type)) { 4091 continue; 4092 } 4093 if (Type->isReferenceType()) { 4094 if (IsImplicitClause) { 4095 Diag(ImplicitClauseLoc, 4096 diag::err_omp_task_predetermined_firstprivate_ref_type_arg) 4097 << Type; 4098 Diag(RefExpr->getExprLoc(), diag::note_used_here); 4099 } else { 4100 Diag(ELoc, diag::err_omp_clause_ref_type_arg) 4101 << getOpenMPClauseName(OMPC_firstprivate) << Type; 4102 } 4103 bool IsDecl = 4104 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly; 4105 Diag(VD->getLocation(), 4106 IsDecl ? diag::note_previous_decl : diag::note_defined_here) 4107 << VD; 4108 continue; 4109 } 4110 4111 // OpenMP [2.9.3.4, Restrictions, C/C++, p.1] 4112 // A variable of class type (or array thereof) that appears in a private 4113 // clause requires an accessible, unambiguous copy constructor for the 4114 // class type. 4115 Type = Context.getBaseElementType(Type); 4116 4117 // If an implicit firstprivate variable found it was checked already. 4118 if (!IsImplicitClause) { 4119 DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(VD, false); 4120 Type = Type.getNonReferenceType().getCanonicalType(); 4121 bool IsConstant = Type.isConstant(Context); 4122 Type = Context.getBaseElementType(Type); 4123 // OpenMP [2.4.13, Data-sharing Attribute Clauses] 4124 // A list item that specifies a given variable may not appear in more 4125 // than one clause on the same directive, except that a variable may be 4126 // specified in both firstprivate and lastprivate clauses. 4127 if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_firstprivate && 4128 DVar.CKind != OMPC_lastprivate && DVar.RefExpr) { 4129 Diag(ELoc, diag::err_omp_wrong_dsa) 4130 << getOpenMPClauseName(DVar.CKind) 4131 << getOpenMPClauseName(OMPC_firstprivate); 4132 ReportOriginalDSA(*this, DSAStack, VD, DVar); 4133 continue; 4134 } 4135 4136 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced 4137 // in a Construct] 4138 // Variables with the predetermined data-sharing attributes may not be 4139 // listed in data-sharing attributes clauses, except for the cases 4140 // listed below. For these exceptions only, listing a predetermined 4141 // variable in a data-sharing attribute clause is allowed and overrides 4142 // the variable's predetermined data-sharing attributes. 4143 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced 4144 // in a Construct, C/C++, p.2] 4145 // Variables with const-qualified type having no mutable member may be 4146 // listed in a firstprivate clause, even if they are static data members. 4147 if (!(IsConstant || VD->isStaticDataMember()) && !DVar.RefExpr && 4148 DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_shared) { 4149 Diag(ELoc, diag::err_omp_wrong_dsa) 4150 << getOpenMPClauseName(DVar.CKind) 4151 << getOpenMPClauseName(OMPC_firstprivate); 4152 ReportOriginalDSA(*this, DSAStack, VD, DVar); 4153 continue; 4154 } 4155 4156 OpenMPDirectiveKind CurrDir = DSAStack->getCurrentDirective(); 4157 // OpenMP [2.9.3.4, Restrictions, p.2] 4158 // A list item that is private within a parallel region must not appear 4159 // in a firstprivate clause on a worksharing construct if any of the 4160 // worksharing regions arising from the worksharing construct ever bind 4161 // to any of the parallel regions arising from the parallel construct. 4162 if (isOpenMPWorksharingDirective(CurrDir) && 4163 !isOpenMPParallelDirective(CurrDir)) { 4164 DVar = DSAStack->getImplicitDSA(VD, true); 4165 if (DVar.CKind != OMPC_shared && 4166 (isOpenMPParallelDirective(DVar.DKind) || 4167 DVar.DKind == OMPD_unknown)) { 4168 Diag(ELoc, diag::err_omp_required_access) 4169 << getOpenMPClauseName(OMPC_firstprivate) 4170 << getOpenMPClauseName(OMPC_shared); 4171 ReportOriginalDSA(*this, DSAStack, VD, DVar); 4172 continue; 4173 } 4174 } 4175 // OpenMP [2.9.3.4, Restrictions, p.3] 4176 // A list item that appears in a reduction clause of a parallel construct 4177 // must not appear in a firstprivate clause on a worksharing or task 4178 // construct if any of the worksharing or task regions arising from the 4179 // worksharing or task construct ever bind to any of the parallel regions 4180 // arising from the parallel construct. 4181 // OpenMP [2.9.3.4, Restrictions, p.4] 4182 // A list item that appears in a reduction clause in worksharing 4183 // construct must not appear in a firstprivate clause in a task construct 4184 // encountered during execution of any of the worksharing regions arising 4185 // from the worksharing construct. 4186 if (CurrDir == OMPD_task) { 4187 DVar = 4188 DSAStack->hasInnermostDSA(VD, MatchesAnyClause(OMPC_reduction), 4189 [](OpenMPDirectiveKind K) -> bool { 4190 return isOpenMPParallelDirective(K) || 4191 isOpenMPWorksharingDirective(K); 4192 }, 4193 false); 4194 if (DVar.CKind == OMPC_reduction && 4195 (isOpenMPParallelDirective(DVar.DKind) || 4196 isOpenMPWorksharingDirective(DVar.DKind))) { 4197 Diag(ELoc, diag::err_omp_parallel_reduction_in_task_firstprivate) 4198 << getOpenMPDirectiveName(DVar.DKind); 4199 ReportOriginalDSA(*this, DSAStack, VD, DVar); 4200 continue; 4201 } 4202 } 4203 } 4204 4205 Type = Type.getUnqualifiedType(); 4206 auto VDPrivate = VarDecl::Create(Context, CurContext, DE->getLocStart(), 4207 ELoc, VD->getIdentifier(), VD->getType(), 4208 VD->getTypeSourceInfo(), /*S*/ SC_Auto); 4209 // Generate helper private variable and initialize it with the value of the 4210 // original variable. The address of the original variable is replaced by 4211 // the address of the new private variable in the CodeGen. This new variable 4212 // is not added to IdResolver, so the code in the OpenMP region uses 4213 // original variable for proper diagnostics and variable capturing. 4214 Expr *VDInitRefExpr = nullptr; 4215 // For arrays generate initializer for single element and replace it by the 4216 // original array element in CodeGen. 4217 if (DE->getType()->isArrayType()) { 4218 auto VDInit = VarDecl::Create(Context, CurContext, DE->getLocStart(), 4219 ELoc, VD->getIdentifier(), Type, 4220 VD->getTypeSourceInfo(), /*S*/ SC_Auto); 4221 CurContext->addHiddenDecl(VDInit); 4222 VDInitRefExpr = DeclRefExpr::Create( 4223 Context, /*QualifierLoc*/ NestedNameSpecifierLoc(), 4224 /*TemplateKWLoc*/ SourceLocation(), VDInit, 4225 /*isEnclosingLocal*/ false, ELoc, Type, 4226 /*VK*/ VK_LValue); 4227 VDInit->setIsUsed(); 4228 auto Init = DefaultLvalueConversion(VDInitRefExpr).get(); 4229 InitializedEntity Entity = InitializedEntity::InitializeVariable(VDInit); 4230 InitializationKind Kind = InitializationKind::CreateCopy(ELoc, ELoc); 4231 4232 InitializationSequence InitSeq(*this, Entity, Kind, Init); 4233 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Init); 4234 if (Result.isInvalid()) 4235 VDPrivate->setInvalidDecl(); 4236 else 4237 VDPrivate->setInit(Result.getAs<Expr>()); 4238 } else { 4239 AddInitializerToDecl(VDPrivate, DefaultLvalueConversion(DE).get(), 4240 /*DirectInit*/ false, /*TypeMayContainAuto*/ false); 4241 } 4242 if (VDPrivate->isInvalidDecl()) { 4243 if (IsImplicitClause) { 4244 Diag(DE->getExprLoc(), 4245 diag::note_omp_task_predetermined_firstprivate_here); 4246 } 4247 continue; 4248 } 4249 CurContext->addDecl(VDPrivate); 4250 auto VDPrivateRefExpr = DeclRefExpr::Create( 4251 Context, /*QualifierLoc*/ NestedNameSpecifierLoc(), 4252 /*TemplateKWLoc*/ SourceLocation(), VDPrivate, 4253 /*isEnclosingLocal*/ false, DE->getLocStart(), DE->getType(), 4254 /*VK*/ VK_LValue); 4255 DSAStack->addDSA(VD, DE, OMPC_firstprivate); 4256 Vars.push_back(DE); 4257 PrivateCopies.push_back(VDPrivateRefExpr); 4258 Inits.push_back(VDInitRefExpr); 4259 } 4260 4261 if (Vars.empty()) 4262 return nullptr; 4263 4264 return OMPFirstprivateClause::Create(Context, StartLoc, LParenLoc, EndLoc, 4265 Vars, PrivateCopies, Inits); 4266 } 4267 4268 OMPClause *Sema::ActOnOpenMPLastprivateClause(ArrayRef<Expr *> VarList, 4269 SourceLocation StartLoc, 4270 SourceLocation LParenLoc, 4271 SourceLocation EndLoc) { 4272 SmallVector<Expr *, 8> Vars; 4273 for (auto &RefExpr : VarList) { 4274 assert(RefExpr && "NULL expr in OpenMP lastprivate clause."); 4275 if (isa<DependentScopeDeclRefExpr>(RefExpr)) { 4276 // It will be analyzed later. 4277 Vars.push_back(RefExpr); 4278 continue; 4279 } 4280 4281 SourceLocation ELoc = RefExpr->getExprLoc(); 4282 // OpenMP [2.1, C/C++] 4283 // A list item is a variable name. 4284 // OpenMP [2.14.3.5, Restrictions, p.1] 4285 // A variable that is part of another variable (as an array or structure 4286 // element) cannot appear in a lastprivate clause. 4287 DeclRefExpr *DE = dyn_cast_or_null<DeclRefExpr>(RefExpr); 4288 if (!DE || !isa<VarDecl>(DE->getDecl())) { 4289 Diag(ELoc, diag::err_omp_expected_var_name) << RefExpr->getSourceRange(); 4290 continue; 4291 } 4292 Decl *D = DE->getDecl(); 4293 VarDecl *VD = cast<VarDecl>(D); 4294 4295 QualType Type = VD->getType(); 4296 if (Type->isDependentType() || Type->isInstantiationDependentType()) { 4297 // It will be analyzed later. 4298 Vars.push_back(DE); 4299 continue; 4300 } 4301 4302 // OpenMP [2.14.3.5, Restrictions, C/C++, p.2] 4303 // A variable that appears in a lastprivate clause must not have an 4304 // incomplete type or a reference type. 4305 if (RequireCompleteType(ELoc, Type, 4306 diag::err_omp_lastprivate_incomplete_type)) { 4307 continue; 4308 } 4309 if (Type->isReferenceType()) { 4310 Diag(ELoc, diag::err_omp_clause_ref_type_arg) 4311 << getOpenMPClauseName(OMPC_lastprivate) << Type; 4312 bool IsDecl = 4313 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly; 4314 Diag(VD->getLocation(), 4315 IsDecl ? diag::note_previous_decl : diag::note_defined_here) 4316 << VD; 4317 continue; 4318 } 4319 4320 // OpenMP [2.14.1.1, Data-sharing Attribute Rules for Variables Referenced 4321 // in a Construct] 4322 // Variables with the predetermined data-sharing attributes may not be 4323 // listed in data-sharing attributes clauses, except for the cases 4324 // listed below. 4325 DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(VD, false); 4326 if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_lastprivate && 4327 DVar.CKind != OMPC_firstprivate && 4328 (DVar.CKind != OMPC_private || DVar.RefExpr != nullptr)) { 4329 Diag(ELoc, diag::err_omp_wrong_dsa) 4330 << getOpenMPClauseName(DVar.CKind) 4331 << getOpenMPClauseName(OMPC_lastprivate); 4332 ReportOriginalDSA(*this, DSAStack, VD, DVar); 4333 continue; 4334 } 4335 4336 OpenMPDirectiveKind CurrDir = DSAStack->getCurrentDirective(); 4337 // OpenMP [2.14.3.5, Restrictions, p.2] 4338 // A list item that is private within a parallel region, or that appears in 4339 // the reduction clause of a parallel construct, must not appear in a 4340 // lastprivate clause on a worksharing construct if any of the corresponding 4341 // worksharing regions ever binds to any of the corresponding parallel 4342 // regions. 4343 if (isOpenMPWorksharingDirective(CurrDir) && 4344 !isOpenMPParallelDirective(CurrDir)) { 4345 DVar = DSAStack->getImplicitDSA(VD, true); 4346 if (DVar.CKind != OMPC_shared) { 4347 Diag(ELoc, diag::err_omp_required_access) 4348 << getOpenMPClauseName(OMPC_lastprivate) 4349 << getOpenMPClauseName(OMPC_shared); 4350 ReportOriginalDSA(*this, DSAStack, VD, DVar); 4351 continue; 4352 } 4353 } 4354 // OpenMP [2.14.3.5, Restrictions, C++, p.1,2] 4355 // A variable of class type (or array thereof) that appears in a 4356 // lastprivate clause requires an accessible, unambiguous default 4357 // constructor for the class type, unless the list item is also specified 4358 // in a firstprivate clause. 4359 // A variable of class type (or array thereof) that appears in a 4360 // lastprivate clause requires an accessible, unambiguous copy assignment 4361 // operator for the class type. 4362 while (Type.getNonReferenceType()->isArrayType()) 4363 Type = cast<ArrayType>(Type.getNonReferenceType().getTypePtr()) 4364 ->getElementType(); 4365 CXXRecordDecl *RD = getLangOpts().CPlusPlus 4366 ? Type.getNonReferenceType()->getAsCXXRecordDecl() 4367 : nullptr; 4368 // FIXME This code must be replaced by actual copying and destructing of the 4369 // lastprivate variable. 4370 if (RD) { 4371 CXXMethodDecl *MD = LookupCopyingAssignment(RD, 0, false, 0); 4372 DeclAccessPair FoundDecl = DeclAccessPair::make(MD, MD->getAccess()); 4373 if (MD) { 4374 if (CheckMemberAccess(ELoc, RD, FoundDecl) == AR_inaccessible || 4375 MD->isDeleted()) { 4376 Diag(ELoc, diag::err_omp_required_method) 4377 << getOpenMPClauseName(OMPC_lastprivate) << 2; 4378 bool IsDecl = VD->isThisDeclarationADefinition(Context) == 4379 VarDecl::DeclarationOnly; 4380 Diag(VD->getLocation(), 4381 IsDecl ? diag::note_previous_decl : diag::note_defined_here) 4382 << VD; 4383 Diag(RD->getLocation(), diag::note_previous_decl) << RD; 4384 continue; 4385 } 4386 MarkFunctionReferenced(ELoc, MD); 4387 DiagnoseUseOfDecl(MD, ELoc); 4388 } 4389 4390 CXXDestructorDecl *DD = RD->getDestructor(); 4391 if (DD) { 4392 PartialDiagnostic PD = 4393 PartialDiagnostic(PartialDiagnostic::NullDiagnostic()); 4394 if (CheckDestructorAccess(ELoc, DD, PD) == AR_inaccessible || 4395 DD->isDeleted()) { 4396 Diag(ELoc, diag::err_omp_required_method) 4397 << getOpenMPClauseName(OMPC_lastprivate) << 4; 4398 bool IsDecl = VD->isThisDeclarationADefinition(Context) == 4399 VarDecl::DeclarationOnly; 4400 Diag(VD->getLocation(), 4401 IsDecl ? diag::note_previous_decl : diag::note_defined_here) 4402 << VD; 4403 Diag(RD->getLocation(), diag::note_previous_decl) << RD; 4404 continue; 4405 } 4406 MarkFunctionReferenced(ELoc, DD); 4407 DiagnoseUseOfDecl(DD, ELoc); 4408 } 4409 } 4410 4411 if (DVar.CKind != OMPC_firstprivate) 4412 DSAStack->addDSA(VD, DE, OMPC_lastprivate); 4413 Vars.push_back(DE); 4414 } 4415 4416 if (Vars.empty()) 4417 return nullptr; 4418 4419 return OMPLastprivateClause::Create(Context, StartLoc, LParenLoc, EndLoc, 4420 Vars); 4421 } 4422 4423 OMPClause *Sema::ActOnOpenMPSharedClause(ArrayRef<Expr *> VarList, 4424 SourceLocation StartLoc, 4425 SourceLocation LParenLoc, 4426 SourceLocation EndLoc) { 4427 SmallVector<Expr *, 8> Vars; 4428 for (auto &RefExpr : VarList) { 4429 assert(RefExpr && "NULL expr in OpenMP shared clause."); 4430 if (isa<DependentScopeDeclRefExpr>(RefExpr)) { 4431 // It will be analyzed later. 4432 Vars.push_back(RefExpr); 4433 continue; 4434 } 4435 4436 SourceLocation ELoc = RefExpr->getExprLoc(); 4437 // OpenMP [2.1, C/C++] 4438 // A list item is a variable name. 4439 // OpenMP [2.14.3.2, Restrictions, p.1] 4440 // A variable that is part of another variable (as an array or structure 4441 // element) cannot appear in a shared unless it is a static data member 4442 // of a C++ class. 4443 DeclRefExpr *DE = dyn_cast<DeclRefExpr>(RefExpr); 4444 if (!DE || !isa<VarDecl>(DE->getDecl())) { 4445 Diag(ELoc, diag::err_omp_expected_var_name) << RefExpr->getSourceRange(); 4446 continue; 4447 } 4448 Decl *D = DE->getDecl(); 4449 VarDecl *VD = cast<VarDecl>(D); 4450 4451 QualType Type = VD->getType(); 4452 if (Type->isDependentType() || Type->isInstantiationDependentType()) { 4453 // It will be analyzed later. 4454 Vars.push_back(DE); 4455 continue; 4456 } 4457 4458 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced 4459 // in a Construct] 4460 // Variables with the predetermined data-sharing attributes may not be 4461 // listed in data-sharing attributes clauses, except for the cases 4462 // listed below. For these exceptions only, listing a predetermined 4463 // variable in a data-sharing attribute clause is allowed and overrides 4464 // the variable's predetermined data-sharing attributes. 4465 DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(VD, false); 4466 if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_shared && 4467 DVar.RefExpr) { 4468 Diag(ELoc, diag::err_omp_wrong_dsa) << getOpenMPClauseName(DVar.CKind) 4469 << getOpenMPClauseName(OMPC_shared); 4470 ReportOriginalDSA(*this, DSAStack, VD, DVar); 4471 continue; 4472 } 4473 4474 DSAStack->addDSA(VD, DE, OMPC_shared); 4475 Vars.push_back(DE); 4476 } 4477 4478 if (Vars.empty()) 4479 return nullptr; 4480 4481 return OMPSharedClause::Create(Context, StartLoc, LParenLoc, EndLoc, Vars); 4482 } 4483 4484 namespace { 4485 class DSARefChecker : public StmtVisitor<DSARefChecker, bool> { 4486 DSAStackTy *Stack; 4487 4488 public: 4489 bool VisitDeclRefExpr(DeclRefExpr *E) { 4490 if (VarDecl *VD = dyn_cast<VarDecl>(E->getDecl())) { 4491 DSAStackTy::DSAVarData DVar = Stack->getTopDSA(VD, false); 4492 if (DVar.CKind == OMPC_shared && !DVar.RefExpr) 4493 return false; 4494 if (DVar.CKind != OMPC_unknown) 4495 return true; 4496 DSAStackTy::DSAVarData DVarPrivate = 4497 Stack->hasDSA(VD, isOpenMPPrivate, MatchesAlways(), false); 4498 if (DVarPrivate.CKind != OMPC_unknown) 4499 return true; 4500 return false; 4501 } 4502 return false; 4503 } 4504 bool VisitStmt(Stmt *S) { 4505 for (auto Child : S->children()) { 4506 if (Child && Visit(Child)) 4507 return true; 4508 } 4509 return false; 4510 } 4511 explicit DSARefChecker(DSAStackTy *S) : Stack(S) {} 4512 }; 4513 } // namespace 4514 4515 OMPClause *Sema::ActOnOpenMPReductionClause( 4516 ArrayRef<Expr *> VarList, SourceLocation StartLoc, SourceLocation LParenLoc, 4517 SourceLocation ColonLoc, SourceLocation EndLoc, 4518 CXXScopeSpec &ReductionIdScopeSpec, 4519 const DeclarationNameInfo &ReductionId) { 4520 // TODO: Allow scope specification search when 'declare reduction' is 4521 // supported. 4522 assert(ReductionIdScopeSpec.isEmpty() && 4523 "No support for scoped reduction identifiers yet."); 4524 4525 auto DN = ReductionId.getName(); 4526 auto OOK = DN.getCXXOverloadedOperator(); 4527 BinaryOperatorKind BOK = BO_Comma; 4528 4529 // OpenMP [2.14.3.6, reduction clause] 4530 // C 4531 // reduction-identifier is either an identifier or one of the following 4532 // operators: +, -, *, &, |, ^, && and || 4533 // C++ 4534 // reduction-identifier is either an id-expression or one of the following 4535 // operators: +, -, *, &, |, ^, && and || 4536 // FIXME: Only 'min' and 'max' identifiers are supported for now. 4537 switch (OOK) { 4538 case OO_Plus: 4539 case OO_Minus: 4540 BOK = BO_AddAssign; 4541 break; 4542 case OO_Star: 4543 BOK = BO_MulAssign; 4544 break; 4545 case OO_Amp: 4546 BOK = BO_AndAssign; 4547 break; 4548 case OO_Pipe: 4549 BOK = BO_OrAssign; 4550 break; 4551 case OO_Caret: 4552 BOK = BO_XorAssign; 4553 break; 4554 case OO_AmpAmp: 4555 BOK = BO_LAnd; 4556 break; 4557 case OO_PipePipe: 4558 BOK = BO_LOr; 4559 break; 4560 default: 4561 if (auto II = DN.getAsIdentifierInfo()) { 4562 if (II->isStr("max")) 4563 BOK = BO_GT; 4564 else if (II->isStr("min")) 4565 BOK = BO_LT; 4566 } 4567 break; 4568 } 4569 SourceRange ReductionIdRange; 4570 if (ReductionIdScopeSpec.isValid()) { 4571 ReductionIdRange.setBegin(ReductionIdScopeSpec.getBeginLoc()); 4572 } 4573 ReductionIdRange.setEnd(ReductionId.getEndLoc()); 4574 if (BOK == BO_Comma) { 4575 // Not allowed reduction identifier is found. 4576 Diag(ReductionId.getLocStart(), diag::err_omp_unknown_reduction_identifier) 4577 << ReductionIdRange; 4578 return nullptr; 4579 } 4580 4581 SmallVector<Expr *, 8> Vars; 4582 for (auto RefExpr : VarList) { 4583 assert(RefExpr && "nullptr expr in OpenMP reduction clause."); 4584 if (isa<DependentScopeDeclRefExpr>(RefExpr)) { 4585 // It will be analyzed later. 4586 Vars.push_back(RefExpr); 4587 continue; 4588 } 4589 4590 if (RefExpr->isTypeDependent() || RefExpr->isValueDependent() || 4591 RefExpr->isInstantiationDependent() || 4592 RefExpr->containsUnexpandedParameterPack()) { 4593 // It will be analyzed later. 4594 Vars.push_back(RefExpr); 4595 continue; 4596 } 4597 4598 auto ELoc = RefExpr->getExprLoc(); 4599 auto ERange = RefExpr->getSourceRange(); 4600 // OpenMP [2.1, C/C++] 4601 // A list item is a variable or array section, subject to the restrictions 4602 // specified in Section 2.4 on page 42 and in each of the sections 4603 // describing clauses and directives for which a list appears. 4604 // OpenMP [2.14.3.3, Restrictions, p.1] 4605 // A variable that is part of another variable (as an array or 4606 // structure element) cannot appear in a private clause. 4607 auto DE = dyn_cast<DeclRefExpr>(RefExpr); 4608 if (!DE || !isa<VarDecl>(DE->getDecl())) { 4609 Diag(ELoc, diag::err_omp_expected_var_name) << ERange; 4610 continue; 4611 } 4612 auto D = DE->getDecl(); 4613 auto VD = cast<VarDecl>(D); 4614 auto Type = VD->getType(); 4615 // OpenMP [2.9.3.3, Restrictions, C/C++, p.3] 4616 // A variable that appears in a private clause must not have an incomplete 4617 // type or a reference type. 4618 if (RequireCompleteType(ELoc, Type, 4619 diag::err_omp_reduction_incomplete_type)) 4620 continue; 4621 // OpenMP [2.14.3.6, reduction clause, Restrictions] 4622 // Arrays may not appear in a reduction clause. 4623 if (Type.getNonReferenceType()->isArrayType()) { 4624 Diag(ELoc, diag::err_omp_reduction_type_array) << Type << ERange; 4625 bool IsDecl = 4626 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly; 4627 Diag(VD->getLocation(), 4628 IsDecl ? diag::note_previous_decl : diag::note_defined_here) 4629 << VD; 4630 continue; 4631 } 4632 // OpenMP [2.14.3.6, reduction clause, Restrictions] 4633 // A list item that appears in a reduction clause must not be 4634 // const-qualified. 4635 if (Type.getNonReferenceType().isConstant(Context)) { 4636 Diag(ELoc, diag::err_omp_const_variable) 4637 << getOpenMPClauseName(OMPC_reduction) << Type << ERange; 4638 bool IsDecl = 4639 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly; 4640 Diag(VD->getLocation(), 4641 IsDecl ? diag::note_previous_decl : diag::note_defined_here) 4642 << VD; 4643 continue; 4644 } 4645 // OpenMP [2.9.3.6, Restrictions, C/C++, p.4] 4646 // If a list-item is a reference type then it must bind to the same object 4647 // for all threads of the team. 4648 VarDecl *VDDef = VD->getDefinition(); 4649 if (Type->isReferenceType() && VDDef) { 4650 DSARefChecker Check(DSAStack); 4651 if (Check.Visit(VDDef->getInit())) { 4652 Diag(ELoc, diag::err_omp_reduction_ref_type_arg) << ERange; 4653 Diag(VDDef->getLocation(), diag::note_defined_here) << VDDef; 4654 continue; 4655 } 4656 } 4657 // OpenMP [2.14.3.6, reduction clause, Restrictions] 4658 // The type of a list item that appears in a reduction clause must be valid 4659 // for the reduction-identifier. For a max or min reduction in C, the type 4660 // of the list item must be an allowed arithmetic data type: char, int, 4661 // float, double, or _Bool, possibly modified with long, short, signed, or 4662 // unsigned. For a max or min reduction in C++, the type of the list item 4663 // must be an allowed arithmetic data type: char, wchar_t, int, float, 4664 // double, or bool, possibly modified with long, short, signed, or unsigned. 4665 if ((BOK == BO_GT || BOK == BO_LT) && 4666 !(Type->isScalarType() || 4667 (getLangOpts().CPlusPlus && Type->isArithmeticType()))) { 4668 Diag(ELoc, diag::err_omp_clause_not_arithmetic_type_arg) 4669 << getLangOpts().CPlusPlus; 4670 bool IsDecl = 4671 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly; 4672 Diag(VD->getLocation(), 4673 IsDecl ? diag::note_previous_decl : diag::note_defined_here) 4674 << VD; 4675 continue; 4676 } 4677 if ((BOK == BO_OrAssign || BOK == BO_AndAssign || BOK == BO_XorAssign) && 4678 !getLangOpts().CPlusPlus && Type->isFloatingType()) { 4679 Diag(ELoc, diag::err_omp_clause_floating_type_arg); 4680 bool IsDecl = 4681 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly; 4682 Diag(VD->getLocation(), 4683 IsDecl ? diag::note_previous_decl : diag::note_defined_here) 4684 << VD; 4685 continue; 4686 } 4687 bool Suppress = getDiagnostics().getSuppressAllDiagnostics(); 4688 getDiagnostics().setSuppressAllDiagnostics(true); 4689 ExprResult ReductionOp = 4690 BuildBinOp(DSAStack->getCurScope(), ReductionId.getLocStart(), BOK, 4691 RefExpr, RefExpr); 4692 getDiagnostics().setSuppressAllDiagnostics(Suppress); 4693 if (ReductionOp.isInvalid()) { 4694 Diag(ELoc, diag::err_omp_reduction_id_not_compatible) << Type 4695 << ReductionIdRange; 4696 bool IsDecl = 4697 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly; 4698 Diag(VD->getLocation(), 4699 IsDecl ? diag::note_previous_decl : diag::note_defined_here) 4700 << VD; 4701 continue; 4702 } 4703 4704 // OpenMP [2.14.1.1, Data-sharing Attribute Rules for Variables Referenced 4705 // in a Construct] 4706 // Variables with the predetermined data-sharing attributes may not be 4707 // listed in data-sharing attributes clauses, except for the cases 4708 // listed below. For these exceptions only, listing a predetermined 4709 // variable in a data-sharing attribute clause is allowed and overrides 4710 // the variable's predetermined data-sharing attributes. 4711 // OpenMP [2.14.3.6, Restrictions, p.3] 4712 // Any number of reduction clauses can be specified on the directive, 4713 // but a list item can appear only once in the reduction clauses for that 4714 // directive. 4715 DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(VD, false); 4716 if (DVar.CKind == OMPC_reduction) { 4717 Diag(ELoc, diag::err_omp_once_referenced) 4718 << getOpenMPClauseName(OMPC_reduction); 4719 if (DVar.RefExpr) { 4720 Diag(DVar.RefExpr->getExprLoc(), diag::note_omp_referenced); 4721 } 4722 } else if (DVar.CKind != OMPC_unknown) { 4723 Diag(ELoc, diag::err_omp_wrong_dsa) 4724 << getOpenMPClauseName(DVar.CKind) 4725 << getOpenMPClauseName(OMPC_reduction); 4726 ReportOriginalDSA(*this, DSAStack, VD, DVar); 4727 continue; 4728 } 4729 4730 // OpenMP [2.14.3.6, Restrictions, p.1] 4731 // A list item that appears in a reduction clause of a worksharing 4732 // construct must be shared in the parallel regions to which any of the 4733 // worksharing regions arising from the worksharing construct bind. 4734 OpenMPDirectiveKind CurrDir = DSAStack->getCurrentDirective(); 4735 if (isOpenMPWorksharingDirective(CurrDir) && 4736 !isOpenMPParallelDirective(CurrDir)) { 4737 DVar = DSAStack->getImplicitDSA(VD, true); 4738 if (DVar.CKind != OMPC_shared) { 4739 Diag(ELoc, diag::err_omp_required_access) 4740 << getOpenMPClauseName(OMPC_reduction) 4741 << getOpenMPClauseName(OMPC_shared); 4742 ReportOriginalDSA(*this, DSAStack, VD, DVar); 4743 continue; 4744 } 4745 } 4746 4747 CXXRecordDecl *RD = getLangOpts().CPlusPlus 4748 ? Type.getNonReferenceType()->getAsCXXRecordDecl() 4749 : nullptr; 4750 // FIXME This code must be replaced by actual constructing/destructing of 4751 // the reduction variable. 4752 if (RD) { 4753 CXXConstructorDecl *CD = LookupDefaultConstructor(RD); 4754 PartialDiagnostic PD = 4755 PartialDiagnostic(PartialDiagnostic::NullDiagnostic()); 4756 if (!CD || 4757 CheckConstructorAccess(ELoc, CD, 4758 InitializedEntity::InitializeTemporary(Type), 4759 CD->getAccess(), PD) == AR_inaccessible || 4760 CD->isDeleted()) { 4761 Diag(ELoc, diag::err_omp_required_method) 4762 << getOpenMPClauseName(OMPC_reduction) << 0; 4763 bool IsDecl = VD->isThisDeclarationADefinition(Context) == 4764 VarDecl::DeclarationOnly; 4765 Diag(VD->getLocation(), 4766 IsDecl ? diag::note_previous_decl : diag::note_defined_here) 4767 << VD; 4768 Diag(RD->getLocation(), diag::note_previous_decl) << RD; 4769 continue; 4770 } 4771 MarkFunctionReferenced(ELoc, CD); 4772 DiagnoseUseOfDecl(CD, ELoc); 4773 4774 CXXDestructorDecl *DD = RD->getDestructor(); 4775 if (DD) { 4776 if (CheckDestructorAccess(ELoc, DD, PD) == AR_inaccessible || 4777 DD->isDeleted()) { 4778 Diag(ELoc, diag::err_omp_required_method) 4779 << getOpenMPClauseName(OMPC_reduction) << 4; 4780 bool IsDecl = VD->isThisDeclarationADefinition(Context) == 4781 VarDecl::DeclarationOnly; 4782 Diag(VD->getLocation(), 4783 IsDecl ? diag::note_previous_decl : diag::note_defined_here) 4784 << VD; 4785 Diag(RD->getLocation(), diag::note_previous_decl) << RD; 4786 continue; 4787 } 4788 MarkFunctionReferenced(ELoc, DD); 4789 DiagnoseUseOfDecl(DD, ELoc); 4790 } 4791 } 4792 4793 DSAStack->addDSA(VD, DE, OMPC_reduction); 4794 Vars.push_back(DE); 4795 } 4796 4797 if (Vars.empty()) 4798 return nullptr; 4799 4800 return OMPReductionClause::Create( 4801 Context, StartLoc, LParenLoc, ColonLoc, EndLoc, Vars, 4802 ReductionIdScopeSpec.getWithLocInContext(Context), ReductionId); 4803 } 4804 4805 OMPClause *Sema::ActOnOpenMPLinearClause(ArrayRef<Expr *> VarList, Expr *Step, 4806 SourceLocation StartLoc, 4807 SourceLocation LParenLoc, 4808 SourceLocation ColonLoc, 4809 SourceLocation EndLoc) { 4810 SmallVector<Expr *, 8> Vars; 4811 for (auto &RefExpr : VarList) { 4812 assert(RefExpr && "NULL expr in OpenMP linear clause."); 4813 if (isa<DependentScopeDeclRefExpr>(RefExpr)) { 4814 // It will be analyzed later. 4815 Vars.push_back(RefExpr); 4816 continue; 4817 } 4818 4819 // OpenMP [2.14.3.7, linear clause] 4820 // A list item that appears in a linear clause is subject to the private 4821 // clause semantics described in Section 2.14.3.3 on page 159 except as 4822 // noted. In addition, the value of the new list item on each iteration 4823 // of the associated loop(s) corresponds to the value of the original 4824 // list item before entering the construct plus the logical number of 4825 // the iteration times linear-step. 4826 4827 SourceLocation ELoc = RefExpr->getExprLoc(); 4828 // OpenMP [2.1, C/C++] 4829 // A list item is a variable name. 4830 // OpenMP [2.14.3.3, Restrictions, p.1] 4831 // A variable that is part of another variable (as an array or 4832 // structure element) cannot appear in a private clause. 4833 DeclRefExpr *DE = dyn_cast<DeclRefExpr>(RefExpr); 4834 if (!DE || !isa<VarDecl>(DE->getDecl())) { 4835 Diag(ELoc, diag::err_omp_expected_var_name) << RefExpr->getSourceRange(); 4836 continue; 4837 } 4838 4839 VarDecl *VD = cast<VarDecl>(DE->getDecl()); 4840 4841 // OpenMP [2.14.3.7, linear clause] 4842 // A list-item cannot appear in more than one linear clause. 4843 // A list-item that appears in a linear clause cannot appear in any 4844 // other data-sharing attribute clause. 4845 DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(VD, false); 4846 if (DVar.RefExpr) { 4847 Diag(ELoc, diag::err_omp_wrong_dsa) << getOpenMPClauseName(DVar.CKind) 4848 << getOpenMPClauseName(OMPC_linear); 4849 ReportOriginalDSA(*this, DSAStack, VD, DVar); 4850 continue; 4851 } 4852 4853 QualType QType = VD->getType(); 4854 if (QType->isDependentType() || QType->isInstantiationDependentType()) { 4855 // It will be analyzed later. 4856 Vars.push_back(DE); 4857 continue; 4858 } 4859 4860 // A variable must not have an incomplete type or a reference type. 4861 if (RequireCompleteType(ELoc, QType, 4862 diag::err_omp_linear_incomplete_type)) { 4863 continue; 4864 } 4865 if (QType->isReferenceType()) { 4866 Diag(ELoc, diag::err_omp_clause_ref_type_arg) 4867 << getOpenMPClauseName(OMPC_linear) << QType; 4868 bool IsDecl = 4869 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly; 4870 Diag(VD->getLocation(), 4871 IsDecl ? diag::note_previous_decl : diag::note_defined_here) 4872 << VD; 4873 continue; 4874 } 4875 4876 // A list item must not be const-qualified. 4877 if (QType.isConstant(Context)) { 4878 Diag(ELoc, diag::err_omp_const_variable) 4879 << getOpenMPClauseName(OMPC_linear); 4880 bool IsDecl = 4881 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly; 4882 Diag(VD->getLocation(), 4883 IsDecl ? diag::note_previous_decl : diag::note_defined_here) 4884 << VD; 4885 continue; 4886 } 4887 4888 // A list item must be of integral or pointer type. 4889 QType = QType.getUnqualifiedType().getCanonicalType(); 4890 const Type *Ty = QType.getTypePtrOrNull(); 4891 if (!Ty || (!Ty->isDependentType() && !Ty->isIntegralType(Context) && 4892 !Ty->isPointerType())) { 4893 Diag(ELoc, diag::err_omp_linear_expected_int_or_ptr) << QType; 4894 bool IsDecl = 4895 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly; 4896 Diag(VD->getLocation(), 4897 IsDecl ? diag::note_previous_decl : diag::note_defined_here) 4898 << VD; 4899 continue; 4900 } 4901 4902 DSAStack->addDSA(VD, DE, OMPC_linear); 4903 Vars.push_back(DE); 4904 } 4905 4906 if (Vars.empty()) 4907 return nullptr; 4908 4909 Expr *StepExpr = Step; 4910 if (Step && !Step->isValueDependent() && !Step->isTypeDependent() && 4911 !Step->isInstantiationDependent() && 4912 !Step->containsUnexpandedParameterPack()) { 4913 SourceLocation StepLoc = Step->getLocStart(); 4914 ExprResult Val = PerformOpenMPImplicitIntegerConversion(StepLoc, Step); 4915 if (Val.isInvalid()) 4916 return nullptr; 4917 StepExpr = Val.get(); 4918 4919 // Warn about zero linear step (it would be probably better specified as 4920 // making corresponding variables 'const'). 4921 llvm::APSInt Result; 4922 if (StepExpr->isIntegerConstantExpr(Result, Context) && 4923 !Result.isNegative() && !Result.isStrictlyPositive()) 4924 Diag(StepLoc, diag::warn_omp_linear_step_zero) << Vars[0] 4925 << (Vars.size() > 1); 4926 } 4927 4928 return OMPLinearClause::Create(Context, StartLoc, LParenLoc, ColonLoc, EndLoc, 4929 Vars, StepExpr); 4930 } 4931 4932 OMPClause *Sema::ActOnOpenMPAlignedClause( 4933 ArrayRef<Expr *> VarList, Expr *Alignment, SourceLocation StartLoc, 4934 SourceLocation LParenLoc, SourceLocation ColonLoc, SourceLocation EndLoc) { 4935 4936 SmallVector<Expr *, 8> Vars; 4937 for (auto &RefExpr : VarList) { 4938 assert(RefExpr && "NULL expr in OpenMP aligned clause."); 4939 if (isa<DependentScopeDeclRefExpr>(RefExpr)) { 4940 // It will be analyzed later. 4941 Vars.push_back(RefExpr); 4942 continue; 4943 } 4944 4945 SourceLocation ELoc = RefExpr->getExprLoc(); 4946 // OpenMP [2.1, C/C++] 4947 // A list item is a variable name. 4948 DeclRefExpr *DE = dyn_cast<DeclRefExpr>(RefExpr); 4949 if (!DE || !isa<VarDecl>(DE->getDecl())) { 4950 Diag(ELoc, diag::err_omp_expected_var_name) << RefExpr->getSourceRange(); 4951 continue; 4952 } 4953 4954 VarDecl *VD = cast<VarDecl>(DE->getDecl()); 4955 4956 // OpenMP [2.8.1, simd construct, Restrictions] 4957 // The type of list items appearing in the aligned clause must be 4958 // array, pointer, reference to array, or reference to pointer. 4959 QualType QType = DE->getType() 4960 .getNonReferenceType() 4961 .getUnqualifiedType() 4962 .getCanonicalType(); 4963 const Type *Ty = QType.getTypePtrOrNull(); 4964 if (!Ty || (!Ty->isDependentType() && !Ty->isArrayType() && 4965 !Ty->isPointerType())) { 4966 Diag(ELoc, diag::err_omp_aligned_expected_array_or_ptr) 4967 << QType << getLangOpts().CPlusPlus << RefExpr->getSourceRange(); 4968 bool IsDecl = 4969 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly; 4970 Diag(VD->getLocation(), 4971 IsDecl ? diag::note_previous_decl : diag::note_defined_here) 4972 << VD; 4973 continue; 4974 } 4975 4976 // OpenMP [2.8.1, simd construct, Restrictions] 4977 // A list-item cannot appear in more than one aligned clause. 4978 if (DeclRefExpr *PrevRef = DSAStack->addUniqueAligned(VD, DE)) { 4979 Diag(ELoc, diag::err_omp_aligned_twice) << RefExpr->getSourceRange(); 4980 Diag(PrevRef->getExprLoc(), diag::note_omp_explicit_dsa) 4981 << getOpenMPClauseName(OMPC_aligned); 4982 continue; 4983 } 4984 4985 Vars.push_back(DE); 4986 } 4987 4988 // OpenMP [2.8.1, simd construct, Description] 4989 // The parameter of the aligned clause, alignment, must be a constant 4990 // positive integer expression. 4991 // If no optional parameter is specified, implementation-defined default 4992 // alignments for SIMD instructions on the target platforms are assumed. 4993 if (Alignment != nullptr) { 4994 ExprResult AlignResult = 4995 VerifyPositiveIntegerConstantInClause(Alignment, OMPC_aligned); 4996 if (AlignResult.isInvalid()) 4997 return nullptr; 4998 Alignment = AlignResult.get(); 4999 } 5000 if (Vars.empty()) 5001 return nullptr; 5002 5003 return OMPAlignedClause::Create(Context, StartLoc, LParenLoc, ColonLoc, 5004 EndLoc, Vars, Alignment); 5005 } 5006 5007 OMPClause *Sema::ActOnOpenMPCopyinClause(ArrayRef<Expr *> VarList, 5008 SourceLocation StartLoc, 5009 SourceLocation LParenLoc, 5010 SourceLocation EndLoc) { 5011 SmallVector<Expr *, 8> Vars; 5012 for (auto &RefExpr : VarList) { 5013 assert(RefExpr && "NULL expr in OpenMP copyin clause."); 5014 if (isa<DependentScopeDeclRefExpr>(RefExpr)) { 5015 // It will be analyzed later. 5016 Vars.push_back(RefExpr); 5017 continue; 5018 } 5019 5020 SourceLocation ELoc = RefExpr->getExprLoc(); 5021 // OpenMP [2.1, C/C++] 5022 // A list item is a variable name. 5023 // OpenMP [2.14.4.1, Restrictions, p.1] 5024 // A list item that appears in a copyin clause must be threadprivate. 5025 DeclRefExpr *DE = dyn_cast<DeclRefExpr>(RefExpr); 5026 if (!DE || !isa<VarDecl>(DE->getDecl())) { 5027 Diag(ELoc, diag::err_omp_expected_var_name) << RefExpr->getSourceRange(); 5028 continue; 5029 } 5030 5031 Decl *D = DE->getDecl(); 5032 VarDecl *VD = cast<VarDecl>(D); 5033 5034 QualType Type = VD->getType(); 5035 if (Type->isDependentType() || Type->isInstantiationDependentType()) { 5036 // It will be analyzed later. 5037 Vars.push_back(DE); 5038 continue; 5039 } 5040 5041 // OpenMP [2.14.4.1, Restrictions, C/C++, p.1] 5042 // A list item that appears in a copyin clause must be threadprivate. 5043 if (!DSAStack->isThreadPrivate(VD)) { 5044 Diag(ELoc, diag::err_omp_required_access) 5045 << getOpenMPClauseName(OMPC_copyin) 5046 << getOpenMPDirectiveName(OMPD_threadprivate); 5047 continue; 5048 } 5049 5050 // OpenMP [2.14.4.1, Restrictions, C/C++, p.2] 5051 // A variable of class type (or array thereof) that appears in a 5052 // copyin clause requires an accessible, unambiguous copy assignment 5053 // operator for the class type. 5054 Type = Context.getBaseElementType(Type); 5055 CXXRecordDecl *RD = 5056 getLangOpts().CPlusPlus ? Type->getAsCXXRecordDecl() : nullptr; 5057 // FIXME This code must be replaced by actual assignment of the 5058 // threadprivate variable. 5059 if (RD) { 5060 CXXMethodDecl *MD = LookupCopyingAssignment(RD, 0, false, 0); 5061 DeclAccessPair FoundDecl = DeclAccessPair::make(MD, MD->getAccess()); 5062 if (MD) { 5063 if (CheckMemberAccess(ELoc, RD, FoundDecl) == AR_inaccessible || 5064 MD->isDeleted()) { 5065 Diag(ELoc, diag::err_omp_required_method) 5066 << getOpenMPClauseName(OMPC_copyin) << 2; 5067 bool IsDecl = VD->isThisDeclarationADefinition(Context) == 5068 VarDecl::DeclarationOnly; 5069 Diag(VD->getLocation(), 5070 IsDecl ? diag::note_previous_decl : diag::note_defined_here) 5071 << VD; 5072 Diag(RD->getLocation(), diag::note_previous_decl) << RD; 5073 continue; 5074 } 5075 MarkFunctionReferenced(ELoc, MD); 5076 DiagnoseUseOfDecl(MD, ELoc); 5077 } 5078 } 5079 5080 DSAStack->addDSA(VD, DE, OMPC_copyin); 5081 Vars.push_back(DE); 5082 } 5083 5084 if (Vars.empty()) 5085 return nullptr; 5086 5087 return OMPCopyinClause::Create(Context, StartLoc, LParenLoc, EndLoc, Vars); 5088 } 5089 5090 OMPClause *Sema::ActOnOpenMPCopyprivateClause(ArrayRef<Expr *> VarList, 5091 SourceLocation StartLoc, 5092 SourceLocation LParenLoc, 5093 SourceLocation EndLoc) { 5094 SmallVector<Expr *, 8> Vars; 5095 for (auto &RefExpr : VarList) { 5096 assert(RefExpr && "NULL expr in OpenMP copyprivate clause."); 5097 if (isa<DependentScopeDeclRefExpr>(RefExpr)) { 5098 // It will be analyzed later. 5099 Vars.push_back(RefExpr); 5100 continue; 5101 } 5102 5103 SourceLocation ELoc = RefExpr->getExprLoc(); 5104 // OpenMP [2.1, C/C++] 5105 // A list item is a variable name. 5106 // OpenMP [2.14.4.1, Restrictions, p.1] 5107 // A list item that appears in a copyin clause must be threadprivate. 5108 DeclRefExpr *DE = dyn_cast<DeclRefExpr>(RefExpr); 5109 if (!DE || !isa<VarDecl>(DE->getDecl())) { 5110 Diag(ELoc, diag::err_omp_expected_var_name) << RefExpr->getSourceRange(); 5111 continue; 5112 } 5113 5114 Decl *D = DE->getDecl(); 5115 VarDecl *VD = cast<VarDecl>(D); 5116 5117 QualType Type = VD->getType(); 5118 if (Type->isDependentType() || Type->isInstantiationDependentType()) { 5119 // It will be analyzed later. 5120 Vars.push_back(DE); 5121 continue; 5122 } 5123 5124 // OpenMP [2.14.4.2, Restrictions, p.2] 5125 // A list item that appears in a copyprivate clause may not appear in a 5126 // private or firstprivate clause on the single construct. 5127 if (!DSAStack->isThreadPrivate(VD)) { 5128 auto DVar = DSAStack->getTopDSA(VD, false); 5129 if (DVar.CKind != OMPC_copyprivate && DVar.CKind != OMPC_unknown && 5130 !(DVar.CKind == OMPC_private && !DVar.RefExpr)) { 5131 Diag(ELoc, diag::err_omp_wrong_dsa) 5132 << getOpenMPClauseName(DVar.CKind) 5133 << getOpenMPClauseName(OMPC_copyprivate); 5134 ReportOriginalDSA(*this, DSAStack, VD, DVar); 5135 continue; 5136 } 5137 5138 // OpenMP [2.11.4.2, Restrictions, p.1] 5139 // All list items that appear in a copyprivate clause must be either 5140 // threadprivate or private in the enclosing context. 5141 if (DVar.CKind == OMPC_unknown) { 5142 DVar = DSAStack->getImplicitDSA(VD, false); 5143 if (DVar.CKind == OMPC_shared) { 5144 Diag(ELoc, diag::err_omp_required_access) 5145 << getOpenMPClauseName(OMPC_copyprivate) 5146 << "threadprivate or private in the enclosing context"; 5147 ReportOriginalDSA(*this, DSAStack, VD, DVar); 5148 continue; 5149 } 5150 } 5151 } 5152 5153 // OpenMP [2.14.4.1, Restrictions, C/C++, p.2] 5154 // A variable of class type (or array thereof) that appears in a 5155 // copyin clause requires an accessible, unambiguous copy assignment 5156 // operator for the class type. 5157 Type = Context.getBaseElementType(Type); 5158 CXXRecordDecl *RD = 5159 getLangOpts().CPlusPlus ? Type->getAsCXXRecordDecl() : nullptr; 5160 // FIXME This code must be replaced by actual assignment of the 5161 // threadprivate variable. 5162 if (RD) { 5163 CXXMethodDecl *MD = LookupCopyingAssignment(RD, 0, false, 0); 5164 DeclAccessPair FoundDecl = DeclAccessPair::make(MD, MD->getAccess()); 5165 if (MD) { 5166 if (CheckMemberAccess(ELoc, RD, FoundDecl) == AR_inaccessible || 5167 MD->isDeleted()) { 5168 Diag(ELoc, diag::err_omp_required_method) 5169 << getOpenMPClauseName(OMPC_copyprivate) << 2; 5170 bool IsDecl = VD->isThisDeclarationADefinition(Context) == 5171 VarDecl::DeclarationOnly; 5172 Diag(VD->getLocation(), 5173 IsDecl ? diag::note_previous_decl : diag::note_defined_here) 5174 << VD; 5175 Diag(RD->getLocation(), diag::note_previous_decl) << RD; 5176 continue; 5177 } 5178 MarkFunctionReferenced(ELoc, MD); 5179 DiagnoseUseOfDecl(MD, ELoc); 5180 } 5181 } 5182 5183 // No need to mark vars as copyprivate, they are already threadprivate or 5184 // implicitly private. 5185 Vars.push_back(DE); 5186 } 5187 5188 if (Vars.empty()) 5189 return nullptr; 5190 5191 return OMPCopyprivateClause::Create(Context, StartLoc, LParenLoc, EndLoc, Vars); 5192 } 5193 5194 OMPClause *Sema::ActOnOpenMPFlushClause(ArrayRef<Expr *> VarList, 5195 SourceLocation StartLoc, 5196 SourceLocation LParenLoc, 5197 SourceLocation EndLoc) { 5198 if (VarList.empty()) 5199 return nullptr; 5200 5201 return OMPFlushClause::Create(Context, StartLoc, LParenLoc, EndLoc, VarList); 5202 } 5203 5204