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 /// Struct that associates a component with the clause kind where they are 76 /// found. 77 struct MappedExprComponentTy { 78 OMPClauseMappableExprCommon::MappableExprComponentLists Components; 79 OpenMPClauseKind Kind = OMPC_unknown; 80 }; 81 typedef llvm::DenseMap<ValueDecl *, MappedExprComponentTy> 82 MappedExprComponentsTy; 83 typedef llvm::StringMap<std::pair<OMPCriticalDirective *, llvm::APSInt>> 84 CriticalsWithHintsTy; 85 typedef llvm::DenseMap<OMPDependClause *, OperatorOffsetTy> 86 DoacrossDependMapTy; 87 88 struct SharingMapTy final { 89 DeclSAMapTy SharingMap; 90 AlignedMapTy AlignedMap; 91 MappedExprComponentsTy MappedExprComponents; 92 LoopControlVariablesMapTy LCVMap; 93 DefaultDataSharingAttributes DefaultAttr = DSA_unspecified; 94 SourceLocation DefaultAttrLoc; 95 OpenMPDirectiveKind Directive = OMPD_unknown; 96 DeclarationNameInfo DirectiveName; 97 Scope *CurScope = nullptr; 98 SourceLocation ConstructLoc; 99 /// Set of 'depend' clauses with 'sink|source' dependence kind. Required to 100 /// get the data (loop counters etc.) about enclosing loop-based construct. 101 /// This data is required during codegen. 102 DoacrossDependMapTy DoacrossDepends; 103 /// \brief first argument (Expr *) contains optional argument of the 104 /// 'ordered' clause, the second one is true if the regions has 'ordered' 105 /// clause, false otherwise. 106 llvm::PointerIntPair<Expr *, 1, bool> OrderedRegion; 107 bool NowaitRegion = false; 108 bool CancelRegion = false; 109 unsigned AssociatedLoops = 1; 110 SourceLocation InnerTeamsRegionLoc; 111 SharingMapTy(OpenMPDirectiveKind DKind, DeclarationNameInfo Name, 112 Scope *CurScope, SourceLocation Loc) 113 : Directive(DKind), DirectiveName(Name), CurScope(CurScope), 114 ConstructLoc(Loc) {} 115 SharingMapTy() {} 116 }; 117 118 typedef SmallVector<SharingMapTy, 4> StackTy; 119 120 /// \brief Stack of used declaration and their data-sharing attributes. 121 StackTy Stack; 122 /// \brief true, if check for DSA must be from parent directive, false, if 123 /// from current directive. 124 OpenMPClauseKind ClauseKindMode = OMPC_unknown; 125 Sema &SemaRef; 126 bool ForceCapturing = false; 127 CriticalsWithHintsTy Criticals; 128 129 typedef SmallVector<SharingMapTy, 8>::reverse_iterator reverse_iterator; 130 131 DSAVarData getDSA(StackTy::reverse_iterator &Iter, ValueDecl *D); 132 133 /// \brief Checks if the variable is a local for OpenMP region. 134 bool isOpenMPLocal(VarDecl *D, StackTy::reverse_iterator Iter); 135 136 public: 137 explicit DSAStackTy(Sema &S) : Stack(1), SemaRef(S) {} 138 139 bool isClauseParsingMode() const { return ClauseKindMode != OMPC_unknown; } 140 void setClauseParsingMode(OpenMPClauseKind K) { ClauseKindMode = K; } 141 142 bool isForceVarCapturing() const { return ForceCapturing; } 143 void setForceVarCapturing(bool V) { ForceCapturing = V; } 144 145 void push(OpenMPDirectiveKind DKind, const DeclarationNameInfo &DirName, 146 Scope *CurScope, SourceLocation Loc) { 147 Stack.push_back(SharingMapTy(DKind, DirName, CurScope, Loc)); 148 Stack.back().DefaultAttrLoc = Loc; 149 } 150 151 void pop() { 152 assert(Stack.size() > 1 && "Data-sharing attributes stack is empty!"); 153 Stack.pop_back(); 154 } 155 156 void addCriticalWithHint(OMPCriticalDirective *D, llvm::APSInt Hint) { 157 Criticals[D->getDirectiveName().getAsString()] = std::make_pair(D, Hint); 158 } 159 const std::pair<OMPCriticalDirective *, llvm::APSInt> 160 getCriticalWithHint(const DeclarationNameInfo &Name) const { 161 auto I = Criticals.find(Name.getAsString()); 162 if (I != Criticals.end()) 163 return I->second; 164 return std::make_pair(nullptr, llvm::APSInt()); 165 } 166 /// \brief If 'aligned' declaration for given variable \a D was not seen yet, 167 /// add it and return NULL; otherwise return previous occurrence's expression 168 /// for diagnostics. 169 Expr *addUniqueAligned(ValueDecl *D, Expr *NewDE); 170 171 /// \brief Register specified variable as loop control variable. 172 void addLoopControlVariable(ValueDecl *D, VarDecl *Capture); 173 /// \brief Check if the specified variable is a loop control variable for 174 /// current region. 175 /// \return The index of the loop control variable in the list of associated 176 /// for-loops (from outer to inner). 177 LCDeclInfo isLoopControlVariable(ValueDecl *D); 178 /// \brief Check if the specified variable is a loop control variable for 179 /// parent region. 180 /// \return The index of the loop control variable in the list of associated 181 /// for-loops (from outer to inner). 182 LCDeclInfo isParentLoopControlVariable(ValueDecl *D); 183 /// \brief Get the loop control variable for the I-th loop (or nullptr) in 184 /// parent directive. 185 ValueDecl *getParentLoopControlVariable(unsigned I); 186 187 /// \brief Adds explicit data sharing attribute to the specified declaration. 188 void addDSA(ValueDecl *D, Expr *E, OpenMPClauseKind A, 189 DeclRefExpr *PrivateCopy = nullptr); 190 191 /// \brief Returns data sharing attributes from top of the stack for the 192 /// specified declaration. 193 DSAVarData getTopDSA(ValueDecl *D, bool FromParent); 194 /// \brief Returns data-sharing attributes for the specified declaration. 195 DSAVarData getImplicitDSA(ValueDecl *D, bool FromParent); 196 /// \brief Checks if the specified variables has data-sharing attributes which 197 /// match specified \a CPred predicate in any directive which matches \a DPred 198 /// predicate. 199 DSAVarData hasDSA(ValueDecl *D, 200 const llvm::function_ref<bool(OpenMPClauseKind)> &CPred, 201 const llvm::function_ref<bool(OpenMPDirectiveKind)> &DPred, 202 bool FromParent); 203 /// \brief Checks if the specified variables has data-sharing attributes which 204 /// match specified \a CPred predicate in any innermost directive which 205 /// matches \a DPred predicate. 206 DSAVarData 207 hasInnermostDSA(ValueDecl *D, 208 const llvm::function_ref<bool(OpenMPClauseKind)> &CPred, 209 const llvm::function_ref<bool(OpenMPDirectiveKind)> &DPred, 210 bool FromParent); 211 /// \brief Checks if the specified variables has explicit data-sharing 212 /// attributes which match specified \a CPred predicate at the specified 213 /// OpenMP region. 214 bool hasExplicitDSA(ValueDecl *D, 215 const llvm::function_ref<bool(OpenMPClauseKind)> &CPred, 216 unsigned Level, bool NotLastprivate = false); 217 218 /// \brief Returns true if the directive at level \Level matches in the 219 /// specified \a DPred predicate. 220 bool hasExplicitDirective( 221 const llvm::function_ref<bool(OpenMPDirectiveKind)> &DPred, 222 unsigned Level); 223 224 /// \brief Finds a directive which matches specified \a DPred predicate. 225 bool hasDirective(const llvm::function_ref<bool(OpenMPDirectiveKind, 226 const DeclarationNameInfo &, 227 SourceLocation)> &DPred, 228 bool FromParent); 229 230 /// \brief Returns currently analyzed directive. 231 OpenMPDirectiveKind getCurrentDirective() const { 232 return Stack.back().Directive; 233 } 234 /// \brief Returns parent directive. 235 OpenMPDirectiveKind getParentDirective() const { 236 if (Stack.size() > 2) 237 return Stack[Stack.size() - 2].Directive; 238 return OMPD_unknown; 239 } 240 241 /// \brief Set default data sharing attribute to none. 242 void setDefaultDSANone(SourceLocation Loc) { 243 Stack.back().DefaultAttr = DSA_none; 244 Stack.back().DefaultAttrLoc = Loc; 245 } 246 /// \brief Set default data sharing attribute to shared. 247 void setDefaultDSAShared(SourceLocation Loc) { 248 Stack.back().DefaultAttr = DSA_shared; 249 Stack.back().DefaultAttrLoc = Loc; 250 } 251 252 DefaultDataSharingAttributes getDefaultDSA() const { 253 return Stack.back().DefaultAttr; 254 } 255 SourceLocation getDefaultDSALocation() const { 256 return Stack.back().DefaultAttrLoc; 257 } 258 259 /// \brief Checks if the specified variable is a threadprivate. 260 bool isThreadPrivate(VarDecl *D) { 261 DSAVarData DVar = getTopDSA(D, false); 262 return isOpenMPThreadPrivate(DVar.CKind); 263 } 264 265 /// \brief Marks current region as ordered (it has an 'ordered' clause). 266 void setOrderedRegion(bool IsOrdered, Expr *Param) { 267 Stack.back().OrderedRegion.setInt(IsOrdered); 268 Stack.back().OrderedRegion.setPointer(Param); 269 } 270 /// \brief Returns true, if parent region is ordered (has associated 271 /// 'ordered' clause), false - otherwise. 272 bool isParentOrderedRegion() const { 273 if (Stack.size() > 2) 274 return Stack[Stack.size() - 2].OrderedRegion.getInt(); 275 return false; 276 } 277 /// \brief Returns optional parameter for the ordered region. 278 Expr *getParentOrderedRegionParam() const { 279 if (Stack.size() > 2) 280 return Stack[Stack.size() - 2].OrderedRegion.getPointer(); 281 return nullptr; 282 } 283 /// \brief Marks current region as nowait (it has a 'nowait' clause). 284 void setNowaitRegion(bool IsNowait = true) { 285 Stack.back().NowaitRegion = IsNowait; 286 } 287 /// \brief Returns true, if parent region is nowait (has associated 288 /// 'nowait' clause), false - otherwise. 289 bool isParentNowaitRegion() const { 290 if (Stack.size() > 2) 291 return Stack[Stack.size() - 2].NowaitRegion; 292 return false; 293 } 294 /// \brief Marks parent region as cancel region. 295 void setParentCancelRegion(bool Cancel = true) { 296 if (Stack.size() > 2) 297 Stack[Stack.size() - 2].CancelRegion = 298 Stack[Stack.size() - 2].CancelRegion || Cancel; 299 } 300 /// \brief Return true if current region has inner cancel construct. 301 bool isCancelRegion() const { return Stack.back().CancelRegion; } 302 303 /// \brief Set collapse value for the region. 304 void setAssociatedLoops(unsigned Val) { Stack.back().AssociatedLoops = Val; } 305 /// \brief Return collapse value for region. 306 unsigned getAssociatedLoops() const { return Stack.back().AssociatedLoops; } 307 308 /// \brief Marks current target region as one with closely nested teams 309 /// region. 310 void setParentTeamsRegionLoc(SourceLocation TeamsRegionLoc) { 311 if (Stack.size() > 2) 312 Stack[Stack.size() - 2].InnerTeamsRegionLoc = TeamsRegionLoc; 313 } 314 /// \brief Returns true, if current region has closely nested teams region. 315 bool hasInnerTeamsRegion() const { 316 return getInnerTeamsRegionLoc().isValid(); 317 } 318 /// \brief Returns location of the nested teams region (if any). 319 SourceLocation getInnerTeamsRegionLoc() const { 320 if (Stack.size() > 1) 321 return Stack.back().InnerTeamsRegionLoc; 322 return SourceLocation(); 323 } 324 325 Scope *getCurScope() const { return Stack.back().CurScope; } 326 Scope *getCurScope() { return Stack.back().CurScope; } 327 SourceLocation getConstructLoc() { return Stack.back().ConstructLoc; } 328 329 /// Do the check specified in \a Check to all component lists and return true 330 /// if any issue is found. 331 bool checkMappableExprComponentListsForDecl( 332 ValueDecl *VD, bool CurrentRegionOnly, 333 const llvm::function_ref< 334 bool(OMPClauseMappableExprCommon::MappableExprComponentListRef, 335 OpenMPClauseKind)> &Check) { 336 auto SI = Stack.rbegin(); 337 auto SE = Stack.rend(); 338 339 if (SI == SE) 340 return false; 341 342 if (CurrentRegionOnly) { 343 SE = std::next(SI); 344 } else { 345 ++SI; 346 } 347 348 for (; SI != SE; ++SI) { 349 auto MI = SI->MappedExprComponents.find(VD); 350 if (MI != SI->MappedExprComponents.end()) 351 for (auto &L : MI->second.Components) 352 if (Check(L, MI->second.Kind)) 353 return true; 354 } 355 return false; 356 } 357 358 /// Create a new mappable expression component list associated with a given 359 /// declaration and initialize it with the provided list of components. 360 void addMappableExpressionComponents( 361 ValueDecl *VD, 362 OMPClauseMappableExprCommon::MappableExprComponentListRef Components, 363 OpenMPClauseKind WhereFoundClauseKind) { 364 assert(Stack.size() > 1 && 365 "Not expecting to retrieve components from a empty stack!"); 366 auto &MEC = Stack.back().MappedExprComponents[VD]; 367 // Create new entry and append the new components there. 368 MEC.Components.resize(MEC.Components.size() + 1); 369 MEC.Components.back().append(Components.begin(), Components.end()); 370 MEC.Kind = WhereFoundClauseKind; 371 } 372 373 unsigned getNestingLevel() const { 374 assert(Stack.size() > 1); 375 return Stack.size() - 2; 376 } 377 void addDoacrossDependClause(OMPDependClause *C, OperatorOffsetTy &OpsOffs) { 378 assert(Stack.size() > 2); 379 assert(isOpenMPWorksharingDirective(Stack[Stack.size() - 2].Directive)); 380 Stack[Stack.size() - 2].DoacrossDepends.insert({C, OpsOffs}); 381 } 382 llvm::iterator_range<DoacrossDependMapTy::const_iterator> 383 getDoacrossDependClauses() const { 384 assert(Stack.size() > 1); 385 if (isOpenMPWorksharingDirective(Stack[Stack.size() - 1].Directive)) { 386 auto &Ref = Stack[Stack.size() - 1].DoacrossDepends; 387 return llvm::make_range(Ref.begin(), Ref.end()); 388 } 389 return llvm::make_range(Stack[0].DoacrossDepends.end(), 390 Stack[0].DoacrossDepends.end()); 391 } 392 }; 393 bool isParallelOrTaskRegion(OpenMPDirectiveKind DKind) { 394 return isOpenMPParallelDirective(DKind) || isOpenMPTaskingDirective(DKind) || 395 isOpenMPTeamsDirective(DKind) || DKind == OMPD_unknown; 396 } 397 } // namespace 398 399 static ValueDecl *getCanonicalDecl(ValueDecl *D) { 400 auto *VD = dyn_cast<VarDecl>(D); 401 auto *FD = dyn_cast<FieldDecl>(D); 402 if (VD != nullptr) { 403 VD = VD->getCanonicalDecl(); 404 D = VD; 405 } else { 406 assert(FD); 407 FD = FD->getCanonicalDecl(); 408 D = FD; 409 } 410 return D; 411 } 412 413 DSAStackTy::DSAVarData DSAStackTy::getDSA(StackTy::reverse_iterator &Iter, 414 ValueDecl *D) { 415 D = getCanonicalDecl(D); 416 auto *VD = dyn_cast<VarDecl>(D); 417 auto *FD = dyn_cast<FieldDecl>(D); 418 DSAVarData DVar; 419 if (Iter == std::prev(Stack.rend())) { 420 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced 421 // in a region but not in construct] 422 // File-scope or namespace-scope variables referenced in called routines 423 // in the region are shared unless they appear in a threadprivate 424 // directive. 425 if (VD && !VD->isFunctionOrMethodVarDecl() && !isa<ParmVarDecl>(D)) 426 DVar.CKind = OMPC_shared; 427 428 // OpenMP [2.9.1.2, Data-sharing Attribute Rules for Variables Referenced 429 // in a region but not in construct] 430 // Variables with static storage duration that are declared in called 431 // routines in the region are shared. 432 if (VD && VD->hasGlobalStorage()) 433 DVar.CKind = OMPC_shared; 434 435 // Non-static data members are shared by default. 436 if (FD) 437 DVar.CKind = OMPC_shared; 438 439 return DVar; 440 } 441 442 DVar.DKind = Iter->Directive; 443 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced 444 // in a Construct, C/C++, predetermined, p.1] 445 // Variables with automatic storage duration that are declared in a scope 446 // inside the construct are private. 447 if (VD && isOpenMPLocal(VD, Iter) && VD->isLocalVarDecl() && 448 (VD->getStorageClass() == SC_Auto || VD->getStorageClass() == SC_None)) { 449 DVar.CKind = OMPC_private; 450 return DVar; 451 } 452 453 // Explicitly specified attributes and local variables with predetermined 454 // attributes. 455 if (Iter->SharingMap.count(D)) { 456 DVar.RefExpr = Iter->SharingMap[D].RefExpr.getPointer(); 457 DVar.PrivateCopy = Iter->SharingMap[D].PrivateCopy; 458 DVar.CKind = Iter->SharingMap[D].Attributes; 459 DVar.ImplicitDSALoc = Iter->DefaultAttrLoc; 460 return DVar; 461 } 462 463 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced 464 // in a Construct, C/C++, implicitly determined, p.1] 465 // In a parallel or task construct, the data-sharing attributes of these 466 // variables are determined by the default clause, if present. 467 switch (Iter->DefaultAttr) { 468 case DSA_shared: 469 DVar.CKind = OMPC_shared; 470 DVar.ImplicitDSALoc = Iter->DefaultAttrLoc; 471 return DVar; 472 case DSA_none: 473 return DVar; 474 case DSA_unspecified: 475 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced 476 // in a Construct, implicitly determined, p.2] 477 // In a parallel construct, if no default clause is present, these 478 // variables are shared. 479 DVar.ImplicitDSALoc = Iter->DefaultAttrLoc; 480 if (isOpenMPParallelDirective(DVar.DKind) || 481 isOpenMPTeamsDirective(DVar.DKind)) { 482 DVar.CKind = OMPC_shared; 483 return DVar; 484 } 485 486 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced 487 // in a Construct, implicitly determined, p.4] 488 // In a task construct, if no default clause is present, a variable that in 489 // the enclosing context is determined to be shared by all implicit tasks 490 // bound to the current team is shared. 491 if (isOpenMPTaskingDirective(DVar.DKind)) { 492 DSAVarData DVarTemp; 493 for (StackTy::reverse_iterator I = std::next(Iter), EE = Stack.rend(); 494 I != EE; ++I) { 495 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables 496 // Referenced in a Construct, implicitly determined, p.6] 497 // In a task construct, if no default clause is present, a variable 498 // whose data-sharing attribute is not determined by the rules above is 499 // firstprivate. 500 DVarTemp = getDSA(I, D); 501 if (DVarTemp.CKind != OMPC_shared) { 502 DVar.RefExpr = nullptr; 503 DVar.CKind = OMPC_firstprivate; 504 return DVar; 505 } 506 if (isParallelOrTaskRegion(I->Directive)) 507 break; 508 } 509 DVar.CKind = 510 (DVarTemp.CKind == OMPC_unknown) ? OMPC_firstprivate : OMPC_shared; 511 return DVar; 512 } 513 } 514 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced 515 // in a Construct, implicitly determined, p.3] 516 // For constructs other than task, if no default clause is present, these 517 // variables inherit their data-sharing attributes from the enclosing 518 // context. 519 return getDSA(++Iter, D); 520 } 521 522 Expr *DSAStackTy::addUniqueAligned(ValueDecl *D, Expr *NewDE) { 523 assert(Stack.size() > 1 && "Data sharing attributes stack is empty"); 524 D = getCanonicalDecl(D); 525 auto It = Stack.back().AlignedMap.find(D); 526 if (It == Stack.back().AlignedMap.end()) { 527 assert(NewDE && "Unexpected nullptr expr to be added into aligned map"); 528 Stack.back().AlignedMap[D] = NewDE; 529 return nullptr; 530 } else { 531 assert(It->second && "Unexpected nullptr expr in the aligned map"); 532 return It->second; 533 } 534 return nullptr; 535 } 536 537 void DSAStackTy::addLoopControlVariable(ValueDecl *D, VarDecl *Capture) { 538 assert(Stack.size() > 1 && "Data-sharing attributes stack is empty"); 539 D = getCanonicalDecl(D); 540 Stack.back().LCVMap.insert( 541 std::make_pair(D, LCDeclInfo(Stack.back().LCVMap.size() + 1, Capture))); 542 } 543 544 DSAStackTy::LCDeclInfo DSAStackTy::isLoopControlVariable(ValueDecl *D) { 545 assert(Stack.size() > 1 && "Data-sharing attributes stack is empty"); 546 D = getCanonicalDecl(D); 547 return Stack.back().LCVMap.count(D) > 0 ? Stack.back().LCVMap[D] 548 : LCDeclInfo(0, nullptr); 549 } 550 551 DSAStackTy::LCDeclInfo DSAStackTy::isParentLoopControlVariable(ValueDecl *D) { 552 assert(Stack.size() > 2 && "Data-sharing attributes stack is empty"); 553 D = getCanonicalDecl(D); 554 return Stack[Stack.size() - 2].LCVMap.count(D) > 0 555 ? Stack[Stack.size() - 2].LCVMap[D] 556 : LCDeclInfo(0, nullptr); 557 } 558 559 ValueDecl *DSAStackTy::getParentLoopControlVariable(unsigned I) { 560 assert(Stack.size() > 2 && "Data-sharing attributes stack is empty"); 561 if (Stack[Stack.size() - 2].LCVMap.size() < I) 562 return nullptr; 563 for (auto &Pair : Stack[Stack.size() - 2].LCVMap) { 564 if (Pair.second.first == I) 565 return Pair.first; 566 } 567 return nullptr; 568 } 569 570 void DSAStackTy::addDSA(ValueDecl *D, Expr *E, OpenMPClauseKind A, 571 DeclRefExpr *PrivateCopy) { 572 D = getCanonicalDecl(D); 573 if (A == OMPC_threadprivate) { 574 auto &Data = Stack[0].SharingMap[D]; 575 Data.Attributes = A; 576 Data.RefExpr.setPointer(E); 577 Data.PrivateCopy = nullptr; 578 } else { 579 assert(Stack.size() > 1 && "Data-sharing attributes stack is empty"); 580 auto &Data = Stack.back().SharingMap[D]; 581 assert(Data.Attributes == OMPC_unknown || (A == Data.Attributes) || 582 (A == OMPC_firstprivate && Data.Attributes == OMPC_lastprivate) || 583 (A == OMPC_lastprivate && Data.Attributes == OMPC_firstprivate) || 584 (isLoopControlVariable(D).first && A == OMPC_private)); 585 if (A == OMPC_lastprivate && Data.Attributes == OMPC_firstprivate) { 586 Data.RefExpr.setInt(/*IntVal=*/true); 587 return; 588 } 589 const bool IsLastprivate = 590 A == OMPC_lastprivate || Data.Attributes == OMPC_lastprivate; 591 Data.Attributes = A; 592 Data.RefExpr.setPointerAndInt(E, IsLastprivate); 593 Data.PrivateCopy = PrivateCopy; 594 if (PrivateCopy) { 595 auto &Data = Stack.back().SharingMap[PrivateCopy->getDecl()]; 596 Data.Attributes = A; 597 Data.RefExpr.setPointerAndInt(PrivateCopy, IsLastprivate); 598 Data.PrivateCopy = nullptr; 599 } 600 } 601 } 602 603 bool DSAStackTy::isOpenMPLocal(VarDecl *D, StackTy::reverse_iterator Iter) { 604 D = D->getCanonicalDecl(); 605 if (Stack.size() > 2) { 606 reverse_iterator I = Iter, E = std::prev(Stack.rend()); 607 Scope *TopScope = nullptr; 608 while (I != E && !isParallelOrTaskRegion(I->Directive)) { 609 ++I; 610 } 611 if (I == E) 612 return false; 613 TopScope = I->CurScope ? I->CurScope->getParent() : nullptr; 614 Scope *CurScope = getCurScope(); 615 while (CurScope != TopScope && !CurScope->isDeclScope(D)) { 616 CurScope = CurScope->getParent(); 617 } 618 return CurScope != TopScope; 619 } 620 return false; 621 } 622 623 /// \brief Build a variable declaration for OpenMP loop iteration variable. 624 static VarDecl *buildVarDecl(Sema &SemaRef, SourceLocation Loc, QualType Type, 625 StringRef Name, const AttrVec *Attrs = nullptr) { 626 DeclContext *DC = SemaRef.CurContext; 627 IdentifierInfo *II = &SemaRef.PP.getIdentifierTable().get(Name); 628 TypeSourceInfo *TInfo = SemaRef.Context.getTrivialTypeSourceInfo(Type, Loc); 629 VarDecl *Decl = 630 VarDecl::Create(SemaRef.Context, DC, Loc, Loc, II, Type, TInfo, SC_None); 631 if (Attrs) { 632 for (specific_attr_iterator<AlignedAttr> I(Attrs->begin()), E(Attrs->end()); 633 I != E; ++I) 634 Decl->addAttr(*I); 635 } 636 Decl->setImplicit(); 637 return Decl; 638 } 639 640 static DeclRefExpr *buildDeclRefExpr(Sema &S, VarDecl *D, QualType Ty, 641 SourceLocation Loc, 642 bool RefersToCapture = false) { 643 D->setReferenced(); 644 D->markUsed(S.Context); 645 return DeclRefExpr::Create(S.getASTContext(), NestedNameSpecifierLoc(), 646 SourceLocation(), D, RefersToCapture, Loc, Ty, 647 VK_LValue); 648 } 649 650 DSAStackTy::DSAVarData DSAStackTy::getTopDSA(ValueDecl *D, bool FromParent) { 651 D = getCanonicalDecl(D); 652 DSAVarData DVar; 653 654 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced 655 // in a Construct, C/C++, predetermined, p.1] 656 // Variables appearing in threadprivate directives are threadprivate. 657 auto *VD = dyn_cast<VarDecl>(D); 658 if ((VD && VD->getTLSKind() != VarDecl::TLS_None && 659 !(VD->hasAttr<OMPThreadPrivateDeclAttr>() && 660 SemaRef.getLangOpts().OpenMPUseTLS && 661 SemaRef.getASTContext().getTargetInfo().isTLSSupported())) || 662 (VD && VD->getStorageClass() == SC_Register && 663 VD->hasAttr<AsmLabelAttr>() && !VD->isLocalVarDecl())) { 664 addDSA(D, buildDeclRefExpr(SemaRef, VD, D->getType().getNonReferenceType(), 665 D->getLocation()), 666 OMPC_threadprivate); 667 } 668 if (Stack[0].SharingMap.count(D)) { 669 DVar.RefExpr = Stack[0].SharingMap[D].RefExpr.getPointer(); 670 DVar.CKind = OMPC_threadprivate; 671 return DVar; 672 } 673 674 if (Stack.size() == 1) { 675 // Not in OpenMP execution region and top scope was already checked. 676 return DVar; 677 } 678 679 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced 680 // in a Construct, C/C++, predetermined, p.4] 681 // Static data members are shared. 682 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced 683 // in a Construct, C/C++, predetermined, p.7] 684 // Variables with static storage duration that are declared in a scope 685 // inside the construct are shared. 686 auto &&MatchesAlways = [](OpenMPDirectiveKind) -> bool { return true; }; 687 if (VD && VD->isStaticDataMember()) { 688 DSAVarData DVarTemp = hasDSA(D, isOpenMPPrivate, MatchesAlways, FromParent); 689 if (DVarTemp.CKind != OMPC_unknown && DVarTemp.RefExpr) 690 return DVar; 691 692 DVar.CKind = OMPC_shared; 693 return DVar; 694 } 695 696 QualType Type = D->getType().getNonReferenceType().getCanonicalType(); 697 bool IsConstant = Type.isConstant(SemaRef.getASTContext()); 698 Type = SemaRef.getASTContext().getBaseElementType(Type); 699 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced 700 // in a Construct, C/C++, predetermined, p.6] 701 // Variables with const qualified type having no mutable member are 702 // shared. 703 CXXRecordDecl *RD = 704 SemaRef.getLangOpts().CPlusPlus ? Type->getAsCXXRecordDecl() : nullptr; 705 if (auto *CTSD = dyn_cast_or_null<ClassTemplateSpecializationDecl>(RD)) 706 if (auto *CTD = CTSD->getSpecializedTemplate()) 707 RD = CTD->getTemplatedDecl(); 708 if (IsConstant && 709 !(SemaRef.getLangOpts().CPlusPlus && RD && RD->hasDefinition() && 710 RD->hasMutableFields())) { 711 // Variables with const-qualified type having no mutable member may be 712 // listed in a firstprivate clause, even if they are static data members. 713 DSAVarData DVarTemp = hasDSA( 714 D, [](OpenMPClauseKind C) -> bool { return C == OMPC_firstprivate; }, 715 MatchesAlways, FromParent); 716 if (DVarTemp.CKind == OMPC_firstprivate && DVarTemp.RefExpr) 717 return DVar; 718 719 DVar.CKind = OMPC_shared; 720 return DVar; 721 } 722 723 // Explicitly specified attributes and local variables with predetermined 724 // attributes. 725 auto StartI = std::next(Stack.rbegin()); 726 auto EndI = std::prev(Stack.rend()); 727 if (FromParent && StartI != EndI) { 728 StartI = std::next(StartI); 729 } 730 auto I = std::prev(StartI); 731 if (I->SharingMap.count(D)) { 732 DVar.RefExpr = I->SharingMap[D].RefExpr.getPointer(); 733 DVar.PrivateCopy = I->SharingMap[D].PrivateCopy; 734 DVar.CKind = I->SharingMap[D].Attributes; 735 DVar.ImplicitDSALoc = I->DefaultAttrLoc; 736 } 737 738 return DVar; 739 } 740 741 DSAStackTy::DSAVarData DSAStackTy::getImplicitDSA(ValueDecl *D, 742 bool FromParent) { 743 D = getCanonicalDecl(D); 744 auto StartI = Stack.rbegin(); 745 auto EndI = std::prev(Stack.rend()); 746 if (FromParent && StartI != EndI) { 747 StartI = std::next(StartI); 748 } 749 return getDSA(StartI, D); 750 } 751 752 DSAStackTy::DSAVarData 753 DSAStackTy::hasDSA(ValueDecl *D, 754 const llvm::function_ref<bool(OpenMPClauseKind)> &CPred, 755 const llvm::function_ref<bool(OpenMPDirectiveKind)> &DPred, 756 bool FromParent) { 757 D = getCanonicalDecl(D); 758 auto StartI = std::next(Stack.rbegin()); 759 auto EndI = Stack.rend(); 760 if (FromParent && StartI != EndI) { 761 StartI = std::next(StartI); 762 } 763 for (auto I = StartI, EE = EndI; I != EE; ++I) { 764 if (!DPred(I->Directive) && !isParallelOrTaskRegion(I->Directive)) 765 continue; 766 DSAVarData DVar = getDSA(I, D); 767 if (CPred(DVar.CKind)) 768 return DVar; 769 } 770 return DSAVarData(); 771 } 772 773 DSAStackTy::DSAVarData DSAStackTy::hasInnermostDSA( 774 ValueDecl *D, const llvm::function_ref<bool(OpenMPClauseKind)> &CPred, 775 const llvm::function_ref<bool(OpenMPDirectiveKind)> &DPred, 776 bool FromParent) { 777 D = getCanonicalDecl(D); 778 auto StartI = std::next(Stack.rbegin()); 779 auto EndI = Stack.rend(); 780 if (FromParent && StartI != EndI) 781 StartI = std::next(StartI); 782 if (StartI == EndI || !DPred(StartI->Directive)) 783 return DSAVarData(); 784 DSAVarData DVar = getDSA(StartI, D); 785 return CPred(DVar.CKind) ? DVar : 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 if (Ty->isReferenceType()) 907 Ty = Ty->castAs<ReferenceType>()->getPointeeType(); 908 909 // Locate map clauses and see if the variable being captured is referred to 910 // in any of those clauses. Here we only care about variables, not fields, 911 // because fields are part of aggregates. 912 bool IsVariableUsedInMapClause = false; 913 bool IsVariableAssociatedWithSection = false; 914 915 DSAStack->checkMappableExprComponentListsForDecl( 916 D, /*CurrentRegionOnly=*/true, 917 [&](OMPClauseMappableExprCommon::MappableExprComponentListRef 918 MapExprComponents, 919 OpenMPClauseKind WhereFoundClauseKind) { 920 // Only the map clause information influences how a variable is 921 // captured. E.g. is_device_ptr does not require changing the default 922 // behavior. 923 if (WhereFoundClauseKind != OMPC_map) 924 return false; 925 926 auto EI = MapExprComponents.rbegin(); 927 auto EE = MapExprComponents.rend(); 928 929 assert(EI != EE && "Invalid map expression!"); 930 931 if (isa<DeclRefExpr>(EI->getAssociatedExpression())) 932 IsVariableUsedInMapClause |= EI->getAssociatedDeclaration() == D; 933 934 ++EI; 935 if (EI == EE) 936 return false; 937 938 if (isa<ArraySubscriptExpr>(EI->getAssociatedExpression()) || 939 isa<OMPArraySectionExpr>(EI->getAssociatedExpression()) || 940 isa<MemberExpr>(EI->getAssociatedExpression())) { 941 IsVariableAssociatedWithSection = true; 942 // There is nothing more we need to know about this variable. 943 return true; 944 } 945 946 // Keep looking for more map info. 947 return false; 948 }); 949 950 if (IsVariableUsedInMapClause) { 951 // If variable is identified in a map clause it is always captured by 952 // reference except if it is a pointer that is dereferenced somehow. 953 IsByRef = !(Ty->isPointerType() && IsVariableAssociatedWithSection); 954 } else { 955 // By default, all the data that has a scalar type is mapped by copy. 956 IsByRef = !Ty->isScalarType(); 957 } 958 } 959 960 if (IsByRef && Ty.getNonReferenceType()->isScalarType()) { 961 IsByRef = !DSAStack->hasExplicitDSA( 962 D, [](OpenMPClauseKind K) -> bool { return K == OMPC_firstprivate; }, 963 Level, /*NotLastprivate=*/true); 964 } 965 966 // When passing data by copy, we need to make sure it fits the uintptr size 967 // and alignment, because the runtime library only deals with uintptr types. 968 // If it does not fit the uintptr size, we need to pass the data by reference 969 // instead. 970 if (!IsByRef && 971 (Ctx.getTypeSizeInChars(Ty) > 972 Ctx.getTypeSizeInChars(Ctx.getUIntPtrType()) || 973 Ctx.getDeclAlign(D) > Ctx.getTypeAlignInChars(Ctx.getUIntPtrType()))) { 974 IsByRef = true; 975 } 976 977 return IsByRef; 978 } 979 980 unsigned Sema::getOpenMPNestingLevel() const { 981 assert(getLangOpts().OpenMP); 982 return DSAStack->getNestingLevel(); 983 } 984 985 VarDecl *Sema::IsOpenMPCapturedDecl(ValueDecl *D) { 986 assert(LangOpts.OpenMP && "OpenMP is not allowed"); 987 D = getCanonicalDecl(D); 988 989 // If we are attempting to capture a global variable in a directive with 990 // 'target' we return true so that this global is also mapped to the device. 991 // 992 // FIXME: If the declaration is enclosed in a 'declare target' directive, 993 // then it should not be captured. Therefore, an extra check has to be 994 // inserted here once support for 'declare target' is added. 995 // 996 auto *VD = dyn_cast<VarDecl>(D); 997 if (VD && !VD->hasLocalStorage()) { 998 if (DSAStack->getCurrentDirective() == OMPD_target && 999 !DSAStack->isClauseParsingMode()) 1000 return VD; 1001 if (DSAStack->hasDirective( 1002 [](OpenMPDirectiveKind K, const DeclarationNameInfo &, 1003 SourceLocation) -> bool { 1004 return isOpenMPTargetExecutionDirective(K); 1005 }, 1006 false)) 1007 return VD; 1008 } 1009 1010 if (DSAStack->getCurrentDirective() != OMPD_unknown && 1011 (!DSAStack->isClauseParsingMode() || 1012 DSAStack->getParentDirective() != OMPD_unknown)) { 1013 auto &&Info = DSAStack->isLoopControlVariable(D); 1014 if (Info.first || 1015 (VD && VD->hasLocalStorage() && 1016 isParallelOrTaskRegion(DSAStack->getCurrentDirective())) || 1017 (VD && DSAStack->isForceVarCapturing())) 1018 return VD ? VD : Info.second; 1019 auto DVarPrivate = DSAStack->getTopDSA(D, DSAStack->isClauseParsingMode()); 1020 if (DVarPrivate.CKind != OMPC_unknown && isOpenMPPrivate(DVarPrivate.CKind)) 1021 return VD ? VD : cast<VarDecl>(DVarPrivate.PrivateCopy->getDecl()); 1022 DVarPrivate = DSAStack->hasDSA( 1023 D, isOpenMPPrivate, [](OpenMPDirectiveKind) -> bool { return true; }, 1024 DSAStack->isClauseParsingMode()); 1025 if (DVarPrivate.CKind != OMPC_unknown) 1026 return VD ? VD : cast<VarDecl>(DVarPrivate.PrivateCopy->getDecl()); 1027 } 1028 return nullptr; 1029 } 1030 1031 bool Sema::isOpenMPPrivateDecl(ValueDecl *D, unsigned Level) { 1032 assert(LangOpts.OpenMP && "OpenMP is not allowed"); 1033 return DSAStack->hasExplicitDSA( 1034 D, [](OpenMPClauseKind K) -> bool { return K == OMPC_private; }, Level); 1035 } 1036 1037 bool Sema::isOpenMPTargetCapturedDecl(ValueDecl *D, unsigned Level) { 1038 assert(LangOpts.OpenMP && "OpenMP is not allowed"); 1039 // Return true if the current level is no longer enclosed in a target region. 1040 1041 auto *VD = dyn_cast<VarDecl>(D); 1042 return VD && !VD->hasLocalStorage() && 1043 DSAStack->hasExplicitDirective(isOpenMPTargetExecutionDirective, 1044 Level); 1045 } 1046 1047 void Sema::DestroyDataSharingAttributesStack() { delete DSAStack; } 1048 1049 void Sema::StartOpenMPDSABlock(OpenMPDirectiveKind DKind, 1050 const DeclarationNameInfo &DirName, 1051 Scope *CurScope, SourceLocation Loc) { 1052 DSAStack->push(DKind, DirName, CurScope, Loc); 1053 PushExpressionEvaluationContext(PotentiallyEvaluated); 1054 } 1055 1056 void Sema::StartOpenMPClause(OpenMPClauseKind K) { 1057 DSAStack->setClauseParsingMode(K); 1058 } 1059 1060 void Sema::EndOpenMPClause() { 1061 DSAStack->setClauseParsingMode(/*K=*/OMPC_unknown); 1062 } 1063 1064 void Sema::EndOpenMPDSABlock(Stmt *CurDirective) { 1065 // OpenMP [2.14.3.5, Restrictions, C/C++, p.1] 1066 // A variable of class type (or array thereof) that appears in a lastprivate 1067 // clause requires an accessible, unambiguous default constructor for the 1068 // class type, unless the list item is also specified in a firstprivate 1069 // clause. 1070 if (auto *D = dyn_cast_or_null<OMPExecutableDirective>(CurDirective)) { 1071 for (auto *C : D->clauses()) { 1072 if (auto *Clause = dyn_cast<OMPLastprivateClause>(C)) { 1073 SmallVector<Expr *, 8> PrivateCopies; 1074 for (auto *DE : Clause->varlists()) { 1075 if (DE->isValueDependent() || DE->isTypeDependent()) { 1076 PrivateCopies.push_back(nullptr); 1077 continue; 1078 } 1079 auto *DRE = cast<DeclRefExpr>(DE->IgnoreParens()); 1080 VarDecl *VD = cast<VarDecl>(DRE->getDecl()); 1081 QualType Type = VD->getType().getNonReferenceType(); 1082 auto DVar = DSAStack->getTopDSA(VD, false); 1083 if (DVar.CKind == OMPC_lastprivate) { 1084 // Generate helper private variable and initialize it with the 1085 // default value. The address of the original variable is replaced 1086 // by the address of the new private variable in CodeGen. This new 1087 // variable is not added to IdResolver, so the code in the OpenMP 1088 // region uses original variable for proper diagnostics. 1089 auto *VDPrivate = buildVarDecl( 1090 *this, DE->getExprLoc(), Type.getUnqualifiedType(), 1091 VD->getName(), VD->hasAttrs() ? &VD->getAttrs() : nullptr); 1092 ActOnUninitializedDecl(VDPrivate); 1093 if (VDPrivate->isInvalidDecl()) 1094 continue; 1095 PrivateCopies.push_back(buildDeclRefExpr( 1096 *this, VDPrivate, DE->getType(), DE->getExprLoc())); 1097 } else { 1098 // The variable is also a firstprivate, so initialization sequence 1099 // for private copy is generated already. 1100 PrivateCopies.push_back(nullptr); 1101 } 1102 } 1103 // Set initializers to private copies if no errors were found. 1104 if (PrivateCopies.size() == Clause->varlist_size()) 1105 Clause->setPrivateCopies(PrivateCopies); 1106 } 1107 } 1108 } 1109 1110 DSAStack->pop(); 1111 DiscardCleanupsInEvaluationContext(); 1112 PopExpressionEvaluationContext(); 1113 } 1114 1115 static bool FinishOpenMPLinearClause(OMPLinearClause &Clause, DeclRefExpr *IV, 1116 Expr *NumIterations, Sema &SemaRef, 1117 Scope *S, DSAStackTy *Stack); 1118 1119 namespace { 1120 1121 class VarDeclFilterCCC : public CorrectionCandidateCallback { 1122 private: 1123 Sema &SemaRef; 1124 1125 public: 1126 explicit VarDeclFilterCCC(Sema &S) : SemaRef(S) {} 1127 bool ValidateCandidate(const TypoCorrection &Candidate) override { 1128 NamedDecl *ND = Candidate.getCorrectionDecl(); 1129 if (auto *VD = dyn_cast_or_null<VarDecl>(ND)) { 1130 return VD->hasGlobalStorage() && 1131 SemaRef.isDeclInScope(ND, SemaRef.getCurLexicalContext(), 1132 SemaRef.getCurScope()); 1133 } 1134 return false; 1135 } 1136 }; 1137 1138 class VarOrFuncDeclFilterCCC : public CorrectionCandidateCallback { 1139 private: 1140 Sema &SemaRef; 1141 1142 public: 1143 explicit VarOrFuncDeclFilterCCC(Sema &S) : SemaRef(S) {} 1144 bool ValidateCandidate(const TypoCorrection &Candidate) override { 1145 NamedDecl *ND = Candidate.getCorrectionDecl(); 1146 if (isa<VarDecl>(ND) || isa<FunctionDecl>(ND)) { 1147 return SemaRef.isDeclInScope(ND, SemaRef.getCurLexicalContext(), 1148 SemaRef.getCurScope()); 1149 } 1150 return false; 1151 } 1152 }; 1153 1154 } // namespace 1155 1156 ExprResult Sema::ActOnOpenMPIdExpression(Scope *CurScope, 1157 CXXScopeSpec &ScopeSpec, 1158 const DeclarationNameInfo &Id) { 1159 LookupResult Lookup(*this, Id, LookupOrdinaryName); 1160 LookupParsedName(Lookup, CurScope, &ScopeSpec, true); 1161 1162 if (Lookup.isAmbiguous()) 1163 return ExprError(); 1164 1165 VarDecl *VD; 1166 if (!Lookup.isSingleResult()) { 1167 if (TypoCorrection Corrected = CorrectTypo( 1168 Id, LookupOrdinaryName, CurScope, nullptr, 1169 llvm::make_unique<VarDeclFilterCCC>(*this), CTK_ErrorRecovery)) { 1170 diagnoseTypo(Corrected, 1171 PDiag(Lookup.empty() 1172 ? diag::err_undeclared_var_use_suggest 1173 : diag::err_omp_expected_var_arg_suggest) 1174 << Id.getName()); 1175 VD = Corrected.getCorrectionDeclAs<VarDecl>(); 1176 } else { 1177 Diag(Id.getLoc(), Lookup.empty() ? diag::err_undeclared_var_use 1178 : diag::err_omp_expected_var_arg) 1179 << Id.getName(); 1180 return ExprError(); 1181 } 1182 } else { 1183 if (!(VD = Lookup.getAsSingle<VarDecl>())) { 1184 Diag(Id.getLoc(), diag::err_omp_expected_var_arg) << Id.getName(); 1185 Diag(Lookup.getFoundDecl()->getLocation(), diag::note_declared_at); 1186 return ExprError(); 1187 } 1188 } 1189 Lookup.suppressDiagnostics(); 1190 1191 // OpenMP [2.9.2, Syntax, C/C++] 1192 // Variables must be file-scope, namespace-scope, or static block-scope. 1193 if (!VD->hasGlobalStorage()) { 1194 Diag(Id.getLoc(), diag::err_omp_global_var_arg) 1195 << getOpenMPDirectiveName(OMPD_threadprivate) << !VD->isStaticLocal(); 1196 bool IsDecl = 1197 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly; 1198 Diag(VD->getLocation(), 1199 IsDecl ? diag::note_previous_decl : diag::note_defined_here) 1200 << VD; 1201 return ExprError(); 1202 } 1203 1204 VarDecl *CanonicalVD = VD->getCanonicalDecl(); 1205 NamedDecl *ND = cast<NamedDecl>(CanonicalVD); 1206 // OpenMP [2.9.2, Restrictions, C/C++, p.2] 1207 // A threadprivate directive for file-scope variables must appear outside 1208 // any definition or declaration. 1209 if (CanonicalVD->getDeclContext()->isTranslationUnit() && 1210 !getCurLexicalContext()->isTranslationUnit()) { 1211 Diag(Id.getLoc(), diag::err_omp_var_scope) 1212 << getOpenMPDirectiveName(OMPD_threadprivate) << VD; 1213 bool IsDecl = 1214 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly; 1215 Diag(VD->getLocation(), 1216 IsDecl ? diag::note_previous_decl : diag::note_defined_here) 1217 << VD; 1218 return ExprError(); 1219 } 1220 // OpenMP [2.9.2, Restrictions, C/C++, p.3] 1221 // A threadprivate directive for static class member variables must appear 1222 // in the class definition, in the same scope in which the member 1223 // variables are declared. 1224 if (CanonicalVD->isStaticDataMember() && 1225 !CanonicalVD->getDeclContext()->Equals(getCurLexicalContext())) { 1226 Diag(Id.getLoc(), diag::err_omp_var_scope) 1227 << getOpenMPDirectiveName(OMPD_threadprivate) << VD; 1228 bool IsDecl = 1229 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly; 1230 Diag(VD->getLocation(), 1231 IsDecl ? diag::note_previous_decl : diag::note_defined_here) 1232 << VD; 1233 return ExprError(); 1234 } 1235 // OpenMP [2.9.2, Restrictions, C/C++, p.4] 1236 // A threadprivate directive for namespace-scope variables must appear 1237 // outside any definition or declaration other than the namespace 1238 // definition itself. 1239 if (CanonicalVD->getDeclContext()->isNamespace() && 1240 (!getCurLexicalContext()->isFileContext() || 1241 !getCurLexicalContext()->Encloses(CanonicalVD->getDeclContext()))) { 1242 Diag(Id.getLoc(), diag::err_omp_var_scope) 1243 << getOpenMPDirectiveName(OMPD_threadprivate) << VD; 1244 bool IsDecl = 1245 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly; 1246 Diag(VD->getLocation(), 1247 IsDecl ? diag::note_previous_decl : diag::note_defined_here) 1248 << VD; 1249 return ExprError(); 1250 } 1251 // OpenMP [2.9.2, Restrictions, C/C++, p.6] 1252 // A threadprivate directive for static block-scope variables must appear 1253 // in the scope of the variable and not in a nested scope. 1254 if (CanonicalVD->isStaticLocal() && CurScope && 1255 !isDeclInScope(ND, getCurLexicalContext(), CurScope)) { 1256 Diag(Id.getLoc(), diag::err_omp_var_scope) 1257 << getOpenMPDirectiveName(OMPD_threadprivate) << VD; 1258 bool IsDecl = 1259 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly; 1260 Diag(VD->getLocation(), 1261 IsDecl ? diag::note_previous_decl : diag::note_defined_here) 1262 << VD; 1263 return ExprError(); 1264 } 1265 1266 // OpenMP [2.9.2, Restrictions, C/C++, p.2-6] 1267 // A threadprivate directive must lexically precede all references to any 1268 // of the variables in its list. 1269 if (VD->isUsed() && !DSAStack->isThreadPrivate(VD)) { 1270 Diag(Id.getLoc(), diag::err_omp_var_used) 1271 << getOpenMPDirectiveName(OMPD_threadprivate) << VD; 1272 return ExprError(); 1273 } 1274 1275 QualType ExprType = VD->getType().getNonReferenceType(); 1276 return DeclRefExpr::Create(Context, NestedNameSpecifierLoc(), 1277 SourceLocation(), VD, 1278 /*RefersToEnclosingVariableOrCapture=*/false, 1279 Id.getLoc(), ExprType, VK_LValue); 1280 } 1281 1282 Sema::DeclGroupPtrTy 1283 Sema::ActOnOpenMPThreadprivateDirective(SourceLocation Loc, 1284 ArrayRef<Expr *> VarList) { 1285 if (OMPThreadPrivateDecl *D = CheckOMPThreadPrivateDecl(Loc, VarList)) { 1286 CurContext->addDecl(D); 1287 return DeclGroupPtrTy::make(DeclGroupRef(D)); 1288 } 1289 return nullptr; 1290 } 1291 1292 namespace { 1293 class LocalVarRefChecker : public ConstStmtVisitor<LocalVarRefChecker, bool> { 1294 Sema &SemaRef; 1295 1296 public: 1297 bool VisitDeclRefExpr(const DeclRefExpr *E) { 1298 if (auto *VD = dyn_cast<VarDecl>(E->getDecl())) { 1299 if (VD->hasLocalStorage()) { 1300 SemaRef.Diag(E->getLocStart(), 1301 diag::err_omp_local_var_in_threadprivate_init) 1302 << E->getSourceRange(); 1303 SemaRef.Diag(VD->getLocation(), diag::note_defined_here) 1304 << VD << VD->getSourceRange(); 1305 return true; 1306 } 1307 } 1308 return false; 1309 } 1310 bool VisitStmt(const Stmt *S) { 1311 for (auto Child : S->children()) { 1312 if (Child && Visit(Child)) 1313 return true; 1314 } 1315 return false; 1316 } 1317 explicit LocalVarRefChecker(Sema &SemaRef) : SemaRef(SemaRef) {} 1318 }; 1319 } // namespace 1320 1321 OMPThreadPrivateDecl * 1322 Sema::CheckOMPThreadPrivateDecl(SourceLocation Loc, ArrayRef<Expr *> VarList) { 1323 SmallVector<Expr *, 8> Vars; 1324 for (auto &RefExpr : VarList) { 1325 DeclRefExpr *DE = cast<DeclRefExpr>(RefExpr); 1326 VarDecl *VD = cast<VarDecl>(DE->getDecl()); 1327 SourceLocation ILoc = DE->getExprLoc(); 1328 1329 // Mark variable as used. 1330 VD->setReferenced(); 1331 VD->markUsed(Context); 1332 1333 QualType QType = VD->getType(); 1334 if (QType->isDependentType() || QType->isInstantiationDependentType()) { 1335 // It will be analyzed later. 1336 Vars.push_back(DE); 1337 continue; 1338 } 1339 1340 // OpenMP [2.9.2, Restrictions, C/C++, p.10] 1341 // A threadprivate variable must not have an incomplete type. 1342 if (RequireCompleteType(ILoc, VD->getType(), 1343 diag::err_omp_threadprivate_incomplete_type)) { 1344 continue; 1345 } 1346 1347 // OpenMP [2.9.2, Restrictions, C/C++, p.10] 1348 // A threadprivate variable must not have a reference type. 1349 if (VD->getType()->isReferenceType()) { 1350 Diag(ILoc, diag::err_omp_ref_type_arg) 1351 << getOpenMPDirectiveName(OMPD_threadprivate) << VD->getType(); 1352 bool IsDecl = 1353 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly; 1354 Diag(VD->getLocation(), 1355 IsDecl ? diag::note_previous_decl : diag::note_defined_here) 1356 << VD; 1357 continue; 1358 } 1359 1360 // Check if this is a TLS variable. If TLS is not being supported, produce 1361 // the corresponding diagnostic. 1362 if ((VD->getTLSKind() != VarDecl::TLS_None && 1363 !(VD->hasAttr<OMPThreadPrivateDeclAttr>() && 1364 getLangOpts().OpenMPUseTLS && 1365 getASTContext().getTargetInfo().isTLSSupported())) || 1366 (VD->getStorageClass() == SC_Register && VD->hasAttr<AsmLabelAttr>() && 1367 !VD->isLocalVarDecl())) { 1368 Diag(ILoc, diag::err_omp_var_thread_local) 1369 << VD << ((VD->getTLSKind() != VarDecl::TLS_None) ? 0 : 1); 1370 bool IsDecl = 1371 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly; 1372 Diag(VD->getLocation(), 1373 IsDecl ? diag::note_previous_decl : diag::note_defined_here) 1374 << VD; 1375 continue; 1376 } 1377 1378 // Check if initial value of threadprivate variable reference variable with 1379 // local storage (it is not supported by runtime). 1380 if (auto Init = VD->getAnyInitializer()) { 1381 LocalVarRefChecker Checker(*this); 1382 if (Checker.Visit(Init)) 1383 continue; 1384 } 1385 1386 Vars.push_back(RefExpr); 1387 DSAStack->addDSA(VD, DE, OMPC_threadprivate); 1388 VD->addAttr(OMPThreadPrivateDeclAttr::CreateImplicit( 1389 Context, SourceRange(Loc, Loc))); 1390 if (auto *ML = Context.getASTMutationListener()) 1391 ML->DeclarationMarkedOpenMPThreadPrivate(VD); 1392 } 1393 OMPThreadPrivateDecl *D = nullptr; 1394 if (!Vars.empty()) { 1395 D = OMPThreadPrivateDecl::Create(Context, getCurLexicalContext(), Loc, 1396 Vars); 1397 D->setAccess(AS_public); 1398 } 1399 return D; 1400 } 1401 1402 static void ReportOriginalDSA(Sema &SemaRef, DSAStackTy *Stack, 1403 const ValueDecl *D, DSAStackTy::DSAVarData DVar, 1404 bool IsLoopIterVar = false) { 1405 if (DVar.RefExpr) { 1406 SemaRef.Diag(DVar.RefExpr->getExprLoc(), diag::note_omp_explicit_dsa) 1407 << getOpenMPClauseName(DVar.CKind); 1408 return; 1409 } 1410 enum { 1411 PDSA_StaticMemberShared, 1412 PDSA_StaticLocalVarShared, 1413 PDSA_LoopIterVarPrivate, 1414 PDSA_LoopIterVarLinear, 1415 PDSA_LoopIterVarLastprivate, 1416 PDSA_ConstVarShared, 1417 PDSA_GlobalVarShared, 1418 PDSA_TaskVarFirstprivate, 1419 PDSA_LocalVarPrivate, 1420 PDSA_Implicit 1421 } Reason = PDSA_Implicit; 1422 bool ReportHint = false; 1423 auto ReportLoc = D->getLocation(); 1424 auto *VD = dyn_cast<VarDecl>(D); 1425 if (IsLoopIterVar) { 1426 if (DVar.CKind == OMPC_private) 1427 Reason = PDSA_LoopIterVarPrivate; 1428 else if (DVar.CKind == OMPC_lastprivate) 1429 Reason = PDSA_LoopIterVarLastprivate; 1430 else 1431 Reason = PDSA_LoopIterVarLinear; 1432 } else if (isOpenMPTaskingDirective(DVar.DKind) && 1433 DVar.CKind == OMPC_firstprivate) { 1434 Reason = PDSA_TaskVarFirstprivate; 1435 ReportLoc = DVar.ImplicitDSALoc; 1436 } else if (VD && VD->isStaticLocal()) 1437 Reason = PDSA_StaticLocalVarShared; 1438 else if (VD && VD->isStaticDataMember()) 1439 Reason = PDSA_StaticMemberShared; 1440 else if (VD && VD->isFileVarDecl()) 1441 Reason = PDSA_GlobalVarShared; 1442 else if (D->getType().isConstant(SemaRef.getASTContext())) 1443 Reason = PDSA_ConstVarShared; 1444 else if (VD && VD->isLocalVarDecl() && DVar.CKind == OMPC_private) { 1445 ReportHint = true; 1446 Reason = PDSA_LocalVarPrivate; 1447 } 1448 if (Reason != PDSA_Implicit) { 1449 SemaRef.Diag(ReportLoc, diag::note_omp_predetermined_dsa) 1450 << Reason << ReportHint 1451 << getOpenMPDirectiveName(Stack->getCurrentDirective()); 1452 } else if (DVar.ImplicitDSALoc.isValid()) { 1453 SemaRef.Diag(DVar.ImplicitDSALoc, diag::note_omp_implicit_dsa) 1454 << getOpenMPClauseName(DVar.CKind); 1455 } 1456 } 1457 1458 namespace { 1459 class DSAAttrChecker : public StmtVisitor<DSAAttrChecker, void> { 1460 DSAStackTy *Stack; 1461 Sema &SemaRef; 1462 bool ErrorFound; 1463 CapturedStmt *CS; 1464 llvm::SmallVector<Expr *, 8> ImplicitFirstprivate; 1465 llvm::DenseMap<ValueDecl *, Expr *> VarsWithInheritedDSA; 1466 1467 public: 1468 void VisitDeclRefExpr(DeclRefExpr *E) { 1469 if (E->isTypeDependent() || E->isValueDependent() || 1470 E->containsUnexpandedParameterPack() || E->isInstantiationDependent()) 1471 return; 1472 if (auto *VD = dyn_cast<VarDecl>(E->getDecl())) { 1473 // Skip internally declared variables. 1474 if (VD->isLocalVarDecl() && !CS->capturesVariable(VD)) 1475 return; 1476 1477 auto DVar = Stack->getTopDSA(VD, false); 1478 // Check if the variable has explicit DSA set and stop analysis if it so. 1479 if (DVar.RefExpr) 1480 return; 1481 1482 auto ELoc = E->getExprLoc(); 1483 auto DKind = Stack->getCurrentDirective(); 1484 // The default(none) clause requires that each variable that is referenced 1485 // in the construct, and does not have a predetermined data-sharing 1486 // attribute, must have its data-sharing attribute explicitly determined 1487 // by being listed in a data-sharing attribute clause. 1488 if (DVar.CKind == OMPC_unknown && Stack->getDefaultDSA() == DSA_none && 1489 isParallelOrTaskRegion(DKind) && 1490 VarsWithInheritedDSA.count(VD) == 0) { 1491 VarsWithInheritedDSA[VD] = E; 1492 return; 1493 } 1494 1495 // OpenMP [2.9.3.6, Restrictions, p.2] 1496 // A list item that appears in a reduction clause of the innermost 1497 // enclosing worksharing or parallel construct may not be accessed in an 1498 // explicit task. 1499 DVar = Stack->hasInnermostDSA( 1500 VD, [](OpenMPClauseKind C) -> bool { return C == OMPC_reduction; }, 1501 [](OpenMPDirectiveKind K) -> bool { 1502 return isOpenMPParallelDirective(K) || 1503 isOpenMPWorksharingDirective(K) || isOpenMPTeamsDirective(K); 1504 }, 1505 false); 1506 if (isOpenMPTaskingDirective(DKind) && DVar.CKind == OMPC_reduction) { 1507 ErrorFound = true; 1508 SemaRef.Diag(ELoc, diag::err_omp_reduction_in_task); 1509 ReportOriginalDSA(SemaRef, Stack, VD, DVar); 1510 return; 1511 } 1512 1513 // Define implicit data-sharing attributes for task. 1514 DVar = Stack->getImplicitDSA(VD, false); 1515 if (isOpenMPTaskingDirective(DKind) && DVar.CKind != OMPC_shared && 1516 !Stack->isLoopControlVariable(VD).first) 1517 ImplicitFirstprivate.push_back(E); 1518 } 1519 } 1520 void VisitMemberExpr(MemberExpr *E) { 1521 if (E->isTypeDependent() || E->isValueDependent() || 1522 E->containsUnexpandedParameterPack() || E->isInstantiationDependent()) 1523 return; 1524 if (isa<CXXThisExpr>(E->getBase()->IgnoreParens())) { 1525 if (auto *FD = dyn_cast<FieldDecl>(E->getMemberDecl())) { 1526 auto DVar = Stack->getTopDSA(FD, false); 1527 // Check if the variable has explicit DSA set and stop analysis if it 1528 // so. 1529 if (DVar.RefExpr) 1530 return; 1531 1532 auto ELoc = E->getExprLoc(); 1533 auto DKind = Stack->getCurrentDirective(); 1534 // OpenMP [2.9.3.6, Restrictions, p.2] 1535 // A list item that appears in a reduction clause of the innermost 1536 // enclosing worksharing or parallel construct may not be accessed in 1537 // an explicit task. 1538 DVar = Stack->hasInnermostDSA( 1539 FD, [](OpenMPClauseKind C) -> bool { return C == OMPC_reduction; }, 1540 [](OpenMPDirectiveKind K) -> bool { 1541 return isOpenMPParallelDirective(K) || 1542 isOpenMPWorksharingDirective(K) || 1543 isOpenMPTeamsDirective(K); 1544 }, 1545 false); 1546 if (isOpenMPTaskingDirective(DKind) && DVar.CKind == OMPC_reduction) { 1547 ErrorFound = true; 1548 SemaRef.Diag(ELoc, diag::err_omp_reduction_in_task); 1549 ReportOriginalDSA(SemaRef, Stack, FD, DVar); 1550 return; 1551 } 1552 1553 // Define implicit data-sharing attributes for task. 1554 DVar = Stack->getImplicitDSA(FD, false); 1555 if (isOpenMPTaskingDirective(DKind) && DVar.CKind != OMPC_shared && 1556 !Stack->isLoopControlVariable(FD).first) 1557 ImplicitFirstprivate.push_back(E); 1558 } 1559 } else 1560 Visit(E->getBase()); 1561 } 1562 void VisitOMPExecutableDirective(OMPExecutableDirective *S) { 1563 for (auto *C : S->clauses()) { 1564 // Skip analysis of arguments of implicitly defined firstprivate clause 1565 // for task directives. 1566 if (C && (!isa<OMPFirstprivateClause>(C) || C->getLocStart().isValid())) 1567 for (auto *CC : C->children()) { 1568 if (CC) 1569 Visit(CC); 1570 } 1571 } 1572 } 1573 void VisitStmt(Stmt *S) { 1574 for (auto *C : S->children()) { 1575 if (C && !isa<OMPExecutableDirective>(C)) 1576 Visit(C); 1577 } 1578 } 1579 1580 bool isErrorFound() { return ErrorFound; } 1581 ArrayRef<Expr *> getImplicitFirstprivate() { return ImplicitFirstprivate; } 1582 llvm::DenseMap<ValueDecl *, Expr *> &getVarsWithInheritedDSA() { 1583 return VarsWithInheritedDSA; 1584 } 1585 1586 DSAAttrChecker(DSAStackTy *S, Sema &SemaRef, CapturedStmt *CS) 1587 : Stack(S), SemaRef(SemaRef), ErrorFound(false), CS(CS) {} 1588 }; 1589 } // namespace 1590 1591 void Sema::ActOnOpenMPRegionStart(OpenMPDirectiveKind DKind, Scope *CurScope) { 1592 switch (DKind) { 1593 case OMPD_parallel: 1594 case OMPD_parallel_for: 1595 case OMPD_parallel_for_simd: 1596 case OMPD_parallel_sections: 1597 case OMPD_teams: 1598 case OMPD_target_teams: { 1599 QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1); 1600 QualType KmpInt32PtrTy = 1601 Context.getPointerType(KmpInt32Ty).withConst().withRestrict(); 1602 Sema::CapturedParamNameType Params[] = { 1603 std::make_pair(".global_tid.", KmpInt32PtrTy), 1604 std::make_pair(".bound_tid.", KmpInt32PtrTy), 1605 std::make_pair(StringRef(), QualType()) // __context with shared vars 1606 }; 1607 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP, 1608 Params); 1609 break; 1610 } 1611 case OMPD_target_parallel: { 1612 Sema::CapturedParamNameType ParamsTarget[] = { 1613 std::make_pair(StringRef(), QualType()) // __context with shared vars 1614 }; 1615 // Start a captured region for 'target' with no implicit parameters. 1616 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP, 1617 ParamsTarget); 1618 QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1); 1619 QualType KmpInt32PtrTy = 1620 Context.getPointerType(KmpInt32Ty).withConst().withRestrict(); 1621 Sema::CapturedParamNameType ParamsParallel[] = { 1622 std::make_pair(".global_tid.", KmpInt32PtrTy), 1623 std::make_pair(".bound_tid.", KmpInt32PtrTy), 1624 std::make_pair(StringRef(), QualType()) // __context with shared vars 1625 }; 1626 // Start a captured region for 'parallel'. 1627 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP, 1628 ParamsParallel); 1629 break; 1630 } 1631 case OMPD_simd: 1632 case OMPD_for: 1633 case OMPD_for_simd: 1634 case OMPD_sections: 1635 case OMPD_section: 1636 case OMPD_single: 1637 case OMPD_master: 1638 case OMPD_critical: 1639 case OMPD_taskgroup: 1640 case OMPD_distribute: 1641 case OMPD_ordered: 1642 case OMPD_atomic: 1643 case OMPD_target_data: 1644 case OMPD_target: 1645 case OMPD_target_parallel_for: 1646 case OMPD_target_parallel_for_simd: 1647 case OMPD_target_simd: { 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_task: { 1656 QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1); 1657 QualType Args[] = {Context.VoidPtrTy.withConst().withRestrict()}; 1658 FunctionProtoType::ExtProtoInfo EPI; 1659 EPI.Variadic = true; 1660 QualType CopyFnType = Context.getFunctionType(Context.VoidTy, Args, EPI); 1661 Sema::CapturedParamNameType Params[] = { 1662 std::make_pair(".global_tid.", KmpInt32Ty), 1663 std::make_pair(".part_id.", Context.getPointerType(KmpInt32Ty)), 1664 std::make_pair(".privates.", Context.VoidPtrTy.withConst()), 1665 std::make_pair(".copy_fn.", 1666 Context.getPointerType(CopyFnType).withConst()), 1667 std::make_pair(".task_t.", Context.VoidPtrTy.withConst()), 1668 std::make_pair(StringRef(), QualType()) // __context with shared vars 1669 }; 1670 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP, 1671 Params); 1672 // Mark this captured region as inlined, because we don't use outlined 1673 // function directly. 1674 getCurCapturedRegion()->TheCapturedDecl->addAttr( 1675 AlwaysInlineAttr::CreateImplicit( 1676 Context, AlwaysInlineAttr::Keyword_forceinline, SourceRange())); 1677 break; 1678 } 1679 case OMPD_taskloop: 1680 case OMPD_taskloop_simd: { 1681 QualType KmpInt32Ty = 1682 Context.getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/1); 1683 QualType KmpUInt64Ty = 1684 Context.getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/0); 1685 QualType KmpInt64Ty = 1686 Context.getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/1); 1687 QualType Args[] = {Context.VoidPtrTy.withConst().withRestrict()}; 1688 FunctionProtoType::ExtProtoInfo EPI; 1689 EPI.Variadic = true; 1690 QualType CopyFnType = Context.getFunctionType(Context.VoidTy, Args, EPI); 1691 Sema::CapturedParamNameType Params[] = { 1692 std::make_pair(".global_tid.", KmpInt32Ty), 1693 std::make_pair(".part_id.", Context.getPointerType(KmpInt32Ty)), 1694 std::make_pair(".privates.", 1695 Context.VoidPtrTy.withConst().withRestrict()), 1696 std::make_pair( 1697 ".copy_fn.", 1698 Context.getPointerType(CopyFnType).withConst().withRestrict()), 1699 std::make_pair(".task_t.", Context.VoidPtrTy.withConst()), 1700 std::make_pair(".lb.", KmpUInt64Ty), 1701 std::make_pair(".ub.", KmpUInt64Ty), std::make_pair(".st.", KmpInt64Ty), 1702 std::make_pair(".liter.", KmpInt32Ty), 1703 std::make_pair(StringRef(), QualType()) // __context with shared vars 1704 }; 1705 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP, 1706 Params); 1707 // Mark this captured region as inlined, because we don't use outlined 1708 // function directly. 1709 getCurCapturedRegion()->TheCapturedDecl->addAttr( 1710 AlwaysInlineAttr::CreateImplicit( 1711 Context, AlwaysInlineAttr::Keyword_forceinline, SourceRange())); 1712 break; 1713 } 1714 case OMPD_distribute_parallel_for_simd: 1715 case OMPD_distribute_simd: 1716 case OMPD_distribute_parallel_for: 1717 case OMPD_teams_distribute: 1718 case OMPD_teams_distribute_simd: 1719 case OMPD_teams_distribute_parallel_for_simd: 1720 case OMPD_teams_distribute_parallel_for: 1721 case OMPD_target_teams_distribute: 1722 case OMPD_target_teams_distribute_parallel_for: 1723 case OMPD_target_teams_distribute_parallel_for_simd: 1724 case OMPD_target_teams_distribute_simd: { 1725 QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1); 1726 QualType KmpInt32PtrTy = 1727 Context.getPointerType(KmpInt32Ty).withConst().withRestrict(); 1728 Sema::CapturedParamNameType Params[] = { 1729 std::make_pair(".global_tid.", KmpInt32PtrTy), 1730 std::make_pair(".bound_tid.", KmpInt32PtrTy), 1731 std::make_pair(".previous.lb.", Context.getSizeType()), 1732 std::make_pair(".previous.ub.", Context.getSizeType()), 1733 std::make_pair(StringRef(), QualType()) // __context with shared vars 1734 }; 1735 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP, 1736 Params); 1737 break; 1738 } 1739 case OMPD_threadprivate: 1740 case OMPD_taskyield: 1741 case OMPD_barrier: 1742 case OMPD_taskwait: 1743 case OMPD_cancellation_point: 1744 case OMPD_cancel: 1745 case OMPD_flush: 1746 case OMPD_target_enter_data: 1747 case OMPD_target_exit_data: 1748 case OMPD_declare_reduction: 1749 case OMPD_declare_simd: 1750 case OMPD_declare_target: 1751 case OMPD_end_declare_target: 1752 case OMPD_target_update: 1753 llvm_unreachable("OpenMP Directive is not allowed"); 1754 case OMPD_unknown: 1755 llvm_unreachable("Unknown OpenMP directive"); 1756 } 1757 } 1758 1759 int Sema::getOpenMPCaptureLevels(OpenMPDirectiveKind DKind) { 1760 SmallVector<OpenMPDirectiveKind, 4> CaptureRegions; 1761 getOpenMPCaptureRegions(CaptureRegions, DKind); 1762 return CaptureRegions.size(); 1763 } 1764 1765 static OMPCapturedExprDecl *buildCaptureDecl(Sema &S, IdentifierInfo *Id, 1766 Expr *CaptureExpr, bool WithInit, 1767 bool AsExpression) { 1768 assert(CaptureExpr); 1769 ASTContext &C = S.getASTContext(); 1770 Expr *Init = AsExpression ? CaptureExpr : CaptureExpr->IgnoreImpCasts(); 1771 QualType Ty = Init->getType(); 1772 if (CaptureExpr->getObjectKind() == OK_Ordinary && CaptureExpr->isGLValue()) { 1773 if (S.getLangOpts().CPlusPlus) 1774 Ty = C.getLValueReferenceType(Ty); 1775 else { 1776 Ty = C.getPointerType(Ty); 1777 ExprResult Res = 1778 S.CreateBuiltinUnaryOp(CaptureExpr->getExprLoc(), UO_AddrOf, Init); 1779 if (!Res.isUsable()) 1780 return nullptr; 1781 Init = Res.get(); 1782 } 1783 WithInit = true; 1784 } 1785 auto *CED = OMPCapturedExprDecl::Create(C, S.CurContext, Id, Ty, 1786 CaptureExpr->getLocStart()); 1787 if (!WithInit) 1788 CED->addAttr(OMPCaptureNoInitAttr::CreateImplicit(C, SourceRange())); 1789 S.CurContext->addHiddenDecl(CED); 1790 S.AddInitializerToDecl(CED, Init, /*DirectInit=*/false); 1791 return CED; 1792 } 1793 1794 static DeclRefExpr *buildCapture(Sema &S, ValueDecl *D, Expr *CaptureExpr, 1795 bool WithInit) { 1796 OMPCapturedExprDecl *CD; 1797 if (auto *VD = S.IsOpenMPCapturedDecl(D)) 1798 CD = cast<OMPCapturedExprDecl>(VD); 1799 else 1800 CD = buildCaptureDecl(S, D->getIdentifier(), CaptureExpr, WithInit, 1801 /*AsExpression=*/false); 1802 return buildDeclRefExpr(S, CD, CD->getType().getNonReferenceType(), 1803 CaptureExpr->getExprLoc()); 1804 } 1805 1806 static ExprResult buildCapture(Sema &S, Expr *CaptureExpr, DeclRefExpr *&Ref) { 1807 if (!Ref) { 1808 auto *CD = 1809 buildCaptureDecl(S, &S.getASTContext().Idents.get(".capture_expr."), 1810 CaptureExpr, /*WithInit=*/true, /*AsExpression=*/true); 1811 Ref = buildDeclRefExpr(S, CD, CD->getType().getNonReferenceType(), 1812 CaptureExpr->getExprLoc()); 1813 } 1814 ExprResult Res = Ref; 1815 if (!S.getLangOpts().CPlusPlus && 1816 CaptureExpr->getObjectKind() == OK_Ordinary && CaptureExpr->isGLValue() && 1817 Ref->getType()->isPointerType()) 1818 Res = S.CreateBuiltinUnaryOp(CaptureExpr->getExprLoc(), UO_Deref, Ref); 1819 if (!Res.isUsable()) 1820 return ExprError(); 1821 return CaptureExpr->isGLValue() ? Res : S.DefaultLvalueConversion(Res.get()); 1822 } 1823 1824 namespace { 1825 // OpenMP directives parsed in this section are represented as a 1826 // CapturedStatement with an associated statement. If a syntax error 1827 // is detected during the parsing of the associated statement, the 1828 // compiler must abort processing and close the CapturedStatement. 1829 // 1830 // Combined directives such as 'target parallel' have more than one 1831 // nested CapturedStatements. This RAII ensures that we unwind out 1832 // of all the nested CapturedStatements when an error is found. 1833 class CaptureRegionUnwinderRAII { 1834 private: 1835 Sema &S; 1836 bool &ErrorFound; 1837 OpenMPDirectiveKind DKind; 1838 1839 public: 1840 CaptureRegionUnwinderRAII(Sema &S, bool &ErrorFound, 1841 OpenMPDirectiveKind DKind) 1842 : S(S), ErrorFound(ErrorFound), DKind(DKind) {} 1843 ~CaptureRegionUnwinderRAII() { 1844 if (ErrorFound) { 1845 int ThisCaptureLevel = S.getOpenMPCaptureLevels(DKind); 1846 while (--ThisCaptureLevel >= 0) 1847 S.ActOnCapturedRegionError(); 1848 } 1849 } 1850 }; 1851 } // namespace 1852 1853 StmtResult Sema::ActOnOpenMPRegionEnd(StmtResult S, 1854 ArrayRef<OMPClause *> Clauses) { 1855 bool ErrorFound = false; 1856 CaptureRegionUnwinderRAII CaptureRegionUnwinder( 1857 *this, ErrorFound, DSAStack->getCurrentDirective()); 1858 if (!S.isUsable()) { 1859 ErrorFound = true; 1860 return StmtError(); 1861 } 1862 1863 OMPOrderedClause *OC = nullptr; 1864 OMPScheduleClause *SC = nullptr; 1865 SmallVector<OMPLinearClause *, 4> LCs; 1866 SmallVector<OMPClauseWithPreInit *, 8> PICs; 1867 // This is required for proper codegen. 1868 for (auto *Clause : Clauses) { 1869 if (isOpenMPPrivate(Clause->getClauseKind()) || 1870 Clause->getClauseKind() == OMPC_copyprivate || 1871 (getLangOpts().OpenMPUseTLS && 1872 getASTContext().getTargetInfo().isTLSSupported() && 1873 Clause->getClauseKind() == OMPC_copyin)) { 1874 DSAStack->setForceVarCapturing(Clause->getClauseKind() == OMPC_copyin); 1875 // Mark all variables in private list clauses as used in inner region. 1876 for (auto *VarRef : Clause->children()) { 1877 if (auto *E = cast_or_null<Expr>(VarRef)) { 1878 MarkDeclarationsReferencedInExpr(E); 1879 } 1880 } 1881 DSAStack->setForceVarCapturing(/*V=*/false); 1882 } else if (isParallelOrTaskRegion(DSAStack->getCurrentDirective())) { 1883 if (auto *C = OMPClauseWithPreInit::get(Clause)) 1884 PICs.push_back(C); 1885 if (auto *C = OMPClauseWithPostUpdate::get(Clause)) { 1886 if (auto *E = C->getPostUpdateExpr()) 1887 MarkDeclarationsReferencedInExpr(E); 1888 } 1889 } 1890 if (Clause->getClauseKind() == OMPC_schedule) 1891 SC = cast<OMPScheduleClause>(Clause); 1892 else if (Clause->getClauseKind() == OMPC_ordered) 1893 OC = cast<OMPOrderedClause>(Clause); 1894 else if (Clause->getClauseKind() == OMPC_linear) 1895 LCs.push_back(cast<OMPLinearClause>(Clause)); 1896 } 1897 // OpenMP, 2.7.1 Loop Construct, Restrictions 1898 // The nonmonotonic modifier cannot be specified if an ordered clause is 1899 // specified. 1900 if (SC && 1901 (SC->getFirstScheduleModifier() == OMPC_SCHEDULE_MODIFIER_nonmonotonic || 1902 SC->getSecondScheduleModifier() == 1903 OMPC_SCHEDULE_MODIFIER_nonmonotonic) && 1904 OC) { 1905 Diag(SC->getFirstScheduleModifier() == OMPC_SCHEDULE_MODIFIER_nonmonotonic 1906 ? SC->getFirstScheduleModifierLoc() 1907 : SC->getSecondScheduleModifierLoc(), 1908 diag::err_omp_schedule_nonmonotonic_ordered) 1909 << SourceRange(OC->getLocStart(), OC->getLocEnd()); 1910 ErrorFound = true; 1911 } 1912 if (!LCs.empty() && OC && OC->getNumForLoops()) { 1913 for (auto *C : LCs) { 1914 Diag(C->getLocStart(), diag::err_omp_linear_ordered) 1915 << SourceRange(OC->getLocStart(), OC->getLocEnd()); 1916 } 1917 ErrorFound = true; 1918 } 1919 if (isOpenMPWorksharingDirective(DSAStack->getCurrentDirective()) && 1920 isOpenMPSimdDirective(DSAStack->getCurrentDirective()) && OC && 1921 OC->getNumForLoops()) { 1922 Diag(OC->getLocStart(), diag::err_omp_ordered_simd) 1923 << getOpenMPDirectiveName(DSAStack->getCurrentDirective()); 1924 ErrorFound = true; 1925 } 1926 if (ErrorFound) { 1927 return StmtError(); 1928 } 1929 StmtResult SR = S; 1930 SmallVector<OpenMPDirectiveKind, 4> CaptureRegions; 1931 getOpenMPCaptureRegions(CaptureRegions, DSAStack->getCurrentDirective()); 1932 for (auto ThisCaptureRegion : llvm::reverse(CaptureRegions)) { 1933 // Mark all variables in private list clauses as used in inner region. 1934 // Required for proper codegen of combined directives. 1935 // TODO: add processing for other clauses. 1936 if (isParallelOrTaskRegion(DSAStack->getCurrentDirective())) { 1937 for (auto *C : PICs) { 1938 OpenMPDirectiveKind CaptureRegion = C->getCaptureRegion(); 1939 // Find the particular capture region for the clause if the 1940 // directive is a combined one with multiple capture regions. 1941 // If the directive is not a combined one, the capture region 1942 // associated with the clause is OMPD_unknown and is generated 1943 // only once. 1944 if (CaptureRegion == ThisCaptureRegion || 1945 CaptureRegion == OMPD_unknown) { 1946 if (auto *DS = cast_or_null<DeclStmt>(C->getPreInitStmt())) { 1947 for (auto *D : DS->decls()) 1948 MarkVariableReferenced(D->getLocation(), cast<VarDecl>(D)); 1949 } 1950 } 1951 } 1952 } 1953 SR = ActOnCapturedRegionEnd(SR.get()); 1954 } 1955 return SR; 1956 } 1957 1958 static bool CheckNestingOfRegions(Sema &SemaRef, DSAStackTy *Stack, 1959 OpenMPDirectiveKind CurrentRegion, 1960 const DeclarationNameInfo &CurrentName, 1961 OpenMPDirectiveKind CancelRegion, 1962 SourceLocation StartLoc) { 1963 if (Stack->getCurScope()) { 1964 auto ParentRegion = Stack->getParentDirective(); 1965 auto OffendingRegion = ParentRegion; 1966 bool NestingProhibited = false; 1967 bool CloseNesting = true; 1968 bool OrphanSeen = false; 1969 enum { 1970 NoRecommend, 1971 ShouldBeInParallelRegion, 1972 ShouldBeInOrderedRegion, 1973 ShouldBeInTargetRegion, 1974 ShouldBeInTeamsRegion 1975 } Recommend = NoRecommend; 1976 if (isOpenMPSimdDirective(ParentRegion) && CurrentRegion != OMPD_ordered) { 1977 // OpenMP [2.16, Nesting of Regions] 1978 // OpenMP constructs may not be nested inside a simd region. 1979 // OpenMP [2.8.1,simd Construct, Restrictions] 1980 // An ordered construct with the simd clause is the only OpenMP 1981 // construct that can appear in the simd region. 1982 // Allowing a SIMD construct nested in another SIMD construct is an 1983 // extension. The OpenMP 4.5 spec does not allow it. Issue a warning 1984 // message. 1985 SemaRef.Diag(StartLoc, (CurrentRegion != OMPD_simd) 1986 ? diag::err_omp_prohibited_region_simd 1987 : diag::warn_omp_nesting_simd); 1988 return CurrentRegion != OMPD_simd; 1989 } 1990 if (ParentRegion == OMPD_atomic) { 1991 // OpenMP [2.16, Nesting of Regions] 1992 // OpenMP constructs may not be nested inside an atomic region. 1993 SemaRef.Diag(StartLoc, diag::err_omp_prohibited_region_atomic); 1994 return true; 1995 } 1996 if (CurrentRegion == OMPD_section) { 1997 // OpenMP [2.7.2, sections Construct, Restrictions] 1998 // Orphaned section directives are prohibited. That is, the section 1999 // directives must appear within the sections construct and must not be 2000 // encountered elsewhere in the sections region. 2001 if (ParentRegion != OMPD_sections && 2002 ParentRegion != OMPD_parallel_sections) { 2003 SemaRef.Diag(StartLoc, diag::err_omp_orphaned_section_directive) 2004 << (ParentRegion != OMPD_unknown) 2005 << getOpenMPDirectiveName(ParentRegion); 2006 return true; 2007 } 2008 return false; 2009 } 2010 // Allow some constructs (except teams) to be orphaned (they could be 2011 // used in functions, called from OpenMP regions with the required 2012 // preconditions). 2013 if (ParentRegion == OMPD_unknown && 2014 !isOpenMPNestingTeamsDirective(CurrentRegion)) 2015 return false; 2016 if (CurrentRegion == OMPD_cancellation_point || 2017 CurrentRegion == OMPD_cancel) { 2018 // OpenMP [2.16, Nesting of Regions] 2019 // A cancellation point construct for which construct-type-clause is 2020 // taskgroup must be nested inside a task construct. A cancellation 2021 // point construct for which construct-type-clause is not taskgroup must 2022 // be closely nested inside an OpenMP construct that matches the type 2023 // specified in construct-type-clause. 2024 // A cancel construct for which construct-type-clause is taskgroup must be 2025 // nested inside a task construct. A cancel construct for which 2026 // construct-type-clause is not taskgroup must be closely nested inside an 2027 // OpenMP construct that matches the type specified in 2028 // construct-type-clause. 2029 NestingProhibited = 2030 !((CancelRegion == OMPD_parallel && 2031 (ParentRegion == OMPD_parallel || 2032 ParentRegion == OMPD_target_parallel)) || 2033 (CancelRegion == OMPD_for && 2034 (ParentRegion == OMPD_for || ParentRegion == OMPD_parallel_for || 2035 ParentRegion == OMPD_target_parallel_for)) || 2036 (CancelRegion == OMPD_taskgroup && ParentRegion == OMPD_task) || 2037 (CancelRegion == OMPD_sections && 2038 (ParentRegion == OMPD_section || ParentRegion == OMPD_sections || 2039 ParentRegion == OMPD_parallel_sections))); 2040 } else if (CurrentRegion == OMPD_master) { 2041 // OpenMP [2.16, Nesting of Regions] 2042 // A master region may not be closely nested inside a worksharing, 2043 // atomic, or explicit task region. 2044 NestingProhibited = isOpenMPWorksharingDirective(ParentRegion) || 2045 isOpenMPTaskingDirective(ParentRegion); 2046 } else if (CurrentRegion == OMPD_critical && CurrentName.getName()) { 2047 // OpenMP [2.16, Nesting of Regions] 2048 // A critical region may not be nested (closely or otherwise) inside a 2049 // critical region with the same name. Note that this restriction is not 2050 // sufficient to prevent deadlock. 2051 SourceLocation PreviousCriticalLoc; 2052 bool DeadLock = Stack->hasDirective( 2053 [CurrentName, &PreviousCriticalLoc](OpenMPDirectiveKind K, 2054 const DeclarationNameInfo &DNI, 2055 SourceLocation Loc) -> bool { 2056 if (K == OMPD_critical && DNI.getName() == CurrentName.getName()) { 2057 PreviousCriticalLoc = Loc; 2058 return true; 2059 } else 2060 return false; 2061 }, 2062 false /* skip top directive */); 2063 if (DeadLock) { 2064 SemaRef.Diag(StartLoc, 2065 diag::err_omp_prohibited_region_critical_same_name) 2066 << CurrentName.getName(); 2067 if (PreviousCriticalLoc.isValid()) 2068 SemaRef.Diag(PreviousCriticalLoc, 2069 diag::note_omp_previous_critical_region); 2070 return true; 2071 } 2072 } else if (CurrentRegion == OMPD_barrier) { 2073 // OpenMP [2.16, Nesting of Regions] 2074 // A barrier region may not be closely nested inside a worksharing, 2075 // explicit task, critical, ordered, atomic, or master region. 2076 NestingProhibited = isOpenMPWorksharingDirective(ParentRegion) || 2077 isOpenMPTaskingDirective(ParentRegion) || 2078 ParentRegion == OMPD_master || 2079 ParentRegion == OMPD_critical || 2080 ParentRegion == OMPD_ordered; 2081 } else if (isOpenMPWorksharingDirective(CurrentRegion) && 2082 !isOpenMPParallelDirective(CurrentRegion) && 2083 !isOpenMPTeamsDirective(CurrentRegion)) { 2084 // OpenMP [2.16, Nesting of Regions] 2085 // A worksharing region may not be closely nested inside a worksharing, 2086 // explicit task, critical, ordered, atomic, or master region. 2087 NestingProhibited = isOpenMPWorksharingDirective(ParentRegion) || 2088 isOpenMPTaskingDirective(ParentRegion) || 2089 ParentRegion == OMPD_master || 2090 ParentRegion == OMPD_critical || 2091 ParentRegion == OMPD_ordered; 2092 Recommend = ShouldBeInParallelRegion; 2093 } else if (CurrentRegion == OMPD_ordered) { 2094 // OpenMP [2.16, Nesting of Regions] 2095 // An ordered region may not be closely nested inside a critical, 2096 // atomic, or explicit task region. 2097 // An ordered region must be closely nested inside a loop region (or 2098 // parallel loop region) with an ordered clause. 2099 // OpenMP [2.8.1,simd Construct, Restrictions] 2100 // An ordered construct with the simd clause is the only OpenMP construct 2101 // that can appear in the simd region. 2102 NestingProhibited = ParentRegion == OMPD_critical || 2103 isOpenMPTaskingDirective(ParentRegion) || 2104 !(isOpenMPSimdDirective(ParentRegion) || 2105 Stack->isParentOrderedRegion()); 2106 Recommend = ShouldBeInOrderedRegion; 2107 } else if (isOpenMPNestingTeamsDirective(CurrentRegion)) { 2108 // OpenMP [2.16, Nesting of Regions] 2109 // If specified, a teams construct must be contained within a target 2110 // construct. 2111 NestingProhibited = ParentRegion != OMPD_target; 2112 OrphanSeen = ParentRegion == OMPD_unknown; 2113 Recommend = ShouldBeInTargetRegion; 2114 Stack->setParentTeamsRegionLoc(Stack->getConstructLoc()); 2115 } 2116 if (!NestingProhibited && 2117 !isOpenMPTargetExecutionDirective(CurrentRegion) && 2118 !isOpenMPTargetDataManagementDirective(CurrentRegion) && 2119 (ParentRegion == OMPD_teams || ParentRegion == OMPD_target_teams)) { 2120 // OpenMP [2.16, Nesting of Regions] 2121 // distribute, parallel, parallel sections, parallel workshare, and the 2122 // parallel loop and parallel loop SIMD constructs are the only OpenMP 2123 // constructs that can be closely nested in the teams region. 2124 NestingProhibited = !isOpenMPParallelDirective(CurrentRegion) && 2125 !isOpenMPDistributeDirective(CurrentRegion); 2126 Recommend = ShouldBeInParallelRegion; 2127 } 2128 if (!NestingProhibited && 2129 isOpenMPNestingDistributeDirective(CurrentRegion)) { 2130 // OpenMP 4.5 [2.17 Nesting of Regions] 2131 // The region associated with the distribute construct must be strictly 2132 // nested inside a teams region 2133 NestingProhibited = 2134 (ParentRegion != OMPD_teams && ParentRegion != OMPD_target_teams); 2135 Recommend = ShouldBeInTeamsRegion; 2136 } 2137 if (!NestingProhibited && 2138 (isOpenMPTargetExecutionDirective(CurrentRegion) || 2139 isOpenMPTargetDataManagementDirective(CurrentRegion))) { 2140 // OpenMP 4.5 [2.17 Nesting of Regions] 2141 // If a target, target update, target data, target enter data, or 2142 // target exit data construct is encountered during execution of a 2143 // target region, the behavior is unspecified. 2144 NestingProhibited = Stack->hasDirective( 2145 [&OffendingRegion](OpenMPDirectiveKind K, const DeclarationNameInfo &, 2146 SourceLocation) -> bool { 2147 if (isOpenMPTargetExecutionDirective(K)) { 2148 OffendingRegion = K; 2149 return true; 2150 } else 2151 return false; 2152 }, 2153 false /* don't skip top directive */); 2154 CloseNesting = false; 2155 } 2156 if (NestingProhibited) { 2157 if (OrphanSeen) { 2158 SemaRef.Diag(StartLoc, diag::err_omp_orphaned_device_directive) 2159 << getOpenMPDirectiveName(CurrentRegion) << Recommend; 2160 } else { 2161 SemaRef.Diag(StartLoc, diag::err_omp_prohibited_region) 2162 << CloseNesting << getOpenMPDirectiveName(OffendingRegion) 2163 << Recommend << getOpenMPDirectiveName(CurrentRegion); 2164 } 2165 return true; 2166 } 2167 } 2168 return false; 2169 } 2170 2171 static bool checkIfClauses(Sema &S, OpenMPDirectiveKind Kind, 2172 ArrayRef<OMPClause *> Clauses, 2173 ArrayRef<OpenMPDirectiveKind> AllowedNameModifiers) { 2174 bool ErrorFound = false; 2175 unsigned NamedModifiersNumber = 0; 2176 SmallVector<const OMPIfClause *, OMPC_unknown + 1> FoundNameModifiers( 2177 OMPD_unknown + 1); 2178 SmallVector<SourceLocation, 4> NameModifierLoc; 2179 for (const auto *C : Clauses) { 2180 if (const auto *IC = dyn_cast_or_null<OMPIfClause>(C)) { 2181 // At most one if clause without a directive-name-modifier can appear on 2182 // the directive. 2183 OpenMPDirectiveKind CurNM = IC->getNameModifier(); 2184 if (FoundNameModifiers[CurNM]) { 2185 S.Diag(C->getLocStart(), diag::err_omp_more_one_clause) 2186 << getOpenMPDirectiveName(Kind) << getOpenMPClauseName(OMPC_if) 2187 << (CurNM != OMPD_unknown) << getOpenMPDirectiveName(CurNM); 2188 ErrorFound = true; 2189 } else if (CurNM != OMPD_unknown) { 2190 NameModifierLoc.push_back(IC->getNameModifierLoc()); 2191 ++NamedModifiersNumber; 2192 } 2193 FoundNameModifiers[CurNM] = IC; 2194 if (CurNM == OMPD_unknown) 2195 continue; 2196 // Check if the specified name modifier is allowed for the current 2197 // directive. 2198 // At most one if clause with the particular directive-name-modifier can 2199 // appear on the directive. 2200 bool MatchFound = false; 2201 for (auto NM : AllowedNameModifiers) { 2202 if (CurNM == NM) { 2203 MatchFound = true; 2204 break; 2205 } 2206 } 2207 if (!MatchFound) { 2208 S.Diag(IC->getNameModifierLoc(), 2209 diag::err_omp_wrong_if_directive_name_modifier) 2210 << getOpenMPDirectiveName(CurNM) << getOpenMPDirectiveName(Kind); 2211 ErrorFound = true; 2212 } 2213 } 2214 } 2215 // If any if clause on the directive includes a directive-name-modifier then 2216 // all if clauses on the directive must include a directive-name-modifier. 2217 if (FoundNameModifiers[OMPD_unknown] && NamedModifiersNumber > 0) { 2218 if (NamedModifiersNumber == AllowedNameModifiers.size()) { 2219 S.Diag(FoundNameModifiers[OMPD_unknown]->getLocStart(), 2220 diag::err_omp_no_more_if_clause); 2221 } else { 2222 std::string Values; 2223 std::string Sep(", "); 2224 unsigned AllowedCnt = 0; 2225 unsigned TotalAllowedNum = 2226 AllowedNameModifiers.size() - NamedModifiersNumber; 2227 for (unsigned Cnt = 0, End = AllowedNameModifiers.size(); Cnt < End; 2228 ++Cnt) { 2229 OpenMPDirectiveKind NM = AllowedNameModifiers[Cnt]; 2230 if (!FoundNameModifiers[NM]) { 2231 Values += "'"; 2232 Values += getOpenMPDirectiveName(NM); 2233 Values += "'"; 2234 if (AllowedCnt + 2 == TotalAllowedNum) 2235 Values += " or "; 2236 else if (AllowedCnt + 1 != TotalAllowedNum) 2237 Values += Sep; 2238 ++AllowedCnt; 2239 } 2240 } 2241 S.Diag(FoundNameModifiers[OMPD_unknown]->getCondition()->getLocStart(), 2242 diag::err_omp_unnamed_if_clause) 2243 << (TotalAllowedNum > 1) << Values; 2244 } 2245 for (auto Loc : NameModifierLoc) { 2246 S.Diag(Loc, diag::note_omp_previous_named_if_clause); 2247 } 2248 ErrorFound = true; 2249 } 2250 return ErrorFound; 2251 } 2252 2253 StmtResult Sema::ActOnOpenMPExecutableDirective( 2254 OpenMPDirectiveKind Kind, const DeclarationNameInfo &DirName, 2255 OpenMPDirectiveKind CancelRegion, ArrayRef<OMPClause *> Clauses, 2256 Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc) { 2257 StmtResult Res = StmtError(); 2258 if (CheckNestingOfRegions(*this, DSAStack, Kind, DirName, CancelRegion, 2259 StartLoc)) 2260 return StmtError(); 2261 2262 llvm::SmallVector<OMPClause *, 8> ClausesWithImplicit; 2263 llvm::DenseMap<ValueDecl *, Expr *> VarsWithInheritedDSA; 2264 bool ErrorFound = false; 2265 ClausesWithImplicit.append(Clauses.begin(), Clauses.end()); 2266 if (AStmt) { 2267 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected"); 2268 2269 // Check default data sharing attributes for referenced variables. 2270 DSAAttrChecker DSAChecker(DSAStack, *this, cast<CapturedStmt>(AStmt)); 2271 DSAChecker.Visit(cast<CapturedStmt>(AStmt)->getCapturedStmt()); 2272 if (DSAChecker.isErrorFound()) 2273 return StmtError(); 2274 // Generate list of implicitly defined firstprivate variables. 2275 VarsWithInheritedDSA = DSAChecker.getVarsWithInheritedDSA(); 2276 2277 if (!DSAChecker.getImplicitFirstprivate().empty()) { 2278 if (OMPClause *Implicit = ActOnOpenMPFirstprivateClause( 2279 DSAChecker.getImplicitFirstprivate(), SourceLocation(), 2280 SourceLocation(), SourceLocation())) { 2281 ClausesWithImplicit.push_back(Implicit); 2282 ErrorFound = cast<OMPFirstprivateClause>(Implicit)->varlist_size() != 2283 DSAChecker.getImplicitFirstprivate().size(); 2284 } else 2285 ErrorFound = true; 2286 } 2287 } 2288 2289 llvm::SmallVector<OpenMPDirectiveKind, 4> AllowedNameModifiers; 2290 switch (Kind) { 2291 case OMPD_parallel: 2292 Res = ActOnOpenMPParallelDirective(ClausesWithImplicit, AStmt, StartLoc, 2293 EndLoc); 2294 AllowedNameModifiers.push_back(OMPD_parallel); 2295 break; 2296 case OMPD_simd: 2297 Res = ActOnOpenMPSimdDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc, 2298 VarsWithInheritedDSA); 2299 break; 2300 case OMPD_for: 2301 Res = ActOnOpenMPForDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc, 2302 VarsWithInheritedDSA); 2303 break; 2304 case OMPD_for_simd: 2305 Res = ActOnOpenMPForSimdDirective(ClausesWithImplicit, AStmt, StartLoc, 2306 EndLoc, VarsWithInheritedDSA); 2307 break; 2308 case OMPD_sections: 2309 Res = ActOnOpenMPSectionsDirective(ClausesWithImplicit, AStmt, StartLoc, 2310 EndLoc); 2311 break; 2312 case OMPD_section: 2313 assert(ClausesWithImplicit.empty() && 2314 "No clauses are allowed for 'omp section' directive"); 2315 Res = ActOnOpenMPSectionDirective(AStmt, StartLoc, EndLoc); 2316 break; 2317 case OMPD_single: 2318 Res = ActOnOpenMPSingleDirective(ClausesWithImplicit, AStmt, StartLoc, 2319 EndLoc); 2320 break; 2321 case OMPD_master: 2322 assert(ClausesWithImplicit.empty() && 2323 "No clauses are allowed for 'omp master' directive"); 2324 Res = ActOnOpenMPMasterDirective(AStmt, StartLoc, EndLoc); 2325 break; 2326 case OMPD_critical: 2327 Res = ActOnOpenMPCriticalDirective(DirName, ClausesWithImplicit, AStmt, 2328 StartLoc, EndLoc); 2329 break; 2330 case OMPD_parallel_for: 2331 Res = ActOnOpenMPParallelForDirective(ClausesWithImplicit, AStmt, StartLoc, 2332 EndLoc, VarsWithInheritedDSA); 2333 AllowedNameModifiers.push_back(OMPD_parallel); 2334 break; 2335 case OMPD_parallel_for_simd: 2336 Res = ActOnOpenMPParallelForSimdDirective( 2337 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA); 2338 AllowedNameModifiers.push_back(OMPD_parallel); 2339 break; 2340 case OMPD_parallel_sections: 2341 Res = ActOnOpenMPParallelSectionsDirective(ClausesWithImplicit, AStmt, 2342 StartLoc, EndLoc); 2343 AllowedNameModifiers.push_back(OMPD_parallel); 2344 break; 2345 case OMPD_task: 2346 Res = 2347 ActOnOpenMPTaskDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc); 2348 AllowedNameModifiers.push_back(OMPD_task); 2349 break; 2350 case OMPD_taskyield: 2351 assert(ClausesWithImplicit.empty() && 2352 "No clauses are allowed for 'omp taskyield' directive"); 2353 assert(AStmt == nullptr && 2354 "No associated statement allowed for 'omp taskyield' directive"); 2355 Res = ActOnOpenMPTaskyieldDirective(StartLoc, EndLoc); 2356 break; 2357 case OMPD_barrier: 2358 assert(ClausesWithImplicit.empty() && 2359 "No clauses are allowed for 'omp barrier' directive"); 2360 assert(AStmt == nullptr && 2361 "No associated statement allowed for 'omp barrier' directive"); 2362 Res = ActOnOpenMPBarrierDirective(StartLoc, EndLoc); 2363 break; 2364 case OMPD_taskwait: 2365 assert(ClausesWithImplicit.empty() && 2366 "No clauses are allowed for 'omp taskwait' directive"); 2367 assert(AStmt == nullptr && 2368 "No associated statement allowed for 'omp taskwait' directive"); 2369 Res = ActOnOpenMPTaskwaitDirective(StartLoc, EndLoc); 2370 break; 2371 case OMPD_taskgroup: 2372 assert(ClausesWithImplicit.empty() && 2373 "No clauses are allowed for 'omp taskgroup' directive"); 2374 Res = ActOnOpenMPTaskgroupDirective(AStmt, StartLoc, EndLoc); 2375 break; 2376 case OMPD_flush: 2377 assert(AStmt == nullptr && 2378 "No associated statement allowed for 'omp flush' directive"); 2379 Res = ActOnOpenMPFlushDirective(ClausesWithImplicit, StartLoc, EndLoc); 2380 break; 2381 case OMPD_ordered: 2382 Res = ActOnOpenMPOrderedDirective(ClausesWithImplicit, AStmt, StartLoc, 2383 EndLoc); 2384 break; 2385 case OMPD_atomic: 2386 Res = ActOnOpenMPAtomicDirective(ClausesWithImplicit, AStmt, StartLoc, 2387 EndLoc); 2388 break; 2389 case OMPD_teams: 2390 Res = 2391 ActOnOpenMPTeamsDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc); 2392 break; 2393 case OMPD_target: 2394 Res = ActOnOpenMPTargetDirective(ClausesWithImplicit, AStmt, StartLoc, 2395 EndLoc); 2396 AllowedNameModifiers.push_back(OMPD_target); 2397 break; 2398 case OMPD_target_parallel: 2399 Res = ActOnOpenMPTargetParallelDirective(ClausesWithImplicit, AStmt, 2400 StartLoc, EndLoc); 2401 AllowedNameModifiers.push_back(OMPD_target); 2402 AllowedNameModifiers.push_back(OMPD_parallel); 2403 break; 2404 case OMPD_target_parallel_for: 2405 Res = ActOnOpenMPTargetParallelForDirective( 2406 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA); 2407 AllowedNameModifiers.push_back(OMPD_target); 2408 AllowedNameModifiers.push_back(OMPD_parallel); 2409 break; 2410 case OMPD_cancellation_point: 2411 assert(ClausesWithImplicit.empty() && 2412 "No clauses are allowed for 'omp cancellation point' directive"); 2413 assert(AStmt == nullptr && "No associated statement allowed for 'omp " 2414 "cancellation point' directive"); 2415 Res = ActOnOpenMPCancellationPointDirective(StartLoc, EndLoc, CancelRegion); 2416 break; 2417 case OMPD_cancel: 2418 assert(AStmt == nullptr && 2419 "No associated statement allowed for 'omp cancel' directive"); 2420 Res = ActOnOpenMPCancelDirective(ClausesWithImplicit, StartLoc, EndLoc, 2421 CancelRegion); 2422 AllowedNameModifiers.push_back(OMPD_cancel); 2423 break; 2424 case OMPD_target_data: 2425 Res = ActOnOpenMPTargetDataDirective(ClausesWithImplicit, AStmt, StartLoc, 2426 EndLoc); 2427 AllowedNameModifiers.push_back(OMPD_target_data); 2428 break; 2429 case OMPD_target_enter_data: 2430 Res = ActOnOpenMPTargetEnterDataDirective(ClausesWithImplicit, StartLoc, 2431 EndLoc); 2432 AllowedNameModifiers.push_back(OMPD_target_enter_data); 2433 break; 2434 case OMPD_target_exit_data: 2435 Res = ActOnOpenMPTargetExitDataDirective(ClausesWithImplicit, StartLoc, 2436 EndLoc); 2437 AllowedNameModifiers.push_back(OMPD_target_exit_data); 2438 break; 2439 case OMPD_taskloop: 2440 Res = ActOnOpenMPTaskLoopDirective(ClausesWithImplicit, AStmt, StartLoc, 2441 EndLoc, VarsWithInheritedDSA); 2442 AllowedNameModifiers.push_back(OMPD_taskloop); 2443 break; 2444 case OMPD_taskloop_simd: 2445 Res = ActOnOpenMPTaskLoopSimdDirective(ClausesWithImplicit, AStmt, StartLoc, 2446 EndLoc, VarsWithInheritedDSA); 2447 AllowedNameModifiers.push_back(OMPD_taskloop); 2448 break; 2449 case OMPD_distribute: 2450 Res = ActOnOpenMPDistributeDirective(ClausesWithImplicit, AStmt, StartLoc, 2451 EndLoc, VarsWithInheritedDSA); 2452 break; 2453 case OMPD_target_update: 2454 assert(!AStmt && "Statement is not allowed for target update"); 2455 Res = 2456 ActOnOpenMPTargetUpdateDirective(ClausesWithImplicit, StartLoc, EndLoc); 2457 AllowedNameModifiers.push_back(OMPD_target_update); 2458 break; 2459 case OMPD_distribute_parallel_for: 2460 Res = ActOnOpenMPDistributeParallelForDirective( 2461 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA); 2462 AllowedNameModifiers.push_back(OMPD_parallel); 2463 break; 2464 case OMPD_distribute_parallel_for_simd: 2465 Res = ActOnOpenMPDistributeParallelForSimdDirective( 2466 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA); 2467 AllowedNameModifiers.push_back(OMPD_parallel); 2468 break; 2469 case OMPD_distribute_simd: 2470 Res = ActOnOpenMPDistributeSimdDirective( 2471 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA); 2472 break; 2473 case OMPD_target_parallel_for_simd: 2474 Res = ActOnOpenMPTargetParallelForSimdDirective( 2475 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA); 2476 AllowedNameModifiers.push_back(OMPD_target); 2477 AllowedNameModifiers.push_back(OMPD_parallel); 2478 break; 2479 case OMPD_target_simd: 2480 Res = ActOnOpenMPTargetSimdDirective(ClausesWithImplicit, AStmt, StartLoc, 2481 EndLoc, VarsWithInheritedDSA); 2482 AllowedNameModifiers.push_back(OMPD_target); 2483 break; 2484 case OMPD_teams_distribute: 2485 Res = ActOnOpenMPTeamsDistributeDirective( 2486 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA); 2487 break; 2488 case OMPD_teams_distribute_simd: 2489 Res = ActOnOpenMPTeamsDistributeSimdDirective( 2490 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA); 2491 break; 2492 case OMPD_teams_distribute_parallel_for_simd: 2493 Res = ActOnOpenMPTeamsDistributeParallelForSimdDirective( 2494 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA); 2495 AllowedNameModifiers.push_back(OMPD_parallel); 2496 break; 2497 case OMPD_teams_distribute_parallel_for: 2498 Res = ActOnOpenMPTeamsDistributeParallelForDirective( 2499 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA); 2500 AllowedNameModifiers.push_back(OMPD_parallel); 2501 break; 2502 case OMPD_target_teams: 2503 Res = ActOnOpenMPTargetTeamsDirective(ClausesWithImplicit, AStmt, StartLoc, 2504 EndLoc); 2505 AllowedNameModifiers.push_back(OMPD_target); 2506 break; 2507 case OMPD_target_teams_distribute: 2508 Res = ActOnOpenMPTargetTeamsDistributeDirective( 2509 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA); 2510 AllowedNameModifiers.push_back(OMPD_target); 2511 break; 2512 case OMPD_target_teams_distribute_parallel_for: 2513 Res = ActOnOpenMPTargetTeamsDistributeParallelForDirective( 2514 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA); 2515 AllowedNameModifiers.push_back(OMPD_target); 2516 AllowedNameModifiers.push_back(OMPD_parallel); 2517 break; 2518 case OMPD_target_teams_distribute_parallel_for_simd: 2519 Res = ActOnOpenMPTargetTeamsDistributeParallelForSimdDirective( 2520 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA); 2521 AllowedNameModifiers.push_back(OMPD_target); 2522 AllowedNameModifiers.push_back(OMPD_parallel); 2523 break; 2524 case OMPD_target_teams_distribute_simd: 2525 Res = ActOnOpenMPTargetTeamsDistributeSimdDirective( 2526 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA); 2527 AllowedNameModifiers.push_back(OMPD_target); 2528 break; 2529 case OMPD_declare_target: 2530 case OMPD_end_declare_target: 2531 case OMPD_threadprivate: 2532 case OMPD_declare_reduction: 2533 case OMPD_declare_simd: 2534 llvm_unreachable("OpenMP Directive is not allowed"); 2535 case OMPD_unknown: 2536 llvm_unreachable("Unknown OpenMP directive"); 2537 } 2538 2539 for (auto P : VarsWithInheritedDSA) { 2540 Diag(P.second->getExprLoc(), diag::err_omp_no_dsa_for_variable) 2541 << P.first << P.second->getSourceRange(); 2542 } 2543 ErrorFound = !VarsWithInheritedDSA.empty() || ErrorFound; 2544 2545 if (!AllowedNameModifiers.empty()) 2546 ErrorFound = checkIfClauses(*this, Kind, Clauses, AllowedNameModifiers) || 2547 ErrorFound; 2548 2549 if (ErrorFound) 2550 return StmtError(); 2551 return Res; 2552 } 2553 2554 Sema::DeclGroupPtrTy Sema::ActOnOpenMPDeclareSimdDirective( 2555 DeclGroupPtrTy DG, OMPDeclareSimdDeclAttr::BranchStateTy BS, Expr *Simdlen, 2556 ArrayRef<Expr *> Uniforms, ArrayRef<Expr *> Aligneds, 2557 ArrayRef<Expr *> Alignments, ArrayRef<Expr *> Linears, 2558 ArrayRef<unsigned> LinModifiers, ArrayRef<Expr *> Steps, SourceRange SR) { 2559 assert(Aligneds.size() == Alignments.size()); 2560 assert(Linears.size() == LinModifiers.size()); 2561 assert(Linears.size() == Steps.size()); 2562 if (!DG || DG.get().isNull()) 2563 return DeclGroupPtrTy(); 2564 2565 if (!DG.get().isSingleDecl()) { 2566 Diag(SR.getBegin(), diag::err_omp_single_decl_in_declare_simd); 2567 return DG; 2568 } 2569 auto *ADecl = DG.get().getSingleDecl(); 2570 if (auto *FTD = dyn_cast<FunctionTemplateDecl>(ADecl)) 2571 ADecl = FTD->getTemplatedDecl(); 2572 2573 auto *FD = dyn_cast<FunctionDecl>(ADecl); 2574 if (!FD) { 2575 Diag(ADecl->getLocation(), diag::err_omp_function_expected); 2576 return DeclGroupPtrTy(); 2577 } 2578 2579 // OpenMP [2.8.2, declare simd construct, Description] 2580 // The parameter of the simdlen clause must be a constant positive integer 2581 // expression. 2582 ExprResult SL; 2583 if (Simdlen) 2584 SL = VerifyPositiveIntegerConstantInClause(Simdlen, OMPC_simdlen); 2585 // OpenMP [2.8.2, declare simd construct, Description] 2586 // The special this pointer can be used as if was one of the arguments to the 2587 // function in any of the linear, aligned, or uniform clauses. 2588 // The uniform clause declares one or more arguments to have an invariant 2589 // value for all concurrent invocations of the function in the execution of a 2590 // single SIMD loop. 2591 llvm::DenseMap<Decl *, Expr *> UniformedArgs; 2592 Expr *UniformedLinearThis = nullptr; 2593 for (auto *E : Uniforms) { 2594 E = E->IgnoreParenImpCasts(); 2595 if (auto *DRE = dyn_cast<DeclRefExpr>(E)) 2596 if (auto *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl())) 2597 if (FD->getNumParams() > PVD->getFunctionScopeIndex() && 2598 FD->getParamDecl(PVD->getFunctionScopeIndex()) 2599 ->getCanonicalDecl() == PVD->getCanonicalDecl()) { 2600 UniformedArgs.insert(std::make_pair(PVD->getCanonicalDecl(), E)); 2601 continue; 2602 } 2603 if (isa<CXXThisExpr>(E)) { 2604 UniformedLinearThis = E; 2605 continue; 2606 } 2607 Diag(E->getExprLoc(), diag::err_omp_param_or_this_in_clause) 2608 << FD->getDeclName() << (isa<CXXMethodDecl>(ADecl) ? 1 : 0); 2609 } 2610 // OpenMP [2.8.2, declare simd construct, Description] 2611 // The aligned clause declares that the object to which each list item points 2612 // is aligned to the number of bytes expressed in the optional parameter of 2613 // the aligned clause. 2614 // The special this pointer can be used as if was one of the arguments to the 2615 // function in any of the linear, aligned, or uniform clauses. 2616 // The type of list items appearing in the aligned clause must be array, 2617 // pointer, reference to array, or reference to pointer. 2618 llvm::DenseMap<Decl *, Expr *> AlignedArgs; 2619 Expr *AlignedThis = nullptr; 2620 for (auto *E : Aligneds) { 2621 E = E->IgnoreParenImpCasts(); 2622 if (auto *DRE = dyn_cast<DeclRefExpr>(E)) 2623 if (auto *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl())) { 2624 auto *CanonPVD = PVD->getCanonicalDecl(); 2625 if (FD->getNumParams() > PVD->getFunctionScopeIndex() && 2626 FD->getParamDecl(PVD->getFunctionScopeIndex()) 2627 ->getCanonicalDecl() == CanonPVD) { 2628 // OpenMP [2.8.1, simd construct, Restrictions] 2629 // A list-item cannot appear in more than one aligned clause. 2630 if (AlignedArgs.count(CanonPVD) > 0) { 2631 Diag(E->getExprLoc(), diag::err_omp_aligned_twice) 2632 << 1 << E->getSourceRange(); 2633 Diag(AlignedArgs[CanonPVD]->getExprLoc(), 2634 diag::note_omp_explicit_dsa) 2635 << getOpenMPClauseName(OMPC_aligned); 2636 continue; 2637 } 2638 AlignedArgs[CanonPVD] = E; 2639 QualType QTy = PVD->getType() 2640 .getNonReferenceType() 2641 .getUnqualifiedType() 2642 .getCanonicalType(); 2643 const Type *Ty = QTy.getTypePtrOrNull(); 2644 if (!Ty || (!Ty->isArrayType() && !Ty->isPointerType())) { 2645 Diag(E->getExprLoc(), diag::err_omp_aligned_expected_array_or_ptr) 2646 << QTy << getLangOpts().CPlusPlus << E->getSourceRange(); 2647 Diag(PVD->getLocation(), diag::note_previous_decl) << PVD; 2648 } 2649 continue; 2650 } 2651 } 2652 if (isa<CXXThisExpr>(E)) { 2653 if (AlignedThis) { 2654 Diag(E->getExprLoc(), diag::err_omp_aligned_twice) 2655 << 2 << E->getSourceRange(); 2656 Diag(AlignedThis->getExprLoc(), diag::note_omp_explicit_dsa) 2657 << getOpenMPClauseName(OMPC_aligned); 2658 } 2659 AlignedThis = E; 2660 continue; 2661 } 2662 Diag(E->getExprLoc(), diag::err_omp_param_or_this_in_clause) 2663 << FD->getDeclName() << (isa<CXXMethodDecl>(ADecl) ? 1 : 0); 2664 } 2665 // The optional parameter of the aligned clause, alignment, must be a constant 2666 // positive integer expression. If no optional parameter is specified, 2667 // implementation-defined default alignments for SIMD instructions on the 2668 // target platforms are assumed. 2669 SmallVector<Expr *, 4> NewAligns; 2670 for (auto *E : Alignments) { 2671 ExprResult Align; 2672 if (E) 2673 Align = VerifyPositiveIntegerConstantInClause(E, OMPC_aligned); 2674 NewAligns.push_back(Align.get()); 2675 } 2676 // OpenMP [2.8.2, declare simd construct, Description] 2677 // The linear clause declares one or more list items to be private to a SIMD 2678 // lane and to have a linear relationship with respect to the iteration space 2679 // of a loop. 2680 // The special this pointer can be used as if was one of the arguments to the 2681 // function in any of the linear, aligned, or uniform clauses. 2682 // When a linear-step expression is specified in a linear clause it must be 2683 // either a constant integer expression or an integer-typed parameter that is 2684 // specified in a uniform clause on the directive. 2685 llvm::DenseMap<Decl *, Expr *> LinearArgs; 2686 const bool IsUniformedThis = UniformedLinearThis != nullptr; 2687 auto MI = LinModifiers.begin(); 2688 for (auto *E : Linears) { 2689 auto LinKind = static_cast<OpenMPLinearClauseKind>(*MI); 2690 ++MI; 2691 E = E->IgnoreParenImpCasts(); 2692 if (auto *DRE = dyn_cast<DeclRefExpr>(E)) 2693 if (auto *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl())) { 2694 auto *CanonPVD = PVD->getCanonicalDecl(); 2695 if (FD->getNumParams() > PVD->getFunctionScopeIndex() && 2696 FD->getParamDecl(PVD->getFunctionScopeIndex()) 2697 ->getCanonicalDecl() == CanonPVD) { 2698 // OpenMP [2.15.3.7, linear Clause, Restrictions] 2699 // A list-item cannot appear in more than one linear clause. 2700 if (LinearArgs.count(CanonPVD) > 0) { 2701 Diag(E->getExprLoc(), diag::err_omp_wrong_dsa) 2702 << getOpenMPClauseName(OMPC_linear) 2703 << getOpenMPClauseName(OMPC_linear) << E->getSourceRange(); 2704 Diag(LinearArgs[CanonPVD]->getExprLoc(), 2705 diag::note_omp_explicit_dsa) 2706 << getOpenMPClauseName(OMPC_linear); 2707 continue; 2708 } 2709 // Each argument can appear in at most one uniform or linear clause. 2710 if (UniformedArgs.count(CanonPVD) > 0) { 2711 Diag(E->getExprLoc(), diag::err_omp_wrong_dsa) 2712 << getOpenMPClauseName(OMPC_linear) 2713 << getOpenMPClauseName(OMPC_uniform) << E->getSourceRange(); 2714 Diag(UniformedArgs[CanonPVD]->getExprLoc(), 2715 diag::note_omp_explicit_dsa) 2716 << getOpenMPClauseName(OMPC_uniform); 2717 continue; 2718 } 2719 LinearArgs[CanonPVD] = E; 2720 if (E->isValueDependent() || E->isTypeDependent() || 2721 E->isInstantiationDependent() || 2722 E->containsUnexpandedParameterPack()) 2723 continue; 2724 (void)CheckOpenMPLinearDecl(CanonPVD, E->getExprLoc(), LinKind, 2725 PVD->getOriginalType()); 2726 continue; 2727 } 2728 } 2729 if (isa<CXXThisExpr>(E)) { 2730 if (UniformedLinearThis) { 2731 Diag(E->getExprLoc(), diag::err_omp_wrong_dsa) 2732 << getOpenMPClauseName(OMPC_linear) 2733 << getOpenMPClauseName(IsUniformedThis ? OMPC_uniform : OMPC_linear) 2734 << E->getSourceRange(); 2735 Diag(UniformedLinearThis->getExprLoc(), diag::note_omp_explicit_dsa) 2736 << getOpenMPClauseName(IsUniformedThis ? OMPC_uniform 2737 : OMPC_linear); 2738 continue; 2739 } 2740 UniformedLinearThis = E; 2741 if (E->isValueDependent() || E->isTypeDependent() || 2742 E->isInstantiationDependent() || E->containsUnexpandedParameterPack()) 2743 continue; 2744 (void)CheckOpenMPLinearDecl(/*D=*/nullptr, E->getExprLoc(), LinKind, 2745 E->getType()); 2746 continue; 2747 } 2748 Diag(E->getExprLoc(), diag::err_omp_param_or_this_in_clause) 2749 << FD->getDeclName() << (isa<CXXMethodDecl>(ADecl) ? 1 : 0); 2750 } 2751 Expr *Step = nullptr; 2752 Expr *NewStep = nullptr; 2753 SmallVector<Expr *, 4> NewSteps; 2754 for (auto *E : Steps) { 2755 // Skip the same step expression, it was checked already. 2756 if (Step == E || !E) { 2757 NewSteps.push_back(E ? NewStep : nullptr); 2758 continue; 2759 } 2760 Step = E; 2761 if (auto *DRE = dyn_cast<DeclRefExpr>(Step)) 2762 if (auto *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl())) { 2763 auto *CanonPVD = PVD->getCanonicalDecl(); 2764 if (UniformedArgs.count(CanonPVD) == 0) { 2765 Diag(Step->getExprLoc(), diag::err_omp_expected_uniform_param) 2766 << Step->getSourceRange(); 2767 } else if (E->isValueDependent() || E->isTypeDependent() || 2768 E->isInstantiationDependent() || 2769 E->containsUnexpandedParameterPack() || 2770 CanonPVD->getType()->hasIntegerRepresentation()) 2771 NewSteps.push_back(Step); 2772 else { 2773 Diag(Step->getExprLoc(), diag::err_omp_expected_int_param) 2774 << Step->getSourceRange(); 2775 } 2776 continue; 2777 } 2778 NewStep = Step; 2779 if (Step && !Step->isValueDependent() && !Step->isTypeDependent() && 2780 !Step->isInstantiationDependent() && 2781 !Step->containsUnexpandedParameterPack()) { 2782 NewStep = PerformOpenMPImplicitIntegerConversion(Step->getExprLoc(), Step) 2783 .get(); 2784 if (NewStep) 2785 NewStep = VerifyIntegerConstantExpression(NewStep).get(); 2786 } 2787 NewSteps.push_back(NewStep); 2788 } 2789 auto *NewAttr = OMPDeclareSimdDeclAttr::CreateImplicit( 2790 Context, BS, SL.get(), const_cast<Expr **>(Uniforms.data()), 2791 Uniforms.size(), const_cast<Expr **>(Aligneds.data()), Aligneds.size(), 2792 const_cast<Expr **>(NewAligns.data()), NewAligns.size(), 2793 const_cast<Expr **>(Linears.data()), Linears.size(), 2794 const_cast<unsigned *>(LinModifiers.data()), LinModifiers.size(), 2795 NewSteps.data(), NewSteps.size(), SR); 2796 ADecl->addAttr(NewAttr); 2797 return ConvertDeclToDeclGroup(ADecl); 2798 } 2799 2800 StmtResult Sema::ActOnOpenMPParallelDirective(ArrayRef<OMPClause *> Clauses, 2801 Stmt *AStmt, 2802 SourceLocation StartLoc, 2803 SourceLocation EndLoc) { 2804 if (!AStmt) 2805 return StmtError(); 2806 2807 CapturedStmt *CS = cast<CapturedStmt>(AStmt); 2808 // 1.2.2 OpenMP Language Terminology 2809 // Structured block - An executable statement with a single entry at the 2810 // top and a single exit at the bottom. 2811 // The point of exit cannot be a branch out of the structured block. 2812 // longjmp() and throw() must not violate the entry/exit criteria. 2813 CS->getCapturedDecl()->setNothrow(); 2814 2815 getCurFunction()->setHasBranchProtectedScope(); 2816 2817 return OMPParallelDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt, 2818 DSAStack->isCancelRegion()); 2819 } 2820 2821 namespace { 2822 /// \brief Helper class for checking canonical form of the OpenMP loops and 2823 /// extracting iteration space of each loop in the loop nest, that will be used 2824 /// for IR generation. 2825 class OpenMPIterationSpaceChecker { 2826 /// \brief Reference to Sema. 2827 Sema &SemaRef; 2828 /// \brief A location for diagnostics (when there is no some better location). 2829 SourceLocation DefaultLoc; 2830 /// \brief A location for diagnostics (when increment is not compatible). 2831 SourceLocation ConditionLoc; 2832 /// \brief A source location for referring to loop init later. 2833 SourceRange InitSrcRange; 2834 /// \brief A source location for referring to condition later. 2835 SourceRange ConditionSrcRange; 2836 /// \brief A source location for referring to increment later. 2837 SourceRange IncrementSrcRange; 2838 /// \brief Loop variable. 2839 ValueDecl *LCDecl = nullptr; 2840 /// \brief Reference to loop variable. 2841 Expr *LCRef = nullptr; 2842 /// \brief Lower bound (initializer for the var). 2843 Expr *LB = nullptr; 2844 /// \brief Upper bound. 2845 Expr *UB = nullptr; 2846 /// \brief Loop step (increment). 2847 Expr *Step = nullptr; 2848 /// \brief This flag is true when condition is one of: 2849 /// Var < UB 2850 /// Var <= UB 2851 /// UB > Var 2852 /// UB >= Var 2853 bool TestIsLessOp = false; 2854 /// \brief This flag is true when condition is strict ( < or > ). 2855 bool TestIsStrictOp = false; 2856 /// \brief This flag is true when step is subtracted on each iteration. 2857 bool SubtractStep = false; 2858 2859 public: 2860 OpenMPIterationSpaceChecker(Sema &SemaRef, SourceLocation DefaultLoc) 2861 : SemaRef(SemaRef), DefaultLoc(DefaultLoc), ConditionLoc(DefaultLoc) {} 2862 /// \brief Check init-expr for canonical loop form and save loop counter 2863 /// variable - #Var and its initialization value - #LB. 2864 bool CheckInit(Stmt *S, bool EmitDiags = true); 2865 /// \brief Check test-expr for canonical form, save upper-bound (#UB), flags 2866 /// for less/greater and for strict/non-strict comparison. 2867 bool CheckCond(Expr *S); 2868 /// \brief Check incr-expr for canonical loop form and return true if it 2869 /// does not conform, otherwise save loop step (#Step). 2870 bool CheckInc(Expr *S); 2871 /// \brief Return the loop counter variable. 2872 ValueDecl *GetLoopDecl() const { return LCDecl; } 2873 /// \brief Return the reference expression to loop counter variable. 2874 Expr *GetLoopDeclRefExpr() const { return LCRef; } 2875 /// \brief Source range of the loop init. 2876 SourceRange GetInitSrcRange() const { return InitSrcRange; } 2877 /// \brief Source range of the loop condition. 2878 SourceRange GetConditionSrcRange() const { return ConditionSrcRange; } 2879 /// \brief Source range of the loop increment. 2880 SourceRange GetIncrementSrcRange() const { return IncrementSrcRange; } 2881 /// \brief True if the step should be subtracted. 2882 bool ShouldSubtractStep() const { return SubtractStep; } 2883 /// \brief Build the expression to calculate the number of iterations. 2884 Expr * 2885 BuildNumIterations(Scope *S, const bool LimitedType, 2886 llvm::MapVector<Expr *, DeclRefExpr *> &Captures) const; 2887 /// \brief Build the precondition expression for the loops. 2888 Expr *BuildPreCond(Scope *S, Expr *Cond, 2889 llvm::MapVector<Expr *, DeclRefExpr *> &Captures) const; 2890 /// \brief Build reference expression to the counter be used for codegen. 2891 DeclRefExpr *BuildCounterVar(llvm::MapVector<Expr *, DeclRefExpr *> &Captures, 2892 DSAStackTy &DSA) const; 2893 /// \brief Build reference expression to the private counter be used for 2894 /// codegen. 2895 Expr *BuildPrivateCounterVar() const; 2896 /// \brief Build initialization of the counter be used for codegen. 2897 Expr *BuildCounterInit() const; 2898 /// \brief Build step of the counter be used for codegen. 2899 Expr *BuildCounterStep() const; 2900 /// \brief Return true if any expression is dependent. 2901 bool Dependent() const; 2902 2903 private: 2904 /// \brief Check the right-hand side of an assignment in the increment 2905 /// expression. 2906 bool CheckIncRHS(Expr *RHS); 2907 /// \brief Helper to set loop counter variable and its initializer. 2908 bool SetLCDeclAndLB(ValueDecl *NewLCDecl, Expr *NewDeclRefExpr, Expr *NewLB); 2909 /// \brief Helper to set upper bound. 2910 bool SetUB(Expr *NewUB, bool LessOp, bool StrictOp, SourceRange SR, 2911 SourceLocation SL); 2912 /// \brief Helper to set loop increment. 2913 bool SetStep(Expr *NewStep, bool Subtract); 2914 }; 2915 2916 bool OpenMPIterationSpaceChecker::Dependent() const { 2917 if (!LCDecl) { 2918 assert(!LB && !UB && !Step); 2919 return false; 2920 } 2921 return LCDecl->getType()->isDependentType() || 2922 (LB && LB->isValueDependent()) || (UB && UB->isValueDependent()) || 2923 (Step && Step->isValueDependent()); 2924 } 2925 2926 static Expr *getExprAsWritten(Expr *E) { 2927 if (auto *ExprTemp = dyn_cast<ExprWithCleanups>(E)) 2928 E = ExprTemp->getSubExpr(); 2929 2930 if (auto *MTE = dyn_cast<MaterializeTemporaryExpr>(E)) 2931 E = MTE->GetTemporaryExpr(); 2932 2933 while (auto *Binder = dyn_cast<CXXBindTemporaryExpr>(E)) 2934 E = Binder->getSubExpr(); 2935 2936 if (auto *ICE = dyn_cast<ImplicitCastExpr>(E)) 2937 E = ICE->getSubExprAsWritten(); 2938 return E->IgnoreParens(); 2939 } 2940 2941 bool OpenMPIterationSpaceChecker::SetLCDeclAndLB(ValueDecl *NewLCDecl, 2942 Expr *NewLCRefExpr, 2943 Expr *NewLB) { 2944 // State consistency checking to ensure correct usage. 2945 assert(LCDecl == nullptr && LB == nullptr && LCRef == nullptr && 2946 UB == nullptr && Step == nullptr && !TestIsLessOp && !TestIsStrictOp); 2947 if (!NewLCDecl || !NewLB) 2948 return true; 2949 LCDecl = getCanonicalDecl(NewLCDecl); 2950 LCRef = NewLCRefExpr; 2951 if (auto *CE = dyn_cast_or_null<CXXConstructExpr>(NewLB)) 2952 if (const CXXConstructorDecl *Ctor = CE->getConstructor()) 2953 if ((Ctor->isCopyOrMoveConstructor() || 2954 Ctor->isConvertingConstructor(/*AllowExplicit=*/false)) && 2955 CE->getNumArgs() > 0 && CE->getArg(0) != nullptr) 2956 NewLB = CE->getArg(0)->IgnoreParenImpCasts(); 2957 LB = NewLB; 2958 return false; 2959 } 2960 2961 bool OpenMPIterationSpaceChecker::SetUB(Expr *NewUB, bool LessOp, bool StrictOp, 2962 SourceRange SR, SourceLocation SL) { 2963 // State consistency checking to ensure correct usage. 2964 assert(LCDecl != nullptr && LB != nullptr && UB == nullptr && 2965 Step == nullptr && !TestIsLessOp && !TestIsStrictOp); 2966 if (!NewUB) 2967 return true; 2968 UB = NewUB; 2969 TestIsLessOp = LessOp; 2970 TestIsStrictOp = StrictOp; 2971 ConditionSrcRange = SR; 2972 ConditionLoc = SL; 2973 return false; 2974 } 2975 2976 bool OpenMPIterationSpaceChecker::SetStep(Expr *NewStep, bool Subtract) { 2977 // State consistency checking to ensure correct usage. 2978 assert(LCDecl != nullptr && LB != nullptr && Step == nullptr); 2979 if (!NewStep) 2980 return true; 2981 if (!NewStep->isValueDependent()) { 2982 // Check that the step is integer expression. 2983 SourceLocation StepLoc = NewStep->getLocStart(); 2984 ExprResult Val = 2985 SemaRef.PerformOpenMPImplicitIntegerConversion(StepLoc, NewStep); 2986 if (Val.isInvalid()) 2987 return true; 2988 NewStep = Val.get(); 2989 2990 // OpenMP [2.6, Canonical Loop Form, Restrictions] 2991 // If test-expr is of form var relational-op b and relational-op is < or 2992 // <= then incr-expr must cause var to increase on each iteration of the 2993 // loop. If test-expr is of form var relational-op b and relational-op is 2994 // > or >= then incr-expr must cause var to decrease on each iteration of 2995 // the loop. 2996 // If test-expr is of form b relational-op var and relational-op is < or 2997 // <= then incr-expr must cause var to decrease on each iteration of the 2998 // loop. If test-expr is of form b relational-op var and relational-op is 2999 // > or >= then incr-expr must cause var to increase on each iteration of 3000 // the loop. 3001 llvm::APSInt Result; 3002 bool IsConstant = NewStep->isIntegerConstantExpr(Result, SemaRef.Context); 3003 bool IsUnsigned = !NewStep->getType()->hasSignedIntegerRepresentation(); 3004 bool IsConstNeg = 3005 IsConstant && Result.isSigned() && (Subtract != Result.isNegative()); 3006 bool IsConstPos = 3007 IsConstant && Result.isSigned() && (Subtract == Result.isNegative()); 3008 bool IsConstZero = IsConstant && !Result.getBoolValue(); 3009 if (UB && (IsConstZero || 3010 (TestIsLessOp ? (IsConstNeg || (IsUnsigned && Subtract)) 3011 : (IsConstPos || (IsUnsigned && !Subtract))))) { 3012 SemaRef.Diag(NewStep->getExprLoc(), 3013 diag::err_omp_loop_incr_not_compatible) 3014 << LCDecl << TestIsLessOp << NewStep->getSourceRange(); 3015 SemaRef.Diag(ConditionLoc, 3016 diag::note_omp_loop_cond_requres_compatible_incr) 3017 << TestIsLessOp << ConditionSrcRange; 3018 return true; 3019 } 3020 if (TestIsLessOp == Subtract) { 3021 NewStep = 3022 SemaRef.CreateBuiltinUnaryOp(NewStep->getExprLoc(), UO_Minus, NewStep) 3023 .get(); 3024 Subtract = !Subtract; 3025 } 3026 } 3027 3028 Step = NewStep; 3029 SubtractStep = Subtract; 3030 return false; 3031 } 3032 3033 bool OpenMPIterationSpaceChecker::CheckInit(Stmt *S, bool EmitDiags) { 3034 // Check init-expr for canonical loop form and save loop counter 3035 // variable - #Var and its initialization value - #LB. 3036 // OpenMP [2.6] Canonical loop form. init-expr may be one of the following: 3037 // var = lb 3038 // integer-type var = lb 3039 // random-access-iterator-type var = lb 3040 // pointer-type var = lb 3041 // 3042 if (!S) { 3043 if (EmitDiags) { 3044 SemaRef.Diag(DefaultLoc, diag::err_omp_loop_not_canonical_init); 3045 } 3046 return true; 3047 } 3048 if (auto *ExprTemp = dyn_cast<ExprWithCleanups>(S)) 3049 if (!ExprTemp->cleanupsHaveSideEffects()) 3050 S = ExprTemp->getSubExpr(); 3051 3052 InitSrcRange = S->getSourceRange(); 3053 if (Expr *E = dyn_cast<Expr>(S)) 3054 S = E->IgnoreParens(); 3055 if (auto *BO = dyn_cast<BinaryOperator>(S)) { 3056 if (BO->getOpcode() == BO_Assign) { 3057 auto *LHS = BO->getLHS()->IgnoreParens(); 3058 if (auto *DRE = dyn_cast<DeclRefExpr>(LHS)) { 3059 if (auto *CED = dyn_cast<OMPCapturedExprDecl>(DRE->getDecl())) 3060 if (auto *ME = dyn_cast<MemberExpr>(getExprAsWritten(CED->getInit()))) 3061 return SetLCDeclAndLB(ME->getMemberDecl(), ME, BO->getRHS()); 3062 return SetLCDeclAndLB(DRE->getDecl(), DRE, BO->getRHS()); 3063 } 3064 if (auto *ME = dyn_cast<MemberExpr>(LHS)) { 3065 if (ME->isArrow() && 3066 isa<CXXThisExpr>(ME->getBase()->IgnoreParenImpCasts())) 3067 return SetLCDeclAndLB(ME->getMemberDecl(), ME, BO->getRHS()); 3068 } 3069 } 3070 } else if (auto *DS = dyn_cast<DeclStmt>(S)) { 3071 if (DS->isSingleDecl()) { 3072 if (auto *Var = dyn_cast_or_null<VarDecl>(DS->getSingleDecl())) { 3073 if (Var->hasInit() && !Var->getType()->isReferenceType()) { 3074 // Accept non-canonical init form here but emit ext. warning. 3075 if (Var->getInitStyle() != VarDecl::CInit && EmitDiags) 3076 SemaRef.Diag(S->getLocStart(), 3077 diag::ext_omp_loop_not_canonical_init) 3078 << S->getSourceRange(); 3079 return SetLCDeclAndLB(Var, nullptr, Var->getInit()); 3080 } 3081 } 3082 } 3083 } else if (auto *CE = dyn_cast<CXXOperatorCallExpr>(S)) { 3084 if (CE->getOperator() == OO_Equal) { 3085 auto *LHS = CE->getArg(0); 3086 if (auto *DRE = dyn_cast<DeclRefExpr>(LHS)) { 3087 if (auto *CED = dyn_cast<OMPCapturedExprDecl>(DRE->getDecl())) 3088 if (auto *ME = dyn_cast<MemberExpr>(getExprAsWritten(CED->getInit()))) 3089 return SetLCDeclAndLB(ME->getMemberDecl(), ME, BO->getRHS()); 3090 return SetLCDeclAndLB(DRE->getDecl(), DRE, CE->getArg(1)); 3091 } 3092 if (auto *ME = dyn_cast<MemberExpr>(LHS)) { 3093 if (ME->isArrow() && 3094 isa<CXXThisExpr>(ME->getBase()->IgnoreParenImpCasts())) 3095 return SetLCDeclAndLB(ME->getMemberDecl(), ME, BO->getRHS()); 3096 } 3097 } 3098 } 3099 3100 if (Dependent() || SemaRef.CurContext->isDependentContext()) 3101 return false; 3102 if (EmitDiags) { 3103 SemaRef.Diag(S->getLocStart(), diag::err_omp_loop_not_canonical_init) 3104 << S->getSourceRange(); 3105 } 3106 return true; 3107 } 3108 3109 /// \brief Ignore parenthesizes, implicit casts, copy constructor and return the 3110 /// variable (which may be the loop variable) if possible. 3111 static const ValueDecl *GetInitLCDecl(Expr *E) { 3112 if (!E) 3113 return nullptr; 3114 E = getExprAsWritten(E); 3115 if (auto *CE = dyn_cast_or_null<CXXConstructExpr>(E)) 3116 if (const CXXConstructorDecl *Ctor = CE->getConstructor()) 3117 if ((Ctor->isCopyOrMoveConstructor() || 3118 Ctor->isConvertingConstructor(/*AllowExplicit=*/false)) && 3119 CE->getNumArgs() > 0 && CE->getArg(0) != nullptr) 3120 E = CE->getArg(0)->IgnoreParenImpCasts(); 3121 if (auto *DRE = dyn_cast_or_null<DeclRefExpr>(E)) { 3122 if (auto *VD = dyn_cast<VarDecl>(DRE->getDecl())) { 3123 if (auto *CED = dyn_cast<OMPCapturedExprDecl>(VD)) 3124 if (auto *ME = dyn_cast<MemberExpr>(getExprAsWritten(CED->getInit()))) 3125 return getCanonicalDecl(ME->getMemberDecl()); 3126 return getCanonicalDecl(VD); 3127 } 3128 } 3129 if (auto *ME = dyn_cast_or_null<MemberExpr>(E)) 3130 if (ME->isArrow() && isa<CXXThisExpr>(ME->getBase()->IgnoreParenImpCasts())) 3131 return getCanonicalDecl(ME->getMemberDecl()); 3132 return nullptr; 3133 } 3134 3135 bool OpenMPIterationSpaceChecker::CheckCond(Expr *S) { 3136 // Check test-expr for canonical form, save upper-bound UB, flags for 3137 // less/greater and for strict/non-strict comparison. 3138 // OpenMP [2.6] Canonical loop form. Test-expr may be one of the following: 3139 // var relational-op b 3140 // b relational-op var 3141 // 3142 if (!S) { 3143 SemaRef.Diag(DefaultLoc, diag::err_omp_loop_not_canonical_cond) << LCDecl; 3144 return true; 3145 } 3146 S = getExprAsWritten(S); 3147 SourceLocation CondLoc = S->getLocStart(); 3148 if (auto *BO = dyn_cast<BinaryOperator>(S)) { 3149 if (BO->isRelationalOp()) { 3150 if (GetInitLCDecl(BO->getLHS()) == LCDecl) 3151 return SetUB(BO->getRHS(), 3152 (BO->getOpcode() == BO_LT || BO->getOpcode() == BO_LE), 3153 (BO->getOpcode() == BO_LT || BO->getOpcode() == BO_GT), 3154 BO->getSourceRange(), BO->getOperatorLoc()); 3155 if (GetInitLCDecl(BO->getRHS()) == LCDecl) 3156 return SetUB(BO->getLHS(), 3157 (BO->getOpcode() == BO_GT || BO->getOpcode() == BO_GE), 3158 (BO->getOpcode() == BO_LT || BO->getOpcode() == BO_GT), 3159 BO->getSourceRange(), BO->getOperatorLoc()); 3160 } 3161 } else if (auto *CE = dyn_cast<CXXOperatorCallExpr>(S)) { 3162 if (CE->getNumArgs() == 2) { 3163 auto Op = CE->getOperator(); 3164 switch (Op) { 3165 case OO_Greater: 3166 case OO_GreaterEqual: 3167 case OO_Less: 3168 case OO_LessEqual: 3169 if (GetInitLCDecl(CE->getArg(0)) == LCDecl) 3170 return SetUB(CE->getArg(1), Op == OO_Less || Op == OO_LessEqual, 3171 Op == OO_Less || Op == OO_Greater, CE->getSourceRange(), 3172 CE->getOperatorLoc()); 3173 if (GetInitLCDecl(CE->getArg(1)) == LCDecl) 3174 return SetUB(CE->getArg(0), Op == OO_Greater || Op == OO_GreaterEqual, 3175 Op == OO_Less || Op == OO_Greater, CE->getSourceRange(), 3176 CE->getOperatorLoc()); 3177 break; 3178 default: 3179 break; 3180 } 3181 } 3182 } 3183 if (Dependent() || SemaRef.CurContext->isDependentContext()) 3184 return false; 3185 SemaRef.Diag(CondLoc, diag::err_omp_loop_not_canonical_cond) 3186 << S->getSourceRange() << LCDecl; 3187 return true; 3188 } 3189 3190 bool OpenMPIterationSpaceChecker::CheckIncRHS(Expr *RHS) { 3191 // RHS of canonical loop form increment can be: 3192 // var + incr 3193 // incr + var 3194 // var - incr 3195 // 3196 RHS = RHS->IgnoreParenImpCasts(); 3197 if (auto *BO = dyn_cast<BinaryOperator>(RHS)) { 3198 if (BO->isAdditiveOp()) { 3199 bool IsAdd = BO->getOpcode() == BO_Add; 3200 if (GetInitLCDecl(BO->getLHS()) == LCDecl) 3201 return SetStep(BO->getRHS(), !IsAdd); 3202 if (IsAdd && GetInitLCDecl(BO->getRHS()) == LCDecl) 3203 return SetStep(BO->getLHS(), false); 3204 } 3205 } else if (auto *CE = dyn_cast<CXXOperatorCallExpr>(RHS)) { 3206 bool IsAdd = CE->getOperator() == OO_Plus; 3207 if ((IsAdd || CE->getOperator() == OO_Minus) && CE->getNumArgs() == 2) { 3208 if (GetInitLCDecl(CE->getArg(0)) == LCDecl) 3209 return SetStep(CE->getArg(1), !IsAdd); 3210 if (IsAdd && GetInitLCDecl(CE->getArg(1)) == LCDecl) 3211 return SetStep(CE->getArg(0), false); 3212 } 3213 } 3214 if (Dependent() || SemaRef.CurContext->isDependentContext()) 3215 return false; 3216 SemaRef.Diag(RHS->getLocStart(), diag::err_omp_loop_not_canonical_incr) 3217 << RHS->getSourceRange() << LCDecl; 3218 return true; 3219 } 3220 3221 bool OpenMPIterationSpaceChecker::CheckInc(Expr *S) { 3222 // Check incr-expr for canonical loop form and return true if it 3223 // does not conform. 3224 // OpenMP [2.6] Canonical loop form. Test-expr may be one of the following: 3225 // ++var 3226 // var++ 3227 // --var 3228 // var-- 3229 // var += incr 3230 // var -= incr 3231 // var = var + incr 3232 // var = incr + var 3233 // var = var - incr 3234 // 3235 if (!S) { 3236 SemaRef.Diag(DefaultLoc, diag::err_omp_loop_not_canonical_incr) << LCDecl; 3237 return true; 3238 } 3239 if (auto *ExprTemp = dyn_cast<ExprWithCleanups>(S)) 3240 if (!ExprTemp->cleanupsHaveSideEffects()) 3241 S = ExprTemp->getSubExpr(); 3242 3243 IncrementSrcRange = S->getSourceRange(); 3244 S = S->IgnoreParens(); 3245 if (auto *UO = dyn_cast<UnaryOperator>(S)) { 3246 if (UO->isIncrementDecrementOp() && 3247 GetInitLCDecl(UO->getSubExpr()) == LCDecl) 3248 return SetStep(SemaRef 3249 .ActOnIntegerConstant(UO->getLocStart(), 3250 (UO->isDecrementOp() ? -1 : 1)) 3251 .get(), 3252 false); 3253 } else if (auto *BO = dyn_cast<BinaryOperator>(S)) { 3254 switch (BO->getOpcode()) { 3255 case BO_AddAssign: 3256 case BO_SubAssign: 3257 if (GetInitLCDecl(BO->getLHS()) == LCDecl) 3258 return SetStep(BO->getRHS(), BO->getOpcode() == BO_SubAssign); 3259 break; 3260 case BO_Assign: 3261 if (GetInitLCDecl(BO->getLHS()) == LCDecl) 3262 return CheckIncRHS(BO->getRHS()); 3263 break; 3264 default: 3265 break; 3266 } 3267 } else if (auto *CE = dyn_cast<CXXOperatorCallExpr>(S)) { 3268 switch (CE->getOperator()) { 3269 case OO_PlusPlus: 3270 case OO_MinusMinus: 3271 if (GetInitLCDecl(CE->getArg(0)) == LCDecl) 3272 return SetStep(SemaRef 3273 .ActOnIntegerConstant( 3274 CE->getLocStart(), 3275 ((CE->getOperator() == OO_MinusMinus) ? -1 : 1)) 3276 .get(), 3277 false); 3278 break; 3279 case OO_PlusEqual: 3280 case OO_MinusEqual: 3281 if (GetInitLCDecl(CE->getArg(0)) == LCDecl) 3282 return SetStep(CE->getArg(1), CE->getOperator() == OO_MinusEqual); 3283 break; 3284 case OO_Equal: 3285 if (GetInitLCDecl(CE->getArg(0)) == LCDecl) 3286 return CheckIncRHS(CE->getArg(1)); 3287 break; 3288 default: 3289 break; 3290 } 3291 } 3292 if (Dependent() || SemaRef.CurContext->isDependentContext()) 3293 return false; 3294 SemaRef.Diag(S->getLocStart(), diag::err_omp_loop_not_canonical_incr) 3295 << S->getSourceRange() << LCDecl; 3296 return true; 3297 } 3298 3299 static ExprResult 3300 tryBuildCapture(Sema &SemaRef, Expr *Capture, 3301 llvm::MapVector<Expr *, DeclRefExpr *> &Captures) { 3302 if (SemaRef.CurContext->isDependentContext()) 3303 return ExprResult(Capture); 3304 if (Capture->isEvaluatable(SemaRef.Context, Expr::SE_AllowSideEffects)) 3305 return SemaRef.PerformImplicitConversion( 3306 Capture->IgnoreImpCasts(), Capture->getType(), Sema::AA_Converting, 3307 /*AllowExplicit=*/true); 3308 auto I = Captures.find(Capture); 3309 if (I != Captures.end()) 3310 return buildCapture(SemaRef, Capture, I->second); 3311 DeclRefExpr *Ref = nullptr; 3312 ExprResult Res = buildCapture(SemaRef, Capture, Ref); 3313 Captures[Capture] = Ref; 3314 return Res; 3315 } 3316 3317 /// \brief Build the expression to calculate the number of iterations. 3318 Expr *OpenMPIterationSpaceChecker::BuildNumIterations( 3319 Scope *S, const bool LimitedType, 3320 llvm::MapVector<Expr *, DeclRefExpr *> &Captures) const { 3321 ExprResult Diff; 3322 auto VarType = LCDecl->getType().getNonReferenceType(); 3323 if (VarType->isIntegerType() || VarType->isPointerType() || 3324 SemaRef.getLangOpts().CPlusPlus) { 3325 // Upper - Lower 3326 auto *UBExpr = TestIsLessOp ? UB : LB; 3327 auto *LBExpr = TestIsLessOp ? LB : UB; 3328 Expr *Upper = tryBuildCapture(SemaRef, UBExpr, Captures).get(); 3329 Expr *Lower = tryBuildCapture(SemaRef, LBExpr, Captures).get(); 3330 if (!Upper || !Lower) 3331 return nullptr; 3332 3333 Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Sub, Upper, Lower); 3334 3335 if (!Diff.isUsable() && VarType->getAsCXXRecordDecl()) { 3336 // BuildBinOp already emitted error, this one is to point user to upper 3337 // and lower bound, and to tell what is passed to 'operator-'. 3338 SemaRef.Diag(Upper->getLocStart(), diag::err_omp_loop_diff_cxx) 3339 << Upper->getSourceRange() << Lower->getSourceRange(); 3340 return nullptr; 3341 } 3342 } 3343 3344 if (!Diff.isUsable()) 3345 return nullptr; 3346 3347 // Upper - Lower [- 1] 3348 if (TestIsStrictOp) 3349 Diff = SemaRef.BuildBinOp( 3350 S, DefaultLoc, BO_Sub, Diff.get(), 3351 SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get()); 3352 if (!Diff.isUsable()) 3353 return nullptr; 3354 3355 // Upper - Lower [- 1] + Step 3356 auto NewStep = tryBuildCapture(SemaRef, Step, Captures); 3357 if (!NewStep.isUsable()) 3358 return nullptr; 3359 Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Add, Diff.get(), NewStep.get()); 3360 if (!Diff.isUsable()) 3361 return nullptr; 3362 3363 // Parentheses (for dumping/debugging purposes only). 3364 Diff = SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, Diff.get()); 3365 if (!Diff.isUsable()) 3366 return nullptr; 3367 3368 // (Upper - Lower [- 1] + Step) / Step 3369 Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Div, Diff.get(), NewStep.get()); 3370 if (!Diff.isUsable()) 3371 return nullptr; 3372 3373 // OpenMP runtime requires 32-bit or 64-bit loop variables. 3374 QualType Type = Diff.get()->getType(); 3375 auto &C = SemaRef.Context; 3376 bool UseVarType = VarType->hasIntegerRepresentation() && 3377 C.getTypeSize(Type) > C.getTypeSize(VarType); 3378 if (!Type->isIntegerType() || UseVarType) { 3379 unsigned NewSize = 3380 UseVarType ? C.getTypeSize(VarType) : C.getTypeSize(Type); 3381 bool IsSigned = UseVarType ? VarType->hasSignedIntegerRepresentation() 3382 : Type->hasSignedIntegerRepresentation(); 3383 Type = C.getIntTypeForBitwidth(NewSize, IsSigned); 3384 if (!SemaRef.Context.hasSameType(Diff.get()->getType(), Type)) { 3385 Diff = SemaRef.PerformImplicitConversion( 3386 Diff.get(), Type, Sema::AA_Converting, /*AllowExplicit=*/true); 3387 if (!Diff.isUsable()) 3388 return nullptr; 3389 } 3390 } 3391 if (LimitedType) { 3392 unsigned NewSize = (C.getTypeSize(Type) > 32) ? 64 : 32; 3393 if (NewSize != C.getTypeSize(Type)) { 3394 if (NewSize < C.getTypeSize(Type)) { 3395 assert(NewSize == 64 && "incorrect loop var size"); 3396 SemaRef.Diag(DefaultLoc, diag::warn_omp_loop_64_bit_var) 3397 << InitSrcRange << ConditionSrcRange; 3398 } 3399 QualType NewType = C.getIntTypeForBitwidth( 3400 NewSize, Type->hasSignedIntegerRepresentation() || 3401 C.getTypeSize(Type) < NewSize); 3402 if (!SemaRef.Context.hasSameType(Diff.get()->getType(), NewType)) { 3403 Diff = SemaRef.PerformImplicitConversion(Diff.get(), NewType, 3404 Sema::AA_Converting, true); 3405 if (!Diff.isUsable()) 3406 return nullptr; 3407 } 3408 } 3409 } 3410 3411 return Diff.get(); 3412 } 3413 3414 Expr *OpenMPIterationSpaceChecker::BuildPreCond( 3415 Scope *S, Expr *Cond, 3416 llvm::MapVector<Expr *, DeclRefExpr *> &Captures) const { 3417 // Try to build LB <op> UB, where <op> is <, >, <=, or >=. 3418 bool Suppress = SemaRef.getDiagnostics().getSuppressAllDiagnostics(); 3419 SemaRef.getDiagnostics().setSuppressAllDiagnostics(/*Val=*/true); 3420 3421 auto NewLB = tryBuildCapture(SemaRef, LB, Captures); 3422 auto NewUB = tryBuildCapture(SemaRef, UB, Captures); 3423 if (!NewLB.isUsable() || !NewUB.isUsable()) 3424 return nullptr; 3425 3426 auto CondExpr = SemaRef.BuildBinOp( 3427 S, DefaultLoc, TestIsLessOp ? (TestIsStrictOp ? BO_LT : BO_LE) 3428 : (TestIsStrictOp ? BO_GT : BO_GE), 3429 NewLB.get(), NewUB.get()); 3430 if (CondExpr.isUsable()) { 3431 if (!SemaRef.Context.hasSameUnqualifiedType(CondExpr.get()->getType(), 3432 SemaRef.Context.BoolTy)) 3433 CondExpr = SemaRef.PerformImplicitConversion( 3434 CondExpr.get(), SemaRef.Context.BoolTy, /*Action=*/Sema::AA_Casting, 3435 /*AllowExplicit=*/true); 3436 } 3437 SemaRef.getDiagnostics().setSuppressAllDiagnostics(Suppress); 3438 // Otherwise use original loop conditon and evaluate it in runtime. 3439 return CondExpr.isUsable() ? CondExpr.get() : Cond; 3440 } 3441 3442 /// \brief Build reference expression to the counter be used for codegen. 3443 DeclRefExpr *OpenMPIterationSpaceChecker::BuildCounterVar( 3444 llvm::MapVector<Expr *, DeclRefExpr *> &Captures, DSAStackTy &DSA) const { 3445 auto *VD = dyn_cast<VarDecl>(LCDecl); 3446 if (!VD) { 3447 VD = SemaRef.IsOpenMPCapturedDecl(LCDecl); 3448 auto *Ref = buildDeclRefExpr( 3449 SemaRef, VD, VD->getType().getNonReferenceType(), DefaultLoc); 3450 DSAStackTy::DSAVarData Data = DSA.getTopDSA(LCDecl, /*FromParent=*/false); 3451 // If the loop control decl is explicitly marked as private, do not mark it 3452 // as captured again. 3453 if (!isOpenMPPrivate(Data.CKind) || !Data.RefExpr) 3454 Captures.insert(std::make_pair(LCRef, Ref)); 3455 return Ref; 3456 } 3457 return buildDeclRefExpr(SemaRef, VD, VD->getType().getNonReferenceType(), 3458 DefaultLoc); 3459 } 3460 3461 Expr *OpenMPIterationSpaceChecker::BuildPrivateCounterVar() const { 3462 if (LCDecl && !LCDecl->isInvalidDecl()) { 3463 auto Type = LCDecl->getType().getNonReferenceType(); 3464 auto *PrivateVar = 3465 buildVarDecl(SemaRef, DefaultLoc, Type, LCDecl->getName(), 3466 LCDecl->hasAttrs() ? &LCDecl->getAttrs() : nullptr); 3467 if (PrivateVar->isInvalidDecl()) 3468 return nullptr; 3469 return buildDeclRefExpr(SemaRef, PrivateVar, Type, DefaultLoc); 3470 } 3471 return nullptr; 3472 } 3473 3474 /// \brief Build initialization of the counter to be used for codegen. 3475 Expr *OpenMPIterationSpaceChecker::BuildCounterInit() const { return LB; } 3476 3477 /// \brief Build step of the counter be used for codegen. 3478 Expr *OpenMPIterationSpaceChecker::BuildCounterStep() const { return Step; } 3479 3480 /// \brief Iteration space of a single for loop. 3481 struct LoopIterationSpace final { 3482 /// \brief Condition of the loop. 3483 Expr *PreCond = nullptr; 3484 /// \brief This expression calculates the number of iterations in the loop. 3485 /// It is always possible to calculate it before starting the loop. 3486 Expr *NumIterations = nullptr; 3487 /// \brief The loop counter variable. 3488 Expr *CounterVar = nullptr; 3489 /// \brief Private loop counter variable. 3490 Expr *PrivateCounterVar = nullptr; 3491 /// \brief This is initializer for the initial value of #CounterVar. 3492 Expr *CounterInit = nullptr; 3493 /// \brief This is step for the #CounterVar used to generate its update: 3494 /// #CounterVar = #CounterInit + #CounterStep * CurrentIteration. 3495 Expr *CounterStep = nullptr; 3496 /// \brief Should step be subtracted? 3497 bool Subtract = false; 3498 /// \brief Source range of the loop init. 3499 SourceRange InitSrcRange; 3500 /// \brief Source range of the loop condition. 3501 SourceRange CondSrcRange; 3502 /// \brief Source range of the loop increment. 3503 SourceRange IncSrcRange; 3504 }; 3505 3506 } // namespace 3507 3508 void Sema::ActOnOpenMPLoopInitialization(SourceLocation ForLoc, Stmt *Init) { 3509 assert(getLangOpts().OpenMP && "OpenMP is not active."); 3510 assert(Init && "Expected loop in canonical form."); 3511 unsigned AssociatedLoops = DSAStack->getAssociatedLoops(); 3512 if (AssociatedLoops > 0 && 3513 isOpenMPLoopDirective(DSAStack->getCurrentDirective())) { 3514 OpenMPIterationSpaceChecker ISC(*this, ForLoc); 3515 if (!ISC.CheckInit(Init, /*EmitDiags=*/false)) { 3516 if (auto *D = ISC.GetLoopDecl()) { 3517 auto *VD = dyn_cast<VarDecl>(D); 3518 if (!VD) { 3519 if (auto *Private = IsOpenMPCapturedDecl(D)) 3520 VD = Private; 3521 else { 3522 auto *Ref = buildCapture(*this, D, ISC.GetLoopDeclRefExpr(), 3523 /*WithInit=*/false); 3524 VD = cast<VarDecl>(Ref->getDecl()); 3525 } 3526 } 3527 DSAStack->addLoopControlVariable(D, VD); 3528 } 3529 } 3530 DSAStack->setAssociatedLoops(AssociatedLoops - 1); 3531 } 3532 } 3533 3534 /// \brief Called on a for stmt to check and extract its iteration space 3535 /// for further processing (such as collapsing). 3536 static bool CheckOpenMPIterationSpace( 3537 OpenMPDirectiveKind DKind, Stmt *S, Sema &SemaRef, DSAStackTy &DSA, 3538 unsigned CurrentNestedLoopCount, unsigned NestedLoopCount, 3539 Expr *CollapseLoopCountExpr, Expr *OrderedLoopCountExpr, 3540 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA, 3541 LoopIterationSpace &ResultIterSpace, 3542 llvm::MapVector<Expr *, DeclRefExpr *> &Captures) { 3543 // OpenMP [2.6, Canonical Loop Form] 3544 // for (init-expr; test-expr; incr-expr) structured-block 3545 auto *For = dyn_cast_or_null<ForStmt>(S); 3546 if (!For) { 3547 SemaRef.Diag(S->getLocStart(), diag::err_omp_not_for) 3548 << (CollapseLoopCountExpr != nullptr || OrderedLoopCountExpr != nullptr) 3549 << getOpenMPDirectiveName(DKind) << NestedLoopCount 3550 << (CurrentNestedLoopCount > 0) << CurrentNestedLoopCount; 3551 if (NestedLoopCount > 1) { 3552 if (CollapseLoopCountExpr && OrderedLoopCountExpr) 3553 SemaRef.Diag(DSA.getConstructLoc(), 3554 diag::note_omp_collapse_ordered_expr) 3555 << 2 << CollapseLoopCountExpr->getSourceRange() 3556 << OrderedLoopCountExpr->getSourceRange(); 3557 else if (CollapseLoopCountExpr) 3558 SemaRef.Diag(CollapseLoopCountExpr->getExprLoc(), 3559 diag::note_omp_collapse_ordered_expr) 3560 << 0 << CollapseLoopCountExpr->getSourceRange(); 3561 else 3562 SemaRef.Diag(OrderedLoopCountExpr->getExprLoc(), 3563 diag::note_omp_collapse_ordered_expr) 3564 << 1 << OrderedLoopCountExpr->getSourceRange(); 3565 } 3566 return true; 3567 } 3568 assert(For->getBody()); 3569 3570 OpenMPIterationSpaceChecker ISC(SemaRef, For->getForLoc()); 3571 3572 // Check init. 3573 auto Init = For->getInit(); 3574 if (ISC.CheckInit(Init)) 3575 return true; 3576 3577 bool HasErrors = false; 3578 3579 // Check loop variable's type. 3580 if (auto *LCDecl = ISC.GetLoopDecl()) { 3581 auto *LoopDeclRefExpr = ISC.GetLoopDeclRefExpr(); 3582 3583 // OpenMP [2.6, Canonical Loop Form] 3584 // Var is one of the following: 3585 // A variable of signed or unsigned integer type. 3586 // For C++, a variable of a random access iterator type. 3587 // For C, a variable of a pointer type. 3588 auto VarType = LCDecl->getType().getNonReferenceType(); 3589 if (!VarType->isDependentType() && !VarType->isIntegerType() && 3590 !VarType->isPointerType() && 3591 !(SemaRef.getLangOpts().CPlusPlus && VarType->isOverloadableType())) { 3592 SemaRef.Diag(Init->getLocStart(), diag::err_omp_loop_variable_type) 3593 << SemaRef.getLangOpts().CPlusPlus; 3594 HasErrors = true; 3595 } 3596 3597 // OpenMP, 2.14.1.1 Data-sharing Attribute Rules for Variables Referenced in 3598 // a Construct 3599 // The loop iteration variable(s) in the associated for-loop(s) of a for or 3600 // parallel for construct is (are) private. 3601 // The loop iteration variable in the associated for-loop of a simd 3602 // construct with just one associated for-loop is linear with a 3603 // constant-linear-step that is the increment of the associated for-loop. 3604 // Exclude loop var from the list of variables with implicitly defined data 3605 // sharing attributes. 3606 VarsWithImplicitDSA.erase(LCDecl); 3607 3608 // OpenMP [2.14.1.1, Data-sharing Attribute Rules for Variables Referenced 3609 // in a Construct, C/C++]. 3610 // The loop iteration variable in the associated for-loop of a simd 3611 // construct with just one associated for-loop may be listed in a linear 3612 // clause with a constant-linear-step that is the increment of the 3613 // associated for-loop. 3614 // The loop iteration variable(s) in the associated for-loop(s) of a for or 3615 // parallel for construct may be listed in a private or lastprivate clause. 3616 DSAStackTy::DSAVarData DVar = DSA.getTopDSA(LCDecl, false); 3617 // If LoopVarRefExpr is nullptr it means the corresponding loop variable is 3618 // declared in the loop and it is predetermined as a private. 3619 auto PredeterminedCKind = 3620 isOpenMPSimdDirective(DKind) 3621 ? ((NestedLoopCount == 1) ? OMPC_linear : OMPC_lastprivate) 3622 : OMPC_private; 3623 if (((isOpenMPSimdDirective(DKind) && DVar.CKind != OMPC_unknown && 3624 DVar.CKind != PredeterminedCKind) || 3625 ((isOpenMPWorksharingDirective(DKind) || DKind == OMPD_taskloop || 3626 isOpenMPDistributeDirective(DKind)) && 3627 !isOpenMPSimdDirective(DKind) && DVar.CKind != OMPC_unknown && 3628 DVar.CKind != OMPC_private && DVar.CKind != OMPC_lastprivate)) && 3629 (DVar.CKind != OMPC_private || DVar.RefExpr != nullptr)) { 3630 SemaRef.Diag(Init->getLocStart(), diag::err_omp_loop_var_dsa) 3631 << getOpenMPClauseName(DVar.CKind) << getOpenMPDirectiveName(DKind) 3632 << getOpenMPClauseName(PredeterminedCKind); 3633 if (DVar.RefExpr == nullptr) 3634 DVar.CKind = PredeterminedCKind; 3635 ReportOriginalDSA(SemaRef, &DSA, LCDecl, DVar, /*IsLoopIterVar=*/true); 3636 HasErrors = true; 3637 } else if (LoopDeclRefExpr != nullptr) { 3638 // Make the loop iteration variable private (for worksharing constructs), 3639 // linear (for simd directives with the only one associated loop) or 3640 // lastprivate (for simd directives with several collapsed or ordered 3641 // loops). 3642 if (DVar.CKind == OMPC_unknown) 3643 DVar = DSA.hasDSA(LCDecl, isOpenMPPrivate, 3644 [](OpenMPDirectiveKind) -> bool { return true; }, 3645 /*FromParent=*/false); 3646 DSA.addDSA(LCDecl, LoopDeclRefExpr, PredeterminedCKind); 3647 } 3648 3649 assert(isOpenMPLoopDirective(DKind) && "DSA for non-loop vars"); 3650 3651 // Check test-expr. 3652 HasErrors |= ISC.CheckCond(For->getCond()); 3653 3654 // Check incr-expr. 3655 HasErrors |= ISC.CheckInc(For->getInc()); 3656 } 3657 3658 if (ISC.Dependent() || SemaRef.CurContext->isDependentContext() || HasErrors) 3659 return HasErrors; 3660 3661 // Build the loop's iteration space representation. 3662 ResultIterSpace.PreCond = 3663 ISC.BuildPreCond(DSA.getCurScope(), For->getCond(), Captures); 3664 ResultIterSpace.NumIterations = ISC.BuildNumIterations( 3665 DSA.getCurScope(), 3666 (isOpenMPWorksharingDirective(DKind) || 3667 isOpenMPTaskLoopDirective(DKind) || isOpenMPDistributeDirective(DKind)), 3668 Captures); 3669 ResultIterSpace.CounterVar = ISC.BuildCounterVar(Captures, DSA); 3670 ResultIterSpace.PrivateCounterVar = ISC.BuildPrivateCounterVar(); 3671 ResultIterSpace.CounterInit = ISC.BuildCounterInit(); 3672 ResultIterSpace.CounterStep = ISC.BuildCounterStep(); 3673 ResultIterSpace.InitSrcRange = ISC.GetInitSrcRange(); 3674 ResultIterSpace.CondSrcRange = ISC.GetConditionSrcRange(); 3675 ResultIterSpace.IncSrcRange = ISC.GetIncrementSrcRange(); 3676 ResultIterSpace.Subtract = ISC.ShouldSubtractStep(); 3677 3678 HasErrors |= (ResultIterSpace.PreCond == nullptr || 3679 ResultIterSpace.NumIterations == nullptr || 3680 ResultIterSpace.CounterVar == nullptr || 3681 ResultIterSpace.PrivateCounterVar == nullptr || 3682 ResultIterSpace.CounterInit == nullptr || 3683 ResultIterSpace.CounterStep == nullptr); 3684 3685 return HasErrors; 3686 } 3687 3688 /// \brief Build 'VarRef = Start. 3689 static ExprResult 3690 BuildCounterInit(Sema &SemaRef, Scope *S, SourceLocation Loc, ExprResult VarRef, 3691 ExprResult Start, 3692 llvm::MapVector<Expr *, DeclRefExpr *> &Captures) { 3693 // Build 'VarRef = Start. 3694 auto NewStart = tryBuildCapture(SemaRef, Start.get(), Captures); 3695 if (!NewStart.isUsable()) 3696 return ExprError(); 3697 if (!SemaRef.Context.hasSameType(NewStart.get()->getType(), 3698 VarRef.get()->getType())) { 3699 NewStart = SemaRef.PerformImplicitConversion( 3700 NewStart.get(), VarRef.get()->getType(), Sema::AA_Converting, 3701 /*AllowExplicit=*/true); 3702 if (!NewStart.isUsable()) 3703 return ExprError(); 3704 } 3705 3706 auto Init = 3707 SemaRef.BuildBinOp(S, Loc, BO_Assign, VarRef.get(), NewStart.get()); 3708 return Init; 3709 } 3710 3711 /// \brief Build 'VarRef = Start + Iter * Step'. 3712 static ExprResult 3713 BuildCounterUpdate(Sema &SemaRef, Scope *S, SourceLocation Loc, 3714 ExprResult VarRef, ExprResult Start, ExprResult Iter, 3715 ExprResult Step, bool Subtract, 3716 llvm::MapVector<Expr *, DeclRefExpr *> *Captures = nullptr) { 3717 // Add parentheses (for debugging purposes only). 3718 Iter = SemaRef.ActOnParenExpr(Loc, Loc, Iter.get()); 3719 if (!VarRef.isUsable() || !Start.isUsable() || !Iter.isUsable() || 3720 !Step.isUsable()) 3721 return ExprError(); 3722 3723 ExprResult NewStep = Step; 3724 if (Captures) 3725 NewStep = tryBuildCapture(SemaRef, Step.get(), *Captures); 3726 if (NewStep.isInvalid()) 3727 return ExprError(); 3728 ExprResult Update = 3729 SemaRef.BuildBinOp(S, Loc, BO_Mul, Iter.get(), NewStep.get()); 3730 if (!Update.isUsable()) 3731 return ExprError(); 3732 3733 // Try to build 'VarRef = Start, VarRef (+|-)= Iter * Step' or 3734 // 'VarRef = Start (+|-) Iter * Step'. 3735 ExprResult NewStart = Start; 3736 if (Captures) 3737 NewStart = tryBuildCapture(SemaRef, Start.get(), *Captures); 3738 if (NewStart.isInvalid()) 3739 return ExprError(); 3740 3741 // First attempt: try to build 'VarRef = Start, VarRef += Iter * Step'. 3742 ExprResult SavedUpdate = Update; 3743 ExprResult UpdateVal; 3744 if (VarRef.get()->getType()->isOverloadableType() || 3745 NewStart.get()->getType()->isOverloadableType() || 3746 Update.get()->getType()->isOverloadableType()) { 3747 bool Suppress = SemaRef.getDiagnostics().getSuppressAllDiagnostics(); 3748 SemaRef.getDiagnostics().setSuppressAllDiagnostics(/*Val=*/true); 3749 Update = 3750 SemaRef.BuildBinOp(S, Loc, BO_Assign, VarRef.get(), NewStart.get()); 3751 if (Update.isUsable()) { 3752 UpdateVal = 3753 SemaRef.BuildBinOp(S, Loc, Subtract ? BO_SubAssign : BO_AddAssign, 3754 VarRef.get(), SavedUpdate.get()); 3755 if (UpdateVal.isUsable()) { 3756 Update = SemaRef.CreateBuiltinBinOp(Loc, BO_Comma, Update.get(), 3757 UpdateVal.get()); 3758 } 3759 } 3760 SemaRef.getDiagnostics().setSuppressAllDiagnostics(Suppress); 3761 } 3762 3763 // Second attempt: try to build 'VarRef = Start (+|-) Iter * Step'. 3764 if (!Update.isUsable() || !UpdateVal.isUsable()) { 3765 Update = SemaRef.BuildBinOp(S, Loc, Subtract ? BO_Sub : BO_Add, 3766 NewStart.get(), SavedUpdate.get()); 3767 if (!Update.isUsable()) 3768 return ExprError(); 3769 3770 if (!SemaRef.Context.hasSameType(Update.get()->getType(), 3771 VarRef.get()->getType())) { 3772 Update = SemaRef.PerformImplicitConversion( 3773 Update.get(), VarRef.get()->getType(), Sema::AA_Converting, true); 3774 if (!Update.isUsable()) 3775 return ExprError(); 3776 } 3777 3778 Update = SemaRef.BuildBinOp(S, Loc, BO_Assign, VarRef.get(), Update.get()); 3779 } 3780 return Update; 3781 } 3782 3783 /// \brief Convert integer expression \a E to make it have at least \a Bits 3784 /// bits. 3785 static ExprResult WidenIterationCount(unsigned Bits, Expr *E, Sema &SemaRef) { 3786 if (E == nullptr) 3787 return ExprError(); 3788 auto &C = SemaRef.Context; 3789 QualType OldType = E->getType(); 3790 unsigned HasBits = C.getTypeSize(OldType); 3791 if (HasBits >= Bits) 3792 return ExprResult(E); 3793 // OK to convert to signed, because new type has more bits than old. 3794 QualType NewType = C.getIntTypeForBitwidth(Bits, /* Signed */ true); 3795 return SemaRef.PerformImplicitConversion(E, NewType, Sema::AA_Converting, 3796 true); 3797 } 3798 3799 /// \brief Check if the given expression \a E is a constant integer that fits 3800 /// into \a Bits bits. 3801 static bool FitsInto(unsigned Bits, bool Signed, Expr *E, Sema &SemaRef) { 3802 if (E == nullptr) 3803 return false; 3804 llvm::APSInt Result; 3805 if (E->isIntegerConstantExpr(Result, SemaRef.Context)) 3806 return Signed ? Result.isSignedIntN(Bits) : Result.isIntN(Bits); 3807 return false; 3808 } 3809 3810 /// Build preinits statement for the given declarations. 3811 static Stmt *buildPreInits(ASTContext &Context, 3812 SmallVectorImpl<Decl *> &PreInits) { 3813 if (!PreInits.empty()) { 3814 return new (Context) DeclStmt( 3815 DeclGroupRef::Create(Context, PreInits.begin(), PreInits.size()), 3816 SourceLocation(), SourceLocation()); 3817 } 3818 return nullptr; 3819 } 3820 3821 /// Build preinits statement for the given declarations. 3822 static Stmt *buildPreInits(ASTContext &Context, 3823 llvm::MapVector<Expr *, DeclRefExpr *> &Captures) { 3824 if (!Captures.empty()) { 3825 SmallVector<Decl *, 16> PreInits; 3826 for (auto &Pair : Captures) 3827 PreInits.push_back(Pair.second->getDecl()); 3828 return buildPreInits(Context, PreInits); 3829 } 3830 return nullptr; 3831 } 3832 3833 /// Build postupdate expression for the given list of postupdates expressions. 3834 static Expr *buildPostUpdate(Sema &S, ArrayRef<Expr *> PostUpdates) { 3835 Expr *PostUpdate = nullptr; 3836 if (!PostUpdates.empty()) { 3837 for (auto *E : PostUpdates) { 3838 Expr *ConvE = S.BuildCStyleCastExpr( 3839 E->getExprLoc(), 3840 S.Context.getTrivialTypeSourceInfo(S.Context.VoidTy), 3841 E->getExprLoc(), E) 3842 .get(); 3843 PostUpdate = PostUpdate 3844 ? S.CreateBuiltinBinOp(ConvE->getExprLoc(), BO_Comma, 3845 PostUpdate, ConvE) 3846 .get() 3847 : ConvE; 3848 } 3849 } 3850 return PostUpdate; 3851 } 3852 3853 /// \brief Called on a for stmt to check itself and nested loops (if any). 3854 /// \return Returns 0 if one of the collapsed stmts is not canonical for loop, 3855 /// number of collapsed loops otherwise. 3856 static unsigned 3857 CheckOpenMPLoop(OpenMPDirectiveKind DKind, Expr *CollapseLoopCountExpr, 3858 Expr *OrderedLoopCountExpr, Stmt *AStmt, Sema &SemaRef, 3859 DSAStackTy &DSA, 3860 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA, 3861 OMPLoopDirective::HelperExprs &Built) { 3862 unsigned NestedLoopCount = 1; 3863 if (CollapseLoopCountExpr) { 3864 // Found 'collapse' clause - calculate collapse number. 3865 llvm::APSInt Result; 3866 if (CollapseLoopCountExpr->EvaluateAsInt(Result, SemaRef.getASTContext())) 3867 NestedLoopCount = Result.getLimitedValue(); 3868 } 3869 if (OrderedLoopCountExpr) { 3870 // Found 'ordered' clause - calculate collapse number. 3871 llvm::APSInt Result; 3872 if (OrderedLoopCountExpr->EvaluateAsInt(Result, SemaRef.getASTContext())) { 3873 if (Result.getLimitedValue() < NestedLoopCount) { 3874 SemaRef.Diag(OrderedLoopCountExpr->getExprLoc(), 3875 diag::err_omp_wrong_ordered_loop_count) 3876 << OrderedLoopCountExpr->getSourceRange(); 3877 SemaRef.Diag(CollapseLoopCountExpr->getExprLoc(), 3878 diag::note_collapse_loop_count) 3879 << CollapseLoopCountExpr->getSourceRange(); 3880 } 3881 NestedLoopCount = Result.getLimitedValue(); 3882 } 3883 } 3884 // This is helper routine for loop directives (e.g., 'for', 'simd', 3885 // 'for simd', etc.). 3886 llvm::MapVector<Expr *, DeclRefExpr *> Captures; 3887 SmallVector<LoopIterationSpace, 4> IterSpaces; 3888 IterSpaces.resize(NestedLoopCount); 3889 Stmt *CurStmt = AStmt->IgnoreContainers(/* IgnoreCaptured */ true); 3890 for (unsigned Cnt = 0; Cnt < NestedLoopCount; ++Cnt) { 3891 if (CheckOpenMPIterationSpace(DKind, CurStmt, SemaRef, DSA, Cnt, 3892 NestedLoopCount, CollapseLoopCountExpr, 3893 OrderedLoopCountExpr, VarsWithImplicitDSA, 3894 IterSpaces[Cnt], Captures)) 3895 return 0; 3896 // Move on to the next nested for loop, or to the loop body. 3897 // OpenMP [2.8.1, simd construct, Restrictions] 3898 // All loops associated with the construct must be perfectly nested; that 3899 // is, there must be no intervening code nor any OpenMP directive between 3900 // any two loops. 3901 CurStmt = cast<ForStmt>(CurStmt)->getBody()->IgnoreContainers(); 3902 } 3903 3904 Built.clear(/* size */ NestedLoopCount); 3905 3906 if (SemaRef.CurContext->isDependentContext()) 3907 return NestedLoopCount; 3908 3909 // An example of what is generated for the following code: 3910 // 3911 // #pragma omp simd collapse(2) ordered(2) 3912 // for (i = 0; i < NI; ++i) 3913 // for (k = 0; k < NK; ++k) 3914 // for (j = J0; j < NJ; j+=2) { 3915 // <loop body> 3916 // } 3917 // 3918 // We generate the code below. 3919 // Note: the loop body may be outlined in CodeGen. 3920 // Note: some counters may be C++ classes, operator- is used to find number of 3921 // iterations and operator+= to calculate counter value. 3922 // Note: decltype(NumIterations) must be integer type (in 'omp for', only i32 3923 // or i64 is currently supported). 3924 // 3925 // #define NumIterations (NI * ((NJ - J0 - 1 + 2) / 2)) 3926 // for (int[32|64]_t IV = 0; IV < NumIterations; ++IV ) { 3927 // .local.i = IV / ((NJ - J0 - 1 + 2) / 2); 3928 // .local.j = J0 + (IV % ((NJ - J0 - 1 + 2) / 2)) * 2; 3929 // // similar updates for vars in clauses (e.g. 'linear') 3930 // <loop body (using local i and j)> 3931 // } 3932 // i = NI; // assign final values of counters 3933 // j = NJ; 3934 // 3935 3936 // Last iteration number is (I1 * I2 * ... In) - 1, where I1, I2 ... In are 3937 // the iteration counts of the collapsed for loops. 3938 // Precondition tests if there is at least one iteration (all conditions are 3939 // true). 3940 auto PreCond = ExprResult(IterSpaces[0].PreCond); 3941 auto N0 = IterSpaces[0].NumIterations; 3942 ExprResult LastIteration32 = WidenIterationCount( 3943 32 /* Bits */, SemaRef 3944 .PerformImplicitConversion( 3945 N0->IgnoreImpCasts(), N0->getType(), 3946 Sema::AA_Converting, /*AllowExplicit=*/true) 3947 .get(), 3948 SemaRef); 3949 ExprResult LastIteration64 = WidenIterationCount( 3950 64 /* Bits */, SemaRef 3951 .PerformImplicitConversion( 3952 N0->IgnoreImpCasts(), N0->getType(), 3953 Sema::AA_Converting, /*AllowExplicit=*/true) 3954 .get(), 3955 SemaRef); 3956 3957 if (!LastIteration32.isUsable() || !LastIteration64.isUsable()) 3958 return NestedLoopCount; 3959 3960 auto &C = SemaRef.Context; 3961 bool AllCountsNeedLessThan32Bits = C.getTypeSize(N0->getType()) < 32; 3962 3963 Scope *CurScope = DSA.getCurScope(); 3964 for (unsigned Cnt = 1; Cnt < NestedLoopCount; ++Cnt) { 3965 if (PreCond.isUsable()) { 3966 PreCond = 3967 SemaRef.BuildBinOp(CurScope, PreCond.get()->getExprLoc(), BO_LAnd, 3968 PreCond.get(), IterSpaces[Cnt].PreCond); 3969 } 3970 auto N = IterSpaces[Cnt].NumIterations; 3971 SourceLocation Loc = N->getExprLoc(); 3972 AllCountsNeedLessThan32Bits &= C.getTypeSize(N->getType()) < 32; 3973 if (LastIteration32.isUsable()) 3974 LastIteration32 = SemaRef.BuildBinOp( 3975 CurScope, Loc, BO_Mul, LastIteration32.get(), 3976 SemaRef 3977 .PerformImplicitConversion(N->IgnoreImpCasts(), N->getType(), 3978 Sema::AA_Converting, 3979 /*AllowExplicit=*/true) 3980 .get()); 3981 if (LastIteration64.isUsable()) 3982 LastIteration64 = SemaRef.BuildBinOp( 3983 CurScope, Loc, BO_Mul, LastIteration64.get(), 3984 SemaRef 3985 .PerformImplicitConversion(N->IgnoreImpCasts(), N->getType(), 3986 Sema::AA_Converting, 3987 /*AllowExplicit=*/true) 3988 .get()); 3989 } 3990 3991 // Choose either the 32-bit or 64-bit version. 3992 ExprResult LastIteration = LastIteration64; 3993 if (LastIteration32.isUsable() && 3994 C.getTypeSize(LastIteration32.get()->getType()) == 32 && 3995 (AllCountsNeedLessThan32Bits || NestedLoopCount == 1 || 3996 FitsInto( 3997 32 /* Bits */, 3998 LastIteration32.get()->getType()->hasSignedIntegerRepresentation(), 3999 LastIteration64.get(), SemaRef))) 4000 LastIteration = LastIteration32; 4001 QualType VType = LastIteration.get()->getType(); 4002 QualType RealVType = VType; 4003 QualType StrideVType = VType; 4004 if (isOpenMPTaskLoopDirective(DKind)) { 4005 VType = 4006 SemaRef.Context.getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/0); 4007 StrideVType = 4008 SemaRef.Context.getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/1); 4009 } 4010 4011 if (!LastIteration.isUsable()) 4012 return 0; 4013 4014 // Save the number of iterations. 4015 ExprResult NumIterations = LastIteration; 4016 { 4017 LastIteration = SemaRef.BuildBinOp( 4018 CurScope, LastIteration.get()->getExprLoc(), BO_Sub, 4019 LastIteration.get(), 4020 SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get()); 4021 if (!LastIteration.isUsable()) 4022 return 0; 4023 } 4024 4025 // Calculate the last iteration number beforehand instead of doing this on 4026 // each iteration. Do not do this if the number of iterations may be kfold-ed. 4027 llvm::APSInt Result; 4028 bool IsConstant = 4029 LastIteration.get()->isIntegerConstantExpr(Result, SemaRef.Context); 4030 ExprResult CalcLastIteration; 4031 if (!IsConstant) { 4032 ExprResult SaveRef = 4033 tryBuildCapture(SemaRef, LastIteration.get(), Captures); 4034 LastIteration = SaveRef; 4035 4036 // Prepare SaveRef + 1. 4037 NumIterations = SemaRef.BuildBinOp( 4038 CurScope, SaveRef.get()->getExprLoc(), BO_Add, SaveRef.get(), 4039 SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get()); 4040 if (!NumIterations.isUsable()) 4041 return 0; 4042 } 4043 4044 SourceLocation InitLoc = IterSpaces[0].InitSrcRange.getBegin(); 4045 4046 // Build variables passed into runtime, necessary for worksharing directives. 4047 ExprResult LB, UB, IL, ST, EUB, PrevLB, PrevUB; 4048 if (isOpenMPWorksharingDirective(DKind) || isOpenMPTaskLoopDirective(DKind) || 4049 isOpenMPDistributeDirective(DKind)) { 4050 // Lower bound variable, initialized with zero. 4051 VarDecl *LBDecl = buildVarDecl(SemaRef, InitLoc, VType, ".omp.lb"); 4052 LB = buildDeclRefExpr(SemaRef, LBDecl, VType, InitLoc); 4053 SemaRef.AddInitializerToDecl(LBDecl, 4054 SemaRef.ActOnIntegerConstant(InitLoc, 0).get(), 4055 /*DirectInit*/ false); 4056 4057 // Upper bound variable, initialized with last iteration number. 4058 VarDecl *UBDecl = buildVarDecl(SemaRef, InitLoc, VType, ".omp.ub"); 4059 UB = buildDeclRefExpr(SemaRef, UBDecl, VType, InitLoc); 4060 SemaRef.AddInitializerToDecl(UBDecl, LastIteration.get(), 4061 /*DirectInit*/ false); 4062 4063 // A 32-bit variable-flag where runtime returns 1 for the last iteration. 4064 // This will be used to implement clause 'lastprivate'. 4065 QualType Int32Ty = SemaRef.Context.getIntTypeForBitwidth(32, true); 4066 VarDecl *ILDecl = buildVarDecl(SemaRef, InitLoc, Int32Ty, ".omp.is_last"); 4067 IL = buildDeclRefExpr(SemaRef, ILDecl, Int32Ty, InitLoc); 4068 SemaRef.AddInitializerToDecl(ILDecl, 4069 SemaRef.ActOnIntegerConstant(InitLoc, 0).get(), 4070 /*DirectInit*/ false); 4071 4072 // Stride variable returned by runtime (we initialize it to 1 by default). 4073 VarDecl *STDecl = 4074 buildVarDecl(SemaRef, InitLoc, StrideVType, ".omp.stride"); 4075 ST = buildDeclRefExpr(SemaRef, STDecl, StrideVType, InitLoc); 4076 SemaRef.AddInitializerToDecl(STDecl, 4077 SemaRef.ActOnIntegerConstant(InitLoc, 1).get(), 4078 /*DirectInit*/ false); 4079 4080 // Build expression: UB = min(UB, LastIteration) 4081 // It is necessary for CodeGen of directives with static scheduling. 4082 ExprResult IsUBGreater = SemaRef.BuildBinOp(CurScope, InitLoc, BO_GT, 4083 UB.get(), LastIteration.get()); 4084 ExprResult CondOp = SemaRef.ActOnConditionalOp( 4085 InitLoc, InitLoc, IsUBGreater.get(), LastIteration.get(), UB.get()); 4086 EUB = SemaRef.BuildBinOp(CurScope, InitLoc, BO_Assign, UB.get(), 4087 CondOp.get()); 4088 EUB = SemaRef.ActOnFinishFullExpr(EUB.get()); 4089 4090 // If we have a combined directive that combines 'distribute', 'for' or 4091 // 'simd' we need to be able to access the bounds of the schedule of the 4092 // enclosing region. E.g. in 'distribute parallel for' the bounds obtained 4093 // by scheduling 'distribute' have to be passed to the schedule of 'for'. 4094 if (isOpenMPLoopBoundSharingDirective(DKind)) { 4095 auto *CD = cast<CapturedStmt>(AStmt)->getCapturedDecl(); 4096 4097 // We expect to have at least 2 more parameters than the 'parallel' 4098 // directive does - the lower and upper bounds of the previous schedule. 4099 assert(CD->getNumParams() >= 4 && 4100 "Unexpected number of parameters in loop combined directive"); 4101 4102 // Set the proper type for the bounds given what we learned from the 4103 // enclosed loops. 4104 auto *PrevLBDecl = CD->getParam(/*PrevLB=*/2); 4105 auto *PrevUBDecl = CD->getParam(/*PrevUB=*/3); 4106 4107 // Previous lower and upper bounds are obtained from the region 4108 // parameters. 4109 PrevLB = 4110 buildDeclRefExpr(SemaRef, PrevLBDecl, PrevLBDecl->getType(), InitLoc); 4111 PrevUB = 4112 buildDeclRefExpr(SemaRef, PrevUBDecl, PrevUBDecl->getType(), InitLoc); 4113 } 4114 } 4115 4116 // Build the iteration variable and its initialization before loop. 4117 ExprResult IV; 4118 ExprResult Init; 4119 { 4120 VarDecl *IVDecl = buildVarDecl(SemaRef, InitLoc, RealVType, ".omp.iv"); 4121 IV = buildDeclRefExpr(SemaRef, IVDecl, RealVType, InitLoc); 4122 Expr *RHS = 4123 (isOpenMPWorksharingDirective(DKind) || 4124 isOpenMPTaskLoopDirective(DKind) || isOpenMPDistributeDirective(DKind)) 4125 ? LB.get() 4126 : SemaRef.ActOnIntegerConstant(SourceLocation(), 0).get(); 4127 Init = SemaRef.BuildBinOp(CurScope, InitLoc, BO_Assign, IV.get(), RHS); 4128 Init = SemaRef.ActOnFinishFullExpr(Init.get()); 4129 } 4130 4131 // Loop condition (IV < NumIterations) or (IV <= UB) for worksharing loops. 4132 SourceLocation CondLoc; 4133 ExprResult Cond = 4134 (isOpenMPWorksharingDirective(DKind) || 4135 isOpenMPTaskLoopDirective(DKind) || isOpenMPDistributeDirective(DKind)) 4136 ? SemaRef.BuildBinOp(CurScope, CondLoc, BO_LE, IV.get(), UB.get()) 4137 : SemaRef.BuildBinOp(CurScope, CondLoc, BO_LT, IV.get(), 4138 NumIterations.get()); 4139 4140 // Loop increment (IV = IV + 1) 4141 SourceLocation IncLoc; 4142 ExprResult Inc = 4143 SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, IV.get(), 4144 SemaRef.ActOnIntegerConstant(IncLoc, 1).get()); 4145 if (!Inc.isUsable()) 4146 return 0; 4147 Inc = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, IV.get(), Inc.get()); 4148 Inc = SemaRef.ActOnFinishFullExpr(Inc.get()); 4149 if (!Inc.isUsable()) 4150 return 0; 4151 4152 // Increments for worksharing loops (LB = LB + ST; UB = UB + ST). 4153 // Used for directives with static scheduling. 4154 ExprResult NextLB, NextUB; 4155 if (isOpenMPWorksharingDirective(DKind) || isOpenMPTaskLoopDirective(DKind) || 4156 isOpenMPDistributeDirective(DKind)) { 4157 // LB + ST 4158 NextLB = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, LB.get(), ST.get()); 4159 if (!NextLB.isUsable()) 4160 return 0; 4161 // LB = LB + ST 4162 NextLB = 4163 SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, LB.get(), NextLB.get()); 4164 NextLB = SemaRef.ActOnFinishFullExpr(NextLB.get()); 4165 if (!NextLB.isUsable()) 4166 return 0; 4167 // UB + ST 4168 NextUB = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, UB.get(), ST.get()); 4169 if (!NextUB.isUsable()) 4170 return 0; 4171 // UB = UB + ST 4172 NextUB = 4173 SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, UB.get(), NextUB.get()); 4174 NextUB = SemaRef.ActOnFinishFullExpr(NextUB.get()); 4175 if (!NextUB.isUsable()) 4176 return 0; 4177 } 4178 4179 // Build updates and final values of the loop counters. 4180 bool HasErrors = false; 4181 Built.Counters.resize(NestedLoopCount); 4182 Built.Inits.resize(NestedLoopCount); 4183 Built.Updates.resize(NestedLoopCount); 4184 Built.Finals.resize(NestedLoopCount); 4185 SmallVector<Expr *, 4> LoopMultipliers; 4186 { 4187 ExprResult Div; 4188 // Go from inner nested loop to outer. 4189 for (int Cnt = NestedLoopCount - 1; Cnt >= 0; --Cnt) { 4190 LoopIterationSpace &IS = IterSpaces[Cnt]; 4191 SourceLocation UpdLoc = IS.IncSrcRange.getBegin(); 4192 // Build: Iter = (IV / Div) % IS.NumIters 4193 // where Div is product of previous iterations' IS.NumIters. 4194 ExprResult Iter; 4195 if (Div.isUsable()) { 4196 Iter = 4197 SemaRef.BuildBinOp(CurScope, UpdLoc, BO_Div, IV.get(), Div.get()); 4198 } else { 4199 Iter = IV; 4200 assert((Cnt == (int)NestedLoopCount - 1) && 4201 "unusable div expected on first iteration only"); 4202 } 4203 4204 if (Cnt != 0 && Iter.isUsable()) 4205 Iter = SemaRef.BuildBinOp(CurScope, UpdLoc, BO_Rem, Iter.get(), 4206 IS.NumIterations); 4207 if (!Iter.isUsable()) { 4208 HasErrors = true; 4209 break; 4210 } 4211 4212 // Build update: IS.CounterVar(Private) = IS.Start + Iter * IS.Step 4213 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(IS.CounterVar)->getDecl()); 4214 auto *CounterVar = buildDeclRefExpr(SemaRef, VD, IS.CounterVar->getType(), 4215 IS.CounterVar->getExprLoc(), 4216 /*RefersToCapture=*/true); 4217 ExprResult Init = BuildCounterInit(SemaRef, CurScope, UpdLoc, CounterVar, 4218 IS.CounterInit, Captures); 4219 if (!Init.isUsable()) { 4220 HasErrors = true; 4221 break; 4222 } 4223 ExprResult Update = BuildCounterUpdate( 4224 SemaRef, CurScope, UpdLoc, CounterVar, IS.CounterInit, Iter, 4225 IS.CounterStep, IS.Subtract, &Captures); 4226 if (!Update.isUsable()) { 4227 HasErrors = true; 4228 break; 4229 } 4230 4231 // Build final: IS.CounterVar = IS.Start + IS.NumIters * IS.Step 4232 ExprResult Final = BuildCounterUpdate( 4233 SemaRef, CurScope, UpdLoc, CounterVar, IS.CounterInit, 4234 IS.NumIterations, IS.CounterStep, IS.Subtract, &Captures); 4235 if (!Final.isUsable()) { 4236 HasErrors = true; 4237 break; 4238 } 4239 4240 // Build Div for the next iteration: Div <- Div * IS.NumIters 4241 if (Cnt != 0) { 4242 if (Div.isUnset()) 4243 Div = IS.NumIterations; 4244 else 4245 Div = SemaRef.BuildBinOp(CurScope, UpdLoc, BO_Mul, Div.get(), 4246 IS.NumIterations); 4247 4248 // Add parentheses (for debugging purposes only). 4249 if (Div.isUsable()) 4250 Div = tryBuildCapture(SemaRef, Div.get(), Captures); 4251 if (!Div.isUsable()) { 4252 HasErrors = true; 4253 break; 4254 } 4255 LoopMultipliers.push_back(Div.get()); 4256 } 4257 if (!Update.isUsable() || !Final.isUsable()) { 4258 HasErrors = true; 4259 break; 4260 } 4261 // Save results 4262 Built.Counters[Cnt] = IS.CounterVar; 4263 Built.PrivateCounters[Cnt] = IS.PrivateCounterVar; 4264 Built.Inits[Cnt] = Init.get(); 4265 Built.Updates[Cnt] = Update.get(); 4266 Built.Finals[Cnt] = Final.get(); 4267 } 4268 } 4269 4270 if (HasErrors) 4271 return 0; 4272 4273 // Save results 4274 Built.IterationVarRef = IV.get(); 4275 Built.LastIteration = LastIteration.get(); 4276 Built.NumIterations = NumIterations.get(); 4277 Built.CalcLastIteration = 4278 SemaRef.ActOnFinishFullExpr(CalcLastIteration.get()).get(); 4279 Built.PreCond = PreCond.get(); 4280 Built.PreInits = buildPreInits(C, Captures); 4281 Built.Cond = Cond.get(); 4282 Built.Init = Init.get(); 4283 Built.Inc = Inc.get(); 4284 Built.LB = LB.get(); 4285 Built.UB = UB.get(); 4286 Built.IL = IL.get(); 4287 Built.ST = ST.get(); 4288 Built.EUB = EUB.get(); 4289 Built.NLB = NextLB.get(); 4290 Built.NUB = NextUB.get(); 4291 Built.PrevLB = PrevLB.get(); 4292 Built.PrevUB = PrevUB.get(); 4293 4294 Expr *CounterVal = SemaRef.DefaultLvalueConversion(IV.get()).get(); 4295 // Fill data for doacross depend clauses. 4296 for (auto Pair : DSA.getDoacrossDependClauses()) { 4297 if (Pair.first->getDependencyKind() == OMPC_DEPEND_source) 4298 Pair.first->setCounterValue(CounterVal); 4299 else { 4300 if (NestedLoopCount != Pair.second.size() || 4301 NestedLoopCount != LoopMultipliers.size() + 1) { 4302 // Erroneous case - clause has some problems. 4303 Pair.first->setCounterValue(CounterVal); 4304 continue; 4305 } 4306 assert(Pair.first->getDependencyKind() == OMPC_DEPEND_sink); 4307 auto I = Pair.second.rbegin(); 4308 auto IS = IterSpaces.rbegin(); 4309 auto ILM = LoopMultipliers.rbegin(); 4310 Expr *UpCounterVal = CounterVal; 4311 Expr *Multiplier = nullptr; 4312 for (int Cnt = NestedLoopCount - 1; Cnt >= 0; --Cnt) { 4313 if (I->first) { 4314 assert(IS->CounterStep); 4315 Expr *NormalizedOffset = 4316 SemaRef 4317 .BuildBinOp(CurScope, I->first->getExprLoc(), BO_Div, 4318 I->first, IS->CounterStep) 4319 .get(); 4320 if (Multiplier) { 4321 NormalizedOffset = 4322 SemaRef 4323 .BuildBinOp(CurScope, I->first->getExprLoc(), BO_Mul, 4324 NormalizedOffset, Multiplier) 4325 .get(); 4326 } 4327 assert(I->second == OO_Plus || I->second == OO_Minus); 4328 BinaryOperatorKind BOK = (I->second == OO_Plus) ? BO_Add : BO_Sub; 4329 UpCounterVal = SemaRef 4330 .BuildBinOp(CurScope, I->first->getExprLoc(), BOK, 4331 UpCounterVal, NormalizedOffset) 4332 .get(); 4333 } 4334 Multiplier = *ILM; 4335 ++I; 4336 ++IS; 4337 ++ILM; 4338 } 4339 Pair.first->setCounterValue(UpCounterVal); 4340 } 4341 } 4342 4343 return NestedLoopCount; 4344 } 4345 4346 static Expr *getCollapseNumberExpr(ArrayRef<OMPClause *> Clauses) { 4347 auto CollapseClauses = 4348 OMPExecutableDirective::getClausesOfKind<OMPCollapseClause>(Clauses); 4349 if (CollapseClauses.begin() != CollapseClauses.end()) 4350 return (*CollapseClauses.begin())->getNumForLoops(); 4351 return nullptr; 4352 } 4353 4354 static Expr *getOrderedNumberExpr(ArrayRef<OMPClause *> Clauses) { 4355 auto OrderedClauses = 4356 OMPExecutableDirective::getClausesOfKind<OMPOrderedClause>(Clauses); 4357 if (OrderedClauses.begin() != OrderedClauses.end()) 4358 return (*OrderedClauses.begin())->getNumForLoops(); 4359 return nullptr; 4360 } 4361 4362 static bool checkSimdlenSafelenSpecified(Sema &S, 4363 const ArrayRef<OMPClause *> Clauses) { 4364 OMPSafelenClause *Safelen = nullptr; 4365 OMPSimdlenClause *Simdlen = nullptr; 4366 4367 for (auto *Clause : Clauses) { 4368 if (Clause->getClauseKind() == OMPC_safelen) 4369 Safelen = cast<OMPSafelenClause>(Clause); 4370 else if (Clause->getClauseKind() == OMPC_simdlen) 4371 Simdlen = cast<OMPSimdlenClause>(Clause); 4372 if (Safelen && Simdlen) 4373 break; 4374 } 4375 4376 if (Simdlen && Safelen) { 4377 llvm::APSInt SimdlenRes, SafelenRes; 4378 auto SimdlenLength = Simdlen->getSimdlen(); 4379 auto SafelenLength = Safelen->getSafelen(); 4380 if (SimdlenLength->isValueDependent() || SimdlenLength->isTypeDependent() || 4381 SimdlenLength->isInstantiationDependent() || 4382 SimdlenLength->containsUnexpandedParameterPack()) 4383 return false; 4384 if (SafelenLength->isValueDependent() || SafelenLength->isTypeDependent() || 4385 SafelenLength->isInstantiationDependent() || 4386 SafelenLength->containsUnexpandedParameterPack()) 4387 return false; 4388 SimdlenLength->EvaluateAsInt(SimdlenRes, S.Context); 4389 SafelenLength->EvaluateAsInt(SafelenRes, S.Context); 4390 // OpenMP 4.5 [2.8.1, simd Construct, Restrictions] 4391 // If both simdlen and safelen clauses are specified, the value of the 4392 // simdlen parameter must be less than or equal to the value of the safelen 4393 // parameter. 4394 if (SimdlenRes > SafelenRes) { 4395 S.Diag(SimdlenLength->getExprLoc(), 4396 diag::err_omp_wrong_simdlen_safelen_values) 4397 << SimdlenLength->getSourceRange() << SafelenLength->getSourceRange(); 4398 return true; 4399 } 4400 } 4401 return false; 4402 } 4403 4404 StmtResult Sema::ActOnOpenMPSimdDirective( 4405 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, 4406 SourceLocation EndLoc, 4407 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) { 4408 if (!AStmt) 4409 return StmtError(); 4410 4411 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected"); 4412 OMPLoopDirective::HelperExprs B; 4413 // In presence of clause 'collapse' or 'ordered' with number of loops, it will 4414 // define the nested loops number. 4415 unsigned NestedLoopCount = CheckOpenMPLoop( 4416 OMPD_simd, getCollapseNumberExpr(Clauses), getOrderedNumberExpr(Clauses), 4417 AStmt, *this, *DSAStack, VarsWithImplicitDSA, B); 4418 if (NestedLoopCount == 0) 4419 return StmtError(); 4420 4421 assert((CurContext->isDependentContext() || B.builtAll()) && 4422 "omp simd loop exprs were not built"); 4423 4424 if (!CurContext->isDependentContext()) { 4425 // Finalize the clauses that need pre-built expressions for CodeGen. 4426 for (auto C : Clauses) { 4427 if (auto *LC = dyn_cast<OMPLinearClause>(C)) 4428 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef), 4429 B.NumIterations, *this, CurScope, 4430 DSAStack)) 4431 return StmtError(); 4432 } 4433 } 4434 4435 if (checkSimdlenSafelenSpecified(*this, Clauses)) 4436 return StmtError(); 4437 4438 getCurFunction()->setHasBranchProtectedScope(); 4439 return OMPSimdDirective::Create(Context, StartLoc, EndLoc, NestedLoopCount, 4440 Clauses, AStmt, B); 4441 } 4442 4443 StmtResult Sema::ActOnOpenMPForDirective( 4444 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, 4445 SourceLocation EndLoc, 4446 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) { 4447 if (!AStmt) 4448 return StmtError(); 4449 4450 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected"); 4451 OMPLoopDirective::HelperExprs B; 4452 // In presence of clause 'collapse' or 'ordered' with number of loops, it will 4453 // define the nested loops number. 4454 unsigned NestedLoopCount = CheckOpenMPLoop( 4455 OMPD_for, getCollapseNumberExpr(Clauses), getOrderedNumberExpr(Clauses), 4456 AStmt, *this, *DSAStack, VarsWithImplicitDSA, B); 4457 if (NestedLoopCount == 0) 4458 return StmtError(); 4459 4460 assert((CurContext->isDependentContext() || B.builtAll()) && 4461 "omp for loop exprs were not built"); 4462 4463 if (!CurContext->isDependentContext()) { 4464 // Finalize the clauses that need pre-built expressions for CodeGen. 4465 for (auto C : Clauses) { 4466 if (auto *LC = dyn_cast<OMPLinearClause>(C)) 4467 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef), 4468 B.NumIterations, *this, CurScope, 4469 DSAStack)) 4470 return StmtError(); 4471 } 4472 } 4473 4474 getCurFunction()->setHasBranchProtectedScope(); 4475 return OMPForDirective::Create(Context, StartLoc, EndLoc, NestedLoopCount, 4476 Clauses, AStmt, B, DSAStack->isCancelRegion()); 4477 } 4478 4479 StmtResult Sema::ActOnOpenMPForSimdDirective( 4480 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, 4481 SourceLocation EndLoc, 4482 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) { 4483 if (!AStmt) 4484 return StmtError(); 4485 4486 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected"); 4487 OMPLoopDirective::HelperExprs B; 4488 // In presence of clause 'collapse' or 'ordered' with number of loops, it will 4489 // define the nested loops number. 4490 unsigned NestedLoopCount = 4491 CheckOpenMPLoop(OMPD_for_simd, getCollapseNumberExpr(Clauses), 4492 getOrderedNumberExpr(Clauses), AStmt, *this, *DSAStack, 4493 VarsWithImplicitDSA, B); 4494 if (NestedLoopCount == 0) 4495 return StmtError(); 4496 4497 assert((CurContext->isDependentContext() || B.builtAll()) && 4498 "omp for simd loop exprs were not built"); 4499 4500 if (!CurContext->isDependentContext()) { 4501 // Finalize the clauses that need pre-built expressions for CodeGen. 4502 for (auto C : Clauses) { 4503 if (auto *LC = dyn_cast<OMPLinearClause>(C)) 4504 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef), 4505 B.NumIterations, *this, CurScope, 4506 DSAStack)) 4507 return StmtError(); 4508 } 4509 } 4510 4511 if (checkSimdlenSafelenSpecified(*this, Clauses)) 4512 return StmtError(); 4513 4514 getCurFunction()->setHasBranchProtectedScope(); 4515 return OMPForSimdDirective::Create(Context, StartLoc, EndLoc, NestedLoopCount, 4516 Clauses, AStmt, B); 4517 } 4518 4519 StmtResult Sema::ActOnOpenMPSectionsDirective(ArrayRef<OMPClause *> Clauses, 4520 Stmt *AStmt, 4521 SourceLocation StartLoc, 4522 SourceLocation EndLoc) { 4523 if (!AStmt) 4524 return StmtError(); 4525 4526 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected"); 4527 auto BaseStmt = AStmt; 4528 while (auto *CS = dyn_cast_or_null<CapturedStmt>(BaseStmt)) 4529 BaseStmt = CS->getCapturedStmt(); 4530 if (auto *C = dyn_cast_or_null<CompoundStmt>(BaseStmt)) { 4531 auto S = C->children(); 4532 if (S.begin() == S.end()) 4533 return StmtError(); 4534 // All associated statements must be '#pragma omp section' except for 4535 // the first one. 4536 for (Stmt *SectionStmt : llvm::make_range(std::next(S.begin()), S.end())) { 4537 if (!SectionStmt || !isa<OMPSectionDirective>(SectionStmt)) { 4538 if (SectionStmt) 4539 Diag(SectionStmt->getLocStart(), 4540 diag::err_omp_sections_substmt_not_section); 4541 return StmtError(); 4542 } 4543 cast<OMPSectionDirective>(SectionStmt) 4544 ->setHasCancel(DSAStack->isCancelRegion()); 4545 } 4546 } else { 4547 Diag(AStmt->getLocStart(), diag::err_omp_sections_not_compound_stmt); 4548 return StmtError(); 4549 } 4550 4551 getCurFunction()->setHasBranchProtectedScope(); 4552 4553 return OMPSectionsDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt, 4554 DSAStack->isCancelRegion()); 4555 } 4556 4557 StmtResult Sema::ActOnOpenMPSectionDirective(Stmt *AStmt, 4558 SourceLocation StartLoc, 4559 SourceLocation EndLoc) { 4560 if (!AStmt) 4561 return StmtError(); 4562 4563 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected"); 4564 4565 getCurFunction()->setHasBranchProtectedScope(); 4566 DSAStack->setParentCancelRegion(DSAStack->isCancelRegion()); 4567 4568 return OMPSectionDirective::Create(Context, StartLoc, EndLoc, AStmt, 4569 DSAStack->isCancelRegion()); 4570 } 4571 4572 StmtResult Sema::ActOnOpenMPSingleDirective(ArrayRef<OMPClause *> Clauses, 4573 Stmt *AStmt, 4574 SourceLocation StartLoc, 4575 SourceLocation EndLoc) { 4576 if (!AStmt) 4577 return StmtError(); 4578 4579 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected"); 4580 4581 getCurFunction()->setHasBranchProtectedScope(); 4582 4583 // OpenMP [2.7.3, single Construct, Restrictions] 4584 // The copyprivate clause must not be used with the nowait clause. 4585 OMPClause *Nowait = nullptr; 4586 OMPClause *Copyprivate = nullptr; 4587 for (auto *Clause : Clauses) { 4588 if (Clause->getClauseKind() == OMPC_nowait) 4589 Nowait = Clause; 4590 else if (Clause->getClauseKind() == OMPC_copyprivate) 4591 Copyprivate = Clause; 4592 if (Copyprivate && Nowait) { 4593 Diag(Copyprivate->getLocStart(), 4594 diag::err_omp_single_copyprivate_with_nowait); 4595 Diag(Nowait->getLocStart(), diag::note_omp_nowait_clause_here); 4596 return StmtError(); 4597 } 4598 } 4599 4600 return OMPSingleDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt); 4601 } 4602 4603 StmtResult Sema::ActOnOpenMPMasterDirective(Stmt *AStmt, 4604 SourceLocation StartLoc, 4605 SourceLocation EndLoc) { 4606 if (!AStmt) 4607 return StmtError(); 4608 4609 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected"); 4610 4611 getCurFunction()->setHasBranchProtectedScope(); 4612 4613 return OMPMasterDirective::Create(Context, StartLoc, EndLoc, AStmt); 4614 } 4615 4616 StmtResult Sema::ActOnOpenMPCriticalDirective( 4617 const DeclarationNameInfo &DirName, ArrayRef<OMPClause *> Clauses, 4618 Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc) { 4619 if (!AStmt) 4620 return StmtError(); 4621 4622 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected"); 4623 4624 bool ErrorFound = false; 4625 llvm::APSInt Hint; 4626 SourceLocation HintLoc; 4627 bool DependentHint = false; 4628 for (auto *C : Clauses) { 4629 if (C->getClauseKind() == OMPC_hint) { 4630 if (!DirName.getName()) { 4631 Diag(C->getLocStart(), diag::err_omp_hint_clause_no_name); 4632 ErrorFound = true; 4633 } 4634 Expr *E = cast<OMPHintClause>(C)->getHint(); 4635 if (E->isTypeDependent() || E->isValueDependent() || 4636 E->isInstantiationDependent()) 4637 DependentHint = true; 4638 else { 4639 Hint = E->EvaluateKnownConstInt(Context); 4640 HintLoc = C->getLocStart(); 4641 } 4642 } 4643 } 4644 if (ErrorFound) 4645 return StmtError(); 4646 auto Pair = DSAStack->getCriticalWithHint(DirName); 4647 if (Pair.first && DirName.getName() && !DependentHint) { 4648 if (llvm::APSInt::compareValues(Hint, Pair.second) != 0) { 4649 Diag(StartLoc, diag::err_omp_critical_with_hint); 4650 if (HintLoc.isValid()) { 4651 Diag(HintLoc, diag::note_omp_critical_hint_here) 4652 << 0 << Hint.toString(/*Radix=*/10, /*Signed=*/false); 4653 } else 4654 Diag(StartLoc, diag::note_omp_critical_no_hint) << 0; 4655 if (auto *C = Pair.first->getSingleClause<OMPHintClause>()) { 4656 Diag(C->getLocStart(), diag::note_omp_critical_hint_here) 4657 << 1 4658 << C->getHint()->EvaluateKnownConstInt(Context).toString( 4659 /*Radix=*/10, /*Signed=*/false); 4660 } else 4661 Diag(Pair.first->getLocStart(), diag::note_omp_critical_no_hint) << 1; 4662 } 4663 } 4664 4665 getCurFunction()->setHasBranchProtectedScope(); 4666 4667 auto *Dir = OMPCriticalDirective::Create(Context, DirName, StartLoc, EndLoc, 4668 Clauses, AStmt); 4669 if (!Pair.first && DirName.getName() && !DependentHint) 4670 DSAStack->addCriticalWithHint(Dir, Hint); 4671 return Dir; 4672 } 4673 4674 StmtResult Sema::ActOnOpenMPParallelForDirective( 4675 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, 4676 SourceLocation EndLoc, 4677 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) { 4678 if (!AStmt) 4679 return StmtError(); 4680 4681 CapturedStmt *CS = cast<CapturedStmt>(AStmt); 4682 // 1.2.2 OpenMP Language Terminology 4683 // Structured block - An executable statement with a single entry at the 4684 // top and a single exit at the bottom. 4685 // The point of exit cannot be a branch out of the structured block. 4686 // longjmp() and throw() must not violate the entry/exit criteria. 4687 CS->getCapturedDecl()->setNothrow(); 4688 4689 OMPLoopDirective::HelperExprs B; 4690 // In presence of clause 'collapse' or 'ordered' with number of loops, it will 4691 // define the nested loops number. 4692 unsigned NestedLoopCount = 4693 CheckOpenMPLoop(OMPD_parallel_for, getCollapseNumberExpr(Clauses), 4694 getOrderedNumberExpr(Clauses), AStmt, *this, *DSAStack, 4695 VarsWithImplicitDSA, B); 4696 if (NestedLoopCount == 0) 4697 return StmtError(); 4698 4699 assert((CurContext->isDependentContext() || B.builtAll()) && 4700 "omp parallel for loop exprs were not built"); 4701 4702 if (!CurContext->isDependentContext()) { 4703 // Finalize the clauses that need pre-built expressions for CodeGen. 4704 for (auto C : Clauses) { 4705 if (auto *LC = dyn_cast<OMPLinearClause>(C)) 4706 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef), 4707 B.NumIterations, *this, CurScope, 4708 DSAStack)) 4709 return StmtError(); 4710 } 4711 } 4712 4713 getCurFunction()->setHasBranchProtectedScope(); 4714 return OMPParallelForDirective::Create(Context, StartLoc, EndLoc, 4715 NestedLoopCount, Clauses, AStmt, B, 4716 DSAStack->isCancelRegion()); 4717 } 4718 4719 StmtResult Sema::ActOnOpenMPParallelForSimdDirective( 4720 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, 4721 SourceLocation EndLoc, 4722 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) { 4723 if (!AStmt) 4724 return StmtError(); 4725 4726 CapturedStmt *CS = cast<CapturedStmt>(AStmt); 4727 // 1.2.2 OpenMP Language Terminology 4728 // Structured block - An executable statement with a single entry at the 4729 // top and a single exit at the bottom. 4730 // The point of exit cannot be a branch out of the structured block. 4731 // longjmp() and throw() must not violate the entry/exit criteria. 4732 CS->getCapturedDecl()->setNothrow(); 4733 4734 OMPLoopDirective::HelperExprs B; 4735 // In presence of clause 'collapse' or 'ordered' with number of loops, it will 4736 // define the nested loops number. 4737 unsigned NestedLoopCount = 4738 CheckOpenMPLoop(OMPD_parallel_for_simd, getCollapseNumberExpr(Clauses), 4739 getOrderedNumberExpr(Clauses), AStmt, *this, *DSAStack, 4740 VarsWithImplicitDSA, B); 4741 if (NestedLoopCount == 0) 4742 return StmtError(); 4743 4744 if (!CurContext->isDependentContext()) { 4745 // Finalize the clauses that need pre-built expressions for CodeGen. 4746 for (auto C : Clauses) { 4747 if (auto *LC = dyn_cast<OMPLinearClause>(C)) 4748 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef), 4749 B.NumIterations, *this, CurScope, 4750 DSAStack)) 4751 return StmtError(); 4752 } 4753 } 4754 4755 if (checkSimdlenSafelenSpecified(*this, Clauses)) 4756 return StmtError(); 4757 4758 getCurFunction()->setHasBranchProtectedScope(); 4759 return OMPParallelForSimdDirective::Create( 4760 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B); 4761 } 4762 4763 StmtResult 4764 Sema::ActOnOpenMPParallelSectionsDirective(ArrayRef<OMPClause *> Clauses, 4765 Stmt *AStmt, SourceLocation StartLoc, 4766 SourceLocation EndLoc) { 4767 if (!AStmt) 4768 return StmtError(); 4769 4770 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected"); 4771 auto BaseStmt = AStmt; 4772 while (auto *CS = dyn_cast_or_null<CapturedStmt>(BaseStmt)) 4773 BaseStmt = CS->getCapturedStmt(); 4774 if (auto *C = dyn_cast_or_null<CompoundStmt>(BaseStmt)) { 4775 auto S = C->children(); 4776 if (S.begin() == S.end()) 4777 return StmtError(); 4778 // All associated statements must be '#pragma omp section' except for 4779 // the first one. 4780 for (Stmt *SectionStmt : llvm::make_range(std::next(S.begin()), S.end())) { 4781 if (!SectionStmt || !isa<OMPSectionDirective>(SectionStmt)) { 4782 if (SectionStmt) 4783 Diag(SectionStmt->getLocStart(), 4784 diag::err_omp_parallel_sections_substmt_not_section); 4785 return StmtError(); 4786 } 4787 cast<OMPSectionDirective>(SectionStmt) 4788 ->setHasCancel(DSAStack->isCancelRegion()); 4789 } 4790 } else { 4791 Diag(AStmt->getLocStart(), 4792 diag::err_omp_parallel_sections_not_compound_stmt); 4793 return StmtError(); 4794 } 4795 4796 getCurFunction()->setHasBranchProtectedScope(); 4797 4798 return OMPParallelSectionsDirective::Create( 4799 Context, StartLoc, EndLoc, Clauses, AStmt, DSAStack->isCancelRegion()); 4800 } 4801 4802 StmtResult Sema::ActOnOpenMPTaskDirective(ArrayRef<OMPClause *> Clauses, 4803 Stmt *AStmt, SourceLocation StartLoc, 4804 SourceLocation EndLoc) { 4805 if (!AStmt) 4806 return StmtError(); 4807 4808 auto *CS = cast<CapturedStmt>(AStmt); 4809 // 1.2.2 OpenMP Language Terminology 4810 // Structured block - An executable statement with a single entry at the 4811 // top and a single exit at the bottom. 4812 // The point of exit cannot be a branch out of the structured block. 4813 // longjmp() and throw() must not violate the entry/exit criteria. 4814 CS->getCapturedDecl()->setNothrow(); 4815 4816 getCurFunction()->setHasBranchProtectedScope(); 4817 4818 return OMPTaskDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt, 4819 DSAStack->isCancelRegion()); 4820 } 4821 4822 StmtResult Sema::ActOnOpenMPTaskyieldDirective(SourceLocation StartLoc, 4823 SourceLocation EndLoc) { 4824 return OMPTaskyieldDirective::Create(Context, StartLoc, EndLoc); 4825 } 4826 4827 StmtResult Sema::ActOnOpenMPBarrierDirective(SourceLocation StartLoc, 4828 SourceLocation EndLoc) { 4829 return OMPBarrierDirective::Create(Context, StartLoc, EndLoc); 4830 } 4831 4832 StmtResult Sema::ActOnOpenMPTaskwaitDirective(SourceLocation StartLoc, 4833 SourceLocation EndLoc) { 4834 return OMPTaskwaitDirective::Create(Context, StartLoc, EndLoc); 4835 } 4836 4837 StmtResult Sema::ActOnOpenMPTaskgroupDirective(Stmt *AStmt, 4838 SourceLocation StartLoc, 4839 SourceLocation EndLoc) { 4840 if (!AStmt) 4841 return StmtError(); 4842 4843 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected"); 4844 4845 getCurFunction()->setHasBranchProtectedScope(); 4846 4847 return OMPTaskgroupDirective::Create(Context, StartLoc, EndLoc, AStmt); 4848 } 4849 4850 StmtResult Sema::ActOnOpenMPFlushDirective(ArrayRef<OMPClause *> Clauses, 4851 SourceLocation StartLoc, 4852 SourceLocation EndLoc) { 4853 assert(Clauses.size() <= 1 && "Extra clauses in flush directive"); 4854 return OMPFlushDirective::Create(Context, StartLoc, EndLoc, Clauses); 4855 } 4856 4857 StmtResult Sema::ActOnOpenMPOrderedDirective(ArrayRef<OMPClause *> Clauses, 4858 Stmt *AStmt, 4859 SourceLocation StartLoc, 4860 SourceLocation EndLoc) { 4861 OMPClause *DependFound = nullptr; 4862 OMPClause *DependSourceClause = nullptr; 4863 OMPClause *DependSinkClause = nullptr; 4864 bool ErrorFound = false; 4865 OMPThreadsClause *TC = nullptr; 4866 OMPSIMDClause *SC = nullptr; 4867 for (auto *C : Clauses) { 4868 if (auto *DC = dyn_cast<OMPDependClause>(C)) { 4869 DependFound = C; 4870 if (DC->getDependencyKind() == OMPC_DEPEND_source) { 4871 if (DependSourceClause) { 4872 Diag(C->getLocStart(), diag::err_omp_more_one_clause) 4873 << getOpenMPDirectiveName(OMPD_ordered) 4874 << getOpenMPClauseName(OMPC_depend) << 2; 4875 ErrorFound = true; 4876 } else 4877 DependSourceClause = C; 4878 if (DependSinkClause) { 4879 Diag(C->getLocStart(), diag::err_omp_depend_sink_source_not_allowed) 4880 << 0; 4881 ErrorFound = true; 4882 } 4883 } else if (DC->getDependencyKind() == OMPC_DEPEND_sink) { 4884 if (DependSourceClause) { 4885 Diag(C->getLocStart(), diag::err_omp_depend_sink_source_not_allowed) 4886 << 1; 4887 ErrorFound = true; 4888 } 4889 DependSinkClause = C; 4890 } 4891 } else if (C->getClauseKind() == OMPC_threads) 4892 TC = cast<OMPThreadsClause>(C); 4893 else if (C->getClauseKind() == OMPC_simd) 4894 SC = cast<OMPSIMDClause>(C); 4895 } 4896 if (!ErrorFound && !SC && 4897 isOpenMPSimdDirective(DSAStack->getParentDirective())) { 4898 // OpenMP [2.8.1,simd Construct, Restrictions] 4899 // An ordered construct with the simd clause is the only OpenMP construct 4900 // that can appear in the simd region. 4901 Diag(StartLoc, diag::err_omp_prohibited_region_simd); 4902 ErrorFound = true; 4903 } else if (DependFound && (TC || SC)) { 4904 Diag(DependFound->getLocStart(), diag::err_omp_depend_clause_thread_simd) 4905 << getOpenMPClauseName(TC ? TC->getClauseKind() : SC->getClauseKind()); 4906 ErrorFound = true; 4907 } else if (DependFound && !DSAStack->getParentOrderedRegionParam()) { 4908 Diag(DependFound->getLocStart(), 4909 diag::err_omp_ordered_directive_without_param); 4910 ErrorFound = true; 4911 } else if (TC || Clauses.empty()) { 4912 if (auto *Param = DSAStack->getParentOrderedRegionParam()) { 4913 SourceLocation ErrLoc = TC ? TC->getLocStart() : StartLoc; 4914 Diag(ErrLoc, diag::err_omp_ordered_directive_with_param) 4915 << (TC != nullptr); 4916 Diag(Param->getLocStart(), diag::note_omp_ordered_param); 4917 ErrorFound = true; 4918 } 4919 } 4920 if ((!AStmt && !DependFound) || ErrorFound) 4921 return StmtError(); 4922 4923 if (AStmt) { 4924 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected"); 4925 4926 getCurFunction()->setHasBranchProtectedScope(); 4927 } 4928 4929 return OMPOrderedDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt); 4930 } 4931 4932 namespace { 4933 /// \brief Helper class for checking expression in 'omp atomic [update]' 4934 /// construct. 4935 class OpenMPAtomicUpdateChecker { 4936 /// \brief Error results for atomic update expressions. 4937 enum ExprAnalysisErrorCode { 4938 /// \brief A statement is not an expression statement. 4939 NotAnExpression, 4940 /// \brief Expression is not builtin binary or unary operation. 4941 NotABinaryOrUnaryExpression, 4942 /// \brief Unary operation is not post-/pre- increment/decrement operation. 4943 NotAnUnaryIncDecExpression, 4944 /// \brief An expression is not of scalar type. 4945 NotAScalarType, 4946 /// \brief A binary operation is not an assignment operation. 4947 NotAnAssignmentOp, 4948 /// \brief RHS part of the binary operation is not a binary expression. 4949 NotABinaryExpression, 4950 /// \brief RHS part is not additive/multiplicative/shift/biwise binary 4951 /// expression. 4952 NotABinaryOperator, 4953 /// \brief RHS binary operation does not have reference to the updated LHS 4954 /// part. 4955 NotAnUpdateExpression, 4956 /// \brief No errors is found. 4957 NoError 4958 }; 4959 /// \brief Reference to Sema. 4960 Sema &SemaRef; 4961 /// \brief A location for note diagnostics (when error is found). 4962 SourceLocation NoteLoc; 4963 /// \brief 'x' lvalue part of the source atomic expression. 4964 Expr *X; 4965 /// \brief 'expr' rvalue part of the source atomic expression. 4966 Expr *E; 4967 /// \brief Helper expression of the form 4968 /// 'OpaqueValueExpr(x) binop OpaqueValueExpr(expr)' or 4969 /// 'OpaqueValueExpr(expr) binop OpaqueValueExpr(x)'. 4970 Expr *UpdateExpr; 4971 /// \brief Is 'x' a LHS in a RHS part of full update expression. It is 4972 /// important for non-associative operations. 4973 bool IsXLHSInRHSPart; 4974 BinaryOperatorKind Op; 4975 SourceLocation OpLoc; 4976 /// \brief true if the source expression is a postfix unary operation, false 4977 /// if it is a prefix unary operation. 4978 bool IsPostfixUpdate; 4979 4980 public: 4981 OpenMPAtomicUpdateChecker(Sema &SemaRef) 4982 : SemaRef(SemaRef), X(nullptr), E(nullptr), UpdateExpr(nullptr), 4983 IsXLHSInRHSPart(false), Op(BO_PtrMemD), IsPostfixUpdate(false) {} 4984 /// \brief Check specified statement that it is suitable for 'atomic update' 4985 /// constructs and extract 'x', 'expr' and Operation from the original 4986 /// expression. If DiagId and NoteId == 0, then only check is performed 4987 /// without error notification. 4988 /// \param DiagId Diagnostic which should be emitted if error is found. 4989 /// \param NoteId Diagnostic note for the main error message. 4990 /// \return true if statement is not an update expression, false otherwise. 4991 bool checkStatement(Stmt *S, unsigned DiagId = 0, unsigned NoteId = 0); 4992 /// \brief Return the 'x' lvalue part of the source atomic expression. 4993 Expr *getX() const { return X; } 4994 /// \brief Return the 'expr' rvalue part of the source atomic expression. 4995 Expr *getExpr() const { return E; } 4996 /// \brief Return the update expression used in calculation of the updated 4997 /// value. Always has form 'OpaqueValueExpr(x) binop OpaqueValueExpr(expr)' or 4998 /// 'OpaqueValueExpr(expr) binop OpaqueValueExpr(x)'. 4999 Expr *getUpdateExpr() const { return UpdateExpr; } 5000 /// \brief Return true if 'x' is LHS in RHS part of full update expression, 5001 /// false otherwise. 5002 bool isXLHSInRHSPart() const { return IsXLHSInRHSPart; } 5003 5004 /// \brief true if the source expression is a postfix unary operation, false 5005 /// if it is a prefix unary operation. 5006 bool isPostfixUpdate() const { return IsPostfixUpdate; } 5007 5008 private: 5009 bool checkBinaryOperation(BinaryOperator *AtomicBinOp, unsigned DiagId = 0, 5010 unsigned NoteId = 0); 5011 }; 5012 } // namespace 5013 5014 bool OpenMPAtomicUpdateChecker::checkBinaryOperation( 5015 BinaryOperator *AtomicBinOp, unsigned DiagId, unsigned NoteId) { 5016 ExprAnalysisErrorCode ErrorFound = NoError; 5017 SourceLocation ErrorLoc, NoteLoc; 5018 SourceRange ErrorRange, NoteRange; 5019 // Allowed constructs are: 5020 // x = x binop expr; 5021 // x = expr binop x; 5022 if (AtomicBinOp->getOpcode() == BO_Assign) { 5023 X = AtomicBinOp->getLHS(); 5024 if (auto *AtomicInnerBinOp = dyn_cast<BinaryOperator>( 5025 AtomicBinOp->getRHS()->IgnoreParenImpCasts())) { 5026 if (AtomicInnerBinOp->isMultiplicativeOp() || 5027 AtomicInnerBinOp->isAdditiveOp() || AtomicInnerBinOp->isShiftOp() || 5028 AtomicInnerBinOp->isBitwiseOp()) { 5029 Op = AtomicInnerBinOp->getOpcode(); 5030 OpLoc = AtomicInnerBinOp->getOperatorLoc(); 5031 auto *LHS = AtomicInnerBinOp->getLHS(); 5032 auto *RHS = AtomicInnerBinOp->getRHS(); 5033 llvm::FoldingSetNodeID XId, LHSId, RHSId; 5034 X->IgnoreParenImpCasts()->Profile(XId, SemaRef.getASTContext(), 5035 /*Canonical=*/true); 5036 LHS->IgnoreParenImpCasts()->Profile(LHSId, SemaRef.getASTContext(), 5037 /*Canonical=*/true); 5038 RHS->IgnoreParenImpCasts()->Profile(RHSId, SemaRef.getASTContext(), 5039 /*Canonical=*/true); 5040 if (XId == LHSId) { 5041 E = RHS; 5042 IsXLHSInRHSPart = true; 5043 } else if (XId == RHSId) { 5044 E = LHS; 5045 IsXLHSInRHSPart = false; 5046 } else { 5047 ErrorLoc = AtomicInnerBinOp->getExprLoc(); 5048 ErrorRange = AtomicInnerBinOp->getSourceRange(); 5049 NoteLoc = X->getExprLoc(); 5050 NoteRange = X->getSourceRange(); 5051 ErrorFound = NotAnUpdateExpression; 5052 } 5053 } else { 5054 ErrorLoc = AtomicInnerBinOp->getExprLoc(); 5055 ErrorRange = AtomicInnerBinOp->getSourceRange(); 5056 NoteLoc = AtomicInnerBinOp->getOperatorLoc(); 5057 NoteRange = SourceRange(NoteLoc, NoteLoc); 5058 ErrorFound = NotABinaryOperator; 5059 } 5060 } else { 5061 NoteLoc = ErrorLoc = AtomicBinOp->getRHS()->getExprLoc(); 5062 NoteRange = ErrorRange = AtomicBinOp->getRHS()->getSourceRange(); 5063 ErrorFound = NotABinaryExpression; 5064 } 5065 } else { 5066 ErrorLoc = AtomicBinOp->getExprLoc(); 5067 ErrorRange = AtomicBinOp->getSourceRange(); 5068 NoteLoc = AtomicBinOp->getOperatorLoc(); 5069 NoteRange = SourceRange(NoteLoc, NoteLoc); 5070 ErrorFound = NotAnAssignmentOp; 5071 } 5072 if (ErrorFound != NoError && DiagId != 0 && NoteId != 0) { 5073 SemaRef.Diag(ErrorLoc, DiagId) << ErrorRange; 5074 SemaRef.Diag(NoteLoc, NoteId) << ErrorFound << NoteRange; 5075 return true; 5076 } else if (SemaRef.CurContext->isDependentContext()) 5077 E = X = UpdateExpr = nullptr; 5078 return ErrorFound != NoError; 5079 } 5080 5081 bool OpenMPAtomicUpdateChecker::checkStatement(Stmt *S, unsigned DiagId, 5082 unsigned NoteId) { 5083 ExprAnalysisErrorCode ErrorFound = NoError; 5084 SourceLocation ErrorLoc, NoteLoc; 5085 SourceRange ErrorRange, NoteRange; 5086 // Allowed constructs are: 5087 // x++; 5088 // x--; 5089 // ++x; 5090 // --x; 5091 // x binop= expr; 5092 // x = x binop expr; 5093 // x = expr binop x; 5094 if (auto *AtomicBody = dyn_cast<Expr>(S)) { 5095 AtomicBody = AtomicBody->IgnoreParenImpCasts(); 5096 if (AtomicBody->getType()->isScalarType() || 5097 AtomicBody->isInstantiationDependent()) { 5098 if (auto *AtomicCompAssignOp = dyn_cast<CompoundAssignOperator>( 5099 AtomicBody->IgnoreParenImpCasts())) { 5100 // Check for Compound Assignment Operation 5101 Op = BinaryOperator::getOpForCompoundAssignment( 5102 AtomicCompAssignOp->getOpcode()); 5103 OpLoc = AtomicCompAssignOp->getOperatorLoc(); 5104 E = AtomicCompAssignOp->getRHS(); 5105 X = AtomicCompAssignOp->getLHS()->IgnoreParens(); 5106 IsXLHSInRHSPart = true; 5107 } else if (auto *AtomicBinOp = dyn_cast<BinaryOperator>( 5108 AtomicBody->IgnoreParenImpCasts())) { 5109 // Check for Binary Operation 5110 if (checkBinaryOperation(AtomicBinOp, DiagId, NoteId)) 5111 return true; 5112 } else if (auto *AtomicUnaryOp = dyn_cast<UnaryOperator>( 5113 AtomicBody->IgnoreParenImpCasts())) { 5114 // Check for Unary Operation 5115 if (AtomicUnaryOp->isIncrementDecrementOp()) { 5116 IsPostfixUpdate = AtomicUnaryOp->isPostfix(); 5117 Op = AtomicUnaryOp->isIncrementOp() ? BO_Add : BO_Sub; 5118 OpLoc = AtomicUnaryOp->getOperatorLoc(); 5119 X = AtomicUnaryOp->getSubExpr()->IgnoreParens(); 5120 E = SemaRef.ActOnIntegerConstant(OpLoc, /*uint64_t Val=*/1).get(); 5121 IsXLHSInRHSPart = true; 5122 } else { 5123 ErrorFound = NotAnUnaryIncDecExpression; 5124 ErrorLoc = AtomicUnaryOp->getExprLoc(); 5125 ErrorRange = AtomicUnaryOp->getSourceRange(); 5126 NoteLoc = AtomicUnaryOp->getOperatorLoc(); 5127 NoteRange = SourceRange(NoteLoc, NoteLoc); 5128 } 5129 } else if (!AtomicBody->isInstantiationDependent()) { 5130 ErrorFound = NotABinaryOrUnaryExpression; 5131 NoteLoc = ErrorLoc = AtomicBody->getExprLoc(); 5132 NoteRange = ErrorRange = AtomicBody->getSourceRange(); 5133 } 5134 } else { 5135 ErrorFound = NotAScalarType; 5136 NoteLoc = ErrorLoc = AtomicBody->getLocStart(); 5137 NoteRange = ErrorRange = SourceRange(NoteLoc, NoteLoc); 5138 } 5139 } else { 5140 ErrorFound = NotAnExpression; 5141 NoteLoc = ErrorLoc = S->getLocStart(); 5142 NoteRange = ErrorRange = SourceRange(NoteLoc, NoteLoc); 5143 } 5144 if (ErrorFound != NoError && DiagId != 0 && NoteId != 0) { 5145 SemaRef.Diag(ErrorLoc, DiagId) << ErrorRange; 5146 SemaRef.Diag(NoteLoc, NoteId) << ErrorFound << NoteRange; 5147 return true; 5148 } else if (SemaRef.CurContext->isDependentContext()) 5149 E = X = UpdateExpr = nullptr; 5150 if (ErrorFound == NoError && E && X) { 5151 // Build an update expression of form 'OpaqueValueExpr(x) binop 5152 // OpaqueValueExpr(expr)' or 'OpaqueValueExpr(expr) binop 5153 // OpaqueValueExpr(x)' and then cast it to the type of the 'x' expression. 5154 auto *OVEX = new (SemaRef.getASTContext()) 5155 OpaqueValueExpr(X->getExprLoc(), X->getType(), VK_RValue); 5156 auto *OVEExpr = new (SemaRef.getASTContext()) 5157 OpaqueValueExpr(E->getExprLoc(), E->getType(), VK_RValue); 5158 auto Update = 5159 SemaRef.CreateBuiltinBinOp(OpLoc, Op, IsXLHSInRHSPart ? OVEX : OVEExpr, 5160 IsXLHSInRHSPart ? OVEExpr : OVEX); 5161 if (Update.isInvalid()) 5162 return true; 5163 Update = SemaRef.PerformImplicitConversion(Update.get(), X->getType(), 5164 Sema::AA_Casting); 5165 if (Update.isInvalid()) 5166 return true; 5167 UpdateExpr = Update.get(); 5168 } 5169 return ErrorFound != NoError; 5170 } 5171 5172 StmtResult Sema::ActOnOpenMPAtomicDirective(ArrayRef<OMPClause *> Clauses, 5173 Stmt *AStmt, 5174 SourceLocation StartLoc, 5175 SourceLocation EndLoc) { 5176 if (!AStmt) 5177 return StmtError(); 5178 5179 auto *CS = cast<CapturedStmt>(AStmt); 5180 // 1.2.2 OpenMP Language Terminology 5181 // Structured block - An executable statement with a single entry at the 5182 // top and a single exit at the bottom. 5183 // The point of exit cannot be a branch out of the structured block. 5184 // longjmp() and throw() must not violate the entry/exit criteria. 5185 OpenMPClauseKind AtomicKind = OMPC_unknown; 5186 SourceLocation AtomicKindLoc; 5187 for (auto *C : Clauses) { 5188 if (C->getClauseKind() == OMPC_read || C->getClauseKind() == OMPC_write || 5189 C->getClauseKind() == OMPC_update || 5190 C->getClauseKind() == OMPC_capture) { 5191 if (AtomicKind != OMPC_unknown) { 5192 Diag(C->getLocStart(), diag::err_omp_atomic_several_clauses) 5193 << SourceRange(C->getLocStart(), C->getLocEnd()); 5194 Diag(AtomicKindLoc, diag::note_omp_atomic_previous_clause) 5195 << getOpenMPClauseName(AtomicKind); 5196 } else { 5197 AtomicKind = C->getClauseKind(); 5198 AtomicKindLoc = C->getLocStart(); 5199 } 5200 } 5201 } 5202 5203 auto Body = CS->getCapturedStmt(); 5204 if (auto *EWC = dyn_cast<ExprWithCleanups>(Body)) 5205 Body = EWC->getSubExpr(); 5206 5207 Expr *X = nullptr; 5208 Expr *V = nullptr; 5209 Expr *E = nullptr; 5210 Expr *UE = nullptr; 5211 bool IsXLHSInRHSPart = false; 5212 bool IsPostfixUpdate = false; 5213 // OpenMP [2.12.6, atomic Construct] 5214 // In the next expressions: 5215 // * x and v (as applicable) are both l-value expressions with scalar type. 5216 // * During the execution of an atomic region, multiple syntactic 5217 // occurrences of x must designate the same storage location. 5218 // * Neither of v and expr (as applicable) may access the storage location 5219 // designated by x. 5220 // * Neither of x and expr (as applicable) may access the storage location 5221 // designated by v. 5222 // * expr is an expression with scalar type. 5223 // * binop is one of +, *, -, /, &, ^, |, <<, or >>. 5224 // * binop, binop=, ++, and -- are not overloaded operators. 5225 // * The expression x binop expr must be numerically equivalent to x binop 5226 // (expr). This requirement is satisfied if the operators in expr have 5227 // precedence greater than binop, or by using parentheses around expr or 5228 // subexpressions of expr. 5229 // * The expression expr binop x must be numerically equivalent to (expr) 5230 // binop x. This requirement is satisfied if the operators in expr have 5231 // precedence equal to or greater than binop, or by using parentheses around 5232 // expr or subexpressions of expr. 5233 // * For forms that allow multiple occurrences of x, the number of times 5234 // that x is evaluated is unspecified. 5235 if (AtomicKind == OMPC_read) { 5236 enum { 5237 NotAnExpression, 5238 NotAnAssignmentOp, 5239 NotAScalarType, 5240 NotAnLValue, 5241 NoError 5242 } ErrorFound = NoError; 5243 SourceLocation ErrorLoc, NoteLoc; 5244 SourceRange ErrorRange, NoteRange; 5245 // If clause is read: 5246 // v = x; 5247 if (auto *AtomicBody = dyn_cast<Expr>(Body)) { 5248 auto *AtomicBinOp = 5249 dyn_cast<BinaryOperator>(AtomicBody->IgnoreParenImpCasts()); 5250 if (AtomicBinOp && AtomicBinOp->getOpcode() == BO_Assign) { 5251 X = AtomicBinOp->getRHS()->IgnoreParenImpCasts(); 5252 V = AtomicBinOp->getLHS()->IgnoreParenImpCasts(); 5253 if ((X->isInstantiationDependent() || X->getType()->isScalarType()) && 5254 (V->isInstantiationDependent() || V->getType()->isScalarType())) { 5255 if (!X->isLValue() || !V->isLValue()) { 5256 auto NotLValueExpr = X->isLValue() ? V : X; 5257 ErrorFound = NotAnLValue; 5258 ErrorLoc = AtomicBinOp->getExprLoc(); 5259 ErrorRange = AtomicBinOp->getSourceRange(); 5260 NoteLoc = NotLValueExpr->getExprLoc(); 5261 NoteRange = NotLValueExpr->getSourceRange(); 5262 } 5263 } else if (!X->isInstantiationDependent() || 5264 !V->isInstantiationDependent()) { 5265 auto NotScalarExpr = 5266 (X->isInstantiationDependent() || X->getType()->isScalarType()) 5267 ? V 5268 : X; 5269 ErrorFound = NotAScalarType; 5270 ErrorLoc = AtomicBinOp->getExprLoc(); 5271 ErrorRange = AtomicBinOp->getSourceRange(); 5272 NoteLoc = NotScalarExpr->getExprLoc(); 5273 NoteRange = NotScalarExpr->getSourceRange(); 5274 } 5275 } else if (!AtomicBody->isInstantiationDependent()) { 5276 ErrorFound = NotAnAssignmentOp; 5277 ErrorLoc = AtomicBody->getExprLoc(); 5278 ErrorRange = AtomicBody->getSourceRange(); 5279 NoteLoc = AtomicBinOp ? AtomicBinOp->getOperatorLoc() 5280 : AtomicBody->getExprLoc(); 5281 NoteRange = AtomicBinOp ? AtomicBinOp->getSourceRange() 5282 : AtomicBody->getSourceRange(); 5283 } 5284 } else { 5285 ErrorFound = NotAnExpression; 5286 NoteLoc = ErrorLoc = Body->getLocStart(); 5287 NoteRange = ErrorRange = SourceRange(NoteLoc, NoteLoc); 5288 } 5289 if (ErrorFound != NoError) { 5290 Diag(ErrorLoc, diag::err_omp_atomic_read_not_expression_statement) 5291 << ErrorRange; 5292 Diag(NoteLoc, diag::note_omp_atomic_read_write) << ErrorFound 5293 << NoteRange; 5294 return StmtError(); 5295 } else if (CurContext->isDependentContext()) 5296 V = X = nullptr; 5297 } else if (AtomicKind == OMPC_write) { 5298 enum { 5299 NotAnExpression, 5300 NotAnAssignmentOp, 5301 NotAScalarType, 5302 NotAnLValue, 5303 NoError 5304 } ErrorFound = NoError; 5305 SourceLocation ErrorLoc, NoteLoc; 5306 SourceRange ErrorRange, NoteRange; 5307 // If clause is write: 5308 // x = expr; 5309 if (auto *AtomicBody = dyn_cast<Expr>(Body)) { 5310 auto *AtomicBinOp = 5311 dyn_cast<BinaryOperator>(AtomicBody->IgnoreParenImpCasts()); 5312 if (AtomicBinOp && AtomicBinOp->getOpcode() == BO_Assign) { 5313 X = AtomicBinOp->getLHS(); 5314 E = AtomicBinOp->getRHS(); 5315 if ((X->isInstantiationDependent() || X->getType()->isScalarType()) && 5316 (E->isInstantiationDependent() || E->getType()->isScalarType())) { 5317 if (!X->isLValue()) { 5318 ErrorFound = NotAnLValue; 5319 ErrorLoc = AtomicBinOp->getExprLoc(); 5320 ErrorRange = AtomicBinOp->getSourceRange(); 5321 NoteLoc = X->getExprLoc(); 5322 NoteRange = X->getSourceRange(); 5323 } 5324 } else if (!X->isInstantiationDependent() || 5325 !E->isInstantiationDependent()) { 5326 auto NotScalarExpr = 5327 (X->isInstantiationDependent() || X->getType()->isScalarType()) 5328 ? E 5329 : X; 5330 ErrorFound = NotAScalarType; 5331 ErrorLoc = AtomicBinOp->getExprLoc(); 5332 ErrorRange = AtomicBinOp->getSourceRange(); 5333 NoteLoc = NotScalarExpr->getExprLoc(); 5334 NoteRange = NotScalarExpr->getSourceRange(); 5335 } 5336 } else if (!AtomicBody->isInstantiationDependent()) { 5337 ErrorFound = NotAnAssignmentOp; 5338 ErrorLoc = AtomicBody->getExprLoc(); 5339 ErrorRange = AtomicBody->getSourceRange(); 5340 NoteLoc = AtomicBinOp ? AtomicBinOp->getOperatorLoc() 5341 : AtomicBody->getExprLoc(); 5342 NoteRange = AtomicBinOp ? AtomicBinOp->getSourceRange() 5343 : AtomicBody->getSourceRange(); 5344 } 5345 } else { 5346 ErrorFound = NotAnExpression; 5347 NoteLoc = ErrorLoc = Body->getLocStart(); 5348 NoteRange = ErrorRange = SourceRange(NoteLoc, NoteLoc); 5349 } 5350 if (ErrorFound != NoError) { 5351 Diag(ErrorLoc, diag::err_omp_atomic_write_not_expression_statement) 5352 << ErrorRange; 5353 Diag(NoteLoc, diag::note_omp_atomic_read_write) << ErrorFound 5354 << NoteRange; 5355 return StmtError(); 5356 } else if (CurContext->isDependentContext()) 5357 E = X = nullptr; 5358 } else if (AtomicKind == OMPC_update || AtomicKind == OMPC_unknown) { 5359 // If clause is update: 5360 // x++; 5361 // x--; 5362 // ++x; 5363 // --x; 5364 // x binop= expr; 5365 // x = x binop expr; 5366 // x = expr binop x; 5367 OpenMPAtomicUpdateChecker Checker(*this); 5368 if (Checker.checkStatement( 5369 Body, (AtomicKind == OMPC_update) 5370 ? diag::err_omp_atomic_update_not_expression_statement 5371 : diag::err_omp_atomic_not_expression_statement, 5372 diag::note_omp_atomic_update)) 5373 return StmtError(); 5374 if (!CurContext->isDependentContext()) { 5375 E = Checker.getExpr(); 5376 X = Checker.getX(); 5377 UE = Checker.getUpdateExpr(); 5378 IsXLHSInRHSPart = Checker.isXLHSInRHSPart(); 5379 } 5380 } else if (AtomicKind == OMPC_capture) { 5381 enum { 5382 NotAnAssignmentOp, 5383 NotACompoundStatement, 5384 NotTwoSubstatements, 5385 NotASpecificExpression, 5386 NoError 5387 } ErrorFound = NoError; 5388 SourceLocation ErrorLoc, NoteLoc; 5389 SourceRange ErrorRange, NoteRange; 5390 if (auto *AtomicBody = dyn_cast<Expr>(Body)) { 5391 // If clause is a capture: 5392 // v = x++; 5393 // v = x--; 5394 // v = ++x; 5395 // v = --x; 5396 // v = x binop= expr; 5397 // v = x = x binop expr; 5398 // v = x = expr binop x; 5399 auto *AtomicBinOp = 5400 dyn_cast<BinaryOperator>(AtomicBody->IgnoreParenImpCasts()); 5401 if (AtomicBinOp && AtomicBinOp->getOpcode() == BO_Assign) { 5402 V = AtomicBinOp->getLHS(); 5403 Body = AtomicBinOp->getRHS()->IgnoreParenImpCasts(); 5404 OpenMPAtomicUpdateChecker Checker(*this); 5405 if (Checker.checkStatement( 5406 Body, diag::err_omp_atomic_capture_not_expression_statement, 5407 diag::note_omp_atomic_update)) 5408 return StmtError(); 5409 E = Checker.getExpr(); 5410 X = Checker.getX(); 5411 UE = Checker.getUpdateExpr(); 5412 IsXLHSInRHSPart = Checker.isXLHSInRHSPart(); 5413 IsPostfixUpdate = Checker.isPostfixUpdate(); 5414 } else if (!AtomicBody->isInstantiationDependent()) { 5415 ErrorLoc = AtomicBody->getExprLoc(); 5416 ErrorRange = AtomicBody->getSourceRange(); 5417 NoteLoc = AtomicBinOp ? AtomicBinOp->getOperatorLoc() 5418 : AtomicBody->getExprLoc(); 5419 NoteRange = AtomicBinOp ? AtomicBinOp->getSourceRange() 5420 : AtomicBody->getSourceRange(); 5421 ErrorFound = NotAnAssignmentOp; 5422 } 5423 if (ErrorFound != NoError) { 5424 Diag(ErrorLoc, diag::err_omp_atomic_capture_not_expression_statement) 5425 << ErrorRange; 5426 Diag(NoteLoc, diag::note_omp_atomic_capture) << ErrorFound << NoteRange; 5427 return StmtError(); 5428 } else if (CurContext->isDependentContext()) { 5429 UE = V = E = X = nullptr; 5430 } 5431 } else { 5432 // If clause is a capture: 5433 // { v = x; x = expr; } 5434 // { v = x; x++; } 5435 // { v = x; x--; } 5436 // { v = x; ++x; } 5437 // { v = x; --x; } 5438 // { v = x; x binop= expr; } 5439 // { v = x; x = x binop expr; } 5440 // { v = x; x = expr binop x; } 5441 // { x++; v = x; } 5442 // { x--; v = x; } 5443 // { ++x; v = x; } 5444 // { --x; v = x; } 5445 // { x binop= expr; v = x; } 5446 // { x = x binop expr; v = x; } 5447 // { x = expr binop x; v = x; } 5448 if (auto *CS = dyn_cast<CompoundStmt>(Body)) { 5449 // Check that this is { expr1; expr2; } 5450 if (CS->size() == 2) { 5451 auto *First = CS->body_front(); 5452 auto *Second = CS->body_back(); 5453 if (auto *EWC = dyn_cast<ExprWithCleanups>(First)) 5454 First = EWC->getSubExpr()->IgnoreParenImpCasts(); 5455 if (auto *EWC = dyn_cast<ExprWithCleanups>(Second)) 5456 Second = EWC->getSubExpr()->IgnoreParenImpCasts(); 5457 // Need to find what subexpression is 'v' and what is 'x'. 5458 OpenMPAtomicUpdateChecker Checker(*this); 5459 bool IsUpdateExprFound = !Checker.checkStatement(Second); 5460 BinaryOperator *BinOp = nullptr; 5461 if (IsUpdateExprFound) { 5462 BinOp = dyn_cast<BinaryOperator>(First); 5463 IsUpdateExprFound = BinOp && BinOp->getOpcode() == BO_Assign; 5464 } 5465 if (IsUpdateExprFound && !CurContext->isDependentContext()) { 5466 // { v = x; x++; } 5467 // { v = x; x--; } 5468 // { v = x; ++x; } 5469 // { v = x; --x; } 5470 // { v = x; x binop= expr; } 5471 // { v = x; x = x binop expr; } 5472 // { v = x; x = expr binop x; } 5473 // Check that the first expression has form v = x. 5474 auto *PossibleX = BinOp->getRHS()->IgnoreParenImpCasts(); 5475 llvm::FoldingSetNodeID XId, PossibleXId; 5476 Checker.getX()->Profile(XId, Context, /*Canonical=*/true); 5477 PossibleX->Profile(PossibleXId, Context, /*Canonical=*/true); 5478 IsUpdateExprFound = XId == PossibleXId; 5479 if (IsUpdateExprFound) { 5480 V = BinOp->getLHS(); 5481 X = Checker.getX(); 5482 E = Checker.getExpr(); 5483 UE = Checker.getUpdateExpr(); 5484 IsXLHSInRHSPart = Checker.isXLHSInRHSPart(); 5485 IsPostfixUpdate = true; 5486 } 5487 } 5488 if (!IsUpdateExprFound) { 5489 IsUpdateExprFound = !Checker.checkStatement(First); 5490 BinOp = nullptr; 5491 if (IsUpdateExprFound) { 5492 BinOp = dyn_cast<BinaryOperator>(Second); 5493 IsUpdateExprFound = BinOp && BinOp->getOpcode() == BO_Assign; 5494 } 5495 if (IsUpdateExprFound && !CurContext->isDependentContext()) { 5496 // { x++; v = x; } 5497 // { x--; v = x; } 5498 // { ++x; v = x; } 5499 // { --x; v = x; } 5500 // { x binop= expr; v = x; } 5501 // { x = x binop expr; v = x; } 5502 // { x = expr binop x; v = x; } 5503 // Check that the second expression has form v = x. 5504 auto *PossibleX = BinOp->getRHS()->IgnoreParenImpCasts(); 5505 llvm::FoldingSetNodeID XId, PossibleXId; 5506 Checker.getX()->Profile(XId, Context, /*Canonical=*/true); 5507 PossibleX->Profile(PossibleXId, Context, /*Canonical=*/true); 5508 IsUpdateExprFound = XId == PossibleXId; 5509 if (IsUpdateExprFound) { 5510 V = BinOp->getLHS(); 5511 X = Checker.getX(); 5512 E = Checker.getExpr(); 5513 UE = Checker.getUpdateExpr(); 5514 IsXLHSInRHSPart = Checker.isXLHSInRHSPart(); 5515 IsPostfixUpdate = false; 5516 } 5517 } 5518 } 5519 if (!IsUpdateExprFound) { 5520 // { v = x; x = expr; } 5521 auto *FirstExpr = dyn_cast<Expr>(First); 5522 auto *SecondExpr = dyn_cast<Expr>(Second); 5523 if (!FirstExpr || !SecondExpr || 5524 !(FirstExpr->isInstantiationDependent() || 5525 SecondExpr->isInstantiationDependent())) { 5526 auto *FirstBinOp = dyn_cast<BinaryOperator>(First); 5527 if (!FirstBinOp || FirstBinOp->getOpcode() != BO_Assign) { 5528 ErrorFound = NotAnAssignmentOp; 5529 NoteLoc = ErrorLoc = FirstBinOp ? FirstBinOp->getOperatorLoc() 5530 : First->getLocStart(); 5531 NoteRange = ErrorRange = FirstBinOp 5532 ? FirstBinOp->getSourceRange() 5533 : SourceRange(ErrorLoc, ErrorLoc); 5534 } else { 5535 auto *SecondBinOp = dyn_cast<BinaryOperator>(Second); 5536 if (!SecondBinOp || SecondBinOp->getOpcode() != BO_Assign) { 5537 ErrorFound = NotAnAssignmentOp; 5538 NoteLoc = ErrorLoc = SecondBinOp 5539 ? SecondBinOp->getOperatorLoc() 5540 : Second->getLocStart(); 5541 NoteRange = ErrorRange = 5542 SecondBinOp ? SecondBinOp->getSourceRange() 5543 : SourceRange(ErrorLoc, ErrorLoc); 5544 } else { 5545 auto *PossibleXRHSInFirst = 5546 FirstBinOp->getRHS()->IgnoreParenImpCasts(); 5547 auto *PossibleXLHSInSecond = 5548 SecondBinOp->getLHS()->IgnoreParenImpCasts(); 5549 llvm::FoldingSetNodeID X1Id, X2Id; 5550 PossibleXRHSInFirst->Profile(X1Id, Context, 5551 /*Canonical=*/true); 5552 PossibleXLHSInSecond->Profile(X2Id, Context, 5553 /*Canonical=*/true); 5554 IsUpdateExprFound = X1Id == X2Id; 5555 if (IsUpdateExprFound) { 5556 V = FirstBinOp->getLHS(); 5557 X = SecondBinOp->getLHS(); 5558 E = SecondBinOp->getRHS(); 5559 UE = nullptr; 5560 IsXLHSInRHSPart = false; 5561 IsPostfixUpdate = true; 5562 } else { 5563 ErrorFound = NotASpecificExpression; 5564 ErrorLoc = FirstBinOp->getExprLoc(); 5565 ErrorRange = FirstBinOp->getSourceRange(); 5566 NoteLoc = SecondBinOp->getLHS()->getExprLoc(); 5567 NoteRange = SecondBinOp->getRHS()->getSourceRange(); 5568 } 5569 } 5570 } 5571 } 5572 } 5573 } else { 5574 NoteLoc = ErrorLoc = Body->getLocStart(); 5575 NoteRange = ErrorRange = 5576 SourceRange(Body->getLocStart(), Body->getLocStart()); 5577 ErrorFound = NotTwoSubstatements; 5578 } 5579 } else { 5580 NoteLoc = ErrorLoc = Body->getLocStart(); 5581 NoteRange = ErrorRange = 5582 SourceRange(Body->getLocStart(), Body->getLocStart()); 5583 ErrorFound = NotACompoundStatement; 5584 } 5585 if (ErrorFound != NoError) { 5586 Diag(ErrorLoc, diag::err_omp_atomic_capture_not_compound_statement) 5587 << ErrorRange; 5588 Diag(NoteLoc, diag::note_omp_atomic_capture) << ErrorFound << NoteRange; 5589 return StmtError(); 5590 } else if (CurContext->isDependentContext()) { 5591 UE = V = E = X = nullptr; 5592 } 5593 } 5594 } 5595 5596 getCurFunction()->setHasBranchProtectedScope(); 5597 5598 return OMPAtomicDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt, 5599 X, V, E, UE, IsXLHSInRHSPart, 5600 IsPostfixUpdate); 5601 } 5602 5603 StmtResult Sema::ActOnOpenMPTargetDirective(ArrayRef<OMPClause *> Clauses, 5604 Stmt *AStmt, 5605 SourceLocation StartLoc, 5606 SourceLocation EndLoc) { 5607 if (!AStmt) 5608 return StmtError(); 5609 5610 CapturedStmt *CS = cast<CapturedStmt>(AStmt); 5611 // 1.2.2 OpenMP Language Terminology 5612 // Structured block - An executable statement with a single entry at the 5613 // top and a single exit at the bottom. 5614 // The point of exit cannot be a branch out of the structured block. 5615 // longjmp() and throw() must not violate the entry/exit criteria. 5616 CS->getCapturedDecl()->setNothrow(); 5617 5618 // OpenMP [2.16, Nesting of Regions] 5619 // If specified, a teams construct must be contained within a target 5620 // construct. That target construct must contain no statements or directives 5621 // outside of the teams construct. 5622 if (DSAStack->hasInnerTeamsRegion()) { 5623 auto S = AStmt->IgnoreContainers(/*IgnoreCaptured*/ true); 5624 bool OMPTeamsFound = true; 5625 if (auto *CS = dyn_cast<CompoundStmt>(S)) { 5626 auto I = CS->body_begin(); 5627 while (I != CS->body_end()) { 5628 auto *OED = dyn_cast<OMPExecutableDirective>(*I); 5629 if (!OED || !isOpenMPTeamsDirective(OED->getDirectiveKind())) { 5630 OMPTeamsFound = false; 5631 break; 5632 } 5633 ++I; 5634 } 5635 assert(I != CS->body_end() && "Not found statement"); 5636 S = *I; 5637 } else { 5638 auto *OED = dyn_cast<OMPExecutableDirective>(S); 5639 OMPTeamsFound = OED && isOpenMPTeamsDirective(OED->getDirectiveKind()); 5640 } 5641 if (!OMPTeamsFound) { 5642 Diag(StartLoc, diag::err_omp_target_contains_not_only_teams); 5643 Diag(DSAStack->getInnerTeamsRegionLoc(), 5644 diag::note_omp_nested_teams_construct_here); 5645 Diag(S->getLocStart(), diag::note_omp_nested_statement_here) 5646 << isa<OMPExecutableDirective>(S); 5647 return StmtError(); 5648 } 5649 } 5650 5651 getCurFunction()->setHasBranchProtectedScope(); 5652 5653 return OMPTargetDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt); 5654 } 5655 5656 StmtResult 5657 Sema::ActOnOpenMPTargetParallelDirective(ArrayRef<OMPClause *> Clauses, 5658 Stmt *AStmt, SourceLocation StartLoc, 5659 SourceLocation EndLoc) { 5660 if (!AStmt) 5661 return StmtError(); 5662 5663 CapturedStmt *CS = cast<CapturedStmt>(AStmt); 5664 // 1.2.2 OpenMP Language Terminology 5665 // Structured block - An executable statement with a single entry at the 5666 // top and a single exit at the bottom. 5667 // The point of exit cannot be a branch out of the structured block. 5668 // longjmp() and throw() must not violate the entry/exit criteria. 5669 CS->getCapturedDecl()->setNothrow(); 5670 5671 getCurFunction()->setHasBranchProtectedScope(); 5672 5673 return OMPTargetParallelDirective::Create(Context, StartLoc, EndLoc, Clauses, 5674 AStmt); 5675 } 5676 5677 StmtResult Sema::ActOnOpenMPTargetParallelForDirective( 5678 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, 5679 SourceLocation EndLoc, 5680 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) { 5681 if (!AStmt) 5682 return StmtError(); 5683 5684 CapturedStmt *CS = cast<CapturedStmt>(AStmt); 5685 // 1.2.2 OpenMP Language Terminology 5686 // Structured block - An executable statement with a single entry at the 5687 // top and a single exit at the bottom. 5688 // The point of exit cannot be a branch out of the structured block. 5689 // longjmp() and throw() must not violate the entry/exit criteria. 5690 CS->getCapturedDecl()->setNothrow(); 5691 5692 OMPLoopDirective::HelperExprs B; 5693 // In presence of clause 'collapse' or 'ordered' with number of loops, it will 5694 // define the nested loops number. 5695 unsigned NestedLoopCount = 5696 CheckOpenMPLoop(OMPD_target_parallel_for, getCollapseNumberExpr(Clauses), 5697 getOrderedNumberExpr(Clauses), AStmt, *this, *DSAStack, 5698 VarsWithImplicitDSA, B); 5699 if (NestedLoopCount == 0) 5700 return StmtError(); 5701 5702 assert((CurContext->isDependentContext() || B.builtAll()) && 5703 "omp target parallel for loop exprs were not built"); 5704 5705 if (!CurContext->isDependentContext()) { 5706 // Finalize the clauses that need pre-built expressions for CodeGen. 5707 for (auto C : Clauses) { 5708 if (auto *LC = dyn_cast<OMPLinearClause>(C)) 5709 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef), 5710 B.NumIterations, *this, CurScope, 5711 DSAStack)) 5712 return StmtError(); 5713 } 5714 } 5715 5716 getCurFunction()->setHasBranchProtectedScope(); 5717 return OMPTargetParallelForDirective::Create(Context, StartLoc, EndLoc, 5718 NestedLoopCount, Clauses, AStmt, 5719 B, DSAStack->isCancelRegion()); 5720 } 5721 5722 /// \brief Check for existence of a map clause in the list of clauses. 5723 static bool HasMapClause(ArrayRef<OMPClause *> Clauses) { 5724 for (ArrayRef<OMPClause *>::iterator I = Clauses.begin(), E = Clauses.end(); 5725 I != E; ++I) { 5726 if (*I != nullptr && (*I)->getClauseKind() == OMPC_map) { 5727 return true; 5728 } 5729 } 5730 5731 return false; 5732 } 5733 5734 StmtResult Sema::ActOnOpenMPTargetDataDirective(ArrayRef<OMPClause *> Clauses, 5735 Stmt *AStmt, 5736 SourceLocation StartLoc, 5737 SourceLocation EndLoc) { 5738 if (!AStmt) 5739 return StmtError(); 5740 5741 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected"); 5742 5743 // OpenMP [2.10.1, Restrictions, p. 97] 5744 // At least one map clause must appear on the directive. 5745 if (!HasMapClause(Clauses)) { 5746 Diag(StartLoc, diag::err_omp_no_map_for_directive) 5747 << getOpenMPDirectiveName(OMPD_target_data); 5748 return StmtError(); 5749 } 5750 5751 getCurFunction()->setHasBranchProtectedScope(); 5752 5753 return OMPTargetDataDirective::Create(Context, StartLoc, EndLoc, Clauses, 5754 AStmt); 5755 } 5756 5757 StmtResult 5758 Sema::ActOnOpenMPTargetEnterDataDirective(ArrayRef<OMPClause *> Clauses, 5759 SourceLocation StartLoc, 5760 SourceLocation EndLoc) { 5761 // OpenMP [2.10.2, Restrictions, p. 99] 5762 // At least one map clause must appear on the directive. 5763 if (!HasMapClause(Clauses)) { 5764 Diag(StartLoc, diag::err_omp_no_map_for_directive) 5765 << getOpenMPDirectiveName(OMPD_target_enter_data); 5766 return StmtError(); 5767 } 5768 5769 return OMPTargetEnterDataDirective::Create(Context, StartLoc, EndLoc, 5770 Clauses); 5771 } 5772 5773 StmtResult 5774 Sema::ActOnOpenMPTargetExitDataDirective(ArrayRef<OMPClause *> Clauses, 5775 SourceLocation StartLoc, 5776 SourceLocation EndLoc) { 5777 // OpenMP [2.10.3, Restrictions, p. 102] 5778 // At least one map clause must appear on the directive. 5779 if (!HasMapClause(Clauses)) { 5780 Diag(StartLoc, diag::err_omp_no_map_for_directive) 5781 << getOpenMPDirectiveName(OMPD_target_exit_data); 5782 return StmtError(); 5783 } 5784 5785 return OMPTargetExitDataDirective::Create(Context, StartLoc, EndLoc, Clauses); 5786 } 5787 5788 StmtResult Sema::ActOnOpenMPTargetUpdateDirective(ArrayRef<OMPClause *> Clauses, 5789 SourceLocation StartLoc, 5790 SourceLocation EndLoc) { 5791 bool seenMotionClause = false; 5792 for (auto *C : Clauses) { 5793 if (C->getClauseKind() == OMPC_to || C->getClauseKind() == OMPC_from) 5794 seenMotionClause = true; 5795 } 5796 if (!seenMotionClause) { 5797 Diag(StartLoc, diag::err_omp_at_least_one_motion_clause_required); 5798 return StmtError(); 5799 } 5800 return OMPTargetUpdateDirective::Create(Context, StartLoc, EndLoc, Clauses); 5801 } 5802 5803 StmtResult Sema::ActOnOpenMPTeamsDirective(ArrayRef<OMPClause *> Clauses, 5804 Stmt *AStmt, SourceLocation StartLoc, 5805 SourceLocation EndLoc) { 5806 if (!AStmt) 5807 return StmtError(); 5808 5809 CapturedStmt *CS = cast<CapturedStmt>(AStmt); 5810 // 1.2.2 OpenMP Language Terminology 5811 // Structured block - An executable statement with a single entry at the 5812 // top and a single exit at the bottom. 5813 // The point of exit cannot be a branch out of the structured block. 5814 // longjmp() and throw() must not violate the entry/exit criteria. 5815 CS->getCapturedDecl()->setNothrow(); 5816 5817 getCurFunction()->setHasBranchProtectedScope(); 5818 5819 return OMPTeamsDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt); 5820 } 5821 5822 StmtResult 5823 Sema::ActOnOpenMPCancellationPointDirective(SourceLocation StartLoc, 5824 SourceLocation EndLoc, 5825 OpenMPDirectiveKind CancelRegion) { 5826 if (CancelRegion != OMPD_parallel && CancelRegion != OMPD_for && 5827 CancelRegion != OMPD_sections && CancelRegion != OMPD_taskgroup) { 5828 Diag(StartLoc, diag::err_omp_wrong_cancel_region) 5829 << getOpenMPDirectiveName(CancelRegion); 5830 return StmtError(); 5831 } 5832 if (DSAStack->isParentNowaitRegion()) { 5833 Diag(StartLoc, diag::err_omp_parent_cancel_region_nowait) << 0; 5834 return StmtError(); 5835 } 5836 if (DSAStack->isParentOrderedRegion()) { 5837 Diag(StartLoc, diag::err_omp_parent_cancel_region_ordered) << 0; 5838 return StmtError(); 5839 } 5840 return OMPCancellationPointDirective::Create(Context, StartLoc, EndLoc, 5841 CancelRegion); 5842 } 5843 5844 StmtResult Sema::ActOnOpenMPCancelDirective(ArrayRef<OMPClause *> Clauses, 5845 SourceLocation StartLoc, 5846 SourceLocation EndLoc, 5847 OpenMPDirectiveKind CancelRegion) { 5848 if (CancelRegion != OMPD_parallel && CancelRegion != OMPD_for && 5849 CancelRegion != OMPD_sections && CancelRegion != OMPD_taskgroup) { 5850 Diag(StartLoc, diag::err_omp_wrong_cancel_region) 5851 << getOpenMPDirectiveName(CancelRegion); 5852 return StmtError(); 5853 } 5854 if (DSAStack->isParentNowaitRegion()) { 5855 Diag(StartLoc, diag::err_omp_parent_cancel_region_nowait) << 1; 5856 return StmtError(); 5857 } 5858 if (DSAStack->isParentOrderedRegion()) { 5859 Diag(StartLoc, diag::err_omp_parent_cancel_region_ordered) << 1; 5860 return StmtError(); 5861 } 5862 DSAStack->setParentCancelRegion(/*Cancel=*/true); 5863 return OMPCancelDirective::Create(Context, StartLoc, EndLoc, Clauses, 5864 CancelRegion); 5865 } 5866 5867 static bool checkGrainsizeNumTasksClauses(Sema &S, 5868 ArrayRef<OMPClause *> Clauses) { 5869 OMPClause *PrevClause = nullptr; 5870 bool ErrorFound = false; 5871 for (auto *C : Clauses) { 5872 if (C->getClauseKind() == OMPC_grainsize || 5873 C->getClauseKind() == OMPC_num_tasks) { 5874 if (!PrevClause) 5875 PrevClause = C; 5876 else if (PrevClause->getClauseKind() != C->getClauseKind()) { 5877 S.Diag(C->getLocStart(), 5878 diag::err_omp_grainsize_num_tasks_mutually_exclusive) 5879 << getOpenMPClauseName(C->getClauseKind()) 5880 << getOpenMPClauseName(PrevClause->getClauseKind()); 5881 S.Diag(PrevClause->getLocStart(), 5882 diag::note_omp_previous_grainsize_num_tasks) 5883 << getOpenMPClauseName(PrevClause->getClauseKind()); 5884 ErrorFound = true; 5885 } 5886 } 5887 } 5888 return ErrorFound; 5889 } 5890 5891 StmtResult Sema::ActOnOpenMPTaskLoopDirective( 5892 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, 5893 SourceLocation EndLoc, 5894 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) { 5895 if (!AStmt) 5896 return StmtError(); 5897 5898 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected"); 5899 OMPLoopDirective::HelperExprs B; 5900 // In presence of clause 'collapse' or 'ordered' with number of loops, it will 5901 // define the nested loops number. 5902 unsigned NestedLoopCount = 5903 CheckOpenMPLoop(OMPD_taskloop, getCollapseNumberExpr(Clauses), 5904 /*OrderedLoopCountExpr=*/nullptr, AStmt, *this, *DSAStack, 5905 VarsWithImplicitDSA, B); 5906 if (NestedLoopCount == 0) 5907 return StmtError(); 5908 5909 assert((CurContext->isDependentContext() || B.builtAll()) && 5910 "omp for loop exprs were not built"); 5911 5912 // OpenMP, [2.9.2 taskloop Construct, Restrictions] 5913 // The grainsize clause and num_tasks clause are mutually exclusive and may 5914 // not appear on the same taskloop directive. 5915 if (checkGrainsizeNumTasksClauses(*this, Clauses)) 5916 return StmtError(); 5917 5918 getCurFunction()->setHasBranchProtectedScope(); 5919 return OMPTaskLoopDirective::Create(Context, StartLoc, EndLoc, 5920 NestedLoopCount, Clauses, AStmt, B); 5921 } 5922 5923 StmtResult Sema::ActOnOpenMPTaskLoopSimdDirective( 5924 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, 5925 SourceLocation EndLoc, 5926 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) { 5927 if (!AStmt) 5928 return StmtError(); 5929 5930 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected"); 5931 OMPLoopDirective::HelperExprs B; 5932 // In presence of clause 'collapse' or 'ordered' with number of loops, it will 5933 // define the nested loops number. 5934 unsigned NestedLoopCount = 5935 CheckOpenMPLoop(OMPD_taskloop_simd, getCollapseNumberExpr(Clauses), 5936 /*OrderedLoopCountExpr=*/nullptr, AStmt, *this, *DSAStack, 5937 VarsWithImplicitDSA, B); 5938 if (NestedLoopCount == 0) 5939 return StmtError(); 5940 5941 assert((CurContext->isDependentContext() || B.builtAll()) && 5942 "omp for loop exprs were not built"); 5943 5944 if (!CurContext->isDependentContext()) { 5945 // Finalize the clauses that need pre-built expressions for CodeGen. 5946 for (auto C : Clauses) { 5947 if (auto *LC = dyn_cast<OMPLinearClause>(C)) 5948 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef), 5949 B.NumIterations, *this, CurScope, 5950 DSAStack)) 5951 return StmtError(); 5952 } 5953 } 5954 5955 // OpenMP, [2.9.2 taskloop Construct, Restrictions] 5956 // The grainsize clause and num_tasks clause are mutually exclusive and may 5957 // not appear on the same taskloop directive. 5958 if (checkGrainsizeNumTasksClauses(*this, Clauses)) 5959 return StmtError(); 5960 5961 getCurFunction()->setHasBranchProtectedScope(); 5962 return OMPTaskLoopSimdDirective::Create(Context, StartLoc, EndLoc, 5963 NestedLoopCount, Clauses, AStmt, B); 5964 } 5965 5966 StmtResult Sema::ActOnOpenMPDistributeDirective( 5967 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, 5968 SourceLocation EndLoc, 5969 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) { 5970 if (!AStmt) 5971 return StmtError(); 5972 5973 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected"); 5974 OMPLoopDirective::HelperExprs B; 5975 // In presence of clause 'collapse' with number of loops, it will 5976 // define the nested loops number. 5977 unsigned NestedLoopCount = 5978 CheckOpenMPLoop(OMPD_distribute, getCollapseNumberExpr(Clauses), 5979 nullptr /*ordered not a clause on distribute*/, AStmt, 5980 *this, *DSAStack, VarsWithImplicitDSA, B); 5981 if (NestedLoopCount == 0) 5982 return StmtError(); 5983 5984 assert((CurContext->isDependentContext() || B.builtAll()) && 5985 "omp for loop exprs were not built"); 5986 5987 getCurFunction()->setHasBranchProtectedScope(); 5988 return OMPDistributeDirective::Create(Context, StartLoc, EndLoc, 5989 NestedLoopCount, Clauses, AStmt, B); 5990 } 5991 5992 StmtResult Sema::ActOnOpenMPDistributeParallelForDirective( 5993 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, 5994 SourceLocation EndLoc, 5995 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) { 5996 if (!AStmt) 5997 return StmtError(); 5998 5999 CapturedStmt *CS = cast<CapturedStmt>(AStmt); 6000 // 1.2.2 OpenMP Language Terminology 6001 // Structured block - An executable statement with a single entry at the 6002 // top and a single exit at the bottom. 6003 // The point of exit cannot be a branch out of the structured block. 6004 // longjmp() and throw() must not violate the entry/exit criteria. 6005 CS->getCapturedDecl()->setNothrow(); 6006 6007 OMPLoopDirective::HelperExprs B; 6008 // In presence of clause 'collapse' with number of loops, it will 6009 // define the nested loops number. 6010 unsigned NestedLoopCount = CheckOpenMPLoop( 6011 OMPD_distribute_parallel_for, getCollapseNumberExpr(Clauses), 6012 nullptr /*ordered not a clause on distribute*/, AStmt, *this, *DSAStack, 6013 VarsWithImplicitDSA, B); 6014 if (NestedLoopCount == 0) 6015 return StmtError(); 6016 6017 assert((CurContext->isDependentContext() || B.builtAll()) && 6018 "omp for loop exprs were not built"); 6019 6020 getCurFunction()->setHasBranchProtectedScope(); 6021 return OMPDistributeParallelForDirective::Create( 6022 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B); 6023 } 6024 6025 StmtResult Sema::ActOnOpenMPDistributeParallelForSimdDirective( 6026 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, 6027 SourceLocation EndLoc, 6028 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) { 6029 if (!AStmt) 6030 return StmtError(); 6031 6032 CapturedStmt *CS = cast<CapturedStmt>(AStmt); 6033 // 1.2.2 OpenMP Language Terminology 6034 // Structured block - An executable statement with a single entry at the 6035 // top and a single exit at the bottom. 6036 // The point of exit cannot be a branch out of the structured block. 6037 // longjmp() and throw() must not violate the entry/exit criteria. 6038 CS->getCapturedDecl()->setNothrow(); 6039 6040 OMPLoopDirective::HelperExprs B; 6041 // In presence of clause 'collapse' with number of loops, it will 6042 // define the nested loops number. 6043 unsigned NestedLoopCount = CheckOpenMPLoop( 6044 OMPD_distribute_parallel_for_simd, getCollapseNumberExpr(Clauses), 6045 nullptr /*ordered not a clause on distribute*/, AStmt, *this, *DSAStack, 6046 VarsWithImplicitDSA, B); 6047 if (NestedLoopCount == 0) 6048 return StmtError(); 6049 6050 assert((CurContext->isDependentContext() || B.builtAll()) && 6051 "omp for loop exprs were not built"); 6052 6053 if (checkSimdlenSafelenSpecified(*this, Clauses)) 6054 return StmtError(); 6055 6056 getCurFunction()->setHasBranchProtectedScope(); 6057 return OMPDistributeParallelForSimdDirective::Create( 6058 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B); 6059 } 6060 6061 StmtResult Sema::ActOnOpenMPDistributeSimdDirective( 6062 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, 6063 SourceLocation EndLoc, 6064 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) { 6065 if (!AStmt) 6066 return StmtError(); 6067 6068 CapturedStmt *CS = cast<CapturedStmt>(AStmt); 6069 // 1.2.2 OpenMP Language Terminology 6070 // Structured block - An executable statement with a single entry at the 6071 // top and a single exit at the bottom. 6072 // The point of exit cannot be a branch out of the structured block. 6073 // longjmp() and throw() must not violate the entry/exit criteria. 6074 CS->getCapturedDecl()->setNothrow(); 6075 6076 OMPLoopDirective::HelperExprs B; 6077 // In presence of clause 'collapse' with number of loops, it will 6078 // define the nested loops number. 6079 unsigned NestedLoopCount = 6080 CheckOpenMPLoop(OMPD_distribute_simd, getCollapseNumberExpr(Clauses), 6081 nullptr /*ordered not a clause on distribute*/, AStmt, 6082 *this, *DSAStack, VarsWithImplicitDSA, B); 6083 if (NestedLoopCount == 0) 6084 return StmtError(); 6085 6086 assert((CurContext->isDependentContext() || B.builtAll()) && 6087 "omp for loop exprs were not built"); 6088 6089 if (checkSimdlenSafelenSpecified(*this, Clauses)) 6090 return StmtError(); 6091 6092 getCurFunction()->setHasBranchProtectedScope(); 6093 return OMPDistributeSimdDirective::Create(Context, StartLoc, EndLoc, 6094 NestedLoopCount, Clauses, AStmt, B); 6095 } 6096 6097 StmtResult Sema::ActOnOpenMPTargetParallelForSimdDirective( 6098 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, 6099 SourceLocation EndLoc, 6100 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) { 6101 if (!AStmt) 6102 return StmtError(); 6103 6104 CapturedStmt *CS = cast<CapturedStmt>(AStmt); 6105 // 1.2.2 OpenMP Language Terminology 6106 // Structured block - An executable statement with a single entry at the 6107 // top and a single exit at the bottom. 6108 // The point of exit cannot be a branch out of the structured block. 6109 // longjmp() and throw() must not violate the entry/exit criteria. 6110 CS->getCapturedDecl()->setNothrow(); 6111 6112 OMPLoopDirective::HelperExprs B; 6113 // In presence of clause 'collapse' or 'ordered' with number of loops, it will 6114 // define the nested loops number. 6115 unsigned NestedLoopCount = CheckOpenMPLoop( 6116 OMPD_target_parallel_for_simd, getCollapseNumberExpr(Clauses), 6117 getOrderedNumberExpr(Clauses), AStmt, *this, *DSAStack, 6118 VarsWithImplicitDSA, B); 6119 if (NestedLoopCount == 0) 6120 return StmtError(); 6121 6122 assert((CurContext->isDependentContext() || B.builtAll()) && 6123 "omp target parallel for simd loop exprs were not built"); 6124 6125 if (!CurContext->isDependentContext()) { 6126 // Finalize the clauses that need pre-built expressions for CodeGen. 6127 for (auto C : Clauses) { 6128 if (auto *LC = dyn_cast<OMPLinearClause>(C)) 6129 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef), 6130 B.NumIterations, *this, CurScope, 6131 DSAStack)) 6132 return StmtError(); 6133 } 6134 } 6135 if (checkSimdlenSafelenSpecified(*this, Clauses)) 6136 return StmtError(); 6137 6138 getCurFunction()->setHasBranchProtectedScope(); 6139 return OMPTargetParallelForSimdDirective::Create( 6140 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B); 6141 } 6142 6143 StmtResult Sema::ActOnOpenMPTargetSimdDirective( 6144 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, 6145 SourceLocation EndLoc, 6146 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) { 6147 if (!AStmt) 6148 return StmtError(); 6149 6150 CapturedStmt *CS = cast<CapturedStmt>(AStmt); 6151 // 1.2.2 OpenMP Language Terminology 6152 // Structured block - An executable statement with a single entry at the 6153 // top and a single exit at the bottom. 6154 // The point of exit cannot be a branch out of the structured block. 6155 // longjmp() and throw() must not violate the entry/exit criteria. 6156 CS->getCapturedDecl()->setNothrow(); 6157 6158 OMPLoopDirective::HelperExprs B; 6159 // In presence of clause 'collapse' with number of loops, it will define the 6160 // nested loops number. 6161 unsigned NestedLoopCount = 6162 CheckOpenMPLoop(OMPD_target_simd, getCollapseNumberExpr(Clauses), 6163 getOrderedNumberExpr(Clauses), AStmt, *this, *DSAStack, 6164 VarsWithImplicitDSA, B); 6165 if (NestedLoopCount == 0) 6166 return StmtError(); 6167 6168 assert((CurContext->isDependentContext() || B.builtAll()) && 6169 "omp target simd loop exprs were not built"); 6170 6171 if (!CurContext->isDependentContext()) { 6172 // Finalize the clauses that need pre-built expressions for CodeGen. 6173 for (auto C : Clauses) { 6174 if (auto *LC = dyn_cast<OMPLinearClause>(C)) 6175 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef), 6176 B.NumIterations, *this, CurScope, 6177 DSAStack)) 6178 return StmtError(); 6179 } 6180 } 6181 6182 if (checkSimdlenSafelenSpecified(*this, Clauses)) 6183 return StmtError(); 6184 6185 getCurFunction()->setHasBranchProtectedScope(); 6186 return OMPTargetSimdDirective::Create(Context, StartLoc, EndLoc, 6187 NestedLoopCount, Clauses, AStmt, B); 6188 } 6189 6190 StmtResult Sema::ActOnOpenMPTeamsDistributeDirective( 6191 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, 6192 SourceLocation EndLoc, 6193 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) { 6194 if (!AStmt) 6195 return StmtError(); 6196 6197 CapturedStmt *CS = cast<CapturedStmt>(AStmt); 6198 // 1.2.2 OpenMP Language Terminology 6199 // Structured block - An executable statement with a single entry at the 6200 // top and a single exit at the bottom. 6201 // The point of exit cannot be a branch out of the structured block. 6202 // longjmp() and throw() must not violate the entry/exit criteria. 6203 CS->getCapturedDecl()->setNothrow(); 6204 6205 OMPLoopDirective::HelperExprs B; 6206 // In presence of clause 'collapse' with number of loops, it will 6207 // define the nested loops number. 6208 unsigned NestedLoopCount = 6209 CheckOpenMPLoop(OMPD_teams_distribute, getCollapseNumberExpr(Clauses), 6210 nullptr /*ordered not a clause on distribute*/, AStmt, 6211 *this, *DSAStack, VarsWithImplicitDSA, B); 6212 if (NestedLoopCount == 0) 6213 return StmtError(); 6214 6215 assert((CurContext->isDependentContext() || B.builtAll()) && 6216 "omp teams distribute loop exprs were not built"); 6217 6218 getCurFunction()->setHasBranchProtectedScope(); 6219 return OMPTeamsDistributeDirective::Create( 6220 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B); 6221 } 6222 6223 StmtResult Sema::ActOnOpenMPTeamsDistributeSimdDirective( 6224 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, 6225 SourceLocation EndLoc, 6226 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) { 6227 if (!AStmt) 6228 return StmtError(); 6229 6230 CapturedStmt *CS = cast<CapturedStmt>(AStmt); 6231 // 1.2.2 OpenMP Language Terminology 6232 // Structured block - An executable statement with a single entry at the 6233 // top and a single exit at the bottom. 6234 // The point of exit cannot be a branch out of the structured block. 6235 // longjmp() and throw() must not violate the entry/exit criteria. 6236 CS->getCapturedDecl()->setNothrow(); 6237 6238 OMPLoopDirective::HelperExprs B; 6239 // In presence of clause 'collapse' with number of loops, it will 6240 // define the nested loops number. 6241 unsigned NestedLoopCount = CheckOpenMPLoop( 6242 OMPD_teams_distribute_simd, getCollapseNumberExpr(Clauses), 6243 nullptr /*ordered not a clause on distribute*/, AStmt, *this, *DSAStack, 6244 VarsWithImplicitDSA, B); 6245 6246 if (NestedLoopCount == 0) 6247 return StmtError(); 6248 6249 assert((CurContext->isDependentContext() || B.builtAll()) && 6250 "omp teams distribute simd loop exprs were not built"); 6251 6252 if (!CurContext->isDependentContext()) { 6253 // Finalize the clauses that need pre-built expressions for CodeGen. 6254 for (auto C : Clauses) { 6255 if (auto *LC = dyn_cast<OMPLinearClause>(C)) 6256 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef), 6257 B.NumIterations, *this, CurScope, 6258 DSAStack)) 6259 return StmtError(); 6260 } 6261 } 6262 6263 if (checkSimdlenSafelenSpecified(*this, Clauses)) 6264 return StmtError(); 6265 6266 getCurFunction()->setHasBranchProtectedScope(); 6267 return OMPTeamsDistributeSimdDirective::Create( 6268 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B); 6269 } 6270 6271 StmtResult Sema::ActOnOpenMPTeamsDistributeParallelForSimdDirective( 6272 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, 6273 SourceLocation EndLoc, 6274 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) { 6275 if (!AStmt) 6276 return StmtError(); 6277 6278 CapturedStmt *CS = cast<CapturedStmt>(AStmt); 6279 // 1.2.2 OpenMP Language Terminology 6280 // Structured block - An executable statement with a single entry at the 6281 // top and a single exit at the bottom. 6282 // The point of exit cannot be a branch out of the structured block. 6283 // longjmp() and throw() must not violate the entry/exit criteria. 6284 CS->getCapturedDecl()->setNothrow(); 6285 6286 OMPLoopDirective::HelperExprs B; 6287 // In presence of clause 'collapse' with number of loops, it will 6288 // define the nested loops number. 6289 auto NestedLoopCount = CheckOpenMPLoop( 6290 OMPD_teams_distribute_parallel_for_simd, getCollapseNumberExpr(Clauses), 6291 nullptr /*ordered not a clause on distribute*/, AStmt, *this, *DSAStack, 6292 VarsWithImplicitDSA, B); 6293 6294 if (NestedLoopCount == 0) 6295 return StmtError(); 6296 6297 assert((CurContext->isDependentContext() || B.builtAll()) && 6298 "omp for loop exprs were not built"); 6299 6300 if (!CurContext->isDependentContext()) { 6301 // Finalize the clauses that need pre-built expressions for CodeGen. 6302 for (auto C : Clauses) { 6303 if (auto *LC = dyn_cast<OMPLinearClause>(C)) 6304 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef), 6305 B.NumIterations, *this, CurScope, 6306 DSAStack)) 6307 return StmtError(); 6308 } 6309 } 6310 6311 if (checkSimdlenSafelenSpecified(*this, Clauses)) 6312 return StmtError(); 6313 6314 getCurFunction()->setHasBranchProtectedScope(); 6315 return OMPTeamsDistributeParallelForSimdDirective::Create( 6316 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B); 6317 } 6318 6319 StmtResult Sema::ActOnOpenMPTeamsDistributeParallelForDirective( 6320 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, 6321 SourceLocation EndLoc, 6322 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) { 6323 if (!AStmt) 6324 return StmtError(); 6325 6326 CapturedStmt *CS = cast<CapturedStmt>(AStmt); 6327 // 1.2.2 OpenMP Language Terminology 6328 // Structured block - An executable statement with a single entry at the 6329 // top and a single exit at the bottom. 6330 // The point of exit cannot be a branch out of the structured block. 6331 // longjmp() and throw() must not violate the entry/exit criteria. 6332 CS->getCapturedDecl()->setNothrow(); 6333 6334 OMPLoopDirective::HelperExprs B; 6335 // In presence of clause 'collapse' with number of loops, it will 6336 // define the nested loops number. 6337 unsigned NestedLoopCount = CheckOpenMPLoop( 6338 OMPD_teams_distribute_parallel_for, getCollapseNumberExpr(Clauses), 6339 nullptr /*ordered not a clause on distribute*/, AStmt, *this, *DSAStack, 6340 VarsWithImplicitDSA, B); 6341 6342 if (NestedLoopCount == 0) 6343 return StmtError(); 6344 6345 assert((CurContext->isDependentContext() || B.builtAll()) && 6346 "omp for loop exprs were not built"); 6347 6348 if (!CurContext->isDependentContext()) { 6349 // Finalize the clauses that need pre-built expressions for CodeGen. 6350 for (auto C : Clauses) { 6351 if (auto *LC = dyn_cast<OMPLinearClause>(C)) 6352 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef), 6353 B.NumIterations, *this, CurScope, 6354 DSAStack)) 6355 return StmtError(); 6356 } 6357 } 6358 6359 getCurFunction()->setHasBranchProtectedScope(); 6360 return OMPTeamsDistributeParallelForDirective::Create( 6361 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B); 6362 } 6363 6364 StmtResult Sema::ActOnOpenMPTargetTeamsDirective(ArrayRef<OMPClause *> Clauses, 6365 Stmt *AStmt, 6366 SourceLocation StartLoc, 6367 SourceLocation EndLoc) { 6368 if (!AStmt) 6369 return StmtError(); 6370 6371 CapturedStmt *CS = cast<CapturedStmt>(AStmt); 6372 // 1.2.2 OpenMP Language Terminology 6373 // Structured block - An executable statement with a single entry at the 6374 // top and a single exit at the bottom. 6375 // The point of exit cannot be a branch out of the structured block. 6376 // longjmp() and throw() must not violate the entry/exit criteria. 6377 CS->getCapturedDecl()->setNothrow(); 6378 6379 getCurFunction()->setHasBranchProtectedScope(); 6380 6381 return OMPTargetTeamsDirective::Create(Context, StartLoc, EndLoc, Clauses, 6382 AStmt); 6383 } 6384 6385 StmtResult Sema::ActOnOpenMPTargetTeamsDistributeDirective( 6386 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, 6387 SourceLocation EndLoc, 6388 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) { 6389 if (!AStmt) 6390 return StmtError(); 6391 6392 CapturedStmt *CS = cast<CapturedStmt>(AStmt); 6393 // 1.2.2 OpenMP Language Terminology 6394 // Structured block - An executable statement with a single entry at the 6395 // top and a single exit at the bottom. 6396 // The point of exit cannot be a branch out of the structured block. 6397 // longjmp() and throw() must not violate the entry/exit criteria. 6398 CS->getCapturedDecl()->setNothrow(); 6399 6400 OMPLoopDirective::HelperExprs B; 6401 // In presence of clause 'collapse' with number of loops, it will 6402 // define the nested loops number. 6403 auto NestedLoopCount = CheckOpenMPLoop( 6404 OMPD_target_teams_distribute, 6405 getCollapseNumberExpr(Clauses), 6406 nullptr /*ordered not a clause on distribute*/, AStmt, *this, *DSAStack, 6407 VarsWithImplicitDSA, B); 6408 if (NestedLoopCount == 0) 6409 return StmtError(); 6410 6411 assert((CurContext->isDependentContext() || B.builtAll()) && 6412 "omp target teams distribute loop exprs were not built"); 6413 6414 getCurFunction()->setHasBranchProtectedScope(); 6415 return OMPTargetTeamsDistributeDirective::Create( 6416 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B); 6417 } 6418 6419 StmtResult Sema::ActOnOpenMPTargetTeamsDistributeParallelForDirective( 6420 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, 6421 SourceLocation EndLoc, 6422 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) { 6423 if (!AStmt) 6424 return StmtError(); 6425 6426 CapturedStmt *CS = cast<CapturedStmt>(AStmt); 6427 // 1.2.2 OpenMP Language Terminology 6428 // Structured block - An executable statement with a single entry at the 6429 // top and a single exit at the bottom. 6430 // The point of exit cannot be a branch out of the structured block. 6431 // longjmp() and throw() must not violate the entry/exit criteria. 6432 CS->getCapturedDecl()->setNothrow(); 6433 6434 OMPLoopDirective::HelperExprs B; 6435 // In presence of clause 'collapse' with number of loops, it will 6436 // define the nested loops number. 6437 auto NestedLoopCount = CheckOpenMPLoop( 6438 OMPD_target_teams_distribute_parallel_for, 6439 getCollapseNumberExpr(Clauses), 6440 nullptr /*ordered not a clause on distribute*/, AStmt, *this, *DSAStack, 6441 VarsWithImplicitDSA, B); 6442 if (NestedLoopCount == 0) 6443 return StmtError(); 6444 6445 assert((CurContext->isDependentContext() || B.builtAll()) && 6446 "omp target teams distribute parallel for loop exprs were not built"); 6447 6448 if (!CurContext->isDependentContext()) { 6449 // Finalize the clauses that need pre-built expressions for CodeGen. 6450 for (auto C : Clauses) { 6451 if (auto *LC = dyn_cast<OMPLinearClause>(C)) 6452 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef), 6453 B.NumIterations, *this, CurScope, 6454 DSAStack)) 6455 return StmtError(); 6456 } 6457 } 6458 6459 getCurFunction()->setHasBranchProtectedScope(); 6460 return OMPTargetTeamsDistributeParallelForDirective::Create( 6461 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B); 6462 } 6463 6464 StmtResult Sema::ActOnOpenMPTargetTeamsDistributeParallelForSimdDirective( 6465 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, 6466 SourceLocation EndLoc, 6467 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) { 6468 if (!AStmt) 6469 return StmtError(); 6470 6471 CapturedStmt *CS = cast<CapturedStmt>(AStmt); 6472 // 1.2.2 OpenMP Language Terminology 6473 // Structured block - An executable statement with a single entry at the 6474 // top and a single exit at the bottom. 6475 // The point of exit cannot be a branch out of the structured block. 6476 // longjmp() and throw() must not violate the entry/exit criteria. 6477 CS->getCapturedDecl()->setNothrow(); 6478 6479 OMPLoopDirective::HelperExprs B; 6480 // In presence of clause 'collapse' with number of loops, it will 6481 // define the nested loops number. 6482 auto NestedLoopCount = CheckOpenMPLoop( 6483 OMPD_target_teams_distribute_parallel_for_simd, 6484 getCollapseNumberExpr(Clauses), 6485 nullptr /*ordered not a clause on distribute*/, AStmt, *this, *DSAStack, 6486 VarsWithImplicitDSA, B); 6487 if (NestedLoopCount == 0) 6488 return StmtError(); 6489 6490 assert((CurContext->isDependentContext() || B.builtAll()) && 6491 "omp target teams distribute parallel for simd loop exprs were not " 6492 "built"); 6493 6494 if (!CurContext->isDependentContext()) { 6495 // Finalize the clauses that need pre-built expressions for CodeGen. 6496 for (auto C : Clauses) { 6497 if (auto *LC = dyn_cast<OMPLinearClause>(C)) 6498 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef), 6499 B.NumIterations, *this, CurScope, 6500 DSAStack)) 6501 return StmtError(); 6502 } 6503 } 6504 6505 getCurFunction()->setHasBranchProtectedScope(); 6506 return OMPTargetTeamsDistributeParallelForSimdDirective::Create( 6507 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B); 6508 } 6509 6510 StmtResult Sema::ActOnOpenMPTargetTeamsDistributeSimdDirective( 6511 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, 6512 SourceLocation EndLoc, 6513 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) { 6514 if (!AStmt) 6515 return StmtError(); 6516 6517 auto *CS = cast<CapturedStmt>(AStmt); 6518 // 1.2.2 OpenMP Language Terminology 6519 // Structured block - An executable statement with a single entry at the 6520 // top and a single exit at the bottom. 6521 // The point of exit cannot be a branch out of the structured block. 6522 // longjmp() and throw() must not violate the entry/exit criteria. 6523 CS->getCapturedDecl()->setNothrow(); 6524 6525 OMPLoopDirective::HelperExprs B; 6526 // In presence of clause 'collapse' with number of loops, it will 6527 // define the nested loops number. 6528 auto NestedLoopCount = CheckOpenMPLoop( 6529 OMPD_target_teams_distribute_simd, getCollapseNumberExpr(Clauses), 6530 nullptr /*ordered not a clause on distribute*/, AStmt, *this, *DSAStack, 6531 VarsWithImplicitDSA, B); 6532 if (NestedLoopCount == 0) 6533 return StmtError(); 6534 6535 assert((CurContext->isDependentContext() || B.builtAll()) && 6536 "omp target teams distribute simd loop exprs were not built"); 6537 6538 getCurFunction()->setHasBranchProtectedScope(); 6539 return OMPTargetTeamsDistributeSimdDirective::Create( 6540 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B); 6541 } 6542 6543 OMPClause *Sema::ActOnOpenMPSingleExprClause(OpenMPClauseKind Kind, Expr *Expr, 6544 SourceLocation StartLoc, 6545 SourceLocation LParenLoc, 6546 SourceLocation EndLoc) { 6547 OMPClause *Res = nullptr; 6548 switch (Kind) { 6549 case OMPC_final: 6550 Res = ActOnOpenMPFinalClause(Expr, StartLoc, LParenLoc, EndLoc); 6551 break; 6552 case OMPC_num_threads: 6553 Res = ActOnOpenMPNumThreadsClause(Expr, StartLoc, LParenLoc, EndLoc); 6554 break; 6555 case OMPC_safelen: 6556 Res = ActOnOpenMPSafelenClause(Expr, StartLoc, LParenLoc, EndLoc); 6557 break; 6558 case OMPC_simdlen: 6559 Res = ActOnOpenMPSimdlenClause(Expr, StartLoc, LParenLoc, EndLoc); 6560 break; 6561 case OMPC_collapse: 6562 Res = ActOnOpenMPCollapseClause(Expr, StartLoc, LParenLoc, EndLoc); 6563 break; 6564 case OMPC_ordered: 6565 Res = ActOnOpenMPOrderedClause(StartLoc, EndLoc, LParenLoc, Expr); 6566 break; 6567 case OMPC_device: 6568 Res = ActOnOpenMPDeviceClause(Expr, StartLoc, LParenLoc, EndLoc); 6569 break; 6570 case OMPC_num_teams: 6571 Res = ActOnOpenMPNumTeamsClause(Expr, StartLoc, LParenLoc, EndLoc); 6572 break; 6573 case OMPC_thread_limit: 6574 Res = ActOnOpenMPThreadLimitClause(Expr, StartLoc, LParenLoc, EndLoc); 6575 break; 6576 case OMPC_priority: 6577 Res = ActOnOpenMPPriorityClause(Expr, StartLoc, LParenLoc, EndLoc); 6578 break; 6579 case OMPC_grainsize: 6580 Res = ActOnOpenMPGrainsizeClause(Expr, StartLoc, LParenLoc, EndLoc); 6581 break; 6582 case OMPC_num_tasks: 6583 Res = ActOnOpenMPNumTasksClause(Expr, StartLoc, LParenLoc, EndLoc); 6584 break; 6585 case OMPC_hint: 6586 Res = ActOnOpenMPHintClause(Expr, StartLoc, LParenLoc, EndLoc); 6587 break; 6588 case OMPC_if: 6589 case OMPC_default: 6590 case OMPC_proc_bind: 6591 case OMPC_schedule: 6592 case OMPC_private: 6593 case OMPC_firstprivate: 6594 case OMPC_lastprivate: 6595 case OMPC_shared: 6596 case OMPC_reduction: 6597 case OMPC_linear: 6598 case OMPC_aligned: 6599 case OMPC_copyin: 6600 case OMPC_copyprivate: 6601 case OMPC_nowait: 6602 case OMPC_untied: 6603 case OMPC_mergeable: 6604 case OMPC_threadprivate: 6605 case OMPC_flush: 6606 case OMPC_read: 6607 case OMPC_write: 6608 case OMPC_update: 6609 case OMPC_capture: 6610 case OMPC_seq_cst: 6611 case OMPC_depend: 6612 case OMPC_threads: 6613 case OMPC_simd: 6614 case OMPC_map: 6615 case OMPC_nogroup: 6616 case OMPC_dist_schedule: 6617 case OMPC_defaultmap: 6618 case OMPC_unknown: 6619 case OMPC_uniform: 6620 case OMPC_to: 6621 case OMPC_from: 6622 case OMPC_use_device_ptr: 6623 case OMPC_is_device_ptr: 6624 llvm_unreachable("Clause is not allowed."); 6625 } 6626 return Res; 6627 } 6628 6629 // An OpenMP directive such as 'target parallel' has two captured regions: 6630 // for the 'target' and 'parallel' respectively. This function returns 6631 // the region in which to capture expressions associated with a clause. 6632 // A return value of OMPD_unknown signifies that the expression should not 6633 // be captured. 6634 static OpenMPDirectiveKind 6635 getOpenMPCaptureRegionForClause(OpenMPDirectiveKind DKind, 6636 OpenMPClauseKind CKind, 6637 OpenMPDirectiveKind NameModifier) { 6638 OpenMPDirectiveKind CaptureRegion = OMPD_unknown; 6639 6640 switch (CKind) { 6641 case OMPC_if: 6642 switch (DKind) { 6643 case OMPD_target_parallel: 6644 // If this clause applies to the nested 'parallel' region, capture within 6645 // the 'target' region, otherwise do not capture. 6646 if (NameModifier == OMPD_unknown || NameModifier == OMPD_parallel) 6647 CaptureRegion = OMPD_target; 6648 break; 6649 case OMPD_cancel: 6650 case OMPD_parallel: 6651 case OMPD_parallel_sections: 6652 case OMPD_parallel_for: 6653 case OMPD_parallel_for_simd: 6654 case OMPD_target: 6655 case OMPD_target_simd: 6656 case OMPD_target_parallel_for: 6657 case OMPD_target_parallel_for_simd: 6658 case OMPD_target_teams: 6659 case OMPD_target_teams_distribute: 6660 case OMPD_target_teams_distribute_simd: 6661 case OMPD_target_teams_distribute_parallel_for: 6662 case OMPD_target_teams_distribute_parallel_for_simd: 6663 case OMPD_teams_distribute_parallel_for: 6664 case OMPD_teams_distribute_parallel_for_simd: 6665 case OMPD_distribute_parallel_for: 6666 case OMPD_distribute_parallel_for_simd: 6667 case OMPD_task: 6668 case OMPD_taskloop: 6669 case OMPD_taskloop_simd: 6670 case OMPD_target_data: 6671 case OMPD_target_enter_data: 6672 case OMPD_target_exit_data: 6673 case OMPD_target_update: 6674 // Do not capture if-clause expressions. 6675 break; 6676 case OMPD_threadprivate: 6677 case OMPD_taskyield: 6678 case OMPD_barrier: 6679 case OMPD_taskwait: 6680 case OMPD_cancellation_point: 6681 case OMPD_flush: 6682 case OMPD_declare_reduction: 6683 case OMPD_declare_simd: 6684 case OMPD_declare_target: 6685 case OMPD_end_declare_target: 6686 case OMPD_teams: 6687 case OMPD_simd: 6688 case OMPD_for: 6689 case OMPD_for_simd: 6690 case OMPD_sections: 6691 case OMPD_section: 6692 case OMPD_single: 6693 case OMPD_master: 6694 case OMPD_critical: 6695 case OMPD_taskgroup: 6696 case OMPD_distribute: 6697 case OMPD_ordered: 6698 case OMPD_atomic: 6699 case OMPD_distribute_simd: 6700 case OMPD_teams_distribute: 6701 case OMPD_teams_distribute_simd: 6702 llvm_unreachable("Unexpected OpenMP directive with if-clause"); 6703 case OMPD_unknown: 6704 llvm_unreachable("Unknown OpenMP directive"); 6705 } 6706 break; 6707 case OMPC_schedule: 6708 case OMPC_dist_schedule: 6709 case OMPC_firstprivate: 6710 case OMPC_lastprivate: 6711 case OMPC_reduction: 6712 case OMPC_linear: 6713 case OMPC_default: 6714 case OMPC_proc_bind: 6715 case OMPC_final: 6716 case OMPC_num_threads: 6717 case OMPC_safelen: 6718 case OMPC_simdlen: 6719 case OMPC_collapse: 6720 case OMPC_private: 6721 case OMPC_shared: 6722 case OMPC_aligned: 6723 case OMPC_copyin: 6724 case OMPC_copyprivate: 6725 case OMPC_ordered: 6726 case OMPC_nowait: 6727 case OMPC_untied: 6728 case OMPC_mergeable: 6729 case OMPC_threadprivate: 6730 case OMPC_flush: 6731 case OMPC_read: 6732 case OMPC_write: 6733 case OMPC_update: 6734 case OMPC_capture: 6735 case OMPC_seq_cst: 6736 case OMPC_depend: 6737 case OMPC_device: 6738 case OMPC_threads: 6739 case OMPC_simd: 6740 case OMPC_map: 6741 case OMPC_num_teams: 6742 case OMPC_thread_limit: 6743 case OMPC_priority: 6744 case OMPC_grainsize: 6745 case OMPC_nogroup: 6746 case OMPC_num_tasks: 6747 case OMPC_hint: 6748 case OMPC_defaultmap: 6749 case OMPC_unknown: 6750 case OMPC_uniform: 6751 case OMPC_to: 6752 case OMPC_from: 6753 case OMPC_use_device_ptr: 6754 case OMPC_is_device_ptr: 6755 llvm_unreachable("Unexpected OpenMP clause."); 6756 } 6757 return CaptureRegion; 6758 } 6759 6760 OMPClause *Sema::ActOnOpenMPIfClause(OpenMPDirectiveKind NameModifier, 6761 Expr *Condition, SourceLocation StartLoc, 6762 SourceLocation LParenLoc, 6763 SourceLocation NameModifierLoc, 6764 SourceLocation ColonLoc, 6765 SourceLocation EndLoc) { 6766 Expr *ValExpr = Condition; 6767 Stmt *HelperValStmt = nullptr; 6768 OpenMPDirectiveKind CaptureRegion = OMPD_unknown; 6769 if (!Condition->isValueDependent() && !Condition->isTypeDependent() && 6770 !Condition->isInstantiationDependent() && 6771 !Condition->containsUnexpandedParameterPack()) { 6772 ExprResult Val = CheckBooleanCondition(StartLoc, Condition); 6773 if (Val.isInvalid()) 6774 return nullptr; 6775 6776 ValExpr = MakeFullExpr(Val.get()).get(); 6777 6778 OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective(); 6779 CaptureRegion = 6780 getOpenMPCaptureRegionForClause(DKind, OMPC_if, NameModifier); 6781 if (CaptureRegion != OMPD_unknown) { 6782 llvm::MapVector<Expr *, DeclRefExpr *> Captures; 6783 ValExpr = tryBuildCapture(*this, ValExpr, Captures).get(); 6784 HelperValStmt = buildPreInits(Context, Captures); 6785 } 6786 } 6787 6788 return new (Context) 6789 OMPIfClause(NameModifier, ValExpr, HelperValStmt, CaptureRegion, StartLoc, 6790 LParenLoc, NameModifierLoc, ColonLoc, EndLoc); 6791 } 6792 6793 OMPClause *Sema::ActOnOpenMPFinalClause(Expr *Condition, 6794 SourceLocation StartLoc, 6795 SourceLocation LParenLoc, 6796 SourceLocation EndLoc) { 6797 Expr *ValExpr = Condition; 6798 if (!Condition->isValueDependent() && !Condition->isTypeDependent() && 6799 !Condition->isInstantiationDependent() && 6800 !Condition->containsUnexpandedParameterPack()) { 6801 ExprResult Val = CheckBooleanCondition(StartLoc, Condition); 6802 if (Val.isInvalid()) 6803 return nullptr; 6804 6805 ValExpr = MakeFullExpr(Val.get()).get(); 6806 } 6807 6808 return new (Context) OMPFinalClause(ValExpr, StartLoc, LParenLoc, EndLoc); 6809 } 6810 ExprResult Sema::PerformOpenMPImplicitIntegerConversion(SourceLocation Loc, 6811 Expr *Op) { 6812 if (!Op) 6813 return ExprError(); 6814 6815 class IntConvertDiagnoser : public ICEConvertDiagnoser { 6816 public: 6817 IntConvertDiagnoser() 6818 : ICEConvertDiagnoser(/*AllowScopedEnumerations*/ false, false, true) {} 6819 SemaDiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc, 6820 QualType T) override { 6821 return S.Diag(Loc, diag::err_omp_not_integral) << T; 6822 } 6823 SemaDiagnosticBuilder diagnoseIncomplete(Sema &S, SourceLocation Loc, 6824 QualType T) override { 6825 return S.Diag(Loc, diag::err_omp_incomplete_type) << T; 6826 } 6827 SemaDiagnosticBuilder diagnoseExplicitConv(Sema &S, SourceLocation Loc, 6828 QualType T, 6829 QualType ConvTy) override { 6830 return S.Diag(Loc, diag::err_omp_explicit_conversion) << T << ConvTy; 6831 } 6832 SemaDiagnosticBuilder noteExplicitConv(Sema &S, CXXConversionDecl *Conv, 6833 QualType ConvTy) override { 6834 return S.Diag(Conv->getLocation(), diag::note_omp_conversion_here) 6835 << ConvTy->isEnumeralType() << ConvTy; 6836 } 6837 SemaDiagnosticBuilder diagnoseAmbiguous(Sema &S, SourceLocation Loc, 6838 QualType T) override { 6839 return S.Diag(Loc, diag::err_omp_ambiguous_conversion) << T; 6840 } 6841 SemaDiagnosticBuilder noteAmbiguous(Sema &S, CXXConversionDecl *Conv, 6842 QualType ConvTy) override { 6843 return S.Diag(Conv->getLocation(), diag::note_omp_conversion_here) 6844 << ConvTy->isEnumeralType() << ConvTy; 6845 } 6846 SemaDiagnosticBuilder diagnoseConversion(Sema &, SourceLocation, QualType, 6847 QualType) override { 6848 llvm_unreachable("conversion functions are permitted"); 6849 } 6850 } ConvertDiagnoser; 6851 return PerformContextualImplicitConversion(Loc, Op, ConvertDiagnoser); 6852 } 6853 6854 static bool IsNonNegativeIntegerValue(Expr *&ValExpr, Sema &SemaRef, 6855 OpenMPClauseKind CKind, 6856 bool StrictlyPositive) { 6857 if (!ValExpr->isTypeDependent() && !ValExpr->isValueDependent() && 6858 !ValExpr->isInstantiationDependent()) { 6859 SourceLocation Loc = ValExpr->getExprLoc(); 6860 ExprResult Value = 6861 SemaRef.PerformOpenMPImplicitIntegerConversion(Loc, ValExpr); 6862 if (Value.isInvalid()) 6863 return false; 6864 6865 ValExpr = Value.get(); 6866 // The expression must evaluate to a non-negative integer value. 6867 llvm::APSInt Result; 6868 if (ValExpr->isIntegerConstantExpr(Result, SemaRef.Context) && 6869 Result.isSigned() && 6870 !((!StrictlyPositive && Result.isNonNegative()) || 6871 (StrictlyPositive && Result.isStrictlyPositive()))) { 6872 SemaRef.Diag(Loc, diag::err_omp_negative_expression_in_clause) 6873 << getOpenMPClauseName(CKind) << (StrictlyPositive ? 1 : 0) 6874 << ValExpr->getSourceRange(); 6875 return false; 6876 } 6877 } 6878 return true; 6879 } 6880 6881 OMPClause *Sema::ActOnOpenMPNumThreadsClause(Expr *NumThreads, 6882 SourceLocation StartLoc, 6883 SourceLocation LParenLoc, 6884 SourceLocation EndLoc) { 6885 Expr *ValExpr = NumThreads; 6886 6887 // OpenMP [2.5, Restrictions] 6888 // The num_threads expression must evaluate to a positive integer value. 6889 if (!IsNonNegativeIntegerValue(ValExpr, *this, OMPC_num_threads, 6890 /*StrictlyPositive=*/true)) 6891 return nullptr; 6892 6893 return new (Context) 6894 OMPNumThreadsClause(ValExpr, StartLoc, LParenLoc, EndLoc); 6895 } 6896 6897 ExprResult Sema::VerifyPositiveIntegerConstantInClause(Expr *E, 6898 OpenMPClauseKind CKind, 6899 bool StrictlyPositive) { 6900 if (!E) 6901 return ExprError(); 6902 if (E->isValueDependent() || E->isTypeDependent() || 6903 E->isInstantiationDependent() || E->containsUnexpandedParameterPack()) 6904 return E; 6905 llvm::APSInt Result; 6906 ExprResult ICE = VerifyIntegerConstantExpression(E, &Result); 6907 if (ICE.isInvalid()) 6908 return ExprError(); 6909 if ((StrictlyPositive && !Result.isStrictlyPositive()) || 6910 (!StrictlyPositive && !Result.isNonNegative())) { 6911 Diag(E->getExprLoc(), diag::err_omp_negative_expression_in_clause) 6912 << getOpenMPClauseName(CKind) << (StrictlyPositive ? 1 : 0) 6913 << E->getSourceRange(); 6914 return ExprError(); 6915 } 6916 if (CKind == OMPC_aligned && !Result.isPowerOf2()) { 6917 Diag(E->getExprLoc(), diag::warn_omp_alignment_not_power_of_two) 6918 << E->getSourceRange(); 6919 return ExprError(); 6920 } 6921 if (CKind == OMPC_collapse && DSAStack->getAssociatedLoops() == 1) 6922 DSAStack->setAssociatedLoops(Result.getExtValue()); 6923 else if (CKind == OMPC_ordered) 6924 DSAStack->setAssociatedLoops(Result.getExtValue()); 6925 return ICE; 6926 } 6927 6928 OMPClause *Sema::ActOnOpenMPSafelenClause(Expr *Len, SourceLocation StartLoc, 6929 SourceLocation LParenLoc, 6930 SourceLocation EndLoc) { 6931 // OpenMP [2.8.1, simd construct, Description] 6932 // The parameter of the safelen clause must be a constant 6933 // positive integer expression. 6934 ExprResult Safelen = VerifyPositiveIntegerConstantInClause(Len, OMPC_safelen); 6935 if (Safelen.isInvalid()) 6936 return nullptr; 6937 return new (Context) 6938 OMPSafelenClause(Safelen.get(), StartLoc, LParenLoc, EndLoc); 6939 } 6940 6941 OMPClause *Sema::ActOnOpenMPSimdlenClause(Expr *Len, SourceLocation StartLoc, 6942 SourceLocation LParenLoc, 6943 SourceLocation EndLoc) { 6944 // OpenMP [2.8.1, simd construct, Description] 6945 // The parameter of the simdlen clause must be a constant 6946 // positive integer expression. 6947 ExprResult Simdlen = VerifyPositiveIntegerConstantInClause(Len, OMPC_simdlen); 6948 if (Simdlen.isInvalid()) 6949 return nullptr; 6950 return new (Context) 6951 OMPSimdlenClause(Simdlen.get(), StartLoc, LParenLoc, EndLoc); 6952 } 6953 6954 OMPClause *Sema::ActOnOpenMPCollapseClause(Expr *NumForLoops, 6955 SourceLocation StartLoc, 6956 SourceLocation LParenLoc, 6957 SourceLocation EndLoc) { 6958 // OpenMP [2.7.1, loop construct, Description] 6959 // OpenMP [2.8.1, simd construct, Description] 6960 // OpenMP [2.9.6, distribute construct, Description] 6961 // The parameter of the collapse clause must be a constant 6962 // positive integer expression. 6963 ExprResult NumForLoopsResult = 6964 VerifyPositiveIntegerConstantInClause(NumForLoops, OMPC_collapse); 6965 if (NumForLoopsResult.isInvalid()) 6966 return nullptr; 6967 return new (Context) 6968 OMPCollapseClause(NumForLoopsResult.get(), StartLoc, LParenLoc, EndLoc); 6969 } 6970 6971 OMPClause *Sema::ActOnOpenMPOrderedClause(SourceLocation StartLoc, 6972 SourceLocation EndLoc, 6973 SourceLocation LParenLoc, 6974 Expr *NumForLoops) { 6975 // OpenMP [2.7.1, loop construct, Description] 6976 // OpenMP [2.8.1, simd construct, Description] 6977 // OpenMP [2.9.6, distribute construct, Description] 6978 // The parameter of the ordered clause must be a constant 6979 // positive integer expression if any. 6980 if (NumForLoops && LParenLoc.isValid()) { 6981 ExprResult NumForLoopsResult = 6982 VerifyPositiveIntegerConstantInClause(NumForLoops, OMPC_ordered); 6983 if (NumForLoopsResult.isInvalid()) 6984 return nullptr; 6985 NumForLoops = NumForLoopsResult.get(); 6986 } else 6987 NumForLoops = nullptr; 6988 DSAStack->setOrderedRegion(/*IsOrdered=*/true, NumForLoops); 6989 return new (Context) 6990 OMPOrderedClause(NumForLoops, StartLoc, LParenLoc, EndLoc); 6991 } 6992 6993 OMPClause *Sema::ActOnOpenMPSimpleClause( 6994 OpenMPClauseKind Kind, unsigned Argument, SourceLocation ArgumentLoc, 6995 SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc) { 6996 OMPClause *Res = nullptr; 6997 switch (Kind) { 6998 case OMPC_default: 6999 Res = 7000 ActOnOpenMPDefaultClause(static_cast<OpenMPDefaultClauseKind>(Argument), 7001 ArgumentLoc, StartLoc, LParenLoc, EndLoc); 7002 break; 7003 case OMPC_proc_bind: 7004 Res = ActOnOpenMPProcBindClause( 7005 static_cast<OpenMPProcBindClauseKind>(Argument), ArgumentLoc, StartLoc, 7006 LParenLoc, EndLoc); 7007 break; 7008 case OMPC_if: 7009 case OMPC_final: 7010 case OMPC_num_threads: 7011 case OMPC_safelen: 7012 case OMPC_simdlen: 7013 case OMPC_collapse: 7014 case OMPC_schedule: 7015 case OMPC_private: 7016 case OMPC_firstprivate: 7017 case OMPC_lastprivate: 7018 case OMPC_shared: 7019 case OMPC_reduction: 7020 case OMPC_linear: 7021 case OMPC_aligned: 7022 case OMPC_copyin: 7023 case OMPC_copyprivate: 7024 case OMPC_ordered: 7025 case OMPC_nowait: 7026 case OMPC_untied: 7027 case OMPC_mergeable: 7028 case OMPC_threadprivate: 7029 case OMPC_flush: 7030 case OMPC_read: 7031 case OMPC_write: 7032 case OMPC_update: 7033 case OMPC_capture: 7034 case OMPC_seq_cst: 7035 case OMPC_depend: 7036 case OMPC_device: 7037 case OMPC_threads: 7038 case OMPC_simd: 7039 case OMPC_map: 7040 case OMPC_num_teams: 7041 case OMPC_thread_limit: 7042 case OMPC_priority: 7043 case OMPC_grainsize: 7044 case OMPC_nogroup: 7045 case OMPC_num_tasks: 7046 case OMPC_hint: 7047 case OMPC_dist_schedule: 7048 case OMPC_defaultmap: 7049 case OMPC_unknown: 7050 case OMPC_uniform: 7051 case OMPC_to: 7052 case OMPC_from: 7053 case OMPC_use_device_ptr: 7054 case OMPC_is_device_ptr: 7055 llvm_unreachable("Clause is not allowed."); 7056 } 7057 return Res; 7058 } 7059 7060 static std::string 7061 getListOfPossibleValues(OpenMPClauseKind K, unsigned First, unsigned Last, 7062 ArrayRef<unsigned> Exclude = llvm::None) { 7063 std::string Values; 7064 unsigned Bound = Last >= 2 ? Last - 2 : 0; 7065 unsigned Skipped = Exclude.size(); 7066 auto S = Exclude.begin(), E = Exclude.end(); 7067 for (unsigned i = First; i < Last; ++i) { 7068 if (std::find(S, E, i) != E) { 7069 --Skipped; 7070 continue; 7071 } 7072 Values += "'"; 7073 Values += getOpenMPSimpleClauseTypeName(K, i); 7074 Values += "'"; 7075 if (i == Bound - Skipped) 7076 Values += " or "; 7077 else if (i != Bound + 1 - Skipped) 7078 Values += ", "; 7079 } 7080 return Values; 7081 } 7082 7083 OMPClause *Sema::ActOnOpenMPDefaultClause(OpenMPDefaultClauseKind Kind, 7084 SourceLocation KindKwLoc, 7085 SourceLocation StartLoc, 7086 SourceLocation LParenLoc, 7087 SourceLocation EndLoc) { 7088 if (Kind == OMPC_DEFAULT_unknown) { 7089 static_assert(OMPC_DEFAULT_unknown > 0, 7090 "OMPC_DEFAULT_unknown not greater than 0"); 7091 Diag(KindKwLoc, diag::err_omp_unexpected_clause_value) 7092 << getListOfPossibleValues(OMPC_default, /*First=*/0, 7093 /*Last=*/OMPC_DEFAULT_unknown) 7094 << getOpenMPClauseName(OMPC_default); 7095 return nullptr; 7096 } 7097 switch (Kind) { 7098 case OMPC_DEFAULT_none: 7099 DSAStack->setDefaultDSANone(KindKwLoc); 7100 break; 7101 case OMPC_DEFAULT_shared: 7102 DSAStack->setDefaultDSAShared(KindKwLoc); 7103 break; 7104 case OMPC_DEFAULT_unknown: 7105 llvm_unreachable("Clause kind is not allowed."); 7106 break; 7107 } 7108 return new (Context) 7109 OMPDefaultClause(Kind, KindKwLoc, StartLoc, LParenLoc, EndLoc); 7110 } 7111 7112 OMPClause *Sema::ActOnOpenMPProcBindClause(OpenMPProcBindClauseKind Kind, 7113 SourceLocation KindKwLoc, 7114 SourceLocation StartLoc, 7115 SourceLocation LParenLoc, 7116 SourceLocation EndLoc) { 7117 if (Kind == OMPC_PROC_BIND_unknown) { 7118 Diag(KindKwLoc, diag::err_omp_unexpected_clause_value) 7119 << getListOfPossibleValues(OMPC_proc_bind, /*First=*/0, 7120 /*Last=*/OMPC_PROC_BIND_unknown) 7121 << getOpenMPClauseName(OMPC_proc_bind); 7122 return nullptr; 7123 } 7124 return new (Context) 7125 OMPProcBindClause(Kind, KindKwLoc, StartLoc, LParenLoc, EndLoc); 7126 } 7127 7128 OMPClause *Sema::ActOnOpenMPSingleExprWithArgClause( 7129 OpenMPClauseKind Kind, ArrayRef<unsigned> Argument, Expr *Expr, 7130 SourceLocation StartLoc, SourceLocation LParenLoc, 7131 ArrayRef<SourceLocation> ArgumentLoc, SourceLocation DelimLoc, 7132 SourceLocation EndLoc) { 7133 OMPClause *Res = nullptr; 7134 switch (Kind) { 7135 case OMPC_schedule: 7136 enum { Modifier1, Modifier2, ScheduleKind, NumberOfElements }; 7137 assert(Argument.size() == NumberOfElements && 7138 ArgumentLoc.size() == NumberOfElements); 7139 Res = ActOnOpenMPScheduleClause( 7140 static_cast<OpenMPScheduleClauseModifier>(Argument[Modifier1]), 7141 static_cast<OpenMPScheduleClauseModifier>(Argument[Modifier2]), 7142 static_cast<OpenMPScheduleClauseKind>(Argument[ScheduleKind]), Expr, 7143 StartLoc, LParenLoc, ArgumentLoc[Modifier1], ArgumentLoc[Modifier2], 7144 ArgumentLoc[ScheduleKind], DelimLoc, EndLoc); 7145 break; 7146 case OMPC_if: 7147 assert(Argument.size() == 1 && ArgumentLoc.size() == 1); 7148 Res = ActOnOpenMPIfClause(static_cast<OpenMPDirectiveKind>(Argument.back()), 7149 Expr, StartLoc, LParenLoc, ArgumentLoc.back(), 7150 DelimLoc, EndLoc); 7151 break; 7152 case OMPC_dist_schedule: 7153 Res = ActOnOpenMPDistScheduleClause( 7154 static_cast<OpenMPDistScheduleClauseKind>(Argument.back()), Expr, 7155 StartLoc, LParenLoc, ArgumentLoc.back(), DelimLoc, EndLoc); 7156 break; 7157 case OMPC_defaultmap: 7158 enum { Modifier, DefaultmapKind }; 7159 Res = ActOnOpenMPDefaultmapClause( 7160 static_cast<OpenMPDefaultmapClauseModifier>(Argument[Modifier]), 7161 static_cast<OpenMPDefaultmapClauseKind>(Argument[DefaultmapKind]), 7162 StartLoc, LParenLoc, ArgumentLoc[Modifier], ArgumentLoc[DefaultmapKind], 7163 EndLoc); 7164 break; 7165 case OMPC_final: 7166 case OMPC_num_threads: 7167 case OMPC_safelen: 7168 case OMPC_simdlen: 7169 case OMPC_collapse: 7170 case OMPC_default: 7171 case OMPC_proc_bind: 7172 case OMPC_private: 7173 case OMPC_firstprivate: 7174 case OMPC_lastprivate: 7175 case OMPC_shared: 7176 case OMPC_reduction: 7177 case OMPC_linear: 7178 case OMPC_aligned: 7179 case OMPC_copyin: 7180 case OMPC_copyprivate: 7181 case OMPC_ordered: 7182 case OMPC_nowait: 7183 case OMPC_untied: 7184 case OMPC_mergeable: 7185 case OMPC_threadprivate: 7186 case OMPC_flush: 7187 case OMPC_read: 7188 case OMPC_write: 7189 case OMPC_update: 7190 case OMPC_capture: 7191 case OMPC_seq_cst: 7192 case OMPC_depend: 7193 case OMPC_device: 7194 case OMPC_threads: 7195 case OMPC_simd: 7196 case OMPC_map: 7197 case OMPC_num_teams: 7198 case OMPC_thread_limit: 7199 case OMPC_priority: 7200 case OMPC_grainsize: 7201 case OMPC_nogroup: 7202 case OMPC_num_tasks: 7203 case OMPC_hint: 7204 case OMPC_unknown: 7205 case OMPC_uniform: 7206 case OMPC_to: 7207 case OMPC_from: 7208 case OMPC_use_device_ptr: 7209 case OMPC_is_device_ptr: 7210 llvm_unreachable("Clause is not allowed."); 7211 } 7212 return Res; 7213 } 7214 7215 static bool checkScheduleModifiers(Sema &S, OpenMPScheduleClauseModifier M1, 7216 OpenMPScheduleClauseModifier M2, 7217 SourceLocation M1Loc, SourceLocation M2Loc) { 7218 if (M1 == OMPC_SCHEDULE_MODIFIER_unknown && M1Loc.isValid()) { 7219 SmallVector<unsigned, 2> Excluded; 7220 if (M2 != OMPC_SCHEDULE_MODIFIER_unknown) 7221 Excluded.push_back(M2); 7222 if (M2 == OMPC_SCHEDULE_MODIFIER_nonmonotonic) 7223 Excluded.push_back(OMPC_SCHEDULE_MODIFIER_monotonic); 7224 if (M2 == OMPC_SCHEDULE_MODIFIER_monotonic) 7225 Excluded.push_back(OMPC_SCHEDULE_MODIFIER_nonmonotonic); 7226 S.Diag(M1Loc, diag::err_omp_unexpected_clause_value) 7227 << getListOfPossibleValues(OMPC_schedule, 7228 /*First=*/OMPC_SCHEDULE_MODIFIER_unknown + 1, 7229 /*Last=*/OMPC_SCHEDULE_MODIFIER_last, 7230 Excluded) 7231 << getOpenMPClauseName(OMPC_schedule); 7232 return true; 7233 } 7234 return false; 7235 } 7236 7237 OMPClause *Sema::ActOnOpenMPScheduleClause( 7238 OpenMPScheduleClauseModifier M1, OpenMPScheduleClauseModifier M2, 7239 OpenMPScheduleClauseKind Kind, Expr *ChunkSize, SourceLocation StartLoc, 7240 SourceLocation LParenLoc, SourceLocation M1Loc, SourceLocation M2Loc, 7241 SourceLocation KindLoc, SourceLocation CommaLoc, SourceLocation EndLoc) { 7242 if (checkScheduleModifiers(*this, M1, M2, M1Loc, M2Loc) || 7243 checkScheduleModifiers(*this, M2, M1, M2Loc, M1Loc)) 7244 return nullptr; 7245 // OpenMP, 2.7.1, Loop Construct, Restrictions 7246 // Either the monotonic modifier or the nonmonotonic modifier can be specified 7247 // but not both. 7248 if ((M1 == M2 && M1 != OMPC_SCHEDULE_MODIFIER_unknown) || 7249 (M1 == OMPC_SCHEDULE_MODIFIER_monotonic && 7250 M2 == OMPC_SCHEDULE_MODIFIER_nonmonotonic) || 7251 (M1 == OMPC_SCHEDULE_MODIFIER_nonmonotonic && 7252 M2 == OMPC_SCHEDULE_MODIFIER_monotonic)) { 7253 Diag(M2Loc, diag::err_omp_unexpected_schedule_modifier) 7254 << getOpenMPSimpleClauseTypeName(OMPC_schedule, M2) 7255 << getOpenMPSimpleClauseTypeName(OMPC_schedule, M1); 7256 return nullptr; 7257 } 7258 if (Kind == OMPC_SCHEDULE_unknown) { 7259 std::string Values; 7260 if (M1Loc.isInvalid() && M2Loc.isInvalid()) { 7261 unsigned Exclude[] = {OMPC_SCHEDULE_unknown}; 7262 Values = getListOfPossibleValues(OMPC_schedule, /*First=*/0, 7263 /*Last=*/OMPC_SCHEDULE_MODIFIER_last, 7264 Exclude); 7265 } else { 7266 Values = getListOfPossibleValues(OMPC_schedule, /*First=*/0, 7267 /*Last=*/OMPC_SCHEDULE_unknown); 7268 } 7269 Diag(KindLoc, diag::err_omp_unexpected_clause_value) 7270 << Values << getOpenMPClauseName(OMPC_schedule); 7271 return nullptr; 7272 } 7273 // OpenMP, 2.7.1, Loop Construct, Restrictions 7274 // The nonmonotonic modifier can only be specified with schedule(dynamic) or 7275 // schedule(guided). 7276 if ((M1 == OMPC_SCHEDULE_MODIFIER_nonmonotonic || 7277 M2 == OMPC_SCHEDULE_MODIFIER_nonmonotonic) && 7278 Kind != OMPC_SCHEDULE_dynamic && Kind != OMPC_SCHEDULE_guided) { 7279 Diag(M1 == OMPC_SCHEDULE_MODIFIER_nonmonotonic ? M1Loc : M2Loc, 7280 diag::err_omp_schedule_nonmonotonic_static); 7281 return nullptr; 7282 } 7283 Expr *ValExpr = ChunkSize; 7284 Stmt *HelperValStmt = nullptr; 7285 if (ChunkSize) { 7286 if (!ChunkSize->isValueDependent() && !ChunkSize->isTypeDependent() && 7287 !ChunkSize->isInstantiationDependent() && 7288 !ChunkSize->containsUnexpandedParameterPack()) { 7289 SourceLocation ChunkSizeLoc = ChunkSize->getLocStart(); 7290 ExprResult Val = 7291 PerformOpenMPImplicitIntegerConversion(ChunkSizeLoc, ChunkSize); 7292 if (Val.isInvalid()) 7293 return nullptr; 7294 7295 ValExpr = Val.get(); 7296 7297 // OpenMP [2.7.1, Restrictions] 7298 // chunk_size must be a loop invariant integer expression with a positive 7299 // value. 7300 llvm::APSInt Result; 7301 if (ValExpr->isIntegerConstantExpr(Result, Context)) { 7302 if (Result.isSigned() && !Result.isStrictlyPositive()) { 7303 Diag(ChunkSizeLoc, diag::err_omp_negative_expression_in_clause) 7304 << "schedule" << 1 << ChunkSize->getSourceRange(); 7305 return nullptr; 7306 } 7307 } else if (isParallelOrTaskRegion(DSAStack->getCurrentDirective()) && 7308 !CurContext->isDependentContext()) { 7309 llvm::MapVector<Expr *, DeclRefExpr *> Captures; 7310 ValExpr = tryBuildCapture(*this, ValExpr, Captures).get(); 7311 HelperValStmt = buildPreInits(Context, Captures); 7312 } 7313 } 7314 } 7315 7316 return new (Context) 7317 OMPScheduleClause(StartLoc, LParenLoc, KindLoc, CommaLoc, EndLoc, Kind, 7318 ValExpr, HelperValStmt, M1, M1Loc, M2, M2Loc); 7319 } 7320 7321 OMPClause *Sema::ActOnOpenMPClause(OpenMPClauseKind Kind, 7322 SourceLocation StartLoc, 7323 SourceLocation EndLoc) { 7324 OMPClause *Res = nullptr; 7325 switch (Kind) { 7326 case OMPC_ordered: 7327 Res = ActOnOpenMPOrderedClause(StartLoc, EndLoc); 7328 break; 7329 case OMPC_nowait: 7330 Res = ActOnOpenMPNowaitClause(StartLoc, EndLoc); 7331 break; 7332 case OMPC_untied: 7333 Res = ActOnOpenMPUntiedClause(StartLoc, EndLoc); 7334 break; 7335 case OMPC_mergeable: 7336 Res = ActOnOpenMPMergeableClause(StartLoc, EndLoc); 7337 break; 7338 case OMPC_read: 7339 Res = ActOnOpenMPReadClause(StartLoc, EndLoc); 7340 break; 7341 case OMPC_write: 7342 Res = ActOnOpenMPWriteClause(StartLoc, EndLoc); 7343 break; 7344 case OMPC_update: 7345 Res = ActOnOpenMPUpdateClause(StartLoc, EndLoc); 7346 break; 7347 case OMPC_capture: 7348 Res = ActOnOpenMPCaptureClause(StartLoc, EndLoc); 7349 break; 7350 case OMPC_seq_cst: 7351 Res = ActOnOpenMPSeqCstClause(StartLoc, EndLoc); 7352 break; 7353 case OMPC_threads: 7354 Res = ActOnOpenMPThreadsClause(StartLoc, EndLoc); 7355 break; 7356 case OMPC_simd: 7357 Res = ActOnOpenMPSIMDClause(StartLoc, EndLoc); 7358 break; 7359 case OMPC_nogroup: 7360 Res = ActOnOpenMPNogroupClause(StartLoc, EndLoc); 7361 break; 7362 case OMPC_if: 7363 case OMPC_final: 7364 case OMPC_num_threads: 7365 case OMPC_safelen: 7366 case OMPC_simdlen: 7367 case OMPC_collapse: 7368 case OMPC_schedule: 7369 case OMPC_private: 7370 case OMPC_firstprivate: 7371 case OMPC_lastprivate: 7372 case OMPC_shared: 7373 case OMPC_reduction: 7374 case OMPC_linear: 7375 case OMPC_aligned: 7376 case OMPC_copyin: 7377 case OMPC_copyprivate: 7378 case OMPC_default: 7379 case OMPC_proc_bind: 7380 case OMPC_threadprivate: 7381 case OMPC_flush: 7382 case OMPC_depend: 7383 case OMPC_device: 7384 case OMPC_map: 7385 case OMPC_num_teams: 7386 case OMPC_thread_limit: 7387 case OMPC_priority: 7388 case OMPC_grainsize: 7389 case OMPC_num_tasks: 7390 case OMPC_hint: 7391 case OMPC_dist_schedule: 7392 case OMPC_defaultmap: 7393 case OMPC_unknown: 7394 case OMPC_uniform: 7395 case OMPC_to: 7396 case OMPC_from: 7397 case OMPC_use_device_ptr: 7398 case OMPC_is_device_ptr: 7399 llvm_unreachable("Clause is not allowed."); 7400 } 7401 return Res; 7402 } 7403 7404 OMPClause *Sema::ActOnOpenMPNowaitClause(SourceLocation StartLoc, 7405 SourceLocation EndLoc) { 7406 DSAStack->setNowaitRegion(); 7407 return new (Context) OMPNowaitClause(StartLoc, EndLoc); 7408 } 7409 7410 OMPClause *Sema::ActOnOpenMPUntiedClause(SourceLocation StartLoc, 7411 SourceLocation EndLoc) { 7412 return new (Context) OMPUntiedClause(StartLoc, EndLoc); 7413 } 7414 7415 OMPClause *Sema::ActOnOpenMPMergeableClause(SourceLocation StartLoc, 7416 SourceLocation EndLoc) { 7417 return new (Context) OMPMergeableClause(StartLoc, EndLoc); 7418 } 7419 7420 OMPClause *Sema::ActOnOpenMPReadClause(SourceLocation StartLoc, 7421 SourceLocation EndLoc) { 7422 return new (Context) OMPReadClause(StartLoc, EndLoc); 7423 } 7424 7425 OMPClause *Sema::ActOnOpenMPWriteClause(SourceLocation StartLoc, 7426 SourceLocation EndLoc) { 7427 return new (Context) OMPWriteClause(StartLoc, EndLoc); 7428 } 7429 7430 OMPClause *Sema::ActOnOpenMPUpdateClause(SourceLocation StartLoc, 7431 SourceLocation EndLoc) { 7432 return new (Context) OMPUpdateClause(StartLoc, EndLoc); 7433 } 7434 7435 OMPClause *Sema::ActOnOpenMPCaptureClause(SourceLocation StartLoc, 7436 SourceLocation EndLoc) { 7437 return new (Context) OMPCaptureClause(StartLoc, EndLoc); 7438 } 7439 7440 OMPClause *Sema::ActOnOpenMPSeqCstClause(SourceLocation StartLoc, 7441 SourceLocation EndLoc) { 7442 return new (Context) OMPSeqCstClause(StartLoc, EndLoc); 7443 } 7444 7445 OMPClause *Sema::ActOnOpenMPThreadsClause(SourceLocation StartLoc, 7446 SourceLocation EndLoc) { 7447 return new (Context) OMPThreadsClause(StartLoc, EndLoc); 7448 } 7449 7450 OMPClause *Sema::ActOnOpenMPSIMDClause(SourceLocation StartLoc, 7451 SourceLocation EndLoc) { 7452 return new (Context) OMPSIMDClause(StartLoc, EndLoc); 7453 } 7454 7455 OMPClause *Sema::ActOnOpenMPNogroupClause(SourceLocation StartLoc, 7456 SourceLocation EndLoc) { 7457 return new (Context) OMPNogroupClause(StartLoc, EndLoc); 7458 } 7459 7460 OMPClause *Sema::ActOnOpenMPVarListClause( 7461 OpenMPClauseKind Kind, ArrayRef<Expr *> VarList, Expr *TailExpr, 7462 SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation ColonLoc, 7463 SourceLocation EndLoc, CXXScopeSpec &ReductionIdScopeSpec, 7464 const DeclarationNameInfo &ReductionId, OpenMPDependClauseKind DepKind, 7465 OpenMPLinearClauseKind LinKind, OpenMPMapClauseKind MapTypeModifier, 7466 OpenMPMapClauseKind MapType, bool IsMapTypeImplicit, 7467 SourceLocation DepLinMapLoc) { 7468 OMPClause *Res = nullptr; 7469 switch (Kind) { 7470 case OMPC_private: 7471 Res = ActOnOpenMPPrivateClause(VarList, StartLoc, LParenLoc, EndLoc); 7472 break; 7473 case OMPC_firstprivate: 7474 Res = ActOnOpenMPFirstprivateClause(VarList, StartLoc, LParenLoc, EndLoc); 7475 break; 7476 case OMPC_lastprivate: 7477 Res = ActOnOpenMPLastprivateClause(VarList, StartLoc, LParenLoc, EndLoc); 7478 break; 7479 case OMPC_shared: 7480 Res = ActOnOpenMPSharedClause(VarList, StartLoc, LParenLoc, EndLoc); 7481 break; 7482 case OMPC_reduction: 7483 Res = ActOnOpenMPReductionClause(VarList, StartLoc, LParenLoc, ColonLoc, 7484 EndLoc, ReductionIdScopeSpec, ReductionId); 7485 break; 7486 case OMPC_linear: 7487 Res = ActOnOpenMPLinearClause(VarList, TailExpr, StartLoc, LParenLoc, 7488 LinKind, DepLinMapLoc, ColonLoc, EndLoc); 7489 break; 7490 case OMPC_aligned: 7491 Res = ActOnOpenMPAlignedClause(VarList, TailExpr, StartLoc, LParenLoc, 7492 ColonLoc, EndLoc); 7493 break; 7494 case OMPC_copyin: 7495 Res = ActOnOpenMPCopyinClause(VarList, StartLoc, LParenLoc, EndLoc); 7496 break; 7497 case OMPC_copyprivate: 7498 Res = ActOnOpenMPCopyprivateClause(VarList, StartLoc, LParenLoc, EndLoc); 7499 break; 7500 case OMPC_flush: 7501 Res = ActOnOpenMPFlushClause(VarList, StartLoc, LParenLoc, EndLoc); 7502 break; 7503 case OMPC_depend: 7504 Res = ActOnOpenMPDependClause(DepKind, DepLinMapLoc, ColonLoc, VarList, 7505 StartLoc, LParenLoc, EndLoc); 7506 break; 7507 case OMPC_map: 7508 Res = ActOnOpenMPMapClause(MapTypeModifier, MapType, IsMapTypeImplicit, 7509 DepLinMapLoc, ColonLoc, VarList, StartLoc, 7510 LParenLoc, EndLoc); 7511 break; 7512 case OMPC_to: 7513 Res = ActOnOpenMPToClause(VarList, StartLoc, LParenLoc, EndLoc); 7514 break; 7515 case OMPC_from: 7516 Res = ActOnOpenMPFromClause(VarList, StartLoc, LParenLoc, EndLoc); 7517 break; 7518 case OMPC_use_device_ptr: 7519 Res = ActOnOpenMPUseDevicePtrClause(VarList, StartLoc, LParenLoc, EndLoc); 7520 break; 7521 case OMPC_is_device_ptr: 7522 Res = ActOnOpenMPIsDevicePtrClause(VarList, StartLoc, LParenLoc, EndLoc); 7523 break; 7524 case OMPC_if: 7525 case OMPC_final: 7526 case OMPC_num_threads: 7527 case OMPC_safelen: 7528 case OMPC_simdlen: 7529 case OMPC_collapse: 7530 case OMPC_default: 7531 case OMPC_proc_bind: 7532 case OMPC_schedule: 7533 case OMPC_ordered: 7534 case OMPC_nowait: 7535 case OMPC_untied: 7536 case OMPC_mergeable: 7537 case OMPC_threadprivate: 7538 case OMPC_read: 7539 case OMPC_write: 7540 case OMPC_update: 7541 case OMPC_capture: 7542 case OMPC_seq_cst: 7543 case OMPC_device: 7544 case OMPC_threads: 7545 case OMPC_simd: 7546 case OMPC_num_teams: 7547 case OMPC_thread_limit: 7548 case OMPC_priority: 7549 case OMPC_grainsize: 7550 case OMPC_nogroup: 7551 case OMPC_num_tasks: 7552 case OMPC_hint: 7553 case OMPC_dist_schedule: 7554 case OMPC_defaultmap: 7555 case OMPC_unknown: 7556 case OMPC_uniform: 7557 llvm_unreachable("Clause is not allowed."); 7558 } 7559 return Res; 7560 } 7561 7562 ExprResult Sema::getOpenMPCapturedExpr(VarDecl *Capture, ExprValueKind VK, 7563 ExprObjectKind OK, SourceLocation Loc) { 7564 ExprResult Res = BuildDeclRefExpr( 7565 Capture, Capture->getType().getNonReferenceType(), VK_LValue, Loc); 7566 if (!Res.isUsable()) 7567 return ExprError(); 7568 if (OK == OK_Ordinary && !getLangOpts().CPlusPlus) { 7569 Res = CreateBuiltinUnaryOp(Loc, UO_Deref, Res.get()); 7570 if (!Res.isUsable()) 7571 return ExprError(); 7572 } 7573 if (VK != VK_LValue && Res.get()->isGLValue()) { 7574 Res = DefaultLvalueConversion(Res.get()); 7575 if (!Res.isUsable()) 7576 return ExprError(); 7577 } 7578 return Res; 7579 } 7580 7581 static std::pair<ValueDecl *, bool> 7582 getPrivateItem(Sema &S, Expr *&RefExpr, SourceLocation &ELoc, 7583 SourceRange &ERange, bool AllowArraySection = false) { 7584 if (RefExpr->isTypeDependent() || RefExpr->isValueDependent() || 7585 RefExpr->containsUnexpandedParameterPack()) 7586 return std::make_pair(nullptr, true); 7587 7588 // OpenMP [3.1, C/C++] 7589 // A list item is a variable name. 7590 // OpenMP [2.9.3.3, Restrictions, p.1] 7591 // A variable that is part of another variable (as an array or 7592 // structure element) cannot appear in a private clause. 7593 RefExpr = RefExpr->IgnoreParens(); 7594 enum { 7595 NoArrayExpr = -1, 7596 ArraySubscript = 0, 7597 OMPArraySection = 1 7598 } IsArrayExpr = NoArrayExpr; 7599 if (AllowArraySection) { 7600 if (auto *ASE = dyn_cast_or_null<ArraySubscriptExpr>(RefExpr)) { 7601 auto *Base = ASE->getBase()->IgnoreParenImpCasts(); 7602 while (auto *TempASE = dyn_cast<ArraySubscriptExpr>(Base)) 7603 Base = TempASE->getBase()->IgnoreParenImpCasts(); 7604 RefExpr = Base; 7605 IsArrayExpr = ArraySubscript; 7606 } else if (auto *OASE = dyn_cast_or_null<OMPArraySectionExpr>(RefExpr)) { 7607 auto *Base = OASE->getBase()->IgnoreParenImpCasts(); 7608 while (auto *TempOASE = dyn_cast<OMPArraySectionExpr>(Base)) 7609 Base = TempOASE->getBase()->IgnoreParenImpCasts(); 7610 while (auto *TempASE = dyn_cast<ArraySubscriptExpr>(Base)) 7611 Base = TempASE->getBase()->IgnoreParenImpCasts(); 7612 RefExpr = Base; 7613 IsArrayExpr = OMPArraySection; 7614 } 7615 } 7616 ELoc = RefExpr->getExprLoc(); 7617 ERange = RefExpr->getSourceRange(); 7618 RefExpr = RefExpr->IgnoreParenImpCasts(); 7619 auto *DE = dyn_cast_or_null<DeclRefExpr>(RefExpr); 7620 auto *ME = dyn_cast_or_null<MemberExpr>(RefExpr); 7621 if ((!DE || !isa<VarDecl>(DE->getDecl())) && 7622 (S.getCurrentThisType().isNull() || !ME || 7623 !isa<CXXThisExpr>(ME->getBase()->IgnoreParenImpCasts()) || 7624 !isa<FieldDecl>(ME->getMemberDecl()))) { 7625 if (IsArrayExpr != NoArrayExpr) 7626 S.Diag(ELoc, diag::err_omp_expected_base_var_name) << IsArrayExpr 7627 << ERange; 7628 else { 7629 S.Diag(ELoc, 7630 AllowArraySection 7631 ? diag::err_omp_expected_var_name_member_expr_or_array_item 7632 : diag::err_omp_expected_var_name_member_expr) 7633 << (S.getCurrentThisType().isNull() ? 0 : 1) << ERange; 7634 } 7635 return std::make_pair(nullptr, false); 7636 } 7637 return std::make_pair(DE ? DE->getDecl() : ME->getMemberDecl(), false); 7638 } 7639 7640 OMPClause *Sema::ActOnOpenMPPrivateClause(ArrayRef<Expr *> VarList, 7641 SourceLocation StartLoc, 7642 SourceLocation LParenLoc, 7643 SourceLocation EndLoc) { 7644 SmallVector<Expr *, 8> Vars; 7645 SmallVector<Expr *, 8> PrivateCopies; 7646 for (auto &RefExpr : VarList) { 7647 assert(RefExpr && "NULL expr in OpenMP private clause."); 7648 SourceLocation ELoc; 7649 SourceRange ERange; 7650 Expr *SimpleRefExpr = RefExpr; 7651 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange); 7652 if (Res.second) { 7653 // It will be analyzed later. 7654 Vars.push_back(RefExpr); 7655 PrivateCopies.push_back(nullptr); 7656 } 7657 ValueDecl *D = Res.first; 7658 if (!D) 7659 continue; 7660 7661 QualType Type = D->getType(); 7662 auto *VD = dyn_cast<VarDecl>(D); 7663 7664 // OpenMP [2.9.3.3, Restrictions, C/C++, p.3] 7665 // A variable that appears in a private clause must not have an incomplete 7666 // type or a reference type. 7667 if (RequireCompleteType(ELoc, Type, diag::err_omp_private_incomplete_type)) 7668 continue; 7669 Type = Type.getNonReferenceType(); 7670 7671 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced 7672 // in a Construct] 7673 // Variables with the predetermined data-sharing attributes may not be 7674 // listed in data-sharing attributes clauses, except for the cases 7675 // listed below. For these exceptions only, listing a predetermined 7676 // variable in a data-sharing attribute clause is allowed and overrides 7677 // the variable's predetermined data-sharing attributes. 7678 DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, false); 7679 if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_private) { 7680 Diag(ELoc, diag::err_omp_wrong_dsa) << getOpenMPClauseName(DVar.CKind) 7681 << getOpenMPClauseName(OMPC_private); 7682 ReportOriginalDSA(*this, DSAStack, D, DVar); 7683 continue; 7684 } 7685 7686 auto CurrDir = DSAStack->getCurrentDirective(); 7687 // Variably modified types are not supported for tasks. 7688 if (!Type->isAnyPointerType() && Type->isVariablyModifiedType() && 7689 isOpenMPTaskingDirective(CurrDir)) { 7690 Diag(ELoc, diag::err_omp_variably_modified_type_not_supported) 7691 << getOpenMPClauseName(OMPC_private) << Type 7692 << getOpenMPDirectiveName(CurrDir); 7693 bool IsDecl = 7694 !VD || 7695 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly; 7696 Diag(D->getLocation(), 7697 IsDecl ? diag::note_previous_decl : diag::note_defined_here) 7698 << D; 7699 continue; 7700 } 7701 7702 // OpenMP 4.5 [2.15.5.1, Restrictions, p.3] 7703 // A list item cannot appear in both a map clause and a data-sharing 7704 // attribute clause on the same construct 7705 if (CurrDir == OMPD_target || CurrDir == OMPD_target_parallel || 7706 CurrDir == OMPD_target_teams || 7707 CurrDir == OMPD_target_teams_distribute || 7708 CurrDir == OMPD_target_teams_distribute_parallel_for || 7709 CurrDir == OMPD_target_teams_distribute_parallel_for_simd || 7710 CurrDir == OMPD_target_teams_distribute_simd || 7711 CurrDir == OMPD_target_parallel_for_simd || 7712 CurrDir == OMPD_target_parallel_for) { 7713 OpenMPClauseKind ConflictKind; 7714 if (DSAStack->checkMappableExprComponentListsForDecl( 7715 VD, /*CurrentRegionOnly=*/true, 7716 [&](OMPClauseMappableExprCommon::MappableExprComponentListRef, 7717 OpenMPClauseKind WhereFoundClauseKind) -> bool { 7718 ConflictKind = WhereFoundClauseKind; 7719 return true; 7720 })) { 7721 Diag(ELoc, diag::err_omp_variable_in_given_clause_and_dsa) 7722 << getOpenMPClauseName(OMPC_private) 7723 << getOpenMPClauseName(ConflictKind) 7724 << getOpenMPDirectiveName(CurrDir); 7725 ReportOriginalDSA(*this, DSAStack, D, DVar); 7726 continue; 7727 } 7728 } 7729 7730 // OpenMP [2.9.3.3, Restrictions, C/C++, p.1] 7731 // A variable of class type (or array thereof) that appears in a private 7732 // clause requires an accessible, unambiguous default constructor for the 7733 // class type. 7734 // Generate helper private variable and initialize it with the default 7735 // value. The address of the original variable is replaced by the address of 7736 // the new private variable in CodeGen. This new variable is not added to 7737 // IdResolver, so the code in the OpenMP region uses original variable for 7738 // proper diagnostics. 7739 Type = Type.getUnqualifiedType(); 7740 auto VDPrivate = buildVarDecl(*this, ELoc, Type, D->getName(), 7741 D->hasAttrs() ? &D->getAttrs() : nullptr); 7742 ActOnUninitializedDecl(VDPrivate); 7743 if (VDPrivate->isInvalidDecl()) 7744 continue; 7745 auto VDPrivateRefExpr = buildDeclRefExpr( 7746 *this, VDPrivate, RefExpr->getType().getUnqualifiedType(), ELoc); 7747 7748 DeclRefExpr *Ref = nullptr; 7749 if (!VD && !CurContext->isDependentContext()) 7750 Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/false); 7751 DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_private, Ref); 7752 Vars.push_back((VD || CurContext->isDependentContext()) 7753 ? RefExpr->IgnoreParens() 7754 : Ref); 7755 PrivateCopies.push_back(VDPrivateRefExpr); 7756 } 7757 7758 if (Vars.empty()) 7759 return nullptr; 7760 7761 return OMPPrivateClause::Create(Context, StartLoc, LParenLoc, EndLoc, Vars, 7762 PrivateCopies); 7763 } 7764 7765 namespace { 7766 class DiagsUninitializedSeveretyRAII { 7767 private: 7768 DiagnosticsEngine &Diags; 7769 SourceLocation SavedLoc; 7770 bool IsIgnored; 7771 7772 public: 7773 DiagsUninitializedSeveretyRAII(DiagnosticsEngine &Diags, SourceLocation Loc, 7774 bool IsIgnored) 7775 : Diags(Diags), SavedLoc(Loc), IsIgnored(IsIgnored) { 7776 if (!IsIgnored) { 7777 Diags.setSeverity(/*Diag*/ diag::warn_uninit_self_reference_in_init, 7778 /*Map*/ diag::Severity::Ignored, Loc); 7779 } 7780 } 7781 ~DiagsUninitializedSeveretyRAII() { 7782 if (!IsIgnored) 7783 Diags.popMappings(SavedLoc); 7784 } 7785 }; 7786 } 7787 7788 OMPClause *Sema::ActOnOpenMPFirstprivateClause(ArrayRef<Expr *> VarList, 7789 SourceLocation StartLoc, 7790 SourceLocation LParenLoc, 7791 SourceLocation EndLoc) { 7792 SmallVector<Expr *, 8> Vars; 7793 SmallVector<Expr *, 8> PrivateCopies; 7794 SmallVector<Expr *, 8> Inits; 7795 SmallVector<Decl *, 4> ExprCaptures; 7796 bool IsImplicitClause = 7797 StartLoc.isInvalid() && LParenLoc.isInvalid() && EndLoc.isInvalid(); 7798 auto ImplicitClauseLoc = DSAStack->getConstructLoc(); 7799 7800 for (auto &RefExpr : VarList) { 7801 assert(RefExpr && "NULL expr in OpenMP firstprivate clause."); 7802 SourceLocation ELoc; 7803 SourceRange ERange; 7804 Expr *SimpleRefExpr = RefExpr; 7805 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange); 7806 if (Res.second) { 7807 // It will be analyzed later. 7808 Vars.push_back(RefExpr); 7809 PrivateCopies.push_back(nullptr); 7810 Inits.push_back(nullptr); 7811 } 7812 ValueDecl *D = Res.first; 7813 if (!D) 7814 continue; 7815 7816 ELoc = IsImplicitClause ? ImplicitClauseLoc : ELoc; 7817 QualType Type = D->getType(); 7818 auto *VD = dyn_cast<VarDecl>(D); 7819 7820 // OpenMP [2.9.3.3, Restrictions, C/C++, p.3] 7821 // A variable that appears in a private clause must not have an incomplete 7822 // type or a reference type. 7823 if (RequireCompleteType(ELoc, Type, 7824 diag::err_omp_firstprivate_incomplete_type)) 7825 continue; 7826 Type = Type.getNonReferenceType(); 7827 7828 // OpenMP [2.9.3.4, Restrictions, C/C++, p.1] 7829 // A variable of class type (or array thereof) that appears in a private 7830 // clause requires an accessible, unambiguous copy constructor for the 7831 // class type. 7832 auto ElemType = Context.getBaseElementType(Type).getNonReferenceType(); 7833 7834 // If an implicit firstprivate variable found it was checked already. 7835 DSAStackTy::DSAVarData TopDVar; 7836 if (!IsImplicitClause) { 7837 DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, false); 7838 TopDVar = DVar; 7839 bool IsConstant = ElemType.isConstant(Context); 7840 // OpenMP [2.4.13, Data-sharing Attribute Clauses] 7841 // A list item that specifies a given variable may not appear in more 7842 // than one clause on the same directive, except that a variable may be 7843 // specified in both firstprivate and lastprivate clauses. 7844 if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_firstprivate && 7845 DVar.CKind != OMPC_lastprivate && DVar.RefExpr) { 7846 Diag(ELoc, diag::err_omp_wrong_dsa) 7847 << getOpenMPClauseName(DVar.CKind) 7848 << getOpenMPClauseName(OMPC_firstprivate); 7849 ReportOriginalDSA(*this, DSAStack, D, DVar); 7850 continue; 7851 } 7852 7853 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced 7854 // in a Construct] 7855 // Variables with the predetermined data-sharing attributes may not be 7856 // listed in data-sharing attributes clauses, except for the cases 7857 // listed below. For these exceptions only, listing a predetermined 7858 // variable in a data-sharing attribute clause is allowed and overrides 7859 // the variable's predetermined data-sharing attributes. 7860 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced 7861 // in a Construct, C/C++, p.2] 7862 // Variables with const-qualified type having no mutable member may be 7863 // listed in a firstprivate clause, even if they are static data members. 7864 if (!(IsConstant || (VD && VD->isStaticDataMember())) && !DVar.RefExpr && 7865 DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_shared) { 7866 Diag(ELoc, diag::err_omp_wrong_dsa) 7867 << getOpenMPClauseName(DVar.CKind) 7868 << getOpenMPClauseName(OMPC_firstprivate); 7869 ReportOriginalDSA(*this, DSAStack, D, DVar); 7870 continue; 7871 } 7872 7873 OpenMPDirectiveKind CurrDir = DSAStack->getCurrentDirective(); 7874 // OpenMP [2.9.3.4, Restrictions, p.2] 7875 // A list item that is private within a parallel region must not appear 7876 // in a firstprivate clause on a worksharing construct if any of the 7877 // worksharing regions arising from the worksharing construct ever bind 7878 // to any of the parallel regions arising from the parallel construct. 7879 if (isOpenMPWorksharingDirective(CurrDir) && 7880 !isOpenMPParallelDirective(CurrDir) && 7881 !isOpenMPTeamsDirective(CurrDir)) { 7882 DVar = DSAStack->getImplicitDSA(D, true); 7883 if (DVar.CKind != OMPC_shared && 7884 (isOpenMPParallelDirective(DVar.DKind) || 7885 DVar.DKind == OMPD_unknown)) { 7886 Diag(ELoc, diag::err_omp_required_access) 7887 << getOpenMPClauseName(OMPC_firstprivate) 7888 << getOpenMPClauseName(OMPC_shared); 7889 ReportOriginalDSA(*this, DSAStack, D, DVar); 7890 continue; 7891 } 7892 } 7893 // OpenMP [2.9.3.4, Restrictions, p.3] 7894 // A list item that appears in a reduction clause of a parallel construct 7895 // must not appear in a firstprivate clause on a worksharing or task 7896 // construct if any of the worksharing or task regions arising from the 7897 // worksharing or task construct ever bind to any of the parallel regions 7898 // arising from the parallel construct. 7899 // OpenMP [2.9.3.4, Restrictions, p.4] 7900 // A list item that appears in a reduction clause in worksharing 7901 // construct must not appear in a firstprivate clause in a task construct 7902 // encountered during execution of any of the worksharing regions arising 7903 // from the worksharing construct. 7904 if (isOpenMPTaskingDirective(CurrDir)) { 7905 DVar = DSAStack->hasInnermostDSA( 7906 D, [](OpenMPClauseKind C) -> bool { return C == OMPC_reduction; }, 7907 [](OpenMPDirectiveKind K) -> bool { 7908 return isOpenMPParallelDirective(K) || 7909 isOpenMPWorksharingDirective(K); 7910 }, 7911 false); 7912 if (DVar.CKind == OMPC_reduction && 7913 (isOpenMPParallelDirective(DVar.DKind) || 7914 isOpenMPWorksharingDirective(DVar.DKind))) { 7915 Diag(ELoc, diag::err_omp_parallel_reduction_in_task_firstprivate) 7916 << getOpenMPDirectiveName(DVar.DKind); 7917 ReportOriginalDSA(*this, DSAStack, D, DVar); 7918 continue; 7919 } 7920 } 7921 7922 // OpenMP 4.5 [2.15.3.4, Restrictions, p.3] 7923 // A list item that is private within a teams region must not appear in a 7924 // firstprivate clause on a distribute construct if any of the distribute 7925 // regions arising from the distribute construct ever bind to any of the 7926 // teams regions arising from the teams construct. 7927 // OpenMP 4.5 [2.15.3.4, Restrictions, p.3] 7928 // A list item that appears in a reduction clause of a teams construct 7929 // must not appear in a firstprivate clause on a distribute construct if 7930 // any of the distribute regions arising from the distribute construct 7931 // ever bind to any of the teams regions arising from the teams construct. 7932 // OpenMP 4.5 [2.10.8, Distribute Construct, p.3] 7933 // A list item may appear in a firstprivate or lastprivate clause but not 7934 // both. 7935 if (CurrDir == OMPD_distribute) { 7936 DVar = DSAStack->hasInnermostDSA( 7937 D, [](OpenMPClauseKind C) -> bool { return C == OMPC_private; }, 7938 [](OpenMPDirectiveKind K) -> bool { 7939 return isOpenMPTeamsDirective(K); 7940 }, 7941 false); 7942 if (DVar.CKind == OMPC_private && isOpenMPTeamsDirective(DVar.DKind)) { 7943 Diag(ELoc, diag::err_omp_firstprivate_distribute_private_teams); 7944 ReportOriginalDSA(*this, DSAStack, D, DVar); 7945 continue; 7946 } 7947 DVar = DSAStack->hasInnermostDSA( 7948 D, [](OpenMPClauseKind C) -> bool { return C == OMPC_reduction; }, 7949 [](OpenMPDirectiveKind K) -> bool { 7950 return isOpenMPTeamsDirective(K); 7951 }, 7952 false); 7953 if (DVar.CKind == OMPC_reduction && 7954 isOpenMPTeamsDirective(DVar.DKind)) { 7955 Diag(ELoc, diag::err_omp_firstprivate_distribute_in_teams_reduction); 7956 ReportOriginalDSA(*this, DSAStack, D, DVar); 7957 continue; 7958 } 7959 DVar = DSAStack->getTopDSA(D, false); 7960 if (DVar.CKind == OMPC_lastprivate) { 7961 Diag(ELoc, diag::err_omp_firstprivate_and_lastprivate_in_distribute); 7962 ReportOriginalDSA(*this, DSAStack, D, DVar); 7963 continue; 7964 } 7965 } 7966 // OpenMP 4.5 [2.15.5.1, Restrictions, p.3] 7967 // A list item cannot appear in both a map clause and a data-sharing 7968 // attribute clause on the same construct 7969 if (CurrDir == OMPD_target || CurrDir == OMPD_target_parallel || 7970 CurrDir == OMPD_target_teams || 7971 CurrDir == OMPD_target_teams_distribute || 7972 CurrDir == OMPD_target_teams_distribute_parallel_for || 7973 CurrDir == OMPD_target_teams_distribute_parallel_for_simd || 7974 CurrDir == OMPD_target_teams_distribute_simd || 7975 CurrDir == OMPD_target_parallel_for_simd || 7976 CurrDir == OMPD_target_parallel_for) { 7977 OpenMPClauseKind ConflictKind; 7978 if (DSAStack->checkMappableExprComponentListsForDecl( 7979 VD, /*CurrentRegionOnly=*/true, 7980 [&](OMPClauseMappableExprCommon::MappableExprComponentListRef, 7981 OpenMPClauseKind WhereFoundClauseKind) -> bool { 7982 ConflictKind = WhereFoundClauseKind; 7983 return true; 7984 })) { 7985 Diag(ELoc, diag::err_omp_variable_in_given_clause_and_dsa) 7986 << getOpenMPClauseName(OMPC_firstprivate) 7987 << getOpenMPClauseName(ConflictKind) 7988 << getOpenMPDirectiveName(DSAStack->getCurrentDirective()); 7989 ReportOriginalDSA(*this, DSAStack, D, DVar); 7990 continue; 7991 } 7992 } 7993 } 7994 7995 // Variably modified types are not supported for tasks. 7996 if (!Type->isAnyPointerType() && Type->isVariablyModifiedType() && 7997 isOpenMPTaskingDirective(DSAStack->getCurrentDirective())) { 7998 Diag(ELoc, diag::err_omp_variably_modified_type_not_supported) 7999 << getOpenMPClauseName(OMPC_firstprivate) << Type 8000 << getOpenMPDirectiveName(DSAStack->getCurrentDirective()); 8001 bool IsDecl = 8002 !VD || 8003 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly; 8004 Diag(D->getLocation(), 8005 IsDecl ? diag::note_previous_decl : diag::note_defined_here) 8006 << D; 8007 continue; 8008 } 8009 8010 Type = Type.getUnqualifiedType(); 8011 auto VDPrivate = buildVarDecl(*this, ELoc, Type, D->getName(), 8012 D->hasAttrs() ? &D->getAttrs() : nullptr); 8013 // Generate helper private variable and initialize it with the value of the 8014 // original variable. The address of the original variable is replaced by 8015 // the address of the new private variable in the CodeGen. This new variable 8016 // is not added to IdResolver, so the code in the OpenMP region uses 8017 // original variable for proper diagnostics and variable capturing. 8018 Expr *VDInitRefExpr = nullptr; 8019 // For arrays generate initializer for single element and replace it by the 8020 // original array element in CodeGen. 8021 if (Type->isArrayType()) { 8022 auto VDInit = 8023 buildVarDecl(*this, RefExpr->getExprLoc(), ElemType, D->getName()); 8024 VDInitRefExpr = buildDeclRefExpr(*this, VDInit, ElemType, ELoc); 8025 auto Init = DefaultLvalueConversion(VDInitRefExpr).get(); 8026 ElemType = ElemType.getUnqualifiedType(); 8027 auto *VDInitTemp = buildVarDecl(*this, RefExpr->getExprLoc(), ElemType, 8028 ".firstprivate.temp"); 8029 InitializedEntity Entity = 8030 InitializedEntity::InitializeVariable(VDInitTemp); 8031 InitializationKind Kind = InitializationKind::CreateCopy(ELoc, ELoc); 8032 8033 InitializationSequence InitSeq(*this, Entity, Kind, Init); 8034 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Init); 8035 if (Result.isInvalid()) 8036 VDPrivate->setInvalidDecl(); 8037 else 8038 VDPrivate->setInit(Result.getAs<Expr>()); 8039 // Remove temp variable declaration. 8040 Context.Deallocate(VDInitTemp); 8041 } else { 8042 auto *VDInit = buildVarDecl(*this, RefExpr->getExprLoc(), Type, 8043 ".firstprivate.temp"); 8044 VDInitRefExpr = buildDeclRefExpr(*this, VDInit, RefExpr->getType(), 8045 RefExpr->getExprLoc()); 8046 AddInitializerToDecl(VDPrivate, 8047 DefaultLvalueConversion(VDInitRefExpr).get(), 8048 /*DirectInit=*/false); 8049 } 8050 if (VDPrivate->isInvalidDecl()) { 8051 if (IsImplicitClause) { 8052 Diag(RefExpr->getExprLoc(), 8053 diag::note_omp_task_predetermined_firstprivate_here); 8054 } 8055 continue; 8056 } 8057 CurContext->addDecl(VDPrivate); 8058 auto VDPrivateRefExpr = buildDeclRefExpr( 8059 *this, VDPrivate, RefExpr->getType().getUnqualifiedType(), 8060 RefExpr->getExprLoc()); 8061 DeclRefExpr *Ref = nullptr; 8062 if (!VD && !CurContext->isDependentContext()) { 8063 if (TopDVar.CKind == OMPC_lastprivate) 8064 Ref = TopDVar.PrivateCopy; 8065 else { 8066 Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/true); 8067 if (!IsOpenMPCapturedDecl(D)) 8068 ExprCaptures.push_back(Ref->getDecl()); 8069 } 8070 } 8071 DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_firstprivate, Ref); 8072 Vars.push_back((VD || CurContext->isDependentContext()) 8073 ? RefExpr->IgnoreParens() 8074 : Ref); 8075 PrivateCopies.push_back(VDPrivateRefExpr); 8076 Inits.push_back(VDInitRefExpr); 8077 } 8078 8079 if (Vars.empty()) 8080 return nullptr; 8081 8082 return OMPFirstprivateClause::Create(Context, StartLoc, LParenLoc, EndLoc, 8083 Vars, PrivateCopies, Inits, 8084 buildPreInits(Context, ExprCaptures)); 8085 } 8086 8087 OMPClause *Sema::ActOnOpenMPLastprivateClause(ArrayRef<Expr *> VarList, 8088 SourceLocation StartLoc, 8089 SourceLocation LParenLoc, 8090 SourceLocation EndLoc) { 8091 SmallVector<Expr *, 8> Vars; 8092 SmallVector<Expr *, 8> SrcExprs; 8093 SmallVector<Expr *, 8> DstExprs; 8094 SmallVector<Expr *, 8> AssignmentOps; 8095 SmallVector<Decl *, 4> ExprCaptures; 8096 SmallVector<Expr *, 4> ExprPostUpdates; 8097 for (auto &RefExpr : VarList) { 8098 assert(RefExpr && "NULL expr in OpenMP lastprivate clause."); 8099 SourceLocation ELoc; 8100 SourceRange ERange; 8101 Expr *SimpleRefExpr = RefExpr; 8102 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange); 8103 if (Res.second) { 8104 // It will be analyzed later. 8105 Vars.push_back(RefExpr); 8106 SrcExprs.push_back(nullptr); 8107 DstExprs.push_back(nullptr); 8108 AssignmentOps.push_back(nullptr); 8109 } 8110 ValueDecl *D = Res.first; 8111 if (!D) 8112 continue; 8113 8114 QualType Type = D->getType(); 8115 auto *VD = dyn_cast<VarDecl>(D); 8116 8117 // OpenMP [2.14.3.5, Restrictions, C/C++, p.2] 8118 // A variable that appears in a lastprivate clause must not have an 8119 // incomplete type or a reference type. 8120 if (RequireCompleteType(ELoc, Type, 8121 diag::err_omp_lastprivate_incomplete_type)) 8122 continue; 8123 Type = Type.getNonReferenceType(); 8124 8125 // OpenMP [2.14.1.1, Data-sharing Attribute Rules for Variables Referenced 8126 // in a Construct] 8127 // Variables with the predetermined data-sharing attributes may not be 8128 // listed in data-sharing attributes clauses, except for the cases 8129 // listed below. 8130 DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, false); 8131 if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_lastprivate && 8132 DVar.CKind != OMPC_firstprivate && 8133 (DVar.CKind != OMPC_private || DVar.RefExpr != nullptr)) { 8134 Diag(ELoc, diag::err_omp_wrong_dsa) 8135 << getOpenMPClauseName(DVar.CKind) 8136 << getOpenMPClauseName(OMPC_lastprivate); 8137 ReportOriginalDSA(*this, DSAStack, D, DVar); 8138 continue; 8139 } 8140 8141 OpenMPDirectiveKind CurrDir = DSAStack->getCurrentDirective(); 8142 // OpenMP [2.14.3.5, Restrictions, p.2] 8143 // A list item that is private within a parallel region, or that appears in 8144 // the reduction clause of a parallel construct, must not appear in a 8145 // lastprivate clause on a worksharing construct if any of the corresponding 8146 // worksharing regions ever binds to any of the corresponding parallel 8147 // regions. 8148 DSAStackTy::DSAVarData TopDVar = DVar; 8149 if (isOpenMPWorksharingDirective(CurrDir) && 8150 !isOpenMPParallelDirective(CurrDir) && 8151 !isOpenMPTeamsDirective(CurrDir)) { 8152 DVar = DSAStack->getImplicitDSA(D, true); 8153 if (DVar.CKind != OMPC_shared) { 8154 Diag(ELoc, diag::err_omp_required_access) 8155 << getOpenMPClauseName(OMPC_lastprivate) 8156 << getOpenMPClauseName(OMPC_shared); 8157 ReportOriginalDSA(*this, DSAStack, D, DVar); 8158 continue; 8159 } 8160 } 8161 8162 // OpenMP 4.5 [2.10.8, Distribute Construct, p.3] 8163 // A list item may appear in a firstprivate or lastprivate clause but not 8164 // both. 8165 if (CurrDir == OMPD_distribute) { 8166 DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, false); 8167 if (DVar.CKind == OMPC_firstprivate) { 8168 Diag(ELoc, diag::err_omp_firstprivate_and_lastprivate_in_distribute); 8169 ReportOriginalDSA(*this, DSAStack, D, DVar); 8170 continue; 8171 } 8172 } 8173 8174 // OpenMP [2.14.3.5, Restrictions, C++, p.1,2] 8175 // A variable of class type (or array thereof) that appears in a 8176 // lastprivate clause requires an accessible, unambiguous default 8177 // constructor for the class type, unless the list item is also specified 8178 // in a firstprivate clause. 8179 // A variable of class type (or array thereof) that appears in a 8180 // lastprivate clause requires an accessible, unambiguous copy assignment 8181 // operator for the class type. 8182 Type = Context.getBaseElementType(Type).getNonReferenceType(); 8183 auto *SrcVD = buildVarDecl(*this, ERange.getBegin(), 8184 Type.getUnqualifiedType(), ".lastprivate.src", 8185 D->hasAttrs() ? &D->getAttrs() : nullptr); 8186 auto *PseudoSrcExpr = 8187 buildDeclRefExpr(*this, SrcVD, Type.getUnqualifiedType(), ELoc); 8188 auto *DstVD = 8189 buildVarDecl(*this, ERange.getBegin(), Type, ".lastprivate.dst", 8190 D->hasAttrs() ? &D->getAttrs() : nullptr); 8191 auto *PseudoDstExpr = buildDeclRefExpr(*this, DstVD, Type, ELoc); 8192 // For arrays generate assignment operation for single element and replace 8193 // it by the original array element in CodeGen. 8194 auto AssignmentOp = BuildBinOp(/*S=*/nullptr, ELoc, BO_Assign, 8195 PseudoDstExpr, PseudoSrcExpr); 8196 if (AssignmentOp.isInvalid()) 8197 continue; 8198 AssignmentOp = ActOnFinishFullExpr(AssignmentOp.get(), ELoc, 8199 /*DiscardedValue=*/true); 8200 if (AssignmentOp.isInvalid()) 8201 continue; 8202 8203 DeclRefExpr *Ref = nullptr; 8204 if (!VD && !CurContext->isDependentContext()) { 8205 if (TopDVar.CKind == OMPC_firstprivate) 8206 Ref = TopDVar.PrivateCopy; 8207 else { 8208 Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/false); 8209 if (!IsOpenMPCapturedDecl(D)) 8210 ExprCaptures.push_back(Ref->getDecl()); 8211 } 8212 if (TopDVar.CKind == OMPC_firstprivate || 8213 (!IsOpenMPCapturedDecl(D) && 8214 Ref->getDecl()->hasAttr<OMPCaptureNoInitAttr>())) { 8215 ExprResult RefRes = DefaultLvalueConversion(Ref); 8216 if (!RefRes.isUsable()) 8217 continue; 8218 ExprResult PostUpdateRes = 8219 BuildBinOp(DSAStack->getCurScope(), ELoc, BO_Assign, SimpleRefExpr, 8220 RefRes.get()); 8221 if (!PostUpdateRes.isUsable()) 8222 continue; 8223 ExprPostUpdates.push_back( 8224 IgnoredValueConversions(PostUpdateRes.get()).get()); 8225 } 8226 } 8227 DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_lastprivate, Ref); 8228 Vars.push_back((VD || CurContext->isDependentContext()) 8229 ? RefExpr->IgnoreParens() 8230 : Ref); 8231 SrcExprs.push_back(PseudoSrcExpr); 8232 DstExprs.push_back(PseudoDstExpr); 8233 AssignmentOps.push_back(AssignmentOp.get()); 8234 } 8235 8236 if (Vars.empty()) 8237 return nullptr; 8238 8239 return OMPLastprivateClause::Create(Context, StartLoc, LParenLoc, EndLoc, 8240 Vars, SrcExprs, DstExprs, AssignmentOps, 8241 buildPreInits(Context, ExprCaptures), 8242 buildPostUpdate(*this, ExprPostUpdates)); 8243 } 8244 8245 OMPClause *Sema::ActOnOpenMPSharedClause(ArrayRef<Expr *> VarList, 8246 SourceLocation StartLoc, 8247 SourceLocation LParenLoc, 8248 SourceLocation EndLoc) { 8249 SmallVector<Expr *, 8> Vars; 8250 for (auto &RefExpr : VarList) { 8251 assert(RefExpr && "NULL expr in OpenMP lastprivate clause."); 8252 SourceLocation ELoc; 8253 SourceRange ERange; 8254 Expr *SimpleRefExpr = RefExpr; 8255 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange); 8256 if (Res.second) { 8257 // It will be analyzed later. 8258 Vars.push_back(RefExpr); 8259 } 8260 ValueDecl *D = Res.first; 8261 if (!D) 8262 continue; 8263 8264 auto *VD = dyn_cast<VarDecl>(D); 8265 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced 8266 // in a Construct] 8267 // Variables with the predetermined data-sharing attributes may not be 8268 // listed in data-sharing attributes clauses, except for the cases 8269 // listed below. For these exceptions only, listing a predetermined 8270 // variable in a data-sharing attribute clause is allowed and overrides 8271 // the variable's predetermined data-sharing attributes. 8272 DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, false); 8273 if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_shared && 8274 DVar.RefExpr) { 8275 Diag(ELoc, diag::err_omp_wrong_dsa) << getOpenMPClauseName(DVar.CKind) 8276 << getOpenMPClauseName(OMPC_shared); 8277 ReportOriginalDSA(*this, DSAStack, D, DVar); 8278 continue; 8279 } 8280 8281 DeclRefExpr *Ref = nullptr; 8282 if (!VD && IsOpenMPCapturedDecl(D) && !CurContext->isDependentContext()) 8283 Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/true); 8284 DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_shared, Ref); 8285 Vars.push_back((VD || !Ref || CurContext->isDependentContext()) 8286 ? RefExpr->IgnoreParens() 8287 : Ref); 8288 } 8289 8290 if (Vars.empty()) 8291 return nullptr; 8292 8293 return OMPSharedClause::Create(Context, StartLoc, LParenLoc, EndLoc, Vars); 8294 } 8295 8296 namespace { 8297 class DSARefChecker : public StmtVisitor<DSARefChecker, bool> { 8298 DSAStackTy *Stack; 8299 8300 public: 8301 bool VisitDeclRefExpr(DeclRefExpr *E) { 8302 if (VarDecl *VD = dyn_cast<VarDecl>(E->getDecl())) { 8303 DSAStackTy::DSAVarData DVar = Stack->getTopDSA(VD, false); 8304 if (DVar.CKind == OMPC_shared && !DVar.RefExpr) 8305 return false; 8306 if (DVar.CKind != OMPC_unknown) 8307 return true; 8308 DSAStackTy::DSAVarData DVarPrivate = Stack->hasDSA( 8309 VD, isOpenMPPrivate, [](OpenMPDirectiveKind) -> bool { return true; }, 8310 false); 8311 if (DVarPrivate.CKind != OMPC_unknown) 8312 return true; 8313 return false; 8314 } 8315 return false; 8316 } 8317 bool VisitStmt(Stmt *S) { 8318 for (auto Child : S->children()) { 8319 if (Child && Visit(Child)) 8320 return true; 8321 } 8322 return false; 8323 } 8324 explicit DSARefChecker(DSAStackTy *S) : Stack(S) {} 8325 }; 8326 } // namespace 8327 8328 namespace { 8329 // Transform MemberExpression for specified FieldDecl of current class to 8330 // DeclRefExpr to specified OMPCapturedExprDecl. 8331 class TransformExprToCaptures : public TreeTransform<TransformExprToCaptures> { 8332 typedef TreeTransform<TransformExprToCaptures> BaseTransform; 8333 ValueDecl *Field; 8334 DeclRefExpr *CapturedExpr; 8335 8336 public: 8337 TransformExprToCaptures(Sema &SemaRef, ValueDecl *FieldDecl) 8338 : BaseTransform(SemaRef), Field(FieldDecl), CapturedExpr(nullptr) {} 8339 8340 ExprResult TransformMemberExpr(MemberExpr *E) { 8341 if (isa<CXXThisExpr>(E->getBase()->IgnoreParenImpCasts()) && 8342 E->getMemberDecl() == Field) { 8343 CapturedExpr = buildCapture(SemaRef, Field, E, /*WithInit=*/false); 8344 return CapturedExpr; 8345 } 8346 return BaseTransform::TransformMemberExpr(E); 8347 } 8348 DeclRefExpr *getCapturedExpr() { return CapturedExpr; } 8349 }; 8350 } // namespace 8351 8352 template <typename T> 8353 static T filterLookupForUDR(SmallVectorImpl<UnresolvedSet<8>> &Lookups, 8354 const llvm::function_ref<T(ValueDecl *)> &Gen) { 8355 for (auto &Set : Lookups) { 8356 for (auto *D : Set) { 8357 if (auto Res = Gen(cast<ValueDecl>(D))) 8358 return Res; 8359 } 8360 } 8361 return T(); 8362 } 8363 8364 static ExprResult 8365 buildDeclareReductionRef(Sema &SemaRef, SourceLocation Loc, SourceRange Range, 8366 Scope *S, CXXScopeSpec &ReductionIdScopeSpec, 8367 const DeclarationNameInfo &ReductionId, QualType Ty, 8368 CXXCastPath &BasePath, Expr *UnresolvedReduction) { 8369 if (ReductionIdScopeSpec.isInvalid()) 8370 return ExprError(); 8371 SmallVector<UnresolvedSet<8>, 4> Lookups; 8372 if (S) { 8373 LookupResult Lookup(SemaRef, ReductionId, Sema::LookupOMPReductionName); 8374 Lookup.suppressDiagnostics(); 8375 while (S && SemaRef.LookupParsedName(Lookup, S, &ReductionIdScopeSpec)) { 8376 auto *D = Lookup.getRepresentativeDecl(); 8377 do { 8378 S = S->getParent(); 8379 } while (S && !S->isDeclScope(D)); 8380 if (S) 8381 S = S->getParent(); 8382 Lookups.push_back(UnresolvedSet<8>()); 8383 Lookups.back().append(Lookup.begin(), Lookup.end()); 8384 Lookup.clear(); 8385 } 8386 } else if (auto *ULE = 8387 cast_or_null<UnresolvedLookupExpr>(UnresolvedReduction)) { 8388 Lookups.push_back(UnresolvedSet<8>()); 8389 Decl *PrevD = nullptr; 8390 for (auto *D : ULE->decls()) { 8391 if (D == PrevD) 8392 Lookups.push_back(UnresolvedSet<8>()); 8393 else if (auto *DRD = cast<OMPDeclareReductionDecl>(D)) 8394 Lookups.back().addDecl(DRD); 8395 PrevD = D; 8396 } 8397 } 8398 if (Ty->isDependentType() || Ty->isInstantiationDependentType() || 8399 Ty->containsUnexpandedParameterPack() || 8400 filterLookupForUDR<bool>(Lookups, [](ValueDecl *D) -> bool { 8401 return !D->isInvalidDecl() && 8402 (D->getType()->isDependentType() || 8403 D->getType()->isInstantiationDependentType() || 8404 D->getType()->containsUnexpandedParameterPack()); 8405 })) { 8406 UnresolvedSet<8> ResSet; 8407 for (auto &Set : Lookups) { 8408 ResSet.append(Set.begin(), Set.end()); 8409 // The last item marks the end of all declarations at the specified scope. 8410 ResSet.addDecl(Set[Set.size() - 1]); 8411 } 8412 return UnresolvedLookupExpr::Create( 8413 SemaRef.Context, /*NamingClass=*/nullptr, 8414 ReductionIdScopeSpec.getWithLocInContext(SemaRef.Context), ReductionId, 8415 /*ADL=*/true, /*Overloaded=*/true, ResSet.begin(), ResSet.end()); 8416 } 8417 if (auto *VD = filterLookupForUDR<ValueDecl *>( 8418 Lookups, [&SemaRef, Ty](ValueDecl *D) -> ValueDecl * { 8419 if (!D->isInvalidDecl() && 8420 SemaRef.Context.hasSameType(D->getType(), Ty)) 8421 return D; 8422 return nullptr; 8423 })) 8424 return SemaRef.BuildDeclRefExpr(VD, Ty, VK_LValue, Loc); 8425 if (auto *VD = filterLookupForUDR<ValueDecl *>( 8426 Lookups, [&SemaRef, Ty, Loc](ValueDecl *D) -> ValueDecl * { 8427 if (!D->isInvalidDecl() && 8428 SemaRef.IsDerivedFrom(Loc, Ty, D->getType()) && 8429 !Ty.isMoreQualifiedThan(D->getType())) 8430 return D; 8431 return nullptr; 8432 })) { 8433 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true, 8434 /*DetectVirtual=*/false); 8435 if (SemaRef.IsDerivedFrom(Loc, Ty, VD->getType(), Paths)) { 8436 if (!Paths.isAmbiguous(SemaRef.Context.getCanonicalType( 8437 VD->getType().getUnqualifiedType()))) { 8438 if (SemaRef.CheckBaseClassAccess(Loc, VD->getType(), Ty, Paths.front(), 8439 /*DiagID=*/0) != 8440 Sema::AR_inaccessible) { 8441 SemaRef.BuildBasePathArray(Paths, BasePath); 8442 return SemaRef.BuildDeclRefExpr(VD, Ty, VK_LValue, Loc); 8443 } 8444 } 8445 } 8446 } 8447 if (ReductionIdScopeSpec.isSet()) { 8448 SemaRef.Diag(Loc, diag::err_omp_not_resolved_reduction_identifier) << Range; 8449 return ExprError(); 8450 } 8451 return ExprEmpty(); 8452 } 8453 8454 OMPClause *Sema::ActOnOpenMPReductionClause( 8455 ArrayRef<Expr *> VarList, SourceLocation StartLoc, SourceLocation LParenLoc, 8456 SourceLocation ColonLoc, SourceLocation EndLoc, 8457 CXXScopeSpec &ReductionIdScopeSpec, const DeclarationNameInfo &ReductionId, 8458 ArrayRef<Expr *> UnresolvedReductions) { 8459 auto DN = ReductionId.getName(); 8460 auto OOK = DN.getCXXOverloadedOperator(); 8461 BinaryOperatorKind BOK = BO_Comma; 8462 8463 // OpenMP [2.14.3.6, reduction clause] 8464 // C 8465 // reduction-identifier is either an identifier or one of the following 8466 // operators: +, -, *, &, |, ^, && and || 8467 // C++ 8468 // reduction-identifier is either an id-expression or one of the following 8469 // operators: +, -, *, &, |, ^, && and || 8470 // FIXME: Only 'min' and 'max' identifiers are supported for now. 8471 switch (OOK) { 8472 case OO_Plus: 8473 case OO_Minus: 8474 BOK = BO_Add; 8475 break; 8476 case OO_Star: 8477 BOK = BO_Mul; 8478 break; 8479 case OO_Amp: 8480 BOK = BO_And; 8481 break; 8482 case OO_Pipe: 8483 BOK = BO_Or; 8484 break; 8485 case OO_Caret: 8486 BOK = BO_Xor; 8487 break; 8488 case OO_AmpAmp: 8489 BOK = BO_LAnd; 8490 break; 8491 case OO_PipePipe: 8492 BOK = BO_LOr; 8493 break; 8494 case OO_New: 8495 case OO_Delete: 8496 case OO_Array_New: 8497 case OO_Array_Delete: 8498 case OO_Slash: 8499 case OO_Percent: 8500 case OO_Tilde: 8501 case OO_Exclaim: 8502 case OO_Equal: 8503 case OO_Less: 8504 case OO_Greater: 8505 case OO_LessEqual: 8506 case OO_GreaterEqual: 8507 case OO_PlusEqual: 8508 case OO_MinusEqual: 8509 case OO_StarEqual: 8510 case OO_SlashEqual: 8511 case OO_PercentEqual: 8512 case OO_CaretEqual: 8513 case OO_AmpEqual: 8514 case OO_PipeEqual: 8515 case OO_LessLess: 8516 case OO_GreaterGreater: 8517 case OO_LessLessEqual: 8518 case OO_GreaterGreaterEqual: 8519 case OO_EqualEqual: 8520 case OO_ExclaimEqual: 8521 case OO_PlusPlus: 8522 case OO_MinusMinus: 8523 case OO_Comma: 8524 case OO_ArrowStar: 8525 case OO_Arrow: 8526 case OO_Call: 8527 case OO_Subscript: 8528 case OO_Conditional: 8529 case OO_Coawait: 8530 case NUM_OVERLOADED_OPERATORS: 8531 llvm_unreachable("Unexpected reduction identifier"); 8532 case OO_None: 8533 if (auto II = DN.getAsIdentifierInfo()) { 8534 if (II->isStr("max")) 8535 BOK = BO_GT; 8536 else if (II->isStr("min")) 8537 BOK = BO_LT; 8538 } 8539 break; 8540 } 8541 SourceRange ReductionIdRange; 8542 if (ReductionIdScopeSpec.isValid()) 8543 ReductionIdRange.setBegin(ReductionIdScopeSpec.getBeginLoc()); 8544 ReductionIdRange.setEnd(ReductionId.getEndLoc()); 8545 8546 SmallVector<Expr *, 8> Vars; 8547 SmallVector<Expr *, 8> Privates; 8548 SmallVector<Expr *, 8> LHSs; 8549 SmallVector<Expr *, 8> RHSs; 8550 SmallVector<Expr *, 8> ReductionOps; 8551 SmallVector<Decl *, 4> ExprCaptures; 8552 SmallVector<Expr *, 4> ExprPostUpdates; 8553 auto IR = UnresolvedReductions.begin(), ER = UnresolvedReductions.end(); 8554 bool FirstIter = true; 8555 for (auto RefExpr : VarList) { 8556 assert(RefExpr && "nullptr expr in OpenMP reduction clause."); 8557 // OpenMP [2.1, C/C++] 8558 // A list item is a variable or array section, subject to the restrictions 8559 // specified in Section 2.4 on page 42 and in each of the sections 8560 // describing clauses and directives for which a list appears. 8561 // OpenMP [2.14.3.3, Restrictions, p.1] 8562 // A variable that is part of another variable (as an array or 8563 // structure element) cannot appear in a private clause. 8564 if (!FirstIter && IR != ER) 8565 ++IR; 8566 FirstIter = false; 8567 SourceLocation ELoc; 8568 SourceRange ERange; 8569 Expr *SimpleRefExpr = RefExpr; 8570 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange, 8571 /*AllowArraySection=*/true); 8572 if (Res.second) { 8573 // It will be analyzed later. 8574 Vars.push_back(RefExpr); 8575 Privates.push_back(nullptr); 8576 LHSs.push_back(nullptr); 8577 RHSs.push_back(nullptr); 8578 // Try to find 'declare reduction' corresponding construct before using 8579 // builtin/overloaded operators. 8580 QualType Type = Context.DependentTy; 8581 CXXCastPath BasePath; 8582 ExprResult DeclareReductionRef = buildDeclareReductionRef( 8583 *this, ELoc, ERange, DSAStack->getCurScope(), ReductionIdScopeSpec, 8584 ReductionId, Type, BasePath, IR == ER ? nullptr : *IR); 8585 if (CurContext->isDependentContext() && 8586 (DeclareReductionRef.isUnset() || 8587 isa<UnresolvedLookupExpr>(DeclareReductionRef.get()))) 8588 ReductionOps.push_back(DeclareReductionRef.get()); 8589 else 8590 ReductionOps.push_back(nullptr); 8591 } 8592 ValueDecl *D = Res.first; 8593 if (!D) 8594 continue; 8595 8596 QualType Type; 8597 auto *ASE = dyn_cast<ArraySubscriptExpr>(RefExpr->IgnoreParens()); 8598 auto *OASE = dyn_cast<OMPArraySectionExpr>(RefExpr->IgnoreParens()); 8599 if (ASE) 8600 Type = ASE->getType().getNonReferenceType(); 8601 else if (OASE) { 8602 auto BaseType = OMPArraySectionExpr::getBaseOriginalType(OASE->getBase()); 8603 if (auto *ATy = BaseType->getAsArrayTypeUnsafe()) 8604 Type = ATy->getElementType(); 8605 else 8606 Type = BaseType->getPointeeType(); 8607 Type = Type.getNonReferenceType(); 8608 } else 8609 Type = Context.getBaseElementType(D->getType().getNonReferenceType()); 8610 auto *VD = dyn_cast<VarDecl>(D); 8611 8612 // OpenMP [2.9.3.3, Restrictions, C/C++, p.3] 8613 // A variable that appears in a private clause must not have an incomplete 8614 // type or a reference type. 8615 if (RequireCompleteType(ELoc, Type, 8616 diag::err_omp_reduction_incomplete_type)) 8617 continue; 8618 // OpenMP [2.14.3.6, reduction clause, Restrictions] 8619 // A list item that appears in a reduction clause must not be 8620 // const-qualified. 8621 if (Type.getNonReferenceType().isConstant(Context)) { 8622 Diag(ELoc, diag::err_omp_const_reduction_list_item) 8623 << getOpenMPClauseName(OMPC_reduction) << Type << ERange; 8624 if (!ASE && !OASE) { 8625 bool IsDecl = !VD || 8626 VD->isThisDeclarationADefinition(Context) == 8627 VarDecl::DeclarationOnly; 8628 Diag(D->getLocation(), 8629 IsDecl ? diag::note_previous_decl : diag::note_defined_here) 8630 << D; 8631 } 8632 continue; 8633 } 8634 // OpenMP [2.9.3.6, Restrictions, C/C++, p.4] 8635 // If a list-item is a reference type then it must bind to the same object 8636 // for all threads of the team. 8637 if (!ASE && !OASE && VD) { 8638 VarDecl *VDDef = VD->getDefinition(); 8639 if (VD->getType()->isReferenceType() && VDDef && VDDef->hasInit()) { 8640 DSARefChecker Check(DSAStack); 8641 if (Check.Visit(VDDef->getInit())) { 8642 Diag(ELoc, diag::err_omp_reduction_ref_type_arg) << ERange; 8643 Diag(VDDef->getLocation(), diag::note_defined_here) << VDDef; 8644 continue; 8645 } 8646 } 8647 } 8648 8649 // OpenMP [2.14.1.1, Data-sharing Attribute Rules for Variables Referenced 8650 // in a Construct] 8651 // Variables with the predetermined data-sharing attributes may not be 8652 // listed in data-sharing attributes clauses, except for the cases 8653 // listed below. For these exceptions only, listing a predetermined 8654 // variable in a data-sharing attribute clause is allowed and overrides 8655 // the variable's predetermined data-sharing attributes. 8656 // OpenMP [2.14.3.6, Restrictions, p.3] 8657 // Any number of reduction clauses can be specified on the directive, 8658 // but a list item can appear only once in the reduction clauses for that 8659 // directive. 8660 DSAStackTy::DSAVarData DVar; 8661 DVar = DSAStack->getTopDSA(D, false); 8662 if (DVar.CKind == OMPC_reduction) { 8663 Diag(ELoc, diag::err_omp_once_referenced) 8664 << getOpenMPClauseName(OMPC_reduction); 8665 if (DVar.RefExpr) 8666 Diag(DVar.RefExpr->getExprLoc(), diag::note_omp_referenced); 8667 } else if (DVar.CKind != OMPC_unknown) { 8668 Diag(ELoc, diag::err_omp_wrong_dsa) 8669 << getOpenMPClauseName(DVar.CKind) 8670 << getOpenMPClauseName(OMPC_reduction); 8671 ReportOriginalDSA(*this, DSAStack, D, DVar); 8672 continue; 8673 } 8674 8675 // OpenMP [2.14.3.6, Restrictions, p.1] 8676 // A list item that appears in a reduction clause of a worksharing 8677 // construct must be shared in the parallel regions to which any of the 8678 // worksharing regions arising from the worksharing construct bind. 8679 OpenMPDirectiveKind CurrDir = DSAStack->getCurrentDirective(); 8680 if (isOpenMPWorksharingDirective(CurrDir) && 8681 !isOpenMPParallelDirective(CurrDir) && 8682 !isOpenMPTeamsDirective(CurrDir)) { 8683 DVar = DSAStack->getImplicitDSA(D, true); 8684 if (DVar.CKind != OMPC_shared) { 8685 Diag(ELoc, diag::err_omp_required_access) 8686 << getOpenMPClauseName(OMPC_reduction) 8687 << getOpenMPClauseName(OMPC_shared); 8688 ReportOriginalDSA(*this, DSAStack, D, DVar); 8689 continue; 8690 } 8691 } 8692 8693 // Try to find 'declare reduction' corresponding construct before using 8694 // builtin/overloaded operators. 8695 CXXCastPath BasePath; 8696 ExprResult DeclareReductionRef = buildDeclareReductionRef( 8697 *this, ELoc, ERange, DSAStack->getCurScope(), ReductionIdScopeSpec, 8698 ReductionId, Type, BasePath, IR == ER ? nullptr : *IR); 8699 if (DeclareReductionRef.isInvalid()) 8700 continue; 8701 if (CurContext->isDependentContext() && 8702 (DeclareReductionRef.isUnset() || 8703 isa<UnresolvedLookupExpr>(DeclareReductionRef.get()))) { 8704 Vars.push_back(RefExpr); 8705 Privates.push_back(nullptr); 8706 LHSs.push_back(nullptr); 8707 RHSs.push_back(nullptr); 8708 ReductionOps.push_back(DeclareReductionRef.get()); 8709 continue; 8710 } 8711 if (BOK == BO_Comma && DeclareReductionRef.isUnset()) { 8712 // Not allowed reduction identifier is found. 8713 Diag(ReductionId.getLocStart(), 8714 diag::err_omp_unknown_reduction_identifier) 8715 << Type << ReductionIdRange; 8716 continue; 8717 } 8718 8719 // OpenMP [2.14.3.6, reduction clause, Restrictions] 8720 // The type of a list item that appears in a reduction clause must be valid 8721 // for the reduction-identifier. For a max or min reduction in C, the type 8722 // of the list item must be an allowed arithmetic data type: char, int, 8723 // float, double, or _Bool, possibly modified with long, short, signed, or 8724 // unsigned. For a max or min reduction in C++, the type of the list item 8725 // must be an allowed arithmetic data type: char, wchar_t, int, float, 8726 // double, or bool, possibly modified with long, short, signed, or unsigned. 8727 if (DeclareReductionRef.isUnset()) { 8728 if ((BOK == BO_GT || BOK == BO_LT) && 8729 !(Type->isScalarType() || 8730 (getLangOpts().CPlusPlus && Type->isArithmeticType()))) { 8731 Diag(ELoc, diag::err_omp_clause_not_arithmetic_type_arg) 8732 << getLangOpts().CPlusPlus; 8733 if (!ASE && !OASE) { 8734 bool IsDecl = !VD || 8735 VD->isThisDeclarationADefinition(Context) == 8736 VarDecl::DeclarationOnly; 8737 Diag(D->getLocation(), 8738 IsDecl ? diag::note_previous_decl : diag::note_defined_here) 8739 << D; 8740 } 8741 continue; 8742 } 8743 if ((BOK == BO_OrAssign || BOK == BO_AndAssign || BOK == BO_XorAssign) && 8744 !getLangOpts().CPlusPlus && Type->isFloatingType()) { 8745 Diag(ELoc, diag::err_omp_clause_floating_type_arg); 8746 if (!ASE && !OASE) { 8747 bool IsDecl = !VD || 8748 VD->isThisDeclarationADefinition(Context) == 8749 VarDecl::DeclarationOnly; 8750 Diag(D->getLocation(), 8751 IsDecl ? diag::note_previous_decl : diag::note_defined_here) 8752 << D; 8753 } 8754 continue; 8755 } 8756 } 8757 8758 Type = Type.getNonLValueExprType(Context).getUnqualifiedType(); 8759 auto *LHSVD = buildVarDecl(*this, ELoc, Type, ".reduction.lhs", 8760 D->hasAttrs() ? &D->getAttrs() : nullptr); 8761 auto *RHSVD = buildVarDecl(*this, ELoc, Type, D->getName(), 8762 D->hasAttrs() ? &D->getAttrs() : nullptr); 8763 auto PrivateTy = Type; 8764 if (OASE || 8765 (!ASE && 8766 D->getType().getNonReferenceType()->isVariablyModifiedType())) { 8767 // For arrays/array sections only: 8768 // Create pseudo array type for private copy. The size for this array will 8769 // be generated during codegen. 8770 // For array subscripts or single variables Private Ty is the same as Type 8771 // (type of the variable or single array element). 8772 PrivateTy = Context.getVariableArrayType( 8773 Type, new (Context) OpaqueValueExpr(SourceLocation(), 8774 Context.getSizeType(), VK_RValue), 8775 ArrayType::Normal, /*IndexTypeQuals=*/0, SourceRange()); 8776 } else if (!ASE && !OASE && 8777 Context.getAsArrayType(D->getType().getNonReferenceType())) 8778 PrivateTy = D->getType().getNonReferenceType(); 8779 // Private copy. 8780 auto *PrivateVD = buildVarDecl(*this, ELoc, PrivateTy, D->getName(), 8781 D->hasAttrs() ? &D->getAttrs() : nullptr); 8782 // Add initializer for private variable. 8783 Expr *Init = nullptr; 8784 auto *LHSDRE = buildDeclRefExpr(*this, LHSVD, Type, ELoc); 8785 auto *RHSDRE = buildDeclRefExpr(*this, RHSVD, Type, ELoc); 8786 if (DeclareReductionRef.isUsable()) { 8787 auto *DRDRef = DeclareReductionRef.getAs<DeclRefExpr>(); 8788 auto *DRD = cast<OMPDeclareReductionDecl>(DRDRef->getDecl()); 8789 if (DRD->getInitializer()) { 8790 Init = DRDRef; 8791 RHSVD->setInit(DRDRef); 8792 RHSVD->setInitStyle(VarDecl::CallInit); 8793 } 8794 } else { 8795 switch (BOK) { 8796 case BO_Add: 8797 case BO_Xor: 8798 case BO_Or: 8799 case BO_LOr: 8800 // '+', '-', '^', '|', '||' reduction ops - initializer is '0'. 8801 if (Type->isScalarType() || Type->isAnyComplexType()) 8802 Init = ActOnIntegerConstant(ELoc, /*Val=*/0).get(); 8803 break; 8804 case BO_Mul: 8805 case BO_LAnd: 8806 if (Type->isScalarType() || Type->isAnyComplexType()) { 8807 // '*' and '&&' reduction ops - initializer is '1'. 8808 Init = ActOnIntegerConstant(ELoc, /*Val=*/1).get(); 8809 } 8810 break; 8811 case BO_And: { 8812 // '&' reduction op - initializer is '~0'. 8813 QualType OrigType = Type; 8814 if (auto *ComplexTy = OrigType->getAs<ComplexType>()) 8815 Type = ComplexTy->getElementType(); 8816 if (Type->isRealFloatingType()) { 8817 llvm::APFloat InitValue = 8818 llvm::APFloat::getAllOnesValue(Context.getTypeSize(Type), 8819 /*isIEEE=*/true); 8820 Init = FloatingLiteral::Create(Context, InitValue, /*isexact=*/true, 8821 Type, ELoc); 8822 } else if (Type->isScalarType()) { 8823 auto Size = Context.getTypeSize(Type); 8824 QualType IntTy = Context.getIntTypeForBitwidth(Size, /*Signed=*/0); 8825 llvm::APInt InitValue = llvm::APInt::getAllOnesValue(Size); 8826 Init = IntegerLiteral::Create(Context, InitValue, IntTy, ELoc); 8827 } 8828 if (Init && OrigType->isAnyComplexType()) { 8829 // Init = 0xFFFF + 0xFFFFi; 8830 auto *Im = new (Context) ImaginaryLiteral(Init, OrigType); 8831 Init = CreateBuiltinBinOp(ELoc, BO_Add, Init, Im).get(); 8832 } 8833 Type = OrigType; 8834 break; 8835 } 8836 case BO_LT: 8837 case BO_GT: { 8838 // 'min' reduction op - initializer is 'Largest representable number in 8839 // the reduction list item type'. 8840 // 'max' reduction op - initializer is 'Least representable number in 8841 // the reduction list item type'. 8842 if (Type->isIntegerType() || Type->isPointerType()) { 8843 bool IsSigned = Type->hasSignedIntegerRepresentation(); 8844 auto Size = Context.getTypeSize(Type); 8845 QualType IntTy = 8846 Context.getIntTypeForBitwidth(Size, /*Signed=*/IsSigned); 8847 llvm::APInt InitValue = 8848 (BOK != BO_LT) 8849 ? IsSigned ? llvm::APInt::getSignedMinValue(Size) 8850 : llvm::APInt::getMinValue(Size) 8851 : IsSigned ? llvm::APInt::getSignedMaxValue(Size) 8852 : llvm::APInt::getMaxValue(Size); 8853 Init = IntegerLiteral::Create(Context, InitValue, IntTy, ELoc); 8854 if (Type->isPointerType()) { 8855 // Cast to pointer type. 8856 auto CastExpr = BuildCStyleCastExpr( 8857 SourceLocation(), Context.getTrivialTypeSourceInfo(Type, ELoc), 8858 SourceLocation(), Init); 8859 if (CastExpr.isInvalid()) 8860 continue; 8861 Init = CastExpr.get(); 8862 } 8863 } else if (Type->isRealFloatingType()) { 8864 llvm::APFloat InitValue = llvm::APFloat::getLargest( 8865 Context.getFloatTypeSemantics(Type), BOK != BO_LT); 8866 Init = FloatingLiteral::Create(Context, InitValue, /*isexact=*/true, 8867 Type, ELoc); 8868 } 8869 break; 8870 } 8871 case BO_PtrMemD: 8872 case BO_PtrMemI: 8873 case BO_MulAssign: 8874 case BO_Div: 8875 case BO_Rem: 8876 case BO_Sub: 8877 case BO_Shl: 8878 case BO_Shr: 8879 case BO_LE: 8880 case BO_GE: 8881 case BO_EQ: 8882 case BO_NE: 8883 case BO_AndAssign: 8884 case BO_XorAssign: 8885 case BO_OrAssign: 8886 case BO_Assign: 8887 case BO_AddAssign: 8888 case BO_SubAssign: 8889 case BO_DivAssign: 8890 case BO_RemAssign: 8891 case BO_ShlAssign: 8892 case BO_ShrAssign: 8893 case BO_Comma: 8894 llvm_unreachable("Unexpected reduction operation"); 8895 } 8896 } 8897 if (Init && DeclareReductionRef.isUnset()) { 8898 AddInitializerToDecl(RHSVD, Init, /*DirectInit=*/false); 8899 } else if (!Init) 8900 ActOnUninitializedDecl(RHSVD); 8901 if (RHSVD->isInvalidDecl()) 8902 continue; 8903 if (!RHSVD->hasInit() && DeclareReductionRef.isUnset()) { 8904 Diag(ELoc, diag::err_omp_reduction_id_not_compatible) << Type 8905 << ReductionIdRange; 8906 bool IsDecl = 8907 !VD || 8908 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly; 8909 Diag(D->getLocation(), 8910 IsDecl ? diag::note_previous_decl : diag::note_defined_here) 8911 << D; 8912 continue; 8913 } 8914 // Store initializer for single element in private copy. Will be used during 8915 // codegen. 8916 PrivateVD->setInit(RHSVD->getInit()); 8917 PrivateVD->setInitStyle(RHSVD->getInitStyle()); 8918 auto *PrivateDRE = buildDeclRefExpr(*this, PrivateVD, PrivateTy, ELoc); 8919 ExprResult ReductionOp; 8920 if (DeclareReductionRef.isUsable()) { 8921 QualType RedTy = DeclareReductionRef.get()->getType(); 8922 QualType PtrRedTy = Context.getPointerType(RedTy); 8923 ExprResult LHS = CreateBuiltinUnaryOp(ELoc, UO_AddrOf, LHSDRE); 8924 ExprResult RHS = CreateBuiltinUnaryOp(ELoc, UO_AddrOf, RHSDRE); 8925 if (!BasePath.empty()) { 8926 LHS = DefaultLvalueConversion(LHS.get()); 8927 RHS = DefaultLvalueConversion(RHS.get()); 8928 LHS = ImplicitCastExpr::Create(Context, PtrRedTy, 8929 CK_UncheckedDerivedToBase, LHS.get(), 8930 &BasePath, LHS.get()->getValueKind()); 8931 RHS = ImplicitCastExpr::Create(Context, PtrRedTy, 8932 CK_UncheckedDerivedToBase, RHS.get(), 8933 &BasePath, RHS.get()->getValueKind()); 8934 } 8935 FunctionProtoType::ExtProtoInfo EPI; 8936 QualType Params[] = {PtrRedTy, PtrRedTy}; 8937 QualType FnTy = Context.getFunctionType(Context.VoidTy, Params, EPI); 8938 auto *OVE = new (Context) OpaqueValueExpr( 8939 ELoc, Context.getPointerType(FnTy), VK_RValue, OK_Ordinary, 8940 DefaultLvalueConversion(DeclareReductionRef.get()).get()); 8941 Expr *Args[] = {LHS.get(), RHS.get()}; 8942 ReductionOp = new (Context) 8943 CallExpr(Context, OVE, Args, Context.VoidTy, VK_RValue, ELoc); 8944 } else { 8945 ReductionOp = BuildBinOp(DSAStack->getCurScope(), 8946 ReductionId.getLocStart(), BOK, LHSDRE, RHSDRE); 8947 if (ReductionOp.isUsable()) { 8948 if (BOK != BO_LT && BOK != BO_GT) { 8949 ReductionOp = 8950 BuildBinOp(DSAStack->getCurScope(), ReductionId.getLocStart(), 8951 BO_Assign, LHSDRE, ReductionOp.get()); 8952 } else { 8953 auto *ConditionalOp = new (Context) ConditionalOperator( 8954 ReductionOp.get(), SourceLocation(), LHSDRE, SourceLocation(), 8955 RHSDRE, Type, VK_LValue, OK_Ordinary); 8956 ReductionOp = 8957 BuildBinOp(DSAStack->getCurScope(), ReductionId.getLocStart(), 8958 BO_Assign, LHSDRE, ConditionalOp); 8959 } 8960 ReductionOp = ActOnFinishFullExpr(ReductionOp.get()); 8961 } 8962 if (ReductionOp.isInvalid()) 8963 continue; 8964 } 8965 8966 DeclRefExpr *Ref = nullptr; 8967 Expr *VarsExpr = RefExpr->IgnoreParens(); 8968 if (!VD && !CurContext->isDependentContext()) { 8969 if (ASE || OASE) { 8970 TransformExprToCaptures RebuildToCapture(*this, D); 8971 VarsExpr = 8972 RebuildToCapture.TransformExpr(RefExpr->IgnoreParens()).get(); 8973 Ref = RebuildToCapture.getCapturedExpr(); 8974 } else { 8975 VarsExpr = Ref = 8976 buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/false); 8977 } 8978 if (!IsOpenMPCapturedDecl(D)) { 8979 ExprCaptures.push_back(Ref->getDecl()); 8980 if (Ref->getDecl()->hasAttr<OMPCaptureNoInitAttr>()) { 8981 ExprResult RefRes = DefaultLvalueConversion(Ref); 8982 if (!RefRes.isUsable()) 8983 continue; 8984 ExprResult PostUpdateRes = 8985 BuildBinOp(DSAStack->getCurScope(), ELoc, BO_Assign, 8986 SimpleRefExpr, RefRes.get()); 8987 if (!PostUpdateRes.isUsable()) 8988 continue; 8989 ExprPostUpdates.push_back( 8990 IgnoredValueConversions(PostUpdateRes.get()).get()); 8991 } 8992 } 8993 } 8994 DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_reduction, Ref); 8995 Vars.push_back(VarsExpr); 8996 Privates.push_back(PrivateDRE); 8997 LHSs.push_back(LHSDRE); 8998 RHSs.push_back(RHSDRE); 8999 ReductionOps.push_back(ReductionOp.get()); 9000 } 9001 9002 if (Vars.empty()) 9003 return nullptr; 9004 9005 return OMPReductionClause::Create( 9006 Context, StartLoc, LParenLoc, ColonLoc, EndLoc, Vars, 9007 ReductionIdScopeSpec.getWithLocInContext(Context), ReductionId, Privates, 9008 LHSs, RHSs, ReductionOps, buildPreInits(Context, ExprCaptures), 9009 buildPostUpdate(*this, ExprPostUpdates)); 9010 } 9011 9012 bool Sema::CheckOpenMPLinearModifier(OpenMPLinearClauseKind LinKind, 9013 SourceLocation LinLoc) { 9014 if ((!LangOpts.CPlusPlus && LinKind != OMPC_LINEAR_val) || 9015 LinKind == OMPC_LINEAR_unknown) { 9016 Diag(LinLoc, diag::err_omp_wrong_linear_modifier) << LangOpts.CPlusPlus; 9017 return true; 9018 } 9019 return false; 9020 } 9021 9022 bool Sema::CheckOpenMPLinearDecl(ValueDecl *D, SourceLocation ELoc, 9023 OpenMPLinearClauseKind LinKind, 9024 QualType Type) { 9025 auto *VD = dyn_cast_or_null<VarDecl>(D); 9026 // A variable must not have an incomplete type or a reference type. 9027 if (RequireCompleteType(ELoc, Type, diag::err_omp_linear_incomplete_type)) 9028 return true; 9029 if ((LinKind == OMPC_LINEAR_uval || LinKind == OMPC_LINEAR_ref) && 9030 !Type->isReferenceType()) { 9031 Diag(ELoc, diag::err_omp_wrong_linear_modifier_non_reference) 9032 << Type << getOpenMPSimpleClauseTypeName(OMPC_linear, LinKind); 9033 return true; 9034 } 9035 Type = Type.getNonReferenceType(); 9036 9037 // A list item must not be const-qualified. 9038 if (Type.isConstant(Context)) { 9039 Diag(ELoc, diag::err_omp_const_variable) 9040 << getOpenMPClauseName(OMPC_linear); 9041 if (D) { 9042 bool IsDecl = 9043 !VD || 9044 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly; 9045 Diag(D->getLocation(), 9046 IsDecl ? diag::note_previous_decl : diag::note_defined_here) 9047 << D; 9048 } 9049 return true; 9050 } 9051 9052 // A list item must be of integral or pointer type. 9053 Type = Type.getUnqualifiedType().getCanonicalType(); 9054 const auto *Ty = Type.getTypePtrOrNull(); 9055 if (!Ty || (!Ty->isDependentType() && !Ty->isIntegralType(Context) && 9056 !Ty->isPointerType())) { 9057 Diag(ELoc, diag::err_omp_linear_expected_int_or_ptr) << Type; 9058 if (D) { 9059 bool IsDecl = 9060 !VD || 9061 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly; 9062 Diag(D->getLocation(), 9063 IsDecl ? diag::note_previous_decl : diag::note_defined_here) 9064 << D; 9065 } 9066 return true; 9067 } 9068 return false; 9069 } 9070 9071 OMPClause *Sema::ActOnOpenMPLinearClause( 9072 ArrayRef<Expr *> VarList, Expr *Step, SourceLocation StartLoc, 9073 SourceLocation LParenLoc, OpenMPLinearClauseKind LinKind, 9074 SourceLocation LinLoc, SourceLocation ColonLoc, SourceLocation EndLoc) { 9075 SmallVector<Expr *, 8> Vars; 9076 SmallVector<Expr *, 8> Privates; 9077 SmallVector<Expr *, 8> Inits; 9078 SmallVector<Decl *, 4> ExprCaptures; 9079 SmallVector<Expr *, 4> ExprPostUpdates; 9080 if (CheckOpenMPLinearModifier(LinKind, LinLoc)) 9081 LinKind = OMPC_LINEAR_val; 9082 for (auto &RefExpr : VarList) { 9083 assert(RefExpr && "NULL expr in OpenMP linear clause."); 9084 SourceLocation ELoc; 9085 SourceRange ERange; 9086 Expr *SimpleRefExpr = RefExpr; 9087 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange, 9088 /*AllowArraySection=*/false); 9089 if (Res.second) { 9090 // It will be analyzed later. 9091 Vars.push_back(RefExpr); 9092 Privates.push_back(nullptr); 9093 Inits.push_back(nullptr); 9094 } 9095 ValueDecl *D = Res.first; 9096 if (!D) 9097 continue; 9098 9099 QualType Type = D->getType(); 9100 auto *VD = dyn_cast<VarDecl>(D); 9101 9102 // OpenMP [2.14.3.7, linear clause] 9103 // A list-item cannot appear in more than one linear clause. 9104 // A list-item that appears in a linear clause cannot appear in any 9105 // other data-sharing attribute clause. 9106 DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, false); 9107 if (DVar.RefExpr) { 9108 Diag(ELoc, diag::err_omp_wrong_dsa) << getOpenMPClauseName(DVar.CKind) 9109 << getOpenMPClauseName(OMPC_linear); 9110 ReportOriginalDSA(*this, DSAStack, D, DVar); 9111 continue; 9112 } 9113 9114 if (CheckOpenMPLinearDecl(D, ELoc, LinKind, Type)) 9115 continue; 9116 Type = Type.getNonReferenceType().getUnqualifiedType().getCanonicalType(); 9117 9118 // Build private copy of original var. 9119 auto *Private = buildVarDecl(*this, ELoc, Type, D->getName(), 9120 D->hasAttrs() ? &D->getAttrs() : nullptr); 9121 auto *PrivateRef = buildDeclRefExpr(*this, Private, Type, ELoc); 9122 // Build var to save initial value. 9123 VarDecl *Init = buildVarDecl(*this, ELoc, Type, ".linear.start"); 9124 Expr *InitExpr; 9125 DeclRefExpr *Ref = nullptr; 9126 if (!VD && !CurContext->isDependentContext()) { 9127 Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/false); 9128 if (!IsOpenMPCapturedDecl(D)) { 9129 ExprCaptures.push_back(Ref->getDecl()); 9130 if (Ref->getDecl()->hasAttr<OMPCaptureNoInitAttr>()) { 9131 ExprResult RefRes = DefaultLvalueConversion(Ref); 9132 if (!RefRes.isUsable()) 9133 continue; 9134 ExprResult PostUpdateRes = 9135 BuildBinOp(DSAStack->getCurScope(), ELoc, BO_Assign, 9136 SimpleRefExpr, RefRes.get()); 9137 if (!PostUpdateRes.isUsable()) 9138 continue; 9139 ExprPostUpdates.push_back( 9140 IgnoredValueConversions(PostUpdateRes.get()).get()); 9141 } 9142 } 9143 } 9144 if (LinKind == OMPC_LINEAR_uval) 9145 InitExpr = VD ? VD->getInit() : SimpleRefExpr; 9146 else 9147 InitExpr = VD ? SimpleRefExpr : Ref; 9148 AddInitializerToDecl(Init, DefaultLvalueConversion(InitExpr).get(), 9149 /*DirectInit=*/false); 9150 auto InitRef = buildDeclRefExpr(*this, Init, Type, ELoc); 9151 9152 DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_linear, Ref); 9153 Vars.push_back((VD || CurContext->isDependentContext()) 9154 ? RefExpr->IgnoreParens() 9155 : Ref); 9156 Privates.push_back(PrivateRef); 9157 Inits.push_back(InitRef); 9158 } 9159 9160 if (Vars.empty()) 9161 return nullptr; 9162 9163 Expr *StepExpr = Step; 9164 Expr *CalcStepExpr = nullptr; 9165 if (Step && !Step->isValueDependent() && !Step->isTypeDependent() && 9166 !Step->isInstantiationDependent() && 9167 !Step->containsUnexpandedParameterPack()) { 9168 SourceLocation StepLoc = Step->getLocStart(); 9169 ExprResult Val = PerformOpenMPImplicitIntegerConversion(StepLoc, Step); 9170 if (Val.isInvalid()) 9171 return nullptr; 9172 StepExpr = Val.get(); 9173 9174 // Build var to save the step value. 9175 VarDecl *SaveVar = 9176 buildVarDecl(*this, StepLoc, StepExpr->getType(), ".linear.step"); 9177 ExprResult SaveRef = 9178 buildDeclRefExpr(*this, SaveVar, StepExpr->getType(), StepLoc); 9179 ExprResult CalcStep = 9180 BuildBinOp(CurScope, StepLoc, BO_Assign, SaveRef.get(), StepExpr); 9181 CalcStep = ActOnFinishFullExpr(CalcStep.get()); 9182 9183 // Warn about zero linear step (it would be probably better specified as 9184 // making corresponding variables 'const'). 9185 llvm::APSInt Result; 9186 bool IsConstant = StepExpr->isIntegerConstantExpr(Result, Context); 9187 if (IsConstant && !Result.isNegative() && !Result.isStrictlyPositive()) 9188 Diag(StepLoc, diag::warn_omp_linear_step_zero) << Vars[0] 9189 << (Vars.size() > 1); 9190 if (!IsConstant && CalcStep.isUsable()) { 9191 // Calculate the step beforehand instead of doing this on each iteration. 9192 // (This is not used if the number of iterations may be kfold-ed). 9193 CalcStepExpr = CalcStep.get(); 9194 } 9195 } 9196 9197 return OMPLinearClause::Create(Context, StartLoc, LParenLoc, LinKind, LinLoc, 9198 ColonLoc, EndLoc, Vars, Privates, Inits, 9199 StepExpr, CalcStepExpr, 9200 buildPreInits(Context, ExprCaptures), 9201 buildPostUpdate(*this, ExprPostUpdates)); 9202 } 9203 9204 static bool FinishOpenMPLinearClause(OMPLinearClause &Clause, DeclRefExpr *IV, 9205 Expr *NumIterations, Sema &SemaRef, 9206 Scope *S, DSAStackTy *Stack) { 9207 // Walk the vars and build update/final expressions for the CodeGen. 9208 SmallVector<Expr *, 8> Updates; 9209 SmallVector<Expr *, 8> Finals; 9210 Expr *Step = Clause.getStep(); 9211 Expr *CalcStep = Clause.getCalcStep(); 9212 // OpenMP [2.14.3.7, linear clause] 9213 // If linear-step is not specified it is assumed to be 1. 9214 if (Step == nullptr) 9215 Step = SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get(); 9216 else if (CalcStep) { 9217 Step = cast<BinaryOperator>(CalcStep)->getLHS(); 9218 } 9219 bool HasErrors = false; 9220 auto CurInit = Clause.inits().begin(); 9221 auto CurPrivate = Clause.privates().begin(); 9222 auto LinKind = Clause.getModifier(); 9223 for (auto &RefExpr : Clause.varlists()) { 9224 SourceLocation ELoc; 9225 SourceRange ERange; 9226 Expr *SimpleRefExpr = RefExpr; 9227 auto Res = getPrivateItem(SemaRef, SimpleRefExpr, ELoc, ERange, 9228 /*AllowArraySection=*/false); 9229 ValueDecl *D = Res.first; 9230 if (Res.second || !D) { 9231 Updates.push_back(nullptr); 9232 Finals.push_back(nullptr); 9233 HasErrors = true; 9234 continue; 9235 } 9236 if (auto *CED = dyn_cast<OMPCapturedExprDecl>(D)) { 9237 D = cast<MemberExpr>(CED->getInit()->IgnoreParenImpCasts()) 9238 ->getMemberDecl(); 9239 } 9240 auto &&Info = Stack->isLoopControlVariable(D); 9241 Expr *InitExpr = *CurInit; 9242 9243 // Build privatized reference to the current linear var. 9244 auto *DE = cast<DeclRefExpr>(SimpleRefExpr); 9245 Expr *CapturedRef; 9246 if (LinKind == OMPC_LINEAR_uval) 9247 CapturedRef = cast<VarDecl>(DE->getDecl())->getInit(); 9248 else 9249 CapturedRef = 9250 buildDeclRefExpr(SemaRef, cast<VarDecl>(DE->getDecl()), 9251 DE->getType().getUnqualifiedType(), DE->getExprLoc(), 9252 /*RefersToCapture=*/true); 9253 9254 // Build update: Var = InitExpr + IV * Step 9255 ExprResult Update; 9256 if (!Info.first) { 9257 Update = 9258 BuildCounterUpdate(SemaRef, S, RefExpr->getExprLoc(), *CurPrivate, 9259 InitExpr, IV, Step, /* Subtract */ false); 9260 } else 9261 Update = *CurPrivate; 9262 Update = SemaRef.ActOnFinishFullExpr(Update.get(), DE->getLocStart(), 9263 /*DiscardedValue=*/true); 9264 9265 // Build final: Var = InitExpr + NumIterations * Step 9266 ExprResult Final; 9267 if (!Info.first) { 9268 Final = BuildCounterUpdate(SemaRef, S, RefExpr->getExprLoc(), CapturedRef, 9269 InitExpr, NumIterations, Step, 9270 /* Subtract */ false); 9271 } else 9272 Final = *CurPrivate; 9273 Final = SemaRef.ActOnFinishFullExpr(Final.get(), DE->getLocStart(), 9274 /*DiscardedValue=*/true); 9275 9276 if (!Update.isUsable() || !Final.isUsable()) { 9277 Updates.push_back(nullptr); 9278 Finals.push_back(nullptr); 9279 HasErrors = true; 9280 } else { 9281 Updates.push_back(Update.get()); 9282 Finals.push_back(Final.get()); 9283 } 9284 ++CurInit; 9285 ++CurPrivate; 9286 } 9287 Clause.setUpdates(Updates); 9288 Clause.setFinals(Finals); 9289 return HasErrors; 9290 } 9291 9292 OMPClause *Sema::ActOnOpenMPAlignedClause( 9293 ArrayRef<Expr *> VarList, Expr *Alignment, SourceLocation StartLoc, 9294 SourceLocation LParenLoc, SourceLocation ColonLoc, SourceLocation EndLoc) { 9295 9296 SmallVector<Expr *, 8> Vars; 9297 for (auto &RefExpr : VarList) { 9298 assert(RefExpr && "NULL expr in OpenMP linear clause."); 9299 SourceLocation ELoc; 9300 SourceRange ERange; 9301 Expr *SimpleRefExpr = RefExpr; 9302 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange, 9303 /*AllowArraySection=*/false); 9304 if (Res.second) { 9305 // It will be analyzed later. 9306 Vars.push_back(RefExpr); 9307 } 9308 ValueDecl *D = Res.first; 9309 if (!D) 9310 continue; 9311 9312 QualType QType = D->getType(); 9313 auto *VD = dyn_cast<VarDecl>(D); 9314 9315 // OpenMP [2.8.1, simd construct, Restrictions] 9316 // The type of list items appearing in the aligned clause must be 9317 // array, pointer, reference to array, or reference to pointer. 9318 QType = QType.getNonReferenceType().getUnqualifiedType().getCanonicalType(); 9319 const Type *Ty = QType.getTypePtrOrNull(); 9320 if (!Ty || (!Ty->isArrayType() && !Ty->isPointerType())) { 9321 Diag(ELoc, diag::err_omp_aligned_expected_array_or_ptr) 9322 << QType << getLangOpts().CPlusPlus << ERange; 9323 bool IsDecl = 9324 !VD || 9325 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly; 9326 Diag(D->getLocation(), 9327 IsDecl ? diag::note_previous_decl : diag::note_defined_here) 9328 << D; 9329 continue; 9330 } 9331 9332 // OpenMP [2.8.1, simd construct, Restrictions] 9333 // A list-item cannot appear in more than one aligned clause. 9334 if (Expr *PrevRef = DSAStack->addUniqueAligned(D, SimpleRefExpr)) { 9335 Diag(ELoc, diag::err_omp_aligned_twice) << 0 << ERange; 9336 Diag(PrevRef->getExprLoc(), diag::note_omp_explicit_dsa) 9337 << getOpenMPClauseName(OMPC_aligned); 9338 continue; 9339 } 9340 9341 DeclRefExpr *Ref = nullptr; 9342 if (!VD && IsOpenMPCapturedDecl(D)) 9343 Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/true); 9344 Vars.push_back(DefaultFunctionArrayConversion( 9345 (VD || !Ref) ? RefExpr->IgnoreParens() : Ref) 9346 .get()); 9347 } 9348 9349 // OpenMP [2.8.1, simd construct, Description] 9350 // The parameter of the aligned clause, alignment, must be a constant 9351 // positive integer expression. 9352 // If no optional parameter is specified, implementation-defined default 9353 // alignments for SIMD instructions on the target platforms are assumed. 9354 if (Alignment != nullptr) { 9355 ExprResult AlignResult = 9356 VerifyPositiveIntegerConstantInClause(Alignment, OMPC_aligned); 9357 if (AlignResult.isInvalid()) 9358 return nullptr; 9359 Alignment = AlignResult.get(); 9360 } 9361 if (Vars.empty()) 9362 return nullptr; 9363 9364 return OMPAlignedClause::Create(Context, StartLoc, LParenLoc, ColonLoc, 9365 EndLoc, Vars, Alignment); 9366 } 9367 9368 OMPClause *Sema::ActOnOpenMPCopyinClause(ArrayRef<Expr *> VarList, 9369 SourceLocation StartLoc, 9370 SourceLocation LParenLoc, 9371 SourceLocation EndLoc) { 9372 SmallVector<Expr *, 8> Vars; 9373 SmallVector<Expr *, 8> SrcExprs; 9374 SmallVector<Expr *, 8> DstExprs; 9375 SmallVector<Expr *, 8> AssignmentOps; 9376 for (auto &RefExpr : VarList) { 9377 assert(RefExpr && "NULL expr in OpenMP copyin clause."); 9378 if (isa<DependentScopeDeclRefExpr>(RefExpr)) { 9379 // It will be analyzed later. 9380 Vars.push_back(RefExpr); 9381 SrcExprs.push_back(nullptr); 9382 DstExprs.push_back(nullptr); 9383 AssignmentOps.push_back(nullptr); 9384 continue; 9385 } 9386 9387 SourceLocation ELoc = RefExpr->getExprLoc(); 9388 // OpenMP [2.1, C/C++] 9389 // A list item is a variable name. 9390 // OpenMP [2.14.4.1, Restrictions, p.1] 9391 // A list item that appears in a copyin clause must be threadprivate. 9392 DeclRefExpr *DE = dyn_cast<DeclRefExpr>(RefExpr); 9393 if (!DE || !isa<VarDecl>(DE->getDecl())) { 9394 Diag(ELoc, diag::err_omp_expected_var_name_member_expr) 9395 << 0 << RefExpr->getSourceRange(); 9396 continue; 9397 } 9398 9399 Decl *D = DE->getDecl(); 9400 VarDecl *VD = cast<VarDecl>(D); 9401 9402 QualType Type = VD->getType(); 9403 if (Type->isDependentType() || Type->isInstantiationDependentType()) { 9404 // It will be analyzed later. 9405 Vars.push_back(DE); 9406 SrcExprs.push_back(nullptr); 9407 DstExprs.push_back(nullptr); 9408 AssignmentOps.push_back(nullptr); 9409 continue; 9410 } 9411 9412 // OpenMP [2.14.4.1, Restrictions, C/C++, p.1] 9413 // A list item that appears in a copyin clause must be threadprivate. 9414 if (!DSAStack->isThreadPrivate(VD)) { 9415 Diag(ELoc, diag::err_omp_required_access) 9416 << getOpenMPClauseName(OMPC_copyin) 9417 << getOpenMPDirectiveName(OMPD_threadprivate); 9418 continue; 9419 } 9420 9421 // OpenMP [2.14.4.1, Restrictions, C/C++, p.2] 9422 // A variable of class type (or array thereof) that appears in a 9423 // copyin clause requires an accessible, unambiguous copy assignment 9424 // operator for the class type. 9425 auto ElemType = Context.getBaseElementType(Type).getNonReferenceType(); 9426 auto *SrcVD = 9427 buildVarDecl(*this, DE->getLocStart(), ElemType.getUnqualifiedType(), 9428 ".copyin.src", VD->hasAttrs() ? &VD->getAttrs() : nullptr); 9429 auto *PseudoSrcExpr = buildDeclRefExpr( 9430 *this, SrcVD, ElemType.getUnqualifiedType(), DE->getExprLoc()); 9431 auto *DstVD = 9432 buildVarDecl(*this, DE->getLocStart(), ElemType, ".copyin.dst", 9433 VD->hasAttrs() ? &VD->getAttrs() : nullptr); 9434 auto *PseudoDstExpr = 9435 buildDeclRefExpr(*this, DstVD, ElemType, DE->getExprLoc()); 9436 // For arrays generate assignment operation for single element and replace 9437 // it by the original array element in CodeGen. 9438 auto AssignmentOp = BuildBinOp(/*S=*/nullptr, DE->getExprLoc(), BO_Assign, 9439 PseudoDstExpr, PseudoSrcExpr); 9440 if (AssignmentOp.isInvalid()) 9441 continue; 9442 AssignmentOp = ActOnFinishFullExpr(AssignmentOp.get(), DE->getExprLoc(), 9443 /*DiscardedValue=*/true); 9444 if (AssignmentOp.isInvalid()) 9445 continue; 9446 9447 DSAStack->addDSA(VD, DE, OMPC_copyin); 9448 Vars.push_back(DE); 9449 SrcExprs.push_back(PseudoSrcExpr); 9450 DstExprs.push_back(PseudoDstExpr); 9451 AssignmentOps.push_back(AssignmentOp.get()); 9452 } 9453 9454 if (Vars.empty()) 9455 return nullptr; 9456 9457 return OMPCopyinClause::Create(Context, StartLoc, LParenLoc, EndLoc, Vars, 9458 SrcExprs, DstExprs, AssignmentOps); 9459 } 9460 9461 OMPClause *Sema::ActOnOpenMPCopyprivateClause(ArrayRef<Expr *> VarList, 9462 SourceLocation StartLoc, 9463 SourceLocation LParenLoc, 9464 SourceLocation EndLoc) { 9465 SmallVector<Expr *, 8> Vars; 9466 SmallVector<Expr *, 8> SrcExprs; 9467 SmallVector<Expr *, 8> DstExprs; 9468 SmallVector<Expr *, 8> AssignmentOps; 9469 for (auto &RefExpr : VarList) { 9470 assert(RefExpr && "NULL expr in OpenMP linear clause."); 9471 SourceLocation ELoc; 9472 SourceRange ERange; 9473 Expr *SimpleRefExpr = RefExpr; 9474 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange, 9475 /*AllowArraySection=*/false); 9476 if (Res.second) { 9477 // It will be analyzed later. 9478 Vars.push_back(RefExpr); 9479 SrcExprs.push_back(nullptr); 9480 DstExprs.push_back(nullptr); 9481 AssignmentOps.push_back(nullptr); 9482 } 9483 ValueDecl *D = Res.first; 9484 if (!D) 9485 continue; 9486 9487 QualType Type = D->getType(); 9488 auto *VD = dyn_cast<VarDecl>(D); 9489 9490 // OpenMP [2.14.4.2, Restrictions, p.2] 9491 // A list item that appears in a copyprivate clause may not appear in a 9492 // private or firstprivate clause on the single construct. 9493 if (!VD || !DSAStack->isThreadPrivate(VD)) { 9494 auto DVar = DSAStack->getTopDSA(D, false); 9495 if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_copyprivate && 9496 DVar.RefExpr) { 9497 Diag(ELoc, diag::err_omp_wrong_dsa) 9498 << getOpenMPClauseName(DVar.CKind) 9499 << getOpenMPClauseName(OMPC_copyprivate); 9500 ReportOriginalDSA(*this, DSAStack, D, DVar); 9501 continue; 9502 } 9503 9504 // OpenMP [2.11.4.2, Restrictions, p.1] 9505 // All list items that appear in a copyprivate clause must be either 9506 // threadprivate or private in the enclosing context. 9507 if (DVar.CKind == OMPC_unknown) { 9508 DVar = DSAStack->getImplicitDSA(D, false); 9509 if (DVar.CKind == OMPC_shared) { 9510 Diag(ELoc, diag::err_omp_required_access) 9511 << getOpenMPClauseName(OMPC_copyprivate) 9512 << "threadprivate or private in the enclosing context"; 9513 ReportOriginalDSA(*this, DSAStack, D, DVar); 9514 continue; 9515 } 9516 } 9517 } 9518 9519 // Variably modified types are not supported. 9520 if (!Type->isAnyPointerType() && Type->isVariablyModifiedType()) { 9521 Diag(ELoc, diag::err_omp_variably_modified_type_not_supported) 9522 << getOpenMPClauseName(OMPC_copyprivate) << Type 9523 << getOpenMPDirectiveName(DSAStack->getCurrentDirective()); 9524 bool IsDecl = 9525 !VD || 9526 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly; 9527 Diag(D->getLocation(), 9528 IsDecl ? diag::note_previous_decl : diag::note_defined_here) 9529 << D; 9530 continue; 9531 } 9532 9533 // OpenMP [2.14.4.1, Restrictions, C/C++, p.2] 9534 // A variable of class type (or array thereof) that appears in a 9535 // copyin clause requires an accessible, unambiguous copy assignment 9536 // operator for the class type. 9537 Type = Context.getBaseElementType(Type.getNonReferenceType()) 9538 .getUnqualifiedType(); 9539 auto *SrcVD = 9540 buildVarDecl(*this, RefExpr->getLocStart(), Type, ".copyprivate.src", 9541 D->hasAttrs() ? &D->getAttrs() : nullptr); 9542 auto *PseudoSrcExpr = buildDeclRefExpr(*this, SrcVD, Type, ELoc); 9543 auto *DstVD = 9544 buildVarDecl(*this, RefExpr->getLocStart(), Type, ".copyprivate.dst", 9545 D->hasAttrs() ? &D->getAttrs() : nullptr); 9546 auto *PseudoDstExpr = buildDeclRefExpr(*this, DstVD, Type, ELoc); 9547 auto AssignmentOp = BuildBinOp(DSAStack->getCurScope(), ELoc, BO_Assign, 9548 PseudoDstExpr, PseudoSrcExpr); 9549 if (AssignmentOp.isInvalid()) 9550 continue; 9551 AssignmentOp = ActOnFinishFullExpr(AssignmentOp.get(), ELoc, 9552 /*DiscardedValue=*/true); 9553 if (AssignmentOp.isInvalid()) 9554 continue; 9555 9556 // No need to mark vars as copyprivate, they are already threadprivate or 9557 // implicitly private. 9558 assert(VD || IsOpenMPCapturedDecl(D)); 9559 Vars.push_back( 9560 VD ? RefExpr->IgnoreParens() 9561 : buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/false)); 9562 SrcExprs.push_back(PseudoSrcExpr); 9563 DstExprs.push_back(PseudoDstExpr); 9564 AssignmentOps.push_back(AssignmentOp.get()); 9565 } 9566 9567 if (Vars.empty()) 9568 return nullptr; 9569 9570 return OMPCopyprivateClause::Create(Context, StartLoc, LParenLoc, EndLoc, 9571 Vars, SrcExprs, DstExprs, AssignmentOps); 9572 } 9573 9574 OMPClause *Sema::ActOnOpenMPFlushClause(ArrayRef<Expr *> VarList, 9575 SourceLocation StartLoc, 9576 SourceLocation LParenLoc, 9577 SourceLocation EndLoc) { 9578 if (VarList.empty()) 9579 return nullptr; 9580 9581 return OMPFlushClause::Create(Context, StartLoc, LParenLoc, EndLoc, VarList); 9582 } 9583 9584 OMPClause * 9585 Sema::ActOnOpenMPDependClause(OpenMPDependClauseKind DepKind, 9586 SourceLocation DepLoc, SourceLocation ColonLoc, 9587 ArrayRef<Expr *> VarList, SourceLocation StartLoc, 9588 SourceLocation LParenLoc, SourceLocation EndLoc) { 9589 if (DSAStack->getCurrentDirective() == OMPD_ordered && 9590 DepKind != OMPC_DEPEND_source && DepKind != OMPC_DEPEND_sink) { 9591 Diag(DepLoc, diag::err_omp_unexpected_clause_value) 9592 << "'source' or 'sink'" << getOpenMPClauseName(OMPC_depend); 9593 return nullptr; 9594 } 9595 if (DSAStack->getCurrentDirective() != OMPD_ordered && 9596 (DepKind == OMPC_DEPEND_unknown || DepKind == OMPC_DEPEND_source || 9597 DepKind == OMPC_DEPEND_sink)) { 9598 unsigned Except[] = {OMPC_DEPEND_source, OMPC_DEPEND_sink}; 9599 Diag(DepLoc, diag::err_omp_unexpected_clause_value) 9600 << getListOfPossibleValues(OMPC_depend, /*First=*/0, 9601 /*Last=*/OMPC_DEPEND_unknown, Except) 9602 << getOpenMPClauseName(OMPC_depend); 9603 return nullptr; 9604 } 9605 SmallVector<Expr *, 8> Vars; 9606 DSAStackTy::OperatorOffsetTy OpsOffs; 9607 llvm::APSInt DepCounter(/*BitWidth=*/32); 9608 llvm::APSInt TotalDepCount(/*BitWidth=*/32); 9609 if (DepKind == OMPC_DEPEND_sink) { 9610 if (auto *OrderedCountExpr = DSAStack->getParentOrderedRegionParam()) { 9611 TotalDepCount = OrderedCountExpr->EvaluateKnownConstInt(Context); 9612 TotalDepCount.setIsUnsigned(/*Val=*/true); 9613 } 9614 } 9615 if ((DepKind != OMPC_DEPEND_sink && DepKind != OMPC_DEPEND_source) || 9616 DSAStack->getParentOrderedRegionParam()) { 9617 for (auto &RefExpr : VarList) { 9618 assert(RefExpr && "NULL expr in OpenMP shared clause."); 9619 if (isa<DependentScopeDeclRefExpr>(RefExpr)) { 9620 // It will be analyzed later. 9621 Vars.push_back(RefExpr); 9622 continue; 9623 } 9624 9625 SourceLocation ELoc = RefExpr->getExprLoc(); 9626 auto *SimpleExpr = RefExpr->IgnoreParenCasts(); 9627 if (DepKind == OMPC_DEPEND_sink) { 9628 if (DepCounter >= TotalDepCount) { 9629 Diag(ELoc, diag::err_omp_depend_sink_unexpected_expr); 9630 continue; 9631 } 9632 ++DepCounter; 9633 // OpenMP [2.13.9, Summary] 9634 // depend(dependence-type : vec), where dependence-type is: 9635 // 'sink' and where vec is the iteration vector, which has the form: 9636 // x1 [+- d1], x2 [+- d2 ], . . . , xn [+- dn] 9637 // where n is the value specified by the ordered clause in the loop 9638 // directive, xi denotes the loop iteration variable of the i-th nested 9639 // loop associated with the loop directive, and di is a constant 9640 // non-negative integer. 9641 if (CurContext->isDependentContext()) { 9642 // It will be analyzed later. 9643 Vars.push_back(RefExpr); 9644 continue; 9645 } 9646 SimpleExpr = SimpleExpr->IgnoreImplicit(); 9647 OverloadedOperatorKind OOK = OO_None; 9648 SourceLocation OOLoc; 9649 Expr *LHS = SimpleExpr; 9650 Expr *RHS = nullptr; 9651 if (auto *BO = dyn_cast<BinaryOperator>(SimpleExpr)) { 9652 OOK = BinaryOperator::getOverloadedOperator(BO->getOpcode()); 9653 OOLoc = BO->getOperatorLoc(); 9654 LHS = BO->getLHS()->IgnoreParenImpCasts(); 9655 RHS = BO->getRHS()->IgnoreParenImpCasts(); 9656 } else if (auto *OCE = dyn_cast<CXXOperatorCallExpr>(SimpleExpr)) { 9657 OOK = OCE->getOperator(); 9658 OOLoc = OCE->getOperatorLoc(); 9659 LHS = OCE->getArg(/*Arg=*/0)->IgnoreParenImpCasts(); 9660 RHS = OCE->getArg(/*Arg=*/1)->IgnoreParenImpCasts(); 9661 } else if (auto *MCE = dyn_cast<CXXMemberCallExpr>(SimpleExpr)) { 9662 OOK = MCE->getMethodDecl() 9663 ->getNameInfo() 9664 .getName() 9665 .getCXXOverloadedOperator(); 9666 OOLoc = MCE->getCallee()->getExprLoc(); 9667 LHS = MCE->getImplicitObjectArgument()->IgnoreParenImpCasts(); 9668 RHS = MCE->getArg(/*Arg=*/0)->IgnoreParenImpCasts(); 9669 } 9670 SourceLocation ELoc; 9671 SourceRange ERange; 9672 auto Res = getPrivateItem(*this, LHS, ELoc, ERange, 9673 /*AllowArraySection=*/false); 9674 if (Res.second) { 9675 // It will be analyzed later. 9676 Vars.push_back(RefExpr); 9677 } 9678 ValueDecl *D = Res.first; 9679 if (!D) 9680 continue; 9681 9682 if (OOK != OO_Plus && OOK != OO_Minus && (RHS || OOK != OO_None)) { 9683 Diag(OOLoc, diag::err_omp_depend_sink_expected_plus_minus); 9684 continue; 9685 } 9686 if (RHS) { 9687 ExprResult RHSRes = VerifyPositiveIntegerConstantInClause( 9688 RHS, OMPC_depend, /*StrictlyPositive=*/false); 9689 if (RHSRes.isInvalid()) 9690 continue; 9691 } 9692 if (!CurContext->isDependentContext() && 9693 DSAStack->getParentOrderedRegionParam() && 9694 DepCounter != DSAStack->isParentLoopControlVariable(D).first) { 9695 Diag(ELoc, diag::err_omp_depend_sink_expected_loop_iteration) 9696 << DSAStack->getParentLoopControlVariable( 9697 DepCounter.getZExtValue()); 9698 continue; 9699 } 9700 OpsOffs.push_back({RHS, OOK}); 9701 } else { 9702 // OpenMP [2.11.1.1, Restrictions, p.3] 9703 // A variable that is part of another variable (such as a field of a 9704 // structure) but is not an array element or an array section cannot 9705 // appear in a depend clause. 9706 auto *DE = dyn_cast<DeclRefExpr>(SimpleExpr); 9707 auto *ASE = dyn_cast<ArraySubscriptExpr>(SimpleExpr); 9708 auto *OASE = dyn_cast<OMPArraySectionExpr>(SimpleExpr); 9709 if (!RefExpr->IgnoreParenImpCasts()->isLValue() || 9710 (!ASE && !DE && !OASE) || (DE && !isa<VarDecl>(DE->getDecl())) || 9711 (ASE && 9712 !ASE->getBase() 9713 ->getType() 9714 .getNonReferenceType() 9715 ->isPointerType() && 9716 !ASE->getBase()->getType().getNonReferenceType()->isArrayType())) { 9717 Diag(ELoc, diag::err_omp_expected_var_name_member_expr_or_array_item) 9718 << 0 << RefExpr->getSourceRange(); 9719 continue; 9720 } 9721 } 9722 Vars.push_back(RefExpr->IgnoreParenImpCasts()); 9723 } 9724 9725 if (!CurContext->isDependentContext() && DepKind == OMPC_DEPEND_sink && 9726 TotalDepCount > VarList.size() && 9727 DSAStack->getParentOrderedRegionParam()) { 9728 Diag(EndLoc, diag::err_omp_depend_sink_expected_loop_iteration) 9729 << DSAStack->getParentLoopControlVariable(VarList.size() + 1); 9730 } 9731 if (DepKind != OMPC_DEPEND_source && DepKind != OMPC_DEPEND_sink && 9732 Vars.empty()) 9733 return nullptr; 9734 } 9735 auto *C = OMPDependClause::Create(Context, StartLoc, LParenLoc, EndLoc, 9736 DepKind, DepLoc, ColonLoc, Vars); 9737 if (DepKind == OMPC_DEPEND_sink || DepKind == OMPC_DEPEND_source) 9738 DSAStack->addDoacrossDependClause(C, OpsOffs); 9739 return C; 9740 } 9741 9742 OMPClause *Sema::ActOnOpenMPDeviceClause(Expr *Device, SourceLocation StartLoc, 9743 SourceLocation LParenLoc, 9744 SourceLocation EndLoc) { 9745 Expr *ValExpr = Device; 9746 9747 // OpenMP [2.9.1, Restrictions] 9748 // The device expression must evaluate to a non-negative integer value. 9749 if (!IsNonNegativeIntegerValue(ValExpr, *this, OMPC_device, 9750 /*StrictlyPositive=*/false)) 9751 return nullptr; 9752 9753 return new (Context) OMPDeviceClause(ValExpr, StartLoc, LParenLoc, EndLoc); 9754 } 9755 9756 static bool IsCXXRecordForMappable(Sema &SemaRef, SourceLocation Loc, 9757 DSAStackTy *Stack, CXXRecordDecl *RD) { 9758 if (!RD || RD->isInvalidDecl()) 9759 return true; 9760 9761 auto QTy = SemaRef.Context.getRecordType(RD); 9762 if (RD->isDynamicClass()) { 9763 SemaRef.Diag(Loc, diag::err_omp_not_mappable_type) << QTy; 9764 SemaRef.Diag(RD->getLocation(), diag::note_omp_polymorphic_in_target); 9765 return false; 9766 } 9767 auto *DC = RD; 9768 bool IsCorrect = true; 9769 for (auto *I : DC->decls()) { 9770 if (I) { 9771 if (auto *MD = dyn_cast<CXXMethodDecl>(I)) { 9772 if (MD->isStatic()) { 9773 SemaRef.Diag(Loc, diag::err_omp_not_mappable_type) << QTy; 9774 SemaRef.Diag(MD->getLocation(), 9775 diag::note_omp_static_member_in_target); 9776 IsCorrect = false; 9777 } 9778 } else if (auto *VD = dyn_cast<VarDecl>(I)) { 9779 if (VD->isStaticDataMember()) { 9780 SemaRef.Diag(Loc, diag::err_omp_not_mappable_type) << QTy; 9781 SemaRef.Diag(VD->getLocation(), 9782 diag::note_omp_static_member_in_target); 9783 IsCorrect = false; 9784 } 9785 } 9786 } 9787 } 9788 9789 for (auto &I : RD->bases()) { 9790 if (!IsCXXRecordForMappable(SemaRef, I.getLocStart(), Stack, 9791 I.getType()->getAsCXXRecordDecl())) 9792 IsCorrect = false; 9793 } 9794 return IsCorrect; 9795 } 9796 9797 static bool CheckTypeMappable(SourceLocation SL, SourceRange SR, Sema &SemaRef, 9798 DSAStackTy *Stack, QualType QTy) { 9799 NamedDecl *ND; 9800 if (QTy->isIncompleteType(&ND)) { 9801 SemaRef.Diag(SL, diag::err_incomplete_type) << QTy << SR; 9802 return false; 9803 } else if (CXXRecordDecl *RD = dyn_cast_or_null<CXXRecordDecl>(ND)) { 9804 if (!RD->isInvalidDecl() && !IsCXXRecordForMappable(SemaRef, SL, Stack, RD)) 9805 return false; 9806 } 9807 return true; 9808 } 9809 9810 /// \brief Return true if it can be proven that the provided array expression 9811 /// (array section or array subscript) does NOT specify the whole size of the 9812 /// array whose base type is \a BaseQTy. 9813 static bool CheckArrayExpressionDoesNotReferToWholeSize(Sema &SemaRef, 9814 const Expr *E, 9815 QualType BaseQTy) { 9816 auto *OASE = dyn_cast<OMPArraySectionExpr>(E); 9817 9818 // If this is an array subscript, it refers to the whole size if the size of 9819 // the dimension is constant and equals 1. Also, an array section assumes the 9820 // format of an array subscript if no colon is used. 9821 if (isa<ArraySubscriptExpr>(E) || (OASE && OASE->getColonLoc().isInvalid())) { 9822 if (auto *ATy = dyn_cast<ConstantArrayType>(BaseQTy.getTypePtr())) 9823 return ATy->getSize().getSExtValue() != 1; 9824 // Size can't be evaluated statically. 9825 return false; 9826 } 9827 9828 assert(OASE && "Expecting array section if not an array subscript."); 9829 auto *LowerBound = OASE->getLowerBound(); 9830 auto *Length = OASE->getLength(); 9831 9832 // If there is a lower bound that does not evaluates to zero, we are not 9833 // covering the whole dimension. 9834 if (LowerBound) { 9835 llvm::APSInt ConstLowerBound; 9836 if (!LowerBound->EvaluateAsInt(ConstLowerBound, SemaRef.getASTContext())) 9837 return false; // Can't get the integer value as a constant. 9838 if (ConstLowerBound.getSExtValue()) 9839 return true; 9840 } 9841 9842 // If we don't have a length we covering the whole dimension. 9843 if (!Length) 9844 return false; 9845 9846 // If the base is a pointer, we don't have a way to get the size of the 9847 // pointee. 9848 if (BaseQTy->isPointerType()) 9849 return false; 9850 9851 // We can only check if the length is the same as the size of the dimension 9852 // if we have a constant array. 9853 auto *CATy = dyn_cast<ConstantArrayType>(BaseQTy.getTypePtr()); 9854 if (!CATy) 9855 return false; 9856 9857 llvm::APSInt ConstLength; 9858 if (!Length->EvaluateAsInt(ConstLength, SemaRef.getASTContext())) 9859 return false; // Can't get the integer value as a constant. 9860 9861 return CATy->getSize().getSExtValue() != ConstLength.getSExtValue(); 9862 } 9863 9864 // Return true if it can be proven that the provided array expression (array 9865 // section or array subscript) does NOT specify a single element of the array 9866 // whose base type is \a BaseQTy. 9867 static bool CheckArrayExpressionDoesNotReferToUnitySize(Sema &SemaRef, 9868 const Expr *E, 9869 QualType BaseQTy) { 9870 auto *OASE = dyn_cast<OMPArraySectionExpr>(E); 9871 9872 // An array subscript always refer to a single element. Also, an array section 9873 // assumes the format of an array subscript if no colon is used. 9874 if (isa<ArraySubscriptExpr>(E) || (OASE && OASE->getColonLoc().isInvalid())) 9875 return false; 9876 9877 assert(OASE && "Expecting array section if not an array subscript."); 9878 auto *Length = OASE->getLength(); 9879 9880 // If we don't have a length we have to check if the array has unitary size 9881 // for this dimension. Also, we should always expect a length if the base type 9882 // is pointer. 9883 if (!Length) { 9884 if (auto *ATy = dyn_cast<ConstantArrayType>(BaseQTy.getTypePtr())) 9885 return ATy->getSize().getSExtValue() != 1; 9886 // We cannot assume anything. 9887 return false; 9888 } 9889 9890 // Check if the length evaluates to 1. 9891 llvm::APSInt ConstLength; 9892 if (!Length->EvaluateAsInt(ConstLength, SemaRef.getASTContext())) 9893 return false; // Can't get the integer value as a constant. 9894 9895 return ConstLength.getSExtValue() != 1; 9896 } 9897 9898 // Return the expression of the base of the mappable expression or null if it 9899 // cannot be determined and do all the necessary checks to see if the expression 9900 // is valid as a standalone mappable expression. In the process, record all the 9901 // components of the expression. 9902 static Expr *CheckMapClauseExpressionBase( 9903 Sema &SemaRef, Expr *E, 9904 OMPClauseMappableExprCommon::MappableExprComponentList &CurComponents, 9905 OpenMPClauseKind CKind) { 9906 SourceLocation ELoc = E->getExprLoc(); 9907 SourceRange ERange = E->getSourceRange(); 9908 9909 // The base of elements of list in a map clause have to be either: 9910 // - a reference to variable or field. 9911 // - a member expression. 9912 // - an array expression. 9913 // 9914 // E.g. if we have the expression 'r.S.Arr[:12]', we want to retrieve the 9915 // reference to 'r'. 9916 // 9917 // If we have: 9918 // 9919 // struct SS { 9920 // Bla S; 9921 // foo() { 9922 // #pragma omp target map (S.Arr[:12]); 9923 // } 9924 // } 9925 // 9926 // We want to retrieve the member expression 'this->S'; 9927 9928 Expr *RelevantExpr = nullptr; 9929 9930 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.2] 9931 // If a list item is an array section, it must specify contiguous storage. 9932 // 9933 // For this restriction it is sufficient that we make sure only references 9934 // to variables or fields and array expressions, and that no array sections 9935 // exist except in the rightmost expression (unless they cover the whole 9936 // dimension of the array). E.g. these would be invalid: 9937 // 9938 // r.ArrS[3:5].Arr[6:7] 9939 // 9940 // r.ArrS[3:5].x 9941 // 9942 // but these would be valid: 9943 // r.ArrS[3].Arr[6:7] 9944 // 9945 // r.ArrS[3].x 9946 9947 bool AllowUnitySizeArraySection = true; 9948 bool AllowWholeSizeArraySection = true; 9949 9950 while (!RelevantExpr) { 9951 E = E->IgnoreParenImpCasts(); 9952 9953 if (auto *CurE = dyn_cast<DeclRefExpr>(E)) { 9954 if (!isa<VarDecl>(CurE->getDecl())) 9955 break; 9956 9957 RelevantExpr = CurE; 9958 9959 // If we got a reference to a declaration, we should not expect any array 9960 // section before that. 9961 AllowUnitySizeArraySection = false; 9962 AllowWholeSizeArraySection = false; 9963 9964 // Record the component. 9965 CurComponents.push_back(OMPClauseMappableExprCommon::MappableComponent( 9966 CurE, CurE->getDecl())); 9967 continue; 9968 } 9969 9970 if (auto *CurE = dyn_cast<MemberExpr>(E)) { 9971 auto *BaseE = CurE->getBase()->IgnoreParenImpCasts(); 9972 9973 if (isa<CXXThisExpr>(BaseE)) 9974 // We found a base expression: this->Val. 9975 RelevantExpr = CurE; 9976 else 9977 E = BaseE; 9978 9979 if (!isa<FieldDecl>(CurE->getMemberDecl())) { 9980 SemaRef.Diag(ELoc, diag::err_omp_expected_access_to_data_field) 9981 << CurE->getSourceRange(); 9982 break; 9983 } 9984 9985 auto *FD = cast<FieldDecl>(CurE->getMemberDecl()); 9986 9987 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C/C++, p.3] 9988 // A bit-field cannot appear in a map clause. 9989 // 9990 if (FD->isBitField()) { 9991 SemaRef.Diag(ELoc, diag::err_omp_bit_fields_forbidden_in_clause) 9992 << CurE->getSourceRange() << getOpenMPClauseName(CKind); 9993 break; 9994 } 9995 9996 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C++, p.1] 9997 // If the type of a list item is a reference to a type T then the type 9998 // will be considered to be T for all purposes of this clause. 9999 QualType CurType = BaseE->getType().getNonReferenceType(); 10000 10001 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C/C++, p.2] 10002 // A list item cannot be a variable that is a member of a structure with 10003 // a union type. 10004 // 10005 if (auto *RT = CurType->getAs<RecordType>()) 10006 if (RT->isUnionType()) { 10007 SemaRef.Diag(ELoc, diag::err_omp_union_type_not_allowed) 10008 << CurE->getSourceRange(); 10009 break; 10010 } 10011 10012 // If we got a member expression, we should not expect any array section 10013 // before that: 10014 // 10015 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.7] 10016 // If a list item is an element of a structure, only the rightmost symbol 10017 // of the variable reference can be an array section. 10018 // 10019 AllowUnitySizeArraySection = false; 10020 AllowWholeSizeArraySection = false; 10021 10022 // Record the component. 10023 CurComponents.push_back( 10024 OMPClauseMappableExprCommon::MappableComponent(CurE, FD)); 10025 continue; 10026 } 10027 10028 if (auto *CurE = dyn_cast<ArraySubscriptExpr>(E)) { 10029 E = CurE->getBase()->IgnoreParenImpCasts(); 10030 10031 if (!E->getType()->isAnyPointerType() && !E->getType()->isArrayType()) { 10032 SemaRef.Diag(ELoc, diag::err_omp_expected_base_var_name) 10033 << 0 << CurE->getSourceRange(); 10034 break; 10035 } 10036 10037 // If we got an array subscript that express the whole dimension we 10038 // can have any array expressions before. If it only expressing part of 10039 // the dimension, we can only have unitary-size array expressions. 10040 if (CheckArrayExpressionDoesNotReferToWholeSize(SemaRef, CurE, 10041 E->getType())) 10042 AllowWholeSizeArraySection = false; 10043 10044 // Record the component - we don't have any declaration associated. 10045 CurComponents.push_back( 10046 OMPClauseMappableExprCommon::MappableComponent(CurE, nullptr)); 10047 continue; 10048 } 10049 10050 if (auto *CurE = dyn_cast<OMPArraySectionExpr>(E)) { 10051 E = CurE->getBase()->IgnoreParenImpCasts(); 10052 10053 auto CurType = 10054 OMPArraySectionExpr::getBaseOriginalType(E).getCanonicalType(); 10055 10056 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C++, p.1] 10057 // If the type of a list item is a reference to a type T then the type 10058 // will be considered to be T for all purposes of this clause. 10059 if (CurType->isReferenceType()) 10060 CurType = CurType->getPointeeType(); 10061 10062 bool IsPointer = CurType->isAnyPointerType(); 10063 10064 if (!IsPointer && !CurType->isArrayType()) { 10065 SemaRef.Diag(ELoc, diag::err_omp_expected_base_var_name) 10066 << 0 << CurE->getSourceRange(); 10067 break; 10068 } 10069 10070 bool NotWhole = 10071 CheckArrayExpressionDoesNotReferToWholeSize(SemaRef, CurE, CurType); 10072 bool NotUnity = 10073 CheckArrayExpressionDoesNotReferToUnitySize(SemaRef, CurE, CurType); 10074 10075 if (AllowWholeSizeArraySection) { 10076 // Any array section is currently allowed. Allowing a whole size array 10077 // section implies allowing a unity array section as well. 10078 // 10079 // If this array section refers to the whole dimension we can still 10080 // accept other array sections before this one, except if the base is a 10081 // pointer. Otherwise, only unitary sections are accepted. 10082 if (NotWhole || IsPointer) 10083 AllowWholeSizeArraySection = false; 10084 } else if (AllowUnitySizeArraySection && NotUnity) { 10085 // A unity or whole array section is not allowed and that is not 10086 // compatible with the properties of the current array section. 10087 SemaRef.Diag( 10088 ELoc, diag::err_array_section_does_not_specify_contiguous_storage) 10089 << CurE->getSourceRange(); 10090 break; 10091 } 10092 10093 // Record the component - we don't have any declaration associated. 10094 CurComponents.push_back( 10095 OMPClauseMappableExprCommon::MappableComponent(CurE, nullptr)); 10096 continue; 10097 } 10098 10099 // If nothing else worked, this is not a valid map clause expression. 10100 SemaRef.Diag(ELoc, 10101 diag::err_omp_expected_named_var_member_or_array_expression) 10102 << ERange; 10103 break; 10104 } 10105 10106 return RelevantExpr; 10107 } 10108 10109 // Return true if expression E associated with value VD has conflicts with other 10110 // map information. 10111 static bool CheckMapConflicts( 10112 Sema &SemaRef, DSAStackTy *DSAS, ValueDecl *VD, Expr *E, 10113 bool CurrentRegionOnly, 10114 OMPClauseMappableExprCommon::MappableExprComponentListRef CurComponents, 10115 OpenMPClauseKind CKind) { 10116 assert(VD && E); 10117 SourceLocation ELoc = E->getExprLoc(); 10118 SourceRange ERange = E->getSourceRange(); 10119 10120 // In order to easily check the conflicts we need to match each component of 10121 // the expression under test with the components of the expressions that are 10122 // already in the stack. 10123 10124 assert(!CurComponents.empty() && "Map clause expression with no components!"); 10125 assert(CurComponents.back().getAssociatedDeclaration() == VD && 10126 "Map clause expression with unexpected base!"); 10127 10128 // Variables to help detecting enclosing problems in data environment nests. 10129 bool IsEnclosedByDataEnvironmentExpr = false; 10130 const Expr *EnclosingExpr = nullptr; 10131 10132 bool FoundError = DSAS->checkMappableExprComponentListsForDecl( 10133 VD, CurrentRegionOnly, 10134 [&](OMPClauseMappableExprCommon::MappableExprComponentListRef 10135 StackComponents, 10136 OpenMPClauseKind) -> bool { 10137 10138 assert(!StackComponents.empty() && 10139 "Map clause expression with no components!"); 10140 assert(StackComponents.back().getAssociatedDeclaration() == VD && 10141 "Map clause expression with unexpected base!"); 10142 10143 // The whole expression in the stack. 10144 auto *RE = StackComponents.front().getAssociatedExpression(); 10145 10146 // Expressions must start from the same base. Here we detect at which 10147 // point both expressions diverge from each other and see if we can 10148 // detect if the memory referred to both expressions is contiguous and 10149 // do not overlap. 10150 auto CI = CurComponents.rbegin(); 10151 auto CE = CurComponents.rend(); 10152 auto SI = StackComponents.rbegin(); 10153 auto SE = StackComponents.rend(); 10154 for (; CI != CE && SI != SE; ++CI, ++SI) { 10155 10156 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.3] 10157 // At most one list item can be an array item derived from a given 10158 // variable in map clauses of the same construct. 10159 if (CurrentRegionOnly && 10160 (isa<ArraySubscriptExpr>(CI->getAssociatedExpression()) || 10161 isa<OMPArraySectionExpr>(CI->getAssociatedExpression())) && 10162 (isa<ArraySubscriptExpr>(SI->getAssociatedExpression()) || 10163 isa<OMPArraySectionExpr>(SI->getAssociatedExpression()))) { 10164 SemaRef.Diag(CI->getAssociatedExpression()->getExprLoc(), 10165 diag::err_omp_multiple_array_items_in_map_clause) 10166 << CI->getAssociatedExpression()->getSourceRange(); 10167 SemaRef.Diag(SI->getAssociatedExpression()->getExprLoc(), 10168 diag::note_used_here) 10169 << SI->getAssociatedExpression()->getSourceRange(); 10170 return true; 10171 } 10172 10173 // Do both expressions have the same kind? 10174 if (CI->getAssociatedExpression()->getStmtClass() != 10175 SI->getAssociatedExpression()->getStmtClass()) 10176 break; 10177 10178 // Are we dealing with different variables/fields? 10179 if (CI->getAssociatedDeclaration() != SI->getAssociatedDeclaration()) 10180 break; 10181 } 10182 // Check if the extra components of the expressions in the enclosing 10183 // data environment are redundant for the current base declaration. 10184 // If they are, the maps completely overlap, which is legal. 10185 for (; SI != SE; ++SI) { 10186 QualType Type; 10187 if (auto *ASE = 10188 dyn_cast<ArraySubscriptExpr>(SI->getAssociatedExpression())) { 10189 Type = ASE->getBase()->IgnoreParenImpCasts()->getType(); 10190 } else if (auto *OASE = dyn_cast<OMPArraySectionExpr>( 10191 SI->getAssociatedExpression())) { 10192 auto *E = OASE->getBase()->IgnoreParenImpCasts(); 10193 Type = 10194 OMPArraySectionExpr::getBaseOriginalType(E).getCanonicalType(); 10195 } 10196 if (Type.isNull() || Type->isAnyPointerType() || 10197 CheckArrayExpressionDoesNotReferToWholeSize( 10198 SemaRef, SI->getAssociatedExpression(), Type)) 10199 break; 10200 } 10201 10202 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.4] 10203 // List items of map clauses in the same construct must not share 10204 // original storage. 10205 // 10206 // If the expressions are exactly the same or one is a subset of the 10207 // other, it means they are sharing storage. 10208 if (CI == CE && SI == SE) { 10209 if (CurrentRegionOnly) { 10210 if (CKind == OMPC_map) 10211 SemaRef.Diag(ELoc, diag::err_omp_map_shared_storage) << ERange; 10212 else { 10213 assert(CKind == OMPC_to || CKind == OMPC_from); 10214 SemaRef.Diag(ELoc, diag::err_omp_once_referenced_in_target_update) 10215 << ERange; 10216 } 10217 SemaRef.Diag(RE->getExprLoc(), diag::note_used_here) 10218 << RE->getSourceRange(); 10219 return true; 10220 } else { 10221 // If we find the same expression in the enclosing data environment, 10222 // that is legal. 10223 IsEnclosedByDataEnvironmentExpr = true; 10224 return false; 10225 } 10226 } 10227 10228 QualType DerivedType = 10229 std::prev(CI)->getAssociatedDeclaration()->getType(); 10230 SourceLocation DerivedLoc = 10231 std::prev(CI)->getAssociatedExpression()->getExprLoc(); 10232 10233 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C++, p.1] 10234 // If the type of a list item is a reference to a type T then the type 10235 // will be considered to be T for all purposes of this clause. 10236 DerivedType = DerivedType.getNonReferenceType(); 10237 10238 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C/C++, p.1] 10239 // A variable for which the type is pointer and an array section 10240 // derived from that variable must not appear as list items of map 10241 // clauses of the same construct. 10242 // 10243 // Also, cover one of the cases in: 10244 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.5] 10245 // If any part of the original storage of a list item has corresponding 10246 // storage in the device data environment, all of the original storage 10247 // must have corresponding storage in the device data environment. 10248 // 10249 if (DerivedType->isAnyPointerType()) { 10250 if (CI == CE || SI == SE) { 10251 SemaRef.Diag( 10252 DerivedLoc, 10253 diag::err_omp_pointer_mapped_along_with_derived_section) 10254 << DerivedLoc; 10255 } else { 10256 assert(CI != CE && SI != SE); 10257 SemaRef.Diag(DerivedLoc, diag::err_omp_same_pointer_derreferenced) 10258 << DerivedLoc; 10259 } 10260 SemaRef.Diag(RE->getExprLoc(), diag::note_used_here) 10261 << RE->getSourceRange(); 10262 return true; 10263 } 10264 10265 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.4] 10266 // List items of map clauses in the same construct must not share 10267 // original storage. 10268 // 10269 // An expression is a subset of the other. 10270 if (CurrentRegionOnly && (CI == CE || SI == SE)) { 10271 if (CKind == OMPC_map) 10272 SemaRef.Diag(ELoc, diag::err_omp_map_shared_storage) << ERange; 10273 else { 10274 assert(CKind == OMPC_to || CKind == OMPC_from); 10275 SemaRef.Diag(ELoc, diag::err_omp_once_referenced_in_target_update) 10276 << ERange; 10277 } 10278 SemaRef.Diag(RE->getExprLoc(), diag::note_used_here) 10279 << RE->getSourceRange(); 10280 return true; 10281 } 10282 10283 // The current expression uses the same base as other expression in the 10284 // data environment but does not contain it completely. 10285 if (!CurrentRegionOnly && SI != SE) 10286 EnclosingExpr = RE; 10287 10288 // The current expression is a subset of the expression in the data 10289 // environment. 10290 IsEnclosedByDataEnvironmentExpr |= 10291 (!CurrentRegionOnly && CI != CE && SI == SE); 10292 10293 return false; 10294 }); 10295 10296 if (CurrentRegionOnly) 10297 return FoundError; 10298 10299 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.5] 10300 // If any part of the original storage of a list item has corresponding 10301 // storage in the device data environment, all of the original storage must 10302 // have corresponding storage in the device data environment. 10303 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.6] 10304 // If a list item is an element of a structure, and a different element of 10305 // the structure has a corresponding list item in the device data environment 10306 // prior to a task encountering the construct associated with the map clause, 10307 // then the list item must also have a corresponding list item in the device 10308 // data environment prior to the task encountering the construct. 10309 // 10310 if (EnclosingExpr && !IsEnclosedByDataEnvironmentExpr) { 10311 SemaRef.Diag(ELoc, 10312 diag::err_omp_original_storage_is_shared_and_does_not_contain) 10313 << ERange; 10314 SemaRef.Diag(EnclosingExpr->getExprLoc(), diag::note_used_here) 10315 << EnclosingExpr->getSourceRange(); 10316 return true; 10317 } 10318 10319 return FoundError; 10320 } 10321 10322 namespace { 10323 // Utility struct that gathers all the related lists associated with a mappable 10324 // expression. 10325 struct MappableVarListInfo final { 10326 // The list of expressions. 10327 ArrayRef<Expr *> VarList; 10328 // The list of processed expressions. 10329 SmallVector<Expr *, 16> ProcessedVarList; 10330 // The mappble components for each expression. 10331 OMPClauseMappableExprCommon::MappableExprComponentLists VarComponents; 10332 // The base declaration of the variable. 10333 SmallVector<ValueDecl *, 16> VarBaseDeclarations; 10334 10335 MappableVarListInfo(ArrayRef<Expr *> VarList) : VarList(VarList) { 10336 // We have a list of components and base declarations for each entry in the 10337 // variable list. 10338 VarComponents.reserve(VarList.size()); 10339 VarBaseDeclarations.reserve(VarList.size()); 10340 } 10341 }; 10342 } 10343 10344 // Check the validity of the provided variable list for the provided clause kind 10345 // \a CKind. In the check process the valid expressions, and mappable expression 10346 // components and variables are extracted and used to fill \a Vars, 10347 // \a ClauseComponents, and \a ClauseBaseDeclarations. \a MapType and 10348 // \a IsMapTypeImplicit are expected to be valid if the clause kind is 'map'. 10349 static void 10350 checkMappableExpressionList(Sema &SemaRef, DSAStackTy *DSAS, 10351 OpenMPClauseKind CKind, MappableVarListInfo &MVLI, 10352 SourceLocation StartLoc, 10353 OpenMPMapClauseKind MapType = OMPC_MAP_unknown, 10354 bool IsMapTypeImplicit = false) { 10355 // We only expect mappable expressions in 'to', 'from', and 'map' clauses. 10356 assert((CKind == OMPC_map || CKind == OMPC_to || CKind == OMPC_from) && 10357 "Unexpected clause kind with mappable expressions!"); 10358 10359 // Keep track of the mappable components and base declarations in this clause. 10360 // Each entry in the list is going to have a list of components associated. We 10361 // record each set of the components so that we can build the clause later on. 10362 // In the end we should have the same amount of declarations and component 10363 // lists. 10364 10365 for (auto &RE : MVLI.VarList) { 10366 assert(RE && "Null expr in omp to/from/map clause"); 10367 SourceLocation ELoc = RE->getExprLoc(); 10368 10369 auto *VE = RE->IgnoreParenLValueCasts(); 10370 10371 if (VE->isValueDependent() || VE->isTypeDependent() || 10372 VE->isInstantiationDependent() || 10373 VE->containsUnexpandedParameterPack()) { 10374 // We can only analyze this information once the missing information is 10375 // resolved. 10376 MVLI.ProcessedVarList.push_back(RE); 10377 continue; 10378 } 10379 10380 auto *SimpleExpr = RE->IgnoreParenCasts(); 10381 10382 if (!RE->IgnoreParenImpCasts()->isLValue()) { 10383 SemaRef.Diag(ELoc, 10384 diag::err_omp_expected_named_var_member_or_array_expression) 10385 << RE->getSourceRange(); 10386 continue; 10387 } 10388 10389 OMPClauseMappableExprCommon::MappableExprComponentList CurComponents; 10390 ValueDecl *CurDeclaration = nullptr; 10391 10392 // Obtain the array or member expression bases if required. Also, fill the 10393 // components array with all the components identified in the process. 10394 auto *BE = 10395 CheckMapClauseExpressionBase(SemaRef, SimpleExpr, CurComponents, CKind); 10396 if (!BE) 10397 continue; 10398 10399 assert(!CurComponents.empty() && 10400 "Invalid mappable expression information."); 10401 10402 // For the following checks, we rely on the base declaration which is 10403 // expected to be associated with the last component. The declaration is 10404 // expected to be a variable or a field (if 'this' is being mapped). 10405 CurDeclaration = CurComponents.back().getAssociatedDeclaration(); 10406 assert(CurDeclaration && "Null decl on map clause."); 10407 assert( 10408 CurDeclaration->isCanonicalDecl() && 10409 "Expecting components to have associated only canonical declarations."); 10410 10411 auto *VD = dyn_cast<VarDecl>(CurDeclaration); 10412 auto *FD = dyn_cast<FieldDecl>(CurDeclaration); 10413 10414 assert((VD || FD) && "Only variables or fields are expected here!"); 10415 (void)FD; 10416 10417 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.10] 10418 // threadprivate variables cannot appear in a map clause. 10419 // OpenMP 4.5 [2.10.5, target update Construct] 10420 // threadprivate variables cannot appear in a from clause. 10421 if (VD && DSAS->isThreadPrivate(VD)) { 10422 auto DVar = DSAS->getTopDSA(VD, false); 10423 SemaRef.Diag(ELoc, diag::err_omp_threadprivate_in_clause) 10424 << getOpenMPClauseName(CKind); 10425 ReportOriginalDSA(SemaRef, DSAS, VD, DVar); 10426 continue; 10427 } 10428 10429 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.9] 10430 // A list item cannot appear in both a map clause and a data-sharing 10431 // attribute clause on the same construct. 10432 10433 // Check conflicts with other map clause expressions. We check the conflicts 10434 // with the current construct separately from the enclosing data 10435 // environment, because the restrictions are different. We only have to 10436 // check conflicts across regions for the map clauses. 10437 if (CheckMapConflicts(SemaRef, DSAS, CurDeclaration, SimpleExpr, 10438 /*CurrentRegionOnly=*/true, CurComponents, CKind)) 10439 break; 10440 if (CKind == OMPC_map && 10441 CheckMapConflicts(SemaRef, DSAS, CurDeclaration, SimpleExpr, 10442 /*CurrentRegionOnly=*/false, CurComponents, CKind)) 10443 break; 10444 10445 // OpenMP 4.5 [2.10.5, target update Construct] 10446 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C++, p.1] 10447 // If the type of a list item is a reference to a type T then the type will 10448 // be considered to be T for all purposes of this clause. 10449 QualType Type = CurDeclaration->getType().getNonReferenceType(); 10450 10451 // OpenMP 4.5 [2.10.5, target update Construct, Restrictions, p.4] 10452 // A list item in a to or from clause must have a mappable type. 10453 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.9] 10454 // A list item must have a mappable type. 10455 if (!CheckTypeMappable(VE->getExprLoc(), VE->getSourceRange(), SemaRef, 10456 DSAS, Type)) 10457 continue; 10458 10459 if (CKind == OMPC_map) { 10460 // target enter data 10461 // OpenMP [2.10.2, Restrictions, p. 99] 10462 // A map-type must be specified in all map clauses and must be either 10463 // to or alloc. 10464 OpenMPDirectiveKind DKind = DSAS->getCurrentDirective(); 10465 if (DKind == OMPD_target_enter_data && 10466 !(MapType == OMPC_MAP_to || MapType == OMPC_MAP_alloc)) { 10467 SemaRef.Diag(StartLoc, diag::err_omp_invalid_map_type_for_directive) 10468 << (IsMapTypeImplicit ? 1 : 0) 10469 << getOpenMPSimpleClauseTypeName(OMPC_map, MapType) 10470 << getOpenMPDirectiveName(DKind); 10471 continue; 10472 } 10473 10474 // target exit_data 10475 // OpenMP [2.10.3, Restrictions, p. 102] 10476 // A map-type must be specified in all map clauses and must be either 10477 // from, release, or delete. 10478 if (DKind == OMPD_target_exit_data && 10479 !(MapType == OMPC_MAP_from || MapType == OMPC_MAP_release || 10480 MapType == OMPC_MAP_delete)) { 10481 SemaRef.Diag(StartLoc, diag::err_omp_invalid_map_type_for_directive) 10482 << (IsMapTypeImplicit ? 1 : 0) 10483 << getOpenMPSimpleClauseTypeName(OMPC_map, MapType) 10484 << getOpenMPDirectiveName(DKind); 10485 continue; 10486 } 10487 10488 // OpenMP 4.5 [2.15.5.1, Restrictions, p.3] 10489 // A list item cannot appear in both a map clause and a data-sharing 10490 // attribute clause on the same construct 10491 if ((DKind == OMPD_target || DKind == OMPD_target_teams || 10492 DKind == OMPD_target_teams_distribute || 10493 DKind == OMPD_target_teams_distribute_parallel_for || 10494 DKind == OMPD_target_teams_distribute_parallel_for_simd || 10495 DKind == OMPD_target_teams_distribute_simd) && VD) { 10496 auto DVar = DSAS->getTopDSA(VD, false); 10497 if (isOpenMPPrivate(DVar.CKind)) { 10498 SemaRef.Diag(ELoc, diag::err_omp_variable_in_given_clause_and_dsa) 10499 << getOpenMPClauseName(DVar.CKind) 10500 << getOpenMPClauseName(OMPC_map) 10501 << getOpenMPDirectiveName(DSAS->getCurrentDirective()); 10502 ReportOriginalDSA(SemaRef, DSAS, CurDeclaration, DVar); 10503 continue; 10504 } 10505 } 10506 } 10507 10508 // Save the current expression. 10509 MVLI.ProcessedVarList.push_back(RE); 10510 10511 // Store the components in the stack so that they can be used to check 10512 // against other clauses later on. 10513 DSAS->addMappableExpressionComponents(CurDeclaration, CurComponents, 10514 /*WhereFoundClauseKind=*/OMPC_map); 10515 10516 // Save the components and declaration to create the clause. For purposes of 10517 // the clause creation, any component list that has has base 'this' uses 10518 // null as base declaration. 10519 MVLI.VarComponents.resize(MVLI.VarComponents.size() + 1); 10520 MVLI.VarComponents.back().append(CurComponents.begin(), 10521 CurComponents.end()); 10522 MVLI.VarBaseDeclarations.push_back(isa<MemberExpr>(BE) ? nullptr 10523 : CurDeclaration); 10524 } 10525 } 10526 10527 OMPClause * 10528 Sema::ActOnOpenMPMapClause(OpenMPMapClauseKind MapTypeModifier, 10529 OpenMPMapClauseKind MapType, bool IsMapTypeImplicit, 10530 SourceLocation MapLoc, SourceLocation ColonLoc, 10531 ArrayRef<Expr *> VarList, SourceLocation StartLoc, 10532 SourceLocation LParenLoc, SourceLocation EndLoc) { 10533 MappableVarListInfo MVLI(VarList); 10534 checkMappableExpressionList(*this, DSAStack, OMPC_map, MVLI, StartLoc, 10535 MapType, IsMapTypeImplicit); 10536 10537 // We need to produce a map clause even if we don't have variables so that 10538 // other diagnostics related with non-existing map clauses are accurate. 10539 return OMPMapClause::Create(Context, StartLoc, LParenLoc, EndLoc, 10540 MVLI.ProcessedVarList, MVLI.VarBaseDeclarations, 10541 MVLI.VarComponents, MapTypeModifier, MapType, 10542 IsMapTypeImplicit, MapLoc); 10543 } 10544 10545 QualType Sema::ActOnOpenMPDeclareReductionType(SourceLocation TyLoc, 10546 TypeResult ParsedType) { 10547 assert(ParsedType.isUsable()); 10548 10549 QualType ReductionType = GetTypeFromParser(ParsedType.get()); 10550 if (ReductionType.isNull()) 10551 return QualType(); 10552 10553 // [OpenMP 4.0], 2.15 declare reduction Directive, Restrictions, C\C++ 10554 // A type name in a declare reduction directive cannot be a function type, an 10555 // array type, a reference type, or a type qualified with const, volatile or 10556 // restrict. 10557 if (ReductionType.hasQualifiers()) { 10558 Diag(TyLoc, diag::err_omp_reduction_wrong_type) << 0; 10559 return QualType(); 10560 } 10561 10562 if (ReductionType->isFunctionType()) { 10563 Diag(TyLoc, diag::err_omp_reduction_wrong_type) << 1; 10564 return QualType(); 10565 } 10566 if (ReductionType->isReferenceType()) { 10567 Diag(TyLoc, diag::err_omp_reduction_wrong_type) << 2; 10568 return QualType(); 10569 } 10570 if (ReductionType->isArrayType()) { 10571 Diag(TyLoc, diag::err_omp_reduction_wrong_type) << 3; 10572 return QualType(); 10573 } 10574 return ReductionType; 10575 } 10576 10577 Sema::DeclGroupPtrTy Sema::ActOnOpenMPDeclareReductionDirectiveStart( 10578 Scope *S, DeclContext *DC, DeclarationName Name, 10579 ArrayRef<std::pair<QualType, SourceLocation>> ReductionTypes, 10580 AccessSpecifier AS, Decl *PrevDeclInScope) { 10581 SmallVector<Decl *, 8> Decls; 10582 Decls.reserve(ReductionTypes.size()); 10583 10584 LookupResult Lookup(*this, Name, SourceLocation(), LookupOMPReductionName, 10585 ForRedeclaration); 10586 // [OpenMP 4.0], 2.15 declare reduction Directive, Restrictions 10587 // A reduction-identifier may not be re-declared in the current scope for the 10588 // same type or for a type that is compatible according to the base language 10589 // rules. 10590 llvm::DenseMap<QualType, SourceLocation> PreviousRedeclTypes; 10591 OMPDeclareReductionDecl *PrevDRD = nullptr; 10592 bool InCompoundScope = true; 10593 if (S != nullptr) { 10594 // Find previous declaration with the same name not referenced in other 10595 // declarations. 10596 FunctionScopeInfo *ParentFn = getEnclosingFunction(); 10597 InCompoundScope = 10598 (ParentFn != nullptr) && !ParentFn->CompoundScopes.empty(); 10599 LookupName(Lookup, S); 10600 FilterLookupForScope(Lookup, DC, S, /*ConsiderLinkage=*/false, 10601 /*AllowInlineNamespace=*/false); 10602 llvm::DenseMap<OMPDeclareReductionDecl *, bool> UsedAsPrevious; 10603 auto Filter = Lookup.makeFilter(); 10604 while (Filter.hasNext()) { 10605 auto *PrevDecl = cast<OMPDeclareReductionDecl>(Filter.next()); 10606 if (InCompoundScope) { 10607 auto I = UsedAsPrevious.find(PrevDecl); 10608 if (I == UsedAsPrevious.end()) 10609 UsedAsPrevious[PrevDecl] = false; 10610 if (auto *D = PrevDecl->getPrevDeclInScope()) 10611 UsedAsPrevious[D] = true; 10612 } 10613 PreviousRedeclTypes[PrevDecl->getType().getCanonicalType()] = 10614 PrevDecl->getLocation(); 10615 } 10616 Filter.done(); 10617 if (InCompoundScope) { 10618 for (auto &PrevData : UsedAsPrevious) { 10619 if (!PrevData.second) { 10620 PrevDRD = PrevData.first; 10621 break; 10622 } 10623 } 10624 } 10625 } else if (PrevDeclInScope != nullptr) { 10626 auto *PrevDRDInScope = PrevDRD = 10627 cast<OMPDeclareReductionDecl>(PrevDeclInScope); 10628 do { 10629 PreviousRedeclTypes[PrevDRDInScope->getType().getCanonicalType()] = 10630 PrevDRDInScope->getLocation(); 10631 PrevDRDInScope = PrevDRDInScope->getPrevDeclInScope(); 10632 } while (PrevDRDInScope != nullptr); 10633 } 10634 for (auto &TyData : ReductionTypes) { 10635 auto I = PreviousRedeclTypes.find(TyData.first.getCanonicalType()); 10636 bool Invalid = false; 10637 if (I != PreviousRedeclTypes.end()) { 10638 Diag(TyData.second, diag::err_omp_declare_reduction_redefinition) 10639 << TyData.first; 10640 Diag(I->second, diag::note_previous_definition); 10641 Invalid = true; 10642 } 10643 PreviousRedeclTypes[TyData.first.getCanonicalType()] = TyData.second; 10644 auto *DRD = OMPDeclareReductionDecl::Create(Context, DC, TyData.second, 10645 Name, TyData.first, PrevDRD); 10646 DC->addDecl(DRD); 10647 DRD->setAccess(AS); 10648 Decls.push_back(DRD); 10649 if (Invalid) 10650 DRD->setInvalidDecl(); 10651 else 10652 PrevDRD = DRD; 10653 } 10654 10655 return DeclGroupPtrTy::make( 10656 DeclGroupRef::Create(Context, Decls.begin(), Decls.size())); 10657 } 10658 10659 void Sema::ActOnOpenMPDeclareReductionCombinerStart(Scope *S, Decl *D) { 10660 auto *DRD = cast<OMPDeclareReductionDecl>(D); 10661 10662 // Enter new function scope. 10663 PushFunctionScope(); 10664 getCurFunction()->setHasBranchProtectedScope(); 10665 getCurFunction()->setHasOMPDeclareReductionCombiner(); 10666 10667 if (S != nullptr) 10668 PushDeclContext(S, DRD); 10669 else 10670 CurContext = DRD; 10671 10672 PushExpressionEvaluationContext(PotentiallyEvaluated); 10673 10674 QualType ReductionType = DRD->getType(); 10675 // Create 'T* omp_parm;T omp_in;'. All references to 'omp_in' will 10676 // be replaced by '*omp_parm' during codegen. This required because 'omp_in' 10677 // uses semantics of argument handles by value, but it should be passed by 10678 // reference. C lang does not support references, so pass all parameters as 10679 // pointers. 10680 // Create 'T omp_in;' variable. 10681 auto *OmpInParm = 10682 buildVarDecl(*this, D->getLocation(), ReductionType, "omp_in"); 10683 // Create 'T* omp_parm;T omp_out;'. All references to 'omp_out' will 10684 // be replaced by '*omp_parm' during codegen. This required because 'omp_out' 10685 // uses semantics of argument handles by value, but it should be passed by 10686 // reference. C lang does not support references, so pass all parameters as 10687 // pointers. 10688 // Create 'T omp_out;' variable. 10689 auto *OmpOutParm = 10690 buildVarDecl(*this, D->getLocation(), ReductionType, "omp_out"); 10691 if (S != nullptr) { 10692 PushOnScopeChains(OmpInParm, S); 10693 PushOnScopeChains(OmpOutParm, S); 10694 } else { 10695 DRD->addDecl(OmpInParm); 10696 DRD->addDecl(OmpOutParm); 10697 } 10698 } 10699 10700 void Sema::ActOnOpenMPDeclareReductionCombinerEnd(Decl *D, Expr *Combiner) { 10701 auto *DRD = cast<OMPDeclareReductionDecl>(D); 10702 DiscardCleanupsInEvaluationContext(); 10703 PopExpressionEvaluationContext(); 10704 10705 PopDeclContext(); 10706 PopFunctionScopeInfo(); 10707 10708 if (Combiner != nullptr) 10709 DRD->setCombiner(Combiner); 10710 else 10711 DRD->setInvalidDecl(); 10712 } 10713 10714 void Sema::ActOnOpenMPDeclareReductionInitializerStart(Scope *S, Decl *D) { 10715 auto *DRD = cast<OMPDeclareReductionDecl>(D); 10716 10717 // Enter new function scope. 10718 PushFunctionScope(); 10719 getCurFunction()->setHasBranchProtectedScope(); 10720 10721 if (S != nullptr) 10722 PushDeclContext(S, DRD); 10723 else 10724 CurContext = DRD; 10725 10726 PushExpressionEvaluationContext(PotentiallyEvaluated); 10727 10728 QualType ReductionType = DRD->getType(); 10729 // Create 'T* omp_parm;T omp_priv;'. All references to 'omp_priv' will 10730 // be replaced by '*omp_parm' during codegen. This required because 'omp_priv' 10731 // uses semantics of argument handles by value, but it should be passed by 10732 // reference. C lang does not support references, so pass all parameters as 10733 // pointers. 10734 // Create 'T omp_priv;' variable. 10735 auto *OmpPrivParm = 10736 buildVarDecl(*this, D->getLocation(), ReductionType, "omp_priv"); 10737 // Create 'T* omp_parm;T omp_orig;'. All references to 'omp_orig' will 10738 // be replaced by '*omp_parm' during codegen. This required because 'omp_orig' 10739 // uses semantics of argument handles by value, but it should be passed by 10740 // reference. C lang does not support references, so pass all parameters as 10741 // pointers. 10742 // Create 'T omp_orig;' variable. 10743 auto *OmpOrigParm = 10744 buildVarDecl(*this, D->getLocation(), ReductionType, "omp_orig"); 10745 if (S != nullptr) { 10746 PushOnScopeChains(OmpPrivParm, S); 10747 PushOnScopeChains(OmpOrigParm, S); 10748 } else { 10749 DRD->addDecl(OmpPrivParm); 10750 DRD->addDecl(OmpOrigParm); 10751 } 10752 } 10753 10754 void Sema::ActOnOpenMPDeclareReductionInitializerEnd(Decl *D, 10755 Expr *Initializer) { 10756 auto *DRD = cast<OMPDeclareReductionDecl>(D); 10757 DiscardCleanupsInEvaluationContext(); 10758 PopExpressionEvaluationContext(); 10759 10760 PopDeclContext(); 10761 PopFunctionScopeInfo(); 10762 10763 if (Initializer != nullptr) 10764 DRD->setInitializer(Initializer); 10765 else 10766 DRD->setInvalidDecl(); 10767 } 10768 10769 Sema::DeclGroupPtrTy Sema::ActOnOpenMPDeclareReductionDirectiveEnd( 10770 Scope *S, DeclGroupPtrTy DeclReductions, bool IsValid) { 10771 for (auto *D : DeclReductions.get()) { 10772 if (IsValid) { 10773 auto *DRD = cast<OMPDeclareReductionDecl>(D); 10774 if (S != nullptr) 10775 PushOnScopeChains(DRD, S, /*AddToContext=*/false); 10776 } else 10777 D->setInvalidDecl(); 10778 } 10779 return DeclReductions; 10780 } 10781 10782 OMPClause *Sema::ActOnOpenMPNumTeamsClause(Expr *NumTeams, 10783 SourceLocation StartLoc, 10784 SourceLocation LParenLoc, 10785 SourceLocation EndLoc) { 10786 Expr *ValExpr = NumTeams; 10787 10788 // OpenMP [teams Constrcut, Restrictions] 10789 // The num_teams expression must evaluate to a positive integer value. 10790 if (!IsNonNegativeIntegerValue(ValExpr, *this, OMPC_num_teams, 10791 /*StrictlyPositive=*/true)) 10792 return nullptr; 10793 10794 return new (Context) OMPNumTeamsClause(ValExpr, StartLoc, LParenLoc, EndLoc); 10795 } 10796 10797 OMPClause *Sema::ActOnOpenMPThreadLimitClause(Expr *ThreadLimit, 10798 SourceLocation StartLoc, 10799 SourceLocation LParenLoc, 10800 SourceLocation EndLoc) { 10801 Expr *ValExpr = ThreadLimit; 10802 10803 // OpenMP [teams Constrcut, Restrictions] 10804 // The thread_limit expression must evaluate to a positive integer value. 10805 if (!IsNonNegativeIntegerValue(ValExpr, *this, OMPC_thread_limit, 10806 /*StrictlyPositive=*/true)) 10807 return nullptr; 10808 10809 return new (Context) 10810 OMPThreadLimitClause(ValExpr, StartLoc, LParenLoc, EndLoc); 10811 } 10812 10813 OMPClause *Sema::ActOnOpenMPPriorityClause(Expr *Priority, 10814 SourceLocation StartLoc, 10815 SourceLocation LParenLoc, 10816 SourceLocation EndLoc) { 10817 Expr *ValExpr = Priority; 10818 10819 // OpenMP [2.9.1, task Constrcut] 10820 // The priority-value is a non-negative numerical scalar expression. 10821 if (!IsNonNegativeIntegerValue(ValExpr, *this, OMPC_priority, 10822 /*StrictlyPositive=*/false)) 10823 return nullptr; 10824 10825 return new (Context) OMPPriorityClause(ValExpr, StartLoc, LParenLoc, EndLoc); 10826 } 10827 10828 OMPClause *Sema::ActOnOpenMPGrainsizeClause(Expr *Grainsize, 10829 SourceLocation StartLoc, 10830 SourceLocation LParenLoc, 10831 SourceLocation EndLoc) { 10832 Expr *ValExpr = Grainsize; 10833 10834 // OpenMP [2.9.2, taskloop Constrcut] 10835 // The parameter of the grainsize clause must be a positive integer 10836 // expression. 10837 if (!IsNonNegativeIntegerValue(ValExpr, *this, OMPC_grainsize, 10838 /*StrictlyPositive=*/true)) 10839 return nullptr; 10840 10841 return new (Context) OMPGrainsizeClause(ValExpr, StartLoc, LParenLoc, EndLoc); 10842 } 10843 10844 OMPClause *Sema::ActOnOpenMPNumTasksClause(Expr *NumTasks, 10845 SourceLocation StartLoc, 10846 SourceLocation LParenLoc, 10847 SourceLocation EndLoc) { 10848 Expr *ValExpr = NumTasks; 10849 10850 // OpenMP [2.9.2, taskloop Constrcut] 10851 // The parameter of the num_tasks clause must be a positive integer 10852 // expression. 10853 if (!IsNonNegativeIntegerValue(ValExpr, *this, OMPC_num_tasks, 10854 /*StrictlyPositive=*/true)) 10855 return nullptr; 10856 10857 return new (Context) OMPNumTasksClause(ValExpr, StartLoc, LParenLoc, EndLoc); 10858 } 10859 10860 OMPClause *Sema::ActOnOpenMPHintClause(Expr *Hint, SourceLocation StartLoc, 10861 SourceLocation LParenLoc, 10862 SourceLocation EndLoc) { 10863 // OpenMP [2.13.2, critical construct, Description] 10864 // ... where hint-expression is an integer constant expression that evaluates 10865 // to a valid lock hint. 10866 ExprResult HintExpr = VerifyPositiveIntegerConstantInClause(Hint, OMPC_hint); 10867 if (HintExpr.isInvalid()) 10868 return nullptr; 10869 return new (Context) 10870 OMPHintClause(HintExpr.get(), StartLoc, LParenLoc, EndLoc); 10871 } 10872 10873 OMPClause *Sema::ActOnOpenMPDistScheduleClause( 10874 OpenMPDistScheduleClauseKind Kind, Expr *ChunkSize, SourceLocation StartLoc, 10875 SourceLocation LParenLoc, SourceLocation KindLoc, SourceLocation CommaLoc, 10876 SourceLocation EndLoc) { 10877 if (Kind == OMPC_DIST_SCHEDULE_unknown) { 10878 std::string Values; 10879 Values += "'"; 10880 Values += getOpenMPSimpleClauseTypeName(OMPC_dist_schedule, 0); 10881 Values += "'"; 10882 Diag(KindLoc, diag::err_omp_unexpected_clause_value) 10883 << Values << getOpenMPClauseName(OMPC_dist_schedule); 10884 return nullptr; 10885 } 10886 Expr *ValExpr = ChunkSize; 10887 Stmt *HelperValStmt = nullptr; 10888 if (ChunkSize) { 10889 if (!ChunkSize->isValueDependent() && !ChunkSize->isTypeDependent() && 10890 !ChunkSize->isInstantiationDependent() && 10891 !ChunkSize->containsUnexpandedParameterPack()) { 10892 SourceLocation ChunkSizeLoc = ChunkSize->getLocStart(); 10893 ExprResult Val = 10894 PerformOpenMPImplicitIntegerConversion(ChunkSizeLoc, ChunkSize); 10895 if (Val.isInvalid()) 10896 return nullptr; 10897 10898 ValExpr = Val.get(); 10899 10900 // OpenMP [2.7.1, Restrictions] 10901 // chunk_size must be a loop invariant integer expression with a positive 10902 // value. 10903 llvm::APSInt Result; 10904 if (ValExpr->isIntegerConstantExpr(Result, Context)) { 10905 if (Result.isSigned() && !Result.isStrictlyPositive()) { 10906 Diag(ChunkSizeLoc, diag::err_omp_negative_expression_in_clause) 10907 << "dist_schedule" << ChunkSize->getSourceRange(); 10908 return nullptr; 10909 } 10910 } else if (isParallelOrTaskRegion(DSAStack->getCurrentDirective()) && 10911 !CurContext->isDependentContext()) { 10912 llvm::MapVector<Expr *, DeclRefExpr *> Captures; 10913 ValExpr = tryBuildCapture(*this, ValExpr, Captures).get(); 10914 HelperValStmt = buildPreInits(Context, Captures); 10915 } 10916 } 10917 } 10918 10919 return new (Context) 10920 OMPDistScheduleClause(StartLoc, LParenLoc, KindLoc, CommaLoc, EndLoc, 10921 Kind, ValExpr, HelperValStmt); 10922 } 10923 10924 OMPClause *Sema::ActOnOpenMPDefaultmapClause( 10925 OpenMPDefaultmapClauseModifier M, OpenMPDefaultmapClauseKind Kind, 10926 SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation MLoc, 10927 SourceLocation KindLoc, SourceLocation EndLoc) { 10928 // OpenMP 4.5 only supports 'defaultmap(tofrom: scalar)' 10929 if (M != OMPC_DEFAULTMAP_MODIFIER_tofrom || Kind != OMPC_DEFAULTMAP_scalar) { 10930 std::string Value; 10931 SourceLocation Loc; 10932 Value += "'"; 10933 if (M != OMPC_DEFAULTMAP_MODIFIER_tofrom) { 10934 Value += getOpenMPSimpleClauseTypeName(OMPC_defaultmap, 10935 OMPC_DEFAULTMAP_MODIFIER_tofrom); 10936 Loc = MLoc; 10937 } else { 10938 Value += getOpenMPSimpleClauseTypeName(OMPC_defaultmap, 10939 OMPC_DEFAULTMAP_scalar); 10940 Loc = KindLoc; 10941 } 10942 Value += "'"; 10943 Diag(Loc, diag::err_omp_unexpected_clause_value) 10944 << Value << getOpenMPClauseName(OMPC_defaultmap); 10945 return nullptr; 10946 } 10947 10948 return new (Context) 10949 OMPDefaultmapClause(StartLoc, LParenLoc, MLoc, KindLoc, EndLoc, Kind, M); 10950 } 10951 10952 bool Sema::ActOnStartOpenMPDeclareTargetDirective(SourceLocation Loc) { 10953 DeclContext *CurLexicalContext = getCurLexicalContext(); 10954 if (!CurLexicalContext->isFileContext() && 10955 !CurLexicalContext->isExternCContext() && 10956 !CurLexicalContext->isExternCXXContext()) { 10957 Diag(Loc, diag::err_omp_region_not_file_context); 10958 return false; 10959 } 10960 if (IsInOpenMPDeclareTargetContext) { 10961 Diag(Loc, diag::err_omp_enclosed_declare_target); 10962 return false; 10963 } 10964 10965 IsInOpenMPDeclareTargetContext = true; 10966 return true; 10967 } 10968 10969 void Sema::ActOnFinishOpenMPDeclareTargetDirective() { 10970 assert(IsInOpenMPDeclareTargetContext && 10971 "Unexpected ActOnFinishOpenMPDeclareTargetDirective"); 10972 10973 IsInOpenMPDeclareTargetContext = false; 10974 } 10975 10976 void Sema::ActOnOpenMPDeclareTargetName(Scope *CurScope, 10977 CXXScopeSpec &ScopeSpec, 10978 const DeclarationNameInfo &Id, 10979 OMPDeclareTargetDeclAttr::MapTypeTy MT, 10980 NamedDeclSetType &SameDirectiveDecls) { 10981 LookupResult Lookup(*this, Id, LookupOrdinaryName); 10982 LookupParsedName(Lookup, CurScope, &ScopeSpec, true); 10983 10984 if (Lookup.isAmbiguous()) 10985 return; 10986 Lookup.suppressDiagnostics(); 10987 10988 if (!Lookup.isSingleResult()) { 10989 if (TypoCorrection Corrected = 10990 CorrectTypo(Id, LookupOrdinaryName, CurScope, nullptr, 10991 llvm::make_unique<VarOrFuncDeclFilterCCC>(*this), 10992 CTK_ErrorRecovery)) { 10993 diagnoseTypo(Corrected, PDiag(diag::err_undeclared_var_use_suggest) 10994 << Id.getName()); 10995 checkDeclIsAllowedInOpenMPTarget(nullptr, Corrected.getCorrectionDecl()); 10996 return; 10997 } 10998 10999 Diag(Id.getLoc(), diag::err_undeclared_var_use) << Id.getName(); 11000 return; 11001 } 11002 11003 NamedDecl *ND = Lookup.getAsSingle<NamedDecl>(); 11004 if (isa<VarDecl>(ND) || isa<FunctionDecl>(ND)) { 11005 if (!SameDirectiveDecls.insert(cast<NamedDecl>(ND->getCanonicalDecl()))) 11006 Diag(Id.getLoc(), diag::err_omp_declare_target_multiple) << Id.getName(); 11007 11008 if (!ND->hasAttr<OMPDeclareTargetDeclAttr>()) { 11009 Attr *A = OMPDeclareTargetDeclAttr::CreateImplicit(Context, MT); 11010 ND->addAttr(A); 11011 if (ASTMutationListener *ML = Context.getASTMutationListener()) 11012 ML->DeclarationMarkedOpenMPDeclareTarget(ND, A); 11013 checkDeclIsAllowedInOpenMPTarget(nullptr, ND); 11014 } else if (ND->getAttr<OMPDeclareTargetDeclAttr>()->getMapType() != MT) { 11015 Diag(Id.getLoc(), diag::err_omp_declare_target_to_and_link) 11016 << Id.getName(); 11017 } 11018 } else 11019 Diag(Id.getLoc(), diag::err_omp_invalid_target_decl) << Id.getName(); 11020 } 11021 11022 static void checkDeclInTargetContext(SourceLocation SL, SourceRange SR, 11023 Sema &SemaRef, Decl *D) { 11024 if (!D) 11025 return; 11026 Decl *LD = nullptr; 11027 if (isa<TagDecl>(D)) { 11028 LD = cast<TagDecl>(D)->getDefinition(); 11029 } else if (isa<VarDecl>(D)) { 11030 LD = cast<VarDecl>(D)->getDefinition(); 11031 11032 // If this is an implicit variable that is legal and we do not need to do 11033 // anything. 11034 if (cast<VarDecl>(D)->isImplicit()) { 11035 Attr *A = OMPDeclareTargetDeclAttr::CreateImplicit( 11036 SemaRef.Context, OMPDeclareTargetDeclAttr::MT_To); 11037 D->addAttr(A); 11038 if (ASTMutationListener *ML = SemaRef.Context.getASTMutationListener()) 11039 ML->DeclarationMarkedOpenMPDeclareTarget(D, A); 11040 return; 11041 } 11042 11043 } else if (isa<FunctionDecl>(D)) { 11044 const FunctionDecl *FD = nullptr; 11045 if (cast<FunctionDecl>(D)->hasBody(FD)) 11046 LD = const_cast<FunctionDecl *>(FD); 11047 11048 // If the definition is associated with the current declaration in the 11049 // target region (it can be e.g. a lambda) that is legal and we do not need 11050 // to do anything else. 11051 if (LD == D) { 11052 Attr *A = OMPDeclareTargetDeclAttr::CreateImplicit( 11053 SemaRef.Context, OMPDeclareTargetDeclAttr::MT_To); 11054 D->addAttr(A); 11055 if (ASTMutationListener *ML = SemaRef.Context.getASTMutationListener()) 11056 ML->DeclarationMarkedOpenMPDeclareTarget(D, A); 11057 return; 11058 } 11059 } 11060 if (!LD) 11061 LD = D; 11062 if (LD && !LD->hasAttr<OMPDeclareTargetDeclAttr>() && 11063 (isa<VarDecl>(LD) || isa<FunctionDecl>(LD))) { 11064 // Outlined declaration is not declared target. 11065 if (LD->isOutOfLine()) { 11066 SemaRef.Diag(LD->getLocation(), diag::warn_omp_not_in_target_context); 11067 SemaRef.Diag(SL, diag::note_used_here) << SR; 11068 } else { 11069 DeclContext *DC = LD->getDeclContext(); 11070 while (DC) { 11071 if (isa<FunctionDecl>(DC) && 11072 cast<FunctionDecl>(DC)->hasAttr<OMPDeclareTargetDeclAttr>()) 11073 break; 11074 DC = DC->getParent(); 11075 } 11076 if (DC) 11077 return; 11078 11079 // Is not declared in target context. 11080 SemaRef.Diag(LD->getLocation(), diag::warn_omp_not_in_target_context); 11081 SemaRef.Diag(SL, diag::note_used_here) << SR; 11082 } 11083 // Mark decl as declared target to prevent further diagnostic. 11084 Attr *A = OMPDeclareTargetDeclAttr::CreateImplicit( 11085 SemaRef.Context, OMPDeclareTargetDeclAttr::MT_To); 11086 D->addAttr(A); 11087 if (ASTMutationListener *ML = SemaRef.Context.getASTMutationListener()) 11088 ML->DeclarationMarkedOpenMPDeclareTarget(D, A); 11089 } 11090 } 11091 11092 static bool checkValueDeclInTarget(SourceLocation SL, SourceRange SR, 11093 Sema &SemaRef, DSAStackTy *Stack, 11094 ValueDecl *VD) { 11095 if (VD->hasAttr<OMPDeclareTargetDeclAttr>()) 11096 return true; 11097 if (!CheckTypeMappable(SL, SR, SemaRef, Stack, VD->getType())) 11098 return false; 11099 return true; 11100 } 11101 11102 void Sema::checkDeclIsAllowedInOpenMPTarget(Expr *E, Decl *D) { 11103 if (!D || D->isInvalidDecl()) 11104 return; 11105 SourceRange SR = E ? E->getSourceRange() : D->getSourceRange(); 11106 SourceLocation SL = E ? E->getLocStart() : D->getLocation(); 11107 // 2.10.6: threadprivate variable cannot appear in a declare target directive. 11108 if (VarDecl *VD = dyn_cast<VarDecl>(D)) { 11109 if (DSAStack->isThreadPrivate(VD)) { 11110 Diag(SL, diag::err_omp_threadprivate_in_target); 11111 ReportOriginalDSA(*this, DSAStack, VD, DSAStack->getTopDSA(VD, false)); 11112 return; 11113 } 11114 } 11115 if (ValueDecl *VD = dyn_cast<ValueDecl>(D)) { 11116 // Problem if any with var declared with incomplete type will be reported 11117 // as normal, so no need to check it here. 11118 if ((E || !VD->getType()->isIncompleteType()) && 11119 !checkValueDeclInTarget(SL, SR, *this, DSAStack, VD)) { 11120 // Mark decl as declared target to prevent further diagnostic. 11121 if (isa<VarDecl>(VD) || isa<FunctionDecl>(VD)) { 11122 Attr *A = OMPDeclareTargetDeclAttr::CreateImplicit( 11123 Context, OMPDeclareTargetDeclAttr::MT_To); 11124 VD->addAttr(A); 11125 if (ASTMutationListener *ML = Context.getASTMutationListener()) 11126 ML->DeclarationMarkedOpenMPDeclareTarget(VD, A); 11127 } 11128 return; 11129 } 11130 } 11131 if (!E) { 11132 // Checking declaration inside declare target region. 11133 if (!D->hasAttr<OMPDeclareTargetDeclAttr>() && 11134 (isa<VarDecl>(D) || isa<FunctionDecl>(D))) { 11135 Attr *A = OMPDeclareTargetDeclAttr::CreateImplicit( 11136 Context, OMPDeclareTargetDeclAttr::MT_To); 11137 D->addAttr(A); 11138 if (ASTMutationListener *ML = Context.getASTMutationListener()) 11139 ML->DeclarationMarkedOpenMPDeclareTarget(D, A); 11140 } 11141 return; 11142 } 11143 checkDeclInTargetContext(E->getExprLoc(), E->getSourceRange(), *this, D); 11144 } 11145 11146 OMPClause *Sema::ActOnOpenMPToClause(ArrayRef<Expr *> VarList, 11147 SourceLocation StartLoc, 11148 SourceLocation LParenLoc, 11149 SourceLocation EndLoc) { 11150 MappableVarListInfo MVLI(VarList); 11151 checkMappableExpressionList(*this, DSAStack, OMPC_to, MVLI, StartLoc); 11152 if (MVLI.ProcessedVarList.empty()) 11153 return nullptr; 11154 11155 return OMPToClause::Create(Context, StartLoc, LParenLoc, EndLoc, 11156 MVLI.ProcessedVarList, MVLI.VarBaseDeclarations, 11157 MVLI.VarComponents); 11158 } 11159 11160 OMPClause *Sema::ActOnOpenMPFromClause(ArrayRef<Expr *> VarList, 11161 SourceLocation StartLoc, 11162 SourceLocation LParenLoc, 11163 SourceLocation EndLoc) { 11164 MappableVarListInfo MVLI(VarList); 11165 checkMappableExpressionList(*this, DSAStack, OMPC_from, MVLI, StartLoc); 11166 if (MVLI.ProcessedVarList.empty()) 11167 return nullptr; 11168 11169 return OMPFromClause::Create(Context, StartLoc, LParenLoc, EndLoc, 11170 MVLI.ProcessedVarList, MVLI.VarBaseDeclarations, 11171 MVLI.VarComponents); 11172 } 11173 11174 OMPClause *Sema::ActOnOpenMPUseDevicePtrClause(ArrayRef<Expr *> VarList, 11175 SourceLocation StartLoc, 11176 SourceLocation LParenLoc, 11177 SourceLocation EndLoc) { 11178 MappableVarListInfo MVLI(VarList); 11179 SmallVector<Expr *, 8> PrivateCopies; 11180 SmallVector<Expr *, 8> Inits; 11181 11182 for (auto &RefExpr : VarList) { 11183 assert(RefExpr && "NULL expr in OpenMP use_device_ptr clause."); 11184 SourceLocation ELoc; 11185 SourceRange ERange; 11186 Expr *SimpleRefExpr = RefExpr; 11187 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange); 11188 if (Res.second) { 11189 // It will be analyzed later. 11190 MVLI.ProcessedVarList.push_back(RefExpr); 11191 PrivateCopies.push_back(nullptr); 11192 Inits.push_back(nullptr); 11193 } 11194 ValueDecl *D = Res.first; 11195 if (!D) 11196 continue; 11197 11198 QualType Type = D->getType(); 11199 Type = Type.getNonReferenceType().getUnqualifiedType(); 11200 11201 auto *VD = dyn_cast<VarDecl>(D); 11202 11203 // Item should be a pointer or reference to pointer. 11204 if (!Type->isPointerType()) { 11205 Diag(ELoc, diag::err_omp_usedeviceptr_not_a_pointer) 11206 << 0 << RefExpr->getSourceRange(); 11207 continue; 11208 } 11209 11210 // Build the private variable and the expression that refers to it. 11211 auto VDPrivate = buildVarDecl(*this, ELoc, Type, D->getName(), 11212 D->hasAttrs() ? &D->getAttrs() : nullptr); 11213 if (VDPrivate->isInvalidDecl()) 11214 continue; 11215 11216 CurContext->addDecl(VDPrivate); 11217 auto VDPrivateRefExpr = buildDeclRefExpr( 11218 *this, VDPrivate, RefExpr->getType().getUnqualifiedType(), ELoc); 11219 11220 // Add temporary variable to initialize the private copy of the pointer. 11221 auto *VDInit = 11222 buildVarDecl(*this, RefExpr->getExprLoc(), Type, ".devptr.temp"); 11223 auto *VDInitRefExpr = buildDeclRefExpr(*this, VDInit, RefExpr->getType(), 11224 RefExpr->getExprLoc()); 11225 AddInitializerToDecl(VDPrivate, 11226 DefaultLvalueConversion(VDInitRefExpr).get(), 11227 /*DirectInit=*/false); 11228 11229 // If required, build a capture to implement the privatization initialized 11230 // with the current list item value. 11231 DeclRefExpr *Ref = nullptr; 11232 if (!VD) 11233 Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/true); 11234 MVLI.ProcessedVarList.push_back(VD ? RefExpr->IgnoreParens() : Ref); 11235 PrivateCopies.push_back(VDPrivateRefExpr); 11236 Inits.push_back(VDInitRefExpr); 11237 11238 // We need to add a data sharing attribute for this variable to make sure it 11239 // is correctly captured. A variable that shows up in a use_device_ptr has 11240 // similar properties of a first private variable. 11241 DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_firstprivate, Ref); 11242 11243 // Create a mappable component for the list item. List items in this clause 11244 // only need a component. 11245 MVLI.VarBaseDeclarations.push_back(D); 11246 MVLI.VarComponents.resize(MVLI.VarComponents.size() + 1); 11247 MVLI.VarComponents.back().push_back( 11248 OMPClauseMappableExprCommon::MappableComponent(SimpleRefExpr, D)); 11249 } 11250 11251 if (MVLI.ProcessedVarList.empty()) 11252 return nullptr; 11253 11254 return OMPUseDevicePtrClause::Create( 11255 Context, StartLoc, LParenLoc, EndLoc, MVLI.ProcessedVarList, 11256 PrivateCopies, Inits, MVLI.VarBaseDeclarations, MVLI.VarComponents); 11257 } 11258 11259 OMPClause *Sema::ActOnOpenMPIsDevicePtrClause(ArrayRef<Expr *> VarList, 11260 SourceLocation StartLoc, 11261 SourceLocation LParenLoc, 11262 SourceLocation EndLoc) { 11263 MappableVarListInfo MVLI(VarList); 11264 for (auto &RefExpr : VarList) { 11265 assert(RefExpr && "NULL expr in OpenMP is_device_ptr clause."); 11266 SourceLocation ELoc; 11267 SourceRange ERange; 11268 Expr *SimpleRefExpr = RefExpr; 11269 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange); 11270 if (Res.second) { 11271 // It will be analyzed later. 11272 MVLI.ProcessedVarList.push_back(RefExpr); 11273 } 11274 ValueDecl *D = Res.first; 11275 if (!D) 11276 continue; 11277 11278 QualType Type = D->getType(); 11279 // item should be a pointer or array or reference to pointer or array 11280 if (!Type.getNonReferenceType()->isPointerType() && 11281 !Type.getNonReferenceType()->isArrayType()) { 11282 Diag(ELoc, diag::err_omp_argument_type_isdeviceptr) 11283 << 0 << RefExpr->getSourceRange(); 11284 continue; 11285 } 11286 11287 // Check if the declaration in the clause does not show up in any data 11288 // sharing attribute. 11289 auto DVar = DSAStack->getTopDSA(D, false); 11290 if (isOpenMPPrivate(DVar.CKind)) { 11291 Diag(ELoc, diag::err_omp_variable_in_given_clause_and_dsa) 11292 << getOpenMPClauseName(DVar.CKind) 11293 << getOpenMPClauseName(OMPC_is_device_ptr) 11294 << getOpenMPDirectiveName(DSAStack->getCurrentDirective()); 11295 ReportOriginalDSA(*this, DSAStack, D, DVar); 11296 continue; 11297 } 11298 11299 Expr *ConflictExpr; 11300 if (DSAStack->checkMappableExprComponentListsForDecl( 11301 D, /*CurrentRegionOnly=*/true, 11302 [&ConflictExpr]( 11303 OMPClauseMappableExprCommon::MappableExprComponentListRef R, 11304 OpenMPClauseKind) -> bool { 11305 ConflictExpr = R.front().getAssociatedExpression(); 11306 return true; 11307 })) { 11308 Diag(ELoc, diag::err_omp_map_shared_storage) << RefExpr->getSourceRange(); 11309 Diag(ConflictExpr->getExprLoc(), diag::note_used_here) 11310 << ConflictExpr->getSourceRange(); 11311 continue; 11312 } 11313 11314 // Store the components in the stack so that they can be used to check 11315 // against other clauses later on. 11316 OMPClauseMappableExprCommon::MappableComponent MC(SimpleRefExpr, D); 11317 DSAStack->addMappableExpressionComponents( 11318 D, MC, /*WhereFoundClauseKind=*/OMPC_is_device_ptr); 11319 11320 // Record the expression we've just processed. 11321 MVLI.ProcessedVarList.push_back(SimpleRefExpr); 11322 11323 // Create a mappable component for the list item. List items in this clause 11324 // only need a component. We use a null declaration to signal fields in 11325 // 'this'. 11326 assert((isa<DeclRefExpr>(SimpleRefExpr) || 11327 isa<CXXThisExpr>(cast<MemberExpr>(SimpleRefExpr)->getBase())) && 11328 "Unexpected device pointer expression!"); 11329 MVLI.VarBaseDeclarations.push_back( 11330 isa<DeclRefExpr>(SimpleRefExpr) ? D : nullptr); 11331 MVLI.VarComponents.resize(MVLI.VarComponents.size() + 1); 11332 MVLI.VarComponents.back().push_back(MC); 11333 } 11334 11335 if (MVLI.ProcessedVarList.empty()) 11336 return nullptr; 11337 11338 return OMPIsDevicePtrClause::Create( 11339 Context, StartLoc, LParenLoc, EndLoc, MVLI.ProcessedVarList, 11340 MVLI.VarBaseDeclarations, MVLI.VarComponents); 11341 } 11342