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 "TreeTransform.h" 16 #include "clang/AST/ASTContext.h" 17 #include "clang/AST/ASTMutationListener.h" 18 #include "clang/AST/Decl.h" 19 #include "clang/AST/DeclCXX.h" 20 #include "clang/AST/DeclOpenMP.h" 21 #include "clang/AST/StmtCXX.h" 22 #include "clang/AST/StmtOpenMP.h" 23 #include "clang/AST/StmtVisitor.h" 24 #include "clang/Basic/OpenMPKinds.h" 25 #include "clang/Basic/TargetInfo.h" 26 #include "clang/Lex/Preprocessor.h" 27 #include "clang/Sema/Initialization.h" 28 #include "clang/Sema/Lookup.h" 29 #include "clang/Sema/Scope.h" 30 #include "clang/Sema/ScopeInfo.h" 31 #include "clang/Sema/SemaInternal.h" 32 using namespace clang; 33 34 //===----------------------------------------------------------------------===// 35 // Stack of data-sharing attributes for variables 36 //===----------------------------------------------------------------------===// 37 38 namespace { 39 /// \brief Default data sharing attributes, which can be applied to directive. 40 enum DefaultDataSharingAttributes { 41 DSA_unspecified = 0, /// \brief Data sharing attribute not specified. 42 DSA_none = 1 << 0, /// \brief Default data sharing attribute 'none'. 43 DSA_shared = 1 << 1 /// \brief Default data sharing attribute 'shared'. 44 }; 45 46 template <class T> struct MatchesAny { 47 explicit MatchesAny(ArrayRef<T> Arr) : Arr(std::move(Arr)) {} 48 bool operator()(T Kind) { 49 for (auto KindEl : Arr) 50 if (KindEl == Kind) 51 return true; 52 return false; 53 } 54 55 private: 56 ArrayRef<T> Arr; 57 }; 58 struct MatchesAlways { 59 MatchesAlways() {} 60 template <class T> bool operator()(T) { return true; } 61 }; 62 63 typedef MatchesAny<OpenMPClauseKind> MatchesAnyClause; 64 typedef MatchesAny<OpenMPDirectiveKind> MatchesAnyDirective; 65 66 /// \brief Stack for tracking declarations used in OpenMP directives and 67 /// clauses and their data-sharing attributes. 68 class DSAStackTy { 69 public: 70 struct DSAVarData { 71 OpenMPDirectiveKind DKind; 72 OpenMPClauseKind CKind; 73 DeclRefExpr *RefExpr; 74 SourceLocation ImplicitDSALoc; 75 DSAVarData() 76 : DKind(OMPD_unknown), CKind(OMPC_unknown), RefExpr(nullptr), 77 ImplicitDSALoc() {} 78 }; 79 80 public: 81 struct MapInfo { 82 Expr *RefExpr; 83 }; 84 85 private: 86 struct DSAInfo { 87 OpenMPClauseKind Attributes; 88 DeclRefExpr *RefExpr; 89 }; 90 typedef llvm::SmallDenseMap<VarDecl *, DSAInfo, 64> DeclSAMapTy; 91 typedef llvm::SmallDenseMap<VarDecl *, DeclRefExpr *, 64> AlignedMapTy; 92 typedef llvm::DenseSet<VarDecl *> LoopControlVariablesSetTy; 93 typedef llvm::SmallDenseMap<VarDecl *, MapInfo, 64> MappedDeclsTy; 94 95 struct SharingMapTy { 96 DeclSAMapTy SharingMap; 97 AlignedMapTy AlignedMap; 98 MappedDeclsTy MappedDecls; 99 LoopControlVariablesSetTy LCVSet; 100 DefaultDataSharingAttributes DefaultAttr; 101 SourceLocation DefaultAttrLoc; 102 OpenMPDirectiveKind Directive; 103 DeclarationNameInfo DirectiveName; 104 Scope *CurScope; 105 SourceLocation ConstructLoc; 106 /// \brief first argument (Expr *) contains optional argument of the 107 /// 'ordered' clause, the second one is true if the regions has 'ordered' 108 /// clause, false otherwise. 109 llvm::PointerIntPair<Expr *, 1, bool> OrderedRegion; 110 bool NowaitRegion; 111 bool CancelRegion; 112 unsigned CollapseNumber; 113 SourceLocation InnerTeamsRegionLoc; 114 SharingMapTy(OpenMPDirectiveKind DKind, DeclarationNameInfo Name, 115 Scope *CurScope, SourceLocation Loc) 116 : SharingMap(), AlignedMap(), LCVSet(), DefaultAttr(DSA_unspecified), 117 Directive(DKind), DirectiveName(std::move(Name)), CurScope(CurScope), 118 ConstructLoc(Loc), OrderedRegion(), NowaitRegion(false), 119 CancelRegion(false), CollapseNumber(1), InnerTeamsRegionLoc() {} 120 SharingMapTy() 121 : SharingMap(), AlignedMap(), LCVSet(), DefaultAttr(DSA_unspecified), 122 Directive(OMPD_unknown), DirectiveName(), CurScope(nullptr), 123 ConstructLoc(), OrderedRegion(), NowaitRegion(false), 124 CancelRegion(false), CollapseNumber(1), InnerTeamsRegionLoc() {} 125 }; 126 127 typedef SmallVector<SharingMapTy, 64> StackTy; 128 129 /// \brief Stack of used declaration and their data-sharing attributes. 130 StackTy Stack; 131 /// \brief true, if check for DSA must be from parent directive, false, if 132 /// from current directive. 133 OpenMPClauseKind ClauseKindMode; 134 Sema &SemaRef; 135 bool ForceCapturing; 136 137 typedef SmallVector<SharingMapTy, 8>::reverse_iterator reverse_iterator; 138 139 DSAVarData getDSA(StackTy::reverse_iterator Iter, VarDecl *D); 140 141 /// \brief Checks if the variable is a local for OpenMP region. 142 bool isOpenMPLocal(VarDecl *D, StackTy::reverse_iterator Iter); 143 144 public: 145 explicit DSAStackTy(Sema &S) 146 : Stack(1), ClauseKindMode(OMPC_unknown), SemaRef(S), 147 ForceCapturing(false) {} 148 149 bool isClauseParsingMode() const { return ClauseKindMode != OMPC_unknown; } 150 void setClauseParsingMode(OpenMPClauseKind K) { ClauseKindMode = K; } 151 152 bool isForceVarCapturing() const { return ForceCapturing; } 153 void setForceVarCapturing(bool V) { ForceCapturing = V; } 154 155 void push(OpenMPDirectiveKind DKind, const DeclarationNameInfo &DirName, 156 Scope *CurScope, SourceLocation Loc) { 157 Stack.push_back(SharingMapTy(DKind, DirName, CurScope, Loc)); 158 Stack.back().DefaultAttrLoc = Loc; 159 } 160 161 void pop() { 162 assert(Stack.size() > 1 && "Data-sharing attributes stack is empty!"); 163 Stack.pop_back(); 164 } 165 166 /// \brief If 'aligned' declaration for given variable \a D was not seen yet, 167 /// add it and return NULL; otherwise return previous occurrence's expression 168 /// for diagnostics. 169 DeclRefExpr *addUniqueAligned(VarDecl *D, DeclRefExpr *NewDE); 170 171 /// \brief Register specified variable as loop control variable. 172 void addLoopControlVariable(VarDecl *D); 173 /// \brief Check if the specified variable is a loop control variable for 174 /// current region. 175 bool isLoopControlVariable(VarDecl *D); 176 177 /// \brief Adds explicit data sharing attribute to the specified declaration. 178 void addDSA(VarDecl *D, DeclRefExpr *E, OpenMPClauseKind A); 179 180 /// \brief Returns data sharing attributes from top of the stack for the 181 /// specified declaration. 182 DSAVarData getTopDSA(VarDecl *D, bool FromParent); 183 /// \brief Returns data-sharing attributes for the specified declaration. 184 DSAVarData getImplicitDSA(VarDecl *D, bool FromParent); 185 /// \brief Checks if the specified variables has data-sharing attributes which 186 /// match specified \a CPred predicate in any directive which matches \a DPred 187 /// predicate. 188 template <class ClausesPredicate, class DirectivesPredicate> 189 DSAVarData hasDSA(VarDecl *D, ClausesPredicate CPred, 190 DirectivesPredicate DPred, bool FromParent); 191 /// \brief Checks if the specified variables has data-sharing attributes which 192 /// match specified \a CPred predicate in any innermost directive which 193 /// matches \a DPred predicate. 194 template <class ClausesPredicate, class DirectivesPredicate> 195 DSAVarData hasInnermostDSA(VarDecl *D, ClausesPredicate CPred, 196 DirectivesPredicate DPred, 197 bool FromParent); 198 /// \brief Checks if the specified variables has explicit data-sharing 199 /// attributes which match specified \a CPred predicate at the specified 200 /// OpenMP region. 201 bool hasExplicitDSA(VarDecl *D, 202 const llvm::function_ref<bool(OpenMPClauseKind)> &CPred, 203 unsigned Level); 204 205 /// \brief Returns true if the directive at level \Level matches in the 206 /// specified \a DPred predicate. 207 bool hasExplicitDirective( 208 const llvm::function_ref<bool(OpenMPDirectiveKind)> &DPred, 209 unsigned Level); 210 211 /// \brief Finds a directive which matches specified \a DPred predicate. 212 template <class NamedDirectivesPredicate> 213 bool hasDirective(NamedDirectivesPredicate DPred, bool FromParent); 214 215 /// \brief Returns currently analyzed directive. 216 OpenMPDirectiveKind getCurrentDirective() const { 217 return Stack.back().Directive; 218 } 219 /// \brief Returns parent directive. 220 OpenMPDirectiveKind getParentDirective() const { 221 if (Stack.size() > 2) 222 return Stack[Stack.size() - 2].Directive; 223 return OMPD_unknown; 224 } 225 /// \brief Return the directive associated with the provided scope. 226 OpenMPDirectiveKind getDirectiveForScope(const Scope *S) const; 227 228 /// \brief Set default data sharing attribute to none. 229 void setDefaultDSANone(SourceLocation Loc) { 230 Stack.back().DefaultAttr = DSA_none; 231 Stack.back().DefaultAttrLoc = Loc; 232 } 233 /// \brief Set default data sharing attribute to shared. 234 void setDefaultDSAShared(SourceLocation Loc) { 235 Stack.back().DefaultAttr = DSA_shared; 236 Stack.back().DefaultAttrLoc = Loc; 237 } 238 239 DefaultDataSharingAttributes getDefaultDSA() const { 240 return Stack.back().DefaultAttr; 241 } 242 SourceLocation getDefaultDSALocation() const { 243 return Stack.back().DefaultAttrLoc; 244 } 245 246 /// \brief Checks if the specified variable is a threadprivate. 247 bool isThreadPrivate(VarDecl *D) { 248 DSAVarData DVar = getTopDSA(D, false); 249 return isOpenMPThreadPrivate(DVar.CKind); 250 } 251 252 /// \brief Marks current region as ordered (it has an 'ordered' clause). 253 void setOrderedRegion(bool IsOrdered, Expr *Param) { 254 Stack.back().OrderedRegion.setInt(IsOrdered); 255 Stack.back().OrderedRegion.setPointer(Param); 256 } 257 /// \brief Returns true, if parent region is ordered (has associated 258 /// 'ordered' clause), false - otherwise. 259 bool isParentOrderedRegion() const { 260 if (Stack.size() > 2) 261 return Stack[Stack.size() - 2].OrderedRegion.getInt(); 262 return false; 263 } 264 /// \brief Returns optional parameter for the ordered region. 265 Expr *getParentOrderedRegionParam() const { 266 if (Stack.size() > 2) 267 return Stack[Stack.size() - 2].OrderedRegion.getPointer(); 268 return nullptr; 269 } 270 /// \brief Marks current region as nowait (it has a 'nowait' clause). 271 void setNowaitRegion(bool IsNowait = true) { 272 Stack.back().NowaitRegion = IsNowait; 273 } 274 /// \brief Returns true, if parent region is nowait (has associated 275 /// 'nowait' clause), false - otherwise. 276 bool isParentNowaitRegion() const { 277 if (Stack.size() > 2) 278 return Stack[Stack.size() - 2].NowaitRegion; 279 return false; 280 } 281 /// \brief Marks parent region as cancel region. 282 void setParentCancelRegion(bool Cancel = true) { 283 if (Stack.size() > 2) 284 Stack[Stack.size() - 2].CancelRegion = 285 Stack[Stack.size() - 2].CancelRegion || Cancel; 286 } 287 /// \brief Return true if current region has inner cancel construct. 288 bool isCancelRegion() const { 289 return Stack.back().CancelRegion; 290 } 291 292 /// \brief Set collapse value for the region. 293 void setCollapseNumber(unsigned Val) { Stack.back().CollapseNumber = Val; } 294 /// \brief Return collapse value for region. 295 unsigned getCollapseNumber() const { 296 return Stack.back().CollapseNumber; 297 } 298 299 /// \brief Marks current target region as one with closely nested teams 300 /// region. 301 void setParentTeamsRegionLoc(SourceLocation TeamsRegionLoc) { 302 if (Stack.size() > 2) 303 Stack[Stack.size() - 2].InnerTeamsRegionLoc = TeamsRegionLoc; 304 } 305 /// \brief Returns true, if current region has closely nested teams region. 306 bool hasInnerTeamsRegion() const { 307 return getInnerTeamsRegionLoc().isValid(); 308 } 309 /// \brief Returns location of the nested teams region (if any). 310 SourceLocation getInnerTeamsRegionLoc() const { 311 if (Stack.size() > 1) 312 return Stack.back().InnerTeamsRegionLoc; 313 return SourceLocation(); 314 } 315 316 Scope *getCurScope() const { return Stack.back().CurScope; } 317 Scope *getCurScope() { return Stack.back().CurScope; } 318 SourceLocation getConstructLoc() { return Stack.back().ConstructLoc; } 319 320 MapInfo getMapInfoForVar(VarDecl *VD) { 321 MapInfo VarMI = {0}; 322 for (auto Cnt = Stack.size() - 1; Cnt > 0; --Cnt) { 323 if (Stack[Cnt].MappedDecls.count(VD)) { 324 VarMI = Stack[Cnt].MappedDecls[VD]; 325 break; 326 } 327 } 328 return VarMI; 329 } 330 331 void addMapInfoForVar(VarDecl *VD, MapInfo MI) { 332 if (Stack.size() > 1) { 333 Stack.back().MappedDecls[VD] = MI; 334 } 335 } 336 337 MapInfo IsMappedInCurrentRegion(VarDecl *VD) { 338 assert(Stack.size() > 1 && "Target level is 0"); 339 MapInfo VarMI = {0}; 340 if (Stack.size() > 1 && Stack.back().MappedDecls.count(VD)) { 341 VarMI = Stack.back().MappedDecls[VD]; 342 } 343 return VarMI; 344 } 345 }; 346 bool isParallelOrTaskRegion(OpenMPDirectiveKind DKind) { 347 return isOpenMPParallelDirective(DKind) || DKind == OMPD_task || 348 isOpenMPTeamsDirective(DKind) || DKind == OMPD_unknown || 349 isOpenMPTaskLoopDirective(DKind); 350 } 351 } // namespace 352 353 DSAStackTy::DSAVarData DSAStackTy::getDSA(StackTy::reverse_iterator Iter, 354 VarDecl *D) { 355 D = D->getCanonicalDecl(); 356 DSAVarData DVar; 357 if (Iter == std::prev(Stack.rend())) { 358 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced 359 // in a region but not in construct] 360 // File-scope or namespace-scope variables referenced in called routines 361 // in the region are shared unless they appear in a threadprivate 362 // directive. 363 if (!D->isFunctionOrMethodVarDecl() && !isa<ParmVarDecl>(D)) 364 DVar.CKind = OMPC_shared; 365 366 // OpenMP [2.9.1.2, Data-sharing Attribute Rules for Variables Referenced 367 // in a region but not in construct] 368 // Variables with static storage duration that are declared in called 369 // routines in the region are shared. 370 if (D->hasGlobalStorage()) 371 DVar.CKind = OMPC_shared; 372 373 return DVar; 374 } 375 376 DVar.DKind = Iter->Directive; 377 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced 378 // in a Construct, C/C++, predetermined, p.1] 379 // Variables with automatic storage duration that are declared in a scope 380 // inside the construct are private. 381 if (isOpenMPLocal(D, Iter) && D->isLocalVarDecl() && 382 (D->getStorageClass() == SC_Auto || D->getStorageClass() == SC_None)) { 383 DVar.CKind = OMPC_private; 384 return DVar; 385 } 386 387 // Explicitly specified attributes and local variables with predetermined 388 // attributes. 389 if (Iter->SharingMap.count(D)) { 390 DVar.RefExpr = Iter->SharingMap[D].RefExpr; 391 DVar.CKind = Iter->SharingMap[D].Attributes; 392 DVar.ImplicitDSALoc = Iter->DefaultAttrLoc; 393 return DVar; 394 } 395 396 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced 397 // in a Construct, C/C++, implicitly determined, p.1] 398 // In a parallel or task construct, the data-sharing attributes of these 399 // variables are determined by the default clause, if present. 400 switch (Iter->DefaultAttr) { 401 case DSA_shared: 402 DVar.CKind = OMPC_shared; 403 DVar.ImplicitDSALoc = Iter->DefaultAttrLoc; 404 return DVar; 405 case DSA_none: 406 return DVar; 407 case DSA_unspecified: 408 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced 409 // in a Construct, implicitly determined, p.2] 410 // In a parallel construct, if no default clause is present, these 411 // variables are shared. 412 DVar.ImplicitDSALoc = Iter->DefaultAttrLoc; 413 if (isOpenMPParallelDirective(DVar.DKind) || 414 isOpenMPTeamsDirective(DVar.DKind)) { 415 DVar.CKind = OMPC_shared; 416 return DVar; 417 } 418 419 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced 420 // in a Construct, implicitly determined, p.4] 421 // In a task construct, if no default clause is present, a variable that in 422 // the enclosing context is determined to be shared by all implicit tasks 423 // bound to the current team is shared. 424 if (DVar.DKind == OMPD_task) { 425 DSAVarData DVarTemp; 426 for (StackTy::reverse_iterator I = std::next(Iter), EE = Stack.rend(); 427 I != EE; ++I) { 428 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables 429 // Referenced 430 // in a Construct, implicitly determined, p.6] 431 // In a task construct, if no default clause is present, a variable 432 // whose data-sharing attribute is not determined by the rules above is 433 // firstprivate. 434 DVarTemp = getDSA(I, D); 435 if (DVarTemp.CKind != OMPC_shared) { 436 DVar.RefExpr = nullptr; 437 DVar.DKind = OMPD_task; 438 DVar.CKind = OMPC_firstprivate; 439 return DVar; 440 } 441 if (isParallelOrTaskRegion(I->Directive)) 442 break; 443 } 444 DVar.DKind = OMPD_task; 445 DVar.CKind = 446 (DVarTemp.CKind == OMPC_unknown) ? OMPC_firstprivate : OMPC_shared; 447 return DVar; 448 } 449 } 450 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced 451 // in a Construct, implicitly determined, p.3] 452 // For constructs other than task, if no default clause is present, these 453 // variables inherit their data-sharing attributes from the enclosing 454 // context. 455 return getDSA(std::next(Iter), D); 456 } 457 458 DeclRefExpr *DSAStackTy::addUniqueAligned(VarDecl *D, DeclRefExpr *NewDE) { 459 assert(Stack.size() > 1 && "Data sharing attributes stack is empty"); 460 D = D->getCanonicalDecl(); 461 auto It = Stack.back().AlignedMap.find(D); 462 if (It == Stack.back().AlignedMap.end()) { 463 assert(NewDE && "Unexpected nullptr expr to be added into aligned map"); 464 Stack.back().AlignedMap[D] = NewDE; 465 return nullptr; 466 } else { 467 assert(It->second && "Unexpected nullptr expr in the aligned map"); 468 return It->second; 469 } 470 return nullptr; 471 } 472 473 void DSAStackTy::addLoopControlVariable(VarDecl *D) { 474 assert(Stack.size() > 1 && "Data-sharing attributes stack is empty"); 475 D = D->getCanonicalDecl(); 476 Stack.back().LCVSet.insert(D); 477 } 478 479 bool DSAStackTy::isLoopControlVariable(VarDecl *D) { 480 assert(Stack.size() > 1 && "Data-sharing attributes stack is empty"); 481 D = D->getCanonicalDecl(); 482 return Stack.back().LCVSet.count(D) > 0; 483 } 484 485 void DSAStackTy::addDSA(VarDecl *D, DeclRefExpr *E, OpenMPClauseKind A) { 486 D = D->getCanonicalDecl(); 487 if (A == OMPC_threadprivate) { 488 Stack[0].SharingMap[D].Attributes = A; 489 Stack[0].SharingMap[D].RefExpr = E; 490 } else { 491 assert(Stack.size() > 1 && "Data-sharing attributes stack is empty"); 492 Stack.back().SharingMap[D].Attributes = A; 493 Stack.back().SharingMap[D].RefExpr = E; 494 } 495 } 496 497 bool DSAStackTy::isOpenMPLocal(VarDecl *D, StackTy::reverse_iterator Iter) { 498 D = D->getCanonicalDecl(); 499 if (Stack.size() > 2) { 500 reverse_iterator I = Iter, E = std::prev(Stack.rend()); 501 Scope *TopScope = nullptr; 502 while (I != E && !isParallelOrTaskRegion(I->Directive)) { 503 ++I; 504 } 505 if (I == E) 506 return false; 507 TopScope = I->CurScope ? I->CurScope->getParent() : nullptr; 508 Scope *CurScope = getCurScope(); 509 while (CurScope != TopScope && !CurScope->isDeclScope(D)) { 510 CurScope = CurScope->getParent(); 511 } 512 return CurScope != TopScope; 513 } 514 return false; 515 } 516 517 /// \brief Build a variable declaration for OpenMP loop iteration variable. 518 static VarDecl *buildVarDecl(Sema &SemaRef, SourceLocation Loc, QualType Type, 519 StringRef Name, const AttrVec *Attrs = nullptr) { 520 DeclContext *DC = SemaRef.CurContext; 521 IdentifierInfo *II = &SemaRef.PP.getIdentifierTable().get(Name); 522 TypeSourceInfo *TInfo = SemaRef.Context.getTrivialTypeSourceInfo(Type, Loc); 523 VarDecl *Decl = 524 VarDecl::Create(SemaRef.Context, DC, Loc, Loc, II, Type, TInfo, SC_None); 525 if (Attrs) { 526 for (specific_attr_iterator<AlignedAttr> I(Attrs->begin()), E(Attrs->end()); 527 I != E; ++I) 528 Decl->addAttr(*I); 529 } 530 Decl->setImplicit(); 531 return Decl; 532 } 533 534 static DeclRefExpr *buildDeclRefExpr(Sema &S, VarDecl *D, QualType Ty, 535 SourceLocation Loc, 536 bool RefersToCapture = false) { 537 D->setReferenced(); 538 D->markUsed(S.Context); 539 return DeclRefExpr::Create(S.getASTContext(), NestedNameSpecifierLoc(), 540 SourceLocation(), D, RefersToCapture, Loc, Ty, 541 VK_LValue); 542 } 543 544 DSAStackTy::DSAVarData DSAStackTy::getTopDSA(VarDecl *D, bool FromParent) { 545 D = D->getCanonicalDecl(); 546 DSAVarData DVar; 547 548 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced 549 // in a Construct, C/C++, predetermined, p.1] 550 // Variables appearing in threadprivate directives are threadprivate. 551 if ((D->getTLSKind() != VarDecl::TLS_None && 552 !(D->hasAttr<OMPThreadPrivateDeclAttr>() && 553 SemaRef.getLangOpts().OpenMPUseTLS && 554 SemaRef.getASTContext().getTargetInfo().isTLSSupported())) || 555 (D->getStorageClass() == SC_Register && D->hasAttr<AsmLabelAttr>() && 556 !D->isLocalVarDecl())) { 557 addDSA(D, buildDeclRefExpr(SemaRef, D, D->getType().getNonReferenceType(), 558 D->getLocation()), 559 OMPC_threadprivate); 560 } 561 if (Stack[0].SharingMap.count(D)) { 562 DVar.RefExpr = Stack[0].SharingMap[D].RefExpr; 563 DVar.CKind = OMPC_threadprivate; 564 return DVar; 565 } 566 567 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced 568 // in a Construct, C/C++, predetermined, p.4] 569 // Static data members are shared. 570 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced 571 // in a Construct, C/C++, predetermined, p.7] 572 // Variables with static storage duration that are declared in a scope 573 // inside the construct are shared. 574 if (D->isStaticDataMember()) { 575 DSAVarData DVarTemp = 576 hasDSA(D, isOpenMPPrivate, MatchesAlways(), FromParent); 577 if (DVarTemp.CKind != OMPC_unknown && DVarTemp.RefExpr) 578 return DVar; 579 580 DVar.CKind = OMPC_shared; 581 return DVar; 582 } 583 584 QualType Type = D->getType().getNonReferenceType().getCanonicalType(); 585 bool IsConstant = Type.isConstant(SemaRef.getASTContext()); 586 Type = SemaRef.getASTContext().getBaseElementType(Type); 587 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced 588 // in a Construct, C/C++, predetermined, p.6] 589 // Variables with const qualified type having no mutable member are 590 // shared. 591 CXXRecordDecl *RD = 592 SemaRef.getLangOpts().CPlusPlus ? Type->getAsCXXRecordDecl() : nullptr; 593 if (IsConstant && 594 !(SemaRef.getLangOpts().CPlusPlus && RD && RD->hasMutableFields())) { 595 // Variables with const-qualified type having no mutable member may be 596 // listed in a firstprivate clause, even if they are static data members. 597 DSAVarData DVarTemp = hasDSA(D, MatchesAnyClause(OMPC_firstprivate), 598 MatchesAlways(), FromParent); 599 if (DVarTemp.CKind == OMPC_firstprivate && DVarTemp.RefExpr) 600 return DVar; 601 602 DVar.CKind = OMPC_shared; 603 return DVar; 604 } 605 606 // Explicitly specified attributes and local variables with predetermined 607 // attributes. 608 auto StartI = std::next(Stack.rbegin()); 609 auto EndI = std::prev(Stack.rend()); 610 if (FromParent && StartI != EndI) { 611 StartI = std::next(StartI); 612 } 613 auto I = std::prev(StartI); 614 if (I->SharingMap.count(D)) { 615 DVar.RefExpr = I->SharingMap[D].RefExpr; 616 DVar.CKind = I->SharingMap[D].Attributes; 617 DVar.ImplicitDSALoc = I->DefaultAttrLoc; 618 } 619 620 return DVar; 621 } 622 623 DSAStackTy::DSAVarData DSAStackTy::getImplicitDSA(VarDecl *D, bool FromParent) { 624 D = D->getCanonicalDecl(); 625 auto StartI = Stack.rbegin(); 626 auto EndI = std::prev(Stack.rend()); 627 if (FromParent && StartI != EndI) { 628 StartI = std::next(StartI); 629 } 630 return getDSA(StartI, D); 631 } 632 633 template <class ClausesPredicate, class DirectivesPredicate> 634 DSAStackTy::DSAVarData DSAStackTy::hasDSA(VarDecl *D, ClausesPredicate CPred, 635 DirectivesPredicate DPred, 636 bool FromParent) { 637 D = D->getCanonicalDecl(); 638 auto StartI = std::next(Stack.rbegin()); 639 auto EndI = std::prev(Stack.rend()); 640 if (FromParent && StartI != EndI) { 641 StartI = std::next(StartI); 642 } 643 for (auto I = StartI, EE = EndI; I != EE; ++I) { 644 if (!DPred(I->Directive) && !isParallelOrTaskRegion(I->Directive)) 645 continue; 646 DSAVarData DVar = getDSA(I, D); 647 if (CPred(DVar.CKind)) 648 return DVar; 649 } 650 return DSAVarData(); 651 } 652 653 template <class ClausesPredicate, class DirectivesPredicate> 654 DSAStackTy::DSAVarData 655 DSAStackTy::hasInnermostDSA(VarDecl *D, ClausesPredicate CPred, 656 DirectivesPredicate DPred, bool FromParent) { 657 D = D->getCanonicalDecl(); 658 auto StartI = std::next(Stack.rbegin()); 659 auto EndI = std::prev(Stack.rend()); 660 if (FromParent && StartI != EndI) { 661 StartI = std::next(StartI); 662 } 663 for (auto I = StartI, EE = EndI; I != EE; ++I) { 664 if (!DPred(I->Directive)) 665 break; 666 DSAVarData DVar = getDSA(I, D); 667 if (CPred(DVar.CKind)) 668 return DVar; 669 return DSAVarData(); 670 } 671 return DSAVarData(); 672 } 673 674 bool DSAStackTy::hasExplicitDSA( 675 VarDecl *D, const llvm::function_ref<bool(OpenMPClauseKind)> &CPred, 676 unsigned Level) { 677 if (CPred(ClauseKindMode)) 678 return true; 679 if (isClauseParsingMode()) 680 ++Level; 681 D = D->getCanonicalDecl(); 682 auto StartI = Stack.rbegin(); 683 auto EndI = std::prev(Stack.rend()); 684 if (std::distance(StartI, EndI) <= (int)Level) 685 return false; 686 std::advance(StartI, Level); 687 return (StartI->SharingMap.count(D) > 0) && StartI->SharingMap[D].RefExpr && 688 CPred(StartI->SharingMap[D].Attributes); 689 } 690 691 bool DSAStackTy::hasExplicitDirective( 692 const llvm::function_ref<bool(OpenMPDirectiveKind)> &DPred, 693 unsigned Level) { 694 if (isClauseParsingMode()) 695 ++Level; 696 auto StartI = Stack.rbegin(); 697 auto EndI = std::prev(Stack.rend()); 698 if (std::distance(StartI, EndI) <= (int)Level) 699 return false; 700 std::advance(StartI, Level); 701 return DPred(StartI->Directive); 702 } 703 704 template <class NamedDirectivesPredicate> 705 bool DSAStackTy::hasDirective(NamedDirectivesPredicate DPred, bool FromParent) { 706 auto StartI = std::next(Stack.rbegin()); 707 auto EndI = std::prev(Stack.rend()); 708 if (FromParent && StartI != EndI) { 709 StartI = std::next(StartI); 710 } 711 for (auto I = StartI, EE = EndI; I != EE; ++I) { 712 if (DPred(I->Directive, I->DirectiveName, I->ConstructLoc)) 713 return true; 714 } 715 return false; 716 } 717 718 OpenMPDirectiveKind DSAStackTy::getDirectiveForScope(const Scope *S) const { 719 for (auto I = Stack.rbegin(), EE = Stack.rend(); I != EE; ++I) 720 if (I->CurScope == S) 721 return I->Directive; 722 return OMPD_unknown; 723 } 724 725 void Sema::InitDataSharingAttributesStack() { 726 VarDataSharingAttributesStack = new DSAStackTy(*this); 727 } 728 729 #define DSAStack static_cast<DSAStackTy *>(VarDataSharingAttributesStack) 730 731 bool Sema::IsOpenMPCapturedByRef(VarDecl *VD, 732 const CapturedRegionScopeInfo *RSI) { 733 assert(LangOpts.OpenMP && "OpenMP is not allowed"); 734 735 auto &Ctx = getASTContext(); 736 bool IsByRef = true; 737 738 // Find the directive that is associated with the provided scope. 739 auto DKind = DSAStack->getDirectiveForScope(RSI->TheScope); 740 auto Ty = VD->getType(); 741 742 if (isOpenMPTargetDirective(DKind)) { 743 // This table summarizes how a given variable should be passed to the device 744 // given its type and the clauses where it appears. This table is based on 745 // the description in OpenMP 4.5 [2.10.4, target Construct] and 746 // OpenMP 4.5 [2.15.5, Data-mapping Attribute Rules and Clauses]. 747 // 748 // ========================================================================= 749 // | type | defaultmap | pvt | first | is_device_ptr | map | res. | 750 // | |(tofrom:scalar)| | pvt | | | | 751 // ========================================================================= 752 // | scl | | | | - | | bycopy| 753 // | scl | | - | x | - | - | bycopy| 754 // | scl | | x | - | - | - | null | 755 // | scl | x | | | - | | byref | 756 // | scl | x | - | x | - | - | bycopy| 757 // | scl | x | x | - | - | - | null | 758 // | scl | | - | - | - | x | byref | 759 // | scl | x | - | - | - | x | byref | 760 // 761 // | agg | n.a. | | | - | | byref | 762 // | agg | n.a. | - | x | - | - | byref | 763 // | agg | n.a. | x | - | - | - | null | 764 // | agg | n.a. | - | - | - | x | byref | 765 // | agg | n.a. | - | - | - | x[] | byref | 766 // 767 // | ptr | n.a. | | | - | | bycopy| 768 // | ptr | n.a. | - | x | - | - | bycopy| 769 // | ptr | n.a. | x | - | - | - | null | 770 // | ptr | n.a. | - | - | - | x | byref | 771 // | ptr | n.a. | - | - | - | x[] | bycopy| 772 // | ptr | n.a. | - | - | x | | bycopy| 773 // | ptr | n.a. | - | - | x | x | bycopy| 774 // | ptr | n.a. | - | - | x | x[] | bycopy| 775 // ========================================================================= 776 // Legend: 777 // scl - scalar 778 // ptr - pointer 779 // agg - aggregate 780 // x - applies 781 // - - invalid in this combination 782 // [] - mapped with an array section 783 // byref - should be mapped by reference 784 // byval - should be mapped by value 785 // null - initialize a local variable to null on the device 786 // 787 // Observations: 788 // - All scalar declarations that show up in a map clause have to be passed 789 // by reference, because they may have been mapped in the enclosing data 790 // environment. 791 // - If the scalar value does not fit the size of uintptr, it has to be 792 // passed by reference, regardless the result in the table above. 793 // - For pointers mapped by value that have either an implicit map or an 794 // array section, the runtime library may pass the NULL value to the 795 // device instead of the value passed to it by the compiler. 796 797 // FIXME: Right now, only implicit maps are implemented. Properly mapping 798 // values requires having the map, private, and firstprivate clauses SEMA 799 // and parsing in place, which we don't yet. 800 801 if (Ty->isReferenceType()) 802 Ty = Ty->castAs<ReferenceType>()->getPointeeType(); 803 IsByRef = !Ty->isScalarType(); 804 } 805 806 // When passing data by value, we need to make sure it fits the uintptr size 807 // and alignment, because the runtime library only deals with uintptr types. 808 // If it does not fit the uintptr size, we need to pass the data by reference 809 // instead. 810 if (!IsByRef && 811 (Ctx.getTypeSizeInChars(Ty) > 812 Ctx.getTypeSizeInChars(Ctx.getUIntPtrType()) || 813 Ctx.getDeclAlign(VD) > Ctx.getTypeAlignInChars(Ctx.getUIntPtrType()))) 814 IsByRef = true; 815 816 return IsByRef; 817 } 818 819 bool Sema::IsOpenMPCapturedVar(VarDecl *VD) { 820 assert(LangOpts.OpenMP && "OpenMP is not allowed"); 821 VD = VD->getCanonicalDecl(); 822 823 // If we are attempting to capture a global variable in a directive with 824 // 'target' we return true so that this global is also mapped to the device. 825 // 826 // FIXME: If the declaration is enclosed in a 'declare target' directive, 827 // then it should not be captured. Therefore, an extra check has to be 828 // inserted here once support for 'declare target' is added. 829 // 830 if (!VD->hasLocalStorage()) { 831 if (DSAStack->getCurrentDirective() == OMPD_target && 832 !DSAStack->isClauseParsingMode()) { 833 return true; 834 } 835 if (DSAStack->getCurScope() && 836 DSAStack->hasDirective( 837 [](OpenMPDirectiveKind K, const DeclarationNameInfo &DNI, 838 SourceLocation Loc) -> bool { 839 return isOpenMPTargetDirective(K); 840 }, 841 false)) { 842 return true; 843 } 844 } 845 846 if (DSAStack->getCurrentDirective() != OMPD_unknown && 847 (!DSAStack->isClauseParsingMode() || 848 DSAStack->getParentDirective() != OMPD_unknown)) { 849 if (DSAStack->isLoopControlVariable(VD) || 850 (VD->hasLocalStorage() && 851 isParallelOrTaskRegion(DSAStack->getCurrentDirective())) || 852 DSAStack->isForceVarCapturing()) 853 return true; 854 auto DVarPrivate = DSAStack->getTopDSA(VD, DSAStack->isClauseParsingMode()); 855 if (DVarPrivate.CKind != OMPC_unknown && isOpenMPPrivate(DVarPrivate.CKind)) 856 return true; 857 DVarPrivate = DSAStack->hasDSA(VD, isOpenMPPrivate, MatchesAlways(), 858 DSAStack->isClauseParsingMode()); 859 return DVarPrivate.CKind != OMPC_unknown; 860 } 861 return false; 862 } 863 864 bool Sema::isOpenMPPrivateVar(VarDecl *VD, unsigned Level) { 865 assert(LangOpts.OpenMP && "OpenMP is not allowed"); 866 return DSAStack->hasExplicitDSA( 867 VD, [](OpenMPClauseKind K) -> bool { return K == OMPC_private; }, Level); 868 } 869 870 bool Sema::isOpenMPTargetCapturedVar(VarDecl *VD, unsigned Level) { 871 assert(LangOpts.OpenMP && "OpenMP is not allowed"); 872 // Return true if the current level is no longer enclosed in a target region. 873 874 return !VD->hasLocalStorage() && 875 DSAStack->hasExplicitDirective(isOpenMPTargetDirective, Level); 876 } 877 878 void Sema::DestroyDataSharingAttributesStack() { delete DSAStack; } 879 880 void Sema::StartOpenMPDSABlock(OpenMPDirectiveKind DKind, 881 const DeclarationNameInfo &DirName, 882 Scope *CurScope, SourceLocation Loc) { 883 DSAStack->push(DKind, DirName, CurScope, Loc); 884 PushExpressionEvaluationContext(PotentiallyEvaluated); 885 } 886 887 void Sema::StartOpenMPClause(OpenMPClauseKind K) { 888 DSAStack->setClauseParsingMode(K); 889 } 890 891 void Sema::EndOpenMPClause() { 892 DSAStack->setClauseParsingMode(/*K=*/OMPC_unknown); 893 } 894 895 void Sema::EndOpenMPDSABlock(Stmt *CurDirective) { 896 // OpenMP [2.14.3.5, Restrictions, C/C++, p.1] 897 // A variable of class type (or array thereof) that appears in a lastprivate 898 // clause requires an accessible, unambiguous default constructor for the 899 // class type, unless the list item is also specified in a firstprivate 900 // clause. 901 if (auto D = dyn_cast_or_null<OMPExecutableDirective>(CurDirective)) { 902 for (auto *C : D->clauses()) { 903 if (auto *Clause = dyn_cast<OMPLastprivateClause>(C)) { 904 SmallVector<Expr *, 8> PrivateCopies; 905 for (auto *DE : Clause->varlists()) { 906 if (DE->isValueDependent() || DE->isTypeDependent()) { 907 PrivateCopies.push_back(nullptr); 908 continue; 909 } 910 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(DE)->getDecl()); 911 QualType Type = VD->getType().getNonReferenceType(); 912 auto DVar = DSAStack->getTopDSA(VD, false); 913 if (DVar.CKind == OMPC_lastprivate) { 914 // Generate helper private variable and initialize it with the 915 // default value. The address of the original variable is replaced 916 // by the address of the new private variable in CodeGen. This new 917 // variable is not added to IdResolver, so the code in the OpenMP 918 // region uses original variable for proper diagnostics. 919 auto *VDPrivate = buildVarDecl( 920 *this, DE->getExprLoc(), Type.getUnqualifiedType(), 921 VD->getName(), VD->hasAttrs() ? &VD->getAttrs() : nullptr); 922 ActOnUninitializedDecl(VDPrivate, /*TypeMayContainAuto=*/false); 923 if (VDPrivate->isInvalidDecl()) 924 continue; 925 PrivateCopies.push_back(buildDeclRefExpr( 926 *this, VDPrivate, DE->getType(), DE->getExprLoc())); 927 } else { 928 // The variable is also a firstprivate, so initialization sequence 929 // for private copy is generated already. 930 PrivateCopies.push_back(nullptr); 931 } 932 } 933 // Set initializers to private copies if no errors were found. 934 if (PrivateCopies.size() == Clause->varlist_size()) { 935 Clause->setPrivateCopies(PrivateCopies); 936 } 937 } 938 } 939 } 940 941 DSAStack->pop(); 942 DiscardCleanupsInEvaluationContext(); 943 PopExpressionEvaluationContext(); 944 } 945 946 static bool FinishOpenMPLinearClause(OMPLinearClause &Clause, DeclRefExpr *IV, 947 Expr *NumIterations, Sema &SemaRef, 948 Scope *S); 949 950 namespace { 951 952 class VarDeclFilterCCC : public CorrectionCandidateCallback { 953 private: 954 Sema &SemaRef; 955 956 public: 957 explicit VarDeclFilterCCC(Sema &S) : SemaRef(S) {} 958 bool ValidateCandidate(const TypoCorrection &Candidate) override { 959 NamedDecl *ND = Candidate.getCorrectionDecl(); 960 if (VarDecl *VD = dyn_cast_or_null<VarDecl>(ND)) { 961 return VD->hasGlobalStorage() && 962 SemaRef.isDeclInScope(ND, SemaRef.getCurLexicalContext(), 963 SemaRef.getCurScope()); 964 } 965 return false; 966 } 967 }; 968 } // namespace 969 970 ExprResult Sema::ActOnOpenMPIdExpression(Scope *CurScope, 971 CXXScopeSpec &ScopeSpec, 972 const DeclarationNameInfo &Id) { 973 LookupResult Lookup(*this, Id, LookupOrdinaryName); 974 LookupParsedName(Lookup, CurScope, &ScopeSpec, true); 975 976 if (Lookup.isAmbiguous()) 977 return ExprError(); 978 979 VarDecl *VD; 980 if (!Lookup.isSingleResult()) { 981 if (TypoCorrection Corrected = CorrectTypo( 982 Id, LookupOrdinaryName, CurScope, nullptr, 983 llvm::make_unique<VarDeclFilterCCC>(*this), CTK_ErrorRecovery)) { 984 diagnoseTypo(Corrected, 985 PDiag(Lookup.empty() 986 ? diag::err_undeclared_var_use_suggest 987 : diag::err_omp_expected_var_arg_suggest) 988 << Id.getName()); 989 VD = Corrected.getCorrectionDeclAs<VarDecl>(); 990 } else { 991 Diag(Id.getLoc(), Lookup.empty() ? diag::err_undeclared_var_use 992 : diag::err_omp_expected_var_arg) 993 << Id.getName(); 994 return ExprError(); 995 } 996 } else { 997 if (!(VD = Lookup.getAsSingle<VarDecl>())) { 998 Diag(Id.getLoc(), diag::err_omp_expected_var_arg) << Id.getName(); 999 Diag(Lookup.getFoundDecl()->getLocation(), diag::note_declared_at); 1000 return ExprError(); 1001 } 1002 } 1003 Lookup.suppressDiagnostics(); 1004 1005 // OpenMP [2.9.2, Syntax, C/C++] 1006 // Variables must be file-scope, namespace-scope, or static block-scope. 1007 if (!VD->hasGlobalStorage()) { 1008 Diag(Id.getLoc(), diag::err_omp_global_var_arg) 1009 << getOpenMPDirectiveName(OMPD_threadprivate) << !VD->isStaticLocal(); 1010 bool IsDecl = 1011 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly; 1012 Diag(VD->getLocation(), 1013 IsDecl ? diag::note_previous_decl : diag::note_defined_here) 1014 << VD; 1015 return ExprError(); 1016 } 1017 1018 VarDecl *CanonicalVD = VD->getCanonicalDecl(); 1019 NamedDecl *ND = cast<NamedDecl>(CanonicalVD); 1020 // OpenMP [2.9.2, Restrictions, C/C++, p.2] 1021 // A threadprivate directive for file-scope variables must appear outside 1022 // any definition or declaration. 1023 if (CanonicalVD->getDeclContext()->isTranslationUnit() && 1024 !getCurLexicalContext()->isTranslationUnit()) { 1025 Diag(Id.getLoc(), diag::err_omp_var_scope) 1026 << getOpenMPDirectiveName(OMPD_threadprivate) << VD; 1027 bool IsDecl = 1028 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly; 1029 Diag(VD->getLocation(), 1030 IsDecl ? diag::note_previous_decl : diag::note_defined_here) 1031 << VD; 1032 return ExprError(); 1033 } 1034 // OpenMP [2.9.2, Restrictions, C/C++, p.3] 1035 // A threadprivate directive for static class member variables must appear 1036 // in the class definition, in the same scope in which the member 1037 // variables are declared. 1038 if (CanonicalVD->isStaticDataMember() && 1039 !CanonicalVD->getDeclContext()->Equals(getCurLexicalContext())) { 1040 Diag(Id.getLoc(), diag::err_omp_var_scope) 1041 << getOpenMPDirectiveName(OMPD_threadprivate) << VD; 1042 bool IsDecl = 1043 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly; 1044 Diag(VD->getLocation(), 1045 IsDecl ? diag::note_previous_decl : diag::note_defined_here) 1046 << VD; 1047 return ExprError(); 1048 } 1049 // OpenMP [2.9.2, Restrictions, C/C++, p.4] 1050 // A threadprivate directive for namespace-scope variables must appear 1051 // outside any definition or declaration other than the namespace 1052 // definition itself. 1053 if (CanonicalVD->getDeclContext()->isNamespace() && 1054 (!getCurLexicalContext()->isFileContext() || 1055 !getCurLexicalContext()->Encloses(CanonicalVD->getDeclContext()))) { 1056 Diag(Id.getLoc(), diag::err_omp_var_scope) 1057 << getOpenMPDirectiveName(OMPD_threadprivate) << VD; 1058 bool IsDecl = 1059 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly; 1060 Diag(VD->getLocation(), 1061 IsDecl ? diag::note_previous_decl : diag::note_defined_here) 1062 << VD; 1063 return ExprError(); 1064 } 1065 // OpenMP [2.9.2, Restrictions, C/C++, p.6] 1066 // A threadprivate directive for static block-scope variables must appear 1067 // in the scope of the variable and not in a nested scope. 1068 if (CanonicalVD->isStaticLocal() && CurScope && 1069 !isDeclInScope(ND, getCurLexicalContext(), CurScope)) { 1070 Diag(Id.getLoc(), diag::err_omp_var_scope) 1071 << getOpenMPDirectiveName(OMPD_threadprivate) << VD; 1072 bool IsDecl = 1073 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly; 1074 Diag(VD->getLocation(), 1075 IsDecl ? diag::note_previous_decl : diag::note_defined_here) 1076 << VD; 1077 return ExprError(); 1078 } 1079 1080 // OpenMP [2.9.2, Restrictions, C/C++, p.2-6] 1081 // A threadprivate directive must lexically precede all references to any 1082 // of the variables in its list. 1083 if (VD->isUsed() && !DSAStack->isThreadPrivate(VD)) { 1084 Diag(Id.getLoc(), diag::err_omp_var_used) 1085 << getOpenMPDirectiveName(OMPD_threadprivate) << VD; 1086 return ExprError(); 1087 } 1088 1089 QualType ExprType = VD->getType().getNonReferenceType(); 1090 ExprResult DE = buildDeclRefExpr(*this, VD, ExprType, Id.getLoc()); 1091 return DE; 1092 } 1093 1094 Sema::DeclGroupPtrTy 1095 Sema::ActOnOpenMPThreadprivateDirective(SourceLocation Loc, 1096 ArrayRef<Expr *> VarList) { 1097 if (OMPThreadPrivateDecl *D = CheckOMPThreadPrivateDecl(Loc, VarList)) { 1098 CurContext->addDecl(D); 1099 return DeclGroupPtrTy::make(DeclGroupRef(D)); 1100 } 1101 return DeclGroupPtrTy(); 1102 } 1103 1104 namespace { 1105 class LocalVarRefChecker : public ConstStmtVisitor<LocalVarRefChecker, bool> { 1106 Sema &SemaRef; 1107 1108 public: 1109 bool VisitDeclRefExpr(const DeclRefExpr *E) { 1110 if (auto VD = dyn_cast<VarDecl>(E->getDecl())) { 1111 if (VD->hasLocalStorage()) { 1112 SemaRef.Diag(E->getLocStart(), 1113 diag::err_omp_local_var_in_threadprivate_init) 1114 << E->getSourceRange(); 1115 SemaRef.Diag(VD->getLocation(), diag::note_defined_here) 1116 << VD << VD->getSourceRange(); 1117 return true; 1118 } 1119 } 1120 return false; 1121 } 1122 bool VisitStmt(const Stmt *S) { 1123 for (auto Child : S->children()) { 1124 if (Child && Visit(Child)) 1125 return true; 1126 } 1127 return false; 1128 } 1129 explicit LocalVarRefChecker(Sema &SemaRef) : SemaRef(SemaRef) {} 1130 }; 1131 } // namespace 1132 1133 OMPThreadPrivateDecl * 1134 Sema::CheckOMPThreadPrivateDecl(SourceLocation Loc, ArrayRef<Expr *> VarList) { 1135 SmallVector<Expr *, 8> Vars; 1136 for (auto &RefExpr : VarList) { 1137 DeclRefExpr *DE = cast<DeclRefExpr>(RefExpr); 1138 VarDecl *VD = cast<VarDecl>(DE->getDecl()); 1139 SourceLocation ILoc = DE->getExprLoc(); 1140 1141 QualType QType = VD->getType(); 1142 if (QType->isDependentType() || QType->isInstantiationDependentType()) { 1143 // It will be analyzed later. 1144 Vars.push_back(DE); 1145 continue; 1146 } 1147 1148 // OpenMP [2.9.2, Restrictions, C/C++, p.10] 1149 // A threadprivate variable must not have an incomplete type. 1150 if (RequireCompleteType(ILoc, VD->getType(), 1151 diag::err_omp_threadprivate_incomplete_type)) { 1152 continue; 1153 } 1154 1155 // OpenMP [2.9.2, Restrictions, C/C++, p.10] 1156 // A threadprivate variable must not have a reference type. 1157 if (VD->getType()->isReferenceType()) { 1158 Diag(ILoc, diag::err_omp_ref_type_arg) 1159 << getOpenMPDirectiveName(OMPD_threadprivate) << VD->getType(); 1160 bool IsDecl = 1161 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly; 1162 Diag(VD->getLocation(), 1163 IsDecl ? diag::note_previous_decl : diag::note_defined_here) 1164 << VD; 1165 continue; 1166 } 1167 1168 // Check if this is a TLS variable. If TLS is not being supported, produce 1169 // the corresponding diagnostic. 1170 if ((VD->getTLSKind() != VarDecl::TLS_None && 1171 !(VD->hasAttr<OMPThreadPrivateDeclAttr>() && 1172 getLangOpts().OpenMPUseTLS && 1173 getASTContext().getTargetInfo().isTLSSupported())) || 1174 (VD->getStorageClass() == SC_Register && VD->hasAttr<AsmLabelAttr>() && 1175 !VD->isLocalVarDecl())) { 1176 Diag(ILoc, diag::err_omp_var_thread_local) 1177 << VD << ((VD->getTLSKind() != VarDecl::TLS_None) ? 0 : 1); 1178 bool IsDecl = 1179 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly; 1180 Diag(VD->getLocation(), 1181 IsDecl ? diag::note_previous_decl : diag::note_defined_here) 1182 << VD; 1183 continue; 1184 } 1185 1186 // Check if initial value of threadprivate variable reference variable with 1187 // local storage (it is not supported by runtime). 1188 if (auto Init = VD->getAnyInitializer()) { 1189 LocalVarRefChecker Checker(*this); 1190 if (Checker.Visit(Init)) 1191 continue; 1192 } 1193 1194 Vars.push_back(RefExpr); 1195 DSAStack->addDSA(VD, DE, OMPC_threadprivate); 1196 VD->addAttr(OMPThreadPrivateDeclAttr::CreateImplicit( 1197 Context, SourceRange(Loc, Loc))); 1198 if (auto *ML = Context.getASTMutationListener()) 1199 ML->DeclarationMarkedOpenMPThreadPrivate(VD); 1200 } 1201 OMPThreadPrivateDecl *D = nullptr; 1202 if (!Vars.empty()) { 1203 D = OMPThreadPrivateDecl::Create(Context, getCurLexicalContext(), Loc, 1204 Vars); 1205 D->setAccess(AS_public); 1206 } 1207 return D; 1208 } 1209 1210 static void ReportOriginalDSA(Sema &SemaRef, DSAStackTy *Stack, 1211 const VarDecl *VD, DSAStackTy::DSAVarData DVar, 1212 bool IsLoopIterVar = false) { 1213 if (DVar.RefExpr) { 1214 SemaRef.Diag(DVar.RefExpr->getExprLoc(), diag::note_omp_explicit_dsa) 1215 << getOpenMPClauseName(DVar.CKind); 1216 return; 1217 } 1218 enum { 1219 PDSA_StaticMemberShared, 1220 PDSA_StaticLocalVarShared, 1221 PDSA_LoopIterVarPrivate, 1222 PDSA_LoopIterVarLinear, 1223 PDSA_LoopIterVarLastprivate, 1224 PDSA_ConstVarShared, 1225 PDSA_GlobalVarShared, 1226 PDSA_TaskVarFirstprivate, 1227 PDSA_LocalVarPrivate, 1228 PDSA_Implicit 1229 } Reason = PDSA_Implicit; 1230 bool ReportHint = false; 1231 auto ReportLoc = VD->getLocation(); 1232 if (IsLoopIterVar) { 1233 if (DVar.CKind == OMPC_private) 1234 Reason = PDSA_LoopIterVarPrivate; 1235 else if (DVar.CKind == OMPC_lastprivate) 1236 Reason = PDSA_LoopIterVarLastprivate; 1237 else 1238 Reason = PDSA_LoopIterVarLinear; 1239 } else if (DVar.DKind == OMPD_task && DVar.CKind == OMPC_firstprivate) { 1240 Reason = PDSA_TaskVarFirstprivate; 1241 ReportLoc = DVar.ImplicitDSALoc; 1242 } else if (VD->isStaticLocal()) 1243 Reason = PDSA_StaticLocalVarShared; 1244 else if (VD->isStaticDataMember()) 1245 Reason = PDSA_StaticMemberShared; 1246 else if (VD->isFileVarDecl()) 1247 Reason = PDSA_GlobalVarShared; 1248 else if (VD->getType().isConstant(SemaRef.getASTContext())) 1249 Reason = PDSA_ConstVarShared; 1250 else if (VD->isLocalVarDecl() && DVar.CKind == OMPC_private) { 1251 ReportHint = true; 1252 Reason = PDSA_LocalVarPrivate; 1253 } 1254 if (Reason != PDSA_Implicit) { 1255 SemaRef.Diag(ReportLoc, diag::note_omp_predetermined_dsa) 1256 << Reason << ReportHint 1257 << getOpenMPDirectiveName(Stack->getCurrentDirective()); 1258 } else if (DVar.ImplicitDSALoc.isValid()) { 1259 SemaRef.Diag(DVar.ImplicitDSALoc, diag::note_omp_implicit_dsa) 1260 << getOpenMPClauseName(DVar.CKind); 1261 } 1262 } 1263 1264 namespace { 1265 class DSAAttrChecker : public StmtVisitor<DSAAttrChecker, void> { 1266 DSAStackTy *Stack; 1267 Sema &SemaRef; 1268 bool ErrorFound; 1269 CapturedStmt *CS; 1270 llvm::SmallVector<Expr *, 8> ImplicitFirstprivate; 1271 llvm::DenseMap<VarDecl *, Expr *> VarsWithInheritedDSA; 1272 1273 public: 1274 void VisitDeclRefExpr(DeclRefExpr *E) { 1275 if (auto *VD = dyn_cast<VarDecl>(E->getDecl())) { 1276 // Skip internally declared variables. 1277 if (VD->isLocalVarDecl() && !CS->capturesVariable(VD)) 1278 return; 1279 1280 auto DVar = Stack->getTopDSA(VD, false); 1281 // Check if the variable has explicit DSA set and stop analysis if it so. 1282 if (DVar.RefExpr) return; 1283 1284 auto ELoc = E->getExprLoc(); 1285 auto DKind = Stack->getCurrentDirective(); 1286 // The default(none) clause requires that each variable that is referenced 1287 // in the construct, and does not have a predetermined data-sharing 1288 // attribute, must have its data-sharing attribute explicitly determined 1289 // by being listed in a data-sharing attribute clause. 1290 if (DVar.CKind == OMPC_unknown && Stack->getDefaultDSA() == DSA_none && 1291 isParallelOrTaskRegion(DKind) && 1292 VarsWithInheritedDSA.count(VD) == 0) { 1293 VarsWithInheritedDSA[VD] = E; 1294 return; 1295 } 1296 1297 // OpenMP [2.9.3.6, Restrictions, p.2] 1298 // A list item that appears in a reduction clause of the innermost 1299 // enclosing worksharing or parallel construct may not be accessed in an 1300 // explicit task. 1301 DVar = Stack->hasInnermostDSA(VD, MatchesAnyClause(OMPC_reduction), 1302 [](OpenMPDirectiveKind K) -> bool { 1303 return isOpenMPParallelDirective(K) || 1304 isOpenMPWorksharingDirective(K) || 1305 isOpenMPTeamsDirective(K); 1306 }, 1307 false); 1308 if (DKind == OMPD_task && DVar.CKind == OMPC_reduction) { 1309 ErrorFound = true; 1310 SemaRef.Diag(ELoc, diag::err_omp_reduction_in_task); 1311 ReportOriginalDSA(SemaRef, Stack, VD, DVar); 1312 return; 1313 } 1314 1315 // Define implicit data-sharing attributes for task. 1316 DVar = Stack->getImplicitDSA(VD, false); 1317 if (DKind == OMPD_task && DVar.CKind != OMPC_shared) 1318 ImplicitFirstprivate.push_back(E); 1319 } 1320 } 1321 void VisitOMPExecutableDirective(OMPExecutableDirective *S) { 1322 for (auto *C : S->clauses()) { 1323 // Skip analysis of arguments of implicitly defined firstprivate clause 1324 // for task directives. 1325 if (C && (!isa<OMPFirstprivateClause>(C) || C->getLocStart().isValid())) 1326 for (auto *CC : C->children()) { 1327 if (CC) 1328 Visit(CC); 1329 } 1330 } 1331 } 1332 void VisitStmt(Stmt *S) { 1333 for (auto *C : S->children()) { 1334 if (C && !isa<OMPExecutableDirective>(C)) 1335 Visit(C); 1336 } 1337 } 1338 1339 bool isErrorFound() { return ErrorFound; } 1340 ArrayRef<Expr *> getImplicitFirstprivate() { return ImplicitFirstprivate; } 1341 llvm::DenseMap<VarDecl *, Expr *> &getVarsWithInheritedDSA() { 1342 return VarsWithInheritedDSA; 1343 } 1344 1345 DSAAttrChecker(DSAStackTy *S, Sema &SemaRef, CapturedStmt *CS) 1346 : Stack(S), SemaRef(SemaRef), ErrorFound(false), CS(CS) {} 1347 }; 1348 } // namespace 1349 1350 void Sema::ActOnOpenMPRegionStart(OpenMPDirectiveKind DKind, Scope *CurScope) { 1351 switch (DKind) { 1352 case OMPD_parallel: { 1353 QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1); 1354 QualType KmpInt32PtrTy = 1355 Context.getPointerType(KmpInt32Ty).withConst().withRestrict(); 1356 Sema::CapturedParamNameType Params[] = { 1357 std::make_pair(".global_tid.", KmpInt32PtrTy), 1358 std::make_pair(".bound_tid.", KmpInt32PtrTy), 1359 std::make_pair(StringRef(), QualType()) // __context with shared vars 1360 }; 1361 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP, 1362 Params); 1363 break; 1364 } 1365 case OMPD_simd: { 1366 Sema::CapturedParamNameType Params[] = { 1367 std::make_pair(StringRef(), QualType()) // __context with shared vars 1368 }; 1369 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP, 1370 Params); 1371 break; 1372 } 1373 case OMPD_for: { 1374 Sema::CapturedParamNameType Params[] = { 1375 std::make_pair(StringRef(), QualType()) // __context with shared vars 1376 }; 1377 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP, 1378 Params); 1379 break; 1380 } 1381 case OMPD_for_simd: { 1382 Sema::CapturedParamNameType Params[] = { 1383 std::make_pair(StringRef(), QualType()) // __context with shared vars 1384 }; 1385 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP, 1386 Params); 1387 break; 1388 } 1389 case OMPD_sections: { 1390 Sema::CapturedParamNameType Params[] = { 1391 std::make_pair(StringRef(), QualType()) // __context with shared vars 1392 }; 1393 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP, 1394 Params); 1395 break; 1396 } 1397 case OMPD_section: { 1398 Sema::CapturedParamNameType Params[] = { 1399 std::make_pair(StringRef(), QualType()) // __context with shared vars 1400 }; 1401 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP, 1402 Params); 1403 break; 1404 } 1405 case OMPD_single: { 1406 Sema::CapturedParamNameType Params[] = { 1407 std::make_pair(StringRef(), QualType()) // __context with shared vars 1408 }; 1409 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP, 1410 Params); 1411 break; 1412 } 1413 case OMPD_master: { 1414 Sema::CapturedParamNameType Params[] = { 1415 std::make_pair(StringRef(), QualType()) // __context with shared vars 1416 }; 1417 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP, 1418 Params); 1419 break; 1420 } 1421 case OMPD_critical: { 1422 Sema::CapturedParamNameType Params[] = { 1423 std::make_pair(StringRef(), QualType()) // __context with shared vars 1424 }; 1425 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP, 1426 Params); 1427 break; 1428 } 1429 case OMPD_parallel_for: { 1430 QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1); 1431 QualType KmpInt32PtrTy = 1432 Context.getPointerType(KmpInt32Ty).withConst().withRestrict(); 1433 Sema::CapturedParamNameType Params[] = { 1434 std::make_pair(".global_tid.", KmpInt32PtrTy), 1435 std::make_pair(".bound_tid.", KmpInt32PtrTy), 1436 std::make_pair(StringRef(), QualType()) // __context with shared vars 1437 }; 1438 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP, 1439 Params); 1440 break; 1441 } 1442 case OMPD_parallel_for_simd: { 1443 QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1); 1444 QualType KmpInt32PtrTy = 1445 Context.getPointerType(KmpInt32Ty).withConst().withRestrict(); 1446 Sema::CapturedParamNameType Params[] = { 1447 std::make_pair(".global_tid.", KmpInt32PtrTy), 1448 std::make_pair(".bound_tid.", KmpInt32PtrTy), 1449 std::make_pair(StringRef(), QualType()) // __context with shared vars 1450 }; 1451 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP, 1452 Params); 1453 break; 1454 } 1455 case OMPD_parallel_sections: { 1456 QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1); 1457 QualType KmpInt32PtrTy = 1458 Context.getPointerType(KmpInt32Ty).withConst().withRestrict(); 1459 Sema::CapturedParamNameType Params[] = { 1460 std::make_pair(".global_tid.", KmpInt32PtrTy), 1461 std::make_pair(".bound_tid.", KmpInt32PtrTy), 1462 std::make_pair(StringRef(), QualType()) // __context with shared vars 1463 }; 1464 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP, 1465 Params); 1466 break; 1467 } 1468 case OMPD_task: { 1469 QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1); 1470 QualType Args[] = {Context.VoidPtrTy.withConst().withRestrict()}; 1471 FunctionProtoType::ExtProtoInfo EPI; 1472 EPI.Variadic = true; 1473 QualType CopyFnType = Context.getFunctionType(Context.VoidTy, Args, EPI); 1474 Sema::CapturedParamNameType Params[] = { 1475 std::make_pair(".global_tid.", KmpInt32Ty), 1476 std::make_pair(".part_id.", KmpInt32Ty), 1477 std::make_pair(".privates.", 1478 Context.VoidPtrTy.withConst().withRestrict()), 1479 std::make_pair( 1480 ".copy_fn.", 1481 Context.getPointerType(CopyFnType).withConst().withRestrict()), 1482 std::make_pair(StringRef(), QualType()) // __context with shared vars 1483 }; 1484 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP, 1485 Params); 1486 // Mark this captured region as inlined, because we don't use outlined 1487 // function directly. 1488 getCurCapturedRegion()->TheCapturedDecl->addAttr( 1489 AlwaysInlineAttr::CreateImplicit( 1490 Context, AlwaysInlineAttr::Keyword_forceinline, SourceRange())); 1491 break; 1492 } 1493 case OMPD_ordered: { 1494 Sema::CapturedParamNameType Params[] = { 1495 std::make_pair(StringRef(), QualType()) // __context with shared vars 1496 }; 1497 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP, 1498 Params); 1499 break; 1500 } 1501 case OMPD_atomic: { 1502 Sema::CapturedParamNameType Params[] = { 1503 std::make_pair(StringRef(), QualType()) // __context with shared vars 1504 }; 1505 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP, 1506 Params); 1507 break; 1508 } 1509 case OMPD_target_data: 1510 case OMPD_target: { 1511 Sema::CapturedParamNameType Params[] = { 1512 std::make_pair(StringRef(), QualType()) // __context with shared vars 1513 }; 1514 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP, 1515 Params); 1516 break; 1517 } 1518 case OMPD_teams: { 1519 QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1); 1520 QualType KmpInt32PtrTy = 1521 Context.getPointerType(KmpInt32Ty).withConst().withRestrict(); 1522 Sema::CapturedParamNameType Params[] = { 1523 std::make_pair(".global_tid.", KmpInt32PtrTy), 1524 std::make_pair(".bound_tid.", KmpInt32PtrTy), 1525 std::make_pair(StringRef(), QualType()) // __context with shared vars 1526 }; 1527 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP, 1528 Params); 1529 break; 1530 } 1531 case OMPD_taskgroup: { 1532 Sema::CapturedParamNameType Params[] = { 1533 std::make_pair(StringRef(), QualType()) // __context with shared vars 1534 }; 1535 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP, 1536 Params); 1537 break; 1538 } 1539 case OMPD_taskloop: { 1540 Sema::CapturedParamNameType Params[] = { 1541 std::make_pair(StringRef(), QualType()) // __context with shared vars 1542 }; 1543 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP, 1544 Params); 1545 break; 1546 } 1547 case OMPD_taskloop_simd: { 1548 Sema::CapturedParamNameType Params[] = { 1549 std::make_pair(StringRef(), QualType()) // __context with shared vars 1550 }; 1551 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP, 1552 Params); 1553 break; 1554 } 1555 case OMPD_threadprivate: 1556 case OMPD_taskyield: 1557 case OMPD_barrier: 1558 case OMPD_taskwait: 1559 case OMPD_cancellation_point: 1560 case OMPD_cancel: 1561 case OMPD_flush: 1562 llvm_unreachable("OpenMP Directive is not allowed"); 1563 case OMPD_unknown: 1564 llvm_unreachable("Unknown OpenMP directive"); 1565 } 1566 } 1567 1568 StmtResult Sema::ActOnOpenMPRegionEnd(StmtResult S, 1569 ArrayRef<OMPClause *> Clauses) { 1570 if (!S.isUsable()) { 1571 ActOnCapturedRegionError(); 1572 return StmtError(); 1573 } 1574 // This is required for proper codegen. 1575 for (auto *Clause : Clauses) { 1576 if (isOpenMPPrivate(Clause->getClauseKind()) || 1577 Clause->getClauseKind() == OMPC_copyprivate || 1578 (getLangOpts().OpenMPUseTLS && 1579 getASTContext().getTargetInfo().isTLSSupported() && 1580 Clause->getClauseKind() == OMPC_copyin)) { 1581 DSAStack->setForceVarCapturing(Clause->getClauseKind() == OMPC_copyin); 1582 // Mark all variables in private list clauses as used in inner region. 1583 for (auto *VarRef : Clause->children()) { 1584 if (auto *E = cast_or_null<Expr>(VarRef)) { 1585 MarkDeclarationsReferencedInExpr(E); 1586 } 1587 } 1588 DSAStack->setForceVarCapturing(/*V=*/false); 1589 } else if (isParallelOrTaskRegion(DSAStack->getCurrentDirective()) && 1590 Clause->getClauseKind() == OMPC_schedule) { 1591 // Mark all variables in private list clauses as used in inner region. 1592 // Required for proper codegen of combined directives. 1593 // TODO: add processing for other clauses. 1594 if (auto *E = cast_or_null<Expr>( 1595 cast<OMPScheduleClause>(Clause)->getHelperChunkSize())) { 1596 MarkDeclarationsReferencedInExpr(E); 1597 } 1598 } 1599 } 1600 return ActOnCapturedRegionEnd(S.get()); 1601 } 1602 1603 static bool CheckNestingOfRegions(Sema &SemaRef, DSAStackTy *Stack, 1604 OpenMPDirectiveKind CurrentRegion, 1605 const DeclarationNameInfo &CurrentName, 1606 OpenMPDirectiveKind CancelRegion, 1607 SourceLocation StartLoc) { 1608 // Allowed nesting of constructs 1609 // +------------------+-----------------+------------------------------------+ 1610 // | Parent directive | Child directive | Closely (!), No-Closely(+), Both(*)| 1611 // +------------------+-----------------+------------------------------------+ 1612 // | parallel | parallel | * | 1613 // | parallel | for | * | 1614 // | parallel | for simd | * | 1615 // | parallel | master | * | 1616 // | parallel | critical | * | 1617 // | parallel | simd | * | 1618 // | parallel | sections | * | 1619 // | parallel | section | + | 1620 // | parallel | single | * | 1621 // | parallel | parallel for | * | 1622 // | parallel |parallel for simd| * | 1623 // | parallel |parallel sections| * | 1624 // | parallel | task | * | 1625 // | parallel | taskyield | * | 1626 // | parallel | barrier | * | 1627 // | parallel | taskwait | * | 1628 // | parallel | taskgroup | * | 1629 // | parallel | flush | * | 1630 // | parallel | ordered | + | 1631 // | parallel | atomic | * | 1632 // | parallel | target | * | 1633 // | parallel | teams | + | 1634 // | parallel | cancellation | | 1635 // | | point | ! | 1636 // | parallel | cancel | ! | 1637 // | parallel | taskloop | * | 1638 // | parallel | taskloop simd | * | 1639 // +------------------+-----------------+------------------------------------+ 1640 // | for | parallel | * | 1641 // | for | for | + | 1642 // | for | for simd | + | 1643 // | for | master | + | 1644 // | for | critical | * | 1645 // | for | simd | * | 1646 // | for | sections | + | 1647 // | for | section | + | 1648 // | for | single | + | 1649 // | for | parallel for | * | 1650 // | for |parallel for simd| * | 1651 // | for |parallel sections| * | 1652 // | for | task | * | 1653 // | for | taskyield | * | 1654 // | for | barrier | + | 1655 // | for | taskwait | * | 1656 // | for | taskgroup | * | 1657 // | for | flush | * | 1658 // | for | ordered | * (if construct is ordered) | 1659 // | for | atomic | * | 1660 // | for | target | * | 1661 // | for | teams | + | 1662 // | for | cancellation | | 1663 // | | point | ! | 1664 // | for | cancel | ! | 1665 // | for | taskloop | * | 1666 // | for | taskloop simd | * | 1667 // +------------------+-----------------+------------------------------------+ 1668 // | master | parallel | * | 1669 // | master | for | + | 1670 // | master | for simd | + | 1671 // | master | master | * | 1672 // | master | critical | * | 1673 // | master | simd | * | 1674 // | master | sections | + | 1675 // | master | section | + | 1676 // | master | single | + | 1677 // | master | parallel for | * | 1678 // | master |parallel for simd| * | 1679 // | master |parallel sections| * | 1680 // | master | task | * | 1681 // | master | taskyield | * | 1682 // | master | barrier | + | 1683 // | master | taskwait | * | 1684 // | master | taskgroup | * | 1685 // | master | flush | * | 1686 // | master | ordered | + | 1687 // | master | atomic | * | 1688 // | master | target | * | 1689 // | master | teams | + | 1690 // | master | cancellation | | 1691 // | | point | | 1692 // | master | cancel | | 1693 // | master | taskloop | * | 1694 // | master | taskloop simd | * | 1695 // +------------------+-----------------+------------------------------------+ 1696 // | critical | parallel | * | 1697 // | critical | for | + | 1698 // | critical | for simd | + | 1699 // | critical | master | * | 1700 // | critical | critical | * (should have different names) | 1701 // | critical | simd | * | 1702 // | critical | sections | + | 1703 // | critical | section | + | 1704 // | critical | single | + | 1705 // | critical | parallel for | * | 1706 // | critical |parallel for simd| * | 1707 // | critical |parallel sections| * | 1708 // | critical | task | * | 1709 // | critical | taskyield | * | 1710 // | critical | barrier | + | 1711 // | critical | taskwait | * | 1712 // | critical | taskgroup | * | 1713 // | critical | ordered | + | 1714 // | critical | atomic | * | 1715 // | critical | target | * | 1716 // | critical | teams | + | 1717 // | critical | cancellation | | 1718 // | | point | | 1719 // | critical | cancel | | 1720 // | critical | taskloop | * | 1721 // | critical | taskloop simd | * | 1722 // +------------------+-----------------+------------------------------------+ 1723 // | simd | parallel | | 1724 // | simd | for | | 1725 // | simd | for simd | | 1726 // | simd | master | | 1727 // | simd | critical | | 1728 // | simd | simd | | 1729 // | simd | sections | | 1730 // | simd | section | | 1731 // | simd | single | | 1732 // | simd | parallel for | | 1733 // | simd |parallel for simd| | 1734 // | simd |parallel sections| | 1735 // | simd | task | | 1736 // | simd | taskyield | | 1737 // | simd | barrier | | 1738 // | simd | taskwait | | 1739 // | simd | taskgroup | | 1740 // | simd | flush | | 1741 // | simd | ordered | + (with simd clause) | 1742 // | simd | atomic | | 1743 // | simd | target | | 1744 // | simd | teams | | 1745 // | simd | cancellation | | 1746 // | | point | | 1747 // | simd | cancel | | 1748 // | simd | taskloop | | 1749 // | simd | taskloop simd | | 1750 // +------------------+-----------------+------------------------------------+ 1751 // | for simd | parallel | | 1752 // | for simd | for | | 1753 // | for simd | for simd | | 1754 // | for simd | master | | 1755 // | for simd | critical | | 1756 // | for simd | simd | | 1757 // | for simd | sections | | 1758 // | for simd | section | | 1759 // | for simd | single | | 1760 // | for simd | parallel for | | 1761 // | for simd |parallel for simd| | 1762 // | for simd |parallel sections| | 1763 // | for simd | task | | 1764 // | for simd | taskyield | | 1765 // | for simd | barrier | | 1766 // | for simd | taskwait | | 1767 // | for simd | taskgroup | | 1768 // | for simd | flush | | 1769 // | for simd | ordered | + (with simd clause) | 1770 // | for simd | atomic | | 1771 // | for simd | target | | 1772 // | for simd | teams | | 1773 // | for simd | cancellation | | 1774 // | | point | | 1775 // | for simd | cancel | | 1776 // | for simd | taskloop | | 1777 // | for simd | taskloop simd | | 1778 // +------------------+-----------------+------------------------------------+ 1779 // | parallel for simd| parallel | | 1780 // | parallel for simd| for | | 1781 // | parallel for simd| for simd | | 1782 // | parallel for simd| master | | 1783 // | parallel for simd| critical | | 1784 // | parallel for simd| simd | | 1785 // | parallel for simd| sections | | 1786 // | parallel for simd| section | | 1787 // | parallel for simd| single | | 1788 // | parallel for simd| parallel for | | 1789 // | parallel for simd|parallel for simd| | 1790 // | parallel for simd|parallel sections| | 1791 // | parallel for simd| task | | 1792 // | parallel for simd| taskyield | | 1793 // | parallel for simd| barrier | | 1794 // | parallel for simd| taskwait | | 1795 // | parallel for simd| taskgroup | | 1796 // | parallel for simd| flush | | 1797 // | parallel for simd| ordered | + (with simd clause) | 1798 // | parallel for simd| atomic | | 1799 // | parallel for simd| target | | 1800 // | parallel for simd| teams | | 1801 // | parallel for simd| cancellation | | 1802 // | | point | | 1803 // | parallel for simd| cancel | | 1804 // | parallel for simd| taskloop | | 1805 // | parallel for simd| taskloop simd | | 1806 // +------------------+-----------------+------------------------------------+ 1807 // | sections | parallel | * | 1808 // | sections | for | + | 1809 // | sections | for simd | + | 1810 // | sections | master | + | 1811 // | sections | critical | * | 1812 // | sections | simd | * | 1813 // | sections | sections | + | 1814 // | sections | section | * | 1815 // | sections | single | + | 1816 // | sections | parallel for | * | 1817 // | sections |parallel for simd| * | 1818 // | sections |parallel sections| * | 1819 // | sections | task | * | 1820 // | sections | taskyield | * | 1821 // | sections | barrier | + | 1822 // | sections | taskwait | * | 1823 // | sections | taskgroup | * | 1824 // | sections | flush | * | 1825 // | sections | ordered | + | 1826 // | sections | atomic | * | 1827 // | sections | target | * | 1828 // | sections | teams | + | 1829 // | sections | cancellation | | 1830 // | | point | ! | 1831 // | sections | cancel | ! | 1832 // | sections | taskloop | * | 1833 // | sections | taskloop simd | * | 1834 // +------------------+-----------------+------------------------------------+ 1835 // | section | parallel | * | 1836 // | section | for | + | 1837 // | section | for simd | + | 1838 // | section | master | + | 1839 // | section | critical | * | 1840 // | section | simd | * | 1841 // | section | sections | + | 1842 // | section | section | + | 1843 // | section | single | + | 1844 // | section | parallel for | * | 1845 // | section |parallel for simd| * | 1846 // | section |parallel sections| * | 1847 // | section | task | * | 1848 // | section | taskyield | * | 1849 // | section | barrier | + | 1850 // | section | taskwait | * | 1851 // | section | taskgroup | * | 1852 // | section | flush | * | 1853 // | section | ordered | + | 1854 // | section | atomic | * | 1855 // | section | target | * | 1856 // | section | teams | + | 1857 // | section | cancellation | | 1858 // | | point | ! | 1859 // | section | cancel | ! | 1860 // | section | taskloop | * | 1861 // | section | taskloop simd | * | 1862 // +------------------+-----------------+------------------------------------+ 1863 // | single | parallel | * | 1864 // | single | for | + | 1865 // | single | for simd | + | 1866 // | single | master | + | 1867 // | single | critical | * | 1868 // | single | simd | * | 1869 // | single | sections | + | 1870 // | single | section | + | 1871 // | single | single | + | 1872 // | single | parallel for | * | 1873 // | single |parallel for simd| * | 1874 // | single |parallel sections| * | 1875 // | single | task | * | 1876 // | single | taskyield | * | 1877 // | single | barrier | + | 1878 // | single | taskwait | * | 1879 // | single | taskgroup | * | 1880 // | single | flush | * | 1881 // | single | ordered | + | 1882 // | single | atomic | * | 1883 // | single | target | * | 1884 // | single | teams | + | 1885 // | single | cancellation | | 1886 // | | point | | 1887 // | single | cancel | | 1888 // | single | taskloop | * | 1889 // | single | taskloop simd | * | 1890 // +------------------+-----------------+------------------------------------+ 1891 // | parallel for | parallel | * | 1892 // | parallel for | for | + | 1893 // | parallel for | for simd | + | 1894 // | parallel for | master | + | 1895 // | parallel for | critical | * | 1896 // | parallel for | simd | * | 1897 // | parallel for | sections | + | 1898 // | parallel for | section | + | 1899 // | parallel for | single | + | 1900 // | parallel for | parallel for | * | 1901 // | parallel for |parallel for simd| * | 1902 // | parallel for |parallel sections| * | 1903 // | parallel for | task | * | 1904 // | parallel for | taskyield | * | 1905 // | parallel for | barrier | + | 1906 // | parallel for | taskwait | * | 1907 // | parallel for | taskgroup | * | 1908 // | parallel for | flush | * | 1909 // | parallel for | ordered | * (if construct is ordered) | 1910 // | parallel for | atomic | * | 1911 // | parallel for | target | * | 1912 // | parallel for | teams | + | 1913 // | parallel for | cancellation | | 1914 // | | point | ! | 1915 // | parallel for | cancel | ! | 1916 // | parallel for | taskloop | * | 1917 // | parallel for | taskloop simd | * | 1918 // +------------------+-----------------+------------------------------------+ 1919 // | parallel sections| parallel | * | 1920 // | parallel sections| for | + | 1921 // | parallel sections| for simd | + | 1922 // | parallel sections| master | + | 1923 // | parallel sections| critical | + | 1924 // | parallel sections| simd | * | 1925 // | parallel sections| sections | + | 1926 // | parallel sections| section | * | 1927 // | parallel sections| single | + | 1928 // | parallel sections| parallel for | * | 1929 // | parallel sections|parallel for simd| * | 1930 // | parallel sections|parallel sections| * | 1931 // | parallel sections| task | * | 1932 // | parallel sections| taskyield | * | 1933 // | parallel sections| barrier | + | 1934 // | parallel sections| taskwait | * | 1935 // | parallel sections| taskgroup | * | 1936 // | parallel sections| flush | * | 1937 // | parallel sections| ordered | + | 1938 // | parallel sections| atomic | * | 1939 // | parallel sections| target | * | 1940 // | parallel sections| teams | + | 1941 // | parallel sections| cancellation | | 1942 // | | point | ! | 1943 // | parallel sections| cancel | ! | 1944 // | parallel sections| taskloop | * | 1945 // | parallel sections| taskloop simd | * | 1946 // +------------------+-----------------+------------------------------------+ 1947 // | task | parallel | * | 1948 // | task | for | + | 1949 // | task | for simd | + | 1950 // | task | master | + | 1951 // | task | critical | * | 1952 // | task | simd | * | 1953 // | task | sections | + | 1954 // | task | section | + | 1955 // | task | single | + | 1956 // | task | parallel for | * | 1957 // | task |parallel for simd| * | 1958 // | task |parallel sections| * | 1959 // | task | task | * | 1960 // | task | taskyield | * | 1961 // | task | barrier | + | 1962 // | task | taskwait | * | 1963 // | task | taskgroup | * | 1964 // | task | flush | * | 1965 // | task | ordered | + | 1966 // | task | atomic | * | 1967 // | task | target | * | 1968 // | task | teams | + | 1969 // | task | cancellation | | 1970 // | | point | ! | 1971 // | task | cancel | ! | 1972 // | task | taskloop | * | 1973 // | task | taskloop simd | * | 1974 // +------------------+-----------------+------------------------------------+ 1975 // | ordered | parallel | * | 1976 // | ordered | for | + | 1977 // | ordered | for simd | + | 1978 // | ordered | master | * | 1979 // | ordered | critical | * | 1980 // | ordered | simd | * | 1981 // | ordered | sections | + | 1982 // | ordered | section | + | 1983 // | ordered | single | + | 1984 // | ordered | parallel for | * | 1985 // | ordered |parallel for simd| * | 1986 // | ordered |parallel sections| * | 1987 // | ordered | task | * | 1988 // | ordered | taskyield | * | 1989 // | ordered | barrier | + | 1990 // | ordered | taskwait | * | 1991 // | ordered | taskgroup | * | 1992 // | ordered | flush | * | 1993 // | ordered | ordered | + | 1994 // | ordered | atomic | * | 1995 // | ordered | target | * | 1996 // | ordered | teams | + | 1997 // | ordered | cancellation | | 1998 // | | point | | 1999 // | ordered | cancel | | 2000 // | ordered | taskloop | * | 2001 // | ordered | taskloop simd | * | 2002 // +------------------+-----------------+------------------------------------+ 2003 // | atomic | parallel | | 2004 // | atomic | for | | 2005 // | atomic | for simd | | 2006 // | atomic | master | | 2007 // | atomic | critical | | 2008 // | atomic | simd | | 2009 // | atomic | sections | | 2010 // | atomic | section | | 2011 // | atomic | single | | 2012 // | atomic | parallel for | | 2013 // | atomic |parallel for simd| | 2014 // | atomic |parallel sections| | 2015 // | atomic | task | | 2016 // | atomic | taskyield | | 2017 // | atomic | barrier | | 2018 // | atomic | taskwait | | 2019 // | atomic | taskgroup | | 2020 // | atomic | flush | | 2021 // | atomic | ordered | | 2022 // | atomic | atomic | | 2023 // | atomic | target | | 2024 // | atomic | teams | | 2025 // | atomic | cancellation | | 2026 // | | point | | 2027 // | atomic | cancel | | 2028 // | atomic | taskloop | | 2029 // | atomic | taskloop simd | | 2030 // +------------------+-----------------+------------------------------------+ 2031 // | target | parallel | * | 2032 // | target | for | * | 2033 // | target | for simd | * | 2034 // | target | master | * | 2035 // | target | critical | * | 2036 // | target | simd | * | 2037 // | target | sections | * | 2038 // | target | section | * | 2039 // | target | single | * | 2040 // | target | parallel for | * | 2041 // | target |parallel for simd| * | 2042 // | target |parallel sections| * | 2043 // | target | task | * | 2044 // | target | taskyield | * | 2045 // | target | barrier | * | 2046 // | target | taskwait | * | 2047 // | target | taskgroup | * | 2048 // | target | flush | * | 2049 // | target | ordered | * | 2050 // | target | atomic | * | 2051 // | target | target | * | 2052 // | target | teams | * | 2053 // | target | cancellation | | 2054 // | | point | | 2055 // | target | cancel | | 2056 // | target | taskloop | * | 2057 // | target | taskloop simd | * | 2058 // +------------------+-----------------+------------------------------------+ 2059 // | teams | parallel | * | 2060 // | teams | for | + | 2061 // | teams | for simd | + | 2062 // | teams | master | + | 2063 // | teams | critical | + | 2064 // | teams | simd | + | 2065 // | teams | sections | + | 2066 // | teams | section | + | 2067 // | teams | single | + | 2068 // | teams | parallel for | * | 2069 // | teams |parallel for simd| * | 2070 // | teams |parallel sections| * | 2071 // | teams | task | + | 2072 // | teams | taskyield | + | 2073 // | teams | barrier | + | 2074 // | teams | taskwait | + | 2075 // | teams | taskgroup | + | 2076 // | teams | flush | + | 2077 // | teams | ordered | + | 2078 // | teams | atomic | + | 2079 // | teams | target | + | 2080 // | teams | teams | + | 2081 // | teams | cancellation | | 2082 // | | point | | 2083 // | teams | cancel | | 2084 // | teams | taskloop | + | 2085 // | teams | taskloop simd | + | 2086 // +------------------+-----------------+------------------------------------+ 2087 // | taskloop | parallel | * | 2088 // | taskloop | for | + | 2089 // | taskloop | for simd | + | 2090 // | taskloop | master | + | 2091 // | taskloop | critical | * | 2092 // | taskloop | simd | * | 2093 // | taskloop | sections | + | 2094 // | taskloop | section | + | 2095 // | taskloop | single | + | 2096 // | taskloop | parallel for | * | 2097 // | taskloop |parallel for simd| * | 2098 // | taskloop |parallel sections| * | 2099 // | taskloop | task | * | 2100 // | taskloop | taskyield | * | 2101 // | taskloop | barrier | + | 2102 // | taskloop | taskwait | * | 2103 // | taskloop | taskgroup | * | 2104 // | taskloop | flush | * | 2105 // | taskloop | ordered | + | 2106 // | taskloop | atomic | * | 2107 // | taskloop | target | * | 2108 // | taskloop | teams | + | 2109 // | taskloop | cancellation | | 2110 // | | point | | 2111 // | taskloop | cancel | | 2112 // | taskloop | taskloop | * | 2113 // +------------------+-----------------+------------------------------------+ 2114 // | taskloop simd | parallel | | 2115 // | taskloop simd | for | | 2116 // | taskloop simd | for simd | | 2117 // | taskloop simd | master | | 2118 // | taskloop simd | critical | | 2119 // | taskloop simd | simd | | 2120 // | taskloop simd | sections | | 2121 // | taskloop simd | section | | 2122 // | taskloop simd | single | | 2123 // | taskloop simd | parallel for | | 2124 // | taskloop simd |parallel for simd| | 2125 // | taskloop simd |parallel sections| | 2126 // | taskloop simd | task | | 2127 // | taskloop simd | taskyield | | 2128 // | taskloop simd | barrier | | 2129 // | taskloop simd | taskwait | | 2130 // | taskloop simd | taskgroup | | 2131 // | taskloop simd | flush | | 2132 // | taskloop simd | ordered | + (with simd clause) | 2133 // | taskloop simd | atomic | | 2134 // | taskloop simd | target | | 2135 // | taskloop simd | teams | | 2136 // | taskloop simd | cancellation | | 2137 // | | point | | 2138 // | taskloop simd | cancel | | 2139 // | taskloop simd | taskloop | | 2140 // | taskloop simd | taskloop simd | | 2141 // +------------------+-----------------+------------------------------------+ 2142 if (Stack->getCurScope()) { 2143 auto ParentRegion = Stack->getParentDirective(); 2144 bool NestingProhibited = false; 2145 bool CloseNesting = true; 2146 enum { 2147 NoRecommend, 2148 ShouldBeInParallelRegion, 2149 ShouldBeInOrderedRegion, 2150 ShouldBeInTargetRegion 2151 } Recommend = NoRecommend; 2152 if (isOpenMPSimdDirective(ParentRegion) && CurrentRegion != OMPD_ordered) { 2153 // OpenMP [2.16, Nesting of Regions] 2154 // OpenMP constructs may not be nested inside a simd region. 2155 // OpenMP [2.8.1,simd Construct, Restrictions] 2156 // An ordered construct with the simd clause is the only OpenMP construct 2157 // that can appear in the simd region. 2158 SemaRef.Diag(StartLoc, diag::err_omp_prohibited_region_simd); 2159 return true; 2160 } 2161 if (ParentRegion == OMPD_atomic) { 2162 // OpenMP [2.16, Nesting of Regions] 2163 // OpenMP constructs may not be nested inside an atomic region. 2164 SemaRef.Diag(StartLoc, diag::err_omp_prohibited_region_atomic); 2165 return true; 2166 } 2167 if (CurrentRegion == OMPD_section) { 2168 // OpenMP [2.7.2, sections Construct, Restrictions] 2169 // Orphaned section directives are prohibited. That is, the section 2170 // directives must appear within the sections construct and must not be 2171 // encountered elsewhere in the sections region. 2172 if (ParentRegion != OMPD_sections && 2173 ParentRegion != OMPD_parallel_sections) { 2174 SemaRef.Diag(StartLoc, diag::err_omp_orphaned_section_directive) 2175 << (ParentRegion != OMPD_unknown) 2176 << getOpenMPDirectiveName(ParentRegion); 2177 return true; 2178 } 2179 return false; 2180 } 2181 // Allow some constructs to be orphaned (they could be used in functions, 2182 // called from OpenMP regions with the required preconditions). 2183 if (ParentRegion == OMPD_unknown) 2184 return false; 2185 if (CurrentRegion == OMPD_cancellation_point || 2186 CurrentRegion == OMPD_cancel) { 2187 // OpenMP [2.16, Nesting of Regions] 2188 // A cancellation point construct for which construct-type-clause is 2189 // taskgroup must be nested inside a task construct. A cancellation 2190 // point construct for which construct-type-clause is not taskgroup must 2191 // be closely nested inside an OpenMP construct that matches the type 2192 // specified in construct-type-clause. 2193 // A cancel construct for which construct-type-clause is taskgroup must be 2194 // nested inside a task construct. A cancel construct for which 2195 // construct-type-clause is not taskgroup must be closely nested inside an 2196 // OpenMP construct that matches the type specified in 2197 // construct-type-clause. 2198 NestingProhibited = 2199 !((CancelRegion == OMPD_parallel && ParentRegion == OMPD_parallel) || 2200 (CancelRegion == OMPD_for && 2201 (ParentRegion == OMPD_for || ParentRegion == OMPD_parallel_for)) || 2202 (CancelRegion == OMPD_taskgroup && ParentRegion == OMPD_task) || 2203 (CancelRegion == OMPD_sections && 2204 (ParentRegion == OMPD_section || ParentRegion == OMPD_sections || 2205 ParentRegion == OMPD_parallel_sections))); 2206 } else if (CurrentRegion == OMPD_master) { 2207 // OpenMP [2.16, Nesting of Regions] 2208 // A master region may not be closely nested inside a worksharing, 2209 // atomic, or explicit task region. 2210 NestingProhibited = isOpenMPWorksharingDirective(ParentRegion) || 2211 ParentRegion == OMPD_task || 2212 isOpenMPTaskLoopDirective(ParentRegion); 2213 } else if (CurrentRegion == OMPD_critical && CurrentName.getName()) { 2214 // OpenMP [2.16, Nesting of Regions] 2215 // A critical region may not be nested (closely or otherwise) inside a 2216 // critical region with the same name. Note that this restriction is not 2217 // sufficient to prevent deadlock. 2218 SourceLocation PreviousCriticalLoc; 2219 bool DeadLock = 2220 Stack->hasDirective([CurrentName, &PreviousCriticalLoc]( 2221 OpenMPDirectiveKind K, 2222 const DeclarationNameInfo &DNI, 2223 SourceLocation Loc) 2224 ->bool { 2225 if (K == OMPD_critical && 2226 DNI.getName() == CurrentName.getName()) { 2227 PreviousCriticalLoc = Loc; 2228 return true; 2229 } else 2230 return false; 2231 }, 2232 false /* skip top directive */); 2233 if (DeadLock) { 2234 SemaRef.Diag(StartLoc, 2235 diag::err_omp_prohibited_region_critical_same_name) 2236 << CurrentName.getName(); 2237 if (PreviousCriticalLoc.isValid()) 2238 SemaRef.Diag(PreviousCriticalLoc, 2239 diag::note_omp_previous_critical_region); 2240 return true; 2241 } 2242 } else if (CurrentRegion == OMPD_barrier) { 2243 // OpenMP [2.16, Nesting of Regions] 2244 // A barrier region may not be closely nested inside a worksharing, 2245 // explicit task, critical, ordered, atomic, or master region. 2246 NestingProhibited = 2247 isOpenMPWorksharingDirective(ParentRegion) || 2248 ParentRegion == OMPD_task || ParentRegion == OMPD_master || 2249 ParentRegion == OMPD_critical || ParentRegion == OMPD_ordered || 2250 isOpenMPTaskLoopDirective(ParentRegion); 2251 } else if (isOpenMPWorksharingDirective(CurrentRegion) && 2252 !isOpenMPParallelDirective(CurrentRegion)) { 2253 // OpenMP [2.16, Nesting of Regions] 2254 // A worksharing region may not be closely nested inside a worksharing, 2255 // explicit task, critical, ordered, atomic, or master region. 2256 NestingProhibited = 2257 isOpenMPWorksharingDirective(ParentRegion) || 2258 ParentRegion == OMPD_task || ParentRegion == OMPD_master || 2259 ParentRegion == OMPD_critical || ParentRegion == OMPD_ordered || 2260 isOpenMPTaskLoopDirective(ParentRegion); 2261 Recommend = ShouldBeInParallelRegion; 2262 } else if (CurrentRegion == OMPD_ordered) { 2263 // OpenMP [2.16, Nesting of Regions] 2264 // An ordered region may not be closely nested inside a critical, 2265 // atomic, or explicit task region. 2266 // An ordered region must be closely nested inside a loop region (or 2267 // parallel loop region) with an ordered clause. 2268 // OpenMP [2.8.1,simd Construct, Restrictions] 2269 // An ordered construct with the simd clause is the only OpenMP construct 2270 // that can appear in the simd region. 2271 NestingProhibited = ParentRegion == OMPD_critical || 2272 ParentRegion == OMPD_task || 2273 isOpenMPTaskLoopDirective(ParentRegion) || 2274 !(isOpenMPSimdDirective(ParentRegion) || 2275 Stack->isParentOrderedRegion()); 2276 Recommend = ShouldBeInOrderedRegion; 2277 } else if (isOpenMPTeamsDirective(CurrentRegion)) { 2278 // OpenMP [2.16, Nesting of Regions] 2279 // If specified, a teams construct must be contained within a target 2280 // construct. 2281 NestingProhibited = ParentRegion != OMPD_target; 2282 Recommend = ShouldBeInTargetRegion; 2283 Stack->setParentTeamsRegionLoc(Stack->getConstructLoc()); 2284 } 2285 if (!NestingProhibited && isOpenMPTeamsDirective(ParentRegion)) { 2286 // OpenMP [2.16, Nesting of Regions] 2287 // distribute, parallel, parallel sections, parallel workshare, and the 2288 // parallel loop and parallel loop SIMD constructs are the only OpenMP 2289 // constructs that can be closely nested in the teams region. 2290 // TODO: add distribute directive. 2291 NestingProhibited = !isOpenMPParallelDirective(CurrentRegion); 2292 Recommend = ShouldBeInParallelRegion; 2293 } 2294 if (NestingProhibited) { 2295 SemaRef.Diag(StartLoc, diag::err_omp_prohibited_region) 2296 << CloseNesting << getOpenMPDirectiveName(ParentRegion) << Recommend 2297 << getOpenMPDirectiveName(CurrentRegion); 2298 return true; 2299 } 2300 } 2301 return false; 2302 } 2303 2304 static bool checkIfClauses(Sema &S, OpenMPDirectiveKind Kind, 2305 ArrayRef<OMPClause *> Clauses, 2306 ArrayRef<OpenMPDirectiveKind> AllowedNameModifiers) { 2307 bool ErrorFound = false; 2308 unsigned NamedModifiersNumber = 0; 2309 SmallVector<const OMPIfClause *, OMPC_unknown + 1> FoundNameModifiers( 2310 OMPD_unknown + 1); 2311 SmallVector<SourceLocation, 4> NameModifierLoc; 2312 for (const auto *C : Clauses) { 2313 if (const auto *IC = dyn_cast_or_null<OMPIfClause>(C)) { 2314 // At most one if clause without a directive-name-modifier can appear on 2315 // the directive. 2316 OpenMPDirectiveKind CurNM = IC->getNameModifier(); 2317 if (FoundNameModifiers[CurNM]) { 2318 S.Diag(C->getLocStart(), diag::err_omp_more_one_clause) 2319 << getOpenMPDirectiveName(Kind) << getOpenMPClauseName(OMPC_if) 2320 << (CurNM != OMPD_unknown) << getOpenMPDirectiveName(CurNM); 2321 ErrorFound = true; 2322 } else if (CurNM != OMPD_unknown) { 2323 NameModifierLoc.push_back(IC->getNameModifierLoc()); 2324 ++NamedModifiersNumber; 2325 } 2326 FoundNameModifiers[CurNM] = IC; 2327 if (CurNM == OMPD_unknown) 2328 continue; 2329 // Check if the specified name modifier is allowed for the current 2330 // directive. 2331 // At most one if clause with the particular directive-name-modifier can 2332 // appear on the directive. 2333 bool MatchFound = false; 2334 for (auto NM : AllowedNameModifiers) { 2335 if (CurNM == NM) { 2336 MatchFound = true; 2337 break; 2338 } 2339 } 2340 if (!MatchFound) { 2341 S.Diag(IC->getNameModifierLoc(), 2342 diag::err_omp_wrong_if_directive_name_modifier) 2343 << getOpenMPDirectiveName(CurNM) << getOpenMPDirectiveName(Kind); 2344 ErrorFound = true; 2345 } 2346 } 2347 } 2348 // If any if clause on the directive includes a directive-name-modifier then 2349 // all if clauses on the directive must include a directive-name-modifier. 2350 if (FoundNameModifiers[OMPD_unknown] && NamedModifiersNumber > 0) { 2351 if (NamedModifiersNumber == AllowedNameModifiers.size()) { 2352 S.Diag(FoundNameModifiers[OMPD_unknown]->getLocStart(), 2353 diag::err_omp_no_more_if_clause); 2354 } else { 2355 std::string Values; 2356 std::string Sep(", "); 2357 unsigned AllowedCnt = 0; 2358 unsigned TotalAllowedNum = 2359 AllowedNameModifiers.size() - NamedModifiersNumber; 2360 for (unsigned Cnt = 0, End = AllowedNameModifiers.size(); Cnt < End; 2361 ++Cnt) { 2362 OpenMPDirectiveKind NM = AllowedNameModifiers[Cnt]; 2363 if (!FoundNameModifiers[NM]) { 2364 Values += "'"; 2365 Values += getOpenMPDirectiveName(NM); 2366 Values += "'"; 2367 if (AllowedCnt + 2 == TotalAllowedNum) 2368 Values += " or "; 2369 else if (AllowedCnt + 1 != TotalAllowedNum) 2370 Values += Sep; 2371 ++AllowedCnt; 2372 } 2373 } 2374 S.Diag(FoundNameModifiers[OMPD_unknown]->getCondition()->getLocStart(), 2375 diag::err_omp_unnamed_if_clause) 2376 << (TotalAllowedNum > 1) << Values; 2377 } 2378 for (auto Loc : NameModifierLoc) { 2379 S.Diag(Loc, diag::note_omp_previous_named_if_clause); 2380 } 2381 ErrorFound = true; 2382 } 2383 return ErrorFound; 2384 } 2385 2386 StmtResult Sema::ActOnOpenMPExecutableDirective( 2387 OpenMPDirectiveKind Kind, const DeclarationNameInfo &DirName, 2388 OpenMPDirectiveKind CancelRegion, ArrayRef<OMPClause *> Clauses, 2389 Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc) { 2390 StmtResult Res = StmtError(); 2391 if (CheckNestingOfRegions(*this, DSAStack, Kind, DirName, CancelRegion, 2392 StartLoc)) 2393 return StmtError(); 2394 2395 llvm::SmallVector<OMPClause *, 8> ClausesWithImplicit; 2396 llvm::DenseMap<VarDecl *, Expr *> VarsWithInheritedDSA; 2397 bool ErrorFound = false; 2398 ClausesWithImplicit.append(Clauses.begin(), Clauses.end()); 2399 if (AStmt) { 2400 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected"); 2401 2402 // Check default data sharing attributes for referenced variables. 2403 DSAAttrChecker DSAChecker(DSAStack, *this, cast<CapturedStmt>(AStmt)); 2404 DSAChecker.Visit(cast<CapturedStmt>(AStmt)->getCapturedStmt()); 2405 if (DSAChecker.isErrorFound()) 2406 return StmtError(); 2407 // Generate list of implicitly defined firstprivate variables. 2408 VarsWithInheritedDSA = DSAChecker.getVarsWithInheritedDSA(); 2409 2410 if (!DSAChecker.getImplicitFirstprivate().empty()) { 2411 if (OMPClause *Implicit = ActOnOpenMPFirstprivateClause( 2412 DSAChecker.getImplicitFirstprivate(), SourceLocation(), 2413 SourceLocation(), SourceLocation())) { 2414 ClausesWithImplicit.push_back(Implicit); 2415 ErrorFound = cast<OMPFirstprivateClause>(Implicit)->varlist_size() != 2416 DSAChecker.getImplicitFirstprivate().size(); 2417 } else 2418 ErrorFound = true; 2419 } 2420 } 2421 2422 llvm::SmallVector<OpenMPDirectiveKind, 4> AllowedNameModifiers; 2423 switch (Kind) { 2424 case OMPD_parallel: 2425 Res = ActOnOpenMPParallelDirective(ClausesWithImplicit, AStmt, StartLoc, 2426 EndLoc); 2427 AllowedNameModifiers.push_back(OMPD_parallel); 2428 break; 2429 case OMPD_simd: 2430 Res = ActOnOpenMPSimdDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc, 2431 VarsWithInheritedDSA); 2432 break; 2433 case OMPD_for: 2434 Res = ActOnOpenMPForDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc, 2435 VarsWithInheritedDSA); 2436 break; 2437 case OMPD_for_simd: 2438 Res = ActOnOpenMPForSimdDirective(ClausesWithImplicit, AStmt, StartLoc, 2439 EndLoc, VarsWithInheritedDSA); 2440 break; 2441 case OMPD_sections: 2442 Res = ActOnOpenMPSectionsDirective(ClausesWithImplicit, AStmt, StartLoc, 2443 EndLoc); 2444 break; 2445 case OMPD_section: 2446 assert(ClausesWithImplicit.empty() && 2447 "No clauses are allowed for 'omp section' directive"); 2448 Res = ActOnOpenMPSectionDirective(AStmt, StartLoc, EndLoc); 2449 break; 2450 case OMPD_single: 2451 Res = ActOnOpenMPSingleDirective(ClausesWithImplicit, AStmt, StartLoc, 2452 EndLoc); 2453 break; 2454 case OMPD_master: 2455 assert(ClausesWithImplicit.empty() && 2456 "No clauses are allowed for 'omp master' directive"); 2457 Res = ActOnOpenMPMasterDirective(AStmt, StartLoc, EndLoc); 2458 break; 2459 case OMPD_critical: 2460 assert(ClausesWithImplicit.empty() && 2461 "No clauses are allowed for 'omp critical' directive"); 2462 Res = ActOnOpenMPCriticalDirective(DirName, AStmt, StartLoc, EndLoc); 2463 break; 2464 case OMPD_parallel_for: 2465 Res = ActOnOpenMPParallelForDirective(ClausesWithImplicit, AStmt, StartLoc, 2466 EndLoc, VarsWithInheritedDSA); 2467 AllowedNameModifiers.push_back(OMPD_parallel); 2468 break; 2469 case OMPD_parallel_for_simd: 2470 Res = ActOnOpenMPParallelForSimdDirective( 2471 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA); 2472 AllowedNameModifiers.push_back(OMPD_parallel); 2473 break; 2474 case OMPD_parallel_sections: 2475 Res = ActOnOpenMPParallelSectionsDirective(ClausesWithImplicit, AStmt, 2476 StartLoc, EndLoc); 2477 AllowedNameModifiers.push_back(OMPD_parallel); 2478 break; 2479 case OMPD_task: 2480 Res = 2481 ActOnOpenMPTaskDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc); 2482 AllowedNameModifiers.push_back(OMPD_task); 2483 break; 2484 case OMPD_taskyield: 2485 assert(ClausesWithImplicit.empty() && 2486 "No clauses are allowed for 'omp taskyield' directive"); 2487 assert(AStmt == nullptr && 2488 "No associated statement allowed for 'omp taskyield' directive"); 2489 Res = ActOnOpenMPTaskyieldDirective(StartLoc, EndLoc); 2490 break; 2491 case OMPD_barrier: 2492 assert(ClausesWithImplicit.empty() && 2493 "No clauses are allowed for 'omp barrier' directive"); 2494 assert(AStmt == nullptr && 2495 "No associated statement allowed for 'omp barrier' directive"); 2496 Res = ActOnOpenMPBarrierDirective(StartLoc, EndLoc); 2497 break; 2498 case OMPD_taskwait: 2499 assert(ClausesWithImplicit.empty() && 2500 "No clauses are allowed for 'omp taskwait' directive"); 2501 assert(AStmt == nullptr && 2502 "No associated statement allowed for 'omp taskwait' directive"); 2503 Res = ActOnOpenMPTaskwaitDirective(StartLoc, EndLoc); 2504 break; 2505 case OMPD_taskgroup: 2506 assert(ClausesWithImplicit.empty() && 2507 "No clauses are allowed for 'omp taskgroup' directive"); 2508 Res = ActOnOpenMPTaskgroupDirective(AStmt, StartLoc, EndLoc); 2509 break; 2510 case OMPD_flush: 2511 assert(AStmt == nullptr && 2512 "No associated statement allowed for 'omp flush' directive"); 2513 Res = ActOnOpenMPFlushDirective(ClausesWithImplicit, StartLoc, EndLoc); 2514 break; 2515 case OMPD_ordered: 2516 Res = ActOnOpenMPOrderedDirective(ClausesWithImplicit, AStmt, StartLoc, 2517 EndLoc); 2518 break; 2519 case OMPD_atomic: 2520 Res = ActOnOpenMPAtomicDirective(ClausesWithImplicit, AStmt, StartLoc, 2521 EndLoc); 2522 break; 2523 case OMPD_teams: 2524 Res = 2525 ActOnOpenMPTeamsDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc); 2526 break; 2527 case OMPD_target: 2528 Res = ActOnOpenMPTargetDirective(ClausesWithImplicit, AStmt, StartLoc, 2529 EndLoc); 2530 AllowedNameModifiers.push_back(OMPD_target); 2531 break; 2532 case OMPD_cancellation_point: 2533 assert(ClausesWithImplicit.empty() && 2534 "No clauses are allowed for 'omp cancellation point' directive"); 2535 assert(AStmt == nullptr && "No associated statement allowed for 'omp " 2536 "cancellation point' directive"); 2537 Res = ActOnOpenMPCancellationPointDirective(StartLoc, EndLoc, CancelRegion); 2538 break; 2539 case OMPD_cancel: 2540 assert(AStmt == nullptr && 2541 "No associated statement allowed for 'omp cancel' directive"); 2542 Res = ActOnOpenMPCancelDirective(ClausesWithImplicit, StartLoc, EndLoc, 2543 CancelRegion); 2544 AllowedNameModifiers.push_back(OMPD_cancel); 2545 break; 2546 case OMPD_target_data: 2547 Res = ActOnOpenMPTargetDataDirective(ClausesWithImplicit, AStmt, StartLoc, 2548 EndLoc); 2549 AllowedNameModifiers.push_back(OMPD_target_data); 2550 break; 2551 case OMPD_taskloop: 2552 Res = ActOnOpenMPTaskLoopDirective(ClausesWithImplicit, AStmt, StartLoc, 2553 EndLoc, VarsWithInheritedDSA); 2554 AllowedNameModifiers.push_back(OMPD_taskloop); 2555 break; 2556 case OMPD_taskloop_simd: 2557 Res = ActOnOpenMPTaskLoopSimdDirective(ClausesWithImplicit, AStmt, StartLoc, 2558 EndLoc, VarsWithInheritedDSA); 2559 AllowedNameModifiers.push_back(OMPD_taskloop); 2560 break; 2561 case OMPD_threadprivate: 2562 llvm_unreachable("OpenMP Directive is not allowed"); 2563 case OMPD_unknown: 2564 llvm_unreachable("Unknown OpenMP directive"); 2565 } 2566 2567 for (auto P : VarsWithInheritedDSA) { 2568 Diag(P.second->getExprLoc(), diag::err_omp_no_dsa_for_variable) 2569 << P.first << P.second->getSourceRange(); 2570 } 2571 ErrorFound = !VarsWithInheritedDSA.empty() || ErrorFound; 2572 2573 if (!AllowedNameModifiers.empty()) 2574 ErrorFound = checkIfClauses(*this, Kind, Clauses, AllowedNameModifiers) || 2575 ErrorFound; 2576 2577 if (ErrorFound) 2578 return StmtError(); 2579 return Res; 2580 } 2581 2582 StmtResult Sema::ActOnOpenMPParallelDirective(ArrayRef<OMPClause *> Clauses, 2583 Stmt *AStmt, 2584 SourceLocation StartLoc, 2585 SourceLocation EndLoc) { 2586 if (!AStmt) 2587 return StmtError(); 2588 2589 CapturedStmt *CS = cast<CapturedStmt>(AStmt); 2590 // 1.2.2 OpenMP Language Terminology 2591 // Structured block - An executable statement with a single entry at the 2592 // top and a single exit at the bottom. 2593 // The point of exit cannot be a branch out of the structured block. 2594 // longjmp() and throw() must not violate the entry/exit criteria. 2595 CS->getCapturedDecl()->setNothrow(); 2596 2597 getCurFunction()->setHasBranchProtectedScope(); 2598 2599 return OMPParallelDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt, 2600 DSAStack->isCancelRegion()); 2601 } 2602 2603 namespace { 2604 /// \brief Helper class for checking canonical form of the OpenMP loops and 2605 /// extracting iteration space of each loop in the loop nest, that will be used 2606 /// for IR generation. 2607 class OpenMPIterationSpaceChecker { 2608 /// \brief Reference to Sema. 2609 Sema &SemaRef; 2610 /// \brief A location for diagnostics (when there is no some better location). 2611 SourceLocation DefaultLoc; 2612 /// \brief A location for diagnostics (when increment is not compatible). 2613 SourceLocation ConditionLoc; 2614 /// \brief A source location for referring to loop init later. 2615 SourceRange InitSrcRange; 2616 /// \brief A source location for referring to condition later. 2617 SourceRange ConditionSrcRange; 2618 /// \brief A source location for referring to increment later. 2619 SourceRange IncrementSrcRange; 2620 /// \brief Loop variable. 2621 VarDecl *Var; 2622 /// \brief Reference to loop variable. 2623 DeclRefExpr *VarRef; 2624 /// \brief Lower bound (initializer for the var). 2625 Expr *LB; 2626 /// \brief Upper bound. 2627 Expr *UB; 2628 /// \brief Loop step (increment). 2629 Expr *Step; 2630 /// \brief This flag is true when condition is one of: 2631 /// Var < UB 2632 /// Var <= UB 2633 /// UB > Var 2634 /// UB >= Var 2635 bool TestIsLessOp; 2636 /// \brief This flag is true when condition is strict ( < or > ). 2637 bool TestIsStrictOp; 2638 /// \brief This flag is true when step is subtracted on each iteration. 2639 bool SubtractStep; 2640 2641 public: 2642 OpenMPIterationSpaceChecker(Sema &SemaRef, SourceLocation DefaultLoc) 2643 : SemaRef(SemaRef), DefaultLoc(DefaultLoc), ConditionLoc(DefaultLoc), 2644 InitSrcRange(SourceRange()), ConditionSrcRange(SourceRange()), 2645 IncrementSrcRange(SourceRange()), Var(nullptr), VarRef(nullptr), 2646 LB(nullptr), UB(nullptr), Step(nullptr), TestIsLessOp(false), 2647 TestIsStrictOp(false), SubtractStep(false) {} 2648 /// \brief Check init-expr for canonical loop form and save loop counter 2649 /// variable - #Var and its initialization value - #LB. 2650 bool CheckInit(Stmt *S, bool EmitDiags = true); 2651 /// \brief Check test-expr for canonical form, save upper-bound (#UB), flags 2652 /// for less/greater and for strict/non-strict comparison. 2653 bool CheckCond(Expr *S); 2654 /// \brief Check incr-expr for canonical loop form and return true if it 2655 /// does not conform, otherwise save loop step (#Step). 2656 bool CheckInc(Expr *S); 2657 /// \brief Return the loop counter variable. 2658 VarDecl *GetLoopVar() const { return Var; } 2659 /// \brief Return the reference expression to loop counter variable. 2660 DeclRefExpr *GetLoopVarRefExpr() const { return VarRef; } 2661 /// \brief Source range of the loop init. 2662 SourceRange GetInitSrcRange() const { return InitSrcRange; } 2663 /// \brief Source range of the loop condition. 2664 SourceRange GetConditionSrcRange() const { return ConditionSrcRange; } 2665 /// \brief Source range of the loop increment. 2666 SourceRange GetIncrementSrcRange() const { return IncrementSrcRange; } 2667 /// \brief True if the step should be subtracted. 2668 bool ShouldSubtractStep() const { return SubtractStep; } 2669 /// \brief Build the expression to calculate the number of iterations. 2670 Expr *BuildNumIterations(Scope *S, const bool LimitedType) const; 2671 /// \brief Build the precondition expression for the loops. 2672 Expr *BuildPreCond(Scope *S, Expr *Cond) const; 2673 /// \brief Build reference expression to the counter be used for codegen. 2674 Expr *BuildCounterVar() const; 2675 /// \brief Build reference expression to the private counter be used for 2676 /// codegen. 2677 Expr *BuildPrivateCounterVar() const; 2678 /// \brief Build initization of the counter be used for codegen. 2679 Expr *BuildCounterInit() const; 2680 /// \brief Build step of the counter be used for codegen. 2681 Expr *BuildCounterStep() const; 2682 /// \brief Return true if any expression is dependent. 2683 bool Dependent() const; 2684 2685 private: 2686 /// \brief Check the right-hand side of an assignment in the increment 2687 /// expression. 2688 bool CheckIncRHS(Expr *RHS); 2689 /// \brief Helper to set loop counter variable and its initializer. 2690 bool SetVarAndLB(VarDecl *NewVar, DeclRefExpr *NewVarRefExpr, Expr *NewLB); 2691 /// \brief Helper to set upper bound. 2692 bool SetUB(Expr *NewUB, bool LessOp, bool StrictOp, SourceRange SR, 2693 SourceLocation SL); 2694 /// \brief Helper to set loop increment. 2695 bool SetStep(Expr *NewStep, bool Subtract); 2696 }; 2697 2698 bool OpenMPIterationSpaceChecker::Dependent() const { 2699 if (!Var) { 2700 assert(!LB && !UB && !Step); 2701 return false; 2702 } 2703 return Var->getType()->isDependentType() || (LB && LB->isValueDependent()) || 2704 (UB && UB->isValueDependent()) || (Step && Step->isValueDependent()); 2705 } 2706 2707 template <typename T> 2708 static T *getExprAsWritten(T *E) { 2709 if (auto *ExprTemp = dyn_cast<ExprWithCleanups>(E)) 2710 E = ExprTemp->getSubExpr(); 2711 2712 if (auto *MTE = dyn_cast<MaterializeTemporaryExpr>(E)) 2713 E = MTE->GetTemporaryExpr(); 2714 2715 while (auto *Binder = dyn_cast<CXXBindTemporaryExpr>(E)) 2716 E = Binder->getSubExpr(); 2717 2718 if (auto *ICE = dyn_cast<ImplicitCastExpr>(E)) 2719 E = ICE->getSubExprAsWritten(); 2720 return E->IgnoreParens(); 2721 } 2722 2723 bool OpenMPIterationSpaceChecker::SetVarAndLB(VarDecl *NewVar, 2724 DeclRefExpr *NewVarRefExpr, 2725 Expr *NewLB) { 2726 // State consistency checking to ensure correct usage. 2727 assert(Var == nullptr && LB == nullptr && VarRef == nullptr && 2728 UB == nullptr && Step == nullptr && !TestIsLessOp && !TestIsStrictOp); 2729 if (!NewVar || !NewLB) 2730 return true; 2731 Var = NewVar; 2732 VarRef = NewVarRefExpr; 2733 if (auto *CE = dyn_cast_or_null<CXXConstructExpr>(NewLB)) 2734 if (const CXXConstructorDecl *Ctor = CE->getConstructor()) 2735 if ((Ctor->isCopyOrMoveConstructor() || 2736 Ctor->isConvertingConstructor(/*AllowExplicit=*/false)) && 2737 CE->getNumArgs() > 0 && CE->getArg(0) != nullptr) 2738 NewLB = CE->getArg(0)->IgnoreParenImpCasts(); 2739 LB = NewLB; 2740 return false; 2741 } 2742 2743 bool OpenMPIterationSpaceChecker::SetUB(Expr *NewUB, bool LessOp, bool StrictOp, 2744 SourceRange SR, SourceLocation SL) { 2745 // State consistency checking to ensure correct usage. 2746 assert(Var != nullptr && LB != nullptr && UB == nullptr && Step == nullptr && 2747 !TestIsLessOp && !TestIsStrictOp); 2748 if (!NewUB) 2749 return true; 2750 UB = NewUB; 2751 TestIsLessOp = LessOp; 2752 TestIsStrictOp = StrictOp; 2753 ConditionSrcRange = SR; 2754 ConditionLoc = SL; 2755 return false; 2756 } 2757 2758 bool OpenMPIterationSpaceChecker::SetStep(Expr *NewStep, bool Subtract) { 2759 // State consistency checking to ensure correct usage. 2760 assert(Var != nullptr && LB != nullptr && Step == nullptr); 2761 if (!NewStep) 2762 return true; 2763 if (!NewStep->isValueDependent()) { 2764 // Check that the step is integer expression. 2765 SourceLocation StepLoc = NewStep->getLocStart(); 2766 ExprResult Val = 2767 SemaRef.PerformOpenMPImplicitIntegerConversion(StepLoc, NewStep); 2768 if (Val.isInvalid()) 2769 return true; 2770 NewStep = Val.get(); 2771 2772 // OpenMP [2.6, Canonical Loop Form, Restrictions] 2773 // If test-expr is of form var relational-op b and relational-op is < or 2774 // <= then incr-expr must cause var to increase on each iteration of the 2775 // loop. If test-expr is of form var relational-op b and relational-op is 2776 // > or >= then incr-expr must cause var to decrease on each iteration of 2777 // the loop. 2778 // If test-expr is of form b relational-op var and relational-op is < or 2779 // <= then incr-expr must cause var to decrease on each iteration of the 2780 // loop. If test-expr is of form b relational-op var and relational-op is 2781 // > or >= then incr-expr must cause var to increase on each iteration of 2782 // the loop. 2783 llvm::APSInt Result; 2784 bool IsConstant = NewStep->isIntegerConstantExpr(Result, SemaRef.Context); 2785 bool IsUnsigned = !NewStep->getType()->hasSignedIntegerRepresentation(); 2786 bool IsConstNeg = 2787 IsConstant && Result.isSigned() && (Subtract != Result.isNegative()); 2788 bool IsConstPos = 2789 IsConstant && Result.isSigned() && (Subtract == Result.isNegative()); 2790 bool IsConstZero = IsConstant && !Result.getBoolValue(); 2791 if (UB && (IsConstZero || 2792 (TestIsLessOp ? (IsConstNeg || (IsUnsigned && Subtract)) 2793 : (IsConstPos || (IsUnsigned && !Subtract))))) { 2794 SemaRef.Diag(NewStep->getExprLoc(), 2795 diag::err_omp_loop_incr_not_compatible) 2796 << Var << TestIsLessOp << NewStep->getSourceRange(); 2797 SemaRef.Diag(ConditionLoc, 2798 diag::note_omp_loop_cond_requres_compatible_incr) 2799 << TestIsLessOp << ConditionSrcRange; 2800 return true; 2801 } 2802 if (TestIsLessOp == Subtract) { 2803 NewStep = SemaRef.CreateBuiltinUnaryOp(NewStep->getExprLoc(), UO_Minus, 2804 NewStep).get(); 2805 Subtract = !Subtract; 2806 } 2807 } 2808 2809 Step = NewStep; 2810 SubtractStep = Subtract; 2811 return false; 2812 } 2813 2814 bool OpenMPIterationSpaceChecker::CheckInit(Stmt *S, bool EmitDiags) { 2815 // Check init-expr for canonical loop form and save loop counter 2816 // variable - #Var and its initialization value - #LB. 2817 // OpenMP [2.6] Canonical loop form. init-expr may be one of the following: 2818 // var = lb 2819 // integer-type var = lb 2820 // random-access-iterator-type var = lb 2821 // pointer-type var = lb 2822 // 2823 if (!S) { 2824 if (EmitDiags) { 2825 SemaRef.Diag(DefaultLoc, diag::err_omp_loop_not_canonical_init); 2826 } 2827 return true; 2828 } 2829 InitSrcRange = S->getSourceRange(); 2830 if (Expr *E = dyn_cast<Expr>(S)) 2831 S = E->IgnoreParens(); 2832 if (auto BO = dyn_cast<BinaryOperator>(S)) { 2833 if (BO->getOpcode() == BO_Assign) 2834 if (auto DRE = dyn_cast<DeclRefExpr>(BO->getLHS()->IgnoreParens())) 2835 return SetVarAndLB(dyn_cast<VarDecl>(DRE->getDecl()), DRE, 2836 BO->getRHS()); 2837 } else if (auto DS = dyn_cast<DeclStmt>(S)) { 2838 if (DS->isSingleDecl()) { 2839 if (auto Var = dyn_cast_or_null<VarDecl>(DS->getSingleDecl())) { 2840 if (Var->hasInit() && !Var->getType()->isReferenceType()) { 2841 // Accept non-canonical init form here but emit ext. warning. 2842 if (Var->getInitStyle() != VarDecl::CInit && EmitDiags) 2843 SemaRef.Diag(S->getLocStart(), 2844 diag::ext_omp_loop_not_canonical_init) 2845 << S->getSourceRange(); 2846 return SetVarAndLB(Var, nullptr, Var->getInit()); 2847 } 2848 } 2849 } 2850 } else if (auto CE = dyn_cast<CXXOperatorCallExpr>(S)) 2851 if (CE->getOperator() == OO_Equal) 2852 if (auto DRE = dyn_cast<DeclRefExpr>(CE->getArg(0))) 2853 return SetVarAndLB(dyn_cast<VarDecl>(DRE->getDecl()), DRE, 2854 CE->getArg(1)); 2855 2856 if (EmitDiags) { 2857 SemaRef.Diag(S->getLocStart(), diag::err_omp_loop_not_canonical_init) 2858 << S->getSourceRange(); 2859 } 2860 return true; 2861 } 2862 2863 /// \brief Ignore parenthesizes, implicit casts, copy constructor and return the 2864 /// variable (which may be the loop variable) if possible. 2865 static const VarDecl *GetInitVarDecl(const Expr *E) { 2866 if (!E) 2867 return nullptr; 2868 E = getExprAsWritten(E); 2869 if (auto *CE = dyn_cast_or_null<CXXConstructExpr>(E)) 2870 if (const CXXConstructorDecl *Ctor = CE->getConstructor()) 2871 if ((Ctor->isCopyOrMoveConstructor() || 2872 Ctor->isConvertingConstructor(/*AllowExplicit=*/false)) && 2873 CE->getNumArgs() > 0 && CE->getArg(0) != nullptr) 2874 E = CE->getArg(0)->IgnoreParenImpCasts(); 2875 auto DRE = dyn_cast_or_null<DeclRefExpr>(E); 2876 if (!DRE) 2877 return nullptr; 2878 return dyn_cast<VarDecl>(DRE->getDecl()); 2879 } 2880 2881 bool OpenMPIterationSpaceChecker::CheckCond(Expr *S) { 2882 // Check test-expr for canonical form, save upper-bound UB, flags for 2883 // less/greater and for strict/non-strict comparison. 2884 // OpenMP [2.6] Canonical loop form. Test-expr may be one of the following: 2885 // var relational-op b 2886 // b relational-op var 2887 // 2888 if (!S) { 2889 SemaRef.Diag(DefaultLoc, diag::err_omp_loop_not_canonical_cond) << Var; 2890 return true; 2891 } 2892 S = getExprAsWritten(S); 2893 SourceLocation CondLoc = S->getLocStart(); 2894 if (auto BO = dyn_cast<BinaryOperator>(S)) { 2895 if (BO->isRelationalOp()) { 2896 if (GetInitVarDecl(BO->getLHS()) == Var) 2897 return SetUB(BO->getRHS(), 2898 (BO->getOpcode() == BO_LT || BO->getOpcode() == BO_LE), 2899 (BO->getOpcode() == BO_LT || BO->getOpcode() == BO_GT), 2900 BO->getSourceRange(), BO->getOperatorLoc()); 2901 if (GetInitVarDecl(BO->getRHS()) == Var) 2902 return SetUB(BO->getLHS(), 2903 (BO->getOpcode() == BO_GT || BO->getOpcode() == BO_GE), 2904 (BO->getOpcode() == BO_LT || BO->getOpcode() == BO_GT), 2905 BO->getSourceRange(), BO->getOperatorLoc()); 2906 } 2907 } else if (auto CE = dyn_cast<CXXOperatorCallExpr>(S)) { 2908 if (CE->getNumArgs() == 2) { 2909 auto Op = CE->getOperator(); 2910 switch (Op) { 2911 case OO_Greater: 2912 case OO_GreaterEqual: 2913 case OO_Less: 2914 case OO_LessEqual: 2915 if (GetInitVarDecl(CE->getArg(0)) == Var) 2916 return SetUB(CE->getArg(1), Op == OO_Less || Op == OO_LessEqual, 2917 Op == OO_Less || Op == OO_Greater, CE->getSourceRange(), 2918 CE->getOperatorLoc()); 2919 if (GetInitVarDecl(CE->getArg(1)) == Var) 2920 return SetUB(CE->getArg(0), Op == OO_Greater || Op == OO_GreaterEqual, 2921 Op == OO_Less || Op == OO_Greater, CE->getSourceRange(), 2922 CE->getOperatorLoc()); 2923 break; 2924 default: 2925 break; 2926 } 2927 } 2928 } 2929 SemaRef.Diag(CondLoc, diag::err_omp_loop_not_canonical_cond) 2930 << S->getSourceRange() << Var; 2931 return true; 2932 } 2933 2934 bool OpenMPIterationSpaceChecker::CheckIncRHS(Expr *RHS) { 2935 // RHS of canonical loop form increment can be: 2936 // var + incr 2937 // incr + var 2938 // var - incr 2939 // 2940 RHS = RHS->IgnoreParenImpCasts(); 2941 if (auto BO = dyn_cast<BinaryOperator>(RHS)) { 2942 if (BO->isAdditiveOp()) { 2943 bool IsAdd = BO->getOpcode() == BO_Add; 2944 if (GetInitVarDecl(BO->getLHS()) == Var) 2945 return SetStep(BO->getRHS(), !IsAdd); 2946 if (IsAdd && GetInitVarDecl(BO->getRHS()) == Var) 2947 return SetStep(BO->getLHS(), false); 2948 } 2949 } else if (auto CE = dyn_cast<CXXOperatorCallExpr>(RHS)) { 2950 bool IsAdd = CE->getOperator() == OO_Plus; 2951 if ((IsAdd || CE->getOperator() == OO_Minus) && CE->getNumArgs() == 2) { 2952 if (GetInitVarDecl(CE->getArg(0)) == Var) 2953 return SetStep(CE->getArg(1), !IsAdd); 2954 if (IsAdd && GetInitVarDecl(CE->getArg(1)) == Var) 2955 return SetStep(CE->getArg(0), false); 2956 } 2957 } 2958 SemaRef.Diag(RHS->getLocStart(), diag::err_omp_loop_not_canonical_incr) 2959 << RHS->getSourceRange() << Var; 2960 return true; 2961 } 2962 2963 bool OpenMPIterationSpaceChecker::CheckInc(Expr *S) { 2964 // Check incr-expr for canonical loop form and return true if it 2965 // does not conform. 2966 // OpenMP [2.6] Canonical loop form. Test-expr may be one of the following: 2967 // ++var 2968 // var++ 2969 // --var 2970 // var-- 2971 // var += incr 2972 // var -= incr 2973 // var = var + incr 2974 // var = incr + var 2975 // var = var - incr 2976 // 2977 if (!S) { 2978 SemaRef.Diag(DefaultLoc, diag::err_omp_loop_not_canonical_incr) << Var; 2979 return true; 2980 } 2981 IncrementSrcRange = S->getSourceRange(); 2982 S = S->IgnoreParens(); 2983 if (auto UO = dyn_cast<UnaryOperator>(S)) { 2984 if (UO->isIncrementDecrementOp() && GetInitVarDecl(UO->getSubExpr()) == Var) 2985 return SetStep( 2986 SemaRef.ActOnIntegerConstant(UO->getLocStart(), 2987 (UO->isDecrementOp() ? -1 : 1)).get(), 2988 false); 2989 } else if (auto BO = dyn_cast<BinaryOperator>(S)) { 2990 switch (BO->getOpcode()) { 2991 case BO_AddAssign: 2992 case BO_SubAssign: 2993 if (GetInitVarDecl(BO->getLHS()) == Var) 2994 return SetStep(BO->getRHS(), BO->getOpcode() == BO_SubAssign); 2995 break; 2996 case BO_Assign: 2997 if (GetInitVarDecl(BO->getLHS()) == Var) 2998 return CheckIncRHS(BO->getRHS()); 2999 break; 3000 default: 3001 break; 3002 } 3003 } else if (auto CE = dyn_cast<CXXOperatorCallExpr>(S)) { 3004 switch (CE->getOperator()) { 3005 case OO_PlusPlus: 3006 case OO_MinusMinus: 3007 if (GetInitVarDecl(CE->getArg(0)) == Var) 3008 return SetStep( 3009 SemaRef.ActOnIntegerConstant( 3010 CE->getLocStart(), 3011 ((CE->getOperator() == OO_MinusMinus) ? -1 : 1)).get(), 3012 false); 3013 break; 3014 case OO_PlusEqual: 3015 case OO_MinusEqual: 3016 if (GetInitVarDecl(CE->getArg(0)) == Var) 3017 return SetStep(CE->getArg(1), CE->getOperator() == OO_MinusEqual); 3018 break; 3019 case OO_Equal: 3020 if (GetInitVarDecl(CE->getArg(0)) == Var) 3021 return CheckIncRHS(CE->getArg(1)); 3022 break; 3023 default: 3024 break; 3025 } 3026 } 3027 SemaRef.Diag(S->getLocStart(), diag::err_omp_loop_not_canonical_incr) 3028 << S->getSourceRange() << Var; 3029 return true; 3030 } 3031 3032 namespace { 3033 // Transform variables declared in GNU statement expressions to new ones to 3034 // avoid crash on codegen. 3035 class TransformToNewDefs : public TreeTransform<TransformToNewDefs> { 3036 typedef TreeTransform<TransformToNewDefs> BaseTransform; 3037 3038 public: 3039 TransformToNewDefs(Sema &SemaRef) : BaseTransform(SemaRef) {} 3040 3041 Decl *TransformDefinition(SourceLocation Loc, Decl *D) { 3042 if (auto *VD = cast<VarDecl>(D)) 3043 if (!isa<ParmVarDecl>(D) && !isa<VarTemplateSpecializationDecl>(D) && 3044 !isa<ImplicitParamDecl>(D)) { 3045 auto *NewVD = VarDecl::Create( 3046 SemaRef.Context, VD->getDeclContext(), VD->getLocStart(), 3047 VD->getLocation(), VD->getIdentifier(), VD->getType(), 3048 VD->getTypeSourceInfo(), VD->getStorageClass()); 3049 NewVD->setTSCSpec(VD->getTSCSpec()); 3050 NewVD->setInit(VD->getInit()); 3051 NewVD->setInitStyle(VD->getInitStyle()); 3052 NewVD->setExceptionVariable(VD->isExceptionVariable()); 3053 NewVD->setNRVOVariable(VD->isNRVOVariable()); 3054 NewVD->setCXXForRangeDecl(VD->isInExternCXXContext()); 3055 NewVD->setConstexpr(VD->isConstexpr()); 3056 NewVD->setInitCapture(VD->isInitCapture()); 3057 NewVD->setPreviousDeclInSameBlockScope( 3058 VD->isPreviousDeclInSameBlockScope()); 3059 VD->getDeclContext()->addHiddenDecl(NewVD); 3060 if (VD->hasAttrs()) 3061 NewVD->setAttrs(VD->getAttrs()); 3062 transformedLocalDecl(VD, NewVD); 3063 return NewVD; 3064 } 3065 return BaseTransform::TransformDefinition(Loc, D); 3066 } 3067 3068 ExprResult TransformDeclRefExpr(DeclRefExpr *E) { 3069 if (auto *NewD = TransformDecl(E->getExprLoc(), E->getDecl())) 3070 if (E->getDecl() != NewD) { 3071 NewD->setReferenced(); 3072 NewD->markUsed(SemaRef.Context); 3073 return DeclRefExpr::Create( 3074 SemaRef.Context, E->getQualifierLoc(), E->getTemplateKeywordLoc(), 3075 cast<ValueDecl>(NewD), E->refersToEnclosingVariableOrCapture(), 3076 E->getNameInfo(), E->getType(), E->getValueKind()); 3077 } 3078 return BaseTransform::TransformDeclRefExpr(E); 3079 } 3080 }; 3081 } 3082 3083 /// \brief Build the expression to calculate the number of iterations. 3084 Expr * 3085 OpenMPIterationSpaceChecker::BuildNumIterations(Scope *S, 3086 const bool LimitedType) const { 3087 TransformToNewDefs Transform(SemaRef); 3088 ExprResult Diff; 3089 auto VarType = Var->getType().getNonReferenceType(); 3090 if (VarType->isIntegerType() || VarType->isPointerType() || 3091 SemaRef.getLangOpts().CPlusPlus) { 3092 // Upper - Lower 3093 auto *UBExpr = TestIsLessOp ? UB : LB; 3094 auto *LBExpr = TestIsLessOp ? LB : UB; 3095 Expr *Upper = Transform.TransformExpr(UBExpr).get(); 3096 Expr *Lower = Transform.TransformExpr(LBExpr).get(); 3097 if (!Upper || !Lower) 3098 return nullptr; 3099 Upper = SemaRef.PerformImplicitConversion(Upper, UBExpr->getType(), 3100 Sema::AA_Converting, 3101 /*AllowExplicit=*/true) 3102 .get(); 3103 Lower = SemaRef.PerformImplicitConversion(Lower, LBExpr->getType(), 3104 Sema::AA_Converting, 3105 /*AllowExplicit=*/true) 3106 .get(); 3107 if (!Upper || !Lower) 3108 return nullptr; 3109 3110 Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Sub, Upper, Lower); 3111 3112 if (!Diff.isUsable() && VarType->getAsCXXRecordDecl()) { 3113 // BuildBinOp already emitted error, this one is to point user to upper 3114 // and lower bound, and to tell what is passed to 'operator-'. 3115 SemaRef.Diag(Upper->getLocStart(), diag::err_omp_loop_diff_cxx) 3116 << Upper->getSourceRange() << Lower->getSourceRange(); 3117 return nullptr; 3118 } 3119 } 3120 3121 if (!Diff.isUsable()) 3122 return nullptr; 3123 3124 // Upper - Lower [- 1] 3125 if (TestIsStrictOp) 3126 Diff = SemaRef.BuildBinOp( 3127 S, DefaultLoc, BO_Sub, Diff.get(), 3128 SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get()); 3129 if (!Diff.isUsable()) 3130 return nullptr; 3131 3132 // Upper - Lower [- 1] + Step 3133 auto NewStep = Transform.TransformExpr(Step->IgnoreImplicit()); 3134 if (NewStep.isInvalid()) 3135 return nullptr; 3136 NewStep = SemaRef.PerformImplicitConversion( 3137 NewStep.get(), Step->IgnoreImplicit()->getType(), Sema::AA_Converting, 3138 /*AllowExplicit=*/true); 3139 if (NewStep.isInvalid()) 3140 return nullptr; 3141 Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Add, Diff.get(), NewStep.get()); 3142 if (!Diff.isUsable()) 3143 return nullptr; 3144 3145 // Parentheses (for dumping/debugging purposes only). 3146 Diff = SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, Diff.get()); 3147 if (!Diff.isUsable()) 3148 return nullptr; 3149 3150 // (Upper - Lower [- 1] + Step) / Step 3151 NewStep = Transform.TransformExpr(Step->IgnoreImplicit()); 3152 if (NewStep.isInvalid()) 3153 return nullptr; 3154 NewStep = SemaRef.PerformImplicitConversion( 3155 NewStep.get(), Step->IgnoreImplicit()->getType(), Sema::AA_Converting, 3156 /*AllowExplicit=*/true); 3157 if (NewStep.isInvalid()) 3158 return nullptr; 3159 Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Div, Diff.get(), NewStep.get()); 3160 if (!Diff.isUsable()) 3161 return nullptr; 3162 3163 // OpenMP runtime requires 32-bit or 64-bit loop variables. 3164 QualType Type = Diff.get()->getType(); 3165 auto &C = SemaRef.Context; 3166 bool UseVarType = VarType->hasIntegerRepresentation() && 3167 C.getTypeSize(Type) > C.getTypeSize(VarType); 3168 if (!Type->isIntegerType() || UseVarType) { 3169 unsigned NewSize = 3170 UseVarType ? C.getTypeSize(VarType) : C.getTypeSize(Type); 3171 bool IsSigned = UseVarType ? VarType->hasSignedIntegerRepresentation() 3172 : Type->hasSignedIntegerRepresentation(); 3173 Type = C.getIntTypeForBitwidth(NewSize, IsSigned); 3174 Diff = SemaRef.PerformImplicitConversion( 3175 Diff.get(), Type, Sema::AA_Converting, /*AllowExplicit=*/true); 3176 if (!Diff.isUsable()) 3177 return nullptr; 3178 } 3179 if (LimitedType) { 3180 unsigned NewSize = (C.getTypeSize(Type) > 32) ? 64 : 32; 3181 if (NewSize != C.getTypeSize(Type)) { 3182 if (NewSize < C.getTypeSize(Type)) { 3183 assert(NewSize == 64 && "incorrect loop var size"); 3184 SemaRef.Diag(DefaultLoc, diag::warn_omp_loop_64_bit_var) 3185 << InitSrcRange << ConditionSrcRange; 3186 } 3187 QualType NewType = C.getIntTypeForBitwidth( 3188 NewSize, Type->hasSignedIntegerRepresentation() || 3189 C.getTypeSize(Type) < NewSize); 3190 Diff = SemaRef.PerformImplicitConversion(Diff.get(), NewType, 3191 Sema::AA_Converting, true); 3192 if (!Diff.isUsable()) 3193 return nullptr; 3194 } 3195 } 3196 3197 return Diff.get(); 3198 } 3199 3200 Expr *OpenMPIterationSpaceChecker::BuildPreCond(Scope *S, Expr *Cond) const { 3201 // Try to build LB <op> UB, where <op> is <, >, <=, or >=. 3202 bool Suppress = SemaRef.getDiagnostics().getSuppressAllDiagnostics(); 3203 SemaRef.getDiagnostics().setSuppressAllDiagnostics(/*Val=*/true); 3204 TransformToNewDefs Transform(SemaRef); 3205 3206 auto NewLB = Transform.TransformExpr(LB); 3207 auto NewUB = Transform.TransformExpr(UB); 3208 if (NewLB.isInvalid() || NewUB.isInvalid()) 3209 return Cond; 3210 NewLB = SemaRef.PerformImplicitConversion(NewLB.get(), LB->getType(), 3211 Sema::AA_Converting, 3212 /*AllowExplicit=*/true); 3213 NewUB = SemaRef.PerformImplicitConversion(NewUB.get(), UB->getType(), 3214 Sema::AA_Converting, 3215 /*AllowExplicit=*/true); 3216 if (NewLB.isInvalid() || NewUB.isInvalid()) 3217 return Cond; 3218 auto CondExpr = SemaRef.BuildBinOp( 3219 S, DefaultLoc, TestIsLessOp ? (TestIsStrictOp ? BO_LT : BO_LE) 3220 : (TestIsStrictOp ? BO_GT : BO_GE), 3221 NewLB.get(), NewUB.get()); 3222 if (CondExpr.isUsable()) { 3223 CondExpr = SemaRef.PerformImplicitConversion( 3224 CondExpr.get(), SemaRef.Context.BoolTy, /*Action=*/Sema::AA_Casting, 3225 /*AllowExplicit=*/true); 3226 } 3227 SemaRef.getDiagnostics().setSuppressAllDiagnostics(Suppress); 3228 // Otherwise use original loop conditon and evaluate it in runtime. 3229 return CondExpr.isUsable() ? CondExpr.get() : Cond; 3230 } 3231 3232 /// \brief Build reference expression to the counter be used for codegen. 3233 Expr *OpenMPIterationSpaceChecker::BuildCounterVar() const { 3234 return buildDeclRefExpr(SemaRef, Var, Var->getType().getNonReferenceType(), 3235 DefaultLoc); 3236 } 3237 3238 Expr *OpenMPIterationSpaceChecker::BuildPrivateCounterVar() const { 3239 if (Var && !Var->isInvalidDecl()) { 3240 auto Type = Var->getType().getNonReferenceType(); 3241 auto *PrivateVar = 3242 buildVarDecl(SemaRef, DefaultLoc, Type, Var->getName(), 3243 Var->hasAttrs() ? &Var->getAttrs() : nullptr); 3244 if (PrivateVar->isInvalidDecl()) 3245 return nullptr; 3246 return buildDeclRefExpr(SemaRef, PrivateVar, Type, DefaultLoc); 3247 } 3248 return nullptr; 3249 } 3250 3251 /// \brief Build initization of the counter be used for codegen. 3252 Expr *OpenMPIterationSpaceChecker::BuildCounterInit() const { return LB; } 3253 3254 /// \brief Build step of the counter be used for codegen. 3255 Expr *OpenMPIterationSpaceChecker::BuildCounterStep() const { return Step; } 3256 3257 /// \brief Iteration space of a single for loop. 3258 struct LoopIterationSpace { 3259 /// \brief Condition of the loop. 3260 Expr *PreCond; 3261 /// \brief This expression calculates the number of iterations in the loop. 3262 /// It is always possible to calculate it before starting the loop. 3263 Expr *NumIterations; 3264 /// \brief The loop counter variable. 3265 Expr *CounterVar; 3266 /// \brief Private loop counter variable. 3267 Expr *PrivateCounterVar; 3268 /// \brief This is initializer for the initial value of #CounterVar. 3269 Expr *CounterInit; 3270 /// \brief This is step for the #CounterVar used to generate its update: 3271 /// #CounterVar = #CounterInit + #CounterStep * CurrentIteration. 3272 Expr *CounterStep; 3273 /// \brief Should step be subtracted? 3274 bool Subtract; 3275 /// \brief Source range of the loop init. 3276 SourceRange InitSrcRange; 3277 /// \brief Source range of the loop condition. 3278 SourceRange CondSrcRange; 3279 /// \brief Source range of the loop increment. 3280 SourceRange IncSrcRange; 3281 }; 3282 3283 } // namespace 3284 3285 void Sema::ActOnOpenMPLoopInitialization(SourceLocation ForLoc, Stmt *Init) { 3286 assert(getLangOpts().OpenMP && "OpenMP is not active."); 3287 assert(Init && "Expected loop in canonical form."); 3288 unsigned CollapseIteration = DSAStack->getCollapseNumber(); 3289 if (CollapseIteration > 0 && 3290 isOpenMPLoopDirective(DSAStack->getCurrentDirective())) { 3291 OpenMPIterationSpaceChecker ISC(*this, ForLoc); 3292 if (!ISC.CheckInit(Init, /*EmitDiags=*/false)) { 3293 DSAStack->addLoopControlVariable(ISC.GetLoopVar()); 3294 } 3295 DSAStack->setCollapseNumber(CollapseIteration - 1); 3296 } 3297 } 3298 3299 /// \brief Called on a for stmt to check and extract its iteration space 3300 /// for further processing (such as collapsing). 3301 static bool CheckOpenMPIterationSpace( 3302 OpenMPDirectiveKind DKind, Stmt *S, Sema &SemaRef, DSAStackTy &DSA, 3303 unsigned CurrentNestedLoopCount, unsigned NestedLoopCount, 3304 Expr *CollapseLoopCountExpr, Expr *OrderedLoopCountExpr, 3305 llvm::DenseMap<VarDecl *, Expr *> &VarsWithImplicitDSA, 3306 LoopIterationSpace &ResultIterSpace) { 3307 // OpenMP [2.6, Canonical Loop Form] 3308 // for (init-expr; test-expr; incr-expr) structured-block 3309 auto For = dyn_cast_or_null<ForStmt>(S); 3310 if (!For) { 3311 SemaRef.Diag(S->getLocStart(), diag::err_omp_not_for) 3312 << (CollapseLoopCountExpr != nullptr || OrderedLoopCountExpr != nullptr) 3313 << getOpenMPDirectiveName(DKind) << NestedLoopCount 3314 << (CurrentNestedLoopCount > 0) << CurrentNestedLoopCount; 3315 if (NestedLoopCount > 1) { 3316 if (CollapseLoopCountExpr && OrderedLoopCountExpr) 3317 SemaRef.Diag(DSA.getConstructLoc(), 3318 diag::note_omp_collapse_ordered_expr) 3319 << 2 << CollapseLoopCountExpr->getSourceRange() 3320 << OrderedLoopCountExpr->getSourceRange(); 3321 else if (CollapseLoopCountExpr) 3322 SemaRef.Diag(CollapseLoopCountExpr->getExprLoc(), 3323 diag::note_omp_collapse_ordered_expr) 3324 << 0 << CollapseLoopCountExpr->getSourceRange(); 3325 else 3326 SemaRef.Diag(OrderedLoopCountExpr->getExprLoc(), 3327 diag::note_omp_collapse_ordered_expr) 3328 << 1 << OrderedLoopCountExpr->getSourceRange(); 3329 } 3330 return true; 3331 } 3332 assert(For->getBody()); 3333 3334 OpenMPIterationSpaceChecker ISC(SemaRef, For->getForLoc()); 3335 3336 // Check init. 3337 auto Init = For->getInit(); 3338 if (ISC.CheckInit(Init)) { 3339 return true; 3340 } 3341 3342 bool HasErrors = false; 3343 3344 // Check loop variable's type. 3345 auto Var = ISC.GetLoopVar(); 3346 3347 // OpenMP [2.6, Canonical Loop Form] 3348 // Var is one of the following: 3349 // A variable of signed or unsigned integer type. 3350 // For C++, a variable of a random access iterator type. 3351 // For C, a variable of a pointer type. 3352 auto VarType = Var->getType().getNonReferenceType(); 3353 if (!VarType->isDependentType() && !VarType->isIntegerType() && 3354 !VarType->isPointerType() && 3355 !(SemaRef.getLangOpts().CPlusPlus && VarType->isOverloadableType())) { 3356 SemaRef.Diag(Init->getLocStart(), diag::err_omp_loop_variable_type) 3357 << SemaRef.getLangOpts().CPlusPlus; 3358 HasErrors = true; 3359 } 3360 3361 // OpenMP, 2.14.1.1 Data-sharing Attribute Rules for Variables Referenced in a 3362 // Construct 3363 // The loop iteration variable(s) in the associated for-loop(s) of a for or 3364 // parallel for construct is (are) private. 3365 // The loop iteration variable in the associated for-loop of a simd construct 3366 // with just one associated for-loop is linear with a constant-linear-step 3367 // that is the increment of the associated for-loop. 3368 // Exclude loop var from the list of variables with implicitly defined data 3369 // sharing attributes. 3370 VarsWithImplicitDSA.erase(Var); 3371 3372 // OpenMP [2.14.1.1, Data-sharing Attribute Rules for Variables Referenced in 3373 // a Construct, C/C++]. 3374 // The loop iteration variable in the associated for-loop of a simd construct 3375 // with just one associated for-loop may be listed in a linear clause with a 3376 // constant-linear-step that is the increment of the associated for-loop. 3377 // The loop iteration variable(s) in the associated for-loop(s) of a for or 3378 // parallel for construct may be listed in a private or lastprivate clause. 3379 DSAStackTy::DSAVarData DVar = DSA.getTopDSA(Var, false); 3380 auto LoopVarRefExpr = ISC.GetLoopVarRefExpr(); 3381 // If LoopVarRefExpr is nullptr it means the corresponding loop variable is 3382 // declared in the loop and it is predetermined as a private. 3383 auto PredeterminedCKind = 3384 isOpenMPSimdDirective(DKind) 3385 ? ((NestedLoopCount == 1) ? OMPC_linear : OMPC_lastprivate) 3386 : OMPC_private; 3387 if (((isOpenMPSimdDirective(DKind) && DVar.CKind != OMPC_unknown && 3388 DVar.CKind != OMPC_threadprivate && DVar.CKind != PredeterminedCKind) || 3389 ((isOpenMPWorksharingDirective(DKind) || DKind == OMPD_taskloop) && 3390 !isOpenMPSimdDirective(DKind) && DVar.CKind != OMPC_unknown && 3391 DVar.CKind != OMPC_private && DVar.CKind != OMPC_lastprivate && 3392 DVar.CKind != OMPC_threadprivate)) && 3393 ((DVar.CKind != OMPC_private && DVar.CKind != OMPC_threadprivate) || 3394 DVar.RefExpr != nullptr)) { 3395 SemaRef.Diag(Init->getLocStart(), diag::err_omp_loop_var_dsa) 3396 << getOpenMPClauseName(DVar.CKind) << getOpenMPDirectiveName(DKind) 3397 << getOpenMPClauseName(PredeterminedCKind); 3398 if (DVar.RefExpr == nullptr) 3399 DVar.CKind = PredeterminedCKind; 3400 ReportOriginalDSA(SemaRef, &DSA, Var, DVar, /*IsLoopIterVar=*/true); 3401 HasErrors = true; 3402 } else if (LoopVarRefExpr != nullptr) { 3403 // Make the loop iteration variable private (for worksharing constructs), 3404 // linear (for simd directives with the only one associated loop) or 3405 // lastprivate (for simd directives with several collapsed or ordered 3406 // loops). 3407 if (DVar.CKind == OMPC_unknown) 3408 DVar = DSA.hasDSA(Var, isOpenMPPrivate, MatchesAlways(), 3409 /*FromParent=*/false); 3410 DSA.addDSA(Var, LoopVarRefExpr, PredeterminedCKind); 3411 } 3412 3413 assert(isOpenMPLoopDirective(DKind) && "DSA for non-loop vars"); 3414 3415 // Check test-expr. 3416 HasErrors |= ISC.CheckCond(For->getCond()); 3417 3418 // Check incr-expr. 3419 HasErrors |= ISC.CheckInc(For->getInc()); 3420 3421 if (ISC.Dependent() || SemaRef.CurContext->isDependentContext() || HasErrors) 3422 return HasErrors; 3423 3424 // Build the loop's iteration space representation. 3425 ResultIterSpace.PreCond = ISC.BuildPreCond(DSA.getCurScope(), For->getCond()); 3426 ResultIterSpace.NumIterations = ISC.BuildNumIterations( 3427 DSA.getCurScope(), (isOpenMPWorksharingDirective(DKind) || 3428 isOpenMPTaskLoopDirective(DKind))); 3429 ResultIterSpace.CounterVar = ISC.BuildCounterVar(); 3430 ResultIterSpace.PrivateCounterVar = ISC.BuildPrivateCounterVar(); 3431 ResultIterSpace.CounterInit = ISC.BuildCounterInit(); 3432 ResultIterSpace.CounterStep = ISC.BuildCounterStep(); 3433 ResultIterSpace.InitSrcRange = ISC.GetInitSrcRange(); 3434 ResultIterSpace.CondSrcRange = ISC.GetConditionSrcRange(); 3435 ResultIterSpace.IncSrcRange = ISC.GetIncrementSrcRange(); 3436 ResultIterSpace.Subtract = ISC.ShouldSubtractStep(); 3437 3438 HasErrors |= (ResultIterSpace.PreCond == nullptr || 3439 ResultIterSpace.NumIterations == nullptr || 3440 ResultIterSpace.CounterVar == nullptr || 3441 ResultIterSpace.PrivateCounterVar == nullptr || 3442 ResultIterSpace.CounterInit == nullptr || 3443 ResultIterSpace.CounterStep == nullptr); 3444 3445 return HasErrors; 3446 } 3447 3448 /// \brief Build 'VarRef = Start. 3449 static ExprResult BuildCounterInit(Sema &SemaRef, Scope *S, SourceLocation Loc, 3450 ExprResult VarRef, ExprResult Start) { 3451 TransformToNewDefs Transform(SemaRef); 3452 // Build 'VarRef = Start. 3453 auto NewStart = Transform.TransformExpr(Start.get()->IgnoreImplicit()); 3454 if (NewStart.isInvalid()) 3455 return ExprError(); 3456 NewStart = SemaRef.PerformImplicitConversion( 3457 NewStart.get(), Start.get()->IgnoreImplicit()->getType(), 3458 Sema::AA_Converting, 3459 /*AllowExplicit=*/true); 3460 if (NewStart.isInvalid()) 3461 return ExprError(); 3462 NewStart = SemaRef.PerformImplicitConversion( 3463 NewStart.get(), VarRef.get()->getType(), Sema::AA_Converting, 3464 /*AllowExplicit=*/true); 3465 if (!NewStart.isUsable()) 3466 return ExprError(); 3467 3468 auto Init = 3469 SemaRef.BuildBinOp(S, Loc, BO_Assign, VarRef.get(), NewStart.get()); 3470 return Init; 3471 } 3472 3473 /// \brief Build 'VarRef = Start + Iter * Step'. 3474 static ExprResult BuildCounterUpdate(Sema &SemaRef, Scope *S, 3475 SourceLocation Loc, ExprResult VarRef, 3476 ExprResult Start, ExprResult Iter, 3477 ExprResult Step, bool Subtract) { 3478 // Add parentheses (for debugging purposes only). 3479 Iter = SemaRef.ActOnParenExpr(Loc, Loc, Iter.get()); 3480 if (!VarRef.isUsable() || !Start.isUsable() || !Iter.isUsable() || 3481 !Step.isUsable()) 3482 return ExprError(); 3483 3484 TransformToNewDefs Transform(SemaRef); 3485 auto NewStep = Transform.TransformExpr(Step.get()->IgnoreImplicit()); 3486 if (NewStep.isInvalid()) 3487 return ExprError(); 3488 NewStep = SemaRef.PerformImplicitConversion( 3489 NewStep.get(), Step.get()->IgnoreImplicit()->getType(), 3490 Sema::AA_Converting, 3491 /*AllowExplicit=*/true); 3492 if (NewStep.isInvalid()) 3493 return ExprError(); 3494 ExprResult Update = 3495 SemaRef.BuildBinOp(S, Loc, BO_Mul, Iter.get(), NewStep.get()); 3496 if (!Update.isUsable()) 3497 return ExprError(); 3498 3499 // Build 'VarRef = Start + Iter * Step'. 3500 auto NewStart = Transform.TransformExpr(Start.get()->IgnoreImplicit()); 3501 if (NewStart.isInvalid()) 3502 return ExprError(); 3503 NewStart = SemaRef.PerformImplicitConversion( 3504 NewStart.get(), Start.get()->IgnoreImplicit()->getType(), 3505 Sema::AA_Converting, 3506 /*AllowExplicit=*/true); 3507 if (NewStart.isInvalid()) 3508 return ExprError(); 3509 Update = SemaRef.BuildBinOp(S, Loc, (Subtract ? BO_Sub : BO_Add), 3510 NewStart.get(), Update.get()); 3511 if (!Update.isUsable()) 3512 return ExprError(); 3513 3514 Update = SemaRef.PerformImplicitConversion( 3515 Update.get(), VarRef.get()->getType(), Sema::AA_Converting, true); 3516 if (!Update.isUsable()) 3517 return ExprError(); 3518 3519 Update = SemaRef.BuildBinOp(S, Loc, BO_Assign, VarRef.get(), Update.get()); 3520 return Update; 3521 } 3522 3523 /// \brief Convert integer expression \a E to make it have at least \a Bits 3524 /// bits. 3525 static ExprResult WidenIterationCount(unsigned Bits, Expr *E, 3526 Sema &SemaRef) { 3527 if (E == nullptr) 3528 return ExprError(); 3529 auto &C = SemaRef.Context; 3530 QualType OldType = E->getType(); 3531 unsigned HasBits = C.getTypeSize(OldType); 3532 if (HasBits >= Bits) 3533 return ExprResult(E); 3534 // OK to convert to signed, because new type has more bits than old. 3535 QualType NewType = C.getIntTypeForBitwidth(Bits, /* Signed */ true); 3536 return SemaRef.PerformImplicitConversion(E, NewType, Sema::AA_Converting, 3537 true); 3538 } 3539 3540 /// \brief Check if the given expression \a E is a constant integer that fits 3541 /// into \a Bits bits. 3542 static bool FitsInto(unsigned Bits, bool Signed, Expr *E, Sema &SemaRef) { 3543 if (E == nullptr) 3544 return false; 3545 llvm::APSInt Result; 3546 if (E->isIntegerConstantExpr(Result, SemaRef.Context)) 3547 return Signed ? Result.isSignedIntN(Bits) : Result.isIntN(Bits); 3548 return false; 3549 } 3550 3551 /// \brief Called on a for stmt to check itself and nested loops (if any). 3552 /// \return Returns 0 if one of the collapsed stmts is not canonical for loop, 3553 /// number of collapsed loops otherwise. 3554 static unsigned 3555 CheckOpenMPLoop(OpenMPDirectiveKind DKind, Expr *CollapseLoopCountExpr, 3556 Expr *OrderedLoopCountExpr, Stmt *AStmt, Sema &SemaRef, 3557 DSAStackTy &DSA, 3558 llvm::DenseMap<VarDecl *, Expr *> &VarsWithImplicitDSA, 3559 OMPLoopDirective::HelperExprs &Built) { 3560 unsigned NestedLoopCount = 1; 3561 if (CollapseLoopCountExpr) { 3562 // Found 'collapse' clause - calculate collapse number. 3563 llvm::APSInt Result; 3564 if (CollapseLoopCountExpr->EvaluateAsInt(Result, SemaRef.getASTContext())) 3565 NestedLoopCount = Result.getLimitedValue(); 3566 } 3567 if (OrderedLoopCountExpr) { 3568 // Found 'ordered' clause - calculate collapse number. 3569 llvm::APSInt Result; 3570 if (OrderedLoopCountExpr->EvaluateAsInt(Result, SemaRef.getASTContext())) { 3571 if (Result.getLimitedValue() < NestedLoopCount) { 3572 SemaRef.Diag(OrderedLoopCountExpr->getExprLoc(), 3573 diag::err_omp_wrong_ordered_loop_count) 3574 << OrderedLoopCountExpr->getSourceRange(); 3575 SemaRef.Diag(CollapseLoopCountExpr->getExprLoc(), 3576 diag::note_collapse_loop_count) 3577 << CollapseLoopCountExpr->getSourceRange(); 3578 } 3579 NestedLoopCount = Result.getLimitedValue(); 3580 } 3581 } 3582 // This is helper routine for loop directives (e.g., 'for', 'simd', 3583 // 'for simd', etc.). 3584 SmallVector<LoopIterationSpace, 4> IterSpaces; 3585 IterSpaces.resize(NestedLoopCount); 3586 Stmt *CurStmt = AStmt->IgnoreContainers(/* IgnoreCaptured */ true); 3587 for (unsigned Cnt = 0; Cnt < NestedLoopCount; ++Cnt) { 3588 if (CheckOpenMPIterationSpace(DKind, CurStmt, SemaRef, DSA, Cnt, 3589 NestedLoopCount, CollapseLoopCountExpr, 3590 OrderedLoopCountExpr, VarsWithImplicitDSA, 3591 IterSpaces[Cnt])) 3592 return 0; 3593 // Move on to the next nested for loop, or to the loop body. 3594 // OpenMP [2.8.1, simd construct, Restrictions] 3595 // All loops associated with the construct must be perfectly nested; that 3596 // is, there must be no intervening code nor any OpenMP directive between 3597 // any two loops. 3598 CurStmt = cast<ForStmt>(CurStmt)->getBody()->IgnoreContainers(); 3599 } 3600 3601 Built.clear(/* size */ NestedLoopCount); 3602 3603 if (SemaRef.CurContext->isDependentContext()) 3604 return NestedLoopCount; 3605 3606 // An example of what is generated for the following code: 3607 // 3608 // #pragma omp simd collapse(2) ordered(2) 3609 // for (i = 0; i < NI; ++i) 3610 // for (k = 0; k < NK; ++k) 3611 // for (j = J0; j < NJ; j+=2) { 3612 // <loop body> 3613 // } 3614 // 3615 // We generate the code below. 3616 // Note: the loop body may be outlined in CodeGen. 3617 // Note: some counters may be C++ classes, operator- is used to find number of 3618 // iterations and operator+= to calculate counter value. 3619 // Note: decltype(NumIterations) must be integer type (in 'omp for', only i32 3620 // or i64 is currently supported). 3621 // 3622 // #define NumIterations (NI * ((NJ - J0 - 1 + 2) / 2)) 3623 // for (int[32|64]_t IV = 0; IV < NumIterations; ++IV ) { 3624 // .local.i = IV / ((NJ - J0 - 1 + 2) / 2); 3625 // .local.j = J0 + (IV % ((NJ - J0 - 1 + 2) / 2)) * 2; 3626 // // similar updates for vars in clauses (e.g. 'linear') 3627 // <loop body (using local i and j)> 3628 // } 3629 // i = NI; // assign final values of counters 3630 // j = NJ; 3631 // 3632 3633 // Last iteration number is (I1 * I2 * ... In) - 1, where I1, I2 ... In are 3634 // the iteration counts of the collapsed for loops. 3635 // Precondition tests if there is at least one iteration (all conditions are 3636 // true). 3637 auto PreCond = ExprResult(IterSpaces[0].PreCond); 3638 auto N0 = IterSpaces[0].NumIterations; 3639 ExprResult LastIteration32 = WidenIterationCount( 3640 32 /* Bits */, SemaRef.PerformImplicitConversion( 3641 N0->IgnoreImpCasts(), N0->getType(), 3642 Sema::AA_Converting, /*AllowExplicit=*/true) 3643 .get(), 3644 SemaRef); 3645 ExprResult LastIteration64 = WidenIterationCount( 3646 64 /* Bits */, SemaRef.PerformImplicitConversion( 3647 N0->IgnoreImpCasts(), N0->getType(), 3648 Sema::AA_Converting, /*AllowExplicit=*/true) 3649 .get(), 3650 SemaRef); 3651 3652 if (!LastIteration32.isUsable() || !LastIteration64.isUsable()) 3653 return NestedLoopCount; 3654 3655 auto &C = SemaRef.Context; 3656 bool AllCountsNeedLessThan32Bits = C.getTypeSize(N0->getType()) < 32; 3657 3658 Scope *CurScope = DSA.getCurScope(); 3659 for (unsigned Cnt = 1; Cnt < NestedLoopCount; ++Cnt) { 3660 if (PreCond.isUsable()) { 3661 PreCond = SemaRef.BuildBinOp(CurScope, SourceLocation(), BO_LAnd, 3662 PreCond.get(), IterSpaces[Cnt].PreCond); 3663 } 3664 auto N = IterSpaces[Cnt].NumIterations; 3665 AllCountsNeedLessThan32Bits &= C.getTypeSize(N->getType()) < 32; 3666 if (LastIteration32.isUsable()) 3667 LastIteration32 = SemaRef.BuildBinOp( 3668 CurScope, SourceLocation(), BO_Mul, LastIteration32.get(), 3669 SemaRef.PerformImplicitConversion(N->IgnoreImpCasts(), N->getType(), 3670 Sema::AA_Converting, 3671 /*AllowExplicit=*/true) 3672 .get()); 3673 if (LastIteration64.isUsable()) 3674 LastIteration64 = SemaRef.BuildBinOp( 3675 CurScope, SourceLocation(), BO_Mul, LastIteration64.get(), 3676 SemaRef.PerformImplicitConversion(N->IgnoreImpCasts(), N->getType(), 3677 Sema::AA_Converting, 3678 /*AllowExplicit=*/true) 3679 .get()); 3680 } 3681 3682 // Choose either the 32-bit or 64-bit version. 3683 ExprResult LastIteration = LastIteration64; 3684 if (LastIteration32.isUsable() && 3685 C.getTypeSize(LastIteration32.get()->getType()) == 32 && 3686 (AllCountsNeedLessThan32Bits || NestedLoopCount == 1 || 3687 FitsInto( 3688 32 /* Bits */, 3689 LastIteration32.get()->getType()->hasSignedIntegerRepresentation(), 3690 LastIteration64.get(), SemaRef))) 3691 LastIteration = LastIteration32; 3692 3693 if (!LastIteration.isUsable()) 3694 return 0; 3695 3696 // Save the number of iterations. 3697 ExprResult NumIterations = LastIteration; 3698 { 3699 LastIteration = SemaRef.BuildBinOp( 3700 CurScope, SourceLocation(), BO_Sub, LastIteration.get(), 3701 SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get()); 3702 if (!LastIteration.isUsable()) 3703 return 0; 3704 } 3705 3706 // Calculate the last iteration number beforehand instead of doing this on 3707 // each iteration. Do not do this if the number of iterations may be kfold-ed. 3708 llvm::APSInt Result; 3709 bool IsConstant = 3710 LastIteration.get()->isIntegerConstantExpr(Result, SemaRef.Context); 3711 ExprResult CalcLastIteration; 3712 if (!IsConstant) { 3713 SourceLocation SaveLoc; 3714 VarDecl *SaveVar = 3715 buildVarDecl(SemaRef, SaveLoc, LastIteration.get()->getType(), 3716 ".omp.last.iteration"); 3717 ExprResult SaveRef = buildDeclRefExpr( 3718 SemaRef, SaveVar, LastIteration.get()->getType(), SaveLoc); 3719 CalcLastIteration = SemaRef.BuildBinOp(CurScope, SaveLoc, BO_Assign, 3720 SaveRef.get(), LastIteration.get()); 3721 LastIteration = SaveRef; 3722 3723 // Prepare SaveRef + 1. 3724 NumIterations = SemaRef.BuildBinOp( 3725 CurScope, SaveLoc, BO_Add, SaveRef.get(), 3726 SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get()); 3727 if (!NumIterations.isUsable()) 3728 return 0; 3729 } 3730 3731 SourceLocation InitLoc = IterSpaces[0].InitSrcRange.getBegin(); 3732 3733 QualType VType = LastIteration.get()->getType(); 3734 // Build variables passed into runtime, nesessary for worksharing directives. 3735 ExprResult LB, UB, IL, ST, EUB; 3736 if (isOpenMPWorksharingDirective(DKind) || isOpenMPTaskLoopDirective(DKind)) { 3737 // Lower bound variable, initialized with zero. 3738 VarDecl *LBDecl = buildVarDecl(SemaRef, InitLoc, VType, ".omp.lb"); 3739 LB = buildDeclRefExpr(SemaRef, LBDecl, VType, InitLoc); 3740 SemaRef.AddInitializerToDecl( 3741 LBDecl, SemaRef.ActOnIntegerConstant(InitLoc, 0).get(), 3742 /*DirectInit*/ false, /*TypeMayContainAuto*/ false); 3743 3744 // Upper bound variable, initialized with last iteration number. 3745 VarDecl *UBDecl = buildVarDecl(SemaRef, InitLoc, VType, ".omp.ub"); 3746 UB = buildDeclRefExpr(SemaRef, UBDecl, VType, InitLoc); 3747 SemaRef.AddInitializerToDecl(UBDecl, LastIteration.get(), 3748 /*DirectInit*/ false, 3749 /*TypeMayContainAuto*/ false); 3750 3751 // A 32-bit variable-flag where runtime returns 1 for the last iteration. 3752 // This will be used to implement clause 'lastprivate'. 3753 QualType Int32Ty = SemaRef.Context.getIntTypeForBitwidth(32, true); 3754 VarDecl *ILDecl = buildVarDecl(SemaRef, InitLoc, Int32Ty, ".omp.is_last"); 3755 IL = buildDeclRefExpr(SemaRef, ILDecl, Int32Ty, InitLoc); 3756 SemaRef.AddInitializerToDecl( 3757 ILDecl, SemaRef.ActOnIntegerConstant(InitLoc, 0).get(), 3758 /*DirectInit*/ false, /*TypeMayContainAuto*/ false); 3759 3760 // Stride variable returned by runtime (we initialize it to 1 by default). 3761 VarDecl *STDecl = buildVarDecl(SemaRef, InitLoc, VType, ".omp.stride"); 3762 ST = buildDeclRefExpr(SemaRef, STDecl, VType, InitLoc); 3763 SemaRef.AddInitializerToDecl( 3764 STDecl, SemaRef.ActOnIntegerConstant(InitLoc, 1).get(), 3765 /*DirectInit*/ false, /*TypeMayContainAuto*/ false); 3766 3767 // Build expression: UB = min(UB, LastIteration) 3768 // It is nesessary for CodeGen of directives with static scheduling. 3769 ExprResult IsUBGreater = SemaRef.BuildBinOp(CurScope, InitLoc, BO_GT, 3770 UB.get(), LastIteration.get()); 3771 ExprResult CondOp = SemaRef.ActOnConditionalOp( 3772 InitLoc, InitLoc, IsUBGreater.get(), LastIteration.get(), UB.get()); 3773 EUB = SemaRef.BuildBinOp(CurScope, InitLoc, BO_Assign, UB.get(), 3774 CondOp.get()); 3775 EUB = SemaRef.ActOnFinishFullExpr(EUB.get()); 3776 } 3777 3778 // Build the iteration variable and its initialization before loop. 3779 ExprResult IV; 3780 ExprResult Init; 3781 { 3782 VarDecl *IVDecl = buildVarDecl(SemaRef, InitLoc, VType, ".omp.iv"); 3783 IV = buildDeclRefExpr(SemaRef, IVDecl, VType, InitLoc); 3784 Expr *RHS = (isOpenMPWorksharingDirective(DKind) || 3785 isOpenMPTaskLoopDirective(DKind)) 3786 ? LB.get() 3787 : SemaRef.ActOnIntegerConstant(SourceLocation(), 0).get(); 3788 Init = SemaRef.BuildBinOp(CurScope, InitLoc, BO_Assign, IV.get(), RHS); 3789 Init = SemaRef.ActOnFinishFullExpr(Init.get()); 3790 } 3791 3792 // Loop condition (IV < NumIterations) or (IV <= UB) for worksharing loops. 3793 SourceLocation CondLoc; 3794 ExprResult Cond = 3795 (isOpenMPWorksharingDirective(DKind) || isOpenMPTaskLoopDirective(DKind)) 3796 ? SemaRef.BuildBinOp(CurScope, CondLoc, BO_LE, IV.get(), UB.get()) 3797 : SemaRef.BuildBinOp(CurScope, CondLoc, BO_LT, IV.get(), 3798 NumIterations.get()); 3799 3800 // Loop increment (IV = IV + 1) 3801 SourceLocation IncLoc; 3802 ExprResult Inc = 3803 SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, IV.get(), 3804 SemaRef.ActOnIntegerConstant(IncLoc, 1).get()); 3805 if (!Inc.isUsable()) 3806 return 0; 3807 Inc = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, IV.get(), Inc.get()); 3808 Inc = SemaRef.ActOnFinishFullExpr(Inc.get()); 3809 if (!Inc.isUsable()) 3810 return 0; 3811 3812 // Increments for worksharing loops (LB = LB + ST; UB = UB + ST). 3813 // Used for directives with static scheduling. 3814 ExprResult NextLB, NextUB; 3815 if (isOpenMPWorksharingDirective(DKind) || isOpenMPTaskLoopDirective(DKind)) { 3816 // LB + ST 3817 NextLB = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, LB.get(), ST.get()); 3818 if (!NextLB.isUsable()) 3819 return 0; 3820 // LB = LB + ST 3821 NextLB = 3822 SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, LB.get(), NextLB.get()); 3823 NextLB = SemaRef.ActOnFinishFullExpr(NextLB.get()); 3824 if (!NextLB.isUsable()) 3825 return 0; 3826 // UB + ST 3827 NextUB = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, UB.get(), ST.get()); 3828 if (!NextUB.isUsable()) 3829 return 0; 3830 // UB = UB + ST 3831 NextUB = 3832 SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, UB.get(), NextUB.get()); 3833 NextUB = SemaRef.ActOnFinishFullExpr(NextUB.get()); 3834 if (!NextUB.isUsable()) 3835 return 0; 3836 } 3837 3838 // Build updates and final values of the loop counters. 3839 bool HasErrors = false; 3840 Built.Counters.resize(NestedLoopCount); 3841 Built.Inits.resize(NestedLoopCount); 3842 Built.Updates.resize(NestedLoopCount); 3843 Built.Finals.resize(NestedLoopCount); 3844 { 3845 ExprResult Div; 3846 // Go from inner nested loop to outer. 3847 for (int Cnt = NestedLoopCount - 1; Cnt >= 0; --Cnt) { 3848 LoopIterationSpace &IS = IterSpaces[Cnt]; 3849 SourceLocation UpdLoc = IS.IncSrcRange.getBegin(); 3850 // Build: Iter = (IV / Div) % IS.NumIters 3851 // where Div is product of previous iterations' IS.NumIters. 3852 ExprResult Iter; 3853 if (Div.isUsable()) { 3854 Iter = 3855 SemaRef.BuildBinOp(CurScope, UpdLoc, BO_Div, IV.get(), Div.get()); 3856 } else { 3857 Iter = IV; 3858 assert((Cnt == (int)NestedLoopCount - 1) && 3859 "unusable div expected on first iteration only"); 3860 } 3861 3862 if (Cnt != 0 && Iter.isUsable()) 3863 Iter = SemaRef.BuildBinOp(CurScope, UpdLoc, BO_Rem, Iter.get(), 3864 IS.NumIterations); 3865 if (!Iter.isUsable()) { 3866 HasErrors = true; 3867 break; 3868 } 3869 3870 // Build update: IS.CounterVar(Private) = IS.Start + Iter * IS.Step 3871 auto *CounterVar = buildDeclRefExpr( 3872 SemaRef, cast<VarDecl>(cast<DeclRefExpr>(IS.CounterVar)->getDecl()), 3873 IS.CounterVar->getType(), IS.CounterVar->getExprLoc(), 3874 /*RefersToCapture=*/true); 3875 ExprResult Init = BuildCounterInit(SemaRef, CurScope, UpdLoc, CounterVar, 3876 IS.CounterInit); 3877 if (!Init.isUsable()) { 3878 HasErrors = true; 3879 break; 3880 } 3881 ExprResult Update = 3882 BuildCounterUpdate(SemaRef, CurScope, UpdLoc, CounterVar, 3883 IS.CounterInit, Iter, IS.CounterStep, IS.Subtract); 3884 if (!Update.isUsable()) { 3885 HasErrors = true; 3886 break; 3887 } 3888 3889 // Build final: IS.CounterVar = IS.Start + IS.NumIters * IS.Step 3890 ExprResult Final = BuildCounterUpdate( 3891 SemaRef, CurScope, UpdLoc, CounterVar, IS.CounterInit, 3892 IS.NumIterations, IS.CounterStep, IS.Subtract); 3893 if (!Final.isUsable()) { 3894 HasErrors = true; 3895 break; 3896 } 3897 3898 // Build Div for the next iteration: Div <- Div * IS.NumIters 3899 if (Cnt != 0) { 3900 if (Div.isUnset()) 3901 Div = IS.NumIterations; 3902 else 3903 Div = SemaRef.BuildBinOp(CurScope, UpdLoc, BO_Mul, Div.get(), 3904 IS.NumIterations); 3905 3906 // Add parentheses (for debugging purposes only). 3907 if (Div.isUsable()) 3908 Div = SemaRef.ActOnParenExpr(UpdLoc, UpdLoc, Div.get()); 3909 if (!Div.isUsable()) { 3910 HasErrors = true; 3911 break; 3912 } 3913 } 3914 if (!Update.isUsable() || !Final.isUsable()) { 3915 HasErrors = true; 3916 break; 3917 } 3918 // Save results 3919 Built.Counters[Cnt] = IS.CounterVar; 3920 Built.PrivateCounters[Cnt] = IS.PrivateCounterVar; 3921 Built.Inits[Cnt] = Init.get(); 3922 Built.Updates[Cnt] = Update.get(); 3923 Built.Finals[Cnt] = Final.get(); 3924 } 3925 } 3926 3927 if (HasErrors) 3928 return 0; 3929 3930 // Save results 3931 Built.IterationVarRef = IV.get(); 3932 Built.LastIteration = LastIteration.get(); 3933 Built.NumIterations = NumIterations.get(); 3934 Built.CalcLastIteration = 3935 SemaRef.ActOnFinishFullExpr(CalcLastIteration.get()).get(); 3936 Built.PreCond = PreCond.get(); 3937 Built.Cond = Cond.get(); 3938 Built.Init = Init.get(); 3939 Built.Inc = Inc.get(); 3940 Built.LB = LB.get(); 3941 Built.UB = UB.get(); 3942 Built.IL = IL.get(); 3943 Built.ST = ST.get(); 3944 Built.EUB = EUB.get(); 3945 Built.NLB = NextLB.get(); 3946 Built.NUB = NextUB.get(); 3947 3948 return NestedLoopCount; 3949 } 3950 3951 static Expr *getCollapseNumberExpr(ArrayRef<OMPClause *> Clauses) { 3952 auto CollapseClauses = 3953 OMPExecutableDirective::getClausesOfKind<OMPCollapseClause>(Clauses); 3954 if (CollapseClauses.begin() != CollapseClauses.end()) 3955 return (*CollapseClauses.begin())->getNumForLoops(); 3956 return nullptr; 3957 } 3958 3959 static Expr *getOrderedNumberExpr(ArrayRef<OMPClause *> Clauses) { 3960 auto OrderedClauses = 3961 OMPExecutableDirective::getClausesOfKind<OMPOrderedClause>(Clauses); 3962 if (OrderedClauses.begin() != OrderedClauses.end()) 3963 return (*OrderedClauses.begin())->getNumForLoops(); 3964 return nullptr; 3965 } 3966 3967 static bool checkSimdlenSafelenValues(Sema &S, const Expr *Simdlen, 3968 const Expr *Safelen) { 3969 llvm::APSInt SimdlenRes, SafelenRes; 3970 if (Simdlen->isValueDependent() || Simdlen->isTypeDependent() || 3971 Simdlen->isInstantiationDependent() || 3972 Simdlen->containsUnexpandedParameterPack()) 3973 return false; 3974 if (Safelen->isValueDependent() || Safelen->isTypeDependent() || 3975 Safelen->isInstantiationDependent() || 3976 Safelen->containsUnexpandedParameterPack()) 3977 return false; 3978 Simdlen->EvaluateAsInt(SimdlenRes, S.Context); 3979 Safelen->EvaluateAsInt(SafelenRes, S.Context); 3980 // OpenMP 4.1 [2.8.1, simd Construct, Restrictions] 3981 // If both simdlen and safelen clauses are specified, the value of the simdlen 3982 // parameter must be less than or equal to the value of the safelen parameter. 3983 if (SimdlenRes > SafelenRes) { 3984 S.Diag(Simdlen->getExprLoc(), diag::err_omp_wrong_simdlen_safelen_values) 3985 << Simdlen->getSourceRange() << Safelen->getSourceRange(); 3986 return true; 3987 } 3988 return false; 3989 } 3990 3991 StmtResult Sema::ActOnOpenMPSimdDirective( 3992 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, 3993 SourceLocation EndLoc, 3994 llvm::DenseMap<VarDecl *, Expr *> &VarsWithImplicitDSA) { 3995 if (!AStmt) 3996 return StmtError(); 3997 3998 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected"); 3999 OMPLoopDirective::HelperExprs B; 4000 // In presence of clause 'collapse' or 'ordered' with number of loops, it will 4001 // define the nested loops number. 4002 unsigned NestedLoopCount = CheckOpenMPLoop( 4003 OMPD_simd, getCollapseNumberExpr(Clauses), getOrderedNumberExpr(Clauses), 4004 AStmt, *this, *DSAStack, VarsWithImplicitDSA, B); 4005 if (NestedLoopCount == 0) 4006 return StmtError(); 4007 4008 assert((CurContext->isDependentContext() || B.builtAll()) && 4009 "omp simd loop exprs were not built"); 4010 4011 if (!CurContext->isDependentContext()) { 4012 // Finalize the clauses that need pre-built expressions for CodeGen. 4013 for (auto C : Clauses) { 4014 if (auto LC = dyn_cast<OMPLinearClause>(C)) 4015 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef), 4016 B.NumIterations, *this, CurScope)) 4017 return StmtError(); 4018 } 4019 } 4020 4021 // OpenMP 4.1 [2.8.1, simd Construct, Restrictions] 4022 // If both simdlen and safelen clauses are specified, the value of the simdlen 4023 // parameter must be less than or equal to the value of the safelen parameter. 4024 OMPSafelenClause *Safelen = nullptr; 4025 OMPSimdlenClause *Simdlen = nullptr; 4026 for (auto *Clause : Clauses) { 4027 if (Clause->getClauseKind() == OMPC_safelen) 4028 Safelen = cast<OMPSafelenClause>(Clause); 4029 else if (Clause->getClauseKind() == OMPC_simdlen) 4030 Simdlen = cast<OMPSimdlenClause>(Clause); 4031 if (Safelen && Simdlen) 4032 break; 4033 } 4034 if (Simdlen && Safelen && 4035 checkSimdlenSafelenValues(*this, Simdlen->getSimdlen(), 4036 Safelen->getSafelen())) 4037 return StmtError(); 4038 4039 getCurFunction()->setHasBranchProtectedScope(); 4040 return OMPSimdDirective::Create(Context, StartLoc, EndLoc, NestedLoopCount, 4041 Clauses, AStmt, B); 4042 } 4043 4044 StmtResult Sema::ActOnOpenMPForDirective( 4045 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, 4046 SourceLocation EndLoc, 4047 llvm::DenseMap<VarDecl *, Expr *> &VarsWithImplicitDSA) { 4048 if (!AStmt) 4049 return StmtError(); 4050 4051 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected"); 4052 OMPLoopDirective::HelperExprs B; 4053 // In presence of clause 'collapse' or 'ordered' with number of loops, it will 4054 // define the nested loops number. 4055 unsigned NestedLoopCount = CheckOpenMPLoop( 4056 OMPD_for, getCollapseNumberExpr(Clauses), getOrderedNumberExpr(Clauses), 4057 AStmt, *this, *DSAStack, VarsWithImplicitDSA, B); 4058 if (NestedLoopCount == 0) 4059 return StmtError(); 4060 4061 assert((CurContext->isDependentContext() || B.builtAll()) && 4062 "omp for loop exprs were not built"); 4063 4064 if (!CurContext->isDependentContext()) { 4065 // Finalize the clauses that need pre-built expressions for CodeGen. 4066 for (auto C : Clauses) { 4067 if (auto LC = dyn_cast<OMPLinearClause>(C)) 4068 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef), 4069 B.NumIterations, *this, CurScope)) 4070 return StmtError(); 4071 } 4072 } 4073 4074 getCurFunction()->setHasBranchProtectedScope(); 4075 return OMPForDirective::Create(Context, StartLoc, EndLoc, NestedLoopCount, 4076 Clauses, AStmt, B, DSAStack->isCancelRegion()); 4077 } 4078 4079 StmtResult Sema::ActOnOpenMPForSimdDirective( 4080 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, 4081 SourceLocation EndLoc, 4082 llvm::DenseMap<VarDecl *, Expr *> &VarsWithImplicitDSA) { 4083 if (!AStmt) 4084 return StmtError(); 4085 4086 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected"); 4087 OMPLoopDirective::HelperExprs B; 4088 // In presence of clause 'collapse' or 'ordered' with number of loops, it will 4089 // define the nested loops number. 4090 unsigned NestedLoopCount = 4091 CheckOpenMPLoop(OMPD_for_simd, getCollapseNumberExpr(Clauses), 4092 getOrderedNumberExpr(Clauses), AStmt, *this, *DSAStack, 4093 VarsWithImplicitDSA, B); 4094 if (NestedLoopCount == 0) 4095 return StmtError(); 4096 4097 assert((CurContext->isDependentContext() || B.builtAll()) && 4098 "omp for simd loop exprs were not built"); 4099 4100 if (!CurContext->isDependentContext()) { 4101 // Finalize the clauses that need pre-built expressions for CodeGen. 4102 for (auto C : Clauses) { 4103 if (auto LC = dyn_cast<OMPLinearClause>(C)) 4104 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef), 4105 B.NumIterations, *this, CurScope)) 4106 return StmtError(); 4107 } 4108 } 4109 4110 // OpenMP 4.1 [2.8.1, simd Construct, Restrictions] 4111 // If both simdlen and safelen clauses are specified, the value of the simdlen 4112 // parameter must be less than or equal to the value of the safelen parameter. 4113 OMPSafelenClause *Safelen = nullptr; 4114 OMPSimdlenClause *Simdlen = nullptr; 4115 for (auto *Clause : Clauses) { 4116 if (Clause->getClauseKind() == OMPC_safelen) 4117 Safelen = cast<OMPSafelenClause>(Clause); 4118 else if (Clause->getClauseKind() == OMPC_simdlen) 4119 Simdlen = cast<OMPSimdlenClause>(Clause); 4120 if (Safelen && Simdlen) 4121 break; 4122 } 4123 if (Simdlen && Safelen && 4124 checkSimdlenSafelenValues(*this, Simdlen->getSimdlen(), 4125 Safelen->getSafelen())) 4126 return StmtError(); 4127 4128 getCurFunction()->setHasBranchProtectedScope(); 4129 return OMPForSimdDirective::Create(Context, StartLoc, EndLoc, NestedLoopCount, 4130 Clauses, AStmt, B); 4131 } 4132 4133 StmtResult Sema::ActOnOpenMPSectionsDirective(ArrayRef<OMPClause *> Clauses, 4134 Stmt *AStmt, 4135 SourceLocation StartLoc, 4136 SourceLocation EndLoc) { 4137 if (!AStmt) 4138 return StmtError(); 4139 4140 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected"); 4141 auto BaseStmt = AStmt; 4142 while (CapturedStmt *CS = dyn_cast_or_null<CapturedStmt>(BaseStmt)) 4143 BaseStmt = CS->getCapturedStmt(); 4144 if (auto C = dyn_cast_or_null<CompoundStmt>(BaseStmt)) { 4145 auto S = C->children(); 4146 if (S.begin() == S.end()) 4147 return StmtError(); 4148 // All associated statements must be '#pragma omp section' except for 4149 // the first one. 4150 for (Stmt *SectionStmt : llvm::make_range(std::next(S.begin()), S.end())) { 4151 if (!SectionStmt || !isa<OMPSectionDirective>(SectionStmt)) { 4152 if (SectionStmt) 4153 Diag(SectionStmt->getLocStart(), 4154 diag::err_omp_sections_substmt_not_section); 4155 return StmtError(); 4156 } 4157 cast<OMPSectionDirective>(SectionStmt) 4158 ->setHasCancel(DSAStack->isCancelRegion()); 4159 } 4160 } else { 4161 Diag(AStmt->getLocStart(), diag::err_omp_sections_not_compound_stmt); 4162 return StmtError(); 4163 } 4164 4165 getCurFunction()->setHasBranchProtectedScope(); 4166 4167 return OMPSectionsDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt, 4168 DSAStack->isCancelRegion()); 4169 } 4170 4171 StmtResult Sema::ActOnOpenMPSectionDirective(Stmt *AStmt, 4172 SourceLocation StartLoc, 4173 SourceLocation EndLoc) { 4174 if (!AStmt) 4175 return StmtError(); 4176 4177 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected"); 4178 4179 getCurFunction()->setHasBranchProtectedScope(); 4180 DSAStack->setParentCancelRegion(DSAStack->isCancelRegion()); 4181 4182 return OMPSectionDirective::Create(Context, StartLoc, EndLoc, AStmt, 4183 DSAStack->isCancelRegion()); 4184 } 4185 4186 StmtResult Sema::ActOnOpenMPSingleDirective(ArrayRef<OMPClause *> Clauses, 4187 Stmt *AStmt, 4188 SourceLocation StartLoc, 4189 SourceLocation EndLoc) { 4190 if (!AStmt) 4191 return StmtError(); 4192 4193 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected"); 4194 4195 getCurFunction()->setHasBranchProtectedScope(); 4196 4197 // OpenMP [2.7.3, single Construct, Restrictions] 4198 // The copyprivate clause must not be used with the nowait clause. 4199 OMPClause *Nowait = nullptr; 4200 OMPClause *Copyprivate = nullptr; 4201 for (auto *Clause : Clauses) { 4202 if (Clause->getClauseKind() == OMPC_nowait) 4203 Nowait = Clause; 4204 else if (Clause->getClauseKind() == OMPC_copyprivate) 4205 Copyprivate = Clause; 4206 if (Copyprivate && Nowait) { 4207 Diag(Copyprivate->getLocStart(), 4208 diag::err_omp_single_copyprivate_with_nowait); 4209 Diag(Nowait->getLocStart(), diag::note_omp_nowait_clause_here); 4210 return StmtError(); 4211 } 4212 } 4213 4214 return OMPSingleDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt); 4215 } 4216 4217 StmtResult Sema::ActOnOpenMPMasterDirective(Stmt *AStmt, 4218 SourceLocation StartLoc, 4219 SourceLocation EndLoc) { 4220 if (!AStmt) 4221 return StmtError(); 4222 4223 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected"); 4224 4225 getCurFunction()->setHasBranchProtectedScope(); 4226 4227 return OMPMasterDirective::Create(Context, StartLoc, EndLoc, AStmt); 4228 } 4229 4230 StmtResult 4231 Sema::ActOnOpenMPCriticalDirective(const DeclarationNameInfo &DirName, 4232 Stmt *AStmt, SourceLocation StartLoc, 4233 SourceLocation EndLoc) { 4234 if (!AStmt) 4235 return StmtError(); 4236 4237 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected"); 4238 4239 getCurFunction()->setHasBranchProtectedScope(); 4240 4241 return OMPCriticalDirective::Create(Context, DirName, StartLoc, EndLoc, 4242 AStmt); 4243 } 4244 4245 StmtResult Sema::ActOnOpenMPParallelForDirective( 4246 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, 4247 SourceLocation EndLoc, 4248 llvm::DenseMap<VarDecl *, Expr *> &VarsWithImplicitDSA) { 4249 if (!AStmt) 4250 return StmtError(); 4251 4252 CapturedStmt *CS = cast<CapturedStmt>(AStmt); 4253 // 1.2.2 OpenMP Language Terminology 4254 // Structured block - An executable statement with a single entry at the 4255 // top and a single exit at the bottom. 4256 // The point of exit cannot be a branch out of the structured block. 4257 // longjmp() and throw() must not violate the entry/exit criteria. 4258 CS->getCapturedDecl()->setNothrow(); 4259 4260 OMPLoopDirective::HelperExprs B; 4261 // In presence of clause 'collapse' or 'ordered' with number of loops, it will 4262 // define the nested loops number. 4263 unsigned NestedLoopCount = 4264 CheckOpenMPLoop(OMPD_parallel_for, getCollapseNumberExpr(Clauses), 4265 getOrderedNumberExpr(Clauses), AStmt, *this, *DSAStack, 4266 VarsWithImplicitDSA, B); 4267 if (NestedLoopCount == 0) 4268 return StmtError(); 4269 4270 assert((CurContext->isDependentContext() || B.builtAll()) && 4271 "omp parallel for loop exprs were not built"); 4272 4273 if (!CurContext->isDependentContext()) { 4274 // Finalize the clauses that need pre-built expressions for CodeGen. 4275 for (auto C : Clauses) { 4276 if (auto LC = dyn_cast<OMPLinearClause>(C)) 4277 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef), 4278 B.NumIterations, *this, CurScope)) 4279 return StmtError(); 4280 } 4281 } 4282 4283 getCurFunction()->setHasBranchProtectedScope(); 4284 return OMPParallelForDirective::Create(Context, StartLoc, EndLoc, 4285 NestedLoopCount, Clauses, AStmt, B, 4286 DSAStack->isCancelRegion()); 4287 } 4288 4289 StmtResult Sema::ActOnOpenMPParallelForSimdDirective( 4290 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, 4291 SourceLocation EndLoc, 4292 llvm::DenseMap<VarDecl *, Expr *> &VarsWithImplicitDSA) { 4293 if (!AStmt) 4294 return StmtError(); 4295 4296 CapturedStmt *CS = cast<CapturedStmt>(AStmt); 4297 // 1.2.2 OpenMP Language Terminology 4298 // Structured block - An executable statement with a single entry at the 4299 // top and a single exit at the bottom. 4300 // The point of exit cannot be a branch out of the structured block. 4301 // longjmp() and throw() must not violate the entry/exit criteria. 4302 CS->getCapturedDecl()->setNothrow(); 4303 4304 OMPLoopDirective::HelperExprs B; 4305 // In presence of clause 'collapse' or 'ordered' with number of loops, it will 4306 // define the nested loops number. 4307 unsigned NestedLoopCount = 4308 CheckOpenMPLoop(OMPD_parallel_for_simd, getCollapseNumberExpr(Clauses), 4309 getOrderedNumberExpr(Clauses), AStmt, *this, *DSAStack, 4310 VarsWithImplicitDSA, B); 4311 if (NestedLoopCount == 0) 4312 return StmtError(); 4313 4314 if (!CurContext->isDependentContext()) { 4315 // Finalize the clauses that need pre-built expressions for CodeGen. 4316 for (auto C : Clauses) { 4317 if (auto LC = dyn_cast<OMPLinearClause>(C)) 4318 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef), 4319 B.NumIterations, *this, CurScope)) 4320 return StmtError(); 4321 } 4322 } 4323 4324 // OpenMP 4.1 [2.8.1, simd Construct, Restrictions] 4325 // If both simdlen and safelen clauses are specified, the value of the simdlen 4326 // parameter must be less than or equal to the value of the safelen parameter. 4327 OMPSafelenClause *Safelen = nullptr; 4328 OMPSimdlenClause *Simdlen = nullptr; 4329 for (auto *Clause : Clauses) { 4330 if (Clause->getClauseKind() == OMPC_safelen) 4331 Safelen = cast<OMPSafelenClause>(Clause); 4332 else if (Clause->getClauseKind() == OMPC_simdlen) 4333 Simdlen = cast<OMPSimdlenClause>(Clause); 4334 if (Safelen && Simdlen) 4335 break; 4336 } 4337 if (Simdlen && Safelen && 4338 checkSimdlenSafelenValues(*this, Simdlen->getSimdlen(), 4339 Safelen->getSafelen())) 4340 return StmtError(); 4341 4342 getCurFunction()->setHasBranchProtectedScope(); 4343 return OMPParallelForSimdDirective::Create( 4344 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B); 4345 } 4346 4347 StmtResult 4348 Sema::ActOnOpenMPParallelSectionsDirective(ArrayRef<OMPClause *> Clauses, 4349 Stmt *AStmt, SourceLocation StartLoc, 4350 SourceLocation EndLoc) { 4351 if (!AStmt) 4352 return StmtError(); 4353 4354 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected"); 4355 auto BaseStmt = AStmt; 4356 while (CapturedStmt *CS = dyn_cast_or_null<CapturedStmt>(BaseStmt)) 4357 BaseStmt = CS->getCapturedStmt(); 4358 if (auto C = dyn_cast_or_null<CompoundStmt>(BaseStmt)) { 4359 auto S = C->children(); 4360 if (S.begin() == S.end()) 4361 return StmtError(); 4362 // All associated statements must be '#pragma omp section' except for 4363 // the first one. 4364 for (Stmt *SectionStmt : llvm::make_range(std::next(S.begin()), S.end())) { 4365 if (!SectionStmt || !isa<OMPSectionDirective>(SectionStmt)) { 4366 if (SectionStmt) 4367 Diag(SectionStmt->getLocStart(), 4368 diag::err_omp_parallel_sections_substmt_not_section); 4369 return StmtError(); 4370 } 4371 cast<OMPSectionDirective>(SectionStmt) 4372 ->setHasCancel(DSAStack->isCancelRegion()); 4373 } 4374 } else { 4375 Diag(AStmt->getLocStart(), 4376 diag::err_omp_parallel_sections_not_compound_stmt); 4377 return StmtError(); 4378 } 4379 4380 getCurFunction()->setHasBranchProtectedScope(); 4381 4382 return OMPParallelSectionsDirective::Create( 4383 Context, StartLoc, EndLoc, Clauses, AStmt, DSAStack->isCancelRegion()); 4384 } 4385 4386 StmtResult Sema::ActOnOpenMPTaskDirective(ArrayRef<OMPClause *> Clauses, 4387 Stmt *AStmt, SourceLocation StartLoc, 4388 SourceLocation EndLoc) { 4389 if (!AStmt) 4390 return StmtError(); 4391 4392 CapturedStmt *CS = cast<CapturedStmt>(AStmt); 4393 // 1.2.2 OpenMP Language Terminology 4394 // Structured block - An executable statement with a single entry at the 4395 // top and a single exit at the bottom. 4396 // The point of exit cannot be a branch out of the structured block. 4397 // longjmp() and throw() must not violate the entry/exit criteria. 4398 CS->getCapturedDecl()->setNothrow(); 4399 4400 getCurFunction()->setHasBranchProtectedScope(); 4401 4402 return OMPTaskDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt, 4403 DSAStack->isCancelRegion()); 4404 } 4405 4406 StmtResult Sema::ActOnOpenMPTaskyieldDirective(SourceLocation StartLoc, 4407 SourceLocation EndLoc) { 4408 return OMPTaskyieldDirective::Create(Context, StartLoc, EndLoc); 4409 } 4410 4411 StmtResult Sema::ActOnOpenMPBarrierDirective(SourceLocation StartLoc, 4412 SourceLocation EndLoc) { 4413 return OMPBarrierDirective::Create(Context, StartLoc, EndLoc); 4414 } 4415 4416 StmtResult Sema::ActOnOpenMPTaskwaitDirective(SourceLocation StartLoc, 4417 SourceLocation EndLoc) { 4418 return OMPTaskwaitDirective::Create(Context, StartLoc, EndLoc); 4419 } 4420 4421 StmtResult Sema::ActOnOpenMPTaskgroupDirective(Stmt *AStmt, 4422 SourceLocation StartLoc, 4423 SourceLocation EndLoc) { 4424 if (!AStmt) 4425 return StmtError(); 4426 4427 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected"); 4428 4429 getCurFunction()->setHasBranchProtectedScope(); 4430 4431 return OMPTaskgroupDirective::Create(Context, StartLoc, EndLoc, AStmt); 4432 } 4433 4434 StmtResult Sema::ActOnOpenMPFlushDirective(ArrayRef<OMPClause *> Clauses, 4435 SourceLocation StartLoc, 4436 SourceLocation EndLoc) { 4437 assert(Clauses.size() <= 1 && "Extra clauses in flush directive"); 4438 return OMPFlushDirective::Create(Context, StartLoc, EndLoc, Clauses); 4439 } 4440 4441 StmtResult Sema::ActOnOpenMPOrderedDirective(ArrayRef<OMPClause *> Clauses, 4442 Stmt *AStmt, 4443 SourceLocation StartLoc, 4444 SourceLocation EndLoc) { 4445 if (!AStmt) 4446 return StmtError(); 4447 4448 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected"); 4449 4450 getCurFunction()->setHasBranchProtectedScope(); 4451 4452 OMPThreadsClause *TC = nullptr; 4453 OMPSIMDClause *SC = nullptr; 4454 for (auto *C: Clauses) { 4455 if (C->getClauseKind() == OMPC_threads) 4456 TC = cast<OMPThreadsClause>(C); 4457 else if (C->getClauseKind() == OMPC_simd) 4458 SC = cast<OMPSIMDClause>(C); 4459 } 4460 4461 // TODO: this must happen only if 'threads' clause specified or if no clauses 4462 // is specified. 4463 if (auto *Param = DSAStack->getParentOrderedRegionParam()) { 4464 SourceLocation ErrLoc = TC ? TC->getLocStart() : StartLoc; 4465 Diag(ErrLoc, diag::err_omp_ordered_directive_with_param) << (TC != nullptr); 4466 Diag(Param->getLocStart(), diag::note_omp_ordered_param); 4467 return StmtError(); 4468 } 4469 if (!SC && isOpenMPSimdDirective(DSAStack->getParentDirective())) { 4470 // OpenMP [2.8.1,simd Construct, Restrictions] 4471 // An ordered construct with the simd clause is the only OpenMP construct 4472 // that can appear in the simd region. 4473 Diag(StartLoc, diag::err_omp_prohibited_region_simd); 4474 return StmtError(); 4475 } 4476 4477 return OMPOrderedDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt); 4478 } 4479 4480 namespace { 4481 /// \brief Helper class for checking expression in 'omp atomic [update]' 4482 /// construct. 4483 class OpenMPAtomicUpdateChecker { 4484 /// \brief Error results for atomic update expressions. 4485 enum ExprAnalysisErrorCode { 4486 /// \brief A statement is not an expression statement. 4487 NotAnExpression, 4488 /// \brief Expression is not builtin binary or unary operation. 4489 NotABinaryOrUnaryExpression, 4490 /// \brief Unary operation is not post-/pre- increment/decrement operation. 4491 NotAnUnaryIncDecExpression, 4492 /// \brief An expression is not of scalar type. 4493 NotAScalarType, 4494 /// \brief A binary operation is not an assignment operation. 4495 NotAnAssignmentOp, 4496 /// \brief RHS part of the binary operation is not a binary expression. 4497 NotABinaryExpression, 4498 /// \brief RHS part is not additive/multiplicative/shift/biwise binary 4499 /// expression. 4500 NotABinaryOperator, 4501 /// \brief RHS binary operation does not have reference to the updated LHS 4502 /// part. 4503 NotAnUpdateExpression, 4504 /// \brief No errors is found. 4505 NoError 4506 }; 4507 /// \brief Reference to Sema. 4508 Sema &SemaRef; 4509 /// \brief A location for note diagnostics (when error is found). 4510 SourceLocation NoteLoc; 4511 /// \brief 'x' lvalue part of the source atomic expression. 4512 Expr *X; 4513 /// \brief 'expr' rvalue part of the source atomic expression. 4514 Expr *E; 4515 /// \brief Helper expression of the form 4516 /// 'OpaqueValueExpr(x) binop OpaqueValueExpr(expr)' or 4517 /// 'OpaqueValueExpr(expr) binop OpaqueValueExpr(x)'. 4518 Expr *UpdateExpr; 4519 /// \brief Is 'x' a LHS in a RHS part of full update expression. It is 4520 /// important for non-associative operations. 4521 bool IsXLHSInRHSPart; 4522 BinaryOperatorKind Op; 4523 SourceLocation OpLoc; 4524 /// \brief true if the source expression is a postfix unary operation, false 4525 /// if it is a prefix unary operation. 4526 bool IsPostfixUpdate; 4527 4528 public: 4529 OpenMPAtomicUpdateChecker(Sema &SemaRef) 4530 : SemaRef(SemaRef), X(nullptr), E(nullptr), UpdateExpr(nullptr), 4531 IsXLHSInRHSPart(false), Op(BO_PtrMemD), IsPostfixUpdate(false) {} 4532 /// \brief Check specified statement that it is suitable for 'atomic update' 4533 /// constructs and extract 'x', 'expr' and Operation from the original 4534 /// expression. If DiagId and NoteId == 0, then only check is performed 4535 /// without error notification. 4536 /// \param DiagId Diagnostic which should be emitted if error is found. 4537 /// \param NoteId Diagnostic note for the main error message. 4538 /// \return true if statement is not an update expression, false otherwise. 4539 bool checkStatement(Stmt *S, unsigned DiagId = 0, unsigned NoteId = 0); 4540 /// \brief Return the 'x' lvalue part of the source atomic expression. 4541 Expr *getX() const { return X; } 4542 /// \brief Return the 'expr' rvalue part of the source atomic expression. 4543 Expr *getExpr() const { return E; } 4544 /// \brief Return the update expression used in calculation of the updated 4545 /// value. Always has form 'OpaqueValueExpr(x) binop OpaqueValueExpr(expr)' or 4546 /// 'OpaqueValueExpr(expr) binop OpaqueValueExpr(x)'. 4547 Expr *getUpdateExpr() const { return UpdateExpr; } 4548 /// \brief Return true if 'x' is LHS in RHS part of full update expression, 4549 /// false otherwise. 4550 bool isXLHSInRHSPart() const { return IsXLHSInRHSPart; } 4551 4552 /// \brief true if the source expression is a postfix unary operation, false 4553 /// if it is a prefix unary operation. 4554 bool isPostfixUpdate() const { return IsPostfixUpdate; } 4555 4556 private: 4557 bool checkBinaryOperation(BinaryOperator *AtomicBinOp, unsigned DiagId = 0, 4558 unsigned NoteId = 0); 4559 }; 4560 } // namespace 4561 4562 bool OpenMPAtomicUpdateChecker::checkBinaryOperation( 4563 BinaryOperator *AtomicBinOp, unsigned DiagId, unsigned NoteId) { 4564 ExprAnalysisErrorCode ErrorFound = NoError; 4565 SourceLocation ErrorLoc, NoteLoc; 4566 SourceRange ErrorRange, NoteRange; 4567 // Allowed constructs are: 4568 // x = x binop expr; 4569 // x = expr binop x; 4570 if (AtomicBinOp->getOpcode() == BO_Assign) { 4571 X = AtomicBinOp->getLHS(); 4572 if (auto *AtomicInnerBinOp = dyn_cast<BinaryOperator>( 4573 AtomicBinOp->getRHS()->IgnoreParenImpCasts())) { 4574 if (AtomicInnerBinOp->isMultiplicativeOp() || 4575 AtomicInnerBinOp->isAdditiveOp() || AtomicInnerBinOp->isShiftOp() || 4576 AtomicInnerBinOp->isBitwiseOp()) { 4577 Op = AtomicInnerBinOp->getOpcode(); 4578 OpLoc = AtomicInnerBinOp->getOperatorLoc(); 4579 auto *LHS = AtomicInnerBinOp->getLHS(); 4580 auto *RHS = AtomicInnerBinOp->getRHS(); 4581 llvm::FoldingSetNodeID XId, LHSId, RHSId; 4582 X->IgnoreParenImpCasts()->Profile(XId, SemaRef.getASTContext(), 4583 /*Canonical=*/true); 4584 LHS->IgnoreParenImpCasts()->Profile(LHSId, SemaRef.getASTContext(), 4585 /*Canonical=*/true); 4586 RHS->IgnoreParenImpCasts()->Profile(RHSId, SemaRef.getASTContext(), 4587 /*Canonical=*/true); 4588 if (XId == LHSId) { 4589 E = RHS; 4590 IsXLHSInRHSPart = true; 4591 } else if (XId == RHSId) { 4592 E = LHS; 4593 IsXLHSInRHSPart = false; 4594 } else { 4595 ErrorLoc = AtomicInnerBinOp->getExprLoc(); 4596 ErrorRange = AtomicInnerBinOp->getSourceRange(); 4597 NoteLoc = X->getExprLoc(); 4598 NoteRange = X->getSourceRange(); 4599 ErrorFound = NotAnUpdateExpression; 4600 } 4601 } else { 4602 ErrorLoc = AtomicInnerBinOp->getExprLoc(); 4603 ErrorRange = AtomicInnerBinOp->getSourceRange(); 4604 NoteLoc = AtomicInnerBinOp->getOperatorLoc(); 4605 NoteRange = SourceRange(NoteLoc, NoteLoc); 4606 ErrorFound = NotABinaryOperator; 4607 } 4608 } else { 4609 NoteLoc = ErrorLoc = AtomicBinOp->getRHS()->getExprLoc(); 4610 NoteRange = ErrorRange = AtomicBinOp->getRHS()->getSourceRange(); 4611 ErrorFound = NotABinaryExpression; 4612 } 4613 } else { 4614 ErrorLoc = AtomicBinOp->getExprLoc(); 4615 ErrorRange = AtomicBinOp->getSourceRange(); 4616 NoteLoc = AtomicBinOp->getOperatorLoc(); 4617 NoteRange = SourceRange(NoteLoc, NoteLoc); 4618 ErrorFound = NotAnAssignmentOp; 4619 } 4620 if (ErrorFound != NoError && DiagId != 0 && NoteId != 0) { 4621 SemaRef.Diag(ErrorLoc, DiagId) << ErrorRange; 4622 SemaRef.Diag(NoteLoc, NoteId) << ErrorFound << NoteRange; 4623 return true; 4624 } else if (SemaRef.CurContext->isDependentContext()) 4625 E = X = UpdateExpr = nullptr; 4626 return ErrorFound != NoError; 4627 } 4628 4629 bool OpenMPAtomicUpdateChecker::checkStatement(Stmt *S, unsigned DiagId, 4630 unsigned NoteId) { 4631 ExprAnalysisErrorCode ErrorFound = NoError; 4632 SourceLocation ErrorLoc, NoteLoc; 4633 SourceRange ErrorRange, NoteRange; 4634 // Allowed constructs are: 4635 // x++; 4636 // x--; 4637 // ++x; 4638 // --x; 4639 // x binop= expr; 4640 // x = x binop expr; 4641 // x = expr binop x; 4642 if (auto *AtomicBody = dyn_cast<Expr>(S)) { 4643 AtomicBody = AtomicBody->IgnoreParenImpCasts(); 4644 if (AtomicBody->getType()->isScalarType() || 4645 AtomicBody->isInstantiationDependent()) { 4646 if (auto *AtomicCompAssignOp = dyn_cast<CompoundAssignOperator>( 4647 AtomicBody->IgnoreParenImpCasts())) { 4648 // Check for Compound Assignment Operation 4649 Op = BinaryOperator::getOpForCompoundAssignment( 4650 AtomicCompAssignOp->getOpcode()); 4651 OpLoc = AtomicCompAssignOp->getOperatorLoc(); 4652 E = AtomicCompAssignOp->getRHS(); 4653 X = AtomicCompAssignOp->getLHS(); 4654 IsXLHSInRHSPart = true; 4655 } else if (auto *AtomicBinOp = dyn_cast<BinaryOperator>( 4656 AtomicBody->IgnoreParenImpCasts())) { 4657 // Check for Binary Operation 4658 if(checkBinaryOperation(AtomicBinOp, DiagId, NoteId)) 4659 return true; 4660 } else if (auto *AtomicUnaryOp = 4661 dyn_cast<UnaryOperator>(AtomicBody->IgnoreParenImpCasts())) { 4662 // Check for Unary Operation 4663 if (AtomicUnaryOp->isIncrementDecrementOp()) { 4664 IsPostfixUpdate = AtomicUnaryOp->isPostfix(); 4665 Op = AtomicUnaryOp->isIncrementOp() ? BO_Add : BO_Sub; 4666 OpLoc = AtomicUnaryOp->getOperatorLoc(); 4667 X = AtomicUnaryOp->getSubExpr(); 4668 E = SemaRef.ActOnIntegerConstant(OpLoc, /*uint64_t Val=*/1).get(); 4669 IsXLHSInRHSPart = true; 4670 } else { 4671 ErrorFound = NotAnUnaryIncDecExpression; 4672 ErrorLoc = AtomicUnaryOp->getExprLoc(); 4673 ErrorRange = AtomicUnaryOp->getSourceRange(); 4674 NoteLoc = AtomicUnaryOp->getOperatorLoc(); 4675 NoteRange = SourceRange(NoteLoc, NoteLoc); 4676 } 4677 } else if (!AtomicBody->isInstantiationDependent()) { 4678 ErrorFound = NotABinaryOrUnaryExpression; 4679 NoteLoc = ErrorLoc = AtomicBody->getExprLoc(); 4680 NoteRange = ErrorRange = AtomicBody->getSourceRange(); 4681 } 4682 } else { 4683 ErrorFound = NotAScalarType; 4684 NoteLoc = ErrorLoc = AtomicBody->getLocStart(); 4685 NoteRange = ErrorRange = SourceRange(NoteLoc, NoteLoc); 4686 } 4687 } else { 4688 ErrorFound = NotAnExpression; 4689 NoteLoc = ErrorLoc = S->getLocStart(); 4690 NoteRange = ErrorRange = SourceRange(NoteLoc, NoteLoc); 4691 } 4692 if (ErrorFound != NoError && DiagId != 0 && NoteId != 0) { 4693 SemaRef.Diag(ErrorLoc, DiagId) << ErrorRange; 4694 SemaRef.Diag(NoteLoc, NoteId) << ErrorFound << NoteRange; 4695 return true; 4696 } else if (SemaRef.CurContext->isDependentContext()) 4697 E = X = UpdateExpr = nullptr; 4698 if (ErrorFound == NoError && E && X) { 4699 // Build an update expression of form 'OpaqueValueExpr(x) binop 4700 // OpaqueValueExpr(expr)' or 'OpaqueValueExpr(expr) binop 4701 // OpaqueValueExpr(x)' and then cast it to the type of the 'x' expression. 4702 auto *OVEX = new (SemaRef.getASTContext()) 4703 OpaqueValueExpr(X->getExprLoc(), X->getType(), VK_RValue); 4704 auto *OVEExpr = new (SemaRef.getASTContext()) 4705 OpaqueValueExpr(E->getExprLoc(), E->getType(), VK_RValue); 4706 auto Update = 4707 SemaRef.CreateBuiltinBinOp(OpLoc, Op, IsXLHSInRHSPart ? OVEX : OVEExpr, 4708 IsXLHSInRHSPart ? OVEExpr : OVEX); 4709 if (Update.isInvalid()) 4710 return true; 4711 Update = SemaRef.PerformImplicitConversion(Update.get(), X->getType(), 4712 Sema::AA_Casting); 4713 if (Update.isInvalid()) 4714 return true; 4715 UpdateExpr = Update.get(); 4716 } 4717 return ErrorFound != NoError; 4718 } 4719 4720 StmtResult Sema::ActOnOpenMPAtomicDirective(ArrayRef<OMPClause *> Clauses, 4721 Stmt *AStmt, 4722 SourceLocation StartLoc, 4723 SourceLocation EndLoc) { 4724 if (!AStmt) 4725 return StmtError(); 4726 4727 auto CS = cast<CapturedStmt>(AStmt); 4728 // 1.2.2 OpenMP Language Terminology 4729 // Structured block - An executable statement with a single entry at the 4730 // top and a single exit at the bottom. 4731 // The point of exit cannot be a branch out of the structured block. 4732 // longjmp() and throw() must not violate the entry/exit criteria. 4733 OpenMPClauseKind AtomicKind = OMPC_unknown; 4734 SourceLocation AtomicKindLoc; 4735 for (auto *C : Clauses) { 4736 if (C->getClauseKind() == OMPC_read || C->getClauseKind() == OMPC_write || 4737 C->getClauseKind() == OMPC_update || 4738 C->getClauseKind() == OMPC_capture) { 4739 if (AtomicKind != OMPC_unknown) { 4740 Diag(C->getLocStart(), diag::err_omp_atomic_several_clauses) 4741 << SourceRange(C->getLocStart(), C->getLocEnd()); 4742 Diag(AtomicKindLoc, diag::note_omp_atomic_previous_clause) 4743 << getOpenMPClauseName(AtomicKind); 4744 } else { 4745 AtomicKind = C->getClauseKind(); 4746 AtomicKindLoc = C->getLocStart(); 4747 } 4748 } 4749 } 4750 4751 auto Body = CS->getCapturedStmt(); 4752 if (auto *EWC = dyn_cast<ExprWithCleanups>(Body)) 4753 Body = EWC->getSubExpr(); 4754 4755 Expr *X = nullptr; 4756 Expr *V = nullptr; 4757 Expr *E = nullptr; 4758 Expr *UE = nullptr; 4759 bool IsXLHSInRHSPart = false; 4760 bool IsPostfixUpdate = false; 4761 // OpenMP [2.12.6, atomic Construct] 4762 // In the next expressions: 4763 // * x and v (as applicable) are both l-value expressions with scalar type. 4764 // * During the execution of an atomic region, multiple syntactic 4765 // occurrences of x must designate the same storage location. 4766 // * Neither of v and expr (as applicable) may access the storage location 4767 // designated by x. 4768 // * Neither of x and expr (as applicable) may access the storage location 4769 // designated by v. 4770 // * expr is an expression with scalar type. 4771 // * binop is one of +, *, -, /, &, ^, |, <<, or >>. 4772 // * binop, binop=, ++, and -- are not overloaded operators. 4773 // * The expression x binop expr must be numerically equivalent to x binop 4774 // (expr). This requirement is satisfied if the operators in expr have 4775 // precedence greater than binop, or by using parentheses around expr or 4776 // subexpressions of expr. 4777 // * The expression expr binop x must be numerically equivalent to (expr) 4778 // binop x. This requirement is satisfied if the operators in expr have 4779 // precedence equal to or greater than binop, or by using parentheses around 4780 // expr or subexpressions of expr. 4781 // * For forms that allow multiple occurrences of x, the number of times 4782 // that x is evaluated is unspecified. 4783 if (AtomicKind == OMPC_read) { 4784 enum { 4785 NotAnExpression, 4786 NotAnAssignmentOp, 4787 NotAScalarType, 4788 NotAnLValue, 4789 NoError 4790 } ErrorFound = NoError; 4791 SourceLocation ErrorLoc, NoteLoc; 4792 SourceRange ErrorRange, NoteRange; 4793 // If clause is read: 4794 // v = x; 4795 if (auto AtomicBody = dyn_cast<Expr>(Body)) { 4796 auto AtomicBinOp = 4797 dyn_cast<BinaryOperator>(AtomicBody->IgnoreParenImpCasts()); 4798 if (AtomicBinOp && AtomicBinOp->getOpcode() == BO_Assign) { 4799 X = AtomicBinOp->getRHS()->IgnoreParenImpCasts(); 4800 V = AtomicBinOp->getLHS()->IgnoreParenImpCasts(); 4801 if ((X->isInstantiationDependent() || X->getType()->isScalarType()) && 4802 (V->isInstantiationDependent() || V->getType()->isScalarType())) { 4803 if (!X->isLValue() || !V->isLValue()) { 4804 auto NotLValueExpr = X->isLValue() ? V : X; 4805 ErrorFound = NotAnLValue; 4806 ErrorLoc = AtomicBinOp->getExprLoc(); 4807 ErrorRange = AtomicBinOp->getSourceRange(); 4808 NoteLoc = NotLValueExpr->getExprLoc(); 4809 NoteRange = NotLValueExpr->getSourceRange(); 4810 } 4811 } else if (!X->isInstantiationDependent() || 4812 !V->isInstantiationDependent()) { 4813 auto NotScalarExpr = 4814 (X->isInstantiationDependent() || X->getType()->isScalarType()) 4815 ? V 4816 : X; 4817 ErrorFound = NotAScalarType; 4818 ErrorLoc = AtomicBinOp->getExprLoc(); 4819 ErrorRange = AtomicBinOp->getSourceRange(); 4820 NoteLoc = NotScalarExpr->getExprLoc(); 4821 NoteRange = NotScalarExpr->getSourceRange(); 4822 } 4823 } else if (!AtomicBody->isInstantiationDependent()) { 4824 ErrorFound = NotAnAssignmentOp; 4825 ErrorLoc = AtomicBody->getExprLoc(); 4826 ErrorRange = AtomicBody->getSourceRange(); 4827 NoteLoc = AtomicBinOp ? AtomicBinOp->getOperatorLoc() 4828 : AtomicBody->getExprLoc(); 4829 NoteRange = AtomicBinOp ? AtomicBinOp->getSourceRange() 4830 : AtomicBody->getSourceRange(); 4831 } 4832 } else { 4833 ErrorFound = NotAnExpression; 4834 NoteLoc = ErrorLoc = Body->getLocStart(); 4835 NoteRange = ErrorRange = SourceRange(NoteLoc, NoteLoc); 4836 } 4837 if (ErrorFound != NoError) { 4838 Diag(ErrorLoc, diag::err_omp_atomic_read_not_expression_statement) 4839 << ErrorRange; 4840 Diag(NoteLoc, diag::note_omp_atomic_read_write) << ErrorFound 4841 << NoteRange; 4842 return StmtError(); 4843 } else if (CurContext->isDependentContext()) 4844 V = X = nullptr; 4845 } else if (AtomicKind == OMPC_write) { 4846 enum { 4847 NotAnExpression, 4848 NotAnAssignmentOp, 4849 NotAScalarType, 4850 NotAnLValue, 4851 NoError 4852 } ErrorFound = NoError; 4853 SourceLocation ErrorLoc, NoteLoc; 4854 SourceRange ErrorRange, NoteRange; 4855 // If clause is write: 4856 // x = expr; 4857 if (auto AtomicBody = dyn_cast<Expr>(Body)) { 4858 auto AtomicBinOp = 4859 dyn_cast<BinaryOperator>(AtomicBody->IgnoreParenImpCasts()); 4860 if (AtomicBinOp && AtomicBinOp->getOpcode() == BO_Assign) { 4861 X = AtomicBinOp->getLHS(); 4862 E = AtomicBinOp->getRHS(); 4863 if ((X->isInstantiationDependent() || X->getType()->isScalarType()) && 4864 (E->isInstantiationDependent() || E->getType()->isScalarType())) { 4865 if (!X->isLValue()) { 4866 ErrorFound = NotAnLValue; 4867 ErrorLoc = AtomicBinOp->getExprLoc(); 4868 ErrorRange = AtomicBinOp->getSourceRange(); 4869 NoteLoc = X->getExprLoc(); 4870 NoteRange = X->getSourceRange(); 4871 } 4872 } else if (!X->isInstantiationDependent() || 4873 !E->isInstantiationDependent()) { 4874 auto NotScalarExpr = 4875 (X->isInstantiationDependent() || X->getType()->isScalarType()) 4876 ? E 4877 : X; 4878 ErrorFound = NotAScalarType; 4879 ErrorLoc = AtomicBinOp->getExprLoc(); 4880 ErrorRange = AtomicBinOp->getSourceRange(); 4881 NoteLoc = NotScalarExpr->getExprLoc(); 4882 NoteRange = NotScalarExpr->getSourceRange(); 4883 } 4884 } else if (!AtomicBody->isInstantiationDependent()) { 4885 ErrorFound = NotAnAssignmentOp; 4886 ErrorLoc = AtomicBody->getExprLoc(); 4887 ErrorRange = AtomicBody->getSourceRange(); 4888 NoteLoc = AtomicBinOp ? AtomicBinOp->getOperatorLoc() 4889 : AtomicBody->getExprLoc(); 4890 NoteRange = AtomicBinOp ? AtomicBinOp->getSourceRange() 4891 : AtomicBody->getSourceRange(); 4892 } 4893 } else { 4894 ErrorFound = NotAnExpression; 4895 NoteLoc = ErrorLoc = Body->getLocStart(); 4896 NoteRange = ErrorRange = SourceRange(NoteLoc, NoteLoc); 4897 } 4898 if (ErrorFound != NoError) { 4899 Diag(ErrorLoc, diag::err_omp_atomic_write_not_expression_statement) 4900 << ErrorRange; 4901 Diag(NoteLoc, diag::note_omp_atomic_read_write) << ErrorFound 4902 << NoteRange; 4903 return StmtError(); 4904 } else if (CurContext->isDependentContext()) 4905 E = X = nullptr; 4906 } else if (AtomicKind == OMPC_update || AtomicKind == OMPC_unknown) { 4907 // If clause is update: 4908 // x++; 4909 // x--; 4910 // ++x; 4911 // --x; 4912 // x binop= expr; 4913 // x = x binop expr; 4914 // x = expr binop x; 4915 OpenMPAtomicUpdateChecker Checker(*this); 4916 if (Checker.checkStatement( 4917 Body, (AtomicKind == OMPC_update) 4918 ? diag::err_omp_atomic_update_not_expression_statement 4919 : diag::err_omp_atomic_not_expression_statement, 4920 diag::note_omp_atomic_update)) 4921 return StmtError(); 4922 if (!CurContext->isDependentContext()) { 4923 E = Checker.getExpr(); 4924 X = Checker.getX(); 4925 UE = Checker.getUpdateExpr(); 4926 IsXLHSInRHSPart = Checker.isXLHSInRHSPart(); 4927 } 4928 } else if (AtomicKind == OMPC_capture) { 4929 enum { 4930 NotAnAssignmentOp, 4931 NotACompoundStatement, 4932 NotTwoSubstatements, 4933 NotASpecificExpression, 4934 NoError 4935 } ErrorFound = NoError; 4936 SourceLocation ErrorLoc, NoteLoc; 4937 SourceRange ErrorRange, NoteRange; 4938 if (auto *AtomicBody = dyn_cast<Expr>(Body)) { 4939 // If clause is a capture: 4940 // v = x++; 4941 // v = x--; 4942 // v = ++x; 4943 // v = --x; 4944 // v = x binop= expr; 4945 // v = x = x binop expr; 4946 // v = x = expr binop x; 4947 auto *AtomicBinOp = 4948 dyn_cast<BinaryOperator>(AtomicBody->IgnoreParenImpCasts()); 4949 if (AtomicBinOp && AtomicBinOp->getOpcode() == BO_Assign) { 4950 V = AtomicBinOp->getLHS(); 4951 Body = AtomicBinOp->getRHS()->IgnoreParenImpCasts(); 4952 OpenMPAtomicUpdateChecker Checker(*this); 4953 if (Checker.checkStatement( 4954 Body, diag::err_omp_atomic_capture_not_expression_statement, 4955 diag::note_omp_atomic_update)) 4956 return StmtError(); 4957 E = Checker.getExpr(); 4958 X = Checker.getX(); 4959 UE = Checker.getUpdateExpr(); 4960 IsXLHSInRHSPart = Checker.isXLHSInRHSPart(); 4961 IsPostfixUpdate = Checker.isPostfixUpdate(); 4962 } else if (!AtomicBody->isInstantiationDependent()) { 4963 ErrorLoc = AtomicBody->getExprLoc(); 4964 ErrorRange = AtomicBody->getSourceRange(); 4965 NoteLoc = AtomicBinOp ? AtomicBinOp->getOperatorLoc() 4966 : AtomicBody->getExprLoc(); 4967 NoteRange = AtomicBinOp ? AtomicBinOp->getSourceRange() 4968 : AtomicBody->getSourceRange(); 4969 ErrorFound = NotAnAssignmentOp; 4970 } 4971 if (ErrorFound != NoError) { 4972 Diag(ErrorLoc, diag::err_omp_atomic_capture_not_expression_statement) 4973 << ErrorRange; 4974 Diag(NoteLoc, diag::note_omp_atomic_capture) << ErrorFound << NoteRange; 4975 return StmtError(); 4976 } else if (CurContext->isDependentContext()) { 4977 UE = V = E = X = nullptr; 4978 } 4979 } else { 4980 // If clause is a capture: 4981 // { v = x; x = expr; } 4982 // { v = x; x++; } 4983 // { v = x; x--; } 4984 // { v = x; ++x; } 4985 // { v = x; --x; } 4986 // { v = x; x binop= expr; } 4987 // { v = x; x = x binop expr; } 4988 // { v = x; x = expr binop x; } 4989 // { x++; v = x; } 4990 // { x--; v = x; } 4991 // { ++x; v = x; } 4992 // { --x; v = x; } 4993 // { x binop= expr; v = x; } 4994 // { x = x binop expr; v = x; } 4995 // { x = expr binop x; v = x; } 4996 if (auto *CS = dyn_cast<CompoundStmt>(Body)) { 4997 // Check that this is { expr1; expr2; } 4998 if (CS->size() == 2) { 4999 auto *First = CS->body_front(); 5000 auto *Second = CS->body_back(); 5001 if (auto *EWC = dyn_cast<ExprWithCleanups>(First)) 5002 First = EWC->getSubExpr()->IgnoreParenImpCasts(); 5003 if (auto *EWC = dyn_cast<ExprWithCleanups>(Second)) 5004 Second = EWC->getSubExpr()->IgnoreParenImpCasts(); 5005 // Need to find what subexpression is 'v' and what is 'x'. 5006 OpenMPAtomicUpdateChecker Checker(*this); 5007 bool IsUpdateExprFound = !Checker.checkStatement(Second); 5008 BinaryOperator *BinOp = nullptr; 5009 if (IsUpdateExprFound) { 5010 BinOp = dyn_cast<BinaryOperator>(First); 5011 IsUpdateExprFound = BinOp && BinOp->getOpcode() == BO_Assign; 5012 } 5013 if (IsUpdateExprFound && !CurContext->isDependentContext()) { 5014 // { v = x; x++; } 5015 // { v = x; x--; } 5016 // { v = x; ++x; } 5017 // { v = x; --x; } 5018 // { v = x; x binop= expr; } 5019 // { v = x; x = x binop expr; } 5020 // { v = x; x = expr binop x; } 5021 // Check that the first expression has form v = x. 5022 auto *PossibleX = BinOp->getRHS()->IgnoreParenImpCasts(); 5023 llvm::FoldingSetNodeID XId, PossibleXId; 5024 Checker.getX()->Profile(XId, Context, /*Canonical=*/true); 5025 PossibleX->Profile(PossibleXId, Context, /*Canonical=*/true); 5026 IsUpdateExprFound = XId == PossibleXId; 5027 if (IsUpdateExprFound) { 5028 V = BinOp->getLHS(); 5029 X = Checker.getX(); 5030 E = Checker.getExpr(); 5031 UE = Checker.getUpdateExpr(); 5032 IsXLHSInRHSPart = Checker.isXLHSInRHSPart(); 5033 IsPostfixUpdate = true; 5034 } 5035 } 5036 if (!IsUpdateExprFound) { 5037 IsUpdateExprFound = !Checker.checkStatement(First); 5038 BinOp = nullptr; 5039 if (IsUpdateExprFound) { 5040 BinOp = dyn_cast<BinaryOperator>(Second); 5041 IsUpdateExprFound = BinOp && BinOp->getOpcode() == BO_Assign; 5042 } 5043 if (IsUpdateExprFound && !CurContext->isDependentContext()) { 5044 // { x++; v = x; } 5045 // { x--; v = x; } 5046 // { ++x; v = x; } 5047 // { --x; v = x; } 5048 // { x binop= expr; v = x; } 5049 // { x = x binop expr; v = x; } 5050 // { x = expr binop x; v = x; } 5051 // Check that the second expression has form v = x. 5052 auto *PossibleX = BinOp->getRHS()->IgnoreParenImpCasts(); 5053 llvm::FoldingSetNodeID XId, PossibleXId; 5054 Checker.getX()->Profile(XId, Context, /*Canonical=*/true); 5055 PossibleX->Profile(PossibleXId, Context, /*Canonical=*/true); 5056 IsUpdateExprFound = XId == PossibleXId; 5057 if (IsUpdateExprFound) { 5058 V = BinOp->getLHS(); 5059 X = Checker.getX(); 5060 E = Checker.getExpr(); 5061 UE = Checker.getUpdateExpr(); 5062 IsXLHSInRHSPart = Checker.isXLHSInRHSPart(); 5063 IsPostfixUpdate = false; 5064 } 5065 } 5066 } 5067 if (!IsUpdateExprFound) { 5068 // { v = x; x = expr; } 5069 auto *FirstExpr = dyn_cast<Expr>(First); 5070 auto *SecondExpr = dyn_cast<Expr>(Second); 5071 if (!FirstExpr || !SecondExpr || 5072 !(FirstExpr->isInstantiationDependent() || 5073 SecondExpr->isInstantiationDependent())) { 5074 auto *FirstBinOp = dyn_cast<BinaryOperator>(First); 5075 if (!FirstBinOp || FirstBinOp->getOpcode() != BO_Assign) { 5076 ErrorFound = NotAnAssignmentOp; 5077 NoteLoc = ErrorLoc = FirstBinOp ? FirstBinOp->getOperatorLoc() 5078 : First->getLocStart(); 5079 NoteRange = ErrorRange = FirstBinOp 5080 ? FirstBinOp->getSourceRange() 5081 : SourceRange(ErrorLoc, ErrorLoc); 5082 } else { 5083 auto *SecondBinOp = dyn_cast<BinaryOperator>(Second); 5084 if (!SecondBinOp || SecondBinOp->getOpcode() != BO_Assign) { 5085 ErrorFound = NotAnAssignmentOp; 5086 NoteLoc = ErrorLoc = SecondBinOp 5087 ? SecondBinOp->getOperatorLoc() 5088 : Second->getLocStart(); 5089 NoteRange = ErrorRange = 5090 SecondBinOp ? SecondBinOp->getSourceRange() 5091 : SourceRange(ErrorLoc, ErrorLoc); 5092 } else { 5093 auto *PossibleXRHSInFirst = 5094 FirstBinOp->getRHS()->IgnoreParenImpCasts(); 5095 auto *PossibleXLHSInSecond = 5096 SecondBinOp->getLHS()->IgnoreParenImpCasts(); 5097 llvm::FoldingSetNodeID X1Id, X2Id; 5098 PossibleXRHSInFirst->Profile(X1Id, Context, 5099 /*Canonical=*/true); 5100 PossibleXLHSInSecond->Profile(X2Id, Context, 5101 /*Canonical=*/true); 5102 IsUpdateExprFound = X1Id == X2Id; 5103 if (IsUpdateExprFound) { 5104 V = FirstBinOp->getLHS(); 5105 X = SecondBinOp->getLHS(); 5106 E = SecondBinOp->getRHS(); 5107 UE = nullptr; 5108 IsXLHSInRHSPart = false; 5109 IsPostfixUpdate = true; 5110 } else { 5111 ErrorFound = NotASpecificExpression; 5112 ErrorLoc = FirstBinOp->getExprLoc(); 5113 ErrorRange = FirstBinOp->getSourceRange(); 5114 NoteLoc = SecondBinOp->getLHS()->getExprLoc(); 5115 NoteRange = SecondBinOp->getRHS()->getSourceRange(); 5116 } 5117 } 5118 } 5119 } 5120 } 5121 } else { 5122 NoteLoc = ErrorLoc = Body->getLocStart(); 5123 NoteRange = ErrorRange = 5124 SourceRange(Body->getLocStart(), Body->getLocStart()); 5125 ErrorFound = NotTwoSubstatements; 5126 } 5127 } else { 5128 NoteLoc = ErrorLoc = Body->getLocStart(); 5129 NoteRange = ErrorRange = 5130 SourceRange(Body->getLocStart(), Body->getLocStart()); 5131 ErrorFound = NotACompoundStatement; 5132 } 5133 if (ErrorFound != NoError) { 5134 Diag(ErrorLoc, diag::err_omp_atomic_capture_not_compound_statement) 5135 << ErrorRange; 5136 Diag(NoteLoc, diag::note_omp_atomic_capture) << ErrorFound << NoteRange; 5137 return StmtError(); 5138 } else if (CurContext->isDependentContext()) { 5139 UE = V = E = X = nullptr; 5140 } 5141 } 5142 } 5143 5144 getCurFunction()->setHasBranchProtectedScope(); 5145 5146 return OMPAtomicDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt, 5147 X, V, E, UE, IsXLHSInRHSPart, 5148 IsPostfixUpdate); 5149 } 5150 5151 StmtResult Sema::ActOnOpenMPTargetDirective(ArrayRef<OMPClause *> Clauses, 5152 Stmt *AStmt, 5153 SourceLocation StartLoc, 5154 SourceLocation EndLoc) { 5155 if (!AStmt) 5156 return StmtError(); 5157 5158 CapturedStmt *CS = cast<CapturedStmt>(AStmt); 5159 // 1.2.2 OpenMP Language Terminology 5160 // Structured block - An executable statement with a single entry at the 5161 // top and a single exit at the bottom. 5162 // The point of exit cannot be a branch out of the structured block. 5163 // longjmp() and throw() must not violate the entry/exit criteria. 5164 CS->getCapturedDecl()->setNothrow(); 5165 5166 // OpenMP [2.16, Nesting of Regions] 5167 // If specified, a teams construct must be contained within a target 5168 // construct. That target construct must contain no statements or directives 5169 // outside of the teams construct. 5170 if (DSAStack->hasInnerTeamsRegion()) { 5171 auto S = AStmt->IgnoreContainers(/*IgnoreCaptured*/ true); 5172 bool OMPTeamsFound = true; 5173 if (auto *CS = dyn_cast<CompoundStmt>(S)) { 5174 auto I = CS->body_begin(); 5175 while (I != CS->body_end()) { 5176 auto OED = dyn_cast<OMPExecutableDirective>(*I); 5177 if (!OED || !isOpenMPTeamsDirective(OED->getDirectiveKind())) { 5178 OMPTeamsFound = false; 5179 break; 5180 } 5181 ++I; 5182 } 5183 assert(I != CS->body_end() && "Not found statement"); 5184 S = *I; 5185 } 5186 if (!OMPTeamsFound) { 5187 Diag(StartLoc, diag::err_omp_target_contains_not_only_teams); 5188 Diag(DSAStack->getInnerTeamsRegionLoc(), 5189 diag::note_omp_nested_teams_construct_here); 5190 Diag(S->getLocStart(), diag::note_omp_nested_statement_here) 5191 << isa<OMPExecutableDirective>(S); 5192 return StmtError(); 5193 } 5194 } 5195 5196 getCurFunction()->setHasBranchProtectedScope(); 5197 5198 return OMPTargetDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt); 5199 } 5200 5201 StmtResult Sema::ActOnOpenMPTargetDataDirective(ArrayRef<OMPClause *> Clauses, 5202 Stmt *AStmt, 5203 SourceLocation StartLoc, 5204 SourceLocation EndLoc) { 5205 if (!AStmt) 5206 return StmtError(); 5207 5208 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected"); 5209 5210 getCurFunction()->setHasBranchProtectedScope(); 5211 5212 return OMPTargetDataDirective::Create(Context, StartLoc, EndLoc, Clauses, 5213 AStmt); 5214 } 5215 5216 StmtResult Sema::ActOnOpenMPTeamsDirective(ArrayRef<OMPClause *> Clauses, 5217 Stmt *AStmt, SourceLocation StartLoc, 5218 SourceLocation EndLoc) { 5219 if (!AStmt) 5220 return StmtError(); 5221 5222 CapturedStmt *CS = cast<CapturedStmt>(AStmt); 5223 // 1.2.2 OpenMP Language Terminology 5224 // Structured block - An executable statement with a single entry at the 5225 // top and a single exit at the bottom. 5226 // The point of exit cannot be a branch out of the structured block. 5227 // longjmp() and throw() must not violate the entry/exit criteria. 5228 CS->getCapturedDecl()->setNothrow(); 5229 5230 getCurFunction()->setHasBranchProtectedScope(); 5231 5232 return OMPTeamsDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt); 5233 } 5234 5235 StmtResult 5236 Sema::ActOnOpenMPCancellationPointDirective(SourceLocation StartLoc, 5237 SourceLocation EndLoc, 5238 OpenMPDirectiveKind CancelRegion) { 5239 if (CancelRegion != OMPD_parallel && CancelRegion != OMPD_for && 5240 CancelRegion != OMPD_sections && CancelRegion != OMPD_taskgroup) { 5241 Diag(StartLoc, diag::err_omp_wrong_cancel_region) 5242 << getOpenMPDirectiveName(CancelRegion); 5243 return StmtError(); 5244 } 5245 if (DSAStack->isParentNowaitRegion()) { 5246 Diag(StartLoc, diag::err_omp_parent_cancel_region_nowait) << 0; 5247 return StmtError(); 5248 } 5249 if (DSAStack->isParentOrderedRegion()) { 5250 Diag(StartLoc, diag::err_omp_parent_cancel_region_ordered) << 0; 5251 return StmtError(); 5252 } 5253 return OMPCancellationPointDirective::Create(Context, StartLoc, EndLoc, 5254 CancelRegion); 5255 } 5256 5257 StmtResult Sema::ActOnOpenMPCancelDirective(ArrayRef<OMPClause *> Clauses, 5258 SourceLocation StartLoc, 5259 SourceLocation EndLoc, 5260 OpenMPDirectiveKind CancelRegion) { 5261 if (CancelRegion != OMPD_parallel && CancelRegion != OMPD_for && 5262 CancelRegion != OMPD_sections && CancelRegion != OMPD_taskgroup) { 5263 Diag(StartLoc, diag::err_omp_wrong_cancel_region) 5264 << getOpenMPDirectiveName(CancelRegion); 5265 return StmtError(); 5266 } 5267 if (DSAStack->isParentNowaitRegion()) { 5268 Diag(StartLoc, diag::err_omp_parent_cancel_region_nowait) << 1; 5269 return StmtError(); 5270 } 5271 if (DSAStack->isParentOrderedRegion()) { 5272 Diag(StartLoc, diag::err_omp_parent_cancel_region_ordered) << 1; 5273 return StmtError(); 5274 } 5275 DSAStack->setParentCancelRegion(/*Cancel=*/true); 5276 return OMPCancelDirective::Create(Context, StartLoc, EndLoc, Clauses, 5277 CancelRegion); 5278 } 5279 5280 static bool checkGrainsizeNumTasksClauses(Sema &S, 5281 ArrayRef<OMPClause *> Clauses) { 5282 OMPClause *PrevClause = nullptr; 5283 bool ErrorFound = false; 5284 for (auto *C : Clauses) { 5285 if (C->getClauseKind() == OMPC_grainsize || 5286 C->getClauseKind() == OMPC_num_tasks) { 5287 if (!PrevClause) 5288 PrevClause = C; 5289 else if (PrevClause->getClauseKind() != C->getClauseKind()) { 5290 S.Diag(C->getLocStart(), 5291 diag::err_omp_grainsize_num_tasks_mutually_exclusive) 5292 << getOpenMPClauseName(C->getClauseKind()) 5293 << getOpenMPClauseName(PrevClause->getClauseKind()); 5294 S.Diag(PrevClause->getLocStart(), 5295 diag::note_omp_previous_grainsize_num_tasks) 5296 << getOpenMPClauseName(PrevClause->getClauseKind()); 5297 ErrorFound = true; 5298 } 5299 } 5300 } 5301 return ErrorFound; 5302 } 5303 5304 StmtResult Sema::ActOnOpenMPTaskLoopDirective( 5305 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, 5306 SourceLocation EndLoc, 5307 llvm::DenseMap<VarDecl *, Expr *> &VarsWithImplicitDSA) { 5308 if (!AStmt) 5309 return StmtError(); 5310 5311 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected"); 5312 OMPLoopDirective::HelperExprs B; 5313 // In presence of clause 'collapse' or 'ordered' with number of loops, it will 5314 // define the nested loops number. 5315 unsigned NestedLoopCount = 5316 CheckOpenMPLoop(OMPD_taskloop, getCollapseNumberExpr(Clauses), 5317 /*OrderedLoopCountExpr=*/nullptr, AStmt, *this, *DSAStack, 5318 VarsWithImplicitDSA, B); 5319 if (NestedLoopCount == 0) 5320 return StmtError(); 5321 5322 assert((CurContext->isDependentContext() || B.builtAll()) && 5323 "omp for loop exprs were not built"); 5324 5325 // OpenMP, [2.9.2 taskloop Construct, Restrictions] 5326 // The grainsize clause and num_tasks clause are mutually exclusive and may 5327 // not appear on the same taskloop directive. 5328 if (checkGrainsizeNumTasksClauses(*this, Clauses)) 5329 return StmtError(); 5330 5331 getCurFunction()->setHasBranchProtectedScope(); 5332 return OMPTaskLoopDirective::Create(Context, StartLoc, EndLoc, 5333 NestedLoopCount, Clauses, AStmt, B); 5334 } 5335 5336 StmtResult Sema::ActOnOpenMPTaskLoopSimdDirective( 5337 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, 5338 SourceLocation EndLoc, 5339 llvm::DenseMap<VarDecl *, Expr *> &VarsWithImplicitDSA) { 5340 if (!AStmt) 5341 return StmtError(); 5342 5343 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected"); 5344 OMPLoopDirective::HelperExprs B; 5345 // In presence of clause 'collapse' or 'ordered' with number of loops, it will 5346 // define the nested loops number. 5347 unsigned NestedLoopCount = 5348 CheckOpenMPLoop(OMPD_taskloop_simd, getCollapseNumberExpr(Clauses), 5349 /*OrderedLoopCountExpr=*/nullptr, AStmt, *this, *DSAStack, 5350 VarsWithImplicitDSA, B); 5351 if (NestedLoopCount == 0) 5352 return StmtError(); 5353 5354 assert((CurContext->isDependentContext() || B.builtAll()) && 5355 "omp for loop exprs were not built"); 5356 5357 // OpenMP, [2.9.2 taskloop Construct, Restrictions] 5358 // The grainsize clause and num_tasks clause are mutually exclusive and may 5359 // not appear on the same taskloop directive. 5360 if (checkGrainsizeNumTasksClauses(*this, Clauses)) 5361 return StmtError(); 5362 5363 getCurFunction()->setHasBranchProtectedScope(); 5364 return OMPTaskLoopSimdDirective::Create(Context, StartLoc, EndLoc, 5365 NestedLoopCount, Clauses, AStmt, B); 5366 } 5367 5368 OMPClause *Sema::ActOnOpenMPSingleExprClause(OpenMPClauseKind Kind, Expr *Expr, 5369 SourceLocation StartLoc, 5370 SourceLocation LParenLoc, 5371 SourceLocation EndLoc) { 5372 OMPClause *Res = nullptr; 5373 switch (Kind) { 5374 case OMPC_final: 5375 Res = ActOnOpenMPFinalClause(Expr, StartLoc, LParenLoc, EndLoc); 5376 break; 5377 case OMPC_num_threads: 5378 Res = ActOnOpenMPNumThreadsClause(Expr, StartLoc, LParenLoc, EndLoc); 5379 break; 5380 case OMPC_safelen: 5381 Res = ActOnOpenMPSafelenClause(Expr, StartLoc, LParenLoc, EndLoc); 5382 break; 5383 case OMPC_simdlen: 5384 Res = ActOnOpenMPSimdlenClause(Expr, StartLoc, LParenLoc, EndLoc); 5385 break; 5386 case OMPC_collapse: 5387 Res = ActOnOpenMPCollapseClause(Expr, StartLoc, LParenLoc, EndLoc); 5388 break; 5389 case OMPC_ordered: 5390 Res = ActOnOpenMPOrderedClause(StartLoc, EndLoc, LParenLoc, Expr); 5391 break; 5392 case OMPC_device: 5393 Res = ActOnOpenMPDeviceClause(Expr, StartLoc, LParenLoc, EndLoc); 5394 break; 5395 case OMPC_num_teams: 5396 Res = ActOnOpenMPNumTeamsClause(Expr, StartLoc, LParenLoc, EndLoc); 5397 break; 5398 case OMPC_thread_limit: 5399 Res = ActOnOpenMPThreadLimitClause(Expr, StartLoc, LParenLoc, EndLoc); 5400 break; 5401 case OMPC_priority: 5402 Res = ActOnOpenMPPriorityClause(Expr, StartLoc, LParenLoc, EndLoc); 5403 break; 5404 case OMPC_grainsize: 5405 Res = ActOnOpenMPGrainsizeClause(Expr, StartLoc, LParenLoc, EndLoc); 5406 break; 5407 case OMPC_num_tasks: 5408 Res = ActOnOpenMPNumTasksClause(Expr, StartLoc, LParenLoc, EndLoc); 5409 break; 5410 case OMPC_if: 5411 case OMPC_default: 5412 case OMPC_proc_bind: 5413 case OMPC_schedule: 5414 case OMPC_private: 5415 case OMPC_firstprivate: 5416 case OMPC_lastprivate: 5417 case OMPC_shared: 5418 case OMPC_reduction: 5419 case OMPC_linear: 5420 case OMPC_aligned: 5421 case OMPC_copyin: 5422 case OMPC_copyprivate: 5423 case OMPC_nowait: 5424 case OMPC_untied: 5425 case OMPC_mergeable: 5426 case OMPC_threadprivate: 5427 case OMPC_flush: 5428 case OMPC_read: 5429 case OMPC_write: 5430 case OMPC_update: 5431 case OMPC_capture: 5432 case OMPC_seq_cst: 5433 case OMPC_depend: 5434 case OMPC_threads: 5435 case OMPC_simd: 5436 case OMPC_map: 5437 case OMPC_nogroup: 5438 case OMPC_unknown: 5439 llvm_unreachable("Clause is not allowed."); 5440 } 5441 return Res; 5442 } 5443 5444 OMPClause *Sema::ActOnOpenMPIfClause(OpenMPDirectiveKind NameModifier, 5445 Expr *Condition, SourceLocation StartLoc, 5446 SourceLocation LParenLoc, 5447 SourceLocation NameModifierLoc, 5448 SourceLocation ColonLoc, 5449 SourceLocation EndLoc) { 5450 Expr *ValExpr = Condition; 5451 if (!Condition->isValueDependent() && !Condition->isTypeDependent() && 5452 !Condition->isInstantiationDependent() && 5453 !Condition->containsUnexpandedParameterPack()) { 5454 ExprResult Val = ActOnBooleanCondition(DSAStack->getCurScope(), 5455 Condition->getExprLoc(), Condition); 5456 if (Val.isInvalid()) 5457 return nullptr; 5458 5459 ValExpr = Val.get(); 5460 } 5461 5462 return new (Context) OMPIfClause(NameModifier, ValExpr, StartLoc, LParenLoc, 5463 NameModifierLoc, ColonLoc, EndLoc); 5464 } 5465 5466 OMPClause *Sema::ActOnOpenMPFinalClause(Expr *Condition, 5467 SourceLocation StartLoc, 5468 SourceLocation LParenLoc, 5469 SourceLocation EndLoc) { 5470 Expr *ValExpr = Condition; 5471 if (!Condition->isValueDependent() && !Condition->isTypeDependent() && 5472 !Condition->isInstantiationDependent() && 5473 !Condition->containsUnexpandedParameterPack()) { 5474 ExprResult Val = ActOnBooleanCondition(DSAStack->getCurScope(), 5475 Condition->getExprLoc(), Condition); 5476 if (Val.isInvalid()) 5477 return nullptr; 5478 5479 ValExpr = Val.get(); 5480 } 5481 5482 return new (Context) OMPFinalClause(ValExpr, StartLoc, LParenLoc, EndLoc); 5483 } 5484 ExprResult Sema::PerformOpenMPImplicitIntegerConversion(SourceLocation Loc, 5485 Expr *Op) { 5486 if (!Op) 5487 return ExprError(); 5488 5489 class IntConvertDiagnoser : public ICEConvertDiagnoser { 5490 public: 5491 IntConvertDiagnoser() 5492 : ICEConvertDiagnoser(/*AllowScopedEnumerations*/ false, false, true) {} 5493 SemaDiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc, 5494 QualType T) override { 5495 return S.Diag(Loc, diag::err_omp_not_integral) << T; 5496 } 5497 SemaDiagnosticBuilder diagnoseIncomplete(Sema &S, SourceLocation Loc, 5498 QualType T) override { 5499 return S.Diag(Loc, diag::err_omp_incomplete_type) << T; 5500 } 5501 SemaDiagnosticBuilder diagnoseExplicitConv(Sema &S, SourceLocation Loc, 5502 QualType T, 5503 QualType ConvTy) override { 5504 return S.Diag(Loc, diag::err_omp_explicit_conversion) << T << ConvTy; 5505 } 5506 SemaDiagnosticBuilder noteExplicitConv(Sema &S, CXXConversionDecl *Conv, 5507 QualType ConvTy) override { 5508 return S.Diag(Conv->getLocation(), diag::note_omp_conversion_here) 5509 << ConvTy->isEnumeralType() << ConvTy; 5510 } 5511 SemaDiagnosticBuilder diagnoseAmbiguous(Sema &S, SourceLocation Loc, 5512 QualType T) override { 5513 return S.Diag(Loc, diag::err_omp_ambiguous_conversion) << T; 5514 } 5515 SemaDiagnosticBuilder noteAmbiguous(Sema &S, CXXConversionDecl *Conv, 5516 QualType ConvTy) override { 5517 return S.Diag(Conv->getLocation(), diag::note_omp_conversion_here) 5518 << ConvTy->isEnumeralType() << ConvTy; 5519 } 5520 SemaDiagnosticBuilder diagnoseConversion(Sema &, SourceLocation, QualType, 5521 QualType) override { 5522 llvm_unreachable("conversion functions are permitted"); 5523 } 5524 } ConvertDiagnoser; 5525 return PerformContextualImplicitConversion(Loc, Op, ConvertDiagnoser); 5526 } 5527 5528 static bool IsNonNegativeIntegerValue(Expr *&ValExpr, Sema &SemaRef, 5529 OpenMPClauseKind CKind, 5530 bool StrictlyPositive) { 5531 if (!ValExpr->isTypeDependent() && !ValExpr->isValueDependent() && 5532 !ValExpr->isInstantiationDependent()) { 5533 SourceLocation Loc = ValExpr->getExprLoc(); 5534 ExprResult Value = 5535 SemaRef.PerformOpenMPImplicitIntegerConversion(Loc, ValExpr); 5536 if (Value.isInvalid()) 5537 return false; 5538 5539 ValExpr = Value.get(); 5540 // The expression must evaluate to a non-negative integer value. 5541 llvm::APSInt Result; 5542 if (ValExpr->isIntegerConstantExpr(Result, SemaRef.Context) && 5543 Result.isSigned() && 5544 !((!StrictlyPositive && Result.isNonNegative()) || 5545 (StrictlyPositive && Result.isStrictlyPositive()))) { 5546 SemaRef.Diag(Loc, diag::err_omp_negative_expression_in_clause) 5547 << getOpenMPClauseName(CKind) << (StrictlyPositive ? 1 : 0) 5548 << ValExpr->getSourceRange(); 5549 return false; 5550 } 5551 } 5552 return true; 5553 } 5554 5555 OMPClause *Sema::ActOnOpenMPNumThreadsClause(Expr *NumThreads, 5556 SourceLocation StartLoc, 5557 SourceLocation LParenLoc, 5558 SourceLocation EndLoc) { 5559 Expr *ValExpr = NumThreads; 5560 5561 // OpenMP [2.5, Restrictions] 5562 // The num_threads expression must evaluate to a positive integer value. 5563 if (!IsNonNegativeIntegerValue(ValExpr, *this, OMPC_num_threads, 5564 /*StrictlyPositive=*/true)) 5565 return nullptr; 5566 5567 return new (Context) 5568 OMPNumThreadsClause(ValExpr, StartLoc, LParenLoc, EndLoc); 5569 } 5570 5571 ExprResult Sema::VerifyPositiveIntegerConstantInClause(Expr *E, 5572 OpenMPClauseKind CKind) { 5573 if (!E) 5574 return ExprError(); 5575 if (E->isValueDependent() || E->isTypeDependent() || 5576 E->isInstantiationDependent() || E->containsUnexpandedParameterPack()) 5577 return E; 5578 llvm::APSInt Result; 5579 ExprResult ICE = VerifyIntegerConstantExpression(E, &Result); 5580 if (ICE.isInvalid()) 5581 return ExprError(); 5582 if (!Result.isStrictlyPositive()) { 5583 Diag(E->getExprLoc(), diag::err_omp_negative_expression_in_clause) 5584 << getOpenMPClauseName(CKind) << 1 << E->getSourceRange(); 5585 return ExprError(); 5586 } 5587 if (CKind == OMPC_aligned && !Result.isPowerOf2()) { 5588 Diag(E->getExprLoc(), diag::warn_omp_alignment_not_power_of_two) 5589 << E->getSourceRange(); 5590 return ExprError(); 5591 } 5592 if (CKind == OMPC_collapse) 5593 DSAStack->setCollapseNumber(Result.getExtValue()); 5594 else if (CKind == OMPC_ordered) 5595 DSAStack->setCollapseNumber(Result.getExtValue()); 5596 return ICE; 5597 } 5598 5599 OMPClause *Sema::ActOnOpenMPSafelenClause(Expr *Len, SourceLocation StartLoc, 5600 SourceLocation LParenLoc, 5601 SourceLocation EndLoc) { 5602 // OpenMP [2.8.1, simd construct, Description] 5603 // The parameter of the safelen clause must be a constant 5604 // positive integer expression. 5605 ExprResult Safelen = VerifyPositiveIntegerConstantInClause(Len, OMPC_safelen); 5606 if (Safelen.isInvalid()) 5607 return nullptr; 5608 return new (Context) 5609 OMPSafelenClause(Safelen.get(), StartLoc, LParenLoc, EndLoc); 5610 } 5611 5612 OMPClause *Sema::ActOnOpenMPSimdlenClause(Expr *Len, SourceLocation StartLoc, 5613 SourceLocation LParenLoc, 5614 SourceLocation EndLoc) { 5615 // OpenMP [2.8.1, simd construct, Description] 5616 // The parameter of the simdlen clause must be a constant 5617 // positive integer expression. 5618 ExprResult Simdlen = VerifyPositiveIntegerConstantInClause(Len, OMPC_simdlen); 5619 if (Simdlen.isInvalid()) 5620 return nullptr; 5621 return new (Context) 5622 OMPSimdlenClause(Simdlen.get(), StartLoc, LParenLoc, EndLoc); 5623 } 5624 5625 OMPClause *Sema::ActOnOpenMPCollapseClause(Expr *NumForLoops, 5626 SourceLocation StartLoc, 5627 SourceLocation LParenLoc, 5628 SourceLocation EndLoc) { 5629 // OpenMP [2.7.1, loop construct, Description] 5630 // OpenMP [2.8.1, simd construct, Description] 5631 // OpenMP [2.9.6, distribute construct, Description] 5632 // The parameter of the collapse clause must be a constant 5633 // positive integer expression. 5634 ExprResult NumForLoopsResult = 5635 VerifyPositiveIntegerConstantInClause(NumForLoops, OMPC_collapse); 5636 if (NumForLoopsResult.isInvalid()) 5637 return nullptr; 5638 return new (Context) 5639 OMPCollapseClause(NumForLoopsResult.get(), StartLoc, LParenLoc, EndLoc); 5640 } 5641 5642 OMPClause *Sema::ActOnOpenMPOrderedClause(SourceLocation StartLoc, 5643 SourceLocation EndLoc, 5644 SourceLocation LParenLoc, 5645 Expr *NumForLoops) { 5646 // OpenMP [2.7.1, loop construct, Description] 5647 // OpenMP [2.8.1, simd construct, Description] 5648 // OpenMP [2.9.6, distribute construct, Description] 5649 // The parameter of the ordered clause must be a constant 5650 // positive integer expression if any. 5651 if (NumForLoops && LParenLoc.isValid()) { 5652 ExprResult NumForLoopsResult = 5653 VerifyPositiveIntegerConstantInClause(NumForLoops, OMPC_ordered); 5654 if (NumForLoopsResult.isInvalid()) 5655 return nullptr; 5656 NumForLoops = NumForLoopsResult.get(); 5657 } else 5658 NumForLoops = nullptr; 5659 DSAStack->setOrderedRegion(/*IsOrdered=*/true, NumForLoops); 5660 return new (Context) 5661 OMPOrderedClause(NumForLoops, StartLoc, LParenLoc, EndLoc); 5662 } 5663 5664 OMPClause *Sema::ActOnOpenMPSimpleClause( 5665 OpenMPClauseKind Kind, unsigned Argument, SourceLocation ArgumentLoc, 5666 SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc) { 5667 OMPClause *Res = nullptr; 5668 switch (Kind) { 5669 case OMPC_default: 5670 Res = 5671 ActOnOpenMPDefaultClause(static_cast<OpenMPDefaultClauseKind>(Argument), 5672 ArgumentLoc, StartLoc, LParenLoc, EndLoc); 5673 break; 5674 case OMPC_proc_bind: 5675 Res = ActOnOpenMPProcBindClause( 5676 static_cast<OpenMPProcBindClauseKind>(Argument), ArgumentLoc, StartLoc, 5677 LParenLoc, EndLoc); 5678 break; 5679 case OMPC_if: 5680 case OMPC_final: 5681 case OMPC_num_threads: 5682 case OMPC_safelen: 5683 case OMPC_simdlen: 5684 case OMPC_collapse: 5685 case OMPC_schedule: 5686 case OMPC_private: 5687 case OMPC_firstprivate: 5688 case OMPC_lastprivate: 5689 case OMPC_shared: 5690 case OMPC_reduction: 5691 case OMPC_linear: 5692 case OMPC_aligned: 5693 case OMPC_copyin: 5694 case OMPC_copyprivate: 5695 case OMPC_ordered: 5696 case OMPC_nowait: 5697 case OMPC_untied: 5698 case OMPC_mergeable: 5699 case OMPC_threadprivate: 5700 case OMPC_flush: 5701 case OMPC_read: 5702 case OMPC_write: 5703 case OMPC_update: 5704 case OMPC_capture: 5705 case OMPC_seq_cst: 5706 case OMPC_depend: 5707 case OMPC_device: 5708 case OMPC_threads: 5709 case OMPC_simd: 5710 case OMPC_map: 5711 case OMPC_num_teams: 5712 case OMPC_thread_limit: 5713 case OMPC_priority: 5714 case OMPC_grainsize: 5715 case OMPC_nogroup: 5716 case OMPC_num_tasks: 5717 case OMPC_unknown: 5718 llvm_unreachable("Clause is not allowed."); 5719 } 5720 return Res; 5721 } 5722 5723 OMPClause *Sema::ActOnOpenMPDefaultClause(OpenMPDefaultClauseKind Kind, 5724 SourceLocation KindKwLoc, 5725 SourceLocation StartLoc, 5726 SourceLocation LParenLoc, 5727 SourceLocation EndLoc) { 5728 if (Kind == OMPC_DEFAULT_unknown) { 5729 std::string Values; 5730 static_assert(OMPC_DEFAULT_unknown > 0, 5731 "OMPC_DEFAULT_unknown not greater than 0"); 5732 std::string Sep(", "); 5733 for (unsigned i = 0; i < OMPC_DEFAULT_unknown; ++i) { 5734 Values += "'"; 5735 Values += getOpenMPSimpleClauseTypeName(OMPC_default, i); 5736 Values += "'"; 5737 switch (i) { 5738 case OMPC_DEFAULT_unknown - 2: 5739 Values += " or "; 5740 break; 5741 case OMPC_DEFAULT_unknown - 1: 5742 break; 5743 default: 5744 Values += Sep; 5745 break; 5746 } 5747 } 5748 Diag(KindKwLoc, diag::err_omp_unexpected_clause_value) 5749 << Values << getOpenMPClauseName(OMPC_default); 5750 return nullptr; 5751 } 5752 switch (Kind) { 5753 case OMPC_DEFAULT_none: 5754 DSAStack->setDefaultDSANone(KindKwLoc); 5755 break; 5756 case OMPC_DEFAULT_shared: 5757 DSAStack->setDefaultDSAShared(KindKwLoc); 5758 break; 5759 case OMPC_DEFAULT_unknown: 5760 llvm_unreachable("Clause kind is not allowed."); 5761 break; 5762 } 5763 return new (Context) 5764 OMPDefaultClause(Kind, KindKwLoc, StartLoc, LParenLoc, EndLoc); 5765 } 5766 5767 OMPClause *Sema::ActOnOpenMPProcBindClause(OpenMPProcBindClauseKind Kind, 5768 SourceLocation KindKwLoc, 5769 SourceLocation StartLoc, 5770 SourceLocation LParenLoc, 5771 SourceLocation EndLoc) { 5772 if (Kind == OMPC_PROC_BIND_unknown) { 5773 std::string Values; 5774 std::string Sep(", "); 5775 for (unsigned i = 0; i < OMPC_PROC_BIND_unknown; ++i) { 5776 Values += "'"; 5777 Values += getOpenMPSimpleClauseTypeName(OMPC_proc_bind, i); 5778 Values += "'"; 5779 switch (i) { 5780 case OMPC_PROC_BIND_unknown - 2: 5781 Values += " or "; 5782 break; 5783 case OMPC_PROC_BIND_unknown - 1: 5784 break; 5785 default: 5786 Values += Sep; 5787 break; 5788 } 5789 } 5790 Diag(KindKwLoc, diag::err_omp_unexpected_clause_value) 5791 << Values << getOpenMPClauseName(OMPC_proc_bind); 5792 return nullptr; 5793 } 5794 return new (Context) 5795 OMPProcBindClause(Kind, KindKwLoc, StartLoc, LParenLoc, EndLoc); 5796 } 5797 5798 OMPClause *Sema::ActOnOpenMPSingleExprWithArgClause( 5799 OpenMPClauseKind Kind, unsigned Argument, Expr *Expr, 5800 SourceLocation StartLoc, SourceLocation LParenLoc, 5801 SourceLocation ArgumentLoc, SourceLocation DelimLoc, 5802 SourceLocation EndLoc) { 5803 OMPClause *Res = nullptr; 5804 switch (Kind) { 5805 case OMPC_schedule: 5806 Res = ActOnOpenMPScheduleClause( 5807 static_cast<OpenMPScheduleClauseKind>(Argument), Expr, StartLoc, 5808 LParenLoc, ArgumentLoc, DelimLoc, EndLoc); 5809 break; 5810 case OMPC_if: 5811 Res = 5812 ActOnOpenMPIfClause(static_cast<OpenMPDirectiveKind>(Argument), Expr, 5813 StartLoc, LParenLoc, ArgumentLoc, DelimLoc, EndLoc); 5814 break; 5815 case OMPC_final: 5816 case OMPC_num_threads: 5817 case OMPC_safelen: 5818 case OMPC_simdlen: 5819 case OMPC_collapse: 5820 case OMPC_default: 5821 case OMPC_proc_bind: 5822 case OMPC_private: 5823 case OMPC_firstprivate: 5824 case OMPC_lastprivate: 5825 case OMPC_shared: 5826 case OMPC_reduction: 5827 case OMPC_linear: 5828 case OMPC_aligned: 5829 case OMPC_copyin: 5830 case OMPC_copyprivate: 5831 case OMPC_ordered: 5832 case OMPC_nowait: 5833 case OMPC_untied: 5834 case OMPC_mergeable: 5835 case OMPC_threadprivate: 5836 case OMPC_flush: 5837 case OMPC_read: 5838 case OMPC_write: 5839 case OMPC_update: 5840 case OMPC_capture: 5841 case OMPC_seq_cst: 5842 case OMPC_depend: 5843 case OMPC_device: 5844 case OMPC_threads: 5845 case OMPC_simd: 5846 case OMPC_map: 5847 case OMPC_num_teams: 5848 case OMPC_thread_limit: 5849 case OMPC_priority: 5850 case OMPC_grainsize: 5851 case OMPC_nogroup: 5852 case OMPC_num_tasks: 5853 case OMPC_unknown: 5854 llvm_unreachable("Clause is not allowed."); 5855 } 5856 return Res; 5857 } 5858 5859 OMPClause *Sema::ActOnOpenMPScheduleClause( 5860 OpenMPScheduleClauseKind Kind, Expr *ChunkSize, SourceLocation StartLoc, 5861 SourceLocation LParenLoc, SourceLocation KindLoc, SourceLocation CommaLoc, 5862 SourceLocation EndLoc) { 5863 if (Kind == OMPC_SCHEDULE_unknown) { 5864 std::string Values; 5865 std::string Sep(", "); 5866 for (unsigned i = 0; i < OMPC_SCHEDULE_unknown; ++i) { 5867 Values += "'"; 5868 Values += getOpenMPSimpleClauseTypeName(OMPC_schedule, i); 5869 Values += "'"; 5870 switch (i) { 5871 case OMPC_SCHEDULE_unknown - 2: 5872 Values += " or "; 5873 break; 5874 case OMPC_SCHEDULE_unknown - 1: 5875 break; 5876 default: 5877 Values += Sep; 5878 break; 5879 } 5880 } 5881 Diag(KindLoc, diag::err_omp_unexpected_clause_value) 5882 << Values << getOpenMPClauseName(OMPC_schedule); 5883 return nullptr; 5884 } 5885 Expr *ValExpr = ChunkSize; 5886 Expr *HelperValExpr = nullptr; 5887 if (ChunkSize) { 5888 if (!ChunkSize->isValueDependent() && !ChunkSize->isTypeDependent() && 5889 !ChunkSize->isInstantiationDependent() && 5890 !ChunkSize->containsUnexpandedParameterPack()) { 5891 SourceLocation ChunkSizeLoc = ChunkSize->getLocStart(); 5892 ExprResult Val = 5893 PerformOpenMPImplicitIntegerConversion(ChunkSizeLoc, ChunkSize); 5894 if (Val.isInvalid()) 5895 return nullptr; 5896 5897 ValExpr = Val.get(); 5898 5899 // OpenMP [2.7.1, Restrictions] 5900 // chunk_size must be a loop invariant integer expression with a positive 5901 // value. 5902 llvm::APSInt Result; 5903 if (ValExpr->isIntegerConstantExpr(Result, Context)) { 5904 if (Result.isSigned() && !Result.isStrictlyPositive()) { 5905 Diag(ChunkSizeLoc, diag::err_omp_negative_expression_in_clause) 5906 << "schedule" << 1 << ChunkSize->getSourceRange(); 5907 return nullptr; 5908 } 5909 } else if (isParallelOrTaskRegion(DSAStack->getCurrentDirective())) { 5910 auto *ImpVar = buildVarDecl(*this, ChunkSize->getExprLoc(), 5911 ChunkSize->getType(), ".chunk."); 5912 auto *ImpVarRef = buildDeclRefExpr(*this, ImpVar, ChunkSize->getType(), 5913 ChunkSize->getExprLoc(), 5914 /*RefersToCapture=*/true); 5915 HelperValExpr = ImpVarRef; 5916 } 5917 } 5918 } 5919 5920 return new (Context) OMPScheduleClause(StartLoc, LParenLoc, KindLoc, CommaLoc, 5921 EndLoc, Kind, ValExpr, HelperValExpr); 5922 } 5923 5924 OMPClause *Sema::ActOnOpenMPClause(OpenMPClauseKind Kind, 5925 SourceLocation StartLoc, 5926 SourceLocation EndLoc) { 5927 OMPClause *Res = nullptr; 5928 switch (Kind) { 5929 case OMPC_ordered: 5930 Res = ActOnOpenMPOrderedClause(StartLoc, EndLoc); 5931 break; 5932 case OMPC_nowait: 5933 Res = ActOnOpenMPNowaitClause(StartLoc, EndLoc); 5934 break; 5935 case OMPC_untied: 5936 Res = ActOnOpenMPUntiedClause(StartLoc, EndLoc); 5937 break; 5938 case OMPC_mergeable: 5939 Res = ActOnOpenMPMergeableClause(StartLoc, EndLoc); 5940 break; 5941 case OMPC_read: 5942 Res = ActOnOpenMPReadClause(StartLoc, EndLoc); 5943 break; 5944 case OMPC_write: 5945 Res = ActOnOpenMPWriteClause(StartLoc, EndLoc); 5946 break; 5947 case OMPC_update: 5948 Res = ActOnOpenMPUpdateClause(StartLoc, EndLoc); 5949 break; 5950 case OMPC_capture: 5951 Res = ActOnOpenMPCaptureClause(StartLoc, EndLoc); 5952 break; 5953 case OMPC_seq_cst: 5954 Res = ActOnOpenMPSeqCstClause(StartLoc, EndLoc); 5955 break; 5956 case OMPC_threads: 5957 Res = ActOnOpenMPThreadsClause(StartLoc, EndLoc); 5958 break; 5959 case OMPC_simd: 5960 Res = ActOnOpenMPSIMDClause(StartLoc, EndLoc); 5961 break; 5962 case OMPC_nogroup: 5963 Res = ActOnOpenMPNogroupClause(StartLoc, EndLoc); 5964 break; 5965 case OMPC_if: 5966 case OMPC_final: 5967 case OMPC_num_threads: 5968 case OMPC_safelen: 5969 case OMPC_simdlen: 5970 case OMPC_collapse: 5971 case OMPC_schedule: 5972 case OMPC_private: 5973 case OMPC_firstprivate: 5974 case OMPC_lastprivate: 5975 case OMPC_shared: 5976 case OMPC_reduction: 5977 case OMPC_linear: 5978 case OMPC_aligned: 5979 case OMPC_copyin: 5980 case OMPC_copyprivate: 5981 case OMPC_default: 5982 case OMPC_proc_bind: 5983 case OMPC_threadprivate: 5984 case OMPC_flush: 5985 case OMPC_depend: 5986 case OMPC_device: 5987 case OMPC_map: 5988 case OMPC_num_teams: 5989 case OMPC_thread_limit: 5990 case OMPC_priority: 5991 case OMPC_grainsize: 5992 case OMPC_num_tasks: 5993 case OMPC_unknown: 5994 llvm_unreachable("Clause is not allowed."); 5995 } 5996 return Res; 5997 } 5998 5999 OMPClause *Sema::ActOnOpenMPNowaitClause(SourceLocation StartLoc, 6000 SourceLocation EndLoc) { 6001 DSAStack->setNowaitRegion(); 6002 return new (Context) OMPNowaitClause(StartLoc, EndLoc); 6003 } 6004 6005 OMPClause *Sema::ActOnOpenMPUntiedClause(SourceLocation StartLoc, 6006 SourceLocation EndLoc) { 6007 return new (Context) OMPUntiedClause(StartLoc, EndLoc); 6008 } 6009 6010 OMPClause *Sema::ActOnOpenMPMergeableClause(SourceLocation StartLoc, 6011 SourceLocation EndLoc) { 6012 return new (Context) OMPMergeableClause(StartLoc, EndLoc); 6013 } 6014 6015 OMPClause *Sema::ActOnOpenMPReadClause(SourceLocation StartLoc, 6016 SourceLocation EndLoc) { 6017 return new (Context) OMPReadClause(StartLoc, EndLoc); 6018 } 6019 6020 OMPClause *Sema::ActOnOpenMPWriteClause(SourceLocation StartLoc, 6021 SourceLocation EndLoc) { 6022 return new (Context) OMPWriteClause(StartLoc, EndLoc); 6023 } 6024 6025 OMPClause *Sema::ActOnOpenMPUpdateClause(SourceLocation StartLoc, 6026 SourceLocation EndLoc) { 6027 return new (Context) OMPUpdateClause(StartLoc, EndLoc); 6028 } 6029 6030 OMPClause *Sema::ActOnOpenMPCaptureClause(SourceLocation StartLoc, 6031 SourceLocation EndLoc) { 6032 return new (Context) OMPCaptureClause(StartLoc, EndLoc); 6033 } 6034 6035 OMPClause *Sema::ActOnOpenMPSeqCstClause(SourceLocation StartLoc, 6036 SourceLocation EndLoc) { 6037 return new (Context) OMPSeqCstClause(StartLoc, EndLoc); 6038 } 6039 6040 OMPClause *Sema::ActOnOpenMPThreadsClause(SourceLocation StartLoc, 6041 SourceLocation EndLoc) { 6042 return new (Context) OMPThreadsClause(StartLoc, EndLoc); 6043 } 6044 6045 OMPClause *Sema::ActOnOpenMPSIMDClause(SourceLocation StartLoc, 6046 SourceLocation EndLoc) { 6047 return new (Context) OMPSIMDClause(StartLoc, EndLoc); 6048 } 6049 6050 OMPClause *Sema::ActOnOpenMPNogroupClause(SourceLocation StartLoc, 6051 SourceLocation EndLoc) { 6052 return new (Context) OMPNogroupClause(StartLoc, EndLoc); 6053 } 6054 6055 OMPClause *Sema::ActOnOpenMPVarListClause( 6056 OpenMPClauseKind Kind, ArrayRef<Expr *> VarList, Expr *TailExpr, 6057 SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation ColonLoc, 6058 SourceLocation EndLoc, CXXScopeSpec &ReductionIdScopeSpec, 6059 const DeclarationNameInfo &ReductionId, OpenMPDependClauseKind DepKind, 6060 OpenMPLinearClauseKind LinKind, OpenMPMapClauseKind MapTypeModifier, 6061 OpenMPMapClauseKind MapType, SourceLocation DepLinMapLoc) { 6062 OMPClause *Res = nullptr; 6063 switch (Kind) { 6064 case OMPC_private: 6065 Res = ActOnOpenMPPrivateClause(VarList, StartLoc, LParenLoc, EndLoc); 6066 break; 6067 case OMPC_firstprivate: 6068 Res = ActOnOpenMPFirstprivateClause(VarList, StartLoc, LParenLoc, EndLoc); 6069 break; 6070 case OMPC_lastprivate: 6071 Res = ActOnOpenMPLastprivateClause(VarList, StartLoc, LParenLoc, EndLoc); 6072 break; 6073 case OMPC_shared: 6074 Res = ActOnOpenMPSharedClause(VarList, StartLoc, LParenLoc, EndLoc); 6075 break; 6076 case OMPC_reduction: 6077 Res = ActOnOpenMPReductionClause(VarList, StartLoc, LParenLoc, ColonLoc, 6078 EndLoc, ReductionIdScopeSpec, ReductionId); 6079 break; 6080 case OMPC_linear: 6081 Res = ActOnOpenMPLinearClause(VarList, TailExpr, StartLoc, LParenLoc, 6082 LinKind, DepLinMapLoc, ColonLoc, EndLoc); 6083 break; 6084 case OMPC_aligned: 6085 Res = ActOnOpenMPAlignedClause(VarList, TailExpr, StartLoc, LParenLoc, 6086 ColonLoc, EndLoc); 6087 break; 6088 case OMPC_copyin: 6089 Res = ActOnOpenMPCopyinClause(VarList, StartLoc, LParenLoc, EndLoc); 6090 break; 6091 case OMPC_copyprivate: 6092 Res = ActOnOpenMPCopyprivateClause(VarList, StartLoc, LParenLoc, EndLoc); 6093 break; 6094 case OMPC_flush: 6095 Res = ActOnOpenMPFlushClause(VarList, StartLoc, LParenLoc, EndLoc); 6096 break; 6097 case OMPC_depend: 6098 Res = ActOnOpenMPDependClause(DepKind, DepLinMapLoc, ColonLoc, VarList, 6099 StartLoc, LParenLoc, EndLoc); 6100 break; 6101 case OMPC_map: 6102 Res = ActOnOpenMPMapClause(MapTypeModifier, MapType, DepLinMapLoc, ColonLoc, 6103 VarList, StartLoc, LParenLoc, EndLoc); 6104 break; 6105 case OMPC_if: 6106 case OMPC_final: 6107 case OMPC_num_threads: 6108 case OMPC_safelen: 6109 case OMPC_simdlen: 6110 case OMPC_collapse: 6111 case OMPC_default: 6112 case OMPC_proc_bind: 6113 case OMPC_schedule: 6114 case OMPC_ordered: 6115 case OMPC_nowait: 6116 case OMPC_untied: 6117 case OMPC_mergeable: 6118 case OMPC_threadprivate: 6119 case OMPC_read: 6120 case OMPC_write: 6121 case OMPC_update: 6122 case OMPC_capture: 6123 case OMPC_seq_cst: 6124 case OMPC_device: 6125 case OMPC_threads: 6126 case OMPC_simd: 6127 case OMPC_num_teams: 6128 case OMPC_thread_limit: 6129 case OMPC_priority: 6130 case OMPC_grainsize: 6131 case OMPC_nogroup: 6132 case OMPC_num_tasks: 6133 case OMPC_unknown: 6134 llvm_unreachable("Clause is not allowed."); 6135 } 6136 return Res; 6137 } 6138 6139 OMPClause *Sema::ActOnOpenMPPrivateClause(ArrayRef<Expr *> VarList, 6140 SourceLocation StartLoc, 6141 SourceLocation LParenLoc, 6142 SourceLocation EndLoc) { 6143 SmallVector<Expr *, 8> Vars; 6144 SmallVector<Expr *, 8> PrivateCopies; 6145 for (auto &RefExpr : VarList) { 6146 assert(RefExpr && "NULL expr in OpenMP private clause."); 6147 if (isa<DependentScopeDeclRefExpr>(RefExpr)) { 6148 // It will be analyzed later. 6149 Vars.push_back(RefExpr); 6150 PrivateCopies.push_back(nullptr); 6151 continue; 6152 } 6153 6154 SourceLocation ELoc = RefExpr->getExprLoc(); 6155 // OpenMP [2.1, C/C++] 6156 // A list item is a variable name. 6157 // OpenMP [2.9.3.3, Restrictions, p.1] 6158 // A variable that is part of another variable (as an array or 6159 // structure element) cannot appear in a private clause. 6160 DeclRefExpr *DE = dyn_cast_or_null<DeclRefExpr>(RefExpr); 6161 if (!DE || !isa<VarDecl>(DE->getDecl())) { 6162 Diag(ELoc, diag::err_omp_expected_var_name) << RefExpr->getSourceRange(); 6163 continue; 6164 } 6165 Decl *D = DE->getDecl(); 6166 VarDecl *VD = cast<VarDecl>(D); 6167 6168 QualType Type = VD->getType(); 6169 if (Type->isDependentType() || Type->isInstantiationDependentType()) { 6170 // It will be analyzed later. 6171 Vars.push_back(DE); 6172 PrivateCopies.push_back(nullptr); 6173 continue; 6174 } 6175 6176 // OpenMP [2.9.3.3, Restrictions, C/C++, p.3] 6177 // A variable that appears in a private clause must not have an incomplete 6178 // type or a reference type. 6179 if (RequireCompleteType(ELoc, Type, 6180 diag::err_omp_private_incomplete_type)) { 6181 continue; 6182 } 6183 Type = Type.getNonReferenceType(); 6184 6185 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced 6186 // in a Construct] 6187 // Variables with the predetermined data-sharing attributes may not be 6188 // listed in data-sharing attributes clauses, except for the cases 6189 // listed below. For these exceptions only, listing a predetermined 6190 // variable in a data-sharing attribute clause is allowed and overrides 6191 // the variable's predetermined data-sharing attributes. 6192 DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(VD, false); 6193 if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_private) { 6194 Diag(ELoc, diag::err_omp_wrong_dsa) << getOpenMPClauseName(DVar.CKind) 6195 << getOpenMPClauseName(OMPC_private); 6196 ReportOriginalDSA(*this, DSAStack, VD, DVar); 6197 continue; 6198 } 6199 6200 // Variably modified types are not supported for tasks. 6201 if (!Type->isAnyPointerType() && Type->isVariablyModifiedType() && 6202 DSAStack->getCurrentDirective() == OMPD_task) { 6203 Diag(ELoc, diag::err_omp_variably_modified_type_not_supported) 6204 << getOpenMPClauseName(OMPC_private) << Type 6205 << getOpenMPDirectiveName(DSAStack->getCurrentDirective()); 6206 bool IsDecl = 6207 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly; 6208 Diag(VD->getLocation(), 6209 IsDecl ? diag::note_previous_decl : diag::note_defined_here) 6210 << VD; 6211 continue; 6212 } 6213 6214 // OpenMP [2.9.3.3, Restrictions, C/C++, p.1] 6215 // A variable of class type (or array thereof) that appears in a private 6216 // clause requires an accessible, unambiguous default constructor for the 6217 // class type. 6218 // Generate helper private variable and initialize it with the default 6219 // value. The address of the original variable is replaced by the address of 6220 // the new private variable in CodeGen. This new variable is not added to 6221 // IdResolver, so the code in the OpenMP region uses original variable for 6222 // proper diagnostics. 6223 Type = Type.getUnqualifiedType(); 6224 auto VDPrivate = buildVarDecl(*this, DE->getExprLoc(), Type, VD->getName(), 6225 VD->hasAttrs() ? &VD->getAttrs() : nullptr); 6226 ActOnUninitializedDecl(VDPrivate, /*TypeMayContainAuto=*/false); 6227 if (VDPrivate->isInvalidDecl()) 6228 continue; 6229 auto VDPrivateRefExpr = buildDeclRefExpr( 6230 *this, VDPrivate, DE->getType().getUnqualifiedType(), DE->getExprLoc()); 6231 6232 DSAStack->addDSA(VD, DE, OMPC_private); 6233 Vars.push_back(DE); 6234 PrivateCopies.push_back(VDPrivateRefExpr); 6235 } 6236 6237 if (Vars.empty()) 6238 return nullptr; 6239 6240 return OMPPrivateClause::Create(Context, StartLoc, LParenLoc, EndLoc, Vars, 6241 PrivateCopies); 6242 } 6243 6244 namespace { 6245 class DiagsUninitializedSeveretyRAII { 6246 private: 6247 DiagnosticsEngine &Diags; 6248 SourceLocation SavedLoc; 6249 bool IsIgnored; 6250 6251 public: 6252 DiagsUninitializedSeveretyRAII(DiagnosticsEngine &Diags, SourceLocation Loc, 6253 bool IsIgnored) 6254 : Diags(Diags), SavedLoc(Loc), IsIgnored(IsIgnored) { 6255 if (!IsIgnored) { 6256 Diags.setSeverity(/*Diag*/ diag::warn_uninit_self_reference_in_init, 6257 /*Map*/ diag::Severity::Ignored, Loc); 6258 } 6259 } 6260 ~DiagsUninitializedSeveretyRAII() { 6261 if (!IsIgnored) 6262 Diags.popMappings(SavedLoc); 6263 } 6264 }; 6265 } 6266 6267 OMPClause *Sema::ActOnOpenMPFirstprivateClause(ArrayRef<Expr *> VarList, 6268 SourceLocation StartLoc, 6269 SourceLocation LParenLoc, 6270 SourceLocation EndLoc) { 6271 SmallVector<Expr *, 8> Vars; 6272 SmallVector<Expr *, 8> PrivateCopies; 6273 SmallVector<Expr *, 8> Inits; 6274 bool IsImplicitClause = 6275 StartLoc.isInvalid() && LParenLoc.isInvalid() && EndLoc.isInvalid(); 6276 auto ImplicitClauseLoc = DSAStack->getConstructLoc(); 6277 6278 for (auto &RefExpr : VarList) { 6279 assert(RefExpr && "NULL expr in OpenMP firstprivate clause."); 6280 if (isa<DependentScopeDeclRefExpr>(RefExpr)) { 6281 // It will be analyzed later. 6282 Vars.push_back(RefExpr); 6283 PrivateCopies.push_back(nullptr); 6284 Inits.push_back(nullptr); 6285 continue; 6286 } 6287 6288 SourceLocation ELoc = 6289 IsImplicitClause ? ImplicitClauseLoc : RefExpr->getExprLoc(); 6290 // OpenMP [2.1, C/C++] 6291 // A list item is a variable name. 6292 // OpenMP [2.9.3.3, Restrictions, p.1] 6293 // A variable that is part of another variable (as an array or 6294 // structure element) cannot appear in a private clause. 6295 DeclRefExpr *DE = dyn_cast_or_null<DeclRefExpr>(RefExpr); 6296 if (!DE || !isa<VarDecl>(DE->getDecl())) { 6297 Diag(ELoc, diag::err_omp_expected_var_name) << RefExpr->getSourceRange(); 6298 continue; 6299 } 6300 Decl *D = DE->getDecl(); 6301 VarDecl *VD = cast<VarDecl>(D); 6302 6303 QualType Type = VD->getType(); 6304 if (Type->isDependentType() || Type->isInstantiationDependentType()) { 6305 // It will be analyzed later. 6306 Vars.push_back(DE); 6307 PrivateCopies.push_back(nullptr); 6308 Inits.push_back(nullptr); 6309 continue; 6310 } 6311 6312 // OpenMP [2.9.3.3, Restrictions, C/C++, p.3] 6313 // A variable that appears in a private clause must not have an incomplete 6314 // type or a reference type. 6315 if (RequireCompleteType(ELoc, Type, 6316 diag::err_omp_firstprivate_incomplete_type)) { 6317 continue; 6318 } 6319 Type = Type.getNonReferenceType(); 6320 6321 // OpenMP [2.9.3.4, Restrictions, C/C++, p.1] 6322 // A variable of class type (or array thereof) that appears in a private 6323 // clause requires an accessible, unambiguous copy constructor for the 6324 // class type. 6325 auto ElemType = Context.getBaseElementType(Type).getNonReferenceType(); 6326 6327 // If an implicit firstprivate variable found it was checked already. 6328 if (!IsImplicitClause) { 6329 DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(VD, false); 6330 bool IsConstant = ElemType.isConstant(Context); 6331 // OpenMP [2.4.13, Data-sharing Attribute Clauses] 6332 // A list item that specifies a given variable may not appear in more 6333 // than one clause on the same directive, except that a variable may be 6334 // specified in both firstprivate and lastprivate clauses. 6335 if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_firstprivate && 6336 DVar.CKind != OMPC_lastprivate && DVar.RefExpr) { 6337 Diag(ELoc, diag::err_omp_wrong_dsa) 6338 << getOpenMPClauseName(DVar.CKind) 6339 << getOpenMPClauseName(OMPC_firstprivate); 6340 ReportOriginalDSA(*this, DSAStack, VD, DVar); 6341 continue; 6342 } 6343 6344 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced 6345 // in a Construct] 6346 // Variables with the predetermined data-sharing attributes may not be 6347 // listed in data-sharing attributes clauses, except for the cases 6348 // listed below. For these exceptions only, listing a predetermined 6349 // variable in a data-sharing attribute clause is allowed and overrides 6350 // the variable's predetermined data-sharing attributes. 6351 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced 6352 // in a Construct, C/C++, p.2] 6353 // Variables with const-qualified type having no mutable member may be 6354 // listed in a firstprivate clause, even if they are static data members. 6355 if (!(IsConstant || VD->isStaticDataMember()) && !DVar.RefExpr && 6356 DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_shared) { 6357 Diag(ELoc, diag::err_omp_wrong_dsa) 6358 << getOpenMPClauseName(DVar.CKind) 6359 << getOpenMPClauseName(OMPC_firstprivate); 6360 ReportOriginalDSA(*this, DSAStack, VD, DVar); 6361 continue; 6362 } 6363 6364 OpenMPDirectiveKind CurrDir = DSAStack->getCurrentDirective(); 6365 // OpenMP [2.9.3.4, Restrictions, p.2] 6366 // A list item that is private within a parallel region must not appear 6367 // in a firstprivate clause on a worksharing construct if any of the 6368 // worksharing regions arising from the worksharing construct ever bind 6369 // to any of the parallel regions arising from the parallel construct. 6370 if (isOpenMPWorksharingDirective(CurrDir) && 6371 !isOpenMPParallelDirective(CurrDir)) { 6372 DVar = DSAStack->getImplicitDSA(VD, true); 6373 if (DVar.CKind != OMPC_shared && 6374 (isOpenMPParallelDirective(DVar.DKind) || 6375 DVar.DKind == OMPD_unknown)) { 6376 Diag(ELoc, diag::err_omp_required_access) 6377 << getOpenMPClauseName(OMPC_firstprivate) 6378 << getOpenMPClauseName(OMPC_shared); 6379 ReportOriginalDSA(*this, DSAStack, VD, DVar); 6380 continue; 6381 } 6382 } 6383 // OpenMP [2.9.3.4, Restrictions, p.3] 6384 // A list item that appears in a reduction clause of a parallel construct 6385 // must not appear in a firstprivate clause on a worksharing or task 6386 // construct if any of the worksharing or task regions arising from the 6387 // worksharing or task construct ever bind to any of the parallel regions 6388 // arising from the parallel construct. 6389 // OpenMP [2.9.3.4, Restrictions, p.4] 6390 // A list item that appears in a reduction clause in worksharing 6391 // construct must not appear in a firstprivate clause in a task construct 6392 // encountered during execution of any of the worksharing regions arising 6393 // from the worksharing construct. 6394 if (CurrDir == OMPD_task) { 6395 DVar = 6396 DSAStack->hasInnermostDSA(VD, MatchesAnyClause(OMPC_reduction), 6397 [](OpenMPDirectiveKind K) -> bool { 6398 return isOpenMPParallelDirective(K) || 6399 isOpenMPWorksharingDirective(K); 6400 }, 6401 false); 6402 if (DVar.CKind == OMPC_reduction && 6403 (isOpenMPParallelDirective(DVar.DKind) || 6404 isOpenMPWorksharingDirective(DVar.DKind))) { 6405 Diag(ELoc, diag::err_omp_parallel_reduction_in_task_firstprivate) 6406 << getOpenMPDirectiveName(DVar.DKind); 6407 ReportOriginalDSA(*this, DSAStack, VD, DVar); 6408 continue; 6409 } 6410 } 6411 } 6412 6413 // Variably modified types are not supported for tasks. 6414 if (!Type->isAnyPointerType() && Type->isVariablyModifiedType() && 6415 DSAStack->getCurrentDirective() == OMPD_task) { 6416 Diag(ELoc, diag::err_omp_variably_modified_type_not_supported) 6417 << getOpenMPClauseName(OMPC_firstprivate) << Type 6418 << getOpenMPDirectiveName(DSAStack->getCurrentDirective()); 6419 bool IsDecl = 6420 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly; 6421 Diag(VD->getLocation(), 6422 IsDecl ? diag::note_previous_decl : diag::note_defined_here) 6423 << VD; 6424 continue; 6425 } 6426 6427 Type = Type.getUnqualifiedType(); 6428 auto VDPrivate = buildVarDecl(*this, ELoc, Type, VD->getName(), 6429 VD->hasAttrs() ? &VD->getAttrs() : nullptr); 6430 // Generate helper private variable and initialize it with the value of the 6431 // original variable. The address of the original variable is replaced by 6432 // the address of the new private variable in the CodeGen. This new variable 6433 // is not added to IdResolver, so the code in the OpenMP region uses 6434 // original variable for proper diagnostics and variable capturing. 6435 Expr *VDInitRefExpr = nullptr; 6436 // For arrays generate initializer for single element and replace it by the 6437 // original array element in CodeGen. 6438 if (Type->isArrayType()) { 6439 auto VDInit = 6440 buildVarDecl(*this, DE->getExprLoc(), ElemType, VD->getName()); 6441 VDInitRefExpr = buildDeclRefExpr(*this, VDInit, ElemType, ELoc); 6442 auto Init = DefaultLvalueConversion(VDInitRefExpr).get(); 6443 ElemType = ElemType.getUnqualifiedType(); 6444 auto *VDInitTemp = buildVarDecl(*this, DE->getLocStart(), ElemType, 6445 ".firstprivate.temp"); 6446 InitializedEntity Entity = 6447 InitializedEntity::InitializeVariable(VDInitTemp); 6448 InitializationKind Kind = InitializationKind::CreateCopy(ELoc, ELoc); 6449 6450 InitializationSequence InitSeq(*this, Entity, Kind, Init); 6451 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Init); 6452 if (Result.isInvalid()) 6453 VDPrivate->setInvalidDecl(); 6454 else 6455 VDPrivate->setInit(Result.getAs<Expr>()); 6456 // Remove temp variable declaration. 6457 Context.Deallocate(VDInitTemp); 6458 } else { 6459 auto *VDInit = 6460 buildVarDecl(*this, DE->getLocStart(), Type, ".firstprivate.temp"); 6461 VDInitRefExpr = 6462 buildDeclRefExpr(*this, VDInit, DE->getType(), DE->getExprLoc()); 6463 AddInitializerToDecl(VDPrivate, 6464 DefaultLvalueConversion(VDInitRefExpr).get(), 6465 /*DirectInit=*/false, /*TypeMayContainAuto=*/false); 6466 } 6467 if (VDPrivate->isInvalidDecl()) { 6468 if (IsImplicitClause) { 6469 Diag(DE->getExprLoc(), 6470 diag::note_omp_task_predetermined_firstprivate_here); 6471 } 6472 continue; 6473 } 6474 CurContext->addDecl(VDPrivate); 6475 auto VDPrivateRefExpr = buildDeclRefExpr( 6476 *this, VDPrivate, DE->getType().getUnqualifiedType(), DE->getExprLoc()); 6477 DSAStack->addDSA(VD, DE, OMPC_firstprivate); 6478 Vars.push_back(DE); 6479 PrivateCopies.push_back(VDPrivateRefExpr); 6480 Inits.push_back(VDInitRefExpr); 6481 } 6482 6483 if (Vars.empty()) 6484 return nullptr; 6485 6486 return OMPFirstprivateClause::Create(Context, StartLoc, LParenLoc, EndLoc, 6487 Vars, PrivateCopies, Inits); 6488 } 6489 6490 OMPClause *Sema::ActOnOpenMPLastprivateClause(ArrayRef<Expr *> VarList, 6491 SourceLocation StartLoc, 6492 SourceLocation LParenLoc, 6493 SourceLocation EndLoc) { 6494 SmallVector<Expr *, 8> Vars; 6495 SmallVector<Expr *, 8> SrcExprs; 6496 SmallVector<Expr *, 8> DstExprs; 6497 SmallVector<Expr *, 8> AssignmentOps; 6498 for (auto &RefExpr : VarList) { 6499 assert(RefExpr && "NULL expr in OpenMP lastprivate clause."); 6500 if (isa<DependentScopeDeclRefExpr>(RefExpr)) { 6501 // It will be analyzed later. 6502 Vars.push_back(RefExpr); 6503 SrcExprs.push_back(nullptr); 6504 DstExprs.push_back(nullptr); 6505 AssignmentOps.push_back(nullptr); 6506 continue; 6507 } 6508 6509 SourceLocation ELoc = RefExpr->getExprLoc(); 6510 // OpenMP [2.1, C/C++] 6511 // A list item is a variable name. 6512 // OpenMP [2.14.3.5, Restrictions, p.1] 6513 // A variable that is part of another variable (as an array or structure 6514 // element) cannot appear in a lastprivate clause. 6515 DeclRefExpr *DE = dyn_cast_or_null<DeclRefExpr>(RefExpr); 6516 if (!DE || !isa<VarDecl>(DE->getDecl())) { 6517 Diag(ELoc, diag::err_omp_expected_var_name) << RefExpr->getSourceRange(); 6518 continue; 6519 } 6520 Decl *D = DE->getDecl(); 6521 VarDecl *VD = cast<VarDecl>(D); 6522 6523 QualType Type = VD->getType(); 6524 if (Type->isDependentType() || Type->isInstantiationDependentType()) { 6525 // It will be analyzed later. 6526 Vars.push_back(DE); 6527 SrcExprs.push_back(nullptr); 6528 DstExprs.push_back(nullptr); 6529 AssignmentOps.push_back(nullptr); 6530 continue; 6531 } 6532 6533 // OpenMP [2.14.3.5, Restrictions, C/C++, p.2] 6534 // A variable that appears in a lastprivate clause must not have an 6535 // incomplete type or a reference type. 6536 if (RequireCompleteType(ELoc, Type, 6537 diag::err_omp_lastprivate_incomplete_type)) { 6538 continue; 6539 } 6540 Type = Type.getNonReferenceType(); 6541 6542 // OpenMP [2.14.1.1, Data-sharing Attribute Rules for Variables Referenced 6543 // in a Construct] 6544 // Variables with the predetermined data-sharing attributes may not be 6545 // listed in data-sharing attributes clauses, except for the cases 6546 // listed below. 6547 DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(VD, false); 6548 if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_lastprivate && 6549 DVar.CKind != OMPC_firstprivate && 6550 (DVar.CKind != OMPC_private || DVar.RefExpr != nullptr)) { 6551 Diag(ELoc, diag::err_omp_wrong_dsa) 6552 << getOpenMPClauseName(DVar.CKind) 6553 << getOpenMPClauseName(OMPC_lastprivate); 6554 ReportOriginalDSA(*this, DSAStack, VD, DVar); 6555 continue; 6556 } 6557 6558 OpenMPDirectiveKind CurrDir = DSAStack->getCurrentDirective(); 6559 // OpenMP [2.14.3.5, Restrictions, p.2] 6560 // A list item that is private within a parallel region, or that appears in 6561 // the reduction clause of a parallel construct, must not appear in a 6562 // lastprivate clause on a worksharing construct if any of the corresponding 6563 // worksharing regions ever binds to any of the corresponding parallel 6564 // regions. 6565 DSAStackTy::DSAVarData TopDVar = DVar; 6566 if (isOpenMPWorksharingDirective(CurrDir) && 6567 !isOpenMPParallelDirective(CurrDir)) { 6568 DVar = DSAStack->getImplicitDSA(VD, true); 6569 if (DVar.CKind != OMPC_shared) { 6570 Diag(ELoc, diag::err_omp_required_access) 6571 << getOpenMPClauseName(OMPC_lastprivate) 6572 << getOpenMPClauseName(OMPC_shared); 6573 ReportOriginalDSA(*this, DSAStack, VD, DVar); 6574 continue; 6575 } 6576 } 6577 // OpenMP [2.14.3.5, Restrictions, C++, p.1,2] 6578 // A variable of class type (or array thereof) that appears in a 6579 // lastprivate clause requires an accessible, unambiguous default 6580 // constructor for the class type, unless the list item is also specified 6581 // in a firstprivate clause. 6582 // A variable of class type (or array thereof) that appears in a 6583 // lastprivate clause requires an accessible, unambiguous copy assignment 6584 // operator for the class type. 6585 Type = Context.getBaseElementType(Type).getNonReferenceType(); 6586 auto *SrcVD = buildVarDecl(*this, DE->getLocStart(), 6587 Type.getUnqualifiedType(), ".lastprivate.src", 6588 VD->hasAttrs() ? &VD->getAttrs() : nullptr); 6589 auto *PseudoSrcExpr = buildDeclRefExpr( 6590 *this, SrcVD, Type.getUnqualifiedType(), DE->getExprLoc()); 6591 auto *DstVD = 6592 buildVarDecl(*this, DE->getLocStart(), Type, ".lastprivate.dst", 6593 VD->hasAttrs() ? &VD->getAttrs() : nullptr); 6594 auto *PseudoDstExpr = 6595 buildDeclRefExpr(*this, DstVD, Type, DE->getExprLoc()); 6596 // For arrays generate assignment operation for single element and replace 6597 // it by the original array element in CodeGen. 6598 auto AssignmentOp = BuildBinOp(/*S=*/nullptr, DE->getExprLoc(), BO_Assign, 6599 PseudoDstExpr, PseudoSrcExpr); 6600 if (AssignmentOp.isInvalid()) 6601 continue; 6602 AssignmentOp = ActOnFinishFullExpr(AssignmentOp.get(), DE->getExprLoc(), 6603 /*DiscardedValue=*/true); 6604 if (AssignmentOp.isInvalid()) 6605 continue; 6606 6607 if (TopDVar.CKind != OMPC_firstprivate) 6608 DSAStack->addDSA(VD, DE, OMPC_lastprivate); 6609 Vars.push_back(DE); 6610 SrcExprs.push_back(PseudoSrcExpr); 6611 DstExprs.push_back(PseudoDstExpr); 6612 AssignmentOps.push_back(AssignmentOp.get()); 6613 } 6614 6615 if (Vars.empty()) 6616 return nullptr; 6617 6618 return OMPLastprivateClause::Create(Context, StartLoc, LParenLoc, EndLoc, 6619 Vars, SrcExprs, DstExprs, AssignmentOps); 6620 } 6621 6622 OMPClause *Sema::ActOnOpenMPSharedClause(ArrayRef<Expr *> VarList, 6623 SourceLocation StartLoc, 6624 SourceLocation LParenLoc, 6625 SourceLocation EndLoc) { 6626 SmallVector<Expr *, 8> Vars; 6627 for (auto &RefExpr : VarList) { 6628 assert(RefExpr && "NULL expr in OpenMP shared clause."); 6629 if (isa<DependentScopeDeclRefExpr>(RefExpr)) { 6630 // It will be analyzed later. 6631 Vars.push_back(RefExpr); 6632 continue; 6633 } 6634 6635 SourceLocation ELoc = RefExpr->getExprLoc(); 6636 // OpenMP [2.1, C/C++] 6637 // A list item is a variable name. 6638 // OpenMP [2.14.3.2, Restrictions, p.1] 6639 // A variable that is part of another variable (as an array or structure 6640 // element) cannot appear in a shared unless it is a static data member 6641 // of a C++ class. 6642 DeclRefExpr *DE = dyn_cast<DeclRefExpr>(RefExpr); 6643 if (!DE || !isa<VarDecl>(DE->getDecl())) { 6644 Diag(ELoc, diag::err_omp_expected_var_name) << RefExpr->getSourceRange(); 6645 continue; 6646 } 6647 Decl *D = DE->getDecl(); 6648 VarDecl *VD = cast<VarDecl>(D); 6649 6650 QualType Type = VD->getType(); 6651 if (Type->isDependentType() || Type->isInstantiationDependentType()) { 6652 // It will be analyzed later. 6653 Vars.push_back(DE); 6654 continue; 6655 } 6656 6657 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced 6658 // in a Construct] 6659 // Variables with the predetermined data-sharing attributes may not be 6660 // listed in data-sharing attributes clauses, except for the cases 6661 // listed below. For these exceptions only, listing a predetermined 6662 // variable in a data-sharing attribute clause is allowed and overrides 6663 // the variable's predetermined data-sharing attributes. 6664 DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(VD, false); 6665 if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_shared && 6666 DVar.RefExpr) { 6667 Diag(ELoc, diag::err_omp_wrong_dsa) << getOpenMPClauseName(DVar.CKind) 6668 << getOpenMPClauseName(OMPC_shared); 6669 ReportOriginalDSA(*this, DSAStack, VD, DVar); 6670 continue; 6671 } 6672 6673 DSAStack->addDSA(VD, DE, OMPC_shared); 6674 Vars.push_back(DE); 6675 } 6676 6677 if (Vars.empty()) 6678 return nullptr; 6679 6680 return OMPSharedClause::Create(Context, StartLoc, LParenLoc, EndLoc, Vars); 6681 } 6682 6683 namespace { 6684 class DSARefChecker : public StmtVisitor<DSARefChecker, bool> { 6685 DSAStackTy *Stack; 6686 6687 public: 6688 bool VisitDeclRefExpr(DeclRefExpr *E) { 6689 if (VarDecl *VD = dyn_cast<VarDecl>(E->getDecl())) { 6690 DSAStackTy::DSAVarData DVar = Stack->getTopDSA(VD, false); 6691 if (DVar.CKind == OMPC_shared && !DVar.RefExpr) 6692 return false; 6693 if (DVar.CKind != OMPC_unknown) 6694 return true; 6695 DSAStackTy::DSAVarData DVarPrivate = 6696 Stack->hasDSA(VD, isOpenMPPrivate, MatchesAlways(), false); 6697 if (DVarPrivate.CKind != OMPC_unknown) 6698 return true; 6699 return false; 6700 } 6701 return false; 6702 } 6703 bool VisitStmt(Stmt *S) { 6704 for (auto Child : S->children()) { 6705 if (Child && Visit(Child)) 6706 return true; 6707 } 6708 return false; 6709 } 6710 explicit DSARefChecker(DSAStackTy *S) : Stack(S) {} 6711 }; 6712 } // namespace 6713 6714 OMPClause *Sema::ActOnOpenMPReductionClause( 6715 ArrayRef<Expr *> VarList, SourceLocation StartLoc, SourceLocation LParenLoc, 6716 SourceLocation ColonLoc, SourceLocation EndLoc, 6717 CXXScopeSpec &ReductionIdScopeSpec, 6718 const DeclarationNameInfo &ReductionId) { 6719 // TODO: Allow scope specification search when 'declare reduction' is 6720 // supported. 6721 assert(ReductionIdScopeSpec.isEmpty() && 6722 "No support for scoped reduction identifiers yet."); 6723 6724 auto DN = ReductionId.getName(); 6725 auto OOK = DN.getCXXOverloadedOperator(); 6726 BinaryOperatorKind BOK = BO_Comma; 6727 6728 // OpenMP [2.14.3.6, reduction clause] 6729 // C 6730 // reduction-identifier is either an identifier or one of the following 6731 // operators: +, -, *, &, |, ^, && and || 6732 // C++ 6733 // reduction-identifier is either an id-expression or one of the following 6734 // operators: +, -, *, &, |, ^, && and || 6735 // FIXME: Only 'min' and 'max' identifiers are supported for now. 6736 switch (OOK) { 6737 case OO_Plus: 6738 case OO_Minus: 6739 BOK = BO_Add; 6740 break; 6741 case OO_Star: 6742 BOK = BO_Mul; 6743 break; 6744 case OO_Amp: 6745 BOK = BO_And; 6746 break; 6747 case OO_Pipe: 6748 BOK = BO_Or; 6749 break; 6750 case OO_Caret: 6751 BOK = BO_Xor; 6752 break; 6753 case OO_AmpAmp: 6754 BOK = BO_LAnd; 6755 break; 6756 case OO_PipePipe: 6757 BOK = BO_LOr; 6758 break; 6759 case OO_New: 6760 case OO_Delete: 6761 case OO_Array_New: 6762 case OO_Array_Delete: 6763 case OO_Slash: 6764 case OO_Percent: 6765 case OO_Tilde: 6766 case OO_Exclaim: 6767 case OO_Equal: 6768 case OO_Less: 6769 case OO_Greater: 6770 case OO_LessEqual: 6771 case OO_GreaterEqual: 6772 case OO_PlusEqual: 6773 case OO_MinusEqual: 6774 case OO_StarEqual: 6775 case OO_SlashEqual: 6776 case OO_PercentEqual: 6777 case OO_CaretEqual: 6778 case OO_AmpEqual: 6779 case OO_PipeEqual: 6780 case OO_LessLess: 6781 case OO_GreaterGreater: 6782 case OO_LessLessEqual: 6783 case OO_GreaterGreaterEqual: 6784 case OO_EqualEqual: 6785 case OO_ExclaimEqual: 6786 case OO_PlusPlus: 6787 case OO_MinusMinus: 6788 case OO_Comma: 6789 case OO_ArrowStar: 6790 case OO_Arrow: 6791 case OO_Call: 6792 case OO_Subscript: 6793 case OO_Conditional: 6794 case OO_Coawait: 6795 case NUM_OVERLOADED_OPERATORS: 6796 llvm_unreachable("Unexpected reduction identifier"); 6797 case OO_None: 6798 if (auto II = DN.getAsIdentifierInfo()) { 6799 if (II->isStr("max")) 6800 BOK = BO_GT; 6801 else if (II->isStr("min")) 6802 BOK = BO_LT; 6803 } 6804 break; 6805 } 6806 SourceRange ReductionIdRange; 6807 if (ReductionIdScopeSpec.isValid()) { 6808 ReductionIdRange.setBegin(ReductionIdScopeSpec.getBeginLoc()); 6809 } 6810 ReductionIdRange.setEnd(ReductionId.getEndLoc()); 6811 if (BOK == BO_Comma) { 6812 // Not allowed reduction identifier is found. 6813 Diag(ReductionId.getLocStart(), diag::err_omp_unknown_reduction_identifier) 6814 << ReductionIdRange; 6815 return nullptr; 6816 } 6817 6818 SmallVector<Expr *, 8> Vars; 6819 SmallVector<Expr *, 8> Privates; 6820 SmallVector<Expr *, 8> LHSs; 6821 SmallVector<Expr *, 8> RHSs; 6822 SmallVector<Expr *, 8> ReductionOps; 6823 for (auto RefExpr : VarList) { 6824 assert(RefExpr && "nullptr expr in OpenMP reduction clause."); 6825 if (isa<DependentScopeDeclRefExpr>(RefExpr)) { 6826 // It will be analyzed later. 6827 Vars.push_back(RefExpr); 6828 Privates.push_back(nullptr); 6829 LHSs.push_back(nullptr); 6830 RHSs.push_back(nullptr); 6831 ReductionOps.push_back(nullptr); 6832 continue; 6833 } 6834 6835 if (RefExpr->isTypeDependent() || RefExpr->isValueDependent() || 6836 RefExpr->isInstantiationDependent() || 6837 RefExpr->containsUnexpandedParameterPack()) { 6838 // It will be analyzed later. 6839 Vars.push_back(RefExpr); 6840 Privates.push_back(nullptr); 6841 LHSs.push_back(nullptr); 6842 RHSs.push_back(nullptr); 6843 ReductionOps.push_back(nullptr); 6844 continue; 6845 } 6846 6847 auto ELoc = RefExpr->getExprLoc(); 6848 auto ERange = RefExpr->getSourceRange(); 6849 // OpenMP [2.1, C/C++] 6850 // A list item is a variable or array section, subject to the restrictions 6851 // specified in Section 2.4 on page 42 and in each of the sections 6852 // describing clauses and directives for which a list appears. 6853 // OpenMP [2.14.3.3, Restrictions, p.1] 6854 // A variable that is part of another variable (as an array or 6855 // structure element) cannot appear in a private clause. 6856 auto *DE = dyn_cast<DeclRefExpr>(RefExpr); 6857 auto *ASE = dyn_cast<ArraySubscriptExpr>(RefExpr); 6858 auto *OASE = dyn_cast<OMPArraySectionExpr>(RefExpr); 6859 if (!ASE && !OASE && (!DE || !isa<VarDecl>(DE->getDecl()))) { 6860 Diag(ELoc, diag::err_omp_expected_var_name_or_array_item) << ERange; 6861 continue; 6862 } 6863 QualType Type; 6864 VarDecl *VD = nullptr; 6865 if (DE) { 6866 auto D = DE->getDecl(); 6867 VD = cast<VarDecl>(D); 6868 Type = VD->getType(); 6869 } else if (ASE) { 6870 Type = ASE->getType(); 6871 auto *Base = ASE->getBase()->IgnoreParenImpCasts(); 6872 while (auto *TempASE = dyn_cast<ArraySubscriptExpr>(Base)) 6873 Base = TempASE->getBase()->IgnoreParenImpCasts(); 6874 DE = dyn_cast<DeclRefExpr>(Base); 6875 if (DE) 6876 VD = dyn_cast<VarDecl>(DE->getDecl()); 6877 if (!VD) { 6878 Diag(Base->getExprLoc(), diag::err_omp_expected_base_var_name) 6879 << 0 << Base->getSourceRange(); 6880 continue; 6881 } 6882 } else if (OASE) { 6883 auto BaseType = OMPArraySectionExpr::getBaseOriginalType(OASE->getBase()); 6884 if (auto *ATy = BaseType->getAsArrayTypeUnsafe()) 6885 Type = ATy->getElementType(); 6886 else 6887 Type = BaseType->getPointeeType(); 6888 auto *Base = OASE->getBase()->IgnoreParenImpCasts(); 6889 while (auto *TempOASE = dyn_cast<OMPArraySectionExpr>(Base)) 6890 Base = TempOASE->getBase()->IgnoreParenImpCasts(); 6891 while (auto *TempASE = dyn_cast<ArraySubscriptExpr>(Base)) 6892 Base = TempASE->getBase()->IgnoreParenImpCasts(); 6893 DE = dyn_cast<DeclRefExpr>(Base); 6894 if (DE) 6895 VD = dyn_cast<VarDecl>(DE->getDecl()); 6896 if (!VD) { 6897 Diag(Base->getExprLoc(), diag::err_omp_expected_base_var_name) 6898 << 1 << Base->getSourceRange(); 6899 continue; 6900 } 6901 } 6902 6903 // OpenMP [2.9.3.3, Restrictions, C/C++, p.3] 6904 // A variable that appears in a private clause must not have an incomplete 6905 // type or a reference type. 6906 if (RequireCompleteType(ELoc, Type, 6907 diag::err_omp_reduction_incomplete_type)) 6908 continue; 6909 // OpenMP [2.14.3.6, reduction clause, Restrictions] 6910 // Arrays may not appear in a reduction clause. 6911 if (Type.getNonReferenceType()->isArrayType()) { 6912 Diag(ELoc, diag::err_omp_reduction_type_array) << Type << ERange; 6913 if (!ASE && !OASE) { 6914 bool IsDecl = VD->isThisDeclarationADefinition(Context) == 6915 VarDecl::DeclarationOnly; 6916 Diag(VD->getLocation(), 6917 IsDecl ? diag::note_previous_decl : diag::note_defined_here) 6918 << VD; 6919 } 6920 continue; 6921 } 6922 // OpenMP [2.14.3.6, reduction clause, Restrictions] 6923 // A list item that appears in a reduction clause must not be 6924 // const-qualified. 6925 if (Type.getNonReferenceType().isConstant(Context)) { 6926 Diag(ELoc, diag::err_omp_const_reduction_list_item) 6927 << getOpenMPClauseName(OMPC_reduction) << Type << ERange; 6928 if (!ASE && !OASE) { 6929 bool IsDecl = VD->isThisDeclarationADefinition(Context) == 6930 VarDecl::DeclarationOnly; 6931 Diag(VD->getLocation(), 6932 IsDecl ? diag::note_previous_decl : diag::note_defined_here) 6933 << VD; 6934 } 6935 continue; 6936 } 6937 // OpenMP [2.9.3.6, Restrictions, C/C++, p.4] 6938 // If a list-item is a reference type then it must bind to the same object 6939 // for all threads of the team. 6940 if (!ASE && !OASE) { 6941 VarDecl *VDDef = VD->getDefinition(); 6942 if (Type->isReferenceType() && VDDef) { 6943 DSARefChecker Check(DSAStack); 6944 if (Check.Visit(VDDef->getInit())) { 6945 Diag(ELoc, diag::err_omp_reduction_ref_type_arg) << ERange; 6946 Diag(VDDef->getLocation(), diag::note_defined_here) << VDDef; 6947 continue; 6948 } 6949 } 6950 } 6951 // OpenMP [2.14.3.6, reduction clause, Restrictions] 6952 // The type of a list item that appears in a reduction clause must be valid 6953 // for the reduction-identifier. For a max or min reduction in C, the type 6954 // of the list item must be an allowed arithmetic data type: char, int, 6955 // float, double, or _Bool, possibly modified with long, short, signed, or 6956 // unsigned. For a max or min reduction in C++, the type of the list item 6957 // must be an allowed arithmetic data type: char, wchar_t, int, float, 6958 // double, or bool, possibly modified with long, short, signed, or unsigned. 6959 if ((BOK == BO_GT || BOK == BO_LT) && 6960 !(Type->isScalarType() || 6961 (getLangOpts().CPlusPlus && Type->isArithmeticType()))) { 6962 Diag(ELoc, diag::err_omp_clause_not_arithmetic_type_arg) 6963 << getLangOpts().CPlusPlus; 6964 if (!ASE && !OASE) { 6965 bool IsDecl = VD->isThisDeclarationADefinition(Context) == 6966 VarDecl::DeclarationOnly; 6967 Diag(VD->getLocation(), 6968 IsDecl ? diag::note_previous_decl : diag::note_defined_here) 6969 << VD; 6970 } 6971 continue; 6972 } 6973 if ((BOK == BO_OrAssign || BOK == BO_AndAssign || BOK == BO_XorAssign) && 6974 !getLangOpts().CPlusPlus && Type->isFloatingType()) { 6975 Diag(ELoc, diag::err_omp_clause_floating_type_arg); 6976 if (!ASE && !OASE) { 6977 bool IsDecl = VD->isThisDeclarationADefinition(Context) == 6978 VarDecl::DeclarationOnly; 6979 Diag(VD->getLocation(), 6980 IsDecl ? diag::note_previous_decl : diag::note_defined_here) 6981 << VD; 6982 } 6983 continue; 6984 } 6985 // OpenMP [2.14.1.1, Data-sharing Attribute Rules for Variables Referenced 6986 // in a Construct] 6987 // Variables with the predetermined data-sharing attributes may not be 6988 // listed in data-sharing attributes clauses, except for the cases 6989 // listed below. For these exceptions only, listing a predetermined 6990 // variable in a data-sharing attribute clause is allowed and overrides 6991 // the variable's predetermined data-sharing attributes. 6992 // OpenMP [2.14.3.6, Restrictions, p.3] 6993 // Any number of reduction clauses can be specified on the directive, 6994 // but a list item can appear only once in the reduction clauses for that 6995 // directive. 6996 DSAStackTy::DSAVarData DVar; 6997 DVar = DSAStack->getTopDSA(VD, false); 6998 if (DVar.CKind == OMPC_reduction) { 6999 Diag(ELoc, diag::err_omp_once_referenced) 7000 << getOpenMPClauseName(OMPC_reduction); 7001 if (DVar.RefExpr) { 7002 Diag(DVar.RefExpr->getExprLoc(), diag::note_omp_referenced); 7003 } 7004 } else if (DVar.CKind != OMPC_unknown) { 7005 Diag(ELoc, diag::err_omp_wrong_dsa) 7006 << getOpenMPClauseName(DVar.CKind) 7007 << getOpenMPClauseName(OMPC_reduction); 7008 ReportOriginalDSA(*this, DSAStack, VD, DVar); 7009 continue; 7010 } 7011 7012 // OpenMP [2.14.3.6, Restrictions, p.1] 7013 // A list item that appears in a reduction clause of a worksharing 7014 // construct must be shared in the parallel regions to which any of the 7015 // worksharing regions arising from the worksharing construct bind. 7016 OpenMPDirectiveKind CurrDir = DSAStack->getCurrentDirective(); 7017 if (isOpenMPWorksharingDirective(CurrDir) && 7018 !isOpenMPParallelDirective(CurrDir)) { 7019 DVar = DSAStack->getImplicitDSA(VD, true); 7020 if (DVar.CKind != OMPC_shared) { 7021 Diag(ELoc, diag::err_omp_required_access) 7022 << getOpenMPClauseName(OMPC_reduction) 7023 << getOpenMPClauseName(OMPC_shared); 7024 ReportOriginalDSA(*this, DSAStack, VD, DVar); 7025 continue; 7026 } 7027 } 7028 7029 Type = Type.getNonLValueExprType(Context).getUnqualifiedType(); 7030 auto *LHSVD = buildVarDecl(*this, ELoc, Type, ".reduction.lhs", 7031 VD->hasAttrs() ? &VD->getAttrs() : nullptr); 7032 auto *RHSVD = buildVarDecl(*this, ELoc, Type, VD->getName(), 7033 VD->hasAttrs() ? &VD->getAttrs() : nullptr); 7034 auto PrivateTy = Type; 7035 if (OASE) { 7036 // For array sections only: 7037 // Create pseudo array type for private copy. The size for this array will 7038 // be generated during codegen. 7039 // For array subscripts or single variables Private Ty is the same as Type 7040 // (type of the variable or single array element). 7041 PrivateTy = Context.getVariableArrayType( 7042 Type, new (Context) OpaqueValueExpr(SourceLocation(), 7043 Context.getSizeType(), VK_RValue), 7044 ArrayType::Normal, /*IndexTypeQuals=*/0, SourceRange()); 7045 } 7046 // Private copy. 7047 auto *PrivateVD = buildVarDecl(*this, ELoc, PrivateTy, VD->getName(), 7048 VD->hasAttrs() ? &VD->getAttrs() : nullptr); 7049 // Add initializer for private variable. 7050 Expr *Init = nullptr; 7051 switch (BOK) { 7052 case BO_Add: 7053 case BO_Xor: 7054 case BO_Or: 7055 case BO_LOr: 7056 // '+', '-', '^', '|', '||' reduction ops - initializer is '0'. 7057 if (Type->isScalarType() || Type->isAnyComplexType()) { 7058 Init = ActOnIntegerConstant(ELoc, /*Val=*/0).get(); 7059 } 7060 break; 7061 case BO_Mul: 7062 case BO_LAnd: 7063 if (Type->isScalarType() || Type->isAnyComplexType()) { 7064 // '*' and '&&' reduction ops - initializer is '1'. 7065 Init = ActOnIntegerConstant(ELoc, /*Val=*/1).get(); 7066 } 7067 break; 7068 case BO_And: { 7069 // '&' reduction op - initializer is '~0'. 7070 QualType OrigType = Type; 7071 if (auto *ComplexTy = OrigType->getAs<ComplexType>()) { 7072 Type = ComplexTy->getElementType(); 7073 } 7074 if (Type->isRealFloatingType()) { 7075 llvm::APFloat InitValue = 7076 llvm::APFloat::getAllOnesValue(Context.getTypeSize(Type), 7077 /*isIEEE=*/true); 7078 Init = FloatingLiteral::Create(Context, InitValue, /*isexact=*/true, 7079 Type, ELoc); 7080 } else if (Type->isScalarType()) { 7081 auto Size = Context.getTypeSize(Type); 7082 QualType IntTy = Context.getIntTypeForBitwidth(Size, /*Signed=*/0); 7083 llvm::APInt InitValue = llvm::APInt::getAllOnesValue(Size); 7084 Init = IntegerLiteral::Create(Context, InitValue, IntTy, ELoc); 7085 } 7086 if (Init && OrigType->isAnyComplexType()) { 7087 // Init = 0xFFFF + 0xFFFFi; 7088 auto *Im = new (Context) ImaginaryLiteral(Init, OrigType); 7089 Init = CreateBuiltinBinOp(ELoc, BO_Add, Init, Im).get(); 7090 } 7091 Type = OrigType; 7092 break; 7093 } 7094 case BO_LT: 7095 case BO_GT: { 7096 // 'min' reduction op - initializer is 'Largest representable number in 7097 // the reduction list item type'. 7098 // 'max' reduction op - initializer is 'Least representable number in 7099 // the reduction list item type'. 7100 if (Type->isIntegerType() || Type->isPointerType()) { 7101 bool IsSigned = Type->hasSignedIntegerRepresentation(); 7102 auto Size = Context.getTypeSize(Type); 7103 QualType IntTy = 7104 Context.getIntTypeForBitwidth(Size, /*Signed=*/IsSigned); 7105 llvm::APInt InitValue = 7106 (BOK != BO_LT) 7107 ? IsSigned ? llvm::APInt::getSignedMinValue(Size) 7108 : llvm::APInt::getMinValue(Size) 7109 : IsSigned ? llvm::APInt::getSignedMaxValue(Size) 7110 : llvm::APInt::getMaxValue(Size); 7111 Init = IntegerLiteral::Create(Context, InitValue, IntTy, ELoc); 7112 if (Type->isPointerType()) { 7113 // Cast to pointer type. 7114 auto CastExpr = BuildCStyleCastExpr( 7115 SourceLocation(), Context.getTrivialTypeSourceInfo(Type, ELoc), 7116 SourceLocation(), Init); 7117 if (CastExpr.isInvalid()) 7118 continue; 7119 Init = CastExpr.get(); 7120 } 7121 } else if (Type->isRealFloatingType()) { 7122 llvm::APFloat InitValue = llvm::APFloat::getLargest( 7123 Context.getFloatTypeSemantics(Type), BOK != BO_LT); 7124 Init = FloatingLiteral::Create(Context, InitValue, /*isexact=*/true, 7125 Type, ELoc); 7126 } 7127 break; 7128 } 7129 case BO_PtrMemD: 7130 case BO_PtrMemI: 7131 case BO_MulAssign: 7132 case BO_Div: 7133 case BO_Rem: 7134 case BO_Sub: 7135 case BO_Shl: 7136 case BO_Shr: 7137 case BO_LE: 7138 case BO_GE: 7139 case BO_EQ: 7140 case BO_NE: 7141 case BO_AndAssign: 7142 case BO_XorAssign: 7143 case BO_OrAssign: 7144 case BO_Assign: 7145 case BO_AddAssign: 7146 case BO_SubAssign: 7147 case BO_DivAssign: 7148 case BO_RemAssign: 7149 case BO_ShlAssign: 7150 case BO_ShrAssign: 7151 case BO_Comma: 7152 llvm_unreachable("Unexpected reduction operation"); 7153 } 7154 if (Init) { 7155 AddInitializerToDecl(RHSVD, Init, /*DirectInit=*/false, 7156 /*TypeMayContainAuto=*/false); 7157 } else 7158 ActOnUninitializedDecl(RHSVD, /*TypeMayContainAuto=*/false); 7159 if (!RHSVD->hasInit()) { 7160 Diag(ELoc, diag::err_omp_reduction_id_not_compatible) << Type 7161 << ReductionIdRange; 7162 if (VD) { 7163 bool IsDecl = VD->isThisDeclarationADefinition(Context) == 7164 VarDecl::DeclarationOnly; 7165 Diag(VD->getLocation(), 7166 IsDecl ? diag::note_previous_decl : diag::note_defined_here) 7167 << VD; 7168 } 7169 continue; 7170 } 7171 // Store initializer for single element in private copy. Will be used during 7172 // codegen. 7173 PrivateVD->setInit(RHSVD->getInit()); 7174 PrivateVD->setInitStyle(RHSVD->getInitStyle()); 7175 auto *LHSDRE = buildDeclRefExpr(*this, LHSVD, Type, ELoc); 7176 auto *RHSDRE = buildDeclRefExpr(*this, RHSVD, Type, ELoc); 7177 auto *PrivateDRE = buildDeclRefExpr(*this, PrivateVD, PrivateTy, ELoc); 7178 ExprResult ReductionOp = 7179 BuildBinOp(DSAStack->getCurScope(), ReductionId.getLocStart(), BOK, 7180 LHSDRE, RHSDRE); 7181 if (ReductionOp.isUsable()) { 7182 if (BOK != BO_LT && BOK != BO_GT) { 7183 ReductionOp = 7184 BuildBinOp(DSAStack->getCurScope(), ReductionId.getLocStart(), 7185 BO_Assign, LHSDRE, ReductionOp.get()); 7186 } else { 7187 auto *ConditionalOp = new (Context) ConditionalOperator( 7188 ReductionOp.get(), SourceLocation(), LHSDRE, SourceLocation(), 7189 RHSDRE, Type, VK_LValue, OK_Ordinary); 7190 ReductionOp = 7191 BuildBinOp(DSAStack->getCurScope(), ReductionId.getLocStart(), 7192 BO_Assign, LHSDRE, ConditionalOp); 7193 } 7194 ReductionOp = ActOnFinishFullExpr(ReductionOp.get()); 7195 } 7196 if (ReductionOp.isInvalid()) 7197 continue; 7198 7199 DSAStack->addDSA(VD, DE, OMPC_reduction); 7200 Vars.push_back(RefExpr); 7201 Privates.push_back(PrivateDRE); 7202 LHSs.push_back(LHSDRE); 7203 RHSs.push_back(RHSDRE); 7204 ReductionOps.push_back(ReductionOp.get()); 7205 } 7206 7207 if (Vars.empty()) 7208 return nullptr; 7209 7210 return OMPReductionClause::Create( 7211 Context, StartLoc, LParenLoc, ColonLoc, EndLoc, Vars, 7212 ReductionIdScopeSpec.getWithLocInContext(Context), ReductionId, Privates, 7213 LHSs, RHSs, ReductionOps); 7214 } 7215 7216 OMPClause *Sema::ActOnOpenMPLinearClause( 7217 ArrayRef<Expr *> VarList, Expr *Step, SourceLocation StartLoc, 7218 SourceLocation LParenLoc, OpenMPLinearClauseKind LinKind, 7219 SourceLocation LinLoc, SourceLocation ColonLoc, SourceLocation EndLoc) { 7220 SmallVector<Expr *, 8> Vars; 7221 SmallVector<Expr *, 8> Privates; 7222 SmallVector<Expr *, 8> Inits; 7223 if ((!LangOpts.CPlusPlus && LinKind != OMPC_LINEAR_val) || 7224 LinKind == OMPC_LINEAR_unknown) { 7225 Diag(LinLoc, diag::err_omp_wrong_linear_modifier) << LangOpts.CPlusPlus; 7226 LinKind = OMPC_LINEAR_val; 7227 } 7228 for (auto &RefExpr : VarList) { 7229 assert(RefExpr && "NULL expr in OpenMP linear clause."); 7230 if (isa<DependentScopeDeclRefExpr>(RefExpr)) { 7231 // It will be analyzed later. 7232 Vars.push_back(RefExpr); 7233 Privates.push_back(nullptr); 7234 Inits.push_back(nullptr); 7235 continue; 7236 } 7237 7238 // OpenMP [2.14.3.7, linear clause] 7239 // A list item that appears in a linear clause is subject to the private 7240 // clause semantics described in Section 2.14.3.3 on page 159 except as 7241 // noted. In addition, the value of the new list item on each iteration 7242 // of the associated loop(s) corresponds to the value of the original 7243 // list item before entering the construct plus the logical number of 7244 // the iteration times linear-step. 7245 7246 SourceLocation ELoc = RefExpr->getExprLoc(); 7247 // OpenMP [2.1, C/C++] 7248 // A list item is a variable name. 7249 // OpenMP [2.14.3.3, Restrictions, p.1] 7250 // A variable that is part of another variable (as an array or 7251 // structure element) cannot appear in a private clause. 7252 DeclRefExpr *DE = dyn_cast<DeclRefExpr>(RefExpr); 7253 if (!DE || !isa<VarDecl>(DE->getDecl())) { 7254 Diag(ELoc, diag::err_omp_expected_var_name) << RefExpr->getSourceRange(); 7255 continue; 7256 } 7257 7258 VarDecl *VD = cast<VarDecl>(DE->getDecl()); 7259 7260 // OpenMP [2.14.3.7, linear clause] 7261 // A list-item cannot appear in more than one linear clause. 7262 // A list-item that appears in a linear clause cannot appear in any 7263 // other data-sharing attribute clause. 7264 DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(VD, false); 7265 if (DVar.RefExpr) { 7266 Diag(ELoc, diag::err_omp_wrong_dsa) << getOpenMPClauseName(DVar.CKind) 7267 << getOpenMPClauseName(OMPC_linear); 7268 ReportOriginalDSA(*this, DSAStack, VD, DVar); 7269 continue; 7270 } 7271 7272 QualType QType = VD->getType(); 7273 if (QType->isDependentType() || QType->isInstantiationDependentType()) { 7274 // It will be analyzed later. 7275 Vars.push_back(DE); 7276 Privates.push_back(nullptr); 7277 Inits.push_back(nullptr); 7278 continue; 7279 } 7280 7281 // A variable must not have an incomplete type or a reference type. 7282 if (RequireCompleteType(ELoc, QType, 7283 diag::err_omp_linear_incomplete_type)) { 7284 continue; 7285 } 7286 if ((LinKind == OMPC_LINEAR_uval || LinKind == OMPC_LINEAR_ref) && 7287 !QType->isReferenceType()) { 7288 Diag(ELoc, diag::err_omp_wrong_linear_modifier_non_reference) 7289 << QType << getOpenMPSimpleClauseTypeName(OMPC_linear, LinKind); 7290 continue; 7291 } 7292 QType = QType.getNonReferenceType(); 7293 7294 // A list item must not be const-qualified. 7295 if (QType.isConstant(Context)) { 7296 Diag(ELoc, diag::err_omp_const_variable) 7297 << getOpenMPClauseName(OMPC_linear); 7298 bool IsDecl = 7299 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly; 7300 Diag(VD->getLocation(), 7301 IsDecl ? diag::note_previous_decl : diag::note_defined_here) 7302 << VD; 7303 continue; 7304 } 7305 7306 // A list item must be of integral or pointer type. 7307 QType = QType.getUnqualifiedType().getCanonicalType(); 7308 const Type *Ty = QType.getTypePtrOrNull(); 7309 if (!Ty || (!Ty->isDependentType() && !Ty->isIntegralType(Context) && 7310 !Ty->isPointerType())) { 7311 Diag(ELoc, diag::err_omp_linear_expected_int_or_ptr) << QType; 7312 bool IsDecl = 7313 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly; 7314 Diag(VD->getLocation(), 7315 IsDecl ? diag::note_previous_decl : diag::note_defined_here) 7316 << VD; 7317 continue; 7318 } 7319 7320 // Build private copy of original var. 7321 auto *Private = buildVarDecl(*this, ELoc, QType, VD->getName(), 7322 VD->hasAttrs() ? &VD->getAttrs() : nullptr); 7323 auto *PrivateRef = buildDeclRefExpr( 7324 *this, Private, DE->getType().getUnqualifiedType(), DE->getExprLoc()); 7325 // Build var to save initial value. 7326 VarDecl *Init = buildVarDecl(*this, ELoc, QType, ".linear.start"); 7327 Expr *InitExpr; 7328 if (LinKind == OMPC_LINEAR_uval) 7329 InitExpr = VD->getInit(); 7330 else 7331 InitExpr = DE; 7332 AddInitializerToDecl(Init, DefaultLvalueConversion(InitExpr).get(), 7333 /*DirectInit*/ false, /*TypeMayContainAuto*/ false); 7334 auto InitRef = buildDeclRefExpr( 7335 *this, Init, DE->getType().getUnqualifiedType(), DE->getExprLoc()); 7336 DSAStack->addDSA(VD, DE, OMPC_linear); 7337 Vars.push_back(DE); 7338 Privates.push_back(PrivateRef); 7339 Inits.push_back(InitRef); 7340 } 7341 7342 if (Vars.empty()) 7343 return nullptr; 7344 7345 Expr *StepExpr = Step; 7346 Expr *CalcStepExpr = nullptr; 7347 if (Step && !Step->isValueDependent() && !Step->isTypeDependent() && 7348 !Step->isInstantiationDependent() && 7349 !Step->containsUnexpandedParameterPack()) { 7350 SourceLocation StepLoc = Step->getLocStart(); 7351 ExprResult Val = PerformOpenMPImplicitIntegerConversion(StepLoc, Step); 7352 if (Val.isInvalid()) 7353 return nullptr; 7354 StepExpr = Val.get(); 7355 7356 // Build var to save the step value. 7357 VarDecl *SaveVar = 7358 buildVarDecl(*this, StepLoc, StepExpr->getType(), ".linear.step"); 7359 ExprResult SaveRef = 7360 buildDeclRefExpr(*this, SaveVar, StepExpr->getType(), StepLoc); 7361 ExprResult CalcStep = 7362 BuildBinOp(CurScope, StepLoc, BO_Assign, SaveRef.get(), StepExpr); 7363 CalcStep = ActOnFinishFullExpr(CalcStep.get()); 7364 7365 // Warn about zero linear step (it would be probably better specified as 7366 // making corresponding variables 'const'). 7367 llvm::APSInt Result; 7368 bool IsConstant = StepExpr->isIntegerConstantExpr(Result, Context); 7369 if (IsConstant && !Result.isNegative() && !Result.isStrictlyPositive()) 7370 Diag(StepLoc, diag::warn_omp_linear_step_zero) << Vars[0] 7371 << (Vars.size() > 1); 7372 if (!IsConstant && CalcStep.isUsable()) { 7373 // Calculate the step beforehand instead of doing this on each iteration. 7374 // (This is not used if the number of iterations may be kfold-ed). 7375 CalcStepExpr = CalcStep.get(); 7376 } 7377 } 7378 7379 return OMPLinearClause::Create(Context, StartLoc, LParenLoc, LinKind, LinLoc, 7380 ColonLoc, EndLoc, Vars, Privates, Inits, 7381 StepExpr, CalcStepExpr); 7382 } 7383 7384 static bool FinishOpenMPLinearClause(OMPLinearClause &Clause, DeclRefExpr *IV, 7385 Expr *NumIterations, Sema &SemaRef, 7386 Scope *S) { 7387 // Walk the vars and build update/final expressions for the CodeGen. 7388 SmallVector<Expr *, 8> Updates; 7389 SmallVector<Expr *, 8> Finals; 7390 Expr *Step = Clause.getStep(); 7391 Expr *CalcStep = Clause.getCalcStep(); 7392 // OpenMP [2.14.3.7, linear clause] 7393 // If linear-step is not specified it is assumed to be 1. 7394 if (Step == nullptr) 7395 Step = SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get(); 7396 else if (CalcStep) 7397 Step = cast<BinaryOperator>(CalcStep)->getLHS(); 7398 bool HasErrors = false; 7399 auto CurInit = Clause.inits().begin(); 7400 auto CurPrivate = Clause.privates().begin(); 7401 auto LinKind = Clause.getModifier(); 7402 for (auto &RefExpr : Clause.varlists()) { 7403 Expr *InitExpr = *CurInit; 7404 7405 // Build privatized reference to the current linear var. 7406 auto DE = cast<DeclRefExpr>(RefExpr); 7407 Expr *CapturedRef; 7408 if (LinKind == OMPC_LINEAR_uval) 7409 CapturedRef = cast<VarDecl>(DE->getDecl())->getInit(); 7410 else 7411 CapturedRef = 7412 buildDeclRefExpr(SemaRef, cast<VarDecl>(DE->getDecl()), 7413 DE->getType().getUnqualifiedType(), DE->getExprLoc(), 7414 /*RefersToCapture=*/true); 7415 7416 // Build update: Var = InitExpr + IV * Step 7417 ExprResult Update = 7418 BuildCounterUpdate(SemaRef, S, RefExpr->getExprLoc(), *CurPrivate, 7419 InitExpr, IV, Step, /* Subtract */ false); 7420 Update = SemaRef.ActOnFinishFullExpr(Update.get(), DE->getLocStart(), 7421 /*DiscardedValue=*/true); 7422 7423 // Build final: Var = InitExpr + NumIterations * Step 7424 ExprResult Final = 7425 BuildCounterUpdate(SemaRef, S, RefExpr->getExprLoc(), CapturedRef, 7426 InitExpr, NumIterations, Step, /* Subtract */ false); 7427 Final = SemaRef.ActOnFinishFullExpr(Final.get(), DE->getLocStart(), 7428 /*DiscardedValue=*/true); 7429 if (!Update.isUsable() || !Final.isUsable()) { 7430 Updates.push_back(nullptr); 7431 Finals.push_back(nullptr); 7432 HasErrors = true; 7433 } else { 7434 Updates.push_back(Update.get()); 7435 Finals.push_back(Final.get()); 7436 } 7437 ++CurInit, ++CurPrivate; 7438 } 7439 Clause.setUpdates(Updates); 7440 Clause.setFinals(Finals); 7441 return HasErrors; 7442 } 7443 7444 OMPClause *Sema::ActOnOpenMPAlignedClause( 7445 ArrayRef<Expr *> VarList, Expr *Alignment, SourceLocation StartLoc, 7446 SourceLocation LParenLoc, SourceLocation ColonLoc, SourceLocation EndLoc) { 7447 7448 SmallVector<Expr *, 8> Vars; 7449 for (auto &RefExpr : VarList) { 7450 assert(RefExpr && "NULL expr in OpenMP aligned clause."); 7451 if (isa<DependentScopeDeclRefExpr>(RefExpr)) { 7452 // It will be analyzed later. 7453 Vars.push_back(RefExpr); 7454 continue; 7455 } 7456 7457 SourceLocation ELoc = RefExpr->getExprLoc(); 7458 // OpenMP [2.1, C/C++] 7459 // A list item is a variable name. 7460 DeclRefExpr *DE = dyn_cast<DeclRefExpr>(RefExpr); 7461 if (!DE || !isa<VarDecl>(DE->getDecl())) { 7462 Diag(ELoc, diag::err_omp_expected_var_name) << RefExpr->getSourceRange(); 7463 continue; 7464 } 7465 7466 VarDecl *VD = cast<VarDecl>(DE->getDecl()); 7467 7468 // OpenMP [2.8.1, simd construct, Restrictions] 7469 // The type of list items appearing in the aligned clause must be 7470 // array, pointer, reference to array, or reference to pointer. 7471 QualType QType = VD->getType(); 7472 QType = QType.getNonReferenceType().getUnqualifiedType().getCanonicalType(); 7473 const Type *Ty = QType.getTypePtrOrNull(); 7474 if (!Ty || (!Ty->isDependentType() && !Ty->isArrayType() && 7475 !Ty->isPointerType())) { 7476 Diag(ELoc, diag::err_omp_aligned_expected_array_or_ptr) 7477 << QType << getLangOpts().CPlusPlus << RefExpr->getSourceRange(); 7478 bool IsDecl = 7479 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly; 7480 Diag(VD->getLocation(), 7481 IsDecl ? diag::note_previous_decl : diag::note_defined_here) 7482 << VD; 7483 continue; 7484 } 7485 7486 // OpenMP [2.8.1, simd construct, Restrictions] 7487 // A list-item cannot appear in more than one aligned clause. 7488 if (DeclRefExpr *PrevRef = DSAStack->addUniqueAligned(VD, DE)) { 7489 Diag(ELoc, diag::err_omp_aligned_twice) << RefExpr->getSourceRange(); 7490 Diag(PrevRef->getExprLoc(), diag::note_omp_explicit_dsa) 7491 << getOpenMPClauseName(OMPC_aligned); 7492 continue; 7493 } 7494 7495 Vars.push_back(DE); 7496 } 7497 7498 // OpenMP [2.8.1, simd construct, Description] 7499 // The parameter of the aligned clause, alignment, must be a constant 7500 // positive integer expression. 7501 // If no optional parameter is specified, implementation-defined default 7502 // alignments for SIMD instructions on the target platforms are assumed. 7503 if (Alignment != nullptr) { 7504 ExprResult AlignResult = 7505 VerifyPositiveIntegerConstantInClause(Alignment, OMPC_aligned); 7506 if (AlignResult.isInvalid()) 7507 return nullptr; 7508 Alignment = AlignResult.get(); 7509 } 7510 if (Vars.empty()) 7511 return nullptr; 7512 7513 return OMPAlignedClause::Create(Context, StartLoc, LParenLoc, ColonLoc, 7514 EndLoc, Vars, Alignment); 7515 } 7516 7517 OMPClause *Sema::ActOnOpenMPCopyinClause(ArrayRef<Expr *> VarList, 7518 SourceLocation StartLoc, 7519 SourceLocation LParenLoc, 7520 SourceLocation EndLoc) { 7521 SmallVector<Expr *, 8> Vars; 7522 SmallVector<Expr *, 8> SrcExprs; 7523 SmallVector<Expr *, 8> DstExprs; 7524 SmallVector<Expr *, 8> AssignmentOps; 7525 for (auto &RefExpr : VarList) { 7526 assert(RefExpr && "NULL expr in OpenMP copyin clause."); 7527 if (isa<DependentScopeDeclRefExpr>(RefExpr)) { 7528 // It will be analyzed later. 7529 Vars.push_back(RefExpr); 7530 SrcExprs.push_back(nullptr); 7531 DstExprs.push_back(nullptr); 7532 AssignmentOps.push_back(nullptr); 7533 continue; 7534 } 7535 7536 SourceLocation ELoc = RefExpr->getExprLoc(); 7537 // OpenMP [2.1, C/C++] 7538 // A list item is a variable name. 7539 // OpenMP [2.14.4.1, Restrictions, p.1] 7540 // A list item that appears in a copyin clause must be threadprivate. 7541 DeclRefExpr *DE = dyn_cast<DeclRefExpr>(RefExpr); 7542 if (!DE || !isa<VarDecl>(DE->getDecl())) { 7543 Diag(ELoc, diag::err_omp_expected_var_name) << RefExpr->getSourceRange(); 7544 continue; 7545 } 7546 7547 Decl *D = DE->getDecl(); 7548 VarDecl *VD = cast<VarDecl>(D); 7549 7550 QualType Type = VD->getType(); 7551 if (Type->isDependentType() || Type->isInstantiationDependentType()) { 7552 // It will be analyzed later. 7553 Vars.push_back(DE); 7554 SrcExprs.push_back(nullptr); 7555 DstExprs.push_back(nullptr); 7556 AssignmentOps.push_back(nullptr); 7557 continue; 7558 } 7559 7560 // OpenMP [2.14.4.1, Restrictions, C/C++, p.1] 7561 // A list item that appears in a copyin clause must be threadprivate. 7562 if (!DSAStack->isThreadPrivate(VD)) { 7563 Diag(ELoc, diag::err_omp_required_access) 7564 << getOpenMPClauseName(OMPC_copyin) 7565 << getOpenMPDirectiveName(OMPD_threadprivate); 7566 continue; 7567 } 7568 7569 // OpenMP [2.14.4.1, Restrictions, C/C++, p.2] 7570 // A variable of class type (or array thereof) that appears in a 7571 // copyin clause requires an accessible, unambiguous copy assignment 7572 // operator for the class type. 7573 auto ElemType = Context.getBaseElementType(Type).getNonReferenceType(); 7574 auto *SrcVD = 7575 buildVarDecl(*this, DE->getLocStart(), ElemType.getUnqualifiedType(), 7576 ".copyin.src", VD->hasAttrs() ? &VD->getAttrs() : nullptr); 7577 auto *PseudoSrcExpr = buildDeclRefExpr( 7578 *this, SrcVD, ElemType.getUnqualifiedType(), DE->getExprLoc()); 7579 auto *DstVD = 7580 buildVarDecl(*this, DE->getLocStart(), ElemType, ".copyin.dst", 7581 VD->hasAttrs() ? &VD->getAttrs() : nullptr); 7582 auto *PseudoDstExpr = 7583 buildDeclRefExpr(*this, DstVD, ElemType, DE->getExprLoc()); 7584 // For arrays generate assignment operation for single element and replace 7585 // it by the original array element in CodeGen. 7586 auto AssignmentOp = BuildBinOp(/*S=*/nullptr, DE->getExprLoc(), BO_Assign, 7587 PseudoDstExpr, PseudoSrcExpr); 7588 if (AssignmentOp.isInvalid()) 7589 continue; 7590 AssignmentOp = ActOnFinishFullExpr(AssignmentOp.get(), DE->getExprLoc(), 7591 /*DiscardedValue=*/true); 7592 if (AssignmentOp.isInvalid()) 7593 continue; 7594 7595 DSAStack->addDSA(VD, DE, OMPC_copyin); 7596 Vars.push_back(DE); 7597 SrcExprs.push_back(PseudoSrcExpr); 7598 DstExprs.push_back(PseudoDstExpr); 7599 AssignmentOps.push_back(AssignmentOp.get()); 7600 } 7601 7602 if (Vars.empty()) 7603 return nullptr; 7604 7605 return OMPCopyinClause::Create(Context, StartLoc, LParenLoc, EndLoc, Vars, 7606 SrcExprs, DstExprs, AssignmentOps); 7607 } 7608 7609 OMPClause *Sema::ActOnOpenMPCopyprivateClause(ArrayRef<Expr *> VarList, 7610 SourceLocation StartLoc, 7611 SourceLocation LParenLoc, 7612 SourceLocation EndLoc) { 7613 SmallVector<Expr *, 8> Vars; 7614 SmallVector<Expr *, 8> SrcExprs; 7615 SmallVector<Expr *, 8> DstExprs; 7616 SmallVector<Expr *, 8> AssignmentOps; 7617 for (auto &RefExpr : VarList) { 7618 assert(RefExpr && "NULL expr in OpenMP copyprivate clause."); 7619 if (isa<DependentScopeDeclRefExpr>(RefExpr)) { 7620 // It will be analyzed later. 7621 Vars.push_back(RefExpr); 7622 SrcExprs.push_back(nullptr); 7623 DstExprs.push_back(nullptr); 7624 AssignmentOps.push_back(nullptr); 7625 continue; 7626 } 7627 7628 SourceLocation ELoc = RefExpr->getExprLoc(); 7629 // OpenMP [2.1, C/C++] 7630 // A list item is a variable name. 7631 // OpenMP [2.14.4.1, Restrictions, p.1] 7632 // A list item that appears in a copyin clause must be threadprivate. 7633 DeclRefExpr *DE = dyn_cast<DeclRefExpr>(RefExpr); 7634 if (!DE || !isa<VarDecl>(DE->getDecl())) { 7635 Diag(ELoc, diag::err_omp_expected_var_name) << RefExpr->getSourceRange(); 7636 continue; 7637 } 7638 7639 Decl *D = DE->getDecl(); 7640 VarDecl *VD = cast<VarDecl>(D); 7641 7642 QualType Type = VD->getType(); 7643 if (Type->isDependentType() || Type->isInstantiationDependentType()) { 7644 // It will be analyzed later. 7645 Vars.push_back(DE); 7646 SrcExprs.push_back(nullptr); 7647 DstExprs.push_back(nullptr); 7648 AssignmentOps.push_back(nullptr); 7649 continue; 7650 } 7651 7652 // OpenMP [2.14.4.2, Restrictions, p.2] 7653 // A list item that appears in a copyprivate clause may not appear in a 7654 // private or firstprivate clause on the single construct. 7655 if (!DSAStack->isThreadPrivate(VD)) { 7656 auto DVar = DSAStack->getTopDSA(VD, false); 7657 if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_copyprivate && 7658 DVar.RefExpr) { 7659 Diag(ELoc, diag::err_omp_wrong_dsa) 7660 << getOpenMPClauseName(DVar.CKind) 7661 << getOpenMPClauseName(OMPC_copyprivate); 7662 ReportOriginalDSA(*this, DSAStack, VD, DVar); 7663 continue; 7664 } 7665 7666 // OpenMP [2.11.4.2, Restrictions, p.1] 7667 // All list items that appear in a copyprivate clause must be either 7668 // threadprivate or private in the enclosing context. 7669 if (DVar.CKind == OMPC_unknown) { 7670 DVar = DSAStack->getImplicitDSA(VD, false); 7671 if (DVar.CKind == OMPC_shared) { 7672 Diag(ELoc, diag::err_omp_required_access) 7673 << getOpenMPClauseName(OMPC_copyprivate) 7674 << "threadprivate or private in the enclosing context"; 7675 ReportOriginalDSA(*this, DSAStack, VD, DVar); 7676 continue; 7677 } 7678 } 7679 } 7680 7681 // Variably modified types are not supported. 7682 if (!Type->isAnyPointerType() && Type->isVariablyModifiedType()) { 7683 Diag(ELoc, diag::err_omp_variably_modified_type_not_supported) 7684 << getOpenMPClauseName(OMPC_copyprivate) << Type 7685 << getOpenMPDirectiveName(DSAStack->getCurrentDirective()); 7686 bool IsDecl = 7687 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly; 7688 Diag(VD->getLocation(), 7689 IsDecl ? diag::note_previous_decl : diag::note_defined_here) 7690 << VD; 7691 continue; 7692 } 7693 7694 // OpenMP [2.14.4.1, Restrictions, C/C++, p.2] 7695 // A variable of class type (or array thereof) that appears in a 7696 // copyin clause requires an accessible, unambiguous copy assignment 7697 // operator for the class type. 7698 Type = Context.getBaseElementType(Type.getNonReferenceType()) 7699 .getUnqualifiedType(); 7700 auto *SrcVD = 7701 buildVarDecl(*this, DE->getLocStart(), Type, ".copyprivate.src", 7702 VD->hasAttrs() ? &VD->getAttrs() : nullptr); 7703 auto *PseudoSrcExpr = 7704 buildDeclRefExpr(*this, SrcVD, Type, DE->getExprLoc()); 7705 auto *DstVD = 7706 buildVarDecl(*this, DE->getLocStart(), Type, ".copyprivate.dst", 7707 VD->hasAttrs() ? &VD->getAttrs() : nullptr); 7708 auto *PseudoDstExpr = 7709 buildDeclRefExpr(*this, DstVD, Type, DE->getExprLoc()); 7710 auto AssignmentOp = BuildBinOp(/*S=*/nullptr, DE->getExprLoc(), BO_Assign, 7711 PseudoDstExpr, PseudoSrcExpr); 7712 if (AssignmentOp.isInvalid()) 7713 continue; 7714 AssignmentOp = ActOnFinishFullExpr(AssignmentOp.get(), DE->getExprLoc(), 7715 /*DiscardedValue=*/true); 7716 if (AssignmentOp.isInvalid()) 7717 continue; 7718 7719 // No need to mark vars as copyprivate, they are already threadprivate or 7720 // implicitly private. 7721 Vars.push_back(DE); 7722 SrcExprs.push_back(PseudoSrcExpr); 7723 DstExprs.push_back(PseudoDstExpr); 7724 AssignmentOps.push_back(AssignmentOp.get()); 7725 } 7726 7727 if (Vars.empty()) 7728 return nullptr; 7729 7730 return OMPCopyprivateClause::Create(Context, StartLoc, LParenLoc, EndLoc, 7731 Vars, SrcExprs, DstExprs, AssignmentOps); 7732 } 7733 7734 OMPClause *Sema::ActOnOpenMPFlushClause(ArrayRef<Expr *> VarList, 7735 SourceLocation StartLoc, 7736 SourceLocation LParenLoc, 7737 SourceLocation EndLoc) { 7738 if (VarList.empty()) 7739 return nullptr; 7740 7741 return OMPFlushClause::Create(Context, StartLoc, LParenLoc, EndLoc, VarList); 7742 } 7743 7744 OMPClause * 7745 Sema::ActOnOpenMPDependClause(OpenMPDependClauseKind DepKind, 7746 SourceLocation DepLoc, SourceLocation ColonLoc, 7747 ArrayRef<Expr *> VarList, SourceLocation StartLoc, 7748 SourceLocation LParenLoc, SourceLocation EndLoc) { 7749 if (DepKind == OMPC_DEPEND_unknown) { 7750 std::string Values; 7751 std::string Sep(", "); 7752 for (unsigned i = 0; i < OMPC_DEPEND_unknown; ++i) { 7753 Values += "'"; 7754 Values += getOpenMPSimpleClauseTypeName(OMPC_depend, i); 7755 Values += "'"; 7756 switch (i) { 7757 case OMPC_DEPEND_unknown - 2: 7758 Values += " or "; 7759 break; 7760 case OMPC_DEPEND_unknown - 1: 7761 break; 7762 default: 7763 Values += Sep; 7764 break; 7765 } 7766 } 7767 Diag(DepLoc, diag::err_omp_unexpected_clause_value) 7768 << Values << getOpenMPClauseName(OMPC_depend); 7769 return nullptr; 7770 } 7771 SmallVector<Expr *, 8> Vars; 7772 for (auto &RefExpr : VarList) { 7773 assert(RefExpr && "NULL expr in OpenMP shared clause."); 7774 if (isa<DependentScopeDeclRefExpr>(RefExpr)) { 7775 // It will be analyzed later. 7776 Vars.push_back(RefExpr); 7777 continue; 7778 } 7779 7780 SourceLocation ELoc = RefExpr->getExprLoc(); 7781 // OpenMP [2.11.1.1, Restrictions, p.3] 7782 // A variable that is part of another variable (such as a field of a 7783 // structure) but is not an array element or an array section cannot appear 7784 // in a depend clause. 7785 auto *SimpleExpr = RefExpr->IgnoreParenCasts(); 7786 auto *DE = dyn_cast<DeclRefExpr>(SimpleExpr); 7787 auto *ASE = dyn_cast<ArraySubscriptExpr>(SimpleExpr); 7788 auto *OASE = dyn_cast<OMPArraySectionExpr>(SimpleExpr); 7789 if (!RefExpr->IgnoreParenImpCasts()->isLValue() || 7790 (!ASE && !DE && !OASE) || (DE && !isa<VarDecl>(DE->getDecl())) || 7791 (ASE && !ASE->getBase()->getType()->isAnyPointerType() && 7792 !ASE->getBase()->getType()->isArrayType())) { 7793 Diag(ELoc, diag::err_omp_expected_var_name_or_array_item) 7794 << RefExpr->getSourceRange(); 7795 continue; 7796 } 7797 7798 Vars.push_back(RefExpr->IgnoreParenImpCasts()); 7799 } 7800 7801 if (Vars.empty()) 7802 return nullptr; 7803 7804 return OMPDependClause::Create(Context, StartLoc, LParenLoc, EndLoc, DepKind, 7805 DepLoc, ColonLoc, Vars); 7806 } 7807 7808 OMPClause *Sema::ActOnOpenMPDeviceClause(Expr *Device, SourceLocation StartLoc, 7809 SourceLocation LParenLoc, 7810 SourceLocation EndLoc) { 7811 Expr *ValExpr = Device; 7812 7813 // OpenMP [2.9.1, Restrictions] 7814 // The device expression must evaluate to a non-negative integer value. 7815 if (!IsNonNegativeIntegerValue(ValExpr, *this, OMPC_device, 7816 /*StrictlyPositive=*/false)) 7817 return nullptr; 7818 7819 return new (Context) OMPDeviceClause(ValExpr, StartLoc, LParenLoc, EndLoc); 7820 } 7821 7822 static bool IsCXXRecordForMappable(Sema &SemaRef, SourceLocation Loc, 7823 DSAStackTy *Stack, CXXRecordDecl *RD) { 7824 if (!RD || RD->isInvalidDecl()) 7825 return true; 7826 7827 auto QTy = SemaRef.Context.getRecordType(RD); 7828 if (RD->isDynamicClass()) { 7829 SemaRef.Diag(Loc, diag::err_omp_not_mappable_type) << QTy; 7830 SemaRef.Diag(RD->getLocation(), diag::note_omp_polymorphic_in_target); 7831 return false; 7832 } 7833 auto *DC = RD; 7834 bool IsCorrect = true; 7835 for (auto *I : DC->decls()) { 7836 if (I) { 7837 if (auto *MD = dyn_cast<CXXMethodDecl>(I)) { 7838 if (MD->isStatic()) { 7839 SemaRef.Diag(Loc, diag::err_omp_not_mappable_type) << QTy; 7840 SemaRef.Diag(MD->getLocation(), 7841 diag::note_omp_static_member_in_target); 7842 IsCorrect = false; 7843 } 7844 } else if (auto *VD = dyn_cast<VarDecl>(I)) { 7845 if (VD->isStaticDataMember()) { 7846 SemaRef.Diag(Loc, diag::err_omp_not_mappable_type) << QTy; 7847 SemaRef.Diag(VD->getLocation(), 7848 diag::note_omp_static_member_in_target); 7849 IsCorrect = false; 7850 } 7851 } 7852 } 7853 } 7854 7855 for (auto &I : RD->bases()) { 7856 if (!IsCXXRecordForMappable(SemaRef, I.getLocStart(), Stack, 7857 I.getType()->getAsCXXRecordDecl())) 7858 IsCorrect = false; 7859 } 7860 return IsCorrect; 7861 } 7862 7863 static bool CheckTypeMappable(SourceLocation SL, SourceRange SR, Sema &SemaRef, 7864 DSAStackTy *Stack, QualType QTy) { 7865 NamedDecl *ND; 7866 if (QTy->isIncompleteType(&ND)) { 7867 SemaRef.Diag(SL, diag::err_incomplete_type) << QTy << SR; 7868 return false; 7869 } else if (CXXRecordDecl *RD = dyn_cast_or_null<CXXRecordDecl>(ND)) { 7870 if (!RD->isInvalidDecl() && 7871 !IsCXXRecordForMappable(SemaRef, SL, Stack, RD)) 7872 return false; 7873 } 7874 return true; 7875 } 7876 7877 OMPClause *Sema::ActOnOpenMPMapClause( 7878 OpenMPMapClauseKind MapTypeModifier, OpenMPMapClauseKind MapType, 7879 SourceLocation MapLoc, SourceLocation ColonLoc, ArrayRef<Expr *> VarList, 7880 SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc) { 7881 SmallVector<Expr *, 4> Vars; 7882 7883 for (auto &RE : VarList) { 7884 assert(RE && "Null expr in omp map"); 7885 if (isa<DependentScopeDeclRefExpr>(RE)) { 7886 // It will be analyzed later. 7887 Vars.push_back(RE); 7888 continue; 7889 } 7890 SourceLocation ELoc = RE->getExprLoc(); 7891 7892 // OpenMP [2.14.5, Restrictions] 7893 // A variable that is part of another variable (such as field of a 7894 // structure) but is not an array element or an array section cannot appear 7895 // in a map clause. 7896 auto *VE = RE->IgnoreParenLValueCasts(); 7897 7898 if (VE->isValueDependent() || VE->isTypeDependent() || 7899 VE->isInstantiationDependent() || 7900 VE->containsUnexpandedParameterPack()) { 7901 // It will be analyzed later. 7902 Vars.push_back(RE); 7903 continue; 7904 } 7905 7906 auto *SimpleExpr = RE->IgnoreParenCasts(); 7907 auto *DE = dyn_cast<DeclRefExpr>(SimpleExpr); 7908 auto *ASE = dyn_cast<ArraySubscriptExpr>(SimpleExpr); 7909 auto *OASE = dyn_cast<OMPArraySectionExpr>(SimpleExpr); 7910 7911 if (!RE->IgnoreParenImpCasts()->isLValue() || 7912 (!OASE && !ASE && !DE) || 7913 (DE && !isa<VarDecl>(DE->getDecl())) || 7914 (ASE && !ASE->getBase()->getType()->isAnyPointerType() && 7915 !ASE->getBase()->getType()->isArrayType())) { 7916 Diag(ELoc, diag::err_omp_expected_var_name_or_array_item) 7917 << RE->getSourceRange(); 7918 continue; 7919 } 7920 7921 Decl *D = nullptr; 7922 if (DE) { 7923 D = DE->getDecl(); 7924 } else if (ASE) { 7925 auto *B = ASE->getBase()->IgnoreParenCasts(); 7926 D = dyn_cast<DeclRefExpr>(B)->getDecl(); 7927 } else if (OASE) { 7928 auto *B = OASE->getBase(); 7929 D = dyn_cast<DeclRefExpr>(B)->getDecl(); 7930 } 7931 assert(D && "Null decl on map clause."); 7932 auto *VD = cast<VarDecl>(D); 7933 7934 // OpenMP [2.14.5, Restrictions, p.8] 7935 // threadprivate variables cannot appear in a map clause. 7936 if (DSAStack->isThreadPrivate(VD)) { 7937 auto DVar = DSAStack->getTopDSA(VD, false); 7938 Diag(ELoc, diag::err_omp_threadprivate_in_map); 7939 ReportOriginalDSA(*this, DSAStack, VD, DVar); 7940 continue; 7941 } 7942 7943 // OpenMP [2.14.5, Restrictions, p.2] 7944 // At most one list item can be an array item derived from a given variable 7945 // in map clauses of the same construct. 7946 // OpenMP [2.14.5, Restrictions, p.3] 7947 // List items of map clauses in the same construct must not share original 7948 // storage. 7949 // OpenMP [2.14.5, Restrictions, C/C++, p.2] 7950 // A variable for which the type is pointer, reference to array, or 7951 // reference to pointer and an array section derived from that variable 7952 // must not appear as list items of map clauses of the same construct. 7953 DSAStackTy::MapInfo MI = DSAStack->IsMappedInCurrentRegion(VD); 7954 if (MI.RefExpr) { 7955 Diag(ELoc, diag::err_omp_map_shared_storage) << ELoc; 7956 Diag(MI.RefExpr->getExprLoc(), diag::note_used_here) 7957 << MI.RefExpr->getSourceRange(); 7958 continue; 7959 } 7960 7961 // OpenMP [2.14.5, Restrictions, C/C++, p.3,4] 7962 // A variable for which the type is pointer, reference to array, or 7963 // reference to pointer must not appear as a list item if the enclosing 7964 // device data environment already contains an array section derived from 7965 // that variable. 7966 // An array section derived from a variable for which the type is pointer, 7967 // reference to array, or reference to pointer must not appear as a list 7968 // item if the enclosing device data environment already contains that 7969 // variable. 7970 QualType Type = VD->getType(); 7971 MI = DSAStack->getMapInfoForVar(VD); 7972 if (MI.RefExpr && (isa<DeclRefExpr>(MI.RefExpr->IgnoreParenLValueCasts()) != 7973 isa<DeclRefExpr>(VE)) && 7974 (Type->isPointerType() || Type->isReferenceType())) { 7975 Diag(ELoc, diag::err_omp_map_shared_storage) << ELoc; 7976 Diag(MI.RefExpr->getExprLoc(), diag::note_used_here) 7977 << MI.RefExpr->getSourceRange(); 7978 continue; 7979 } 7980 7981 // OpenMP [2.14.5, Restrictions, C/C++, p.7] 7982 // A list item must have a mappable type. 7983 if (!CheckTypeMappable(VE->getExprLoc(), VE->getSourceRange(), *this, 7984 DSAStack, Type)) 7985 continue; 7986 7987 Vars.push_back(RE); 7988 MI.RefExpr = RE; 7989 DSAStack->addMapInfoForVar(VD, MI); 7990 } 7991 if (Vars.empty()) 7992 return nullptr; 7993 7994 return OMPMapClause::Create(Context, StartLoc, LParenLoc, EndLoc, Vars, 7995 MapTypeModifier, MapType, MapLoc); 7996 } 7997 7998 OMPClause *Sema::ActOnOpenMPNumTeamsClause(Expr *NumTeams, 7999 SourceLocation StartLoc, 8000 SourceLocation LParenLoc, 8001 SourceLocation EndLoc) { 8002 Expr *ValExpr = NumTeams; 8003 8004 // OpenMP [teams Constrcut, Restrictions] 8005 // The num_teams expression must evaluate to a positive integer value. 8006 if (!IsNonNegativeIntegerValue(ValExpr, *this, OMPC_num_teams, 8007 /*StrictlyPositive=*/true)) 8008 return nullptr; 8009 8010 return new (Context) OMPNumTeamsClause(ValExpr, StartLoc, LParenLoc, EndLoc); 8011 } 8012 8013 OMPClause *Sema::ActOnOpenMPThreadLimitClause(Expr *ThreadLimit, 8014 SourceLocation StartLoc, 8015 SourceLocation LParenLoc, 8016 SourceLocation EndLoc) { 8017 Expr *ValExpr = ThreadLimit; 8018 8019 // OpenMP [teams Constrcut, Restrictions] 8020 // The thread_limit expression must evaluate to a positive integer value. 8021 if (!IsNonNegativeIntegerValue(ValExpr, *this, OMPC_thread_limit, 8022 /*StrictlyPositive=*/true)) 8023 return nullptr; 8024 8025 return new (Context) OMPThreadLimitClause(ValExpr, StartLoc, LParenLoc, 8026 EndLoc); 8027 } 8028 8029 OMPClause *Sema::ActOnOpenMPPriorityClause(Expr *Priority, 8030 SourceLocation StartLoc, 8031 SourceLocation LParenLoc, 8032 SourceLocation EndLoc) { 8033 Expr *ValExpr = Priority; 8034 8035 // OpenMP [2.9.1, task Constrcut] 8036 // The priority-value is a non-negative numerical scalar expression. 8037 if (!IsNonNegativeIntegerValue(ValExpr, *this, OMPC_priority, 8038 /*StrictlyPositive=*/false)) 8039 return nullptr; 8040 8041 return new (Context) OMPPriorityClause(ValExpr, StartLoc, LParenLoc, EndLoc); 8042 } 8043 8044 OMPClause *Sema::ActOnOpenMPGrainsizeClause(Expr *Grainsize, 8045 SourceLocation StartLoc, 8046 SourceLocation LParenLoc, 8047 SourceLocation EndLoc) { 8048 Expr *ValExpr = Grainsize; 8049 8050 // OpenMP [2.9.2, taskloop Constrcut] 8051 // The parameter of the grainsize clause must be a positive integer 8052 // expression. 8053 if (!IsNonNegativeIntegerValue(ValExpr, *this, OMPC_grainsize, 8054 /*StrictlyPositive=*/true)) 8055 return nullptr; 8056 8057 return new (Context) OMPGrainsizeClause(ValExpr, StartLoc, LParenLoc, EndLoc); 8058 } 8059 8060 OMPClause *Sema::ActOnOpenMPNumTasksClause(Expr *NumTasks, 8061 SourceLocation StartLoc, 8062 SourceLocation LParenLoc, 8063 SourceLocation EndLoc) { 8064 Expr *ValExpr = NumTasks; 8065 8066 // OpenMP [2.9.2, taskloop Constrcut] 8067 // The parameter of the num_tasks clause must be a positive integer 8068 // expression. 8069 if (!IsNonNegativeIntegerValue(ValExpr, *this, OMPC_num_tasks, 8070 /*StrictlyPositive=*/true)) 8071 return nullptr; 8072 8073 return new (Context) OMPNumTasksClause(ValExpr, StartLoc, LParenLoc, EndLoc); 8074 } 8075 8076