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/CXXInheritance.h" 19 #include "clang/AST/Decl.h" 20 #include "clang/AST/DeclCXX.h" 21 #include "clang/AST/DeclOpenMP.h" 22 #include "clang/AST/StmtCXX.h" 23 #include "clang/AST/StmtOpenMP.h" 24 #include "clang/AST/StmtVisitor.h" 25 #include "clang/AST/TypeOrdering.h" 26 #include "clang/Basic/OpenMPKinds.h" 27 #include "clang/Basic/TargetInfo.h" 28 #include "clang/Lex/Preprocessor.h" 29 #include "clang/Sema/Initialization.h" 30 #include "clang/Sema/Lookup.h" 31 #include "clang/Sema/Scope.h" 32 #include "clang/Sema/ScopeInfo.h" 33 #include "clang/Sema/SemaInternal.h" 34 using namespace clang; 35 36 //===----------------------------------------------------------------------===// 37 // Stack of data-sharing attributes for variables 38 //===----------------------------------------------------------------------===// 39 40 namespace { 41 /// \brief Default data sharing attributes, which can be applied to directive. 42 enum DefaultDataSharingAttributes { 43 DSA_unspecified = 0, /// \brief Data sharing attribute not specified. 44 DSA_none = 1 << 0, /// \brief Default data sharing attribute 'none'. 45 DSA_shared = 1 << 1 /// \brief Default data sharing attribute 'shared'. 46 }; 47 48 /// \brief Stack for tracking declarations used in OpenMP directives and 49 /// clauses and their data-sharing attributes. 50 class DSAStackTy final { 51 public: 52 struct DSAVarData final { 53 OpenMPDirectiveKind DKind = OMPD_unknown; 54 OpenMPClauseKind CKind = OMPC_unknown; 55 Expr *RefExpr = nullptr; 56 DeclRefExpr *PrivateCopy = nullptr; 57 SourceLocation ImplicitDSALoc; 58 DSAVarData() {} 59 }; 60 typedef llvm::SmallVector<std::pair<Expr *, OverloadedOperatorKind>, 4> 61 OperatorOffsetTy; 62 63 private: 64 struct DSAInfo final { 65 OpenMPClauseKind Attributes = OMPC_unknown; 66 /// Pointer to a reference expression and a flag which shows that the 67 /// variable is marked as lastprivate(true) or not (false). 68 llvm::PointerIntPair<Expr *, 1, bool> RefExpr; 69 DeclRefExpr *PrivateCopy = nullptr; 70 }; 71 typedef llvm::DenseMap<ValueDecl *, DSAInfo> DeclSAMapTy; 72 typedef llvm::DenseMap<ValueDecl *, Expr *> AlignedMapTy; 73 typedef std::pair<unsigned, VarDecl *> LCDeclInfo; 74 typedef llvm::DenseMap<ValueDecl *, LCDeclInfo> LoopControlVariablesMapTy; 75 typedef llvm::DenseMap< 76 ValueDecl *, OMPClauseMappableExprCommon::MappableExprComponentLists> 77 MappedExprComponentsTy; 78 typedef llvm::StringMap<std::pair<OMPCriticalDirective *, llvm::APSInt>> 79 CriticalsWithHintsTy; 80 typedef llvm::DenseMap<OMPDependClause *, OperatorOffsetTy> 81 DoacrossDependMapTy; 82 83 struct SharingMapTy final { 84 DeclSAMapTy SharingMap; 85 AlignedMapTy AlignedMap; 86 MappedExprComponentsTy MappedExprComponents; 87 LoopControlVariablesMapTy LCVMap; 88 DefaultDataSharingAttributes DefaultAttr = DSA_unspecified; 89 SourceLocation DefaultAttrLoc; 90 OpenMPDirectiveKind Directive = OMPD_unknown; 91 DeclarationNameInfo DirectiveName; 92 Scope *CurScope = nullptr; 93 SourceLocation ConstructLoc; 94 /// Set of 'depend' clauses with 'sink|source' dependence kind. Required to 95 /// get the data (loop counters etc.) about enclosing loop-based construct. 96 /// This data is required during codegen. 97 DoacrossDependMapTy DoacrossDepends; 98 /// \brief first argument (Expr *) contains optional argument of the 99 /// 'ordered' clause, the second one is true if the regions has 'ordered' 100 /// clause, false otherwise. 101 llvm::PointerIntPair<Expr *, 1, bool> OrderedRegion; 102 bool NowaitRegion = false; 103 bool CancelRegion = false; 104 unsigned AssociatedLoops = 1; 105 SourceLocation InnerTeamsRegionLoc; 106 SharingMapTy(OpenMPDirectiveKind DKind, DeclarationNameInfo Name, 107 Scope *CurScope, SourceLocation Loc) 108 : Directive(DKind), DirectiveName(Name), CurScope(CurScope), 109 ConstructLoc(Loc) {} 110 SharingMapTy() {} 111 }; 112 113 typedef SmallVector<SharingMapTy, 4> StackTy; 114 115 /// \brief Stack of used declaration and their data-sharing attributes. 116 StackTy Stack; 117 /// \brief true, if check for DSA must be from parent directive, false, if 118 /// from current directive. 119 OpenMPClauseKind ClauseKindMode = OMPC_unknown; 120 Sema &SemaRef; 121 bool ForceCapturing = false; 122 CriticalsWithHintsTy Criticals; 123 124 typedef SmallVector<SharingMapTy, 8>::reverse_iterator reverse_iterator; 125 126 DSAVarData getDSA(StackTy::reverse_iterator& Iter, ValueDecl *D); 127 128 /// \brief Checks if the variable is a local for OpenMP region. 129 bool isOpenMPLocal(VarDecl *D, StackTy::reverse_iterator Iter); 130 131 public: 132 explicit DSAStackTy(Sema &S) : Stack(1), SemaRef(S) {} 133 134 bool isClauseParsingMode() const { return ClauseKindMode != OMPC_unknown; } 135 void setClauseParsingMode(OpenMPClauseKind K) { ClauseKindMode = K; } 136 137 bool isForceVarCapturing() const { return ForceCapturing; } 138 void setForceVarCapturing(bool V) { ForceCapturing = V; } 139 140 void push(OpenMPDirectiveKind DKind, const DeclarationNameInfo &DirName, 141 Scope *CurScope, SourceLocation Loc) { 142 Stack.push_back(SharingMapTy(DKind, DirName, CurScope, Loc)); 143 Stack.back().DefaultAttrLoc = Loc; 144 } 145 146 void pop() { 147 assert(Stack.size() > 1 && "Data-sharing attributes stack is empty!"); 148 Stack.pop_back(); 149 } 150 151 void addCriticalWithHint(OMPCriticalDirective *D, llvm::APSInt Hint) { 152 Criticals[D->getDirectiveName().getAsString()] = std::make_pair(D, Hint); 153 } 154 const std::pair<OMPCriticalDirective *, llvm::APSInt> 155 getCriticalWithHint(const DeclarationNameInfo &Name) const { 156 auto I = Criticals.find(Name.getAsString()); 157 if (I != Criticals.end()) 158 return I->second; 159 return std::make_pair(nullptr, llvm::APSInt()); 160 } 161 /// \brief If 'aligned' declaration for given variable \a D was not seen yet, 162 /// add it and return NULL; otherwise return previous occurrence's expression 163 /// for diagnostics. 164 Expr *addUniqueAligned(ValueDecl *D, Expr *NewDE); 165 166 /// \brief Register specified variable as loop control variable. 167 void addLoopControlVariable(ValueDecl *D, VarDecl *Capture); 168 /// \brief Check if the specified variable is a loop control variable for 169 /// current region. 170 /// \return The index of the loop control variable in the list of associated 171 /// for-loops (from outer to inner). 172 LCDeclInfo isLoopControlVariable(ValueDecl *D); 173 /// \brief Check if the specified variable is a loop control variable for 174 /// parent region. 175 /// \return The index of the loop control variable in the list of associated 176 /// for-loops (from outer to inner). 177 LCDeclInfo isParentLoopControlVariable(ValueDecl *D); 178 /// \brief Get the loop control variable for the I-th loop (or nullptr) in 179 /// parent directive. 180 ValueDecl *getParentLoopControlVariable(unsigned I); 181 182 /// \brief Adds explicit data sharing attribute to the specified declaration. 183 void addDSA(ValueDecl *D, Expr *E, OpenMPClauseKind A, 184 DeclRefExpr *PrivateCopy = nullptr); 185 186 /// \brief Returns data sharing attributes from top of the stack for the 187 /// specified declaration. 188 DSAVarData getTopDSA(ValueDecl *D, bool FromParent); 189 /// \brief Returns data-sharing attributes for the specified declaration. 190 DSAVarData getImplicitDSA(ValueDecl *D, bool FromParent); 191 /// \brief Checks if the specified variables has data-sharing attributes which 192 /// match specified \a CPred predicate in any directive which matches \a DPred 193 /// predicate. 194 DSAVarData hasDSA(ValueDecl *D, 195 const llvm::function_ref<bool(OpenMPClauseKind)> &CPred, 196 const llvm::function_ref<bool(OpenMPDirectiveKind)> &DPred, 197 bool FromParent); 198 /// \brief Checks if the specified variables has data-sharing attributes which 199 /// match specified \a CPred predicate in any innermost directive which 200 /// matches \a DPred predicate. 201 DSAVarData 202 hasInnermostDSA(ValueDecl *D, 203 const llvm::function_ref<bool(OpenMPClauseKind)> &CPred, 204 const llvm::function_ref<bool(OpenMPDirectiveKind)> &DPred, 205 bool FromParent); 206 /// \brief Checks if the specified variables has explicit data-sharing 207 /// attributes which match specified \a CPred predicate at the specified 208 /// OpenMP region. 209 bool hasExplicitDSA(ValueDecl *D, 210 const llvm::function_ref<bool(OpenMPClauseKind)> &CPred, 211 unsigned Level, bool NotLastprivate = false); 212 213 /// \brief Returns true if the directive at level \Level matches in the 214 /// specified \a DPred predicate. 215 bool hasExplicitDirective( 216 const llvm::function_ref<bool(OpenMPDirectiveKind)> &DPred, 217 unsigned Level); 218 219 /// \brief Finds a directive which matches specified \a DPred predicate. 220 bool hasDirective(const llvm::function_ref<bool(OpenMPDirectiveKind, 221 const DeclarationNameInfo &, 222 SourceLocation)> &DPred, 223 bool FromParent); 224 225 /// \brief Returns currently analyzed directive. 226 OpenMPDirectiveKind getCurrentDirective() const { 227 return Stack.back().Directive; 228 } 229 /// \brief Returns parent directive. 230 OpenMPDirectiveKind getParentDirective() const { 231 if (Stack.size() > 2) 232 return Stack[Stack.size() - 2].Directive; 233 return OMPD_unknown; 234 } 235 236 /// \brief Set default data sharing attribute to none. 237 void setDefaultDSANone(SourceLocation Loc) { 238 Stack.back().DefaultAttr = DSA_none; 239 Stack.back().DefaultAttrLoc = Loc; 240 } 241 /// \brief Set default data sharing attribute to shared. 242 void setDefaultDSAShared(SourceLocation Loc) { 243 Stack.back().DefaultAttr = DSA_shared; 244 Stack.back().DefaultAttrLoc = Loc; 245 } 246 247 DefaultDataSharingAttributes getDefaultDSA() const { 248 return Stack.back().DefaultAttr; 249 } 250 SourceLocation getDefaultDSALocation() const { 251 return Stack.back().DefaultAttrLoc; 252 } 253 254 /// \brief Checks if the specified variable is a threadprivate. 255 bool isThreadPrivate(VarDecl *D) { 256 DSAVarData DVar = getTopDSA(D, false); 257 return isOpenMPThreadPrivate(DVar.CKind); 258 } 259 260 /// \brief Marks current region as ordered (it has an 'ordered' clause). 261 void setOrderedRegion(bool IsOrdered, Expr *Param) { 262 Stack.back().OrderedRegion.setInt(IsOrdered); 263 Stack.back().OrderedRegion.setPointer(Param); 264 } 265 /// \brief Returns true, if parent region is ordered (has associated 266 /// 'ordered' clause), false - otherwise. 267 bool isParentOrderedRegion() const { 268 if (Stack.size() > 2) 269 return Stack[Stack.size() - 2].OrderedRegion.getInt(); 270 return false; 271 } 272 /// \brief Returns optional parameter for the ordered region. 273 Expr *getParentOrderedRegionParam() const { 274 if (Stack.size() > 2) 275 return Stack[Stack.size() - 2].OrderedRegion.getPointer(); 276 return nullptr; 277 } 278 /// \brief Marks current region as nowait (it has a 'nowait' clause). 279 void setNowaitRegion(bool IsNowait = true) { 280 Stack.back().NowaitRegion = IsNowait; 281 } 282 /// \brief Returns true, if parent region is nowait (has associated 283 /// 'nowait' clause), false - otherwise. 284 bool isParentNowaitRegion() const { 285 if (Stack.size() > 2) 286 return Stack[Stack.size() - 2].NowaitRegion; 287 return false; 288 } 289 /// \brief Marks parent region as cancel region. 290 void setParentCancelRegion(bool Cancel = true) { 291 if (Stack.size() > 2) 292 Stack[Stack.size() - 2].CancelRegion = 293 Stack[Stack.size() - 2].CancelRegion || Cancel; 294 } 295 /// \brief Return true if current region has inner cancel construct. 296 bool isCancelRegion() const { 297 return Stack.back().CancelRegion; 298 } 299 300 /// \brief Set collapse value for the region. 301 void setAssociatedLoops(unsigned Val) { Stack.back().AssociatedLoops = Val; } 302 /// \brief Return collapse value for region. 303 unsigned getAssociatedLoops() const { return Stack.back().AssociatedLoops; } 304 305 /// \brief Marks current target region as one with closely nested teams 306 /// region. 307 void setParentTeamsRegionLoc(SourceLocation TeamsRegionLoc) { 308 if (Stack.size() > 2) 309 Stack[Stack.size() - 2].InnerTeamsRegionLoc = TeamsRegionLoc; 310 } 311 /// \brief Returns true, if current region has closely nested teams region. 312 bool hasInnerTeamsRegion() const { 313 return getInnerTeamsRegionLoc().isValid(); 314 } 315 /// \brief Returns location of the nested teams region (if any). 316 SourceLocation getInnerTeamsRegionLoc() const { 317 if (Stack.size() > 1) 318 return Stack.back().InnerTeamsRegionLoc; 319 return SourceLocation(); 320 } 321 322 Scope *getCurScope() const { return Stack.back().CurScope; } 323 Scope *getCurScope() { return Stack.back().CurScope; } 324 SourceLocation getConstructLoc() { return Stack.back().ConstructLoc; } 325 326 // Do the check specified in \a Check to all component lists and return true 327 // if any issue is found. 328 bool checkMappableExprComponentListsForDecl( 329 ValueDecl *VD, bool CurrentRegionOnly, 330 const llvm::function_ref<bool( 331 OMPClauseMappableExprCommon::MappableExprComponentListRef)> &Check) { 332 auto SI = Stack.rbegin(); 333 auto SE = Stack.rend(); 334 335 if (SI == SE) 336 return false; 337 338 if (CurrentRegionOnly) { 339 SE = std::next(SI); 340 } else { 341 ++SI; 342 } 343 344 for (; SI != SE; ++SI) { 345 auto MI = SI->MappedExprComponents.find(VD); 346 if (MI != SI->MappedExprComponents.end()) 347 for (auto &L : MI->second) 348 if (Check(L)) 349 return true; 350 } 351 return false; 352 } 353 354 // Create a new mappable expression component list associated with a given 355 // declaration and initialize it with the provided list of components. 356 void addMappableExpressionComponents( 357 ValueDecl *VD, 358 OMPClauseMappableExprCommon::MappableExprComponentListRef Components) { 359 assert(Stack.size() > 1 && 360 "Not expecting to retrieve components from a empty stack!"); 361 auto &MEC = Stack.back().MappedExprComponents[VD]; 362 // Create new entry and append the new components there. 363 MEC.resize(MEC.size() + 1); 364 MEC.back().append(Components.begin(), Components.end()); 365 } 366 367 unsigned getNestingLevel() const { 368 assert(Stack.size() > 1); 369 return Stack.size() - 2; 370 } 371 void addDoacrossDependClause(OMPDependClause *C, OperatorOffsetTy &OpsOffs) { 372 assert(Stack.size() > 2); 373 assert(isOpenMPWorksharingDirective(Stack[Stack.size() - 2].Directive)); 374 Stack[Stack.size() - 2].DoacrossDepends.insert({C, OpsOffs}); 375 } 376 llvm::iterator_range<DoacrossDependMapTy::const_iterator> 377 getDoacrossDependClauses() const { 378 assert(Stack.size() > 1); 379 if (isOpenMPWorksharingDirective(Stack[Stack.size() - 1].Directive)) { 380 auto &Ref = Stack[Stack.size() - 1].DoacrossDepends; 381 return llvm::make_range(Ref.begin(), Ref.end()); 382 } 383 return llvm::make_range(Stack[0].DoacrossDepends.end(), 384 Stack[0].DoacrossDepends.end()); 385 } 386 }; 387 bool isParallelOrTaskRegion(OpenMPDirectiveKind DKind) { 388 return isOpenMPParallelDirective(DKind) || isOpenMPTaskingDirective(DKind) || 389 isOpenMPTeamsDirective(DKind) || DKind == OMPD_unknown; 390 } 391 } // namespace 392 393 static ValueDecl *getCanonicalDecl(ValueDecl *D) { 394 auto *VD = dyn_cast<VarDecl>(D); 395 auto *FD = dyn_cast<FieldDecl>(D); 396 if (VD != nullptr) { 397 VD = VD->getCanonicalDecl(); 398 D = VD; 399 } else { 400 assert(FD); 401 FD = FD->getCanonicalDecl(); 402 D = FD; 403 } 404 return D; 405 } 406 407 DSAStackTy::DSAVarData DSAStackTy::getDSA(StackTy::reverse_iterator& Iter, 408 ValueDecl *D) { 409 D = getCanonicalDecl(D); 410 auto *VD = dyn_cast<VarDecl>(D); 411 auto *FD = dyn_cast<FieldDecl>(D); 412 DSAVarData DVar; 413 if (Iter == std::prev(Stack.rend())) { 414 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced 415 // in a region but not in construct] 416 // File-scope or namespace-scope variables referenced in called routines 417 // in the region are shared unless they appear in a threadprivate 418 // directive. 419 if (VD && !VD->isFunctionOrMethodVarDecl() && !isa<ParmVarDecl>(D)) 420 DVar.CKind = OMPC_shared; 421 422 // OpenMP [2.9.1.2, Data-sharing Attribute Rules for Variables Referenced 423 // in a region but not in construct] 424 // Variables with static storage duration that are declared in called 425 // routines in the region are shared. 426 if (VD && VD->hasGlobalStorage()) 427 DVar.CKind = OMPC_shared; 428 429 // Non-static data members are shared by default. 430 if (FD) 431 DVar.CKind = OMPC_shared; 432 433 return DVar; 434 } 435 436 DVar.DKind = Iter->Directive; 437 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced 438 // in a Construct, C/C++, predetermined, p.1] 439 // Variables with automatic storage duration that are declared in a scope 440 // inside the construct are private. 441 if (VD && isOpenMPLocal(VD, Iter) && VD->isLocalVarDecl() && 442 (VD->getStorageClass() == SC_Auto || VD->getStorageClass() == SC_None)) { 443 DVar.CKind = OMPC_private; 444 return DVar; 445 } 446 447 // Explicitly specified attributes and local variables with predetermined 448 // attributes. 449 if (Iter->SharingMap.count(D)) { 450 DVar.RefExpr = Iter->SharingMap[D].RefExpr.getPointer(); 451 DVar.PrivateCopy = Iter->SharingMap[D].PrivateCopy; 452 DVar.CKind = Iter->SharingMap[D].Attributes; 453 DVar.ImplicitDSALoc = Iter->DefaultAttrLoc; 454 return DVar; 455 } 456 457 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced 458 // in a Construct, C/C++, implicitly determined, p.1] 459 // In a parallel or task construct, the data-sharing attributes of these 460 // variables are determined by the default clause, if present. 461 switch (Iter->DefaultAttr) { 462 case DSA_shared: 463 DVar.CKind = OMPC_shared; 464 DVar.ImplicitDSALoc = Iter->DefaultAttrLoc; 465 return DVar; 466 case DSA_none: 467 return DVar; 468 case DSA_unspecified: 469 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced 470 // in a Construct, implicitly determined, p.2] 471 // In a parallel construct, if no default clause is present, these 472 // variables are shared. 473 DVar.ImplicitDSALoc = Iter->DefaultAttrLoc; 474 if (isOpenMPParallelDirective(DVar.DKind) || 475 isOpenMPTeamsDirective(DVar.DKind)) { 476 DVar.CKind = OMPC_shared; 477 return DVar; 478 } 479 480 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced 481 // in a Construct, implicitly determined, p.4] 482 // In a task construct, if no default clause is present, a variable that in 483 // the enclosing context is determined to be shared by all implicit tasks 484 // bound to the current team is shared. 485 if (isOpenMPTaskingDirective(DVar.DKind)) { 486 DSAVarData DVarTemp; 487 for (StackTy::reverse_iterator I = std::next(Iter), EE = Stack.rend(); 488 I != EE; ++I) { 489 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables 490 // Referenced in a Construct, implicitly determined, p.6] 491 // In a task construct, if no default clause is present, a variable 492 // whose data-sharing attribute is not determined by the rules above is 493 // firstprivate. 494 DVarTemp = getDSA(I, D); 495 if (DVarTemp.CKind != OMPC_shared) { 496 DVar.RefExpr = nullptr; 497 DVar.CKind = OMPC_firstprivate; 498 return DVar; 499 } 500 if (isParallelOrTaskRegion(I->Directive)) 501 break; 502 } 503 DVar.CKind = 504 (DVarTemp.CKind == OMPC_unknown) ? OMPC_firstprivate : OMPC_shared; 505 return DVar; 506 } 507 } 508 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced 509 // in a Construct, implicitly determined, p.3] 510 // For constructs other than task, if no default clause is present, these 511 // variables inherit their data-sharing attributes from the enclosing 512 // context. 513 return getDSA(++Iter, D); 514 } 515 516 Expr *DSAStackTy::addUniqueAligned(ValueDecl *D, Expr *NewDE) { 517 assert(Stack.size() > 1 && "Data sharing attributes stack is empty"); 518 D = getCanonicalDecl(D); 519 auto It = Stack.back().AlignedMap.find(D); 520 if (It == Stack.back().AlignedMap.end()) { 521 assert(NewDE && "Unexpected nullptr expr to be added into aligned map"); 522 Stack.back().AlignedMap[D] = NewDE; 523 return nullptr; 524 } else { 525 assert(It->second && "Unexpected nullptr expr in the aligned map"); 526 return It->second; 527 } 528 return nullptr; 529 } 530 531 void DSAStackTy::addLoopControlVariable(ValueDecl *D, VarDecl *Capture) { 532 assert(Stack.size() > 1 && "Data-sharing attributes stack is empty"); 533 D = getCanonicalDecl(D); 534 Stack.back().LCVMap.insert( 535 std::make_pair(D, LCDeclInfo(Stack.back().LCVMap.size() + 1, Capture))); 536 } 537 538 DSAStackTy::LCDeclInfo DSAStackTy::isLoopControlVariable(ValueDecl *D) { 539 assert(Stack.size() > 1 && "Data-sharing attributes stack is empty"); 540 D = getCanonicalDecl(D); 541 return Stack.back().LCVMap.count(D) > 0 ? Stack.back().LCVMap[D] 542 : LCDeclInfo(0, nullptr); 543 } 544 545 DSAStackTy::LCDeclInfo DSAStackTy::isParentLoopControlVariable(ValueDecl *D) { 546 assert(Stack.size() > 2 && "Data-sharing attributes stack is empty"); 547 D = getCanonicalDecl(D); 548 return Stack[Stack.size() - 2].LCVMap.count(D) > 0 549 ? Stack[Stack.size() - 2].LCVMap[D] 550 : LCDeclInfo(0, nullptr); 551 } 552 553 ValueDecl *DSAStackTy::getParentLoopControlVariable(unsigned I) { 554 assert(Stack.size() > 2 && "Data-sharing attributes stack is empty"); 555 if (Stack[Stack.size() - 2].LCVMap.size() < I) 556 return nullptr; 557 for (auto &Pair : Stack[Stack.size() - 2].LCVMap) { 558 if (Pair.second.first == I) 559 return Pair.first; 560 } 561 return nullptr; 562 } 563 564 void DSAStackTy::addDSA(ValueDecl *D, Expr *E, OpenMPClauseKind A, 565 DeclRefExpr *PrivateCopy) { 566 D = getCanonicalDecl(D); 567 if (A == OMPC_threadprivate) { 568 auto &Data = Stack[0].SharingMap[D]; 569 Data.Attributes = A; 570 Data.RefExpr.setPointer(E); 571 Data.PrivateCopy = nullptr; 572 } else { 573 assert(Stack.size() > 1 && "Data-sharing attributes stack is empty"); 574 auto &Data = Stack.back().SharingMap[D]; 575 assert(Data.Attributes == OMPC_unknown || (A == Data.Attributes) || 576 (A == OMPC_firstprivate && Data.Attributes == OMPC_lastprivate) || 577 (A == OMPC_lastprivate && Data.Attributes == OMPC_firstprivate) || 578 (isLoopControlVariable(D).first && A == OMPC_private)); 579 if (A == OMPC_lastprivate && Data.Attributes == OMPC_firstprivate) { 580 Data.RefExpr.setInt(/*IntVal=*/true); 581 return; 582 } 583 const bool IsLastprivate = 584 A == OMPC_lastprivate || Data.Attributes == OMPC_lastprivate; 585 Data.Attributes = A; 586 Data.RefExpr.setPointerAndInt(E, IsLastprivate); 587 Data.PrivateCopy = PrivateCopy; 588 if (PrivateCopy) { 589 auto &Data = Stack.back().SharingMap[PrivateCopy->getDecl()]; 590 Data.Attributes = A; 591 Data.RefExpr.setPointerAndInt(PrivateCopy, IsLastprivate); 592 Data.PrivateCopy = nullptr; 593 } 594 } 595 } 596 597 bool DSAStackTy::isOpenMPLocal(VarDecl *D, StackTy::reverse_iterator Iter) { 598 D = D->getCanonicalDecl(); 599 if (Stack.size() > 2) { 600 reverse_iterator I = Iter, E = std::prev(Stack.rend()); 601 Scope *TopScope = nullptr; 602 while (I != E && !isParallelOrTaskRegion(I->Directive)) { 603 ++I; 604 } 605 if (I == E) 606 return false; 607 TopScope = I->CurScope ? I->CurScope->getParent() : nullptr; 608 Scope *CurScope = getCurScope(); 609 while (CurScope != TopScope && !CurScope->isDeclScope(D)) { 610 CurScope = CurScope->getParent(); 611 } 612 return CurScope != TopScope; 613 } 614 return false; 615 } 616 617 /// \brief Build a variable declaration for OpenMP loop iteration variable. 618 static VarDecl *buildVarDecl(Sema &SemaRef, SourceLocation Loc, QualType Type, 619 StringRef Name, const AttrVec *Attrs = nullptr) { 620 DeclContext *DC = SemaRef.CurContext; 621 IdentifierInfo *II = &SemaRef.PP.getIdentifierTable().get(Name); 622 TypeSourceInfo *TInfo = SemaRef.Context.getTrivialTypeSourceInfo(Type, Loc); 623 VarDecl *Decl = 624 VarDecl::Create(SemaRef.Context, DC, Loc, Loc, II, Type, TInfo, SC_None); 625 if (Attrs) { 626 for (specific_attr_iterator<AlignedAttr> I(Attrs->begin()), E(Attrs->end()); 627 I != E; ++I) 628 Decl->addAttr(*I); 629 } 630 Decl->setImplicit(); 631 return Decl; 632 } 633 634 static DeclRefExpr *buildDeclRefExpr(Sema &S, VarDecl *D, QualType Ty, 635 SourceLocation Loc, 636 bool RefersToCapture = false) { 637 D->setReferenced(); 638 D->markUsed(S.Context); 639 return DeclRefExpr::Create(S.getASTContext(), NestedNameSpecifierLoc(), 640 SourceLocation(), D, RefersToCapture, Loc, Ty, 641 VK_LValue); 642 } 643 644 DSAStackTy::DSAVarData DSAStackTy::getTopDSA(ValueDecl *D, bool FromParent) { 645 D = getCanonicalDecl(D); 646 DSAVarData DVar; 647 648 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced 649 // in a Construct, C/C++, predetermined, p.1] 650 // Variables appearing in threadprivate directives are threadprivate. 651 auto *VD = dyn_cast<VarDecl>(D); 652 if ((VD && VD->getTLSKind() != VarDecl::TLS_None && 653 !(VD->hasAttr<OMPThreadPrivateDeclAttr>() && 654 SemaRef.getLangOpts().OpenMPUseTLS && 655 SemaRef.getASTContext().getTargetInfo().isTLSSupported())) || 656 (VD && VD->getStorageClass() == SC_Register && 657 VD->hasAttr<AsmLabelAttr>() && !VD->isLocalVarDecl())) { 658 addDSA(D, buildDeclRefExpr(SemaRef, VD, D->getType().getNonReferenceType(), 659 D->getLocation()), 660 OMPC_threadprivate); 661 } 662 if (Stack[0].SharingMap.count(D)) { 663 DVar.RefExpr = Stack[0].SharingMap[D].RefExpr.getPointer(); 664 DVar.CKind = OMPC_threadprivate; 665 return DVar; 666 } 667 668 if (Stack.size() == 1) { 669 // Not in OpenMP execution region and top scope was already checked. 670 return DVar; 671 } 672 673 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced 674 // in a Construct, C/C++, predetermined, p.4] 675 // Static data members are shared. 676 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced 677 // in a Construct, C/C++, predetermined, p.7] 678 // Variables with static storage duration that are declared in a scope 679 // inside the construct are shared. 680 auto &&MatchesAlways = [](OpenMPDirectiveKind) -> bool { return true; }; 681 if (VD && VD->isStaticDataMember()) { 682 DSAVarData DVarTemp = hasDSA(D, isOpenMPPrivate, MatchesAlways, FromParent); 683 if (DVarTemp.CKind != OMPC_unknown && DVarTemp.RefExpr) 684 return DVar; 685 686 DVar.CKind = OMPC_shared; 687 return DVar; 688 } 689 690 QualType Type = D->getType().getNonReferenceType().getCanonicalType(); 691 bool IsConstant = Type.isConstant(SemaRef.getASTContext()); 692 Type = SemaRef.getASTContext().getBaseElementType(Type); 693 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced 694 // in a Construct, C/C++, predetermined, p.6] 695 // Variables with const qualified type having no mutable member are 696 // shared. 697 CXXRecordDecl *RD = 698 SemaRef.getLangOpts().CPlusPlus ? Type->getAsCXXRecordDecl() : nullptr; 699 if (auto *CTSD = dyn_cast_or_null<ClassTemplateSpecializationDecl>(RD)) 700 if (auto *CTD = CTSD->getSpecializedTemplate()) 701 RD = CTD->getTemplatedDecl(); 702 if (IsConstant && 703 !(SemaRef.getLangOpts().CPlusPlus && RD && RD->hasDefinition() && 704 RD->hasMutableFields())) { 705 // Variables with const-qualified type having no mutable member may be 706 // listed in a firstprivate clause, even if they are static data members. 707 DSAVarData DVarTemp = hasDSA( 708 D, [](OpenMPClauseKind C) -> bool { return C == OMPC_firstprivate; }, 709 MatchesAlways, FromParent); 710 if (DVarTemp.CKind == OMPC_firstprivate && DVarTemp.RefExpr) 711 return DVar; 712 713 DVar.CKind = OMPC_shared; 714 return DVar; 715 } 716 717 // Explicitly specified attributes and local variables with predetermined 718 // attributes. 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 auto I = std::prev(StartI); 725 if (I->SharingMap.count(D)) { 726 DVar.RefExpr = I->SharingMap[D].RefExpr.getPointer(); 727 DVar.PrivateCopy = I->SharingMap[D].PrivateCopy; 728 DVar.CKind = I->SharingMap[D].Attributes; 729 DVar.ImplicitDSALoc = I->DefaultAttrLoc; 730 } 731 732 return DVar; 733 } 734 735 DSAStackTy::DSAVarData DSAStackTy::getImplicitDSA(ValueDecl *D, 736 bool FromParent) { 737 D = getCanonicalDecl(D); 738 auto StartI = Stack.rbegin(); 739 auto EndI = std::prev(Stack.rend()); 740 if (FromParent && StartI != EndI) { 741 StartI = std::next(StartI); 742 } 743 return getDSA(StartI, D); 744 } 745 746 DSAStackTy::DSAVarData 747 DSAStackTy::hasDSA(ValueDecl *D, 748 const llvm::function_ref<bool(OpenMPClauseKind)> &CPred, 749 const llvm::function_ref<bool(OpenMPDirectiveKind)> &DPred, 750 bool FromParent) { 751 D = getCanonicalDecl(D); 752 auto StartI = std::next(Stack.rbegin()); 753 auto EndI = Stack.rend(); 754 if (FromParent && StartI != EndI) { 755 StartI = std::next(StartI); 756 } 757 for (auto I = StartI, EE = EndI; I != EE; ++I) { 758 if (!DPred(I->Directive) && !isParallelOrTaskRegion(I->Directive)) 759 continue; 760 DSAVarData DVar = getDSA(I, D); 761 if (CPred(DVar.CKind)) 762 return DVar; 763 } 764 return DSAVarData(); 765 } 766 767 DSAStackTy::DSAVarData DSAStackTy::hasInnermostDSA( 768 ValueDecl *D, const llvm::function_ref<bool(OpenMPClauseKind)> &CPred, 769 const llvm::function_ref<bool(OpenMPDirectiveKind)> &DPred, 770 bool FromParent) { 771 D = getCanonicalDecl(D); 772 auto StartI = std::next(Stack.rbegin()); 773 auto EndI = Stack.rend(); 774 if (FromParent && StartI != EndI) { 775 StartI = std::next(StartI); 776 } 777 for (auto I = StartI, EE = EndI; I != EE; ++I) { 778 if (!DPred(I->Directive)) 779 break; 780 DSAVarData DVar = getDSA(I, D); 781 if (CPred(DVar.CKind)) 782 return DVar; 783 return DSAVarData(); 784 } 785 return DSAVarData(); 786 } 787 788 bool DSAStackTy::hasExplicitDSA( 789 ValueDecl *D, const llvm::function_ref<bool(OpenMPClauseKind)> &CPred, 790 unsigned Level, bool NotLastprivate) { 791 if (CPred(ClauseKindMode)) 792 return true; 793 D = getCanonicalDecl(D); 794 auto StartI = std::next(Stack.begin()); 795 auto EndI = Stack.end(); 796 if (std::distance(StartI, EndI) <= (int)Level) 797 return false; 798 std::advance(StartI, Level); 799 return (StartI->SharingMap.count(D) > 0) && 800 StartI->SharingMap[D].RefExpr.getPointer() && 801 CPred(StartI->SharingMap[D].Attributes) && 802 (!NotLastprivate || !StartI->SharingMap[D].RefExpr.getInt()); 803 } 804 805 bool DSAStackTy::hasExplicitDirective( 806 const llvm::function_ref<bool(OpenMPDirectiveKind)> &DPred, 807 unsigned Level) { 808 auto StartI = std::next(Stack.begin()); 809 auto EndI = Stack.end(); 810 if (std::distance(StartI, EndI) <= (int)Level) 811 return false; 812 std::advance(StartI, Level); 813 return DPred(StartI->Directive); 814 } 815 816 bool DSAStackTy::hasDirective( 817 const llvm::function_ref<bool(OpenMPDirectiveKind, 818 const DeclarationNameInfo &, SourceLocation)> 819 &DPred, 820 bool FromParent) { 821 // We look only in the enclosing region. 822 if (Stack.size() < 2) 823 return false; 824 auto StartI = std::next(Stack.rbegin()); 825 auto EndI = std::prev(Stack.rend()); 826 if (FromParent && StartI != EndI) { 827 StartI = std::next(StartI); 828 } 829 for (auto I = StartI, EE = EndI; I != EE; ++I) { 830 if (DPred(I->Directive, I->DirectiveName, I->ConstructLoc)) 831 return true; 832 } 833 return false; 834 } 835 836 void Sema::InitDataSharingAttributesStack() { 837 VarDataSharingAttributesStack = new DSAStackTy(*this); 838 } 839 840 #define DSAStack static_cast<DSAStackTy *>(VarDataSharingAttributesStack) 841 842 bool Sema::IsOpenMPCapturedByRef(ValueDecl *D, unsigned Level) { 843 assert(LangOpts.OpenMP && "OpenMP is not allowed"); 844 845 auto &Ctx = getASTContext(); 846 bool IsByRef = true; 847 848 // Find the directive that is associated with the provided scope. 849 auto Ty = D->getType(); 850 851 if (DSAStack->hasExplicitDirective(isOpenMPTargetExecutionDirective, Level)) { 852 // This table summarizes how a given variable should be passed to the device 853 // given its type and the clauses where it appears. This table is based on 854 // the description in OpenMP 4.5 [2.10.4, target Construct] and 855 // OpenMP 4.5 [2.15.5, Data-mapping Attribute Rules and Clauses]. 856 // 857 // ========================================================================= 858 // | type | defaultmap | pvt | first | is_device_ptr | map | res. | 859 // | |(tofrom:scalar)| | pvt | | | | 860 // ========================================================================= 861 // | scl | | | | - | | bycopy| 862 // | scl | | - | x | - | - | bycopy| 863 // | scl | | x | - | - | - | null | 864 // | scl | x | | | - | | byref | 865 // | scl | x | - | x | - | - | bycopy| 866 // | scl | x | x | - | - | - | null | 867 // | scl | | - | - | - | x | byref | 868 // | scl | x | - | - | - | x | byref | 869 // 870 // | agg | n.a. | | | - | | byref | 871 // | agg | n.a. | - | x | - | - | byref | 872 // | agg | n.a. | x | - | - | - | null | 873 // | agg | n.a. | - | - | - | x | byref | 874 // | agg | n.a. | - | - | - | x[] | byref | 875 // 876 // | ptr | n.a. | | | - | | bycopy| 877 // | ptr | n.a. | - | x | - | - | bycopy| 878 // | ptr | n.a. | x | - | - | - | null | 879 // | ptr | n.a. | - | - | - | x | byref | 880 // | ptr | n.a. | - | - | - | x[] | bycopy| 881 // | ptr | n.a. | - | - | x | | bycopy| 882 // | ptr | n.a. | - | - | x | x | bycopy| 883 // | ptr | n.a. | - | - | x | x[] | bycopy| 884 // ========================================================================= 885 // Legend: 886 // scl - scalar 887 // ptr - pointer 888 // agg - aggregate 889 // x - applies 890 // - - invalid in this combination 891 // [] - mapped with an array section 892 // byref - should be mapped by reference 893 // byval - should be mapped by value 894 // null - initialize a local variable to null on the device 895 // 896 // Observations: 897 // - All scalar declarations that show up in a map clause have to be passed 898 // by reference, because they may have been mapped in the enclosing data 899 // environment. 900 // - If the scalar value does not fit the size of uintptr, it has to be 901 // passed by reference, regardless the result in the table above. 902 // - For pointers mapped by value that have either an implicit map or an 903 // array section, the runtime library may pass the NULL value to the 904 // device instead of the value passed to it by the compiler. 905 906 907 if (Ty->isReferenceType()) 908 Ty = Ty->castAs<ReferenceType>()->getPointeeType(); 909 910 // Locate map clauses and see if the variable being captured is referred to 911 // in any of those clauses. Here we only care about variables, not fields, 912 // because fields are part of aggregates. 913 bool IsVariableUsedInMapClause = false; 914 bool IsVariableAssociatedWithSection = false; 915 916 DSAStack->checkMappableExprComponentListsForDecl( 917 D, /*CurrentRegionOnly=*/true, 918 [&](OMPClauseMappableExprCommon::MappableExprComponentListRef 919 MapExprComponents) { 920 921 auto EI = MapExprComponents.rbegin(); 922 auto EE = MapExprComponents.rend(); 923 924 assert(EI != EE && "Invalid map expression!"); 925 926 if (isa<DeclRefExpr>(EI->getAssociatedExpression())) 927 IsVariableUsedInMapClause |= EI->getAssociatedDeclaration() == D; 928 929 ++EI; 930 if (EI == EE) 931 return false; 932 933 if (isa<ArraySubscriptExpr>(EI->getAssociatedExpression()) || 934 isa<OMPArraySectionExpr>(EI->getAssociatedExpression()) || 935 isa<MemberExpr>(EI->getAssociatedExpression())) { 936 IsVariableAssociatedWithSection = true; 937 // There is nothing more we need to know about this variable. 938 return true; 939 } 940 941 // Keep looking for more map info. 942 return false; 943 }); 944 945 if (IsVariableUsedInMapClause) { 946 // If variable is identified in a map clause it is always captured by 947 // reference except if it is a pointer that is dereferenced somehow. 948 IsByRef = !(Ty->isPointerType() && IsVariableAssociatedWithSection); 949 } else { 950 // By default, all the data that has a scalar type is mapped by copy. 951 IsByRef = !Ty->isScalarType(); 952 } 953 } 954 955 if (IsByRef && Ty.getNonReferenceType()->isScalarType()) { 956 IsByRef = !DSAStack->hasExplicitDSA( 957 D, [](OpenMPClauseKind K) -> bool { return K == OMPC_firstprivate; }, 958 Level, /*NotLastprivate=*/true); 959 } 960 961 // When passing data by copy, we need to make sure it fits the uintptr size 962 // and alignment, because the runtime library only deals with uintptr types. 963 // If it does not fit the uintptr size, we need to pass the data by reference 964 // instead. 965 if (!IsByRef && 966 (Ctx.getTypeSizeInChars(Ty) > 967 Ctx.getTypeSizeInChars(Ctx.getUIntPtrType()) || 968 Ctx.getDeclAlign(D) > Ctx.getTypeAlignInChars(Ctx.getUIntPtrType()))) { 969 IsByRef = true; 970 } 971 972 return IsByRef; 973 } 974 975 unsigned Sema::getOpenMPNestingLevel() const { 976 assert(getLangOpts().OpenMP); 977 return DSAStack->getNestingLevel(); 978 } 979 980 VarDecl *Sema::IsOpenMPCapturedDecl(ValueDecl *D) { 981 assert(LangOpts.OpenMP && "OpenMP is not allowed"); 982 D = getCanonicalDecl(D); 983 984 // If we are attempting to capture a global variable in a directive with 985 // 'target' we return true so that this global is also mapped to the device. 986 // 987 // FIXME: If the declaration is enclosed in a 'declare target' directive, 988 // then it should not be captured. Therefore, an extra check has to be 989 // inserted here once support for 'declare target' is added. 990 // 991 auto *VD = dyn_cast<VarDecl>(D); 992 if (VD && !VD->hasLocalStorage()) { 993 if (DSAStack->getCurrentDirective() == OMPD_target && 994 !DSAStack->isClauseParsingMode()) 995 return VD; 996 if (DSAStack->hasDirective( 997 [](OpenMPDirectiveKind K, const DeclarationNameInfo &, 998 SourceLocation) -> bool { 999 return isOpenMPTargetExecutionDirective(K); 1000 }, 1001 false)) 1002 return VD; 1003 } 1004 1005 if (DSAStack->getCurrentDirective() != OMPD_unknown && 1006 (!DSAStack->isClauseParsingMode() || 1007 DSAStack->getParentDirective() != OMPD_unknown)) { 1008 auto &&Info = DSAStack->isLoopControlVariable(D); 1009 if (Info.first || 1010 (VD && VD->hasLocalStorage() && 1011 isParallelOrTaskRegion(DSAStack->getCurrentDirective())) || 1012 (VD && DSAStack->isForceVarCapturing())) 1013 return VD ? VD : Info.second; 1014 auto DVarPrivate = DSAStack->getTopDSA(D, DSAStack->isClauseParsingMode()); 1015 if (DVarPrivate.CKind != OMPC_unknown && isOpenMPPrivate(DVarPrivate.CKind)) 1016 return VD ? VD : cast<VarDecl>(DVarPrivate.PrivateCopy->getDecl()); 1017 DVarPrivate = DSAStack->hasDSA( 1018 D, isOpenMPPrivate, [](OpenMPDirectiveKind) -> bool { return true; }, 1019 DSAStack->isClauseParsingMode()); 1020 if (DVarPrivate.CKind != OMPC_unknown) 1021 return VD ? VD : cast<VarDecl>(DVarPrivate.PrivateCopy->getDecl()); 1022 } 1023 return nullptr; 1024 } 1025 1026 bool Sema::isOpenMPPrivateDecl(ValueDecl *D, unsigned Level) { 1027 assert(LangOpts.OpenMP && "OpenMP is not allowed"); 1028 return DSAStack->hasExplicitDSA( 1029 D, [](OpenMPClauseKind K) -> bool { return K == OMPC_private; }, Level); 1030 } 1031 1032 bool Sema::isOpenMPTargetCapturedDecl(ValueDecl *D, unsigned Level) { 1033 assert(LangOpts.OpenMP && "OpenMP is not allowed"); 1034 // Return true if the current level is no longer enclosed in a target region. 1035 1036 auto *VD = dyn_cast<VarDecl>(D); 1037 return VD && !VD->hasLocalStorage() && 1038 DSAStack->hasExplicitDirective(isOpenMPTargetExecutionDirective, 1039 Level); 1040 } 1041 1042 void Sema::DestroyDataSharingAttributesStack() { delete DSAStack; } 1043 1044 void Sema::StartOpenMPDSABlock(OpenMPDirectiveKind DKind, 1045 const DeclarationNameInfo &DirName, 1046 Scope *CurScope, SourceLocation Loc) { 1047 DSAStack->push(DKind, DirName, CurScope, Loc); 1048 PushExpressionEvaluationContext(PotentiallyEvaluated); 1049 } 1050 1051 void Sema::StartOpenMPClause(OpenMPClauseKind K) { 1052 DSAStack->setClauseParsingMode(K); 1053 } 1054 1055 void Sema::EndOpenMPClause() { 1056 DSAStack->setClauseParsingMode(/*K=*/OMPC_unknown); 1057 } 1058 1059 void Sema::EndOpenMPDSABlock(Stmt *CurDirective) { 1060 // OpenMP [2.14.3.5, Restrictions, C/C++, p.1] 1061 // A variable of class type (or array thereof) that appears in a lastprivate 1062 // clause requires an accessible, unambiguous default constructor for the 1063 // class type, unless the list item is also specified in a firstprivate 1064 // clause. 1065 if (auto D = dyn_cast_or_null<OMPExecutableDirective>(CurDirective)) { 1066 for (auto *C : D->clauses()) { 1067 if (auto *Clause = dyn_cast<OMPLastprivateClause>(C)) { 1068 SmallVector<Expr *, 8> PrivateCopies; 1069 for (auto *DE : Clause->varlists()) { 1070 if (DE->isValueDependent() || DE->isTypeDependent()) { 1071 PrivateCopies.push_back(nullptr); 1072 continue; 1073 } 1074 auto *DRE = cast<DeclRefExpr>(DE->IgnoreParens()); 1075 VarDecl *VD = cast<VarDecl>(DRE->getDecl()); 1076 QualType Type = VD->getType().getNonReferenceType(); 1077 auto DVar = DSAStack->getTopDSA(VD, false); 1078 if (DVar.CKind == OMPC_lastprivate) { 1079 // Generate helper private variable and initialize it with the 1080 // default value. The address of the original variable is replaced 1081 // by the address of the new private variable in CodeGen. This new 1082 // variable is not added to IdResolver, so the code in the OpenMP 1083 // region uses original variable for proper diagnostics. 1084 auto *VDPrivate = buildVarDecl( 1085 *this, DE->getExprLoc(), Type.getUnqualifiedType(), 1086 VD->getName(), VD->hasAttrs() ? &VD->getAttrs() : nullptr); 1087 ActOnUninitializedDecl(VDPrivate, /*TypeMayContainAuto=*/false); 1088 if (VDPrivate->isInvalidDecl()) 1089 continue; 1090 PrivateCopies.push_back(buildDeclRefExpr( 1091 *this, VDPrivate, DE->getType(), DE->getExprLoc())); 1092 } else { 1093 // The variable is also a firstprivate, so initialization sequence 1094 // for private copy is generated already. 1095 PrivateCopies.push_back(nullptr); 1096 } 1097 } 1098 // Set initializers to private copies if no errors were found. 1099 if (PrivateCopies.size() == Clause->varlist_size()) 1100 Clause->setPrivateCopies(PrivateCopies); 1101 } 1102 } 1103 } 1104 1105 DSAStack->pop(); 1106 DiscardCleanupsInEvaluationContext(); 1107 PopExpressionEvaluationContext(); 1108 } 1109 1110 static bool FinishOpenMPLinearClause(OMPLinearClause &Clause, DeclRefExpr *IV, 1111 Expr *NumIterations, Sema &SemaRef, 1112 Scope *S, DSAStackTy *Stack); 1113 1114 namespace { 1115 1116 class VarDeclFilterCCC : public CorrectionCandidateCallback { 1117 private: 1118 Sema &SemaRef; 1119 1120 public: 1121 explicit VarDeclFilterCCC(Sema &S) : SemaRef(S) {} 1122 bool ValidateCandidate(const TypoCorrection &Candidate) override { 1123 NamedDecl *ND = Candidate.getCorrectionDecl(); 1124 if (VarDecl *VD = dyn_cast_or_null<VarDecl>(ND)) { 1125 return VD->hasGlobalStorage() && 1126 SemaRef.isDeclInScope(ND, SemaRef.getCurLexicalContext(), 1127 SemaRef.getCurScope()); 1128 } 1129 return false; 1130 } 1131 }; 1132 1133 class VarOrFuncDeclFilterCCC : public CorrectionCandidateCallback { 1134 private: 1135 Sema &SemaRef; 1136 1137 public: 1138 explicit VarOrFuncDeclFilterCCC(Sema &S) : SemaRef(S) {} 1139 bool ValidateCandidate(const TypoCorrection &Candidate) override { 1140 NamedDecl *ND = Candidate.getCorrectionDecl(); 1141 if (isa<VarDecl>(ND) || isa<FunctionDecl>(ND)) { 1142 return SemaRef.isDeclInScope(ND, SemaRef.getCurLexicalContext(), 1143 SemaRef.getCurScope()); 1144 } 1145 return false; 1146 } 1147 }; 1148 1149 } // namespace 1150 1151 ExprResult Sema::ActOnOpenMPIdExpression(Scope *CurScope, 1152 CXXScopeSpec &ScopeSpec, 1153 const DeclarationNameInfo &Id) { 1154 LookupResult Lookup(*this, Id, LookupOrdinaryName); 1155 LookupParsedName(Lookup, CurScope, &ScopeSpec, true); 1156 1157 if (Lookup.isAmbiguous()) 1158 return ExprError(); 1159 1160 VarDecl *VD; 1161 if (!Lookup.isSingleResult()) { 1162 if (TypoCorrection Corrected = CorrectTypo( 1163 Id, LookupOrdinaryName, CurScope, nullptr, 1164 llvm::make_unique<VarDeclFilterCCC>(*this), CTK_ErrorRecovery)) { 1165 diagnoseTypo(Corrected, 1166 PDiag(Lookup.empty() 1167 ? diag::err_undeclared_var_use_suggest 1168 : diag::err_omp_expected_var_arg_suggest) 1169 << Id.getName()); 1170 VD = Corrected.getCorrectionDeclAs<VarDecl>(); 1171 } else { 1172 Diag(Id.getLoc(), Lookup.empty() ? diag::err_undeclared_var_use 1173 : diag::err_omp_expected_var_arg) 1174 << Id.getName(); 1175 return ExprError(); 1176 } 1177 } else { 1178 if (!(VD = Lookup.getAsSingle<VarDecl>())) { 1179 Diag(Id.getLoc(), diag::err_omp_expected_var_arg) << Id.getName(); 1180 Diag(Lookup.getFoundDecl()->getLocation(), diag::note_declared_at); 1181 return ExprError(); 1182 } 1183 } 1184 Lookup.suppressDiagnostics(); 1185 1186 // OpenMP [2.9.2, Syntax, C/C++] 1187 // Variables must be file-scope, namespace-scope, or static block-scope. 1188 if (!VD->hasGlobalStorage()) { 1189 Diag(Id.getLoc(), diag::err_omp_global_var_arg) 1190 << getOpenMPDirectiveName(OMPD_threadprivate) << !VD->isStaticLocal(); 1191 bool IsDecl = 1192 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly; 1193 Diag(VD->getLocation(), 1194 IsDecl ? diag::note_previous_decl : diag::note_defined_here) 1195 << VD; 1196 return ExprError(); 1197 } 1198 1199 VarDecl *CanonicalVD = VD->getCanonicalDecl(); 1200 NamedDecl *ND = cast<NamedDecl>(CanonicalVD); 1201 // OpenMP [2.9.2, Restrictions, C/C++, p.2] 1202 // A threadprivate directive for file-scope variables must appear outside 1203 // any definition or declaration. 1204 if (CanonicalVD->getDeclContext()->isTranslationUnit() && 1205 !getCurLexicalContext()->isTranslationUnit()) { 1206 Diag(Id.getLoc(), diag::err_omp_var_scope) 1207 << getOpenMPDirectiveName(OMPD_threadprivate) << VD; 1208 bool IsDecl = 1209 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly; 1210 Diag(VD->getLocation(), 1211 IsDecl ? diag::note_previous_decl : diag::note_defined_here) 1212 << VD; 1213 return ExprError(); 1214 } 1215 // OpenMP [2.9.2, Restrictions, C/C++, p.3] 1216 // A threadprivate directive for static class member variables must appear 1217 // in the class definition, in the same scope in which the member 1218 // variables are declared. 1219 if (CanonicalVD->isStaticDataMember() && 1220 !CanonicalVD->getDeclContext()->Equals(getCurLexicalContext())) { 1221 Diag(Id.getLoc(), diag::err_omp_var_scope) 1222 << getOpenMPDirectiveName(OMPD_threadprivate) << VD; 1223 bool IsDecl = 1224 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly; 1225 Diag(VD->getLocation(), 1226 IsDecl ? diag::note_previous_decl : diag::note_defined_here) 1227 << VD; 1228 return ExprError(); 1229 } 1230 // OpenMP [2.9.2, Restrictions, C/C++, p.4] 1231 // A threadprivate directive for namespace-scope variables must appear 1232 // outside any definition or declaration other than the namespace 1233 // definition itself. 1234 if (CanonicalVD->getDeclContext()->isNamespace() && 1235 (!getCurLexicalContext()->isFileContext() || 1236 !getCurLexicalContext()->Encloses(CanonicalVD->getDeclContext()))) { 1237 Diag(Id.getLoc(), diag::err_omp_var_scope) 1238 << getOpenMPDirectiveName(OMPD_threadprivate) << VD; 1239 bool IsDecl = 1240 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly; 1241 Diag(VD->getLocation(), 1242 IsDecl ? diag::note_previous_decl : diag::note_defined_here) 1243 << VD; 1244 return ExprError(); 1245 } 1246 // OpenMP [2.9.2, Restrictions, C/C++, p.6] 1247 // A threadprivate directive for static block-scope variables must appear 1248 // in the scope of the variable and not in a nested scope. 1249 if (CanonicalVD->isStaticLocal() && CurScope && 1250 !isDeclInScope(ND, getCurLexicalContext(), CurScope)) { 1251 Diag(Id.getLoc(), diag::err_omp_var_scope) 1252 << getOpenMPDirectiveName(OMPD_threadprivate) << VD; 1253 bool IsDecl = 1254 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly; 1255 Diag(VD->getLocation(), 1256 IsDecl ? diag::note_previous_decl : diag::note_defined_here) 1257 << VD; 1258 return ExprError(); 1259 } 1260 1261 // OpenMP [2.9.2, Restrictions, C/C++, p.2-6] 1262 // A threadprivate directive must lexically precede all references to any 1263 // of the variables in its list. 1264 if (VD->isUsed() && !DSAStack->isThreadPrivate(VD)) { 1265 Diag(Id.getLoc(), diag::err_omp_var_used) 1266 << getOpenMPDirectiveName(OMPD_threadprivate) << VD; 1267 return ExprError(); 1268 } 1269 1270 QualType ExprType = VD->getType().getNonReferenceType(); 1271 return DeclRefExpr::Create(Context, NestedNameSpecifierLoc(), 1272 SourceLocation(), VD, 1273 /*RefersToEnclosingVariableOrCapture=*/false, 1274 Id.getLoc(), ExprType, VK_LValue); 1275 } 1276 1277 Sema::DeclGroupPtrTy 1278 Sema::ActOnOpenMPThreadprivateDirective(SourceLocation Loc, 1279 ArrayRef<Expr *> VarList) { 1280 if (OMPThreadPrivateDecl *D = CheckOMPThreadPrivateDecl(Loc, VarList)) { 1281 CurContext->addDecl(D); 1282 return DeclGroupPtrTy::make(DeclGroupRef(D)); 1283 } 1284 return nullptr; 1285 } 1286 1287 namespace { 1288 class LocalVarRefChecker : public ConstStmtVisitor<LocalVarRefChecker, bool> { 1289 Sema &SemaRef; 1290 1291 public: 1292 bool VisitDeclRefExpr(const DeclRefExpr *E) { 1293 if (auto VD = dyn_cast<VarDecl>(E->getDecl())) { 1294 if (VD->hasLocalStorage()) { 1295 SemaRef.Diag(E->getLocStart(), 1296 diag::err_omp_local_var_in_threadprivate_init) 1297 << E->getSourceRange(); 1298 SemaRef.Diag(VD->getLocation(), diag::note_defined_here) 1299 << VD << VD->getSourceRange(); 1300 return true; 1301 } 1302 } 1303 return false; 1304 } 1305 bool VisitStmt(const Stmt *S) { 1306 for (auto Child : S->children()) { 1307 if (Child && Visit(Child)) 1308 return true; 1309 } 1310 return false; 1311 } 1312 explicit LocalVarRefChecker(Sema &SemaRef) : SemaRef(SemaRef) {} 1313 }; 1314 } // namespace 1315 1316 OMPThreadPrivateDecl * 1317 Sema::CheckOMPThreadPrivateDecl(SourceLocation Loc, ArrayRef<Expr *> VarList) { 1318 SmallVector<Expr *, 8> Vars; 1319 for (auto &RefExpr : VarList) { 1320 DeclRefExpr *DE = cast<DeclRefExpr>(RefExpr); 1321 VarDecl *VD = cast<VarDecl>(DE->getDecl()); 1322 SourceLocation ILoc = DE->getExprLoc(); 1323 1324 // Mark variable as used. 1325 VD->setReferenced(); 1326 VD->markUsed(Context); 1327 1328 QualType QType = VD->getType(); 1329 if (QType->isDependentType() || QType->isInstantiationDependentType()) { 1330 // It will be analyzed later. 1331 Vars.push_back(DE); 1332 continue; 1333 } 1334 1335 // OpenMP [2.9.2, Restrictions, C/C++, p.10] 1336 // A threadprivate variable must not have an incomplete type. 1337 if (RequireCompleteType(ILoc, VD->getType(), 1338 diag::err_omp_threadprivate_incomplete_type)) { 1339 continue; 1340 } 1341 1342 // OpenMP [2.9.2, Restrictions, C/C++, p.10] 1343 // A threadprivate variable must not have a reference type. 1344 if (VD->getType()->isReferenceType()) { 1345 Diag(ILoc, diag::err_omp_ref_type_arg) 1346 << getOpenMPDirectiveName(OMPD_threadprivate) << VD->getType(); 1347 bool IsDecl = 1348 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly; 1349 Diag(VD->getLocation(), 1350 IsDecl ? diag::note_previous_decl : diag::note_defined_here) 1351 << VD; 1352 continue; 1353 } 1354 1355 // Check if this is a TLS variable. If TLS is not being supported, produce 1356 // the corresponding diagnostic. 1357 if ((VD->getTLSKind() != VarDecl::TLS_None && 1358 !(VD->hasAttr<OMPThreadPrivateDeclAttr>() && 1359 getLangOpts().OpenMPUseTLS && 1360 getASTContext().getTargetInfo().isTLSSupported())) || 1361 (VD->getStorageClass() == SC_Register && VD->hasAttr<AsmLabelAttr>() && 1362 !VD->isLocalVarDecl())) { 1363 Diag(ILoc, diag::err_omp_var_thread_local) 1364 << VD << ((VD->getTLSKind() != VarDecl::TLS_None) ? 0 : 1); 1365 bool IsDecl = 1366 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly; 1367 Diag(VD->getLocation(), 1368 IsDecl ? diag::note_previous_decl : diag::note_defined_here) 1369 << VD; 1370 continue; 1371 } 1372 1373 // Check if initial value of threadprivate variable reference variable with 1374 // local storage (it is not supported by runtime). 1375 if (auto Init = VD->getAnyInitializer()) { 1376 LocalVarRefChecker Checker(*this); 1377 if (Checker.Visit(Init)) 1378 continue; 1379 } 1380 1381 Vars.push_back(RefExpr); 1382 DSAStack->addDSA(VD, DE, OMPC_threadprivate); 1383 VD->addAttr(OMPThreadPrivateDeclAttr::CreateImplicit( 1384 Context, SourceRange(Loc, Loc))); 1385 if (auto *ML = Context.getASTMutationListener()) 1386 ML->DeclarationMarkedOpenMPThreadPrivate(VD); 1387 } 1388 OMPThreadPrivateDecl *D = nullptr; 1389 if (!Vars.empty()) { 1390 D = OMPThreadPrivateDecl::Create(Context, getCurLexicalContext(), Loc, 1391 Vars); 1392 D->setAccess(AS_public); 1393 } 1394 return D; 1395 } 1396 1397 static void ReportOriginalDSA(Sema &SemaRef, DSAStackTy *Stack, 1398 const ValueDecl *D, DSAStackTy::DSAVarData DVar, 1399 bool IsLoopIterVar = false) { 1400 if (DVar.RefExpr) { 1401 SemaRef.Diag(DVar.RefExpr->getExprLoc(), diag::note_omp_explicit_dsa) 1402 << getOpenMPClauseName(DVar.CKind); 1403 return; 1404 } 1405 enum { 1406 PDSA_StaticMemberShared, 1407 PDSA_StaticLocalVarShared, 1408 PDSA_LoopIterVarPrivate, 1409 PDSA_LoopIterVarLinear, 1410 PDSA_LoopIterVarLastprivate, 1411 PDSA_ConstVarShared, 1412 PDSA_GlobalVarShared, 1413 PDSA_TaskVarFirstprivate, 1414 PDSA_LocalVarPrivate, 1415 PDSA_Implicit 1416 } Reason = PDSA_Implicit; 1417 bool ReportHint = false; 1418 auto ReportLoc = D->getLocation(); 1419 auto *VD = dyn_cast<VarDecl>(D); 1420 if (IsLoopIterVar) { 1421 if (DVar.CKind == OMPC_private) 1422 Reason = PDSA_LoopIterVarPrivate; 1423 else if (DVar.CKind == OMPC_lastprivate) 1424 Reason = PDSA_LoopIterVarLastprivate; 1425 else 1426 Reason = PDSA_LoopIterVarLinear; 1427 } else if (isOpenMPTaskingDirective(DVar.DKind) && 1428 DVar.CKind == OMPC_firstprivate) { 1429 Reason = PDSA_TaskVarFirstprivate; 1430 ReportLoc = DVar.ImplicitDSALoc; 1431 } else if (VD && VD->isStaticLocal()) 1432 Reason = PDSA_StaticLocalVarShared; 1433 else if (VD && VD->isStaticDataMember()) 1434 Reason = PDSA_StaticMemberShared; 1435 else if (VD && VD->isFileVarDecl()) 1436 Reason = PDSA_GlobalVarShared; 1437 else if (D->getType().isConstant(SemaRef.getASTContext())) 1438 Reason = PDSA_ConstVarShared; 1439 else if (VD && VD->isLocalVarDecl() && DVar.CKind == OMPC_private) { 1440 ReportHint = true; 1441 Reason = PDSA_LocalVarPrivate; 1442 } 1443 if (Reason != PDSA_Implicit) { 1444 SemaRef.Diag(ReportLoc, diag::note_omp_predetermined_dsa) 1445 << Reason << ReportHint 1446 << getOpenMPDirectiveName(Stack->getCurrentDirective()); 1447 } else if (DVar.ImplicitDSALoc.isValid()) { 1448 SemaRef.Diag(DVar.ImplicitDSALoc, diag::note_omp_implicit_dsa) 1449 << getOpenMPClauseName(DVar.CKind); 1450 } 1451 } 1452 1453 namespace { 1454 class DSAAttrChecker : public StmtVisitor<DSAAttrChecker, void> { 1455 DSAStackTy *Stack; 1456 Sema &SemaRef; 1457 bool ErrorFound; 1458 CapturedStmt *CS; 1459 llvm::SmallVector<Expr *, 8> ImplicitFirstprivate; 1460 llvm::DenseMap<ValueDecl *, Expr *> VarsWithInheritedDSA; 1461 1462 public: 1463 void VisitDeclRefExpr(DeclRefExpr *E) { 1464 if (E->isTypeDependent() || E->isValueDependent() || 1465 E->containsUnexpandedParameterPack() || E->isInstantiationDependent()) 1466 return; 1467 if (auto *VD = dyn_cast<VarDecl>(E->getDecl())) { 1468 // Skip internally declared variables. 1469 if (VD->isLocalVarDecl() && !CS->capturesVariable(VD)) 1470 return; 1471 1472 auto DVar = Stack->getTopDSA(VD, false); 1473 // Check if the variable has explicit DSA set and stop analysis if it so. 1474 if (DVar.RefExpr) return; 1475 1476 auto ELoc = E->getExprLoc(); 1477 auto DKind = Stack->getCurrentDirective(); 1478 // The default(none) clause requires that each variable that is referenced 1479 // in the construct, and does not have a predetermined data-sharing 1480 // attribute, must have its data-sharing attribute explicitly determined 1481 // by being listed in a data-sharing attribute clause. 1482 if (DVar.CKind == OMPC_unknown && Stack->getDefaultDSA() == DSA_none && 1483 isParallelOrTaskRegion(DKind) && 1484 VarsWithInheritedDSA.count(VD) == 0) { 1485 VarsWithInheritedDSA[VD] = E; 1486 return; 1487 } 1488 1489 // OpenMP [2.9.3.6, Restrictions, p.2] 1490 // A list item that appears in a reduction clause of the innermost 1491 // enclosing worksharing or parallel construct may not be accessed in an 1492 // explicit task. 1493 DVar = Stack->hasInnermostDSA( 1494 VD, [](OpenMPClauseKind C) -> bool { return C == OMPC_reduction; }, 1495 [](OpenMPDirectiveKind K) -> bool { 1496 return isOpenMPParallelDirective(K) || 1497 isOpenMPWorksharingDirective(K) || isOpenMPTeamsDirective(K); 1498 }, 1499 false); 1500 if (isOpenMPTaskingDirective(DKind) && DVar.CKind == OMPC_reduction) { 1501 ErrorFound = true; 1502 SemaRef.Diag(ELoc, diag::err_omp_reduction_in_task); 1503 ReportOriginalDSA(SemaRef, Stack, VD, DVar); 1504 return; 1505 } 1506 1507 // Define implicit data-sharing attributes for task. 1508 DVar = Stack->getImplicitDSA(VD, false); 1509 if (isOpenMPTaskingDirective(DKind) && DVar.CKind != OMPC_shared && 1510 !Stack->isLoopControlVariable(VD).first) 1511 ImplicitFirstprivate.push_back(E); 1512 } 1513 } 1514 void VisitMemberExpr(MemberExpr *E) { 1515 if (E->isTypeDependent() || E->isValueDependent() || 1516 E->containsUnexpandedParameterPack() || E->isInstantiationDependent()) 1517 return; 1518 if (isa<CXXThisExpr>(E->getBase()->IgnoreParens())) { 1519 if (auto *FD = dyn_cast<FieldDecl>(E->getMemberDecl())) { 1520 auto DVar = Stack->getTopDSA(FD, false); 1521 // Check if the variable has explicit DSA set and stop analysis if it 1522 // so. 1523 if (DVar.RefExpr) 1524 return; 1525 1526 auto ELoc = E->getExprLoc(); 1527 auto DKind = Stack->getCurrentDirective(); 1528 // OpenMP [2.9.3.6, Restrictions, p.2] 1529 // A list item that appears in a reduction clause of the innermost 1530 // enclosing worksharing or parallel construct may not be accessed in 1531 // an explicit task. 1532 DVar = Stack->hasInnermostDSA( 1533 FD, [](OpenMPClauseKind C) -> bool { return C == OMPC_reduction; }, 1534 [](OpenMPDirectiveKind K) -> bool { 1535 return isOpenMPParallelDirective(K) || 1536 isOpenMPWorksharingDirective(K) || 1537 isOpenMPTeamsDirective(K); 1538 }, 1539 false); 1540 if (isOpenMPTaskingDirective(DKind) && DVar.CKind == OMPC_reduction) { 1541 ErrorFound = true; 1542 SemaRef.Diag(ELoc, diag::err_omp_reduction_in_task); 1543 ReportOriginalDSA(SemaRef, Stack, FD, DVar); 1544 return; 1545 } 1546 1547 // Define implicit data-sharing attributes for task. 1548 DVar = Stack->getImplicitDSA(FD, false); 1549 if (isOpenMPTaskingDirective(DKind) && DVar.CKind != OMPC_shared && 1550 !Stack->isLoopControlVariable(FD).first) 1551 ImplicitFirstprivate.push_back(E); 1552 } 1553 } 1554 } 1555 void VisitOMPExecutableDirective(OMPExecutableDirective *S) { 1556 for (auto *C : S->clauses()) { 1557 // Skip analysis of arguments of implicitly defined firstprivate clause 1558 // for task directives. 1559 if (C && (!isa<OMPFirstprivateClause>(C) || C->getLocStart().isValid())) 1560 for (auto *CC : C->children()) { 1561 if (CC) 1562 Visit(CC); 1563 } 1564 } 1565 } 1566 void VisitStmt(Stmt *S) { 1567 for (auto *C : S->children()) { 1568 if (C && !isa<OMPExecutableDirective>(C)) 1569 Visit(C); 1570 } 1571 } 1572 1573 bool isErrorFound() { return ErrorFound; } 1574 ArrayRef<Expr *> getImplicitFirstprivate() { return ImplicitFirstprivate; } 1575 llvm::DenseMap<ValueDecl *, Expr *> &getVarsWithInheritedDSA() { 1576 return VarsWithInheritedDSA; 1577 } 1578 1579 DSAAttrChecker(DSAStackTy *S, Sema &SemaRef, CapturedStmt *CS) 1580 : Stack(S), SemaRef(SemaRef), ErrorFound(false), CS(CS) {} 1581 }; 1582 } // namespace 1583 1584 void Sema::ActOnOpenMPRegionStart(OpenMPDirectiveKind DKind, Scope *CurScope) { 1585 switch (DKind) { 1586 case OMPD_parallel: { 1587 QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1); 1588 QualType KmpInt32PtrTy = 1589 Context.getPointerType(KmpInt32Ty).withConst().withRestrict(); 1590 Sema::CapturedParamNameType Params[] = { 1591 std::make_pair(".global_tid.", KmpInt32PtrTy), 1592 std::make_pair(".bound_tid.", KmpInt32PtrTy), 1593 std::make_pair(StringRef(), QualType()) // __context with shared vars 1594 }; 1595 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP, 1596 Params); 1597 break; 1598 } 1599 case OMPD_simd: { 1600 Sema::CapturedParamNameType Params[] = { 1601 std::make_pair(StringRef(), QualType()) // __context with shared vars 1602 }; 1603 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP, 1604 Params); 1605 break; 1606 } 1607 case OMPD_for: { 1608 Sema::CapturedParamNameType Params[] = { 1609 std::make_pair(StringRef(), QualType()) // __context with shared vars 1610 }; 1611 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP, 1612 Params); 1613 break; 1614 } 1615 case OMPD_for_simd: { 1616 Sema::CapturedParamNameType Params[] = { 1617 std::make_pair(StringRef(), QualType()) // __context with shared vars 1618 }; 1619 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP, 1620 Params); 1621 break; 1622 } 1623 case OMPD_sections: { 1624 Sema::CapturedParamNameType Params[] = { 1625 std::make_pair(StringRef(), QualType()) // __context with shared vars 1626 }; 1627 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP, 1628 Params); 1629 break; 1630 } 1631 case OMPD_section: { 1632 Sema::CapturedParamNameType Params[] = { 1633 std::make_pair(StringRef(), QualType()) // __context with shared vars 1634 }; 1635 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP, 1636 Params); 1637 break; 1638 } 1639 case OMPD_single: { 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_master: { 1648 Sema::CapturedParamNameType Params[] = { 1649 std::make_pair(StringRef(), QualType()) // __context with shared vars 1650 }; 1651 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP, 1652 Params); 1653 break; 1654 } 1655 case OMPD_critical: { 1656 Sema::CapturedParamNameType Params[] = { 1657 std::make_pair(StringRef(), QualType()) // __context with shared vars 1658 }; 1659 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP, 1660 Params); 1661 break; 1662 } 1663 case OMPD_parallel_for: { 1664 QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1); 1665 QualType KmpInt32PtrTy = 1666 Context.getPointerType(KmpInt32Ty).withConst().withRestrict(); 1667 Sema::CapturedParamNameType Params[] = { 1668 std::make_pair(".global_tid.", KmpInt32PtrTy), 1669 std::make_pair(".bound_tid.", KmpInt32PtrTy), 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_parallel_for_simd: { 1677 QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1); 1678 QualType KmpInt32PtrTy = 1679 Context.getPointerType(KmpInt32Ty).withConst().withRestrict(); 1680 Sema::CapturedParamNameType Params[] = { 1681 std::make_pair(".global_tid.", KmpInt32PtrTy), 1682 std::make_pair(".bound_tid.", KmpInt32PtrTy), 1683 std::make_pair(StringRef(), QualType()) // __context with shared vars 1684 }; 1685 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP, 1686 Params); 1687 break; 1688 } 1689 case OMPD_parallel_sections: { 1690 QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1); 1691 QualType KmpInt32PtrTy = 1692 Context.getPointerType(KmpInt32Ty).withConst().withRestrict(); 1693 Sema::CapturedParamNameType Params[] = { 1694 std::make_pair(".global_tid.", KmpInt32PtrTy), 1695 std::make_pair(".bound_tid.", KmpInt32PtrTy), 1696 std::make_pair(StringRef(), QualType()) // __context with shared vars 1697 }; 1698 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP, 1699 Params); 1700 break; 1701 } 1702 case OMPD_task: { 1703 QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1); 1704 QualType Args[] = {Context.VoidPtrTy.withConst().withRestrict()}; 1705 FunctionProtoType::ExtProtoInfo EPI; 1706 EPI.Variadic = true; 1707 QualType CopyFnType = Context.getFunctionType(Context.VoidTy, Args, EPI); 1708 Sema::CapturedParamNameType Params[] = { 1709 std::make_pair(".global_tid.", KmpInt32Ty), 1710 std::make_pair(".part_id.", Context.getPointerType(KmpInt32Ty)), 1711 std::make_pair(".privates.", Context.VoidPtrTy.withConst()), 1712 std::make_pair(".copy_fn.", 1713 Context.getPointerType(CopyFnType).withConst()), 1714 std::make_pair(".task_t.", Context.VoidPtrTy.withConst()), 1715 std::make_pair(StringRef(), QualType()) // __context with shared vars 1716 }; 1717 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP, 1718 Params); 1719 // Mark this captured region as inlined, because we don't use outlined 1720 // function directly. 1721 getCurCapturedRegion()->TheCapturedDecl->addAttr( 1722 AlwaysInlineAttr::CreateImplicit( 1723 Context, AlwaysInlineAttr::Keyword_forceinline, SourceRange())); 1724 break; 1725 } 1726 case OMPD_ordered: { 1727 Sema::CapturedParamNameType Params[] = { 1728 std::make_pair(StringRef(), QualType()) // __context with shared vars 1729 }; 1730 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP, 1731 Params); 1732 break; 1733 } 1734 case OMPD_atomic: { 1735 Sema::CapturedParamNameType Params[] = { 1736 std::make_pair(StringRef(), QualType()) // __context with shared vars 1737 }; 1738 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP, 1739 Params); 1740 break; 1741 } 1742 case OMPD_target_data: 1743 case OMPD_target: 1744 case OMPD_target_parallel: 1745 case OMPD_target_parallel_for: { 1746 Sema::CapturedParamNameType Params[] = { 1747 std::make_pair(StringRef(), QualType()) // __context with shared vars 1748 }; 1749 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP, 1750 Params); 1751 break; 1752 } 1753 case OMPD_teams: { 1754 QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1); 1755 QualType KmpInt32PtrTy = 1756 Context.getPointerType(KmpInt32Ty).withConst().withRestrict(); 1757 Sema::CapturedParamNameType Params[] = { 1758 std::make_pair(".global_tid.", KmpInt32PtrTy), 1759 std::make_pair(".bound_tid.", KmpInt32PtrTy), 1760 std::make_pair(StringRef(), QualType()) // __context with shared vars 1761 }; 1762 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP, 1763 Params); 1764 break; 1765 } 1766 case OMPD_taskgroup: { 1767 Sema::CapturedParamNameType Params[] = { 1768 std::make_pair(StringRef(), QualType()) // __context with shared vars 1769 }; 1770 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP, 1771 Params); 1772 break; 1773 } 1774 case OMPD_taskloop: 1775 case OMPD_taskloop_simd: { 1776 QualType KmpInt32Ty = 1777 Context.getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/1); 1778 QualType KmpUInt64Ty = 1779 Context.getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/0); 1780 QualType KmpInt64Ty = 1781 Context.getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/1); 1782 QualType Args[] = {Context.VoidPtrTy.withConst().withRestrict()}; 1783 FunctionProtoType::ExtProtoInfo EPI; 1784 EPI.Variadic = true; 1785 QualType CopyFnType = Context.getFunctionType(Context.VoidTy, Args, EPI); 1786 Sema::CapturedParamNameType Params[] = { 1787 std::make_pair(".global_tid.", KmpInt32Ty), 1788 std::make_pair(".part_id.", Context.getPointerType(KmpInt32Ty)), 1789 std::make_pair(".privates.", 1790 Context.VoidPtrTy.withConst().withRestrict()), 1791 std::make_pair( 1792 ".copy_fn.", 1793 Context.getPointerType(CopyFnType).withConst().withRestrict()), 1794 std::make_pair(".task_t.", Context.VoidPtrTy.withConst()), 1795 std::make_pair(".lb.", KmpUInt64Ty), 1796 std::make_pair(".ub.", KmpUInt64Ty), std::make_pair(".st.", KmpInt64Ty), 1797 std::make_pair(".liter.", KmpInt32Ty), 1798 std::make_pair(StringRef(), QualType()) // __context with shared vars 1799 }; 1800 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP, 1801 Params); 1802 // Mark this captured region as inlined, because we don't use outlined 1803 // function directly. 1804 getCurCapturedRegion()->TheCapturedDecl->addAttr( 1805 AlwaysInlineAttr::CreateImplicit( 1806 Context, AlwaysInlineAttr::Keyword_forceinline, SourceRange())); 1807 break; 1808 } 1809 case OMPD_distribute: { 1810 Sema::CapturedParamNameType Params[] = { 1811 std::make_pair(StringRef(), QualType()) // __context with shared vars 1812 }; 1813 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP, 1814 Params); 1815 break; 1816 } 1817 case OMPD_distribute_parallel_for_simd: 1818 case OMPD_distribute_parallel_for: { 1819 QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1); 1820 QualType KmpInt32PtrTy = 1821 Context.getPointerType(KmpInt32Ty).withConst().withRestrict(); 1822 Sema::CapturedParamNameType Params[] = { 1823 std::make_pair(".global_tid.", KmpInt32PtrTy), 1824 std::make_pair(".bound_tid.", KmpInt32PtrTy), 1825 std::make_pair(".previous.lb.", Context.getSizeType()), 1826 std::make_pair(".previous.ub.", Context.getSizeType()), 1827 std::make_pair(StringRef(), QualType()) // __context with shared vars 1828 }; 1829 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP, 1830 Params); 1831 break; 1832 } 1833 case OMPD_threadprivate: 1834 case OMPD_taskyield: 1835 case OMPD_barrier: 1836 case OMPD_taskwait: 1837 case OMPD_cancellation_point: 1838 case OMPD_cancel: 1839 case OMPD_flush: 1840 case OMPD_target_enter_data: 1841 case OMPD_target_exit_data: 1842 case OMPD_declare_reduction: 1843 case OMPD_declare_simd: 1844 case OMPD_declare_target: 1845 case OMPD_end_declare_target: 1846 case OMPD_target_update: 1847 llvm_unreachable("OpenMP Directive is not allowed"); 1848 case OMPD_unknown: 1849 llvm_unreachable("Unknown OpenMP directive"); 1850 } 1851 } 1852 1853 static OMPCapturedExprDecl *buildCaptureDecl(Sema &S, IdentifierInfo *Id, 1854 Expr *CaptureExpr, bool WithInit, 1855 bool AsExpression) { 1856 assert(CaptureExpr); 1857 ASTContext &C = S.getASTContext(); 1858 Expr *Init = AsExpression ? CaptureExpr : CaptureExpr->IgnoreImpCasts(); 1859 QualType Ty = Init->getType(); 1860 if (CaptureExpr->getObjectKind() == OK_Ordinary && CaptureExpr->isGLValue()) { 1861 if (S.getLangOpts().CPlusPlus) 1862 Ty = C.getLValueReferenceType(Ty); 1863 else { 1864 Ty = C.getPointerType(Ty); 1865 ExprResult Res = 1866 S.CreateBuiltinUnaryOp(CaptureExpr->getExprLoc(), UO_AddrOf, Init); 1867 if (!Res.isUsable()) 1868 return nullptr; 1869 Init = Res.get(); 1870 } 1871 WithInit = true; 1872 } 1873 auto *CED = OMPCapturedExprDecl::Create(C, S.CurContext, Id, Ty); 1874 if (!WithInit) 1875 CED->addAttr(OMPCaptureNoInitAttr::CreateImplicit(C, SourceRange())); 1876 S.CurContext->addHiddenDecl(CED); 1877 S.AddInitializerToDecl(CED, Init, /*DirectInit=*/false, 1878 /*TypeMayContainAuto=*/true); 1879 return CED; 1880 } 1881 1882 static DeclRefExpr *buildCapture(Sema &S, ValueDecl *D, Expr *CaptureExpr, 1883 bool WithInit) { 1884 OMPCapturedExprDecl *CD; 1885 if (auto *VD = S.IsOpenMPCapturedDecl(D)) 1886 CD = cast<OMPCapturedExprDecl>(VD); 1887 else 1888 CD = buildCaptureDecl(S, D->getIdentifier(), CaptureExpr, WithInit, 1889 /*AsExpression=*/false); 1890 return buildDeclRefExpr(S, CD, CD->getType().getNonReferenceType(), 1891 CaptureExpr->getExprLoc()); 1892 } 1893 1894 static ExprResult buildCapture(Sema &S, Expr *CaptureExpr, DeclRefExpr *&Ref) { 1895 if (!Ref) { 1896 auto *CD = 1897 buildCaptureDecl(S, &S.getASTContext().Idents.get(".capture_expr."), 1898 CaptureExpr, /*WithInit=*/true, /*AsExpression=*/true); 1899 Ref = buildDeclRefExpr(S, CD, CD->getType().getNonReferenceType(), 1900 CaptureExpr->getExprLoc()); 1901 } 1902 ExprResult Res = Ref; 1903 if (!S.getLangOpts().CPlusPlus && 1904 CaptureExpr->getObjectKind() == OK_Ordinary && CaptureExpr->isGLValue() && 1905 Ref->getType()->isPointerType()) 1906 Res = S.CreateBuiltinUnaryOp(CaptureExpr->getExprLoc(), UO_Deref, Ref); 1907 if (!Res.isUsable()) 1908 return ExprError(); 1909 return CaptureExpr->isGLValue() ? Res : S.DefaultLvalueConversion(Res.get()); 1910 } 1911 1912 StmtResult Sema::ActOnOpenMPRegionEnd(StmtResult S, 1913 ArrayRef<OMPClause *> Clauses) { 1914 if (!S.isUsable()) { 1915 ActOnCapturedRegionError(); 1916 return StmtError(); 1917 } 1918 1919 OMPOrderedClause *OC = nullptr; 1920 OMPScheduleClause *SC = nullptr; 1921 SmallVector<OMPLinearClause *, 4> LCs; 1922 // This is required for proper codegen. 1923 for (auto *Clause : Clauses) { 1924 if (isOpenMPPrivate(Clause->getClauseKind()) || 1925 Clause->getClauseKind() == OMPC_copyprivate || 1926 (getLangOpts().OpenMPUseTLS && 1927 getASTContext().getTargetInfo().isTLSSupported() && 1928 Clause->getClauseKind() == OMPC_copyin)) { 1929 DSAStack->setForceVarCapturing(Clause->getClauseKind() == OMPC_copyin); 1930 // Mark all variables in private list clauses as used in inner region. 1931 for (auto *VarRef : Clause->children()) { 1932 if (auto *E = cast_or_null<Expr>(VarRef)) { 1933 MarkDeclarationsReferencedInExpr(E); 1934 } 1935 } 1936 DSAStack->setForceVarCapturing(/*V=*/false); 1937 } else if (isParallelOrTaskRegion(DSAStack->getCurrentDirective())) { 1938 // Mark all variables in private list clauses as used in inner region. 1939 // Required for proper codegen of combined directives. 1940 // TODO: add processing for other clauses. 1941 if (auto *C = OMPClauseWithPreInit::get(Clause)) { 1942 if (auto *DS = cast_or_null<DeclStmt>(C->getPreInitStmt())) { 1943 for (auto *D : DS->decls()) 1944 MarkVariableReferenced(D->getLocation(), cast<VarDecl>(D)); 1945 } 1946 } 1947 if (auto *C = OMPClauseWithPostUpdate::get(Clause)) { 1948 if (auto *E = C->getPostUpdateExpr()) 1949 MarkDeclarationsReferencedInExpr(E); 1950 } 1951 } 1952 if (Clause->getClauseKind() == OMPC_schedule) 1953 SC = cast<OMPScheduleClause>(Clause); 1954 else if (Clause->getClauseKind() == OMPC_ordered) 1955 OC = cast<OMPOrderedClause>(Clause); 1956 else if (Clause->getClauseKind() == OMPC_linear) 1957 LCs.push_back(cast<OMPLinearClause>(Clause)); 1958 } 1959 bool ErrorFound = false; 1960 // OpenMP, 2.7.1 Loop Construct, Restrictions 1961 // The nonmonotonic modifier cannot be specified if an ordered clause is 1962 // specified. 1963 if (SC && 1964 (SC->getFirstScheduleModifier() == OMPC_SCHEDULE_MODIFIER_nonmonotonic || 1965 SC->getSecondScheduleModifier() == 1966 OMPC_SCHEDULE_MODIFIER_nonmonotonic) && 1967 OC) { 1968 Diag(SC->getFirstScheduleModifier() == OMPC_SCHEDULE_MODIFIER_nonmonotonic 1969 ? SC->getFirstScheduleModifierLoc() 1970 : SC->getSecondScheduleModifierLoc(), 1971 diag::err_omp_schedule_nonmonotonic_ordered) 1972 << SourceRange(OC->getLocStart(), OC->getLocEnd()); 1973 ErrorFound = true; 1974 } 1975 if (!LCs.empty() && OC && OC->getNumForLoops()) { 1976 for (auto *C : LCs) { 1977 Diag(C->getLocStart(), diag::err_omp_linear_ordered) 1978 << SourceRange(OC->getLocStart(), OC->getLocEnd()); 1979 } 1980 ErrorFound = true; 1981 } 1982 if (isOpenMPWorksharingDirective(DSAStack->getCurrentDirective()) && 1983 isOpenMPSimdDirective(DSAStack->getCurrentDirective()) && OC && 1984 OC->getNumForLoops()) { 1985 Diag(OC->getLocStart(), diag::err_omp_ordered_simd) 1986 << getOpenMPDirectiveName(DSAStack->getCurrentDirective()); 1987 ErrorFound = true; 1988 } 1989 if (ErrorFound) { 1990 ActOnCapturedRegionError(); 1991 return StmtError(); 1992 } 1993 return ActOnCapturedRegionEnd(S.get()); 1994 } 1995 1996 static bool CheckNestingOfRegions(Sema &SemaRef, DSAStackTy *Stack, 1997 OpenMPDirectiveKind CurrentRegion, 1998 const DeclarationNameInfo &CurrentName, 1999 OpenMPDirectiveKind CancelRegion, 2000 SourceLocation StartLoc) { 2001 // Allowed nesting of constructs 2002 // +------------------+-----------------+------------------------------------+ 2003 // | Parent directive | Child directive | Closely (!), No-Closely(+), Both(*)| 2004 // +------------------+-----------------+------------------------------------+ 2005 // | parallel | parallel | * | 2006 // | parallel | for | * | 2007 // | parallel | for simd | * | 2008 // | parallel | master | * | 2009 // | parallel | critical | * | 2010 // | parallel | simd | * | 2011 // | parallel | sections | * | 2012 // | parallel | section | + | 2013 // | parallel | single | * | 2014 // | parallel | parallel for | * | 2015 // | parallel |parallel for simd| * | 2016 // | parallel |parallel sections| * | 2017 // | parallel | task | * | 2018 // | parallel | taskyield | * | 2019 // | parallel | barrier | * | 2020 // | parallel | taskwait | * | 2021 // | parallel | taskgroup | * | 2022 // | parallel | flush | * | 2023 // | parallel | ordered | + | 2024 // | parallel | atomic | * | 2025 // | parallel | target | * | 2026 // | parallel | target parallel | * | 2027 // | parallel | target parallel | * | 2028 // | | for | | 2029 // | parallel | target enter | * | 2030 // | | data | | 2031 // | parallel | target exit | * | 2032 // | | data | | 2033 // | parallel | teams | + | 2034 // | parallel | cancellation | | 2035 // | | point | ! | 2036 // | parallel | cancel | ! | 2037 // | parallel | taskloop | * | 2038 // | parallel | taskloop simd | * | 2039 // | parallel | distribute | + | 2040 // | parallel | distribute | + | 2041 // | | parallel for | | 2042 // | parallel | distribute | + | 2043 // | |parallel for simd| | 2044 // +------------------+-----------------+------------------------------------+ 2045 // | for | parallel | * | 2046 // | for | for | + | 2047 // | for | for simd | + | 2048 // | for | master | + | 2049 // | for | critical | * | 2050 // | for | simd | * | 2051 // | for | sections | + | 2052 // | for | section | + | 2053 // | for | single | + | 2054 // | for | parallel for | * | 2055 // | for |parallel for simd| * | 2056 // | for |parallel sections| * | 2057 // | for | task | * | 2058 // | for | taskyield | * | 2059 // | for | barrier | + | 2060 // | for | taskwait | * | 2061 // | for | taskgroup | * | 2062 // | for | flush | * | 2063 // | for | ordered | * (if construct is ordered) | 2064 // | for | atomic | * | 2065 // | for | target | * | 2066 // | for | target parallel | * | 2067 // | for | target parallel | * | 2068 // | | for | | 2069 // | for | target enter | * | 2070 // | | data | | 2071 // | for | target exit | * | 2072 // | | data | | 2073 // | for | teams | + | 2074 // | for | cancellation | | 2075 // | | point | ! | 2076 // | for | cancel | ! | 2077 // | for | taskloop | * | 2078 // | for | taskloop simd | * | 2079 // | for | distribute | + | 2080 // | for | distribute | + | 2081 // | | parallel for | | 2082 // | for | distribute | + | 2083 // | |parallel for simd| | 2084 // +------------------+-----------------+------------------------------------+ 2085 // | master | parallel | * | 2086 // | master | for | + | 2087 // | master | for simd | + | 2088 // | master | master | * | 2089 // | master | critical | * | 2090 // | master | simd | * | 2091 // | master | sections | + | 2092 // | master | section | + | 2093 // | master | single | + | 2094 // | master | parallel for | * | 2095 // | master |parallel for simd| * | 2096 // | master |parallel sections| * | 2097 // | master | task | * | 2098 // | master | taskyield | * | 2099 // | master | barrier | + | 2100 // | master | taskwait | * | 2101 // | master | taskgroup | * | 2102 // | master | flush | * | 2103 // | master | ordered | + | 2104 // | master | atomic | * | 2105 // | master | target | * | 2106 // | master | target parallel | * | 2107 // | master | target parallel | * | 2108 // | | for | | 2109 // | master | target enter | * | 2110 // | | data | | 2111 // | master | target exit | * | 2112 // | | data | | 2113 // | master | teams | + | 2114 // | master | cancellation | | 2115 // | | point | | 2116 // | master | cancel | | 2117 // | master | taskloop | * | 2118 // | master | taskloop simd | * | 2119 // | master | distribute | + | 2120 // | master | distribute | + | 2121 // | | parallel for | | 2122 // | master | distribute | + | 2123 // | |parallel for simd| | 2124 // +------------------+-----------------+------------------------------------+ 2125 // | critical | parallel | * | 2126 // | critical | for | + | 2127 // | critical | for simd | + | 2128 // | critical | master | * | 2129 // | critical | critical | * (should have different names) | 2130 // | critical | simd | * | 2131 // | critical | sections | + | 2132 // | critical | section | + | 2133 // | critical | single | + | 2134 // | critical | parallel for | * | 2135 // | critical |parallel for simd| * | 2136 // | critical |parallel sections| * | 2137 // | critical | task | * | 2138 // | critical | taskyield | * | 2139 // | critical | barrier | + | 2140 // | critical | taskwait | * | 2141 // | critical | taskgroup | * | 2142 // | critical | ordered | + | 2143 // | critical | atomic | * | 2144 // | critical | target | * | 2145 // | critical | target parallel | * | 2146 // | critical | target parallel | * | 2147 // | | for | | 2148 // | critical | target enter | * | 2149 // | | data | | 2150 // | critical | target exit | * | 2151 // | | data | | 2152 // | critical | teams | + | 2153 // | critical | cancellation | | 2154 // | | point | | 2155 // | critical | cancel | | 2156 // | critical | taskloop | * | 2157 // | critical | taskloop simd | * | 2158 // | critical | distribute | + | 2159 // | critical | distribute | + | 2160 // | | parallel for | | 2161 // | critical | distribute | + | 2162 // | |parallel for simd| | 2163 // +------------------+-----------------+------------------------------------+ 2164 // | simd | parallel | | 2165 // | simd | for | | 2166 // | simd | for simd | | 2167 // | simd | master | | 2168 // | simd | critical | | 2169 // | simd | simd | * | 2170 // | simd | sections | | 2171 // | simd | section | | 2172 // | simd | single | | 2173 // | simd | parallel for | | 2174 // | simd |parallel for simd| | 2175 // | simd |parallel sections| | 2176 // | simd | task | | 2177 // | simd | taskyield | | 2178 // | simd | barrier | | 2179 // | simd | taskwait | | 2180 // | simd | taskgroup | | 2181 // | simd | flush | | 2182 // | simd | ordered | + (with simd clause) | 2183 // | simd | atomic | | 2184 // | simd | target | | 2185 // | simd | target parallel | | 2186 // | simd | target parallel | | 2187 // | | for | | 2188 // | simd | target enter | | 2189 // | | data | | 2190 // | simd | target exit | | 2191 // | | data | | 2192 // | simd | teams | | 2193 // | simd | cancellation | | 2194 // | | point | | 2195 // | simd | cancel | | 2196 // | simd | taskloop | | 2197 // | simd | taskloop simd | | 2198 // | simd | distribute | | 2199 // | simd | distribute | | 2200 // | | parallel for | | 2201 // | simd | distribute | | 2202 // | |parallel for simd| | 2203 // +------------------+-----------------+------------------------------------+ 2204 // | for simd | parallel | | 2205 // | for simd | for | | 2206 // | for simd | for simd | | 2207 // | for simd | master | | 2208 // | for simd | critical | | 2209 // | for simd | simd | * | 2210 // | for simd | sections | | 2211 // | for simd | section | | 2212 // | for simd | single | | 2213 // | for simd | parallel for | | 2214 // | for simd |parallel for simd| | 2215 // | for simd |parallel sections| | 2216 // | for simd | task | | 2217 // | for simd | taskyield | | 2218 // | for simd | barrier | | 2219 // | for simd | taskwait | | 2220 // | for simd | taskgroup | | 2221 // | for simd | flush | | 2222 // | for simd | ordered | + (with simd clause) | 2223 // | for simd | atomic | | 2224 // | for simd | target | | 2225 // | for simd | target parallel | | 2226 // | for simd | target parallel | | 2227 // | | for | | 2228 // | for simd | target enter | | 2229 // | | data | | 2230 // | for simd | target exit | | 2231 // | | data | | 2232 // | for simd | teams | | 2233 // | for simd | cancellation | | 2234 // | | point | | 2235 // | for simd | cancel | | 2236 // | for simd | taskloop | | 2237 // | for simd | taskloop simd | | 2238 // | for simd | distribute | | 2239 // | for simd | distribute | | 2240 // | | parallel for | | 2241 // | for simd | distribute | | 2242 // | |parallel for simd| | 2243 // +------------------+-----------------+------------------------------------+ 2244 // | parallel for simd| parallel | | 2245 // | parallel for simd| for | | 2246 // | parallel for simd| for simd | | 2247 // | parallel for simd| master | | 2248 // | parallel for simd| critical | | 2249 // | parallel for simd| simd | * | 2250 // | parallel for simd| sections | | 2251 // | parallel for simd| section | | 2252 // | parallel for simd| single | | 2253 // | parallel for simd| parallel for | | 2254 // | parallel for simd|parallel for simd| | 2255 // | parallel for simd|parallel sections| | 2256 // | parallel for simd| task | | 2257 // | parallel for simd| taskyield | | 2258 // | parallel for simd| barrier | | 2259 // | parallel for simd| taskwait | | 2260 // | parallel for simd| taskgroup | | 2261 // | parallel for simd| flush | | 2262 // | parallel for simd| ordered | + (with simd clause) | 2263 // | parallel for simd| atomic | | 2264 // | parallel for simd| target | | 2265 // | parallel for simd| target parallel | | 2266 // | parallel for simd| target parallel | | 2267 // | | for | | 2268 // | parallel for simd| target enter | | 2269 // | | data | | 2270 // | parallel for simd| target exit | | 2271 // | | data | | 2272 // | parallel for simd| teams | | 2273 // | parallel for simd| cancellation | | 2274 // | | point | | 2275 // | parallel for simd| cancel | | 2276 // | parallel for simd| taskloop | | 2277 // | parallel for simd| taskloop simd | | 2278 // | parallel for simd| distribute | | 2279 // | parallel for simd| distribute | | 2280 // | | parallel for | | 2281 // | parallel for simd| distribute | | 2282 // | |parallel for simd| | 2283 // +------------------+-----------------+------------------------------------+ 2284 // | sections | parallel | * | 2285 // | sections | for | + | 2286 // | sections | for simd | + | 2287 // | sections | master | + | 2288 // | sections | critical | * | 2289 // | sections | simd | * | 2290 // | sections | sections | + | 2291 // | sections | section | * | 2292 // | sections | single | + | 2293 // | sections | parallel for | * | 2294 // | sections |parallel for simd| * | 2295 // | sections |parallel sections| * | 2296 // | sections | task | * | 2297 // | sections | taskyield | * | 2298 // | sections | barrier | + | 2299 // | sections | taskwait | * | 2300 // | sections | taskgroup | * | 2301 // | sections | flush | * | 2302 // | sections | ordered | + | 2303 // | sections | atomic | * | 2304 // | sections | target | * | 2305 // | sections | target parallel | * | 2306 // | sections | target parallel | * | 2307 // | | for | | 2308 // | sections | target enter | * | 2309 // | | data | | 2310 // | sections | target exit | * | 2311 // | | data | | 2312 // | sections | teams | + | 2313 // | sections | cancellation | | 2314 // | | point | ! | 2315 // | sections | cancel | ! | 2316 // | sections | taskloop | * | 2317 // | sections | taskloop simd | * | 2318 // | sections | distribute | + | 2319 // | sections | distribute | + | 2320 // | | parallel for | | 2321 // | sections | distribute | + | 2322 // | |parallel for simd| | 2323 // +------------------+-----------------+------------------------------------+ 2324 // | section | parallel | * | 2325 // | section | for | + | 2326 // | section | for simd | + | 2327 // | section | master | + | 2328 // | section | critical | * | 2329 // | section | simd | * | 2330 // | section | sections | + | 2331 // | section | section | + | 2332 // | section | single | + | 2333 // | section | parallel for | * | 2334 // | section |parallel for simd| * | 2335 // | section |parallel sections| * | 2336 // | section | task | * | 2337 // | section | taskyield | * | 2338 // | section | barrier | + | 2339 // | section | taskwait | * | 2340 // | section | taskgroup | * | 2341 // | section | flush | * | 2342 // | section | ordered | + | 2343 // | section | atomic | * | 2344 // | section | target | * | 2345 // | section | target parallel | * | 2346 // | section | target parallel | * | 2347 // | | for | | 2348 // | section | target enter | * | 2349 // | | data | | 2350 // | section | target exit | * | 2351 // | | data | | 2352 // | section | teams | + | 2353 // | section | cancellation | | 2354 // | | point | ! | 2355 // | section | cancel | ! | 2356 // | section | taskloop | * | 2357 // | section | taskloop simd | * | 2358 // | section | distribute | + | 2359 // | section | distribute | + | 2360 // | | parallel for | | 2361 // | section | distribute | + | 2362 // | |parallel for simd| | 2363 // +------------------+-----------------+------------------------------------+ 2364 // | single | parallel | * | 2365 // | single | for | + | 2366 // | single | for simd | + | 2367 // | single | master | + | 2368 // | single | critical | * | 2369 // | single | simd | * | 2370 // | single | sections | + | 2371 // | single | section | + | 2372 // | single | single | + | 2373 // | single | parallel for | * | 2374 // | single |parallel for simd| * | 2375 // | single |parallel sections| * | 2376 // | single | task | * | 2377 // | single | taskyield | * | 2378 // | single | barrier | + | 2379 // | single | taskwait | * | 2380 // | single | taskgroup | * | 2381 // | single | flush | * | 2382 // | single | ordered | + | 2383 // | single | atomic | * | 2384 // | single | target | * | 2385 // | single | target parallel | * | 2386 // | single | target parallel | * | 2387 // | | for | | 2388 // | single | target enter | * | 2389 // | | data | | 2390 // | single | target exit | * | 2391 // | | data | | 2392 // | single | teams | + | 2393 // | single | cancellation | | 2394 // | | point | | 2395 // | single | cancel | | 2396 // | single | taskloop | * | 2397 // | single | taskloop simd | * | 2398 // | single | distribute | + | 2399 // | single | distribute | + | 2400 // | | parallel for | | 2401 // | single | distribute | + | 2402 // | |parallel for simd| | 2403 // +------------------+-----------------+------------------------------------+ 2404 // | parallel for | parallel | * | 2405 // | parallel for | for | + | 2406 // | parallel for | for simd | + | 2407 // | parallel for | master | + | 2408 // | parallel for | critical | * | 2409 // | parallel for | simd | * | 2410 // | parallel for | sections | + | 2411 // | parallel for | section | + | 2412 // | parallel for | single | + | 2413 // | parallel for | parallel for | * | 2414 // | parallel for |parallel for simd| * | 2415 // | parallel for |parallel sections| * | 2416 // | parallel for | task | * | 2417 // | parallel for | taskyield | * | 2418 // | parallel for | barrier | + | 2419 // | parallel for | taskwait | * | 2420 // | parallel for | taskgroup | * | 2421 // | parallel for | flush | * | 2422 // | parallel for | ordered | * (if construct is ordered) | 2423 // | parallel for | atomic | * | 2424 // | parallel for | target | * | 2425 // | parallel for | target parallel | * | 2426 // | parallel for | target parallel | * | 2427 // | | for | | 2428 // | parallel for | target enter | * | 2429 // | | data | | 2430 // | parallel for | target exit | * | 2431 // | | data | | 2432 // | parallel for | teams | + | 2433 // | parallel for | cancellation | | 2434 // | | point | ! | 2435 // | parallel for | cancel | ! | 2436 // | parallel for | taskloop | * | 2437 // | parallel for | taskloop simd | * | 2438 // | parallel for | distribute | + | 2439 // | parallel for | distribute | + | 2440 // | | parallel for | | 2441 // | parallel for | distribute | + | 2442 // | |parallel for simd| | 2443 // +------------------+-----------------+------------------------------------+ 2444 // | parallel sections| parallel | * | 2445 // | parallel sections| for | + | 2446 // | parallel sections| for simd | + | 2447 // | parallel sections| master | + | 2448 // | parallel sections| critical | + | 2449 // | parallel sections| simd | * | 2450 // | parallel sections| sections | + | 2451 // | parallel sections| section | * | 2452 // | parallel sections| single | + | 2453 // | parallel sections| parallel for | * | 2454 // | parallel sections|parallel for simd| * | 2455 // | parallel sections|parallel sections| * | 2456 // | parallel sections| task | * | 2457 // | parallel sections| taskyield | * | 2458 // | parallel sections| barrier | + | 2459 // | parallel sections| taskwait | * | 2460 // | parallel sections| taskgroup | * | 2461 // | parallel sections| flush | * | 2462 // | parallel sections| ordered | + | 2463 // | parallel sections| atomic | * | 2464 // | parallel sections| target | * | 2465 // | parallel sections| target parallel | * | 2466 // | parallel sections| target parallel | * | 2467 // | | for | | 2468 // | parallel sections| target enter | * | 2469 // | | data | | 2470 // | parallel sections| target exit | * | 2471 // | | data | | 2472 // | parallel sections| teams | + | 2473 // | parallel sections| cancellation | | 2474 // | | point | ! | 2475 // | parallel sections| cancel | ! | 2476 // | parallel sections| taskloop | * | 2477 // | parallel sections| taskloop simd | * | 2478 // | parallel sections| distribute | + | 2479 // | parallel sections| distribute | + | 2480 // | | parallel for | | 2481 // | parallel sections| distribute | + | 2482 // | |parallel for simd| | 2483 // +------------------+-----------------+------------------------------------+ 2484 // | task | parallel | * | 2485 // | task | for | + | 2486 // | task | for simd | + | 2487 // | task | master | + | 2488 // | task | critical | * | 2489 // | task | simd | * | 2490 // | task | sections | + | 2491 // | task | section | + | 2492 // | task | single | + | 2493 // | task | parallel for | * | 2494 // | task |parallel for simd| * | 2495 // | task |parallel sections| * | 2496 // | task | task | * | 2497 // | task | taskyield | * | 2498 // | task | barrier | + | 2499 // | task | taskwait | * | 2500 // | task | taskgroup | * | 2501 // | task | flush | * | 2502 // | task | ordered | + | 2503 // | task | atomic | * | 2504 // | task | target | * | 2505 // | task | target parallel | * | 2506 // | task | target parallel | * | 2507 // | | for | | 2508 // | task | target enter | * | 2509 // | | data | | 2510 // | task | target exit | * | 2511 // | | data | | 2512 // | task | teams | + | 2513 // | task | cancellation | | 2514 // | | point | ! | 2515 // | task | cancel | ! | 2516 // | task | taskloop | * | 2517 // | task | taskloop simd | * | 2518 // | task | distribute | + | 2519 // | task | distribute | + | 2520 // | | parallel for | | 2521 // | task | distribute | + | 2522 // | |parallel for simd| | 2523 // +------------------+-----------------+------------------------------------+ 2524 // | ordered | parallel | * | 2525 // | ordered | for | + | 2526 // | ordered | for simd | + | 2527 // | ordered | master | * | 2528 // | ordered | critical | * | 2529 // | ordered | simd | * | 2530 // | ordered | sections | + | 2531 // | ordered | section | + | 2532 // | ordered | single | + | 2533 // | ordered | parallel for | * | 2534 // | ordered |parallel for simd| * | 2535 // | ordered |parallel sections| * | 2536 // | ordered | task | * | 2537 // | ordered | taskyield | * | 2538 // | ordered | barrier | + | 2539 // | ordered | taskwait | * | 2540 // | ordered | taskgroup | * | 2541 // | ordered | flush | * | 2542 // | ordered | ordered | + | 2543 // | ordered | atomic | * | 2544 // | ordered | target | * | 2545 // | ordered | target parallel | * | 2546 // | ordered | target parallel | * | 2547 // | | for | | 2548 // | ordered | target enter | * | 2549 // | | data | | 2550 // | ordered | target exit | * | 2551 // | | data | | 2552 // | ordered | teams | + | 2553 // | ordered | cancellation | | 2554 // | | point | | 2555 // | ordered | cancel | | 2556 // | ordered | taskloop | * | 2557 // | ordered | taskloop simd | * | 2558 // | ordered | distribute | + | 2559 // | ordered | distribute | + | 2560 // | | parallel for | | 2561 // | ordered | distribute | + | 2562 // | |parallel for simd| | 2563 // +------------------+-----------------+------------------------------------+ 2564 // | atomic | parallel | | 2565 // | atomic | for | | 2566 // | atomic | for simd | | 2567 // | atomic | master | | 2568 // | atomic | critical | | 2569 // | atomic | simd | | 2570 // | atomic | sections | | 2571 // | atomic | section | | 2572 // | atomic | single | | 2573 // | atomic | parallel for | | 2574 // | atomic |parallel for simd| | 2575 // | atomic |parallel sections| | 2576 // | atomic | task | | 2577 // | atomic | taskyield | | 2578 // | atomic | barrier | | 2579 // | atomic | taskwait | | 2580 // | atomic | taskgroup | | 2581 // | atomic | flush | | 2582 // | atomic | ordered | | 2583 // | atomic | atomic | | 2584 // | atomic | target | | 2585 // | atomic | target parallel | | 2586 // | atomic | target parallel | | 2587 // | | for | | 2588 // | atomic | target enter | | 2589 // | | data | | 2590 // | atomic | target exit | | 2591 // | | data | | 2592 // | atomic | teams | | 2593 // | atomic | cancellation | | 2594 // | | point | | 2595 // | atomic | cancel | | 2596 // | atomic | taskloop | | 2597 // | atomic | taskloop simd | | 2598 // | atomic | distribute | | 2599 // | atomic | distribute | | 2600 // | | parallel for | | 2601 // | atomic | distribute | | 2602 // | |parallel for simd| | 2603 // +------------------+-----------------+------------------------------------+ 2604 // | target | parallel | * | 2605 // | target | for | * | 2606 // | target | for simd | * | 2607 // | target | master | * | 2608 // | target | critical | * | 2609 // | target | simd | * | 2610 // | target | sections | * | 2611 // | target | section | * | 2612 // | target | single | * | 2613 // | target | parallel for | * | 2614 // | target |parallel for simd| * | 2615 // | target |parallel sections| * | 2616 // | target | task | * | 2617 // | target | taskyield | * | 2618 // | target | barrier | * | 2619 // | target | taskwait | * | 2620 // | target | taskgroup | * | 2621 // | target | flush | * | 2622 // | target | ordered | * | 2623 // | target | atomic | * | 2624 // | target | target | | 2625 // | target | target parallel | | 2626 // | target | target parallel | | 2627 // | | for | | 2628 // | target | target enter | | 2629 // | | data | | 2630 // | target | target exit | | 2631 // | | data | | 2632 // | target | teams | * | 2633 // | target | cancellation | | 2634 // | | point | | 2635 // | target | cancel | | 2636 // | target | taskloop | * | 2637 // | target | taskloop simd | * | 2638 // | target | distribute | + | 2639 // | target | distribute | + | 2640 // | | parallel for | | 2641 // | target | distribute | + | 2642 // | |parallel for simd| | 2643 // +------------------+-----------------+------------------------------------+ 2644 // | target parallel | parallel | * | 2645 // | target parallel | for | * | 2646 // | target parallel | for simd | * | 2647 // | target parallel | master | * | 2648 // | target parallel | critical | * | 2649 // | target parallel | simd | * | 2650 // | target parallel | sections | * | 2651 // | target parallel | section | * | 2652 // | target parallel | single | * | 2653 // | target parallel | parallel for | * | 2654 // | target parallel |parallel for simd| * | 2655 // | target parallel |parallel sections| * | 2656 // | target parallel | task | * | 2657 // | target parallel | taskyield | * | 2658 // | target parallel | barrier | * | 2659 // | target parallel | taskwait | * | 2660 // | target parallel | taskgroup | * | 2661 // | target parallel | flush | * | 2662 // | target parallel | ordered | * | 2663 // | target parallel | atomic | * | 2664 // | target parallel | target | | 2665 // | target parallel | target parallel | | 2666 // | target parallel | target parallel | | 2667 // | | for | | 2668 // | target parallel | target enter | | 2669 // | | data | | 2670 // | target parallel | target exit | | 2671 // | | data | | 2672 // | target parallel | teams | | 2673 // | target parallel | cancellation | | 2674 // | | point | ! | 2675 // | target parallel | cancel | ! | 2676 // | target parallel | taskloop | * | 2677 // | target parallel | taskloop simd | * | 2678 // | target parallel | distribute | | 2679 // | target parallel | distribute | | 2680 // | | parallel for | | 2681 // | target parallel | distribute | | 2682 // | |parallel for simd| | 2683 // +------------------+-----------------+------------------------------------+ 2684 // | target parallel | parallel | * | 2685 // | for | | | 2686 // | target parallel | for | * | 2687 // | for | | | 2688 // | target parallel | for simd | * | 2689 // | for | | | 2690 // | target parallel | master | * | 2691 // | for | | | 2692 // | target parallel | critical | * | 2693 // | for | | | 2694 // | target parallel | simd | * | 2695 // | for | | | 2696 // | target parallel | sections | * | 2697 // | for | | | 2698 // | target parallel | section | * | 2699 // | for | | | 2700 // | target parallel | single | * | 2701 // | for | | | 2702 // | target parallel | parallel for | * | 2703 // | for | | | 2704 // | target parallel |parallel for simd| * | 2705 // | for | | | 2706 // | target parallel |parallel sections| * | 2707 // | for | | | 2708 // | target parallel | task | * | 2709 // | for | | | 2710 // | target parallel | taskyield | * | 2711 // | for | | | 2712 // | target parallel | barrier | * | 2713 // | for | | | 2714 // | target parallel | taskwait | * | 2715 // | for | | | 2716 // | target parallel | taskgroup | * | 2717 // | for | | | 2718 // | target parallel | flush | * | 2719 // | for | | | 2720 // | target parallel | ordered | * | 2721 // | for | | | 2722 // | target parallel | atomic | * | 2723 // | for | | | 2724 // | target parallel | target | | 2725 // | for | | | 2726 // | target parallel | target parallel | | 2727 // | for | | | 2728 // | target parallel | target parallel | | 2729 // | for | for | | 2730 // | target parallel | target enter | | 2731 // | for | data | | 2732 // | target parallel | target exit | | 2733 // | for | data | | 2734 // | target parallel | teams | | 2735 // | for | | | 2736 // | target parallel | cancellation | | 2737 // | for | point | ! | 2738 // | target parallel | cancel | ! | 2739 // | for | | | 2740 // | target parallel | taskloop | * | 2741 // | for | | | 2742 // | target parallel | taskloop simd | * | 2743 // | for | | | 2744 // | target parallel | distribute | | 2745 // | for | | | 2746 // | parallel | distribute | | 2747 // | for | parallel for | | 2748 // | parallel | distribute | | 2749 // | for |parallel for simd| | 2750 // +------------------+-----------------+------------------------------------+ 2751 // | teams | parallel | * | 2752 // | teams | for | + | 2753 // | teams | for simd | + | 2754 // | teams | master | + | 2755 // | teams | critical | + | 2756 // | teams | simd | + | 2757 // | teams | sections | + | 2758 // | teams | section | + | 2759 // | teams | single | + | 2760 // | teams | parallel for | * | 2761 // | teams |parallel for simd| * | 2762 // | teams |parallel sections| * | 2763 // | teams | task | + | 2764 // | teams | taskyield | + | 2765 // | teams | barrier | + | 2766 // | teams | taskwait | + | 2767 // | teams | taskgroup | + | 2768 // | teams | flush | + | 2769 // | teams | ordered | + | 2770 // | teams | atomic | + | 2771 // | teams | target | + | 2772 // | teams | target parallel | + | 2773 // | teams | target parallel | + | 2774 // | | for | | 2775 // | teams | target enter | + | 2776 // | | data | | 2777 // | teams | target exit | + | 2778 // | | data | | 2779 // | teams | teams | + | 2780 // | teams | cancellation | | 2781 // | | point | | 2782 // | teams | cancel | | 2783 // | teams | taskloop | + | 2784 // | teams | taskloop simd | + | 2785 // | teams | distribute | ! | 2786 // | teams | distribute | ! | 2787 // | | parallel for | | 2788 // | teams | distribute | ! | 2789 // | |parallel for simd| | 2790 // +------------------+-----------------+------------------------------------+ 2791 // | taskloop | parallel | * | 2792 // | taskloop | for | + | 2793 // | taskloop | for simd | + | 2794 // | taskloop | master | + | 2795 // | taskloop | critical | * | 2796 // | taskloop | simd | * | 2797 // | taskloop | sections | + | 2798 // | taskloop | section | + | 2799 // | taskloop | single | + | 2800 // | taskloop | parallel for | * | 2801 // | taskloop |parallel for simd| * | 2802 // | taskloop |parallel sections| * | 2803 // | taskloop | task | * | 2804 // | taskloop | taskyield | * | 2805 // | taskloop | barrier | + | 2806 // | taskloop | taskwait | * | 2807 // | taskloop | taskgroup | * | 2808 // | taskloop | flush | * | 2809 // | taskloop | ordered | + | 2810 // | taskloop | atomic | * | 2811 // | taskloop | target | * | 2812 // | taskloop | target parallel | * | 2813 // | taskloop | target parallel | * | 2814 // | | for | | 2815 // | taskloop | target enter | * | 2816 // | | data | | 2817 // | taskloop | target exit | * | 2818 // | | data | | 2819 // | taskloop | teams | + | 2820 // | taskloop | cancellation | | 2821 // | | point | | 2822 // | taskloop | cancel | | 2823 // | taskloop | taskloop | * | 2824 // | taskloop | distribute | + | 2825 // | taskloop | distribute | + | 2826 // | | parallel for | | 2827 // | taskloop | distribute | + | 2828 // | |parallel for simd| | 2829 // +------------------+-----------------+------------------------------------+ 2830 // | taskloop simd | parallel | | 2831 // | taskloop simd | for | | 2832 // | taskloop simd | for simd | | 2833 // | taskloop simd | master | | 2834 // | taskloop simd | critical | | 2835 // | taskloop simd | simd | * | 2836 // | taskloop simd | sections | | 2837 // | taskloop simd | section | | 2838 // | taskloop simd | single | | 2839 // | taskloop simd | parallel for | | 2840 // | taskloop simd |parallel for simd| | 2841 // | taskloop simd |parallel sections| | 2842 // | taskloop simd | task | | 2843 // | taskloop simd | taskyield | | 2844 // | taskloop simd | barrier | | 2845 // | taskloop simd | taskwait | | 2846 // | taskloop simd | taskgroup | | 2847 // | taskloop simd | flush | | 2848 // | taskloop simd | ordered | + (with simd clause) | 2849 // | taskloop simd | atomic | | 2850 // | taskloop simd | target | | 2851 // | taskloop simd | target parallel | | 2852 // | taskloop simd | target parallel | | 2853 // | | for | | 2854 // | taskloop simd | target enter | | 2855 // | | data | | 2856 // | taskloop simd | target exit | | 2857 // | | data | | 2858 // | taskloop simd | teams | | 2859 // | taskloop simd | cancellation | | 2860 // | | point | | 2861 // | taskloop simd | cancel | | 2862 // | taskloop simd | taskloop | | 2863 // | taskloop simd | taskloop simd | | 2864 // | taskloop simd | distribute | | 2865 // | taskloop simd | distribute | | 2866 // | | parallel for | | 2867 // | taskloop simd | distribute | | 2868 // | |parallel for simd| | 2869 // +------------------+-----------------+------------------------------------+ 2870 // | distribute | parallel | * | 2871 // | distribute | for | * | 2872 // | distribute | for simd | * | 2873 // | distribute | master | * | 2874 // | distribute | critical | * | 2875 // | distribute | simd | * | 2876 // | distribute | sections | * | 2877 // | distribute | section | * | 2878 // | distribute | single | * | 2879 // | distribute | parallel for | * | 2880 // | distribute |parallel for simd| * | 2881 // | distribute |parallel sections| * | 2882 // | distribute | task | * | 2883 // | distribute | taskyield | * | 2884 // | distribute | barrier | * | 2885 // | distribute | taskwait | * | 2886 // | distribute | taskgroup | * | 2887 // | distribute | flush | * | 2888 // | distribute | ordered | + | 2889 // | distribute | atomic | * | 2890 // | distribute | target | | 2891 // | distribute | target parallel | | 2892 // | distribute | target parallel | | 2893 // | | for | | 2894 // | distribute | target enter | | 2895 // | | data | | 2896 // | distribute | target exit | | 2897 // | | data | | 2898 // | distribute | teams | | 2899 // | distribute | cancellation | + | 2900 // | | point | | 2901 // | distribute | cancel | + | 2902 // | distribute | taskloop | * | 2903 // | distribute | taskloop simd | * | 2904 // | distribute | distribute | | 2905 // | distribute | distribute | | 2906 // | | parallel for | | 2907 // | distribute | distribute | | 2908 // | |parallel for simd| | 2909 // +------------------+-----------------+------------------------------------+ 2910 // | distribute | parallel | * | 2911 // | parallel for | | | 2912 // | distribute | for | * | 2913 // | parallel for | | | 2914 // | distribute | for simd | * | 2915 // | parallel for | | | 2916 // | distribute | master | * | 2917 // | parallel for | | | 2918 // | distribute | critical | * | 2919 // | parallel for | | | 2920 // | distribute | simd | * | 2921 // | parallel for | | | 2922 // | distribute | sections | * | 2923 // | parallel for | | | 2924 // | distribute | section | * | 2925 // | parallel for | | | 2926 // | distribute | single | * | 2927 // | parallel for | | | 2928 // | distribute | parallel for | * | 2929 // | parallel for | | | 2930 // | distribute |parallel for simd| * | 2931 // | parallel for | | | 2932 // | distribute |parallel sections| * | 2933 // | parallel for | | | 2934 // | distribute | task | * | 2935 // | parallel for | | | 2936 // | parallel for | | | 2937 // | distribute | taskyield | * | 2938 // | parallel for | | | 2939 // | distribute | barrier | * | 2940 // | parallel for | | | 2941 // | distribute | taskwait | * | 2942 // | parallel for | | | 2943 // | distribute | taskgroup | * | 2944 // | parallel for | | | 2945 // | distribute | flush | * | 2946 // | parallel for | | | 2947 // | distribute | ordered | + | 2948 // | parallel for | | | 2949 // | distribute | atomic | * | 2950 // | parallel for | | | 2951 // | distribute | target | | 2952 // | parallel for | | | 2953 // | distribute | target parallel | | 2954 // | parallel for | | | 2955 // | distribute | target parallel | | 2956 // | parallel for | for | | 2957 // | distribute | target enter | | 2958 // | parallel for | data | | 2959 // | distribute | target exit | | 2960 // | parallel for | data | | 2961 // | distribute | teams | | 2962 // | parallel for | | | 2963 // | distribute | cancellation | + | 2964 // | parallel for | point | | 2965 // | distribute | cancel | + | 2966 // | parallel for | | | 2967 // | distribute | taskloop | * | 2968 // | parallel for | | | 2969 // | distribute | taskloop simd | * | 2970 // | parallel for | | | 2971 // | distribute | distribute | | 2972 // | parallel for | | | 2973 // | distribute | distribute | | 2974 // | parallel for | parallel for | | 2975 // | distribute | distribute | | 2976 // | parallel for |parallel for simd| | 2977 // +------------------+-----------------+------------------------------------+ 2978 // | distribute | parallel | * | 2979 // | parallel for simd| | | 2980 // | distribute | for | * | 2981 // | parallel for simd| | | 2982 // | distribute | for simd | * | 2983 // | parallel for simd| | | 2984 // | distribute | master | * | 2985 // | parallel for simd| | | 2986 // | distribute | critical | * | 2987 // | parallel for simd| | | 2988 // | distribute | simd | * | 2989 // | parallel for simd| | | 2990 // | distribute | sections | * | 2991 // | parallel for simd| | | 2992 // | distribute | section | * | 2993 // | parallel for simd| | | 2994 // | distribute | single | * | 2995 // | parallel for simd| | | 2996 // | distribute | parallel for | * | 2997 // | parallel for simd| | | 2998 // | distribute |parallel for simd| * | 2999 // | parallel for simd| | | 3000 // | distribute |parallel sections| * | 3001 // | parallel for simd| | | 3002 // | distribute | task | * | 3003 // | parallel for simd| | | 3004 // | distribute | taskyield | * | 3005 // | parallel for simd| | | 3006 // | distribute | barrier | * | 3007 // | parallel for simd| | | 3008 // | distribute | taskwait | * | 3009 // | parallel for simd| | | 3010 // | distribute | taskgroup | * | 3011 // | parallel for simd| | | 3012 // | distribute | flush | * | 3013 // | parallel for simd| | | 3014 // | distribute | ordered | + | 3015 // | parallel for simd| | | 3016 // | distribute | atomic | * | 3017 // | parallel for simd| | | 3018 // | distribute | target | | 3019 // | parallel for simd| | | 3020 // | distribute | target parallel | | 3021 // | parallel for simd| | | 3022 // | distribute | target parallel | | 3023 // | parallel for simd| for | | 3024 // | distribute | target enter | | 3025 // | parallel for simd| data | | 3026 // | distribute | target exit | | 3027 // | parallel for simd| data | | 3028 // | distribute | teams | | 3029 // | parallel for simd| | | 3030 // | distribute | cancellation | + | 3031 // | parallel for simd| point | | 3032 // | distribute | cancel | + | 3033 // | parallel for simd| | | 3034 // | distribute | taskloop | * | 3035 // | parallel for simd| | | 3036 // | distribute | taskloop simd | * | 3037 // | parallel for simd| | | 3038 // | distribute | distribute | | 3039 // | parallel for simd| | | 3040 // | distribute | distribute | * | 3041 // | parallel for simd| parallel for | | 3042 // | distribute | distribute | * | 3043 // | parallel for simd|parallel for simd| | 3044 // +------------------+-----------------+------------------------------------+ 3045 if (Stack->getCurScope()) { 3046 auto ParentRegion = Stack->getParentDirective(); 3047 auto OffendingRegion = ParentRegion; 3048 bool NestingProhibited = false; 3049 bool CloseNesting = true; 3050 enum { 3051 NoRecommend, 3052 ShouldBeInParallelRegion, 3053 ShouldBeInOrderedRegion, 3054 ShouldBeInTargetRegion, 3055 ShouldBeInTeamsRegion 3056 } Recommend = NoRecommend; 3057 if (isOpenMPSimdDirective(ParentRegion) && CurrentRegion != OMPD_ordered) { 3058 // OpenMP [2.16, Nesting of Regions] 3059 // OpenMP constructs may not be nested inside a simd region. 3060 // OpenMP [2.8.1,simd Construct, Restrictions] 3061 // An ordered construct with the simd clause is the only OpenMP 3062 // construct that can appear in the simd region. 3063 // Allowing a SIMD consruct nested in another SIMD construct is an 3064 // extension. The OpenMP 4.5 spec does not allow it. Issue a warning 3065 // message. 3066 SemaRef.Diag(StartLoc, (CurrentRegion != OMPD_simd) 3067 ? diag::err_omp_prohibited_region_simd 3068 : diag::warn_omp_nesting_simd); 3069 return CurrentRegion != OMPD_simd; 3070 } 3071 if (ParentRegion == OMPD_atomic) { 3072 // OpenMP [2.16, Nesting of Regions] 3073 // OpenMP constructs may not be nested inside an atomic region. 3074 SemaRef.Diag(StartLoc, diag::err_omp_prohibited_region_atomic); 3075 return true; 3076 } 3077 if (CurrentRegion == OMPD_section) { 3078 // OpenMP [2.7.2, sections Construct, Restrictions] 3079 // Orphaned section directives are prohibited. That is, the section 3080 // directives must appear within the sections construct and must not be 3081 // encountered elsewhere in the sections region. 3082 if (ParentRegion != OMPD_sections && 3083 ParentRegion != OMPD_parallel_sections) { 3084 SemaRef.Diag(StartLoc, diag::err_omp_orphaned_section_directive) 3085 << (ParentRegion != OMPD_unknown) 3086 << getOpenMPDirectiveName(ParentRegion); 3087 return true; 3088 } 3089 return false; 3090 } 3091 // Allow some constructs to be orphaned (they could be used in functions, 3092 // called from OpenMP regions with the required preconditions). 3093 if (ParentRegion == OMPD_unknown) 3094 return false; 3095 if (CurrentRegion == OMPD_cancellation_point || 3096 CurrentRegion == OMPD_cancel) { 3097 // OpenMP [2.16, Nesting of Regions] 3098 // A cancellation point construct for which construct-type-clause is 3099 // taskgroup must be nested inside a task construct. A cancellation 3100 // point construct for which construct-type-clause is not taskgroup must 3101 // be closely nested inside an OpenMP construct that matches the type 3102 // specified in construct-type-clause. 3103 // A cancel construct for which construct-type-clause is taskgroup must be 3104 // nested inside a task construct. A cancel construct for which 3105 // construct-type-clause is not taskgroup must be closely nested inside an 3106 // OpenMP construct that matches the type specified in 3107 // construct-type-clause. 3108 NestingProhibited = 3109 !((CancelRegion == OMPD_parallel && 3110 (ParentRegion == OMPD_parallel || 3111 ParentRegion == OMPD_target_parallel)) || 3112 (CancelRegion == OMPD_for && 3113 (ParentRegion == OMPD_for || ParentRegion == OMPD_parallel_for || 3114 ParentRegion == OMPD_target_parallel_for)) || 3115 (CancelRegion == OMPD_taskgroup && ParentRegion == OMPD_task) || 3116 (CancelRegion == OMPD_sections && 3117 (ParentRegion == OMPD_section || ParentRegion == OMPD_sections || 3118 ParentRegion == OMPD_parallel_sections))); 3119 } else if (CurrentRegion == OMPD_master) { 3120 // OpenMP [2.16, Nesting of Regions] 3121 // A master region may not be closely nested inside a worksharing, 3122 // atomic, or explicit task region. 3123 NestingProhibited = isOpenMPWorksharingDirective(ParentRegion) || 3124 isOpenMPTaskingDirective(ParentRegion); 3125 } else if (CurrentRegion == OMPD_critical && CurrentName.getName()) { 3126 // OpenMP [2.16, Nesting of Regions] 3127 // A critical region may not be nested (closely or otherwise) inside a 3128 // critical region with the same name. Note that this restriction is not 3129 // sufficient to prevent deadlock. 3130 SourceLocation PreviousCriticalLoc; 3131 bool DeadLock = 3132 Stack->hasDirective([CurrentName, &PreviousCriticalLoc]( 3133 OpenMPDirectiveKind K, 3134 const DeclarationNameInfo &DNI, 3135 SourceLocation Loc) 3136 ->bool { 3137 if (K == OMPD_critical && 3138 DNI.getName() == CurrentName.getName()) { 3139 PreviousCriticalLoc = Loc; 3140 return true; 3141 } else 3142 return false; 3143 }, 3144 false /* skip top directive */); 3145 if (DeadLock) { 3146 SemaRef.Diag(StartLoc, 3147 diag::err_omp_prohibited_region_critical_same_name) 3148 << CurrentName.getName(); 3149 if (PreviousCriticalLoc.isValid()) 3150 SemaRef.Diag(PreviousCriticalLoc, 3151 diag::note_omp_previous_critical_region); 3152 return true; 3153 } 3154 } else if (CurrentRegion == OMPD_barrier) { 3155 // OpenMP [2.16, Nesting of Regions] 3156 // A barrier region may not be closely nested inside a worksharing, 3157 // explicit task, critical, ordered, atomic, or master region. 3158 NestingProhibited = isOpenMPWorksharingDirective(ParentRegion) || 3159 isOpenMPTaskingDirective(ParentRegion) || 3160 ParentRegion == OMPD_master || 3161 ParentRegion == OMPD_critical || 3162 ParentRegion == OMPD_ordered; 3163 } else if (isOpenMPWorksharingDirective(CurrentRegion) && 3164 !isOpenMPParallelDirective(CurrentRegion)) { 3165 // OpenMP [2.16, Nesting of Regions] 3166 // A worksharing region may not be closely nested inside a worksharing, 3167 // explicit task, critical, ordered, atomic, or master region. 3168 NestingProhibited = isOpenMPWorksharingDirective(ParentRegion) || 3169 isOpenMPTaskingDirective(ParentRegion) || 3170 ParentRegion == OMPD_master || 3171 ParentRegion == OMPD_critical || 3172 ParentRegion == OMPD_ordered; 3173 Recommend = ShouldBeInParallelRegion; 3174 } else if (CurrentRegion == OMPD_ordered) { 3175 // OpenMP [2.16, Nesting of Regions] 3176 // An ordered region may not be closely nested inside a critical, 3177 // atomic, or explicit task region. 3178 // An ordered region must be closely nested inside a loop region (or 3179 // parallel loop region) with an ordered clause. 3180 // OpenMP [2.8.1,simd Construct, Restrictions] 3181 // An ordered construct with the simd clause is the only OpenMP construct 3182 // that can appear in the simd region. 3183 NestingProhibited = ParentRegion == OMPD_critical || 3184 isOpenMPTaskingDirective(ParentRegion) || 3185 !(isOpenMPSimdDirective(ParentRegion) || 3186 Stack->isParentOrderedRegion()); 3187 Recommend = ShouldBeInOrderedRegion; 3188 } else if (isOpenMPTeamsDirective(CurrentRegion)) { 3189 // OpenMP [2.16, Nesting of Regions] 3190 // If specified, a teams construct must be contained within a target 3191 // construct. 3192 NestingProhibited = ParentRegion != OMPD_target; 3193 Recommend = ShouldBeInTargetRegion; 3194 Stack->setParentTeamsRegionLoc(Stack->getConstructLoc()); 3195 } 3196 if (!NestingProhibited && isOpenMPTeamsDirective(ParentRegion)) { 3197 // OpenMP [2.16, Nesting of Regions] 3198 // distribute, parallel, parallel sections, parallel workshare, and the 3199 // parallel loop and parallel loop SIMD constructs are the only OpenMP 3200 // constructs that can be closely nested in the teams region. 3201 NestingProhibited = !isOpenMPParallelDirective(CurrentRegion) && 3202 !isOpenMPDistributeDirective(CurrentRegion); 3203 Recommend = ShouldBeInParallelRegion; 3204 } 3205 if (!NestingProhibited && isOpenMPDistributeDirective(CurrentRegion)) { 3206 // OpenMP 4.5 [2.17 Nesting of Regions] 3207 // The region associated with the distribute construct must be strictly 3208 // nested inside a teams region 3209 NestingProhibited = !isOpenMPTeamsDirective(ParentRegion); 3210 Recommend = ShouldBeInTeamsRegion; 3211 } 3212 if (!NestingProhibited && 3213 (isOpenMPTargetExecutionDirective(CurrentRegion) || 3214 isOpenMPTargetDataManagementDirective(CurrentRegion))) { 3215 // OpenMP 4.5 [2.17 Nesting of Regions] 3216 // If a target, target update, target data, target enter data, or 3217 // target exit data construct is encountered during execution of a 3218 // target region, the behavior is unspecified. 3219 NestingProhibited = Stack->hasDirective( 3220 [&OffendingRegion](OpenMPDirectiveKind K, const DeclarationNameInfo &, 3221 SourceLocation) -> bool { 3222 if (isOpenMPTargetExecutionDirective(K)) { 3223 OffendingRegion = K; 3224 return true; 3225 } else 3226 return false; 3227 }, 3228 false /* don't skip top directive */); 3229 CloseNesting = false; 3230 } 3231 if (NestingProhibited) { 3232 SemaRef.Diag(StartLoc, diag::err_omp_prohibited_region) 3233 << CloseNesting << getOpenMPDirectiveName(OffendingRegion) 3234 << Recommend << getOpenMPDirectiveName(CurrentRegion); 3235 return true; 3236 } 3237 } 3238 return false; 3239 } 3240 3241 static bool checkIfClauses(Sema &S, OpenMPDirectiveKind Kind, 3242 ArrayRef<OMPClause *> Clauses, 3243 ArrayRef<OpenMPDirectiveKind> AllowedNameModifiers) { 3244 bool ErrorFound = false; 3245 unsigned NamedModifiersNumber = 0; 3246 SmallVector<const OMPIfClause *, OMPC_unknown + 1> FoundNameModifiers( 3247 OMPD_unknown + 1); 3248 SmallVector<SourceLocation, 4> NameModifierLoc; 3249 for (const auto *C : Clauses) { 3250 if (const auto *IC = dyn_cast_or_null<OMPIfClause>(C)) { 3251 // At most one if clause without a directive-name-modifier can appear on 3252 // the directive. 3253 OpenMPDirectiveKind CurNM = IC->getNameModifier(); 3254 if (FoundNameModifiers[CurNM]) { 3255 S.Diag(C->getLocStart(), diag::err_omp_more_one_clause) 3256 << getOpenMPDirectiveName(Kind) << getOpenMPClauseName(OMPC_if) 3257 << (CurNM != OMPD_unknown) << getOpenMPDirectiveName(CurNM); 3258 ErrorFound = true; 3259 } else if (CurNM != OMPD_unknown) { 3260 NameModifierLoc.push_back(IC->getNameModifierLoc()); 3261 ++NamedModifiersNumber; 3262 } 3263 FoundNameModifiers[CurNM] = IC; 3264 if (CurNM == OMPD_unknown) 3265 continue; 3266 // Check if the specified name modifier is allowed for the current 3267 // directive. 3268 // At most one if clause with the particular directive-name-modifier can 3269 // appear on the directive. 3270 bool MatchFound = false; 3271 for (auto NM : AllowedNameModifiers) { 3272 if (CurNM == NM) { 3273 MatchFound = true; 3274 break; 3275 } 3276 } 3277 if (!MatchFound) { 3278 S.Diag(IC->getNameModifierLoc(), 3279 diag::err_omp_wrong_if_directive_name_modifier) 3280 << getOpenMPDirectiveName(CurNM) << getOpenMPDirectiveName(Kind); 3281 ErrorFound = true; 3282 } 3283 } 3284 } 3285 // If any if clause on the directive includes a directive-name-modifier then 3286 // all if clauses on the directive must include a directive-name-modifier. 3287 if (FoundNameModifiers[OMPD_unknown] && NamedModifiersNumber > 0) { 3288 if (NamedModifiersNumber == AllowedNameModifiers.size()) { 3289 S.Diag(FoundNameModifiers[OMPD_unknown]->getLocStart(), 3290 diag::err_omp_no_more_if_clause); 3291 } else { 3292 std::string Values; 3293 std::string Sep(", "); 3294 unsigned AllowedCnt = 0; 3295 unsigned TotalAllowedNum = 3296 AllowedNameModifiers.size() - NamedModifiersNumber; 3297 for (unsigned Cnt = 0, End = AllowedNameModifiers.size(); Cnt < End; 3298 ++Cnt) { 3299 OpenMPDirectiveKind NM = AllowedNameModifiers[Cnt]; 3300 if (!FoundNameModifiers[NM]) { 3301 Values += "'"; 3302 Values += getOpenMPDirectiveName(NM); 3303 Values += "'"; 3304 if (AllowedCnt + 2 == TotalAllowedNum) 3305 Values += " or "; 3306 else if (AllowedCnt + 1 != TotalAllowedNum) 3307 Values += Sep; 3308 ++AllowedCnt; 3309 } 3310 } 3311 S.Diag(FoundNameModifiers[OMPD_unknown]->getCondition()->getLocStart(), 3312 diag::err_omp_unnamed_if_clause) 3313 << (TotalAllowedNum > 1) << Values; 3314 } 3315 for (auto Loc : NameModifierLoc) { 3316 S.Diag(Loc, diag::note_omp_previous_named_if_clause); 3317 } 3318 ErrorFound = true; 3319 } 3320 return ErrorFound; 3321 } 3322 3323 StmtResult Sema::ActOnOpenMPExecutableDirective( 3324 OpenMPDirectiveKind Kind, const DeclarationNameInfo &DirName, 3325 OpenMPDirectiveKind CancelRegion, ArrayRef<OMPClause *> Clauses, 3326 Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc) { 3327 StmtResult Res = StmtError(); 3328 if (CheckNestingOfRegions(*this, DSAStack, Kind, DirName, CancelRegion, 3329 StartLoc)) 3330 return StmtError(); 3331 3332 llvm::SmallVector<OMPClause *, 8> ClausesWithImplicit; 3333 llvm::DenseMap<ValueDecl *, Expr *> VarsWithInheritedDSA; 3334 bool ErrorFound = false; 3335 ClausesWithImplicit.append(Clauses.begin(), Clauses.end()); 3336 if (AStmt) { 3337 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected"); 3338 3339 // Check default data sharing attributes for referenced variables. 3340 DSAAttrChecker DSAChecker(DSAStack, *this, cast<CapturedStmt>(AStmt)); 3341 DSAChecker.Visit(cast<CapturedStmt>(AStmt)->getCapturedStmt()); 3342 if (DSAChecker.isErrorFound()) 3343 return StmtError(); 3344 // Generate list of implicitly defined firstprivate variables. 3345 VarsWithInheritedDSA = DSAChecker.getVarsWithInheritedDSA(); 3346 3347 if (!DSAChecker.getImplicitFirstprivate().empty()) { 3348 if (OMPClause *Implicit = ActOnOpenMPFirstprivateClause( 3349 DSAChecker.getImplicitFirstprivate(), SourceLocation(), 3350 SourceLocation(), SourceLocation())) { 3351 ClausesWithImplicit.push_back(Implicit); 3352 ErrorFound = cast<OMPFirstprivateClause>(Implicit)->varlist_size() != 3353 DSAChecker.getImplicitFirstprivate().size(); 3354 } else 3355 ErrorFound = true; 3356 } 3357 } 3358 3359 llvm::SmallVector<OpenMPDirectiveKind, 4> AllowedNameModifiers; 3360 switch (Kind) { 3361 case OMPD_parallel: 3362 Res = ActOnOpenMPParallelDirective(ClausesWithImplicit, AStmt, StartLoc, 3363 EndLoc); 3364 AllowedNameModifiers.push_back(OMPD_parallel); 3365 break; 3366 case OMPD_simd: 3367 Res = ActOnOpenMPSimdDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc, 3368 VarsWithInheritedDSA); 3369 break; 3370 case OMPD_for: 3371 Res = ActOnOpenMPForDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc, 3372 VarsWithInheritedDSA); 3373 break; 3374 case OMPD_for_simd: 3375 Res = ActOnOpenMPForSimdDirective(ClausesWithImplicit, AStmt, StartLoc, 3376 EndLoc, VarsWithInheritedDSA); 3377 break; 3378 case OMPD_sections: 3379 Res = ActOnOpenMPSectionsDirective(ClausesWithImplicit, AStmt, StartLoc, 3380 EndLoc); 3381 break; 3382 case OMPD_section: 3383 assert(ClausesWithImplicit.empty() && 3384 "No clauses are allowed for 'omp section' directive"); 3385 Res = ActOnOpenMPSectionDirective(AStmt, StartLoc, EndLoc); 3386 break; 3387 case OMPD_single: 3388 Res = ActOnOpenMPSingleDirective(ClausesWithImplicit, AStmt, StartLoc, 3389 EndLoc); 3390 break; 3391 case OMPD_master: 3392 assert(ClausesWithImplicit.empty() && 3393 "No clauses are allowed for 'omp master' directive"); 3394 Res = ActOnOpenMPMasterDirective(AStmt, StartLoc, EndLoc); 3395 break; 3396 case OMPD_critical: 3397 Res = ActOnOpenMPCriticalDirective(DirName, ClausesWithImplicit, AStmt, 3398 StartLoc, EndLoc); 3399 break; 3400 case OMPD_parallel_for: 3401 Res = ActOnOpenMPParallelForDirective(ClausesWithImplicit, AStmt, StartLoc, 3402 EndLoc, VarsWithInheritedDSA); 3403 AllowedNameModifiers.push_back(OMPD_parallel); 3404 break; 3405 case OMPD_parallel_for_simd: 3406 Res = ActOnOpenMPParallelForSimdDirective( 3407 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA); 3408 AllowedNameModifiers.push_back(OMPD_parallel); 3409 break; 3410 case OMPD_parallel_sections: 3411 Res = ActOnOpenMPParallelSectionsDirective(ClausesWithImplicit, AStmt, 3412 StartLoc, EndLoc); 3413 AllowedNameModifiers.push_back(OMPD_parallel); 3414 break; 3415 case OMPD_task: 3416 Res = 3417 ActOnOpenMPTaskDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc); 3418 AllowedNameModifiers.push_back(OMPD_task); 3419 break; 3420 case OMPD_taskyield: 3421 assert(ClausesWithImplicit.empty() && 3422 "No clauses are allowed for 'omp taskyield' directive"); 3423 assert(AStmt == nullptr && 3424 "No associated statement allowed for 'omp taskyield' directive"); 3425 Res = ActOnOpenMPTaskyieldDirective(StartLoc, EndLoc); 3426 break; 3427 case OMPD_barrier: 3428 assert(ClausesWithImplicit.empty() && 3429 "No clauses are allowed for 'omp barrier' directive"); 3430 assert(AStmt == nullptr && 3431 "No associated statement allowed for 'omp barrier' directive"); 3432 Res = ActOnOpenMPBarrierDirective(StartLoc, EndLoc); 3433 break; 3434 case OMPD_taskwait: 3435 assert(ClausesWithImplicit.empty() && 3436 "No clauses are allowed for 'omp taskwait' directive"); 3437 assert(AStmt == nullptr && 3438 "No associated statement allowed for 'omp taskwait' directive"); 3439 Res = ActOnOpenMPTaskwaitDirective(StartLoc, EndLoc); 3440 break; 3441 case OMPD_taskgroup: 3442 assert(ClausesWithImplicit.empty() && 3443 "No clauses are allowed for 'omp taskgroup' directive"); 3444 Res = ActOnOpenMPTaskgroupDirective(AStmt, StartLoc, EndLoc); 3445 break; 3446 case OMPD_flush: 3447 assert(AStmt == nullptr && 3448 "No associated statement allowed for 'omp flush' directive"); 3449 Res = ActOnOpenMPFlushDirective(ClausesWithImplicit, StartLoc, EndLoc); 3450 break; 3451 case OMPD_ordered: 3452 Res = ActOnOpenMPOrderedDirective(ClausesWithImplicit, AStmt, StartLoc, 3453 EndLoc); 3454 break; 3455 case OMPD_atomic: 3456 Res = ActOnOpenMPAtomicDirective(ClausesWithImplicit, AStmt, StartLoc, 3457 EndLoc); 3458 break; 3459 case OMPD_teams: 3460 Res = 3461 ActOnOpenMPTeamsDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc); 3462 break; 3463 case OMPD_target: 3464 Res = ActOnOpenMPTargetDirective(ClausesWithImplicit, AStmt, StartLoc, 3465 EndLoc); 3466 AllowedNameModifiers.push_back(OMPD_target); 3467 break; 3468 case OMPD_target_parallel: 3469 Res = ActOnOpenMPTargetParallelDirective(ClausesWithImplicit, AStmt, 3470 StartLoc, EndLoc); 3471 AllowedNameModifiers.push_back(OMPD_target); 3472 AllowedNameModifiers.push_back(OMPD_parallel); 3473 break; 3474 case OMPD_target_parallel_for: 3475 Res = ActOnOpenMPTargetParallelForDirective( 3476 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA); 3477 AllowedNameModifiers.push_back(OMPD_target); 3478 AllowedNameModifiers.push_back(OMPD_parallel); 3479 break; 3480 case OMPD_cancellation_point: 3481 assert(ClausesWithImplicit.empty() && 3482 "No clauses are allowed for 'omp cancellation point' directive"); 3483 assert(AStmt == nullptr && "No associated statement allowed for 'omp " 3484 "cancellation point' directive"); 3485 Res = ActOnOpenMPCancellationPointDirective(StartLoc, EndLoc, CancelRegion); 3486 break; 3487 case OMPD_cancel: 3488 assert(AStmt == nullptr && 3489 "No associated statement allowed for 'omp cancel' directive"); 3490 Res = ActOnOpenMPCancelDirective(ClausesWithImplicit, StartLoc, EndLoc, 3491 CancelRegion); 3492 AllowedNameModifiers.push_back(OMPD_cancel); 3493 break; 3494 case OMPD_target_data: 3495 Res = ActOnOpenMPTargetDataDirective(ClausesWithImplicit, AStmt, StartLoc, 3496 EndLoc); 3497 AllowedNameModifiers.push_back(OMPD_target_data); 3498 break; 3499 case OMPD_target_enter_data: 3500 Res = ActOnOpenMPTargetEnterDataDirective(ClausesWithImplicit, StartLoc, 3501 EndLoc); 3502 AllowedNameModifiers.push_back(OMPD_target_enter_data); 3503 break; 3504 case OMPD_target_exit_data: 3505 Res = ActOnOpenMPTargetExitDataDirective(ClausesWithImplicit, StartLoc, 3506 EndLoc); 3507 AllowedNameModifiers.push_back(OMPD_target_exit_data); 3508 break; 3509 case OMPD_taskloop: 3510 Res = ActOnOpenMPTaskLoopDirective(ClausesWithImplicit, AStmt, StartLoc, 3511 EndLoc, VarsWithInheritedDSA); 3512 AllowedNameModifiers.push_back(OMPD_taskloop); 3513 break; 3514 case OMPD_taskloop_simd: 3515 Res = ActOnOpenMPTaskLoopSimdDirective(ClausesWithImplicit, AStmt, StartLoc, 3516 EndLoc, VarsWithInheritedDSA); 3517 AllowedNameModifiers.push_back(OMPD_taskloop); 3518 break; 3519 case OMPD_distribute: 3520 Res = ActOnOpenMPDistributeDirective(ClausesWithImplicit, AStmt, StartLoc, 3521 EndLoc, VarsWithInheritedDSA); 3522 break; 3523 case OMPD_target_update: 3524 assert(!AStmt && "Statement is not allowed for target update"); 3525 Res = 3526 ActOnOpenMPTargetUpdateDirective(ClausesWithImplicit, StartLoc, EndLoc); 3527 AllowedNameModifiers.push_back(OMPD_target_update); 3528 break; 3529 case OMPD_distribute_parallel_for: 3530 Res = ActOnOpenMPDistributeParallelForDirective( 3531 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA); 3532 AllowedNameModifiers.push_back(OMPD_parallel); 3533 break; 3534 case OMPD_distribute_parallel_for_simd: 3535 Res = ActOnOpenMPDistributeParallelForSimdDirective( 3536 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA); 3537 AllowedNameModifiers.push_back(OMPD_parallel); 3538 break; 3539 case OMPD_declare_target: 3540 case OMPD_end_declare_target: 3541 case OMPD_threadprivate: 3542 case OMPD_declare_reduction: 3543 case OMPD_declare_simd: 3544 llvm_unreachable("OpenMP Directive is not allowed"); 3545 case OMPD_unknown: 3546 llvm_unreachable("Unknown OpenMP directive"); 3547 } 3548 3549 for (auto P : VarsWithInheritedDSA) { 3550 Diag(P.second->getExprLoc(), diag::err_omp_no_dsa_for_variable) 3551 << P.first << P.second->getSourceRange(); 3552 } 3553 ErrorFound = !VarsWithInheritedDSA.empty() || ErrorFound; 3554 3555 if (!AllowedNameModifiers.empty()) 3556 ErrorFound = checkIfClauses(*this, Kind, Clauses, AllowedNameModifiers) || 3557 ErrorFound; 3558 3559 if (ErrorFound) 3560 return StmtError(); 3561 return Res; 3562 } 3563 3564 Sema::DeclGroupPtrTy Sema::ActOnOpenMPDeclareSimdDirective( 3565 DeclGroupPtrTy DG, OMPDeclareSimdDeclAttr::BranchStateTy BS, Expr *Simdlen, 3566 ArrayRef<Expr *> Uniforms, ArrayRef<Expr *> Aligneds, 3567 ArrayRef<Expr *> Alignments, ArrayRef<Expr *> Linears, 3568 ArrayRef<unsigned> LinModifiers, ArrayRef<Expr *> Steps, SourceRange SR) { 3569 assert(Aligneds.size() == Alignments.size()); 3570 assert(Linears.size() == LinModifiers.size()); 3571 assert(Linears.size() == Steps.size()); 3572 if (!DG || DG.get().isNull()) 3573 return DeclGroupPtrTy(); 3574 3575 if (!DG.get().isSingleDecl()) { 3576 Diag(SR.getBegin(), diag::err_omp_single_decl_in_declare_simd); 3577 return DG; 3578 } 3579 auto *ADecl = DG.get().getSingleDecl(); 3580 if (auto *FTD = dyn_cast<FunctionTemplateDecl>(ADecl)) 3581 ADecl = FTD->getTemplatedDecl(); 3582 3583 auto *FD = dyn_cast<FunctionDecl>(ADecl); 3584 if (!FD) { 3585 Diag(ADecl->getLocation(), diag::err_omp_function_expected); 3586 return DeclGroupPtrTy(); 3587 } 3588 3589 // OpenMP [2.8.2, declare simd construct, Description] 3590 // The parameter of the simdlen clause must be a constant positive integer 3591 // expression. 3592 ExprResult SL; 3593 if (Simdlen) 3594 SL = VerifyPositiveIntegerConstantInClause(Simdlen, OMPC_simdlen); 3595 // OpenMP [2.8.2, declare simd construct, Description] 3596 // The special this pointer can be used as if was one of the arguments to the 3597 // function in any of the linear, aligned, or uniform clauses. 3598 // The uniform clause declares one or more arguments to have an invariant 3599 // value for all concurrent invocations of the function in the execution of a 3600 // single SIMD loop. 3601 llvm::DenseMap<Decl *, Expr *> UniformedArgs; 3602 Expr *UniformedLinearThis = nullptr; 3603 for (auto *E : Uniforms) { 3604 E = E->IgnoreParenImpCasts(); 3605 if (auto *DRE = dyn_cast<DeclRefExpr>(E)) 3606 if (auto *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl())) 3607 if (FD->getNumParams() > PVD->getFunctionScopeIndex() && 3608 FD->getParamDecl(PVD->getFunctionScopeIndex()) 3609 ->getCanonicalDecl() == PVD->getCanonicalDecl()) { 3610 UniformedArgs.insert(std::make_pair(PVD->getCanonicalDecl(), E)); 3611 continue; 3612 } 3613 if (isa<CXXThisExpr>(E)) { 3614 UniformedLinearThis = E; 3615 continue; 3616 } 3617 Diag(E->getExprLoc(), diag::err_omp_param_or_this_in_clause) 3618 << FD->getDeclName() << (isa<CXXMethodDecl>(ADecl) ? 1 : 0); 3619 } 3620 // OpenMP [2.8.2, declare simd construct, Description] 3621 // The aligned clause declares that the object to which each list item points 3622 // is aligned to the number of bytes expressed in the optional parameter of 3623 // the aligned clause. 3624 // The special this pointer can be used as if was one of the arguments to the 3625 // function in any of the linear, aligned, or uniform clauses. 3626 // The type of list items appearing in the aligned clause must be array, 3627 // pointer, reference to array, or reference to pointer. 3628 llvm::DenseMap<Decl *, Expr *> AlignedArgs; 3629 Expr *AlignedThis = nullptr; 3630 for (auto *E : Aligneds) { 3631 E = E->IgnoreParenImpCasts(); 3632 if (auto *DRE = dyn_cast<DeclRefExpr>(E)) 3633 if (auto *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl())) { 3634 auto *CanonPVD = PVD->getCanonicalDecl(); 3635 if (FD->getNumParams() > PVD->getFunctionScopeIndex() && 3636 FD->getParamDecl(PVD->getFunctionScopeIndex()) 3637 ->getCanonicalDecl() == CanonPVD) { 3638 // OpenMP [2.8.1, simd construct, Restrictions] 3639 // A list-item cannot appear in more than one aligned clause. 3640 if (AlignedArgs.count(CanonPVD) > 0) { 3641 Diag(E->getExprLoc(), diag::err_omp_aligned_twice) 3642 << 1 << E->getSourceRange(); 3643 Diag(AlignedArgs[CanonPVD]->getExprLoc(), 3644 diag::note_omp_explicit_dsa) 3645 << getOpenMPClauseName(OMPC_aligned); 3646 continue; 3647 } 3648 AlignedArgs[CanonPVD] = E; 3649 QualType QTy = PVD->getType() 3650 .getNonReferenceType() 3651 .getUnqualifiedType() 3652 .getCanonicalType(); 3653 const Type *Ty = QTy.getTypePtrOrNull(); 3654 if (!Ty || (!Ty->isArrayType() && !Ty->isPointerType())) { 3655 Diag(E->getExprLoc(), diag::err_omp_aligned_expected_array_or_ptr) 3656 << QTy << getLangOpts().CPlusPlus << E->getSourceRange(); 3657 Diag(PVD->getLocation(), diag::note_previous_decl) << PVD; 3658 } 3659 continue; 3660 } 3661 } 3662 if (isa<CXXThisExpr>(E)) { 3663 if (AlignedThis) { 3664 Diag(E->getExprLoc(), diag::err_omp_aligned_twice) 3665 << 2 << E->getSourceRange(); 3666 Diag(AlignedThis->getExprLoc(), diag::note_omp_explicit_dsa) 3667 << getOpenMPClauseName(OMPC_aligned); 3668 } 3669 AlignedThis = E; 3670 continue; 3671 } 3672 Diag(E->getExprLoc(), diag::err_omp_param_or_this_in_clause) 3673 << FD->getDeclName() << (isa<CXXMethodDecl>(ADecl) ? 1 : 0); 3674 } 3675 // The optional parameter of the aligned clause, alignment, must be a constant 3676 // positive integer expression. If no optional parameter is specified, 3677 // implementation-defined default alignments for SIMD instructions on the 3678 // target platforms are assumed. 3679 SmallVector<Expr *, 4> NewAligns; 3680 for (auto *E : Alignments) { 3681 ExprResult Align; 3682 if (E) 3683 Align = VerifyPositiveIntegerConstantInClause(E, OMPC_aligned); 3684 NewAligns.push_back(Align.get()); 3685 } 3686 // OpenMP [2.8.2, declare simd construct, Description] 3687 // The linear clause declares one or more list items to be private to a SIMD 3688 // lane and to have a linear relationship with respect to the iteration space 3689 // of a loop. 3690 // The special this pointer can be used as if was one of the arguments to the 3691 // function in any of the linear, aligned, or uniform clauses. 3692 // When a linear-step expression is specified in a linear clause it must be 3693 // either a constant integer expression or an integer-typed parameter that is 3694 // specified in a uniform clause on the directive. 3695 llvm::DenseMap<Decl *, Expr *> LinearArgs; 3696 const bool IsUniformedThis = UniformedLinearThis != nullptr; 3697 auto MI = LinModifiers.begin(); 3698 for (auto *E : Linears) { 3699 auto LinKind = static_cast<OpenMPLinearClauseKind>(*MI); 3700 ++MI; 3701 E = E->IgnoreParenImpCasts(); 3702 if (auto *DRE = dyn_cast<DeclRefExpr>(E)) 3703 if (auto *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl())) { 3704 auto *CanonPVD = PVD->getCanonicalDecl(); 3705 if (FD->getNumParams() > PVD->getFunctionScopeIndex() && 3706 FD->getParamDecl(PVD->getFunctionScopeIndex()) 3707 ->getCanonicalDecl() == CanonPVD) { 3708 // OpenMP [2.15.3.7, linear Clause, Restrictions] 3709 // A list-item cannot appear in more than one linear clause. 3710 if (LinearArgs.count(CanonPVD) > 0) { 3711 Diag(E->getExprLoc(), diag::err_omp_wrong_dsa) 3712 << getOpenMPClauseName(OMPC_linear) 3713 << getOpenMPClauseName(OMPC_linear) << E->getSourceRange(); 3714 Diag(LinearArgs[CanonPVD]->getExprLoc(), 3715 diag::note_omp_explicit_dsa) 3716 << getOpenMPClauseName(OMPC_linear); 3717 continue; 3718 } 3719 // Each argument can appear in at most one uniform or linear clause. 3720 if (UniformedArgs.count(CanonPVD) > 0) { 3721 Diag(E->getExprLoc(), diag::err_omp_wrong_dsa) 3722 << getOpenMPClauseName(OMPC_linear) 3723 << getOpenMPClauseName(OMPC_uniform) << E->getSourceRange(); 3724 Diag(UniformedArgs[CanonPVD]->getExprLoc(), 3725 diag::note_omp_explicit_dsa) 3726 << getOpenMPClauseName(OMPC_uniform); 3727 continue; 3728 } 3729 LinearArgs[CanonPVD] = E; 3730 if (E->isValueDependent() || E->isTypeDependent() || 3731 E->isInstantiationDependent() || 3732 E->containsUnexpandedParameterPack()) 3733 continue; 3734 (void)CheckOpenMPLinearDecl(CanonPVD, E->getExprLoc(), LinKind, 3735 PVD->getOriginalType()); 3736 continue; 3737 } 3738 } 3739 if (isa<CXXThisExpr>(E)) { 3740 if (UniformedLinearThis) { 3741 Diag(E->getExprLoc(), diag::err_omp_wrong_dsa) 3742 << getOpenMPClauseName(OMPC_linear) 3743 << getOpenMPClauseName(IsUniformedThis ? OMPC_uniform : OMPC_linear) 3744 << E->getSourceRange(); 3745 Diag(UniformedLinearThis->getExprLoc(), diag::note_omp_explicit_dsa) 3746 << getOpenMPClauseName(IsUniformedThis ? OMPC_uniform 3747 : OMPC_linear); 3748 continue; 3749 } 3750 UniformedLinearThis = E; 3751 if (E->isValueDependent() || E->isTypeDependent() || 3752 E->isInstantiationDependent() || E->containsUnexpandedParameterPack()) 3753 continue; 3754 (void)CheckOpenMPLinearDecl(/*D=*/nullptr, E->getExprLoc(), LinKind, 3755 E->getType()); 3756 continue; 3757 } 3758 Diag(E->getExprLoc(), diag::err_omp_param_or_this_in_clause) 3759 << FD->getDeclName() << (isa<CXXMethodDecl>(ADecl) ? 1 : 0); 3760 } 3761 Expr *Step = nullptr; 3762 Expr *NewStep = nullptr; 3763 SmallVector<Expr *, 4> NewSteps; 3764 for (auto *E : Steps) { 3765 // Skip the same step expression, it was checked already. 3766 if (Step == E || !E) { 3767 NewSteps.push_back(E ? NewStep : nullptr); 3768 continue; 3769 } 3770 Step = E; 3771 if (auto *DRE = dyn_cast<DeclRefExpr>(Step)) 3772 if (auto *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl())) { 3773 auto *CanonPVD = PVD->getCanonicalDecl(); 3774 if (UniformedArgs.count(CanonPVD) == 0) { 3775 Diag(Step->getExprLoc(), diag::err_omp_expected_uniform_param) 3776 << Step->getSourceRange(); 3777 } else if (E->isValueDependent() || E->isTypeDependent() || 3778 E->isInstantiationDependent() || 3779 E->containsUnexpandedParameterPack() || 3780 CanonPVD->getType()->hasIntegerRepresentation()) 3781 NewSteps.push_back(Step); 3782 else { 3783 Diag(Step->getExprLoc(), diag::err_omp_expected_int_param) 3784 << Step->getSourceRange(); 3785 } 3786 continue; 3787 } 3788 NewStep = Step; 3789 if (Step && !Step->isValueDependent() && !Step->isTypeDependent() && 3790 !Step->isInstantiationDependent() && 3791 !Step->containsUnexpandedParameterPack()) { 3792 NewStep = PerformOpenMPImplicitIntegerConversion(Step->getExprLoc(), Step) 3793 .get(); 3794 if (NewStep) 3795 NewStep = VerifyIntegerConstantExpression(NewStep).get(); 3796 } 3797 NewSteps.push_back(NewStep); 3798 } 3799 auto *NewAttr = OMPDeclareSimdDeclAttr::CreateImplicit( 3800 Context, BS, SL.get(), const_cast<Expr **>(Uniforms.data()), 3801 Uniforms.size(), const_cast<Expr **>(Aligneds.data()), Aligneds.size(), 3802 const_cast<Expr **>(NewAligns.data()), NewAligns.size(), 3803 const_cast<Expr **>(Linears.data()), Linears.size(), 3804 const_cast<unsigned *>(LinModifiers.data()), LinModifiers.size(), 3805 NewSteps.data(), NewSteps.size(), SR); 3806 ADecl->addAttr(NewAttr); 3807 return ConvertDeclToDeclGroup(ADecl); 3808 } 3809 3810 StmtResult Sema::ActOnOpenMPParallelDirective(ArrayRef<OMPClause *> Clauses, 3811 Stmt *AStmt, 3812 SourceLocation StartLoc, 3813 SourceLocation EndLoc) { 3814 if (!AStmt) 3815 return StmtError(); 3816 3817 CapturedStmt *CS = cast<CapturedStmt>(AStmt); 3818 // 1.2.2 OpenMP Language Terminology 3819 // Structured block - An executable statement with a single entry at the 3820 // top and a single exit at the bottom. 3821 // The point of exit cannot be a branch out of the structured block. 3822 // longjmp() and throw() must not violate the entry/exit criteria. 3823 CS->getCapturedDecl()->setNothrow(); 3824 3825 getCurFunction()->setHasBranchProtectedScope(); 3826 3827 return OMPParallelDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt, 3828 DSAStack->isCancelRegion()); 3829 } 3830 3831 namespace { 3832 /// \brief Helper class for checking canonical form of the OpenMP loops and 3833 /// extracting iteration space of each loop in the loop nest, that will be used 3834 /// for IR generation. 3835 class OpenMPIterationSpaceChecker { 3836 /// \brief Reference to Sema. 3837 Sema &SemaRef; 3838 /// \brief A location for diagnostics (when there is no some better location). 3839 SourceLocation DefaultLoc; 3840 /// \brief A location for diagnostics (when increment is not compatible). 3841 SourceLocation ConditionLoc; 3842 /// \brief A source location for referring to loop init later. 3843 SourceRange InitSrcRange; 3844 /// \brief A source location for referring to condition later. 3845 SourceRange ConditionSrcRange; 3846 /// \brief A source location for referring to increment later. 3847 SourceRange IncrementSrcRange; 3848 /// \brief Loop variable. 3849 ValueDecl *LCDecl = nullptr; 3850 /// \brief Reference to loop variable. 3851 Expr *LCRef = nullptr; 3852 /// \brief Lower bound (initializer for the var). 3853 Expr *LB = nullptr; 3854 /// \brief Upper bound. 3855 Expr *UB = nullptr; 3856 /// \brief Loop step (increment). 3857 Expr *Step = nullptr; 3858 /// \brief This flag is true when condition is one of: 3859 /// Var < UB 3860 /// Var <= UB 3861 /// UB > Var 3862 /// UB >= Var 3863 bool TestIsLessOp = false; 3864 /// \brief This flag is true when condition is strict ( < or > ). 3865 bool TestIsStrictOp = false; 3866 /// \brief This flag is true when step is subtracted on each iteration. 3867 bool SubtractStep = false; 3868 3869 public: 3870 OpenMPIterationSpaceChecker(Sema &SemaRef, SourceLocation DefaultLoc) 3871 : SemaRef(SemaRef), DefaultLoc(DefaultLoc), ConditionLoc(DefaultLoc) {} 3872 /// \brief Check init-expr for canonical loop form and save loop counter 3873 /// variable - #Var and its initialization value - #LB. 3874 bool CheckInit(Stmt *S, bool EmitDiags = true); 3875 /// \brief Check test-expr for canonical form, save upper-bound (#UB), flags 3876 /// for less/greater and for strict/non-strict comparison. 3877 bool CheckCond(Expr *S); 3878 /// \brief Check incr-expr for canonical loop form and return true if it 3879 /// does not conform, otherwise save loop step (#Step). 3880 bool CheckInc(Expr *S); 3881 /// \brief Return the loop counter variable. 3882 ValueDecl *GetLoopDecl() const { return LCDecl; } 3883 /// \brief Return the reference expression to loop counter variable. 3884 Expr *GetLoopDeclRefExpr() const { return LCRef; } 3885 /// \brief Source range of the loop init. 3886 SourceRange GetInitSrcRange() const { return InitSrcRange; } 3887 /// \brief Source range of the loop condition. 3888 SourceRange GetConditionSrcRange() const { return ConditionSrcRange; } 3889 /// \brief Source range of the loop increment. 3890 SourceRange GetIncrementSrcRange() const { return IncrementSrcRange; } 3891 /// \brief True if the step should be subtracted. 3892 bool ShouldSubtractStep() const { return SubtractStep; } 3893 /// \brief Build the expression to calculate the number of iterations. 3894 Expr * 3895 BuildNumIterations(Scope *S, const bool LimitedType, 3896 llvm::MapVector<Expr *, DeclRefExpr *> &Captures) const; 3897 /// \brief Build the precondition expression for the loops. 3898 Expr *BuildPreCond(Scope *S, Expr *Cond, 3899 llvm::MapVector<Expr *, DeclRefExpr *> &Captures) const; 3900 /// \brief Build reference expression to the counter be used for codegen. 3901 DeclRefExpr *BuildCounterVar(llvm::MapVector<Expr *, DeclRefExpr *> &Captures, 3902 DSAStackTy &DSA) const; 3903 /// \brief Build reference expression to the private counter be used for 3904 /// codegen. 3905 Expr *BuildPrivateCounterVar() const; 3906 /// \brief Build initization of the counter be used for codegen. 3907 Expr *BuildCounterInit() const; 3908 /// \brief Build step of the counter be used for codegen. 3909 Expr *BuildCounterStep() const; 3910 /// \brief Return true if any expression is dependent. 3911 bool Dependent() const; 3912 3913 private: 3914 /// \brief Check the right-hand side of an assignment in the increment 3915 /// expression. 3916 bool CheckIncRHS(Expr *RHS); 3917 /// \brief Helper to set loop counter variable and its initializer. 3918 bool SetLCDeclAndLB(ValueDecl *NewLCDecl, Expr *NewDeclRefExpr, Expr *NewLB); 3919 /// \brief Helper to set upper bound. 3920 bool SetUB(Expr *NewUB, bool LessOp, bool StrictOp, SourceRange SR, 3921 SourceLocation SL); 3922 /// \brief Helper to set loop increment. 3923 bool SetStep(Expr *NewStep, bool Subtract); 3924 }; 3925 3926 bool OpenMPIterationSpaceChecker::Dependent() const { 3927 if (!LCDecl) { 3928 assert(!LB && !UB && !Step); 3929 return false; 3930 } 3931 return LCDecl->getType()->isDependentType() || 3932 (LB && LB->isValueDependent()) || (UB && UB->isValueDependent()) || 3933 (Step && Step->isValueDependent()); 3934 } 3935 3936 static Expr *getExprAsWritten(Expr *E) { 3937 if (auto *ExprTemp = dyn_cast<ExprWithCleanups>(E)) 3938 E = ExprTemp->getSubExpr(); 3939 3940 if (auto *MTE = dyn_cast<MaterializeTemporaryExpr>(E)) 3941 E = MTE->GetTemporaryExpr(); 3942 3943 while (auto *Binder = dyn_cast<CXXBindTemporaryExpr>(E)) 3944 E = Binder->getSubExpr(); 3945 3946 if (auto *ICE = dyn_cast<ImplicitCastExpr>(E)) 3947 E = ICE->getSubExprAsWritten(); 3948 return E->IgnoreParens(); 3949 } 3950 3951 bool OpenMPIterationSpaceChecker::SetLCDeclAndLB(ValueDecl *NewLCDecl, 3952 Expr *NewLCRefExpr, 3953 Expr *NewLB) { 3954 // State consistency checking to ensure correct usage. 3955 assert(LCDecl == nullptr && LB == nullptr && LCRef == nullptr && 3956 UB == nullptr && Step == nullptr && !TestIsLessOp && !TestIsStrictOp); 3957 if (!NewLCDecl || !NewLB) 3958 return true; 3959 LCDecl = getCanonicalDecl(NewLCDecl); 3960 LCRef = NewLCRefExpr; 3961 if (auto *CE = dyn_cast_or_null<CXXConstructExpr>(NewLB)) 3962 if (const CXXConstructorDecl *Ctor = CE->getConstructor()) 3963 if ((Ctor->isCopyOrMoveConstructor() || 3964 Ctor->isConvertingConstructor(/*AllowExplicit=*/false)) && 3965 CE->getNumArgs() > 0 && CE->getArg(0) != nullptr) 3966 NewLB = CE->getArg(0)->IgnoreParenImpCasts(); 3967 LB = NewLB; 3968 return false; 3969 } 3970 3971 bool OpenMPIterationSpaceChecker::SetUB(Expr *NewUB, bool LessOp, bool StrictOp, 3972 SourceRange SR, SourceLocation SL) { 3973 // State consistency checking to ensure correct usage. 3974 assert(LCDecl != nullptr && LB != nullptr && UB == nullptr && 3975 Step == nullptr && !TestIsLessOp && !TestIsStrictOp); 3976 if (!NewUB) 3977 return true; 3978 UB = NewUB; 3979 TestIsLessOp = LessOp; 3980 TestIsStrictOp = StrictOp; 3981 ConditionSrcRange = SR; 3982 ConditionLoc = SL; 3983 return false; 3984 } 3985 3986 bool OpenMPIterationSpaceChecker::SetStep(Expr *NewStep, bool Subtract) { 3987 // State consistency checking to ensure correct usage. 3988 assert(LCDecl != nullptr && LB != nullptr && Step == nullptr); 3989 if (!NewStep) 3990 return true; 3991 if (!NewStep->isValueDependent()) { 3992 // Check that the step is integer expression. 3993 SourceLocation StepLoc = NewStep->getLocStart(); 3994 ExprResult Val = 3995 SemaRef.PerformOpenMPImplicitIntegerConversion(StepLoc, NewStep); 3996 if (Val.isInvalid()) 3997 return true; 3998 NewStep = Val.get(); 3999 4000 // OpenMP [2.6, Canonical Loop Form, Restrictions] 4001 // If test-expr is of form var relational-op b and relational-op is < or 4002 // <= then incr-expr must cause var to increase on each iteration of the 4003 // loop. If test-expr is of form var relational-op b and relational-op is 4004 // > or >= then incr-expr must cause var to decrease on each iteration of 4005 // the loop. 4006 // If test-expr is of form b relational-op var and relational-op is < or 4007 // <= then incr-expr must cause var to decrease on each iteration of the 4008 // loop. If test-expr is of form b relational-op var and relational-op is 4009 // > or >= then incr-expr must cause var to increase on each iteration of 4010 // the loop. 4011 llvm::APSInt Result; 4012 bool IsConstant = NewStep->isIntegerConstantExpr(Result, SemaRef.Context); 4013 bool IsUnsigned = !NewStep->getType()->hasSignedIntegerRepresentation(); 4014 bool IsConstNeg = 4015 IsConstant && Result.isSigned() && (Subtract != Result.isNegative()); 4016 bool IsConstPos = 4017 IsConstant && Result.isSigned() && (Subtract == Result.isNegative()); 4018 bool IsConstZero = IsConstant && !Result.getBoolValue(); 4019 if (UB && (IsConstZero || 4020 (TestIsLessOp ? (IsConstNeg || (IsUnsigned && Subtract)) 4021 : (IsConstPos || (IsUnsigned && !Subtract))))) { 4022 SemaRef.Diag(NewStep->getExprLoc(), 4023 diag::err_omp_loop_incr_not_compatible) 4024 << LCDecl << TestIsLessOp << NewStep->getSourceRange(); 4025 SemaRef.Diag(ConditionLoc, 4026 diag::note_omp_loop_cond_requres_compatible_incr) 4027 << TestIsLessOp << ConditionSrcRange; 4028 return true; 4029 } 4030 if (TestIsLessOp == Subtract) { 4031 NewStep = SemaRef.CreateBuiltinUnaryOp(NewStep->getExprLoc(), UO_Minus, 4032 NewStep).get(); 4033 Subtract = !Subtract; 4034 } 4035 } 4036 4037 Step = NewStep; 4038 SubtractStep = Subtract; 4039 return false; 4040 } 4041 4042 bool OpenMPIterationSpaceChecker::CheckInit(Stmt *S, bool EmitDiags) { 4043 // Check init-expr for canonical loop form and save loop counter 4044 // variable - #Var and its initialization value - #LB. 4045 // OpenMP [2.6] Canonical loop form. init-expr may be one of the following: 4046 // var = lb 4047 // integer-type var = lb 4048 // random-access-iterator-type var = lb 4049 // pointer-type var = lb 4050 // 4051 if (!S) { 4052 if (EmitDiags) { 4053 SemaRef.Diag(DefaultLoc, diag::err_omp_loop_not_canonical_init); 4054 } 4055 return true; 4056 } 4057 if (auto *ExprTemp = dyn_cast<ExprWithCleanups>(S)) 4058 if (!ExprTemp->cleanupsHaveSideEffects()) 4059 S = ExprTemp->getSubExpr(); 4060 4061 InitSrcRange = S->getSourceRange(); 4062 if (Expr *E = dyn_cast<Expr>(S)) 4063 S = E->IgnoreParens(); 4064 if (auto BO = dyn_cast<BinaryOperator>(S)) { 4065 if (BO->getOpcode() == BO_Assign) { 4066 auto *LHS = BO->getLHS()->IgnoreParens(); 4067 if (auto *DRE = dyn_cast<DeclRefExpr>(LHS)) { 4068 if (auto *CED = dyn_cast<OMPCapturedExprDecl>(DRE->getDecl())) 4069 if (auto *ME = dyn_cast<MemberExpr>(getExprAsWritten(CED->getInit()))) 4070 return SetLCDeclAndLB(ME->getMemberDecl(), ME, BO->getRHS()); 4071 return SetLCDeclAndLB(DRE->getDecl(), DRE, BO->getRHS()); 4072 } 4073 if (auto *ME = dyn_cast<MemberExpr>(LHS)) { 4074 if (ME->isArrow() && 4075 isa<CXXThisExpr>(ME->getBase()->IgnoreParenImpCasts())) 4076 return SetLCDeclAndLB(ME->getMemberDecl(), ME, BO->getRHS()); 4077 } 4078 } 4079 } else if (auto DS = dyn_cast<DeclStmt>(S)) { 4080 if (DS->isSingleDecl()) { 4081 if (auto Var = dyn_cast_or_null<VarDecl>(DS->getSingleDecl())) { 4082 if (Var->hasInit() && !Var->getType()->isReferenceType()) { 4083 // Accept non-canonical init form here but emit ext. warning. 4084 if (Var->getInitStyle() != VarDecl::CInit && EmitDiags) 4085 SemaRef.Diag(S->getLocStart(), 4086 diag::ext_omp_loop_not_canonical_init) 4087 << S->getSourceRange(); 4088 return SetLCDeclAndLB(Var, nullptr, Var->getInit()); 4089 } 4090 } 4091 } 4092 } else if (auto CE = dyn_cast<CXXOperatorCallExpr>(S)) { 4093 if (CE->getOperator() == OO_Equal) { 4094 auto *LHS = CE->getArg(0); 4095 if (auto DRE = dyn_cast<DeclRefExpr>(LHS)) { 4096 if (auto *CED = dyn_cast<OMPCapturedExprDecl>(DRE->getDecl())) 4097 if (auto *ME = dyn_cast<MemberExpr>(getExprAsWritten(CED->getInit()))) 4098 return SetLCDeclAndLB(ME->getMemberDecl(), ME, BO->getRHS()); 4099 return SetLCDeclAndLB(DRE->getDecl(), DRE, CE->getArg(1)); 4100 } 4101 if (auto *ME = dyn_cast<MemberExpr>(LHS)) { 4102 if (ME->isArrow() && 4103 isa<CXXThisExpr>(ME->getBase()->IgnoreParenImpCasts())) 4104 return SetLCDeclAndLB(ME->getMemberDecl(), ME, BO->getRHS()); 4105 } 4106 } 4107 } 4108 4109 if (Dependent() || SemaRef.CurContext->isDependentContext()) 4110 return false; 4111 if (EmitDiags) { 4112 SemaRef.Diag(S->getLocStart(), diag::err_omp_loop_not_canonical_init) 4113 << S->getSourceRange(); 4114 } 4115 return true; 4116 } 4117 4118 /// \brief Ignore parenthesizes, implicit casts, copy constructor and return the 4119 /// variable (which may be the loop variable) if possible. 4120 static const ValueDecl *GetInitLCDecl(Expr *E) { 4121 if (!E) 4122 return nullptr; 4123 E = getExprAsWritten(E); 4124 if (auto *CE = dyn_cast_or_null<CXXConstructExpr>(E)) 4125 if (const CXXConstructorDecl *Ctor = CE->getConstructor()) 4126 if ((Ctor->isCopyOrMoveConstructor() || 4127 Ctor->isConvertingConstructor(/*AllowExplicit=*/false)) && 4128 CE->getNumArgs() > 0 && CE->getArg(0) != nullptr) 4129 E = CE->getArg(0)->IgnoreParenImpCasts(); 4130 if (auto *DRE = dyn_cast_or_null<DeclRefExpr>(E)) { 4131 if (auto *VD = dyn_cast<VarDecl>(DRE->getDecl())) { 4132 if (auto *CED = dyn_cast<OMPCapturedExprDecl>(VD)) 4133 if (auto *ME = dyn_cast<MemberExpr>(getExprAsWritten(CED->getInit()))) 4134 return getCanonicalDecl(ME->getMemberDecl()); 4135 return getCanonicalDecl(VD); 4136 } 4137 } 4138 if (auto *ME = dyn_cast_or_null<MemberExpr>(E)) 4139 if (ME->isArrow() && isa<CXXThisExpr>(ME->getBase()->IgnoreParenImpCasts())) 4140 return getCanonicalDecl(ME->getMemberDecl()); 4141 return nullptr; 4142 } 4143 4144 bool OpenMPIterationSpaceChecker::CheckCond(Expr *S) { 4145 // Check test-expr for canonical form, save upper-bound UB, flags for 4146 // less/greater and for strict/non-strict comparison. 4147 // OpenMP [2.6] Canonical loop form. Test-expr may be one of the following: 4148 // var relational-op b 4149 // b relational-op var 4150 // 4151 if (!S) { 4152 SemaRef.Diag(DefaultLoc, diag::err_omp_loop_not_canonical_cond) << LCDecl; 4153 return true; 4154 } 4155 S = getExprAsWritten(S); 4156 SourceLocation CondLoc = S->getLocStart(); 4157 if (auto BO = dyn_cast<BinaryOperator>(S)) { 4158 if (BO->isRelationalOp()) { 4159 if (GetInitLCDecl(BO->getLHS()) == LCDecl) 4160 return SetUB(BO->getRHS(), 4161 (BO->getOpcode() == BO_LT || BO->getOpcode() == BO_LE), 4162 (BO->getOpcode() == BO_LT || BO->getOpcode() == BO_GT), 4163 BO->getSourceRange(), BO->getOperatorLoc()); 4164 if (GetInitLCDecl(BO->getRHS()) == LCDecl) 4165 return SetUB(BO->getLHS(), 4166 (BO->getOpcode() == BO_GT || BO->getOpcode() == BO_GE), 4167 (BO->getOpcode() == BO_LT || BO->getOpcode() == BO_GT), 4168 BO->getSourceRange(), BO->getOperatorLoc()); 4169 } 4170 } else if (auto CE = dyn_cast<CXXOperatorCallExpr>(S)) { 4171 if (CE->getNumArgs() == 2) { 4172 auto Op = CE->getOperator(); 4173 switch (Op) { 4174 case OO_Greater: 4175 case OO_GreaterEqual: 4176 case OO_Less: 4177 case OO_LessEqual: 4178 if (GetInitLCDecl(CE->getArg(0)) == LCDecl) 4179 return SetUB(CE->getArg(1), Op == OO_Less || Op == OO_LessEqual, 4180 Op == OO_Less || Op == OO_Greater, CE->getSourceRange(), 4181 CE->getOperatorLoc()); 4182 if (GetInitLCDecl(CE->getArg(1)) == LCDecl) 4183 return SetUB(CE->getArg(0), Op == OO_Greater || Op == OO_GreaterEqual, 4184 Op == OO_Less || Op == OO_Greater, CE->getSourceRange(), 4185 CE->getOperatorLoc()); 4186 break; 4187 default: 4188 break; 4189 } 4190 } 4191 } 4192 if (Dependent() || SemaRef.CurContext->isDependentContext()) 4193 return false; 4194 SemaRef.Diag(CondLoc, diag::err_omp_loop_not_canonical_cond) 4195 << S->getSourceRange() << LCDecl; 4196 return true; 4197 } 4198 4199 bool OpenMPIterationSpaceChecker::CheckIncRHS(Expr *RHS) { 4200 // RHS of canonical loop form increment can be: 4201 // var + incr 4202 // incr + var 4203 // var - incr 4204 // 4205 RHS = RHS->IgnoreParenImpCasts(); 4206 if (auto BO = dyn_cast<BinaryOperator>(RHS)) { 4207 if (BO->isAdditiveOp()) { 4208 bool IsAdd = BO->getOpcode() == BO_Add; 4209 if (GetInitLCDecl(BO->getLHS()) == LCDecl) 4210 return SetStep(BO->getRHS(), !IsAdd); 4211 if (IsAdd && GetInitLCDecl(BO->getRHS()) == LCDecl) 4212 return SetStep(BO->getLHS(), false); 4213 } 4214 } else if (auto CE = dyn_cast<CXXOperatorCallExpr>(RHS)) { 4215 bool IsAdd = CE->getOperator() == OO_Plus; 4216 if ((IsAdd || CE->getOperator() == OO_Minus) && CE->getNumArgs() == 2) { 4217 if (GetInitLCDecl(CE->getArg(0)) == LCDecl) 4218 return SetStep(CE->getArg(1), !IsAdd); 4219 if (IsAdd && GetInitLCDecl(CE->getArg(1)) == LCDecl) 4220 return SetStep(CE->getArg(0), false); 4221 } 4222 } 4223 if (Dependent() || SemaRef.CurContext->isDependentContext()) 4224 return false; 4225 SemaRef.Diag(RHS->getLocStart(), diag::err_omp_loop_not_canonical_incr) 4226 << RHS->getSourceRange() << LCDecl; 4227 return true; 4228 } 4229 4230 bool OpenMPIterationSpaceChecker::CheckInc(Expr *S) { 4231 // Check incr-expr for canonical loop form and return true if it 4232 // does not conform. 4233 // OpenMP [2.6] Canonical loop form. Test-expr may be one of the following: 4234 // ++var 4235 // var++ 4236 // --var 4237 // var-- 4238 // var += incr 4239 // var -= incr 4240 // var = var + incr 4241 // var = incr + var 4242 // var = var - incr 4243 // 4244 if (!S) { 4245 SemaRef.Diag(DefaultLoc, diag::err_omp_loop_not_canonical_incr) << LCDecl; 4246 return true; 4247 } 4248 if (auto *ExprTemp = dyn_cast<ExprWithCleanups>(S)) 4249 if (!ExprTemp->cleanupsHaveSideEffects()) 4250 S = ExprTemp->getSubExpr(); 4251 4252 IncrementSrcRange = S->getSourceRange(); 4253 S = S->IgnoreParens(); 4254 if (auto UO = dyn_cast<UnaryOperator>(S)) { 4255 if (UO->isIncrementDecrementOp() && 4256 GetInitLCDecl(UO->getSubExpr()) == LCDecl) 4257 return SetStep( 4258 SemaRef.ActOnIntegerConstant(UO->getLocStart(), 4259 (UO->isDecrementOp() ? -1 : 1)).get(), 4260 false); 4261 } else if (auto BO = dyn_cast<BinaryOperator>(S)) { 4262 switch (BO->getOpcode()) { 4263 case BO_AddAssign: 4264 case BO_SubAssign: 4265 if (GetInitLCDecl(BO->getLHS()) == LCDecl) 4266 return SetStep(BO->getRHS(), BO->getOpcode() == BO_SubAssign); 4267 break; 4268 case BO_Assign: 4269 if (GetInitLCDecl(BO->getLHS()) == LCDecl) 4270 return CheckIncRHS(BO->getRHS()); 4271 break; 4272 default: 4273 break; 4274 } 4275 } else if (auto CE = dyn_cast<CXXOperatorCallExpr>(S)) { 4276 switch (CE->getOperator()) { 4277 case OO_PlusPlus: 4278 case OO_MinusMinus: 4279 if (GetInitLCDecl(CE->getArg(0)) == LCDecl) 4280 return SetStep( 4281 SemaRef.ActOnIntegerConstant( 4282 CE->getLocStart(), 4283 ((CE->getOperator() == OO_MinusMinus) ? -1 : 1)).get(), 4284 false); 4285 break; 4286 case OO_PlusEqual: 4287 case OO_MinusEqual: 4288 if (GetInitLCDecl(CE->getArg(0)) == LCDecl) 4289 return SetStep(CE->getArg(1), CE->getOperator() == OO_MinusEqual); 4290 break; 4291 case OO_Equal: 4292 if (GetInitLCDecl(CE->getArg(0)) == LCDecl) 4293 return CheckIncRHS(CE->getArg(1)); 4294 break; 4295 default: 4296 break; 4297 } 4298 } 4299 if (Dependent() || SemaRef.CurContext->isDependentContext()) 4300 return false; 4301 SemaRef.Diag(S->getLocStart(), diag::err_omp_loop_not_canonical_incr) 4302 << S->getSourceRange() << LCDecl; 4303 return true; 4304 } 4305 4306 static ExprResult 4307 tryBuildCapture(Sema &SemaRef, Expr *Capture, 4308 llvm::MapVector<Expr *, DeclRefExpr *> &Captures) { 4309 if (Capture->isEvaluatable(SemaRef.Context, Expr::SE_AllowSideEffects)) 4310 return SemaRef.PerformImplicitConversion( 4311 Capture->IgnoreImpCasts(), Capture->getType(), Sema::AA_Converting, 4312 /*AllowExplicit=*/true); 4313 auto I = Captures.find(Capture); 4314 if (I != Captures.end()) 4315 return buildCapture(SemaRef, Capture, I->second); 4316 DeclRefExpr *Ref = nullptr; 4317 ExprResult Res = buildCapture(SemaRef, Capture, Ref); 4318 Captures[Capture] = Ref; 4319 return Res; 4320 } 4321 4322 /// \brief Build the expression to calculate the number of iterations. 4323 Expr *OpenMPIterationSpaceChecker::BuildNumIterations( 4324 Scope *S, const bool LimitedType, 4325 llvm::MapVector<Expr *, DeclRefExpr *> &Captures) const { 4326 ExprResult Diff; 4327 auto VarType = LCDecl->getType().getNonReferenceType(); 4328 if (VarType->isIntegerType() || VarType->isPointerType() || 4329 SemaRef.getLangOpts().CPlusPlus) { 4330 // Upper - Lower 4331 auto *UBExpr = TestIsLessOp ? UB : LB; 4332 auto *LBExpr = TestIsLessOp ? LB : UB; 4333 Expr *Upper = tryBuildCapture(SemaRef, UBExpr, Captures).get(); 4334 Expr *Lower = tryBuildCapture(SemaRef, LBExpr, Captures).get(); 4335 if (!Upper || !Lower) 4336 return nullptr; 4337 4338 Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Sub, Upper, Lower); 4339 4340 if (!Diff.isUsable() && VarType->getAsCXXRecordDecl()) { 4341 // BuildBinOp already emitted error, this one is to point user to upper 4342 // and lower bound, and to tell what is passed to 'operator-'. 4343 SemaRef.Diag(Upper->getLocStart(), diag::err_omp_loop_diff_cxx) 4344 << Upper->getSourceRange() << Lower->getSourceRange(); 4345 return nullptr; 4346 } 4347 } 4348 4349 if (!Diff.isUsable()) 4350 return nullptr; 4351 4352 // Upper - Lower [- 1] 4353 if (TestIsStrictOp) 4354 Diff = SemaRef.BuildBinOp( 4355 S, DefaultLoc, BO_Sub, Diff.get(), 4356 SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get()); 4357 if (!Diff.isUsable()) 4358 return nullptr; 4359 4360 // Upper - Lower [- 1] + Step 4361 auto NewStep = tryBuildCapture(SemaRef, Step, Captures); 4362 if (!NewStep.isUsable()) 4363 return nullptr; 4364 Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Add, Diff.get(), NewStep.get()); 4365 if (!Diff.isUsable()) 4366 return nullptr; 4367 4368 // Parentheses (for dumping/debugging purposes only). 4369 Diff = SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, Diff.get()); 4370 if (!Diff.isUsable()) 4371 return nullptr; 4372 4373 // (Upper - Lower [- 1] + Step) / Step 4374 Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Div, Diff.get(), NewStep.get()); 4375 if (!Diff.isUsable()) 4376 return nullptr; 4377 4378 // OpenMP runtime requires 32-bit or 64-bit loop variables. 4379 QualType Type = Diff.get()->getType(); 4380 auto &C = SemaRef.Context; 4381 bool UseVarType = VarType->hasIntegerRepresentation() && 4382 C.getTypeSize(Type) > C.getTypeSize(VarType); 4383 if (!Type->isIntegerType() || UseVarType) { 4384 unsigned NewSize = 4385 UseVarType ? C.getTypeSize(VarType) : C.getTypeSize(Type); 4386 bool IsSigned = UseVarType ? VarType->hasSignedIntegerRepresentation() 4387 : Type->hasSignedIntegerRepresentation(); 4388 Type = C.getIntTypeForBitwidth(NewSize, IsSigned); 4389 if (!SemaRef.Context.hasSameType(Diff.get()->getType(), Type)) { 4390 Diff = SemaRef.PerformImplicitConversion( 4391 Diff.get(), Type, Sema::AA_Converting, /*AllowExplicit=*/true); 4392 if (!Diff.isUsable()) 4393 return nullptr; 4394 } 4395 } 4396 if (LimitedType) { 4397 unsigned NewSize = (C.getTypeSize(Type) > 32) ? 64 : 32; 4398 if (NewSize != C.getTypeSize(Type)) { 4399 if (NewSize < C.getTypeSize(Type)) { 4400 assert(NewSize == 64 && "incorrect loop var size"); 4401 SemaRef.Diag(DefaultLoc, diag::warn_omp_loop_64_bit_var) 4402 << InitSrcRange << ConditionSrcRange; 4403 } 4404 QualType NewType = C.getIntTypeForBitwidth( 4405 NewSize, Type->hasSignedIntegerRepresentation() || 4406 C.getTypeSize(Type) < NewSize); 4407 if (!SemaRef.Context.hasSameType(Diff.get()->getType(), NewType)) { 4408 Diff = SemaRef.PerformImplicitConversion(Diff.get(), NewType, 4409 Sema::AA_Converting, true); 4410 if (!Diff.isUsable()) 4411 return nullptr; 4412 } 4413 } 4414 } 4415 4416 return Diff.get(); 4417 } 4418 4419 Expr *OpenMPIterationSpaceChecker::BuildPreCond( 4420 Scope *S, Expr *Cond, 4421 llvm::MapVector<Expr *, DeclRefExpr *> &Captures) const { 4422 // Try to build LB <op> UB, where <op> is <, >, <=, or >=. 4423 bool Suppress = SemaRef.getDiagnostics().getSuppressAllDiagnostics(); 4424 SemaRef.getDiagnostics().setSuppressAllDiagnostics(/*Val=*/true); 4425 4426 auto NewLB = tryBuildCapture(SemaRef, LB, Captures); 4427 auto NewUB = tryBuildCapture(SemaRef, UB, Captures); 4428 if (!NewLB.isUsable() || !NewUB.isUsable()) 4429 return nullptr; 4430 4431 auto CondExpr = SemaRef.BuildBinOp( 4432 S, DefaultLoc, TestIsLessOp ? (TestIsStrictOp ? BO_LT : BO_LE) 4433 : (TestIsStrictOp ? BO_GT : BO_GE), 4434 NewLB.get(), NewUB.get()); 4435 if (CondExpr.isUsable()) { 4436 if (!SemaRef.Context.hasSameUnqualifiedType(CondExpr.get()->getType(), 4437 SemaRef.Context.BoolTy)) 4438 CondExpr = SemaRef.PerformImplicitConversion( 4439 CondExpr.get(), SemaRef.Context.BoolTy, /*Action=*/Sema::AA_Casting, 4440 /*AllowExplicit=*/true); 4441 } 4442 SemaRef.getDiagnostics().setSuppressAllDiagnostics(Suppress); 4443 // Otherwise use original loop conditon and evaluate it in runtime. 4444 return CondExpr.isUsable() ? CondExpr.get() : Cond; 4445 } 4446 4447 /// \brief Build reference expression to the counter be used for codegen. 4448 DeclRefExpr *OpenMPIterationSpaceChecker::BuildCounterVar( 4449 llvm::MapVector<Expr *, DeclRefExpr *> &Captures, DSAStackTy &DSA) const { 4450 auto *VD = dyn_cast<VarDecl>(LCDecl); 4451 if (!VD) { 4452 VD = SemaRef.IsOpenMPCapturedDecl(LCDecl); 4453 auto *Ref = buildDeclRefExpr( 4454 SemaRef, VD, VD->getType().getNonReferenceType(), DefaultLoc); 4455 DSAStackTy::DSAVarData Data = DSA.getTopDSA(LCDecl, /*FromParent=*/false); 4456 // If the loop control decl is explicitly marked as private, do not mark it 4457 // as captured again. 4458 if (!isOpenMPPrivate(Data.CKind) || !Data.RefExpr) 4459 Captures.insert(std::make_pair(LCRef, Ref)); 4460 return Ref; 4461 } 4462 return buildDeclRefExpr(SemaRef, VD, VD->getType().getNonReferenceType(), 4463 DefaultLoc); 4464 } 4465 4466 Expr *OpenMPIterationSpaceChecker::BuildPrivateCounterVar() const { 4467 if (LCDecl && !LCDecl->isInvalidDecl()) { 4468 auto Type = LCDecl->getType().getNonReferenceType(); 4469 auto *PrivateVar = 4470 buildVarDecl(SemaRef, DefaultLoc, Type, LCDecl->getName(), 4471 LCDecl->hasAttrs() ? &LCDecl->getAttrs() : nullptr); 4472 if (PrivateVar->isInvalidDecl()) 4473 return nullptr; 4474 return buildDeclRefExpr(SemaRef, PrivateVar, Type, DefaultLoc); 4475 } 4476 return nullptr; 4477 } 4478 4479 /// \brief Build initization of the counter be used for codegen. 4480 Expr *OpenMPIterationSpaceChecker::BuildCounterInit() const { return LB; } 4481 4482 /// \brief Build step of the counter be used for codegen. 4483 Expr *OpenMPIterationSpaceChecker::BuildCounterStep() const { return Step; } 4484 4485 /// \brief Iteration space of a single for loop. 4486 struct LoopIterationSpace final { 4487 /// \brief Condition of the loop. 4488 Expr *PreCond = nullptr; 4489 /// \brief This expression calculates the number of iterations in the loop. 4490 /// It is always possible to calculate it before starting the loop. 4491 Expr *NumIterations = nullptr; 4492 /// \brief The loop counter variable. 4493 Expr *CounterVar = nullptr; 4494 /// \brief Private loop counter variable. 4495 Expr *PrivateCounterVar = nullptr; 4496 /// \brief This is initializer for the initial value of #CounterVar. 4497 Expr *CounterInit = nullptr; 4498 /// \brief This is step for the #CounterVar used to generate its update: 4499 /// #CounterVar = #CounterInit + #CounterStep * CurrentIteration. 4500 Expr *CounterStep = nullptr; 4501 /// \brief Should step be subtracted? 4502 bool Subtract = false; 4503 /// \brief Source range of the loop init. 4504 SourceRange InitSrcRange; 4505 /// \brief Source range of the loop condition. 4506 SourceRange CondSrcRange; 4507 /// \brief Source range of the loop increment. 4508 SourceRange IncSrcRange; 4509 }; 4510 4511 } // namespace 4512 4513 void Sema::ActOnOpenMPLoopInitialization(SourceLocation ForLoc, Stmt *Init) { 4514 assert(getLangOpts().OpenMP && "OpenMP is not active."); 4515 assert(Init && "Expected loop in canonical form."); 4516 unsigned AssociatedLoops = DSAStack->getAssociatedLoops(); 4517 if (AssociatedLoops > 0 && 4518 isOpenMPLoopDirective(DSAStack->getCurrentDirective())) { 4519 OpenMPIterationSpaceChecker ISC(*this, ForLoc); 4520 if (!ISC.CheckInit(Init, /*EmitDiags=*/false)) { 4521 if (auto *D = ISC.GetLoopDecl()) { 4522 auto *VD = dyn_cast<VarDecl>(D); 4523 if (!VD) { 4524 if (auto *Private = IsOpenMPCapturedDecl(D)) 4525 VD = Private; 4526 else { 4527 auto *Ref = buildCapture(*this, D, ISC.GetLoopDeclRefExpr(), 4528 /*WithInit=*/false); 4529 VD = cast<VarDecl>(Ref->getDecl()); 4530 } 4531 } 4532 DSAStack->addLoopControlVariable(D, VD); 4533 } 4534 } 4535 DSAStack->setAssociatedLoops(AssociatedLoops - 1); 4536 } 4537 } 4538 4539 /// \brief Called on a for stmt to check and extract its iteration space 4540 /// for further processing (such as collapsing). 4541 static bool CheckOpenMPIterationSpace( 4542 OpenMPDirectiveKind DKind, Stmt *S, Sema &SemaRef, DSAStackTy &DSA, 4543 unsigned CurrentNestedLoopCount, unsigned NestedLoopCount, 4544 Expr *CollapseLoopCountExpr, Expr *OrderedLoopCountExpr, 4545 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA, 4546 LoopIterationSpace &ResultIterSpace, 4547 llvm::MapVector<Expr *, DeclRefExpr *> &Captures) { 4548 // OpenMP [2.6, Canonical Loop Form] 4549 // for (init-expr; test-expr; incr-expr) structured-block 4550 auto For = dyn_cast_or_null<ForStmt>(S); 4551 if (!For) { 4552 SemaRef.Diag(S->getLocStart(), diag::err_omp_not_for) 4553 << (CollapseLoopCountExpr != nullptr || OrderedLoopCountExpr != nullptr) 4554 << getOpenMPDirectiveName(DKind) << NestedLoopCount 4555 << (CurrentNestedLoopCount > 0) << CurrentNestedLoopCount; 4556 if (NestedLoopCount > 1) { 4557 if (CollapseLoopCountExpr && OrderedLoopCountExpr) 4558 SemaRef.Diag(DSA.getConstructLoc(), 4559 diag::note_omp_collapse_ordered_expr) 4560 << 2 << CollapseLoopCountExpr->getSourceRange() 4561 << OrderedLoopCountExpr->getSourceRange(); 4562 else if (CollapseLoopCountExpr) 4563 SemaRef.Diag(CollapseLoopCountExpr->getExprLoc(), 4564 diag::note_omp_collapse_ordered_expr) 4565 << 0 << CollapseLoopCountExpr->getSourceRange(); 4566 else 4567 SemaRef.Diag(OrderedLoopCountExpr->getExprLoc(), 4568 diag::note_omp_collapse_ordered_expr) 4569 << 1 << OrderedLoopCountExpr->getSourceRange(); 4570 } 4571 return true; 4572 } 4573 assert(For->getBody()); 4574 4575 OpenMPIterationSpaceChecker ISC(SemaRef, For->getForLoc()); 4576 4577 // Check init. 4578 auto Init = For->getInit(); 4579 if (ISC.CheckInit(Init)) 4580 return true; 4581 4582 bool HasErrors = false; 4583 4584 // Check loop variable's type. 4585 if (auto *LCDecl = ISC.GetLoopDecl()) { 4586 auto *LoopDeclRefExpr = ISC.GetLoopDeclRefExpr(); 4587 4588 // OpenMP [2.6, Canonical Loop Form] 4589 // Var is one of the following: 4590 // A variable of signed or unsigned integer type. 4591 // For C++, a variable of a random access iterator type. 4592 // For C, a variable of a pointer type. 4593 auto VarType = LCDecl->getType().getNonReferenceType(); 4594 if (!VarType->isDependentType() && !VarType->isIntegerType() && 4595 !VarType->isPointerType() && 4596 !(SemaRef.getLangOpts().CPlusPlus && VarType->isOverloadableType())) { 4597 SemaRef.Diag(Init->getLocStart(), diag::err_omp_loop_variable_type) 4598 << SemaRef.getLangOpts().CPlusPlus; 4599 HasErrors = true; 4600 } 4601 4602 // OpenMP, 2.14.1.1 Data-sharing Attribute Rules for Variables Referenced in 4603 // a Construct 4604 // The loop iteration variable(s) in the associated for-loop(s) of a for or 4605 // parallel for construct is (are) private. 4606 // The loop iteration variable in the associated for-loop of a simd 4607 // construct with just one associated for-loop is linear with a 4608 // constant-linear-step that is the increment of the associated for-loop. 4609 // Exclude loop var from the list of variables with implicitly defined data 4610 // sharing attributes. 4611 VarsWithImplicitDSA.erase(LCDecl); 4612 4613 // OpenMP [2.14.1.1, Data-sharing Attribute Rules for Variables Referenced 4614 // in a Construct, C/C++]. 4615 // The loop iteration variable in the associated for-loop of a simd 4616 // construct with just one associated for-loop may be listed in a linear 4617 // clause with a constant-linear-step that is the increment of the 4618 // associated for-loop. 4619 // The loop iteration variable(s) in the associated for-loop(s) of a for or 4620 // parallel for construct may be listed in a private or lastprivate clause. 4621 DSAStackTy::DSAVarData DVar = DSA.getTopDSA(LCDecl, false); 4622 // If LoopVarRefExpr is nullptr it means the corresponding loop variable is 4623 // declared in the loop and it is predetermined as a private. 4624 auto PredeterminedCKind = 4625 isOpenMPSimdDirective(DKind) 4626 ? ((NestedLoopCount == 1) ? OMPC_linear : OMPC_lastprivate) 4627 : OMPC_private; 4628 if (((isOpenMPSimdDirective(DKind) && DVar.CKind != OMPC_unknown && 4629 DVar.CKind != PredeterminedCKind) || 4630 ((isOpenMPWorksharingDirective(DKind) || DKind == OMPD_taskloop || 4631 isOpenMPDistributeDirective(DKind)) && 4632 !isOpenMPSimdDirective(DKind) && DVar.CKind != OMPC_unknown && 4633 DVar.CKind != OMPC_private && DVar.CKind != OMPC_lastprivate)) && 4634 (DVar.CKind != OMPC_private || DVar.RefExpr != nullptr)) { 4635 SemaRef.Diag(Init->getLocStart(), diag::err_omp_loop_var_dsa) 4636 << getOpenMPClauseName(DVar.CKind) << getOpenMPDirectiveName(DKind) 4637 << getOpenMPClauseName(PredeterminedCKind); 4638 if (DVar.RefExpr == nullptr) 4639 DVar.CKind = PredeterminedCKind; 4640 ReportOriginalDSA(SemaRef, &DSA, LCDecl, DVar, /*IsLoopIterVar=*/true); 4641 HasErrors = true; 4642 } else if (LoopDeclRefExpr != nullptr) { 4643 // Make the loop iteration variable private (for worksharing constructs), 4644 // linear (for simd directives with the only one associated loop) or 4645 // lastprivate (for simd directives with several collapsed or ordered 4646 // loops). 4647 if (DVar.CKind == OMPC_unknown) 4648 DVar = DSA.hasDSA(LCDecl, isOpenMPPrivate, 4649 [](OpenMPDirectiveKind) -> bool { return true; }, 4650 /*FromParent=*/false); 4651 DSA.addDSA(LCDecl, LoopDeclRefExpr, PredeterminedCKind); 4652 } 4653 4654 assert(isOpenMPLoopDirective(DKind) && "DSA for non-loop vars"); 4655 4656 // Check test-expr. 4657 HasErrors |= ISC.CheckCond(For->getCond()); 4658 4659 // Check incr-expr. 4660 HasErrors |= ISC.CheckInc(For->getInc()); 4661 } 4662 4663 if (ISC.Dependent() || SemaRef.CurContext->isDependentContext() || HasErrors) 4664 return HasErrors; 4665 4666 // Build the loop's iteration space representation. 4667 ResultIterSpace.PreCond = 4668 ISC.BuildPreCond(DSA.getCurScope(), For->getCond(), Captures); 4669 ResultIterSpace.NumIterations = ISC.BuildNumIterations( 4670 DSA.getCurScope(), 4671 (isOpenMPWorksharingDirective(DKind) || 4672 isOpenMPTaskLoopDirective(DKind) || isOpenMPDistributeDirective(DKind)), 4673 Captures); 4674 ResultIterSpace.CounterVar = ISC.BuildCounterVar(Captures, DSA); 4675 ResultIterSpace.PrivateCounterVar = ISC.BuildPrivateCounterVar(); 4676 ResultIterSpace.CounterInit = ISC.BuildCounterInit(); 4677 ResultIterSpace.CounterStep = ISC.BuildCounterStep(); 4678 ResultIterSpace.InitSrcRange = ISC.GetInitSrcRange(); 4679 ResultIterSpace.CondSrcRange = ISC.GetConditionSrcRange(); 4680 ResultIterSpace.IncSrcRange = ISC.GetIncrementSrcRange(); 4681 ResultIterSpace.Subtract = ISC.ShouldSubtractStep(); 4682 4683 HasErrors |= (ResultIterSpace.PreCond == nullptr || 4684 ResultIterSpace.NumIterations == nullptr || 4685 ResultIterSpace.CounterVar == nullptr || 4686 ResultIterSpace.PrivateCounterVar == nullptr || 4687 ResultIterSpace.CounterInit == nullptr || 4688 ResultIterSpace.CounterStep == nullptr); 4689 4690 return HasErrors; 4691 } 4692 4693 /// \brief Build 'VarRef = Start. 4694 static ExprResult 4695 BuildCounterInit(Sema &SemaRef, Scope *S, SourceLocation Loc, ExprResult VarRef, 4696 ExprResult Start, 4697 llvm::MapVector<Expr *, DeclRefExpr *> &Captures) { 4698 // Build 'VarRef = Start. 4699 auto NewStart = tryBuildCapture(SemaRef, Start.get(), Captures); 4700 if (!NewStart.isUsable()) 4701 return ExprError(); 4702 if (!SemaRef.Context.hasSameType(NewStart.get()->getType(), 4703 VarRef.get()->getType())) { 4704 NewStart = SemaRef.PerformImplicitConversion( 4705 NewStart.get(), VarRef.get()->getType(), Sema::AA_Converting, 4706 /*AllowExplicit=*/true); 4707 if (!NewStart.isUsable()) 4708 return ExprError(); 4709 } 4710 4711 auto Init = 4712 SemaRef.BuildBinOp(S, Loc, BO_Assign, VarRef.get(), NewStart.get()); 4713 return Init; 4714 } 4715 4716 /// \brief Build 'VarRef = Start + Iter * Step'. 4717 static ExprResult 4718 BuildCounterUpdate(Sema &SemaRef, Scope *S, SourceLocation Loc, 4719 ExprResult VarRef, ExprResult Start, ExprResult Iter, 4720 ExprResult Step, bool Subtract, 4721 llvm::MapVector<Expr *, DeclRefExpr *> *Captures = nullptr) { 4722 // Add parentheses (for debugging purposes only). 4723 Iter = SemaRef.ActOnParenExpr(Loc, Loc, Iter.get()); 4724 if (!VarRef.isUsable() || !Start.isUsable() || !Iter.isUsable() || 4725 !Step.isUsable()) 4726 return ExprError(); 4727 4728 ExprResult NewStep = Step; 4729 if (Captures) 4730 NewStep = tryBuildCapture(SemaRef, Step.get(), *Captures); 4731 if (NewStep.isInvalid()) 4732 return ExprError(); 4733 ExprResult Update = 4734 SemaRef.BuildBinOp(S, Loc, BO_Mul, Iter.get(), NewStep.get()); 4735 if (!Update.isUsable()) 4736 return ExprError(); 4737 4738 // Try to build 'VarRef = Start, VarRef (+|-)= Iter * Step' or 4739 // 'VarRef = Start (+|-) Iter * Step'. 4740 ExprResult NewStart = Start; 4741 if (Captures) 4742 NewStart = tryBuildCapture(SemaRef, Start.get(), *Captures); 4743 if (NewStart.isInvalid()) 4744 return ExprError(); 4745 4746 // First attempt: try to build 'VarRef = Start, VarRef += Iter * Step'. 4747 ExprResult SavedUpdate = Update; 4748 ExprResult UpdateVal; 4749 if (VarRef.get()->getType()->isOverloadableType() || 4750 NewStart.get()->getType()->isOverloadableType() || 4751 Update.get()->getType()->isOverloadableType()) { 4752 bool Suppress = SemaRef.getDiagnostics().getSuppressAllDiagnostics(); 4753 SemaRef.getDiagnostics().setSuppressAllDiagnostics(/*Val=*/true); 4754 Update = 4755 SemaRef.BuildBinOp(S, Loc, BO_Assign, VarRef.get(), NewStart.get()); 4756 if (Update.isUsable()) { 4757 UpdateVal = 4758 SemaRef.BuildBinOp(S, Loc, Subtract ? BO_SubAssign : BO_AddAssign, 4759 VarRef.get(), SavedUpdate.get()); 4760 if (UpdateVal.isUsable()) { 4761 Update = SemaRef.CreateBuiltinBinOp(Loc, BO_Comma, Update.get(), 4762 UpdateVal.get()); 4763 } 4764 } 4765 SemaRef.getDiagnostics().setSuppressAllDiagnostics(Suppress); 4766 } 4767 4768 // Second attempt: try to build 'VarRef = Start (+|-) Iter * Step'. 4769 if (!Update.isUsable() || !UpdateVal.isUsable()) { 4770 Update = SemaRef.BuildBinOp(S, Loc, Subtract ? BO_Sub : BO_Add, 4771 NewStart.get(), SavedUpdate.get()); 4772 if (!Update.isUsable()) 4773 return ExprError(); 4774 4775 if (!SemaRef.Context.hasSameType(Update.get()->getType(), 4776 VarRef.get()->getType())) { 4777 Update = SemaRef.PerformImplicitConversion( 4778 Update.get(), VarRef.get()->getType(), Sema::AA_Converting, true); 4779 if (!Update.isUsable()) 4780 return ExprError(); 4781 } 4782 4783 Update = SemaRef.BuildBinOp(S, Loc, BO_Assign, VarRef.get(), Update.get()); 4784 } 4785 return Update; 4786 } 4787 4788 /// \brief Convert integer expression \a E to make it have at least \a Bits 4789 /// bits. 4790 static ExprResult WidenIterationCount(unsigned Bits, Expr *E, 4791 Sema &SemaRef) { 4792 if (E == nullptr) 4793 return ExprError(); 4794 auto &C = SemaRef.Context; 4795 QualType OldType = E->getType(); 4796 unsigned HasBits = C.getTypeSize(OldType); 4797 if (HasBits >= Bits) 4798 return ExprResult(E); 4799 // OK to convert to signed, because new type has more bits than old. 4800 QualType NewType = C.getIntTypeForBitwidth(Bits, /* Signed */ true); 4801 return SemaRef.PerformImplicitConversion(E, NewType, Sema::AA_Converting, 4802 true); 4803 } 4804 4805 /// \brief Check if the given expression \a E is a constant integer that fits 4806 /// into \a Bits bits. 4807 static bool FitsInto(unsigned Bits, bool Signed, Expr *E, Sema &SemaRef) { 4808 if (E == nullptr) 4809 return false; 4810 llvm::APSInt Result; 4811 if (E->isIntegerConstantExpr(Result, SemaRef.Context)) 4812 return Signed ? Result.isSignedIntN(Bits) : Result.isIntN(Bits); 4813 return false; 4814 } 4815 4816 /// Build preinits statement for the given declarations. 4817 static Stmt *buildPreInits(ASTContext &Context, 4818 SmallVectorImpl<Decl *> &PreInits) { 4819 if (!PreInits.empty()) { 4820 return new (Context) DeclStmt( 4821 DeclGroupRef::Create(Context, PreInits.begin(), PreInits.size()), 4822 SourceLocation(), SourceLocation()); 4823 } 4824 return nullptr; 4825 } 4826 4827 /// Build preinits statement for the given declarations. 4828 static Stmt *buildPreInits(ASTContext &Context, 4829 llvm::MapVector<Expr *, DeclRefExpr *> &Captures) { 4830 if (!Captures.empty()) { 4831 SmallVector<Decl *, 16> PreInits; 4832 for (auto &Pair : Captures) 4833 PreInits.push_back(Pair.second->getDecl()); 4834 return buildPreInits(Context, PreInits); 4835 } 4836 return nullptr; 4837 } 4838 4839 /// Build postupdate expression for the given list of postupdates expressions. 4840 static Expr *buildPostUpdate(Sema &S, ArrayRef<Expr *> PostUpdates) { 4841 Expr *PostUpdate = nullptr; 4842 if (!PostUpdates.empty()) { 4843 for (auto *E : PostUpdates) { 4844 Expr *ConvE = S.BuildCStyleCastExpr( 4845 E->getExprLoc(), 4846 S.Context.getTrivialTypeSourceInfo(S.Context.VoidTy), 4847 E->getExprLoc(), E) 4848 .get(); 4849 PostUpdate = PostUpdate 4850 ? S.CreateBuiltinBinOp(ConvE->getExprLoc(), BO_Comma, 4851 PostUpdate, ConvE) 4852 .get() 4853 : ConvE; 4854 } 4855 } 4856 return PostUpdate; 4857 } 4858 4859 /// \brief Called on a for stmt to check itself and nested loops (if any). 4860 /// \return Returns 0 if one of the collapsed stmts is not canonical for loop, 4861 /// number of collapsed loops otherwise. 4862 static unsigned 4863 CheckOpenMPLoop(OpenMPDirectiveKind DKind, Expr *CollapseLoopCountExpr, 4864 Expr *OrderedLoopCountExpr, Stmt *AStmt, Sema &SemaRef, 4865 DSAStackTy &DSA, 4866 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA, 4867 OMPLoopDirective::HelperExprs &Built) { 4868 unsigned NestedLoopCount = 1; 4869 if (CollapseLoopCountExpr) { 4870 // Found 'collapse' clause - calculate collapse number. 4871 llvm::APSInt Result; 4872 if (CollapseLoopCountExpr->EvaluateAsInt(Result, SemaRef.getASTContext())) 4873 NestedLoopCount = Result.getLimitedValue(); 4874 } 4875 if (OrderedLoopCountExpr) { 4876 // Found 'ordered' clause - calculate collapse number. 4877 llvm::APSInt Result; 4878 if (OrderedLoopCountExpr->EvaluateAsInt(Result, SemaRef.getASTContext())) { 4879 if (Result.getLimitedValue() < NestedLoopCount) { 4880 SemaRef.Diag(OrderedLoopCountExpr->getExprLoc(), 4881 diag::err_omp_wrong_ordered_loop_count) 4882 << OrderedLoopCountExpr->getSourceRange(); 4883 SemaRef.Diag(CollapseLoopCountExpr->getExprLoc(), 4884 diag::note_collapse_loop_count) 4885 << CollapseLoopCountExpr->getSourceRange(); 4886 } 4887 NestedLoopCount = Result.getLimitedValue(); 4888 } 4889 } 4890 // This is helper routine for loop directives (e.g., 'for', 'simd', 4891 // 'for simd', etc.). 4892 llvm::MapVector<Expr *, DeclRefExpr *> Captures; 4893 SmallVector<LoopIterationSpace, 4> IterSpaces; 4894 IterSpaces.resize(NestedLoopCount); 4895 Stmt *CurStmt = AStmt->IgnoreContainers(/* IgnoreCaptured */ true); 4896 for (unsigned Cnt = 0; Cnt < NestedLoopCount; ++Cnt) { 4897 if (CheckOpenMPIterationSpace(DKind, CurStmt, SemaRef, DSA, Cnt, 4898 NestedLoopCount, CollapseLoopCountExpr, 4899 OrderedLoopCountExpr, VarsWithImplicitDSA, 4900 IterSpaces[Cnt], Captures)) 4901 return 0; 4902 // Move on to the next nested for loop, or to the loop body. 4903 // OpenMP [2.8.1, simd construct, Restrictions] 4904 // All loops associated with the construct must be perfectly nested; that 4905 // is, there must be no intervening code nor any OpenMP directive between 4906 // any two loops. 4907 CurStmt = cast<ForStmt>(CurStmt)->getBody()->IgnoreContainers(); 4908 } 4909 4910 Built.clear(/* size */ NestedLoopCount); 4911 4912 if (SemaRef.CurContext->isDependentContext()) 4913 return NestedLoopCount; 4914 4915 // An example of what is generated for the following code: 4916 // 4917 // #pragma omp simd collapse(2) ordered(2) 4918 // for (i = 0; i < NI; ++i) 4919 // for (k = 0; k < NK; ++k) 4920 // for (j = J0; j < NJ; j+=2) { 4921 // <loop body> 4922 // } 4923 // 4924 // We generate the code below. 4925 // Note: the loop body may be outlined in CodeGen. 4926 // Note: some counters may be C++ classes, operator- is used to find number of 4927 // iterations and operator+= to calculate counter value. 4928 // Note: decltype(NumIterations) must be integer type (in 'omp for', only i32 4929 // or i64 is currently supported). 4930 // 4931 // #define NumIterations (NI * ((NJ - J0 - 1 + 2) / 2)) 4932 // for (int[32|64]_t IV = 0; IV < NumIterations; ++IV ) { 4933 // .local.i = IV / ((NJ - J0 - 1 + 2) / 2); 4934 // .local.j = J0 + (IV % ((NJ - J0 - 1 + 2) / 2)) * 2; 4935 // // similar updates for vars in clauses (e.g. 'linear') 4936 // <loop body (using local i and j)> 4937 // } 4938 // i = NI; // assign final values of counters 4939 // j = NJ; 4940 // 4941 4942 // Last iteration number is (I1 * I2 * ... In) - 1, where I1, I2 ... In are 4943 // the iteration counts of the collapsed for loops. 4944 // Precondition tests if there is at least one iteration (all conditions are 4945 // true). 4946 auto PreCond = ExprResult(IterSpaces[0].PreCond); 4947 auto N0 = IterSpaces[0].NumIterations; 4948 ExprResult LastIteration32 = WidenIterationCount( 4949 32 /* Bits */, SemaRef.PerformImplicitConversion( 4950 N0->IgnoreImpCasts(), N0->getType(), 4951 Sema::AA_Converting, /*AllowExplicit=*/true) 4952 .get(), 4953 SemaRef); 4954 ExprResult LastIteration64 = WidenIterationCount( 4955 64 /* Bits */, SemaRef.PerformImplicitConversion( 4956 N0->IgnoreImpCasts(), N0->getType(), 4957 Sema::AA_Converting, /*AllowExplicit=*/true) 4958 .get(), 4959 SemaRef); 4960 4961 if (!LastIteration32.isUsable() || !LastIteration64.isUsable()) 4962 return NestedLoopCount; 4963 4964 auto &C = SemaRef.Context; 4965 bool AllCountsNeedLessThan32Bits = C.getTypeSize(N0->getType()) < 32; 4966 4967 Scope *CurScope = DSA.getCurScope(); 4968 for (unsigned Cnt = 1; Cnt < NestedLoopCount; ++Cnt) { 4969 if (PreCond.isUsable()) { 4970 PreCond = SemaRef.BuildBinOp(CurScope, SourceLocation(), BO_LAnd, 4971 PreCond.get(), IterSpaces[Cnt].PreCond); 4972 } 4973 auto N = IterSpaces[Cnt].NumIterations; 4974 AllCountsNeedLessThan32Bits &= C.getTypeSize(N->getType()) < 32; 4975 if (LastIteration32.isUsable()) 4976 LastIteration32 = SemaRef.BuildBinOp( 4977 CurScope, SourceLocation(), BO_Mul, LastIteration32.get(), 4978 SemaRef.PerformImplicitConversion(N->IgnoreImpCasts(), N->getType(), 4979 Sema::AA_Converting, 4980 /*AllowExplicit=*/true) 4981 .get()); 4982 if (LastIteration64.isUsable()) 4983 LastIteration64 = SemaRef.BuildBinOp( 4984 CurScope, SourceLocation(), BO_Mul, LastIteration64.get(), 4985 SemaRef.PerformImplicitConversion(N->IgnoreImpCasts(), N->getType(), 4986 Sema::AA_Converting, 4987 /*AllowExplicit=*/true) 4988 .get()); 4989 } 4990 4991 // Choose either the 32-bit or 64-bit version. 4992 ExprResult LastIteration = LastIteration64; 4993 if (LastIteration32.isUsable() && 4994 C.getTypeSize(LastIteration32.get()->getType()) == 32 && 4995 (AllCountsNeedLessThan32Bits || NestedLoopCount == 1 || 4996 FitsInto( 4997 32 /* Bits */, 4998 LastIteration32.get()->getType()->hasSignedIntegerRepresentation(), 4999 LastIteration64.get(), SemaRef))) 5000 LastIteration = LastIteration32; 5001 QualType VType = LastIteration.get()->getType(); 5002 QualType RealVType = VType; 5003 QualType StrideVType = VType; 5004 if (isOpenMPTaskLoopDirective(DKind)) { 5005 VType = 5006 SemaRef.Context.getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/0); 5007 StrideVType = 5008 SemaRef.Context.getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/1); 5009 } 5010 5011 if (!LastIteration.isUsable()) 5012 return 0; 5013 5014 // Save the number of iterations. 5015 ExprResult NumIterations = LastIteration; 5016 { 5017 LastIteration = SemaRef.BuildBinOp( 5018 CurScope, SourceLocation(), BO_Sub, LastIteration.get(), 5019 SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get()); 5020 if (!LastIteration.isUsable()) 5021 return 0; 5022 } 5023 5024 // Calculate the last iteration number beforehand instead of doing this on 5025 // each iteration. Do not do this if the number of iterations may be kfold-ed. 5026 llvm::APSInt Result; 5027 bool IsConstant = 5028 LastIteration.get()->isIntegerConstantExpr(Result, SemaRef.Context); 5029 ExprResult CalcLastIteration; 5030 if (!IsConstant) { 5031 ExprResult SaveRef = 5032 tryBuildCapture(SemaRef, LastIteration.get(), Captures); 5033 LastIteration = SaveRef; 5034 5035 // Prepare SaveRef + 1. 5036 NumIterations = SemaRef.BuildBinOp( 5037 CurScope, SourceLocation(), BO_Add, SaveRef.get(), 5038 SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get()); 5039 if (!NumIterations.isUsable()) 5040 return 0; 5041 } 5042 5043 SourceLocation InitLoc = IterSpaces[0].InitSrcRange.getBegin(); 5044 5045 // Build variables passed into runtime, nesessary for worksharing directives. 5046 ExprResult LB, UB, IL, ST, EUB, PrevLB, PrevUB; 5047 if (isOpenMPWorksharingDirective(DKind) || isOpenMPTaskLoopDirective(DKind) || 5048 isOpenMPDistributeDirective(DKind)) { 5049 // Lower bound variable, initialized with zero. 5050 VarDecl *LBDecl = buildVarDecl(SemaRef, InitLoc, VType, ".omp.lb"); 5051 LB = buildDeclRefExpr(SemaRef, LBDecl, VType, InitLoc); 5052 SemaRef.AddInitializerToDecl( 5053 LBDecl, SemaRef.ActOnIntegerConstant(InitLoc, 0).get(), 5054 /*DirectInit*/ false, /*TypeMayContainAuto*/ false); 5055 5056 // Upper bound variable, initialized with last iteration number. 5057 VarDecl *UBDecl = buildVarDecl(SemaRef, InitLoc, VType, ".omp.ub"); 5058 UB = buildDeclRefExpr(SemaRef, UBDecl, VType, InitLoc); 5059 SemaRef.AddInitializerToDecl(UBDecl, LastIteration.get(), 5060 /*DirectInit*/ false, 5061 /*TypeMayContainAuto*/ false); 5062 5063 // A 32-bit variable-flag where runtime returns 1 for the last iteration. 5064 // This will be used to implement clause 'lastprivate'. 5065 QualType Int32Ty = SemaRef.Context.getIntTypeForBitwidth(32, true); 5066 VarDecl *ILDecl = buildVarDecl(SemaRef, InitLoc, Int32Ty, ".omp.is_last"); 5067 IL = buildDeclRefExpr(SemaRef, ILDecl, Int32Ty, InitLoc); 5068 SemaRef.AddInitializerToDecl( 5069 ILDecl, SemaRef.ActOnIntegerConstant(InitLoc, 0).get(), 5070 /*DirectInit*/ false, /*TypeMayContainAuto*/ false); 5071 5072 // Stride variable returned by runtime (we initialize it to 1 by default). 5073 VarDecl *STDecl = 5074 buildVarDecl(SemaRef, InitLoc, StrideVType, ".omp.stride"); 5075 ST = buildDeclRefExpr(SemaRef, STDecl, StrideVType, InitLoc); 5076 SemaRef.AddInitializerToDecl( 5077 STDecl, SemaRef.ActOnIntegerConstant(InitLoc, 1).get(), 5078 /*DirectInit*/ false, /*TypeMayContainAuto*/ false); 5079 5080 // Build expression: UB = min(UB, LastIteration) 5081 // It is nesessary for CodeGen of directives with static scheduling. 5082 ExprResult IsUBGreater = SemaRef.BuildBinOp(CurScope, InitLoc, BO_GT, 5083 UB.get(), LastIteration.get()); 5084 ExprResult CondOp = SemaRef.ActOnConditionalOp( 5085 InitLoc, InitLoc, IsUBGreater.get(), LastIteration.get(), UB.get()); 5086 EUB = SemaRef.BuildBinOp(CurScope, InitLoc, BO_Assign, UB.get(), 5087 CondOp.get()); 5088 EUB = SemaRef.ActOnFinishFullExpr(EUB.get()); 5089 5090 // If we have a combined directive that combines 'distribute', 'for' or 5091 // 'simd' we need to be able to access the bounds of the schedule of the 5092 // enclosing region. E.g. in 'distribute parallel for' the bounds obtained 5093 // by scheduling 'distribute' have to be passed to the schedule of 'for'. 5094 if (isOpenMPLoopBoundSharingDirective(DKind)) { 5095 auto *CD = cast<CapturedStmt>(AStmt)->getCapturedDecl(); 5096 5097 // We expect to have at least 2 more parameters than the 'parallel' 5098 // directive does - the lower and upper bounds of the previous schedule. 5099 assert(CD->getNumParams() >= 4 && 5100 "Unexpected number of parameters in loop combined directive"); 5101 5102 // Set the proper type for the bounds given what we learned from the 5103 // enclosed loops. 5104 auto *PrevLBDecl = CD->getParam(/*PrevLB=*/2); 5105 auto *PrevUBDecl = CD->getParam(/*PrevUB=*/3); 5106 5107 // Previous lower and upper bounds are obtained from the region 5108 // parameters. 5109 PrevLB = 5110 buildDeclRefExpr(SemaRef, PrevLBDecl, PrevLBDecl->getType(), InitLoc); 5111 PrevUB = 5112 buildDeclRefExpr(SemaRef, PrevUBDecl, PrevUBDecl->getType(), InitLoc); 5113 } 5114 } 5115 5116 // Build the iteration variable and its initialization before loop. 5117 ExprResult IV; 5118 ExprResult Init; 5119 { 5120 VarDecl *IVDecl = buildVarDecl(SemaRef, InitLoc, RealVType, ".omp.iv"); 5121 IV = buildDeclRefExpr(SemaRef, IVDecl, RealVType, InitLoc); 5122 Expr *RHS = (isOpenMPWorksharingDirective(DKind) || 5123 isOpenMPTaskLoopDirective(DKind) || 5124 isOpenMPDistributeDirective(DKind)) 5125 ? LB.get() 5126 : SemaRef.ActOnIntegerConstant(SourceLocation(), 0).get(); 5127 Init = SemaRef.BuildBinOp(CurScope, InitLoc, BO_Assign, IV.get(), RHS); 5128 Init = SemaRef.ActOnFinishFullExpr(Init.get()); 5129 } 5130 5131 // Loop condition (IV < NumIterations) or (IV <= UB) for worksharing loops. 5132 SourceLocation CondLoc; 5133 ExprResult Cond = 5134 (isOpenMPWorksharingDirective(DKind) || 5135 isOpenMPTaskLoopDirective(DKind) || isOpenMPDistributeDirective(DKind)) 5136 ? SemaRef.BuildBinOp(CurScope, CondLoc, BO_LE, IV.get(), UB.get()) 5137 : SemaRef.BuildBinOp(CurScope, CondLoc, BO_LT, IV.get(), 5138 NumIterations.get()); 5139 5140 // Loop increment (IV = IV + 1) 5141 SourceLocation IncLoc; 5142 ExprResult Inc = 5143 SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, IV.get(), 5144 SemaRef.ActOnIntegerConstant(IncLoc, 1).get()); 5145 if (!Inc.isUsable()) 5146 return 0; 5147 Inc = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, IV.get(), Inc.get()); 5148 Inc = SemaRef.ActOnFinishFullExpr(Inc.get()); 5149 if (!Inc.isUsable()) 5150 return 0; 5151 5152 // Increments for worksharing loops (LB = LB + ST; UB = UB + ST). 5153 // Used for directives with static scheduling. 5154 ExprResult NextLB, NextUB; 5155 if (isOpenMPWorksharingDirective(DKind) || isOpenMPTaskLoopDirective(DKind) || 5156 isOpenMPDistributeDirective(DKind)) { 5157 // LB + ST 5158 NextLB = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, LB.get(), ST.get()); 5159 if (!NextLB.isUsable()) 5160 return 0; 5161 // LB = LB + ST 5162 NextLB = 5163 SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, LB.get(), NextLB.get()); 5164 NextLB = SemaRef.ActOnFinishFullExpr(NextLB.get()); 5165 if (!NextLB.isUsable()) 5166 return 0; 5167 // UB + ST 5168 NextUB = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, UB.get(), ST.get()); 5169 if (!NextUB.isUsable()) 5170 return 0; 5171 // UB = UB + ST 5172 NextUB = 5173 SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, UB.get(), NextUB.get()); 5174 NextUB = SemaRef.ActOnFinishFullExpr(NextUB.get()); 5175 if (!NextUB.isUsable()) 5176 return 0; 5177 } 5178 5179 // Build updates and final values of the loop counters. 5180 bool HasErrors = false; 5181 Built.Counters.resize(NestedLoopCount); 5182 Built.Inits.resize(NestedLoopCount); 5183 Built.Updates.resize(NestedLoopCount); 5184 Built.Finals.resize(NestedLoopCount); 5185 SmallVector<Expr *, 4> LoopMultipliers; 5186 { 5187 ExprResult Div; 5188 // Go from inner nested loop to outer. 5189 for (int Cnt = NestedLoopCount - 1; Cnt >= 0; --Cnt) { 5190 LoopIterationSpace &IS = IterSpaces[Cnt]; 5191 SourceLocation UpdLoc = IS.IncSrcRange.getBegin(); 5192 // Build: Iter = (IV / Div) % IS.NumIters 5193 // where Div is product of previous iterations' IS.NumIters. 5194 ExprResult Iter; 5195 if (Div.isUsable()) { 5196 Iter = 5197 SemaRef.BuildBinOp(CurScope, UpdLoc, BO_Div, IV.get(), Div.get()); 5198 } else { 5199 Iter = IV; 5200 assert((Cnt == (int)NestedLoopCount - 1) && 5201 "unusable div expected on first iteration only"); 5202 } 5203 5204 if (Cnt != 0 && Iter.isUsable()) 5205 Iter = SemaRef.BuildBinOp(CurScope, UpdLoc, BO_Rem, Iter.get(), 5206 IS.NumIterations); 5207 if (!Iter.isUsable()) { 5208 HasErrors = true; 5209 break; 5210 } 5211 5212 // Build update: IS.CounterVar(Private) = IS.Start + Iter * IS.Step 5213 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(IS.CounterVar)->getDecl()); 5214 auto *CounterVar = buildDeclRefExpr(SemaRef, VD, IS.CounterVar->getType(), 5215 IS.CounterVar->getExprLoc(), 5216 /*RefersToCapture=*/true); 5217 ExprResult Init = BuildCounterInit(SemaRef, CurScope, UpdLoc, CounterVar, 5218 IS.CounterInit, Captures); 5219 if (!Init.isUsable()) { 5220 HasErrors = true; 5221 break; 5222 } 5223 ExprResult Update = BuildCounterUpdate( 5224 SemaRef, CurScope, UpdLoc, CounterVar, IS.CounterInit, Iter, 5225 IS.CounterStep, IS.Subtract, &Captures); 5226 if (!Update.isUsable()) { 5227 HasErrors = true; 5228 break; 5229 } 5230 5231 // Build final: IS.CounterVar = IS.Start + IS.NumIters * IS.Step 5232 ExprResult Final = BuildCounterUpdate( 5233 SemaRef, CurScope, UpdLoc, CounterVar, IS.CounterInit, 5234 IS.NumIterations, IS.CounterStep, IS.Subtract, &Captures); 5235 if (!Final.isUsable()) { 5236 HasErrors = true; 5237 break; 5238 } 5239 5240 // Build Div for the next iteration: Div <- Div * IS.NumIters 5241 if (Cnt != 0) { 5242 if (Div.isUnset()) 5243 Div = IS.NumIterations; 5244 else 5245 Div = SemaRef.BuildBinOp(CurScope, UpdLoc, BO_Mul, Div.get(), 5246 IS.NumIterations); 5247 5248 // Add parentheses (for debugging purposes only). 5249 if (Div.isUsable()) 5250 Div = tryBuildCapture(SemaRef, Div.get(), Captures); 5251 if (!Div.isUsable()) { 5252 HasErrors = true; 5253 break; 5254 } 5255 LoopMultipliers.push_back(Div.get()); 5256 } 5257 if (!Update.isUsable() || !Final.isUsable()) { 5258 HasErrors = true; 5259 break; 5260 } 5261 // Save results 5262 Built.Counters[Cnt] = IS.CounterVar; 5263 Built.PrivateCounters[Cnt] = IS.PrivateCounterVar; 5264 Built.Inits[Cnt] = Init.get(); 5265 Built.Updates[Cnt] = Update.get(); 5266 Built.Finals[Cnt] = Final.get(); 5267 } 5268 } 5269 5270 if (HasErrors) 5271 return 0; 5272 5273 // Save results 5274 Built.IterationVarRef = IV.get(); 5275 Built.LastIteration = LastIteration.get(); 5276 Built.NumIterations = NumIterations.get(); 5277 Built.CalcLastIteration = 5278 SemaRef.ActOnFinishFullExpr(CalcLastIteration.get()).get(); 5279 Built.PreCond = PreCond.get(); 5280 Built.PreInits = buildPreInits(C, Captures); 5281 Built.Cond = Cond.get(); 5282 Built.Init = Init.get(); 5283 Built.Inc = Inc.get(); 5284 Built.LB = LB.get(); 5285 Built.UB = UB.get(); 5286 Built.IL = IL.get(); 5287 Built.ST = ST.get(); 5288 Built.EUB = EUB.get(); 5289 Built.NLB = NextLB.get(); 5290 Built.NUB = NextUB.get(); 5291 Built.PrevLB = PrevLB.get(); 5292 Built.PrevUB = PrevUB.get(); 5293 5294 Expr *CounterVal = SemaRef.DefaultLvalueConversion(IV.get()).get(); 5295 // Fill data for doacross depend clauses. 5296 for (auto Pair : DSA.getDoacrossDependClauses()) { 5297 if (Pair.first->getDependencyKind() == OMPC_DEPEND_source) 5298 Pair.first->setCounterValue(CounterVal); 5299 else { 5300 if (NestedLoopCount != Pair.second.size() || 5301 NestedLoopCount != LoopMultipliers.size() + 1) { 5302 // Erroneous case - clause has some problems. 5303 Pair.first->setCounterValue(CounterVal); 5304 continue; 5305 } 5306 assert(Pair.first->getDependencyKind() == OMPC_DEPEND_sink); 5307 auto I = Pair.second.rbegin(); 5308 auto IS = IterSpaces.rbegin(); 5309 auto ILM = LoopMultipliers.rbegin(); 5310 Expr *UpCounterVal = CounterVal; 5311 Expr *Multiplier = nullptr; 5312 for (int Cnt = NestedLoopCount - 1; Cnt >= 0; --Cnt) { 5313 if (I->first) { 5314 assert(IS->CounterStep); 5315 Expr *NormalizedOffset = 5316 SemaRef 5317 .BuildBinOp(CurScope, I->first->getExprLoc(), BO_Div, 5318 I->first, IS->CounterStep) 5319 .get(); 5320 if (Multiplier) { 5321 NormalizedOffset = 5322 SemaRef 5323 .BuildBinOp(CurScope, I->first->getExprLoc(), BO_Mul, 5324 NormalizedOffset, Multiplier) 5325 .get(); 5326 } 5327 assert(I->second == OO_Plus || I->second == OO_Minus); 5328 BinaryOperatorKind BOK = (I->second == OO_Plus) ? BO_Add : BO_Sub; 5329 UpCounterVal = 5330 SemaRef.BuildBinOp(CurScope, I->first->getExprLoc(), BOK, 5331 UpCounterVal, NormalizedOffset).get(); 5332 } 5333 Multiplier = *ILM; 5334 ++I; 5335 ++IS; 5336 ++ILM; 5337 } 5338 Pair.first->setCounterValue(UpCounterVal); 5339 } 5340 } 5341 5342 return NestedLoopCount; 5343 } 5344 5345 static Expr *getCollapseNumberExpr(ArrayRef<OMPClause *> Clauses) { 5346 auto CollapseClauses = 5347 OMPExecutableDirective::getClausesOfKind<OMPCollapseClause>(Clauses); 5348 if (CollapseClauses.begin() != CollapseClauses.end()) 5349 return (*CollapseClauses.begin())->getNumForLoops(); 5350 return nullptr; 5351 } 5352 5353 static Expr *getOrderedNumberExpr(ArrayRef<OMPClause *> Clauses) { 5354 auto OrderedClauses = 5355 OMPExecutableDirective::getClausesOfKind<OMPOrderedClause>(Clauses); 5356 if (OrderedClauses.begin() != OrderedClauses.end()) 5357 return (*OrderedClauses.begin())->getNumForLoops(); 5358 return nullptr; 5359 } 5360 5361 static bool checkSimdlenSafelenValues(Sema &S, const Expr *Simdlen, 5362 const Expr *Safelen) { 5363 llvm::APSInt SimdlenRes, SafelenRes; 5364 if (Simdlen->isValueDependent() || Simdlen->isTypeDependent() || 5365 Simdlen->isInstantiationDependent() || 5366 Simdlen->containsUnexpandedParameterPack()) 5367 return false; 5368 if (Safelen->isValueDependent() || Safelen->isTypeDependent() || 5369 Safelen->isInstantiationDependent() || 5370 Safelen->containsUnexpandedParameterPack()) 5371 return false; 5372 Simdlen->EvaluateAsInt(SimdlenRes, S.Context); 5373 Safelen->EvaluateAsInt(SafelenRes, S.Context); 5374 // OpenMP 4.1 [2.8.1, simd Construct, Restrictions] 5375 // If both simdlen and safelen clauses are specified, the value of the simdlen 5376 // parameter must be less than or equal to the value of the safelen parameter. 5377 if (SimdlenRes > SafelenRes) { 5378 S.Diag(Simdlen->getExprLoc(), diag::err_omp_wrong_simdlen_safelen_values) 5379 << Simdlen->getSourceRange() << Safelen->getSourceRange(); 5380 return true; 5381 } 5382 return false; 5383 } 5384 5385 StmtResult Sema::ActOnOpenMPSimdDirective( 5386 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, 5387 SourceLocation EndLoc, 5388 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) { 5389 if (!AStmt) 5390 return StmtError(); 5391 5392 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected"); 5393 OMPLoopDirective::HelperExprs B; 5394 // In presence of clause 'collapse' or 'ordered' with number of loops, it will 5395 // define the nested loops number. 5396 unsigned NestedLoopCount = CheckOpenMPLoop( 5397 OMPD_simd, getCollapseNumberExpr(Clauses), getOrderedNumberExpr(Clauses), 5398 AStmt, *this, *DSAStack, VarsWithImplicitDSA, B); 5399 if (NestedLoopCount == 0) 5400 return StmtError(); 5401 5402 assert((CurContext->isDependentContext() || B.builtAll()) && 5403 "omp simd loop exprs were not built"); 5404 5405 if (!CurContext->isDependentContext()) { 5406 // Finalize the clauses that need pre-built expressions for CodeGen. 5407 for (auto C : Clauses) { 5408 if (auto LC = dyn_cast<OMPLinearClause>(C)) 5409 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef), 5410 B.NumIterations, *this, CurScope, 5411 DSAStack)) 5412 return StmtError(); 5413 } 5414 } 5415 5416 // OpenMP 4.1 [2.8.1, simd Construct, Restrictions] 5417 // If both simdlen and safelen clauses are specified, the value of the simdlen 5418 // parameter must be less than or equal to the value of the safelen parameter. 5419 OMPSafelenClause *Safelen = nullptr; 5420 OMPSimdlenClause *Simdlen = nullptr; 5421 for (auto *Clause : Clauses) { 5422 if (Clause->getClauseKind() == OMPC_safelen) 5423 Safelen = cast<OMPSafelenClause>(Clause); 5424 else if (Clause->getClauseKind() == OMPC_simdlen) 5425 Simdlen = cast<OMPSimdlenClause>(Clause); 5426 if (Safelen && Simdlen) 5427 break; 5428 } 5429 if (Simdlen && Safelen && 5430 checkSimdlenSafelenValues(*this, Simdlen->getSimdlen(), 5431 Safelen->getSafelen())) 5432 return StmtError(); 5433 5434 getCurFunction()->setHasBranchProtectedScope(); 5435 return OMPSimdDirective::Create(Context, StartLoc, EndLoc, NestedLoopCount, 5436 Clauses, AStmt, B); 5437 } 5438 5439 StmtResult Sema::ActOnOpenMPForDirective( 5440 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, 5441 SourceLocation EndLoc, 5442 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) { 5443 if (!AStmt) 5444 return StmtError(); 5445 5446 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected"); 5447 OMPLoopDirective::HelperExprs B; 5448 // In presence of clause 'collapse' or 'ordered' with number of loops, it will 5449 // define the nested loops number. 5450 unsigned NestedLoopCount = CheckOpenMPLoop( 5451 OMPD_for, getCollapseNumberExpr(Clauses), getOrderedNumberExpr(Clauses), 5452 AStmt, *this, *DSAStack, VarsWithImplicitDSA, B); 5453 if (NestedLoopCount == 0) 5454 return StmtError(); 5455 5456 assert((CurContext->isDependentContext() || B.builtAll()) && 5457 "omp for loop exprs were not built"); 5458 5459 if (!CurContext->isDependentContext()) { 5460 // Finalize the clauses that need pre-built expressions for CodeGen. 5461 for (auto C : Clauses) { 5462 if (auto LC = dyn_cast<OMPLinearClause>(C)) 5463 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef), 5464 B.NumIterations, *this, CurScope, 5465 DSAStack)) 5466 return StmtError(); 5467 } 5468 } 5469 5470 getCurFunction()->setHasBranchProtectedScope(); 5471 return OMPForDirective::Create(Context, StartLoc, EndLoc, NestedLoopCount, 5472 Clauses, AStmt, B, DSAStack->isCancelRegion()); 5473 } 5474 5475 StmtResult Sema::ActOnOpenMPForSimdDirective( 5476 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, 5477 SourceLocation EndLoc, 5478 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) { 5479 if (!AStmt) 5480 return StmtError(); 5481 5482 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected"); 5483 OMPLoopDirective::HelperExprs B; 5484 // In presence of clause 'collapse' or 'ordered' with number of loops, it will 5485 // define the nested loops number. 5486 unsigned NestedLoopCount = 5487 CheckOpenMPLoop(OMPD_for_simd, getCollapseNumberExpr(Clauses), 5488 getOrderedNumberExpr(Clauses), AStmt, *this, *DSAStack, 5489 VarsWithImplicitDSA, B); 5490 if (NestedLoopCount == 0) 5491 return StmtError(); 5492 5493 assert((CurContext->isDependentContext() || B.builtAll()) && 5494 "omp for simd loop exprs were not built"); 5495 5496 if (!CurContext->isDependentContext()) { 5497 // Finalize the clauses that need pre-built expressions for CodeGen. 5498 for (auto C : Clauses) { 5499 if (auto LC = dyn_cast<OMPLinearClause>(C)) 5500 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef), 5501 B.NumIterations, *this, CurScope, 5502 DSAStack)) 5503 return StmtError(); 5504 } 5505 } 5506 5507 // OpenMP 4.1 [2.8.1, simd Construct, Restrictions] 5508 // If both simdlen and safelen clauses are specified, the value of the simdlen 5509 // parameter must be less than or equal to the value of the safelen parameter. 5510 OMPSafelenClause *Safelen = nullptr; 5511 OMPSimdlenClause *Simdlen = nullptr; 5512 for (auto *Clause : Clauses) { 5513 if (Clause->getClauseKind() == OMPC_safelen) 5514 Safelen = cast<OMPSafelenClause>(Clause); 5515 else if (Clause->getClauseKind() == OMPC_simdlen) 5516 Simdlen = cast<OMPSimdlenClause>(Clause); 5517 if (Safelen && Simdlen) 5518 break; 5519 } 5520 if (Simdlen && Safelen && 5521 checkSimdlenSafelenValues(*this, Simdlen->getSimdlen(), 5522 Safelen->getSafelen())) 5523 return StmtError(); 5524 5525 getCurFunction()->setHasBranchProtectedScope(); 5526 return OMPForSimdDirective::Create(Context, StartLoc, EndLoc, NestedLoopCount, 5527 Clauses, AStmt, B); 5528 } 5529 5530 StmtResult Sema::ActOnOpenMPSectionsDirective(ArrayRef<OMPClause *> Clauses, 5531 Stmt *AStmt, 5532 SourceLocation StartLoc, 5533 SourceLocation EndLoc) { 5534 if (!AStmt) 5535 return StmtError(); 5536 5537 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected"); 5538 auto BaseStmt = AStmt; 5539 while (CapturedStmt *CS = dyn_cast_or_null<CapturedStmt>(BaseStmt)) 5540 BaseStmt = CS->getCapturedStmt(); 5541 if (auto C = dyn_cast_or_null<CompoundStmt>(BaseStmt)) { 5542 auto S = C->children(); 5543 if (S.begin() == S.end()) 5544 return StmtError(); 5545 // All associated statements must be '#pragma omp section' except for 5546 // the first one. 5547 for (Stmt *SectionStmt : llvm::make_range(std::next(S.begin()), S.end())) { 5548 if (!SectionStmt || !isa<OMPSectionDirective>(SectionStmt)) { 5549 if (SectionStmt) 5550 Diag(SectionStmt->getLocStart(), 5551 diag::err_omp_sections_substmt_not_section); 5552 return StmtError(); 5553 } 5554 cast<OMPSectionDirective>(SectionStmt) 5555 ->setHasCancel(DSAStack->isCancelRegion()); 5556 } 5557 } else { 5558 Diag(AStmt->getLocStart(), diag::err_omp_sections_not_compound_stmt); 5559 return StmtError(); 5560 } 5561 5562 getCurFunction()->setHasBranchProtectedScope(); 5563 5564 return OMPSectionsDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt, 5565 DSAStack->isCancelRegion()); 5566 } 5567 5568 StmtResult Sema::ActOnOpenMPSectionDirective(Stmt *AStmt, 5569 SourceLocation StartLoc, 5570 SourceLocation EndLoc) { 5571 if (!AStmt) 5572 return StmtError(); 5573 5574 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected"); 5575 5576 getCurFunction()->setHasBranchProtectedScope(); 5577 DSAStack->setParentCancelRegion(DSAStack->isCancelRegion()); 5578 5579 return OMPSectionDirective::Create(Context, StartLoc, EndLoc, AStmt, 5580 DSAStack->isCancelRegion()); 5581 } 5582 5583 StmtResult Sema::ActOnOpenMPSingleDirective(ArrayRef<OMPClause *> Clauses, 5584 Stmt *AStmt, 5585 SourceLocation StartLoc, 5586 SourceLocation EndLoc) { 5587 if (!AStmt) 5588 return StmtError(); 5589 5590 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected"); 5591 5592 getCurFunction()->setHasBranchProtectedScope(); 5593 5594 // OpenMP [2.7.3, single Construct, Restrictions] 5595 // The copyprivate clause must not be used with the nowait clause. 5596 OMPClause *Nowait = nullptr; 5597 OMPClause *Copyprivate = nullptr; 5598 for (auto *Clause : Clauses) { 5599 if (Clause->getClauseKind() == OMPC_nowait) 5600 Nowait = Clause; 5601 else if (Clause->getClauseKind() == OMPC_copyprivate) 5602 Copyprivate = Clause; 5603 if (Copyprivate && Nowait) { 5604 Diag(Copyprivate->getLocStart(), 5605 diag::err_omp_single_copyprivate_with_nowait); 5606 Diag(Nowait->getLocStart(), diag::note_omp_nowait_clause_here); 5607 return StmtError(); 5608 } 5609 } 5610 5611 return OMPSingleDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt); 5612 } 5613 5614 StmtResult Sema::ActOnOpenMPMasterDirective(Stmt *AStmt, 5615 SourceLocation StartLoc, 5616 SourceLocation EndLoc) { 5617 if (!AStmt) 5618 return StmtError(); 5619 5620 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected"); 5621 5622 getCurFunction()->setHasBranchProtectedScope(); 5623 5624 return OMPMasterDirective::Create(Context, StartLoc, EndLoc, AStmt); 5625 } 5626 5627 StmtResult Sema::ActOnOpenMPCriticalDirective( 5628 const DeclarationNameInfo &DirName, ArrayRef<OMPClause *> Clauses, 5629 Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc) { 5630 if (!AStmt) 5631 return StmtError(); 5632 5633 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected"); 5634 5635 bool ErrorFound = false; 5636 llvm::APSInt Hint; 5637 SourceLocation HintLoc; 5638 bool DependentHint = false; 5639 for (auto *C : Clauses) { 5640 if (C->getClauseKind() == OMPC_hint) { 5641 if (!DirName.getName()) { 5642 Diag(C->getLocStart(), diag::err_omp_hint_clause_no_name); 5643 ErrorFound = true; 5644 } 5645 Expr *E = cast<OMPHintClause>(C)->getHint(); 5646 if (E->isTypeDependent() || E->isValueDependent() || 5647 E->isInstantiationDependent()) 5648 DependentHint = true; 5649 else { 5650 Hint = E->EvaluateKnownConstInt(Context); 5651 HintLoc = C->getLocStart(); 5652 } 5653 } 5654 } 5655 if (ErrorFound) 5656 return StmtError(); 5657 auto Pair = DSAStack->getCriticalWithHint(DirName); 5658 if (Pair.first && DirName.getName() && !DependentHint) { 5659 if (llvm::APSInt::compareValues(Hint, Pair.second) != 0) { 5660 Diag(StartLoc, diag::err_omp_critical_with_hint); 5661 if (HintLoc.isValid()) { 5662 Diag(HintLoc, diag::note_omp_critical_hint_here) 5663 << 0 << Hint.toString(/*Radix=*/10, /*Signed=*/false); 5664 } else 5665 Diag(StartLoc, diag::note_omp_critical_no_hint) << 0; 5666 if (auto *C = Pair.first->getSingleClause<OMPHintClause>()) { 5667 Diag(C->getLocStart(), diag::note_omp_critical_hint_here) 5668 << 1 5669 << C->getHint()->EvaluateKnownConstInt(Context).toString( 5670 /*Radix=*/10, /*Signed=*/false); 5671 } else 5672 Diag(Pair.first->getLocStart(), diag::note_omp_critical_no_hint) << 1; 5673 } 5674 } 5675 5676 getCurFunction()->setHasBranchProtectedScope(); 5677 5678 auto *Dir = OMPCriticalDirective::Create(Context, DirName, StartLoc, EndLoc, 5679 Clauses, AStmt); 5680 if (!Pair.first && DirName.getName() && !DependentHint) 5681 DSAStack->addCriticalWithHint(Dir, Hint); 5682 return Dir; 5683 } 5684 5685 StmtResult Sema::ActOnOpenMPParallelForDirective( 5686 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, 5687 SourceLocation EndLoc, 5688 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) { 5689 if (!AStmt) 5690 return StmtError(); 5691 5692 CapturedStmt *CS = cast<CapturedStmt>(AStmt); 5693 // 1.2.2 OpenMP Language Terminology 5694 // Structured block - An executable statement with a single entry at the 5695 // top and a single exit at the bottom. 5696 // The point of exit cannot be a branch out of the structured block. 5697 // longjmp() and throw() must not violate the entry/exit criteria. 5698 CS->getCapturedDecl()->setNothrow(); 5699 5700 OMPLoopDirective::HelperExprs B; 5701 // In presence of clause 'collapse' or 'ordered' with number of loops, it will 5702 // define the nested loops number. 5703 unsigned NestedLoopCount = 5704 CheckOpenMPLoop(OMPD_parallel_for, getCollapseNumberExpr(Clauses), 5705 getOrderedNumberExpr(Clauses), AStmt, *this, *DSAStack, 5706 VarsWithImplicitDSA, B); 5707 if (NestedLoopCount == 0) 5708 return StmtError(); 5709 5710 assert((CurContext->isDependentContext() || B.builtAll()) && 5711 "omp parallel for loop exprs were not built"); 5712 5713 if (!CurContext->isDependentContext()) { 5714 // Finalize the clauses that need pre-built expressions for CodeGen. 5715 for (auto C : Clauses) { 5716 if (auto LC = dyn_cast<OMPLinearClause>(C)) 5717 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef), 5718 B.NumIterations, *this, CurScope, 5719 DSAStack)) 5720 return StmtError(); 5721 } 5722 } 5723 5724 getCurFunction()->setHasBranchProtectedScope(); 5725 return OMPParallelForDirective::Create(Context, StartLoc, EndLoc, 5726 NestedLoopCount, Clauses, AStmt, B, 5727 DSAStack->isCancelRegion()); 5728 } 5729 5730 StmtResult Sema::ActOnOpenMPParallelForSimdDirective( 5731 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, 5732 SourceLocation EndLoc, 5733 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) { 5734 if (!AStmt) 5735 return StmtError(); 5736 5737 CapturedStmt *CS = cast<CapturedStmt>(AStmt); 5738 // 1.2.2 OpenMP Language Terminology 5739 // Structured block - An executable statement with a single entry at the 5740 // top and a single exit at the bottom. 5741 // The point of exit cannot be a branch out of the structured block. 5742 // longjmp() and throw() must not violate the entry/exit criteria. 5743 CS->getCapturedDecl()->setNothrow(); 5744 5745 OMPLoopDirective::HelperExprs B; 5746 // In presence of clause 'collapse' or 'ordered' with number of loops, it will 5747 // define the nested loops number. 5748 unsigned NestedLoopCount = 5749 CheckOpenMPLoop(OMPD_parallel_for_simd, getCollapseNumberExpr(Clauses), 5750 getOrderedNumberExpr(Clauses), AStmt, *this, *DSAStack, 5751 VarsWithImplicitDSA, B); 5752 if (NestedLoopCount == 0) 5753 return StmtError(); 5754 5755 if (!CurContext->isDependentContext()) { 5756 // Finalize the clauses that need pre-built expressions for CodeGen. 5757 for (auto C : Clauses) { 5758 if (auto LC = dyn_cast<OMPLinearClause>(C)) 5759 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef), 5760 B.NumIterations, *this, CurScope, 5761 DSAStack)) 5762 return StmtError(); 5763 } 5764 } 5765 5766 // OpenMP 4.1 [2.8.1, simd Construct, Restrictions] 5767 // If both simdlen and safelen clauses are specified, the value of the simdlen 5768 // parameter must be less than or equal to the value of the safelen parameter. 5769 OMPSafelenClause *Safelen = nullptr; 5770 OMPSimdlenClause *Simdlen = nullptr; 5771 for (auto *Clause : Clauses) { 5772 if (Clause->getClauseKind() == OMPC_safelen) 5773 Safelen = cast<OMPSafelenClause>(Clause); 5774 else if (Clause->getClauseKind() == OMPC_simdlen) 5775 Simdlen = cast<OMPSimdlenClause>(Clause); 5776 if (Safelen && Simdlen) 5777 break; 5778 } 5779 if (Simdlen && Safelen && 5780 checkSimdlenSafelenValues(*this, Simdlen->getSimdlen(), 5781 Safelen->getSafelen())) 5782 return StmtError(); 5783 5784 getCurFunction()->setHasBranchProtectedScope(); 5785 return OMPParallelForSimdDirective::Create( 5786 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B); 5787 } 5788 5789 StmtResult 5790 Sema::ActOnOpenMPParallelSectionsDirective(ArrayRef<OMPClause *> Clauses, 5791 Stmt *AStmt, SourceLocation StartLoc, 5792 SourceLocation EndLoc) { 5793 if (!AStmt) 5794 return StmtError(); 5795 5796 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected"); 5797 auto BaseStmt = AStmt; 5798 while (CapturedStmt *CS = dyn_cast_or_null<CapturedStmt>(BaseStmt)) 5799 BaseStmt = CS->getCapturedStmt(); 5800 if (auto C = dyn_cast_or_null<CompoundStmt>(BaseStmt)) { 5801 auto S = C->children(); 5802 if (S.begin() == S.end()) 5803 return StmtError(); 5804 // All associated statements must be '#pragma omp section' except for 5805 // the first one. 5806 for (Stmt *SectionStmt : llvm::make_range(std::next(S.begin()), S.end())) { 5807 if (!SectionStmt || !isa<OMPSectionDirective>(SectionStmt)) { 5808 if (SectionStmt) 5809 Diag(SectionStmt->getLocStart(), 5810 diag::err_omp_parallel_sections_substmt_not_section); 5811 return StmtError(); 5812 } 5813 cast<OMPSectionDirective>(SectionStmt) 5814 ->setHasCancel(DSAStack->isCancelRegion()); 5815 } 5816 } else { 5817 Diag(AStmt->getLocStart(), 5818 diag::err_omp_parallel_sections_not_compound_stmt); 5819 return StmtError(); 5820 } 5821 5822 getCurFunction()->setHasBranchProtectedScope(); 5823 5824 return OMPParallelSectionsDirective::Create( 5825 Context, StartLoc, EndLoc, Clauses, AStmt, DSAStack->isCancelRegion()); 5826 } 5827 5828 StmtResult Sema::ActOnOpenMPTaskDirective(ArrayRef<OMPClause *> Clauses, 5829 Stmt *AStmt, SourceLocation StartLoc, 5830 SourceLocation EndLoc) { 5831 if (!AStmt) 5832 return StmtError(); 5833 5834 CapturedStmt *CS = cast<CapturedStmt>(AStmt); 5835 // 1.2.2 OpenMP Language Terminology 5836 // Structured block - An executable statement with a single entry at the 5837 // top and a single exit at the bottom. 5838 // The point of exit cannot be a branch out of the structured block. 5839 // longjmp() and throw() must not violate the entry/exit criteria. 5840 CS->getCapturedDecl()->setNothrow(); 5841 5842 getCurFunction()->setHasBranchProtectedScope(); 5843 5844 return OMPTaskDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt, 5845 DSAStack->isCancelRegion()); 5846 } 5847 5848 StmtResult Sema::ActOnOpenMPTaskyieldDirective(SourceLocation StartLoc, 5849 SourceLocation EndLoc) { 5850 return OMPTaskyieldDirective::Create(Context, StartLoc, EndLoc); 5851 } 5852 5853 StmtResult Sema::ActOnOpenMPBarrierDirective(SourceLocation StartLoc, 5854 SourceLocation EndLoc) { 5855 return OMPBarrierDirective::Create(Context, StartLoc, EndLoc); 5856 } 5857 5858 StmtResult Sema::ActOnOpenMPTaskwaitDirective(SourceLocation StartLoc, 5859 SourceLocation EndLoc) { 5860 return OMPTaskwaitDirective::Create(Context, StartLoc, EndLoc); 5861 } 5862 5863 StmtResult Sema::ActOnOpenMPTaskgroupDirective(Stmt *AStmt, 5864 SourceLocation StartLoc, 5865 SourceLocation EndLoc) { 5866 if (!AStmt) 5867 return StmtError(); 5868 5869 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected"); 5870 5871 getCurFunction()->setHasBranchProtectedScope(); 5872 5873 return OMPTaskgroupDirective::Create(Context, StartLoc, EndLoc, AStmt); 5874 } 5875 5876 StmtResult Sema::ActOnOpenMPFlushDirective(ArrayRef<OMPClause *> Clauses, 5877 SourceLocation StartLoc, 5878 SourceLocation EndLoc) { 5879 assert(Clauses.size() <= 1 && "Extra clauses in flush directive"); 5880 return OMPFlushDirective::Create(Context, StartLoc, EndLoc, Clauses); 5881 } 5882 5883 StmtResult Sema::ActOnOpenMPOrderedDirective(ArrayRef<OMPClause *> Clauses, 5884 Stmt *AStmt, 5885 SourceLocation StartLoc, 5886 SourceLocation EndLoc) { 5887 OMPClause *DependFound = nullptr; 5888 OMPClause *DependSourceClause = nullptr; 5889 OMPClause *DependSinkClause = nullptr; 5890 bool ErrorFound = false; 5891 OMPThreadsClause *TC = nullptr; 5892 OMPSIMDClause *SC = nullptr; 5893 for (auto *C : Clauses) { 5894 if (auto *DC = dyn_cast<OMPDependClause>(C)) { 5895 DependFound = C; 5896 if (DC->getDependencyKind() == OMPC_DEPEND_source) { 5897 if (DependSourceClause) { 5898 Diag(C->getLocStart(), diag::err_omp_more_one_clause) 5899 << getOpenMPDirectiveName(OMPD_ordered) 5900 << getOpenMPClauseName(OMPC_depend) << 2; 5901 ErrorFound = true; 5902 } else 5903 DependSourceClause = C; 5904 if (DependSinkClause) { 5905 Diag(C->getLocStart(), diag::err_omp_depend_sink_source_not_allowed) 5906 << 0; 5907 ErrorFound = true; 5908 } 5909 } else if (DC->getDependencyKind() == OMPC_DEPEND_sink) { 5910 if (DependSourceClause) { 5911 Diag(C->getLocStart(), diag::err_omp_depend_sink_source_not_allowed) 5912 << 1; 5913 ErrorFound = true; 5914 } 5915 DependSinkClause = C; 5916 } 5917 } else if (C->getClauseKind() == OMPC_threads) 5918 TC = cast<OMPThreadsClause>(C); 5919 else if (C->getClauseKind() == OMPC_simd) 5920 SC = cast<OMPSIMDClause>(C); 5921 } 5922 if (!ErrorFound && !SC && 5923 isOpenMPSimdDirective(DSAStack->getParentDirective())) { 5924 // OpenMP [2.8.1,simd Construct, Restrictions] 5925 // An ordered construct with the simd clause is the only OpenMP construct 5926 // that can appear in the simd region. 5927 Diag(StartLoc, diag::err_omp_prohibited_region_simd); 5928 ErrorFound = true; 5929 } else if (DependFound && (TC || SC)) { 5930 Diag(DependFound->getLocStart(), diag::err_omp_depend_clause_thread_simd) 5931 << getOpenMPClauseName(TC ? TC->getClauseKind() : SC->getClauseKind()); 5932 ErrorFound = true; 5933 } else if (DependFound && !DSAStack->getParentOrderedRegionParam()) { 5934 Diag(DependFound->getLocStart(), 5935 diag::err_omp_ordered_directive_without_param); 5936 ErrorFound = true; 5937 } else if (TC || Clauses.empty()) { 5938 if (auto *Param = DSAStack->getParentOrderedRegionParam()) { 5939 SourceLocation ErrLoc = TC ? TC->getLocStart() : StartLoc; 5940 Diag(ErrLoc, diag::err_omp_ordered_directive_with_param) 5941 << (TC != nullptr); 5942 Diag(Param->getLocStart(), diag::note_omp_ordered_param); 5943 ErrorFound = true; 5944 } 5945 } 5946 if ((!AStmt && !DependFound) || ErrorFound) 5947 return StmtError(); 5948 5949 if (AStmt) { 5950 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected"); 5951 5952 getCurFunction()->setHasBranchProtectedScope(); 5953 } 5954 5955 return OMPOrderedDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt); 5956 } 5957 5958 namespace { 5959 /// \brief Helper class for checking expression in 'omp atomic [update]' 5960 /// construct. 5961 class OpenMPAtomicUpdateChecker { 5962 /// \brief Error results for atomic update expressions. 5963 enum ExprAnalysisErrorCode { 5964 /// \brief A statement is not an expression statement. 5965 NotAnExpression, 5966 /// \brief Expression is not builtin binary or unary operation. 5967 NotABinaryOrUnaryExpression, 5968 /// \brief Unary operation is not post-/pre- increment/decrement operation. 5969 NotAnUnaryIncDecExpression, 5970 /// \brief An expression is not of scalar type. 5971 NotAScalarType, 5972 /// \brief A binary operation is not an assignment operation. 5973 NotAnAssignmentOp, 5974 /// \brief RHS part of the binary operation is not a binary expression. 5975 NotABinaryExpression, 5976 /// \brief RHS part is not additive/multiplicative/shift/biwise binary 5977 /// expression. 5978 NotABinaryOperator, 5979 /// \brief RHS binary operation does not have reference to the updated LHS 5980 /// part. 5981 NotAnUpdateExpression, 5982 /// \brief No errors is found. 5983 NoError 5984 }; 5985 /// \brief Reference to Sema. 5986 Sema &SemaRef; 5987 /// \brief A location for note diagnostics (when error is found). 5988 SourceLocation NoteLoc; 5989 /// \brief 'x' lvalue part of the source atomic expression. 5990 Expr *X; 5991 /// \brief 'expr' rvalue part of the source atomic expression. 5992 Expr *E; 5993 /// \brief Helper expression of the form 5994 /// 'OpaqueValueExpr(x) binop OpaqueValueExpr(expr)' or 5995 /// 'OpaqueValueExpr(expr) binop OpaqueValueExpr(x)'. 5996 Expr *UpdateExpr; 5997 /// \brief Is 'x' a LHS in a RHS part of full update expression. It is 5998 /// important for non-associative operations. 5999 bool IsXLHSInRHSPart; 6000 BinaryOperatorKind Op; 6001 SourceLocation OpLoc; 6002 /// \brief true if the source expression is a postfix unary operation, false 6003 /// if it is a prefix unary operation. 6004 bool IsPostfixUpdate; 6005 6006 public: 6007 OpenMPAtomicUpdateChecker(Sema &SemaRef) 6008 : SemaRef(SemaRef), X(nullptr), E(nullptr), UpdateExpr(nullptr), 6009 IsXLHSInRHSPart(false), Op(BO_PtrMemD), IsPostfixUpdate(false) {} 6010 /// \brief Check specified statement that it is suitable for 'atomic update' 6011 /// constructs and extract 'x', 'expr' and Operation from the original 6012 /// expression. If DiagId and NoteId == 0, then only check is performed 6013 /// without error notification. 6014 /// \param DiagId Diagnostic which should be emitted if error is found. 6015 /// \param NoteId Diagnostic note for the main error message. 6016 /// \return true if statement is not an update expression, false otherwise. 6017 bool checkStatement(Stmt *S, unsigned DiagId = 0, unsigned NoteId = 0); 6018 /// \brief Return the 'x' lvalue part of the source atomic expression. 6019 Expr *getX() const { return X; } 6020 /// \brief Return the 'expr' rvalue part of the source atomic expression. 6021 Expr *getExpr() const { return E; } 6022 /// \brief Return the update expression used in calculation of the updated 6023 /// value. Always has form 'OpaqueValueExpr(x) binop OpaqueValueExpr(expr)' or 6024 /// 'OpaqueValueExpr(expr) binop OpaqueValueExpr(x)'. 6025 Expr *getUpdateExpr() const { return UpdateExpr; } 6026 /// \brief Return true if 'x' is LHS in RHS part of full update expression, 6027 /// false otherwise. 6028 bool isXLHSInRHSPart() const { return IsXLHSInRHSPart; } 6029 6030 /// \brief true if the source expression is a postfix unary operation, false 6031 /// if it is a prefix unary operation. 6032 bool isPostfixUpdate() const { return IsPostfixUpdate; } 6033 6034 private: 6035 bool checkBinaryOperation(BinaryOperator *AtomicBinOp, unsigned DiagId = 0, 6036 unsigned NoteId = 0); 6037 }; 6038 } // namespace 6039 6040 bool OpenMPAtomicUpdateChecker::checkBinaryOperation( 6041 BinaryOperator *AtomicBinOp, unsigned DiagId, unsigned NoteId) { 6042 ExprAnalysisErrorCode ErrorFound = NoError; 6043 SourceLocation ErrorLoc, NoteLoc; 6044 SourceRange ErrorRange, NoteRange; 6045 // Allowed constructs are: 6046 // x = x binop expr; 6047 // x = expr binop x; 6048 if (AtomicBinOp->getOpcode() == BO_Assign) { 6049 X = AtomicBinOp->getLHS(); 6050 if (auto *AtomicInnerBinOp = dyn_cast<BinaryOperator>( 6051 AtomicBinOp->getRHS()->IgnoreParenImpCasts())) { 6052 if (AtomicInnerBinOp->isMultiplicativeOp() || 6053 AtomicInnerBinOp->isAdditiveOp() || AtomicInnerBinOp->isShiftOp() || 6054 AtomicInnerBinOp->isBitwiseOp()) { 6055 Op = AtomicInnerBinOp->getOpcode(); 6056 OpLoc = AtomicInnerBinOp->getOperatorLoc(); 6057 auto *LHS = AtomicInnerBinOp->getLHS(); 6058 auto *RHS = AtomicInnerBinOp->getRHS(); 6059 llvm::FoldingSetNodeID XId, LHSId, RHSId; 6060 X->IgnoreParenImpCasts()->Profile(XId, SemaRef.getASTContext(), 6061 /*Canonical=*/true); 6062 LHS->IgnoreParenImpCasts()->Profile(LHSId, SemaRef.getASTContext(), 6063 /*Canonical=*/true); 6064 RHS->IgnoreParenImpCasts()->Profile(RHSId, SemaRef.getASTContext(), 6065 /*Canonical=*/true); 6066 if (XId == LHSId) { 6067 E = RHS; 6068 IsXLHSInRHSPart = true; 6069 } else if (XId == RHSId) { 6070 E = LHS; 6071 IsXLHSInRHSPart = false; 6072 } else { 6073 ErrorLoc = AtomicInnerBinOp->getExprLoc(); 6074 ErrorRange = AtomicInnerBinOp->getSourceRange(); 6075 NoteLoc = X->getExprLoc(); 6076 NoteRange = X->getSourceRange(); 6077 ErrorFound = NotAnUpdateExpression; 6078 } 6079 } else { 6080 ErrorLoc = AtomicInnerBinOp->getExprLoc(); 6081 ErrorRange = AtomicInnerBinOp->getSourceRange(); 6082 NoteLoc = AtomicInnerBinOp->getOperatorLoc(); 6083 NoteRange = SourceRange(NoteLoc, NoteLoc); 6084 ErrorFound = NotABinaryOperator; 6085 } 6086 } else { 6087 NoteLoc = ErrorLoc = AtomicBinOp->getRHS()->getExprLoc(); 6088 NoteRange = ErrorRange = AtomicBinOp->getRHS()->getSourceRange(); 6089 ErrorFound = NotABinaryExpression; 6090 } 6091 } else { 6092 ErrorLoc = AtomicBinOp->getExprLoc(); 6093 ErrorRange = AtomicBinOp->getSourceRange(); 6094 NoteLoc = AtomicBinOp->getOperatorLoc(); 6095 NoteRange = SourceRange(NoteLoc, NoteLoc); 6096 ErrorFound = NotAnAssignmentOp; 6097 } 6098 if (ErrorFound != NoError && DiagId != 0 && NoteId != 0) { 6099 SemaRef.Diag(ErrorLoc, DiagId) << ErrorRange; 6100 SemaRef.Diag(NoteLoc, NoteId) << ErrorFound << NoteRange; 6101 return true; 6102 } else if (SemaRef.CurContext->isDependentContext()) 6103 E = X = UpdateExpr = nullptr; 6104 return ErrorFound != NoError; 6105 } 6106 6107 bool OpenMPAtomicUpdateChecker::checkStatement(Stmt *S, unsigned DiagId, 6108 unsigned NoteId) { 6109 ExprAnalysisErrorCode ErrorFound = NoError; 6110 SourceLocation ErrorLoc, NoteLoc; 6111 SourceRange ErrorRange, NoteRange; 6112 // Allowed constructs are: 6113 // x++; 6114 // x--; 6115 // ++x; 6116 // --x; 6117 // x binop= expr; 6118 // x = x binop expr; 6119 // x = expr binop x; 6120 if (auto *AtomicBody = dyn_cast<Expr>(S)) { 6121 AtomicBody = AtomicBody->IgnoreParenImpCasts(); 6122 if (AtomicBody->getType()->isScalarType() || 6123 AtomicBody->isInstantiationDependent()) { 6124 if (auto *AtomicCompAssignOp = dyn_cast<CompoundAssignOperator>( 6125 AtomicBody->IgnoreParenImpCasts())) { 6126 // Check for Compound Assignment Operation 6127 Op = BinaryOperator::getOpForCompoundAssignment( 6128 AtomicCompAssignOp->getOpcode()); 6129 OpLoc = AtomicCompAssignOp->getOperatorLoc(); 6130 E = AtomicCompAssignOp->getRHS(); 6131 X = AtomicCompAssignOp->getLHS(); 6132 IsXLHSInRHSPart = true; 6133 } else if (auto *AtomicBinOp = dyn_cast<BinaryOperator>( 6134 AtomicBody->IgnoreParenImpCasts())) { 6135 // Check for Binary Operation 6136 if(checkBinaryOperation(AtomicBinOp, DiagId, NoteId)) 6137 return true; 6138 } else if (auto *AtomicUnaryOp = 6139 dyn_cast<UnaryOperator>(AtomicBody->IgnoreParenImpCasts())) { 6140 // Check for Unary Operation 6141 if (AtomicUnaryOp->isIncrementDecrementOp()) { 6142 IsPostfixUpdate = AtomicUnaryOp->isPostfix(); 6143 Op = AtomicUnaryOp->isIncrementOp() ? BO_Add : BO_Sub; 6144 OpLoc = AtomicUnaryOp->getOperatorLoc(); 6145 X = AtomicUnaryOp->getSubExpr(); 6146 E = SemaRef.ActOnIntegerConstant(OpLoc, /*uint64_t Val=*/1).get(); 6147 IsXLHSInRHSPart = true; 6148 } else { 6149 ErrorFound = NotAnUnaryIncDecExpression; 6150 ErrorLoc = AtomicUnaryOp->getExprLoc(); 6151 ErrorRange = AtomicUnaryOp->getSourceRange(); 6152 NoteLoc = AtomicUnaryOp->getOperatorLoc(); 6153 NoteRange = SourceRange(NoteLoc, NoteLoc); 6154 } 6155 } else if (!AtomicBody->isInstantiationDependent()) { 6156 ErrorFound = NotABinaryOrUnaryExpression; 6157 NoteLoc = ErrorLoc = AtomicBody->getExprLoc(); 6158 NoteRange = ErrorRange = AtomicBody->getSourceRange(); 6159 } 6160 } else { 6161 ErrorFound = NotAScalarType; 6162 NoteLoc = ErrorLoc = AtomicBody->getLocStart(); 6163 NoteRange = ErrorRange = SourceRange(NoteLoc, NoteLoc); 6164 } 6165 } else { 6166 ErrorFound = NotAnExpression; 6167 NoteLoc = ErrorLoc = S->getLocStart(); 6168 NoteRange = ErrorRange = SourceRange(NoteLoc, NoteLoc); 6169 } 6170 if (ErrorFound != NoError && DiagId != 0 && NoteId != 0) { 6171 SemaRef.Diag(ErrorLoc, DiagId) << ErrorRange; 6172 SemaRef.Diag(NoteLoc, NoteId) << ErrorFound << NoteRange; 6173 return true; 6174 } else if (SemaRef.CurContext->isDependentContext()) 6175 E = X = UpdateExpr = nullptr; 6176 if (ErrorFound == NoError && E && X) { 6177 // Build an update expression of form 'OpaqueValueExpr(x) binop 6178 // OpaqueValueExpr(expr)' or 'OpaqueValueExpr(expr) binop 6179 // OpaqueValueExpr(x)' and then cast it to the type of the 'x' expression. 6180 auto *OVEX = new (SemaRef.getASTContext()) 6181 OpaqueValueExpr(X->getExprLoc(), X->getType(), VK_RValue); 6182 auto *OVEExpr = new (SemaRef.getASTContext()) 6183 OpaqueValueExpr(E->getExprLoc(), E->getType(), VK_RValue); 6184 auto Update = 6185 SemaRef.CreateBuiltinBinOp(OpLoc, Op, IsXLHSInRHSPart ? OVEX : OVEExpr, 6186 IsXLHSInRHSPart ? OVEExpr : OVEX); 6187 if (Update.isInvalid()) 6188 return true; 6189 Update = SemaRef.PerformImplicitConversion(Update.get(), X->getType(), 6190 Sema::AA_Casting); 6191 if (Update.isInvalid()) 6192 return true; 6193 UpdateExpr = Update.get(); 6194 } 6195 return ErrorFound != NoError; 6196 } 6197 6198 StmtResult Sema::ActOnOpenMPAtomicDirective(ArrayRef<OMPClause *> Clauses, 6199 Stmt *AStmt, 6200 SourceLocation StartLoc, 6201 SourceLocation EndLoc) { 6202 if (!AStmt) 6203 return StmtError(); 6204 6205 auto CS = cast<CapturedStmt>(AStmt); 6206 // 1.2.2 OpenMP Language Terminology 6207 // Structured block - An executable statement with a single entry at the 6208 // top and a single exit at the bottom. 6209 // The point of exit cannot be a branch out of the structured block. 6210 // longjmp() and throw() must not violate the entry/exit criteria. 6211 OpenMPClauseKind AtomicKind = OMPC_unknown; 6212 SourceLocation AtomicKindLoc; 6213 for (auto *C : Clauses) { 6214 if (C->getClauseKind() == OMPC_read || C->getClauseKind() == OMPC_write || 6215 C->getClauseKind() == OMPC_update || 6216 C->getClauseKind() == OMPC_capture) { 6217 if (AtomicKind != OMPC_unknown) { 6218 Diag(C->getLocStart(), diag::err_omp_atomic_several_clauses) 6219 << SourceRange(C->getLocStart(), C->getLocEnd()); 6220 Diag(AtomicKindLoc, diag::note_omp_atomic_previous_clause) 6221 << getOpenMPClauseName(AtomicKind); 6222 } else { 6223 AtomicKind = C->getClauseKind(); 6224 AtomicKindLoc = C->getLocStart(); 6225 } 6226 } 6227 } 6228 6229 auto Body = CS->getCapturedStmt(); 6230 if (auto *EWC = dyn_cast<ExprWithCleanups>(Body)) 6231 Body = EWC->getSubExpr(); 6232 6233 Expr *X = nullptr; 6234 Expr *V = nullptr; 6235 Expr *E = nullptr; 6236 Expr *UE = nullptr; 6237 bool IsXLHSInRHSPart = false; 6238 bool IsPostfixUpdate = false; 6239 // OpenMP [2.12.6, atomic Construct] 6240 // In the next expressions: 6241 // * x and v (as applicable) are both l-value expressions with scalar type. 6242 // * During the execution of an atomic region, multiple syntactic 6243 // occurrences of x must designate the same storage location. 6244 // * Neither of v and expr (as applicable) may access the storage location 6245 // designated by x. 6246 // * Neither of x and expr (as applicable) may access the storage location 6247 // designated by v. 6248 // * expr is an expression with scalar type. 6249 // * binop is one of +, *, -, /, &, ^, |, <<, or >>. 6250 // * binop, binop=, ++, and -- are not overloaded operators. 6251 // * The expression x binop expr must be numerically equivalent to x binop 6252 // (expr). This requirement is satisfied if the operators in expr have 6253 // precedence greater than binop, or by using parentheses around expr or 6254 // subexpressions of expr. 6255 // * The expression expr binop x must be numerically equivalent to (expr) 6256 // binop x. This requirement is satisfied if the operators in expr have 6257 // precedence equal to or greater than binop, or by using parentheses around 6258 // expr or subexpressions of expr. 6259 // * For forms that allow multiple occurrences of x, the number of times 6260 // that x is evaluated is unspecified. 6261 if (AtomicKind == OMPC_read) { 6262 enum { 6263 NotAnExpression, 6264 NotAnAssignmentOp, 6265 NotAScalarType, 6266 NotAnLValue, 6267 NoError 6268 } ErrorFound = NoError; 6269 SourceLocation ErrorLoc, NoteLoc; 6270 SourceRange ErrorRange, NoteRange; 6271 // If clause is read: 6272 // v = x; 6273 if (auto AtomicBody = dyn_cast<Expr>(Body)) { 6274 auto AtomicBinOp = 6275 dyn_cast<BinaryOperator>(AtomicBody->IgnoreParenImpCasts()); 6276 if (AtomicBinOp && AtomicBinOp->getOpcode() == BO_Assign) { 6277 X = AtomicBinOp->getRHS()->IgnoreParenImpCasts(); 6278 V = AtomicBinOp->getLHS()->IgnoreParenImpCasts(); 6279 if ((X->isInstantiationDependent() || X->getType()->isScalarType()) && 6280 (V->isInstantiationDependent() || V->getType()->isScalarType())) { 6281 if (!X->isLValue() || !V->isLValue()) { 6282 auto NotLValueExpr = X->isLValue() ? V : X; 6283 ErrorFound = NotAnLValue; 6284 ErrorLoc = AtomicBinOp->getExprLoc(); 6285 ErrorRange = AtomicBinOp->getSourceRange(); 6286 NoteLoc = NotLValueExpr->getExprLoc(); 6287 NoteRange = NotLValueExpr->getSourceRange(); 6288 } 6289 } else if (!X->isInstantiationDependent() || 6290 !V->isInstantiationDependent()) { 6291 auto NotScalarExpr = 6292 (X->isInstantiationDependent() || X->getType()->isScalarType()) 6293 ? V 6294 : X; 6295 ErrorFound = NotAScalarType; 6296 ErrorLoc = AtomicBinOp->getExprLoc(); 6297 ErrorRange = AtomicBinOp->getSourceRange(); 6298 NoteLoc = NotScalarExpr->getExprLoc(); 6299 NoteRange = NotScalarExpr->getSourceRange(); 6300 } 6301 } else if (!AtomicBody->isInstantiationDependent()) { 6302 ErrorFound = NotAnAssignmentOp; 6303 ErrorLoc = AtomicBody->getExprLoc(); 6304 ErrorRange = AtomicBody->getSourceRange(); 6305 NoteLoc = AtomicBinOp ? AtomicBinOp->getOperatorLoc() 6306 : AtomicBody->getExprLoc(); 6307 NoteRange = AtomicBinOp ? AtomicBinOp->getSourceRange() 6308 : AtomicBody->getSourceRange(); 6309 } 6310 } else { 6311 ErrorFound = NotAnExpression; 6312 NoteLoc = ErrorLoc = Body->getLocStart(); 6313 NoteRange = ErrorRange = SourceRange(NoteLoc, NoteLoc); 6314 } 6315 if (ErrorFound != NoError) { 6316 Diag(ErrorLoc, diag::err_omp_atomic_read_not_expression_statement) 6317 << ErrorRange; 6318 Diag(NoteLoc, diag::note_omp_atomic_read_write) << ErrorFound 6319 << NoteRange; 6320 return StmtError(); 6321 } else if (CurContext->isDependentContext()) 6322 V = X = nullptr; 6323 } else if (AtomicKind == OMPC_write) { 6324 enum { 6325 NotAnExpression, 6326 NotAnAssignmentOp, 6327 NotAScalarType, 6328 NotAnLValue, 6329 NoError 6330 } ErrorFound = NoError; 6331 SourceLocation ErrorLoc, NoteLoc; 6332 SourceRange ErrorRange, NoteRange; 6333 // If clause is write: 6334 // x = expr; 6335 if (auto AtomicBody = dyn_cast<Expr>(Body)) { 6336 auto AtomicBinOp = 6337 dyn_cast<BinaryOperator>(AtomicBody->IgnoreParenImpCasts()); 6338 if (AtomicBinOp && AtomicBinOp->getOpcode() == BO_Assign) { 6339 X = AtomicBinOp->getLHS(); 6340 E = AtomicBinOp->getRHS(); 6341 if ((X->isInstantiationDependent() || X->getType()->isScalarType()) && 6342 (E->isInstantiationDependent() || E->getType()->isScalarType())) { 6343 if (!X->isLValue()) { 6344 ErrorFound = NotAnLValue; 6345 ErrorLoc = AtomicBinOp->getExprLoc(); 6346 ErrorRange = AtomicBinOp->getSourceRange(); 6347 NoteLoc = X->getExprLoc(); 6348 NoteRange = X->getSourceRange(); 6349 } 6350 } else if (!X->isInstantiationDependent() || 6351 !E->isInstantiationDependent()) { 6352 auto NotScalarExpr = 6353 (X->isInstantiationDependent() || X->getType()->isScalarType()) 6354 ? E 6355 : X; 6356 ErrorFound = NotAScalarType; 6357 ErrorLoc = AtomicBinOp->getExprLoc(); 6358 ErrorRange = AtomicBinOp->getSourceRange(); 6359 NoteLoc = NotScalarExpr->getExprLoc(); 6360 NoteRange = NotScalarExpr->getSourceRange(); 6361 } 6362 } else if (!AtomicBody->isInstantiationDependent()) { 6363 ErrorFound = NotAnAssignmentOp; 6364 ErrorLoc = AtomicBody->getExprLoc(); 6365 ErrorRange = AtomicBody->getSourceRange(); 6366 NoteLoc = AtomicBinOp ? AtomicBinOp->getOperatorLoc() 6367 : AtomicBody->getExprLoc(); 6368 NoteRange = AtomicBinOp ? AtomicBinOp->getSourceRange() 6369 : AtomicBody->getSourceRange(); 6370 } 6371 } else { 6372 ErrorFound = NotAnExpression; 6373 NoteLoc = ErrorLoc = Body->getLocStart(); 6374 NoteRange = ErrorRange = SourceRange(NoteLoc, NoteLoc); 6375 } 6376 if (ErrorFound != NoError) { 6377 Diag(ErrorLoc, diag::err_omp_atomic_write_not_expression_statement) 6378 << ErrorRange; 6379 Diag(NoteLoc, diag::note_omp_atomic_read_write) << ErrorFound 6380 << NoteRange; 6381 return StmtError(); 6382 } else if (CurContext->isDependentContext()) 6383 E = X = nullptr; 6384 } else if (AtomicKind == OMPC_update || AtomicKind == OMPC_unknown) { 6385 // If clause is update: 6386 // x++; 6387 // x--; 6388 // ++x; 6389 // --x; 6390 // x binop= expr; 6391 // x = x binop expr; 6392 // x = expr binop x; 6393 OpenMPAtomicUpdateChecker Checker(*this); 6394 if (Checker.checkStatement( 6395 Body, (AtomicKind == OMPC_update) 6396 ? diag::err_omp_atomic_update_not_expression_statement 6397 : diag::err_omp_atomic_not_expression_statement, 6398 diag::note_omp_atomic_update)) 6399 return StmtError(); 6400 if (!CurContext->isDependentContext()) { 6401 E = Checker.getExpr(); 6402 X = Checker.getX(); 6403 UE = Checker.getUpdateExpr(); 6404 IsXLHSInRHSPart = Checker.isXLHSInRHSPart(); 6405 } 6406 } else if (AtomicKind == OMPC_capture) { 6407 enum { 6408 NotAnAssignmentOp, 6409 NotACompoundStatement, 6410 NotTwoSubstatements, 6411 NotASpecificExpression, 6412 NoError 6413 } ErrorFound = NoError; 6414 SourceLocation ErrorLoc, NoteLoc; 6415 SourceRange ErrorRange, NoteRange; 6416 if (auto *AtomicBody = dyn_cast<Expr>(Body)) { 6417 // If clause is a capture: 6418 // v = x++; 6419 // v = x--; 6420 // v = ++x; 6421 // v = --x; 6422 // v = x binop= expr; 6423 // v = x = x binop expr; 6424 // v = x = expr binop x; 6425 auto *AtomicBinOp = 6426 dyn_cast<BinaryOperator>(AtomicBody->IgnoreParenImpCasts()); 6427 if (AtomicBinOp && AtomicBinOp->getOpcode() == BO_Assign) { 6428 V = AtomicBinOp->getLHS(); 6429 Body = AtomicBinOp->getRHS()->IgnoreParenImpCasts(); 6430 OpenMPAtomicUpdateChecker Checker(*this); 6431 if (Checker.checkStatement( 6432 Body, diag::err_omp_atomic_capture_not_expression_statement, 6433 diag::note_omp_atomic_update)) 6434 return StmtError(); 6435 E = Checker.getExpr(); 6436 X = Checker.getX(); 6437 UE = Checker.getUpdateExpr(); 6438 IsXLHSInRHSPart = Checker.isXLHSInRHSPart(); 6439 IsPostfixUpdate = Checker.isPostfixUpdate(); 6440 } else if (!AtomicBody->isInstantiationDependent()) { 6441 ErrorLoc = AtomicBody->getExprLoc(); 6442 ErrorRange = AtomicBody->getSourceRange(); 6443 NoteLoc = AtomicBinOp ? AtomicBinOp->getOperatorLoc() 6444 : AtomicBody->getExprLoc(); 6445 NoteRange = AtomicBinOp ? AtomicBinOp->getSourceRange() 6446 : AtomicBody->getSourceRange(); 6447 ErrorFound = NotAnAssignmentOp; 6448 } 6449 if (ErrorFound != NoError) { 6450 Diag(ErrorLoc, diag::err_omp_atomic_capture_not_expression_statement) 6451 << ErrorRange; 6452 Diag(NoteLoc, diag::note_omp_atomic_capture) << ErrorFound << NoteRange; 6453 return StmtError(); 6454 } else if (CurContext->isDependentContext()) { 6455 UE = V = E = X = nullptr; 6456 } 6457 } else { 6458 // If clause is a capture: 6459 // { v = x; x = expr; } 6460 // { v = x; x++; } 6461 // { v = x; x--; } 6462 // { v = x; ++x; } 6463 // { v = x; --x; } 6464 // { v = x; x binop= expr; } 6465 // { v = x; x = x binop expr; } 6466 // { v = x; x = expr binop x; } 6467 // { x++; v = x; } 6468 // { x--; v = x; } 6469 // { ++x; v = x; } 6470 // { --x; v = x; } 6471 // { x binop= expr; v = x; } 6472 // { x = x binop expr; v = x; } 6473 // { x = expr binop x; v = x; } 6474 if (auto *CS = dyn_cast<CompoundStmt>(Body)) { 6475 // Check that this is { expr1; expr2; } 6476 if (CS->size() == 2) { 6477 auto *First = CS->body_front(); 6478 auto *Second = CS->body_back(); 6479 if (auto *EWC = dyn_cast<ExprWithCleanups>(First)) 6480 First = EWC->getSubExpr()->IgnoreParenImpCasts(); 6481 if (auto *EWC = dyn_cast<ExprWithCleanups>(Second)) 6482 Second = EWC->getSubExpr()->IgnoreParenImpCasts(); 6483 // Need to find what subexpression is 'v' and what is 'x'. 6484 OpenMPAtomicUpdateChecker Checker(*this); 6485 bool IsUpdateExprFound = !Checker.checkStatement(Second); 6486 BinaryOperator *BinOp = nullptr; 6487 if (IsUpdateExprFound) { 6488 BinOp = dyn_cast<BinaryOperator>(First); 6489 IsUpdateExprFound = BinOp && BinOp->getOpcode() == BO_Assign; 6490 } 6491 if (IsUpdateExprFound && !CurContext->isDependentContext()) { 6492 // { v = x; x++; } 6493 // { v = x; x--; } 6494 // { v = x; ++x; } 6495 // { v = x; --x; } 6496 // { v = x; x binop= expr; } 6497 // { v = x; x = x binop expr; } 6498 // { v = x; x = expr binop x; } 6499 // Check that the first expression has form v = x. 6500 auto *PossibleX = BinOp->getRHS()->IgnoreParenImpCasts(); 6501 llvm::FoldingSetNodeID XId, PossibleXId; 6502 Checker.getX()->Profile(XId, Context, /*Canonical=*/true); 6503 PossibleX->Profile(PossibleXId, Context, /*Canonical=*/true); 6504 IsUpdateExprFound = XId == PossibleXId; 6505 if (IsUpdateExprFound) { 6506 V = BinOp->getLHS(); 6507 X = Checker.getX(); 6508 E = Checker.getExpr(); 6509 UE = Checker.getUpdateExpr(); 6510 IsXLHSInRHSPart = Checker.isXLHSInRHSPart(); 6511 IsPostfixUpdate = true; 6512 } 6513 } 6514 if (!IsUpdateExprFound) { 6515 IsUpdateExprFound = !Checker.checkStatement(First); 6516 BinOp = nullptr; 6517 if (IsUpdateExprFound) { 6518 BinOp = dyn_cast<BinaryOperator>(Second); 6519 IsUpdateExprFound = BinOp && BinOp->getOpcode() == BO_Assign; 6520 } 6521 if (IsUpdateExprFound && !CurContext->isDependentContext()) { 6522 // { x++; v = x; } 6523 // { x--; v = x; } 6524 // { ++x; v = x; } 6525 // { --x; v = x; } 6526 // { x binop= expr; v = x; } 6527 // { x = x binop expr; v = x; } 6528 // { x = expr binop x; v = x; } 6529 // Check that the second expression has form v = x. 6530 auto *PossibleX = BinOp->getRHS()->IgnoreParenImpCasts(); 6531 llvm::FoldingSetNodeID XId, PossibleXId; 6532 Checker.getX()->Profile(XId, Context, /*Canonical=*/true); 6533 PossibleX->Profile(PossibleXId, Context, /*Canonical=*/true); 6534 IsUpdateExprFound = XId == PossibleXId; 6535 if (IsUpdateExprFound) { 6536 V = BinOp->getLHS(); 6537 X = Checker.getX(); 6538 E = Checker.getExpr(); 6539 UE = Checker.getUpdateExpr(); 6540 IsXLHSInRHSPart = Checker.isXLHSInRHSPart(); 6541 IsPostfixUpdate = false; 6542 } 6543 } 6544 } 6545 if (!IsUpdateExprFound) { 6546 // { v = x; x = expr; } 6547 auto *FirstExpr = dyn_cast<Expr>(First); 6548 auto *SecondExpr = dyn_cast<Expr>(Second); 6549 if (!FirstExpr || !SecondExpr || 6550 !(FirstExpr->isInstantiationDependent() || 6551 SecondExpr->isInstantiationDependent())) { 6552 auto *FirstBinOp = dyn_cast<BinaryOperator>(First); 6553 if (!FirstBinOp || FirstBinOp->getOpcode() != BO_Assign) { 6554 ErrorFound = NotAnAssignmentOp; 6555 NoteLoc = ErrorLoc = FirstBinOp ? FirstBinOp->getOperatorLoc() 6556 : First->getLocStart(); 6557 NoteRange = ErrorRange = FirstBinOp 6558 ? FirstBinOp->getSourceRange() 6559 : SourceRange(ErrorLoc, ErrorLoc); 6560 } else { 6561 auto *SecondBinOp = dyn_cast<BinaryOperator>(Second); 6562 if (!SecondBinOp || SecondBinOp->getOpcode() != BO_Assign) { 6563 ErrorFound = NotAnAssignmentOp; 6564 NoteLoc = ErrorLoc = SecondBinOp 6565 ? SecondBinOp->getOperatorLoc() 6566 : Second->getLocStart(); 6567 NoteRange = ErrorRange = 6568 SecondBinOp ? SecondBinOp->getSourceRange() 6569 : SourceRange(ErrorLoc, ErrorLoc); 6570 } else { 6571 auto *PossibleXRHSInFirst = 6572 FirstBinOp->getRHS()->IgnoreParenImpCasts(); 6573 auto *PossibleXLHSInSecond = 6574 SecondBinOp->getLHS()->IgnoreParenImpCasts(); 6575 llvm::FoldingSetNodeID X1Id, X2Id; 6576 PossibleXRHSInFirst->Profile(X1Id, Context, 6577 /*Canonical=*/true); 6578 PossibleXLHSInSecond->Profile(X2Id, Context, 6579 /*Canonical=*/true); 6580 IsUpdateExprFound = X1Id == X2Id; 6581 if (IsUpdateExprFound) { 6582 V = FirstBinOp->getLHS(); 6583 X = SecondBinOp->getLHS(); 6584 E = SecondBinOp->getRHS(); 6585 UE = nullptr; 6586 IsXLHSInRHSPart = false; 6587 IsPostfixUpdate = true; 6588 } else { 6589 ErrorFound = NotASpecificExpression; 6590 ErrorLoc = FirstBinOp->getExprLoc(); 6591 ErrorRange = FirstBinOp->getSourceRange(); 6592 NoteLoc = SecondBinOp->getLHS()->getExprLoc(); 6593 NoteRange = SecondBinOp->getRHS()->getSourceRange(); 6594 } 6595 } 6596 } 6597 } 6598 } 6599 } else { 6600 NoteLoc = ErrorLoc = Body->getLocStart(); 6601 NoteRange = ErrorRange = 6602 SourceRange(Body->getLocStart(), Body->getLocStart()); 6603 ErrorFound = NotTwoSubstatements; 6604 } 6605 } else { 6606 NoteLoc = ErrorLoc = Body->getLocStart(); 6607 NoteRange = ErrorRange = 6608 SourceRange(Body->getLocStart(), Body->getLocStart()); 6609 ErrorFound = NotACompoundStatement; 6610 } 6611 if (ErrorFound != NoError) { 6612 Diag(ErrorLoc, diag::err_omp_atomic_capture_not_compound_statement) 6613 << ErrorRange; 6614 Diag(NoteLoc, diag::note_omp_atomic_capture) << ErrorFound << NoteRange; 6615 return StmtError(); 6616 } else if (CurContext->isDependentContext()) { 6617 UE = V = E = X = nullptr; 6618 } 6619 } 6620 } 6621 6622 getCurFunction()->setHasBranchProtectedScope(); 6623 6624 return OMPAtomicDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt, 6625 X, V, E, UE, IsXLHSInRHSPart, 6626 IsPostfixUpdate); 6627 } 6628 6629 StmtResult Sema::ActOnOpenMPTargetDirective(ArrayRef<OMPClause *> Clauses, 6630 Stmt *AStmt, 6631 SourceLocation StartLoc, 6632 SourceLocation EndLoc) { 6633 if (!AStmt) 6634 return StmtError(); 6635 6636 CapturedStmt *CS = cast<CapturedStmt>(AStmt); 6637 // 1.2.2 OpenMP Language Terminology 6638 // Structured block - An executable statement with a single entry at the 6639 // top and a single exit at the bottom. 6640 // The point of exit cannot be a branch out of the structured block. 6641 // longjmp() and throw() must not violate the entry/exit criteria. 6642 CS->getCapturedDecl()->setNothrow(); 6643 6644 // OpenMP [2.16, Nesting of Regions] 6645 // If specified, a teams construct must be contained within a target 6646 // construct. That target construct must contain no statements or directives 6647 // outside of the teams construct. 6648 if (DSAStack->hasInnerTeamsRegion()) { 6649 auto S = AStmt->IgnoreContainers(/*IgnoreCaptured*/ true); 6650 bool OMPTeamsFound = true; 6651 if (auto *CS = dyn_cast<CompoundStmt>(S)) { 6652 auto I = CS->body_begin(); 6653 while (I != CS->body_end()) { 6654 auto OED = dyn_cast<OMPExecutableDirective>(*I); 6655 if (!OED || !isOpenMPTeamsDirective(OED->getDirectiveKind())) { 6656 OMPTeamsFound = false; 6657 break; 6658 } 6659 ++I; 6660 } 6661 assert(I != CS->body_end() && "Not found statement"); 6662 S = *I; 6663 } else { 6664 auto *OED = dyn_cast<OMPExecutableDirective>(S); 6665 OMPTeamsFound = OED && isOpenMPTeamsDirective(OED->getDirectiveKind()); 6666 } 6667 if (!OMPTeamsFound) { 6668 Diag(StartLoc, diag::err_omp_target_contains_not_only_teams); 6669 Diag(DSAStack->getInnerTeamsRegionLoc(), 6670 diag::note_omp_nested_teams_construct_here); 6671 Diag(S->getLocStart(), diag::note_omp_nested_statement_here) 6672 << isa<OMPExecutableDirective>(S); 6673 return StmtError(); 6674 } 6675 } 6676 6677 getCurFunction()->setHasBranchProtectedScope(); 6678 6679 return OMPTargetDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt); 6680 } 6681 6682 StmtResult 6683 Sema::ActOnOpenMPTargetParallelDirective(ArrayRef<OMPClause *> Clauses, 6684 Stmt *AStmt, SourceLocation StartLoc, 6685 SourceLocation EndLoc) { 6686 if (!AStmt) 6687 return StmtError(); 6688 6689 CapturedStmt *CS = cast<CapturedStmt>(AStmt); 6690 // 1.2.2 OpenMP Language Terminology 6691 // Structured block - An executable statement with a single entry at the 6692 // top and a single exit at the bottom. 6693 // The point of exit cannot be a branch out of the structured block. 6694 // longjmp() and throw() must not violate the entry/exit criteria. 6695 CS->getCapturedDecl()->setNothrow(); 6696 6697 getCurFunction()->setHasBranchProtectedScope(); 6698 6699 return OMPTargetParallelDirective::Create(Context, StartLoc, EndLoc, Clauses, 6700 AStmt); 6701 } 6702 6703 StmtResult Sema::ActOnOpenMPTargetParallelForDirective( 6704 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, 6705 SourceLocation EndLoc, 6706 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) { 6707 if (!AStmt) 6708 return StmtError(); 6709 6710 CapturedStmt *CS = cast<CapturedStmt>(AStmt); 6711 // 1.2.2 OpenMP Language Terminology 6712 // Structured block - An executable statement with a single entry at the 6713 // top and a single exit at the bottom. 6714 // The point of exit cannot be a branch out of the structured block. 6715 // longjmp() and throw() must not violate the entry/exit criteria. 6716 CS->getCapturedDecl()->setNothrow(); 6717 6718 OMPLoopDirective::HelperExprs B; 6719 // In presence of clause 'collapse' or 'ordered' with number of loops, it will 6720 // define the nested loops number. 6721 unsigned NestedLoopCount = 6722 CheckOpenMPLoop(OMPD_target_parallel_for, getCollapseNumberExpr(Clauses), 6723 getOrderedNumberExpr(Clauses), AStmt, *this, *DSAStack, 6724 VarsWithImplicitDSA, B); 6725 if (NestedLoopCount == 0) 6726 return StmtError(); 6727 6728 assert((CurContext->isDependentContext() || B.builtAll()) && 6729 "omp target parallel for loop exprs were not built"); 6730 6731 if (!CurContext->isDependentContext()) { 6732 // Finalize the clauses that need pre-built expressions for CodeGen. 6733 for (auto C : Clauses) { 6734 if (auto LC = dyn_cast<OMPLinearClause>(C)) 6735 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef), 6736 B.NumIterations, *this, CurScope, 6737 DSAStack)) 6738 return StmtError(); 6739 } 6740 } 6741 6742 getCurFunction()->setHasBranchProtectedScope(); 6743 return OMPTargetParallelForDirective::Create(Context, StartLoc, EndLoc, 6744 NestedLoopCount, Clauses, AStmt, 6745 B, DSAStack->isCancelRegion()); 6746 } 6747 6748 /// \brief Check for existence of a map clause in the list of clauses. 6749 static bool HasMapClause(ArrayRef<OMPClause *> Clauses) { 6750 for (ArrayRef<OMPClause *>::iterator I = Clauses.begin(), E = Clauses.end(); 6751 I != E; ++I) { 6752 if (*I != nullptr && (*I)->getClauseKind() == OMPC_map) { 6753 return true; 6754 } 6755 } 6756 6757 return false; 6758 } 6759 6760 StmtResult Sema::ActOnOpenMPTargetDataDirective(ArrayRef<OMPClause *> Clauses, 6761 Stmt *AStmt, 6762 SourceLocation StartLoc, 6763 SourceLocation EndLoc) { 6764 if (!AStmt) 6765 return StmtError(); 6766 6767 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected"); 6768 6769 // OpenMP [2.10.1, Restrictions, p. 97] 6770 // At least one map clause must appear on the directive. 6771 if (!HasMapClause(Clauses)) { 6772 Diag(StartLoc, diag::err_omp_no_map_for_directive) << 6773 getOpenMPDirectiveName(OMPD_target_data); 6774 return StmtError(); 6775 } 6776 6777 getCurFunction()->setHasBranchProtectedScope(); 6778 6779 return OMPTargetDataDirective::Create(Context, StartLoc, EndLoc, Clauses, 6780 AStmt); 6781 } 6782 6783 StmtResult 6784 Sema::ActOnOpenMPTargetEnterDataDirective(ArrayRef<OMPClause *> Clauses, 6785 SourceLocation StartLoc, 6786 SourceLocation EndLoc) { 6787 // OpenMP [2.10.2, Restrictions, p. 99] 6788 // At least one map clause must appear on the directive. 6789 if (!HasMapClause(Clauses)) { 6790 Diag(StartLoc, diag::err_omp_no_map_for_directive) 6791 << getOpenMPDirectiveName(OMPD_target_enter_data); 6792 return StmtError(); 6793 } 6794 6795 return OMPTargetEnterDataDirective::Create(Context, StartLoc, EndLoc, 6796 Clauses); 6797 } 6798 6799 StmtResult 6800 Sema::ActOnOpenMPTargetExitDataDirective(ArrayRef<OMPClause *> Clauses, 6801 SourceLocation StartLoc, 6802 SourceLocation EndLoc) { 6803 // OpenMP [2.10.3, Restrictions, p. 102] 6804 // At least one map clause must appear on the directive. 6805 if (!HasMapClause(Clauses)) { 6806 Diag(StartLoc, diag::err_omp_no_map_for_directive) 6807 << getOpenMPDirectiveName(OMPD_target_exit_data); 6808 return StmtError(); 6809 } 6810 6811 return OMPTargetExitDataDirective::Create(Context, StartLoc, EndLoc, Clauses); 6812 } 6813 6814 StmtResult Sema::ActOnOpenMPTargetUpdateDirective(ArrayRef<OMPClause *> Clauses, 6815 SourceLocation StartLoc, 6816 SourceLocation EndLoc) { 6817 bool seenMotionClause = false; 6818 for (auto *C : Clauses) { 6819 if (C->getClauseKind() == OMPC_to || C->getClauseKind() == OMPC_from) 6820 seenMotionClause = true; 6821 } 6822 if (!seenMotionClause) { 6823 Diag(StartLoc, diag::err_omp_at_least_one_motion_clause_required); 6824 return StmtError(); 6825 } 6826 return OMPTargetUpdateDirective::Create(Context, StartLoc, EndLoc, Clauses); 6827 } 6828 6829 StmtResult Sema::ActOnOpenMPTeamsDirective(ArrayRef<OMPClause *> Clauses, 6830 Stmt *AStmt, SourceLocation StartLoc, 6831 SourceLocation EndLoc) { 6832 if (!AStmt) 6833 return StmtError(); 6834 6835 CapturedStmt *CS = cast<CapturedStmt>(AStmt); 6836 // 1.2.2 OpenMP Language Terminology 6837 // Structured block - An executable statement with a single entry at the 6838 // top and a single exit at the bottom. 6839 // The point of exit cannot be a branch out of the structured block. 6840 // longjmp() and throw() must not violate the entry/exit criteria. 6841 CS->getCapturedDecl()->setNothrow(); 6842 6843 getCurFunction()->setHasBranchProtectedScope(); 6844 6845 return OMPTeamsDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt); 6846 } 6847 6848 StmtResult 6849 Sema::ActOnOpenMPCancellationPointDirective(SourceLocation StartLoc, 6850 SourceLocation EndLoc, 6851 OpenMPDirectiveKind CancelRegion) { 6852 if (CancelRegion != OMPD_parallel && CancelRegion != OMPD_for && 6853 CancelRegion != OMPD_sections && CancelRegion != OMPD_taskgroup) { 6854 Diag(StartLoc, diag::err_omp_wrong_cancel_region) 6855 << getOpenMPDirectiveName(CancelRegion); 6856 return StmtError(); 6857 } 6858 if (DSAStack->isParentNowaitRegion()) { 6859 Diag(StartLoc, diag::err_omp_parent_cancel_region_nowait) << 0; 6860 return StmtError(); 6861 } 6862 if (DSAStack->isParentOrderedRegion()) { 6863 Diag(StartLoc, diag::err_omp_parent_cancel_region_ordered) << 0; 6864 return StmtError(); 6865 } 6866 return OMPCancellationPointDirective::Create(Context, StartLoc, EndLoc, 6867 CancelRegion); 6868 } 6869 6870 StmtResult Sema::ActOnOpenMPCancelDirective(ArrayRef<OMPClause *> Clauses, 6871 SourceLocation StartLoc, 6872 SourceLocation EndLoc, 6873 OpenMPDirectiveKind CancelRegion) { 6874 if (CancelRegion != OMPD_parallel && CancelRegion != OMPD_for && 6875 CancelRegion != OMPD_sections && CancelRegion != OMPD_taskgroup) { 6876 Diag(StartLoc, diag::err_omp_wrong_cancel_region) 6877 << getOpenMPDirectiveName(CancelRegion); 6878 return StmtError(); 6879 } 6880 if (DSAStack->isParentNowaitRegion()) { 6881 Diag(StartLoc, diag::err_omp_parent_cancel_region_nowait) << 1; 6882 return StmtError(); 6883 } 6884 if (DSAStack->isParentOrderedRegion()) { 6885 Diag(StartLoc, diag::err_omp_parent_cancel_region_ordered) << 1; 6886 return StmtError(); 6887 } 6888 DSAStack->setParentCancelRegion(/*Cancel=*/true); 6889 return OMPCancelDirective::Create(Context, StartLoc, EndLoc, Clauses, 6890 CancelRegion); 6891 } 6892 6893 static bool checkGrainsizeNumTasksClauses(Sema &S, 6894 ArrayRef<OMPClause *> Clauses) { 6895 OMPClause *PrevClause = nullptr; 6896 bool ErrorFound = false; 6897 for (auto *C : Clauses) { 6898 if (C->getClauseKind() == OMPC_grainsize || 6899 C->getClauseKind() == OMPC_num_tasks) { 6900 if (!PrevClause) 6901 PrevClause = C; 6902 else if (PrevClause->getClauseKind() != C->getClauseKind()) { 6903 S.Diag(C->getLocStart(), 6904 diag::err_omp_grainsize_num_tasks_mutually_exclusive) 6905 << getOpenMPClauseName(C->getClauseKind()) 6906 << getOpenMPClauseName(PrevClause->getClauseKind()); 6907 S.Diag(PrevClause->getLocStart(), 6908 diag::note_omp_previous_grainsize_num_tasks) 6909 << getOpenMPClauseName(PrevClause->getClauseKind()); 6910 ErrorFound = true; 6911 } 6912 } 6913 } 6914 return ErrorFound; 6915 } 6916 6917 StmtResult Sema::ActOnOpenMPTaskLoopDirective( 6918 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, 6919 SourceLocation EndLoc, 6920 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) { 6921 if (!AStmt) 6922 return StmtError(); 6923 6924 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected"); 6925 OMPLoopDirective::HelperExprs B; 6926 // In presence of clause 'collapse' or 'ordered' with number of loops, it will 6927 // define the nested loops number. 6928 unsigned NestedLoopCount = 6929 CheckOpenMPLoop(OMPD_taskloop, getCollapseNumberExpr(Clauses), 6930 /*OrderedLoopCountExpr=*/nullptr, AStmt, *this, *DSAStack, 6931 VarsWithImplicitDSA, B); 6932 if (NestedLoopCount == 0) 6933 return StmtError(); 6934 6935 assert((CurContext->isDependentContext() || B.builtAll()) && 6936 "omp for loop exprs were not built"); 6937 6938 // OpenMP, [2.9.2 taskloop Construct, Restrictions] 6939 // The grainsize clause and num_tasks clause are mutually exclusive and may 6940 // not appear on the same taskloop directive. 6941 if (checkGrainsizeNumTasksClauses(*this, Clauses)) 6942 return StmtError(); 6943 6944 getCurFunction()->setHasBranchProtectedScope(); 6945 return OMPTaskLoopDirective::Create(Context, StartLoc, EndLoc, 6946 NestedLoopCount, Clauses, AStmt, B); 6947 } 6948 6949 StmtResult Sema::ActOnOpenMPTaskLoopSimdDirective( 6950 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, 6951 SourceLocation EndLoc, 6952 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) { 6953 if (!AStmt) 6954 return StmtError(); 6955 6956 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected"); 6957 OMPLoopDirective::HelperExprs B; 6958 // In presence of clause 'collapse' or 'ordered' with number of loops, it will 6959 // define the nested loops number. 6960 unsigned NestedLoopCount = 6961 CheckOpenMPLoop(OMPD_taskloop_simd, getCollapseNumberExpr(Clauses), 6962 /*OrderedLoopCountExpr=*/nullptr, AStmt, *this, *DSAStack, 6963 VarsWithImplicitDSA, B); 6964 if (NestedLoopCount == 0) 6965 return StmtError(); 6966 6967 assert((CurContext->isDependentContext() || B.builtAll()) && 6968 "omp for loop exprs were not built"); 6969 6970 if (!CurContext->isDependentContext()) { 6971 // Finalize the clauses that need pre-built expressions for CodeGen. 6972 for (auto C : Clauses) { 6973 if (auto LC = dyn_cast<OMPLinearClause>(C)) 6974 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef), 6975 B.NumIterations, *this, CurScope, 6976 DSAStack)) 6977 return StmtError(); 6978 } 6979 } 6980 6981 // OpenMP, [2.9.2 taskloop Construct, Restrictions] 6982 // The grainsize clause and num_tasks clause are mutually exclusive and may 6983 // not appear on the same taskloop directive. 6984 if (checkGrainsizeNumTasksClauses(*this, Clauses)) 6985 return StmtError(); 6986 6987 getCurFunction()->setHasBranchProtectedScope(); 6988 return OMPTaskLoopSimdDirective::Create(Context, StartLoc, EndLoc, 6989 NestedLoopCount, Clauses, AStmt, B); 6990 } 6991 6992 StmtResult Sema::ActOnOpenMPDistributeDirective( 6993 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, 6994 SourceLocation EndLoc, 6995 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) { 6996 if (!AStmt) 6997 return StmtError(); 6998 6999 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected"); 7000 OMPLoopDirective::HelperExprs B; 7001 // In presence of clause 'collapse' with number of loops, it will 7002 // define the nested loops number. 7003 unsigned NestedLoopCount = 7004 CheckOpenMPLoop(OMPD_distribute, getCollapseNumberExpr(Clauses), 7005 nullptr /*ordered not a clause on distribute*/, AStmt, 7006 *this, *DSAStack, VarsWithImplicitDSA, B); 7007 if (NestedLoopCount == 0) 7008 return StmtError(); 7009 7010 assert((CurContext->isDependentContext() || B.builtAll()) && 7011 "omp for loop exprs were not built"); 7012 7013 getCurFunction()->setHasBranchProtectedScope(); 7014 return OMPDistributeDirective::Create(Context, StartLoc, EndLoc, 7015 NestedLoopCount, Clauses, AStmt, B); 7016 } 7017 7018 StmtResult Sema::ActOnOpenMPDistributeParallelForDirective( 7019 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, 7020 SourceLocation EndLoc, 7021 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) { 7022 if (!AStmt) 7023 return StmtError(); 7024 7025 CapturedStmt *CS = cast<CapturedStmt>(AStmt); 7026 // 1.2.2 OpenMP Language Terminology 7027 // Structured block - An executable statement with a single entry at the 7028 // top and a single exit at the bottom. 7029 // The point of exit cannot be a branch out of the structured block. 7030 // longjmp() and throw() must not violate the entry/exit criteria. 7031 CS->getCapturedDecl()->setNothrow(); 7032 7033 OMPLoopDirective::HelperExprs B; 7034 // In presence of clause 'collapse' with number of loops, it will 7035 // define the nested loops number. 7036 unsigned NestedLoopCount = CheckOpenMPLoop( 7037 OMPD_distribute_parallel_for, getCollapseNumberExpr(Clauses), 7038 nullptr /*ordered not a clause on distribute*/, AStmt, *this, *DSAStack, 7039 VarsWithImplicitDSA, B); 7040 if (NestedLoopCount == 0) 7041 return StmtError(); 7042 7043 assert((CurContext->isDependentContext() || B.builtAll()) && 7044 "omp for loop exprs were not built"); 7045 7046 getCurFunction()->setHasBranchProtectedScope(); 7047 return OMPDistributeParallelForDirective::Create( 7048 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B); 7049 } 7050 7051 StmtResult Sema::ActOnOpenMPDistributeParallelForSimdDirective( 7052 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, 7053 SourceLocation EndLoc, 7054 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) { 7055 if (!AStmt) 7056 return StmtError(); 7057 7058 CapturedStmt *CS = cast<CapturedStmt>(AStmt); 7059 // 1.2.2 OpenMP Language Terminology 7060 // Structured block - An executable statement with a single entry at the 7061 // top and a single exit at the bottom. 7062 // The point of exit cannot be a branch out of the structured block. 7063 // longjmp() and throw() must not violate the entry/exit criteria. 7064 CS->getCapturedDecl()->setNothrow(); 7065 7066 OMPLoopDirective::HelperExprs B; 7067 // In presence of clause 'collapse' with number of loops, it will 7068 // define the nested loops number. 7069 unsigned NestedLoopCount = CheckOpenMPLoop( 7070 OMPD_distribute_parallel_for_simd, getCollapseNumberExpr(Clauses), 7071 nullptr /*ordered not a clause on distribute*/, AStmt, *this, *DSAStack, 7072 VarsWithImplicitDSA, B); 7073 if (NestedLoopCount == 0) 7074 return StmtError(); 7075 7076 assert((CurContext->isDependentContext() || B.builtAll()) && 7077 "omp for loop exprs were not built"); 7078 7079 getCurFunction()->setHasBranchProtectedScope(); 7080 return OMPDistributeParallelForSimdDirective::Create( 7081 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B); 7082 } 7083 7084 OMPClause *Sema::ActOnOpenMPSingleExprClause(OpenMPClauseKind Kind, Expr *Expr, 7085 SourceLocation StartLoc, 7086 SourceLocation LParenLoc, 7087 SourceLocation EndLoc) { 7088 OMPClause *Res = nullptr; 7089 switch (Kind) { 7090 case OMPC_final: 7091 Res = ActOnOpenMPFinalClause(Expr, StartLoc, LParenLoc, EndLoc); 7092 break; 7093 case OMPC_num_threads: 7094 Res = ActOnOpenMPNumThreadsClause(Expr, StartLoc, LParenLoc, EndLoc); 7095 break; 7096 case OMPC_safelen: 7097 Res = ActOnOpenMPSafelenClause(Expr, StartLoc, LParenLoc, EndLoc); 7098 break; 7099 case OMPC_simdlen: 7100 Res = ActOnOpenMPSimdlenClause(Expr, StartLoc, LParenLoc, EndLoc); 7101 break; 7102 case OMPC_collapse: 7103 Res = ActOnOpenMPCollapseClause(Expr, StartLoc, LParenLoc, EndLoc); 7104 break; 7105 case OMPC_ordered: 7106 Res = ActOnOpenMPOrderedClause(StartLoc, EndLoc, LParenLoc, Expr); 7107 break; 7108 case OMPC_device: 7109 Res = ActOnOpenMPDeviceClause(Expr, StartLoc, LParenLoc, EndLoc); 7110 break; 7111 case OMPC_num_teams: 7112 Res = ActOnOpenMPNumTeamsClause(Expr, StartLoc, LParenLoc, EndLoc); 7113 break; 7114 case OMPC_thread_limit: 7115 Res = ActOnOpenMPThreadLimitClause(Expr, StartLoc, LParenLoc, EndLoc); 7116 break; 7117 case OMPC_priority: 7118 Res = ActOnOpenMPPriorityClause(Expr, StartLoc, LParenLoc, EndLoc); 7119 break; 7120 case OMPC_grainsize: 7121 Res = ActOnOpenMPGrainsizeClause(Expr, StartLoc, LParenLoc, EndLoc); 7122 break; 7123 case OMPC_num_tasks: 7124 Res = ActOnOpenMPNumTasksClause(Expr, StartLoc, LParenLoc, EndLoc); 7125 break; 7126 case OMPC_hint: 7127 Res = ActOnOpenMPHintClause(Expr, StartLoc, LParenLoc, EndLoc); 7128 break; 7129 case OMPC_if: 7130 case OMPC_default: 7131 case OMPC_proc_bind: 7132 case OMPC_schedule: 7133 case OMPC_private: 7134 case OMPC_firstprivate: 7135 case OMPC_lastprivate: 7136 case OMPC_shared: 7137 case OMPC_reduction: 7138 case OMPC_linear: 7139 case OMPC_aligned: 7140 case OMPC_copyin: 7141 case OMPC_copyprivate: 7142 case OMPC_nowait: 7143 case OMPC_untied: 7144 case OMPC_mergeable: 7145 case OMPC_threadprivate: 7146 case OMPC_flush: 7147 case OMPC_read: 7148 case OMPC_write: 7149 case OMPC_update: 7150 case OMPC_capture: 7151 case OMPC_seq_cst: 7152 case OMPC_depend: 7153 case OMPC_threads: 7154 case OMPC_simd: 7155 case OMPC_map: 7156 case OMPC_nogroup: 7157 case OMPC_dist_schedule: 7158 case OMPC_defaultmap: 7159 case OMPC_unknown: 7160 case OMPC_uniform: 7161 case OMPC_to: 7162 case OMPC_from: 7163 llvm_unreachable("Clause is not allowed."); 7164 } 7165 return Res; 7166 } 7167 7168 OMPClause *Sema::ActOnOpenMPIfClause(OpenMPDirectiveKind NameModifier, 7169 Expr *Condition, SourceLocation StartLoc, 7170 SourceLocation LParenLoc, 7171 SourceLocation NameModifierLoc, 7172 SourceLocation ColonLoc, 7173 SourceLocation EndLoc) { 7174 Expr *ValExpr = Condition; 7175 if (!Condition->isValueDependent() && !Condition->isTypeDependent() && 7176 !Condition->isInstantiationDependent() && 7177 !Condition->containsUnexpandedParameterPack()) { 7178 ExprResult Val = CheckBooleanCondition(StartLoc, Condition); 7179 if (Val.isInvalid()) 7180 return nullptr; 7181 7182 ValExpr = MakeFullExpr(Val.get()).get(); 7183 } 7184 7185 return new (Context) OMPIfClause(NameModifier, ValExpr, StartLoc, LParenLoc, 7186 NameModifierLoc, ColonLoc, EndLoc); 7187 } 7188 7189 OMPClause *Sema::ActOnOpenMPFinalClause(Expr *Condition, 7190 SourceLocation StartLoc, 7191 SourceLocation LParenLoc, 7192 SourceLocation EndLoc) { 7193 Expr *ValExpr = Condition; 7194 if (!Condition->isValueDependent() && !Condition->isTypeDependent() && 7195 !Condition->isInstantiationDependent() && 7196 !Condition->containsUnexpandedParameterPack()) { 7197 ExprResult Val = CheckBooleanCondition(StartLoc, Condition); 7198 if (Val.isInvalid()) 7199 return nullptr; 7200 7201 ValExpr = MakeFullExpr(Val.get()).get(); 7202 } 7203 7204 return new (Context) OMPFinalClause(ValExpr, StartLoc, LParenLoc, EndLoc); 7205 } 7206 ExprResult Sema::PerformOpenMPImplicitIntegerConversion(SourceLocation Loc, 7207 Expr *Op) { 7208 if (!Op) 7209 return ExprError(); 7210 7211 class IntConvertDiagnoser : public ICEConvertDiagnoser { 7212 public: 7213 IntConvertDiagnoser() 7214 : ICEConvertDiagnoser(/*AllowScopedEnumerations*/ false, false, true) {} 7215 SemaDiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc, 7216 QualType T) override { 7217 return S.Diag(Loc, diag::err_omp_not_integral) << T; 7218 } 7219 SemaDiagnosticBuilder diagnoseIncomplete(Sema &S, SourceLocation Loc, 7220 QualType T) override { 7221 return S.Diag(Loc, diag::err_omp_incomplete_type) << T; 7222 } 7223 SemaDiagnosticBuilder diagnoseExplicitConv(Sema &S, SourceLocation Loc, 7224 QualType T, 7225 QualType ConvTy) override { 7226 return S.Diag(Loc, diag::err_omp_explicit_conversion) << T << ConvTy; 7227 } 7228 SemaDiagnosticBuilder noteExplicitConv(Sema &S, CXXConversionDecl *Conv, 7229 QualType ConvTy) override { 7230 return S.Diag(Conv->getLocation(), diag::note_omp_conversion_here) 7231 << ConvTy->isEnumeralType() << ConvTy; 7232 } 7233 SemaDiagnosticBuilder diagnoseAmbiguous(Sema &S, SourceLocation Loc, 7234 QualType T) override { 7235 return S.Diag(Loc, diag::err_omp_ambiguous_conversion) << T; 7236 } 7237 SemaDiagnosticBuilder noteAmbiguous(Sema &S, CXXConversionDecl *Conv, 7238 QualType ConvTy) override { 7239 return S.Diag(Conv->getLocation(), diag::note_omp_conversion_here) 7240 << ConvTy->isEnumeralType() << ConvTy; 7241 } 7242 SemaDiagnosticBuilder diagnoseConversion(Sema &, SourceLocation, QualType, 7243 QualType) override { 7244 llvm_unreachable("conversion functions are permitted"); 7245 } 7246 } ConvertDiagnoser; 7247 return PerformContextualImplicitConversion(Loc, Op, ConvertDiagnoser); 7248 } 7249 7250 static bool IsNonNegativeIntegerValue(Expr *&ValExpr, Sema &SemaRef, 7251 OpenMPClauseKind CKind, 7252 bool StrictlyPositive) { 7253 if (!ValExpr->isTypeDependent() && !ValExpr->isValueDependent() && 7254 !ValExpr->isInstantiationDependent()) { 7255 SourceLocation Loc = ValExpr->getExprLoc(); 7256 ExprResult Value = 7257 SemaRef.PerformOpenMPImplicitIntegerConversion(Loc, ValExpr); 7258 if (Value.isInvalid()) 7259 return false; 7260 7261 ValExpr = Value.get(); 7262 // The expression must evaluate to a non-negative integer value. 7263 llvm::APSInt Result; 7264 if (ValExpr->isIntegerConstantExpr(Result, SemaRef.Context) && 7265 Result.isSigned() && 7266 !((!StrictlyPositive && Result.isNonNegative()) || 7267 (StrictlyPositive && Result.isStrictlyPositive()))) { 7268 SemaRef.Diag(Loc, diag::err_omp_negative_expression_in_clause) 7269 << getOpenMPClauseName(CKind) << (StrictlyPositive ? 1 : 0) 7270 << ValExpr->getSourceRange(); 7271 return false; 7272 } 7273 } 7274 return true; 7275 } 7276 7277 OMPClause *Sema::ActOnOpenMPNumThreadsClause(Expr *NumThreads, 7278 SourceLocation StartLoc, 7279 SourceLocation LParenLoc, 7280 SourceLocation EndLoc) { 7281 Expr *ValExpr = NumThreads; 7282 7283 // OpenMP [2.5, Restrictions] 7284 // The num_threads expression must evaluate to a positive integer value. 7285 if (!IsNonNegativeIntegerValue(ValExpr, *this, OMPC_num_threads, 7286 /*StrictlyPositive=*/true)) 7287 return nullptr; 7288 7289 return new (Context) 7290 OMPNumThreadsClause(ValExpr, StartLoc, LParenLoc, EndLoc); 7291 } 7292 7293 ExprResult Sema::VerifyPositiveIntegerConstantInClause(Expr *E, 7294 OpenMPClauseKind CKind, 7295 bool StrictlyPositive) { 7296 if (!E) 7297 return ExprError(); 7298 if (E->isValueDependent() || E->isTypeDependent() || 7299 E->isInstantiationDependent() || E->containsUnexpandedParameterPack()) 7300 return E; 7301 llvm::APSInt Result; 7302 ExprResult ICE = VerifyIntegerConstantExpression(E, &Result); 7303 if (ICE.isInvalid()) 7304 return ExprError(); 7305 if ((StrictlyPositive && !Result.isStrictlyPositive()) || 7306 (!StrictlyPositive && !Result.isNonNegative())) { 7307 Diag(E->getExprLoc(), diag::err_omp_negative_expression_in_clause) 7308 << getOpenMPClauseName(CKind) << (StrictlyPositive ? 1 : 0) 7309 << E->getSourceRange(); 7310 return ExprError(); 7311 } 7312 if (CKind == OMPC_aligned && !Result.isPowerOf2()) { 7313 Diag(E->getExprLoc(), diag::warn_omp_alignment_not_power_of_two) 7314 << E->getSourceRange(); 7315 return ExprError(); 7316 } 7317 if (CKind == OMPC_collapse && DSAStack->getAssociatedLoops() == 1) 7318 DSAStack->setAssociatedLoops(Result.getExtValue()); 7319 else if (CKind == OMPC_ordered) 7320 DSAStack->setAssociatedLoops(Result.getExtValue()); 7321 return ICE; 7322 } 7323 7324 OMPClause *Sema::ActOnOpenMPSafelenClause(Expr *Len, SourceLocation StartLoc, 7325 SourceLocation LParenLoc, 7326 SourceLocation EndLoc) { 7327 // OpenMP [2.8.1, simd construct, Description] 7328 // The parameter of the safelen clause must be a constant 7329 // positive integer expression. 7330 ExprResult Safelen = VerifyPositiveIntegerConstantInClause(Len, OMPC_safelen); 7331 if (Safelen.isInvalid()) 7332 return nullptr; 7333 return new (Context) 7334 OMPSafelenClause(Safelen.get(), StartLoc, LParenLoc, EndLoc); 7335 } 7336 7337 OMPClause *Sema::ActOnOpenMPSimdlenClause(Expr *Len, SourceLocation StartLoc, 7338 SourceLocation LParenLoc, 7339 SourceLocation EndLoc) { 7340 // OpenMP [2.8.1, simd construct, Description] 7341 // The parameter of the simdlen clause must be a constant 7342 // positive integer expression. 7343 ExprResult Simdlen = VerifyPositiveIntegerConstantInClause(Len, OMPC_simdlen); 7344 if (Simdlen.isInvalid()) 7345 return nullptr; 7346 return new (Context) 7347 OMPSimdlenClause(Simdlen.get(), StartLoc, LParenLoc, EndLoc); 7348 } 7349 7350 OMPClause *Sema::ActOnOpenMPCollapseClause(Expr *NumForLoops, 7351 SourceLocation StartLoc, 7352 SourceLocation LParenLoc, 7353 SourceLocation EndLoc) { 7354 // OpenMP [2.7.1, loop construct, Description] 7355 // OpenMP [2.8.1, simd construct, Description] 7356 // OpenMP [2.9.6, distribute construct, Description] 7357 // The parameter of the collapse clause must be a constant 7358 // positive integer expression. 7359 ExprResult NumForLoopsResult = 7360 VerifyPositiveIntegerConstantInClause(NumForLoops, OMPC_collapse); 7361 if (NumForLoopsResult.isInvalid()) 7362 return nullptr; 7363 return new (Context) 7364 OMPCollapseClause(NumForLoopsResult.get(), StartLoc, LParenLoc, EndLoc); 7365 } 7366 7367 OMPClause *Sema::ActOnOpenMPOrderedClause(SourceLocation StartLoc, 7368 SourceLocation EndLoc, 7369 SourceLocation LParenLoc, 7370 Expr *NumForLoops) { 7371 // OpenMP [2.7.1, loop construct, Description] 7372 // OpenMP [2.8.1, simd construct, Description] 7373 // OpenMP [2.9.6, distribute construct, Description] 7374 // The parameter of the ordered clause must be a constant 7375 // positive integer expression if any. 7376 if (NumForLoops && LParenLoc.isValid()) { 7377 ExprResult NumForLoopsResult = 7378 VerifyPositiveIntegerConstantInClause(NumForLoops, OMPC_ordered); 7379 if (NumForLoopsResult.isInvalid()) 7380 return nullptr; 7381 NumForLoops = NumForLoopsResult.get(); 7382 } else 7383 NumForLoops = nullptr; 7384 DSAStack->setOrderedRegion(/*IsOrdered=*/true, NumForLoops); 7385 return new (Context) 7386 OMPOrderedClause(NumForLoops, StartLoc, LParenLoc, EndLoc); 7387 } 7388 7389 OMPClause *Sema::ActOnOpenMPSimpleClause( 7390 OpenMPClauseKind Kind, unsigned Argument, SourceLocation ArgumentLoc, 7391 SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc) { 7392 OMPClause *Res = nullptr; 7393 switch (Kind) { 7394 case OMPC_default: 7395 Res = 7396 ActOnOpenMPDefaultClause(static_cast<OpenMPDefaultClauseKind>(Argument), 7397 ArgumentLoc, StartLoc, LParenLoc, EndLoc); 7398 break; 7399 case OMPC_proc_bind: 7400 Res = ActOnOpenMPProcBindClause( 7401 static_cast<OpenMPProcBindClauseKind>(Argument), ArgumentLoc, StartLoc, 7402 LParenLoc, EndLoc); 7403 break; 7404 case OMPC_if: 7405 case OMPC_final: 7406 case OMPC_num_threads: 7407 case OMPC_safelen: 7408 case OMPC_simdlen: 7409 case OMPC_collapse: 7410 case OMPC_schedule: 7411 case OMPC_private: 7412 case OMPC_firstprivate: 7413 case OMPC_lastprivate: 7414 case OMPC_shared: 7415 case OMPC_reduction: 7416 case OMPC_linear: 7417 case OMPC_aligned: 7418 case OMPC_copyin: 7419 case OMPC_copyprivate: 7420 case OMPC_ordered: 7421 case OMPC_nowait: 7422 case OMPC_untied: 7423 case OMPC_mergeable: 7424 case OMPC_threadprivate: 7425 case OMPC_flush: 7426 case OMPC_read: 7427 case OMPC_write: 7428 case OMPC_update: 7429 case OMPC_capture: 7430 case OMPC_seq_cst: 7431 case OMPC_depend: 7432 case OMPC_device: 7433 case OMPC_threads: 7434 case OMPC_simd: 7435 case OMPC_map: 7436 case OMPC_num_teams: 7437 case OMPC_thread_limit: 7438 case OMPC_priority: 7439 case OMPC_grainsize: 7440 case OMPC_nogroup: 7441 case OMPC_num_tasks: 7442 case OMPC_hint: 7443 case OMPC_dist_schedule: 7444 case OMPC_defaultmap: 7445 case OMPC_unknown: 7446 case OMPC_uniform: 7447 case OMPC_to: 7448 case OMPC_from: 7449 llvm_unreachable("Clause is not allowed."); 7450 } 7451 return Res; 7452 } 7453 7454 static std::string 7455 getListOfPossibleValues(OpenMPClauseKind K, unsigned First, unsigned Last, 7456 ArrayRef<unsigned> Exclude = llvm::None) { 7457 std::string Values; 7458 unsigned Bound = Last >= 2 ? Last - 2 : 0; 7459 unsigned Skipped = Exclude.size(); 7460 auto S = Exclude.begin(), E = Exclude.end(); 7461 for (unsigned i = First; i < Last; ++i) { 7462 if (std::find(S, E, i) != E) { 7463 --Skipped; 7464 continue; 7465 } 7466 Values += "'"; 7467 Values += getOpenMPSimpleClauseTypeName(K, i); 7468 Values += "'"; 7469 if (i == Bound - Skipped) 7470 Values += " or "; 7471 else if (i != Bound + 1 - Skipped) 7472 Values += ", "; 7473 } 7474 return Values; 7475 } 7476 7477 OMPClause *Sema::ActOnOpenMPDefaultClause(OpenMPDefaultClauseKind Kind, 7478 SourceLocation KindKwLoc, 7479 SourceLocation StartLoc, 7480 SourceLocation LParenLoc, 7481 SourceLocation EndLoc) { 7482 if (Kind == OMPC_DEFAULT_unknown) { 7483 static_assert(OMPC_DEFAULT_unknown > 0, 7484 "OMPC_DEFAULT_unknown not greater than 0"); 7485 Diag(KindKwLoc, diag::err_omp_unexpected_clause_value) 7486 << getListOfPossibleValues(OMPC_default, /*First=*/0, 7487 /*Last=*/OMPC_DEFAULT_unknown) 7488 << getOpenMPClauseName(OMPC_default); 7489 return nullptr; 7490 } 7491 switch (Kind) { 7492 case OMPC_DEFAULT_none: 7493 DSAStack->setDefaultDSANone(KindKwLoc); 7494 break; 7495 case OMPC_DEFAULT_shared: 7496 DSAStack->setDefaultDSAShared(KindKwLoc); 7497 break; 7498 case OMPC_DEFAULT_unknown: 7499 llvm_unreachable("Clause kind is not allowed."); 7500 break; 7501 } 7502 return new (Context) 7503 OMPDefaultClause(Kind, KindKwLoc, StartLoc, LParenLoc, EndLoc); 7504 } 7505 7506 OMPClause *Sema::ActOnOpenMPProcBindClause(OpenMPProcBindClauseKind Kind, 7507 SourceLocation KindKwLoc, 7508 SourceLocation StartLoc, 7509 SourceLocation LParenLoc, 7510 SourceLocation EndLoc) { 7511 if (Kind == OMPC_PROC_BIND_unknown) { 7512 Diag(KindKwLoc, diag::err_omp_unexpected_clause_value) 7513 << getListOfPossibleValues(OMPC_proc_bind, /*First=*/0, 7514 /*Last=*/OMPC_PROC_BIND_unknown) 7515 << getOpenMPClauseName(OMPC_proc_bind); 7516 return nullptr; 7517 } 7518 return new (Context) 7519 OMPProcBindClause(Kind, KindKwLoc, StartLoc, LParenLoc, EndLoc); 7520 } 7521 7522 OMPClause *Sema::ActOnOpenMPSingleExprWithArgClause( 7523 OpenMPClauseKind Kind, ArrayRef<unsigned> Argument, Expr *Expr, 7524 SourceLocation StartLoc, SourceLocation LParenLoc, 7525 ArrayRef<SourceLocation> ArgumentLoc, SourceLocation DelimLoc, 7526 SourceLocation EndLoc) { 7527 OMPClause *Res = nullptr; 7528 switch (Kind) { 7529 case OMPC_schedule: 7530 enum { Modifier1, Modifier2, ScheduleKind, NumberOfElements }; 7531 assert(Argument.size() == NumberOfElements && 7532 ArgumentLoc.size() == NumberOfElements); 7533 Res = ActOnOpenMPScheduleClause( 7534 static_cast<OpenMPScheduleClauseModifier>(Argument[Modifier1]), 7535 static_cast<OpenMPScheduleClauseModifier>(Argument[Modifier2]), 7536 static_cast<OpenMPScheduleClauseKind>(Argument[ScheduleKind]), Expr, 7537 StartLoc, LParenLoc, ArgumentLoc[Modifier1], ArgumentLoc[Modifier2], 7538 ArgumentLoc[ScheduleKind], DelimLoc, EndLoc); 7539 break; 7540 case OMPC_if: 7541 assert(Argument.size() == 1 && ArgumentLoc.size() == 1); 7542 Res = ActOnOpenMPIfClause(static_cast<OpenMPDirectiveKind>(Argument.back()), 7543 Expr, StartLoc, LParenLoc, ArgumentLoc.back(), 7544 DelimLoc, EndLoc); 7545 break; 7546 case OMPC_dist_schedule: 7547 Res = ActOnOpenMPDistScheduleClause( 7548 static_cast<OpenMPDistScheduleClauseKind>(Argument.back()), Expr, 7549 StartLoc, LParenLoc, ArgumentLoc.back(), DelimLoc, EndLoc); 7550 break; 7551 case OMPC_defaultmap: 7552 enum { Modifier, DefaultmapKind }; 7553 Res = ActOnOpenMPDefaultmapClause( 7554 static_cast<OpenMPDefaultmapClauseModifier>(Argument[Modifier]), 7555 static_cast<OpenMPDefaultmapClauseKind>(Argument[DefaultmapKind]), 7556 StartLoc, LParenLoc, ArgumentLoc[Modifier], 7557 ArgumentLoc[DefaultmapKind], EndLoc); 7558 break; 7559 case OMPC_final: 7560 case OMPC_num_threads: 7561 case OMPC_safelen: 7562 case OMPC_simdlen: 7563 case OMPC_collapse: 7564 case OMPC_default: 7565 case OMPC_proc_bind: 7566 case OMPC_private: 7567 case OMPC_firstprivate: 7568 case OMPC_lastprivate: 7569 case OMPC_shared: 7570 case OMPC_reduction: 7571 case OMPC_linear: 7572 case OMPC_aligned: 7573 case OMPC_copyin: 7574 case OMPC_copyprivate: 7575 case OMPC_ordered: 7576 case OMPC_nowait: 7577 case OMPC_untied: 7578 case OMPC_mergeable: 7579 case OMPC_threadprivate: 7580 case OMPC_flush: 7581 case OMPC_read: 7582 case OMPC_write: 7583 case OMPC_update: 7584 case OMPC_capture: 7585 case OMPC_seq_cst: 7586 case OMPC_depend: 7587 case OMPC_device: 7588 case OMPC_threads: 7589 case OMPC_simd: 7590 case OMPC_map: 7591 case OMPC_num_teams: 7592 case OMPC_thread_limit: 7593 case OMPC_priority: 7594 case OMPC_grainsize: 7595 case OMPC_nogroup: 7596 case OMPC_num_tasks: 7597 case OMPC_hint: 7598 case OMPC_unknown: 7599 case OMPC_uniform: 7600 case OMPC_to: 7601 case OMPC_from: 7602 llvm_unreachable("Clause is not allowed."); 7603 } 7604 return Res; 7605 } 7606 7607 static bool checkScheduleModifiers(Sema &S, OpenMPScheduleClauseModifier M1, 7608 OpenMPScheduleClauseModifier M2, 7609 SourceLocation M1Loc, SourceLocation M2Loc) { 7610 if (M1 == OMPC_SCHEDULE_MODIFIER_unknown && M1Loc.isValid()) { 7611 SmallVector<unsigned, 2> Excluded; 7612 if (M2 != OMPC_SCHEDULE_MODIFIER_unknown) 7613 Excluded.push_back(M2); 7614 if (M2 == OMPC_SCHEDULE_MODIFIER_nonmonotonic) 7615 Excluded.push_back(OMPC_SCHEDULE_MODIFIER_monotonic); 7616 if (M2 == OMPC_SCHEDULE_MODIFIER_monotonic) 7617 Excluded.push_back(OMPC_SCHEDULE_MODIFIER_nonmonotonic); 7618 S.Diag(M1Loc, diag::err_omp_unexpected_clause_value) 7619 << getListOfPossibleValues(OMPC_schedule, 7620 /*First=*/OMPC_SCHEDULE_MODIFIER_unknown + 1, 7621 /*Last=*/OMPC_SCHEDULE_MODIFIER_last, 7622 Excluded) 7623 << getOpenMPClauseName(OMPC_schedule); 7624 return true; 7625 } 7626 return false; 7627 } 7628 7629 OMPClause *Sema::ActOnOpenMPScheduleClause( 7630 OpenMPScheduleClauseModifier M1, OpenMPScheduleClauseModifier M2, 7631 OpenMPScheduleClauseKind Kind, Expr *ChunkSize, SourceLocation StartLoc, 7632 SourceLocation LParenLoc, SourceLocation M1Loc, SourceLocation M2Loc, 7633 SourceLocation KindLoc, SourceLocation CommaLoc, SourceLocation EndLoc) { 7634 if (checkScheduleModifiers(*this, M1, M2, M1Loc, M2Loc) || 7635 checkScheduleModifiers(*this, M2, M1, M2Loc, M1Loc)) 7636 return nullptr; 7637 // OpenMP, 2.7.1, Loop Construct, Restrictions 7638 // Either the monotonic modifier or the nonmonotonic modifier can be specified 7639 // but not both. 7640 if ((M1 == M2 && M1 != OMPC_SCHEDULE_MODIFIER_unknown) || 7641 (M1 == OMPC_SCHEDULE_MODIFIER_monotonic && 7642 M2 == OMPC_SCHEDULE_MODIFIER_nonmonotonic) || 7643 (M1 == OMPC_SCHEDULE_MODIFIER_nonmonotonic && 7644 M2 == OMPC_SCHEDULE_MODIFIER_monotonic)) { 7645 Diag(M2Loc, diag::err_omp_unexpected_schedule_modifier) 7646 << getOpenMPSimpleClauseTypeName(OMPC_schedule, M2) 7647 << getOpenMPSimpleClauseTypeName(OMPC_schedule, M1); 7648 return nullptr; 7649 } 7650 if (Kind == OMPC_SCHEDULE_unknown) { 7651 std::string Values; 7652 if (M1Loc.isInvalid() && M2Loc.isInvalid()) { 7653 unsigned Exclude[] = {OMPC_SCHEDULE_unknown}; 7654 Values = getListOfPossibleValues(OMPC_schedule, /*First=*/0, 7655 /*Last=*/OMPC_SCHEDULE_MODIFIER_last, 7656 Exclude); 7657 } else { 7658 Values = getListOfPossibleValues(OMPC_schedule, /*First=*/0, 7659 /*Last=*/OMPC_SCHEDULE_unknown); 7660 } 7661 Diag(KindLoc, diag::err_omp_unexpected_clause_value) 7662 << Values << getOpenMPClauseName(OMPC_schedule); 7663 return nullptr; 7664 } 7665 // OpenMP, 2.7.1, Loop Construct, Restrictions 7666 // The nonmonotonic modifier can only be specified with schedule(dynamic) or 7667 // schedule(guided). 7668 if ((M1 == OMPC_SCHEDULE_MODIFIER_nonmonotonic || 7669 M2 == OMPC_SCHEDULE_MODIFIER_nonmonotonic) && 7670 Kind != OMPC_SCHEDULE_dynamic && Kind != OMPC_SCHEDULE_guided) { 7671 Diag(M1 == OMPC_SCHEDULE_MODIFIER_nonmonotonic ? M1Loc : M2Loc, 7672 diag::err_omp_schedule_nonmonotonic_static); 7673 return nullptr; 7674 } 7675 Expr *ValExpr = ChunkSize; 7676 Stmt *HelperValStmt = nullptr; 7677 if (ChunkSize) { 7678 if (!ChunkSize->isValueDependent() && !ChunkSize->isTypeDependent() && 7679 !ChunkSize->isInstantiationDependent() && 7680 !ChunkSize->containsUnexpandedParameterPack()) { 7681 SourceLocation ChunkSizeLoc = ChunkSize->getLocStart(); 7682 ExprResult Val = 7683 PerformOpenMPImplicitIntegerConversion(ChunkSizeLoc, ChunkSize); 7684 if (Val.isInvalid()) 7685 return nullptr; 7686 7687 ValExpr = Val.get(); 7688 7689 // OpenMP [2.7.1, Restrictions] 7690 // chunk_size must be a loop invariant integer expression with a positive 7691 // value. 7692 llvm::APSInt Result; 7693 if (ValExpr->isIntegerConstantExpr(Result, Context)) { 7694 if (Result.isSigned() && !Result.isStrictlyPositive()) { 7695 Diag(ChunkSizeLoc, diag::err_omp_negative_expression_in_clause) 7696 << "schedule" << 1 << ChunkSize->getSourceRange(); 7697 return nullptr; 7698 } 7699 } else if (isParallelOrTaskRegion(DSAStack->getCurrentDirective()) && 7700 !CurContext->isDependentContext()) { 7701 llvm::MapVector<Expr *, DeclRefExpr *> Captures; 7702 ValExpr = tryBuildCapture(*this, ValExpr, Captures).get(); 7703 HelperValStmt = buildPreInits(Context, Captures); 7704 } 7705 } 7706 } 7707 7708 return new (Context) 7709 OMPScheduleClause(StartLoc, LParenLoc, KindLoc, CommaLoc, EndLoc, Kind, 7710 ValExpr, HelperValStmt, M1, M1Loc, M2, M2Loc); 7711 } 7712 7713 OMPClause *Sema::ActOnOpenMPClause(OpenMPClauseKind Kind, 7714 SourceLocation StartLoc, 7715 SourceLocation EndLoc) { 7716 OMPClause *Res = nullptr; 7717 switch (Kind) { 7718 case OMPC_ordered: 7719 Res = ActOnOpenMPOrderedClause(StartLoc, EndLoc); 7720 break; 7721 case OMPC_nowait: 7722 Res = ActOnOpenMPNowaitClause(StartLoc, EndLoc); 7723 break; 7724 case OMPC_untied: 7725 Res = ActOnOpenMPUntiedClause(StartLoc, EndLoc); 7726 break; 7727 case OMPC_mergeable: 7728 Res = ActOnOpenMPMergeableClause(StartLoc, EndLoc); 7729 break; 7730 case OMPC_read: 7731 Res = ActOnOpenMPReadClause(StartLoc, EndLoc); 7732 break; 7733 case OMPC_write: 7734 Res = ActOnOpenMPWriteClause(StartLoc, EndLoc); 7735 break; 7736 case OMPC_update: 7737 Res = ActOnOpenMPUpdateClause(StartLoc, EndLoc); 7738 break; 7739 case OMPC_capture: 7740 Res = ActOnOpenMPCaptureClause(StartLoc, EndLoc); 7741 break; 7742 case OMPC_seq_cst: 7743 Res = ActOnOpenMPSeqCstClause(StartLoc, EndLoc); 7744 break; 7745 case OMPC_threads: 7746 Res = ActOnOpenMPThreadsClause(StartLoc, EndLoc); 7747 break; 7748 case OMPC_simd: 7749 Res = ActOnOpenMPSIMDClause(StartLoc, EndLoc); 7750 break; 7751 case OMPC_nogroup: 7752 Res = ActOnOpenMPNogroupClause(StartLoc, EndLoc); 7753 break; 7754 case OMPC_if: 7755 case OMPC_final: 7756 case OMPC_num_threads: 7757 case OMPC_safelen: 7758 case OMPC_simdlen: 7759 case OMPC_collapse: 7760 case OMPC_schedule: 7761 case OMPC_private: 7762 case OMPC_firstprivate: 7763 case OMPC_lastprivate: 7764 case OMPC_shared: 7765 case OMPC_reduction: 7766 case OMPC_linear: 7767 case OMPC_aligned: 7768 case OMPC_copyin: 7769 case OMPC_copyprivate: 7770 case OMPC_default: 7771 case OMPC_proc_bind: 7772 case OMPC_threadprivate: 7773 case OMPC_flush: 7774 case OMPC_depend: 7775 case OMPC_device: 7776 case OMPC_map: 7777 case OMPC_num_teams: 7778 case OMPC_thread_limit: 7779 case OMPC_priority: 7780 case OMPC_grainsize: 7781 case OMPC_num_tasks: 7782 case OMPC_hint: 7783 case OMPC_dist_schedule: 7784 case OMPC_defaultmap: 7785 case OMPC_unknown: 7786 case OMPC_uniform: 7787 case OMPC_to: 7788 case OMPC_from: 7789 llvm_unreachable("Clause is not allowed."); 7790 } 7791 return Res; 7792 } 7793 7794 OMPClause *Sema::ActOnOpenMPNowaitClause(SourceLocation StartLoc, 7795 SourceLocation EndLoc) { 7796 DSAStack->setNowaitRegion(); 7797 return new (Context) OMPNowaitClause(StartLoc, EndLoc); 7798 } 7799 7800 OMPClause *Sema::ActOnOpenMPUntiedClause(SourceLocation StartLoc, 7801 SourceLocation EndLoc) { 7802 return new (Context) OMPUntiedClause(StartLoc, EndLoc); 7803 } 7804 7805 OMPClause *Sema::ActOnOpenMPMergeableClause(SourceLocation StartLoc, 7806 SourceLocation EndLoc) { 7807 return new (Context) OMPMergeableClause(StartLoc, EndLoc); 7808 } 7809 7810 OMPClause *Sema::ActOnOpenMPReadClause(SourceLocation StartLoc, 7811 SourceLocation EndLoc) { 7812 return new (Context) OMPReadClause(StartLoc, EndLoc); 7813 } 7814 7815 OMPClause *Sema::ActOnOpenMPWriteClause(SourceLocation StartLoc, 7816 SourceLocation EndLoc) { 7817 return new (Context) OMPWriteClause(StartLoc, EndLoc); 7818 } 7819 7820 OMPClause *Sema::ActOnOpenMPUpdateClause(SourceLocation StartLoc, 7821 SourceLocation EndLoc) { 7822 return new (Context) OMPUpdateClause(StartLoc, EndLoc); 7823 } 7824 7825 OMPClause *Sema::ActOnOpenMPCaptureClause(SourceLocation StartLoc, 7826 SourceLocation EndLoc) { 7827 return new (Context) OMPCaptureClause(StartLoc, EndLoc); 7828 } 7829 7830 OMPClause *Sema::ActOnOpenMPSeqCstClause(SourceLocation StartLoc, 7831 SourceLocation EndLoc) { 7832 return new (Context) OMPSeqCstClause(StartLoc, EndLoc); 7833 } 7834 7835 OMPClause *Sema::ActOnOpenMPThreadsClause(SourceLocation StartLoc, 7836 SourceLocation EndLoc) { 7837 return new (Context) OMPThreadsClause(StartLoc, EndLoc); 7838 } 7839 7840 OMPClause *Sema::ActOnOpenMPSIMDClause(SourceLocation StartLoc, 7841 SourceLocation EndLoc) { 7842 return new (Context) OMPSIMDClause(StartLoc, EndLoc); 7843 } 7844 7845 OMPClause *Sema::ActOnOpenMPNogroupClause(SourceLocation StartLoc, 7846 SourceLocation EndLoc) { 7847 return new (Context) OMPNogroupClause(StartLoc, EndLoc); 7848 } 7849 7850 OMPClause *Sema::ActOnOpenMPVarListClause( 7851 OpenMPClauseKind Kind, ArrayRef<Expr *> VarList, Expr *TailExpr, 7852 SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation ColonLoc, 7853 SourceLocation EndLoc, CXXScopeSpec &ReductionIdScopeSpec, 7854 const DeclarationNameInfo &ReductionId, OpenMPDependClauseKind DepKind, 7855 OpenMPLinearClauseKind LinKind, OpenMPMapClauseKind MapTypeModifier, 7856 OpenMPMapClauseKind MapType, bool IsMapTypeImplicit, 7857 SourceLocation DepLinMapLoc) { 7858 OMPClause *Res = nullptr; 7859 switch (Kind) { 7860 case OMPC_private: 7861 Res = ActOnOpenMPPrivateClause(VarList, StartLoc, LParenLoc, EndLoc); 7862 break; 7863 case OMPC_firstprivate: 7864 Res = ActOnOpenMPFirstprivateClause(VarList, StartLoc, LParenLoc, EndLoc); 7865 break; 7866 case OMPC_lastprivate: 7867 Res = ActOnOpenMPLastprivateClause(VarList, StartLoc, LParenLoc, EndLoc); 7868 break; 7869 case OMPC_shared: 7870 Res = ActOnOpenMPSharedClause(VarList, StartLoc, LParenLoc, EndLoc); 7871 break; 7872 case OMPC_reduction: 7873 Res = ActOnOpenMPReductionClause(VarList, StartLoc, LParenLoc, ColonLoc, 7874 EndLoc, ReductionIdScopeSpec, ReductionId); 7875 break; 7876 case OMPC_linear: 7877 Res = ActOnOpenMPLinearClause(VarList, TailExpr, StartLoc, LParenLoc, 7878 LinKind, DepLinMapLoc, ColonLoc, EndLoc); 7879 break; 7880 case OMPC_aligned: 7881 Res = ActOnOpenMPAlignedClause(VarList, TailExpr, StartLoc, LParenLoc, 7882 ColonLoc, EndLoc); 7883 break; 7884 case OMPC_copyin: 7885 Res = ActOnOpenMPCopyinClause(VarList, StartLoc, LParenLoc, EndLoc); 7886 break; 7887 case OMPC_copyprivate: 7888 Res = ActOnOpenMPCopyprivateClause(VarList, StartLoc, LParenLoc, EndLoc); 7889 break; 7890 case OMPC_flush: 7891 Res = ActOnOpenMPFlushClause(VarList, StartLoc, LParenLoc, EndLoc); 7892 break; 7893 case OMPC_depend: 7894 Res = ActOnOpenMPDependClause(DepKind, DepLinMapLoc, ColonLoc, VarList, 7895 StartLoc, LParenLoc, EndLoc); 7896 break; 7897 case OMPC_map: 7898 Res = ActOnOpenMPMapClause(MapTypeModifier, MapType, IsMapTypeImplicit, 7899 DepLinMapLoc, ColonLoc, VarList, StartLoc, 7900 LParenLoc, EndLoc); 7901 break; 7902 case OMPC_to: 7903 Res = ActOnOpenMPToClause(VarList, StartLoc, LParenLoc, EndLoc); 7904 break; 7905 case OMPC_from: 7906 Res = ActOnOpenMPFromClause(VarList, StartLoc, LParenLoc, EndLoc); 7907 break; 7908 case OMPC_if: 7909 case OMPC_final: 7910 case OMPC_num_threads: 7911 case OMPC_safelen: 7912 case OMPC_simdlen: 7913 case OMPC_collapse: 7914 case OMPC_default: 7915 case OMPC_proc_bind: 7916 case OMPC_schedule: 7917 case OMPC_ordered: 7918 case OMPC_nowait: 7919 case OMPC_untied: 7920 case OMPC_mergeable: 7921 case OMPC_threadprivate: 7922 case OMPC_read: 7923 case OMPC_write: 7924 case OMPC_update: 7925 case OMPC_capture: 7926 case OMPC_seq_cst: 7927 case OMPC_device: 7928 case OMPC_threads: 7929 case OMPC_simd: 7930 case OMPC_num_teams: 7931 case OMPC_thread_limit: 7932 case OMPC_priority: 7933 case OMPC_grainsize: 7934 case OMPC_nogroup: 7935 case OMPC_num_tasks: 7936 case OMPC_hint: 7937 case OMPC_dist_schedule: 7938 case OMPC_defaultmap: 7939 case OMPC_unknown: 7940 case OMPC_uniform: 7941 llvm_unreachable("Clause is not allowed."); 7942 } 7943 return Res; 7944 } 7945 7946 ExprResult Sema::getOpenMPCapturedExpr(VarDecl *Capture, ExprValueKind VK, 7947 ExprObjectKind OK, SourceLocation Loc) { 7948 ExprResult Res = BuildDeclRefExpr( 7949 Capture, Capture->getType().getNonReferenceType(), VK_LValue, Loc); 7950 if (!Res.isUsable()) 7951 return ExprError(); 7952 if (OK == OK_Ordinary && !getLangOpts().CPlusPlus) { 7953 Res = CreateBuiltinUnaryOp(Loc, UO_Deref, Res.get()); 7954 if (!Res.isUsable()) 7955 return ExprError(); 7956 } 7957 if (VK != VK_LValue && Res.get()->isGLValue()) { 7958 Res = DefaultLvalueConversion(Res.get()); 7959 if (!Res.isUsable()) 7960 return ExprError(); 7961 } 7962 return Res; 7963 } 7964 7965 static std::pair<ValueDecl *, bool> 7966 getPrivateItem(Sema &S, Expr *&RefExpr, SourceLocation &ELoc, 7967 SourceRange &ERange, bool AllowArraySection = false) { 7968 if (RefExpr->isTypeDependent() || RefExpr->isValueDependent() || 7969 RefExpr->containsUnexpandedParameterPack()) 7970 return std::make_pair(nullptr, true); 7971 7972 // OpenMP [3.1, C/C++] 7973 // A list item is a variable name. 7974 // OpenMP [2.9.3.3, Restrictions, p.1] 7975 // A variable that is part of another variable (as an array or 7976 // structure element) cannot appear in a private clause. 7977 RefExpr = RefExpr->IgnoreParens(); 7978 enum { 7979 NoArrayExpr = -1, 7980 ArraySubscript = 0, 7981 OMPArraySection = 1 7982 } IsArrayExpr = NoArrayExpr; 7983 if (AllowArraySection) { 7984 if (auto *ASE = dyn_cast_or_null<ArraySubscriptExpr>(RefExpr)) { 7985 auto *Base = ASE->getBase()->IgnoreParenImpCasts(); 7986 while (auto *TempASE = dyn_cast<ArraySubscriptExpr>(Base)) 7987 Base = TempASE->getBase()->IgnoreParenImpCasts(); 7988 RefExpr = Base; 7989 IsArrayExpr = ArraySubscript; 7990 } else if (auto *OASE = dyn_cast_or_null<OMPArraySectionExpr>(RefExpr)) { 7991 auto *Base = OASE->getBase()->IgnoreParenImpCasts(); 7992 while (auto *TempOASE = dyn_cast<OMPArraySectionExpr>(Base)) 7993 Base = TempOASE->getBase()->IgnoreParenImpCasts(); 7994 while (auto *TempASE = dyn_cast<ArraySubscriptExpr>(Base)) 7995 Base = TempASE->getBase()->IgnoreParenImpCasts(); 7996 RefExpr = Base; 7997 IsArrayExpr = OMPArraySection; 7998 } 7999 } 8000 ELoc = RefExpr->getExprLoc(); 8001 ERange = RefExpr->getSourceRange(); 8002 RefExpr = RefExpr->IgnoreParenImpCasts(); 8003 auto *DE = dyn_cast_or_null<DeclRefExpr>(RefExpr); 8004 auto *ME = dyn_cast_or_null<MemberExpr>(RefExpr); 8005 if ((!DE || !isa<VarDecl>(DE->getDecl())) && 8006 (S.getCurrentThisType().isNull() || !ME || 8007 !isa<CXXThisExpr>(ME->getBase()->IgnoreParenImpCasts()) || 8008 !isa<FieldDecl>(ME->getMemberDecl()))) { 8009 if (IsArrayExpr != NoArrayExpr) 8010 S.Diag(ELoc, diag::err_omp_expected_base_var_name) << IsArrayExpr 8011 << ERange; 8012 else { 8013 S.Diag(ELoc, 8014 AllowArraySection 8015 ? diag::err_omp_expected_var_name_member_expr_or_array_item 8016 : diag::err_omp_expected_var_name_member_expr) 8017 << (S.getCurrentThisType().isNull() ? 0 : 1) << ERange; 8018 } 8019 return std::make_pair(nullptr, false); 8020 } 8021 return std::make_pair(DE ? DE->getDecl() : ME->getMemberDecl(), false); 8022 } 8023 8024 OMPClause *Sema::ActOnOpenMPPrivateClause(ArrayRef<Expr *> VarList, 8025 SourceLocation StartLoc, 8026 SourceLocation LParenLoc, 8027 SourceLocation EndLoc) { 8028 SmallVector<Expr *, 8> Vars; 8029 SmallVector<Expr *, 8> PrivateCopies; 8030 for (auto &RefExpr : VarList) { 8031 assert(RefExpr && "NULL expr in OpenMP private clause."); 8032 SourceLocation ELoc; 8033 SourceRange ERange; 8034 Expr *SimpleRefExpr = RefExpr; 8035 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange); 8036 if (Res.second) { 8037 // It will be analyzed later. 8038 Vars.push_back(RefExpr); 8039 PrivateCopies.push_back(nullptr); 8040 } 8041 ValueDecl *D = Res.first; 8042 if (!D) 8043 continue; 8044 8045 QualType Type = D->getType(); 8046 auto *VD = dyn_cast<VarDecl>(D); 8047 8048 // OpenMP [2.9.3.3, Restrictions, C/C++, p.3] 8049 // A variable that appears in a private clause must not have an incomplete 8050 // type or a reference type. 8051 if (RequireCompleteType(ELoc, Type, diag::err_omp_private_incomplete_type)) 8052 continue; 8053 Type = Type.getNonReferenceType(); 8054 8055 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced 8056 // in a Construct] 8057 // Variables with the predetermined data-sharing attributes may not be 8058 // listed in data-sharing attributes clauses, except for the cases 8059 // listed below. For these exceptions only, listing a predetermined 8060 // variable in a data-sharing attribute clause is allowed and overrides 8061 // the variable's predetermined data-sharing attributes. 8062 DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, false); 8063 if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_private) { 8064 Diag(ELoc, diag::err_omp_wrong_dsa) << getOpenMPClauseName(DVar.CKind) 8065 << getOpenMPClauseName(OMPC_private); 8066 ReportOriginalDSA(*this, DSAStack, D, DVar); 8067 continue; 8068 } 8069 8070 // Variably modified types are not supported for tasks. 8071 if (!Type->isAnyPointerType() && Type->isVariablyModifiedType() && 8072 isOpenMPTaskingDirective(DSAStack->getCurrentDirective())) { 8073 Diag(ELoc, diag::err_omp_variably_modified_type_not_supported) 8074 << getOpenMPClauseName(OMPC_private) << Type 8075 << getOpenMPDirectiveName(DSAStack->getCurrentDirective()); 8076 bool IsDecl = 8077 !VD || 8078 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly; 8079 Diag(D->getLocation(), 8080 IsDecl ? diag::note_previous_decl : diag::note_defined_here) 8081 << D; 8082 continue; 8083 } 8084 8085 // OpenMP 4.5 [2.15.5.1, Restrictions, p.3] 8086 // A list item cannot appear in both a map clause and a data-sharing 8087 // attribute clause on the same construct 8088 if (DSAStack->getCurrentDirective() == OMPD_target) { 8089 if (DSAStack->checkMappableExprComponentListsForDecl( 8090 VD, /* CurrentRegionOnly = */ true, 8091 [&](OMPClauseMappableExprCommon::MappableExprComponentListRef) 8092 -> bool { return true; })) { 8093 Diag(ELoc, diag::err_omp_variable_in_map_and_dsa) 8094 << getOpenMPClauseName(OMPC_private) 8095 << getOpenMPDirectiveName(DSAStack->getCurrentDirective()); 8096 ReportOriginalDSA(*this, DSAStack, D, DVar); 8097 continue; 8098 } 8099 } 8100 8101 // OpenMP [2.9.3.3, Restrictions, C/C++, p.1] 8102 // A variable of class type (or array thereof) that appears in a private 8103 // clause requires an accessible, unambiguous default constructor for the 8104 // class type. 8105 // Generate helper private variable and initialize it with the default 8106 // value. The address of the original variable is replaced by the address of 8107 // the new private variable in CodeGen. This new variable is not added to 8108 // IdResolver, so the code in the OpenMP region uses original variable for 8109 // proper diagnostics. 8110 Type = Type.getUnqualifiedType(); 8111 auto VDPrivate = buildVarDecl(*this, ELoc, Type, D->getName(), 8112 D->hasAttrs() ? &D->getAttrs() : nullptr); 8113 ActOnUninitializedDecl(VDPrivate, /*TypeMayContainAuto=*/false); 8114 if (VDPrivate->isInvalidDecl()) 8115 continue; 8116 auto VDPrivateRefExpr = buildDeclRefExpr( 8117 *this, VDPrivate, RefExpr->getType().getUnqualifiedType(), ELoc); 8118 8119 DeclRefExpr *Ref = nullptr; 8120 if (!VD) 8121 Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/false); 8122 DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_private, Ref); 8123 Vars.push_back(VD ? RefExpr->IgnoreParens() : Ref); 8124 PrivateCopies.push_back(VDPrivateRefExpr); 8125 } 8126 8127 if (Vars.empty()) 8128 return nullptr; 8129 8130 return OMPPrivateClause::Create(Context, StartLoc, LParenLoc, EndLoc, Vars, 8131 PrivateCopies); 8132 } 8133 8134 namespace { 8135 class DiagsUninitializedSeveretyRAII { 8136 private: 8137 DiagnosticsEngine &Diags; 8138 SourceLocation SavedLoc; 8139 bool IsIgnored; 8140 8141 public: 8142 DiagsUninitializedSeveretyRAII(DiagnosticsEngine &Diags, SourceLocation Loc, 8143 bool IsIgnored) 8144 : Diags(Diags), SavedLoc(Loc), IsIgnored(IsIgnored) { 8145 if (!IsIgnored) { 8146 Diags.setSeverity(/*Diag*/ diag::warn_uninit_self_reference_in_init, 8147 /*Map*/ diag::Severity::Ignored, Loc); 8148 } 8149 } 8150 ~DiagsUninitializedSeveretyRAII() { 8151 if (!IsIgnored) 8152 Diags.popMappings(SavedLoc); 8153 } 8154 }; 8155 } 8156 8157 OMPClause *Sema::ActOnOpenMPFirstprivateClause(ArrayRef<Expr *> VarList, 8158 SourceLocation StartLoc, 8159 SourceLocation LParenLoc, 8160 SourceLocation EndLoc) { 8161 SmallVector<Expr *, 8> Vars; 8162 SmallVector<Expr *, 8> PrivateCopies; 8163 SmallVector<Expr *, 8> Inits; 8164 SmallVector<Decl *, 4> ExprCaptures; 8165 bool IsImplicitClause = 8166 StartLoc.isInvalid() && LParenLoc.isInvalid() && EndLoc.isInvalid(); 8167 auto ImplicitClauseLoc = DSAStack->getConstructLoc(); 8168 8169 for (auto &RefExpr : VarList) { 8170 assert(RefExpr && "NULL expr in OpenMP firstprivate clause."); 8171 SourceLocation ELoc; 8172 SourceRange ERange; 8173 Expr *SimpleRefExpr = RefExpr; 8174 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange); 8175 if (Res.second) { 8176 // It will be analyzed later. 8177 Vars.push_back(RefExpr); 8178 PrivateCopies.push_back(nullptr); 8179 Inits.push_back(nullptr); 8180 } 8181 ValueDecl *D = Res.first; 8182 if (!D) 8183 continue; 8184 8185 ELoc = IsImplicitClause ? ImplicitClauseLoc : ELoc; 8186 QualType Type = D->getType(); 8187 auto *VD = dyn_cast<VarDecl>(D); 8188 8189 // OpenMP [2.9.3.3, Restrictions, C/C++, p.3] 8190 // A variable that appears in a private clause must not have an incomplete 8191 // type or a reference type. 8192 if (RequireCompleteType(ELoc, Type, 8193 diag::err_omp_firstprivate_incomplete_type)) 8194 continue; 8195 Type = Type.getNonReferenceType(); 8196 8197 // OpenMP [2.9.3.4, Restrictions, C/C++, p.1] 8198 // A variable of class type (or array thereof) that appears in a private 8199 // clause requires an accessible, unambiguous copy constructor for the 8200 // class type. 8201 auto ElemType = Context.getBaseElementType(Type).getNonReferenceType(); 8202 8203 // If an implicit firstprivate variable found it was checked already. 8204 DSAStackTy::DSAVarData TopDVar; 8205 if (!IsImplicitClause) { 8206 DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, false); 8207 TopDVar = DVar; 8208 bool IsConstant = ElemType.isConstant(Context); 8209 // OpenMP [2.4.13, Data-sharing Attribute Clauses] 8210 // A list item that specifies a given variable may not appear in more 8211 // than one clause on the same directive, except that a variable may be 8212 // specified in both firstprivate and lastprivate clauses. 8213 if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_firstprivate && 8214 DVar.CKind != OMPC_lastprivate && DVar.RefExpr) { 8215 Diag(ELoc, diag::err_omp_wrong_dsa) 8216 << getOpenMPClauseName(DVar.CKind) 8217 << getOpenMPClauseName(OMPC_firstprivate); 8218 ReportOriginalDSA(*this, DSAStack, D, DVar); 8219 continue; 8220 } 8221 8222 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced 8223 // in a Construct] 8224 // Variables with the predetermined data-sharing attributes may not be 8225 // listed in data-sharing attributes clauses, except for the cases 8226 // listed below. For these exceptions only, listing a predetermined 8227 // variable in a data-sharing attribute clause is allowed and overrides 8228 // the variable's predetermined data-sharing attributes. 8229 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced 8230 // in a Construct, C/C++, p.2] 8231 // Variables with const-qualified type having no mutable member may be 8232 // listed in a firstprivate clause, even if they are static data members. 8233 if (!(IsConstant || (VD && VD->isStaticDataMember())) && !DVar.RefExpr && 8234 DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_shared) { 8235 Diag(ELoc, diag::err_omp_wrong_dsa) 8236 << getOpenMPClauseName(DVar.CKind) 8237 << getOpenMPClauseName(OMPC_firstprivate); 8238 ReportOriginalDSA(*this, DSAStack, D, DVar); 8239 continue; 8240 } 8241 8242 OpenMPDirectiveKind CurrDir = DSAStack->getCurrentDirective(); 8243 // OpenMP [2.9.3.4, Restrictions, p.2] 8244 // A list item that is private within a parallel region must not appear 8245 // in a firstprivate clause on a worksharing construct if any of the 8246 // worksharing regions arising from the worksharing construct ever bind 8247 // to any of the parallel regions arising from the parallel construct. 8248 if (isOpenMPWorksharingDirective(CurrDir) && 8249 !isOpenMPParallelDirective(CurrDir)) { 8250 DVar = DSAStack->getImplicitDSA(D, true); 8251 if (DVar.CKind != OMPC_shared && 8252 (isOpenMPParallelDirective(DVar.DKind) || 8253 DVar.DKind == OMPD_unknown)) { 8254 Diag(ELoc, diag::err_omp_required_access) 8255 << getOpenMPClauseName(OMPC_firstprivate) 8256 << getOpenMPClauseName(OMPC_shared); 8257 ReportOriginalDSA(*this, DSAStack, D, DVar); 8258 continue; 8259 } 8260 } 8261 // OpenMP [2.9.3.4, Restrictions, p.3] 8262 // A list item that appears in a reduction clause of a parallel construct 8263 // must not appear in a firstprivate clause on a worksharing or task 8264 // construct if any of the worksharing or task regions arising from the 8265 // worksharing or task construct ever bind to any of the parallel regions 8266 // arising from the parallel construct. 8267 // OpenMP [2.9.3.4, Restrictions, p.4] 8268 // A list item that appears in a reduction clause in worksharing 8269 // construct must not appear in a firstprivate clause in a task construct 8270 // encountered during execution of any of the worksharing regions arising 8271 // from the worksharing construct. 8272 if (isOpenMPTaskingDirective(CurrDir)) { 8273 DVar = DSAStack->hasInnermostDSA( 8274 D, [](OpenMPClauseKind C) -> bool { return C == OMPC_reduction; }, 8275 [](OpenMPDirectiveKind K) -> bool { 8276 return isOpenMPParallelDirective(K) || 8277 isOpenMPWorksharingDirective(K); 8278 }, 8279 false); 8280 if (DVar.CKind == OMPC_reduction && 8281 (isOpenMPParallelDirective(DVar.DKind) || 8282 isOpenMPWorksharingDirective(DVar.DKind))) { 8283 Diag(ELoc, diag::err_omp_parallel_reduction_in_task_firstprivate) 8284 << getOpenMPDirectiveName(DVar.DKind); 8285 ReportOriginalDSA(*this, DSAStack, D, DVar); 8286 continue; 8287 } 8288 } 8289 8290 // OpenMP 4.5 [2.15.3.4, Restrictions, p.3] 8291 // A list item that is private within a teams region must not appear in a 8292 // firstprivate clause on a distribute construct if any of the distribute 8293 // regions arising from the distribute construct ever bind to any of the 8294 // teams regions arising from the teams construct. 8295 // OpenMP 4.5 [2.15.3.4, Restrictions, p.3] 8296 // A list item that appears in a reduction clause of a teams construct 8297 // must not appear in a firstprivate clause on a distribute construct if 8298 // any of the distribute regions arising from the distribute construct 8299 // ever bind to any of the teams regions arising from the teams construct. 8300 // OpenMP 4.5 [2.10.8, Distribute Construct, p.3] 8301 // A list item may appear in a firstprivate or lastprivate clause but not 8302 // both. 8303 if (CurrDir == OMPD_distribute) { 8304 DVar = DSAStack->hasInnermostDSA( 8305 D, [](OpenMPClauseKind C) -> bool { return C == OMPC_private; }, 8306 [](OpenMPDirectiveKind K) -> bool { 8307 return isOpenMPTeamsDirective(K); 8308 }, 8309 false); 8310 if (DVar.CKind == OMPC_private && isOpenMPTeamsDirective(DVar.DKind)) { 8311 Diag(ELoc, diag::err_omp_firstprivate_distribute_private_teams); 8312 ReportOriginalDSA(*this, DSAStack, D, DVar); 8313 continue; 8314 } 8315 DVar = DSAStack->hasInnermostDSA( 8316 D, [](OpenMPClauseKind C) -> bool { return C == OMPC_reduction; }, 8317 [](OpenMPDirectiveKind K) -> bool { 8318 return isOpenMPTeamsDirective(K); 8319 }, 8320 false); 8321 if (DVar.CKind == OMPC_reduction && 8322 isOpenMPTeamsDirective(DVar.DKind)) { 8323 Diag(ELoc, diag::err_omp_firstprivate_distribute_in_teams_reduction); 8324 ReportOriginalDSA(*this, DSAStack, D, DVar); 8325 continue; 8326 } 8327 DVar = DSAStack->getTopDSA(D, false); 8328 if (DVar.CKind == OMPC_lastprivate) { 8329 Diag(ELoc, diag::err_omp_firstprivate_and_lastprivate_in_distribute); 8330 ReportOriginalDSA(*this, DSAStack, D, DVar); 8331 continue; 8332 } 8333 } 8334 // OpenMP 4.5 [2.15.5.1, Restrictions, p.3] 8335 // A list item cannot appear in both a map clause and a data-sharing 8336 // attribute clause on the same construct 8337 if (CurrDir == OMPD_target) { 8338 if (DSAStack->checkMappableExprComponentListsForDecl( 8339 VD, /* CurrentRegionOnly = */ true, 8340 [&](OMPClauseMappableExprCommon::MappableExprComponentListRef) 8341 -> bool { return true; })) { 8342 Diag(ELoc, diag::err_omp_variable_in_map_and_dsa) 8343 << getOpenMPClauseName(OMPC_firstprivate) 8344 << getOpenMPDirectiveName(DSAStack->getCurrentDirective()); 8345 ReportOriginalDSA(*this, DSAStack, D, DVar); 8346 continue; 8347 } 8348 } 8349 } 8350 8351 // Variably modified types are not supported for tasks. 8352 if (!Type->isAnyPointerType() && Type->isVariablyModifiedType() && 8353 isOpenMPTaskingDirective(DSAStack->getCurrentDirective())) { 8354 Diag(ELoc, diag::err_omp_variably_modified_type_not_supported) 8355 << getOpenMPClauseName(OMPC_firstprivate) << Type 8356 << getOpenMPDirectiveName(DSAStack->getCurrentDirective()); 8357 bool IsDecl = 8358 !VD || 8359 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly; 8360 Diag(D->getLocation(), 8361 IsDecl ? diag::note_previous_decl : diag::note_defined_here) 8362 << D; 8363 continue; 8364 } 8365 8366 Type = Type.getUnqualifiedType(); 8367 auto VDPrivate = buildVarDecl(*this, ELoc, Type, D->getName(), 8368 D->hasAttrs() ? &D->getAttrs() : nullptr); 8369 // Generate helper private variable and initialize it with the value of the 8370 // original variable. The address of the original variable is replaced by 8371 // the address of the new private variable in the CodeGen. This new variable 8372 // is not added to IdResolver, so the code in the OpenMP region uses 8373 // original variable for proper diagnostics and variable capturing. 8374 Expr *VDInitRefExpr = nullptr; 8375 // For arrays generate initializer for single element and replace it by the 8376 // original array element in CodeGen. 8377 if (Type->isArrayType()) { 8378 auto VDInit = 8379 buildVarDecl(*this, RefExpr->getExprLoc(), ElemType, D->getName()); 8380 VDInitRefExpr = buildDeclRefExpr(*this, VDInit, ElemType, ELoc); 8381 auto Init = DefaultLvalueConversion(VDInitRefExpr).get(); 8382 ElemType = ElemType.getUnqualifiedType(); 8383 auto *VDInitTemp = buildVarDecl(*this, RefExpr->getExprLoc(), ElemType, 8384 ".firstprivate.temp"); 8385 InitializedEntity Entity = 8386 InitializedEntity::InitializeVariable(VDInitTemp); 8387 InitializationKind Kind = InitializationKind::CreateCopy(ELoc, ELoc); 8388 8389 InitializationSequence InitSeq(*this, Entity, Kind, Init); 8390 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Init); 8391 if (Result.isInvalid()) 8392 VDPrivate->setInvalidDecl(); 8393 else 8394 VDPrivate->setInit(Result.getAs<Expr>()); 8395 // Remove temp variable declaration. 8396 Context.Deallocate(VDInitTemp); 8397 } else { 8398 auto *VDInit = buildVarDecl(*this, RefExpr->getExprLoc(), Type, 8399 ".firstprivate.temp"); 8400 VDInitRefExpr = buildDeclRefExpr(*this, VDInit, RefExpr->getType(), 8401 RefExpr->getExprLoc()); 8402 AddInitializerToDecl(VDPrivate, 8403 DefaultLvalueConversion(VDInitRefExpr).get(), 8404 /*DirectInit=*/false, /*TypeMayContainAuto=*/false); 8405 } 8406 if (VDPrivate->isInvalidDecl()) { 8407 if (IsImplicitClause) { 8408 Diag(RefExpr->getExprLoc(), 8409 diag::note_omp_task_predetermined_firstprivate_here); 8410 } 8411 continue; 8412 } 8413 CurContext->addDecl(VDPrivate); 8414 auto VDPrivateRefExpr = buildDeclRefExpr( 8415 *this, VDPrivate, RefExpr->getType().getUnqualifiedType(), 8416 RefExpr->getExprLoc()); 8417 DeclRefExpr *Ref = nullptr; 8418 if (!VD) { 8419 if (TopDVar.CKind == OMPC_lastprivate) 8420 Ref = TopDVar.PrivateCopy; 8421 else { 8422 Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/true); 8423 if (!IsOpenMPCapturedDecl(D)) 8424 ExprCaptures.push_back(Ref->getDecl()); 8425 } 8426 } 8427 DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_firstprivate, Ref); 8428 Vars.push_back(VD ? RefExpr->IgnoreParens() : Ref); 8429 PrivateCopies.push_back(VDPrivateRefExpr); 8430 Inits.push_back(VDInitRefExpr); 8431 } 8432 8433 if (Vars.empty()) 8434 return nullptr; 8435 8436 return OMPFirstprivateClause::Create(Context, StartLoc, LParenLoc, EndLoc, 8437 Vars, PrivateCopies, Inits, 8438 buildPreInits(Context, ExprCaptures)); 8439 } 8440 8441 OMPClause *Sema::ActOnOpenMPLastprivateClause(ArrayRef<Expr *> VarList, 8442 SourceLocation StartLoc, 8443 SourceLocation LParenLoc, 8444 SourceLocation EndLoc) { 8445 SmallVector<Expr *, 8> Vars; 8446 SmallVector<Expr *, 8> SrcExprs; 8447 SmallVector<Expr *, 8> DstExprs; 8448 SmallVector<Expr *, 8> AssignmentOps; 8449 SmallVector<Decl *, 4> ExprCaptures; 8450 SmallVector<Expr *, 4> ExprPostUpdates; 8451 for (auto &RefExpr : VarList) { 8452 assert(RefExpr && "NULL expr in OpenMP lastprivate clause."); 8453 SourceLocation ELoc; 8454 SourceRange ERange; 8455 Expr *SimpleRefExpr = RefExpr; 8456 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange); 8457 if (Res.second) { 8458 // It will be analyzed later. 8459 Vars.push_back(RefExpr); 8460 SrcExprs.push_back(nullptr); 8461 DstExprs.push_back(nullptr); 8462 AssignmentOps.push_back(nullptr); 8463 } 8464 ValueDecl *D = Res.first; 8465 if (!D) 8466 continue; 8467 8468 QualType Type = D->getType(); 8469 auto *VD = dyn_cast<VarDecl>(D); 8470 8471 // OpenMP [2.14.3.5, Restrictions, C/C++, p.2] 8472 // A variable that appears in a lastprivate clause must not have an 8473 // incomplete type or a reference type. 8474 if (RequireCompleteType(ELoc, Type, 8475 diag::err_omp_lastprivate_incomplete_type)) 8476 continue; 8477 Type = Type.getNonReferenceType(); 8478 8479 // OpenMP [2.14.1.1, Data-sharing Attribute Rules for Variables Referenced 8480 // in a Construct] 8481 // Variables with the predetermined data-sharing attributes may not be 8482 // listed in data-sharing attributes clauses, except for the cases 8483 // listed below. 8484 DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, false); 8485 if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_lastprivate && 8486 DVar.CKind != OMPC_firstprivate && 8487 (DVar.CKind != OMPC_private || DVar.RefExpr != nullptr)) { 8488 Diag(ELoc, diag::err_omp_wrong_dsa) 8489 << getOpenMPClauseName(DVar.CKind) 8490 << getOpenMPClauseName(OMPC_lastprivate); 8491 ReportOriginalDSA(*this, DSAStack, D, DVar); 8492 continue; 8493 } 8494 8495 OpenMPDirectiveKind CurrDir = DSAStack->getCurrentDirective(); 8496 // OpenMP [2.14.3.5, Restrictions, p.2] 8497 // A list item that is private within a parallel region, or that appears in 8498 // the reduction clause of a parallel construct, must not appear in a 8499 // lastprivate clause on a worksharing construct if any of the corresponding 8500 // worksharing regions ever binds to any of the corresponding parallel 8501 // regions. 8502 DSAStackTy::DSAVarData TopDVar = DVar; 8503 if (isOpenMPWorksharingDirective(CurrDir) && 8504 !isOpenMPParallelDirective(CurrDir)) { 8505 DVar = DSAStack->getImplicitDSA(D, true); 8506 if (DVar.CKind != OMPC_shared) { 8507 Diag(ELoc, diag::err_omp_required_access) 8508 << getOpenMPClauseName(OMPC_lastprivate) 8509 << getOpenMPClauseName(OMPC_shared); 8510 ReportOriginalDSA(*this, DSAStack, D, DVar); 8511 continue; 8512 } 8513 } 8514 8515 // OpenMP 4.5 [2.10.8, Distribute Construct, p.3] 8516 // A list item may appear in a firstprivate or lastprivate clause but not 8517 // both. 8518 if (CurrDir == OMPD_distribute) { 8519 DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, false); 8520 if (DVar.CKind == OMPC_firstprivate) { 8521 Diag(ELoc, diag::err_omp_firstprivate_and_lastprivate_in_distribute); 8522 ReportOriginalDSA(*this, DSAStack, D, DVar); 8523 continue; 8524 } 8525 } 8526 8527 // OpenMP [2.14.3.5, Restrictions, C++, p.1,2] 8528 // A variable of class type (or array thereof) that appears in a 8529 // lastprivate clause requires an accessible, unambiguous default 8530 // constructor for the class type, unless the list item is also specified 8531 // in a firstprivate clause. 8532 // A variable of class type (or array thereof) that appears in a 8533 // lastprivate clause requires an accessible, unambiguous copy assignment 8534 // operator for the class type. 8535 Type = Context.getBaseElementType(Type).getNonReferenceType(); 8536 auto *SrcVD = buildVarDecl(*this, ERange.getBegin(), 8537 Type.getUnqualifiedType(), ".lastprivate.src", 8538 D->hasAttrs() ? &D->getAttrs() : nullptr); 8539 auto *PseudoSrcExpr = 8540 buildDeclRefExpr(*this, SrcVD, Type.getUnqualifiedType(), ELoc); 8541 auto *DstVD = 8542 buildVarDecl(*this, ERange.getBegin(), Type, ".lastprivate.dst", 8543 D->hasAttrs() ? &D->getAttrs() : nullptr); 8544 auto *PseudoDstExpr = buildDeclRefExpr(*this, DstVD, Type, ELoc); 8545 // For arrays generate assignment operation for single element and replace 8546 // it by the original array element in CodeGen. 8547 auto AssignmentOp = BuildBinOp(/*S=*/nullptr, ELoc, BO_Assign, 8548 PseudoDstExpr, PseudoSrcExpr); 8549 if (AssignmentOp.isInvalid()) 8550 continue; 8551 AssignmentOp = ActOnFinishFullExpr(AssignmentOp.get(), ELoc, 8552 /*DiscardedValue=*/true); 8553 if (AssignmentOp.isInvalid()) 8554 continue; 8555 8556 DeclRefExpr *Ref = nullptr; 8557 if (!VD) { 8558 if (TopDVar.CKind == OMPC_firstprivate) 8559 Ref = TopDVar.PrivateCopy; 8560 else { 8561 Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/false); 8562 if (!IsOpenMPCapturedDecl(D)) 8563 ExprCaptures.push_back(Ref->getDecl()); 8564 } 8565 if (TopDVar.CKind == OMPC_firstprivate || 8566 (!IsOpenMPCapturedDecl(D) && 8567 Ref->getDecl()->hasAttr<OMPCaptureNoInitAttr>())) { 8568 ExprResult RefRes = DefaultLvalueConversion(Ref); 8569 if (!RefRes.isUsable()) 8570 continue; 8571 ExprResult PostUpdateRes = 8572 BuildBinOp(DSAStack->getCurScope(), ELoc, BO_Assign, SimpleRefExpr, 8573 RefRes.get()); 8574 if (!PostUpdateRes.isUsable()) 8575 continue; 8576 ExprPostUpdates.push_back( 8577 IgnoredValueConversions(PostUpdateRes.get()).get()); 8578 } 8579 } 8580 DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_lastprivate, Ref); 8581 Vars.push_back(VD ? RefExpr->IgnoreParens() : Ref); 8582 SrcExprs.push_back(PseudoSrcExpr); 8583 DstExprs.push_back(PseudoDstExpr); 8584 AssignmentOps.push_back(AssignmentOp.get()); 8585 } 8586 8587 if (Vars.empty()) 8588 return nullptr; 8589 8590 return OMPLastprivateClause::Create(Context, StartLoc, LParenLoc, EndLoc, 8591 Vars, SrcExprs, DstExprs, AssignmentOps, 8592 buildPreInits(Context, ExprCaptures), 8593 buildPostUpdate(*this, ExprPostUpdates)); 8594 } 8595 8596 OMPClause *Sema::ActOnOpenMPSharedClause(ArrayRef<Expr *> VarList, 8597 SourceLocation StartLoc, 8598 SourceLocation LParenLoc, 8599 SourceLocation EndLoc) { 8600 SmallVector<Expr *, 8> Vars; 8601 for (auto &RefExpr : VarList) { 8602 assert(RefExpr && "NULL expr in OpenMP lastprivate clause."); 8603 SourceLocation ELoc; 8604 SourceRange ERange; 8605 Expr *SimpleRefExpr = RefExpr; 8606 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange); 8607 if (Res.second) { 8608 // It will be analyzed later. 8609 Vars.push_back(RefExpr); 8610 } 8611 ValueDecl *D = Res.first; 8612 if (!D) 8613 continue; 8614 8615 auto *VD = dyn_cast<VarDecl>(D); 8616 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced 8617 // in a Construct] 8618 // Variables with the predetermined data-sharing attributes may not be 8619 // listed in data-sharing attributes clauses, except for the cases 8620 // listed below. For these exceptions only, listing a predetermined 8621 // variable in a data-sharing attribute clause is allowed and overrides 8622 // the variable's predetermined data-sharing attributes. 8623 DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, false); 8624 if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_shared && 8625 DVar.RefExpr) { 8626 Diag(ELoc, diag::err_omp_wrong_dsa) << getOpenMPClauseName(DVar.CKind) 8627 << getOpenMPClauseName(OMPC_shared); 8628 ReportOriginalDSA(*this, DSAStack, D, DVar); 8629 continue; 8630 } 8631 8632 DeclRefExpr *Ref = nullptr; 8633 if (!VD && IsOpenMPCapturedDecl(D)) 8634 Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/true); 8635 DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_shared, Ref); 8636 Vars.push_back((VD || !Ref) ? RefExpr->IgnoreParens() : Ref); 8637 } 8638 8639 if (Vars.empty()) 8640 return nullptr; 8641 8642 return OMPSharedClause::Create(Context, StartLoc, LParenLoc, EndLoc, Vars); 8643 } 8644 8645 namespace { 8646 class DSARefChecker : public StmtVisitor<DSARefChecker, bool> { 8647 DSAStackTy *Stack; 8648 8649 public: 8650 bool VisitDeclRefExpr(DeclRefExpr *E) { 8651 if (VarDecl *VD = dyn_cast<VarDecl>(E->getDecl())) { 8652 DSAStackTy::DSAVarData DVar = Stack->getTopDSA(VD, false); 8653 if (DVar.CKind == OMPC_shared && !DVar.RefExpr) 8654 return false; 8655 if (DVar.CKind != OMPC_unknown) 8656 return true; 8657 DSAStackTy::DSAVarData DVarPrivate = Stack->hasDSA( 8658 VD, isOpenMPPrivate, [](OpenMPDirectiveKind) -> bool { return true; }, 8659 false); 8660 if (DVarPrivate.CKind != OMPC_unknown) 8661 return true; 8662 return false; 8663 } 8664 return false; 8665 } 8666 bool VisitStmt(Stmt *S) { 8667 for (auto Child : S->children()) { 8668 if (Child && Visit(Child)) 8669 return true; 8670 } 8671 return false; 8672 } 8673 explicit DSARefChecker(DSAStackTy *S) : Stack(S) {} 8674 }; 8675 } // namespace 8676 8677 namespace { 8678 // Transform MemberExpression for specified FieldDecl of current class to 8679 // DeclRefExpr to specified OMPCapturedExprDecl. 8680 class TransformExprToCaptures : public TreeTransform<TransformExprToCaptures> { 8681 typedef TreeTransform<TransformExprToCaptures> BaseTransform; 8682 ValueDecl *Field; 8683 DeclRefExpr *CapturedExpr; 8684 8685 public: 8686 TransformExprToCaptures(Sema &SemaRef, ValueDecl *FieldDecl) 8687 : BaseTransform(SemaRef), Field(FieldDecl), CapturedExpr(nullptr) {} 8688 8689 ExprResult TransformMemberExpr(MemberExpr *E) { 8690 if (isa<CXXThisExpr>(E->getBase()->IgnoreParenImpCasts()) && 8691 E->getMemberDecl() == Field) { 8692 CapturedExpr = buildCapture(SemaRef, Field, E, /*WithInit=*/false); 8693 return CapturedExpr; 8694 } 8695 return BaseTransform::TransformMemberExpr(E); 8696 } 8697 DeclRefExpr *getCapturedExpr() { return CapturedExpr; } 8698 }; 8699 } // namespace 8700 8701 template <typename T> 8702 static T filterLookupForUDR(SmallVectorImpl<UnresolvedSet<8>> &Lookups, 8703 const llvm::function_ref<T(ValueDecl *)> &Gen) { 8704 for (auto &Set : Lookups) { 8705 for (auto *D : Set) { 8706 if (auto Res = Gen(cast<ValueDecl>(D))) 8707 return Res; 8708 } 8709 } 8710 return T(); 8711 } 8712 8713 static ExprResult 8714 buildDeclareReductionRef(Sema &SemaRef, SourceLocation Loc, SourceRange Range, 8715 Scope *S, CXXScopeSpec &ReductionIdScopeSpec, 8716 const DeclarationNameInfo &ReductionId, QualType Ty, 8717 CXXCastPath &BasePath, Expr *UnresolvedReduction) { 8718 if (ReductionIdScopeSpec.isInvalid()) 8719 return ExprError(); 8720 SmallVector<UnresolvedSet<8>, 4> Lookups; 8721 if (S) { 8722 LookupResult Lookup(SemaRef, ReductionId, Sema::LookupOMPReductionName); 8723 Lookup.suppressDiagnostics(); 8724 while (S && SemaRef.LookupParsedName(Lookup, S, &ReductionIdScopeSpec)) { 8725 auto *D = Lookup.getRepresentativeDecl(); 8726 do { 8727 S = S->getParent(); 8728 } while (S && !S->isDeclScope(D)); 8729 if (S) 8730 S = S->getParent(); 8731 Lookups.push_back(UnresolvedSet<8>()); 8732 Lookups.back().append(Lookup.begin(), Lookup.end()); 8733 Lookup.clear(); 8734 } 8735 } else if (auto *ULE = 8736 cast_or_null<UnresolvedLookupExpr>(UnresolvedReduction)) { 8737 Lookups.push_back(UnresolvedSet<8>()); 8738 Decl *PrevD = nullptr; 8739 for(auto *D : ULE->decls()) { 8740 if (D == PrevD) 8741 Lookups.push_back(UnresolvedSet<8>()); 8742 else if (auto *DRD = cast<OMPDeclareReductionDecl>(D)) 8743 Lookups.back().addDecl(DRD); 8744 PrevD = D; 8745 } 8746 } 8747 if (Ty->isDependentType() || Ty->isInstantiationDependentType() || 8748 Ty->containsUnexpandedParameterPack() || 8749 filterLookupForUDR<bool>(Lookups, [](ValueDecl *D) -> bool { 8750 return !D->isInvalidDecl() && 8751 (D->getType()->isDependentType() || 8752 D->getType()->isInstantiationDependentType() || 8753 D->getType()->containsUnexpandedParameterPack()); 8754 })) { 8755 UnresolvedSet<8> ResSet; 8756 for (auto &Set : Lookups) { 8757 ResSet.append(Set.begin(), Set.end()); 8758 // The last item marks the end of all declarations at the specified scope. 8759 ResSet.addDecl(Set[Set.size() - 1]); 8760 } 8761 return UnresolvedLookupExpr::Create( 8762 SemaRef.Context, /*NamingClass=*/nullptr, 8763 ReductionIdScopeSpec.getWithLocInContext(SemaRef.Context), ReductionId, 8764 /*ADL=*/true, /*Overloaded=*/true, ResSet.begin(), ResSet.end()); 8765 } 8766 if (auto *VD = filterLookupForUDR<ValueDecl *>( 8767 Lookups, [&SemaRef, Ty](ValueDecl *D) -> ValueDecl * { 8768 if (!D->isInvalidDecl() && 8769 SemaRef.Context.hasSameType(D->getType(), Ty)) 8770 return D; 8771 return nullptr; 8772 })) 8773 return SemaRef.BuildDeclRefExpr(VD, Ty, VK_LValue, Loc); 8774 if (auto *VD = filterLookupForUDR<ValueDecl *>( 8775 Lookups, [&SemaRef, Ty, Loc](ValueDecl *D) -> ValueDecl * { 8776 if (!D->isInvalidDecl() && 8777 SemaRef.IsDerivedFrom(Loc, Ty, D->getType()) && 8778 !Ty.isMoreQualifiedThan(D->getType())) 8779 return D; 8780 return nullptr; 8781 })) { 8782 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true, 8783 /*DetectVirtual=*/false); 8784 if (SemaRef.IsDerivedFrom(Loc, Ty, VD->getType(), Paths)) { 8785 if (!Paths.isAmbiguous(SemaRef.Context.getCanonicalType( 8786 VD->getType().getUnqualifiedType()))) { 8787 if (SemaRef.CheckBaseClassAccess(Loc, VD->getType(), Ty, Paths.front(), 8788 /*DiagID=*/0) != 8789 Sema::AR_inaccessible) { 8790 SemaRef.BuildBasePathArray(Paths, BasePath); 8791 return SemaRef.BuildDeclRefExpr(VD, Ty, VK_LValue, Loc); 8792 } 8793 } 8794 } 8795 } 8796 if (ReductionIdScopeSpec.isSet()) { 8797 SemaRef.Diag(Loc, diag::err_omp_not_resolved_reduction_identifier) << Range; 8798 return ExprError(); 8799 } 8800 return ExprEmpty(); 8801 } 8802 8803 OMPClause *Sema::ActOnOpenMPReductionClause( 8804 ArrayRef<Expr *> VarList, SourceLocation StartLoc, SourceLocation LParenLoc, 8805 SourceLocation ColonLoc, SourceLocation EndLoc, 8806 CXXScopeSpec &ReductionIdScopeSpec, const DeclarationNameInfo &ReductionId, 8807 ArrayRef<Expr *> UnresolvedReductions) { 8808 auto DN = ReductionId.getName(); 8809 auto OOK = DN.getCXXOverloadedOperator(); 8810 BinaryOperatorKind BOK = BO_Comma; 8811 8812 // OpenMP [2.14.3.6, reduction clause] 8813 // C 8814 // reduction-identifier is either an identifier or one of the following 8815 // operators: +, -, *, &, |, ^, && and || 8816 // C++ 8817 // reduction-identifier is either an id-expression or one of the following 8818 // operators: +, -, *, &, |, ^, && and || 8819 // FIXME: Only 'min' and 'max' identifiers are supported for now. 8820 switch (OOK) { 8821 case OO_Plus: 8822 case OO_Minus: 8823 BOK = BO_Add; 8824 break; 8825 case OO_Star: 8826 BOK = BO_Mul; 8827 break; 8828 case OO_Amp: 8829 BOK = BO_And; 8830 break; 8831 case OO_Pipe: 8832 BOK = BO_Or; 8833 break; 8834 case OO_Caret: 8835 BOK = BO_Xor; 8836 break; 8837 case OO_AmpAmp: 8838 BOK = BO_LAnd; 8839 break; 8840 case OO_PipePipe: 8841 BOK = BO_LOr; 8842 break; 8843 case OO_New: 8844 case OO_Delete: 8845 case OO_Array_New: 8846 case OO_Array_Delete: 8847 case OO_Slash: 8848 case OO_Percent: 8849 case OO_Tilde: 8850 case OO_Exclaim: 8851 case OO_Equal: 8852 case OO_Less: 8853 case OO_Greater: 8854 case OO_LessEqual: 8855 case OO_GreaterEqual: 8856 case OO_PlusEqual: 8857 case OO_MinusEqual: 8858 case OO_StarEqual: 8859 case OO_SlashEqual: 8860 case OO_PercentEqual: 8861 case OO_CaretEqual: 8862 case OO_AmpEqual: 8863 case OO_PipeEqual: 8864 case OO_LessLess: 8865 case OO_GreaterGreater: 8866 case OO_LessLessEqual: 8867 case OO_GreaterGreaterEqual: 8868 case OO_EqualEqual: 8869 case OO_ExclaimEqual: 8870 case OO_PlusPlus: 8871 case OO_MinusMinus: 8872 case OO_Comma: 8873 case OO_ArrowStar: 8874 case OO_Arrow: 8875 case OO_Call: 8876 case OO_Subscript: 8877 case OO_Conditional: 8878 case OO_Coawait: 8879 case NUM_OVERLOADED_OPERATORS: 8880 llvm_unreachable("Unexpected reduction identifier"); 8881 case OO_None: 8882 if (auto II = DN.getAsIdentifierInfo()) { 8883 if (II->isStr("max")) 8884 BOK = BO_GT; 8885 else if (II->isStr("min")) 8886 BOK = BO_LT; 8887 } 8888 break; 8889 } 8890 SourceRange ReductionIdRange; 8891 if (ReductionIdScopeSpec.isValid()) 8892 ReductionIdRange.setBegin(ReductionIdScopeSpec.getBeginLoc()); 8893 ReductionIdRange.setEnd(ReductionId.getEndLoc()); 8894 8895 SmallVector<Expr *, 8> Vars; 8896 SmallVector<Expr *, 8> Privates; 8897 SmallVector<Expr *, 8> LHSs; 8898 SmallVector<Expr *, 8> RHSs; 8899 SmallVector<Expr *, 8> ReductionOps; 8900 SmallVector<Decl *, 4> ExprCaptures; 8901 SmallVector<Expr *, 4> ExprPostUpdates; 8902 auto IR = UnresolvedReductions.begin(), ER = UnresolvedReductions.end(); 8903 bool FirstIter = true; 8904 for (auto RefExpr : VarList) { 8905 assert(RefExpr && "nullptr expr in OpenMP reduction clause."); 8906 // OpenMP [2.1, C/C++] 8907 // A list item is a variable or array section, subject to the restrictions 8908 // specified in Section 2.4 on page 42 and in each of the sections 8909 // describing clauses and directives for which a list appears. 8910 // OpenMP [2.14.3.3, Restrictions, p.1] 8911 // A variable that is part of another variable (as an array or 8912 // structure element) cannot appear in a private clause. 8913 if (!FirstIter && IR != ER) 8914 ++IR; 8915 FirstIter = false; 8916 SourceLocation ELoc; 8917 SourceRange ERange; 8918 Expr *SimpleRefExpr = RefExpr; 8919 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange, 8920 /*AllowArraySection=*/true); 8921 if (Res.second) { 8922 // It will be analyzed later. 8923 Vars.push_back(RefExpr); 8924 Privates.push_back(nullptr); 8925 LHSs.push_back(nullptr); 8926 RHSs.push_back(nullptr); 8927 // Try to find 'declare reduction' corresponding construct before using 8928 // builtin/overloaded operators. 8929 QualType Type = Context.DependentTy; 8930 CXXCastPath BasePath; 8931 ExprResult DeclareReductionRef = buildDeclareReductionRef( 8932 *this, ELoc, ERange, DSAStack->getCurScope(), ReductionIdScopeSpec, 8933 ReductionId, Type, BasePath, IR == ER ? nullptr : *IR); 8934 if (CurContext->isDependentContext() && 8935 (DeclareReductionRef.isUnset() || 8936 isa<UnresolvedLookupExpr>(DeclareReductionRef.get()))) 8937 ReductionOps.push_back(DeclareReductionRef.get()); 8938 else 8939 ReductionOps.push_back(nullptr); 8940 } 8941 ValueDecl *D = Res.first; 8942 if (!D) 8943 continue; 8944 8945 QualType Type; 8946 auto *ASE = dyn_cast<ArraySubscriptExpr>(RefExpr->IgnoreParens()); 8947 auto *OASE = dyn_cast<OMPArraySectionExpr>(RefExpr->IgnoreParens()); 8948 if (ASE) 8949 Type = ASE->getType().getNonReferenceType(); 8950 else if (OASE) { 8951 auto BaseType = OMPArraySectionExpr::getBaseOriginalType(OASE->getBase()); 8952 if (auto *ATy = BaseType->getAsArrayTypeUnsafe()) 8953 Type = ATy->getElementType(); 8954 else 8955 Type = BaseType->getPointeeType(); 8956 Type = Type.getNonReferenceType(); 8957 } else 8958 Type = Context.getBaseElementType(D->getType().getNonReferenceType()); 8959 auto *VD = dyn_cast<VarDecl>(D); 8960 8961 // OpenMP [2.9.3.3, Restrictions, C/C++, p.3] 8962 // A variable that appears in a private clause must not have an incomplete 8963 // type or a reference type. 8964 if (RequireCompleteType(ELoc, Type, 8965 diag::err_omp_reduction_incomplete_type)) 8966 continue; 8967 // OpenMP [2.14.3.6, reduction clause, Restrictions] 8968 // A list item that appears in a reduction clause must not be 8969 // const-qualified. 8970 if (Type.getNonReferenceType().isConstant(Context)) { 8971 Diag(ELoc, diag::err_omp_const_reduction_list_item) 8972 << getOpenMPClauseName(OMPC_reduction) << Type << ERange; 8973 if (!ASE && !OASE) { 8974 bool IsDecl = !VD || 8975 VD->isThisDeclarationADefinition(Context) == 8976 VarDecl::DeclarationOnly; 8977 Diag(D->getLocation(), 8978 IsDecl ? diag::note_previous_decl : diag::note_defined_here) 8979 << D; 8980 } 8981 continue; 8982 } 8983 // OpenMP [2.9.3.6, Restrictions, C/C++, p.4] 8984 // If a list-item is a reference type then it must bind to the same object 8985 // for all threads of the team. 8986 if (!ASE && !OASE && VD) { 8987 VarDecl *VDDef = VD->getDefinition(); 8988 if (VD->getType()->isReferenceType() && VDDef) { 8989 DSARefChecker Check(DSAStack); 8990 if (Check.Visit(VDDef->getInit())) { 8991 Diag(ELoc, diag::err_omp_reduction_ref_type_arg) << ERange; 8992 Diag(VDDef->getLocation(), diag::note_defined_here) << VDDef; 8993 continue; 8994 } 8995 } 8996 } 8997 8998 // OpenMP [2.14.1.1, Data-sharing Attribute Rules for Variables Referenced 8999 // in a Construct] 9000 // Variables with the predetermined data-sharing attributes may not be 9001 // listed in data-sharing attributes clauses, except for the cases 9002 // listed below. For these exceptions only, listing a predetermined 9003 // variable in a data-sharing attribute clause is allowed and overrides 9004 // the variable's predetermined data-sharing attributes. 9005 // OpenMP [2.14.3.6, Restrictions, p.3] 9006 // Any number of reduction clauses can be specified on the directive, 9007 // but a list item can appear only once in the reduction clauses for that 9008 // directive. 9009 DSAStackTy::DSAVarData DVar; 9010 DVar = DSAStack->getTopDSA(D, false); 9011 if (DVar.CKind == OMPC_reduction) { 9012 Diag(ELoc, diag::err_omp_once_referenced) 9013 << getOpenMPClauseName(OMPC_reduction); 9014 if (DVar.RefExpr) 9015 Diag(DVar.RefExpr->getExprLoc(), diag::note_omp_referenced); 9016 } else if (DVar.CKind != OMPC_unknown) { 9017 Diag(ELoc, diag::err_omp_wrong_dsa) 9018 << getOpenMPClauseName(DVar.CKind) 9019 << getOpenMPClauseName(OMPC_reduction); 9020 ReportOriginalDSA(*this, DSAStack, D, DVar); 9021 continue; 9022 } 9023 9024 // OpenMP [2.14.3.6, Restrictions, p.1] 9025 // A list item that appears in a reduction clause of a worksharing 9026 // construct must be shared in the parallel regions to which any of the 9027 // worksharing regions arising from the worksharing construct bind. 9028 OpenMPDirectiveKind CurrDir = DSAStack->getCurrentDirective(); 9029 if (isOpenMPWorksharingDirective(CurrDir) && 9030 !isOpenMPParallelDirective(CurrDir)) { 9031 DVar = DSAStack->getImplicitDSA(D, true); 9032 if (DVar.CKind != OMPC_shared) { 9033 Diag(ELoc, diag::err_omp_required_access) 9034 << getOpenMPClauseName(OMPC_reduction) 9035 << getOpenMPClauseName(OMPC_shared); 9036 ReportOriginalDSA(*this, DSAStack, D, DVar); 9037 continue; 9038 } 9039 } 9040 9041 // Try to find 'declare reduction' corresponding construct before using 9042 // builtin/overloaded operators. 9043 CXXCastPath BasePath; 9044 ExprResult DeclareReductionRef = buildDeclareReductionRef( 9045 *this, ELoc, ERange, DSAStack->getCurScope(), ReductionIdScopeSpec, 9046 ReductionId, Type, BasePath, IR == ER ? nullptr : *IR); 9047 if (DeclareReductionRef.isInvalid()) 9048 continue; 9049 if (CurContext->isDependentContext() && 9050 (DeclareReductionRef.isUnset() || 9051 isa<UnresolvedLookupExpr>(DeclareReductionRef.get()))) { 9052 Vars.push_back(RefExpr); 9053 Privates.push_back(nullptr); 9054 LHSs.push_back(nullptr); 9055 RHSs.push_back(nullptr); 9056 ReductionOps.push_back(DeclareReductionRef.get()); 9057 continue; 9058 } 9059 if (BOK == BO_Comma && DeclareReductionRef.isUnset()) { 9060 // Not allowed reduction identifier is found. 9061 Diag(ReductionId.getLocStart(), 9062 diag::err_omp_unknown_reduction_identifier) 9063 << Type << ReductionIdRange; 9064 continue; 9065 } 9066 9067 // OpenMP [2.14.3.6, reduction clause, Restrictions] 9068 // The type of a list item that appears in a reduction clause must be valid 9069 // for the reduction-identifier. For a max or min reduction in C, the type 9070 // of the list item must be an allowed arithmetic data type: char, int, 9071 // float, double, or _Bool, possibly modified with long, short, signed, or 9072 // unsigned. For a max or min reduction in C++, the type of the list item 9073 // must be an allowed arithmetic data type: char, wchar_t, int, float, 9074 // double, or bool, possibly modified with long, short, signed, or unsigned. 9075 if (DeclareReductionRef.isUnset()) { 9076 if ((BOK == BO_GT || BOK == BO_LT) && 9077 !(Type->isScalarType() || 9078 (getLangOpts().CPlusPlus && Type->isArithmeticType()))) { 9079 Diag(ELoc, diag::err_omp_clause_not_arithmetic_type_arg) 9080 << getLangOpts().CPlusPlus; 9081 if (!ASE && !OASE) { 9082 bool IsDecl = !VD || 9083 VD->isThisDeclarationADefinition(Context) == 9084 VarDecl::DeclarationOnly; 9085 Diag(D->getLocation(), 9086 IsDecl ? diag::note_previous_decl : diag::note_defined_here) 9087 << D; 9088 } 9089 continue; 9090 } 9091 if ((BOK == BO_OrAssign || BOK == BO_AndAssign || BOK == BO_XorAssign) && 9092 !getLangOpts().CPlusPlus && Type->isFloatingType()) { 9093 Diag(ELoc, diag::err_omp_clause_floating_type_arg); 9094 if (!ASE && !OASE) { 9095 bool IsDecl = !VD || 9096 VD->isThisDeclarationADefinition(Context) == 9097 VarDecl::DeclarationOnly; 9098 Diag(D->getLocation(), 9099 IsDecl ? diag::note_previous_decl : diag::note_defined_here) 9100 << D; 9101 } 9102 continue; 9103 } 9104 } 9105 9106 Type = Type.getNonLValueExprType(Context).getUnqualifiedType(); 9107 auto *LHSVD = buildVarDecl(*this, ELoc, Type, ".reduction.lhs", 9108 D->hasAttrs() ? &D->getAttrs() : nullptr); 9109 auto *RHSVD = buildVarDecl(*this, ELoc, Type, D->getName(), 9110 D->hasAttrs() ? &D->getAttrs() : nullptr); 9111 auto PrivateTy = Type; 9112 if (OASE || 9113 (!ASE && 9114 D->getType().getNonReferenceType()->isVariablyModifiedType())) { 9115 // For arays/array sections only: 9116 // Create pseudo array type for private copy. The size for this array will 9117 // be generated during codegen. 9118 // For array subscripts or single variables Private Ty is the same as Type 9119 // (type of the variable or single array element). 9120 PrivateTy = Context.getVariableArrayType( 9121 Type, new (Context) OpaqueValueExpr(SourceLocation(), 9122 Context.getSizeType(), VK_RValue), 9123 ArrayType::Normal, /*IndexTypeQuals=*/0, SourceRange()); 9124 } else if (!ASE && !OASE && 9125 Context.getAsArrayType(D->getType().getNonReferenceType())) 9126 PrivateTy = D->getType().getNonReferenceType(); 9127 // Private copy. 9128 auto *PrivateVD = buildVarDecl(*this, ELoc, PrivateTy, D->getName(), 9129 D->hasAttrs() ? &D->getAttrs() : nullptr); 9130 // Add initializer for private variable. 9131 Expr *Init = nullptr; 9132 auto *LHSDRE = buildDeclRefExpr(*this, LHSVD, Type, ELoc); 9133 auto *RHSDRE = buildDeclRefExpr(*this, RHSVD, Type, ELoc); 9134 if (DeclareReductionRef.isUsable()) { 9135 auto *DRDRef = DeclareReductionRef.getAs<DeclRefExpr>(); 9136 auto *DRD = cast<OMPDeclareReductionDecl>(DRDRef->getDecl()); 9137 if (DRD->getInitializer()) { 9138 Init = DRDRef; 9139 RHSVD->setInit(DRDRef); 9140 RHSVD->setInitStyle(VarDecl::CallInit); 9141 } 9142 } else { 9143 switch (BOK) { 9144 case BO_Add: 9145 case BO_Xor: 9146 case BO_Or: 9147 case BO_LOr: 9148 // '+', '-', '^', '|', '||' reduction ops - initializer is '0'. 9149 if (Type->isScalarType() || Type->isAnyComplexType()) 9150 Init = ActOnIntegerConstant(ELoc, /*Val=*/0).get(); 9151 break; 9152 case BO_Mul: 9153 case BO_LAnd: 9154 if (Type->isScalarType() || Type->isAnyComplexType()) { 9155 // '*' and '&&' reduction ops - initializer is '1'. 9156 Init = ActOnIntegerConstant(ELoc, /*Val=*/1).get(); 9157 } 9158 break; 9159 case BO_And: { 9160 // '&' reduction op - initializer is '~0'. 9161 QualType OrigType = Type; 9162 if (auto *ComplexTy = OrigType->getAs<ComplexType>()) 9163 Type = ComplexTy->getElementType(); 9164 if (Type->isRealFloatingType()) { 9165 llvm::APFloat InitValue = 9166 llvm::APFloat::getAllOnesValue(Context.getTypeSize(Type), 9167 /*isIEEE=*/true); 9168 Init = FloatingLiteral::Create(Context, InitValue, /*isexact=*/true, 9169 Type, ELoc); 9170 } else if (Type->isScalarType()) { 9171 auto Size = Context.getTypeSize(Type); 9172 QualType IntTy = Context.getIntTypeForBitwidth(Size, /*Signed=*/0); 9173 llvm::APInt InitValue = llvm::APInt::getAllOnesValue(Size); 9174 Init = IntegerLiteral::Create(Context, InitValue, IntTy, ELoc); 9175 } 9176 if (Init && OrigType->isAnyComplexType()) { 9177 // Init = 0xFFFF + 0xFFFFi; 9178 auto *Im = new (Context) ImaginaryLiteral(Init, OrigType); 9179 Init = CreateBuiltinBinOp(ELoc, BO_Add, Init, Im).get(); 9180 } 9181 Type = OrigType; 9182 break; 9183 } 9184 case BO_LT: 9185 case BO_GT: { 9186 // 'min' reduction op - initializer is 'Largest representable number in 9187 // the reduction list item type'. 9188 // 'max' reduction op - initializer is 'Least representable number in 9189 // the reduction list item type'. 9190 if (Type->isIntegerType() || Type->isPointerType()) { 9191 bool IsSigned = Type->hasSignedIntegerRepresentation(); 9192 auto Size = Context.getTypeSize(Type); 9193 QualType IntTy = 9194 Context.getIntTypeForBitwidth(Size, /*Signed=*/IsSigned); 9195 llvm::APInt InitValue = 9196 (BOK != BO_LT) 9197 ? IsSigned ? llvm::APInt::getSignedMinValue(Size) 9198 : llvm::APInt::getMinValue(Size) 9199 : IsSigned ? llvm::APInt::getSignedMaxValue(Size) 9200 : llvm::APInt::getMaxValue(Size); 9201 Init = IntegerLiteral::Create(Context, InitValue, IntTy, ELoc); 9202 if (Type->isPointerType()) { 9203 // Cast to pointer type. 9204 auto CastExpr = BuildCStyleCastExpr( 9205 SourceLocation(), Context.getTrivialTypeSourceInfo(Type, ELoc), 9206 SourceLocation(), Init); 9207 if (CastExpr.isInvalid()) 9208 continue; 9209 Init = CastExpr.get(); 9210 } 9211 } else if (Type->isRealFloatingType()) { 9212 llvm::APFloat InitValue = llvm::APFloat::getLargest( 9213 Context.getFloatTypeSemantics(Type), BOK != BO_LT); 9214 Init = FloatingLiteral::Create(Context, InitValue, /*isexact=*/true, 9215 Type, ELoc); 9216 } 9217 break; 9218 } 9219 case BO_PtrMemD: 9220 case BO_PtrMemI: 9221 case BO_MulAssign: 9222 case BO_Div: 9223 case BO_Rem: 9224 case BO_Sub: 9225 case BO_Shl: 9226 case BO_Shr: 9227 case BO_LE: 9228 case BO_GE: 9229 case BO_EQ: 9230 case BO_NE: 9231 case BO_AndAssign: 9232 case BO_XorAssign: 9233 case BO_OrAssign: 9234 case BO_Assign: 9235 case BO_AddAssign: 9236 case BO_SubAssign: 9237 case BO_DivAssign: 9238 case BO_RemAssign: 9239 case BO_ShlAssign: 9240 case BO_ShrAssign: 9241 case BO_Comma: 9242 llvm_unreachable("Unexpected reduction operation"); 9243 } 9244 } 9245 if (Init && DeclareReductionRef.isUnset()) { 9246 AddInitializerToDecl(RHSVD, Init, /*DirectInit=*/false, 9247 /*TypeMayContainAuto=*/false); 9248 } else if (!Init) 9249 ActOnUninitializedDecl(RHSVD, /*TypeMayContainAuto=*/false); 9250 if (RHSVD->isInvalidDecl()) 9251 continue; 9252 if (!RHSVD->hasInit() && DeclareReductionRef.isUnset()) { 9253 Diag(ELoc, diag::err_omp_reduction_id_not_compatible) << Type 9254 << ReductionIdRange; 9255 bool IsDecl = 9256 !VD || 9257 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly; 9258 Diag(D->getLocation(), 9259 IsDecl ? diag::note_previous_decl : diag::note_defined_here) 9260 << D; 9261 continue; 9262 } 9263 // Store initializer for single element in private copy. Will be used during 9264 // codegen. 9265 PrivateVD->setInit(RHSVD->getInit()); 9266 PrivateVD->setInitStyle(RHSVD->getInitStyle()); 9267 auto *PrivateDRE = buildDeclRefExpr(*this, PrivateVD, PrivateTy, ELoc); 9268 ExprResult ReductionOp; 9269 if (DeclareReductionRef.isUsable()) { 9270 QualType RedTy = DeclareReductionRef.get()->getType(); 9271 QualType PtrRedTy = Context.getPointerType(RedTy); 9272 ExprResult LHS = CreateBuiltinUnaryOp(ELoc, UO_AddrOf, LHSDRE); 9273 ExprResult RHS = CreateBuiltinUnaryOp(ELoc, UO_AddrOf, RHSDRE); 9274 if (!BasePath.empty()) { 9275 LHS = DefaultLvalueConversion(LHS.get()); 9276 RHS = DefaultLvalueConversion(RHS.get()); 9277 LHS = ImplicitCastExpr::Create(Context, PtrRedTy, 9278 CK_UncheckedDerivedToBase, LHS.get(), 9279 &BasePath, LHS.get()->getValueKind()); 9280 RHS = ImplicitCastExpr::Create(Context, PtrRedTy, 9281 CK_UncheckedDerivedToBase, RHS.get(), 9282 &BasePath, RHS.get()->getValueKind()); 9283 } 9284 FunctionProtoType::ExtProtoInfo EPI; 9285 QualType Params[] = {PtrRedTy, PtrRedTy}; 9286 QualType FnTy = Context.getFunctionType(Context.VoidTy, Params, EPI); 9287 auto *OVE = new (Context) OpaqueValueExpr( 9288 ELoc, Context.getPointerType(FnTy), VK_RValue, OK_Ordinary, 9289 DefaultLvalueConversion(DeclareReductionRef.get()).get()); 9290 Expr *Args[] = {LHS.get(), RHS.get()}; 9291 ReductionOp = new (Context) 9292 CallExpr(Context, OVE, Args, Context.VoidTy, VK_RValue, ELoc); 9293 } else { 9294 ReductionOp = BuildBinOp(DSAStack->getCurScope(), 9295 ReductionId.getLocStart(), BOK, LHSDRE, RHSDRE); 9296 if (ReductionOp.isUsable()) { 9297 if (BOK != BO_LT && BOK != BO_GT) { 9298 ReductionOp = 9299 BuildBinOp(DSAStack->getCurScope(), ReductionId.getLocStart(), 9300 BO_Assign, LHSDRE, ReductionOp.get()); 9301 } else { 9302 auto *ConditionalOp = new (Context) ConditionalOperator( 9303 ReductionOp.get(), SourceLocation(), LHSDRE, SourceLocation(), 9304 RHSDRE, Type, VK_LValue, OK_Ordinary); 9305 ReductionOp = 9306 BuildBinOp(DSAStack->getCurScope(), ReductionId.getLocStart(), 9307 BO_Assign, LHSDRE, ConditionalOp); 9308 } 9309 ReductionOp = ActOnFinishFullExpr(ReductionOp.get()); 9310 } 9311 if (ReductionOp.isInvalid()) 9312 continue; 9313 } 9314 9315 DeclRefExpr *Ref = nullptr; 9316 Expr *VarsExpr = RefExpr->IgnoreParens(); 9317 if (!VD) { 9318 if (ASE || OASE) { 9319 TransformExprToCaptures RebuildToCapture(*this, D); 9320 VarsExpr = 9321 RebuildToCapture.TransformExpr(RefExpr->IgnoreParens()).get(); 9322 Ref = RebuildToCapture.getCapturedExpr(); 9323 } else { 9324 VarsExpr = Ref = 9325 buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/false); 9326 } 9327 if (!IsOpenMPCapturedDecl(D)) { 9328 ExprCaptures.push_back(Ref->getDecl()); 9329 if (Ref->getDecl()->hasAttr<OMPCaptureNoInitAttr>()) { 9330 ExprResult RefRes = DefaultLvalueConversion(Ref); 9331 if (!RefRes.isUsable()) 9332 continue; 9333 ExprResult PostUpdateRes = 9334 BuildBinOp(DSAStack->getCurScope(), ELoc, BO_Assign, 9335 SimpleRefExpr, RefRes.get()); 9336 if (!PostUpdateRes.isUsable()) 9337 continue; 9338 ExprPostUpdates.push_back( 9339 IgnoredValueConversions(PostUpdateRes.get()).get()); 9340 } 9341 } 9342 } 9343 DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_reduction, Ref); 9344 Vars.push_back(VarsExpr); 9345 Privates.push_back(PrivateDRE); 9346 LHSs.push_back(LHSDRE); 9347 RHSs.push_back(RHSDRE); 9348 ReductionOps.push_back(ReductionOp.get()); 9349 } 9350 9351 if (Vars.empty()) 9352 return nullptr; 9353 9354 return OMPReductionClause::Create( 9355 Context, StartLoc, LParenLoc, ColonLoc, EndLoc, Vars, 9356 ReductionIdScopeSpec.getWithLocInContext(Context), ReductionId, Privates, 9357 LHSs, RHSs, ReductionOps, buildPreInits(Context, ExprCaptures), 9358 buildPostUpdate(*this, ExprPostUpdates)); 9359 } 9360 9361 bool Sema::CheckOpenMPLinearModifier(OpenMPLinearClauseKind LinKind, 9362 SourceLocation LinLoc) { 9363 if ((!LangOpts.CPlusPlus && LinKind != OMPC_LINEAR_val) || 9364 LinKind == OMPC_LINEAR_unknown) { 9365 Diag(LinLoc, diag::err_omp_wrong_linear_modifier) << LangOpts.CPlusPlus; 9366 return true; 9367 } 9368 return false; 9369 } 9370 9371 bool Sema::CheckOpenMPLinearDecl(ValueDecl *D, SourceLocation ELoc, 9372 OpenMPLinearClauseKind LinKind, 9373 QualType Type) { 9374 auto *VD = dyn_cast_or_null<VarDecl>(D); 9375 // A variable must not have an incomplete type or a reference type. 9376 if (RequireCompleteType(ELoc, Type, diag::err_omp_linear_incomplete_type)) 9377 return true; 9378 if ((LinKind == OMPC_LINEAR_uval || LinKind == OMPC_LINEAR_ref) && 9379 !Type->isReferenceType()) { 9380 Diag(ELoc, diag::err_omp_wrong_linear_modifier_non_reference) 9381 << Type << getOpenMPSimpleClauseTypeName(OMPC_linear, LinKind); 9382 return true; 9383 } 9384 Type = Type.getNonReferenceType(); 9385 9386 // A list item must not be const-qualified. 9387 if (Type.isConstant(Context)) { 9388 Diag(ELoc, diag::err_omp_const_variable) 9389 << getOpenMPClauseName(OMPC_linear); 9390 if (D) { 9391 bool IsDecl = 9392 !VD || 9393 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly; 9394 Diag(D->getLocation(), 9395 IsDecl ? diag::note_previous_decl : diag::note_defined_here) 9396 << D; 9397 } 9398 return true; 9399 } 9400 9401 // A list item must be of integral or pointer type. 9402 Type = Type.getUnqualifiedType().getCanonicalType(); 9403 const auto *Ty = Type.getTypePtrOrNull(); 9404 if (!Ty || (!Ty->isDependentType() && !Ty->isIntegralType(Context) && 9405 !Ty->isPointerType())) { 9406 Diag(ELoc, diag::err_omp_linear_expected_int_or_ptr) << Type; 9407 if (D) { 9408 bool IsDecl = 9409 !VD || 9410 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly; 9411 Diag(D->getLocation(), 9412 IsDecl ? diag::note_previous_decl : diag::note_defined_here) 9413 << D; 9414 } 9415 return true; 9416 } 9417 return false; 9418 } 9419 9420 OMPClause *Sema::ActOnOpenMPLinearClause( 9421 ArrayRef<Expr *> VarList, Expr *Step, SourceLocation StartLoc, 9422 SourceLocation LParenLoc, OpenMPLinearClauseKind LinKind, 9423 SourceLocation LinLoc, SourceLocation ColonLoc, SourceLocation EndLoc) { 9424 SmallVector<Expr *, 8> Vars; 9425 SmallVector<Expr *, 8> Privates; 9426 SmallVector<Expr *, 8> Inits; 9427 SmallVector<Decl *, 4> ExprCaptures; 9428 SmallVector<Expr *, 4> ExprPostUpdates; 9429 if (CheckOpenMPLinearModifier(LinKind, LinLoc)) 9430 LinKind = OMPC_LINEAR_val; 9431 for (auto &RefExpr : VarList) { 9432 assert(RefExpr && "NULL expr in OpenMP linear clause."); 9433 SourceLocation ELoc; 9434 SourceRange ERange; 9435 Expr *SimpleRefExpr = RefExpr; 9436 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange, 9437 /*AllowArraySection=*/false); 9438 if (Res.second) { 9439 // It will be analyzed later. 9440 Vars.push_back(RefExpr); 9441 Privates.push_back(nullptr); 9442 Inits.push_back(nullptr); 9443 } 9444 ValueDecl *D = Res.first; 9445 if (!D) 9446 continue; 9447 9448 QualType Type = D->getType(); 9449 auto *VD = dyn_cast<VarDecl>(D); 9450 9451 // OpenMP [2.14.3.7, linear clause] 9452 // A list-item cannot appear in more than one linear clause. 9453 // A list-item that appears in a linear clause cannot appear in any 9454 // other data-sharing attribute clause. 9455 DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, false); 9456 if (DVar.RefExpr) { 9457 Diag(ELoc, diag::err_omp_wrong_dsa) << getOpenMPClauseName(DVar.CKind) 9458 << getOpenMPClauseName(OMPC_linear); 9459 ReportOriginalDSA(*this, DSAStack, D, DVar); 9460 continue; 9461 } 9462 9463 if (CheckOpenMPLinearDecl(D, ELoc, LinKind, Type)) 9464 continue; 9465 Type = Type.getNonReferenceType().getUnqualifiedType().getCanonicalType(); 9466 9467 // Build private copy of original var. 9468 auto *Private = buildVarDecl(*this, ELoc, Type, D->getName(), 9469 D->hasAttrs() ? &D->getAttrs() : nullptr); 9470 auto *PrivateRef = buildDeclRefExpr(*this, Private, Type, ELoc); 9471 // Build var to save initial value. 9472 VarDecl *Init = buildVarDecl(*this, ELoc, Type, ".linear.start"); 9473 Expr *InitExpr; 9474 DeclRefExpr *Ref = nullptr; 9475 if (!VD) { 9476 Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/false); 9477 if (!IsOpenMPCapturedDecl(D)) { 9478 ExprCaptures.push_back(Ref->getDecl()); 9479 if (Ref->getDecl()->hasAttr<OMPCaptureNoInitAttr>()) { 9480 ExprResult RefRes = DefaultLvalueConversion(Ref); 9481 if (!RefRes.isUsable()) 9482 continue; 9483 ExprResult PostUpdateRes = 9484 BuildBinOp(DSAStack->getCurScope(), ELoc, BO_Assign, 9485 SimpleRefExpr, RefRes.get()); 9486 if (!PostUpdateRes.isUsable()) 9487 continue; 9488 ExprPostUpdates.push_back( 9489 IgnoredValueConversions(PostUpdateRes.get()).get()); 9490 } 9491 } 9492 } 9493 if (LinKind == OMPC_LINEAR_uval) 9494 InitExpr = VD ? VD->getInit() : SimpleRefExpr; 9495 else 9496 InitExpr = VD ? SimpleRefExpr : Ref; 9497 AddInitializerToDecl(Init, DefaultLvalueConversion(InitExpr).get(), 9498 /*DirectInit=*/false, /*TypeMayContainAuto=*/false); 9499 auto InitRef = buildDeclRefExpr(*this, Init, Type, ELoc); 9500 9501 DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_linear, Ref); 9502 Vars.push_back(VD ? RefExpr->IgnoreParens() : Ref); 9503 Privates.push_back(PrivateRef); 9504 Inits.push_back(InitRef); 9505 } 9506 9507 if (Vars.empty()) 9508 return nullptr; 9509 9510 Expr *StepExpr = Step; 9511 Expr *CalcStepExpr = nullptr; 9512 if (Step && !Step->isValueDependent() && !Step->isTypeDependent() && 9513 !Step->isInstantiationDependent() && 9514 !Step->containsUnexpandedParameterPack()) { 9515 SourceLocation StepLoc = Step->getLocStart(); 9516 ExprResult Val = PerformOpenMPImplicitIntegerConversion(StepLoc, Step); 9517 if (Val.isInvalid()) 9518 return nullptr; 9519 StepExpr = Val.get(); 9520 9521 // Build var to save the step value. 9522 VarDecl *SaveVar = 9523 buildVarDecl(*this, StepLoc, StepExpr->getType(), ".linear.step"); 9524 ExprResult SaveRef = 9525 buildDeclRefExpr(*this, SaveVar, StepExpr->getType(), StepLoc); 9526 ExprResult CalcStep = 9527 BuildBinOp(CurScope, StepLoc, BO_Assign, SaveRef.get(), StepExpr); 9528 CalcStep = ActOnFinishFullExpr(CalcStep.get()); 9529 9530 // Warn about zero linear step (it would be probably better specified as 9531 // making corresponding variables 'const'). 9532 llvm::APSInt Result; 9533 bool IsConstant = StepExpr->isIntegerConstantExpr(Result, Context); 9534 if (IsConstant && !Result.isNegative() && !Result.isStrictlyPositive()) 9535 Diag(StepLoc, diag::warn_omp_linear_step_zero) << Vars[0] 9536 << (Vars.size() > 1); 9537 if (!IsConstant && CalcStep.isUsable()) { 9538 // Calculate the step beforehand instead of doing this on each iteration. 9539 // (This is not used if the number of iterations may be kfold-ed). 9540 CalcStepExpr = CalcStep.get(); 9541 } 9542 } 9543 9544 return OMPLinearClause::Create(Context, StartLoc, LParenLoc, LinKind, LinLoc, 9545 ColonLoc, EndLoc, Vars, Privates, Inits, 9546 StepExpr, CalcStepExpr, 9547 buildPreInits(Context, ExprCaptures), 9548 buildPostUpdate(*this, ExprPostUpdates)); 9549 } 9550 9551 static bool FinishOpenMPLinearClause(OMPLinearClause &Clause, DeclRefExpr *IV, 9552 Expr *NumIterations, Sema &SemaRef, 9553 Scope *S, DSAStackTy *Stack) { 9554 // Walk the vars and build update/final expressions for the CodeGen. 9555 SmallVector<Expr *, 8> Updates; 9556 SmallVector<Expr *, 8> Finals; 9557 Expr *Step = Clause.getStep(); 9558 Expr *CalcStep = Clause.getCalcStep(); 9559 // OpenMP [2.14.3.7, linear clause] 9560 // If linear-step is not specified it is assumed to be 1. 9561 if (Step == nullptr) 9562 Step = SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get(); 9563 else if (CalcStep) { 9564 Step = cast<BinaryOperator>(CalcStep)->getLHS(); 9565 } 9566 bool HasErrors = false; 9567 auto CurInit = Clause.inits().begin(); 9568 auto CurPrivate = Clause.privates().begin(); 9569 auto LinKind = Clause.getModifier(); 9570 for (auto &RefExpr : Clause.varlists()) { 9571 SourceLocation ELoc; 9572 SourceRange ERange; 9573 Expr *SimpleRefExpr = RefExpr; 9574 auto Res = getPrivateItem(SemaRef, SimpleRefExpr, ELoc, ERange, 9575 /*AllowArraySection=*/false); 9576 ValueDecl *D = Res.first; 9577 if (Res.second || !D) { 9578 Updates.push_back(nullptr); 9579 Finals.push_back(nullptr); 9580 HasErrors = true; 9581 continue; 9582 } 9583 if (auto *CED = dyn_cast<OMPCapturedExprDecl>(D)) { 9584 D = cast<MemberExpr>(CED->getInit()->IgnoreParenImpCasts()) 9585 ->getMemberDecl(); 9586 } 9587 auto &&Info = Stack->isLoopControlVariable(D); 9588 Expr *InitExpr = *CurInit; 9589 9590 // Build privatized reference to the current linear var. 9591 auto DE = cast<DeclRefExpr>(SimpleRefExpr); 9592 Expr *CapturedRef; 9593 if (LinKind == OMPC_LINEAR_uval) 9594 CapturedRef = cast<VarDecl>(DE->getDecl())->getInit(); 9595 else 9596 CapturedRef = 9597 buildDeclRefExpr(SemaRef, cast<VarDecl>(DE->getDecl()), 9598 DE->getType().getUnqualifiedType(), DE->getExprLoc(), 9599 /*RefersToCapture=*/true); 9600 9601 // Build update: Var = InitExpr + IV * Step 9602 ExprResult Update; 9603 if (!Info.first) { 9604 Update = 9605 BuildCounterUpdate(SemaRef, S, RefExpr->getExprLoc(), *CurPrivate, 9606 InitExpr, IV, Step, /* Subtract */ false); 9607 } else 9608 Update = *CurPrivate; 9609 Update = SemaRef.ActOnFinishFullExpr(Update.get(), DE->getLocStart(), 9610 /*DiscardedValue=*/true); 9611 9612 // Build final: Var = InitExpr + NumIterations * Step 9613 ExprResult Final; 9614 if (!Info.first) { 9615 Final = BuildCounterUpdate(SemaRef, S, RefExpr->getExprLoc(), CapturedRef, 9616 InitExpr, NumIterations, Step, 9617 /* Subtract */ false); 9618 } else 9619 Final = *CurPrivate; 9620 Final = SemaRef.ActOnFinishFullExpr(Final.get(), DE->getLocStart(), 9621 /*DiscardedValue=*/true); 9622 9623 if (!Update.isUsable() || !Final.isUsable()) { 9624 Updates.push_back(nullptr); 9625 Finals.push_back(nullptr); 9626 HasErrors = true; 9627 } else { 9628 Updates.push_back(Update.get()); 9629 Finals.push_back(Final.get()); 9630 } 9631 ++CurInit; 9632 ++CurPrivate; 9633 } 9634 Clause.setUpdates(Updates); 9635 Clause.setFinals(Finals); 9636 return HasErrors; 9637 } 9638 9639 OMPClause *Sema::ActOnOpenMPAlignedClause( 9640 ArrayRef<Expr *> VarList, Expr *Alignment, SourceLocation StartLoc, 9641 SourceLocation LParenLoc, SourceLocation ColonLoc, SourceLocation EndLoc) { 9642 9643 SmallVector<Expr *, 8> Vars; 9644 for (auto &RefExpr : VarList) { 9645 assert(RefExpr && "NULL expr in OpenMP linear clause."); 9646 SourceLocation ELoc; 9647 SourceRange ERange; 9648 Expr *SimpleRefExpr = RefExpr; 9649 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange, 9650 /*AllowArraySection=*/false); 9651 if (Res.second) { 9652 // It will be analyzed later. 9653 Vars.push_back(RefExpr); 9654 } 9655 ValueDecl *D = Res.first; 9656 if (!D) 9657 continue; 9658 9659 QualType QType = D->getType(); 9660 auto *VD = dyn_cast<VarDecl>(D); 9661 9662 // OpenMP [2.8.1, simd construct, Restrictions] 9663 // The type of list items appearing in the aligned clause must be 9664 // array, pointer, reference to array, or reference to pointer. 9665 QType = QType.getNonReferenceType().getUnqualifiedType().getCanonicalType(); 9666 const Type *Ty = QType.getTypePtrOrNull(); 9667 if (!Ty || (!Ty->isArrayType() && !Ty->isPointerType())) { 9668 Diag(ELoc, diag::err_omp_aligned_expected_array_or_ptr) 9669 << QType << getLangOpts().CPlusPlus << ERange; 9670 bool IsDecl = 9671 !VD || 9672 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly; 9673 Diag(D->getLocation(), 9674 IsDecl ? diag::note_previous_decl : diag::note_defined_here) 9675 << D; 9676 continue; 9677 } 9678 9679 // OpenMP [2.8.1, simd construct, Restrictions] 9680 // A list-item cannot appear in more than one aligned clause. 9681 if (Expr *PrevRef = DSAStack->addUniqueAligned(D, SimpleRefExpr)) { 9682 Diag(ELoc, diag::err_omp_aligned_twice) << 0 << ERange; 9683 Diag(PrevRef->getExprLoc(), diag::note_omp_explicit_dsa) 9684 << getOpenMPClauseName(OMPC_aligned); 9685 continue; 9686 } 9687 9688 DeclRefExpr *Ref = nullptr; 9689 if (!VD && IsOpenMPCapturedDecl(D)) 9690 Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/true); 9691 Vars.push_back(DefaultFunctionArrayConversion( 9692 (VD || !Ref) ? RefExpr->IgnoreParens() : Ref) 9693 .get()); 9694 } 9695 9696 // OpenMP [2.8.1, simd construct, Description] 9697 // The parameter of the aligned clause, alignment, must be a constant 9698 // positive integer expression. 9699 // If no optional parameter is specified, implementation-defined default 9700 // alignments for SIMD instructions on the target platforms are assumed. 9701 if (Alignment != nullptr) { 9702 ExprResult AlignResult = 9703 VerifyPositiveIntegerConstantInClause(Alignment, OMPC_aligned); 9704 if (AlignResult.isInvalid()) 9705 return nullptr; 9706 Alignment = AlignResult.get(); 9707 } 9708 if (Vars.empty()) 9709 return nullptr; 9710 9711 return OMPAlignedClause::Create(Context, StartLoc, LParenLoc, ColonLoc, 9712 EndLoc, Vars, Alignment); 9713 } 9714 9715 OMPClause *Sema::ActOnOpenMPCopyinClause(ArrayRef<Expr *> VarList, 9716 SourceLocation StartLoc, 9717 SourceLocation LParenLoc, 9718 SourceLocation EndLoc) { 9719 SmallVector<Expr *, 8> Vars; 9720 SmallVector<Expr *, 8> SrcExprs; 9721 SmallVector<Expr *, 8> DstExprs; 9722 SmallVector<Expr *, 8> AssignmentOps; 9723 for (auto &RefExpr : VarList) { 9724 assert(RefExpr && "NULL expr in OpenMP copyin clause."); 9725 if (isa<DependentScopeDeclRefExpr>(RefExpr)) { 9726 // It will be analyzed later. 9727 Vars.push_back(RefExpr); 9728 SrcExprs.push_back(nullptr); 9729 DstExprs.push_back(nullptr); 9730 AssignmentOps.push_back(nullptr); 9731 continue; 9732 } 9733 9734 SourceLocation ELoc = RefExpr->getExprLoc(); 9735 // OpenMP [2.1, C/C++] 9736 // A list item is a variable name. 9737 // OpenMP [2.14.4.1, Restrictions, p.1] 9738 // A list item that appears in a copyin clause must be threadprivate. 9739 DeclRefExpr *DE = dyn_cast<DeclRefExpr>(RefExpr); 9740 if (!DE || !isa<VarDecl>(DE->getDecl())) { 9741 Diag(ELoc, diag::err_omp_expected_var_name_member_expr) 9742 << 0 << RefExpr->getSourceRange(); 9743 continue; 9744 } 9745 9746 Decl *D = DE->getDecl(); 9747 VarDecl *VD = cast<VarDecl>(D); 9748 9749 QualType Type = VD->getType(); 9750 if (Type->isDependentType() || Type->isInstantiationDependentType()) { 9751 // It will be analyzed later. 9752 Vars.push_back(DE); 9753 SrcExprs.push_back(nullptr); 9754 DstExprs.push_back(nullptr); 9755 AssignmentOps.push_back(nullptr); 9756 continue; 9757 } 9758 9759 // OpenMP [2.14.4.1, Restrictions, C/C++, p.1] 9760 // A list item that appears in a copyin clause must be threadprivate. 9761 if (!DSAStack->isThreadPrivate(VD)) { 9762 Diag(ELoc, diag::err_omp_required_access) 9763 << getOpenMPClauseName(OMPC_copyin) 9764 << getOpenMPDirectiveName(OMPD_threadprivate); 9765 continue; 9766 } 9767 9768 // OpenMP [2.14.4.1, Restrictions, C/C++, p.2] 9769 // A variable of class type (or array thereof) that appears in a 9770 // copyin clause requires an accessible, unambiguous copy assignment 9771 // operator for the class type. 9772 auto ElemType = Context.getBaseElementType(Type).getNonReferenceType(); 9773 auto *SrcVD = 9774 buildVarDecl(*this, DE->getLocStart(), ElemType.getUnqualifiedType(), 9775 ".copyin.src", VD->hasAttrs() ? &VD->getAttrs() : nullptr); 9776 auto *PseudoSrcExpr = buildDeclRefExpr( 9777 *this, SrcVD, ElemType.getUnqualifiedType(), DE->getExprLoc()); 9778 auto *DstVD = 9779 buildVarDecl(*this, DE->getLocStart(), ElemType, ".copyin.dst", 9780 VD->hasAttrs() ? &VD->getAttrs() : nullptr); 9781 auto *PseudoDstExpr = 9782 buildDeclRefExpr(*this, DstVD, ElemType, DE->getExprLoc()); 9783 // For arrays generate assignment operation for single element and replace 9784 // it by the original array element in CodeGen. 9785 auto AssignmentOp = BuildBinOp(/*S=*/nullptr, DE->getExprLoc(), BO_Assign, 9786 PseudoDstExpr, PseudoSrcExpr); 9787 if (AssignmentOp.isInvalid()) 9788 continue; 9789 AssignmentOp = ActOnFinishFullExpr(AssignmentOp.get(), DE->getExprLoc(), 9790 /*DiscardedValue=*/true); 9791 if (AssignmentOp.isInvalid()) 9792 continue; 9793 9794 DSAStack->addDSA(VD, DE, OMPC_copyin); 9795 Vars.push_back(DE); 9796 SrcExprs.push_back(PseudoSrcExpr); 9797 DstExprs.push_back(PseudoDstExpr); 9798 AssignmentOps.push_back(AssignmentOp.get()); 9799 } 9800 9801 if (Vars.empty()) 9802 return nullptr; 9803 9804 return OMPCopyinClause::Create(Context, StartLoc, LParenLoc, EndLoc, Vars, 9805 SrcExprs, DstExprs, AssignmentOps); 9806 } 9807 9808 OMPClause *Sema::ActOnOpenMPCopyprivateClause(ArrayRef<Expr *> VarList, 9809 SourceLocation StartLoc, 9810 SourceLocation LParenLoc, 9811 SourceLocation EndLoc) { 9812 SmallVector<Expr *, 8> Vars; 9813 SmallVector<Expr *, 8> SrcExprs; 9814 SmallVector<Expr *, 8> DstExprs; 9815 SmallVector<Expr *, 8> AssignmentOps; 9816 for (auto &RefExpr : VarList) { 9817 assert(RefExpr && "NULL expr in OpenMP linear clause."); 9818 SourceLocation ELoc; 9819 SourceRange ERange; 9820 Expr *SimpleRefExpr = RefExpr; 9821 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange, 9822 /*AllowArraySection=*/false); 9823 if (Res.second) { 9824 // It will be analyzed later. 9825 Vars.push_back(RefExpr); 9826 SrcExprs.push_back(nullptr); 9827 DstExprs.push_back(nullptr); 9828 AssignmentOps.push_back(nullptr); 9829 } 9830 ValueDecl *D = Res.first; 9831 if (!D) 9832 continue; 9833 9834 QualType Type = D->getType(); 9835 auto *VD = dyn_cast<VarDecl>(D); 9836 9837 // OpenMP [2.14.4.2, Restrictions, p.2] 9838 // A list item that appears in a copyprivate clause may not appear in a 9839 // private or firstprivate clause on the single construct. 9840 if (!VD || !DSAStack->isThreadPrivate(VD)) { 9841 auto DVar = DSAStack->getTopDSA(D, false); 9842 if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_copyprivate && 9843 DVar.RefExpr) { 9844 Diag(ELoc, diag::err_omp_wrong_dsa) 9845 << getOpenMPClauseName(DVar.CKind) 9846 << getOpenMPClauseName(OMPC_copyprivate); 9847 ReportOriginalDSA(*this, DSAStack, D, DVar); 9848 continue; 9849 } 9850 9851 // OpenMP [2.11.4.2, Restrictions, p.1] 9852 // All list items that appear in a copyprivate clause must be either 9853 // threadprivate or private in the enclosing context. 9854 if (DVar.CKind == OMPC_unknown) { 9855 DVar = DSAStack->getImplicitDSA(D, false); 9856 if (DVar.CKind == OMPC_shared) { 9857 Diag(ELoc, diag::err_omp_required_access) 9858 << getOpenMPClauseName(OMPC_copyprivate) 9859 << "threadprivate or private in the enclosing context"; 9860 ReportOriginalDSA(*this, DSAStack, D, DVar); 9861 continue; 9862 } 9863 } 9864 } 9865 9866 // Variably modified types are not supported. 9867 if (!Type->isAnyPointerType() && Type->isVariablyModifiedType()) { 9868 Diag(ELoc, diag::err_omp_variably_modified_type_not_supported) 9869 << getOpenMPClauseName(OMPC_copyprivate) << Type 9870 << getOpenMPDirectiveName(DSAStack->getCurrentDirective()); 9871 bool IsDecl = 9872 !VD || 9873 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly; 9874 Diag(D->getLocation(), 9875 IsDecl ? diag::note_previous_decl : diag::note_defined_here) 9876 << D; 9877 continue; 9878 } 9879 9880 // OpenMP [2.14.4.1, Restrictions, C/C++, p.2] 9881 // A variable of class type (or array thereof) that appears in a 9882 // copyin clause requires an accessible, unambiguous copy assignment 9883 // operator for the class type. 9884 Type = Context.getBaseElementType(Type.getNonReferenceType()) 9885 .getUnqualifiedType(); 9886 auto *SrcVD = 9887 buildVarDecl(*this, RefExpr->getLocStart(), Type, ".copyprivate.src", 9888 D->hasAttrs() ? &D->getAttrs() : nullptr); 9889 auto *PseudoSrcExpr = buildDeclRefExpr(*this, SrcVD, Type, ELoc); 9890 auto *DstVD = 9891 buildVarDecl(*this, RefExpr->getLocStart(), Type, ".copyprivate.dst", 9892 D->hasAttrs() ? &D->getAttrs() : nullptr); 9893 auto *PseudoDstExpr = 9894 buildDeclRefExpr(*this, DstVD, Type, ELoc); 9895 auto AssignmentOp = BuildBinOp(DSAStack->getCurScope(), ELoc, BO_Assign, 9896 PseudoDstExpr, PseudoSrcExpr); 9897 if (AssignmentOp.isInvalid()) 9898 continue; 9899 AssignmentOp = ActOnFinishFullExpr(AssignmentOp.get(), ELoc, 9900 /*DiscardedValue=*/true); 9901 if (AssignmentOp.isInvalid()) 9902 continue; 9903 9904 // No need to mark vars as copyprivate, they are already threadprivate or 9905 // implicitly private. 9906 assert(VD || IsOpenMPCapturedDecl(D)); 9907 Vars.push_back( 9908 VD ? RefExpr->IgnoreParens() 9909 : buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/false)); 9910 SrcExprs.push_back(PseudoSrcExpr); 9911 DstExprs.push_back(PseudoDstExpr); 9912 AssignmentOps.push_back(AssignmentOp.get()); 9913 } 9914 9915 if (Vars.empty()) 9916 return nullptr; 9917 9918 return OMPCopyprivateClause::Create(Context, StartLoc, LParenLoc, EndLoc, 9919 Vars, SrcExprs, DstExprs, AssignmentOps); 9920 } 9921 9922 OMPClause *Sema::ActOnOpenMPFlushClause(ArrayRef<Expr *> VarList, 9923 SourceLocation StartLoc, 9924 SourceLocation LParenLoc, 9925 SourceLocation EndLoc) { 9926 if (VarList.empty()) 9927 return nullptr; 9928 9929 return OMPFlushClause::Create(Context, StartLoc, LParenLoc, EndLoc, VarList); 9930 } 9931 9932 OMPClause * 9933 Sema::ActOnOpenMPDependClause(OpenMPDependClauseKind DepKind, 9934 SourceLocation DepLoc, SourceLocation ColonLoc, 9935 ArrayRef<Expr *> VarList, SourceLocation StartLoc, 9936 SourceLocation LParenLoc, SourceLocation EndLoc) { 9937 if (DSAStack->getCurrentDirective() == OMPD_ordered && 9938 DepKind != OMPC_DEPEND_source && DepKind != OMPC_DEPEND_sink) { 9939 Diag(DepLoc, diag::err_omp_unexpected_clause_value) 9940 << "'source' or 'sink'" << getOpenMPClauseName(OMPC_depend); 9941 return nullptr; 9942 } 9943 if (DSAStack->getCurrentDirective() != OMPD_ordered && 9944 (DepKind == OMPC_DEPEND_unknown || DepKind == OMPC_DEPEND_source || 9945 DepKind == OMPC_DEPEND_sink)) { 9946 unsigned Except[] = {OMPC_DEPEND_source, OMPC_DEPEND_sink}; 9947 Diag(DepLoc, diag::err_omp_unexpected_clause_value) 9948 << getListOfPossibleValues(OMPC_depend, /*First=*/0, 9949 /*Last=*/OMPC_DEPEND_unknown, Except) 9950 << getOpenMPClauseName(OMPC_depend); 9951 return nullptr; 9952 } 9953 SmallVector<Expr *, 8> Vars; 9954 DSAStackTy::OperatorOffsetTy OpsOffs; 9955 llvm::APSInt DepCounter(/*BitWidth=*/32); 9956 llvm::APSInt TotalDepCount(/*BitWidth=*/32); 9957 if (DepKind == OMPC_DEPEND_sink) { 9958 if (auto *OrderedCountExpr = DSAStack->getParentOrderedRegionParam()) { 9959 TotalDepCount = OrderedCountExpr->EvaluateKnownConstInt(Context); 9960 TotalDepCount.setIsUnsigned(/*Val=*/true); 9961 } 9962 } 9963 if ((DepKind != OMPC_DEPEND_sink && DepKind != OMPC_DEPEND_source) || 9964 DSAStack->getParentOrderedRegionParam()) { 9965 for (auto &RefExpr : VarList) { 9966 assert(RefExpr && "NULL expr in OpenMP shared clause."); 9967 if (isa<DependentScopeDeclRefExpr>(RefExpr)) { 9968 // It will be analyzed later. 9969 Vars.push_back(RefExpr); 9970 continue; 9971 } 9972 9973 SourceLocation ELoc = RefExpr->getExprLoc(); 9974 auto *SimpleExpr = RefExpr->IgnoreParenCasts(); 9975 if (DepKind == OMPC_DEPEND_sink) { 9976 if (DepCounter >= TotalDepCount) { 9977 Diag(ELoc, diag::err_omp_depend_sink_unexpected_expr); 9978 continue; 9979 } 9980 ++DepCounter; 9981 // OpenMP [2.13.9, Summary] 9982 // depend(dependence-type : vec), where dependence-type is: 9983 // 'sink' and where vec is the iteration vector, which has the form: 9984 // x1 [+- d1], x2 [+- d2 ], . . . , xn [+- dn] 9985 // where n is the value specified by the ordered clause in the loop 9986 // directive, xi denotes the loop iteration variable of the i-th nested 9987 // loop associated with the loop directive, and di is a constant 9988 // non-negative integer. 9989 if (CurContext->isDependentContext()) { 9990 // It will be analyzed later. 9991 Vars.push_back(RefExpr); 9992 continue; 9993 } 9994 SimpleExpr = SimpleExpr->IgnoreImplicit(); 9995 OverloadedOperatorKind OOK = OO_None; 9996 SourceLocation OOLoc; 9997 Expr *LHS = SimpleExpr; 9998 Expr *RHS = nullptr; 9999 if (auto *BO = dyn_cast<BinaryOperator>(SimpleExpr)) { 10000 OOK = BinaryOperator::getOverloadedOperator(BO->getOpcode()); 10001 OOLoc = BO->getOperatorLoc(); 10002 LHS = BO->getLHS()->IgnoreParenImpCasts(); 10003 RHS = BO->getRHS()->IgnoreParenImpCasts(); 10004 } else if (auto *OCE = dyn_cast<CXXOperatorCallExpr>(SimpleExpr)) { 10005 OOK = OCE->getOperator(); 10006 OOLoc = OCE->getOperatorLoc(); 10007 LHS = OCE->getArg(/*Arg=*/0)->IgnoreParenImpCasts(); 10008 RHS = OCE->getArg(/*Arg=*/1)->IgnoreParenImpCasts(); 10009 } else if (auto *MCE = dyn_cast<CXXMemberCallExpr>(SimpleExpr)) { 10010 OOK = MCE->getMethodDecl() 10011 ->getNameInfo() 10012 .getName() 10013 .getCXXOverloadedOperator(); 10014 OOLoc = MCE->getCallee()->getExprLoc(); 10015 LHS = MCE->getImplicitObjectArgument()->IgnoreParenImpCasts(); 10016 RHS = MCE->getArg(/*Arg=*/0)->IgnoreParenImpCasts(); 10017 } 10018 SourceLocation ELoc; 10019 SourceRange ERange; 10020 auto Res = getPrivateItem(*this, LHS, ELoc, ERange, 10021 /*AllowArraySection=*/false); 10022 if (Res.second) { 10023 // It will be analyzed later. 10024 Vars.push_back(RefExpr); 10025 } 10026 ValueDecl *D = Res.first; 10027 if (!D) 10028 continue; 10029 10030 if (OOK != OO_Plus && OOK != OO_Minus && (RHS || OOK != OO_None)) { 10031 Diag(OOLoc, diag::err_omp_depend_sink_expected_plus_minus); 10032 continue; 10033 } 10034 if (RHS) { 10035 ExprResult RHSRes = VerifyPositiveIntegerConstantInClause( 10036 RHS, OMPC_depend, /*StrictlyPositive=*/false); 10037 if (RHSRes.isInvalid()) 10038 continue; 10039 } 10040 if (!CurContext->isDependentContext() && 10041 DSAStack->getParentOrderedRegionParam() && 10042 DepCounter != DSAStack->isParentLoopControlVariable(D).first) { 10043 Diag(ELoc, diag::err_omp_depend_sink_expected_loop_iteration) 10044 << DSAStack->getParentLoopControlVariable( 10045 DepCounter.getZExtValue()); 10046 continue; 10047 } 10048 OpsOffs.push_back({RHS, OOK}); 10049 } else { 10050 // OpenMP [2.11.1.1, Restrictions, p.3] 10051 // A variable that is part of another variable (such as a field of a 10052 // structure) but is not an array element or an array section cannot 10053 // appear in a depend clause. 10054 auto *DE = dyn_cast<DeclRefExpr>(SimpleExpr); 10055 auto *ASE = dyn_cast<ArraySubscriptExpr>(SimpleExpr); 10056 auto *OASE = dyn_cast<OMPArraySectionExpr>(SimpleExpr); 10057 if (!RefExpr->IgnoreParenImpCasts()->isLValue() || 10058 (!ASE && !DE && !OASE) || (DE && !isa<VarDecl>(DE->getDecl())) || 10059 (ASE && 10060 !ASE->getBase() 10061 ->getType() 10062 .getNonReferenceType() 10063 ->isPointerType() && 10064 !ASE->getBase()->getType().getNonReferenceType()->isArrayType())) { 10065 Diag(ELoc, diag::err_omp_expected_var_name_member_expr_or_array_item) 10066 << 0 << RefExpr->getSourceRange(); 10067 continue; 10068 } 10069 } 10070 Vars.push_back(RefExpr->IgnoreParenImpCasts()); 10071 } 10072 10073 if (!CurContext->isDependentContext() && DepKind == OMPC_DEPEND_sink && 10074 TotalDepCount > VarList.size() && 10075 DSAStack->getParentOrderedRegionParam()) { 10076 Diag(EndLoc, diag::err_omp_depend_sink_expected_loop_iteration) 10077 << DSAStack->getParentLoopControlVariable(VarList.size() + 1); 10078 } 10079 if (DepKind != OMPC_DEPEND_source && DepKind != OMPC_DEPEND_sink && 10080 Vars.empty()) 10081 return nullptr; 10082 } 10083 auto *C = OMPDependClause::Create(Context, StartLoc, LParenLoc, EndLoc, 10084 DepKind, DepLoc, ColonLoc, Vars); 10085 if (DepKind == OMPC_DEPEND_sink || DepKind == OMPC_DEPEND_source) 10086 DSAStack->addDoacrossDependClause(C, OpsOffs); 10087 return C; 10088 } 10089 10090 OMPClause *Sema::ActOnOpenMPDeviceClause(Expr *Device, SourceLocation StartLoc, 10091 SourceLocation LParenLoc, 10092 SourceLocation EndLoc) { 10093 Expr *ValExpr = Device; 10094 10095 // OpenMP [2.9.1, Restrictions] 10096 // The device expression must evaluate to a non-negative integer value. 10097 if (!IsNonNegativeIntegerValue(ValExpr, *this, OMPC_device, 10098 /*StrictlyPositive=*/false)) 10099 return nullptr; 10100 10101 return new (Context) OMPDeviceClause(ValExpr, StartLoc, LParenLoc, EndLoc); 10102 } 10103 10104 static bool IsCXXRecordForMappable(Sema &SemaRef, SourceLocation Loc, 10105 DSAStackTy *Stack, CXXRecordDecl *RD) { 10106 if (!RD || RD->isInvalidDecl()) 10107 return true; 10108 10109 if (auto *CTSD = dyn_cast<ClassTemplateSpecializationDecl>(RD)) 10110 if (auto *CTD = CTSD->getSpecializedTemplate()) 10111 RD = CTD->getTemplatedDecl(); 10112 auto QTy = SemaRef.Context.getRecordType(RD); 10113 if (RD->isDynamicClass()) { 10114 SemaRef.Diag(Loc, diag::err_omp_not_mappable_type) << QTy; 10115 SemaRef.Diag(RD->getLocation(), diag::note_omp_polymorphic_in_target); 10116 return false; 10117 } 10118 auto *DC = RD; 10119 bool IsCorrect = true; 10120 for (auto *I : DC->decls()) { 10121 if (I) { 10122 if (auto *MD = dyn_cast<CXXMethodDecl>(I)) { 10123 if (MD->isStatic()) { 10124 SemaRef.Diag(Loc, diag::err_omp_not_mappable_type) << QTy; 10125 SemaRef.Diag(MD->getLocation(), 10126 diag::note_omp_static_member_in_target); 10127 IsCorrect = false; 10128 } 10129 } else if (auto *VD = dyn_cast<VarDecl>(I)) { 10130 if (VD->isStaticDataMember()) { 10131 SemaRef.Diag(Loc, diag::err_omp_not_mappable_type) << QTy; 10132 SemaRef.Diag(VD->getLocation(), 10133 diag::note_omp_static_member_in_target); 10134 IsCorrect = false; 10135 } 10136 } 10137 } 10138 } 10139 10140 for (auto &I : RD->bases()) { 10141 if (!IsCXXRecordForMappable(SemaRef, I.getLocStart(), Stack, 10142 I.getType()->getAsCXXRecordDecl())) 10143 IsCorrect = false; 10144 } 10145 return IsCorrect; 10146 } 10147 10148 static bool CheckTypeMappable(SourceLocation SL, SourceRange SR, Sema &SemaRef, 10149 DSAStackTy *Stack, QualType QTy) { 10150 NamedDecl *ND; 10151 if (QTy->isIncompleteType(&ND)) { 10152 SemaRef.Diag(SL, diag::err_incomplete_type) << QTy << SR; 10153 return false; 10154 } else if (CXXRecordDecl *RD = dyn_cast_or_null<CXXRecordDecl>(ND)) { 10155 if (!RD->isInvalidDecl() && 10156 !IsCXXRecordForMappable(SemaRef, SL, Stack, RD)) 10157 return false; 10158 } 10159 return true; 10160 } 10161 10162 /// \brief Return true if it can be proven that the provided array expression 10163 /// (array section or array subscript) does NOT specify the whole size of the 10164 /// array whose base type is \a BaseQTy. 10165 static bool CheckArrayExpressionDoesNotReferToWholeSize(Sema &SemaRef, 10166 const Expr *E, 10167 QualType BaseQTy) { 10168 auto *OASE = dyn_cast<OMPArraySectionExpr>(E); 10169 10170 // If this is an array subscript, it refers to the whole size if the size of 10171 // the dimension is constant and equals 1. Also, an array section assumes the 10172 // format of an array subscript if no colon is used. 10173 if (isa<ArraySubscriptExpr>(E) || (OASE && OASE->getColonLoc().isInvalid())) { 10174 if (auto *ATy = dyn_cast<ConstantArrayType>(BaseQTy.getTypePtr())) 10175 return ATy->getSize().getSExtValue() != 1; 10176 // Size can't be evaluated statically. 10177 return false; 10178 } 10179 10180 assert(OASE && "Expecting array section if not an array subscript."); 10181 auto *LowerBound = OASE->getLowerBound(); 10182 auto *Length = OASE->getLength(); 10183 10184 // If there is a lower bound that does not evaluates to zero, we are not 10185 // convering the whole dimension. 10186 if (LowerBound) { 10187 llvm::APSInt ConstLowerBound; 10188 if (!LowerBound->EvaluateAsInt(ConstLowerBound, SemaRef.getASTContext())) 10189 return false; // Can't get the integer value as a constant. 10190 if (ConstLowerBound.getSExtValue()) 10191 return true; 10192 } 10193 10194 // If we don't have a length we covering the whole dimension. 10195 if (!Length) 10196 return false; 10197 10198 // If the base is a pointer, we don't have a way to get the size of the 10199 // pointee. 10200 if (BaseQTy->isPointerType()) 10201 return false; 10202 10203 // We can only check if the length is the same as the size of the dimension 10204 // if we have a constant array. 10205 auto *CATy = dyn_cast<ConstantArrayType>(BaseQTy.getTypePtr()); 10206 if (!CATy) 10207 return false; 10208 10209 llvm::APSInt ConstLength; 10210 if (!Length->EvaluateAsInt(ConstLength, SemaRef.getASTContext())) 10211 return false; // Can't get the integer value as a constant. 10212 10213 return CATy->getSize().getSExtValue() != ConstLength.getSExtValue(); 10214 } 10215 10216 // Return true if it can be proven that the provided array expression (array 10217 // section or array subscript) does NOT specify a single element of the array 10218 // whose base type is \a BaseQTy. 10219 static bool CheckArrayExpressionDoesNotReferToUnitySize(Sema &SemaRef, 10220 const Expr *E, 10221 QualType BaseQTy) { 10222 auto *OASE = dyn_cast<OMPArraySectionExpr>(E); 10223 10224 // An array subscript always refer to a single element. Also, an array section 10225 // assumes the format of an array subscript if no colon is used. 10226 if (isa<ArraySubscriptExpr>(E) || (OASE && OASE->getColonLoc().isInvalid())) 10227 return false; 10228 10229 assert(OASE && "Expecting array section if not an array subscript."); 10230 auto *Length = OASE->getLength(); 10231 10232 // If we don't have a length we have to check if the array has unitary size 10233 // for this dimension. Also, we should always expect a length if the base type 10234 // is pointer. 10235 if (!Length) { 10236 if (auto *ATy = dyn_cast<ConstantArrayType>(BaseQTy.getTypePtr())) 10237 return ATy->getSize().getSExtValue() != 1; 10238 // We cannot assume anything. 10239 return false; 10240 } 10241 10242 // Check if the length evaluates to 1. 10243 llvm::APSInt ConstLength; 10244 if (!Length->EvaluateAsInt(ConstLength, SemaRef.getASTContext())) 10245 return false; // Can't get the integer value as a constant. 10246 10247 return ConstLength.getSExtValue() != 1; 10248 } 10249 10250 // Return the expression of the base of the mappable expression or null if it 10251 // cannot be determined and do all the necessary checks to see if the expression 10252 // is valid as a standalone mappable expression. In the process, record all the 10253 // components of the expression. 10254 static Expr *CheckMapClauseExpressionBase( 10255 Sema &SemaRef, Expr *E, 10256 OMPClauseMappableExprCommon::MappableExprComponentList &CurComponents, 10257 OpenMPClauseKind CKind) { 10258 SourceLocation ELoc = E->getExprLoc(); 10259 SourceRange ERange = E->getSourceRange(); 10260 10261 // The base of elements of list in a map clause have to be either: 10262 // - a reference to variable or field. 10263 // - a member expression. 10264 // - an array expression. 10265 // 10266 // E.g. if we have the expression 'r.S.Arr[:12]', we want to retrieve the 10267 // reference to 'r'. 10268 // 10269 // If we have: 10270 // 10271 // struct SS { 10272 // Bla S; 10273 // foo() { 10274 // #pragma omp target map (S.Arr[:12]); 10275 // } 10276 // } 10277 // 10278 // We want to retrieve the member expression 'this->S'; 10279 10280 Expr *RelevantExpr = nullptr; 10281 10282 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.2] 10283 // If a list item is an array section, it must specify contiguous storage. 10284 // 10285 // For this restriction it is sufficient that we make sure only references 10286 // to variables or fields and array expressions, and that no array sections 10287 // exist except in the rightmost expression (unless they cover the whole 10288 // dimension of the array). E.g. these would be invalid: 10289 // 10290 // r.ArrS[3:5].Arr[6:7] 10291 // 10292 // r.ArrS[3:5].x 10293 // 10294 // but these would be valid: 10295 // r.ArrS[3].Arr[6:7] 10296 // 10297 // r.ArrS[3].x 10298 10299 bool AllowUnitySizeArraySection = true; 10300 bool AllowWholeSizeArraySection = true; 10301 10302 while (!RelevantExpr) { 10303 E = E->IgnoreParenImpCasts(); 10304 10305 if (auto *CurE = dyn_cast<DeclRefExpr>(E)) { 10306 if (!isa<VarDecl>(CurE->getDecl())) 10307 break; 10308 10309 RelevantExpr = CurE; 10310 10311 // If we got a reference to a declaration, we should not expect any array 10312 // section before that. 10313 AllowUnitySizeArraySection = false; 10314 AllowWholeSizeArraySection = false; 10315 10316 // Record the component. 10317 CurComponents.push_back(OMPClauseMappableExprCommon::MappableComponent( 10318 CurE, CurE->getDecl())); 10319 continue; 10320 } 10321 10322 if (auto *CurE = dyn_cast<MemberExpr>(E)) { 10323 auto *BaseE = CurE->getBase()->IgnoreParenImpCasts(); 10324 10325 if (isa<CXXThisExpr>(BaseE)) 10326 // We found a base expression: this->Val. 10327 RelevantExpr = CurE; 10328 else 10329 E = BaseE; 10330 10331 if (!isa<FieldDecl>(CurE->getMemberDecl())) { 10332 SemaRef.Diag(ELoc, diag::err_omp_expected_access_to_data_field) 10333 << CurE->getSourceRange(); 10334 break; 10335 } 10336 10337 auto *FD = cast<FieldDecl>(CurE->getMemberDecl()); 10338 10339 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C/C++, p.3] 10340 // A bit-field cannot appear in a map clause. 10341 // 10342 if (FD->isBitField()) { 10343 SemaRef.Diag(ELoc, diag::err_omp_bit_fields_forbidden_in_clause) 10344 << CurE->getSourceRange() << getOpenMPClauseName(CKind); 10345 break; 10346 } 10347 10348 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C++, p.1] 10349 // If the type of a list item is a reference to a type T then the type 10350 // will be considered to be T for all purposes of this clause. 10351 QualType CurType = BaseE->getType().getNonReferenceType(); 10352 10353 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C/C++, p.2] 10354 // A list item cannot be a variable that is a member of a structure with 10355 // a union type. 10356 // 10357 if (auto *RT = CurType->getAs<RecordType>()) 10358 if (RT->isUnionType()) { 10359 SemaRef.Diag(ELoc, diag::err_omp_union_type_not_allowed) 10360 << CurE->getSourceRange(); 10361 break; 10362 } 10363 10364 // If we got a member expression, we should not expect any array section 10365 // before that: 10366 // 10367 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.7] 10368 // If a list item is an element of a structure, only the rightmost symbol 10369 // of the variable reference can be an array section. 10370 // 10371 AllowUnitySizeArraySection = false; 10372 AllowWholeSizeArraySection = false; 10373 10374 // Record the component. 10375 CurComponents.push_back( 10376 OMPClauseMappableExprCommon::MappableComponent(CurE, FD)); 10377 continue; 10378 } 10379 10380 if (auto *CurE = dyn_cast<ArraySubscriptExpr>(E)) { 10381 E = CurE->getBase()->IgnoreParenImpCasts(); 10382 10383 if (!E->getType()->isAnyPointerType() && !E->getType()->isArrayType()) { 10384 SemaRef.Diag(ELoc, diag::err_omp_expected_base_var_name) 10385 << 0 << CurE->getSourceRange(); 10386 break; 10387 } 10388 10389 // If we got an array subscript that express the whole dimension we 10390 // can have any array expressions before. If it only expressing part of 10391 // the dimension, we can only have unitary-size array expressions. 10392 if (CheckArrayExpressionDoesNotReferToWholeSize(SemaRef, CurE, 10393 E->getType())) 10394 AllowWholeSizeArraySection = false; 10395 10396 // Record the component - we don't have any declaration associated. 10397 CurComponents.push_back( 10398 OMPClauseMappableExprCommon::MappableComponent(CurE, nullptr)); 10399 continue; 10400 } 10401 10402 if (auto *CurE = dyn_cast<OMPArraySectionExpr>(E)) { 10403 E = CurE->getBase()->IgnoreParenImpCasts(); 10404 10405 auto CurType = 10406 OMPArraySectionExpr::getBaseOriginalType(E).getCanonicalType(); 10407 10408 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C++, p.1] 10409 // If the type of a list item is a reference to a type T then the type 10410 // will be considered to be T for all purposes of this clause. 10411 if (CurType->isReferenceType()) 10412 CurType = CurType->getPointeeType(); 10413 10414 bool IsPointer = CurType->isAnyPointerType(); 10415 10416 if (!IsPointer && !CurType->isArrayType()) { 10417 SemaRef.Diag(ELoc, diag::err_omp_expected_base_var_name) 10418 << 0 << CurE->getSourceRange(); 10419 break; 10420 } 10421 10422 bool NotWhole = 10423 CheckArrayExpressionDoesNotReferToWholeSize(SemaRef, CurE, CurType); 10424 bool NotUnity = 10425 CheckArrayExpressionDoesNotReferToUnitySize(SemaRef, CurE, CurType); 10426 10427 if (AllowWholeSizeArraySection && AllowUnitySizeArraySection) { 10428 // Any array section is currently allowed. 10429 // 10430 // If this array section refers to the whole dimension we can still 10431 // accept other array sections before this one, except if the base is a 10432 // pointer. Otherwise, only unitary sections are accepted. 10433 if (NotWhole || IsPointer) 10434 AllowWholeSizeArraySection = false; 10435 } else if ((AllowUnitySizeArraySection && NotUnity) || 10436 (AllowWholeSizeArraySection && NotWhole)) { 10437 // A unity or whole array section is not allowed and that is not 10438 // compatible with the properties of the current array section. 10439 SemaRef.Diag( 10440 ELoc, diag::err_array_section_does_not_specify_contiguous_storage) 10441 << CurE->getSourceRange(); 10442 break; 10443 } 10444 10445 // Record the component - we don't have any declaration associated. 10446 CurComponents.push_back( 10447 OMPClauseMappableExprCommon::MappableComponent(CurE, nullptr)); 10448 continue; 10449 } 10450 10451 // If nothing else worked, this is not a valid map clause expression. 10452 SemaRef.Diag(ELoc, 10453 diag::err_omp_expected_named_var_member_or_array_expression) 10454 << ERange; 10455 break; 10456 } 10457 10458 return RelevantExpr; 10459 } 10460 10461 // Return true if expression E associated with value VD has conflicts with other 10462 // map information. 10463 static bool CheckMapConflicts( 10464 Sema &SemaRef, DSAStackTy *DSAS, ValueDecl *VD, Expr *E, 10465 bool CurrentRegionOnly, 10466 OMPClauseMappableExprCommon::MappableExprComponentListRef CurComponents, 10467 OpenMPClauseKind CKind) { 10468 assert(VD && E); 10469 SourceLocation ELoc = E->getExprLoc(); 10470 SourceRange ERange = E->getSourceRange(); 10471 10472 // In order to easily check the conflicts we need to match each component of 10473 // the expression under test with the components of the expressions that are 10474 // already in the stack. 10475 10476 assert(!CurComponents.empty() && "Map clause expression with no components!"); 10477 assert(CurComponents.back().getAssociatedDeclaration() == VD && 10478 "Map clause expression with unexpected base!"); 10479 10480 // Variables to help detecting enclosing problems in data environment nests. 10481 bool IsEnclosedByDataEnvironmentExpr = false; 10482 const Expr *EnclosingExpr = nullptr; 10483 10484 bool FoundError = DSAS->checkMappableExprComponentListsForDecl( 10485 VD, CurrentRegionOnly, 10486 [&](OMPClauseMappableExprCommon::MappableExprComponentListRef 10487 StackComponents) -> bool { 10488 10489 assert(!StackComponents.empty() && 10490 "Map clause expression with no components!"); 10491 assert(StackComponents.back().getAssociatedDeclaration() == VD && 10492 "Map clause expression with unexpected base!"); 10493 10494 // The whole expression in the stack. 10495 auto *RE = StackComponents.front().getAssociatedExpression(); 10496 10497 // Expressions must start from the same base. Here we detect at which 10498 // point both expressions diverge from each other and see if we can 10499 // detect if the memory referred to both expressions is contiguous and 10500 // do not overlap. 10501 auto CI = CurComponents.rbegin(); 10502 auto CE = CurComponents.rend(); 10503 auto SI = StackComponents.rbegin(); 10504 auto SE = StackComponents.rend(); 10505 for (; CI != CE && SI != SE; ++CI, ++SI) { 10506 10507 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.3] 10508 // At most one list item can be an array item derived from a given 10509 // variable in map clauses of the same construct. 10510 if (CurrentRegionOnly && 10511 (isa<ArraySubscriptExpr>(CI->getAssociatedExpression()) || 10512 isa<OMPArraySectionExpr>(CI->getAssociatedExpression())) && 10513 (isa<ArraySubscriptExpr>(SI->getAssociatedExpression()) || 10514 isa<OMPArraySectionExpr>(SI->getAssociatedExpression()))) { 10515 SemaRef.Diag(CI->getAssociatedExpression()->getExprLoc(), 10516 diag::err_omp_multiple_array_items_in_map_clause) 10517 << CI->getAssociatedExpression()->getSourceRange(); 10518 SemaRef.Diag(SI->getAssociatedExpression()->getExprLoc(), 10519 diag::note_used_here) 10520 << SI->getAssociatedExpression()->getSourceRange(); 10521 return true; 10522 } 10523 10524 // Do both expressions have the same kind? 10525 if (CI->getAssociatedExpression()->getStmtClass() != 10526 SI->getAssociatedExpression()->getStmtClass()) 10527 break; 10528 10529 // Are we dealing with different variables/fields? 10530 if (CI->getAssociatedDeclaration() != SI->getAssociatedDeclaration()) 10531 break; 10532 } 10533 10534 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.4] 10535 // List items of map clauses in the same construct must not share 10536 // original storage. 10537 // 10538 // If the expressions are exactly the same or one is a subset of the 10539 // other, it means they are sharing storage. 10540 if (CI == CE && SI == SE) { 10541 if (CurrentRegionOnly) { 10542 if (CKind == OMPC_map) 10543 SemaRef.Diag(ELoc, diag::err_omp_map_shared_storage) << ERange; 10544 else { 10545 assert(CKind == OMPC_to || CKind == OMPC_from); 10546 SemaRef.Diag(ELoc, diag::err_omp_once_referenced_in_target_update) 10547 << ERange; 10548 } 10549 SemaRef.Diag(RE->getExprLoc(), diag::note_used_here) 10550 << RE->getSourceRange(); 10551 return true; 10552 } else { 10553 // If we find the same expression in the enclosing data environment, 10554 // that is legal. 10555 IsEnclosedByDataEnvironmentExpr = true; 10556 return false; 10557 } 10558 } 10559 10560 QualType DerivedType = 10561 std::prev(CI)->getAssociatedDeclaration()->getType(); 10562 SourceLocation DerivedLoc = 10563 std::prev(CI)->getAssociatedExpression()->getExprLoc(); 10564 10565 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C++, p.1] 10566 // If the type of a list item is a reference to a type T then the type 10567 // will be considered to be T for all purposes of this clause. 10568 DerivedType = DerivedType.getNonReferenceType(); 10569 10570 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C/C++, p.1] 10571 // A variable for which the type is pointer and an array section 10572 // derived from that variable must not appear as list items of map 10573 // clauses of the same construct. 10574 // 10575 // Also, cover one of the cases in: 10576 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.5] 10577 // If any part of the original storage of a list item has corresponding 10578 // storage in the device data environment, all of the original storage 10579 // must have corresponding storage in the device data environment. 10580 // 10581 if (DerivedType->isAnyPointerType()) { 10582 if (CI == CE || SI == SE) { 10583 SemaRef.Diag( 10584 DerivedLoc, 10585 diag::err_omp_pointer_mapped_along_with_derived_section) 10586 << DerivedLoc; 10587 } else { 10588 assert(CI != CE && SI != SE); 10589 SemaRef.Diag(DerivedLoc, diag::err_omp_same_pointer_derreferenced) 10590 << DerivedLoc; 10591 } 10592 SemaRef.Diag(RE->getExprLoc(), diag::note_used_here) 10593 << RE->getSourceRange(); 10594 return true; 10595 } 10596 10597 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.4] 10598 // List items of map clauses in the same construct must not share 10599 // original storage. 10600 // 10601 // An expression is a subset of the other. 10602 if (CurrentRegionOnly && (CI == CE || SI == SE)) { 10603 if (CKind == OMPC_map) 10604 SemaRef.Diag(ELoc, diag::err_omp_map_shared_storage) << ERange; 10605 else { 10606 assert(CKind == OMPC_to || CKind == OMPC_from); 10607 SemaRef.Diag(ELoc, diag::err_omp_once_referenced_in_target_update) 10608 << ERange; 10609 } 10610 SemaRef.Diag(RE->getExprLoc(), diag::note_used_here) 10611 << RE->getSourceRange(); 10612 return true; 10613 } 10614 10615 // The current expression uses the same base as other expression in the 10616 // data environment but does not contain it completely. 10617 if (!CurrentRegionOnly && SI != SE) 10618 EnclosingExpr = RE; 10619 10620 // The current expression is a subset of the expression in the data 10621 // environment. 10622 IsEnclosedByDataEnvironmentExpr |= 10623 (!CurrentRegionOnly && CI != CE && SI == SE); 10624 10625 return false; 10626 }); 10627 10628 if (CurrentRegionOnly) 10629 return FoundError; 10630 10631 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.5] 10632 // If any part of the original storage of a list item has corresponding 10633 // storage in the device data environment, all of the original storage must 10634 // have corresponding storage in the device data environment. 10635 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.6] 10636 // If a list item is an element of a structure, and a different element of 10637 // the structure has a corresponding list item in the device data environment 10638 // prior to a task encountering the construct associated with the map clause, 10639 // then the list item must also have a corresponding list item in the device 10640 // data environment prior to the task encountering the construct. 10641 // 10642 if (EnclosingExpr && !IsEnclosedByDataEnvironmentExpr) { 10643 SemaRef.Diag(ELoc, 10644 diag::err_omp_original_storage_is_shared_and_does_not_contain) 10645 << ERange; 10646 SemaRef.Diag(EnclosingExpr->getExprLoc(), diag::note_used_here) 10647 << EnclosingExpr->getSourceRange(); 10648 return true; 10649 } 10650 10651 return FoundError; 10652 } 10653 10654 namespace { 10655 // Utility struct that gathers all the related lists associated with a mappable 10656 // expression. 10657 struct MappableVarListInfo final { 10658 // The list of expressions. 10659 ArrayRef<Expr *> VarList; 10660 // The list of processed expressions. 10661 SmallVector<Expr *, 16> ProcessedVarList; 10662 // The mappble components for each expression. 10663 OMPClauseMappableExprCommon::MappableExprComponentLists VarComponents; 10664 // The base declaration of the variable. 10665 SmallVector<ValueDecl *, 16> VarBaseDeclarations; 10666 10667 MappableVarListInfo(ArrayRef<Expr *> VarList) : VarList(VarList) { 10668 // We have a list of components and base declarations for each entry in the 10669 // variable list. 10670 VarComponents.reserve(VarList.size()); 10671 VarBaseDeclarations.reserve(VarList.size()); 10672 } 10673 }; 10674 } 10675 10676 // Check the validity of the provided variable list for the provided clause kind 10677 // \a CKind. In the check process the valid expressions, and mappable expression 10678 // components and variables are extracted and used to fill \a Vars, 10679 // \a ClauseComponents, and \a ClauseBaseDeclarations. \a MapType and 10680 // \a IsMapTypeImplicit are expected to be valid if the clause kind is 'map'. 10681 static void 10682 checkMappableExpressionList(Sema &SemaRef, DSAStackTy *DSAS, 10683 OpenMPClauseKind CKind, MappableVarListInfo &MVLI, 10684 SourceLocation StartLoc, 10685 OpenMPMapClauseKind MapType = OMPC_MAP_unknown, 10686 bool IsMapTypeImplicit = false) { 10687 // We only expect mappable expressions in 'to', 'from', and 'map' clauses. 10688 assert((CKind == OMPC_map || CKind == OMPC_to || CKind == OMPC_from) && 10689 "Unexpected clause kind with mappable expressions!"); 10690 10691 // Keep track of the mappable components and base declarations in this clause. 10692 // Each entry in the list is going to have a list of components associated. We 10693 // record each set of the components so that we can build the clause later on. 10694 // In the end we should have the same amount of declarations and component 10695 // lists. 10696 10697 for (auto &RE : MVLI.VarList) { 10698 assert(RE && "Null expr in omp to/from/map clause"); 10699 SourceLocation ELoc = RE->getExprLoc(); 10700 10701 auto *VE = RE->IgnoreParenLValueCasts(); 10702 10703 if (VE->isValueDependent() || VE->isTypeDependent() || 10704 VE->isInstantiationDependent() || 10705 VE->containsUnexpandedParameterPack()) { 10706 // We can only analyze this information once the missing information is 10707 // resolved. 10708 MVLI.ProcessedVarList.push_back(RE); 10709 continue; 10710 } 10711 10712 auto *SimpleExpr = RE->IgnoreParenCasts(); 10713 10714 if (!RE->IgnoreParenImpCasts()->isLValue()) { 10715 SemaRef.Diag(ELoc, 10716 diag::err_omp_expected_named_var_member_or_array_expression) 10717 << RE->getSourceRange(); 10718 continue; 10719 } 10720 10721 OMPClauseMappableExprCommon::MappableExprComponentList CurComponents; 10722 ValueDecl *CurDeclaration = nullptr; 10723 10724 // Obtain the array or member expression bases if required. Also, fill the 10725 // components array with all the components identified in the process. 10726 auto *BE = 10727 CheckMapClauseExpressionBase(SemaRef, SimpleExpr, CurComponents, CKind); 10728 if (!BE) 10729 continue; 10730 10731 assert(!CurComponents.empty() && 10732 "Invalid mappable expression information."); 10733 10734 // For the following checks, we rely on the base declaration which is 10735 // expected to be associated with the last component. The declaration is 10736 // expected to be a variable or a field (if 'this' is being mapped). 10737 CurDeclaration = CurComponents.back().getAssociatedDeclaration(); 10738 assert(CurDeclaration && "Null decl on map clause."); 10739 assert( 10740 CurDeclaration->isCanonicalDecl() && 10741 "Expecting components to have associated only canonical declarations."); 10742 10743 auto *VD = dyn_cast<VarDecl>(CurDeclaration); 10744 auto *FD = dyn_cast<FieldDecl>(CurDeclaration); 10745 10746 assert((VD || FD) && "Only variables or fields are expected here!"); 10747 (void)FD; 10748 10749 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.10] 10750 // threadprivate variables cannot appear in a map clause. 10751 // OpenMP 4.5 [2.10.5, target update Construct] 10752 // threadprivate variables cannot appear in a from clause. 10753 if (VD && DSAS->isThreadPrivate(VD)) { 10754 auto DVar = DSAS->getTopDSA(VD, false); 10755 SemaRef.Diag(ELoc, diag::err_omp_threadprivate_in_clause) 10756 << getOpenMPClauseName(CKind); 10757 ReportOriginalDSA(SemaRef, DSAS, VD, DVar); 10758 continue; 10759 } 10760 10761 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.9] 10762 // A list item cannot appear in both a map clause and a data-sharing 10763 // attribute clause on the same construct. 10764 10765 // Check conflicts with other map clause expressions. We check the conflicts 10766 // with the current construct separately from the enclosing data 10767 // environment, because the restrictions are different. We only have to 10768 // check conflicts across regions for the map clauses. 10769 if (CheckMapConflicts(SemaRef, DSAS, CurDeclaration, SimpleExpr, 10770 /*CurrentRegionOnly=*/true, CurComponents, CKind)) 10771 break; 10772 if (CKind == OMPC_map && 10773 CheckMapConflicts(SemaRef, DSAS, CurDeclaration, SimpleExpr, 10774 /*CurrentRegionOnly=*/false, CurComponents, CKind)) 10775 break; 10776 10777 // OpenMP 4.5 [2.10.5, target update Construct] 10778 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C++, p.1] 10779 // If the type of a list item is a reference to a type T then the type will 10780 // be considered to be T for all purposes of this clause. 10781 QualType Type = CurDeclaration->getType().getNonReferenceType(); 10782 10783 // OpenMP 4.5 [2.10.5, target update Construct, Restrictions, p.4] 10784 // A list item in a to or from clause must have a mappable type. 10785 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.9] 10786 // A list item must have a mappable type. 10787 if (!CheckTypeMappable(VE->getExprLoc(), VE->getSourceRange(), SemaRef, 10788 DSAS, Type)) 10789 continue; 10790 10791 if (CKind == OMPC_map) { 10792 // target enter data 10793 // OpenMP [2.10.2, Restrictions, p. 99] 10794 // A map-type must be specified in all map clauses and must be either 10795 // to or alloc. 10796 OpenMPDirectiveKind DKind = DSAS->getCurrentDirective(); 10797 if (DKind == OMPD_target_enter_data && 10798 !(MapType == OMPC_MAP_to || MapType == OMPC_MAP_alloc)) { 10799 SemaRef.Diag(StartLoc, diag::err_omp_invalid_map_type_for_directive) 10800 << (IsMapTypeImplicit ? 1 : 0) 10801 << getOpenMPSimpleClauseTypeName(OMPC_map, MapType) 10802 << getOpenMPDirectiveName(DKind); 10803 continue; 10804 } 10805 10806 // target exit_data 10807 // OpenMP [2.10.3, Restrictions, p. 102] 10808 // A map-type must be specified in all map clauses and must be either 10809 // from, release, or delete. 10810 if (DKind == OMPD_target_exit_data && 10811 !(MapType == OMPC_MAP_from || MapType == OMPC_MAP_release || 10812 MapType == OMPC_MAP_delete)) { 10813 SemaRef.Diag(StartLoc, diag::err_omp_invalid_map_type_for_directive) 10814 << (IsMapTypeImplicit ? 1 : 0) 10815 << getOpenMPSimpleClauseTypeName(OMPC_map, MapType) 10816 << getOpenMPDirectiveName(DKind); 10817 continue; 10818 } 10819 10820 // OpenMP 4.5 [2.15.5.1, Restrictions, p.3] 10821 // A list item cannot appear in both a map clause and a data-sharing 10822 // attribute clause on the same construct 10823 if (DKind == OMPD_target && VD) { 10824 auto DVar = DSAS->getTopDSA(VD, false); 10825 if (isOpenMPPrivate(DVar.CKind)) { 10826 SemaRef.Diag(ELoc, diag::err_omp_variable_in_map_and_dsa) 10827 << getOpenMPClauseName(DVar.CKind) 10828 << getOpenMPDirectiveName(DSAS->getCurrentDirective()); 10829 ReportOriginalDSA(SemaRef, DSAS, CurDeclaration, DVar); 10830 continue; 10831 } 10832 } 10833 } 10834 10835 // Save the current expression. 10836 MVLI.ProcessedVarList.push_back(RE); 10837 10838 // Store the components in the stack so that they can be used to check 10839 // against other clauses later on. 10840 DSAS->addMappableExpressionComponents(CurDeclaration, CurComponents); 10841 10842 // Save the components and declaration to create the clause. For purposes of 10843 // the clause creation, any component list that has has base 'this' uses 10844 // null as base declaration. 10845 MVLI.VarComponents.resize(MVLI.VarComponents.size() + 1); 10846 MVLI.VarComponents.back().append(CurComponents.begin(), 10847 CurComponents.end()); 10848 MVLI.VarBaseDeclarations.push_back(isa<MemberExpr>(BE) ? nullptr 10849 : CurDeclaration); 10850 } 10851 } 10852 10853 OMPClause * 10854 Sema::ActOnOpenMPMapClause(OpenMPMapClauseKind MapTypeModifier, 10855 OpenMPMapClauseKind MapType, bool IsMapTypeImplicit, 10856 SourceLocation MapLoc, SourceLocation ColonLoc, 10857 ArrayRef<Expr *> VarList, SourceLocation StartLoc, 10858 SourceLocation LParenLoc, SourceLocation EndLoc) { 10859 MappableVarListInfo MVLI(VarList); 10860 checkMappableExpressionList(*this, DSAStack, OMPC_map, MVLI, StartLoc, 10861 MapType, IsMapTypeImplicit); 10862 10863 // We need to produce a map clause even if we don't have variables so that 10864 // other diagnostics related with non-existing map clauses are accurate. 10865 return OMPMapClause::Create(Context, StartLoc, LParenLoc, EndLoc, 10866 MVLI.ProcessedVarList, MVLI.VarBaseDeclarations, 10867 MVLI.VarComponents, MapTypeModifier, MapType, 10868 IsMapTypeImplicit, MapLoc); 10869 } 10870 10871 QualType Sema::ActOnOpenMPDeclareReductionType(SourceLocation TyLoc, 10872 TypeResult ParsedType) { 10873 assert(ParsedType.isUsable()); 10874 10875 QualType ReductionType = GetTypeFromParser(ParsedType.get()); 10876 if (ReductionType.isNull()) 10877 return QualType(); 10878 10879 // [OpenMP 4.0], 2.15 declare reduction Directive, Restrictions, C\C++ 10880 // A type name in a declare reduction directive cannot be a function type, an 10881 // array type, a reference type, or a type qualified with const, volatile or 10882 // restrict. 10883 if (ReductionType.hasQualifiers()) { 10884 Diag(TyLoc, diag::err_omp_reduction_wrong_type) << 0; 10885 return QualType(); 10886 } 10887 10888 if (ReductionType->isFunctionType()) { 10889 Diag(TyLoc, diag::err_omp_reduction_wrong_type) << 1; 10890 return QualType(); 10891 } 10892 if (ReductionType->isReferenceType()) { 10893 Diag(TyLoc, diag::err_omp_reduction_wrong_type) << 2; 10894 return QualType(); 10895 } 10896 if (ReductionType->isArrayType()) { 10897 Diag(TyLoc, diag::err_omp_reduction_wrong_type) << 3; 10898 return QualType(); 10899 } 10900 return ReductionType; 10901 } 10902 10903 Sema::DeclGroupPtrTy Sema::ActOnOpenMPDeclareReductionDirectiveStart( 10904 Scope *S, DeclContext *DC, DeclarationName Name, 10905 ArrayRef<std::pair<QualType, SourceLocation>> ReductionTypes, 10906 AccessSpecifier AS, Decl *PrevDeclInScope) { 10907 SmallVector<Decl *, 8> Decls; 10908 Decls.reserve(ReductionTypes.size()); 10909 10910 LookupResult Lookup(*this, Name, SourceLocation(), LookupOMPReductionName, 10911 ForRedeclaration); 10912 // [OpenMP 4.0], 2.15 declare reduction Directive, Restrictions 10913 // A reduction-identifier may not be re-declared in the current scope for the 10914 // same type or for a type that is compatible according to the base language 10915 // rules. 10916 llvm::DenseMap<QualType, SourceLocation> PreviousRedeclTypes; 10917 OMPDeclareReductionDecl *PrevDRD = nullptr; 10918 bool InCompoundScope = true; 10919 if (S != nullptr) { 10920 // Find previous declaration with the same name not referenced in other 10921 // declarations. 10922 FunctionScopeInfo *ParentFn = getEnclosingFunction(); 10923 InCompoundScope = 10924 (ParentFn != nullptr) && !ParentFn->CompoundScopes.empty(); 10925 LookupName(Lookup, S); 10926 FilterLookupForScope(Lookup, DC, S, /*ConsiderLinkage=*/false, 10927 /*AllowInlineNamespace=*/false); 10928 llvm::DenseMap<OMPDeclareReductionDecl *, bool> UsedAsPrevious; 10929 auto Filter = Lookup.makeFilter(); 10930 while (Filter.hasNext()) { 10931 auto *PrevDecl = cast<OMPDeclareReductionDecl>(Filter.next()); 10932 if (InCompoundScope) { 10933 auto I = UsedAsPrevious.find(PrevDecl); 10934 if (I == UsedAsPrevious.end()) 10935 UsedAsPrevious[PrevDecl] = false; 10936 if (auto *D = PrevDecl->getPrevDeclInScope()) 10937 UsedAsPrevious[D] = true; 10938 } 10939 PreviousRedeclTypes[PrevDecl->getType().getCanonicalType()] = 10940 PrevDecl->getLocation(); 10941 } 10942 Filter.done(); 10943 if (InCompoundScope) { 10944 for (auto &PrevData : UsedAsPrevious) { 10945 if (!PrevData.second) { 10946 PrevDRD = PrevData.first; 10947 break; 10948 } 10949 } 10950 } 10951 } else if (PrevDeclInScope != nullptr) { 10952 auto *PrevDRDInScope = PrevDRD = 10953 cast<OMPDeclareReductionDecl>(PrevDeclInScope); 10954 do { 10955 PreviousRedeclTypes[PrevDRDInScope->getType().getCanonicalType()] = 10956 PrevDRDInScope->getLocation(); 10957 PrevDRDInScope = PrevDRDInScope->getPrevDeclInScope(); 10958 } while (PrevDRDInScope != nullptr); 10959 } 10960 for (auto &TyData : ReductionTypes) { 10961 auto I = PreviousRedeclTypes.find(TyData.first.getCanonicalType()); 10962 bool Invalid = false; 10963 if (I != PreviousRedeclTypes.end()) { 10964 Diag(TyData.second, diag::err_omp_declare_reduction_redefinition) 10965 << TyData.first; 10966 Diag(I->second, diag::note_previous_definition); 10967 Invalid = true; 10968 } 10969 PreviousRedeclTypes[TyData.first.getCanonicalType()] = TyData.second; 10970 auto *DRD = OMPDeclareReductionDecl::Create(Context, DC, TyData.second, 10971 Name, TyData.first, PrevDRD); 10972 DC->addDecl(DRD); 10973 DRD->setAccess(AS); 10974 Decls.push_back(DRD); 10975 if (Invalid) 10976 DRD->setInvalidDecl(); 10977 else 10978 PrevDRD = DRD; 10979 } 10980 10981 return DeclGroupPtrTy::make( 10982 DeclGroupRef::Create(Context, Decls.begin(), Decls.size())); 10983 } 10984 10985 void Sema::ActOnOpenMPDeclareReductionCombinerStart(Scope *S, Decl *D) { 10986 auto *DRD = cast<OMPDeclareReductionDecl>(D); 10987 10988 // Enter new function scope. 10989 PushFunctionScope(); 10990 getCurFunction()->setHasBranchProtectedScope(); 10991 getCurFunction()->setHasOMPDeclareReductionCombiner(); 10992 10993 if (S != nullptr) 10994 PushDeclContext(S, DRD); 10995 else 10996 CurContext = DRD; 10997 10998 PushExpressionEvaluationContext(PotentiallyEvaluated); 10999 11000 QualType ReductionType = DRD->getType(); 11001 // Create 'T* omp_parm;T omp_in;'. All references to 'omp_in' will 11002 // be replaced by '*omp_parm' during codegen. This required because 'omp_in' 11003 // uses semantics of argument handles by value, but it should be passed by 11004 // reference. C lang does not support references, so pass all parameters as 11005 // pointers. 11006 // Create 'T omp_in;' variable. 11007 auto *OmpInParm = 11008 buildVarDecl(*this, D->getLocation(), ReductionType, "omp_in"); 11009 // Create 'T* omp_parm;T omp_out;'. All references to 'omp_out' will 11010 // be replaced by '*omp_parm' during codegen. This required because 'omp_out' 11011 // uses semantics of argument handles by value, but it should be passed by 11012 // reference. C lang does not support references, so pass all parameters as 11013 // pointers. 11014 // Create 'T omp_out;' variable. 11015 auto *OmpOutParm = 11016 buildVarDecl(*this, D->getLocation(), ReductionType, "omp_out"); 11017 if (S != nullptr) { 11018 PushOnScopeChains(OmpInParm, S); 11019 PushOnScopeChains(OmpOutParm, S); 11020 } else { 11021 DRD->addDecl(OmpInParm); 11022 DRD->addDecl(OmpOutParm); 11023 } 11024 } 11025 11026 void Sema::ActOnOpenMPDeclareReductionCombinerEnd(Decl *D, Expr *Combiner) { 11027 auto *DRD = cast<OMPDeclareReductionDecl>(D); 11028 DiscardCleanupsInEvaluationContext(); 11029 PopExpressionEvaluationContext(); 11030 11031 PopDeclContext(); 11032 PopFunctionScopeInfo(); 11033 11034 if (Combiner != nullptr) 11035 DRD->setCombiner(Combiner); 11036 else 11037 DRD->setInvalidDecl(); 11038 } 11039 11040 void Sema::ActOnOpenMPDeclareReductionInitializerStart(Scope *S, Decl *D) { 11041 auto *DRD = cast<OMPDeclareReductionDecl>(D); 11042 11043 // Enter new function scope. 11044 PushFunctionScope(); 11045 getCurFunction()->setHasBranchProtectedScope(); 11046 11047 if (S != nullptr) 11048 PushDeclContext(S, DRD); 11049 else 11050 CurContext = DRD; 11051 11052 PushExpressionEvaluationContext(PotentiallyEvaluated); 11053 11054 QualType ReductionType = DRD->getType(); 11055 // Create 'T* omp_parm;T omp_priv;'. All references to 'omp_priv' will 11056 // be replaced by '*omp_parm' during codegen. This required because 'omp_priv' 11057 // uses semantics of argument handles by value, but it should be passed by 11058 // reference. C lang does not support references, so pass all parameters as 11059 // pointers. 11060 // Create 'T omp_priv;' variable. 11061 auto *OmpPrivParm = 11062 buildVarDecl(*this, D->getLocation(), ReductionType, "omp_priv"); 11063 // Create 'T* omp_parm;T omp_orig;'. All references to 'omp_orig' will 11064 // be replaced by '*omp_parm' during codegen. This required because 'omp_orig' 11065 // uses semantics of argument handles by value, but it should be passed by 11066 // reference. C lang does not support references, so pass all parameters as 11067 // pointers. 11068 // Create 'T omp_orig;' variable. 11069 auto *OmpOrigParm = 11070 buildVarDecl(*this, D->getLocation(), ReductionType, "omp_orig"); 11071 if (S != nullptr) { 11072 PushOnScopeChains(OmpPrivParm, S); 11073 PushOnScopeChains(OmpOrigParm, S); 11074 } else { 11075 DRD->addDecl(OmpPrivParm); 11076 DRD->addDecl(OmpOrigParm); 11077 } 11078 } 11079 11080 void Sema::ActOnOpenMPDeclareReductionInitializerEnd(Decl *D, 11081 Expr *Initializer) { 11082 auto *DRD = cast<OMPDeclareReductionDecl>(D); 11083 DiscardCleanupsInEvaluationContext(); 11084 PopExpressionEvaluationContext(); 11085 11086 PopDeclContext(); 11087 PopFunctionScopeInfo(); 11088 11089 if (Initializer != nullptr) 11090 DRD->setInitializer(Initializer); 11091 else 11092 DRD->setInvalidDecl(); 11093 } 11094 11095 Sema::DeclGroupPtrTy Sema::ActOnOpenMPDeclareReductionDirectiveEnd( 11096 Scope *S, DeclGroupPtrTy DeclReductions, bool IsValid) { 11097 for (auto *D : DeclReductions.get()) { 11098 if (IsValid) { 11099 auto *DRD = cast<OMPDeclareReductionDecl>(D); 11100 if (S != nullptr) 11101 PushOnScopeChains(DRD, S, /*AddToContext=*/false); 11102 } else 11103 D->setInvalidDecl(); 11104 } 11105 return DeclReductions; 11106 } 11107 11108 OMPClause *Sema::ActOnOpenMPNumTeamsClause(Expr *NumTeams, 11109 SourceLocation StartLoc, 11110 SourceLocation LParenLoc, 11111 SourceLocation EndLoc) { 11112 Expr *ValExpr = NumTeams; 11113 11114 // OpenMP [teams Constrcut, Restrictions] 11115 // The num_teams expression must evaluate to a positive integer value. 11116 if (!IsNonNegativeIntegerValue(ValExpr, *this, OMPC_num_teams, 11117 /*StrictlyPositive=*/true)) 11118 return nullptr; 11119 11120 return new (Context) OMPNumTeamsClause(ValExpr, StartLoc, LParenLoc, EndLoc); 11121 } 11122 11123 OMPClause *Sema::ActOnOpenMPThreadLimitClause(Expr *ThreadLimit, 11124 SourceLocation StartLoc, 11125 SourceLocation LParenLoc, 11126 SourceLocation EndLoc) { 11127 Expr *ValExpr = ThreadLimit; 11128 11129 // OpenMP [teams Constrcut, Restrictions] 11130 // The thread_limit expression must evaluate to a positive integer value. 11131 if (!IsNonNegativeIntegerValue(ValExpr, *this, OMPC_thread_limit, 11132 /*StrictlyPositive=*/true)) 11133 return nullptr; 11134 11135 return new (Context) OMPThreadLimitClause(ValExpr, StartLoc, LParenLoc, 11136 EndLoc); 11137 } 11138 11139 OMPClause *Sema::ActOnOpenMPPriorityClause(Expr *Priority, 11140 SourceLocation StartLoc, 11141 SourceLocation LParenLoc, 11142 SourceLocation EndLoc) { 11143 Expr *ValExpr = Priority; 11144 11145 // OpenMP [2.9.1, task Constrcut] 11146 // The priority-value is a non-negative numerical scalar expression. 11147 if (!IsNonNegativeIntegerValue(ValExpr, *this, OMPC_priority, 11148 /*StrictlyPositive=*/false)) 11149 return nullptr; 11150 11151 return new (Context) OMPPriorityClause(ValExpr, StartLoc, LParenLoc, EndLoc); 11152 } 11153 11154 OMPClause *Sema::ActOnOpenMPGrainsizeClause(Expr *Grainsize, 11155 SourceLocation StartLoc, 11156 SourceLocation LParenLoc, 11157 SourceLocation EndLoc) { 11158 Expr *ValExpr = Grainsize; 11159 11160 // OpenMP [2.9.2, taskloop Constrcut] 11161 // The parameter of the grainsize clause must be a positive integer 11162 // expression. 11163 if (!IsNonNegativeIntegerValue(ValExpr, *this, OMPC_grainsize, 11164 /*StrictlyPositive=*/true)) 11165 return nullptr; 11166 11167 return new (Context) OMPGrainsizeClause(ValExpr, StartLoc, LParenLoc, EndLoc); 11168 } 11169 11170 OMPClause *Sema::ActOnOpenMPNumTasksClause(Expr *NumTasks, 11171 SourceLocation StartLoc, 11172 SourceLocation LParenLoc, 11173 SourceLocation EndLoc) { 11174 Expr *ValExpr = NumTasks; 11175 11176 // OpenMP [2.9.2, taskloop Constrcut] 11177 // The parameter of the num_tasks clause must be a positive integer 11178 // expression. 11179 if (!IsNonNegativeIntegerValue(ValExpr, *this, OMPC_num_tasks, 11180 /*StrictlyPositive=*/true)) 11181 return nullptr; 11182 11183 return new (Context) OMPNumTasksClause(ValExpr, StartLoc, LParenLoc, EndLoc); 11184 } 11185 11186 OMPClause *Sema::ActOnOpenMPHintClause(Expr *Hint, SourceLocation StartLoc, 11187 SourceLocation LParenLoc, 11188 SourceLocation EndLoc) { 11189 // OpenMP [2.13.2, critical construct, Description] 11190 // ... where hint-expression is an integer constant expression that evaluates 11191 // to a valid lock hint. 11192 ExprResult HintExpr = VerifyPositiveIntegerConstantInClause(Hint, OMPC_hint); 11193 if (HintExpr.isInvalid()) 11194 return nullptr; 11195 return new (Context) 11196 OMPHintClause(HintExpr.get(), StartLoc, LParenLoc, EndLoc); 11197 } 11198 11199 OMPClause *Sema::ActOnOpenMPDistScheduleClause( 11200 OpenMPDistScheduleClauseKind Kind, Expr *ChunkSize, SourceLocation StartLoc, 11201 SourceLocation LParenLoc, SourceLocation KindLoc, SourceLocation CommaLoc, 11202 SourceLocation EndLoc) { 11203 if (Kind == OMPC_DIST_SCHEDULE_unknown) { 11204 std::string Values; 11205 Values += "'"; 11206 Values += getOpenMPSimpleClauseTypeName(OMPC_dist_schedule, 0); 11207 Values += "'"; 11208 Diag(KindLoc, diag::err_omp_unexpected_clause_value) 11209 << Values << getOpenMPClauseName(OMPC_dist_schedule); 11210 return nullptr; 11211 } 11212 Expr *ValExpr = ChunkSize; 11213 Stmt *HelperValStmt = nullptr; 11214 if (ChunkSize) { 11215 if (!ChunkSize->isValueDependent() && !ChunkSize->isTypeDependent() && 11216 !ChunkSize->isInstantiationDependent() && 11217 !ChunkSize->containsUnexpandedParameterPack()) { 11218 SourceLocation ChunkSizeLoc = ChunkSize->getLocStart(); 11219 ExprResult Val = 11220 PerformOpenMPImplicitIntegerConversion(ChunkSizeLoc, ChunkSize); 11221 if (Val.isInvalid()) 11222 return nullptr; 11223 11224 ValExpr = Val.get(); 11225 11226 // OpenMP [2.7.1, Restrictions] 11227 // chunk_size must be a loop invariant integer expression with a positive 11228 // value. 11229 llvm::APSInt Result; 11230 if (ValExpr->isIntegerConstantExpr(Result, Context)) { 11231 if (Result.isSigned() && !Result.isStrictlyPositive()) { 11232 Diag(ChunkSizeLoc, diag::err_omp_negative_expression_in_clause) 11233 << "dist_schedule" << ChunkSize->getSourceRange(); 11234 return nullptr; 11235 } 11236 } else if (isParallelOrTaskRegion(DSAStack->getCurrentDirective()) && 11237 !CurContext->isDependentContext()) { 11238 llvm::MapVector<Expr *, DeclRefExpr *> Captures; 11239 ValExpr = tryBuildCapture(*this, ValExpr, Captures).get(); 11240 HelperValStmt = buildPreInits(Context, Captures); 11241 } 11242 } 11243 } 11244 11245 return new (Context) 11246 OMPDistScheduleClause(StartLoc, LParenLoc, KindLoc, CommaLoc, EndLoc, 11247 Kind, ValExpr, HelperValStmt); 11248 } 11249 11250 OMPClause *Sema::ActOnOpenMPDefaultmapClause( 11251 OpenMPDefaultmapClauseModifier M, OpenMPDefaultmapClauseKind Kind, 11252 SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation MLoc, 11253 SourceLocation KindLoc, SourceLocation EndLoc) { 11254 // OpenMP 4.5 only supports 'defaultmap(tofrom: scalar)' 11255 if (M != OMPC_DEFAULTMAP_MODIFIER_tofrom || 11256 Kind != OMPC_DEFAULTMAP_scalar) { 11257 std::string Value; 11258 SourceLocation Loc; 11259 Value += "'"; 11260 if (M != OMPC_DEFAULTMAP_MODIFIER_tofrom) { 11261 Value += getOpenMPSimpleClauseTypeName(OMPC_defaultmap, 11262 OMPC_DEFAULTMAP_MODIFIER_tofrom); 11263 Loc = MLoc; 11264 } else { 11265 Value += getOpenMPSimpleClauseTypeName(OMPC_defaultmap, 11266 OMPC_DEFAULTMAP_scalar); 11267 Loc = KindLoc; 11268 } 11269 Value += "'"; 11270 Diag(Loc, diag::err_omp_unexpected_clause_value) 11271 << Value << getOpenMPClauseName(OMPC_defaultmap); 11272 return nullptr; 11273 } 11274 11275 return new (Context) 11276 OMPDefaultmapClause(StartLoc, LParenLoc, MLoc, KindLoc, EndLoc, Kind, M); 11277 } 11278 11279 bool Sema::ActOnStartOpenMPDeclareTargetDirective(SourceLocation Loc) { 11280 DeclContext *CurLexicalContext = getCurLexicalContext(); 11281 if (!CurLexicalContext->isFileContext() && 11282 !CurLexicalContext->isExternCContext() && 11283 !CurLexicalContext->isExternCXXContext()) { 11284 Diag(Loc, diag::err_omp_region_not_file_context); 11285 return false; 11286 } 11287 if (IsInOpenMPDeclareTargetContext) { 11288 Diag(Loc, diag::err_omp_enclosed_declare_target); 11289 return false; 11290 } 11291 11292 IsInOpenMPDeclareTargetContext = true; 11293 return true; 11294 } 11295 11296 void Sema::ActOnFinishOpenMPDeclareTargetDirective() { 11297 assert(IsInOpenMPDeclareTargetContext && 11298 "Unexpected ActOnFinishOpenMPDeclareTargetDirective"); 11299 11300 IsInOpenMPDeclareTargetContext = false; 11301 } 11302 11303 void 11304 Sema::ActOnOpenMPDeclareTargetName(Scope *CurScope, CXXScopeSpec &ScopeSpec, 11305 const DeclarationNameInfo &Id, 11306 OMPDeclareTargetDeclAttr::MapTypeTy MT, 11307 NamedDeclSetType &SameDirectiveDecls) { 11308 LookupResult Lookup(*this, Id, LookupOrdinaryName); 11309 LookupParsedName(Lookup, CurScope, &ScopeSpec, true); 11310 11311 if (Lookup.isAmbiguous()) 11312 return; 11313 Lookup.suppressDiagnostics(); 11314 11315 if (!Lookup.isSingleResult()) { 11316 if (TypoCorrection Corrected = 11317 CorrectTypo(Id, LookupOrdinaryName, CurScope, nullptr, 11318 llvm::make_unique<VarOrFuncDeclFilterCCC>(*this), 11319 CTK_ErrorRecovery)) { 11320 diagnoseTypo(Corrected, PDiag(diag::err_undeclared_var_use_suggest) 11321 << Id.getName()); 11322 checkDeclIsAllowedInOpenMPTarget(nullptr, Corrected.getCorrectionDecl()); 11323 return; 11324 } 11325 11326 Diag(Id.getLoc(), diag::err_undeclared_var_use) << Id.getName(); 11327 return; 11328 } 11329 11330 NamedDecl *ND = Lookup.getAsSingle<NamedDecl>(); 11331 if (isa<VarDecl>(ND) || isa<FunctionDecl>(ND)) { 11332 if (!SameDirectiveDecls.insert(cast<NamedDecl>(ND->getCanonicalDecl()))) 11333 Diag(Id.getLoc(), diag::err_omp_declare_target_multiple) << Id.getName(); 11334 11335 if (!ND->hasAttr<OMPDeclareTargetDeclAttr>()) { 11336 Attr *A = OMPDeclareTargetDeclAttr::CreateImplicit(Context, MT); 11337 ND->addAttr(A); 11338 if (ASTMutationListener *ML = Context.getASTMutationListener()) 11339 ML->DeclarationMarkedOpenMPDeclareTarget(ND, A); 11340 checkDeclIsAllowedInOpenMPTarget(nullptr, ND); 11341 } else if (ND->getAttr<OMPDeclareTargetDeclAttr>()->getMapType() != MT) { 11342 Diag(Id.getLoc(), diag::err_omp_declare_target_to_and_link) 11343 << Id.getName(); 11344 } 11345 } else 11346 Diag(Id.getLoc(), diag::err_omp_invalid_target_decl) << Id.getName(); 11347 } 11348 11349 static void checkDeclInTargetContext(SourceLocation SL, SourceRange SR, 11350 Sema &SemaRef, Decl *D) { 11351 if (!D) 11352 return; 11353 Decl *LD = nullptr; 11354 if (isa<TagDecl>(D)) { 11355 LD = cast<TagDecl>(D)->getDefinition(); 11356 } else if (isa<VarDecl>(D)) { 11357 LD = cast<VarDecl>(D)->getDefinition(); 11358 11359 // If this is an implicit variable that is legal and we do not need to do 11360 // anything. 11361 if (cast<VarDecl>(D)->isImplicit()) { 11362 Attr *A = OMPDeclareTargetDeclAttr::CreateImplicit( 11363 SemaRef.Context, OMPDeclareTargetDeclAttr::MT_To); 11364 D->addAttr(A); 11365 if (ASTMutationListener *ML = SemaRef.Context.getASTMutationListener()) 11366 ML->DeclarationMarkedOpenMPDeclareTarget(D, A); 11367 return; 11368 } 11369 11370 } else if (isa<FunctionDecl>(D)) { 11371 const FunctionDecl *FD = nullptr; 11372 if (cast<FunctionDecl>(D)->hasBody(FD)) 11373 LD = const_cast<FunctionDecl *>(FD); 11374 11375 // If the definition is associated with the current declaration in the 11376 // target region (it can be e.g. a lambda) that is legal and we do not need 11377 // to do anything else. 11378 if (LD == D) { 11379 Attr *A = OMPDeclareTargetDeclAttr::CreateImplicit( 11380 SemaRef.Context, OMPDeclareTargetDeclAttr::MT_To); 11381 D->addAttr(A); 11382 if (ASTMutationListener *ML = SemaRef.Context.getASTMutationListener()) 11383 ML->DeclarationMarkedOpenMPDeclareTarget(D, A); 11384 return; 11385 } 11386 } 11387 if (!LD) 11388 LD = D; 11389 if (LD && !LD->hasAttr<OMPDeclareTargetDeclAttr>() && 11390 (isa<VarDecl>(LD) || isa<FunctionDecl>(LD))) { 11391 // Outlined declaration is not declared target. 11392 if (LD->isOutOfLine()) { 11393 SemaRef.Diag(LD->getLocation(), diag::warn_omp_not_in_target_context); 11394 SemaRef.Diag(SL, diag::note_used_here) << SR; 11395 } else { 11396 DeclContext *DC = LD->getDeclContext(); 11397 while (DC) { 11398 if (isa<FunctionDecl>(DC) && 11399 cast<FunctionDecl>(DC)->hasAttr<OMPDeclareTargetDeclAttr>()) 11400 break; 11401 DC = DC->getParent(); 11402 } 11403 if (DC) 11404 return; 11405 11406 // Is not declared in target context. 11407 SemaRef.Diag(LD->getLocation(), diag::warn_omp_not_in_target_context); 11408 SemaRef.Diag(SL, diag::note_used_here) << SR; 11409 } 11410 // Mark decl as declared target to prevent further diagnostic. 11411 Attr *A = OMPDeclareTargetDeclAttr::CreateImplicit( 11412 SemaRef.Context, OMPDeclareTargetDeclAttr::MT_To); 11413 D->addAttr(A); 11414 if (ASTMutationListener *ML = SemaRef.Context.getASTMutationListener()) 11415 ML->DeclarationMarkedOpenMPDeclareTarget(D, A); 11416 } 11417 } 11418 11419 static bool checkValueDeclInTarget(SourceLocation SL, SourceRange SR, 11420 Sema &SemaRef, DSAStackTy *Stack, 11421 ValueDecl *VD) { 11422 if (VD->hasAttr<OMPDeclareTargetDeclAttr>()) 11423 return true; 11424 if (!CheckTypeMappable(SL, SR, SemaRef, Stack, VD->getType())) 11425 return false; 11426 return true; 11427 } 11428 11429 void Sema::checkDeclIsAllowedInOpenMPTarget(Expr *E, Decl *D) { 11430 if (!D || D->isInvalidDecl()) 11431 return; 11432 SourceRange SR = E ? E->getSourceRange() : D->getSourceRange(); 11433 SourceLocation SL = E ? E->getLocStart() : D->getLocation(); 11434 // 2.10.6: threadprivate variable cannot appear in a declare target directive. 11435 if (VarDecl *VD = dyn_cast<VarDecl>(D)) { 11436 if (DSAStack->isThreadPrivate(VD)) { 11437 Diag(SL, diag::err_omp_threadprivate_in_target); 11438 ReportOriginalDSA(*this, DSAStack, VD, DSAStack->getTopDSA(VD, false)); 11439 return; 11440 } 11441 } 11442 if (ValueDecl *VD = dyn_cast<ValueDecl>(D)) { 11443 // Problem if any with var declared with incomplete type will be reported 11444 // as normal, so no need to check it here. 11445 if ((E || !VD->getType()->isIncompleteType()) && 11446 !checkValueDeclInTarget(SL, SR, *this, DSAStack, VD)) { 11447 // Mark decl as declared target to prevent further diagnostic. 11448 if (isa<VarDecl>(VD) || isa<FunctionDecl>(VD)) { 11449 Attr *A = OMPDeclareTargetDeclAttr::CreateImplicit( 11450 Context, OMPDeclareTargetDeclAttr::MT_To); 11451 VD->addAttr(A); 11452 if (ASTMutationListener *ML = Context.getASTMutationListener()) 11453 ML->DeclarationMarkedOpenMPDeclareTarget(VD, A); 11454 } 11455 return; 11456 } 11457 } 11458 if (!E) { 11459 // Checking declaration inside declare target region. 11460 if (!D->hasAttr<OMPDeclareTargetDeclAttr>() && 11461 (isa<VarDecl>(D) || isa<FunctionDecl>(D))) { 11462 Attr *A = OMPDeclareTargetDeclAttr::CreateImplicit( 11463 Context, OMPDeclareTargetDeclAttr::MT_To); 11464 D->addAttr(A); 11465 if (ASTMutationListener *ML = Context.getASTMutationListener()) 11466 ML->DeclarationMarkedOpenMPDeclareTarget(D, A); 11467 } 11468 return; 11469 } 11470 checkDeclInTargetContext(E->getExprLoc(), E->getSourceRange(), *this, D); 11471 } 11472 11473 OMPClause *Sema::ActOnOpenMPToClause(ArrayRef<Expr *> VarList, 11474 SourceLocation StartLoc, 11475 SourceLocation LParenLoc, 11476 SourceLocation EndLoc) { 11477 MappableVarListInfo MVLI(VarList); 11478 checkMappableExpressionList(*this, DSAStack, OMPC_to, MVLI, StartLoc); 11479 if (MVLI.ProcessedVarList.empty()) 11480 return nullptr; 11481 11482 return OMPToClause::Create(Context, StartLoc, LParenLoc, EndLoc, 11483 MVLI.ProcessedVarList, MVLI.VarBaseDeclarations, 11484 MVLI.VarComponents); 11485 } 11486 11487 OMPClause *Sema::ActOnOpenMPFromClause(ArrayRef<Expr *> VarList, 11488 SourceLocation StartLoc, 11489 SourceLocation LParenLoc, 11490 SourceLocation EndLoc) { 11491 MappableVarListInfo MVLI(VarList); 11492 checkMappableExpressionList(*this, DSAStack, OMPC_from, MVLI, StartLoc); 11493 if (MVLI.ProcessedVarList.empty()) 11494 return nullptr; 11495 11496 return OMPFromClause::Create(Context, StartLoc, LParenLoc, EndLoc, 11497 MVLI.ProcessedVarList, MVLI.VarBaseDeclarations, 11498 MVLI.VarComponents); 11499 } 11500