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