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 QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1); 1599 QualType KmpInt32PtrTy = 1600 Context.getPointerType(KmpInt32Ty).withConst().withRestrict(); 1601 Sema::CapturedParamNameType Params[] = { 1602 std::make_pair(".global_tid.", KmpInt32PtrTy), 1603 std::make_pair(".bound_tid.", KmpInt32PtrTy), 1604 std::make_pair(StringRef(), QualType()) // __context with shared vars 1605 }; 1606 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP, 1607 Params); 1608 break; 1609 } 1610 case OMPD_target_teams: 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 ParamsTeamsOrParallel[] = { 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 'teams' or 'parallel'. Both regions have 1627 // the same implicit parameters. 1628 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP, 1629 ParamsTeamsOrParallel); 1630 break; 1631 } 1632 case OMPD_simd: 1633 case OMPD_for: 1634 case OMPD_for_simd: 1635 case OMPD_sections: 1636 case OMPD_section: 1637 case OMPD_single: 1638 case OMPD_master: 1639 case OMPD_critical: 1640 case OMPD_taskgroup: 1641 case OMPD_distribute: 1642 case OMPD_ordered: 1643 case OMPD_atomic: 1644 case OMPD_target_data: 1645 case OMPD_target: 1646 case OMPD_target_parallel_for: 1647 case OMPD_target_parallel_for_simd: 1648 case OMPD_target_simd: { 1649 Sema::CapturedParamNameType Params[] = { 1650 std::make_pair(StringRef(), QualType()) // __context with shared vars 1651 }; 1652 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP, 1653 Params); 1654 break; 1655 } 1656 case OMPD_task: { 1657 QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1); 1658 QualType Args[] = {Context.VoidPtrTy.withConst().withRestrict()}; 1659 FunctionProtoType::ExtProtoInfo EPI; 1660 EPI.Variadic = true; 1661 QualType CopyFnType = Context.getFunctionType(Context.VoidTy, Args, EPI); 1662 Sema::CapturedParamNameType Params[] = { 1663 std::make_pair(".global_tid.", KmpInt32Ty), 1664 std::make_pair(".part_id.", Context.getPointerType(KmpInt32Ty)), 1665 std::make_pair(".privates.", Context.VoidPtrTy.withConst()), 1666 std::make_pair(".copy_fn.", 1667 Context.getPointerType(CopyFnType).withConst()), 1668 std::make_pair(".task_t.", Context.VoidPtrTy.withConst()), 1669 std::make_pair(StringRef(), QualType()) // __context with shared vars 1670 }; 1671 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP, 1672 Params); 1673 // Mark this captured region as inlined, because we don't use outlined 1674 // function directly. 1675 getCurCapturedRegion()->TheCapturedDecl->addAttr( 1676 AlwaysInlineAttr::CreateImplicit( 1677 Context, AlwaysInlineAttr::Keyword_forceinline, SourceRange())); 1678 break; 1679 } 1680 case OMPD_taskloop: 1681 case OMPD_taskloop_simd: { 1682 QualType KmpInt32Ty = 1683 Context.getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/1); 1684 QualType KmpUInt64Ty = 1685 Context.getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/0); 1686 QualType KmpInt64Ty = 1687 Context.getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/1); 1688 QualType Args[] = {Context.VoidPtrTy.withConst().withRestrict()}; 1689 FunctionProtoType::ExtProtoInfo EPI; 1690 EPI.Variadic = true; 1691 QualType CopyFnType = Context.getFunctionType(Context.VoidTy, Args, EPI); 1692 Sema::CapturedParamNameType Params[] = { 1693 std::make_pair(".global_tid.", KmpInt32Ty), 1694 std::make_pair(".part_id.", Context.getPointerType(KmpInt32Ty)), 1695 std::make_pair(".privates.", 1696 Context.VoidPtrTy.withConst().withRestrict()), 1697 std::make_pair( 1698 ".copy_fn.", 1699 Context.getPointerType(CopyFnType).withConst().withRestrict()), 1700 std::make_pair(".task_t.", Context.VoidPtrTy.withConst()), 1701 std::make_pair(".lb.", KmpUInt64Ty), 1702 std::make_pair(".ub.", KmpUInt64Ty), std::make_pair(".st.", KmpInt64Ty), 1703 std::make_pair(".liter.", KmpInt32Ty), 1704 std::make_pair(StringRef(), QualType()) // __context with shared vars 1705 }; 1706 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP, 1707 Params); 1708 // Mark this captured region as inlined, because we don't use outlined 1709 // function directly. 1710 getCurCapturedRegion()->TheCapturedDecl->addAttr( 1711 AlwaysInlineAttr::CreateImplicit( 1712 Context, AlwaysInlineAttr::Keyword_forceinline, SourceRange())); 1713 break; 1714 } 1715 case OMPD_distribute_parallel_for_simd: 1716 case OMPD_distribute_simd: 1717 case OMPD_distribute_parallel_for: 1718 case OMPD_teams_distribute: 1719 case OMPD_teams_distribute_simd: 1720 case OMPD_teams_distribute_parallel_for_simd: 1721 case OMPD_teams_distribute_parallel_for: 1722 case OMPD_target_teams_distribute: 1723 case OMPD_target_teams_distribute_parallel_for: 1724 case OMPD_target_teams_distribute_parallel_for_simd: 1725 case OMPD_target_teams_distribute_simd: { 1726 QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1); 1727 QualType KmpInt32PtrTy = 1728 Context.getPointerType(KmpInt32Ty).withConst().withRestrict(); 1729 Sema::CapturedParamNameType Params[] = { 1730 std::make_pair(".global_tid.", KmpInt32PtrTy), 1731 std::make_pair(".bound_tid.", KmpInt32PtrTy), 1732 std::make_pair(".previous.lb.", Context.getSizeType()), 1733 std::make_pair(".previous.ub.", Context.getSizeType()), 1734 std::make_pair(StringRef(), QualType()) // __context with shared vars 1735 }; 1736 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP, 1737 Params); 1738 break; 1739 } 1740 case OMPD_threadprivate: 1741 case OMPD_taskyield: 1742 case OMPD_barrier: 1743 case OMPD_taskwait: 1744 case OMPD_cancellation_point: 1745 case OMPD_cancel: 1746 case OMPD_flush: 1747 case OMPD_target_enter_data: 1748 case OMPD_target_exit_data: 1749 case OMPD_declare_reduction: 1750 case OMPD_declare_simd: 1751 case OMPD_declare_target: 1752 case OMPD_end_declare_target: 1753 case OMPD_target_update: 1754 llvm_unreachable("OpenMP Directive is not allowed"); 1755 case OMPD_unknown: 1756 llvm_unreachable("Unknown OpenMP directive"); 1757 } 1758 } 1759 1760 int Sema::getOpenMPCaptureLevels(OpenMPDirectiveKind DKind) { 1761 SmallVector<OpenMPDirectiveKind, 4> CaptureRegions; 1762 getOpenMPCaptureRegions(CaptureRegions, DKind); 1763 return CaptureRegions.size(); 1764 } 1765 1766 static OMPCapturedExprDecl *buildCaptureDecl(Sema &S, IdentifierInfo *Id, 1767 Expr *CaptureExpr, bool WithInit, 1768 bool AsExpression) { 1769 assert(CaptureExpr); 1770 ASTContext &C = S.getASTContext(); 1771 Expr *Init = AsExpression ? CaptureExpr : CaptureExpr->IgnoreImpCasts(); 1772 QualType Ty = Init->getType(); 1773 if (CaptureExpr->getObjectKind() == OK_Ordinary && CaptureExpr->isGLValue()) { 1774 if (S.getLangOpts().CPlusPlus) 1775 Ty = C.getLValueReferenceType(Ty); 1776 else { 1777 Ty = C.getPointerType(Ty); 1778 ExprResult Res = 1779 S.CreateBuiltinUnaryOp(CaptureExpr->getExprLoc(), UO_AddrOf, Init); 1780 if (!Res.isUsable()) 1781 return nullptr; 1782 Init = Res.get(); 1783 } 1784 WithInit = true; 1785 } 1786 auto *CED = OMPCapturedExprDecl::Create(C, S.CurContext, Id, Ty, 1787 CaptureExpr->getLocStart()); 1788 if (!WithInit) 1789 CED->addAttr(OMPCaptureNoInitAttr::CreateImplicit(C, SourceRange())); 1790 S.CurContext->addHiddenDecl(CED); 1791 S.AddInitializerToDecl(CED, Init, /*DirectInit=*/false); 1792 return CED; 1793 } 1794 1795 static DeclRefExpr *buildCapture(Sema &S, ValueDecl *D, Expr *CaptureExpr, 1796 bool WithInit) { 1797 OMPCapturedExprDecl *CD; 1798 if (auto *VD = S.IsOpenMPCapturedDecl(D)) 1799 CD = cast<OMPCapturedExprDecl>(VD); 1800 else 1801 CD = buildCaptureDecl(S, D->getIdentifier(), CaptureExpr, WithInit, 1802 /*AsExpression=*/false); 1803 return buildDeclRefExpr(S, CD, CD->getType().getNonReferenceType(), 1804 CaptureExpr->getExprLoc()); 1805 } 1806 1807 static ExprResult buildCapture(Sema &S, Expr *CaptureExpr, DeclRefExpr *&Ref) { 1808 if (!Ref) { 1809 auto *CD = 1810 buildCaptureDecl(S, &S.getASTContext().Idents.get(".capture_expr."), 1811 CaptureExpr, /*WithInit=*/true, /*AsExpression=*/true); 1812 Ref = buildDeclRefExpr(S, CD, CD->getType().getNonReferenceType(), 1813 CaptureExpr->getExprLoc()); 1814 } 1815 ExprResult Res = Ref; 1816 if (!S.getLangOpts().CPlusPlus && 1817 CaptureExpr->getObjectKind() == OK_Ordinary && CaptureExpr->isGLValue() && 1818 Ref->getType()->isPointerType()) 1819 Res = S.CreateBuiltinUnaryOp(CaptureExpr->getExprLoc(), UO_Deref, Ref); 1820 if (!Res.isUsable()) 1821 return ExprError(); 1822 return CaptureExpr->isGLValue() ? Res : S.DefaultLvalueConversion(Res.get()); 1823 } 1824 1825 namespace { 1826 // OpenMP directives parsed in this section are represented as a 1827 // CapturedStatement with an associated statement. If a syntax error 1828 // is detected during the parsing of the associated statement, the 1829 // compiler must abort processing and close the CapturedStatement. 1830 // 1831 // Combined directives such as 'target parallel' have more than one 1832 // nested CapturedStatements. This RAII ensures that we unwind out 1833 // of all the nested CapturedStatements when an error is found. 1834 class CaptureRegionUnwinderRAII { 1835 private: 1836 Sema &S; 1837 bool &ErrorFound; 1838 OpenMPDirectiveKind DKind; 1839 1840 public: 1841 CaptureRegionUnwinderRAII(Sema &S, bool &ErrorFound, 1842 OpenMPDirectiveKind DKind) 1843 : S(S), ErrorFound(ErrorFound), DKind(DKind) {} 1844 ~CaptureRegionUnwinderRAII() { 1845 if (ErrorFound) { 1846 int ThisCaptureLevel = S.getOpenMPCaptureLevels(DKind); 1847 while (--ThisCaptureLevel >= 0) 1848 S.ActOnCapturedRegionError(); 1849 } 1850 } 1851 }; 1852 } // namespace 1853 1854 StmtResult Sema::ActOnOpenMPRegionEnd(StmtResult S, 1855 ArrayRef<OMPClause *> Clauses) { 1856 bool ErrorFound = false; 1857 CaptureRegionUnwinderRAII CaptureRegionUnwinder( 1858 *this, ErrorFound, DSAStack->getCurrentDirective()); 1859 if (!S.isUsable()) { 1860 ErrorFound = true; 1861 return StmtError(); 1862 } 1863 1864 OMPOrderedClause *OC = nullptr; 1865 OMPScheduleClause *SC = nullptr; 1866 SmallVector<OMPLinearClause *, 4> LCs; 1867 SmallVector<OMPClauseWithPreInit *, 8> PICs; 1868 // This is required for proper codegen. 1869 for (auto *Clause : Clauses) { 1870 if (isOpenMPPrivate(Clause->getClauseKind()) || 1871 Clause->getClauseKind() == OMPC_copyprivate || 1872 (getLangOpts().OpenMPUseTLS && 1873 getASTContext().getTargetInfo().isTLSSupported() && 1874 Clause->getClauseKind() == OMPC_copyin)) { 1875 DSAStack->setForceVarCapturing(Clause->getClauseKind() == OMPC_copyin); 1876 // Mark all variables in private list clauses as used in inner region. 1877 for (auto *VarRef : Clause->children()) { 1878 if (auto *E = cast_or_null<Expr>(VarRef)) { 1879 MarkDeclarationsReferencedInExpr(E); 1880 } 1881 } 1882 DSAStack->setForceVarCapturing(/*V=*/false); 1883 } else if (isParallelOrTaskRegion(DSAStack->getCurrentDirective())) { 1884 if (auto *C = OMPClauseWithPreInit::get(Clause)) 1885 PICs.push_back(C); 1886 if (auto *C = OMPClauseWithPostUpdate::get(Clause)) { 1887 if (auto *E = C->getPostUpdateExpr()) 1888 MarkDeclarationsReferencedInExpr(E); 1889 } 1890 } 1891 if (Clause->getClauseKind() == OMPC_schedule) 1892 SC = cast<OMPScheduleClause>(Clause); 1893 else if (Clause->getClauseKind() == OMPC_ordered) 1894 OC = cast<OMPOrderedClause>(Clause); 1895 else if (Clause->getClauseKind() == OMPC_linear) 1896 LCs.push_back(cast<OMPLinearClause>(Clause)); 1897 } 1898 // OpenMP, 2.7.1 Loop Construct, Restrictions 1899 // The nonmonotonic modifier cannot be specified if an ordered clause is 1900 // specified. 1901 if (SC && 1902 (SC->getFirstScheduleModifier() == OMPC_SCHEDULE_MODIFIER_nonmonotonic || 1903 SC->getSecondScheduleModifier() == 1904 OMPC_SCHEDULE_MODIFIER_nonmonotonic) && 1905 OC) { 1906 Diag(SC->getFirstScheduleModifier() == OMPC_SCHEDULE_MODIFIER_nonmonotonic 1907 ? SC->getFirstScheduleModifierLoc() 1908 : SC->getSecondScheduleModifierLoc(), 1909 diag::err_omp_schedule_nonmonotonic_ordered) 1910 << SourceRange(OC->getLocStart(), OC->getLocEnd()); 1911 ErrorFound = true; 1912 } 1913 if (!LCs.empty() && OC && OC->getNumForLoops()) { 1914 for (auto *C : LCs) { 1915 Diag(C->getLocStart(), diag::err_omp_linear_ordered) 1916 << SourceRange(OC->getLocStart(), OC->getLocEnd()); 1917 } 1918 ErrorFound = true; 1919 } 1920 if (isOpenMPWorksharingDirective(DSAStack->getCurrentDirective()) && 1921 isOpenMPSimdDirective(DSAStack->getCurrentDirective()) && OC && 1922 OC->getNumForLoops()) { 1923 Diag(OC->getLocStart(), diag::err_omp_ordered_simd) 1924 << getOpenMPDirectiveName(DSAStack->getCurrentDirective()); 1925 ErrorFound = true; 1926 } 1927 if (ErrorFound) { 1928 return StmtError(); 1929 } 1930 StmtResult SR = S; 1931 SmallVector<OpenMPDirectiveKind, 4> CaptureRegions; 1932 getOpenMPCaptureRegions(CaptureRegions, DSAStack->getCurrentDirective()); 1933 for (auto ThisCaptureRegion : llvm::reverse(CaptureRegions)) { 1934 // Mark all variables in private list clauses as used in inner region. 1935 // Required for proper codegen of combined directives. 1936 // TODO: add processing for other clauses. 1937 if (isParallelOrTaskRegion(DSAStack->getCurrentDirective())) { 1938 for (auto *C : PICs) { 1939 OpenMPDirectiveKind CaptureRegion = C->getCaptureRegion(); 1940 // Find the particular capture region for the clause if the 1941 // directive is a combined one with multiple capture regions. 1942 // If the directive is not a combined one, the capture region 1943 // associated with the clause is OMPD_unknown and is generated 1944 // only once. 1945 if (CaptureRegion == ThisCaptureRegion || 1946 CaptureRegion == OMPD_unknown) { 1947 if (auto *DS = cast_or_null<DeclStmt>(C->getPreInitStmt())) { 1948 for (auto *D : DS->decls()) 1949 MarkVariableReferenced(D->getLocation(), cast<VarDecl>(D)); 1950 } 1951 } 1952 } 1953 } 1954 SR = ActOnCapturedRegionEnd(SR.get()); 1955 } 1956 return SR; 1957 } 1958 1959 static bool checkCancelRegion(Sema &SemaRef, OpenMPDirectiveKind CurrentRegion, 1960 OpenMPDirectiveKind CancelRegion, 1961 SourceLocation StartLoc) { 1962 // CancelRegion is only needed for cancel and cancellation_point. 1963 if (CurrentRegion != OMPD_cancel && CurrentRegion != OMPD_cancellation_point) 1964 return false; 1965 1966 if (CancelRegion == OMPD_parallel || CancelRegion == OMPD_for || 1967 CancelRegion == OMPD_sections || CancelRegion == OMPD_taskgroup) 1968 return false; 1969 1970 SemaRef.Diag(StartLoc, diag::err_omp_wrong_cancel_region) 1971 << getOpenMPDirectiveName(CancelRegion); 1972 return true; 1973 } 1974 1975 static bool checkNestingOfRegions(Sema &SemaRef, DSAStackTy *Stack, 1976 OpenMPDirectiveKind CurrentRegion, 1977 const DeclarationNameInfo &CurrentName, 1978 OpenMPDirectiveKind CancelRegion, 1979 SourceLocation StartLoc) { 1980 if (Stack->getCurScope()) { 1981 auto ParentRegion = Stack->getParentDirective(); 1982 auto OffendingRegion = ParentRegion; 1983 bool NestingProhibited = false; 1984 bool CloseNesting = true; 1985 bool OrphanSeen = false; 1986 enum { 1987 NoRecommend, 1988 ShouldBeInParallelRegion, 1989 ShouldBeInOrderedRegion, 1990 ShouldBeInTargetRegion, 1991 ShouldBeInTeamsRegion 1992 } Recommend = NoRecommend; 1993 if (isOpenMPSimdDirective(ParentRegion) && CurrentRegion != OMPD_ordered) { 1994 // OpenMP [2.16, Nesting of Regions] 1995 // OpenMP constructs may not be nested inside a simd region. 1996 // OpenMP [2.8.1,simd Construct, Restrictions] 1997 // An ordered construct with the simd clause is the only OpenMP 1998 // construct that can appear in the simd region. 1999 // Allowing a SIMD construct nested in another SIMD construct is an 2000 // extension. The OpenMP 4.5 spec does not allow it. Issue a warning 2001 // message. 2002 SemaRef.Diag(StartLoc, (CurrentRegion != OMPD_simd) 2003 ? diag::err_omp_prohibited_region_simd 2004 : diag::warn_omp_nesting_simd); 2005 return CurrentRegion != OMPD_simd; 2006 } 2007 if (ParentRegion == OMPD_atomic) { 2008 // OpenMP [2.16, Nesting of Regions] 2009 // OpenMP constructs may not be nested inside an atomic region. 2010 SemaRef.Diag(StartLoc, diag::err_omp_prohibited_region_atomic); 2011 return true; 2012 } 2013 if (CurrentRegion == OMPD_section) { 2014 // OpenMP [2.7.2, sections Construct, Restrictions] 2015 // Orphaned section directives are prohibited. That is, the section 2016 // directives must appear within the sections construct and must not be 2017 // encountered elsewhere in the sections region. 2018 if (ParentRegion != OMPD_sections && 2019 ParentRegion != OMPD_parallel_sections) { 2020 SemaRef.Diag(StartLoc, diag::err_omp_orphaned_section_directive) 2021 << (ParentRegion != OMPD_unknown) 2022 << getOpenMPDirectiveName(ParentRegion); 2023 return true; 2024 } 2025 return false; 2026 } 2027 // Allow some constructs (except teams) to be orphaned (they could be 2028 // used in functions, called from OpenMP regions with the required 2029 // preconditions). 2030 if (ParentRegion == OMPD_unknown && 2031 !isOpenMPNestingTeamsDirective(CurrentRegion)) 2032 return false; 2033 if (CurrentRegion == OMPD_cancellation_point || 2034 CurrentRegion == OMPD_cancel) { 2035 // OpenMP [2.16, Nesting of Regions] 2036 // A cancellation point construct for which construct-type-clause is 2037 // taskgroup must be nested inside a task construct. A cancellation 2038 // point construct for which construct-type-clause is not taskgroup must 2039 // be closely nested inside an OpenMP construct that matches the type 2040 // specified in construct-type-clause. 2041 // A cancel construct for which construct-type-clause is taskgroup must be 2042 // nested inside a task construct. A cancel construct for which 2043 // construct-type-clause is not taskgroup must be closely nested inside an 2044 // OpenMP construct that matches the type specified in 2045 // construct-type-clause. 2046 NestingProhibited = 2047 !((CancelRegion == OMPD_parallel && 2048 (ParentRegion == OMPD_parallel || 2049 ParentRegion == OMPD_target_parallel)) || 2050 (CancelRegion == OMPD_for && 2051 (ParentRegion == OMPD_for || ParentRegion == OMPD_parallel_for || 2052 ParentRegion == OMPD_target_parallel_for)) || 2053 (CancelRegion == OMPD_taskgroup && ParentRegion == OMPD_task) || 2054 (CancelRegion == OMPD_sections && 2055 (ParentRegion == OMPD_section || ParentRegion == OMPD_sections || 2056 ParentRegion == OMPD_parallel_sections))); 2057 } else if (CurrentRegion == OMPD_master) { 2058 // OpenMP [2.16, Nesting of Regions] 2059 // A master region may not be closely nested inside a worksharing, 2060 // atomic, or explicit task region. 2061 NestingProhibited = isOpenMPWorksharingDirective(ParentRegion) || 2062 isOpenMPTaskingDirective(ParentRegion); 2063 } else if (CurrentRegion == OMPD_critical && CurrentName.getName()) { 2064 // OpenMP [2.16, Nesting of Regions] 2065 // A critical region may not be nested (closely or otherwise) inside a 2066 // critical region with the same name. Note that this restriction is not 2067 // sufficient to prevent deadlock. 2068 SourceLocation PreviousCriticalLoc; 2069 bool DeadLock = Stack->hasDirective( 2070 [CurrentName, &PreviousCriticalLoc](OpenMPDirectiveKind K, 2071 const DeclarationNameInfo &DNI, 2072 SourceLocation Loc) -> bool { 2073 if (K == OMPD_critical && DNI.getName() == CurrentName.getName()) { 2074 PreviousCriticalLoc = Loc; 2075 return true; 2076 } else 2077 return false; 2078 }, 2079 false /* skip top directive */); 2080 if (DeadLock) { 2081 SemaRef.Diag(StartLoc, 2082 diag::err_omp_prohibited_region_critical_same_name) 2083 << CurrentName.getName(); 2084 if (PreviousCriticalLoc.isValid()) 2085 SemaRef.Diag(PreviousCriticalLoc, 2086 diag::note_omp_previous_critical_region); 2087 return true; 2088 } 2089 } else if (CurrentRegion == OMPD_barrier) { 2090 // OpenMP [2.16, Nesting of Regions] 2091 // A barrier region may not be closely nested inside a worksharing, 2092 // explicit task, critical, ordered, atomic, or master region. 2093 NestingProhibited = isOpenMPWorksharingDirective(ParentRegion) || 2094 isOpenMPTaskingDirective(ParentRegion) || 2095 ParentRegion == OMPD_master || 2096 ParentRegion == OMPD_critical || 2097 ParentRegion == OMPD_ordered; 2098 } else if (isOpenMPWorksharingDirective(CurrentRegion) && 2099 !isOpenMPParallelDirective(CurrentRegion) && 2100 !isOpenMPTeamsDirective(CurrentRegion)) { 2101 // OpenMP [2.16, Nesting of Regions] 2102 // A worksharing region may not be closely nested inside a worksharing, 2103 // explicit task, critical, ordered, atomic, or master region. 2104 NestingProhibited = isOpenMPWorksharingDirective(ParentRegion) || 2105 isOpenMPTaskingDirective(ParentRegion) || 2106 ParentRegion == OMPD_master || 2107 ParentRegion == OMPD_critical || 2108 ParentRegion == OMPD_ordered; 2109 Recommend = ShouldBeInParallelRegion; 2110 } else if (CurrentRegion == OMPD_ordered) { 2111 // OpenMP [2.16, Nesting of Regions] 2112 // An ordered region may not be closely nested inside a critical, 2113 // atomic, or explicit task region. 2114 // An ordered region must be closely nested inside a loop region (or 2115 // parallel loop region) with an ordered clause. 2116 // OpenMP [2.8.1,simd Construct, Restrictions] 2117 // An ordered construct with the simd clause is the only OpenMP construct 2118 // that can appear in the simd region. 2119 NestingProhibited = ParentRegion == OMPD_critical || 2120 isOpenMPTaskingDirective(ParentRegion) || 2121 !(isOpenMPSimdDirective(ParentRegion) || 2122 Stack->isParentOrderedRegion()); 2123 Recommend = ShouldBeInOrderedRegion; 2124 } else if (isOpenMPNestingTeamsDirective(CurrentRegion)) { 2125 // OpenMP [2.16, Nesting of Regions] 2126 // If specified, a teams construct must be contained within a target 2127 // construct. 2128 NestingProhibited = ParentRegion != OMPD_target; 2129 OrphanSeen = ParentRegion == OMPD_unknown; 2130 Recommend = ShouldBeInTargetRegion; 2131 Stack->setParentTeamsRegionLoc(Stack->getConstructLoc()); 2132 } 2133 if (!NestingProhibited && 2134 !isOpenMPTargetExecutionDirective(CurrentRegion) && 2135 !isOpenMPTargetDataManagementDirective(CurrentRegion) && 2136 (ParentRegion == OMPD_teams || ParentRegion == OMPD_target_teams)) { 2137 // OpenMP [2.16, Nesting of Regions] 2138 // distribute, parallel, parallel sections, parallel workshare, and the 2139 // parallel loop and parallel loop SIMD constructs are the only OpenMP 2140 // constructs that can be closely nested in the teams region. 2141 NestingProhibited = !isOpenMPParallelDirective(CurrentRegion) && 2142 !isOpenMPDistributeDirective(CurrentRegion); 2143 Recommend = ShouldBeInParallelRegion; 2144 } 2145 if (!NestingProhibited && 2146 isOpenMPNestingDistributeDirective(CurrentRegion)) { 2147 // OpenMP 4.5 [2.17 Nesting of Regions] 2148 // The region associated with the distribute construct must be strictly 2149 // nested inside a teams region 2150 NestingProhibited = 2151 (ParentRegion != OMPD_teams && ParentRegion != OMPD_target_teams); 2152 Recommend = ShouldBeInTeamsRegion; 2153 } 2154 if (!NestingProhibited && 2155 (isOpenMPTargetExecutionDirective(CurrentRegion) || 2156 isOpenMPTargetDataManagementDirective(CurrentRegion))) { 2157 // OpenMP 4.5 [2.17 Nesting of Regions] 2158 // If a target, target update, target data, target enter data, or 2159 // target exit data construct is encountered during execution of a 2160 // target region, the behavior is unspecified. 2161 NestingProhibited = Stack->hasDirective( 2162 [&OffendingRegion](OpenMPDirectiveKind K, const DeclarationNameInfo &, 2163 SourceLocation) -> bool { 2164 if (isOpenMPTargetExecutionDirective(K)) { 2165 OffendingRegion = K; 2166 return true; 2167 } else 2168 return false; 2169 }, 2170 false /* don't skip top directive */); 2171 CloseNesting = false; 2172 } 2173 if (NestingProhibited) { 2174 if (OrphanSeen) { 2175 SemaRef.Diag(StartLoc, diag::err_omp_orphaned_device_directive) 2176 << getOpenMPDirectiveName(CurrentRegion) << Recommend; 2177 } else { 2178 SemaRef.Diag(StartLoc, diag::err_omp_prohibited_region) 2179 << CloseNesting << getOpenMPDirectiveName(OffendingRegion) 2180 << Recommend << getOpenMPDirectiveName(CurrentRegion); 2181 } 2182 return true; 2183 } 2184 } 2185 return false; 2186 } 2187 2188 static bool checkIfClauses(Sema &S, OpenMPDirectiveKind Kind, 2189 ArrayRef<OMPClause *> Clauses, 2190 ArrayRef<OpenMPDirectiveKind> AllowedNameModifiers) { 2191 bool ErrorFound = false; 2192 unsigned NamedModifiersNumber = 0; 2193 SmallVector<const OMPIfClause *, OMPC_unknown + 1> FoundNameModifiers( 2194 OMPD_unknown + 1); 2195 SmallVector<SourceLocation, 4> NameModifierLoc; 2196 for (const auto *C : Clauses) { 2197 if (const auto *IC = dyn_cast_or_null<OMPIfClause>(C)) { 2198 // At most one if clause without a directive-name-modifier can appear on 2199 // the directive. 2200 OpenMPDirectiveKind CurNM = IC->getNameModifier(); 2201 if (FoundNameModifiers[CurNM]) { 2202 S.Diag(C->getLocStart(), diag::err_omp_more_one_clause) 2203 << getOpenMPDirectiveName(Kind) << getOpenMPClauseName(OMPC_if) 2204 << (CurNM != OMPD_unknown) << getOpenMPDirectiveName(CurNM); 2205 ErrorFound = true; 2206 } else if (CurNM != OMPD_unknown) { 2207 NameModifierLoc.push_back(IC->getNameModifierLoc()); 2208 ++NamedModifiersNumber; 2209 } 2210 FoundNameModifiers[CurNM] = IC; 2211 if (CurNM == OMPD_unknown) 2212 continue; 2213 // Check if the specified name modifier is allowed for the current 2214 // directive. 2215 // At most one if clause with the particular directive-name-modifier can 2216 // appear on the directive. 2217 bool MatchFound = false; 2218 for (auto NM : AllowedNameModifiers) { 2219 if (CurNM == NM) { 2220 MatchFound = true; 2221 break; 2222 } 2223 } 2224 if (!MatchFound) { 2225 S.Diag(IC->getNameModifierLoc(), 2226 diag::err_omp_wrong_if_directive_name_modifier) 2227 << getOpenMPDirectiveName(CurNM) << getOpenMPDirectiveName(Kind); 2228 ErrorFound = true; 2229 } 2230 } 2231 } 2232 // If any if clause on the directive includes a directive-name-modifier then 2233 // all if clauses on the directive must include a directive-name-modifier. 2234 if (FoundNameModifiers[OMPD_unknown] && NamedModifiersNumber > 0) { 2235 if (NamedModifiersNumber == AllowedNameModifiers.size()) { 2236 S.Diag(FoundNameModifiers[OMPD_unknown]->getLocStart(), 2237 diag::err_omp_no_more_if_clause); 2238 } else { 2239 std::string Values; 2240 std::string Sep(", "); 2241 unsigned AllowedCnt = 0; 2242 unsigned TotalAllowedNum = 2243 AllowedNameModifiers.size() - NamedModifiersNumber; 2244 for (unsigned Cnt = 0, End = AllowedNameModifiers.size(); Cnt < End; 2245 ++Cnt) { 2246 OpenMPDirectiveKind NM = AllowedNameModifiers[Cnt]; 2247 if (!FoundNameModifiers[NM]) { 2248 Values += "'"; 2249 Values += getOpenMPDirectiveName(NM); 2250 Values += "'"; 2251 if (AllowedCnt + 2 == TotalAllowedNum) 2252 Values += " or "; 2253 else if (AllowedCnt + 1 != TotalAllowedNum) 2254 Values += Sep; 2255 ++AllowedCnt; 2256 } 2257 } 2258 S.Diag(FoundNameModifiers[OMPD_unknown]->getCondition()->getLocStart(), 2259 diag::err_omp_unnamed_if_clause) 2260 << (TotalAllowedNum > 1) << Values; 2261 } 2262 for (auto Loc : NameModifierLoc) { 2263 S.Diag(Loc, diag::note_omp_previous_named_if_clause); 2264 } 2265 ErrorFound = true; 2266 } 2267 return ErrorFound; 2268 } 2269 2270 StmtResult Sema::ActOnOpenMPExecutableDirective( 2271 OpenMPDirectiveKind Kind, const DeclarationNameInfo &DirName, 2272 OpenMPDirectiveKind CancelRegion, ArrayRef<OMPClause *> Clauses, 2273 Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc) { 2274 StmtResult Res = StmtError(); 2275 // First check CancelRegion which is then used in checkNestingOfRegions. 2276 if (checkCancelRegion(*this, Kind, CancelRegion, StartLoc) || 2277 checkNestingOfRegions(*this, DSAStack, Kind, DirName, CancelRegion, 2278 StartLoc)) 2279 return StmtError(); 2280 2281 llvm::SmallVector<OMPClause *, 8> ClausesWithImplicit; 2282 llvm::DenseMap<ValueDecl *, Expr *> VarsWithInheritedDSA; 2283 bool ErrorFound = false; 2284 ClausesWithImplicit.append(Clauses.begin(), Clauses.end()); 2285 if (AStmt) { 2286 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected"); 2287 2288 // Check default data sharing attributes for referenced variables. 2289 DSAAttrChecker DSAChecker(DSAStack, *this, cast<CapturedStmt>(AStmt)); 2290 int ThisCaptureLevel = getOpenMPCaptureLevels(Kind); 2291 Stmt *S = AStmt; 2292 while (--ThisCaptureLevel >= 0) 2293 S = cast<CapturedStmt>(S)->getCapturedStmt(); 2294 DSAChecker.Visit(S); 2295 if (DSAChecker.isErrorFound()) 2296 return StmtError(); 2297 // Generate list of implicitly defined firstprivate variables. 2298 VarsWithInheritedDSA = DSAChecker.getVarsWithInheritedDSA(); 2299 2300 if (!DSAChecker.getImplicitFirstprivate().empty()) { 2301 if (OMPClause *Implicit = ActOnOpenMPFirstprivateClause( 2302 DSAChecker.getImplicitFirstprivate(), SourceLocation(), 2303 SourceLocation(), SourceLocation())) { 2304 ClausesWithImplicit.push_back(Implicit); 2305 ErrorFound = cast<OMPFirstprivateClause>(Implicit)->varlist_size() != 2306 DSAChecker.getImplicitFirstprivate().size(); 2307 } else 2308 ErrorFound = true; 2309 } 2310 } 2311 2312 llvm::SmallVector<OpenMPDirectiveKind, 4> AllowedNameModifiers; 2313 switch (Kind) { 2314 case OMPD_parallel: 2315 Res = ActOnOpenMPParallelDirective(ClausesWithImplicit, AStmt, StartLoc, 2316 EndLoc); 2317 AllowedNameModifiers.push_back(OMPD_parallel); 2318 break; 2319 case OMPD_simd: 2320 Res = ActOnOpenMPSimdDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc, 2321 VarsWithInheritedDSA); 2322 break; 2323 case OMPD_for: 2324 Res = ActOnOpenMPForDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc, 2325 VarsWithInheritedDSA); 2326 break; 2327 case OMPD_for_simd: 2328 Res = ActOnOpenMPForSimdDirective(ClausesWithImplicit, AStmt, StartLoc, 2329 EndLoc, VarsWithInheritedDSA); 2330 break; 2331 case OMPD_sections: 2332 Res = ActOnOpenMPSectionsDirective(ClausesWithImplicit, AStmt, StartLoc, 2333 EndLoc); 2334 break; 2335 case OMPD_section: 2336 assert(ClausesWithImplicit.empty() && 2337 "No clauses are allowed for 'omp section' directive"); 2338 Res = ActOnOpenMPSectionDirective(AStmt, StartLoc, EndLoc); 2339 break; 2340 case OMPD_single: 2341 Res = ActOnOpenMPSingleDirective(ClausesWithImplicit, AStmt, StartLoc, 2342 EndLoc); 2343 break; 2344 case OMPD_master: 2345 assert(ClausesWithImplicit.empty() && 2346 "No clauses are allowed for 'omp master' directive"); 2347 Res = ActOnOpenMPMasterDirective(AStmt, StartLoc, EndLoc); 2348 break; 2349 case OMPD_critical: 2350 Res = ActOnOpenMPCriticalDirective(DirName, ClausesWithImplicit, AStmt, 2351 StartLoc, EndLoc); 2352 break; 2353 case OMPD_parallel_for: 2354 Res = ActOnOpenMPParallelForDirective(ClausesWithImplicit, AStmt, StartLoc, 2355 EndLoc, VarsWithInheritedDSA); 2356 AllowedNameModifiers.push_back(OMPD_parallel); 2357 break; 2358 case OMPD_parallel_for_simd: 2359 Res = ActOnOpenMPParallelForSimdDirective( 2360 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA); 2361 AllowedNameModifiers.push_back(OMPD_parallel); 2362 break; 2363 case OMPD_parallel_sections: 2364 Res = ActOnOpenMPParallelSectionsDirective(ClausesWithImplicit, AStmt, 2365 StartLoc, EndLoc); 2366 AllowedNameModifiers.push_back(OMPD_parallel); 2367 break; 2368 case OMPD_task: 2369 Res = 2370 ActOnOpenMPTaskDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc); 2371 AllowedNameModifiers.push_back(OMPD_task); 2372 break; 2373 case OMPD_taskyield: 2374 assert(ClausesWithImplicit.empty() && 2375 "No clauses are allowed for 'omp taskyield' directive"); 2376 assert(AStmt == nullptr && 2377 "No associated statement allowed for 'omp taskyield' directive"); 2378 Res = ActOnOpenMPTaskyieldDirective(StartLoc, EndLoc); 2379 break; 2380 case OMPD_barrier: 2381 assert(ClausesWithImplicit.empty() && 2382 "No clauses are allowed for 'omp barrier' directive"); 2383 assert(AStmt == nullptr && 2384 "No associated statement allowed for 'omp barrier' directive"); 2385 Res = ActOnOpenMPBarrierDirective(StartLoc, EndLoc); 2386 break; 2387 case OMPD_taskwait: 2388 assert(ClausesWithImplicit.empty() && 2389 "No clauses are allowed for 'omp taskwait' directive"); 2390 assert(AStmt == nullptr && 2391 "No associated statement allowed for 'omp taskwait' directive"); 2392 Res = ActOnOpenMPTaskwaitDirective(StartLoc, EndLoc); 2393 break; 2394 case OMPD_taskgroup: 2395 assert(ClausesWithImplicit.empty() && 2396 "No clauses are allowed for 'omp taskgroup' directive"); 2397 Res = ActOnOpenMPTaskgroupDirective(AStmt, StartLoc, EndLoc); 2398 break; 2399 case OMPD_flush: 2400 assert(AStmt == nullptr && 2401 "No associated statement allowed for 'omp flush' directive"); 2402 Res = ActOnOpenMPFlushDirective(ClausesWithImplicit, StartLoc, EndLoc); 2403 break; 2404 case OMPD_ordered: 2405 Res = ActOnOpenMPOrderedDirective(ClausesWithImplicit, AStmt, StartLoc, 2406 EndLoc); 2407 break; 2408 case OMPD_atomic: 2409 Res = ActOnOpenMPAtomicDirective(ClausesWithImplicit, AStmt, StartLoc, 2410 EndLoc); 2411 break; 2412 case OMPD_teams: 2413 Res = 2414 ActOnOpenMPTeamsDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc); 2415 break; 2416 case OMPD_target: 2417 Res = ActOnOpenMPTargetDirective(ClausesWithImplicit, AStmt, StartLoc, 2418 EndLoc); 2419 AllowedNameModifiers.push_back(OMPD_target); 2420 break; 2421 case OMPD_target_parallel: 2422 Res = ActOnOpenMPTargetParallelDirective(ClausesWithImplicit, AStmt, 2423 StartLoc, EndLoc); 2424 AllowedNameModifiers.push_back(OMPD_target); 2425 AllowedNameModifiers.push_back(OMPD_parallel); 2426 break; 2427 case OMPD_target_parallel_for: 2428 Res = ActOnOpenMPTargetParallelForDirective( 2429 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA); 2430 AllowedNameModifiers.push_back(OMPD_target); 2431 AllowedNameModifiers.push_back(OMPD_parallel); 2432 break; 2433 case OMPD_cancellation_point: 2434 assert(ClausesWithImplicit.empty() && 2435 "No clauses are allowed for 'omp cancellation point' directive"); 2436 assert(AStmt == nullptr && "No associated statement allowed for 'omp " 2437 "cancellation point' directive"); 2438 Res = ActOnOpenMPCancellationPointDirective(StartLoc, EndLoc, CancelRegion); 2439 break; 2440 case OMPD_cancel: 2441 assert(AStmt == nullptr && 2442 "No associated statement allowed for 'omp cancel' directive"); 2443 Res = ActOnOpenMPCancelDirective(ClausesWithImplicit, StartLoc, EndLoc, 2444 CancelRegion); 2445 AllowedNameModifiers.push_back(OMPD_cancel); 2446 break; 2447 case OMPD_target_data: 2448 Res = ActOnOpenMPTargetDataDirective(ClausesWithImplicit, AStmt, StartLoc, 2449 EndLoc); 2450 AllowedNameModifiers.push_back(OMPD_target_data); 2451 break; 2452 case OMPD_target_enter_data: 2453 Res = ActOnOpenMPTargetEnterDataDirective(ClausesWithImplicit, StartLoc, 2454 EndLoc); 2455 AllowedNameModifiers.push_back(OMPD_target_enter_data); 2456 break; 2457 case OMPD_target_exit_data: 2458 Res = ActOnOpenMPTargetExitDataDirective(ClausesWithImplicit, StartLoc, 2459 EndLoc); 2460 AllowedNameModifiers.push_back(OMPD_target_exit_data); 2461 break; 2462 case OMPD_taskloop: 2463 Res = ActOnOpenMPTaskLoopDirective(ClausesWithImplicit, AStmt, StartLoc, 2464 EndLoc, VarsWithInheritedDSA); 2465 AllowedNameModifiers.push_back(OMPD_taskloop); 2466 break; 2467 case OMPD_taskloop_simd: 2468 Res = ActOnOpenMPTaskLoopSimdDirective(ClausesWithImplicit, AStmt, StartLoc, 2469 EndLoc, VarsWithInheritedDSA); 2470 AllowedNameModifiers.push_back(OMPD_taskloop); 2471 break; 2472 case OMPD_distribute: 2473 Res = ActOnOpenMPDistributeDirective(ClausesWithImplicit, AStmt, StartLoc, 2474 EndLoc, VarsWithInheritedDSA); 2475 break; 2476 case OMPD_target_update: 2477 assert(!AStmt && "Statement is not allowed for target update"); 2478 Res = 2479 ActOnOpenMPTargetUpdateDirective(ClausesWithImplicit, StartLoc, EndLoc); 2480 AllowedNameModifiers.push_back(OMPD_target_update); 2481 break; 2482 case OMPD_distribute_parallel_for: 2483 Res = ActOnOpenMPDistributeParallelForDirective( 2484 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA); 2485 AllowedNameModifiers.push_back(OMPD_parallel); 2486 break; 2487 case OMPD_distribute_parallel_for_simd: 2488 Res = ActOnOpenMPDistributeParallelForSimdDirective( 2489 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA); 2490 AllowedNameModifiers.push_back(OMPD_parallel); 2491 break; 2492 case OMPD_distribute_simd: 2493 Res = ActOnOpenMPDistributeSimdDirective( 2494 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA); 2495 break; 2496 case OMPD_target_parallel_for_simd: 2497 Res = ActOnOpenMPTargetParallelForSimdDirective( 2498 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA); 2499 AllowedNameModifiers.push_back(OMPD_target); 2500 AllowedNameModifiers.push_back(OMPD_parallel); 2501 break; 2502 case OMPD_target_simd: 2503 Res = ActOnOpenMPTargetSimdDirective(ClausesWithImplicit, AStmt, StartLoc, 2504 EndLoc, VarsWithInheritedDSA); 2505 AllowedNameModifiers.push_back(OMPD_target); 2506 break; 2507 case OMPD_teams_distribute: 2508 Res = ActOnOpenMPTeamsDistributeDirective( 2509 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA); 2510 break; 2511 case OMPD_teams_distribute_simd: 2512 Res = ActOnOpenMPTeamsDistributeSimdDirective( 2513 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA); 2514 break; 2515 case OMPD_teams_distribute_parallel_for_simd: 2516 Res = ActOnOpenMPTeamsDistributeParallelForSimdDirective( 2517 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA); 2518 AllowedNameModifiers.push_back(OMPD_parallel); 2519 break; 2520 case OMPD_teams_distribute_parallel_for: 2521 Res = ActOnOpenMPTeamsDistributeParallelForDirective( 2522 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA); 2523 AllowedNameModifiers.push_back(OMPD_parallel); 2524 break; 2525 case OMPD_target_teams: 2526 Res = ActOnOpenMPTargetTeamsDirective(ClausesWithImplicit, AStmt, StartLoc, 2527 EndLoc); 2528 AllowedNameModifiers.push_back(OMPD_target); 2529 break; 2530 case OMPD_target_teams_distribute: 2531 Res = ActOnOpenMPTargetTeamsDistributeDirective( 2532 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA); 2533 AllowedNameModifiers.push_back(OMPD_target); 2534 break; 2535 case OMPD_target_teams_distribute_parallel_for: 2536 Res = ActOnOpenMPTargetTeamsDistributeParallelForDirective( 2537 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA); 2538 AllowedNameModifiers.push_back(OMPD_target); 2539 AllowedNameModifiers.push_back(OMPD_parallel); 2540 break; 2541 case OMPD_target_teams_distribute_parallel_for_simd: 2542 Res = ActOnOpenMPTargetTeamsDistributeParallelForSimdDirective( 2543 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA); 2544 AllowedNameModifiers.push_back(OMPD_target); 2545 AllowedNameModifiers.push_back(OMPD_parallel); 2546 break; 2547 case OMPD_target_teams_distribute_simd: 2548 Res = ActOnOpenMPTargetTeamsDistributeSimdDirective( 2549 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA); 2550 AllowedNameModifiers.push_back(OMPD_target); 2551 break; 2552 case OMPD_declare_target: 2553 case OMPD_end_declare_target: 2554 case OMPD_threadprivate: 2555 case OMPD_declare_reduction: 2556 case OMPD_declare_simd: 2557 llvm_unreachable("OpenMP Directive is not allowed"); 2558 case OMPD_unknown: 2559 llvm_unreachable("Unknown OpenMP directive"); 2560 } 2561 2562 for (auto P : VarsWithInheritedDSA) { 2563 Diag(P.second->getExprLoc(), diag::err_omp_no_dsa_for_variable) 2564 << P.first << P.second->getSourceRange(); 2565 } 2566 ErrorFound = !VarsWithInheritedDSA.empty() || ErrorFound; 2567 2568 if (!AllowedNameModifiers.empty()) 2569 ErrorFound = checkIfClauses(*this, Kind, Clauses, AllowedNameModifiers) || 2570 ErrorFound; 2571 2572 if (ErrorFound) 2573 return StmtError(); 2574 return Res; 2575 } 2576 2577 Sema::DeclGroupPtrTy Sema::ActOnOpenMPDeclareSimdDirective( 2578 DeclGroupPtrTy DG, OMPDeclareSimdDeclAttr::BranchStateTy BS, Expr *Simdlen, 2579 ArrayRef<Expr *> Uniforms, ArrayRef<Expr *> Aligneds, 2580 ArrayRef<Expr *> Alignments, ArrayRef<Expr *> Linears, 2581 ArrayRef<unsigned> LinModifiers, ArrayRef<Expr *> Steps, SourceRange SR) { 2582 assert(Aligneds.size() == Alignments.size()); 2583 assert(Linears.size() == LinModifiers.size()); 2584 assert(Linears.size() == Steps.size()); 2585 if (!DG || DG.get().isNull()) 2586 return DeclGroupPtrTy(); 2587 2588 if (!DG.get().isSingleDecl()) { 2589 Diag(SR.getBegin(), diag::err_omp_single_decl_in_declare_simd); 2590 return DG; 2591 } 2592 auto *ADecl = DG.get().getSingleDecl(); 2593 if (auto *FTD = dyn_cast<FunctionTemplateDecl>(ADecl)) 2594 ADecl = FTD->getTemplatedDecl(); 2595 2596 auto *FD = dyn_cast<FunctionDecl>(ADecl); 2597 if (!FD) { 2598 Diag(ADecl->getLocation(), diag::err_omp_function_expected); 2599 return DeclGroupPtrTy(); 2600 } 2601 2602 // OpenMP [2.8.2, declare simd construct, Description] 2603 // The parameter of the simdlen clause must be a constant positive integer 2604 // expression. 2605 ExprResult SL; 2606 if (Simdlen) 2607 SL = VerifyPositiveIntegerConstantInClause(Simdlen, OMPC_simdlen); 2608 // OpenMP [2.8.2, declare simd construct, Description] 2609 // The special this pointer can be used as if was one of the arguments to the 2610 // function in any of the linear, aligned, or uniform clauses. 2611 // The uniform clause declares one or more arguments to have an invariant 2612 // value for all concurrent invocations of the function in the execution of a 2613 // single SIMD loop. 2614 llvm::DenseMap<Decl *, Expr *> UniformedArgs; 2615 Expr *UniformedLinearThis = nullptr; 2616 for (auto *E : Uniforms) { 2617 E = E->IgnoreParenImpCasts(); 2618 if (auto *DRE = dyn_cast<DeclRefExpr>(E)) 2619 if (auto *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl())) 2620 if (FD->getNumParams() > PVD->getFunctionScopeIndex() && 2621 FD->getParamDecl(PVD->getFunctionScopeIndex()) 2622 ->getCanonicalDecl() == PVD->getCanonicalDecl()) { 2623 UniformedArgs.insert(std::make_pair(PVD->getCanonicalDecl(), E)); 2624 continue; 2625 } 2626 if (isa<CXXThisExpr>(E)) { 2627 UniformedLinearThis = E; 2628 continue; 2629 } 2630 Diag(E->getExprLoc(), diag::err_omp_param_or_this_in_clause) 2631 << FD->getDeclName() << (isa<CXXMethodDecl>(ADecl) ? 1 : 0); 2632 } 2633 // OpenMP [2.8.2, declare simd construct, Description] 2634 // The aligned clause declares that the object to which each list item points 2635 // is aligned to the number of bytes expressed in the optional parameter of 2636 // the aligned clause. 2637 // The special this pointer can be used as if was one of the arguments to the 2638 // function in any of the linear, aligned, or uniform clauses. 2639 // The type of list items appearing in the aligned clause must be array, 2640 // pointer, reference to array, or reference to pointer. 2641 llvm::DenseMap<Decl *, Expr *> AlignedArgs; 2642 Expr *AlignedThis = nullptr; 2643 for (auto *E : Aligneds) { 2644 E = E->IgnoreParenImpCasts(); 2645 if (auto *DRE = dyn_cast<DeclRefExpr>(E)) 2646 if (auto *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl())) { 2647 auto *CanonPVD = PVD->getCanonicalDecl(); 2648 if (FD->getNumParams() > PVD->getFunctionScopeIndex() && 2649 FD->getParamDecl(PVD->getFunctionScopeIndex()) 2650 ->getCanonicalDecl() == CanonPVD) { 2651 // OpenMP [2.8.1, simd construct, Restrictions] 2652 // A list-item cannot appear in more than one aligned clause. 2653 if (AlignedArgs.count(CanonPVD) > 0) { 2654 Diag(E->getExprLoc(), diag::err_omp_aligned_twice) 2655 << 1 << E->getSourceRange(); 2656 Diag(AlignedArgs[CanonPVD]->getExprLoc(), 2657 diag::note_omp_explicit_dsa) 2658 << getOpenMPClauseName(OMPC_aligned); 2659 continue; 2660 } 2661 AlignedArgs[CanonPVD] = E; 2662 QualType QTy = PVD->getType() 2663 .getNonReferenceType() 2664 .getUnqualifiedType() 2665 .getCanonicalType(); 2666 const Type *Ty = QTy.getTypePtrOrNull(); 2667 if (!Ty || (!Ty->isArrayType() && !Ty->isPointerType())) { 2668 Diag(E->getExprLoc(), diag::err_omp_aligned_expected_array_or_ptr) 2669 << QTy << getLangOpts().CPlusPlus << E->getSourceRange(); 2670 Diag(PVD->getLocation(), diag::note_previous_decl) << PVD; 2671 } 2672 continue; 2673 } 2674 } 2675 if (isa<CXXThisExpr>(E)) { 2676 if (AlignedThis) { 2677 Diag(E->getExprLoc(), diag::err_omp_aligned_twice) 2678 << 2 << E->getSourceRange(); 2679 Diag(AlignedThis->getExprLoc(), diag::note_omp_explicit_dsa) 2680 << getOpenMPClauseName(OMPC_aligned); 2681 } 2682 AlignedThis = E; 2683 continue; 2684 } 2685 Diag(E->getExprLoc(), diag::err_omp_param_or_this_in_clause) 2686 << FD->getDeclName() << (isa<CXXMethodDecl>(ADecl) ? 1 : 0); 2687 } 2688 // The optional parameter of the aligned clause, alignment, must be a constant 2689 // positive integer expression. If no optional parameter is specified, 2690 // implementation-defined default alignments for SIMD instructions on the 2691 // target platforms are assumed. 2692 SmallVector<Expr *, 4> NewAligns; 2693 for (auto *E : Alignments) { 2694 ExprResult Align; 2695 if (E) 2696 Align = VerifyPositiveIntegerConstantInClause(E, OMPC_aligned); 2697 NewAligns.push_back(Align.get()); 2698 } 2699 // OpenMP [2.8.2, declare simd construct, Description] 2700 // The linear clause declares one or more list items to be private to a SIMD 2701 // lane and to have a linear relationship with respect to the iteration space 2702 // of a loop. 2703 // The special this pointer can be used as if was one of the arguments to the 2704 // function in any of the linear, aligned, or uniform clauses. 2705 // When a linear-step expression is specified in a linear clause it must be 2706 // either a constant integer expression or an integer-typed parameter that is 2707 // specified in a uniform clause on the directive. 2708 llvm::DenseMap<Decl *, Expr *> LinearArgs; 2709 const bool IsUniformedThis = UniformedLinearThis != nullptr; 2710 auto MI = LinModifiers.begin(); 2711 for (auto *E : Linears) { 2712 auto LinKind = static_cast<OpenMPLinearClauseKind>(*MI); 2713 ++MI; 2714 E = E->IgnoreParenImpCasts(); 2715 if (auto *DRE = dyn_cast<DeclRefExpr>(E)) 2716 if (auto *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl())) { 2717 auto *CanonPVD = PVD->getCanonicalDecl(); 2718 if (FD->getNumParams() > PVD->getFunctionScopeIndex() && 2719 FD->getParamDecl(PVD->getFunctionScopeIndex()) 2720 ->getCanonicalDecl() == CanonPVD) { 2721 // OpenMP [2.15.3.7, linear Clause, Restrictions] 2722 // A list-item cannot appear in more than one linear clause. 2723 if (LinearArgs.count(CanonPVD) > 0) { 2724 Diag(E->getExprLoc(), diag::err_omp_wrong_dsa) 2725 << getOpenMPClauseName(OMPC_linear) 2726 << getOpenMPClauseName(OMPC_linear) << E->getSourceRange(); 2727 Diag(LinearArgs[CanonPVD]->getExprLoc(), 2728 diag::note_omp_explicit_dsa) 2729 << getOpenMPClauseName(OMPC_linear); 2730 continue; 2731 } 2732 // Each argument can appear in at most one uniform or linear clause. 2733 if (UniformedArgs.count(CanonPVD) > 0) { 2734 Diag(E->getExprLoc(), diag::err_omp_wrong_dsa) 2735 << getOpenMPClauseName(OMPC_linear) 2736 << getOpenMPClauseName(OMPC_uniform) << E->getSourceRange(); 2737 Diag(UniformedArgs[CanonPVD]->getExprLoc(), 2738 diag::note_omp_explicit_dsa) 2739 << getOpenMPClauseName(OMPC_uniform); 2740 continue; 2741 } 2742 LinearArgs[CanonPVD] = E; 2743 if (E->isValueDependent() || E->isTypeDependent() || 2744 E->isInstantiationDependent() || 2745 E->containsUnexpandedParameterPack()) 2746 continue; 2747 (void)CheckOpenMPLinearDecl(CanonPVD, E->getExprLoc(), LinKind, 2748 PVD->getOriginalType()); 2749 continue; 2750 } 2751 } 2752 if (isa<CXXThisExpr>(E)) { 2753 if (UniformedLinearThis) { 2754 Diag(E->getExprLoc(), diag::err_omp_wrong_dsa) 2755 << getOpenMPClauseName(OMPC_linear) 2756 << getOpenMPClauseName(IsUniformedThis ? OMPC_uniform : OMPC_linear) 2757 << E->getSourceRange(); 2758 Diag(UniformedLinearThis->getExprLoc(), diag::note_omp_explicit_dsa) 2759 << getOpenMPClauseName(IsUniformedThis ? OMPC_uniform 2760 : OMPC_linear); 2761 continue; 2762 } 2763 UniformedLinearThis = E; 2764 if (E->isValueDependent() || E->isTypeDependent() || 2765 E->isInstantiationDependent() || E->containsUnexpandedParameterPack()) 2766 continue; 2767 (void)CheckOpenMPLinearDecl(/*D=*/nullptr, E->getExprLoc(), LinKind, 2768 E->getType()); 2769 continue; 2770 } 2771 Diag(E->getExprLoc(), diag::err_omp_param_or_this_in_clause) 2772 << FD->getDeclName() << (isa<CXXMethodDecl>(ADecl) ? 1 : 0); 2773 } 2774 Expr *Step = nullptr; 2775 Expr *NewStep = nullptr; 2776 SmallVector<Expr *, 4> NewSteps; 2777 for (auto *E : Steps) { 2778 // Skip the same step expression, it was checked already. 2779 if (Step == E || !E) { 2780 NewSteps.push_back(E ? NewStep : nullptr); 2781 continue; 2782 } 2783 Step = E; 2784 if (auto *DRE = dyn_cast<DeclRefExpr>(Step)) 2785 if (auto *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl())) { 2786 auto *CanonPVD = PVD->getCanonicalDecl(); 2787 if (UniformedArgs.count(CanonPVD) == 0) { 2788 Diag(Step->getExprLoc(), diag::err_omp_expected_uniform_param) 2789 << Step->getSourceRange(); 2790 } else if (E->isValueDependent() || E->isTypeDependent() || 2791 E->isInstantiationDependent() || 2792 E->containsUnexpandedParameterPack() || 2793 CanonPVD->getType()->hasIntegerRepresentation()) 2794 NewSteps.push_back(Step); 2795 else { 2796 Diag(Step->getExprLoc(), diag::err_omp_expected_int_param) 2797 << Step->getSourceRange(); 2798 } 2799 continue; 2800 } 2801 NewStep = Step; 2802 if (Step && !Step->isValueDependent() && !Step->isTypeDependent() && 2803 !Step->isInstantiationDependent() && 2804 !Step->containsUnexpandedParameterPack()) { 2805 NewStep = PerformOpenMPImplicitIntegerConversion(Step->getExprLoc(), Step) 2806 .get(); 2807 if (NewStep) 2808 NewStep = VerifyIntegerConstantExpression(NewStep).get(); 2809 } 2810 NewSteps.push_back(NewStep); 2811 } 2812 auto *NewAttr = OMPDeclareSimdDeclAttr::CreateImplicit( 2813 Context, BS, SL.get(), const_cast<Expr **>(Uniforms.data()), 2814 Uniforms.size(), const_cast<Expr **>(Aligneds.data()), Aligneds.size(), 2815 const_cast<Expr **>(NewAligns.data()), NewAligns.size(), 2816 const_cast<Expr **>(Linears.data()), Linears.size(), 2817 const_cast<unsigned *>(LinModifiers.data()), LinModifiers.size(), 2818 NewSteps.data(), NewSteps.size(), SR); 2819 ADecl->addAttr(NewAttr); 2820 return ConvertDeclToDeclGroup(ADecl); 2821 } 2822 2823 StmtResult Sema::ActOnOpenMPParallelDirective(ArrayRef<OMPClause *> Clauses, 2824 Stmt *AStmt, 2825 SourceLocation StartLoc, 2826 SourceLocation EndLoc) { 2827 if (!AStmt) 2828 return StmtError(); 2829 2830 CapturedStmt *CS = cast<CapturedStmt>(AStmt); 2831 // 1.2.2 OpenMP Language Terminology 2832 // Structured block - An executable statement with a single entry at the 2833 // top and a single exit at the bottom. 2834 // The point of exit cannot be a branch out of the structured block. 2835 // longjmp() and throw() must not violate the entry/exit criteria. 2836 CS->getCapturedDecl()->setNothrow(); 2837 2838 getCurFunction()->setHasBranchProtectedScope(); 2839 2840 return OMPParallelDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt, 2841 DSAStack->isCancelRegion()); 2842 } 2843 2844 namespace { 2845 /// \brief Helper class for checking canonical form of the OpenMP loops and 2846 /// extracting iteration space of each loop in the loop nest, that will be used 2847 /// for IR generation. 2848 class OpenMPIterationSpaceChecker { 2849 /// \brief Reference to Sema. 2850 Sema &SemaRef; 2851 /// \brief A location for diagnostics (when there is no some better location). 2852 SourceLocation DefaultLoc; 2853 /// \brief A location for diagnostics (when increment is not compatible). 2854 SourceLocation ConditionLoc; 2855 /// \brief A source location for referring to loop init later. 2856 SourceRange InitSrcRange; 2857 /// \brief A source location for referring to condition later. 2858 SourceRange ConditionSrcRange; 2859 /// \brief A source location for referring to increment later. 2860 SourceRange IncrementSrcRange; 2861 /// \brief Loop variable. 2862 ValueDecl *LCDecl = nullptr; 2863 /// \brief Reference to loop variable. 2864 Expr *LCRef = nullptr; 2865 /// \brief Lower bound (initializer for the var). 2866 Expr *LB = nullptr; 2867 /// \brief Upper bound. 2868 Expr *UB = nullptr; 2869 /// \brief Loop step (increment). 2870 Expr *Step = nullptr; 2871 /// \brief This flag is true when condition is one of: 2872 /// Var < UB 2873 /// Var <= UB 2874 /// UB > Var 2875 /// UB >= Var 2876 bool TestIsLessOp = false; 2877 /// \brief This flag is true when condition is strict ( < or > ). 2878 bool TestIsStrictOp = false; 2879 /// \brief This flag is true when step is subtracted on each iteration. 2880 bool SubtractStep = false; 2881 2882 public: 2883 OpenMPIterationSpaceChecker(Sema &SemaRef, SourceLocation DefaultLoc) 2884 : SemaRef(SemaRef), DefaultLoc(DefaultLoc), ConditionLoc(DefaultLoc) {} 2885 /// \brief Check init-expr for canonical loop form and save loop counter 2886 /// variable - #Var and its initialization value - #LB. 2887 bool CheckInit(Stmt *S, bool EmitDiags = true); 2888 /// \brief Check test-expr for canonical form, save upper-bound (#UB), flags 2889 /// for less/greater and for strict/non-strict comparison. 2890 bool CheckCond(Expr *S); 2891 /// \brief Check incr-expr for canonical loop form and return true if it 2892 /// does not conform, otherwise save loop step (#Step). 2893 bool CheckInc(Expr *S); 2894 /// \brief Return the loop counter variable. 2895 ValueDecl *GetLoopDecl() const { return LCDecl; } 2896 /// \brief Return the reference expression to loop counter variable. 2897 Expr *GetLoopDeclRefExpr() const { return LCRef; } 2898 /// \brief Source range of the loop init. 2899 SourceRange GetInitSrcRange() const { return InitSrcRange; } 2900 /// \brief Source range of the loop condition. 2901 SourceRange GetConditionSrcRange() const { return ConditionSrcRange; } 2902 /// \brief Source range of the loop increment. 2903 SourceRange GetIncrementSrcRange() const { return IncrementSrcRange; } 2904 /// \brief True if the step should be subtracted. 2905 bool ShouldSubtractStep() const { return SubtractStep; } 2906 /// \brief Build the expression to calculate the number of iterations. 2907 Expr * 2908 BuildNumIterations(Scope *S, const bool LimitedType, 2909 llvm::MapVector<Expr *, DeclRefExpr *> &Captures) const; 2910 /// \brief Build the precondition expression for the loops. 2911 Expr *BuildPreCond(Scope *S, Expr *Cond, 2912 llvm::MapVector<Expr *, DeclRefExpr *> &Captures) const; 2913 /// \brief Build reference expression to the counter be used for codegen. 2914 DeclRefExpr *BuildCounterVar(llvm::MapVector<Expr *, DeclRefExpr *> &Captures, 2915 DSAStackTy &DSA) const; 2916 /// \brief Build reference expression to the private counter be used for 2917 /// codegen. 2918 Expr *BuildPrivateCounterVar() const; 2919 /// \brief Build initialization of the counter be used for codegen. 2920 Expr *BuildCounterInit() const; 2921 /// \brief Build step of the counter be used for codegen. 2922 Expr *BuildCounterStep() const; 2923 /// \brief Return true if any expression is dependent. 2924 bool Dependent() const; 2925 2926 private: 2927 /// \brief Check the right-hand side of an assignment in the increment 2928 /// expression. 2929 bool CheckIncRHS(Expr *RHS); 2930 /// \brief Helper to set loop counter variable and its initializer. 2931 bool SetLCDeclAndLB(ValueDecl *NewLCDecl, Expr *NewDeclRefExpr, Expr *NewLB); 2932 /// \brief Helper to set upper bound. 2933 bool SetUB(Expr *NewUB, bool LessOp, bool StrictOp, SourceRange SR, 2934 SourceLocation SL); 2935 /// \brief Helper to set loop increment. 2936 bool SetStep(Expr *NewStep, bool Subtract); 2937 }; 2938 2939 bool OpenMPIterationSpaceChecker::Dependent() const { 2940 if (!LCDecl) { 2941 assert(!LB && !UB && !Step); 2942 return false; 2943 } 2944 return LCDecl->getType()->isDependentType() || 2945 (LB && LB->isValueDependent()) || (UB && UB->isValueDependent()) || 2946 (Step && Step->isValueDependent()); 2947 } 2948 2949 static Expr *getExprAsWritten(Expr *E) { 2950 if (auto *ExprTemp = dyn_cast<ExprWithCleanups>(E)) 2951 E = ExprTemp->getSubExpr(); 2952 2953 if (auto *MTE = dyn_cast<MaterializeTemporaryExpr>(E)) 2954 E = MTE->GetTemporaryExpr(); 2955 2956 while (auto *Binder = dyn_cast<CXXBindTemporaryExpr>(E)) 2957 E = Binder->getSubExpr(); 2958 2959 if (auto *ICE = dyn_cast<ImplicitCastExpr>(E)) 2960 E = ICE->getSubExprAsWritten(); 2961 return E->IgnoreParens(); 2962 } 2963 2964 bool OpenMPIterationSpaceChecker::SetLCDeclAndLB(ValueDecl *NewLCDecl, 2965 Expr *NewLCRefExpr, 2966 Expr *NewLB) { 2967 // State consistency checking to ensure correct usage. 2968 assert(LCDecl == nullptr && LB == nullptr && LCRef == nullptr && 2969 UB == nullptr && Step == nullptr && !TestIsLessOp && !TestIsStrictOp); 2970 if (!NewLCDecl || !NewLB) 2971 return true; 2972 LCDecl = getCanonicalDecl(NewLCDecl); 2973 LCRef = NewLCRefExpr; 2974 if (auto *CE = dyn_cast_or_null<CXXConstructExpr>(NewLB)) 2975 if (const CXXConstructorDecl *Ctor = CE->getConstructor()) 2976 if ((Ctor->isCopyOrMoveConstructor() || 2977 Ctor->isConvertingConstructor(/*AllowExplicit=*/false)) && 2978 CE->getNumArgs() > 0 && CE->getArg(0) != nullptr) 2979 NewLB = CE->getArg(0)->IgnoreParenImpCasts(); 2980 LB = NewLB; 2981 return false; 2982 } 2983 2984 bool OpenMPIterationSpaceChecker::SetUB(Expr *NewUB, bool LessOp, bool StrictOp, 2985 SourceRange SR, SourceLocation SL) { 2986 // State consistency checking to ensure correct usage. 2987 assert(LCDecl != nullptr && LB != nullptr && UB == nullptr && 2988 Step == nullptr && !TestIsLessOp && !TestIsStrictOp); 2989 if (!NewUB) 2990 return true; 2991 UB = NewUB; 2992 TestIsLessOp = LessOp; 2993 TestIsStrictOp = StrictOp; 2994 ConditionSrcRange = SR; 2995 ConditionLoc = SL; 2996 return false; 2997 } 2998 2999 bool OpenMPIterationSpaceChecker::SetStep(Expr *NewStep, bool Subtract) { 3000 // State consistency checking to ensure correct usage. 3001 assert(LCDecl != nullptr && LB != nullptr && Step == nullptr); 3002 if (!NewStep) 3003 return true; 3004 if (!NewStep->isValueDependent()) { 3005 // Check that the step is integer expression. 3006 SourceLocation StepLoc = NewStep->getLocStart(); 3007 ExprResult Val = 3008 SemaRef.PerformOpenMPImplicitIntegerConversion(StepLoc, NewStep); 3009 if (Val.isInvalid()) 3010 return true; 3011 NewStep = Val.get(); 3012 3013 // OpenMP [2.6, Canonical Loop Form, Restrictions] 3014 // If test-expr is of form var relational-op b and relational-op is < or 3015 // <= then incr-expr must cause var to increase on each iteration of the 3016 // loop. If test-expr is of form var relational-op b and relational-op is 3017 // > or >= then incr-expr must cause var to decrease on each iteration of 3018 // the loop. 3019 // If test-expr is of form b relational-op var and relational-op is < or 3020 // <= then incr-expr must cause var to decrease on each iteration of the 3021 // loop. If test-expr is of form b relational-op var and relational-op is 3022 // > or >= then incr-expr must cause var to increase on each iteration of 3023 // the loop. 3024 llvm::APSInt Result; 3025 bool IsConstant = NewStep->isIntegerConstantExpr(Result, SemaRef.Context); 3026 bool IsUnsigned = !NewStep->getType()->hasSignedIntegerRepresentation(); 3027 bool IsConstNeg = 3028 IsConstant && Result.isSigned() && (Subtract != Result.isNegative()); 3029 bool IsConstPos = 3030 IsConstant && Result.isSigned() && (Subtract == Result.isNegative()); 3031 bool IsConstZero = IsConstant && !Result.getBoolValue(); 3032 if (UB && (IsConstZero || 3033 (TestIsLessOp ? (IsConstNeg || (IsUnsigned && Subtract)) 3034 : (IsConstPos || (IsUnsigned && !Subtract))))) { 3035 SemaRef.Diag(NewStep->getExprLoc(), 3036 diag::err_omp_loop_incr_not_compatible) 3037 << LCDecl << TestIsLessOp << NewStep->getSourceRange(); 3038 SemaRef.Diag(ConditionLoc, 3039 diag::note_omp_loop_cond_requres_compatible_incr) 3040 << TestIsLessOp << ConditionSrcRange; 3041 return true; 3042 } 3043 if (TestIsLessOp == Subtract) { 3044 NewStep = 3045 SemaRef.CreateBuiltinUnaryOp(NewStep->getExprLoc(), UO_Minus, NewStep) 3046 .get(); 3047 Subtract = !Subtract; 3048 } 3049 } 3050 3051 Step = NewStep; 3052 SubtractStep = Subtract; 3053 return false; 3054 } 3055 3056 bool OpenMPIterationSpaceChecker::CheckInit(Stmt *S, bool EmitDiags) { 3057 // Check init-expr for canonical loop form and save loop counter 3058 // variable - #Var and its initialization value - #LB. 3059 // OpenMP [2.6] Canonical loop form. init-expr may be one of the following: 3060 // var = lb 3061 // integer-type var = lb 3062 // random-access-iterator-type var = lb 3063 // pointer-type var = lb 3064 // 3065 if (!S) { 3066 if (EmitDiags) { 3067 SemaRef.Diag(DefaultLoc, diag::err_omp_loop_not_canonical_init); 3068 } 3069 return true; 3070 } 3071 if (auto *ExprTemp = dyn_cast<ExprWithCleanups>(S)) 3072 if (!ExprTemp->cleanupsHaveSideEffects()) 3073 S = ExprTemp->getSubExpr(); 3074 3075 InitSrcRange = S->getSourceRange(); 3076 if (Expr *E = dyn_cast<Expr>(S)) 3077 S = E->IgnoreParens(); 3078 if (auto *BO = dyn_cast<BinaryOperator>(S)) { 3079 if (BO->getOpcode() == BO_Assign) { 3080 auto *LHS = BO->getLHS()->IgnoreParens(); 3081 if (auto *DRE = dyn_cast<DeclRefExpr>(LHS)) { 3082 if (auto *CED = dyn_cast<OMPCapturedExprDecl>(DRE->getDecl())) 3083 if (auto *ME = dyn_cast<MemberExpr>(getExprAsWritten(CED->getInit()))) 3084 return SetLCDeclAndLB(ME->getMemberDecl(), ME, BO->getRHS()); 3085 return SetLCDeclAndLB(DRE->getDecl(), DRE, BO->getRHS()); 3086 } 3087 if (auto *ME = dyn_cast<MemberExpr>(LHS)) { 3088 if (ME->isArrow() && 3089 isa<CXXThisExpr>(ME->getBase()->IgnoreParenImpCasts())) 3090 return SetLCDeclAndLB(ME->getMemberDecl(), ME, BO->getRHS()); 3091 } 3092 } 3093 } else if (auto *DS = dyn_cast<DeclStmt>(S)) { 3094 if (DS->isSingleDecl()) { 3095 if (auto *Var = dyn_cast_or_null<VarDecl>(DS->getSingleDecl())) { 3096 if (Var->hasInit() && !Var->getType()->isReferenceType()) { 3097 // Accept non-canonical init form here but emit ext. warning. 3098 if (Var->getInitStyle() != VarDecl::CInit && EmitDiags) 3099 SemaRef.Diag(S->getLocStart(), 3100 diag::ext_omp_loop_not_canonical_init) 3101 << S->getSourceRange(); 3102 return SetLCDeclAndLB(Var, nullptr, Var->getInit()); 3103 } 3104 } 3105 } 3106 } else if (auto *CE = dyn_cast<CXXOperatorCallExpr>(S)) { 3107 if (CE->getOperator() == OO_Equal) { 3108 auto *LHS = CE->getArg(0); 3109 if (auto *DRE = dyn_cast<DeclRefExpr>(LHS)) { 3110 if (auto *CED = dyn_cast<OMPCapturedExprDecl>(DRE->getDecl())) 3111 if (auto *ME = dyn_cast<MemberExpr>(getExprAsWritten(CED->getInit()))) 3112 return SetLCDeclAndLB(ME->getMemberDecl(), ME, BO->getRHS()); 3113 return SetLCDeclAndLB(DRE->getDecl(), DRE, CE->getArg(1)); 3114 } 3115 if (auto *ME = dyn_cast<MemberExpr>(LHS)) { 3116 if (ME->isArrow() && 3117 isa<CXXThisExpr>(ME->getBase()->IgnoreParenImpCasts())) 3118 return SetLCDeclAndLB(ME->getMemberDecl(), ME, BO->getRHS()); 3119 } 3120 } 3121 } 3122 3123 if (Dependent() || SemaRef.CurContext->isDependentContext()) 3124 return false; 3125 if (EmitDiags) { 3126 SemaRef.Diag(S->getLocStart(), diag::err_omp_loop_not_canonical_init) 3127 << S->getSourceRange(); 3128 } 3129 return true; 3130 } 3131 3132 /// \brief Ignore parenthesizes, implicit casts, copy constructor and return the 3133 /// variable (which may be the loop variable) if possible. 3134 static const ValueDecl *GetInitLCDecl(Expr *E) { 3135 if (!E) 3136 return nullptr; 3137 E = getExprAsWritten(E); 3138 if (auto *CE = dyn_cast_or_null<CXXConstructExpr>(E)) 3139 if (const CXXConstructorDecl *Ctor = CE->getConstructor()) 3140 if ((Ctor->isCopyOrMoveConstructor() || 3141 Ctor->isConvertingConstructor(/*AllowExplicit=*/false)) && 3142 CE->getNumArgs() > 0 && CE->getArg(0) != nullptr) 3143 E = CE->getArg(0)->IgnoreParenImpCasts(); 3144 if (auto *DRE = dyn_cast_or_null<DeclRefExpr>(E)) { 3145 if (auto *VD = dyn_cast<VarDecl>(DRE->getDecl())) { 3146 if (auto *CED = dyn_cast<OMPCapturedExprDecl>(VD)) 3147 if (auto *ME = dyn_cast<MemberExpr>(getExprAsWritten(CED->getInit()))) 3148 return getCanonicalDecl(ME->getMemberDecl()); 3149 return getCanonicalDecl(VD); 3150 } 3151 } 3152 if (auto *ME = dyn_cast_or_null<MemberExpr>(E)) 3153 if (ME->isArrow() && isa<CXXThisExpr>(ME->getBase()->IgnoreParenImpCasts())) 3154 return getCanonicalDecl(ME->getMemberDecl()); 3155 return nullptr; 3156 } 3157 3158 bool OpenMPIterationSpaceChecker::CheckCond(Expr *S) { 3159 // Check test-expr for canonical form, save upper-bound UB, flags for 3160 // less/greater and for strict/non-strict comparison. 3161 // OpenMP [2.6] Canonical loop form. Test-expr may be one of the following: 3162 // var relational-op b 3163 // b relational-op var 3164 // 3165 if (!S) { 3166 SemaRef.Diag(DefaultLoc, diag::err_omp_loop_not_canonical_cond) << LCDecl; 3167 return true; 3168 } 3169 S = getExprAsWritten(S); 3170 SourceLocation CondLoc = S->getLocStart(); 3171 if (auto *BO = dyn_cast<BinaryOperator>(S)) { 3172 if (BO->isRelationalOp()) { 3173 if (GetInitLCDecl(BO->getLHS()) == LCDecl) 3174 return SetUB(BO->getRHS(), 3175 (BO->getOpcode() == BO_LT || BO->getOpcode() == BO_LE), 3176 (BO->getOpcode() == BO_LT || BO->getOpcode() == BO_GT), 3177 BO->getSourceRange(), BO->getOperatorLoc()); 3178 if (GetInitLCDecl(BO->getRHS()) == LCDecl) 3179 return SetUB(BO->getLHS(), 3180 (BO->getOpcode() == BO_GT || BO->getOpcode() == BO_GE), 3181 (BO->getOpcode() == BO_LT || BO->getOpcode() == BO_GT), 3182 BO->getSourceRange(), BO->getOperatorLoc()); 3183 } 3184 } else if (auto *CE = dyn_cast<CXXOperatorCallExpr>(S)) { 3185 if (CE->getNumArgs() == 2) { 3186 auto Op = CE->getOperator(); 3187 switch (Op) { 3188 case OO_Greater: 3189 case OO_GreaterEqual: 3190 case OO_Less: 3191 case OO_LessEqual: 3192 if (GetInitLCDecl(CE->getArg(0)) == LCDecl) 3193 return SetUB(CE->getArg(1), Op == OO_Less || Op == OO_LessEqual, 3194 Op == OO_Less || Op == OO_Greater, CE->getSourceRange(), 3195 CE->getOperatorLoc()); 3196 if (GetInitLCDecl(CE->getArg(1)) == LCDecl) 3197 return SetUB(CE->getArg(0), Op == OO_Greater || Op == OO_GreaterEqual, 3198 Op == OO_Less || Op == OO_Greater, CE->getSourceRange(), 3199 CE->getOperatorLoc()); 3200 break; 3201 default: 3202 break; 3203 } 3204 } 3205 } 3206 if (Dependent() || SemaRef.CurContext->isDependentContext()) 3207 return false; 3208 SemaRef.Diag(CondLoc, diag::err_omp_loop_not_canonical_cond) 3209 << S->getSourceRange() << LCDecl; 3210 return true; 3211 } 3212 3213 bool OpenMPIterationSpaceChecker::CheckIncRHS(Expr *RHS) { 3214 // RHS of canonical loop form increment can be: 3215 // var + incr 3216 // incr + var 3217 // var - incr 3218 // 3219 RHS = RHS->IgnoreParenImpCasts(); 3220 if (auto *BO = dyn_cast<BinaryOperator>(RHS)) { 3221 if (BO->isAdditiveOp()) { 3222 bool IsAdd = BO->getOpcode() == BO_Add; 3223 if (GetInitLCDecl(BO->getLHS()) == LCDecl) 3224 return SetStep(BO->getRHS(), !IsAdd); 3225 if (IsAdd && GetInitLCDecl(BO->getRHS()) == LCDecl) 3226 return SetStep(BO->getLHS(), false); 3227 } 3228 } else if (auto *CE = dyn_cast<CXXOperatorCallExpr>(RHS)) { 3229 bool IsAdd = CE->getOperator() == OO_Plus; 3230 if ((IsAdd || CE->getOperator() == OO_Minus) && CE->getNumArgs() == 2) { 3231 if (GetInitLCDecl(CE->getArg(0)) == LCDecl) 3232 return SetStep(CE->getArg(1), !IsAdd); 3233 if (IsAdd && GetInitLCDecl(CE->getArg(1)) == LCDecl) 3234 return SetStep(CE->getArg(0), false); 3235 } 3236 } 3237 if (Dependent() || SemaRef.CurContext->isDependentContext()) 3238 return false; 3239 SemaRef.Diag(RHS->getLocStart(), diag::err_omp_loop_not_canonical_incr) 3240 << RHS->getSourceRange() << LCDecl; 3241 return true; 3242 } 3243 3244 bool OpenMPIterationSpaceChecker::CheckInc(Expr *S) { 3245 // Check incr-expr for canonical loop form and return true if it 3246 // does not conform. 3247 // OpenMP [2.6] Canonical loop form. Test-expr may be one of the following: 3248 // ++var 3249 // var++ 3250 // --var 3251 // var-- 3252 // var += incr 3253 // var -= incr 3254 // var = var + incr 3255 // var = incr + var 3256 // var = var - incr 3257 // 3258 if (!S) { 3259 SemaRef.Diag(DefaultLoc, diag::err_omp_loop_not_canonical_incr) << LCDecl; 3260 return true; 3261 } 3262 if (auto *ExprTemp = dyn_cast<ExprWithCleanups>(S)) 3263 if (!ExprTemp->cleanupsHaveSideEffects()) 3264 S = ExprTemp->getSubExpr(); 3265 3266 IncrementSrcRange = S->getSourceRange(); 3267 S = S->IgnoreParens(); 3268 if (auto *UO = dyn_cast<UnaryOperator>(S)) { 3269 if (UO->isIncrementDecrementOp() && 3270 GetInitLCDecl(UO->getSubExpr()) == LCDecl) 3271 return SetStep(SemaRef 3272 .ActOnIntegerConstant(UO->getLocStart(), 3273 (UO->isDecrementOp() ? -1 : 1)) 3274 .get(), 3275 false); 3276 } else if (auto *BO = dyn_cast<BinaryOperator>(S)) { 3277 switch (BO->getOpcode()) { 3278 case BO_AddAssign: 3279 case BO_SubAssign: 3280 if (GetInitLCDecl(BO->getLHS()) == LCDecl) 3281 return SetStep(BO->getRHS(), BO->getOpcode() == BO_SubAssign); 3282 break; 3283 case BO_Assign: 3284 if (GetInitLCDecl(BO->getLHS()) == LCDecl) 3285 return CheckIncRHS(BO->getRHS()); 3286 break; 3287 default: 3288 break; 3289 } 3290 } else if (auto *CE = dyn_cast<CXXOperatorCallExpr>(S)) { 3291 switch (CE->getOperator()) { 3292 case OO_PlusPlus: 3293 case OO_MinusMinus: 3294 if (GetInitLCDecl(CE->getArg(0)) == LCDecl) 3295 return SetStep(SemaRef 3296 .ActOnIntegerConstant( 3297 CE->getLocStart(), 3298 ((CE->getOperator() == OO_MinusMinus) ? -1 : 1)) 3299 .get(), 3300 false); 3301 break; 3302 case OO_PlusEqual: 3303 case OO_MinusEqual: 3304 if (GetInitLCDecl(CE->getArg(0)) == LCDecl) 3305 return SetStep(CE->getArg(1), CE->getOperator() == OO_MinusEqual); 3306 break; 3307 case OO_Equal: 3308 if (GetInitLCDecl(CE->getArg(0)) == LCDecl) 3309 return CheckIncRHS(CE->getArg(1)); 3310 break; 3311 default: 3312 break; 3313 } 3314 } 3315 if (Dependent() || SemaRef.CurContext->isDependentContext()) 3316 return false; 3317 SemaRef.Diag(S->getLocStart(), diag::err_omp_loop_not_canonical_incr) 3318 << S->getSourceRange() << LCDecl; 3319 return true; 3320 } 3321 3322 static ExprResult 3323 tryBuildCapture(Sema &SemaRef, Expr *Capture, 3324 llvm::MapVector<Expr *, DeclRefExpr *> &Captures) { 3325 if (SemaRef.CurContext->isDependentContext()) 3326 return ExprResult(Capture); 3327 if (Capture->isEvaluatable(SemaRef.Context, Expr::SE_AllowSideEffects)) 3328 return SemaRef.PerformImplicitConversion( 3329 Capture->IgnoreImpCasts(), Capture->getType(), Sema::AA_Converting, 3330 /*AllowExplicit=*/true); 3331 auto I = Captures.find(Capture); 3332 if (I != Captures.end()) 3333 return buildCapture(SemaRef, Capture, I->second); 3334 DeclRefExpr *Ref = nullptr; 3335 ExprResult Res = buildCapture(SemaRef, Capture, Ref); 3336 Captures[Capture] = Ref; 3337 return Res; 3338 } 3339 3340 /// \brief Build the expression to calculate the number of iterations. 3341 Expr *OpenMPIterationSpaceChecker::BuildNumIterations( 3342 Scope *S, const bool LimitedType, 3343 llvm::MapVector<Expr *, DeclRefExpr *> &Captures) const { 3344 ExprResult Diff; 3345 auto VarType = LCDecl->getType().getNonReferenceType(); 3346 if (VarType->isIntegerType() || VarType->isPointerType() || 3347 SemaRef.getLangOpts().CPlusPlus) { 3348 // Upper - Lower 3349 auto *UBExpr = TestIsLessOp ? UB : LB; 3350 auto *LBExpr = TestIsLessOp ? LB : UB; 3351 Expr *Upper = tryBuildCapture(SemaRef, UBExpr, Captures).get(); 3352 Expr *Lower = tryBuildCapture(SemaRef, LBExpr, Captures).get(); 3353 if (!Upper || !Lower) 3354 return nullptr; 3355 3356 Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Sub, Upper, Lower); 3357 3358 if (!Diff.isUsable() && VarType->getAsCXXRecordDecl()) { 3359 // BuildBinOp already emitted error, this one is to point user to upper 3360 // and lower bound, and to tell what is passed to 'operator-'. 3361 SemaRef.Diag(Upper->getLocStart(), diag::err_omp_loop_diff_cxx) 3362 << Upper->getSourceRange() << Lower->getSourceRange(); 3363 return nullptr; 3364 } 3365 } 3366 3367 if (!Diff.isUsable()) 3368 return nullptr; 3369 3370 // Upper - Lower [- 1] 3371 if (TestIsStrictOp) 3372 Diff = SemaRef.BuildBinOp( 3373 S, DefaultLoc, BO_Sub, Diff.get(), 3374 SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get()); 3375 if (!Diff.isUsable()) 3376 return nullptr; 3377 3378 // Upper - Lower [- 1] + Step 3379 auto NewStep = tryBuildCapture(SemaRef, Step, Captures); 3380 if (!NewStep.isUsable()) 3381 return nullptr; 3382 Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Add, Diff.get(), NewStep.get()); 3383 if (!Diff.isUsable()) 3384 return nullptr; 3385 3386 // Parentheses (for dumping/debugging purposes only). 3387 Diff = SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, Diff.get()); 3388 if (!Diff.isUsable()) 3389 return nullptr; 3390 3391 // (Upper - Lower [- 1] + Step) / Step 3392 Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Div, Diff.get(), NewStep.get()); 3393 if (!Diff.isUsable()) 3394 return nullptr; 3395 3396 // OpenMP runtime requires 32-bit or 64-bit loop variables. 3397 QualType Type = Diff.get()->getType(); 3398 auto &C = SemaRef.Context; 3399 bool UseVarType = VarType->hasIntegerRepresentation() && 3400 C.getTypeSize(Type) > C.getTypeSize(VarType); 3401 if (!Type->isIntegerType() || UseVarType) { 3402 unsigned NewSize = 3403 UseVarType ? C.getTypeSize(VarType) : C.getTypeSize(Type); 3404 bool IsSigned = UseVarType ? VarType->hasSignedIntegerRepresentation() 3405 : Type->hasSignedIntegerRepresentation(); 3406 Type = C.getIntTypeForBitwidth(NewSize, IsSigned); 3407 if (!SemaRef.Context.hasSameType(Diff.get()->getType(), Type)) { 3408 Diff = SemaRef.PerformImplicitConversion( 3409 Diff.get(), Type, Sema::AA_Converting, /*AllowExplicit=*/true); 3410 if (!Diff.isUsable()) 3411 return nullptr; 3412 } 3413 } 3414 if (LimitedType) { 3415 unsigned NewSize = (C.getTypeSize(Type) > 32) ? 64 : 32; 3416 if (NewSize != C.getTypeSize(Type)) { 3417 if (NewSize < C.getTypeSize(Type)) { 3418 assert(NewSize == 64 && "incorrect loop var size"); 3419 SemaRef.Diag(DefaultLoc, diag::warn_omp_loop_64_bit_var) 3420 << InitSrcRange << ConditionSrcRange; 3421 } 3422 QualType NewType = C.getIntTypeForBitwidth( 3423 NewSize, Type->hasSignedIntegerRepresentation() || 3424 C.getTypeSize(Type) < NewSize); 3425 if (!SemaRef.Context.hasSameType(Diff.get()->getType(), NewType)) { 3426 Diff = SemaRef.PerformImplicitConversion(Diff.get(), NewType, 3427 Sema::AA_Converting, true); 3428 if (!Diff.isUsable()) 3429 return nullptr; 3430 } 3431 } 3432 } 3433 3434 return Diff.get(); 3435 } 3436 3437 Expr *OpenMPIterationSpaceChecker::BuildPreCond( 3438 Scope *S, Expr *Cond, 3439 llvm::MapVector<Expr *, DeclRefExpr *> &Captures) const { 3440 // Try to build LB <op> UB, where <op> is <, >, <=, or >=. 3441 bool Suppress = SemaRef.getDiagnostics().getSuppressAllDiagnostics(); 3442 SemaRef.getDiagnostics().setSuppressAllDiagnostics(/*Val=*/true); 3443 3444 auto NewLB = tryBuildCapture(SemaRef, LB, Captures); 3445 auto NewUB = tryBuildCapture(SemaRef, UB, Captures); 3446 if (!NewLB.isUsable() || !NewUB.isUsable()) 3447 return nullptr; 3448 3449 auto CondExpr = SemaRef.BuildBinOp( 3450 S, DefaultLoc, TestIsLessOp ? (TestIsStrictOp ? BO_LT : BO_LE) 3451 : (TestIsStrictOp ? BO_GT : BO_GE), 3452 NewLB.get(), NewUB.get()); 3453 if (CondExpr.isUsable()) { 3454 if (!SemaRef.Context.hasSameUnqualifiedType(CondExpr.get()->getType(), 3455 SemaRef.Context.BoolTy)) 3456 CondExpr = SemaRef.PerformImplicitConversion( 3457 CondExpr.get(), SemaRef.Context.BoolTy, /*Action=*/Sema::AA_Casting, 3458 /*AllowExplicit=*/true); 3459 } 3460 SemaRef.getDiagnostics().setSuppressAllDiagnostics(Suppress); 3461 // Otherwise use original loop conditon and evaluate it in runtime. 3462 return CondExpr.isUsable() ? CondExpr.get() : Cond; 3463 } 3464 3465 /// \brief Build reference expression to the counter be used for codegen. 3466 DeclRefExpr *OpenMPIterationSpaceChecker::BuildCounterVar( 3467 llvm::MapVector<Expr *, DeclRefExpr *> &Captures, DSAStackTy &DSA) const { 3468 auto *VD = dyn_cast<VarDecl>(LCDecl); 3469 if (!VD) { 3470 VD = SemaRef.IsOpenMPCapturedDecl(LCDecl); 3471 auto *Ref = buildDeclRefExpr( 3472 SemaRef, VD, VD->getType().getNonReferenceType(), DefaultLoc); 3473 DSAStackTy::DSAVarData Data = DSA.getTopDSA(LCDecl, /*FromParent=*/false); 3474 // If the loop control decl is explicitly marked as private, do not mark it 3475 // as captured again. 3476 if (!isOpenMPPrivate(Data.CKind) || !Data.RefExpr) 3477 Captures.insert(std::make_pair(LCRef, Ref)); 3478 return Ref; 3479 } 3480 return buildDeclRefExpr(SemaRef, VD, VD->getType().getNonReferenceType(), 3481 DefaultLoc); 3482 } 3483 3484 Expr *OpenMPIterationSpaceChecker::BuildPrivateCounterVar() const { 3485 if (LCDecl && !LCDecl->isInvalidDecl()) { 3486 auto Type = LCDecl->getType().getNonReferenceType(); 3487 auto *PrivateVar = 3488 buildVarDecl(SemaRef, DefaultLoc, Type, LCDecl->getName(), 3489 LCDecl->hasAttrs() ? &LCDecl->getAttrs() : nullptr); 3490 if (PrivateVar->isInvalidDecl()) 3491 return nullptr; 3492 return buildDeclRefExpr(SemaRef, PrivateVar, Type, DefaultLoc); 3493 } 3494 return nullptr; 3495 } 3496 3497 /// \brief Build initialization of the counter to be used for codegen. 3498 Expr *OpenMPIterationSpaceChecker::BuildCounterInit() const { return LB; } 3499 3500 /// \brief Build step of the counter be used for codegen. 3501 Expr *OpenMPIterationSpaceChecker::BuildCounterStep() const { return Step; } 3502 3503 /// \brief Iteration space of a single for loop. 3504 struct LoopIterationSpace final { 3505 /// \brief Condition of the loop. 3506 Expr *PreCond = nullptr; 3507 /// \brief This expression calculates the number of iterations in the loop. 3508 /// It is always possible to calculate it before starting the loop. 3509 Expr *NumIterations = nullptr; 3510 /// \brief The loop counter variable. 3511 Expr *CounterVar = nullptr; 3512 /// \brief Private loop counter variable. 3513 Expr *PrivateCounterVar = nullptr; 3514 /// \brief This is initializer for the initial value of #CounterVar. 3515 Expr *CounterInit = nullptr; 3516 /// \brief This is step for the #CounterVar used to generate its update: 3517 /// #CounterVar = #CounterInit + #CounterStep * CurrentIteration. 3518 Expr *CounterStep = nullptr; 3519 /// \brief Should step be subtracted? 3520 bool Subtract = false; 3521 /// \brief Source range of the loop init. 3522 SourceRange InitSrcRange; 3523 /// \brief Source range of the loop condition. 3524 SourceRange CondSrcRange; 3525 /// \brief Source range of the loop increment. 3526 SourceRange IncSrcRange; 3527 }; 3528 3529 } // namespace 3530 3531 void Sema::ActOnOpenMPLoopInitialization(SourceLocation ForLoc, Stmt *Init) { 3532 assert(getLangOpts().OpenMP && "OpenMP is not active."); 3533 assert(Init && "Expected loop in canonical form."); 3534 unsigned AssociatedLoops = DSAStack->getAssociatedLoops(); 3535 if (AssociatedLoops > 0 && 3536 isOpenMPLoopDirective(DSAStack->getCurrentDirective())) { 3537 OpenMPIterationSpaceChecker ISC(*this, ForLoc); 3538 if (!ISC.CheckInit(Init, /*EmitDiags=*/false)) { 3539 if (auto *D = ISC.GetLoopDecl()) { 3540 auto *VD = dyn_cast<VarDecl>(D); 3541 if (!VD) { 3542 if (auto *Private = IsOpenMPCapturedDecl(D)) 3543 VD = Private; 3544 else { 3545 auto *Ref = buildCapture(*this, D, ISC.GetLoopDeclRefExpr(), 3546 /*WithInit=*/false); 3547 VD = cast<VarDecl>(Ref->getDecl()); 3548 } 3549 } 3550 DSAStack->addLoopControlVariable(D, VD); 3551 } 3552 } 3553 DSAStack->setAssociatedLoops(AssociatedLoops - 1); 3554 } 3555 } 3556 3557 /// \brief Called on a for stmt to check and extract its iteration space 3558 /// for further processing (such as collapsing). 3559 static bool CheckOpenMPIterationSpace( 3560 OpenMPDirectiveKind DKind, Stmt *S, Sema &SemaRef, DSAStackTy &DSA, 3561 unsigned CurrentNestedLoopCount, unsigned NestedLoopCount, 3562 Expr *CollapseLoopCountExpr, Expr *OrderedLoopCountExpr, 3563 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA, 3564 LoopIterationSpace &ResultIterSpace, 3565 llvm::MapVector<Expr *, DeclRefExpr *> &Captures) { 3566 // OpenMP [2.6, Canonical Loop Form] 3567 // for (init-expr; test-expr; incr-expr) structured-block 3568 auto *For = dyn_cast_or_null<ForStmt>(S); 3569 if (!For) { 3570 SemaRef.Diag(S->getLocStart(), diag::err_omp_not_for) 3571 << (CollapseLoopCountExpr != nullptr || OrderedLoopCountExpr != nullptr) 3572 << getOpenMPDirectiveName(DKind) << NestedLoopCount 3573 << (CurrentNestedLoopCount > 0) << CurrentNestedLoopCount; 3574 if (NestedLoopCount > 1) { 3575 if (CollapseLoopCountExpr && OrderedLoopCountExpr) 3576 SemaRef.Diag(DSA.getConstructLoc(), 3577 diag::note_omp_collapse_ordered_expr) 3578 << 2 << CollapseLoopCountExpr->getSourceRange() 3579 << OrderedLoopCountExpr->getSourceRange(); 3580 else if (CollapseLoopCountExpr) 3581 SemaRef.Diag(CollapseLoopCountExpr->getExprLoc(), 3582 diag::note_omp_collapse_ordered_expr) 3583 << 0 << CollapseLoopCountExpr->getSourceRange(); 3584 else 3585 SemaRef.Diag(OrderedLoopCountExpr->getExprLoc(), 3586 diag::note_omp_collapse_ordered_expr) 3587 << 1 << OrderedLoopCountExpr->getSourceRange(); 3588 } 3589 return true; 3590 } 3591 assert(For->getBody()); 3592 3593 OpenMPIterationSpaceChecker ISC(SemaRef, For->getForLoc()); 3594 3595 // Check init. 3596 auto Init = For->getInit(); 3597 if (ISC.CheckInit(Init)) 3598 return true; 3599 3600 bool HasErrors = false; 3601 3602 // Check loop variable's type. 3603 if (auto *LCDecl = ISC.GetLoopDecl()) { 3604 auto *LoopDeclRefExpr = ISC.GetLoopDeclRefExpr(); 3605 3606 // OpenMP [2.6, Canonical Loop Form] 3607 // Var is one of the following: 3608 // A variable of signed or unsigned integer type. 3609 // For C++, a variable of a random access iterator type. 3610 // For C, a variable of a pointer type. 3611 auto VarType = LCDecl->getType().getNonReferenceType(); 3612 if (!VarType->isDependentType() && !VarType->isIntegerType() && 3613 !VarType->isPointerType() && 3614 !(SemaRef.getLangOpts().CPlusPlus && VarType->isOverloadableType())) { 3615 SemaRef.Diag(Init->getLocStart(), diag::err_omp_loop_variable_type) 3616 << SemaRef.getLangOpts().CPlusPlus; 3617 HasErrors = true; 3618 } 3619 3620 // OpenMP, 2.14.1.1 Data-sharing Attribute Rules for Variables Referenced in 3621 // a Construct 3622 // The loop iteration variable(s) in the associated for-loop(s) of a for or 3623 // parallel for construct is (are) private. 3624 // The loop iteration variable in the associated for-loop of a simd 3625 // construct with just one associated for-loop is linear with a 3626 // constant-linear-step that is the increment of the associated for-loop. 3627 // Exclude loop var from the list of variables with implicitly defined data 3628 // sharing attributes. 3629 VarsWithImplicitDSA.erase(LCDecl); 3630 3631 // OpenMP [2.14.1.1, Data-sharing Attribute Rules for Variables Referenced 3632 // in a Construct, C/C++]. 3633 // The loop iteration variable in the associated for-loop of a simd 3634 // construct with just one associated for-loop may be listed in a linear 3635 // clause with a constant-linear-step that is the increment of the 3636 // associated for-loop. 3637 // The loop iteration variable(s) in the associated for-loop(s) of a for or 3638 // parallel for construct may be listed in a private or lastprivate clause. 3639 DSAStackTy::DSAVarData DVar = DSA.getTopDSA(LCDecl, false); 3640 // If LoopVarRefExpr is nullptr it means the corresponding loop variable is 3641 // declared in the loop and it is predetermined as a private. 3642 auto PredeterminedCKind = 3643 isOpenMPSimdDirective(DKind) 3644 ? ((NestedLoopCount == 1) ? OMPC_linear : OMPC_lastprivate) 3645 : OMPC_private; 3646 if (((isOpenMPSimdDirective(DKind) && DVar.CKind != OMPC_unknown && 3647 DVar.CKind != PredeterminedCKind) || 3648 ((isOpenMPWorksharingDirective(DKind) || DKind == OMPD_taskloop || 3649 isOpenMPDistributeDirective(DKind)) && 3650 !isOpenMPSimdDirective(DKind) && DVar.CKind != OMPC_unknown && 3651 DVar.CKind != OMPC_private && DVar.CKind != OMPC_lastprivate)) && 3652 (DVar.CKind != OMPC_private || DVar.RefExpr != nullptr)) { 3653 SemaRef.Diag(Init->getLocStart(), diag::err_omp_loop_var_dsa) 3654 << getOpenMPClauseName(DVar.CKind) << getOpenMPDirectiveName(DKind) 3655 << getOpenMPClauseName(PredeterminedCKind); 3656 if (DVar.RefExpr == nullptr) 3657 DVar.CKind = PredeterminedCKind; 3658 ReportOriginalDSA(SemaRef, &DSA, LCDecl, DVar, /*IsLoopIterVar=*/true); 3659 HasErrors = true; 3660 } else if (LoopDeclRefExpr != nullptr) { 3661 // Make the loop iteration variable private (for worksharing constructs), 3662 // linear (for simd directives with the only one associated loop) or 3663 // lastprivate (for simd directives with several collapsed or ordered 3664 // loops). 3665 if (DVar.CKind == OMPC_unknown) 3666 DVar = DSA.hasDSA(LCDecl, isOpenMPPrivate, 3667 [](OpenMPDirectiveKind) -> bool { return true; }, 3668 /*FromParent=*/false); 3669 DSA.addDSA(LCDecl, LoopDeclRefExpr, PredeterminedCKind); 3670 } 3671 3672 assert(isOpenMPLoopDirective(DKind) && "DSA for non-loop vars"); 3673 3674 // Check test-expr. 3675 HasErrors |= ISC.CheckCond(For->getCond()); 3676 3677 // Check incr-expr. 3678 HasErrors |= ISC.CheckInc(For->getInc()); 3679 } 3680 3681 if (ISC.Dependent() || SemaRef.CurContext->isDependentContext() || HasErrors) 3682 return HasErrors; 3683 3684 // Build the loop's iteration space representation. 3685 ResultIterSpace.PreCond = 3686 ISC.BuildPreCond(DSA.getCurScope(), For->getCond(), Captures); 3687 ResultIterSpace.NumIterations = ISC.BuildNumIterations( 3688 DSA.getCurScope(), 3689 (isOpenMPWorksharingDirective(DKind) || 3690 isOpenMPTaskLoopDirective(DKind) || isOpenMPDistributeDirective(DKind)), 3691 Captures); 3692 ResultIterSpace.CounterVar = ISC.BuildCounterVar(Captures, DSA); 3693 ResultIterSpace.PrivateCounterVar = ISC.BuildPrivateCounterVar(); 3694 ResultIterSpace.CounterInit = ISC.BuildCounterInit(); 3695 ResultIterSpace.CounterStep = ISC.BuildCounterStep(); 3696 ResultIterSpace.InitSrcRange = ISC.GetInitSrcRange(); 3697 ResultIterSpace.CondSrcRange = ISC.GetConditionSrcRange(); 3698 ResultIterSpace.IncSrcRange = ISC.GetIncrementSrcRange(); 3699 ResultIterSpace.Subtract = ISC.ShouldSubtractStep(); 3700 3701 HasErrors |= (ResultIterSpace.PreCond == nullptr || 3702 ResultIterSpace.NumIterations == nullptr || 3703 ResultIterSpace.CounterVar == nullptr || 3704 ResultIterSpace.PrivateCounterVar == nullptr || 3705 ResultIterSpace.CounterInit == nullptr || 3706 ResultIterSpace.CounterStep == nullptr); 3707 3708 return HasErrors; 3709 } 3710 3711 /// \brief Build 'VarRef = Start. 3712 static ExprResult 3713 BuildCounterInit(Sema &SemaRef, Scope *S, SourceLocation Loc, ExprResult VarRef, 3714 ExprResult Start, 3715 llvm::MapVector<Expr *, DeclRefExpr *> &Captures) { 3716 // Build 'VarRef = Start. 3717 auto NewStart = tryBuildCapture(SemaRef, Start.get(), Captures); 3718 if (!NewStart.isUsable()) 3719 return ExprError(); 3720 if (!SemaRef.Context.hasSameType(NewStart.get()->getType(), 3721 VarRef.get()->getType())) { 3722 NewStart = SemaRef.PerformImplicitConversion( 3723 NewStart.get(), VarRef.get()->getType(), Sema::AA_Converting, 3724 /*AllowExplicit=*/true); 3725 if (!NewStart.isUsable()) 3726 return ExprError(); 3727 } 3728 3729 auto Init = 3730 SemaRef.BuildBinOp(S, Loc, BO_Assign, VarRef.get(), NewStart.get()); 3731 return Init; 3732 } 3733 3734 /// \brief Build 'VarRef = Start + Iter * Step'. 3735 static ExprResult 3736 BuildCounterUpdate(Sema &SemaRef, Scope *S, SourceLocation Loc, 3737 ExprResult VarRef, ExprResult Start, ExprResult Iter, 3738 ExprResult Step, bool Subtract, 3739 llvm::MapVector<Expr *, DeclRefExpr *> *Captures = nullptr) { 3740 // Add parentheses (for debugging purposes only). 3741 Iter = SemaRef.ActOnParenExpr(Loc, Loc, Iter.get()); 3742 if (!VarRef.isUsable() || !Start.isUsable() || !Iter.isUsable() || 3743 !Step.isUsable()) 3744 return ExprError(); 3745 3746 ExprResult NewStep = Step; 3747 if (Captures) 3748 NewStep = tryBuildCapture(SemaRef, Step.get(), *Captures); 3749 if (NewStep.isInvalid()) 3750 return ExprError(); 3751 ExprResult Update = 3752 SemaRef.BuildBinOp(S, Loc, BO_Mul, Iter.get(), NewStep.get()); 3753 if (!Update.isUsable()) 3754 return ExprError(); 3755 3756 // Try to build 'VarRef = Start, VarRef (+|-)= Iter * Step' or 3757 // 'VarRef = Start (+|-) Iter * Step'. 3758 ExprResult NewStart = Start; 3759 if (Captures) 3760 NewStart = tryBuildCapture(SemaRef, Start.get(), *Captures); 3761 if (NewStart.isInvalid()) 3762 return ExprError(); 3763 3764 // First attempt: try to build 'VarRef = Start, VarRef += Iter * Step'. 3765 ExprResult SavedUpdate = Update; 3766 ExprResult UpdateVal; 3767 if (VarRef.get()->getType()->isOverloadableType() || 3768 NewStart.get()->getType()->isOverloadableType() || 3769 Update.get()->getType()->isOverloadableType()) { 3770 bool Suppress = SemaRef.getDiagnostics().getSuppressAllDiagnostics(); 3771 SemaRef.getDiagnostics().setSuppressAllDiagnostics(/*Val=*/true); 3772 Update = 3773 SemaRef.BuildBinOp(S, Loc, BO_Assign, VarRef.get(), NewStart.get()); 3774 if (Update.isUsable()) { 3775 UpdateVal = 3776 SemaRef.BuildBinOp(S, Loc, Subtract ? BO_SubAssign : BO_AddAssign, 3777 VarRef.get(), SavedUpdate.get()); 3778 if (UpdateVal.isUsable()) { 3779 Update = SemaRef.CreateBuiltinBinOp(Loc, BO_Comma, Update.get(), 3780 UpdateVal.get()); 3781 } 3782 } 3783 SemaRef.getDiagnostics().setSuppressAllDiagnostics(Suppress); 3784 } 3785 3786 // Second attempt: try to build 'VarRef = Start (+|-) Iter * Step'. 3787 if (!Update.isUsable() || !UpdateVal.isUsable()) { 3788 Update = SemaRef.BuildBinOp(S, Loc, Subtract ? BO_Sub : BO_Add, 3789 NewStart.get(), SavedUpdate.get()); 3790 if (!Update.isUsable()) 3791 return ExprError(); 3792 3793 if (!SemaRef.Context.hasSameType(Update.get()->getType(), 3794 VarRef.get()->getType())) { 3795 Update = SemaRef.PerformImplicitConversion( 3796 Update.get(), VarRef.get()->getType(), Sema::AA_Converting, true); 3797 if (!Update.isUsable()) 3798 return ExprError(); 3799 } 3800 3801 Update = SemaRef.BuildBinOp(S, Loc, BO_Assign, VarRef.get(), Update.get()); 3802 } 3803 return Update; 3804 } 3805 3806 /// \brief Convert integer expression \a E to make it have at least \a Bits 3807 /// bits. 3808 static ExprResult WidenIterationCount(unsigned Bits, Expr *E, Sema &SemaRef) { 3809 if (E == nullptr) 3810 return ExprError(); 3811 auto &C = SemaRef.Context; 3812 QualType OldType = E->getType(); 3813 unsigned HasBits = C.getTypeSize(OldType); 3814 if (HasBits >= Bits) 3815 return ExprResult(E); 3816 // OK to convert to signed, because new type has more bits than old. 3817 QualType NewType = C.getIntTypeForBitwidth(Bits, /* Signed */ true); 3818 return SemaRef.PerformImplicitConversion(E, NewType, Sema::AA_Converting, 3819 true); 3820 } 3821 3822 /// \brief Check if the given expression \a E is a constant integer that fits 3823 /// into \a Bits bits. 3824 static bool FitsInto(unsigned Bits, bool Signed, Expr *E, Sema &SemaRef) { 3825 if (E == nullptr) 3826 return false; 3827 llvm::APSInt Result; 3828 if (E->isIntegerConstantExpr(Result, SemaRef.Context)) 3829 return Signed ? Result.isSignedIntN(Bits) : Result.isIntN(Bits); 3830 return false; 3831 } 3832 3833 /// Build preinits statement for the given declarations. 3834 static Stmt *buildPreInits(ASTContext &Context, 3835 SmallVectorImpl<Decl *> &PreInits) { 3836 if (!PreInits.empty()) { 3837 return new (Context) DeclStmt( 3838 DeclGroupRef::Create(Context, PreInits.begin(), PreInits.size()), 3839 SourceLocation(), SourceLocation()); 3840 } 3841 return nullptr; 3842 } 3843 3844 /// Build preinits statement for the given declarations. 3845 static Stmt *buildPreInits(ASTContext &Context, 3846 llvm::MapVector<Expr *, DeclRefExpr *> &Captures) { 3847 if (!Captures.empty()) { 3848 SmallVector<Decl *, 16> PreInits; 3849 for (auto &Pair : Captures) 3850 PreInits.push_back(Pair.second->getDecl()); 3851 return buildPreInits(Context, PreInits); 3852 } 3853 return nullptr; 3854 } 3855 3856 /// Build postupdate expression for the given list of postupdates expressions. 3857 static Expr *buildPostUpdate(Sema &S, ArrayRef<Expr *> PostUpdates) { 3858 Expr *PostUpdate = nullptr; 3859 if (!PostUpdates.empty()) { 3860 for (auto *E : PostUpdates) { 3861 Expr *ConvE = S.BuildCStyleCastExpr( 3862 E->getExprLoc(), 3863 S.Context.getTrivialTypeSourceInfo(S.Context.VoidTy), 3864 E->getExprLoc(), E) 3865 .get(); 3866 PostUpdate = PostUpdate 3867 ? S.CreateBuiltinBinOp(ConvE->getExprLoc(), BO_Comma, 3868 PostUpdate, ConvE) 3869 .get() 3870 : ConvE; 3871 } 3872 } 3873 return PostUpdate; 3874 } 3875 3876 /// \brief Called on a for stmt to check itself and nested loops (if any). 3877 /// \return Returns 0 if one of the collapsed stmts is not canonical for loop, 3878 /// number of collapsed loops otherwise. 3879 static unsigned 3880 CheckOpenMPLoop(OpenMPDirectiveKind DKind, Expr *CollapseLoopCountExpr, 3881 Expr *OrderedLoopCountExpr, Stmt *AStmt, Sema &SemaRef, 3882 DSAStackTy &DSA, 3883 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA, 3884 OMPLoopDirective::HelperExprs &Built) { 3885 unsigned NestedLoopCount = 1; 3886 if (CollapseLoopCountExpr) { 3887 // Found 'collapse' clause - calculate collapse number. 3888 llvm::APSInt Result; 3889 if (CollapseLoopCountExpr->EvaluateAsInt(Result, SemaRef.getASTContext())) 3890 NestedLoopCount = Result.getLimitedValue(); 3891 } 3892 if (OrderedLoopCountExpr) { 3893 // Found 'ordered' clause - calculate collapse number. 3894 llvm::APSInt Result; 3895 if (OrderedLoopCountExpr->EvaluateAsInt(Result, SemaRef.getASTContext())) { 3896 if (Result.getLimitedValue() < NestedLoopCount) { 3897 SemaRef.Diag(OrderedLoopCountExpr->getExprLoc(), 3898 diag::err_omp_wrong_ordered_loop_count) 3899 << OrderedLoopCountExpr->getSourceRange(); 3900 SemaRef.Diag(CollapseLoopCountExpr->getExprLoc(), 3901 diag::note_collapse_loop_count) 3902 << CollapseLoopCountExpr->getSourceRange(); 3903 } 3904 NestedLoopCount = Result.getLimitedValue(); 3905 } 3906 } 3907 // This is helper routine for loop directives (e.g., 'for', 'simd', 3908 // 'for simd', etc.). 3909 llvm::MapVector<Expr *, DeclRefExpr *> Captures; 3910 SmallVector<LoopIterationSpace, 4> IterSpaces; 3911 IterSpaces.resize(NestedLoopCount); 3912 Stmt *CurStmt = AStmt->IgnoreContainers(/* IgnoreCaptured */ true); 3913 for (unsigned Cnt = 0; Cnt < NestedLoopCount; ++Cnt) { 3914 if (CheckOpenMPIterationSpace(DKind, CurStmt, SemaRef, DSA, Cnt, 3915 NestedLoopCount, CollapseLoopCountExpr, 3916 OrderedLoopCountExpr, VarsWithImplicitDSA, 3917 IterSpaces[Cnt], Captures)) 3918 return 0; 3919 // Move on to the next nested for loop, or to the loop body. 3920 // OpenMP [2.8.1, simd construct, Restrictions] 3921 // All loops associated with the construct must be perfectly nested; that 3922 // is, there must be no intervening code nor any OpenMP directive between 3923 // any two loops. 3924 CurStmt = cast<ForStmt>(CurStmt)->getBody()->IgnoreContainers(); 3925 } 3926 3927 Built.clear(/* size */ NestedLoopCount); 3928 3929 if (SemaRef.CurContext->isDependentContext()) 3930 return NestedLoopCount; 3931 3932 // An example of what is generated for the following code: 3933 // 3934 // #pragma omp simd collapse(2) ordered(2) 3935 // for (i = 0; i < NI; ++i) 3936 // for (k = 0; k < NK; ++k) 3937 // for (j = J0; j < NJ; j+=2) { 3938 // <loop body> 3939 // } 3940 // 3941 // We generate the code below. 3942 // Note: the loop body may be outlined in CodeGen. 3943 // Note: some counters may be C++ classes, operator- is used to find number of 3944 // iterations and operator+= to calculate counter value. 3945 // Note: decltype(NumIterations) must be integer type (in 'omp for', only i32 3946 // or i64 is currently supported). 3947 // 3948 // #define NumIterations (NI * ((NJ - J0 - 1 + 2) / 2)) 3949 // for (int[32|64]_t IV = 0; IV < NumIterations; ++IV ) { 3950 // .local.i = IV / ((NJ - J0 - 1 + 2) / 2); 3951 // .local.j = J0 + (IV % ((NJ - J0 - 1 + 2) / 2)) * 2; 3952 // // similar updates for vars in clauses (e.g. 'linear') 3953 // <loop body (using local i and j)> 3954 // } 3955 // i = NI; // assign final values of counters 3956 // j = NJ; 3957 // 3958 3959 // Last iteration number is (I1 * I2 * ... In) - 1, where I1, I2 ... In are 3960 // the iteration counts of the collapsed for loops. 3961 // Precondition tests if there is at least one iteration (all conditions are 3962 // true). 3963 auto PreCond = ExprResult(IterSpaces[0].PreCond); 3964 auto N0 = IterSpaces[0].NumIterations; 3965 ExprResult LastIteration32 = WidenIterationCount( 3966 32 /* Bits */, SemaRef 3967 .PerformImplicitConversion( 3968 N0->IgnoreImpCasts(), N0->getType(), 3969 Sema::AA_Converting, /*AllowExplicit=*/true) 3970 .get(), 3971 SemaRef); 3972 ExprResult LastIteration64 = WidenIterationCount( 3973 64 /* Bits */, SemaRef 3974 .PerformImplicitConversion( 3975 N0->IgnoreImpCasts(), N0->getType(), 3976 Sema::AA_Converting, /*AllowExplicit=*/true) 3977 .get(), 3978 SemaRef); 3979 3980 if (!LastIteration32.isUsable() || !LastIteration64.isUsable()) 3981 return NestedLoopCount; 3982 3983 auto &C = SemaRef.Context; 3984 bool AllCountsNeedLessThan32Bits = C.getTypeSize(N0->getType()) < 32; 3985 3986 Scope *CurScope = DSA.getCurScope(); 3987 for (unsigned Cnt = 1; Cnt < NestedLoopCount; ++Cnt) { 3988 if (PreCond.isUsable()) { 3989 PreCond = 3990 SemaRef.BuildBinOp(CurScope, PreCond.get()->getExprLoc(), BO_LAnd, 3991 PreCond.get(), IterSpaces[Cnt].PreCond); 3992 } 3993 auto N = IterSpaces[Cnt].NumIterations; 3994 SourceLocation Loc = N->getExprLoc(); 3995 AllCountsNeedLessThan32Bits &= C.getTypeSize(N->getType()) < 32; 3996 if (LastIteration32.isUsable()) 3997 LastIteration32 = SemaRef.BuildBinOp( 3998 CurScope, Loc, BO_Mul, LastIteration32.get(), 3999 SemaRef 4000 .PerformImplicitConversion(N->IgnoreImpCasts(), N->getType(), 4001 Sema::AA_Converting, 4002 /*AllowExplicit=*/true) 4003 .get()); 4004 if (LastIteration64.isUsable()) 4005 LastIteration64 = SemaRef.BuildBinOp( 4006 CurScope, Loc, BO_Mul, LastIteration64.get(), 4007 SemaRef 4008 .PerformImplicitConversion(N->IgnoreImpCasts(), N->getType(), 4009 Sema::AA_Converting, 4010 /*AllowExplicit=*/true) 4011 .get()); 4012 } 4013 4014 // Choose either the 32-bit or 64-bit version. 4015 ExprResult LastIteration = LastIteration64; 4016 if (LastIteration32.isUsable() && 4017 C.getTypeSize(LastIteration32.get()->getType()) == 32 && 4018 (AllCountsNeedLessThan32Bits || NestedLoopCount == 1 || 4019 FitsInto( 4020 32 /* Bits */, 4021 LastIteration32.get()->getType()->hasSignedIntegerRepresentation(), 4022 LastIteration64.get(), SemaRef))) 4023 LastIteration = LastIteration32; 4024 QualType VType = LastIteration.get()->getType(); 4025 QualType RealVType = VType; 4026 QualType StrideVType = VType; 4027 if (isOpenMPTaskLoopDirective(DKind)) { 4028 VType = 4029 SemaRef.Context.getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/0); 4030 StrideVType = 4031 SemaRef.Context.getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/1); 4032 } 4033 4034 if (!LastIteration.isUsable()) 4035 return 0; 4036 4037 // Save the number of iterations. 4038 ExprResult NumIterations = LastIteration; 4039 { 4040 LastIteration = SemaRef.BuildBinOp( 4041 CurScope, LastIteration.get()->getExprLoc(), BO_Sub, 4042 LastIteration.get(), 4043 SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get()); 4044 if (!LastIteration.isUsable()) 4045 return 0; 4046 } 4047 4048 // Calculate the last iteration number beforehand instead of doing this on 4049 // each iteration. Do not do this if the number of iterations may be kfold-ed. 4050 llvm::APSInt Result; 4051 bool IsConstant = 4052 LastIteration.get()->isIntegerConstantExpr(Result, SemaRef.Context); 4053 ExprResult CalcLastIteration; 4054 if (!IsConstant) { 4055 ExprResult SaveRef = 4056 tryBuildCapture(SemaRef, LastIteration.get(), Captures); 4057 LastIteration = SaveRef; 4058 4059 // Prepare SaveRef + 1. 4060 NumIterations = SemaRef.BuildBinOp( 4061 CurScope, SaveRef.get()->getExprLoc(), BO_Add, SaveRef.get(), 4062 SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get()); 4063 if (!NumIterations.isUsable()) 4064 return 0; 4065 } 4066 4067 SourceLocation InitLoc = IterSpaces[0].InitSrcRange.getBegin(); 4068 4069 // Build variables passed into runtime, necessary for worksharing directives. 4070 ExprResult LB, UB, IL, ST, EUB, PrevLB, PrevUB; 4071 if (isOpenMPWorksharingDirective(DKind) || isOpenMPTaskLoopDirective(DKind) || 4072 isOpenMPDistributeDirective(DKind)) { 4073 // Lower bound variable, initialized with zero. 4074 VarDecl *LBDecl = buildVarDecl(SemaRef, InitLoc, VType, ".omp.lb"); 4075 LB = buildDeclRefExpr(SemaRef, LBDecl, VType, InitLoc); 4076 SemaRef.AddInitializerToDecl(LBDecl, 4077 SemaRef.ActOnIntegerConstant(InitLoc, 0).get(), 4078 /*DirectInit*/ false); 4079 4080 // Upper bound variable, initialized with last iteration number. 4081 VarDecl *UBDecl = buildVarDecl(SemaRef, InitLoc, VType, ".omp.ub"); 4082 UB = buildDeclRefExpr(SemaRef, UBDecl, VType, InitLoc); 4083 SemaRef.AddInitializerToDecl(UBDecl, LastIteration.get(), 4084 /*DirectInit*/ false); 4085 4086 // A 32-bit variable-flag where runtime returns 1 for the last iteration. 4087 // This will be used to implement clause 'lastprivate'. 4088 QualType Int32Ty = SemaRef.Context.getIntTypeForBitwidth(32, true); 4089 VarDecl *ILDecl = buildVarDecl(SemaRef, InitLoc, Int32Ty, ".omp.is_last"); 4090 IL = buildDeclRefExpr(SemaRef, ILDecl, Int32Ty, InitLoc); 4091 SemaRef.AddInitializerToDecl(ILDecl, 4092 SemaRef.ActOnIntegerConstant(InitLoc, 0).get(), 4093 /*DirectInit*/ false); 4094 4095 // Stride variable returned by runtime (we initialize it to 1 by default). 4096 VarDecl *STDecl = 4097 buildVarDecl(SemaRef, InitLoc, StrideVType, ".omp.stride"); 4098 ST = buildDeclRefExpr(SemaRef, STDecl, StrideVType, InitLoc); 4099 SemaRef.AddInitializerToDecl(STDecl, 4100 SemaRef.ActOnIntegerConstant(InitLoc, 1).get(), 4101 /*DirectInit*/ false); 4102 4103 // Build expression: UB = min(UB, LastIteration) 4104 // It is necessary for CodeGen of directives with static scheduling. 4105 ExprResult IsUBGreater = SemaRef.BuildBinOp(CurScope, InitLoc, BO_GT, 4106 UB.get(), LastIteration.get()); 4107 ExprResult CondOp = SemaRef.ActOnConditionalOp( 4108 InitLoc, InitLoc, IsUBGreater.get(), LastIteration.get(), UB.get()); 4109 EUB = SemaRef.BuildBinOp(CurScope, InitLoc, BO_Assign, UB.get(), 4110 CondOp.get()); 4111 EUB = SemaRef.ActOnFinishFullExpr(EUB.get()); 4112 4113 // If we have a combined directive that combines 'distribute', 'for' or 4114 // 'simd' we need to be able to access the bounds of the schedule of the 4115 // enclosing region. E.g. in 'distribute parallel for' the bounds obtained 4116 // by scheduling 'distribute' have to be passed to the schedule of 'for'. 4117 if (isOpenMPLoopBoundSharingDirective(DKind)) { 4118 auto *CD = cast<CapturedStmt>(AStmt)->getCapturedDecl(); 4119 4120 // We expect to have at least 2 more parameters than the 'parallel' 4121 // directive does - the lower and upper bounds of the previous schedule. 4122 assert(CD->getNumParams() >= 4 && 4123 "Unexpected number of parameters in loop combined directive"); 4124 4125 // Set the proper type for the bounds given what we learned from the 4126 // enclosed loops. 4127 auto *PrevLBDecl = CD->getParam(/*PrevLB=*/2); 4128 auto *PrevUBDecl = CD->getParam(/*PrevUB=*/3); 4129 4130 // Previous lower and upper bounds are obtained from the region 4131 // parameters. 4132 PrevLB = 4133 buildDeclRefExpr(SemaRef, PrevLBDecl, PrevLBDecl->getType(), InitLoc); 4134 PrevUB = 4135 buildDeclRefExpr(SemaRef, PrevUBDecl, PrevUBDecl->getType(), InitLoc); 4136 } 4137 } 4138 4139 // Build the iteration variable and its initialization before loop. 4140 ExprResult IV; 4141 ExprResult Init; 4142 { 4143 VarDecl *IVDecl = buildVarDecl(SemaRef, InitLoc, RealVType, ".omp.iv"); 4144 IV = buildDeclRefExpr(SemaRef, IVDecl, RealVType, InitLoc); 4145 Expr *RHS = 4146 (isOpenMPWorksharingDirective(DKind) || 4147 isOpenMPTaskLoopDirective(DKind) || isOpenMPDistributeDirective(DKind)) 4148 ? LB.get() 4149 : SemaRef.ActOnIntegerConstant(SourceLocation(), 0).get(); 4150 Init = SemaRef.BuildBinOp(CurScope, InitLoc, BO_Assign, IV.get(), RHS); 4151 Init = SemaRef.ActOnFinishFullExpr(Init.get()); 4152 } 4153 4154 // Loop condition (IV < NumIterations) or (IV <= UB) for worksharing loops. 4155 SourceLocation CondLoc; 4156 ExprResult Cond = 4157 (isOpenMPWorksharingDirective(DKind) || 4158 isOpenMPTaskLoopDirective(DKind) || isOpenMPDistributeDirective(DKind)) 4159 ? SemaRef.BuildBinOp(CurScope, CondLoc, BO_LE, IV.get(), UB.get()) 4160 : SemaRef.BuildBinOp(CurScope, CondLoc, BO_LT, IV.get(), 4161 NumIterations.get()); 4162 4163 // Loop increment (IV = IV + 1) 4164 SourceLocation IncLoc; 4165 ExprResult Inc = 4166 SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, IV.get(), 4167 SemaRef.ActOnIntegerConstant(IncLoc, 1).get()); 4168 if (!Inc.isUsable()) 4169 return 0; 4170 Inc = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, IV.get(), Inc.get()); 4171 Inc = SemaRef.ActOnFinishFullExpr(Inc.get()); 4172 if (!Inc.isUsable()) 4173 return 0; 4174 4175 // Increments for worksharing loops (LB = LB + ST; UB = UB + ST). 4176 // Used for directives with static scheduling. 4177 ExprResult NextLB, NextUB; 4178 if (isOpenMPWorksharingDirective(DKind) || isOpenMPTaskLoopDirective(DKind) || 4179 isOpenMPDistributeDirective(DKind)) { 4180 // LB + ST 4181 NextLB = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, LB.get(), ST.get()); 4182 if (!NextLB.isUsable()) 4183 return 0; 4184 // LB = LB + ST 4185 NextLB = 4186 SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, LB.get(), NextLB.get()); 4187 NextLB = SemaRef.ActOnFinishFullExpr(NextLB.get()); 4188 if (!NextLB.isUsable()) 4189 return 0; 4190 // UB + ST 4191 NextUB = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, UB.get(), ST.get()); 4192 if (!NextUB.isUsable()) 4193 return 0; 4194 // UB = UB + ST 4195 NextUB = 4196 SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, UB.get(), NextUB.get()); 4197 NextUB = SemaRef.ActOnFinishFullExpr(NextUB.get()); 4198 if (!NextUB.isUsable()) 4199 return 0; 4200 } 4201 4202 // Create: increment expression for distribute loop when combined in a same 4203 // directive with for as IV = IV + ST; ensure upper bound expression based 4204 // on PrevUB instead of NumIterations - used to implement 'for' when found 4205 // in combination with 'distribute', like in 'distribute parallel for' 4206 SourceLocation DistIncLoc; 4207 ExprResult DistCond, DistInc, PrevEUB; 4208 if (isOpenMPLoopBoundSharingDirective(DKind)) { 4209 DistCond = SemaRef.BuildBinOp(CurScope, CondLoc, BO_LE, IV.get(), UB.get()); 4210 assert(DistCond.isUsable() && "distribute cond expr was not built"); 4211 4212 DistInc = 4213 SemaRef.BuildBinOp(CurScope, DistIncLoc, BO_Add, IV.get(), ST.get()); 4214 assert(DistInc.isUsable() && "distribute inc expr was not built"); 4215 DistInc = SemaRef.BuildBinOp(CurScope, DistIncLoc, BO_Assign, IV.get(), 4216 DistInc.get()); 4217 DistInc = SemaRef.ActOnFinishFullExpr(DistInc.get()); 4218 assert(DistInc.isUsable() && "distribute inc expr was not built"); 4219 4220 // Build expression: UB = min(UB, prevUB) for #for in composite or combined 4221 // construct 4222 SourceLocation DistEUBLoc; 4223 ExprResult IsUBGreater = 4224 SemaRef.BuildBinOp(CurScope, DistEUBLoc, BO_GT, UB.get(), PrevUB.get()); 4225 ExprResult CondOp = SemaRef.ActOnConditionalOp( 4226 DistEUBLoc, DistEUBLoc, IsUBGreater.get(), PrevUB.get(), UB.get()); 4227 PrevEUB = SemaRef.BuildBinOp(CurScope, DistIncLoc, BO_Assign, UB.get(), 4228 CondOp.get()); 4229 PrevEUB = SemaRef.ActOnFinishFullExpr(PrevEUB.get()); 4230 } 4231 4232 // Build updates and final values of the loop counters. 4233 bool HasErrors = false; 4234 Built.Counters.resize(NestedLoopCount); 4235 Built.Inits.resize(NestedLoopCount); 4236 Built.Updates.resize(NestedLoopCount); 4237 Built.Finals.resize(NestedLoopCount); 4238 SmallVector<Expr *, 4> LoopMultipliers; 4239 { 4240 ExprResult Div; 4241 // Go from inner nested loop to outer. 4242 for (int Cnt = NestedLoopCount - 1; Cnt >= 0; --Cnt) { 4243 LoopIterationSpace &IS = IterSpaces[Cnt]; 4244 SourceLocation UpdLoc = IS.IncSrcRange.getBegin(); 4245 // Build: Iter = (IV / Div) % IS.NumIters 4246 // where Div is product of previous iterations' IS.NumIters. 4247 ExprResult Iter; 4248 if (Div.isUsable()) { 4249 Iter = 4250 SemaRef.BuildBinOp(CurScope, UpdLoc, BO_Div, IV.get(), Div.get()); 4251 } else { 4252 Iter = IV; 4253 assert((Cnt == (int)NestedLoopCount - 1) && 4254 "unusable div expected on first iteration only"); 4255 } 4256 4257 if (Cnt != 0 && Iter.isUsable()) 4258 Iter = SemaRef.BuildBinOp(CurScope, UpdLoc, BO_Rem, Iter.get(), 4259 IS.NumIterations); 4260 if (!Iter.isUsable()) { 4261 HasErrors = true; 4262 break; 4263 } 4264 4265 // Build update: IS.CounterVar(Private) = IS.Start + Iter * IS.Step 4266 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(IS.CounterVar)->getDecl()); 4267 auto *CounterVar = buildDeclRefExpr(SemaRef, VD, IS.CounterVar->getType(), 4268 IS.CounterVar->getExprLoc(), 4269 /*RefersToCapture=*/true); 4270 ExprResult Init = BuildCounterInit(SemaRef, CurScope, UpdLoc, CounterVar, 4271 IS.CounterInit, Captures); 4272 if (!Init.isUsable()) { 4273 HasErrors = true; 4274 break; 4275 } 4276 ExprResult Update = BuildCounterUpdate( 4277 SemaRef, CurScope, UpdLoc, CounterVar, IS.CounterInit, Iter, 4278 IS.CounterStep, IS.Subtract, &Captures); 4279 if (!Update.isUsable()) { 4280 HasErrors = true; 4281 break; 4282 } 4283 4284 // Build final: IS.CounterVar = IS.Start + IS.NumIters * IS.Step 4285 ExprResult Final = BuildCounterUpdate( 4286 SemaRef, CurScope, UpdLoc, CounterVar, IS.CounterInit, 4287 IS.NumIterations, IS.CounterStep, IS.Subtract, &Captures); 4288 if (!Final.isUsable()) { 4289 HasErrors = true; 4290 break; 4291 } 4292 4293 // Build Div for the next iteration: Div <- Div * IS.NumIters 4294 if (Cnt != 0) { 4295 if (Div.isUnset()) 4296 Div = IS.NumIterations; 4297 else 4298 Div = SemaRef.BuildBinOp(CurScope, UpdLoc, BO_Mul, Div.get(), 4299 IS.NumIterations); 4300 4301 // Add parentheses (for debugging purposes only). 4302 if (Div.isUsable()) 4303 Div = tryBuildCapture(SemaRef, Div.get(), Captures); 4304 if (!Div.isUsable()) { 4305 HasErrors = true; 4306 break; 4307 } 4308 LoopMultipliers.push_back(Div.get()); 4309 } 4310 if (!Update.isUsable() || !Final.isUsable()) { 4311 HasErrors = true; 4312 break; 4313 } 4314 // Save results 4315 Built.Counters[Cnt] = IS.CounterVar; 4316 Built.PrivateCounters[Cnt] = IS.PrivateCounterVar; 4317 Built.Inits[Cnt] = Init.get(); 4318 Built.Updates[Cnt] = Update.get(); 4319 Built.Finals[Cnt] = Final.get(); 4320 } 4321 } 4322 4323 if (HasErrors) 4324 return 0; 4325 4326 // Save results 4327 Built.IterationVarRef = IV.get(); 4328 Built.LastIteration = LastIteration.get(); 4329 Built.NumIterations = NumIterations.get(); 4330 Built.CalcLastIteration = 4331 SemaRef.ActOnFinishFullExpr(CalcLastIteration.get()).get(); 4332 Built.PreCond = PreCond.get(); 4333 Built.PreInits = buildPreInits(C, Captures); 4334 Built.Cond = Cond.get(); 4335 Built.Init = Init.get(); 4336 Built.Inc = Inc.get(); 4337 Built.LB = LB.get(); 4338 Built.UB = UB.get(); 4339 Built.IL = IL.get(); 4340 Built.ST = ST.get(); 4341 Built.EUB = EUB.get(); 4342 Built.NLB = NextLB.get(); 4343 Built.NUB = NextUB.get(); 4344 Built.PrevLB = PrevLB.get(); 4345 Built.PrevUB = PrevUB.get(); 4346 Built.DistInc = DistInc.get(); 4347 Built.PrevEUB = PrevEUB.get(); 4348 4349 Expr *CounterVal = SemaRef.DefaultLvalueConversion(IV.get()).get(); 4350 // Fill data for doacross depend clauses. 4351 for (auto Pair : DSA.getDoacrossDependClauses()) { 4352 if (Pair.first->getDependencyKind() == OMPC_DEPEND_source) 4353 Pair.first->setCounterValue(CounterVal); 4354 else { 4355 if (NestedLoopCount != Pair.second.size() || 4356 NestedLoopCount != LoopMultipliers.size() + 1) { 4357 // Erroneous case - clause has some problems. 4358 Pair.first->setCounterValue(CounterVal); 4359 continue; 4360 } 4361 assert(Pair.first->getDependencyKind() == OMPC_DEPEND_sink); 4362 auto I = Pair.second.rbegin(); 4363 auto IS = IterSpaces.rbegin(); 4364 auto ILM = LoopMultipliers.rbegin(); 4365 Expr *UpCounterVal = CounterVal; 4366 Expr *Multiplier = nullptr; 4367 for (int Cnt = NestedLoopCount - 1; Cnt >= 0; --Cnt) { 4368 if (I->first) { 4369 assert(IS->CounterStep); 4370 Expr *NormalizedOffset = 4371 SemaRef 4372 .BuildBinOp(CurScope, I->first->getExprLoc(), BO_Div, 4373 I->first, IS->CounterStep) 4374 .get(); 4375 if (Multiplier) { 4376 NormalizedOffset = 4377 SemaRef 4378 .BuildBinOp(CurScope, I->first->getExprLoc(), BO_Mul, 4379 NormalizedOffset, Multiplier) 4380 .get(); 4381 } 4382 assert(I->second == OO_Plus || I->second == OO_Minus); 4383 BinaryOperatorKind BOK = (I->second == OO_Plus) ? BO_Add : BO_Sub; 4384 UpCounterVal = SemaRef 4385 .BuildBinOp(CurScope, I->first->getExprLoc(), BOK, 4386 UpCounterVal, NormalizedOffset) 4387 .get(); 4388 } 4389 Multiplier = *ILM; 4390 ++I; 4391 ++IS; 4392 ++ILM; 4393 } 4394 Pair.first->setCounterValue(UpCounterVal); 4395 } 4396 } 4397 4398 return NestedLoopCount; 4399 } 4400 4401 static Expr *getCollapseNumberExpr(ArrayRef<OMPClause *> Clauses) { 4402 auto CollapseClauses = 4403 OMPExecutableDirective::getClausesOfKind<OMPCollapseClause>(Clauses); 4404 if (CollapseClauses.begin() != CollapseClauses.end()) 4405 return (*CollapseClauses.begin())->getNumForLoops(); 4406 return nullptr; 4407 } 4408 4409 static Expr *getOrderedNumberExpr(ArrayRef<OMPClause *> Clauses) { 4410 auto OrderedClauses = 4411 OMPExecutableDirective::getClausesOfKind<OMPOrderedClause>(Clauses); 4412 if (OrderedClauses.begin() != OrderedClauses.end()) 4413 return (*OrderedClauses.begin())->getNumForLoops(); 4414 return nullptr; 4415 } 4416 4417 static bool checkSimdlenSafelenSpecified(Sema &S, 4418 const ArrayRef<OMPClause *> Clauses) { 4419 OMPSafelenClause *Safelen = nullptr; 4420 OMPSimdlenClause *Simdlen = nullptr; 4421 4422 for (auto *Clause : Clauses) { 4423 if (Clause->getClauseKind() == OMPC_safelen) 4424 Safelen = cast<OMPSafelenClause>(Clause); 4425 else if (Clause->getClauseKind() == OMPC_simdlen) 4426 Simdlen = cast<OMPSimdlenClause>(Clause); 4427 if (Safelen && Simdlen) 4428 break; 4429 } 4430 4431 if (Simdlen && Safelen) { 4432 llvm::APSInt SimdlenRes, SafelenRes; 4433 auto SimdlenLength = Simdlen->getSimdlen(); 4434 auto SafelenLength = Safelen->getSafelen(); 4435 if (SimdlenLength->isValueDependent() || SimdlenLength->isTypeDependent() || 4436 SimdlenLength->isInstantiationDependent() || 4437 SimdlenLength->containsUnexpandedParameterPack()) 4438 return false; 4439 if (SafelenLength->isValueDependent() || SafelenLength->isTypeDependent() || 4440 SafelenLength->isInstantiationDependent() || 4441 SafelenLength->containsUnexpandedParameterPack()) 4442 return false; 4443 SimdlenLength->EvaluateAsInt(SimdlenRes, S.Context); 4444 SafelenLength->EvaluateAsInt(SafelenRes, S.Context); 4445 // OpenMP 4.5 [2.8.1, simd Construct, Restrictions] 4446 // If both simdlen and safelen clauses are specified, the value of the 4447 // simdlen parameter must be less than or equal to the value of the safelen 4448 // parameter. 4449 if (SimdlenRes > SafelenRes) { 4450 S.Diag(SimdlenLength->getExprLoc(), 4451 diag::err_omp_wrong_simdlen_safelen_values) 4452 << SimdlenLength->getSourceRange() << SafelenLength->getSourceRange(); 4453 return true; 4454 } 4455 } 4456 return false; 4457 } 4458 4459 StmtResult Sema::ActOnOpenMPSimdDirective( 4460 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, 4461 SourceLocation EndLoc, 4462 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) { 4463 if (!AStmt) 4464 return StmtError(); 4465 4466 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected"); 4467 OMPLoopDirective::HelperExprs B; 4468 // In presence of clause 'collapse' or 'ordered' with number of loops, it will 4469 // define the nested loops number. 4470 unsigned NestedLoopCount = CheckOpenMPLoop( 4471 OMPD_simd, getCollapseNumberExpr(Clauses), getOrderedNumberExpr(Clauses), 4472 AStmt, *this, *DSAStack, VarsWithImplicitDSA, B); 4473 if (NestedLoopCount == 0) 4474 return StmtError(); 4475 4476 assert((CurContext->isDependentContext() || B.builtAll()) && 4477 "omp simd loop exprs were not built"); 4478 4479 if (!CurContext->isDependentContext()) { 4480 // Finalize the clauses that need pre-built expressions for CodeGen. 4481 for (auto C : Clauses) { 4482 if (auto *LC = dyn_cast<OMPLinearClause>(C)) 4483 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef), 4484 B.NumIterations, *this, CurScope, 4485 DSAStack)) 4486 return StmtError(); 4487 } 4488 } 4489 4490 if (checkSimdlenSafelenSpecified(*this, Clauses)) 4491 return StmtError(); 4492 4493 getCurFunction()->setHasBranchProtectedScope(); 4494 return OMPSimdDirective::Create(Context, StartLoc, EndLoc, NestedLoopCount, 4495 Clauses, AStmt, B); 4496 } 4497 4498 StmtResult Sema::ActOnOpenMPForDirective( 4499 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, 4500 SourceLocation EndLoc, 4501 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) { 4502 if (!AStmt) 4503 return StmtError(); 4504 4505 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected"); 4506 OMPLoopDirective::HelperExprs B; 4507 // In presence of clause 'collapse' or 'ordered' with number of loops, it will 4508 // define the nested loops number. 4509 unsigned NestedLoopCount = CheckOpenMPLoop( 4510 OMPD_for, getCollapseNumberExpr(Clauses), getOrderedNumberExpr(Clauses), 4511 AStmt, *this, *DSAStack, VarsWithImplicitDSA, B); 4512 if (NestedLoopCount == 0) 4513 return StmtError(); 4514 4515 assert((CurContext->isDependentContext() || B.builtAll()) && 4516 "omp for loop exprs were not built"); 4517 4518 if (!CurContext->isDependentContext()) { 4519 // Finalize the clauses that need pre-built expressions for CodeGen. 4520 for (auto C : Clauses) { 4521 if (auto *LC = dyn_cast<OMPLinearClause>(C)) 4522 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef), 4523 B.NumIterations, *this, CurScope, 4524 DSAStack)) 4525 return StmtError(); 4526 } 4527 } 4528 4529 getCurFunction()->setHasBranchProtectedScope(); 4530 return OMPForDirective::Create(Context, StartLoc, EndLoc, NestedLoopCount, 4531 Clauses, AStmt, B, DSAStack->isCancelRegion()); 4532 } 4533 4534 StmtResult Sema::ActOnOpenMPForSimdDirective( 4535 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, 4536 SourceLocation EndLoc, 4537 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) { 4538 if (!AStmt) 4539 return StmtError(); 4540 4541 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected"); 4542 OMPLoopDirective::HelperExprs B; 4543 // In presence of clause 'collapse' or 'ordered' with number of loops, it will 4544 // define the nested loops number. 4545 unsigned NestedLoopCount = 4546 CheckOpenMPLoop(OMPD_for_simd, getCollapseNumberExpr(Clauses), 4547 getOrderedNumberExpr(Clauses), AStmt, *this, *DSAStack, 4548 VarsWithImplicitDSA, B); 4549 if (NestedLoopCount == 0) 4550 return StmtError(); 4551 4552 assert((CurContext->isDependentContext() || B.builtAll()) && 4553 "omp for simd loop exprs were not built"); 4554 4555 if (!CurContext->isDependentContext()) { 4556 // Finalize the clauses that need pre-built expressions for CodeGen. 4557 for (auto C : Clauses) { 4558 if (auto *LC = dyn_cast<OMPLinearClause>(C)) 4559 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef), 4560 B.NumIterations, *this, CurScope, 4561 DSAStack)) 4562 return StmtError(); 4563 } 4564 } 4565 4566 if (checkSimdlenSafelenSpecified(*this, Clauses)) 4567 return StmtError(); 4568 4569 getCurFunction()->setHasBranchProtectedScope(); 4570 return OMPForSimdDirective::Create(Context, StartLoc, EndLoc, NestedLoopCount, 4571 Clauses, AStmt, B); 4572 } 4573 4574 StmtResult Sema::ActOnOpenMPSectionsDirective(ArrayRef<OMPClause *> Clauses, 4575 Stmt *AStmt, 4576 SourceLocation StartLoc, 4577 SourceLocation EndLoc) { 4578 if (!AStmt) 4579 return StmtError(); 4580 4581 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected"); 4582 auto BaseStmt = AStmt; 4583 while (auto *CS = dyn_cast_or_null<CapturedStmt>(BaseStmt)) 4584 BaseStmt = CS->getCapturedStmt(); 4585 if (auto *C = dyn_cast_or_null<CompoundStmt>(BaseStmt)) { 4586 auto S = C->children(); 4587 if (S.begin() == S.end()) 4588 return StmtError(); 4589 // All associated statements must be '#pragma omp section' except for 4590 // the first one. 4591 for (Stmt *SectionStmt : llvm::make_range(std::next(S.begin()), S.end())) { 4592 if (!SectionStmt || !isa<OMPSectionDirective>(SectionStmt)) { 4593 if (SectionStmt) 4594 Diag(SectionStmt->getLocStart(), 4595 diag::err_omp_sections_substmt_not_section); 4596 return StmtError(); 4597 } 4598 cast<OMPSectionDirective>(SectionStmt) 4599 ->setHasCancel(DSAStack->isCancelRegion()); 4600 } 4601 } else { 4602 Diag(AStmt->getLocStart(), diag::err_omp_sections_not_compound_stmt); 4603 return StmtError(); 4604 } 4605 4606 getCurFunction()->setHasBranchProtectedScope(); 4607 4608 return OMPSectionsDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt, 4609 DSAStack->isCancelRegion()); 4610 } 4611 4612 StmtResult Sema::ActOnOpenMPSectionDirective(Stmt *AStmt, 4613 SourceLocation StartLoc, 4614 SourceLocation EndLoc) { 4615 if (!AStmt) 4616 return StmtError(); 4617 4618 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected"); 4619 4620 getCurFunction()->setHasBranchProtectedScope(); 4621 DSAStack->setParentCancelRegion(DSAStack->isCancelRegion()); 4622 4623 return OMPSectionDirective::Create(Context, StartLoc, EndLoc, AStmt, 4624 DSAStack->isCancelRegion()); 4625 } 4626 4627 StmtResult Sema::ActOnOpenMPSingleDirective(ArrayRef<OMPClause *> Clauses, 4628 Stmt *AStmt, 4629 SourceLocation StartLoc, 4630 SourceLocation EndLoc) { 4631 if (!AStmt) 4632 return StmtError(); 4633 4634 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected"); 4635 4636 getCurFunction()->setHasBranchProtectedScope(); 4637 4638 // OpenMP [2.7.3, single Construct, Restrictions] 4639 // The copyprivate clause must not be used with the nowait clause. 4640 OMPClause *Nowait = nullptr; 4641 OMPClause *Copyprivate = nullptr; 4642 for (auto *Clause : Clauses) { 4643 if (Clause->getClauseKind() == OMPC_nowait) 4644 Nowait = Clause; 4645 else if (Clause->getClauseKind() == OMPC_copyprivate) 4646 Copyprivate = Clause; 4647 if (Copyprivate && Nowait) { 4648 Diag(Copyprivate->getLocStart(), 4649 diag::err_omp_single_copyprivate_with_nowait); 4650 Diag(Nowait->getLocStart(), diag::note_omp_nowait_clause_here); 4651 return StmtError(); 4652 } 4653 } 4654 4655 return OMPSingleDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt); 4656 } 4657 4658 StmtResult Sema::ActOnOpenMPMasterDirective(Stmt *AStmt, 4659 SourceLocation StartLoc, 4660 SourceLocation EndLoc) { 4661 if (!AStmt) 4662 return StmtError(); 4663 4664 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected"); 4665 4666 getCurFunction()->setHasBranchProtectedScope(); 4667 4668 return OMPMasterDirective::Create(Context, StartLoc, EndLoc, AStmt); 4669 } 4670 4671 StmtResult Sema::ActOnOpenMPCriticalDirective( 4672 const DeclarationNameInfo &DirName, ArrayRef<OMPClause *> Clauses, 4673 Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc) { 4674 if (!AStmt) 4675 return StmtError(); 4676 4677 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected"); 4678 4679 bool ErrorFound = false; 4680 llvm::APSInt Hint; 4681 SourceLocation HintLoc; 4682 bool DependentHint = false; 4683 for (auto *C : Clauses) { 4684 if (C->getClauseKind() == OMPC_hint) { 4685 if (!DirName.getName()) { 4686 Diag(C->getLocStart(), diag::err_omp_hint_clause_no_name); 4687 ErrorFound = true; 4688 } 4689 Expr *E = cast<OMPHintClause>(C)->getHint(); 4690 if (E->isTypeDependent() || E->isValueDependent() || 4691 E->isInstantiationDependent()) 4692 DependentHint = true; 4693 else { 4694 Hint = E->EvaluateKnownConstInt(Context); 4695 HintLoc = C->getLocStart(); 4696 } 4697 } 4698 } 4699 if (ErrorFound) 4700 return StmtError(); 4701 auto Pair = DSAStack->getCriticalWithHint(DirName); 4702 if (Pair.first && DirName.getName() && !DependentHint) { 4703 if (llvm::APSInt::compareValues(Hint, Pair.second) != 0) { 4704 Diag(StartLoc, diag::err_omp_critical_with_hint); 4705 if (HintLoc.isValid()) { 4706 Diag(HintLoc, diag::note_omp_critical_hint_here) 4707 << 0 << Hint.toString(/*Radix=*/10, /*Signed=*/false); 4708 } else 4709 Diag(StartLoc, diag::note_omp_critical_no_hint) << 0; 4710 if (auto *C = Pair.first->getSingleClause<OMPHintClause>()) { 4711 Diag(C->getLocStart(), diag::note_omp_critical_hint_here) 4712 << 1 4713 << C->getHint()->EvaluateKnownConstInt(Context).toString( 4714 /*Radix=*/10, /*Signed=*/false); 4715 } else 4716 Diag(Pair.first->getLocStart(), diag::note_omp_critical_no_hint) << 1; 4717 } 4718 } 4719 4720 getCurFunction()->setHasBranchProtectedScope(); 4721 4722 auto *Dir = OMPCriticalDirective::Create(Context, DirName, StartLoc, EndLoc, 4723 Clauses, AStmt); 4724 if (!Pair.first && DirName.getName() && !DependentHint) 4725 DSAStack->addCriticalWithHint(Dir, Hint); 4726 return Dir; 4727 } 4728 4729 StmtResult Sema::ActOnOpenMPParallelForDirective( 4730 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, 4731 SourceLocation EndLoc, 4732 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) { 4733 if (!AStmt) 4734 return StmtError(); 4735 4736 CapturedStmt *CS = cast<CapturedStmt>(AStmt); 4737 // 1.2.2 OpenMP Language Terminology 4738 // Structured block - An executable statement with a single entry at the 4739 // top and a single exit at the bottom. 4740 // The point of exit cannot be a branch out of the structured block. 4741 // longjmp() and throw() must not violate the entry/exit criteria. 4742 CS->getCapturedDecl()->setNothrow(); 4743 4744 OMPLoopDirective::HelperExprs B; 4745 // In presence of clause 'collapse' or 'ordered' with number of loops, it will 4746 // define the nested loops number. 4747 unsigned NestedLoopCount = 4748 CheckOpenMPLoop(OMPD_parallel_for, getCollapseNumberExpr(Clauses), 4749 getOrderedNumberExpr(Clauses), AStmt, *this, *DSAStack, 4750 VarsWithImplicitDSA, B); 4751 if (NestedLoopCount == 0) 4752 return StmtError(); 4753 4754 assert((CurContext->isDependentContext() || B.builtAll()) && 4755 "omp parallel for loop exprs were not built"); 4756 4757 if (!CurContext->isDependentContext()) { 4758 // Finalize the clauses that need pre-built expressions for CodeGen. 4759 for (auto C : Clauses) { 4760 if (auto *LC = dyn_cast<OMPLinearClause>(C)) 4761 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef), 4762 B.NumIterations, *this, CurScope, 4763 DSAStack)) 4764 return StmtError(); 4765 } 4766 } 4767 4768 getCurFunction()->setHasBranchProtectedScope(); 4769 return OMPParallelForDirective::Create(Context, StartLoc, EndLoc, 4770 NestedLoopCount, Clauses, AStmt, B, 4771 DSAStack->isCancelRegion()); 4772 } 4773 4774 StmtResult Sema::ActOnOpenMPParallelForSimdDirective( 4775 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, 4776 SourceLocation EndLoc, 4777 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) { 4778 if (!AStmt) 4779 return StmtError(); 4780 4781 CapturedStmt *CS = cast<CapturedStmt>(AStmt); 4782 // 1.2.2 OpenMP Language Terminology 4783 // Structured block - An executable statement with a single entry at the 4784 // top and a single exit at the bottom. 4785 // The point of exit cannot be a branch out of the structured block. 4786 // longjmp() and throw() must not violate the entry/exit criteria. 4787 CS->getCapturedDecl()->setNothrow(); 4788 4789 OMPLoopDirective::HelperExprs B; 4790 // In presence of clause 'collapse' or 'ordered' with number of loops, it will 4791 // define the nested loops number. 4792 unsigned NestedLoopCount = 4793 CheckOpenMPLoop(OMPD_parallel_for_simd, getCollapseNumberExpr(Clauses), 4794 getOrderedNumberExpr(Clauses), AStmt, *this, *DSAStack, 4795 VarsWithImplicitDSA, B); 4796 if (NestedLoopCount == 0) 4797 return StmtError(); 4798 4799 if (!CurContext->isDependentContext()) { 4800 // Finalize the clauses that need pre-built expressions for CodeGen. 4801 for (auto C : Clauses) { 4802 if (auto *LC = dyn_cast<OMPLinearClause>(C)) 4803 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef), 4804 B.NumIterations, *this, CurScope, 4805 DSAStack)) 4806 return StmtError(); 4807 } 4808 } 4809 4810 if (checkSimdlenSafelenSpecified(*this, Clauses)) 4811 return StmtError(); 4812 4813 getCurFunction()->setHasBranchProtectedScope(); 4814 return OMPParallelForSimdDirective::Create( 4815 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B); 4816 } 4817 4818 StmtResult 4819 Sema::ActOnOpenMPParallelSectionsDirective(ArrayRef<OMPClause *> Clauses, 4820 Stmt *AStmt, SourceLocation StartLoc, 4821 SourceLocation EndLoc) { 4822 if (!AStmt) 4823 return StmtError(); 4824 4825 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected"); 4826 auto BaseStmt = AStmt; 4827 while (auto *CS = dyn_cast_or_null<CapturedStmt>(BaseStmt)) 4828 BaseStmt = CS->getCapturedStmt(); 4829 if (auto *C = dyn_cast_or_null<CompoundStmt>(BaseStmt)) { 4830 auto S = C->children(); 4831 if (S.begin() == S.end()) 4832 return StmtError(); 4833 // All associated statements must be '#pragma omp section' except for 4834 // the first one. 4835 for (Stmt *SectionStmt : llvm::make_range(std::next(S.begin()), S.end())) { 4836 if (!SectionStmt || !isa<OMPSectionDirective>(SectionStmt)) { 4837 if (SectionStmt) 4838 Diag(SectionStmt->getLocStart(), 4839 diag::err_omp_parallel_sections_substmt_not_section); 4840 return StmtError(); 4841 } 4842 cast<OMPSectionDirective>(SectionStmt) 4843 ->setHasCancel(DSAStack->isCancelRegion()); 4844 } 4845 } else { 4846 Diag(AStmt->getLocStart(), 4847 diag::err_omp_parallel_sections_not_compound_stmt); 4848 return StmtError(); 4849 } 4850 4851 getCurFunction()->setHasBranchProtectedScope(); 4852 4853 return OMPParallelSectionsDirective::Create( 4854 Context, StartLoc, EndLoc, Clauses, AStmt, DSAStack->isCancelRegion()); 4855 } 4856 4857 StmtResult Sema::ActOnOpenMPTaskDirective(ArrayRef<OMPClause *> Clauses, 4858 Stmt *AStmt, SourceLocation StartLoc, 4859 SourceLocation EndLoc) { 4860 if (!AStmt) 4861 return StmtError(); 4862 4863 auto *CS = cast<CapturedStmt>(AStmt); 4864 // 1.2.2 OpenMP Language Terminology 4865 // Structured block - An executable statement with a single entry at the 4866 // top and a single exit at the bottom. 4867 // The point of exit cannot be a branch out of the structured block. 4868 // longjmp() and throw() must not violate the entry/exit criteria. 4869 CS->getCapturedDecl()->setNothrow(); 4870 4871 getCurFunction()->setHasBranchProtectedScope(); 4872 4873 return OMPTaskDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt, 4874 DSAStack->isCancelRegion()); 4875 } 4876 4877 StmtResult Sema::ActOnOpenMPTaskyieldDirective(SourceLocation StartLoc, 4878 SourceLocation EndLoc) { 4879 return OMPTaskyieldDirective::Create(Context, StartLoc, EndLoc); 4880 } 4881 4882 StmtResult Sema::ActOnOpenMPBarrierDirective(SourceLocation StartLoc, 4883 SourceLocation EndLoc) { 4884 return OMPBarrierDirective::Create(Context, StartLoc, EndLoc); 4885 } 4886 4887 StmtResult Sema::ActOnOpenMPTaskwaitDirective(SourceLocation StartLoc, 4888 SourceLocation EndLoc) { 4889 return OMPTaskwaitDirective::Create(Context, StartLoc, EndLoc); 4890 } 4891 4892 StmtResult Sema::ActOnOpenMPTaskgroupDirective(Stmt *AStmt, 4893 SourceLocation StartLoc, 4894 SourceLocation EndLoc) { 4895 if (!AStmt) 4896 return StmtError(); 4897 4898 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected"); 4899 4900 getCurFunction()->setHasBranchProtectedScope(); 4901 4902 return OMPTaskgroupDirective::Create(Context, StartLoc, EndLoc, AStmt); 4903 } 4904 4905 StmtResult Sema::ActOnOpenMPFlushDirective(ArrayRef<OMPClause *> Clauses, 4906 SourceLocation StartLoc, 4907 SourceLocation EndLoc) { 4908 assert(Clauses.size() <= 1 && "Extra clauses in flush directive"); 4909 return OMPFlushDirective::Create(Context, StartLoc, EndLoc, Clauses); 4910 } 4911 4912 StmtResult Sema::ActOnOpenMPOrderedDirective(ArrayRef<OMPClause *> Clauses, 4913 Stmt *AStmt, 4914 SourceLocation StartLoc, 4915 SourceLocation EndLoc) { 4916 OMPClause *DependFound = nullptr; 4917 OMPClause *DependSourceClause = nullptr; 4918 OMPClause *DependSinkClause = nullptr; 4919 bool ErrorFound = false; 4920 OMPThreadsClause *TC = nullptr; 4921 OMPSIMDClause *SC = nullptr; 4922 for (auto *C : Clauses) { 4923 if (auto *DC = dyn_cast<OMPDependClause>(C)) { 4924 DependFound = C; 4925 if (DC->getDependencyKind() == OMPC_DEPEND_source) { 4926 if (DependSourceClause) { 4927 Diag(C->getLocStart(), diag::err_omp_more_one_clause) 4928 << getOpenMPDirectiveName(OMPD_ordered) 4929 << getOpenMPClauseName(OMPC_depend) << 2; 4930 ErrorFound = true; 4931 } else 4932 DependSourceClause = C; 4933 if (DependSinkClause) { 4934 Diag(C->getLocStart(), diag::err_omp_depend_sink_source_not_allowed) 4935 << 0; 4936 ErrorFound = true; 4937 } 4938 } else if (DC->getDependencyKind() == OMPC_DEPEND_sink) { 4939 if (DependSourceClause) { 4940 Diag(C->getLocStart(), diag::err_omp_depend_sink_source_not_allowed) 4941 << 1; 4942 ErrorFound = true; 4943 } 4944 DependSinkClause = C; 4945 } 4946 } else if (C->getClauseKind() == OMPC_threads) 4947 TC = cast<OMPThreadsClause>(C); 4948 else if (C->getClauseKind() == OMPC_simd) 4949 SC = cast<OMPSIMDClause>(C); 4950 } 4951 if (!ErrorFound && !SC && 4952 isOpenMPSimdDirective(DSAStack->getParentDirective())) { 4953 // OpenMP [2.8.1,simd Construct, Restrictions] 4954 // An ordered construct with the simd clause is the only OpenMP construct 4955 // that can appear in the simd region. 4956 Diag(StartLoc, diag::err_omp_prohibited_region_simd); 4957 ErrorFound = true; 4958 } else if (DependFound && (TC || SC)) { 4959 Diag(DependFound->getLocStart(), diag::err_omp_depend_clause_thread_simd) 4960 << getOpenMPClauseName(TC ? TC->getClauseKind() : SC->getClauseKind()); 4961 ErrorFound = true; 4962 } else if (DependFound && !DSAStack->getParentOrderedRegionParam()) { 4963 Diag(DependFound->getLocStart(), 4964 diag::err_omp_ordered_directive_without_param); 4965 ErrorFound = true; 4966 } else if (TC || Clauses.empty()) { 4967 if (auto *Param = DSAStack->getParentOrderedRegionParam()) { 4968 SourceLocation ErrLoc = TC ? TC->getLocStart() : StartLoc; 4969 Diag(ErrLoc, diag::err_omp_ordered_directive_with_param) 4970 << (TC != nullptr); 4971 Diag(Param->getLocStart(), diag::note_omp_ordered_param); 4972 ErrorFound = true; 4973 } 4974 } 4975 if ((!AStmt && !DependFound) || ErrorFound) 4976 return StmtError(); 4977 4978 if (AStmt) { 4979 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected"); 4980 4981 getCurFunction()->setHasBranchProtectedScope(); 4982 } 4983 4984 return OMPOrderedDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt); 4985 } 4986 4987 namespace { 4988 /// \brief Helper class for checking expression in 'omp atomic [update]' 4989 /// construct. 4990 class OpenMPAtomicUpdateChecker { 4991 /// \brief Error results for atomic update expressions. 4992 enum ExprAnalysisErrorCode { 4993 /// \brief A statement is not an expression statement. 4994 NotAnExpression, 4995 /// \brief Expression is not builtin binary or unary operation. 4996 NotABinaryOrUnaryExpression, 4997 /// \brief Unary operation is not post-/pre- increment/decrement operation. 4998 NotAnUnaryIncDecExpression, 4999 /// \brief An expression is not of scalar type. 5000 NotAScalarType, 5001 /// \brief A binary operation is not an assignment operation. 5002 NotAnAssignmentOp, 5003 /// \brief RHS part of the binary operation is not a binary expression. 5004 NotABinaryExpression, 5005 /// \brief RHS part is not additive/multiplicative/shift/biwise binary 5006 /// expression. 5007 NotABinaryOperator, 5008 /// \brief RHS binary operation does not have reference to the updated LHS 5009 /// part. 5010 NotAnUpdateExpression, 5011 /// \brief No errors is found. 5012 NoError 5013 }; 5014 /// \brief Reference to Sema. 5015 Sema &SemaRef; 5016 /// \brief A location for note diagnostics (when error is found). 5017 SourceLocation NoteLoc; 5018 /// \brief 'x' lvalue part of the source atomic expression. 5019 Expr *X; 5020 /// \brief 'expr' rvalue part of the source atomic expression. 5021 Expr *E; 5022 /// \brief Helper expression of the form 5023 /// 'OpaqueValueExpr(x) binop OpaqueValueExpr(expr)' or 5024 /// 'OpaqueValueExpr(expr) binop OpaqueValueExpr(x)'. 5025 Expr *UpdateExpr; 5026 /// \brief Is 'x' a LHS in a RHS part of full update expression. It is 5027 /// important for non-associative operations. 5028 bool IsXLHSInRHSPart; 5029 BinaryOperatorKind Op; 5030 SourceLocation OpLoc; 5031 /// \brief true if the source expression is a postfix unary operation, false 5032 /// if it is a prefix unary operation. 5033 bool IsPostfixUpdate; 5034 5035 public: 5036 OpenMPAtomicUpdateChecker(Sema &SemaRef) 5037 : SemaRef(SemaRef), X(nullptr), E(nullptr), UpdateExpr(nullptr), 5038 IsXLHSInRHSPart(false), Op(BO_PtrMemD), IsPostfixUpdate(false) {} 5039 /// \brief Check specified statement that it is suitable for 'atomic update' 5040 /// constructs and extract 'x', 'expr' and Operation from the original 5041 /// expression. If DiagId and NoteId == 0, then only check is performed 5042 /// without error notification. 5043 /// \param DiagId Diagnostic which should be emitted if error is found. 5044 /// \param NoteId Diagnostic note for the main error message. 5045 /// \return true if statement is not an update expression, false otherwise. 5046 bool checkStatement(Stmt *S, unsigned DiagId = 0, unsigned NoteId = 0); 5047 /// \brief Return the 'x' lvalue part of the source atomic expression. 5048 Expr *getX() const { return X; } 5049 /// \brief Return the 'expr' rvalue part of the source atomic expression. 5050 Expr *getExpr() const { return E; } 5051 /// \brief Return the update expression used in calculation of the updated 5052 /// value. Always has form 'OpaqueValueExpr(x) binop OpaqueValueExpr(expr)' or 5053 /// 'OpaqueValueExpr(expr) binop OpaqueValueExpr(x)'. 5054 Expr *getUpdateExpr() const { return UpdateExpr; } 5055 /// \brief Return true if 'x' is LHS in RHS part of full update expression, 5056 /// false otherwise. 5057 bool isXLHSInRHSPart() const { return IsXLHSInRHSPart; } 5058 5059 /// \brief true if the source expression is a postfix unary operation, false 5060 /// if it is a prefix unary operation. 5061 bool isPostfixUpdate() const { return IsPostfixUpdate; } 5062 5063 private: 5064 bool checkBinaryOperation(BinaryOperator *AtomicBinOp, unsigned DiagId = 0, 5065 unsigned NoteId = 0); 5066 }; 5067 } // namespace 5068 5069 bool OpenMPAtomicUpdateChecker::checkBinaryOperation( 5070 BinaryOperator *AtomicBinOp, unsigned DiagId, unsigned NoteId) { 5071 ExprAnalysisErrorCode ErrorFound = NoError; 5072 SourceLocation ErrorLoc, NoteLoc; 5073 SourceRange ErrorRange, NoteRange; 5074 // Allowed constructs are: 5075 // x = x binop expr; 5076 // x = expr binop x; 5077 if (AtomicBinOp->getOpcode() == BO_Assign) { 5078 X = AtomicBinOp->getLHS(); 5079 if (auto *AtomicInnerBinOp = dyn_cast<BinaryOperator>( 5080 AtomicBinOp->getRHS()->IgnoreParenImpCasts())) { 5081 if (AtomicInnerBinOp->isMultiplicativeOp() || 5082 AtomicInnerBinOp->isAdditiveOp() || AtomicInnerBinOp->isShiftOp() || 5083 AtomicInnerBinOp->isBitwiseOp()) { 5084 Op = AtomicInnerBinOp->getOpcode(); 5085 OpLoc = AtomicInnerBinOp->getOperatorLoc(); 5086 auto *LHS = AtomicInnerBinOp->getLHS(); 5087 auto *RHS = AtomicInnerBinOp->getRHS(); 5088 llvm::FoldingSetNodeID XId, LHSId, RHSId; 5089 X->IgnoreParenImpCasts()->Profile(XId, SemaRef.getASTContext(), 5090 /*Canonical=*/true); 5091 LHS->IgnoreParenImpCasts()->Profile(LHSId, SemaRef.getASTContext(), 5092 /*Canonical=*/true); 5093 RHS->IgnoreParenImpCasts()->Profile(RHSId, SemaRef.getASTContext(), 5094 /*Canonical=*/true); 5095 if (XId == LHSId) { 5096 E = RHS; 5097 IsXLHSInRHSPart = true; 5098 } else if (XId == RHSId) { 5099 E = LHS; 5100 IsXLHSInRHSPart = false; 5101 } else { 5102 ErrorLoc = AtomicInnerBinOp->getExprLoc(); 5103 ErrorRange = AtomicInnerBinOp->getSourceRange(); 5104 NoteLoc = X->getExprLoc(); 5105 NoteRange = X->getSourceRange(); 5106 ErrorFound = NotAnUpdateExpression; 5107 } 5108 } else { 5109 ErrorLoc = AtomicInnerBinOp->getExprLoc(); 5110 ErrorRange = AtomicInnerBinOp->getSourceRange(); 5111 NoteLoc = AtomicInnerBinOp->getOperatorLoc(); 5112 NoteRange = SourceRange(NoteLoc, NoteLoc); 5113 ErrorFound = NotABinaryOperator; 5114 } 5115 } else { 5116 NoteLoc = ErrorLoc = AtomicBinOp->getRHS()->getExprLoc(); 5117 NoteRange = ErrorRange = AtomicBinOp->getRHS()->getSourceRange(); 5118 ErrorFound = NotABinaryExpression; 5119 } 5120 } else { 5121 ErrorLoc = AtomicBinOp->getExprLoc(); 5122 ErrorRange = AtomicBinOp->getSourceRange(); 5123 NoteLoc = AtomicBinOp->getOperatorLoc(); 5124 NoteRange = SourceRange(NoteLoc, NoteLoc); 5125 ErrorFound = NotAnAssignmentOp; 5126 } 5127 if (ErrorFound != NoError && DiagId != 0 && NoteId != 0) { 5128 SemaRef.Diag(ErrorLoc, DiagId) << ErrorRange; 5129 SemaRef.Diag(NoteLoc, NoteId) << ErrorFound << NoteRange; 5130 return true; 5131 } else if (SemaRef.CurContext->isDependentContext()) 5132 E = X = UpdateExpr = nullptr; 5133 return ErrorFound != NoError; 5134 } 5135 5136 bool OpenMPAtomicUpdateChecker::checkStatement(Stmt *S, unsigned DiagId, 5137 unsigned NoteId) { 5138 ExprAnalysisErrorCode ErrorFound = NoError; 5139 SourceLocation ErrorLoc, NoteLoc; 5140 SourceRange ErrorRange, NoteRange; 5141 // Allowed constructs are: 5142 // x++; 5143 // x--; 5144 // ++x; 5145 // --x; 5146 // x binop= expr; 5147 // x = x binop expr; 5148 // x = expr binop x; 5149 if (auto *AtomicBody = dyn_cast<Expr>(S)) { 5150 AtomicBody = AtomicBody->IgnoreParenImpCasts(); 5151 if (AtomicBody->getType()->isScalarType() || 5152 AtomicBody->isInstantiationDependent()) { 5153 if (auto *AtomicCompAssignOp = dyn_cast<CompoundAssignOperator>( 5154 AtomicBody->IgnoreParenImpCasts())) { 5155 // Check for Compound Assignment Operation 5156 Op = BinaryOperator::getOpForCompoundAssignment( 5157 AtomicCompAssignOp->getOpcode()); 5158 OpLoc = AtomicCompAssignOp->getOperatorLoc(); 5159 E = AtomicCompAssignOp->getRHS(); 5160 X = AtomicCompAssignOp->getLHS()->IgnoreParens(); 5161 IsXLHSInRHSPart = true; 5162 } else if (auto *AtomicBinOp = dyn_cast<BinaryOperator>( 5163 AtomicBody->IgnoreParenImpCasts())) { 5164 // Check for Binary Operation 5165 if (checkBinaryOperation(AtomicBinOp, DiagId, NoteId)) 5166 return true; 5167 } else if (auto *AtomicUnaryOp = dyn_cast<UnaryOperator>( 5168 AtomicBody->IgnoreParenImpCasts())) { 5169 // Check for Unary Operation 5170 if (AtomicUnaryOp->isIncrementDecrementOp()) { 5171 IsPostfixUpdate = AtomicUnaryOp->isPostfix(); 5172 Op = AtomicUnaryOp->isIncrementOp() ? BO_Add : BO_Sub; 5173 OpLoc = AtomicUnaryOp->getOperatorLoc(); 5174 X = AtomicUnaryOp->getSubExpr()->IgnoreParens(); 5175 E = SemaRef.ActOnIntegerConstant(OpLoc, /*uint64_t Val=*/1).get(); 5176 IsXLHSInRHSPart = true; 5177 } else { 5178 ErrorFound = NotAnUnaryIncDecExpression; 5179 ErrorLoc = AtomicUnaryOp->getExprLoc(); 5180 ErrorRange = AtomicUnaryOp->getSourceRange(); 5181 NoteLoc = AtomicUnaryOp->getOperatorLoc(); 5182 NoteRange = SourceRange(NoteLoc, NoteLoc); 5183 } 5184 } else if (!AtomicBody->isInstantiationDependent()) { 5185 ErrorFound = NotABinaryOrUnaryExpression; 5186 NoteLoc = ErrorLoc = AtomicBody->getExprLoc(); 5187 NoteRange = ErrorRange = AtomicBody->getSourceRange(); 5188 } 5189 } else { 5190 ErrorFound = NotAScalarType; 5191 NoteLoc = ErrorLoc = AtomicBody->getLocStart(); 5192 NoteRange = ErrorRange = SourceRange(NoteLoc, NoteLoc); 5193 } 5194 } else { 5195 ErrorFound = NotAnExpression; 5196 NoteLoc = ErrorLoc = S->getLocStart(); 5197 NoteRange = ErrorRange = SourceRange(NoteLoc, NoteLoc); 5198 } 5199 if (ErrorFound != NoError && DiagId != 0 && NoteId != 0) { 5200 SemaRef.Diag(ErrorLoc, DiagId) << ErrorRange; 5201 SemaRef.Diag(NoteLoc, NoteId) << ErrorFound << NoteRange; 5202 return true; 5203 } else if (SemaRef.CurContext->isDependentContext()) 5204 E = X = UpdateExpr = nullptr; 5205 if (ErrorFound == NoError && E && X) { 5206 // Build an update expression of form 'OpaqueValueExpr(x) binop 5207 // OpaqueValueExpr(expr)' or 'OpaqueValueExpr(expr) binop 5208 // OpaqueValueExpr(x)' and then cast it to the type of the 'x' expression. 5209 auto *OVEX = new (SemaRef.getASTContext()) 5210 OpaqueValueExpr(X->getExprLoc(), X->getType(), VK_RValue); 5211 auto *OVEExpr = new (SemaRef.getASTContext()) 5212 OpaqueValueExpr(E->getExprLoc(), E->getType(), VK_RValue); 5213 auto Update = 5214 SemaRef.CreateBuiltinBinOp(OpLoc, Op, IsXLHSInRHSPart ? OVEX : OVEExpr, 5215 IsXLHSInRHSPart ? OVEExpr : OVEX); 5216 if (Update.isInvalid()) 5217 return true; 5218 Update = SemaRef.PerformImplicitConversion(Update.get(), X->getType(), 5219 Sema::AA_Casting); 5220 if (Update.isInvalid()) 5221 return true; 5222 UpdateExpr = Update.get(); 5223 } 5224 return ErrorFound != NoError; 5225 } 5226 5227 StmtResult Sema::ActOnOpenMPAtomicDirective(ArrayRef<OMPClause *> Clauses, 5228 Stmt *AStmt, 5229 SourceLocation StartLoc, 5230 SourceLocation EndLoc) { 5231 if (!AStmt) 5232 return StmtError(); 5233 5234 auto *CS = cast<CapturedStmt>(AStmt); 5235 // 1.2.2 OpenMP Language Terminology 5236 // Structured block - An executable statement with a single entry at the 5237 // top and a single exit at the bottom. 5238 // The point of exit cannot be a branch out of the structured block. 5239 // longjmp() and throw() must not violate the entry/exit criteria. 5240 OpenMPClauseKind AtomicKind = OMPC_unknown; 5241 SourceLocation AtomicKindLoc; 5242 for (auto *C : Clauses) { 5243 if (C->getClauseKind() == OMPC_read || C->getClauseKind() == OMPC_write || 5244 C->getClauseKind() == OMPC_update || 5245 C->getClauseKind() == OMPC_capture) { 5246 if (AtomicKind != OMPC_unknown) { 5247 Diag(C->getLocStart(), diag::err_omp_atomic_several_clauses) 5248 << SourceRange(C->getLocStart(), C->getLocEnd()); 5249 Diag(AtomicKindLoc, diag::note_omp_atomic_previous_clause) 5250 << getOpenMPClauseName(AtomicKind); 5251 } else { 5252 AtomicKind = C->getClauseKind(); 5253 AtomicKindLoc = C->getLocStart(); 5254 } 5255 } 5256 } 5257 5258 auto Body = CS->getCapturedStmt(); 5259 if (auto *EWC = dyn_cast<ExprWithCleanups>(Body)) 5260 Body = EWC->getSubExpr(); 5261 5262 Expr *X = nullptr; 5263 Expr *V = nullptr; 5264 Expr *E = nullptr; 5265 Expr *UE = nullptr; 5266 bool IsXLHSInRHSPart = false; 5267 bool IsPostfixUpdate = false; 5268 // OpenMP [2.12.6, atomic Construct] 5269 // In the next expressions: 5270 // * x and v (as applicable) are both l-value expressions with scalar type. 5271 // * During the execution of an atomic region, multiple syntactic 5272 // occurrences of x must designate the same storage location. 5273 // * Neither of v and expr (as applicable) may access the storage location 5274 // designated by x. 5275 // * Neither of x and expr (as applicable) may access the storage location 5276 // designated by v. 5277 // * expr is an expression with scalar type. 5278 // * binop is one of +, *, -, /, &, ^, |, <<, or >>. 5279 // * binop, binop=, ++, and -- are not overloaded operators. 5280 // * The expression x binop expr must be numerically equivalent to x binop 5281 // (expr). This requirement is satisfied if the operators in expr have 5282 // precedence greater than binop, or by using parentheses around expr or 5283 // subexpressions of expr. 5284 // * The expression expr binop x must be numerically equivalent to (expr) 5285 // binop x. This requirement is satisfied if the operators in expr have 5286 // precedence equal to or greater than binop, or by using parentheses around 5287 // expr or subexpressions of expr. 5288 // * For forms that allow multiple occurrences of x, the number of times 5289 // that x is evaluated is unspecified. 5290 if (AtomicKind == OMPC_read) { 5291 enum { 5292 NotAnExpression, 5293 NotAnAssignmentOp, 5294 NotAScalarType, 5295 NotAnLValue, 5296 NoError 5297 } ErrorFound = NoError; 5298 SourceLocation ErrorLoc, NoteLoc; 5299 SourceRange ErrorRange, NoteRange; 5300 // If clause is read: 5301 // v = x; 5302 if (auto *AtomicBody = dyn_cast<Expr>(Body)) { 5303 auto *AtomicBinOp = 5304 dyn_cast<BinaryOperator>(AtomicBody->IgnoreParenImpCasts()); 5305 if (AtomicBinOp && AtomicBinOp->getOpcode() == BO_Assign) { 5306 X = AtomicBinOp->getRHS()->IgnoreParenImpCasts(); 5307 V = AtomicBinOp->getLHS()->IgnoreParenImpCasts(); 5308 if ((X->isInstantiationDependent() || X->getType()->isScalarType()) && 5309 (V->isInstantiationDependent() || V->getType()->isScalarType())) { 5310 if (!X->isLValue() || !V->isLValue()) { 5311 auto NotLValueExpr = X->isLValue() ? V : X; 5312 ErrorFound = NotAnLValue; 5313 ErrorLoc = AtomicBinOp->getExprLoc(); 5314 ErrorRange = AtomicBinOp->getSourceRange(); 5315 NoteLoc = NotLValueExpr->getExprLoc(); 5316 NoteRange = NotLValueExpr->getSourceRange(); 5317 } 5318 } else if (!X->isInstantiationDependent() || 5319 !V->isInstantiationDependent()) { 5320 auto NotScalarExpr = 5321 (X->isInstantiationDependent() || X->getType()->isScalarType()) 5322 ? V 5323 : X; 5324 ErrorFound = NotAScalarType; 5325 ErrorLoc = AtomicBinOp->getExprLoc(); 5326 ErrorRange = AtomicBinOp->getSourceRange(); 5327 NoteLoc = NotScalarExpr->getExprLoc(); 5328 NoteRange = NotScalarExpr->getSourceRange(); 5329 } 5330 } else if (!AtomicBody->isInstantiationDependent()) { 5331 ErrorFound = NotAnAssignmentOp; 5332 ErrorLoc = AtomicBody->getExprLoc(); 5333 ErrorRange = AtomicBody->getSourceRange(); 5334 NoteLoc = AtomicBinOp ? AtomicBinOp->getOperatorLoc() 5335 : AtomicBody->getExprLoc(); 5336 NoteRange = AtomicBinOp ? AtomicBinOp->getSourceRange() 5337 : AtomicBody->getSourceRange(); 5338 } 5339 } else { 5340 ErrorFound = NotAnExpression; 5341 NoteLoc = ErrorLoc = Body->getLocStart(); 5342 NoteRange = ErrorRange = SourceRange(NoteLoc, NoteLoc); 5343 } 5344 if (ErrorFound != NoError) { 5345 Diag(ErrorLoc, diag::err_omp_atomic_read_not_expression_statement) 5346 << ErrorRange; 5347 Diag(NoteLoc, diag::note_omp_atomic_read_write) << ErrorFound 5348 << NoteRange; 5349 return StmtError(); 5350 } else if (CurContext->isDependentContext()) 5351 V = X = nullptr; 5352 } else if (AtomicKind == OMPC_write) { 5353 enum { 5354 NotAnExpression, 5355 NotAnAssignmentOp, 5356 NotAScalarType, 5357 NotAnLValue, 5358 NoError 5359 } ErrorFound = NoError; 5360 SourceLocation ErrorLoc, NoteLoc; 5361 SourceRange ErrorRange, NoteRange; 5362 // If clause is write: 5363 // x = expr; 5364 if (auto *AtomicBody = dyn_cast<Expr>(Body)) { 5365 auto *AtomicBinOp = 5366 dyn_cast<BinaryOperator>(AtomicBody->IgnoreParenImpCasts()); 5367 if (AtomicBinOp && AtomicBinOp->getOpcode() == BO_Assign) { 5368 X = AtomicBinOp->getLHS(); 5369 E = AtomicBinOp->getRHS(); 5370 if ((X->isInstantiationDependent() || X->getType()->isScalarType()) && 5371 (E->isInstantiationDependent() || E->getType()->isScalarType())) { 5372 if (!X->isLValue()) { 5373 ErrorFound = NotAnLValue; 5374 ErrorLoc = AtomicBinOp->getExprLoc(); 5375 ErrorRange = AtomicBinOp->getSourceRange(); 5376 NoteLoc = X->getExprLoc(); 5377 NoteRange = X->getSourceRange(); 5378 } 5379 } else if (!X->isInstantiationDependent() || 5380 !E->isInstantiationDependent()) { 5381 auto NotScalarExpr = 5382 (X->isInstantiationDependent() || X->getType()->isScalarType()) 5383 ? E 5384 : X; 5385 ErrorFound = NotAScalarType; 5386 ErrorLoc = AtomicBinOp->getExprLoc(); 5387 ErrorRange = AtomicBinOp->getSourceRange(); 5388 NoteLoc = NotScalarExpr->getExprLoc(); 5389 NoteRange = NotScalarExpr->getSourceRange(); 5390 } 5391 } else if (!AtomicBody->isInstantiationDependent()) { 5392 ErrorFound = NotAnAssignmentOp; 5393 ErrorLoc = AtomicBody->getExprLoc(); 5394 ErrorRange = AtomicBody->getSourceRange(); 5395 NoteLoc = AtomicBinOp ? AtomicBinOp->getOperatorLoc() 5396 : AtomicBody->getExprLoc(); 5397 NoteRange = AtomicBinOp ? AtomicBinOp->getSourceRange() 5398 : AtomicBody->getSourceRange(); 5399 } 5400 } else { 5401 ErrorFound = NotAnExpression; 5402 NoteLoc = ErrorLoc = Body->getLocStart(); 5403 NoteRange = ErrorRange = SourceRange(NoteLoc, NoteLoc); 5404 } 5405 if (ErrorFound != NoError) { 5406 Diag(ErrorLoc, diag::err_omp_atomic_write_not_expression_statement) 5407 << ErrorRange; 5408 Diag(NoteLoc, diag::note_omp_atomic_read_write) << ErrorFound 5409 << NoteRange; 5410 return StmtError(); 5411 } else if (CurContext->isDependentContext()) 5412 E = X = nullptr; 5413 } else if (AtomicKind == OMPC_update || AtomicKind == OMPC_unknown) { 5414 // If clause is update: 5415 // x++; 5416 // x--; 5417 // ++x; 5418 // --x; 5419 // x binop= expr; 5420 // x = x binop expr; 5421 // x = expr binop x; 5422 OpenMPAtomicUpdateChecker Checker(*this); 5423 if (Checker.checkStatement( 5424 Body, (AtomicKind == OMPC_update) 5425 ? diag::err_omp_atomic_update_not_expression_statement 5426 : diag::err_omp_atomic_not_expression_statement, 5427 diag::note_omp_atomic_update)) 5428 return StmtError(); 5429 if (!CurContext->isDependentContext()) { 5430 E = Checker.getExpr(); 5431 X = Checker.getX(); 5432 UE = Checker.getUpdateExpr(); 5433 IsXLHSInRHSPart = Checker.isXLHSInRHSPart(); 5434 } 5435 } else if (AtomicKind == OMPC_capture) { 5436 enum { 5437 NotAnAssignmentOp, 5438 NotACompoundStatement, 5439 NotTwoSubstatements, 5440 NotASpecificExpression, 5441 NoError 5442 } ErrorFound = NoError; 5443 SourceLocation ErrorLoc, NoteLoc; 5444 SourceRange ErrorRange, NoteRange; 5445 if (auto *AtomicBody = dyn_cast<Expr>(Body)) { 5446 // If clause is a capture: 5447 // v = x++; 5448 // v = x--; 5449 // v = ++x; 5450 // v = --x; 5451 // v = x binop= expr; 5452 // v = x = x binop expr; 5453 // v = x = expr binop x; 5454 auto *AtomicBinOp = 5455 dyn_cast<BinaryOperator>(AtomicBody->IgnoreParenImpCasts()); 5456 if (AtomicBinOp && AtomicBinOp->getOpcode() == BO_Assign) { 5457 V = AtomicBinOp->getLHS(); 5458 Body = AtomicBinOp->getRHS()->IgnoreParenImpCasts(); 5459 OpenMPAtomicUpdateChecker Checker(*this); 5460 if (Checker.checkStatement( 5461 Body, diag::err_omp_atomic_capture_not_expression_statement, 5462 diag::note_omp_atomic_update)) 5463 return StmtError(); 5464 E = Checker.getExpr(); 5465 X = Checker.getX(); 5466 UE = Checker.getUpdateExpr(); 5467 IsXLHSInRHSPart = Checker.isXLHSInRHSPart(); 5468 IsPostfixUpdate = Checker.isPostfixUpdate(); 5469 } else if (!AtomicBody->isInstantiationDependent()) { 5470 ErrorLoc = AtomicBody->getExprLoc(); 5471 ErrorRange = AtomicBody->getSourceRange(); 5472 NoteLoc = AtomicBinOp ? AtomicBinOp->getOperatorLoc() 5473 : AtomicBody->getExprLoc(); 5474 NoteRange = AtomicBinOp ? AtomicBinOp->getSourceRange() 5475 : AtomicBody->getSourceRange(); 5476 ErrorFound = NotAnAssignmentOp; 5477 } 5478 if (ErrorFound != NoError) { 5479 Diag(ErrorLoc, diag::err_omp_atomic_capture_not_expression_statement) 5480 << ErrorRange; 5481 Diag(NoteLoc, diag::note_omp_atomic_capture) << ErrorFound << NoteRange; 5482 return StmtError(); 5483 } else if (CurContext->isDependentContext()) { 5484 UE = V = E = X = nullptr; 5485 } 5486 } else { 5487 // If clause is a capture: 5488 // { v = x; x = expr; } 5489 // { v = x; x++; } 5490 // { v = x; x--; } 5491 // { v = x; ++x; } 5492 // { v = x; --x; } 5493 // { v = x; x binop= expr; } 5494 // { v = x; x = x binop expr; } 5495 // { v = x; x = expr binop x; } 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 if (auto *CS = dyn_cast<CompoundStmt>(Body)) { 5504 // Check that this is { expr1; expr2; } 5505 if (CS->size() == 2) { 5506 auto *First = CS->body_front(); 5507 auto *Second = CS->body_back(); 5508 if (auto *EWC = dyn_cast<ExprWithCleanups>(First)) 5509 First = EWC->getSubExpr()->IgnoreParenImpCasts(); 5510 if (auto *EWC = dyn_cast<ExprWithCleanups>(Second)) 5511 Second = EWC->getSubExpr()->IgnoreParenImpCasts(); 5512 // Need to find what subexpression is 'v' and what is 'x'. 5513 OpenMPAtomicUpdateChecker Checker(*this); 5514 bool IsUpdateExprFound = !Checker.checkStatement(Second); 5515 BinaryOperator *BinOp = nullptr; 5516 if (IsUpdateExprFound) { 5517 BinOp = dyn_cast<BinaryOperator>(First); 5518 IsUpdateExprFound = BinOp && BinOp->getOpcode() == BO_Assign; 5519 } 5520 if (IsUpdateExprFound && !CurContext->isDependentContext()) { 5521 // { v = x; x++; } 5522 // { v = x; x--; } 5523 // { v = x; ++x; } 5524 // { v = x; --x; } 5525 // { v = x; x binop= expr; } 5526 // { v = x; x = x binop expr; } 5527 // { v = x; x = expr binop x; } 5528 // Check that the first expression has form v = x. 5529 auto *PossibleX = BinOp->getRHS()->IgnoreParenImpCasts(); 5530 llvm::FoldingSetNodeID XId, PossibleXId; 5531 Checker.getX()->Profile(XId, Context, /*Canonical=*/true); 5532 PossibleX->Profile(PossibleXId, Context, /*Canonical=*/true); 5533 IsUpdateExprFound = XId == PossibleXId; 5534 if (IsUpdateExprFound) { 5535 V = BinOp->getLHS(); 5536 X = Checker.getX(); 5537 E = Checker.getExpr(); 5538 UE = Checker.getUpdateExpr(); 5539 IsXLHSInRHSPart = Checker.isXLHSInRHSPart(); 5540 IsPostfixUpdate = true; 5541 } 5542 } 5543 if (!IsUpdateExprFound) { 5544 IsUpdateExprFound = !Checker.checkStatement(First); 5545 BinOp = nullptr; 5546 if (IsUpdateExprFound) { 5547 BinOp = dyn_cast<BinaryOperator>(Second); 5548 IsUpdateExprFound = BinOp && BinOp->getOpcode() == BO_Assign; 5549 } 5550 if (IsUpdateExprFound && !CurContext->isDependentContext()) { 5551 // { x++; v = x; } 5552 // { x--; v = x; } 5553 // { ++x; v = x; } 5554 // { --x; v = x; } 5555 // { x binop= expr; v = x; } 5556 // { x = x binop expr; v = x; } 5557 // { x = expr binop x; v = x; } 5558 // Check that the second expression has form v = x. 5559 auto *PossibleX = BinOp->getRHS()->IgnoreParenImpCasts(); 5560 llvm::FoldingSetNodeID XId, PossibleXId; 5561 Checker.getX()->Profile(XId, Context, /*Canonical=*/true); 5562 PossibleX->Profile(PossibleXId, Context, /*Canonical=*/true); 5563 IsUpdateExprFound = XId == PossibleXId; 5564 if (IsUpdateExprFound) { 5565 V = BinOp->getLHS(); 5566 X = Checker.getX(); 5567 E = Checker.getExpr(); 5568 UE = Checker.getUpdateExpr(); 5569 IsXLHSInRHSPart = Checker.isXLHSInRHSPart(); 5570 IsPostfixUpdate = false; 5571 } 5572 } 5573 } 5574 if (!IsUpdateExprFound) { 5575 // { v = x; x = expr; } 5576 auto *FirstExpr = dyn_cast<Expr>(First); 5577 auto *SecondExpr = dyn_cast<Expr>(Second); 5578 if (!FirstExpr || !SecondExpr || 5579 !(FirstExpr->isInstantiationDependent() || 5580 SecondExpr->isInstantiationDependent())) { 5581 auto *FirstBinOp = dyn_cast<BinaryOperator>(First); 5582 if (!FirstBinOp || FirstBinOp->getOpcode() != BO_Assign) { 5583 ErrorFound = NotAnAssignmentOp; 5584 NoteLoc = ErrorLoc = FirstBinOp ? FirstBinOp->getOperatorLoc() 5585 : First->getLocStart(); 5586 NoteRange = ErrorRange = FirstBinOp 5587 ? FirstBinOp->getSourceRange() 5588 : SourceRange(ErrorLoc, ErrorLoc); 5589 } else { 5590 auto *SecondBinOp = dyn_cast<BinaryOperator>(Second); 5591 if (!SecondBinOp || SecondBinOp->getOpcode() != BO_Assign) { 5592 ErrorFound = NotAnAssignmentOp; 5593 NoteLoc = ErrorLoc = SecondBinOp 5594 ? SecondBinOp->getOperatorLoc() 5595 : Second->getLocStart(); 5596 NoteRange = ErrorRange = 5597 SecondBinOp ? SecondBinOp->getSourceRange() 5598 : SourceRange(ErrorLoc, ErrorLoc); 5599 } else { 5600 auto *PossibleXRHSInFirst = 5601 FirstBinOp->getRHS()->IgnoreParenImpCasts(); 5602 auto *PossibleXLHSInSecond = 5603 SecondBinOp->getLHS()->IgnoreParenImpCasts(); 5604 llvm::FoldingSetNodeID X1Id, X2Id; 5605 PossibleXRHSInFirst->Profile(X1Id, Context, 5606 /*Canonical=*/true); 5607 PossibleXLHSInSecond->Profile(X2Id, Context, 5608 /*Canonical=*/true); 5609 IsUpdateExprFound = X1Id == X2Id; 5610 if (IsUpdateExprFound) { 5611 V = FirstBinOp->getLHS(); 5612 X = SecondBinOp->getLHS(); 5613 E = SecondBinOp->getRHS(); 5614 UE = nullptr; 5615 IsXLHSInRHSPart = false; 5616 IsPostfixUpdate = true; 5617 } else { 5618 ErrorFound = NotASpecificExpression; 5619 ErrorLoc = FirstBinOp->getExprLoc(); 5620 ErrorRange = FirstBinOp->getSourceRange(); 5621 NoteLoc = SecondBinOp->getLHS()->getExprLoc(); 5622 NoteRange = SecondBinOp->getRHS()->getSourceRange(); 5623 } 5624 } 5625 } 5626 } 5627 } 5628 } else { 5629 NoteLoc = ErrorLoc = Body->getLocStart(); 5630 NoteRange = ErrorRange = 5631 SourceRange(Body->getLocStart(), Body->getLocStart()); 5632 ErrorFound = NotTwoSubstatements; 5633 } 5634 } else { 5635 NoteLoc = ErrorLoc = Body->getLocStart(); 5636 NoteRange = ErrorRange = 5637 SourceRange(Body->getLocStart(), Body->getLocStart()); 5638 ErrorFound = NotACompoundStatement; 5639 } 5640 if (ErrorFound != NoError) { 5641 Diag(ErrorLoc, diag::err_omp_atomic_capture_not_compound_statement) 5642 << ErrorRange; 5643 Diag(NoteLoc, diag::note_omp_atomic_capture) << ErrorFound << NoteRange; 5644 return StmtError(); 5645 } else if (CurContext->isDependentContext()) { 5646 UE = V = E = X = nullptr; 5647 } 5648 } 5649 } 5650 5651 getCurFunction()->setHasBranchProtectedScope(); 5652 5653 return OMPAtomicDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt, 5654 X, V, E, UE, IsXLHSInRHSPart, 5655 IsPostfixUpdate); 5656 } 5657 5658 StmtResult Sema::ActOnOpenMPTargetDirective(ArrayRef<OMPClause *> Clauses, 5659 Stmt *AStmt, 5660 SourceLocation StartLoc, 5661 SourceLocation EndLoc) { 5662 if (!AStmt) 5663 return StmtError(); 5664 5665 CapturedStmt *CS = cast<CapturedStmt>(AStmt); 5666 // 1.2.2 OpenMP Language Terminology 5667 // Structured block - An executable statement with a single entry at the 5668 // top and a single exit at the bottom. 5669 // The point of exit cannot be a branch out of the structured block. 5670 // longjmp() and throw() must not violate the entry/exit criteria. 5671 CS->getCapturedDecl()->setNothrow(); 5672 5673 // OpenMP [2.16, Nesting of Regions] 5674 // If specified, a teams construct must be contained within a target 5675 // construct. That target construct must contain no statements or directives 5676 // outside of the teams construct. 5677 if (DSAStack->hasInnerTeamsRegion()) { 5678 auto S = AStmt->IgnoreContainers(/*IgnoreCaptured*/ true); 5679 bool OMPTeamsFound = true; 5680 if (auto *CS = dyn_cast<CompoundStmt>(S)) { 5681 auto I = CS->body_begin(); 5682 while (I != CS->body_end()) { 5683 auto *OED = dyn_cast<OMPExecutableDirective>(*I); 5684 if (!OED || !isOpenMPTeamsDirective(OED->getDirectiveKind())) { 5685 OMPTeamsFound = false; 5686 break; 5687 } 5688 ++I; 5689 } 5690 assert(I != CS->body_end() && "Not found statement"); 5691 S = *I; 5692 } else { 5693 auto *OED = dyn_cast<OMPExecutableDirective>(S); 5694 OMPTeamsFound = OED && isOpenMPTeamsDirective(OED->getDirectiveKind()); 5695 } 5696 if (!OMPTeamsFound) { 5697 Diag(StartLoc, diag::err_omp_target_contains_not_only_teams); 5698 Diag(DSAStack->getInnerTeamsRegionLoc(), 5699 diag::note_omp_nested_teams_construct_here); 5700 Diag(S->getLocStart(), diag::note_omp_nested_statement_here) 5701 << isa<OMPExecutableDirective>(S); 5702 return StmtError(); 5703 } 5704 } 5705 5706 getCurFunction()->setHasBranchProtectedScope(); 5707 5708 return OMPTargetDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt); 5709 } 5710 5711 StmtResult 5712 Sema::ActOnOpenMPTargetParallelDirective(ArrayRef<OMPClause *> Clauses, 5713 Stmt *AStmt, SourceLocation StartLoc, 5714 SourceLocation EndLoc) { 5715 if (!AStmt) 5716 return StmtError(); 5717 5718 CapturedStmt *CS = cast<CapturedStmt>(AStmt); 5719 // 1.2.2 OpenMP Language Terminology 5720 // Structured block - An executable statement with a single entry at the 5721 // top and a single exit at the bottom. 5722 // The point of exit cannot be a branch out of the structured block. 5723 // longjmp() and throw() must not violate the entry/exit criteria. 5724 CS->getCapturedDecl()->setNothrow(); 5725 5726 getCurFunction()->setHasBranchProtectedScope(); 5727 5728 return OMPTargetParallelDirective::Create(Context, StartLoc, EndLoc, Clauses, 5729 AStmt); 5730 } 5731 5732 StmtResult Sema::ActOnOpenMPTargetParallelForDirective( 5733 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, 5734 SourceLocation EndLoc, 5735 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) { 5736 if (!AStmt) 5737 return StmtError(); 5738 5739 CapturedStmt *CS = cast<CapturedStmt>(AStmt); 5740 // 1.2.2 OpenMP Language Terminology 5741 // Structured block - An executable statement with a single entry at the 5742 // top and a single exit at the bottom. 5743 // The point of exit cannot be a branch out of the structured block. 5744 // longjmp() and throw() must not violate the entry/exit criteria. 5745 CS->getCapturedDecl()->setNothrow(); 5746 5747 OMPLoopDirective::HelperExprs B; 5748 // In presence of clause 'collapse' or 'ordered' with number of loops, it will 5749 // define the nested loops number. 5750 unsigned NestedLoopCount = 5751 CheckOpenMPLoop(OMPD_target_parallel_for, getCollapseNumberExpr(Clauses), 5752 getOrderedNumberExpr(Clauses), AStmt, *this, *DSAStack, 5753 VarsWithImplicitDSA, B); 5754 if (NestedLoopCount == 0) 5755 return StmtError(); 5756 5757 assert((CurContext->isDependentContext() || B.builtAll()) && 5758 "omp target parallel for loop exprs were not built"); 5759 5760 if (!CurContext->isDependentContext()) { 5761 // Finalize the clauses that need pre-built expressions for CodeGen. 5762 for (auto C : Clauses) { 5763 if (auto *LC = dyn_cast<OMPLinearClause>(C)) 5764 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef), 5765 B.NumIterations, *this, CurScope, 5766 DSAStack)) 5767 return StmtError(); 5768 } 5769 } 5770 5771 getCurFunction()->setHasBranchProtectedScope(); 5772 return OMPTargetParallelForDirective::Create(Context, StartLoc, EndLoc, 5773 NestedLoopCount, Clauses, AStmt, 5774 B, DSAStack->isCancelRegion()); 5775 } 5776 5777 /// \brief Check for existence of a map clause in the list of clauses. 5778 static bool HasMapClause(ArrayRef<OMPClause *> Clauses) { 5779 for (ArrayRef<OMPClause *>::iterator I = Clauses.begin(), E = Clauses.end(); 5780 I != E; ++I) { 5781 if (*I != nullptr && (*I)->getClauseKind() == OMPC_map) { 5782 return true; 5783 } 5784 } 5785 5786 return false; 5787 } 5788 5789 StmtResult Sema::ActOnOpenMPTargetDataDirective(ArrayRef<OMPClause *> Clauses, 5790 Stmt *AStmt, 5791 SourceLocation StartLoc, 5792 SourceLocation EndLoc) { 5793 if (!AStmt) 5794 return StmtError(); 5795 5796 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected"); 5797 5798 // OpenMP [2.10.1, Restrictions, p. 97] 5799 // At least one map clause must appear on the directive. 5800 if (!HasMapClause(Clauses)) { 5801 Diag(StartLoc, diag::err_omp_no_map_for_directive) 5802 << getOpenMPDirectiveName(OMPD_target_data); 5803 return StmtError(); 5804 } 5805 5806 getCurFunction()->setHasBranchProtectedScope(); 5807 5808 return OMPTargetDataDirective::Create(Context, StartLoc, EndLoc, Clauses, 5809 AStmt); 5810 } 5811 5812 StmtResult 5813 Sema::ActOnOpenMPTargetEnterDataDirective(ArrayRef<OMPClause *> Clauses, 5814 SourceLocation StartLoc, 5815 SourceLocation EndLoc) { 5816 // OpenMP [2.10.2, Restrictions, p. 99] 5817 // At least one map clause must appear on the directive. 5818 if (!HasMapClause(Clauses)) { 5819 Diag(StartLoc, diag::err_omp_no_map_for_directive) 5820 << getOpenMPDirectiveName(OMPD_target_enter_data); 5821 return StmtError(); 5822 } 5823 5824 return OMPTargetEnterDataDirective::Create(Context, StartLoc, EndLoc, 5825 Clauses); 5826 } 5827 5828 StmtResult 5829 Sema::ActOnOpenMPTargetExitDataDirective(ArrayRef<OMPClause *> Clauses, 5830 SourceLocation StartLoc, 5831 SourceLocation EndLoc) { 5832 // OpenMP [2.10.3, Restrictions, p. 102] 5833 // At least one map clause must appear on the directive. 5834 if (!HasMapClause(Clauses)) { 5835 Diag(StartLoc, diag::err_omp_no_map_for_directive) 5836 << getOpenMPDirectiveName(OMPD_target_exit_data); 5837 return StmtError(); 5838 } 5839 5840 return OMPTargetExitDataDirective::Create(Context, StartLoc, EndLoc, Clauses); 5841 } 5842 5843 StmtResult Sema::ActOnOpenMPTargetUpdateDirective(ArrayRef<OMPClause *> Clauses, 5844 SourceLocation StartLoc, 5845 SourceLocation EndLoc) { 5846 bool seenMotionClause = false; 5847 for (auto *C : Clauses) { 5848 if (C->getClauseKind() == OMPC_to || C->getClauseKind() == OMPC_from) 5849 seenMotionClause = true; 5850 } 5851 if (!seenMotionClause) { 5852 Diag(StartLoc, diag::err_omp_at_least_one_motion_clause_required); 5853 return StmtError(); 5854 } 5855 return OMPTargetUpdateDirective::Create(Context, StartLoc, EndLoc, Clauses); 5856 } 5857 5858 StmtResult Sema::ActOnOpenMPTeamsDirective(ArrayRef<OMPClause *> Clauses, 5859 Stmt *AStmt, SourceLocation StartLoc, 5860 SourceLocation EndLoc) { 5861 if (!AStmt) 5862 return StmtError(); 5863 5864 CapturedStmt *CS = cast<CapturedStmt>(AStmt); 5865 // 1.2.2 OpenMP Language Terminology 5866 // Structured block - An executable statement with a single entry at the 5867 // top and a single exit at the bottom. 5868 // The point of exit cannot be a branch out of the structured block. 5869 // longjmp() and throw() must not violate the entry/exit criteria. 5870 CS->getCapturedDecl()->setNothrow(); 5871 5872 getCurFunction()->setHasBranchProtectedScope(); 5873 5874 return OMPTeamsDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt); 5875 } 5876 5877 StmtResult 5878 Sema::ActOnOpenMPCancellationPointDirective(SourceLocation StartLoc, 5879 SourceLocation EndLoc, 5880 OpenMPDirectiveKind CancelRegion) { 5881 if (DSAStack->isParentNowaitRegion()) { 5882 Diag(StartLoc, diag::err_omp_parent_cancel_region_nowait) << 0; 5883 return StmtError(); 5884 } 5885 if (DSAStack->isParentOrderedRegion()) { 5886 Diag(StartLoc, diag::err_omp_parent_cancel_region_ordered) << 0; 5887 return StmtError(); 5888 } 5889 return OMPCancellationPointDirective::Create(Context, StartLoc, EndLoc, 5890 CancelRegion); 5891 } 5892 5893 StmtResult Sema::ActOnOpenMPCancelDirective(ArrayRef<OMPClause *> Clauses, 5894 SourceLocation StartLoc, 5895 SourceLocation EndLoc, 5896 OpenMPDirectiveKind CancelRegion) { 5897 if (DSAStack->isParentNowaitRegion()) { 5898 Diag(StartLoc, diag::err_omp_parent_cancel_region_nowait) << 1; 5899 return StmtError(); 5900 } 5901 if (DSAStack->isParentOrderedRegion()) { 5902 Diag(StartLoc, diag::err_omp_parent_cancel_region_ordered) << 1; 5903 return StmtError(); 5904 } 5905 DSAStack->setParentCancelRegion(/*Cancel=*/true); 5906 return OMPCancelDirective::Create(Context, StartLoc, EndLoc, Clauses, 5907 CancelRegion); 5908 } 5909 5910 static bool checkGrainsizeNumTasksClauses(Sema &S, 5911 ArrayRef<OMPClause *> Clauses) { 5912 OMPClause *PrevClause = nullptr; 5913 bool ErrorFound = false; 5914 for (auto *C : Clauses) { 5915 if (C->getClauseKind() == OMPC_grainsize || 5916 C->getClauseKind() == OMPC_num_tasks) { 5917 if (!PrevClause) 5918 PrevClause = C; 5919 else if (PrevClause->getClauseKind() != C->getClauseKind()) { 5920 S.Diag(C->getLocStart(), 5921 diag::err_omp_grainsize_num_tasks_mutually_exclusive) 5922 << getOpenMPClauseName(C->getClauseKind()) 5923 << getOpenMPClauseName(PrevClause->getClauseKind()); 5924 S.Diag(PrevClause->getLocStart(), 5925 diag::note_omp_previous_grainsize_num_tasks) 5926 << getOpenMPClauseName(PrevClause->getClauseKind()); 5927 ErrorFound = true; 5928 } 5929 } 5930 } 5931 return ErrorFound; 5932 } 5933 5934 StmtResult Sema::ActOnOpenMPTaskLoopDirective( 5935 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, 5936 SourceLocation EndLoc, 5937 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) { 5938 if (!AStmt) 5939 return StmtError(); 5940 5941 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected"); 5942 OMPLoopDirective::HelperExprs B; 5943 // In presence of clause 'collapse' or 'ordered' with number of loops, it will 5944 // define the nested loops number. 5945 unsigned NestedLoopCount = 5946 CheckOpenMPLoop(OMPD_taskloop, getCollapseNumberExpr(Clauses), 5947 /*OrderedLoopCountExpr=*/nullptr, AStmt, *this, *DSAStack, 5948 VarsWithImplicitDSA, B); 5949 if (NestedLoopCount == 0) 5950 return StmtError(); 5951 5952 assert((CurContext->isDependentContext() || B.builtAll()) && 5953 "omp for loop exprs were not built"); 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 OMPTaskLoopDirective::Create(Context, StartLoc, EndLoc, 5963 NestedLoopCount, Clauses, AStmt, B); 5964 } 5965 5966 StmtResult Sema::ActOnOpenMPTaskLoopSimdDirective( 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' or 'ordered' with number of loops, it will 5976 // define the nested loops number. 5977 unsigned NestedLoopCount = 5978 CheckOpenMPLoop(OMPD_taskloop_simd, getCollapseNumberExpr(Clauses), 5979 /*OrderedLoopCountExpr=*/nullptr, AStmt, *this, *DSAStack, 5980 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 if (!CurContext->isDependentContext()) { 5988 // Finalize the clauses that need pre-built expressions for CodeGen. 5989 for (auto C : Clauses) { 5990 if (auto *LC = dyn_cast<OMPLinearClause>(C)) 5991 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef), 5992 B.NumIterations, *this, CurScope, 5993 DSAStack)) 5994 return StmtError(); 5995 } 5996 } 5997 5998 // OpenMP, [2.9.2 taskloop Construct, Restrictions] 5999 // The grainsize clause and num_tasks clause are mutually exclusive and may 6000 // not appear on the same taskloop directive. 6001 if (checkGrainsizeNumTasksClauses(*this, Clauses)) 6002 return StmtError(); 6003 6004 getCurFunction()->setHasBranchProtectedScope(); 6005 return OMPTaskLoopSimdDirective::Create(Context, StartLoc, EndLoc, 6006 NestedLoopCount, Clauses, AStmt, B); 6007 } 6008 6009 StmtResult Sema::ActOnOpenMPDistributeDirective( 6010 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, 6011 SourceLocation EndLoc, 6012 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) { 6013 if (!AStmt) 6014 return StmtError(); 6015 6016 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected"); 6017 OMPLoopDirective::HelperExprs B; 6018 // In presence of clause 'collapse' with number of loops, it will 6019 // define the nested loops number. 6020 unsigned NestedLoopCount = 6021 CheckOpenMPLoop(OMPD_distribute, getCollapseNumberExpr(Clauses), 6022 nullptr /*ordered not a clause on distribute*/, AStmt, 6023 *this, *DSAStack, VarsWithImplicitDSA, B); 6024 if (NestedLoopCount == 0) 6025 return StmtError(); 6026 6027 assert((CurContext->isDependentContext() || B.builtAll()) && 6028 "omp for loop exprs were not built"); 6029 6030 getCurFunction()->setHasBranchProtectedScope(); 6031 return OMPDistributeDirective::Create(Context, StartLoc, EndLoc, 6032 NestedLoopCount, Clauses, AStmt, B); 6033 } 6034 6035 StmtResult Sema::ActOnOpenMPDistributeParallelForDirective( 6036 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, 6037 SourceLocation EndLoc, 6038 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) { 6039 if (!AStmt) 6040 return StmtError(); 6041 6042 CapturedStmt *CS = cast<CapturedStmt>(AStmt); 6043 // 1.2.2 OpenMP Language Terminology 6044 // Structured block - An executable statement with a single entry at the 6045 // top and a single exit at the bottom. 6046 // The point of exit cannot be a branch out of the structured block. 6047 // longjmp() and throw() must not violate the entry/exit criteria. 6048 CS->getCapturedDecl()->setNothrow(); 6049 6050 OMPLoopDirective::HelperExprs B; 6051 // In presence of clause 'collapse' with number of loops, it will 6052 // define the nested loops number. 6053 unsigned NestedLoopCount = CheckOpenMPLoop( 6054 OMPD_distribute_parallel_for, getCollapseNumberExpr(Clauses), 6055 nullptr /*ordered not a clause on distribute*/, AStmt, *this, *DSAStack, 6056 VarsWithImplicitDSA, B); 6057 if (NestedLoopCount == 0) 6058 return StmtError(); 6059 6060 assert((CurContext->isDependentContext() || B.builtAll()) && 6061 "omp for loop exprs were not built"); 6062 6063 getCurFunction()->setHasBranchProtectedScope(); 6064 return OMPDistributeParallelForDirective::Create( 6065 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B); 6066 } 6067 6068 StmtResult Sema::ActOnOpenMPDistributeParallelForSimdDirective( 6069 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, 6070 SourceLocation EndLoc, 6071 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) { 6072 if (!AStmt) 6073 return StmtError(); 6074 6075 CapturedStmt *CS = cast<CapturedStmt>(AStmt); 6076 // 1.2.2 OpenMP Language Terminology 6077 // Structured block - An executable statement with a single entry at the 6078 // top and a single exit at the bottom. 6079 // The point of exit cannot be a branch out of the structured block. 6080 // longjmp() and throw() must not violate the entry/exit criteria. 6081 CS->getCapturedDecl()->setNothrow(); 6082 6083 OMPLoopDirective::HelperExprs B; 6084 // In presence of clause 'collapse' with number of loops, it will 6085 // define the nested loops number. 6086 unsigned NestedLoopCount = CheckOpenMPLoop( 6087 OMPD_distribute_parallel_for_simd, getCollapseNumberExpr(Clauses), 6088 nullptr /*ordered not a clause on distribute*/, AStmt, *this, *DSAStack, 6089 VarsWithImplicitDSA, B); 6090 if (NestedLoopCount == 0) 6091 return StmtError(); 6092 6093 assert((CurContext->isDependentContext() || B.builtAll()) && 6094 "omp for loop exprs were not built"); 6095 6096 if (checkSimdlenSafelenSpecified(*this, Clauses)) 6097 return StmtError(); 6098 6099 getCurFunction()->setHasBranchProtectedScope(); 6100 return OMPDistributeParallelForSimdDirective::Create( 6101 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B); 6102 } 6103 6104 StmtResult Sema::ActOnOpenMPDistributeSimdDirective( 6105 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, 6106 SourceLocation EndLoc, 6107 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) { 6108 if (!AStmt) 6109 return StmtError(); 6110 6111 CapturedStmt *CS = cast<CapturedStmt>(AStmt); 6112 // 1.2.2 OpenMP Language Terminology 6113 // Structured block - An executable statement with a single entry at the 6114 // top and a single exit at the bottom. 6115 // The point of exit cannot be a branch out of the structured block. 6116 // longjmp() and throw() must not violate the entry/exit criteria. 6117 CS->getCapturedDecl()->setNothrow(); 6118 6119 OMPLoopDirective::HelperExprs B; 6120 // In presence of clause 'collapse' with number of loops, it will 6121 // define the nested loops number. 6122 unsigned NestedLoopCount = 6123 CheckOpenMPLoop(OMPD_distribute_simd, getCollapseNumberExpr(Clauses), 6124 nullptr /*ordered not a clause on distribute*/, AStmt, 6125 *this, *DSAStack, VarsWithImplicitDSA, B); 6126 if (NestedLoopCount == 0) 6127 return StmtError(); 6128 6129 assert((CurContext->isDependentContext() || B.builtAll()) && 6130 "omp for loop exprs were not built"); 6131 6132 if (checkSimdlenSafelenSpecified(*this, Clauses)) 6133 return StmtError(); 6134 6135 getCurFunction()->setHasBranchProtectedScope(); 6136 return OMPDistributeSimdDirective::Create(Context, StartLoc, EndLoc, 6137 NestedLoopCount, Clauses, AStmt, B); 6138 } 6139 6140 StmtResult Sema::ActOnOpenMPTargetParallelForSimdDirective( 6141 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, 6142 SourceLocation EndLoc, 6143 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) { 6144 if (!AStmt) 6145 return StmtError(); 6146 6147 CapturedStmt *CS = cast<CapturedStmt>(AStmt); 6148 // 1.2.2 OpenMP Language Terminology 6149 // Structured block - An executable statement with a single entry at the 6150 // top and a single exit at the bottom. 6151 // The point of exit cannot be a branch out of the structured block. 6152 // longjmp() and throw() must not violate the entry/exit criteria. 6153 CS->getCapturedDecl()->setNothrow(); 6154 6155 OMPLoopDirective::HelperExprs B; 6156 // In presence of clause 'collapse' or 'ordered' with number of loops, it will 6157 // define the nested loops number. 6158 unsigned NestedLoopCount = CheckOpenMPLoop( 6159 OMPD_target_parallel_for_simd, getCollapseNumberExpr(Clauses), 6160 getOrderedNumberExpr(Clauses), AStmt, *this, *DSAStack, 6161 VarsWithImplicitDSA, B); 6162 if (NestedLoopCount == 0) 6163 return StmtError(); 6164 6165 assert((CurContext->isDependentContext() || B.builtAll()) && 6166 "omp target parallel for simd loop exprs were not built"); 6167 6168 if (!CurContext->isDependentContext()) { 6169 // Finalize the clauses that need pre-built expressions for CodeGen. 6170 for (auto C : Clauses) { 6171 if (auto *LC = dyn_cast<OMPLinearClause>(C)) 6172 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef), 6173 B.NumIterations, *this, CurScope, 6174 DSAStack)) 6175 return StmtError(); 6176 } 6177 } 6178 if (checkSimdlenSafelenSpecified(*this, Clauses)) 6179 return StmtError(); 6180 6181 getCurFunction()->setHasBranchProtectedScope(); 6182 return OMPTargetParallelForSimdDirective::Create( 6183 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B); 6184 } 6185 6186 StmtResult Sema::ActOnOpenMPTargetSimdDirective( 6187 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, 6188 SourceLocation EndLoc, 6189 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) { 6190 if (!AStmt) 6191 return StmtError(); 6192 6193 CapturedStmt *CS = cast<CapturedStmt>(AStmt); 6194 // 1.2.2 OpenMP Language Terminology 6195 // Structured block - An executable statement with a single entry at the 6196 // top and a single exit at the bottom. 6197 // The point of exit cannot be a branch out of the structured block. 6198 // longjmp() and throw() must not violate the entry/exit criteria. 6199 CS->getCapturedDecl()->setNothrow(); 6200 6201 OMPLoopDirective::HelperExprs B; 6202 // In presence of clause 'collapse' with number of loops, it will define the 6203 // nested loops number. 6204 unsigned NestedLoopCount = 6205 CheckOpenMPLoop(OMPD_target_simd, getCollapseNumberExpr(Clauses), 6206 getOrderedNumberExpr(Clauses), AStmt, *this, *DSAStack, 6207 VarsWithImplicitDSA, B); 6208 if (NestedLoopCount == 0) 6209 return StmtError(); 6210 6211 assert((CurContext->isDependentContext() || B.builtAll()) && 6212 "omp target simd loop exprs were not built"); 6213 6214 if (!CurContext->isDependentContext()) { 6215 // Finalize the clauses that need pre-built expressions for CodeGen. 6216 for (auto C : Clauses) { 6217 if (auto *LC = dyn_cast<OMPLinearClause>(C)) 6218 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef), 6219 B.NumIterations, *this, CurScope, 6220 DSAStack)) 6221 return StmtError(); 6222 } 6223 } 6224 6225 if (checkSimdlenSafelenSpecified(*this, Clauses)) 6226 return StmtError(); 6227 6228 getCurFunction()->setHasBranchProtectedScope(); 6229 return OMPTargetSimdDirective::Create(Context, StartLoc, EndLoc, 6230 NestedLoopCount, Clauses, AStmt, B); 6231 } 6232 6233 StmtResult Sema::ActOnOpenMPTeamsDistributeDirective( 6234 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, 6235 SourceLocation EndLoc, 6236 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) { 6237 if (!AStmt) 6238 return StmtError(); 6239 6240 CapturedStmt *CS = cast<CapturedStmt>(AStmt); 6241 // 1.2.2 OpenMP Language Terminology 6242 // Structured block - An executable statement with a single entry at the 6243 // top and a single exit at the bottom. 6244 // The point of exit cannot be a branch out of the structured block. 6245 // longjmp() and throw() must not violate the entry/exit criteria. 6246 CS->getCapturedDecl()->setNothrow(); 6247 6248 OMPLoopDirective::HelperExprs B; 6249 // In presence of clause 'collapse' with number of loops, it will 6250 // define the nested loops number. 6251 unsigned NestedLoopCount = 6252 CheckOpenMPLoop(OMPD_teams_distribute, getCollapseNumberExpr(Clauses), 6253 nullptr /*ordered not a clause on distribute*/, AStmt, 6254 *this, *DSAStack, VarsWithImplicitDSA, B); 6255 if (NestedLoopCount == 0) 6256 return StmtError(); 6257 6258 assert((CurContext->isDependentContext() || B.builtAll()) && 6259 "omp teams distribute loop exprs were not built"); 6260 6261 getCurFunction()->setHasBranchProtectedScope(); 6262 return OMPTeamsDistributeDirective::Create( 6263 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B); 6264 } 6265 6266 StmtResult Sema::ActOnOpenMPTeamsDistributeSimdDirective( 6267 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, 6268 SourceLocation EndLoc, 6269 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) { 6270 if (!AStmt) 6271 return StmtError(); 6272 6273 CapturedStmt *CS = cast<CapturedStmt>(AStmt); 6274 // 1.2.2 OpenMP Language Terminology 6275 // Structured block - An executable statement with a single entry at the 6276 // top and a single exit at the bottom. 6277 // The point of exit cannot be a branch out of the structured block. 6278 // longjmp() and throw() must not violate the entry/exit criteria. 6279 CS->getCapturedDecl()->setNothrow(); 6280 6281 OMPLoopDirective::HelperExprs B; 6282 // In presence of clause 'collapse' with number of loops, it will 6283 // define the nested loops number. 6284 unsigned NestedLoopCount = CheckOpenMPLoop( 6285 OMPD_teams_distribute_simd, getCollapseNumberExpr(Clauses), 6286 nullptr /*ordered not a clause on distribute*/, AStmt, *this, *DSAStack, 6287 VarsWithImplicitDSA, B); 6288 6289 if (NestedLoopCount == 0) 6290 return StmtError(); 6291 6292 assert((CurContext->isDependentContext() || B.builtAll()) && 6293 "omp teams distribute simd loop exprs were not built"); 6294 6295 if (!CurContext->isDependentContext()) { 6296 // Finalize the clauses that need pre-built expressions for CodeGen. 6297 for (auto C : Clauses) { 6298 if (auto *LC = dyn_cast<OMPLinearClause>(C)) 6299 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef), 6300 B.NumIterations, *this, CurScope, 6301 DSAStack)) 6302 return StmtError(); 6303 } 6304 } 6305 6306 if (checkSimdlenSafelenSpecified(*this, Clauses)) 6307 return StmtError(); 6308 6309 getCurFunction()->setHasBranchProtectedScope(); 6310 return OMPTeamsDistributeSimdDirective::Create( 6311 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B); 6312 } 6313 6314 StmtResult Sema::ActOnOpenMPTeamsDistributeParallelForSimdDirective( 6315 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, 6316 SourceLocation EndLoc, 6317 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) { 6318 if (!AStmt) 6319 return StmtError(); 6320 6321 CapturedStmt *CS = cast<CapturedStmt>(AStmt); 6322 // 1.2.2 OpenMP Language Terminology 6323 // Structured block - An executable statement with a single entry at the 6324 // top and a single exit at the bottom. 6325 // The point of exit cannot be a branch out of the structured block. 6326 // longjmp() and throw() must not violate the entry/exit criteria. 6327 CS->getCapturedDecl()->setNothrow(); 6328 6329 OMPLoopDirective::HelperExprs B; 6330 // In presence of clause 'collapse' with number of loops, it will 6331 // define the nested loops number. 6332 auto NestedLoopCount = CheckOpenMPLoop( 6333 OMPD_teams_distribute_parallel_for_simd, getCollapseNumberExpr(Clauses), 6334 nullptr /*ordered not a clause on distribute*/, AStmt, *this, *DSAStack, 6335 VarsWithImplicitDSA, B); 6336 6337 if (NestedLoopCount == 0) 6338 return StmtError(); 6339 6340 assert((CurContext->isDependentContext() || B.builtAll()) && 6341 "omp for loop exprs were not built"); 6342 6343 if (!CurContext->isDependentContext()) { 6344 // Finalize the clauses that need pre-built expressions for CodeGen. 6345 for (auto C : Clauses) { 6346 if (auto *LC = dyn_cast<OMPLinearClause>(C)) 6347 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef), 6348 B.NumIterations, *this, CurScope, 6349 DSAStack)) 6350 return StmtError(); 6351 } 6352 } 6353 6354 if (checkSimdlenSafelenSpecified(*this, Clauses)) 6355 return StmtError(); 6356 6357 getCurFunction()->setHasBranchProtectedScope(); 6358 return OMPTeamsDistributeParallelForSimdDirective::Create( 6359 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B); 6360 } 6361 6362 StmtResult Sema::ActOnOpenMPTeamsDistributeParallelForDirective( 6363 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, 6364 SourceLocation EndLoc, 6365 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) { 6366 if (!AStmt) 6367 return StmtError(); 6368 6369 CapturedStmt *CS = cast<CapturedStmt>(AStmt); 6370 // 1.2.2 OpenMP Language Terminology 6371 // Structured block - An executable statement with a single entry at the 6372 // top and a single exit at the bottom. 6373 // The point of exit cannot be a branch out of the structured block. 6374 // longjmp() and throw() must not violate the entry/exit criteria. 6375 CS->getCapturedDecl()->setNothrow(); 6376 6377 OMPLoopDirective::HelperExprs B; 6378 // In presence of clause 'collapse' with number of loops, it will 6379 // define the nested loops number. 6380 unsigned NestedLoopCount = CheckOpenMPLoop( 6381 OMPD_teams_distribute_parallel_for, getCollapseNumberExpr(Clauses), 6382 nullptr /*ordered not a clause on distribute*/, AStmt, *this, *DSAStack, 6383 VarsWithImplicitDSA, B); 6384 6385 if (NestedLoopCount == 0) 6386 return StmtError(); 6387 6388 assert((CurContext->isDependentContext() || B.builtAll()) && 6389 "omp for loop exprs were not built"); 6390 6391 if (!CurContext->isDependentContext()) { 6392 // Finalize the clauses that need pre-built expressions for CodeGen. 6393 for (auto C : Clauses) { 6394 if (auto *LC = dyn_cast<OMPLinearClause>(C)) 6395 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef), 6396 B.NumIterations, *this, CurScope, 6397 DSAStack)) 6398 return StmtError(); 6399 } 6400 } 6401 6402 getCurFunction()->setHasBranchProtectedScope(); 6403 return OMPTeamsDistributeParallelForDirective::Create( 6404 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B); 6405 } 6406 6407 StmtResult Sema::ActOnOpenMPTargetTeamsDirective(ArrayRef<OMPClause *> Clauses, 6408 Stmt *AStmt, 6409 SourceLocation StartLoc, 6410 SourceLocation EndLoc) { 6411 if (!AStmt) 6412 return StmtError(); 6413 6414 CapturedStmt *CS = cast<CapturedStmt>(AStmt); 6415 // 1.2.2 OpenMP Language Terminology 6416 // Structured block - An executable statement with a single entry at the 6417 // top and a single exit at the bottom. 6418 // The point of exit cannot be a branch out of the structured block. 6419 // longjmp() and throw() must not violate the entry/exit criteria. 6420 CS->getCapturedDecl()->setNothrow(); 6421 6422 getCurFunction()->setHasBranchProtectedScope(); 6423 6424 return OMPTargetTeamsDirective::Create(Context, StartLoc, EndLoc, Clauses, 6425 AStmt); 6426 } 6427 6428 StmtResult Sema::ActOnOpenMPTargetTeamsDistributeDirective( 6429 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, 6430 SourceLocation EndLoc, 6431 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) { 6432 if (!AStmt) 6433 return StmtError(); 6434 6435 CapturedStmt *CS = cast<CapturedStmt>(AStmt); 6436 // 1.2.2 OpenMP Language Terminology 6437 // Structured block - An executable statement with a single entry at the 6438 // top and a single exit at the bottom. 6439 // The point of exit cannot be a branch out of the structured block. 6440 // longjmp() and throw() must not violate the entry/exit criteria. 6441 CS->getCapturedDecl()->setNothrow(); 6442 6443 OMPLoopDirective::HelperExprs B; 6444 // In presence of clause 'collapse' with number of loops, it will 6445 // define the nested loops number. 6446 auto NestedLoopCount = CheckOpenMPLoop( 6447 OMPD_target_teams_distribute, 6448 getCollapseNumberExpr(Clauses), 6449 nullptr /*ordered not a clause on distribute*/, AStmt, *this, *DSAStack, 6450 VarsWithImplicitDSA, B); 6451 if (NestedLoopCount == 0) 6452 return StmtError(); 6453 6454 assert((CurContext->isDependentContext() || B.builtAll()) && 6455 "omp target teams distribute loop exprs were not built"); 6456 6457 getCurFunction()->setHasBranchProtectedScope(); 6458 return OMPTargetTeamsDistributeDirective::Create( 6459 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B); 6460 } 6461 6462 StmtResult Sema::ActOnOpenMPTargetTeamsDistributeParallelForDirective( 6463 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, 6464 SourceLocation EndLoc, 6465 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) { 6466 if (!AStmt) 6467 return StmtError(); 6468 6469 CapturedStmt *CS = cast<CapturedStmt>(AStmt); 6470 // 1.2.2 OpenMP Language Terminology 6471 // Structured block - An executable statement with a single entry at the 6472 // top and a single exit at the bottom. 6473 // The point of exit cannot be a branch out of the structured block. 6474 // longjmp() and throw() must not violate the entry/exit criteria. 6475 CS->getCapturedDecl()->setNothrow(); 6476 6477 OMPLoopDirective::HelperExprs B; 6478 // In presence of clause 'collapse' with number of loops, it will 6479 // define the nested loops number. 6480 auto NestedLoopCount = CheckOpenMPLoop( 6481 OMPD_target_teams_distribute_parallel_for, 6482 getCollapseNumberExpr(Clauses), 6483 nullptr /*ordered not a clause on distribute*/, AStmt, *this, *DSAStack, 6484 VarsWithImplicitDSA, B); 6485 if (NestedLoopCount == 0) 6486 return StmtError(); 6487 6488 assert((CurContext->isDependentContext() || B.builtAll()) && 6489 "omp target teams distribute parallel for loop exprs were not built"); 6490 6491 if (!CurContext->isDependentContext()) { 6492 // Finalize the clauses that need pre-built expressions for CodeGen. 6493 for (auto C : Clauses) { 6494 if (auto *LC = dyn_cast<OMPLinearClause>(C)) 6495 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef), 6496 B.NumIterations, *this, CurScope, 6497 DSAStack)) 6498 return StmtError(); 6499 } 6500 } 6501 6502 getCurFunction()->setHasBranchProtectedScope(); 6503 return OMPTargetTeamsDistributeParallelForDirective::Create( 6504 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B); 6505 } 6506 6507 StmtResult Sema::ActOnOpenMPTargetTeamsDistributeParallelForSimdDirective( 6508 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, 6509 SourceLocation EndLoc, 6510 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) { 6511 if (!AStmt) 6512 return StmtError(); 6513 6514 CapturedStmt *CS = cast<CapturedStmt>(AStmt); 6515 // 1.2.2 OpenMP Language Terminology 6516 // Structured block - An executable statement with a single entry at the 6517 // top and a single exit at the bottom. 6518 // The point of exit cannot be a branch out of the structured block. 6519 // longjmp() and throw() must not violate the entry/exit criteria. 6520 CS->getCapturedDecl()->setNothrow(); 6521 6522 OMPLoopDirective::HelperExprs B; 6523 // In presence of clause 'collapse' with number of loops, it will 6524 // define the nested loops number. 6525 auto NestedLoopCount = CheckOpenMPLoop( 6526 OMPD_target_teams_distribute_parallel_for_simd, 6527 getCollapseNumberExpr(Clauses), 6528 nullptr /*ordered not a clause on distribute*/, AStmt, *this, *DSAStack, 6529 VarsWithImplicitDSA, B); 6530 if (NestedLoopCount == 0) 6531 return StmtError(); 6532 6533 assert((CurContext->isDependentContext() || B.builtAll()) && 6534 "omp target teams distribute parallel for simd loop exprs were not " 6535 "built"); 6536 6537 if (!CurContext->isDependentContext()) { 6538 // Finalize the clauses that need pre-built expressions for CodeGen. 6539 for (auto C : Clauses) { 6540 if (auto *LC = dyn_cast<OMPLinearClause>(C)) 6541 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef), 6542 B.NumIterations, *this, CurScope, 6543 DSAStack)) 6544 return StmtError(); 6545 } 6546 } 6547 6548 getCurFunction()->setHasBranchProtectedScope(); 6549 return OMPTargetTeamsDistributeParallelForSimdDirective::Create( 6550 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B); 6551 } 6552 6553 StmtResult Sema::ActOnOpenMPTargetTeamsDistributeSimdDirective( 6554 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, 6555 SourceLocation EndLoc, 6556 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) { 6557 if (!AStmt) 6558 return StmtError(); 6559 6560 auto *CS = cast<CapturedStmt>(AStmt); 6561 // 1.2.2 OpenMP Language Terminology 6562 // Structured block - An executable statement with a single entry at the 6563 // top and a single exit at the bottom. 6564 // The point of exit cannot be a branch out of the structured block. 6565 // longjmp() and throw() must not violate the entry/exit criteria. 6566 CS->getCapturedDecl()->setNothrow(); 6567 6568 OMPLoopDirective::HelperExprs B; 6569 // In presence of clause 'collapse' with number of loops, it will 6570 // define the nested loops number. 6571 auto NestedLoopCount = CheckOpenMPLoop( 6572 OMPD_target_teams_distribute_simd, getCollapseNumberExpr(Clauses), 6573 nullptr /*ordered not a clause on distribute*/, AStmt, *this, *DSAStack, 6574 VarsWithImplicitDSA, B); 6575 if (NestedLoopCount == 0) 6576 return StmtError(); 6577 6578 assert((CurContext->isDependentContext() || B.builtAll()) && 6579 "omp target teams distribute simd loop exprs were not built"); 6580 6581 getCurFunction()->setHasBranchProtectedScope(); 6582 return OMPTargetTeamsDistributeSimdDirective::Create( 6583 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B); 6584 } 6585 6586 OMPClause *Sema::ActOnOpenMPSingleExprClause(OpenMPClauseKind Kind, Expr *Expr, 6587 SourceLocation StartLoc, 6588 SourceLocation LParenLoc, 6589 SourceLocation EndLoc) { 6590 OMPClause *Res = nullptr; 6591 switch (Kind) { 6592 case OMPC_final: 6593 Res = ActOnOpenMPFinalClause(Expr, StartLoc, LParenLoc, EndLoc); 6594 break; 6595 case OMPC_num_threads: 6596 Res = ActOnOpenMPNumThreadsClause(Expr, StartLoc, LParenLoc, EndLoc); 6597 break; 6598 case OMPC_safelen: 6599 Res = ActOnOpenMPSafelenClause(Expr, StartLoc, LParenLoc, EndLoc); 6600 break; 6601 case OMPC_simdlen: 6602 Res = ActOnOpenMPSimdlenClause(Expr, StartLoc, LParenLoc, EndLoc); 6603 break; 6604 case OMPC_collapse: 6605 Res = ActOnOpenMPCollapseClause(Expr, StartLoc, LParenLoc, EndLoc); 6606 break; 6607 case OMPC_ordered: 6608 Res = ActOnOpenMPOrderedClause(StartLoc, EndLoc, LParenLoc, Expr); 6609 break; 6610 case OMPC_device: 6611 Res = ActOnOpenMPDeviceClause(Expr, StartLoc, LParenLoc, EndLoc); 6612 break; 6613 case OMPC_num_teams: 6614 Res = ActOnOpenMPNumTeamsClause(Expr, StartLoc, LParenLoc, EndLoc); 6615 break; 6616 case OMPC_thread_limit: 6617 Res = ActOnOpenMPThreadLimitClause(Expr, StartLoc, LParenLoc, EndLoc); 6618 break; 6619 case OMPC_priority: 6620 Res = ActOnOpenMPPriorityClause(Expr, StartLoc, LParenLoc, EndLoc); 6621 break; 6622 case OMPC_grainsize: 6623 Res = ActOnOpenMPGrainsizeClause(Expr, StartLoc, LParenLoc, EndLoc); 6624 break; 6625 case OMPC_num_tasks: 6626 Res = ActOnOpenMPNumTasksClause(Expr, StartLoc, LParenLoc, EndLoc); 6627 break; 6628 case OMPC_hint: 6629 Res = ActOnOpenMPHintClause(Expr, StartLoc, LParenLoc, EndLoc); 6630 break; 6631 case OMPC_if: 6632 case OMPC_default: 6633 case OMPC_proc_bind: 6634 case OMPC_schedule: 6635 case OMPC_private: 6636 case OMPC_firstprivate: 6637 case OMPC_lastprivate: 6638 case OMPC_shared: 6639 case OMPC_reduction: 6640 case OMPC_linear: 6641 case OMPC_aligned: 6642 case OMPC_copyin: 6643 case OMPC_copyprivate: 6644 case OMPC_nowait: 6645 case OMPC_untied: 6646 case OMPC_mergeable: 6647 case OMPC_threadprivate: 6648 case OMPC_flush: 6649 case OMPC_read: 6650 case OMPC_write: 6651 case OMPC_update: 6652 case OMPC_capture: 6653 case OMPC_seq_cst: 6654 case OMPC_depend: 6655 case OMPC_threads: 6656 case OMPC_simd: 6657 case OMPC_map: 6658 case OMPC_nogroup: 6659 case OMPC_dist_schedule: 6660 case OMPC_defaultmap: 6661 case OMPC_unknown: 6662 case OMPC_uniform: 6663 case OMPC_to: 6664 case OMPC_from: 6665 case OMPC_use_device_ptr: 6666 case OMPC_is_device_ptr: 6667 llvm_unreachable("Clause is not allowed."); 6668 } 6669 return Res; 6670 } 6671 6672 // An OpenMP directive such as 'target parallel' has two captured regions: 6673 // for the 'target' and 'parallel' respectively. This function returns 6674 // the region in which to capture expressions associated with a clause. 6675 // A return value of OMPD_unknown signifies that the expression should not 6676 // be captured. 6677 static OpenMPDirectiveKind getOpenMPCaptureRegionForClause( 6678 OpenMPDirectiveKind DKind, OpenMPClauseKind CKind, 6679 OpenMPDirectiveKind NameModifier = OMPD_unknown) { 6680 OpenMPDirectiveKind CaptureRegion = OMPD_unknown; 6681 6682 switch (CKind) { 6683 case OMPC_if: 6684 switch (DKind) { 6685 case OMPD_target_parallel: 6686 // If this clause applies to the nested 'parallel' region, capture within 6687 // the 'target' region, otherwise do not capture. 6688 if (NameModifier == OMPD_unknown || NameModifier == OMPD_parallel) 6689 CaptureRegion = OMPD_target; 6690 break; 6691 case OMPD_cancel: 6692 case OMPD_parallel: 6693 case OMPD_parallel_sections: 6694 case OMPD_parallel_for: 6695 case OMPD_parallel_for_simd: 6696 case OMPD_target: 6697 case OMPD_target_simd: 6698 case OMPD_target_parallel_for: 6699 case OMPD_target_parallel_for_simd: 6700 case OMPD_target_teams: 6701 case OMPD_target_teams_distribute: 6702 case OMPD_target_teams_distribute_simd: 6703 case OMPD_target_teams_distribute_parallel_for: 6704 case OMPD_target_teams_distribute_parallel_for_simd: 6705 case OMPD_teams_distribute_parallel_for: 6706 case OMPD_teams_distribute_parallel_for_simd: 6707 case OMPD_distribute_parallel_for: 6708 case OMPD_distribute_parallel_for_simd: 6709 case OMPD_task: 6710 case OMPD_taskloop: 6711 case OMPD_taskloop_simd: 6712 case OMPD_target_data: 6713 case OMPD_target_enter_data: 6714 case OMPD_target_exit_data: 6715 case OMPD_target_update: 6716 // Do not capture if-clause expressions. 6717 break; 6718 case OMPD_threadprivate: 6719 case OMPD_taskyield: 6720 case OMPD_barrier: 6721 case OMPD_taskwait: 6722 case OMPD_cancellation_point: 6723 case OMPD_flush: 6724 case OMPD_declare_reduction: 6725 case OMPD_declare_simd: 6726 case OMPD_declare_target: 6727 case OMPD_end_declare_target: 6728 case OMPD_teams: 6729 case OMPD_simd: 6730 case OMPD_for: 6731 case OMPD_for_simd: 6732 case OMPD_sections: 6733 case OMPD_section: 6734 case OMPD_single: 6735 case OMPD_master: 6736 case OMPD_critical: 6737 case OMPD_taskgroup: 6738 case OMPD_distribute: 6739 case OMPD_ordered: 6740 case OMPD_atomic: 6741 case OMPD_distribute_simd: 6742 case OMPD_teams_distribute: 6743 case OMPD_teams_distribute_simd: 6744 llvm_unreachable("Unexpected OpenMP directive with if-clause"); 6745 case OMPD_unknown: 6746 llvm_unreachable("Unknown OpenMP directive"); 6747 } 6748 break; 6749 case OMPC_num_threads: 6750 switch (DKind) { 6751 case OMPD_target_parallel: 6752 CaptureRegion = OMPD_target; 6753 break; 6754 case OMPD_cancel: 6755 case OMPD_parallel: 6756 case OMPD_parallel_sections: 6757 case OMPD_parallel_for: 6758 case OMPD_parallel_for_simd: 6759 case OMPD_target: 6760 case OMPD_target_simd: 6761 case OMPD_target_parallel_for: 6762 case OMPD_target_parallel_for_simd: 6763 case OMPD_target_teams: 6764 case OMPD_target_teams_distribute: 6765 case OMPD_target_teams_distribute_simd: 6766 case OMPD_target_teams_distribute_parallel_for: 6767 case OMPD_target_teams_distribute_parallel_for_simd: 6768 case OMPD_teams_distribute_parallel_for: 6769 case OMPD_teams_distribute_parallel_for_simd: 6770 case OMPD_distribute_parallel_for: 6771 case OMPD_distribute_parallel_for_simd: 6772 case OMPD_task: 6773 case OMPD_taskloop: 6774 case OMPD_taskloop_simd: 6775 case OMPD_target_data: 6776 case OMPD_target_enter_data: 6777 case OMPD_target_exit_data: 6778 case OMPD_target_update: 6779 // Do not capture num_threads-clause expressions. 6780 break; 6781 case OMPD_threadprivate: 6782 case OMPD_taskyield: 6783 case OMPD_barrier: 6784 case OMPD_taskwait: 6785 case OMPD_cancellation_point: 6786 case OMPD_flush: 6787 case OMPD_declare_reduction: 6788 case OMPD_declare_simd: 6789 case OMPD_declare_target: 6790 case OMPD_end_declare_target: 6791 case OMPD_teams: 6792 case OMPD_simd: 6793 case OMPD_for: 6794 case OMPD_for_simd: 6795 case OMPD_sections: 6796 case OMPD_section: 6797 case OMPD_single: 6798 case OMPD_master: 6799 case OMPD_critical: 6800 case OMPD_taskgroup: 6801 case OMPD_distribute: 6802 case OMPD_ordered: 6803 case OMPD_atomic: 6804 case OMPD_distribute_simd: 6805 case OMPD_teams_distribute: 6806 case OMPD_teams_distribute_simd: 6807 llvm_unreachable("Unexpected OpenMP directive with num_threads-clause"); 6808 case OMPD_unknown: 6809 llvm_unreachable("Unknown OpenMP directive"); 6810 } 6811 break; 6812 case OMPC_num_teams: 6813 switch (DKind) { 6814 case OMPD_target_teams: 6815 CaptureRegion = OMPD_target; 6816 break; 6817 case OMPD_cancel: 6818 case OMPD_parallel: 6819 case OMPD_parallel_sections: 6820 case OMPD_parallel_for: 6821 case OMPD_parallel_for_simd: 6822 case OMPD_target: 6823 case OMPD_target_simd: 6824 case OMPD_target_parallel: 6825 case OMPD_target_parallel_for: 6826 case OMPD_target_parallel_for_simd: 6827 case OMPD_target_teams_distribute: 6828 case OMPD_target_teams_distribute_simd: 6829 case OMPD_target_teams_distribute_parallel_for: 6830 case OMPD_target_teams_distribute_parallel_for_simd: 6831 case OMPD_teams_distribute_parallel_for: 6832 case OMPD_teams_distribute_parallel_for_simd: 6833 case OMPD_distribute_parallel_for: 6834 case OMPD_distribute_parallel_for_simd: 6835 case OMPD_task: 6836 case OMPD_taskloop: 6837 case OMPD_taskloop_simd: 6838 case OMPD_target_data: 6839 case OMPD_target_enter_data: 6840 case OMPD_target_exit_data: 6841 case OMPD_target_update: 6842 case OMPD_teams: 6843 case OMPD_teams_distribute: 6844 case OMPD_teams_distribute_simd: 6845 // Do not capture num_teams-clause expressions. 6846 break; 6847 case OMPD_threadprivate: 6848 case OMPD_taskyield: 6849 case OMPD_barrier: 6850 case OMPD_taskwait: 6851 case OMPD_cancellation_point: 6852 case OMPD_flush: 6853 case OMPD_declare_reduction: 6854 case OMPD_declare_simd: 6855 case OMPD_declare_target: 6856 case OMPD_end_declare_target: 6857 case OMPD_simd: 6858 case OMPD_for: 6859 case OMPD_for_simd: 6860 case OMPD_sections: 6861 case OMPD_section: 6862 case OMPD_single: 6863 case OMPD_master: 6864 case OMPD_critical: 6865 case OMPD_taskgroup: 6866 case OMPD_distribute: 6867 case OMPD_ordered: 6868 case OMPD_atomic: 6869 case OMPD_distribute_simd: 6870 llvm_unreachable("Unexpected OpenMP directive with num_teams-clause"); 6871 case OMPD_unknown: 6872 llvm_unreachable("Unknown OpenMP directive"); 6873 } 6874 break; 6875 case OMPC_thread_limit: 6876 switch (DKind) { 6877 case OMPD_target_teams: 6878 CaptureRegion = OMPD_target; 6879 break; 6880 case OMPD_cancel: 6881 case OMPD_parallel: 6882 case OMPD_parallel_sections: 6883 case OMPD_parallel_for: 6884 case OMPD_parallel_for_simd: 6885 case OMPD_target: 6886 case OMPD_target_simd: 6887 case OMPD_target_parallel: 6888 case OMPD_target_parallel_for: 6889 case OMPD_target_parallel_for_simd: 6890 case OMPD_target_teams_distribute: 6891 case OMPD_target_teams_distribute_simd: 6892 case OMPD_target_teams_distribute_parallel_for: 6893 case OMPD_target_teams_distribute_parallel_for_simd: 6894 case OMPD_teams_distribute_parallel_for: 6895 case OMPD_teams_distribute_parallel_for_simd: 6896 case OMPD_distribute_parallel_for: 6897 case OMPD_distribute_parallel_for_simd: 6898 case OMPD_task: 6899 case OMPD_taskloop: 6900 case OMPD_taskloop_simd: 6901 case OMPD_target_data: 6902 case OMPD_target_enter_data: 6903 case OMPD_target_exit_data: 6904 case OMPD_target_update: 6905 case OMPD_teams: 6906 case OMPD_teams_distribute: 6907 case OMPD_teams_distribute_simd: 6908 // Do not capture thread_limit-clause expressions. 6909 break; 6910 case OMPD_threadprivate: 6911 case OMPD_taskyield: 6912 case OMPD_barrier: 6913 case OMPD_taskwait: 6914 case OMPD_cancellation_point: 6915 case OMPD_flush: 6916 case OMPD_declare_reduction: 6917 case OMPD_declare_simd: 6918 case OMPD_declare_target: 6919 case OMPD_end_declare_target: 6920 case OMPD_simd: 6921 case OMPD_for: 6922 case OMPD_for_simd: 6923 case OMPD_sections: 6924 case OMPD_section: 6925 case OMPD_single: 6926 case OMPD_master: 6927 case OMPD_critical: 6928 case OMPD_taskgroup: 6929 case OMPD_distribute: 6930 case OMPD_ordered: 6931 case OMPD_atomic: 6932 case OMPD_distribute_simd: 6933 llvm_unreachable("Unexpected OpenMP directive with thread_limit-clause"); 6934 case OMPD_unknown: 6935 llvm_unreachable("Unknown OpenMP directive"); 6936 } 6937 break; 6938 case OMPC_schedule: 6939 case OMPC_dist_schedule: 6940 case OMPC_firstprivate: 6941 case OMPC_lastprivate: 6942 case OMPC_reduction: 6943 case OMPC_linear: 6944 case OMPC_default: 6945 case OMPC_proc_bind: 6946 case OMPC_final: 6947 case OMPC_safelen: 6948 case OMPC_simdlen: 6949 case OMPC_collapse: 6950 case OMPC_private: 6951 case OMPC_shared: 6952 case OMPC_aligned: 6953 case OMPC_copyin: 6954 case OMPC_copyprivate: 6955 case OMPC_ordered: 6956 case OMPC_nowait: 6957 case OMPC_untied: 6958 case OMPC_mergeable: 6959 case OMPC_threadprivate: 6960 case OMPC_flush: 6961 case OMPC_read: 6962 case OMPC_write: 6963 case OMPC_update: 6964 case OMPC_capture: 6965 case OMPC_seq_cst: 6966 case OMPC_depend: 6967 case OMPC_device: 6968 case OMPC_threads: 6969 case OMPC_simd: 6970 case OMPC_map: 6971 case OMPC_priority: 6972 case OMPC_grainsize: 6973 case OMPC_nogroup: 6974 case OMPC_num_tasks: 6975 case OMPC_hint: 6976 case OMPC_defaultmap: 6977 case OMPC_unknown: 6978 case OMPC_uniform: 6979 case OMPC_to: 6980 case OMPC_from: 6981 case OMPC_use_device_ptr: 6982 case OMPC_is_device_ptr: 6983 llvm_unreachable("Unexpected OpenMP clause."); 6984 } 6985 return CaptureRegion; 6986 } 6987 6988 OMPClause *Sema::ActOnOpenMPIfClause(OpenMPDirectiveKind NameModifier, 6989 Expr *Condition, SourceLocation StartLoc, 6990 SourceLocation LParenLoc, 6991 SourceLocation NameModifierLoc, 6992 SourceLocation ColonLoc, 6993 SourceLocation EndLoc) { 6994 Expr *ValExpr = Condition; 6995 Stmt *HelperValStmt = nullptr; 6996 OpenMPDirectiveKind CaptureRegion = OMPD_unknown; 6997 if (!Condition->isValueDependent() && !Condition->isTypeDependent() && 6998 !Condition->isInstantiationDependent() && 6999 !Condition->containsUnexpandedParameterPack()) { 7000 ExprResult Val = CheckBooleanCondition(StartLoc, Condition); 7001 if (Val.isInvalid()) 7002 return nullptr; 7003 7004 ValExpr = MakeFullExpr(Val.get()).get(); 7005 7006 OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective(); 7007 CaptureRegion = 7008 getOpenMPCaptureRegionForClause(DKind, OMPC_if, NameModifier); 7009 if (CaptureRegion != OMPD_unknown) { 7010 llvm::MapVector<Expr *, DeclRefExpr *> Captures; 7011 ValExpr = tryBuildCapture(*this, ValExpr, Captures).get(); 7012 HelperValStmt = buildPreInits(Context, Captures); 7013 } 7014 } 7015 7016 return new (Context) 7017 OMPIfClause(NameModifier, ValExpr, HelperValStmt, CaptureRegion, StartLoc, 7018 LParenLoc, NameModifierLoc, ColonLoc, EndLoc); 7019 } 7020 7021 OMPClause *Sema::ActOnOpenMPFinalClause(Expr *Condition, 7022 SourceLocation StartLoc, 7023 SourceLocation LParenLoc, 7024 SourceLocation EndLoc) { 7025 Expr *ValExpr = Condition; 7026 if (!Condition->isValueDependent() && !Condition->isTypeDependent() && 7027 !Condition->isInstantiationDependent() && 7028 !Condition->containsUnexpandedParameterPack()) { 7029 ExprResult Val = CheckBooleanCondition(StartLoc, Condition); 7030 if (Val.isInvalid()) 7031 return nullptr; 7032 7033 ValExpr = MakeFullExpr(Val.get()).get(); 7034 } 7035 7036 return new (Context) OMPFinalClause(ValExpr, StartLoc, LParenLoc, EndLoc); 7037 } 7038 ExprResult Sema::PerformOpenMPImplicitIntegerConversion(SourceLocation Loc, 7039 Expr *Op) { 7040 if (!Op) 7041 return ExprError(); 7042 7043 class IntConvertDiagnoser : public ICEConvertDiagnoser { 7044 public: 7045 IntConvertDiagnoser() 7046 : ICEConvertDiagnoser(/*AllowScopedEnumerations*/ false, false, true) {} 7047 SemaDiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc, 7048 QualType T) override { 7049 return S.Diag(Loc, diag::err_omp_not_integral) << T; 7050 } 7051 SemaDiagnosticBuilder diagnoseIncomplete(Sema &S, SourceLocation Loc, 7052 QualType T) override { 7053 return S.Diag(Loc, diag::err_omp_incomplete_type) << T; 7054 } 7055 SemaDiagnosticBuilder diagnoseExplicitConv(Sema &S, SourceLocation Loc, 7056 QualType T, 7057 QualType ConvTy) override { 7058 return S.Diag(Loc, diag::err_omp_explicit_conversion) << T << ConvTy; 7059 } 7060 SemaDiagnosticBuilder noteExplicitConv(Sema &S, CXXConversionDecl *Conv, 7061 QualType ConvTy) override { 7062 return S.Diag(Conv->getLocation(), diag::note_omp_conversion_here) 7063 << ConvTy->isEnumeralType() << ConvTy; 7064 } 7065 SemaDiagnosticBuilder diagnoseAmbiguous(Sema &S, SourceLocation Loc, 7066 QualType T) override { 7067 return S.Diag(Loc, diag::err_omp_ambiguous_conversion) << T; 7068 } 7069 SemaDiagnosticBuilder noteAmbiguous(Sema &S, CXXConversionDecl *Conv, 7070 QualType ConvTy) override { 7071 return S.Diag(Conv->getLocation(), diag::note_omp_conversion_here) 7072 << ConvTy->isEnumeralType() << ConvTy; 7073 } 7074 SemaDiagnosticBuilder diagnoseConversion(Sema &, SourceLocation, QualType, 7075 QualType) override { 7076 llvm_unreachable("conversion functions are permitted"); 7077 } 7078 } ConvertDiagnoser; 7079 return PerformContextualImplicitConversion(Loc, Op, ConvertDiagnoser); 7080 } 7081 7082 static bool IsNonNegativeIntegerValue(Expr *&ValExpr, Sema &SemaRef, 7083 OpenMPClauseKind CKind, 7084 bool StrictlyPositive) { 7085 if (!ValExpr->isTypeDependent() && !ValExpr->isValueDependent() && 7086 !ValExpr->isInstantiationDependent()) { 7087 SourceLocation Loc = ValExpr->getExprLoc(); 7088 ExprResult Value = 7089 SemaRef.PerformOpenMPImplicitIntegerConversion(Loc, ValExpr); 7090 if (Value.isInvalid()) 7091 return false; 7092 7093 ValExpr = Value.get(); 7094 // The expression must evaluate to a non-negative integer value. 7095 llvm::APSInt Result; 7096 if (ValExpr->isIntegerConstantExpr(Result, SemaRef.Context) && 7097 Result.isSigned() && 7098 !((!StrictlyPositive && Result.isNonNegative()) || 7099 (StrictlyPositive && Result.isStrictlyPositive()))) { 7100 SemaRef.Diag(Loc, diag::err_omp_negative_expression_in_clause) 7101 << getOpenMPClauseName(CKind) << (StrictlyPositive ? 1 : 0) 7102 << ValExpr->getSourceRange(); 7103 return false; 7104 } 7105 } 7106 return true; 7107 } 7108 7109 OMPClause *Sema::ActOnOpenMPNumThreadsClause(Expr *NumThreads, 7110 SourceLocation StartLoc, 7111 SourceLocation LParenLoc, 7112 SourceLocation EndLoc) { 7113 Expr *ValExpr = NumThreads; 7114 Stmt *HelperValStmt = nullptr; 7115 OpenMPDirectiveKind CaptureRegion = OMPD_unknown; 7116 7117 // OpenMP [2.5, Restrictions] 7118 // The num_threads expression must evaluate to a positive integer value. 7119 if (!IsNonNegativeIntegerValue(ValExpr, *this, OMPC_num_threads, 7120 /*StrictlyPositive=*/true)) 7121 return nullptr; 7122 7123 OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective(); 7124 CaptureRegion = getOpenMPCaptureRegionForClause(DKind, OMPC_num_threads); 7125 if (CaptureRegion != OMPD_unknown) { 7126 llvm::MapVector<Expr *, DeclRefExpr *> Captures; 7127 ValExpr = tryBuildCapture(*this, ValExpr, Captures).get(); 7128 HelperValStmt = buildPreInits(Context, Captures); 7129 } 7130 7131 return new (Context) OMPNumThreadsClause( 7132 ValExpr, HelperValStmt, CaptureRegion, StartLoc, LParenLoc, EndLoc); 7133 } 7134 7135 ExprResult Sema::VerifyPositiveIntegerConstantInClause(Expr *E, 7136 OpenMPClauseKind CKind, 7137 bool StrictlyPositive) { 7138 if (!E) 7139 return ExprError(); 7140 if (E->isValueDependent() || E->isTypeDependent() || 7141 E->isInstantiationDependent() || E->containsUnexpandedParameterPack()) 7142 return E; 7143 llvm::APSInt Result; 7144 ExprResult ICE = VerifyIntegerConstantExpression(E, &Result); 7145 if (ICE.isInvalid()) 7146 return ExprError(); 7147 if ((StrictlyPositive && !Result.isStrictlyPositive()) || 7148 (!StrictlyPositive && !Result.isNonNegative())) { 7149 Diag(E->getExprLoc(), diag::err_omp_negative_expression_in_clause) 7150 << getOpenMPClauseName(CKind) << (StrictlyPositive ? 1 : 0) 7151 << E->getSourceRange(); 7152 return ExprError(); 7153 } 7154 if (CKind == OMPC_aligned && !Result.isPowerOf2()) { 7155 Diag(E->getExprLoc(), diag::warn_omp_alignment_not_power_of_two) 7156 << E->getSourceRange(); 7157 return ExprError(); 7158 } 7159 if (CKind == OMPC_collapse && DSAStack->getAssociatedLoops() == 1) 7160 DSAStack->setAssociatedLoops(Result.getExtValue()); 7161 else if (CKind == OMPC_ordered) 7162 DSAStack->setAssociatedLoops(Result.getExtValue()); 7163 return ICE; 7164 } 7165 7166 OMPClause *Sema::ActOnOpenMPSafelenClause(Expr *Len, SourceLocation StartLoc, 7167 SourceLocation LParenLoc, 7168 SourceLocation EndLoc) { 7169 // OpenMP [2.8.1, simd construct, Description] 7170 // The parameter of the safelen clause must be a constant 7171 // positive integer expression. 7172 ExprResult Safelen = VerifyPositiveIntegerConstantInClause(Len, OMPC_safelen); 7173 if (Safelen.isInvalid()) 7174 return nullptr; 7175 return new (Context) 7176 OMPSafelenClause(Safelen.get(), StartLoc, LParenLoc, EndLoc); 7177 } 7178 7179 OMPClause *Sema::ActOnOpenMPSimdlenClause(Expr *Len, SourceLocation StartLoc, 7180 SourceLocation LParenLoc, 7181 SourceLocation EndLoc) { 7182 // OpenMP [2.8.1, simd construct, Description] 7183 // The parameter of the simdlen clause must be a constant 7184 // positive integer expression. 7185 ExprResult Simdlen = VerifyPositiveIntegerConstantInClause(Len, OMPC_simdlen); 7186 if (Simdlen.isInvalid()) 7187 return nullptr; 7188 return new (Context) 7189 OMPSimdlenClause(Simdlen.get(), StartLoc, LParenLoc, EndLoc); 7190 } 7191 7192 OMPClause *Sema::ActOnOpenMPCollapseClause(Expr *NumForLoops, 7193 SourceLocation StartLoc, 7194 SourceLocation LParenLoc, 7195 SourceLocation EndLoc) { 7196 // OpenMP [2.7.1, loop construct, Description] 7197 // OpenMP [2.8.1, simd construct, Description] 7198 // OpenMP [2.9.6, distribute construct, Description] 7199 // The parameter of the collapse clause must be a constant 7200 // positive integer expression. 7201 ExprResult NumForLoopsResult = 7202 VerifyPositiveIntegerConstantInClause(NumForLoops, OMPC_collapse); 7203 if (NumForLoopsResult.isInvalid()) 7204 return nullptr; 7205 return new (Context) 7206 OMPCollapseClause(NumForLoopsResult.get(), StartLoc, LParenLoc, EndLoc); 7207 } 7208 7209 OMPClause *Sema::ActOnOpenMPOrderedClause(SourceLocation StartLoc, 7210 SourceLocation EndLoc, 7211 SourceLocation LParenLoc, 7212 Expr *NumForLoops) { 7213 // OpenMP [2.7.1, loop construct, Description] 7214 // OpenMP [2.8.1, simd construct, Description] 7215 // OpenMP [2.9.6, distribute construct, Description] 7216 // The parameter of the ordered clause must be a constant 7217 // positive integer expression if any. 7218 if (NumForLoops && LParenLoc.isValid()) { 7219 ExprResult NumForLoopsResult = 7220 VerifyPositiveIntegerConstantInClause(NumForLoops, OMPC_ordered); 7221 if (NumForLoopsResult.isInvalid()) 7222 return nullptr; 7223 NumForLoops = NumForLoopsResult.get(); 7224 } else 7225 NumForLoops = nullptr; 7226 DSAStack->setOrderedRegion(/*IsOrdered=*/true, NumForLoops); 7227 return new (Context) 7228 OMPOrderedClause(NumForLoops, StartLoc, LParenLoc, EndLoc); 7229 } 7230 7231 OMPClause *Sema::ActOnOpenMPSimpleClause( 7232 OpenMPClauseKind Kind, unsigned Argument, SourceLocation ArgumentLoc, 7233 SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc) { 7234 OMPClause *Res = nullptr; 7235 switch (Kind) { 7236 case OMPC_default: 7237 Res = 7238 ActOnOpenMPDefaultClause(static_cast<OpenMPDefaultClauseKind>(Argument), 7239 ArgumentLoc, StartLoc, LParenLoc, EndLoc); 7240 break; 7241 case OMPC_proc_bind: 7242 Res = ActOnOpenMPProcBindClause( 7243 static_cast<OpenMPProcBindClauseKind>(Argument), ArgumentLoc, StartLoc, 7244 LParenLoc, EndLoc); 7245 break; 7246 case OMPC_if: 7247 case OMPC_final: 7248 case OMPC_num_threads: 7249 case OMPC_safelen: 7250 case OMPC_simdlen: 7251 case OMPC_collapse: 7252 case OMPC_schedule: 7253 case OMPC_private: 7254 case OMPC_firstprivate: 7255 case OMPC_lastprivate: 7256 case OMPC_shared: 7257 case OMPC_reduction: 7258 case OMPC_linear: 7259 case OMPC_aligned: 7260 case OMPC_copyin: 7261 case OMPC_copyprivate: 7262 case OMPC_ordered: 7263 case OMPC_nowait: 7264 case OMPC_untied: 7265 case OMPC_mergeable: 7266 case OMPC_threadprivate: 7267 case OMPC_flush: 7268 case OMPC_read: 7269 case OMPC_write: 7270 case OMPC_update: 7271 case OMPC_capture: 7272 case OMPC_seq_cst: 7273 case OMPC_depend: 7274 case OMPC_device: 7275 case OMPC_threads: 7276 case OMPC_simd: 7277 case OMPC_map: 7278 case OMPC_num_teams: 7279 case OMPC_thread_limit: 7280 case OMPC_priority: 7281 case OMPC_grainsize: 7282 case OMPC_nogroup: 7283 case OMPC_num_tasks: 7284 case OMPC_hint: 7285 case OMPC_dist_schedule: 7286 case OMPC_defaultmap: 7287 case OMPC_unknown: 7288 case OMPC_uniform: 7289 case OMPC_to: 7290 case OMPC_from: 7291 case OMPC_use_device_ptr: 7292 case OMPC_is_device_ptr: 7293 llvm_unreachable("Clause is not allowed."); 7294 } 7295 return Res; 7296 } 7297 7298 static std::string 7299 getListOfPossibleValues(OpenMPClauseKind K, unsigned First, unsigned Last, 7300 ArrayRef<unsigned> Exclude = llvm::None) { 7301 std::string Values; 7302 unsigned Bound = Last >= 2 ? Last - 2 : 0; 7303 unsigned Skipped = Exclude.size(); 7304 auto S = Exclude.begin(), E = Exclude.end(); 7305 for (unsigned i = First; i < Last; ++i) { 7306 if (std::find(S, E, i) != E) { 7307 --Skipped; 7308 continue; 7309 } 7310 Values += "'"; 7311 Values += getOpenMPSimpleClauseTypeName(K, i); 7312 Values += "'"; 7313 if (i == Bound - Skipped) 7314 Values += " or "; 7315 else if (i != Bound + 1 - Skipped) 7316 Values += ", "; 7317 } 7318 return Values; 7319 } 7320 7321 OMPClause *Sema::ActOnOpenMPDefaultClause(OpenMPDefaultClauseKind Kind, 7322 SourceLocation KindKwLoc, 7323 SourceLocation StartLoc, 7324 SourceLocation LParenLoc, 7325 SourceLocation EndLoc) { 7326 if (Kind == OMPC_DEFAULT_unknown) { 7327 static_assert(OMPC_DEFAULT_unknown > 0, 7328 "OMPC_DEFAULT_unknown not greater than 0"); 7329 Diag(KindKwLoc, diag::err_omp_unexpected_clause_value) 7330 << getListOfPossibleValues(OMPC_default, /*First=*/0, 7331 /*Last=*/OMPC_DEFAULT_unknown) 7332 << getOpenMPClauseName(OMPC_default); 7333 return nullptr; 7334 } 7335 switch (Kind) { 7336 case OMPC_DEFAULT_none: 7337 DSAStack->setDefaultDSANone(KindKwLoc); 7338 break; 7339 case OMPC_DEFAULT_shared: 7340 DSAStack->setDefaultDSAShared(KindKwLoc); 7341 break; 7342 case OMPC_DEFAULT_unknown: 7343 llvm_unreachable("Clause kind is not allowed."); 7344 break; 7345 } 7346 return new (Context) 7347 OMPDefaultClause(Kind, KindKwLoc, StartLoc, LParenLoc, EndLoc); 7348 } 7349 7350 OMPClause *Sema::ActOnOpenMPProcBindClause(OpenMPProcBindClauseKind Kind, 7351 SourceLocation KindKwLoc, 7352 SourceLocation StartLoc, 7353 SourceLocation LParenLoc, 7354 SourceLocation EndLoc) { 7355 if (Kind == OMPC_PROC_BIND_unknown) { 7356 Diag(KindKwLoc, diag::err_omp_unexpected_clause_value) 7357 << getListOfPossibleValues(OMPC_proc_bind, /*First=*/0, 7358 /*Last=*/OMPC_PROC_BIND_unknown) 7359 << getOpenMPClauseName(OMPC_proc_bind); 7360 return nullptr; 7361 } 7362 return new (Context) 7363 OMPProcBindClause(Kind, KindKwLoc, StartLoc, LParenLoc, EndLoc); 7364 } 7365 7366 OMPClause *Sema::ActOnOpenMPSingleExprWithArgClause( 7367 OpenMPClauseKind Kind, ArrayRef<unsigned> Argument, Expr *Expr, 7368 SourceLocation StartLoc, SourceLocation LParenLoc, 7369 ArrayRef<SourceLocation> ArgumentLoc, SourceLocation DelimLoc, 7370 SourceLocation EndLoc) { 7371 OMPClause *Res = nullptr; 7372 switch (Kind) { 7373 case OMPC_schedule: 7374 enum { Modifier1, Modifier2, ScheduleKind, NumberOfElements }; 7375 assert(Argument.size() == NumberOfElements && 7376 ArgumentLoc.size() == NumberOfElements); 7377 Res = ActOnOpenMPScheduleClause( 7378 static_cast<OpenMPScheduleClauseModifier>(Argument[Modifier1]), 7379 static_cast<OpenMPScheduleClauseModifier>(Argument[Modifier2]), 7380 static_cast<OpenMPScheduleClauseKind>(Argument[ScheduleKind]), Expr, 7381 StartLoc, LParenLoc, ArgumentLoc[Modifier1], ArgumentLoc[Modifier2], 7382 ArgumentLoc[ScheduleKind], DelimLoc, EndLoc); 7383 break; 7384 case OMPC_if: 7385 assert(Argument.size() == 1 && ArgumentLoc.size() == 1); 7386 Res = ActOnOpenMPIfClause(static_cast<OpenMPDirectiveKind>(Argument.back()), 7387 Expr, StartLoc, LParenLoc, ArgumentLoc.back(), 7388 DelimLoc, EndLoc); 7389 break; 7390 case OMPC_dist_schedule: 7391 Res = ActOnOpenMPDistScheduleClause( 7392 static_cast<OpenMPDistScheduleClauseKind>(Argument.back()), Expr, 7393 StartLoc, LParenLoc, ArgumentLoc.back(), DelimLoc, EndLoc); 7394 break; 7395 case OMPC_defaultmap: 7396 enum { Modifier, DefaultmapKind }; 7397 Res = ActOnOpenMPDefaultmapClause( 7398 static_cast<OpenMPDefaultmapClauseModifier>(Argument[Modifier]), 7399 static_cast<OpenMPDefaultmapClauseKind>(Argument[DefaultmapKind]), 7400 StartLoc, LParenLoc, ArgumentLoc[Modifier], ArgumentLoc[DefaultmapKind], 7401 EndLoc); 7402 break; 7403 case OMPC_final: 7404 case OMPC_num_threads: 7405 case OMPC_safelen: 7406 case OMPC_simdlen: 7407 case OMPC_collapse: 7408 case OMPC_default: 7409 case OMPC_proc_bind: 7410 case OMPC_private: 7411 case OMPC_firstprivate: 7412 case OMPC_lastprivate: 7413 case OMPC_shared: 7414 case OMPC_reduction: 7415 case OMPC_linear: 7416 case OMPC_aligned: 7417 case OMPC_copyin: 7418 case OMPC_copyprivate: 7419 case OMPC_ordered: 7420 case OMPC_nowait: 7421 case OMPC_untied: 7422 case OMPC_mergeable: 7423 case OMPC_threadprivate: 7424 case OMPC_flush: 7425 case OMPC_read: 7426 case OMPC_write: 7427 case OMPC_update: 7428 case OMPC_capture: 7429 case OMPC_seq_cst: 7430 case OMPC_depend: 7431 case OMPC_device: 7432 case OMPC_threads: 7433 case OMPC_simd: 7434 case OMPC_map: 7435 case OMPC_num_teams: 7436 case OMPC_thread_limit: 7437 case OMPC_priority: 7438 case OMPC_grainsize: 7439 case OMPC_nogroup: 7440 case OMPC_num_tasks: 7441 case OMPC_hint: 7442 case OMPC_unknown: 7443 case OMPC_uniform: 7444 case OMPC_to: 7445 case OMPC_from: 7446 case OMPC_use_device_ptr: 7447 case OMPC_is_device_ptr: 7448 llvm_unreachable("Clause is not allowed."); 7449 } 7450 return Res; 7451 } 7452 7453 static bool checkScheduleModifiers(Sema &S, OpenMPScheduleClauseModifier M1, 7454 OpenMPScheduleClauseModifier M2, 7455 SourceLocation M1Loc, SourceLocation M2Loc) { 7456 if (M1 == OMPC_SCHEDULE_MODIFIER_unknown && M1Loc.isValid()) { 7457 SmallVector<unsigned, 2> Excluded; 7458 if (M2 != OMPC_SCHEDULE_MODIFIER_unknown) 7459 Excluded.push_back(M2); 7460 if (M2 == OMPC_SCHEDULE_MODIFIER_nonmonotonic) 7461 Excluded.push_back(OMPC_SCHEDULE_MODIFIER_monotonic); 7462 if (M2 == OMPC_SCHEDULE_MODIFIER_monotonic) 7463 Excluded.push_back(OMPC_SCHEDULE_MODIFIER_nonmonotonic); 7464 S.Diag(M1Loc, diag::err_omp_unexpected_clause_value) 7465 << getListOfPossibleValues(OMPC_schedule, 7466 /*First=*/OMPC_SCHEDULE_MODIFIER_unknown + 1, 7467 /*Last=*/OMPC_SCHEDULE_MODIFIER_last, 7468 Excluded) 7469 << getOpenMPClauseName(OMPC_schedule); 7470 return true; 7471 } 7472 return false; 7473 } 7474 7475 OMPClause *Sema::ActOnOpenMPScheduleClause( 7476 OpenMPScheduleClauseModifier M1, OpenMPScheduleClauseModifier M2, 7477 OpenMPScheduleClauseKind Kind, Expr *ChunkSize, SourceLocation StartLoc, 7478 SourceLocation LParenLoc, SourceLocation M1Loc, SourceLocation M2Loc, 7479 SourceLocation KindLoc, SourceLocation CommaLoc, SourceLocation EndLoc) { 7480 if (checkScheduleModifiers(*this, M1, M2, M1Loc, M2Loc) || 7481 checkScheduleModifiers(*this, M2, M1, M2Loc, M1Loc)) 7482 return nullptr; 7483 // OpenMP, 2.7.1, Loop Construct, Restrictions 7484 // Either the monotonic modifier or the nonmonotonic modifier can be specified 7485 // but not both. 7486 if ((M1 == M2 && M1 != OMPC_SCHEDULE_MODIFIER_unknown) || 7487 (M1 == OMPC_SCHEDULE_MODIFIER_monotonic && 7488 M2 == OMPC_SCHEDULE_MODIFIER_nonmonotonic) || 7489 (M1 == OMPC_SCHEDULE_MODIFIER_nonmonotonic && 7490 M2 == OMPC_SCHEDULE_MODIFIER_monotonic)) { 7491 Diag(M2Loc, diag::err_omp_unexpected_schedule_modifier) 7492 << getOpenMPSimpleClauseTypeName(OMPC_schedule, M2) 7493 << getOpenMPSimpleClauseTypeName(OMPC_schedule, M1); 7494 return nullptr; 7495 } 7496 if (Kind == OMPC_SCHEDULE_unknown) { 7497 std::string Values; 7498 if (M1Loc.isInvalid() && M2Loc.isInvalid()) { 7499 unsigned Exclude[] = {OMPC_SCHEDULE_unknown}; 7500 Values = getListOfPossibleValues(OMPC_schedule, /*First=*/0, 7501 /*Last=*/OMPC_SCHEDULE_MODIFIER_last, 7502 Exclude); 7503 } else { 7504 Values = getListOfPossibleValues(OMPC_schedule, /*First=*/0, 7505 /*Last=*/OMPC_SCHEDULE_unknown); 7506 } 7507 Diag(KindLoc, diag::err_omp_unexpected_clause_value) 7508 << Values << getOpenMPClauseName(OMPC_schedule); 7509 return nullptr; 7510 } 7511 // OpenMP, 2.7.1, Loop Construct, Restrictions 7512 // The nonmonotonic modifier can only be specified with schedule(dynamic) or 7513 // schedule(guided). 7514 if ((M1 == OMPC_SCHEDULE_MODIFIER_nonmonotonic || 7515 M2 == OMPC_SCHEDULE_MODIFIER_nonmonotonic) && 7516 Kind != OMPC_SCHEDULE_dynamic && Kind != OMPC_SCHEDULE_guided) { 7517 Diag(M1 == OMPC_SCHEDULE_MODIFIER_nonmonotonic ? M1Loc : M2Loc, 7518 diag::err_omp_schedule_nonmonotonic_static); 7519 return nullptr; 7520 } 7521 Expr *ValExpr = ChunkSize; 7522 Stmt *HelperValStmt = nullptr; 7523 if (ChunkSize) { 7524 if (!ChunkSize->isValueDependent() && !ChunkSize->isTypeDependent() && 7525 !ChunkSize->isInstantiationDependent() && 7526 !ChunkSize->containsUnexpandedParameterPack()) { 7527 SourceLocation ChunkSizeLoc = ChunkSize->getLocStart(); 7528 ExprResult Val = 7529 PerformOpenMPImplicitIntegerConversion(ChunkSizeLoc, ChunkSize); 7530 if (Val.isInvalid()) 7531 return nullptr; 7532 7533 ValExpr = Val.get(); 7534 7535 // OpenMP [2.7.1, Restrictions] 7536 // chunk_size must be a loop invariant integer expression with a positive 7537 // value. 7538 llvm::APSInt Result; 7539 if (ValExpr->isIntegerConstantExpr(Result, Context)) { 7540 if (Result.isSigned() && !Result.isStrictlyPositive()) { 7541 Diag(ChunkSizeLoc, diag::err_omp_negative_expression_in_clause) 7542 << "schedule" << 1 << ChunkSize->getSourceRange(); 7543 return nullptr; 7544 } 7545 } else if (isParallelOrTaskRegion(DSAStack->getCurrentDirective()) && 7546 !CurContext->isDependentContext()) { 7547 llvm::MapVector<Expr *, DeclRefExpr *> Captures; 7548 ValExpr = tryBuildCapture(*this, ValExpr, Captures).get(); 7549 HelperValStmt = buildPreInits(Context, Captures); 7550 } 7551 } 7552 } 7553 7554 return new (Context) 7555 OMPScheduleClause(StartLoc, LParenLoc, KindLoc, CommaLoc, EndLoc, Kind, 7556 ValExpr, HelperValStmt, M1, M1Loc, M2, M2Loc); 7557 } 7558 7559 OMPClause *Sema::ActOnOpenMPClause(OpenMPClauseKind Kind, 7560 SourceLocation StartLoc, 7561 SourceLocation EndLoc) { 7562 OMPClause *Res = nullptr; 7563 switch (Kind) { 7564 case OMPC_ordered: 7565 Res = ActOnOpenMPOrderedClause(StartLoc, EndLoc); 7566 break; 7567 case OMPC_nowait: 7568 Res = ActOnOpenMPNowaitClause(StartLoc, EndLoc); 7569 break; 7570 case OMPC_untied: 7571 Res = ActOnOpenMPUntiedClause(StartLoc, EndLoc); 7572 break; 7573 case OMPC_mergeable: 7574 Res = ActOnOpenMPMergeableClause(StartLoc, EndLoc); 7575 break; 7576 case OMPC_read: 7577 Res = ActOnOpenMPReadClause(StartLoc, EndLoc); 7578 break; 7579 case OMPC_write: 7580 Res = ActOnOpenMPWriteClause(StartLoc, EndLoc); 7581 break; 7582 case OMPC_update: 7583 Res = ActOnOpenMPUpdateClause(StartLoc, EndLoc); 7584 break; 7585 case OMPC_capture: 7586 Res = ActOnOpenMPCaptureClause(StartLoc, EndLoc); 7587 break; 7588 case OMPC_seq_cst: 7589 Res = ActOnOpenMPSeqCstClause(StartLoc, EndLoc); 7590 break; 7591 case OMPC_threads: 7592 Res = ActOnOpenMPThreadsClause(StartLoc, EndLoc); 7593 break; 7594 case OMPC_simd: 7595 Res = ActOnOpenMPSIMDClause(StartLoc, EndLoc); 7596 break; 7597 case OMPC_nogroup: 7598 Res = ActOnOpenMPNogroupClause(StartLoc, EndLoc); 7599 break; 7600 case OMPC_if: 7601 case OMPC_final: 7602 case OMPC_num_threads: 7603 case OMPC_safelen: 7604 case OMPC_simdlen: 7605 case OMPC_collapse: 7606 case OMPC_schedule: 7607 case OMPC_private: 7608 case OMPC_firstprivate: 7609 case OMPC_lastprivate: 7610 case OMPC_shared: 7611 case OMPC_reduction: 7612 case OMPC_linear: 7613 case OMPC_aligned: 7614 case OMPC_copyin: 7615 case OMPC_copyprivate: 7616 case OMPC_default: 7617 case OMPC_proc_bind: 7618 case OMPC_threadprivate: 7619 case OMPC_flush: 7620 case OMPC_depend: 7621 case OMPC_device: 7622 case OMPC_map: 7623 case OMPC_num_teams: 7624 case OMPC_thread_limit: 7625 case OMPC_priority: 7626 case OMPC_grainsize: 7627 case OMPC_num_tasks: 7628 case OMPC_hint: 7629 case OMPC_dist_schedule: 7630 case OMPC_defaultmap: 7631 case OMPC_unknown: 7632 case OMPC_uniform: 7633 case OMPC_to: 7634 case OMPC_from: 7635 case OMPC_use_device_ptr: 7636 case OMPC_is_device_ptr: 7637 llvm_unreachable("Clause is not allowed."); 7638 } 7639 return Res; 7640 } 7641 7642 OMPClause *Sema::ActOnOpenMPNowaitClause(SourceLocation StartLoc, 7643 SourceLocation EndLoc) { 7644 DSAStack->setNowaitRegion(); 7645 return new (Context) OMPNowaitClause(StartLoc, EndLoc); 7646 } 7647 7648 OMPClause *Sema::ActOnOpenMPUntiedClause(SourceLocation StartLoc, 7649 SourceLocation EndLoc) { 7650 return new (Context) OMPUntiedClause(StartLoc, EndLoc); 7651 } 7652 7653 OMPClause *Sema::ActOnOpenMPMergeableClause(SourceLocation StartLoc, 7654 SourceLocation EndLoc) { 7655 return new (Context) OMPMergeableClause(StartLoc, EndLoc); 7656 } 7657 7658 OMPClause *Sema::ActOnOpenMPReadClause(SourceLocation StartLoc, 7659 SourceLocation EndLoc) { 7660 return new (Context) OMPReadClause(StartLoc, EndLoc); 7661 } 7662 7663 OMPClause *Sema::ActOnOpenMPWriteClause(SourceLocation StartLoc, 7664 SourceLocation EndLoc) { 7665 return new (Context) OMPWriteClause(StartLoc, EndLoc); 7666 } 7667 7668 OMPClause *Sema::ActOnOpenMPUpdateClause(SourceLocation StartLoc, 7669 SourceLocation EndLoc) { 7670 return new (Context) OMPUpdateClause(StartLoc, EndLoc); 7671 } 7672 7673 OMPClause *Sema::ActOnOpenMPCaptureClause(SourceLocation StartLoc, 7674 SourceLocation EndLoc) { 7675 return new (Context) OMPCaptureClause(StartLoc, EndLoc); 7676 } 7677 7678 OMPClause *Sema::ActOnOpenMPSeqCstClause(SourceLocation StartLoc, 7679 SourceLocation EndLoc) { 7680 return new (Context) OMPSeqCstClause(StartLoc, EndLoc); 7681 } 7682 7683 OMPClause *Sema::ActOnOpenMPThreadsClause(SourceLocation StartLoc, 7684 SourceLocation EndLoc) { 7685 return new (Context) OMPThreadsClause(StartLoc, EndLoc); 7686 } 7687 7688 OMPClause *Sema::ActOnOpenMPSIMDClause(SourceLocation StartLoc, 7689 SourceLocation EndLoc) { 7690 return new (Context) OMPSIMDClause(StartLoc, EndLoc); 7691 } 7692 7693 OMPClause *Sema::ActOnOpenMPNogroupClause(SourceLocation StartLoc, 7694 SourceLocation EndLoc) { 7695 return new (Context) OMPNogroupClause(StartLoc, EndLoc); 7696 } 7697 7698 OMPClause *Sema::ActOnOpenMPVarListClause( 7699 OpenMPClauseKind Kind, ArrayRef<Expr *> VarList, Expr *TailExpr, 7700 SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation ColonLoc, 7701 SourceLocation EndLoc, CXXScopeSpec &ReductionIdScopeSpec, 7702 const DeclarationNameInfo &ReductionId, OpenMPDependClauseKind DepKind, 7703 OpenMPLinearClauseKind LinKind, OpenMPMapClauseKind MapTypeModifier, 7704 OpenMPMapClauseKind MapType, bool IsMapTypeImplicit, 7705 SourceLocation DepLinMapLoc) { 7706 OMPClause *Res = nullptr; 7707 switch (Kind) { 7708 case OMPC_private: 7709 Res = ActOnOpenMPPrivateClause(VarList, StartLoc, LParenLoc, EndLoc); 7710 break; 7711 case OMPC_firstprivate: 7712 Res = ActOnOpenMPFirstprivateClause(VarList, StartLoc, LParenLoc, EndLoc); 7713 break; 7714 case OMPC_lastprivate: 7715 Res = ActOnOpenMPLastprivateClause(VarList, StartLoc, LParenLoc, EndLoc); 7716 break; 7717 case OMPC_shared: 7718 Res = ActOnOpenMPSharedClause(VarList, StartLoc, LParenLoc, EndLoc); 7719 break; 7720 case OMPC_reduction: 7721 Res = ActOnOpenMPReductionClause(VarList, StartLoc, LParenLoc, ColonLoc, 7722 EndLoc, ReductionIdScopeSpec, ReductionId); 7723 break; 7724 case OMPC_linear: 7725 Res = ActOnOpenMPLinearClause(VarList, TailExpr, StartLoc, LParenLoc, 7726 LinKind, DepLinMapLoc, ColonLoc, EndLoc); 7727 break; 7728 case OMPC_aligned: 7729 Res = ActOnOpenMPAlignedClause(VarList, TailExpr, StartLoc, LParenLoc, 7730 ColonLoc, EndLoc); 7731 break; 7732 case OMPC_copyin: 7733 Res = ActOnOpenMPCopyinClause(VarList, StartLoc, LParenLoc, EndLoc); 7734 break; 7735 case OMPC_copyprivate: 7736 Res = ActOnOpenMPCopyprivateClause(VarList, StartLoc, LParenLoc, EndLoc); 7737 break; 7738 case OMPC_flush: 7739 Res = ActOnOpenMPFlushClause(VarList, StartLoc, LParenLoc, EndLoc); 7740 break; 7741 case OMPC_depend: 7742 Res = ActOnOpenMPDependClause(DepKind, DepLinMapLoc, ColonLoc, VarList, 7743 StartLoc, LParenLoc, EndLoc); 7744 break; 7745 case OMPC_map: 7746 Res = ActOnOpenMPMapClause(MapTypeModifier, MapType, IsMapTypeImplicit, 7747 DepLinMapLoc, ColonLoc, VarList, StartLoc, 7748 LParenLoc, EndLoc); 7749 break; 7750 case OMPC_to: 7751 Res = ActOnOpenMPToClause(VarList, StartLoc, LParenLoc, EndLoc); 7752 break; 7753 case OMPC_from: 7754 Res = ActOnOpenMPFromClause(VarList, StartLoc, LParenLoc, EndLoc); 7755 break; 7756 case OMPC_use_device_ptr: 7757 Res = ActOnOpenMPUseDevicePtrClause(VarList, StartLoc, LParenLoc, EndLoc); 7758 break; 7759 case OMPC_is_device_ptr: 7760 Res = ActOnOpenMPIsDevicePtrClause(VarList, StartLoc, LParenLoc, EndLoc); 7761 break; 7762 case OMPC_if: 7763 case OMPC_final: 7764 case OMPC_num_threads: 7765 case OMPC_safelen: 7766 case OMPC_simdlen: 7767 case OMPC_collapse: 7768 case OMPC_default: 7769 case OMPC_proc_bind: 7770 case OMPC_schedule: 7771 case OMPC_ordered: 7772 case OMPC_nowait: 7773 case OMPC_untied: 7774 case OMPC_mergeable: 7775 case OMPC_threadprivate: 7776 case OMPC_read: 7777 case OMPC_write: 7778 case OMPC_update: 7779 case OMPC_capture: 7780 case OMPC_seq_cst: 7781 case OMPC_device: 7782 case OMPC_threads: 7783 case OMPC_simd: 7784 case OMPC_num_teams: 7785 case OMPC_thread_limit: 7786 case OMPC_priority: 7787 case OMPC_grainsize: 7788 case OMPC_nogroup: 7789 case OMPC_num_tasks: 7790 case OMPC_hint: 7791 case OMPC_dist_schedule: 7792 case OMPC_defaultmap: 7793 case OMPC_unknown: 7794 case OMPC_uniform: 7795 llvm_unreachable("Clause is not allowed."); 7796 } 7797 return Res; 7798 } 7799 7800 ExprResult Sema::getOpenMPCapturedExpr(VarDecl *Capture, ExprValueKind VK, 7801 ExprObjectKind OK, SourceLocation Loc) { 7802 ExprResult Res = BuildDeclRefExpr( 7803 Capture, Capture->getType().getNonReferenceType(), VK_LValue, Loc); 7804 if (!Res.isUsable()) 7805 return ExprError(); 7806 if (OK == OK_Ordinary && !getLangOpts().CPlusPlus) { 7807 Res = CreateBuiltinUnaryOp(Loc, UO_Deref, Res.get()); 7808 if (!Res.isUsable()) 7809 return ExprError(); 7810 } 7811 if (VK != VK_LValue && Res.get()->isGLValue()) { 7812 Res = DefaultLvalueConversion(Res.get()); 7813 if (!Res.isUsable()) 7814 return ExprError(); 7815 } 7816 return Res; 7817 } 7818 7819 static std::pair<ValueDecl *, bool> 7820 getPrivateItem(Sema &S, Expr *&RefExpr, SourceLocation &ELoc, 7821 SourceRange &ERange, bool AllowArraySection = false) { 7822 if (RefExpr->isTypeDependent() || RefExpr->isValueDependent() || 7823 RefExpr->containsUnexpandedParameterPack()) 7824 return std::make_pair(nullptr, true); 7825 7826 // OpenMP [3.1, C/C++] 7827 // A list item is a variable name. 7828 // OpenMP [2.9.3.3, Restrictions, p.1] 7829 // A variable that is part of another variable (as an array or 7830 // structure element) cannot appear in a private clause. 7831 RefExpr = RefExpr->IgnoreParens(); 7832 enum { 7833 NoArrayExpr = -1, 7834 ArraySubscript = 0, 7835 OMPArraySection = 1 7836 } IsArrayExpr = NoArrayExpr; 7837 if (AllowArraySection) { 7838 if (auto *ASE = dyn_cast_or_null<ArraySubscriptExpr>(RefExpr)) { 7839 auto *Base = ASE->getBase()->IgnoreParenImpCasts(); 7840 while (auto *TempASE = dyn_cast<ArraySubscriptExpr>(Base)) 7841 Base = TempASE->getBase()->IgnoreParenImpCasts(); 7842 RefExpr = Base; 7843 IsArrayExpr = ArraySubscript; 7844 } else if (auto *OASE = dyn_cast_or_null<OMPArraySectionExpr>(RefExpr)) { 7845 auto *Base = OASE->getBase()->IgnoreParenImpCasts(); 7846 while (auto *TempOASE = dyn_cast<OMPArraySectionExpr>(Base)) 7847 Base = TempOASE->getBase()->IgnoreParenImpCasts(); 7848 while (auto *TempASE = dyn_cast<ArraySubscriptExpr>(Base)) 7849 Base = TempASE->getBase()->IgnoreParenImpCasts(); 7850 RefExpr = Base; 7851 IsArrayExpr = OMPArraySection; 7852 } 7853 } 7854 ELoc = RefExpr->getExprLoc(); 7855 ERange = RefExpr->getSourceRange(); 7856 RefExpr = RefExpr->IgnoreParenImpCasts(); 7857 auto *DE = dyn_cast_or_null<DeclRefExpr>(RefExpr); 7858 auto *ME = dyn_cast_or_null<MemberExpr>(RefExpr); 7859 if ((!DE || !isa<VarDecl>(DE->getDecl())) && 7860 (S.getCurrentThisType().isNull() || !ME || 7861 !isa<CXXThisExpr>(ME->getBase()->IgnoreParenImpCasts()) || 7862 !isa<FieldDecl>(ME->getMemberDecl()))) { 7863 if (IsArrayExpr != NoArrayExpr) 7864 S.Diag(ELoc, diag::err_omp_expected_base_var_name) << IsArrayExpr 7865 << ERange; 7866 else { 7867 S.Diag(ELoc, 7868 AllowArraySection 7869 ? diag::err_omp_expected_var_name_member_expr_or_array_item 7870 : diag::err_omp_expected_var_name_member_expr) 7871 << (S.getCurrentThisType().isNull() ? 0 : 1) << ERange; 7872 } 7873 return std::make_pair(nullptr, false); 7874 } 7875 return std::make_pair(DE ? DE->getDecl() : ME->getMemberDecl(), false); 7876 } 7877 7878 OMPClause *Sema::ActOnOpenMPPrivateClause(ArrayRef<Expr *> VarList, 7879 SourceLocation StartLoc, 7880 SourceLocation LParenLoc, 7881 SourceLocation EndLoc) { 7882 SmallVector<Expr *, 8> Vars; 7883 SmallVector<Expr *, 8> PrivateCopies; 7884 for (auto &RefExpr : VarList) { 7885 assert(RefExpr && "NULL expr in OpenMP private clause."); 7886 SourceLocation ELoc; 7887 SourceRange ERange; 7888 Expr *SimpleRefExpr = RefExpr; 7889 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange); 7890 if (Res.second) { 7891 // It will be analyzed later. 7892 Vars.push_back(RefExpr); 7893 PrivateCopies.push_back(nullptr); 7894 } 7895 ValueDecl *D = Res.first; 7896 if (!D) 7897 continue; 7898 7899 QualType Type = D->getType(); 7900 auto *VD = dyn_cast<VarDecl>(D); 7901 7902 // OpenMP [2.9.3.3, Restrictions, C/C++, p.3] 7903 // A variable that appears in a private clause must not have an incomplete 7904 // type or a reference type. 7905 if (RequireCompleteType(ELoc, Type, diag::err_omp_private_incomplete_type)) 7906 continue; 7907 Type = Type.getNonReferenceType(); 7908 7909 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced 7910 // in a Construct] 7911 // Variables with the predetermined data-sharing attributes may not be 7912 // listed in data-sharing attributes clauses, except for the cases 7913 // listed below. For these exceptions only, listing a predetermined 7914 // variable in a data-sharing attribute clause is allowed and overrides 7915 // the variable's predetermined data-sharing attributes. 7916 DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, false); 7917 if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_private) { 7918 Diag(ELoc, diag::err_omp_wrong_dsa) << getOpenMPClauseName(DVar.CKind) 7919 << getOpenMPClauseName(OMPC_private); 7920 ReportOriginalDSA(*this, DSAStack, D, DVar); 7921 continue; 7922 } 7923 7924 auto CurrDir = DSAStack->getCurrentDirective(); 7925 // Variably modified types are not supported for tasks. 7926 if (!Type->isAnyPointerType() && Type->isVariablyModifiedType() && 7927 isOpenMPTaskingDirective(CurrDir)) { 7928 Diag(ELoc, diag::err_omp_variably_modified_type_not_supported) 7929 << getOpenMPClauseName(OMPC_private) << Type 7930 << getOpenMPDirectiveName(CurrDir); 7931 bool IsDecl = 7932 !VD || 7933 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly; 7934 Diag(D->getLocation(), 7935 IsDecl ? diag::note_previous_decl : diag::note_defined_here) 7936 << D; 7937 continue; 7938 } 7939 7940 // OpenMP 4.5 [2.15.5.1, Restrictions, p.3] 7941 // A list item cannot appear in both a map clause and a data-sharing 7942 // attribute clause on the same construct 7943 if (CurrDir == OMPD_target || CurrDir == OMPD_target_parallel || 7944 CurrDir == OMPD_target_teams || 7945 CurrDir == OMPD_target_teams_distribute || 7946 CurrDir == OMPD_target_teams_distribute_parallel_for || 7947 CurrDir == OMPD_target_teams_distribute_parallel_for_simd || 7948 CurrDir == OMPD_target_teams_distribute_simd || 7949 CurrDir == OMPD_target_parallel_for_simd || 7950 CurrDir == OMPD_target_parallel_for) { 7951 OpenMPClauseKind ConflictKind; 7952 if (DSAStack->checkMappableExprComponentListsForDecl( 7953 VD, /*CurrentRegionOnly=*/true, 7954 [&](OMPClauseMappableExprCommon::MappableExprComponentListRef, 7955 OpenMPClauseKind WhereFoundClauseKind) -> bool { 7956 ConflictKind = WhereFoundClauseKind; 7957 return true; 7958 })) { 7959 Diag(ELoc, diag::err_omp_variable_in_given_clause_and_dsa) 7960 << getOpenMPClauseName(OMPC_private) 7961 << getOpenMPClauseName(ConflictKind) 7962 << getOpenMPDirectiveName(CurrDir); 7963 ReportOriginalDSA(*this, DSAStack, D, DVar); 7964 continue; 7965 } 7966 } 7967 7968 // OpenMP [2.9.3.3, Restrictions, C/C++, p.1] 7969 // A variable of class type (or array thereof) that appears in a private 7970 // clause requires an accessible, unambiguous default constructor for the 7971 // class type. 7972 // Generate helper private variable and initialize it with the default 7973 // value. The address of the original variable is replaced by the address of 7974 // the new private variable in CodeGen. This new variable is not added to 7975 // IdResolver, so the code in the OpenMP region uses original variable for 7976 // proper diagnostics. 7977 Type = Type.getUnqualifiedType(); 7978 auto VDPrivate = buildVarDecl(*this, ELoc, Type, D->getName(), 7979 D->hasAttrs() ? &D->getAttrs() : nullptr); 7980 ActOnUninitializedDecl(VDPrivate); 7981 if (VDPrivate->isInvalidDecl()) 7982 continue; 7983 auto VDPrivateRefExpr = buildDeclRefExpr( 7984 *this, VDPrivate, RefExpr->getType().getUnqualifiedType(), ELoc); 7985 7986 DeclRefExpr *Ref = nullptr; 7987 if (!VD && !CurContext->isDependentContext()) 7988 Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/false); 7989 DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_private, Ref); 7990 Vars.push_back((VD || CurContext->isDependentContext()) 7991 ? RefExpr->IgnoreParens() 7992 : Ref); 7993 PrivateCopies.push_back(VDPrivateRefExpr); 7994 } 7995 7996 if (Vars.empty()) 7997 return nullptr; 7998 7999 return OMPPrivateClause::Create(Context, StartLoc, LParenLoc, EndLoc, Vars, 8000 PrivateCopies); 8001 } 8002 8003 namespace { 8004 class DiagsUninitializedSeveretyRAII { 8005 private: 8006 DiagnosticsEngine &Diags; 8007 SourceLocation SavedLoc; 8008 bool IsIgnored; 8009 8010 public: 8011 DiagsUninitializedSeveretyRAII(DiagnosticsEngine &Diags, SourceLocation Loc, 8012 bool IsIgnored) 8013 : Diags(Diags), SavedLoc(Loc), IsIgnored(IsIgnored) { 8014 if (!IsIgnored) { 8015 Diags.setSeverity(/*Diag*/ diag::warn_uninit_self_reference_in_init, 8016 /*Map*/ diag::Severity::Ignored, Loc); 8017 } 8018 } 8019 ~DiagsUninitializedSeveretyRAII() { 8020 if (!IsIgnored) 8021 Diags.popMappings(SavedLoc); 8022 } 8023 }; 8024 } 8025 8026 OMPClause *Sema::ActOnOpenMPFirstprivateClause(ArrayRef<Expr *> VarList, 8027 SourceLocation StartLoc, 8028 SourceLocation LParenLoc, 8029 SourceLocation EndLoc) { 8030 SmallVector<Expr *, 8> Vars; 8031 SmallVector<Expr *, 8> PrivateCopies; 8032 SmallVector<Expr *, 8> Inits; 8033 SmallVector<Decl *, 4> ExprCaptures; 8034 bool IsImplicitClause = 8035 StartLoc.isInvalid() && LParenLoc.isInvalid() && EndLoc.isInvalid(); 8036 auto ImplicitClauseLoc = DSAStack->getConstructLoc(); 8037 8038 for (auto &RefExpr : VarList) { 8039 assert(RefExpr && "NULL expr in OpenMP firstprivate clause."); 8040 SourceLocation ELoc; 8041 SourceRange ERange; 8042 Expr *SimpleRefExpr = RefExpr; 8043 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange); 8044 if (Res.second) { 8045 // It will be analyzed later. 8046 Vars.push_back(RefExpr); 8047 PrivateCopies.push_back(nullptr); 8048 Inits.push_back(nullptr); 8049 } 8050 ValueDecl *D = Res.first; 8051 if (!D) 8052 continue; 8053 8054 ELoc = IsImplicitClause ? ImplicitClauseLoc : ELoc; 8055 QualType Type = D->getType(); 8056 auto *VD = dyn_cast<VarDecl>(D); 8057 8058 // OpenMP [2.9.3.3, Restrictions, C/C++, p.3] 8059 // A variable that appears in a private clause must not have an incomplete 8060 // type or a reference type. 8061 if (RequireCompleteType(ELoc, Type, 8062 diag::err_omp_firstprivate_incomplete_type)) 8063 continue; 8064 Type = Type.getNonReferenceType(); 8065 8066 // OpenMP [2.9.3.4, Restrictions, C/C++, p.1] 8067 // A variable of class type (or array thereof) that appears in a private 8068 // clause requires an accessible, unambiguous copy constructor for the 8069 // class type. 8070 auto ElemType = Context.getBaseElementType(Type).getNonReferenceType(); 8071 8072 // If an implicit firstprivate variable found it was checked already. 8073 DSAStackTy::DSAVarData TopDVar; 8074 if (!IsImplicitClause) { 8075 DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, false); 8076 TopDVar = DVar; 8077 bool IsConstant = ElemType.isConstant(Context); 8078 // OpenMP [2.4.13, Data-sharing Attribute Clauses] 8079 // A list item that specifies a given variable may not appear in more 8080 // than one clause on the same directive, except that a variable may be 8081 // specified in both firstprivate and lastprivate clauses. 8082 if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_firstprivate && 8083 DVar.CKind != OMPC_lastprivate && DVar.RefExpr) { 8084 Diag(ELoc, diag::err_omp_wrong_dsa) 8085 << getOpenMPClauseName(DVar.CKind) 8086 << getOpenMPClauseName(OMPC_firstprivate); 8087 ReportOriginalDSA(*this, DSAStack, D, DVar); 8088 continue; 8089 } 8090 8091 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced 8092 // in a Construct] 8093 // Variables with the predetermined data-sharing attributes may not be 8094 // listed in data-sharing attributes clauses, except for the cases 8095 // listed below. For these exceptions only, listing a predetermined 8096 // variable in a data-sharing attribute clause is allowed and overrides 8097 // the variable's predetermined data-sharing attributes. 8098 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced 8099 // in a Construct, C/C++, p.2] 8100 // Variables with const-qualified type having no mutable member may be 8101 // listed in a firstprivate clause, even if they are static data members. 8102 if (!(IsConstant || (VD && VD->isStaticDataMember())) && !DVar.RefExpr && 8103 DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_shared) { 8104 Diag(ELoc, diag::err_omp_wrong_dsa) 8105 << getOpenMPClauseName(DVar.CKind) 8106 << getOpenMPClauseName(OMPC_firstprivate); 8107 ReportOriginalDSA(*this, DSAStack, D, DVar); 8108 continue; 8109 } 8110 8111 OpenMPDirectiveKind CurrDir = DSAStack->getCurrentDirective(); 8112 // OpenMP [2.9.3.4, Restrictions, p.2] 8113 // A list item that is private within a parallel region must not appear 8114 // in a firstprivate clause on a worksharing construct if any of the 8115 // worksharing regions arising from the worksharing construct ever bind 8116 // to any of the parallel regions arising from the parallel construct. 8117 if (isOpenMPWorksharingDirective(CurrDir) && 8118 !isOpenMPParallelDirective(CurrDir) && 8119 !isOpenMPTeamsDirective(CurrDir)) { 8120 DVar = DSAStack->getImplicitDSA(D, true); 8121 if (DVar.CKind != OMPC_shared && 8122 (isOpenMPParallelDirective(DVar.DKind) || 8123 DVar.DKind == OMPD_unknown)) { 8124 Diag(ELoc, diag::err_omp_required_access) 8125 << getOpenMPClauseName(OMPC_firstprivate) 8126 << getOpenMPClauseName(OMPC_shared); 8127 ReportOriginalDSA(*this, DSAStack, D, DVar); 8128 continue; 8129 } 8130 } 8131 // OpenMP [2.9.3.4, Restrictions, p.3] 8132 // A list item that appears in a reduction clause of a parallel construct 8133 // must not appear in a firstprivate clause on a worksharing or task 8134 // construct if any of the worksharing or task regions arising from the 8135 // worksharing or task construct ever bind to any of the parallel regions 8136 // arising from the parallel construct. 8137 // OpenMP [2.9.3.4, Restrictions, p.4] 8138 // A list item that appears in a reduction clause in worksharing 8139 // construct must not appear in a firstprivate clause in a task construct 8140 // encountered during execution of any of the worksharing regions arising 8141 // from the worksharing construct. 8142 if (isOpenMPTaskingDirective(CurrDir)) { 8143 DVar = DSAStack->hasInnermostDSA( 8144 D, [](OpenMPClauseKind C) -> bool { return C == OMPC_reduction; }, 8145 [](OpenMPDirectiveKind K) -> bool { 8146 return isOpenMPParallelDirective(K) || 8147 isOpenMPWorksharingDirective(K); 8148 }, 8149 false); 8150 if (DVar.CKind == OMPC_reduction && 8151 (isOpenMPParallelDirective(DVar.DKind) || 8152 isOpenMPWorksharingDirective(DVar.DKind))) { 8153 Diag(ELoc, diag::err_omp_parallel_reduction_in_task_firstprivate) 8154 << getOpenMPDirectiveName(DVar.DKind); 8155 ReportOriginalDSA(*this, DSAStack, D, DVar); 8156 continue; 8157 } 8158 } 8159 8160 // OpenMP 4.5 [2.15.3.4, Restrictions, p.3] 8161 // A list item that is private within a teams region must not appear in a 8162 // firstprivate clause on a distribute construct if any of the distribute 8163 // regions arising from the distribute construct ever bind to any of the 8164 // teams regions arising from the teams construct. 8165 // OpenMP 4.5 [2.15.3.4, Restrictions, p.3] 8166 // A list item that appears in a reduction clause of a teams construct 8167 // must not appear in a firstprivate clause on a distribute construct if 8168 // any of the distribute regions arising from the distribute construct 8169 // ever bind to any of the teams regions arising from the teams construct. 8170 // OpenMP 4.5 [2.10.8, Distribute Construct, p.3] 8171 // A list item may appear in a firstprivate or lastprivate clause but not 8172 // both. 8173 if (CurrDir == OMPD_distribute) { 8174 DVar = DSAStack->hasInnermostDSA( 8175 D, [](OpenMPClauseKind C) -> bool { return C == OMPC_private; }, 8176 [](OpenMPDirectiveKind K) -> bool { 8177 return isOpenMPTeamsDirective(K); 8178 }, 8179 false); 8180 if (DVar.CKind == OMPC_private && isOpenMPTeamsDirective(DVar.DKind)) { 8181 Diag(ELoc, diag::err_omp_firstprivate_distribute_private_teams); 8182 ReportOriginalDSA(*this, DSAStack, D, DVar); 8183 continue; 8184 } 8185 DVar = DSAStack->hasInnermostDSA( 8186 D, [](OpenMPClauseKind C) -> bool { return C == OMPC_reduction; }, 8187 [](OpenMPDirectiveKind K) -> bool { 8188 return isOpenMPTeamsDirective(K); 8189 }, 8190 false); 8191 if (DVar.CKind == OMPC_reduction && 8192 isOpenMPTeamsDirective(DVar.DKind)) { 8193 Diag(ELoc, diag::err_omp_firstprivate_distribute_in_teams_reduction); 8194 ReportOriginalDSA(*this, DSAStack, D, DVar); 8195 continue; 8196 } 8197 DVar = DSAStack->getTopDSA(D, false); 8198 if (DVar.CKind == OMPC_lastprivate) { 8199 Diag(ELoc, diag::err_omp_firstprivate_and_lastprivate_in_distribute); 8200 ReportOriginalDSA(*this, DSAStack, D, DVar); 8201 continue; 8202 } 8203 } 8204 // OpenMP 4.5 [2.15.5.1, Restrictions, p.3] 8205 // A list item cannot appear in both a map clause and a data-sharing 8206 // attribute clause on the same construct 8207 if (CurrDir == OMPD_target || CurrDir == OMPD_target_parallel || 8208 CurrDir == OMPD_target_teams || 8209 CurrDir == OMPD_target_teams_distribute || 8210 CurrDir == OMPD_target_teams_distribute_parallel_for || 8211 CurrDir == OMPD_target_teams_distribute_parallel_for_simd || 8212 CurrDir == OMPD_target_teams_distribute_simd || 8213 CurrDir == OMPD_target_parallel_for_simd || 8214 CurrDir == OMPD_target_parallel_for) { 8215 OpenMPClauseKind ConflictKind; 8216 if (DSAStack->checkMappableExprComponentListsForDecl( 8217 VD, /*CurrentRegionOnly=*/true, 8218 [&](OMPClauseMappableExprCommon::MappableExprComponentListRef, 8219 OpenMPClauseKind WhereFoundClauseKind) -> bool { 8220 ConflictKind = WhereFoundClauseKind; 8221 return true; 8222 })) { 8223 Diag(ELoc, diag::err_omp_variable_in_given_clause_and_dsa) 8224 << getOpenMPClauseName(OMPC_firstprivate) 8225 << getOpenMPClauseName(ConflictKind) 8226 << getOpenMPDirectiveName(DSAStack->getCurrentDirective()); 8227 ReportOriginalDSA(*this, DSAStack, D, DVar); 8228 continue; 8229 } 8230 } 8231 } 8232 8233 // Variably modified types are not supported for tasks. 8234 if (!Type->isAnyPointerType() && Type->isVariablyModifiedType() && 8235 isOpenMPTaskingDirective(DSAStack->getCurrentDirective())) { 8236 Diag(ELoc, diag::err_omp_variably_modified_type_not_supported) 8237 << getOpenMPClauseName(OMPC_firstprivate) << Type 8238 << getOpenMPDirectiveName(DSAStack->getCurrentDirective()); 8239 bool IsDecl = 8240 !VD || 8241 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly; 8242 Diag(D->getLocation(), 8243 IsDecl ? diag::note_previous_decl : diag::note_defined_here) 8244 << D; 8245 continue; 8246 } 8247 8248 Type = Type.getUnqualifiedType(); 8249 auto VDPrivate = buildVarDecl(*this, ELoc, Type, D->getName(), 8250 D->hasAttrs() ? &D->getAttrs() : nullptr); 8251 // Generate helper private variable and initialize it with the value of the 8252 // original variable. The address of the original variable is replaced by 8253 // the address of the new private variable in the CodeGen. This new variable 8254 // is not added to IdResolver, so the code in the OpenMP region uses 8255 // original variable for proper diagnostics and variable capturing. 8256 Expr *VDInitRefExpr = nullptr; 8257 // For arrays generate initializer for single element and replace it by the 8258 // original array element in CodeGen. 8259 if (Type->isArrayType()) { 8260 auto VDInit = 8261 buildVarDecl(*this, RefExpr->getExprLoc(), ElemType, D->getName()); 8262 VDInitRefExpr = buildDeclRefExpr(*this, VDInit, ElemType, ELoc); 8263 auto Init = DefaultLvalueConversion(VDInitRefExpr).get(); 8264 ElemType = ElemType.getUnqualifiedType(); 8265 auto *VDInitTemp = buildVarDecl(*this, RefExpr->getExprLoc(), ElemType, 8266 ".firstprivate.temp"); 8267 InitializedEntity Entity = 8268 InitializedEntity::InitializeVariable(VDInitTemp); 8269 InitializationKind Kind = InitializationKind::CreateCopy(ELoc, ELoc); 8270 8271 InitializationSequence InitSeq(*this, Entity, Kind, Init); 8272 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Init); 8273 if (Result.isInvalid()) 8274 VDPrivate->setInvalidDecl(); 8275 else 8276 VDPrivate->setInit(Result.getAs<Expr>()); 8277 // Remove temp variable declaration. 8278 Context.Deallocate(VDInitTemp); 8279 } else { 8280 auto *VDInit = buildVarDecl(*this, RefExpr->getExprLoc(), Type, 8281 ".firstprivate.temp"); 8282 VDInitRefExpr = buildDeclRefExpr(*this, VDInit, RefExpr->getType(), 8283 RefExpr->getExprLoc()); 8284 AddInitializerToDecl(VDPrivate, 8285 DefaultLvalueConversion(VDInitRefExpr).get(), 8286 /*DirectInit=*/false); 8287 } 8288 if (VDPrivate->isInvalidDecl()) { 8289 if (IsImplicitClause) { 8290 Diag(RefExpr->getExprLoc(), 8291 diag::note_omp_task_predetermined_firstprivate_here); 8292 } 8293 continue; 8294 } 8295 CurContext->addDecl(VDPrivate); 8296 auto VDPrivateRefExpr = buildDeclRefExpr( 8297 *this, VDPrivate, RefExpr->getType().getUnqualifiedType(), 8298 RefExpr->getExprLoc()); 8299 DeclRefExpr *Ref = nullptr; 8300 if (!VD && !CurContext->isDependentContext()) { 8301 if (TopDVar.CKind == OMPC_lastprivate) 8302 Ref = TopDVar.PrivateCopy; 8303 else { 8304 Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/true); 8305 if (!IsOpenMPCapturedDecl(D)) 8306 ExprCaptures.push_back(Ref->getDecl()); 8307 } 8308 } 8309 DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_firstprivate, Ref); 8310 Vars.push_back((VD || CurContext->isDependentContext()) 8311 ? RefExpr->IgnoreParens() 8312 : Ref); 8313 PrivateCopies.push_back(VDPrivateRefExpr); 8314 Inits.push_back(VDInitRefExpr); 8315 } 8316 8317 if (Vars.empty()) 8318 return nullptr; 8319 8320 return OMPFirstprivateClause::Create(Context, StartLoc, LParenLoc, EndLoc, 8321 Vars, PrivateCopies, Inits, 8322 buildPreInits(Context, ExprCaptures)); 8323 } 8324 8325 OMPClause *Sema::ActOnOpenMPLastprivateClause(ArrayRef<Expr *> VarList, 8326 SourceLocation StartLoc, 8327 SourceLocation LParenLoc, 8328 SourceLocation EndLoc) { 8329 SmallVector<Expr *, 8> Vars; 8330 SmallVector<Expr *, 8> SrcExprs; 8331 SmallVector<Expr *, 8> DstExprs; 8332 SmallVector<Expr *, 8> AssignmentOps; 8333 SmallVector<Decl *, 4> ExprCaptures; 8334 SmallVector<Expr *, 4> ExprPostUpdates; 8335 for (auto &RefExpr : VarList) { 8336 assert(RefExpr && "NULL expr in OpenMP lastprivate clause."); 8337 SourceLocation ELoc; 8338 SourceRange ERange; 8339 Expr *SimpleRefExpr = RefExpr; 8340 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange); 8341 if (Res.second) { 8342 // It will be analyzed later. 8343 Vars.push_back(RefExpr); 8344 SrcExprs.push_back(nullptr); 8345 DstExprs.push_back(nullptr); 8346 AssignmentOps.push_back(nullptr); 8347 } 8348 ValueDecl *D = Res.first; 8349 if (!D) 8350 continue; 8351 8352 QualType Type = D->getType(); 8353 auto *VD = dyn_cast<VarDecl>(D); 8354 8355 // OpenMP [2.14.3.5, Restrictions, C/C++, p.2] 8356 // A variable that appears in a lastprivate clause must not have an 8357 // incomplete type or a reference type. 8358 if (RequireCompleteType(ELoc, Type, 8359 diag::err_omp_lastprivate_incomplete_type)) 8360 continue; 8361 Type = Type.getNonReferenceType(); 8362 8363 // OpenMP [2.14.1.1, Data-sharing Attribute Rules for Variables Referenced 8364 // in a Construct] 8365 // Variables with the predetermined data-sharing attributes may not be 8366 // listed in data-sharing attributes clauses, except for the cases 8367 // listed below. 8368 DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, false); 8369 if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_lastprivate && 8370 DVar.CKind != OMPC_firstprivate && 8371 (DVar.CKind != OMPC_private || DVar.RefExpr != nullptr)) { 8372 Diag(ELoc, diag::err_omp_wrong_dsa) 8373 << getOpenMPClauseName(DVar.CKind) 8374 << getOpenMPClauseName(OMPC_lastprivate); 8375 ReportOriginalDSA(*this, DSAStack, D, DVar); 8376 continue; 8377 } 8378 8379 OpenMPDirectiveKind CurrDir = DSAStack->getCurrentDirective(); 8380 // OpenMP [2.14.3.5, Restrictions, p.2] 8381 // A list item that is private within a parallel region, or that appears in 8382 // the reduction clause of a parallel construct, must not appear in a 8383 // lastprivate clause on a worksharing construct if any of the corresponding 8384 // worksharing regions ever binds to any of the corresponding parallel 8385 // regions. 8386 DSAStackTy::DSAVarData TopDVar = DVar; 8387 if (isOpenMPWorksharingDirective(CurrDir) && 8388 !isOpenMPParallelDirective(CurrDir) && 8389 !isOpenMPTeamsDirective(CurrDir)) { 8390 DVar = DSAStack->getImplicitDSA(D, true); 8391 if (DVar.CKind != OMPC_shared) { 8392 Diag(ELoc, diag::err_omp_required_access) 8393 << getOpenMPClauseName(OMPC_lastprivate) 8394 << getOpenMPClauseName(OMPC_shared); 8395 ReportOriginalDSA(*this, DSAStack, D, DVar); 8396 continue; 8397 } 8398 } 8399 8400 // OpenMP 4.5 [2.10.8, Distribute Construct, p.3] 8401 // A list item may appear in a firstprivate or lastprivate clause but not 8402 // both. 8403 if (CurrDir == OMPD_distribute) { 8404 DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, false); 8405 if (DVar.CKind == OMPC_firstprivate) { 8406 Diag(ELoc, diag::err_omp_firstprivate_and_lastprivate_in_distribute); 8407 ReportOriginalDSA(*this, DSAStack, D, DVar); 8408 continue; 8409 } 8410 } 8411 8412 // OpenMP [2.14.3.5, Restrictions, C++, p.1,2] 8413 // A variable of class type (or array thereof) that appears in a 8414 // lastprivate clause requires an accessible, unambiguous default 8415 // constructor for the class type, unless the list item is also specified 8416 // in a firstprivate clause. 8417 // A variable of class type (or array thereof) that appears in a 8418 // lastprivate clause requires an accessible, unambiguous copy assignment 8419 // operator for the class type. 8420 Type = Context.getBaseElementType(Type).getNonReferenceType(); 8421 auto *SrcVD = buildVarDecl(*this, ERange.getBegin(), 8422 Type.getUnqualifiedType(), ".lastprivate.src", 8423 D->hasAttrs() ? &D->getAttrs() : nullptr); 8424 auto *PseudoSrcExpr = 8425 buildDeclRefExpr(*this, SrcVD, Type.getUnqualifiedType(), ELoc); 8426 auto *DstVD = 8427 buildVarDecl(*this, ERange.getBegin(), Type, ".lastprivate.dst", 8428 D->hasAttrs() ? &D->getAttrs() : nullptr); 8429 auto *PseudoDstExpr = buildDeclRefExpr(*this, DstVD, Type, ELoc); 8430 // For arrays generate assignment operation for single element and replace 8431 // it by the original array element in CodeGen. 8432 auto AssignmentOp = BuildBinOp(/*S=*/nullptr, ELoc, BO_Assign, 8433 PseudoDstExpr, PseudoSrcExpr); 8434 if (AssignmentOp.isInvalid()) 8435 continue; 8436 AssignmentOp = ActOnFinishFullExpr(AssignmentOp.get(), ELoc, 8437 /*DiscardedValue=*/true); 8438 if (AssignmentOp.isInvalid()) 8439 continue; 8440 8441 DeclRefExpr *Ref = nullptr; 8442 if (!VD && !CurContext->isDependentContext()) { 8443 if (TopDVar.CKind == OMPC_firstprivate) 8444 Ref = TopDVar.PrivateCopy; 8445 else { 8446 Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/false); 8447 if (!IsOpenMPCapturedDecl(D)) 8448 ExprCaptures.push_back(Ref->getDecl()); 8449 } 8450 if (TopDVar.CKind == OMPC_firstprivate || 8451 (!IsOpenMPCapturedDecl(D) && 8452 Ref->getDecl()->hasAttr<OMPCaptureNoInitAttr>())) { 8453 ExprResult RefRes = DefaultLvalueConversion(Ref); 8454 if (!RefRes.isUsable()) 8455 continue; 8456 ExprResult PostUpdateRes = 8457 BuildBinOp(DSAStack->getCurScope(), ELoc, BO_Assign, SimpleRefExpr, 8458 RefRes.get()); 8459 if (!PostUpdateRes.isUsable()) 8460 continue; 8461 ExprPostUpdates.push_back( 8462 IgnoredValueConversions(PostUpdateRes.get()).get()); 8463 } 8464 } 8465 DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_lastprivate, Ref); 8466 Vars.push_back((VD || CurContext->isDependentContext()) 8467 ? RefExpr->IgnoreParens() 8468 : Ref); 8469 SrcExprs.push_back(PseudoSrcExpr); 8470 DstExprs.push_back(PseudoDstExpr); 8471 AssignmentOps.push_back(AssignmentOp.get()); 8472 } 8473 8474 if (Vars.empty()) 8475 return nullptr; 8476 8477 return OMPLastprivateClause::Create(Context, StartLoc, LParenLoc, EndLoc, 8478 Vars, SrcExprs, DstExprs, AssignmentOps, 8479 buildPreInits(Context, ExprCaptures), 8480 buildPostUpdate(*this, ExprPostUpdates)); 8481 } 8482 8483 OMPClause *Sema::ActOnOpenMPSharedClause(ArrayRef<Expr *> VarList, 8484 SourceLocation StartLoc, 8485 SourceLocation LParenLoc, 8486 SourceLocation EndLoc) { 8487 SmallVector<Expr *, 8> Vars; 8488 for (auto &RefExpr : VarList) { 8489 assert(RefExpr && "NULL expr in OpenMP lastprivate clause."); 8490 SourceLocation ELoc; 8491 SourceRange ERange; 8492 Expr *SimpleRefExpr = RefExpr; 8493 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange); 8494 if (Res.second) { 8495 // It will be analyzed later. 8496 Vars.push_back(RefExpr); 8497 } 8498 ValueDecl *D = Res.first; 8499 if (!D) 8500 continue; 8501 8502 auto *VD = dyn_cast<VarDecl>(D); 8503 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced 8504 // in a Construct] 8505 // Variables with the predetermined data-sharing attributes may not be 8506 // listed in data-sharing attributes clauses, except for the cases 8507 // listed below. For these exceptions only, listing a predetermined 8508 // variable in a data-sharing attribute clause is allowed and overrides 8509 // the variable's predetermined data-sharing attributes. 8510 DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, false); 8511 if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_shared && 8512 DVar.RefExpr) { 8513 Diag(ELoc, diag::err_omp_wrong_dsa) << getOpenMPClauseName(DVar.CKind) 8514 << getOpenMPClauseName(OMPC_shared); 8515 ReportOriginalDSA(*this, DSAStack, D, DVar); 8516 continue; 8517 } 8518 8519 DeclRefExpr *Ref = nullptr; 8520 if (!VD && IsOpenMPCapturedDecl(D) && !CurContext->isDependentContext()) 8521 Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/true); 8522 DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_shared, Ref); 8523 Vars.push_back((VD || !Ref || CurContext->isDependentContext()) 8524 ? RefExpr->IgnoreParens() 8525 : Ref); 8526 } 8527 8528 if (Vars.empty()) 8529 return nullptr; 8530 8531 return OMPSharedClause::Create(Context, StartLoc, LParenLoc, EndLoc, Vars); 8532 } 8533 8534 namespace { 8535 class DSARefChecker : public StmtVisitor<DSARefChecker, bool> { 8536 DSAStackTy *Stack; 8537 8538 public: 8539 bool VisitDeclRefExpr(DeclRefExpr *E) { 8540 if (VarDecl *VD = dyn_cast<VarDecl>(E->getDecl())) { 8541 DSAStackTy::DSAVarData DVar = Stack->getTopDSA(VD, false); 8542 if (DVar.CKind == OMPC_shared && !DVar.RefExpr) 8543 return false; 8544 if (DVar.CKind != OMPC_unknown) 8545 return true; 8546 DSAStackTy::DSAVarData DVarPrivate = Stack->hasDSA( 8547 VD, isOpenMPPrivate, [](OpenMPDirectiveKind) -> bool { return true; }, 8548 false); 8549 if (DVarPrivate.CKind != OMPC_unknown) 8550 return true; 8551 return false; 8552 } 8553 return false; 8554 } 8555 bool VisitStmt(Stmt *S) { 8556 for (auto Child : S->children()) { 8557 if (Child && Visit(Child)) 8558 return true; 8559 } 8560 return false; 8561 } 8562 explicit DSARefChecker(DSAStackTy *S) : Stack(S) {} 8563 }; 8564 } // namespace 8565 8566 namespace { 8567 // Transform MemberExpression for specified FieldDecl of current class to 8568 // DeclRefExpr to specified OMPCapturedExprDecl. 8569 class TransformExprToCaptures : public TreeTransform<TransformExprToCaptures> { 8570 typedef TreeTransform<TransformExprToCaptures> BaseTransform; 8571 ValueDecl *Field; 8572 DeclRefExpr *CapturedExpr; 8573 8574 public: 8575 TransformExprToCaptures(Sema &SemaRef, ValueDecl *FieldDecl) 8576 : BaseTransform(SemaRef), Field(FieldDecl), CapturedExpr(nullptr) {} 8577 8578 ExprResult TransformMemberExpr(MemberExpr *E) { 8579 if (isa<CXXThisExpr>(E->getBase()->IgnoreParenImpCasts()) && 8580 E->getMemberDecl() == Field) { 8581 CapturedExpr = buildCapture(SemaRef, Field, E, /*WithInit=*/false); 8582 return CapturedExpr; 8583 } 8584 return BaseTransform::TransformMemberExpr(E); 8585 } 8586 DeclRefExpr *getCapturedExpr() { return CapturedExpr; } 8587 }; 8588 } // namespace 8589 8590 template <typename T> 8591 static T filterLookupForUDR(SmallVectorImpl<UnresolvedSet<8>> &Lookups, 8592 const llvm::function_ref<T(ValueDecl *)> &Gen) { 8593 for (auto &Set : Lookups) { 8594 for (auto *D : Set) { 8595 if (auto Res = Gen(cast<ValueDecl>(D))) 8596 return Res; 8597 } 8598 } 8599 return T(); 8600 } 8601 8602 static ExprResult 8603 buildDeclareReductionRef(Sema &SemaRef, SourceLocation Loc, SourceRange Range, 8604 Scope *S, CXXScopeSpec &ReductionIdScopeSpec, 8605 const DeclarationNameInfo &ReductionId, QualType Ty, 8606 CXXCastPath &BasePath, Expr *UnresolvedReduction) { 8607 if (ReductionIdScopeSpec.isInvalid()) 8608 return ExprError(); 8609 SmallVector<UnresolvedSet<8>, 4> Lookups; 8610 if (S) { 8611 LookupResult Lookup(SemaRef, ReductionId, Sema::LookupOMPReductionName); 8612 Lookup.suppressDiagnostics(); 8613 while (S && SemaRef.LookupParsedName(Lookup, S, &ReductionIdScopeSpec)) { 8614 auto *D = Lookup.getRepresentativeDecl(); 8615 do { 8616 S = S->getParent(); 8617 } while (S && !S->isDeclScope(D)); 8618 if (S) 8619 S = S->getParent(); 8620 Lookups.push_back(UnresolvedSet<8>()); 8621 Lookups.back().append(Lookup.begin(), Lookup.end()); 8622 Lookup.clear(); 8623 } 8624 } else if (auto *ULE = 8625 cast_or_null<UnresolvedLookupExpr>(UnresolvedReduction)) { 8626 Lookups.push_back(UnresolvedSet<8>()); 8627 Decl *PrevD = nullptr; 8628 for (auto *D : ULE->decls()) { 8629 if (D == PrevD) 8630 Lookups.push_back(UnresolvedSet<8>()); 8631 else if (auto *DRD = cast<OMPDeclareReductionDecl>(D)) 8632 Lookups.back().addDecl(DRD); 8633 PrevD = D; 8634 } 8635 } 8636 if (Ty->isDependentType() || Ty->isInstantiationDependentType() || 8637 Ty->containsUnexpandedParameterPack() || 8638 filterLookupForUDR<bool>(Lookups, [](ValueDecl *D) -> bool { 8639 return !D->isInvalidDecl() && 8640 (D->getType()->isDependentType() || 8641 D->getType()->isInstantiationDependentType() || 8642 D->getType()->containsUnexpandedParameterPack()); 8643 })) { 8644 UnresolvedSet<8> ResSet; 8645 for (auto &Set : Lookups) { 8646 ResSet.append(Set.begin(), Set.end()); 8647 // The last item marks the end of all declarations at the specified scope. 8648 ResSet.addDecl(Set[Set.size() - 1]); 8649 } 8650 return UnresolvedLookupExpr::Create( 8651 SemaRef.Context, /*NamingClass=*/nullptr, 8652 ReductionIdScopeSpec.getWithLocInContext(SemaRef.Context), ReductionId, 8653 /*ADL=*/true, /*Overloaded=*/true, ResSet.begin(), ResSet.end()); 8654 } 8655 if (auto *VD = filterLookupForUDR<ValueDecl *>( 8656 Lookups, [&SemaRef, Ty](ValueDecl *D) -> ValueDecl * { 8657 if (!D->isInvalidDecl() && 8658 SemaRef.Context.hasSameType(D->getType(), Ty)) 8659 return D; 8660 return nullptr; 8661 })) 8662 return SemaRef.BuildDeclRefExpr(VD, Ty, VK_LValue, Loc); 8663 if (auto *VD = filterLookupForUDR<ValueDecl *>( 8664 Lookups, [&SemaRef, Ty, Loc](ValueDecl *D) -> ValueDecl * { 8665 if (!D->isInvalidDecl() && 8666 SemaRef.IsDerivedFrom(Loc, Ty, D->getType()) && 8667 !Ty.isMoreQualifiedThan(D->getType())) 8668 return D; 8669 return nullptr; 8670 })) { 8671 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true, 8672 /*DetectVirtual=*/false); 8673 if (SemaRef.IsDerivedFrom(Loc, Ty, VD->getType(), Paths)) { 8674 if (!Paths.isAmbiguous(SemaRef.Context.getCanonicalType( 8675 VD->getType().getUnqualifiedType()))) { 8676 if (SemaRef.CheckBaseClassAccess(Loc, VD->getType(), Ty, Paths.front(), 8677 /*DiagID=*/0) != 8678 Sema::AR_inaccessible) { 8679 SemaRef.BuildBasePathArray(Paths, BasePath); 8680 return SemaRef.BuildDeclRefExpr(VD, Ty, VK_LValue, Loc); 8681 } 8682 } 8683 } 8684 } 8685 if (ReductionIdScopeSpec.isSet()) { 8686 SemaRef.Diag(Loc, diag::err_omp_not_resolved_reduction_identifier) << Range; 8687 return ExprError(); 8688 } 8689 return ExprEmpty(); 8690 } 8691 8692 OMPClause *Sema::ActOnOpenMPReductionClause( 8693 ArrayRef<Expr *> VarList, SourceLocation StartLoc, SourceLocation LParenLoc, 8694 SourceLocation ColonLoc, SourceLocation EndLoc, 8695 CXXScopeSpec &ReductionIdScopeSpec, const DeclarationNameInfo &ReductionId, 8696 ArrayRef<Expr *> UnresolvedReductions) { 8697 auto DN = ReductionId.getName(); 8698 auto OOK = DN.getCXXOverloadedOperator(); 8699 BinaryOperatorKind BOK = BO_Comma; 8700 8701 // OpenMP [2.14.3.6, reduction clause] 8702 // C 8703 // reduction-identifier is either an identifier or one of the following 8704 // operators: +, -, *, &, |, ^, && and || 8705 // C++ 8706 // reduction-identifier is either an id-expression or one of the following 8707 // operators: +, -, *, &, |, ^, && and || 8708 // FIXME: Only 'min' and 'max' identifiers are supported for now. 8709 switch (OOK) { 8710 case OO_Plus: 8711 case OO_Minus: 8712 BOK = BO_Add; 8713 break; 8714 case OO_Star: 8715 BOK = BO_Mul; 8716 break; 8717 case OO_Amp: 8718 BOK = BO_And; 8719 break; 8720 case OO_Pipe: 8721 BOK = BO_Or; 8722 break; 8723 case OO_Caret: 8724 BOK = BO_Xor; 8725 break; 8726 case OO_AmpAmp: 8727 BOK = BO_LAnd; 8728 break; 8729 case OO_PipePipe: 8730 BOK = BO_LOr; 8731 break; 8732 case OO_New: 8733 case OO_Delete: 8734 case OO_Array_New: 8735 case OO_Array_Delete: 8736 case OO_Slash: 8737 case OO_Percent: 8738 case OO_Tilde: 8739 case OO_Exclaim: 8740 case OO_Equal: 8741 case OO_Less: 8742 case OO_Greater: 8743 case OO_LessEqual: 8744 case OO_GreaterEqual: 8745 case OO_PlusEqual: 8746 case OO_MinusEqual: 8747 case OO_StarEqual: 8748 case OO_SlashEqual: 8749 case OO_PercentEqual: 8750 case OO_CaretEqual: 8751 case OO_AmpEqual: 8752 case OO_PipeEqual: 8753 case OO_LessLess: 8754 case OO_GreaterGreater: 8755 case OO_LessLessEqual: 8756 case OO_GreaterGreaterEqual: 8757 case OO_EqualEqual: 8758 case OO_ExclaimEqual: 8759 case OO_PlusPlus: 8760 case OO_MinusMinus: 8761 case OO_Comma: 8762 case OO_ArrowStar: 8763 case OO_Arrow: 8764 case OO_Call: 8765 case OO_Subscript: 8766 case OO_Conditional: 8767 case OO_Coawait: 8768 case NUM_OVERLOADED_OPERATORS: 8769 llvm_unreachable("Unexpected reduction identifier"); 8770 case OO_None: 8771 if (auto II = DN.getAsIdentifierInfo()) { 8772 if (II->isStr("max")) 8773 BOK = BO_GT; 8774 else if (II->isStr("min")) 8775 BOK = BO_LT; 8776 } 8777 break; 8778 } 8779 SourceRange ReductionIdRange; 8780 if (ReductionIdScopeSpec.isValid()) 8781 ReductionIdRange.setBegin(ReductionIdScopeSpec.getBeginLoc()); 8782 ReductionIdRange.setEnd(ReductionId.getEndLoc()); 8783 8784 SmallVector<Expr *, 8> Vars; 8785 SmallVector<Expr *, 8> Privates; 8786 SmallVector<Expr *, 8> LHSs; 8787 SmallVector<Expr *, 8> RHSs; 8788 SmallVector<Expr *, 8> ReductionOps; 8789 SmallVector<Decl *, 4> ExprCaptures; 8790 SmallVector<Expr *, 4> ExprPostUpdates; 8791 auto IR = UnresolvedReductions.begin(), ER = UnresolvedReductions.end(); 8792 bool FirstIter = true; 8793 for (auto RefExpr : VarList) { 8794 assert(RefExpr && "nullptr expr in OpenMP reduction clause."); 8795 // OpenMP [2.1, C/C++] 8796 // A list item is a variable or array section, subject to the restrictions 8797 // specified in Section 2.4 on page 42 and in each of the sections 8798 // describing clauses and directives for which a list appears. 8799 // OpenMP [2.14.3.3, Restrictions, p.1] 8800 // A variable that is part of another variable (as an array or 8801 // structure element) cannot appear in a private clause. 8802 if (!FirstIter && IR != ER) 8803 ++IR; 8804 FirstIter = false; 8805 SourceLocation ELoc; 8806 SourceRange ERange; 8807 Expr *SimpleRefExpr = RefExpr; 8808 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange, 8809 /*AllowArraySection=*/true); 8810 if (Res.second) { 8811 // It will be analyzed later. 8812 Vars.push_back(RefExpr); 8813 Privates.push_back(nullptr); 8814 LHSs.push_back(nullptr); 8815 RHSs.push_back(nullptr); 8816 // Try to find 'declare reduction' corresponding construct before using 8817 // builtin/overloaded operators. 8818 QualType Type = Context.DependentTy; 8819 CXXCastPath BasePath; 8820 ExprResult DeclareReductionRef = buildDeclareReductionRef( 8821 *this, ELoc, ERange, DSAStack->getCurScope(), ReductionIdScopeSpec, 8822 ReductionId, Type, BasePath, IR == ER ? nullptr : *IR); 8823 if (CurContext->isDependentContext() && 8824 (DeclareReductionRef.isUnset() || 8825 isa<UnresolvedLookupExpr>(DeclareReductionRef.get()))) 8826 ReductionOps.push_back(DeclareReductionRef.get()); 8827 else 8828 ReductionOps.push_back(nullptr); 8829 } 8830 ValueDecl *D = Res.first; 8831 if (!D) 8832 continue; 8833 8834 QualType Type; 8835 auto *ASE = dyn_cast<ArraySubscriptExpr>(RefExpr->IgnoreParens()); 8836 auto *OASE = dyn_cast<OMPArraySectionExpr>(RefExpr->IgnoreParens()); 8837 if (ASE) 8838 Type = ASE->getType().getNonReferenceType(); 8839 else if (OASE) { 8840 auto BaseType = OMPArraySectionExpr::getBaseOriginalType(OASE->getBase()); 8841 if (auto *ATy = BaseType->getAsArrayTypeUnsafe()) 8842 Type = ATy->getElementType(); 8843 else 8844 Type = BaseType->getPointeeType(); 8845 Type = Type.getNonReferenceType(); 8846 } else 8847 Type = Context.getBaseElementType(D->getType().getNonReferenceType()); 8848 auto *VD = dyn_cast<VarDecl>(D); 8849 8850 // OpenMP [2.9.3.3, Restrictions, C/C++, p.3] 8851 // A variable that appears in a private clause must not have an incomplete 8852 // type or a reference type. 8853 if (RequireCompleteType(ELoc, Type, 8854 diag::err_omp_reduction_incomplete_type)) 8855 continue; 8856 // OpenMP [2.14.3.6, reduction clause, Restrictions] 8857 // A list item that appears in a reduction clause must not be 8858 // const-qualified. 8859 if (Type.getNonReferenceType().isConstant(Context)) { 8860 Diag(ELoc, diag::err_omp_const_reduction_list_item) 8861 << getOpenMPClauseName(OMPC_reduction) << Type << ERange; 8862 if (!ASE && !OASE) { 8863 bool IsDecl = !VD || 8864 VD->isThisDeclarationADefinition(Context) == 8865 VarDecl::DeclarationOnly; 8866 Diag(D->getLocation(), 8867 IsDecl ? diag::note_previous_decl : diag::note_defined_here) 8868 << D; 8869 } 8870 continue; 8871 } 8872 // OpenMP [2.9.3.6, Restrictions, C/C++, p.4] 8873 // If a list-item is a reference type then it must bind to the same object 8874 // for all threads of the team. 8875 if (!ASE && !OASE && VD) { 8876 VarDecl *VDDef = VD->getDefinition(); 8877 if (VD->getType()->isReferenceType() && VDDef && VDDef->hasInit()) { 8878 DSARefChecker Check(DSAStack); 8879 if (Check.Visit(VDDef->getInit())) { 8880 Diag(ELoc, diag::err_omp_reduction_ref_type_arg) << ERange; 8881 Diag(VDDef->getLocation(), diag::note_defined_here) << VDDef; 8882 continue; 8883 } 8884 } 8885 } 8886 8887 // OpenMP [2.14.1.1, Data-sharing Attribute Rules for Variables Referenced 8888 // in a Construct] 8889 // Variables with the predetermined data-sharing attributes may not be 8890 // listed in data-sharing attributes clauses, except for the cases 8891 // listed below. For these exceptions only, listing a predetermined 8892 // variable in a data-sharing attribute clause is allowed and overrides 8893 // the variable's predetermined data-sharing attributes. 8894 // OpenMP [2.14.3.6, Restrictions, p.3] 8895 // Any number of reduction clauses can be specified on the directive, 8896 // but a list item can appear only once in the reduction clauses for that 8897 // directive. 8898 DSAStackTy::DSAVarData DVar; 8899 DVar = DSAStack->getTopDSA(D, false); 8900 if (DVar.CKind == OMPC_reduction) { 8901 Diag(ELoc, diag::err_omp_once_referenced) 8902 << getOpenMPClauseName(OMPC_reduction); 8903 if (DVar.RefExpr) 8904 Diag(DVar.RefExpr->getExprLoc(), diag::note_omp_referenced); 8905 } else if (DVar.CKind != OMPC_unknown) { 8906 Diag(ELoc, diag::err_omp_wrong_dsa) 8907 << getOpenMPClauseName(DVar.CKind) 8908 << getOpenMPClauseName(OMPC_reduction); 8909 ReportOriginalDSA(*this, DSAStack, D, DVar); 8910 continue; 8911 } 8912 8913 // OpenMP [2.14.3.6, Restrictions, p.1] 8914 // A list item that appears in a reduction clause of a worksharing 8915 // construct must be shared in the parallel regions to which any of the 8916 // worksharing regions arising from the worksharing construct bind. 8917 OpenMPDirectiveKind CurrDir = DSAStack->getCurrentDirective(); 8918 if (isOpenMPWorksharingDirective(CurrDir) && 8919 !isOpenMPParallelDirective(CurrDir) && 8920 !isOpenMPTeamsDirective(CurrDir)) { 8921 DVar = DSAStack->getImplicitDSA(D, true); 8922 if (DVar.CKind != OMPC_shared) { 8923 Diag(ELoc, diag::err_omp_required_access) 8924 << getOpenMPClauseName(OMPC_reduction) 8925 << getOpenMPClauseName(OMPC_shared); 8926 ReportOriginalDSA(*this, DSAStack, D, DVar); 8927 continue; 8928 } 8929 } 8930 8931 // Try to find 'declare reduction' corresponding construct before using 8932 // builtin/overloaded operators. 8933 CXXCastPath BasePath; 8934 ExprResult DeclareReductionRef = buildDeclareReductionRef( 8935 *this, ELoc, ERange, DSAStack->getCurScope(), ReductionIdScopeSpec, 8936 ReductionId, Type, BasePath, IR == ER ? nullptr : *IR); 8937 if (DeclareReductionRef.isInvalid()) 8938 continue; 8939 if (CurContext->isDependentContext() && 8940 (DeclareReductionRef.isUnset() || 8941 isa<UnresolvedLookupExpr>(DeclareReductionRef.get()))) { 8942 Vars.push_back(RefExpr); 8943 Privates.push_back(nullptr); 8944 LHSs.push_back(nullptr); 8945 RHSs.push_back(nullptr); 8946 ReductionOps.push_back(DeclareReductionRef.get()); 8947 continue; 8948 } 8949 if (BOK == BO_Comma && DeclareReductionRef.isUnset()) { 8950 // Not allowed reduction identifier is found. 8951 Diag(ReductionId.getLocStart(), 8952 diag::err_omp_unknown_reduction_identifier) 8953 << Type << ReductionIdRange; 8954 continue; 8955 } 8956 8957 // OpenMP [2.14.3.6, reduction clause, Restrictions] 8958 // The type of a list item that appears in a reduction clause must be valid 8959 // for the reduction-identifier. For a max or min reduction in C, the type 8960 // of the list item must be an allowed arithmetic data type: char, int, 8961 // float, double, or _Bool, possibly modified with long, short, signed, or 8962 // unsigned. For a max or min reduction in C++, the type of the list item 8963 // must be an allowed arithmetic data type: char, wchar_t, int, float, 8964 // double, or bool, possibly modified with long, short, signed, or unsigned. 8965 if (DeclareReductionRef.isUnset()) { 8966 if ((BOK == BO_GT || BOK == BO_LT) && 8967 !(Type->isScalarType() || 8968 (getLangOpts().CPlusPlus && Type->isArithmeticType()))) { 8969 Diag(ELoc, diag::err_omp_clause_not_arithmetic_type_arg) 8970 << getLangOpts().CPlusPlus; 8971 if (!ASE && !OASE) { 8972 bool IsDecl = !VD || 8973 VD->isThisDeclarationADefinition(Context) == 8974 VarDecl::DeclarationOnly; 8975 Diag(D->getLocation(), 8976 IsDecl ? diag::note_previous_decl : diag::note_defined_here) 8977 << D; 8978 } 8979 continue; 8980 } 8981 if ((BOK == BO_OrAssign || BOK == BO_AndAssign || BOK == BO_XorAssign) && 8982 !getLangOpts().CPlusPlus && Type->isFloatingType()) { 8983 Diag(ELoc, diag::err_omp_clause_floating_type_arg); 8984 if (!ASE && !OASE) { 8985 bool IsDecl = !VD || 8986 VD->isThisDeclarationADefinition(Context) == 8987 VarDecl::DeclarationOnly; 8988 Diag(D->getLocation(), 8989 IsDecl ? diag::note_previous_decl : diag::note_defined_here) 8990 << D; 8991 } 8992 continue; 8993 } 8994 } 8995 8996 Type = Type.getNonLValueExprType(Context).getUnqualifiedType(); 8997 auto *LHSVD = buildVarDecl(*this, ELoc, Type, ".reduction.lhs", 8998 D->hasAttrs() ? &D->getAttrs() : nullptr); 8999 auto *RHSVD = buildVarDecl(*this, ELoc, Type, D->getName(), 9000 D->hasAttrs() ? &D->getAttrs() : nullptr); 9001 auto PrivateTy = Type; 9002 if (OASE || 9003 (!ASE && 9004 D->getType().getNonReferenceType()->isVariablyModifiedType())) { 9005 // For arrays/array sections only: 9006 // Create pseudo array type for private copy. The size for this array will 9007 // be generated during codegen. 9008 // For array subscripts or single variables Private Ty is the same as Type 9009 // (type of the variable or single array element). 9010 PrivateTy = Context.getVariableArrayType( 9011 Type, new (Context) OpaqueValueExpr(SourceLocation(), 9012 Context.getSizeType(), VK_RValue), 9013 ArrayType::Normal, /*IndexTypeQuals=*/0, SourceRange()); 9014 } else if (!ASE && !OASE && 9015 Context.getAsArrayType(D->getType().getNonReferenceType())) 9016 PrivateTy = D->getType().getNonReferenceType(); 9017 // Private copy. 9018 auto *PrivateVD = buildVarDecl(*this, ELoc, PrivateTy, D->getName(), 9019 D->hasAttrs() ? &D->getAttrs() : nullptr); 9020 // Add initializer for private variable. 9021 Expr *Init = nullptr; 9022 auto *LHSDRE = buildDeclRefExpr(*this, LHSVD, Type, ELoc); 9023 auto *RHSDRE = buildDeclRefExpr(*this, RHSVD, Type, ELoc); 9024 if (DeclareReductionRef.isUsable()) { 9025 auto *DRDRef = DeclareReductionRef.getAs<DeclRefExpr>(); 9026 auto *DRD = cast<OMPDeclareReductionDecl>(DRDRef->getDecl()); 9027 if (DRD->getInitializer()) { 9028 Init = DRDRef; 9029 RHSVD->setInit(DRDRef); 9030 RHSVD->setInitStyle(VarDecl::CallInit); 9031 } 9032 } else { 9033 switch (BOK) { 9034 case BO_Add: 9035 case BO_Xor: 9036 case BO_Or: 9037 case BO_LOr: 9038 // '+', '-', '^', '|', '||' reduction ops - initializer is '0'. 9039 if (Type->isScalarType() || Type->isAnyComplexType()) 9040 Init = ActOnIntegerConstant(ELoc, /*Val=*/0).get(); 9041 break; 9042 case BO_Mul: 9043 case BO_LAnd: 9044 if (Type->isScalarType() || Type->isAnyComplexType()) { 9045 // '*' and '&&' reduction ops - initializer is '1'. 9046 Init = ActOnIntegerConstant(ELoc, /*Val=*/1).get(); 9047 } 9048 break; 9049 case BO_And: { 9050 // '&' reduction op - initializer is '~0'. 9051 QualType OrigType = Type; 9052 if (auto *ComplexTy = OrigType->getAs<ComplexType>()) 9053 Type = ComplexTy->getElementType(); 9054 if (Type->isRealFloatingType()) { 9055 llvm::APFloat InitValue = 9056 llvm::APFloat::getAllOnesValue(Context.getTypeSize(Type), 9057 /*isIEEE=*/true); 9058 Init = FloatingLiteral::Create(Context, InitValue, /*isexact=*/true, 9059 Type, ELoc); 9060 } else if (Type->isScalarType()) { 9061 auto Size = Context.getTypeSize(Type); 9062 QualType IntTy = Context.getIntTypeForBitwidth(Size, /*Signed=*/0); 9063 llvm::APInt InitValue = llvm::APInt::getAllOnesValue(Size); 9064 Init = IntegerLiteral::Create(Context, InitValue, IntTy, ELoc); 9065 } 9066 if (Init && OrigType->isAnyComplexType()) { 9067 // Init = 0xFFFF + 0xFFFFi; 9068 auto *Im = new (Context) ImaginaryLiteral(Init, OrigType); 9069 Init = CreateBuiltinBinOp(ELoc, BO_Add, Init, Im).get(); 9070 } 9071 Type = OrigType; 9072 break; 9073 } 9074 case BO_LT: 9075 case BO_GT: { 9076 // 'min' reduction op - initializer is 'Largest representable number in 9077 // the reduction list item type'. 9078 // 'max' reduction op - initializer is 'Least representable number in 9079 // the reduction list item type'. 9080 if (Type->isIntegerType() || Type->isPointerType()) { 9081 bool IsSigned = Type->hasSignedIntegerRepresentation(); 9082 auto Size = Context.getTypeSize(Type); 9083 QualType IntTy = 9084 Context.getIntTypeForBitwidth(Size, /*Signed=*/IsSigned); 9085 llvm::APInt InitValue = 9086 (BOK != BO_LT) 9087 ? IsSigned ? llvm::APInt::getSignedMinValue(Size) 9088 : llvm::APInt::getMinValue(Size) 9089 : IsSigned ? llvm::APInt::getSignedMaxValue(Size) 9090 : llvm::APInt::getMaxValue(Size); 9091 Init = IntegerLiteral::Create(Context, InitValue, IntTy, ELoc); 9092 if (Type->isPointerType()) { 9093 // Cast to pointer type. 9094 auto CastExpr = BuildCStyleCastExpr( 9095 SourceLocation(), Context.getTrivialTypeSourceInfo(Type, ELoc), 9096 SourceLocation(), Init); 9097 if (CastExpr.isInvalid()) 9098 continue; 9099 Init = CastExpr.get(); 9100 } 9101 } else if (Type->isRealFloatingType()) { 9102 llvm::APFloat InitValue = llvm::APFloat::getLargest( 9103 Context.getFloatTypeSemantics(Type), BOK != BO_LT); 9104 Init = FloatingLiteral::Create(Context, InitValue, /*isexact=*/true, 9105 Type, ELoc); 9106 } 9107 break; 9108 } 9109 case BO_PtrMemD: 9110 case BO_PtrMemI: 9111 case BO_MulAssign: 9112 case BO_Div: 9113 case BO_Rem: 9114 case BO_Sub: 9115 case BO_Shl: 9116 case BO_Shr: 9117 case BO_LE: 9118 case BO_GE: 9119 case BO_EQ: 9120 case BO_NE: 9121 case BO_AndAssign: 9122 case BO_XorAssign: 9123 case BO_OrAssign: 9124 case BO_Assign: 9125 case BO_AddAssign: 9126 case BO_SubAssign: 9127 case BO_DivAssign: 9128 case BO_RemAssign: 9129 case BO_ShlAssign: 9130 case BO_ShrAssign: 9131 case BO_Comma: 9132 llvm_unreachable("Unexpected reduction operation"); 9133 } 9134 } 9135 if (Init && DeclareReductionRef.isUnset()) { 9136 AddInitializerToDecl(RHSVD, Init, /*DirectInit=*/false); 9137 } else if (!Init) 9138 ActOnUninitializedDecl(RHSVD); 9139 if (RHSVD->isInvalidDecl()) 9140 continue; 9141 if (!RHSVD->hasInit() && DeclareReductionRef.isUnset()) { 9142 Diag(ELoc, diag::err_omp_reduction_id_not_compatible) << Type 9143 << ReductionIdRange; 9144 bool IsDecl = 9145 !VD || 9146 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly; 9147 Diag(D->getLocation(), 9148 IsDecl ? diag::note_previous_decl : diag::note_defined_here) 9149 << D; 9150 continue; 9151 } 9152 // Store initializer for single element in private copy. Will be used during 9153 // codegen. 9154 PrivateVD->setInit(RHSVD->getInit()); 9155 PrivateVD->setInitStyle(RHSVD->getInitStyle()); 9156 auto *PrivateDRE = buildDeclRefExpr(*this, PrivateVD, PrivateTy, ELoc); 9157 ExprResult ReductionOp; 9158 if (DeclareReductionRef.isUsable()) { 9159 QualType RedTy = DeclareReductionRef.get()->getType(); 9160 QualType PtrRedTy = Context.getPointerType(RedTy); 9161 ExprResult LHS = CreateBuiltinUnaryOp(ELoc, UO_AddrOf, LHSDRE); 9162 ExprResult RHS = CreateBuiltinUnaryOp(ELoc, UO_AddrOf, RHSDRE); 9163 if (!BasePath.empty()) { 9164 LHS = DefaultLvalueConversion(LHS.get()); 9165 RHS = DefaultLvalueConversion(RHS.get()); 9166 LHS = ImplicitCastExpr::Create(Context, PtrRedTy, 9167 CK_UncheckedDerivedToBase, LHS.get(), 9168 &BasePath, LHS.get()->getValueKind()); 9169 RHS = ImplicitCastExpr::Create(Context, PtrRedTy, 9170 CK_UncheckedDerivedToBase, RHS.get(), 9171 &BasePath, RHS.get()->getValueKind()); 9172 } 9173 FunctionProtoType::ExtProtoInfo EPI; 9174 QualType Params[] = {PtrRedTy, PtrRedTy}; 9175 QualType FnTy = Context.getFunctionType(Context.VoidTy, Params, EPI); 9176 auto *OVE = new (Context) OpaqueValueExpr( 9177 ELoc, Context.getPointerType(FnTy), VK_RValue, OK_Ordinary, 9178 DefaultLvalueConversion(DeclareReductionRef.get()).get()); 9179 Expr *Args[] = {LHS.get(), RHS.get()}; 9180 ReductionOp = new (Context) 9181 CallExpr(Context, OVE, Args, Context.VoidTy, VK_RValue, ELoc); 9182 } else { 9183 ReductionOp = BuildBinOp(DSAStack->getCurScope(), 9184 ReductionId.getLocStart(), BOK, LHSDRE, RHSDRE); 9185 if (ReductionOp.isUsable()) { 9186 if (BOK != BO_LT && BOK != BO_GT) { 9187 ReductionOp = 9188 BuildBinOp(DSAStack->getCurScope(), ReductionId.getLocStart(), 9189 BO_Assign, LHSDRE, ReductionOp.get()); 9190 } else { 9191 auto *ConditionalOp = new (Context) ConditionalOperator( 9192 ReductionOp.get(), SourceLocation(), LHSDRE, SourceLocation(), 9193 RHSDRE, Type, VK_LValue, OK_Ordinary); 9194 ReductionOp = 9195 BuildBinOp(DSAStack->getCurScope(), ReductionId.getLocStart(), 9196 BO_Assign, LHSDRE, ConditionalOp); 9197 } 9198 ReductionOp = ActOnFinishFullExpr(ReductionOp.get()); 9199 } 9200 if (ReductionOp.isInvalid()) 9201 continue; 9202 } 9203 9204 DeclRefExpr *Ref = nullptr; 9205 Expr *VarsExpr = RefExpr->IgnoreParens(); 9206 if (!VD && !CurContext->isDependentContext()) { 9207 if (ASE || OASE) { 9208 TransformExprToCaptures RebuildToCapture(*this, D); 9209 VarsExpr = 9210 RebuildToCapture.TransformExpr(RefExpr->IgnoreParens()).get(); 9211 Ref = RebuildToCapture.getCapturedExpr(); 9212 } else { 9213 VarsExpr = Ref = 9214 buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/false); 9215 } 9216 if (!IsOpenMPCapturedDecl(D)) { 9217 ExprCaptures.push_back(Ref->getDecl()); 9218 if (Ref->getDecl()->hasAttr<OMPCaptureNoInitAttr>()) { 9219 ExprResult RefRes = DefaultLvalueConversion(Ref); 9220 if (!RefRes.isUsable()) 9221 continue; 9222 ExprResult PostUpdateRes = 9223 BuildBinOp(DSAStack->getCurScope(), ELoc, BO_Assign, 9224 SimpleRefExpr, RefRes.get()); 9225 if (!PostUpdateRes.isUsable()) 9226 continue; 9227 ExprPostUpdates.push_back( 9228 IgnoredValueConversions(PostUpdateRes.get()).get()); 9229 } 9230 } 9231 } 9232 DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_reduction, Ref); 9233 Vars.push_back(VarsExpr); 9234 Privates.push_back(PrivateDRE); 9235 LHSs.push_back(LHSDRE); 9236 RHSs.push_back(RHSDRE); 9237 ReductionOps.push_back(ReductionOp.get()); 9238 } 9239 9240 if (Vars.empty()) 9241 return nullptr; 9242 9243 return OMPReductionClause::Create( 9244 Context, StartLoc, LParenLoc, ColonLoc, EndLoc, Vars, 9245 ReductionIdScopeSpec.getWithLocInContext(Context), ReductionId, Privates, 9246 LHSs, RHSs, ReductionOps, buildPreInits(Context, ExprCaptures), 9247 buildPostUpdate(*this, ExprPostUpdates)); 9248 } 9249 9250 bool Sema::CheckOpenMPLinearModifier(OpenMPLinearClauseKind LinKind, 9251 SourceLocation LinLoc) { 9252 if ((!LangOpts.CPlusPlus && LinKind != OMPC_LINEAR_val) || 9253 LinKind == OMPC_LINEAR_unknown) { 9254 Diag(LinLoc, diag::err_omp_wrong_linear_modifier) << LangOpts.CPlusPlus; 9255 return true; 9256 } 9257 return false; 9258 } 9259 9260 bool Sema::CheckOpenMPLinearDecl(ValueDecl *D, SourceLocation ELoc, 9261 OpenMPLinearClauseKind LinKind, 9262 QualType Type) { 9263 auto *VD = dyn_cast_or_null<VarDecl>(D); 9264 // A variable must not have an incomplete type or a reference type. 9265 if (RequireCompleteType(ELoc, Type, diag::err_omp_linear_incomplete_type)) 9266 return true; 9267 if ((LinKind == OMPC_LINEAR_uval || LinKind == OMPC_LINEAR_ref) && 9268 !Type->isReferenceType()) { 9269 Diag(ELoc, diag::err_omp_wrong_linear_modifier_non_reference) 9270 << Type << getOpenMPSimpleClauseTypeName(OMPC_linear, LinKind); 9271 return true; 9272 } 9273 Type = Type.getNonReferenceType(); 9274 9275 // A list item must not be const-qualified. 9276 if (Type.isConstant(Context)) { 9277 Diag(ELoc, diag::err_omp_const_variable) 9278 << getOpenMPClauseName(OMPC_linear); 9279 if (D) { 9280 bool IsDecl = 9281 !VD || 9282 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly; 9283 Diag(D->getLocation(), 9284 IsDecl ? diag::note_previous_decl : diag::note_defined_here) 9285 << D; 9286 } 9287 return true; 9288 } 9289 9290 // A list item must be of integral or pointer type. 9291 Type = Type.getUnqualifiedType().getCanonicalType(); 9292 const auto *Ty = Type.getTypePtrOrNull(); 9293 if (!Ty || (!Ty->isDependentType() && !Ty->isIntegralType(Context) && 9294 !Ty->isPointerType())) { 9295 Diag(ELoc, diag::err_omp_linear_expected_int_or_ptr) << Type; 9296 if (D) { 9297 bool IsDecl = 9298 !VD || 9299 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly; 9300 Diag(D->getLocation(), 9301 IsDecl ? diag::note_previous_decl : diag::note_defined_here) 9302 << D; 9303 } 9304 return true; 9305 } 9306 return false; 9307 } 9308 9309 OMPClause *Sema::ActOnOpenMPLinearClause( 9310 ArrayRef<Expr *> VarList, Expr *Step, SourceLocation StartLoc, 9311 SourceLocation LParenLoc, OpenMPLinearClauseKind LinKind, 9312 SourceLocation LinLoc, SourceLocation ColonLoc, SourceLocation EndLoc) { 9313 SmallVector<Expr *, 8> Vars; 9314 SmallVector<Expr *, 8> Privates; 9315 SmallVector<Expr *, 8> Inits; 9316 SmallVector<Decl *, 4> ExprCaptures; 9317 SmallVector<Expr *, 4> ExprPostUpdates; 9318 if (CheckOpenMPLinearModifier(LinKind, LinLoc)) 9319 LinKind = OMPC_LINEAR_val; 9320 for (auto &RefExpr : VarList) { 9321 assert(RefExpr && "NULL expr in OpenMP linear clause."); 9322 SourceLocation ELoc; 9323 SourceRange ERange; 9324 Expr *SimpleRefExpr = RefExpr; 9325 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange, 9326 /*AllowArraySection=*/false); 9327 if (Res.second) { 9328 // It will be analyzed later. 9329 Vars.push_back(RefExpr); 9330 Privates.push_back(nullptr); 9331 Inits.push_back(nullptr); 9332 } 9333 ValueDecl *D = Res.first; 9334 if (!D) 9335 continue; 9336 9337 QualType Type = D->getType(); 9338 auto *VD = dyn_cast<VarDecl>(D); 9339 9340 // OpenMP [2.14.3.7, linear clause] 9341 // A list-item cannot appear in more than one linear clause. 9342 // A list-item that appears in a linear clause cannot appear in any 9343 // other data-sharing attribute clause. 9344 DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, false); 9345 if (DVar.RefExpr) { 9346 Diag(ELoc, diag::err_omp_wrong_dsa) << getOpenMPClauseName(DVar.CKind) 9347 << getOpenMPClauseName(OMPC_linear); 9348 ReportOriginalDSA(*this, DSAStack, D, DVar); 9349 continue; 9350 } 9351 9352 if (CheckOpenMPLinearDecl(D, ELoc, LinKind, Type)) 9353 continue; 9354 Type = Type.getNonReferenceType().getUnqualifiedType().getCanonicalType(); 9355 9356 // Build private copy of original var. 9357 auto *Private = buildVarDecl(*this, ELoc, Type, D->getName(), 9358 D->hasAttrs() ? &D->getAttrs() : nullptr); 9359 auto *PrivateRef = buildDeclRefExpr(*this, Private, Type, ELoc); 9360 // Build var to save initial value. 9361 VarDecl *Init = buildVarDecl(*this, ELoc, Type, ".linear.start"); 9362 Expr *InitExpr; 9363 DeclRefExpr *Ref = nullptr; 9364 if (!VD && !CurContext->isDependentContext()) { 9365 Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/false); 9366 if (!IsOpenMPCapturedDecl(D)) { 9367 ExprCaptures.push_back(Ref->getDecl()); 9368 if (Ref->getDecl()->hasAttr<OMPCaptureNoInitAttr>()) { 9369 ExprResult RefRes = DefaultLvalueConversion(Ref); 9370 if (!RefRes.isUsable()) 9371 continue; 9372 ExprResult PostUpdateRes = 9373 BuildBinOp(DSAStack->getCurScope(), ELoc, BO_Assign, 9374 SimpleRefExpr, RefRes.get()); 9375 if (!PostUpdateRes.isUsable()) 9376 continue; 9377 ExprPostUpdates.push_back( 9378 IgnoredValueConversions(PostUpdateRes.get()).get()); 9379 } 9380 } 9381 } 9382 if (LinKind == OMPC_LINEAR_uval) 9383 InitExpr = VD ? VD->getInit() : SimpleRefExpr; 9384 else 9385 InitExpr = VD ? SimpleRefExpr : Ref; 9386 AddInitializerToDecl(Init, DefaultLvalueConversion(InitExpr).get(), 9387 /*DirectInit=*/false); 9388 auto InitRef = buildDeclRefExpr(*this, Init, Type, ELoc); 9389 9390 DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_linear, Ref); 9391 Vars.push_back((VD || CurContext->isDependentContext()) 9392 ? RefExpr->IgnoreParens() 9393 : Ref); 9394 Privates.push_back(PrivateRef); 9395 Inits.push_back(InitRef); 9396 } 9397 9398 if (Vars.empty()) 9399 return nullptr; 9400 9401 Expr *StepExpr = Step; 9402 Expr *CalcStepExpr = nullptr; 9403 if (Step && !Step->isValueDependent() && !Step->isTypeDependent() && 9404 !Step->isInstantiationDependent() && 9405 !Step->containsUnexpandedParameterPack()) { 9406 SourceLocation StepLoc = Step->getLocStart(); 9407 ExprResult Val = PerformOpenMPImplicitIntegerConversion(StepLoc, Step); 9408 if (Val.isInvalid()) 9409 return nullptr; 9410 StepExpr = Val.get(); 9411 9412 // Build var to save the step value. 9413 VarDecl *SaveVar = 9414 buildVarDecl(*this, StepLoc, StepExpr->getType(), ".linear.step"); 9415 ExprResult SaveRef = 9416 buildDeclRefExpr(*this, SaveVar, StepExpr->getType(), StepLoc); 9417 ExprResult CalcStep = 9418 BuildBinOp(CurScope, StepLoc, BO_Assign, SaveRef.get(), StepExpr); 9419 CalcStep = ActOnFinishFullExpr(CalcStep.get()); 9420 9421 // Warn about zero linear step (it would be probably better specified as 9422 // making corresponding variables 'const'). 9423 llvm::APSInt Result; 9424 bool IsConstant = StepExpr->isIntegerConstantExpr(Result, Context); 9425 if (IsConstant && !Result.isNegative() && !Result.isStrictlyPositive()) 9426 Diag(StepLoc, diag::warn_omp_linear_step_zero) << Vars[0] 9427 << (Vars.size() > 1); 9428 if (!IsConstant && CalcStep.isUsable()) { 9429 // Calculate the step beforehand instead of doing this on each iteration. 9430 // (This is not used if the number of iterations may be kfold-ed). 9431 CalcStepExpr = CalcStep.get(); 9432 } 9433 } 9434 9435 return OMPLinearClause::Create(Context, StartLoc, LParenLoc, LinKind, LinLoc, 9436 ColonLoc, EndLoc, Vars, Privates, Inits, 9437 StepExpr, CalcStepExpr, 9438 buildPreInits(Context, ExprCaptures), 9439 buildPostUpdate(*this, ExprPostUpdates)); 9440 } 9441 9442 static bool FinishOpenMPLinearClause(OMPLinearClause &Clause, DeclRefExpr *IV, 9443 Expr *NumIterations, Sema &SemaRef, 9444 Scope *S, DSAStackTy *Stack) { 9445 // Walk the vars and build update/final expressions for the CodeGen. 9446 SmallVector<Expr *, 8> Updates; 9447 SmallVector<Expr *, 8> Finals; 9448 Expr *Step = Clause.getStep(); 9449 Expr *CalcStep = Clause.getCalcStep(); 9450 // OpenMP [2.14.3.7, linear clause] 9451 // If linear-step is not specified it is assumed to be 1. 9452 if (Step == nullptr) 9453 Step = SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get(); 9454 else if (CalcStep) { 9455 Step = cast<BinaryOperator>(CalcStep)->getLHS(); 9456 } 9457 bool HasErrors = false; 9458 auto CurInit = Clause.inits().begin(); 9459 auto CurPrivate = Clause.privates().begin(); 9460 auto LinKind = Clause.getModifier(); 9461 for (auto &RefExpr : Clause.varlists()) { 9462 SourceLocation ELoc; 9463 SourceRange ERange; 9464 Expr *SimpleRefExpr = RefExpr; 9465 auto Res = getPrivateItem(SemaRef, SimpleRefExpr, ELoc, ERange, 9466 /*AllowArraySection=*/false); 9467 ValueDecl *D = Res.first; 9468 if (Res.second || !D) { 9469 Updates.push_back(nullptr); 9470 Finals.push_back(nullptr); 9471 HasErrors = true; 9472 continue; 9473 } 9474 if (auto *CED = dyn_cast<OMPCapturedExprDecl>(D)) { 9475 D = cast<MemberExpr>(CED->getInit()->IgnoreParenImpCasts()) 9476 ->getMemberDecl(); 9477 } 9478 auto &&Info = Stack->isLoopControlVariable(D); 9479 Expr *InitExpr = *CurInit; 9480 9481 // Build privatized reference to the current linear var. 9482 auto *DE = cast<DeclRefExpr>(SimpleRefExpr); 9483 Expr *CapturedRef; 9484 if (LinKind == OMPC_LINEAR_uval) 9485 CapturedRef = cast<VarDecl>(DE->getDecl())->getInit(); 9486 else 9487 CapturedRef = 9488 buildDeclRefExpr(SemaRef, cast<VarDecl>(DE->getDecl()), 9489 DE->getType().getUnqualifiedType(), DE->getExprLoc(), 9490 /*RefersToCapture=*/true); 9491 9492 // Build update: Var = InitExpr + IV * Step 9493 ExprResult Update; 9494 if (!Info.first) { 9495 Update = 9496 BuildCounterUpdate(SemaRef, S, RefExpr->getExprLoc(), *CurPrivate, 9497 InitExpr, IV, Step, /* Subtract */ false); 9498 } else 9499 Update = *CurPrivate; 9500 Update = SemaRef.ActOnFinishFullExpr(Update.get(), DE->getLocStart(), 9501 /*DiscardedValue=*/true); 9502 9503 // Build final: Var = InitExpr + NumIterations * Step 9504 ExprResult Final; 9505 if (!Info.first) { 9506 Final = BuildCounterUpdate(SemaRef, S, RefExpr->getExprLoc(), CapturedRef, 9507 InitExpr, NumIterations, Step, 9508 /* Subtract */ false); 9509 } else 9510 Final = *CurPrivate; 9511 Final = SemaRef.ActOnFinishFullExpr(Final.get(), DE->getLocStart(), 9512 /*DiscardedValue=*/true); 9513 9514 if (!Update.isUsable() || !Final.isUsable()) { 9515 Updates.push_back(nullptr); 9516 Finals.push_back(nullptr); 9517 HasErrors = true; 9518 } else { 9519 Updates.push_back(Update.get()); 9520 Finals.push_back(Final.get()); 9521 } 9522 ++CurInit; 9523 ++CurPrivate; 9524 } 9525 Clause.setUpdates(Updates); 9526 Clause.setFinals(Finals); 9527 return HasErrors; 9528 } 9529 9530 OMPClause *Sema::ActOnOpenMPAlignedClause( 9531 ArrayRef<Expr *> VarList, Expr *Alignment, SourceLocation StartLoc, 9532 SourceLocation LParenLoc, SourceLocation ColonLoc, SourceLocation EndLoc) { 9533 9534 SmallVector<Expr *, 8> Vars; 9535 for (auto &RefExpr : VarList) { 9536 assert(RefExpr && "NULL expr in OpenMP linear clause."); 9537 SourceLocation ELoc; 9538 SourceRange ERange; 9539 Expr *SimpleRefExpr = RefExpr; 9540 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange, 9541 /*AllowArraySection=*/false); 9542 if (Res.second) { 9543 // It will be analyzed later. 9544 Vars.push_back(RefExpr); 9545 } 9546 ValueDecl *D = Res.first; 9547 if (!D) 9548 continue; 9549 9550 QualType QType = D->getType(); 9551 auto *VD = dyn_cast<VarDecl>(D); 9552 9553 // OpenMP [2.8.1, simd construct, Restrictions] 9554 // The type of list items appearing in the aligned clause must be 9555 // array, pointer, reference to array, or reference to pointer. 9556 QType = QType.getNonReferenceType().getUnqualifiedType().getCanonicalType(); 9557 const Type *Ty = QType.getTypePtrOrNull(); 9558 if (!Ty || (!Ty->isArrayType() && !Ty->isPointerType())) { 9559 Diag(ELoc, diag::err_omp_aligned_expected_array_or_ptr) 9560 << QType << getLangOpts().CPlusPlus << ERange; 9561 bool IsDecl = 9562 !VD || 9563 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly; 9564 Diag(D->getLocation(), 9565 IsDecl ? diag::note_previous_decl : diag::note_defined_here) 9566 << D; 9567 continue; 9568 } 9569 9570 // OpenMP [2.8.1, simd construct, Restrictions] 9571 // A list-item cannot appear in more than one aligned clause. 9572 if (Expr *PrevRef = DSAStack->addUniqueAligned(D, SimpleRefExpr)) { 9573 Diag(ELoc, diag::err_omp_aligned_twice) << 0 << ERange; 9574 Diag(PrevRef->getExprLoc(), diag::note_omp_explicit_dsa) 9575 << getOpenMPClauseName(OMPC_aligned); 9576 continue; 9577 } 9578 9579 DeclRefExpr *Ref = nullptr; 9580 if (!VD && IsOpenMPCapturedDecl(D)) 9581 Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/true); 9582 Vars.push_back(DefaultFunctionArrayConversion( 9583 (VD || !Ref) ? RefExpr->IgnoreParens() : Ref) 9584 .get()); 9585 } 9586 9587 // OpenMP [2.8.1, simd construct, Description] 9588 // The parameter of the aligned clause, alignment, must be a constant 9589 // positive integer expression. 9590 // If no optional parameter is specified, implementation-defined default 9591 // alignments for SIMD instructions on the target platforms are assumed. 9592 if (Alignment != nullptr) { 9593 ExprResult AlignResult = 9594 VerifyPositiveIntegerConstantInClause(Alignment, OMPC_aligned); 9595 if (AlignResult.isInvalid()) 9596 return nullptr; 9597 Alignment = AlignResult.get(); 9598 } 9599 if (Vars.empty()) 9600 return nullptr; 9601 9602 return OMPAlignedClause::Create(Context, StartLoc, LParenLoc, ColonLoc, 9603 EndLoc, Vars, Alignment); 9604 } 9605 9606 OMPClause *Sema::ActOnOpenMPCopyinClause(ArrayRef<Expr *> VarList, 9607 SourceLocation StartLoc, 9608 SourceLocation LParenLoc, 9609 SourceLocation EndLoc) { 9610 SmallVector<Expr *, 8> Vars; 9611 SmallVector<Expr *, 8> SrcExprs; 9612 SmallVector<Expr *, 8> DstExprs; 9613 SmallVector<Expr *, 8> AssignmentOps; 9614 for (auto &RefExpr : VarList) { 9615 assert(RefExpr && "NULL expr in OpenMP copyin clause."); 9616 if (isa<DependentScopeDeclRefExpr>(RefExpr)) { 9617 // It will be analyzed later. 9618 Vars.push_back(RefExpr); 9619 SrcExprs.push_back(nullptr); 9620 DstExprs.push_back(nullptr); 9621 AssignmentOps.push_back(nullptr); 9622 continue; 9623 } 9624 9625 SourceLocation ELoc = RefExpr->getExprLoc(); 9626 // OpenMP [2.1, C/C++] 9627 // A list item is a variable name. 9628 // OpenMP [2.14.4.1, Restrictions, p.1] 9629 // A list item that appears in a copyin clause must be threadprivate. 9630 DeclRefExpr *DE = dyn_cast<DeclRefExpr>(RefExpr); 9631 if (!DE || !isa<VarDecl>(DE->getDecl())) { 9632 Diag(ELoc, diag::err_omp_expected_var_name_member_expr) 9633 << 0 << RefExpr->getSourceRange(); 9634 continue; 9635 } 9636 9637 Decl *D = DE->getDecl(); 9638 VarDecl *VD = cast<VarDecl>(D); 9639 9640 QualType Type = VD->getType(); 9641 if (Type->isDependentType() || Type->isInstantiationDependentType()) { 9642 // It will be analyzed later. 9643 Vars.push_back(DE); 9644 SrcExprs.push_back(nullptr); 9645 DstExprs.push_back(nullptr); 9646 AssignmentOps.push_back(nullptr); 9647 continue; 9648 } 9649 9650 // OpenMP [2.14.4.1, Restrictions, C/C++, p.1] 9651 // A list item that appears in a copyin clause must be threadprivate. 9652 if (!DSAStack->isThreadPrivate(VD)) { 9653 Diag(ELoc, diag::err_omp_required_access) 9654 << getOpenMPClauseName(OMPC_copyin) 9655 << getOpenMPDirectiveName(OMPD_threadprivate); 9656 continue; 9657 } 9658 9659 // OpenMP [2.14.4.1, Restrictions, C/C++, p.2] 9660 // A variable of class type (or array thereof) that appears in a 9661 // copyin clause requires an accessible, unambiguous copy assignment 9662 // operator for the class type. 9663 auto ElemType = Context.getBaseElementType(Type).getNonReferenceType(); 9664 auto *SrcVD = 9665 buildVarDecl(*this, DE->getLocStart(), ElemType.getUnqualifiedType(), 9666 ".copyin.src", VD->hasAttrs() ? &VD->getAttrs() : nullptr); 9667 auto *PseudoSrcExpr = buildDeclRefExpr( 9668 *this, SrcVD, ElemType.getUnqualifiedType(), DE->getExprLoc()); 9669 auto *DstVD = 9670 buildVarDecl(*this, DE->getLocStart(), ElemType, ".copyin.dst", 9671 VD->hasAttrs() ? &VD->getAttrs() : nullptr); 9672 auto *PseudoDstExpr = 9673 buildDeclRefExpr(*this, DstVD, ElemType, DE->getExprLoc()); 9674 // For arrays generate assignment operation for single element and replace 9675 // it by the original array element in CodeGen. 9676 auto AssignmentOp = BuildBinOp(/*S=*/nullptr, DE->getExprLoc(), BO_Assign, 9677 PseudoDstExpr, PseudoSrcExpr); 9678 if (AssignmentOp.isInvalid()) 9679 continue; 9680 AssignmentOp = ActOnFinishFullExpr(AssignmentOp.get(), DE->getExprLoc(), 9681 /*DiscardedValue=*/true); 9682 if (AssignmentOp.isInvalid()) 9683 continue; 9684 9685 DSAStack->addDSA(VD, DE, OMPC_copyin); 9686 Vars.push_back(DE); 9687 SrcExprs.push_back(PseudoSrcExpr); 9688 DstExprs.push_back(PseudoDstExpr); 9689 AssignmentOps.push_back(AssignmentOp.get()); 9690 } 9691 9692 if (Vars.empty()) 9693 return nullptr; 9694 9695 return OMPCopyinClause::Create(Context, StartLoc, LParenLoc, EndLoc, Vars, 9696 SrcExprs, DstExprs, AssignmentOps); 9697 } 9698 9699 OMPClause *Sema::ActOnOpenMPCopyprivateClause(ArrayRef<Expr *> VarList, 9700 SourceLocation StartLoc, 9701 SourceLocation LParenLoc, 9702 SourceLocation EndLoc) { 9703 SmallVector<Expr *, 8> Vars; 9704 SmallVector<Expr *, 8> SrcExprs; 9705 SmallVector<Expr *, 8> DstExprs; 9706 SmallVector<Expr *, 8> AssignmentOps; 9707 for (auto &RefExpr : VarList) { 9708 assert(RefExpr && "NULL expr in OpenMP linear clause."); 9709 SourceLocation ELoc; 9710 SourceRange ERange; 9711 Expr *SimpleRefExpr = RefExpr; 9712 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange, 9713 /*AllowArraySection=*/false); 9714 if (Res.second) { 9715 // It will be analyzed later. 9716 Vars.push_back(RefExpr); 9717 SrcExprs.push_back(nullptr); 9718 DstExprs.push_back(nullptr); 9719 AssignmentOps.push_back(nullptr); 9720 } 9721 ValueDecl *D = Res.first; 9722 if (!D) 9723 continue; 9724 9725 QualType Type = D->getType(); 9726 auto *VD = dyn_cast<VarDecl>(D); 9727 9728 // OpenMP [2.14.4.2, Restrictions, p.2] 9729 // A list item that appears in a copyprivate clause may not appear in a 9730 // private or firstprivate clause on the single construct. 9731 if (!VD || !DSAStack->isThreadPrivate(VD)) { 9732 auto DVar = DSAStack->getTopDSA(D, false); 9733 if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_copyprivate && 9734 DVar.RefExpr) { 9735 Diag(ELoc, diag::err_omp_wrong_dsa) 9736 << getOpenMPClauseName(DVar.CKind) 9737 << getOpenMPClauseName(OMPC_copyprivate); 9738 ReportOriginalDSA(*this, DSAStack, D, DVar); 9739 continue; 9740 } 9741 9742 // OpenMP [2.11.4.2, Restrictions, p.1] 9743 // All list items that appear in a copyprivate clause must be either 9744 // threadprivate or private in the enclosing context. 9745 if (DVar.CKind == OMPC_unknown) { 9746 DVar = DSAStack->getImplicitDSA(D, false); 9747 if (DVar.CKind == OMPC_shared) { 9748 Diag(ELoc, diag::err_omp_required_access) 9749 << getOpenMPClauseName(OMPC_copyprivate) 9750 << "threadprivate or private in the enclosing context"; 9751 ReportOriginalDSA(*this, DSAStack, D, DVar); 9752 continue; 9753 } 9754 } 9755 } 9756 9757 // Variably modified types are not supported. 9758 if (!Type->isAnyPointerType() && Type->isVariablyModifiedType()) { 9759 Diag(ELoc, diag::err_omp_variably_modified_type_not_supported) 9760 << getOpenMPClauseName(OMPC_copyprivate) << Type 9761 << getOpenMPDirectiveName(DSAStack->getCurrentDirective()); 9762 bool IsDecl = 9763 !VD || 9764 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly; 9765 Diag(D->getLocation(), 9766 IsDecl ? diag::note_previous_decl : diag::note_defined_here) 9767 << D; 9768 continue; 9769 } 9770 9771 // OpenMP [2.14.4.1, Restrictions, C/C++, p.2] 9772 // A variable of class type (or array thereof) that appears in a 9773 // copyin clause requires an accessible, unambiguous copy assignment 9774 // operator for the class type. 9775 Type = Context.getBaseElementType(Type.getNonReferenceType()) 9776 .getUnqualifiedType(); 9777 auto *SrcVD = 9778 buildVarDecl(*this, RefExpr->getLocStart(), Type, ".copyprivate.src", 9779 D->hasAttrs() ? &D->getAttrs() : nullptr); 9780 auto *PseudoSrcExpr = buildDeclRefExpr(*this, SrcVD, Type, ELoc); 9781 auto *DstVD = 9782 buildVarDecl(*this, RefExpr->getLocStart(), Type, ".copyprivate.dst", 9783 D->hasAttrs() ? &D->getAttrs() : nullptr); 9784 auto *PseudoDstExpr = buildDeclRefExpr(*this, DstVD, Type, ELoc); 9785 auto AssignmentOp = BuildBinOp(DSAStack->getCurScope(), ELoc, BO_Assign, 9786 PseudoDstExpr, PseudoSrcExpr); 9787 if (AssignmentOp.isInvalid()) 9788 continue; 9789 AssignmentOp = ActOnFinishFullExpr(AssignmentOp.get(), ELoc, 9790 /*DiscardedValue=*/true); 9791 if (AssignmentOp.isInvalid()) 9792 continue; 9793 9794 // No need to mark vars as copyprivate, they are already threadprivate or 9795 // implicitly private. 9796 assert(VD || IsOpenMPCapturedDecl(D)); 9797 Vars.push_back( 9798 VD ? RefExpr->IgnoreParens() 9799 : buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/false)); 9800 SrcExprs.push_back(PseudoSrcExpr); 9801 DstExprs.push_back(PseudoDstExpr); 9802 AssignmentOps.push_back(AssignmentOp.get()); 9803 } 9804 9805 if (Vars.empty()) 9806 return nullptr; 9807 9808 return OMPCopyprivateClause::Create(Context, StartLoc, LParenLoc, EndLoc, 9809 Vars, SrcExprs, DstExprs, AssignmentOps); 9810 } 9811 9812 OMPClause *Sema::ActOnOpenMPFlushClause(ArrayRef<Expr *> VarList, 9813 SourceLocation StartLoc, 9814 SourceLocation LParenLoc, 9815 SourceLocation EndLoc) { 9816 if (VarList.empty()) 9817 return nullptr; 9818 9819 return OMPFlushClause::Create(Context, StartLoc, LParenLoc, EndLoc, VarList); 9820 } 9821 9822 OMPClause * 9823 Sema::ActOnOpenMPDependClause(OpenMPDependClauseKind DepKind, 9824 SourceLocation DepLoc, SourceLocation ColonLoc, 9825 ArrayRef<Expr *> VarList, SourceLocation StartLoc, 9826 SourceLocation LParenLoc, SourceLocation EndLoc) { 9827 if (DSAStack->getCurrentDirective() == OMPD_ordered && 9828 DepKind != OMPC_DEPEND_source && DepKind != OMPC_DEPEND_sink) { 9829 Diag(DepLoc, diag::err_omp_unexpected_clause_value) 9830 << "'source' or 'sink'" << getOpenMPClauseName(OMPC_depend); 9831 return nullptr; 9832 } 9833 if (DSAStack->getCurrentDirective() != OMPD_ordered && 9834 (DepKind == OMPC_DEPEND_unknown || DepKind == OMPC_DEPEND_source || 9835 DepKind == OMPC_DEPEND_sink)) { 9836 unsigned Except[] = {OMPC_DEPEND_source, OMPC_DEPEND_sink}; 9837 Diag(DepLoc, diag::err_omp_unexpected_clause_value) 9838 << getListOfPossibleValues(OMPC_depend, /*First=*/0, 9839 /*Last=*/OMPC_DEPEND_unknown, Except) 9840 << getOpenMPClauseName(OMPC_depend); 9841 return nullptr; 9842 } 9843 SmallVector<Expr *, 8> Vars; 9844 DSAStackTy::OperatorOffsetTy OpsOffs; 9845 llvm::APSInt DepCounter(/*BitWidth=*/32); 9846 llvm::APSInt TotalDepCount(/*BitWidth=*/32); 9847 if (DepKind == OMPC_DEPEND_sink) { 9848 if (auto *OrderedCountExpr = DSAStack->getParentOrderedRegionParam()) { 9849 TotalDepCount = OrderedCountExpr->EvaluateKnownConstInt(Context); 9850 TotalDepCount.setIsUnsigned(/*Val=*/true); 9851 } 9852 } 9853 if ((DepKind != OMPC_DEPEND_sink && DepKind != OMPC_DEPEND_source) || 9854 DSAStack->getParentOrderedRegionParam()) { 9855 for (auto &RefExpr : VarList) { 9856 assert(RefExpr && "NULL expr in OpenMP shared clause."); 9857 if (isa<DependentScopeDeclRefExpr>(RefExpr)) { 9858 // It will be analyzed later. 9859 Vars.push_back(RefExpr); 9860 continue; 9861 } 9862 9863 SourceLocation ELoc = RefExpr->getExprLoc(); 9864 auto *SimpleExpr = RefExpr->IgnoreParenCasts(); 9865 if (DepKind == OMPC_DEPEND_sink) { 9866 if (DepCounter >= TotalDepCount) { 9867 Diag(ELoc, diag::err_omp_depend_sink_unexpected_expr); 9868 continue; 9869 } 9870 ++DepCounter; 9871 // OpenMP [2.13.9, Summary] 9872 // depend(dependence-type : vec), where dependence-type is: 9873 // 'sink' and where vec is the iteration vector, which has the form: 9874 // x1 [+- d1], x2 [+- d2 ], . . . , xn [+- dn] 9875 // where n is the value specified by the ordered clause in the loop 9876 // directive, xi denotes the loop iteration variable of the i-th nested 9877 // loop associated with the loop directive, and di is a constant 9878 // non-negative integer. 9879 if (CurContext->isDependentContext()) { 9880 // It will be analyzed later. 9881 Vars.push_back(RefExpr); 9882 continue; 9883 } 9884 SimpleExpr = SimpleExpr->IgnoreImplicit(); 9885 OverloadedOperatorKind OOK = OO_None; 9886 SourceLocation OOLoc; 9887 Expr *LHS = SimpleExpr; 9888 Expr *RHS = nullptr; 9889 if (auto *BO = dyn_cast<BinaryOperator>(SimpleExpr)) { 9890 OOK = BinaryOperator::getOverloadedOperator(BO->getOpcode()); 9891 OOLoc = BO->getOperatorLoc(); 9892 LHS = BO->getLHS()->IgnoreParenImpCasts(); 9893 RHS = BO->getRHS()->IgnoreParenImpCasts(); 9894 } else if (auto *OCE = dyn_cast<CXXOperatorCallExpr>(SimpleExpr)) { 9895 OOK = OCE->getOperator(); 9896 OOLoc = OCE->getOperatorLoc(); 9897 LHS = OCE->getArg(/*Arg=*/0)->IgnoreParenImpCasts(); 9898 RHS = OCE->getArg(/*Arg=*/1)->IgnoreParenImpCasts(); 9899 } else if (auto *MCE = dyn_cast<CXXMemberCallExpr>(SimpleExpr)) { 9900 OOK = MCE->getMethodDecl() 9901 ->getNameInfo() 9902 .getName() 9903 .getCXXOverloadedOperator(); 9904 OOLoc = MCE->getCallee()->getExprLoc(); 9905 LHS = MCE->getImplicitObjectArgument()->IgnoreParenImpCasts(); 9906 RHS = MCE->getArg(/*Arg=*/0)->IgnoreParenImpCasts(); 9907 } 9908 SourceLocation ELoc; 9909 SourceRange ERange; 9910 auto Res = getPrivateItem(*this, LHS, ELoc, ERange, 9911 /*AllowArraySection=*/false); 9912 if (Res.second) { 9913 // It will be analyzed later. 9914 Vars.push_back(RefExpr); 9915 } 9916 ValueDecl *D = Res.first; 9917 if (!D) 9918 continue; 9919 9920 if (OOK != OO_Plus && OOK != OO_Minus && (RHS || OOK != OO_None)) { 9921 Diag(OOLoc, diag::err_omp_depend_sink_expected_plus_minus); 9922 continue; 9923 } 9924 if (RHS) { 9925 ExprResult RHSRes = VerifyPositiveIntegerConstantInClause( 9926 RHS, OMPC_depend, /*StrictlyPositive=*/false); 9927 if (RHSRes.isInvalid()) 9928 continue; 9929 } 9930 if (!CurContext->isDependentContext() && 9931 DSAStack->getParentOrderedRegionParam() && 9932 DepCounter != DSAStack->isParentLoopControlVariable(D).first) { 9933 Diag(ELoc, diag::err_omp_depend_sink_expected_loop_iteration) 9934 << DSAStack->getParentLoopControlVariable( 9935 DepCounter.getZExtValue()); 9936 continue; 9937 } 9938 OpsOffs.push_back({RHS, OOK}); 9939 } else { 9940 // OpenMP [2.11.1.1, Restrictions, p.3] 9941 // A variable that is part of another variable (such as a field of a 9942 // structure) but is not an array element or an array section cannot 9943 // appear in a depend clause. 9944 auto *DE = dyn_cast<DeclRefExpr>(SimpleExpr); 9945 auto *ASE = dyn_cast<ArraySubscriptExpr>(SimpleExpr); 9946 auto *OASE = dyn_cast<OMPArraySectionExpr>(SimpleExpr); 9947 if (!RefExpr->IgnoreParenImpCasts()->isLValue() || 9948 (!ASE && !DE && !OASE) || (DE && !isa<VarDecl>(DE->getDecl())) || 9949 (ASE && 9950 !ASE->getBase() 9951 ->getType() 9952 .getNonReferenceType() 9953 ->isPointerType() && 9954 !ASE->getBase()->getType().getNonReferenceType()->isArrayType())) { 9955 Diag(ELoc, diag::err_omp_expected_var_name_member_expr_or_array_item) 9956 << 0 << RefExpr->getSourceRange(); 9957 continue; 9958 } 9959 } 9960 Vars.push_back(RefExpr->IgnoreParenImpCasts()); 9961 } 9962 9963 if (!CurContext->isDependentContext() && DepKind == OMPC_DEPEND_sink && 9964 TotalDepCount > VarList.size() && 9965 DSAStack->getParentOrderedRegionParam()) { 9966 Diag(EndLoc, diag::err_omp_depend_sink_expected_loop_iteration) 9967 << DSAStack->getParentLoopControlVariable(VarList.size() + 1); 9968 } 9969 if (DepKind != OMPC_DEPEND_source && DepKind != OMPC_DEPEND_sink && 9970 Vars.empty()) 9971 return nullptr; 9972 } 9973 auto *C = OMPDependClause::Create(Context, StartLoc, LParenLoc, EndLoc, 9974 DepKind, DepLoc, ColonLoc, Vars); 9975 if (DepKind == OMPC_DEPEND_sink || DepKind == OMPC_DEPEND_source) 9976 DSAStack->addDoacrossDependClause(C, OpsOffs); 9977 return C; 9978 } 9979 9980 OMPClause *Sema::ActOnOpenMPDeviceClause(Expr *Device, SourceLocation StartLoc, 9981 SourceLocation LParenLoc, 9982 SourceLocation EndLoc) { 9983 Expr *ValExpr = Device; 9984 9985 // OpenMP [2.9.1, Restrictions] 9986 // The device expression must evaluate to a non-negative integer value. 9987 if (!IsNonNegativeIntegerValue(ValExpr, *this, OMPC_device, 9988 /*StrictlyPositive=*/false)) 9989 return nullptr; 9990 9991 return new (Context) OMPDeviceClause(ValExpr, StartLoc, LParenLoc, EndLoc); 9992 } 9993 9994 static bool IsCXXRecordForMappable(Sema &SemaRef, SourceLocation Loc, 9995 DSAStackTy *Stack, CXXRecordDecl *RD) { 9996 if (!RD || RD->isInvalidDecl()) 9997 return true; 9998 9999 auto QTy = SemaRef.Context.getRecordType(RD); 10000 if (RD->isDynamicClass()) { 10001 SemaRef.Diag(Loc, diag::err_omp_not_mappable_type) << QTy; 10002 SemaRef.Diag(RD->getLocation(), diag::note_omp_polymorphic_in_target); 10003 return false; 10004 } 10005 auto *DC = RD; 10006 bool IsCorrect = true; 10007 for (auto *I : DC->decls()) { 10008 if (I) { 10009 if (auto *MD = dyn_cast<CXXMethodDecl>(I)) { 10010 if (MD->isStatic()) { 10011 SemaRef.Diag(Loc, diag::err_omp_not_mappable_type) << QTy; 10012 SemaRef.Diag(MD->getLocation(), 10013 diag::note_omp_static_member_in_target); 10014 IsCorrect = false; 10015 } 10016 } else if (auto *VD = dyn_cast<VarDecl>(I)) { 10017 if (VD->isStaticDataMember()) { 10018 SemaRef.Diag(Loc, diag::err_omp_not_mappable_type) << QTy; 10019 SemaRef.Diag(VD->getLocation(), 10020 diag::note_omp_static_member_in_target); 10021 IsCorrect = false; 10022 } 10023 } 10024 } 10025 } 10026 10027 for (auto &I : RD->bases()) { 10028 if (!IsCXXRecordForMappable(SemaRef, I.getLocStart(), Stack, 10029 I.getType()->getAsCXXRecordDecl())) 10030 IsCorrect = false; 10031 } 10032 return IsCorrect; 10033 } 10034 10035 static bool CheckTypeMappable(SourceLocation SL, SourceRange SR, Sema &SemaRef, 10036 DSAStackTy *Stack, QualType QTy) { 10037 NamedDecl *ND; 10038 if (QTy->isIncompleteType(&ND)) { 10039 SemaRef.Diag(SL, diag::err_incomplete_type) << QTy << SR; 10040 return false; 10041 } else if (CXXRecordDecl *RD = dyn_cast_or_null<CXXRecordDecl>(ND)) { 10042 if (!RD->isInvalidDecl() && !IsCXXRecordForMappable(SemaRef, SL, Stack, RD)) 10043 return false; 10044 } 10045 return true; 10046 } 10047 10048 /// \brief Return true if it can be proven that the provided array expression 10049 /// (array section or array subscript) does NOT specify the whole size of the 10050 /// array whose base type is \a BaseQTy. 10051 static bool CheckArrayExpressionDoesNotReferToWholeSize(Sema &SemaRef, 10052 const Expr *E, 10053 QualType BaseQTy) { 10054 auto *OASE = dyn_cast<OMPArraySectionExpr>(E); 10055 10056 // If this is an array subscript, it refers to the whole size if the size of 10057 // the dimension is constant and equals 1. Also, an array section assumes the 10058 // format of an array subscript if no colon is used. 10059 if (isa<ArraySubscriptExpr>(E) || (OASE && OASE->getColonLoc().isInvalid())) { 10060 if (auto *ATy = dyn_cast<ConstantArrayType>(BaseQTy.getTypePtr())) 10061 return ATy->getSize().getSExtValue() != 1; 10062 // Size can't be evaluated statically. 10063 return false; 10064 } 10065 10066 assert(OASE && "Expecting array section if not an array subscript."); 10067 auto *LowerBound = OASE->getLowerBound(); 10068 auto *Length = OASE->getLength(); 10069 10070 // If there is a lower bound that does not evaluates to zero, we are not 10071 // covering the whole dimension. 10072 if (LowerBound) { 10073 llvm::APSInt ConstLowerBound; 10074 if (!LowerBound->EvaluateAsInt(ConstLowerBound, SemaRef.getASTContext())) 10075 return false; // Can't get the integer value as a constant. 10076 if (ConstLowerBound.getSExtValue()) 10077 return true; 10078 } 10079 10080 // If we don't have a length we covering the whole dimension. 10081 if (!Length) 10082 return false; 10083 10084 // If the base is a pointer, we don't have a way to get the size of the 10085 // pointee. 10086 if (BaseQTy->isPointerType()) 10087 return false; 10088 10089 // We can only check if the length is the same as the size of the dimension 10090 // if we have a constant array. 10091 auto *CATy = dyn_cast<ConstantArrayType>(BaseQTy.getTypePtr()); 10092 if (!CATy) 10093 return false; 10094 10095 llvm::APSInt ConstLength; 10096 if (!Length->EvaluateAsInt(ConstLength, SemaRef.getASTContext())) 10097 return false; // Can't get the integer value as a constant. 10098 10099 return CATy->getSize().getSExtValue() != ConstLength.getSExtValue(); 10100 } 10101 10102 // Return true if it can be proven that the provided array expression (array 10103 // section or array subscript) does NOT specify a single element of the array 10104 // whose base type is \a BaseQTy. 10105 static bool CheckArrayExpressionDoesNotReferToUnitySize(Sema &SemaRef, 10106 const Expr *E, 10107 QualType BaseQTy) { 10108 auto *OASE = dyn_cast<OMPArraySectionExpr>(E); 10109 10110 // An array subscript always refer to a single element. Also, an array section 10111 // assumes the format of an array subscript if no colon is used. 10112 if (isa<ArraySubscriptExpr>(E) || (OASE && OASE->getColonLoc().isInvalid())) 10113 return false; 10114 10115 assert(OASE && "Expecting array section if not an array subscript."); 10116 auto *Length = OASE->getLength(); 10117 10118 // If we don't have a length we have to check if the array has unitary size 10119 // for this dimension. Also, we should always expect a length if the base type 10120 // is pointer. 10121 if (!Length) { 10122 if (auto *ATy = dyn_cast<ConstantArrayType>(BaseQTy.getTypePtr())) 10123 return ATy->getSize().getSExtValue() != 1; 10124 // We cannot assume anything. 10125 return false; 10126 } 10127 10128 // Check if the length evaluates to 1. 10129 llvm::APSInt ConstLength; 10130 if (!Length->EvaluateAsInt(ConstLength, SemaRef.getASTContext())) 10131 return false; // Can't get the integer value as a constant. 10132 10133 return ConstLength.getSExtValue() != 1; 10134 } 10135 10136 // Return the expression of the base of the mappable expression or null if it 10137 // cannot be determined and do all the necessary checks to see if the expression 10138 // is valid as a standalone mappable expression. In the process, record all the 10139 // components of the expression. 10140 static Expr *CheckMapClauseExpressionBase( 10141 Sema &SemaRef, Expr *E, 10142 OMPClauseMappableExprCommon::MappableExprComponentList &CurComponents, 10143 OpenMPClauseKind CKind) { 10144 SourceLocation ELoc = E->getExprLoc(); 10145 SourceRange ERange = E->getSourceRange(); 10146 10147 // The base of elements of list in a map clause have to be either: 10148 // - a reference to variable or field. 10149 // - a member expression. 10150 // - an array expression. 10151 // 10152 // E.g. if we have the expression 'r.S.Arr[:12]', we want to retrieve the 10153 // reference to 'r'. 10154 // 10155 // If we have: 10156 // 10157 // struct SS { 10158 // Bla S; 10159 // foo() { 10160 // #pragma omp target map (S.Arr[:12]); 10161 // } 10162 // } 10163 // 10164 // We want to retrieve the member expression 'this->S'; 10165 10166 Expr *RelevantExpr = nullptr; 10167 10168 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.2] 10169 // If a list item is an array section, it must specify contiguous storage. 10170 // 10171 // For this restriction it is sufficient that we make sure only references 10172 // to variables or fields and array expressions, and that no array sections 10173 // exist except in the rightmost expression (unless they cover the whole 10174 // dimension of the array). E.g. these would be invalid: 10175 // 10176 // r.ArrS[3:5].Arr[6:7] 10177 // 10178 // r.ArrS[3:5].x 10179 // 10180 // but these would be valid: 10181 // r.ArrS[3].Arr[6:7] 10182 // 10183 // r.ArrS[3].x 10184 10185 bool AllowUnitySizeArraySection = true; 10186 bool AllowWholeSizeArraySection = true; 10187 10188 while (!RelevantExpr) { 10189 E = E->IgnoreParenImpCasts(); 10190 10191 if (auto *CurE = dyn_cast<DeclRefExpr>(E)) { 10192 if (!isa<VarDecl>(CurE->getDecl())) 10193 break; 10194 10195 RelevantExpr = CurE; 10196 10197 // If we got a reference to a declaration, we should not expect any array 10198 // section before that. 10199 AllowUnitySizeArraySection = false; 10200 AllowWholeSizeArraySection = false; 10201 10202 // Record the component. 10203 CurComponents.push_back(OMPClauseMappableExprCommon::MappableComponent( 10204 CurE, CurE->getDecl())); 10205 continue; 10206 } 10207 10208 if (auto *CurE = dyn_cast<MemberExpr>(E)) { 10209 auto *BaseE = CurE->getBase()->IgnoreParenImpCasts(); 10210 10211 if (isa<CXXThisExpr>(BaseE)) 10212 // We found a base expression: this->Val. 10213 RelevantExpr = CurE; 10214 else 10215 E = BaseE; 10216 10217 if (!isa<FieldDecl>(CurE->getMemberDecl())) { 10218 SemaRef.Diag(ELoc, diag::err_omp_expected_access_to_data_field) 10219 << CurE->getSourceRange(); 10220 break; 10221 } 10222 10223 auto *FD = cast<FieldDecl>(CurE->getMemberDecl()); 10224 10225 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C/C++, p.3] 10226 // A bit-field cannot appear in a map clause. 10227 // 10228 if (FD->isBitField()) { 10229 SemaRef.Diag(ELoc, diag::err_omp_bit_fields_forbidden_in_clause) 10230 << CurE->getSourceRange() << getOpenMPClauseName(CKind); 10231 break; 10232 } 10233 10234 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C++, p.1] 10235 // If the type of a list item is a reference to a type T then the type 10236 // will be considered to be T for all purposes of this clause. 10237 QualType CurType = BaseE->getType().getNonReferenceType(); 10238 10239 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C/C++, p.2] 10240 // A list item cannot be a variable that is a member of a structure with 10241 // a union type. 10242 // 10243 if (auto *RT = CurType->getAs<RecordType>()) 10244 if (RT->isUnionType()) { 10245 SemaRef.Diag(ELoc, diag::err_omp_union_type_not_allowed) 10246 << CurE->getSourceRange(); 10247 break; 10248 } 10249 10250 // If we got a member expression, we should not expect any array section 10251 // before that: 10252 // 10253 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.7] 10254 // If a list item is an element of a structure, only the rightmost symbol 10255 // of the variable reference can be an array section. 10256 // 10257 AllowUnitySizeArraySection = false; 10258 AllowWholeSizeArraySection = false; 10259 10260 // Record the component. 10261 CurComponents.push_back( 10262 OMPClauseMappableExprCommon::MappableComponent(CurE, FD)); 10263 continue; 10264 } 10265 10266 if (auto *CurE = dyn_cast<ArraySubscriptExpr>(E)) { 10267 E = CurE->getBase()->IgnoreParenImpCasts(); 10268 10269 if (!E->getType()->isAnyPointerType() && !E->getType()->isArrayType()) { 10270 SemaRef.Diag(ELoc, diag::err_omp_expected_base_var_name) 10271 << 0 << CurE->getSourceRange(); 10272 break; 10273 } 10274 10275 // If we got an array subscript that express the whole dimension we 10276 // can have any array expressions before. If it only expressing part of 10277 // the dimension, we can only have unitary-size array expressions. 10278 if (CheckArrayExpressionDoesNotReferToWholeSize(SemaRef, CurE, 10279 E->getType())) 10280 AllowWholeSizeArraySection = false; 10281 10282 // Record the component - we don't have any declaration associated. 10283 CurComponents.push_back( 10284 OMPClauseMappableExprCommon::MappableComponent(CurE, nullptr)); 10285 continue; 10286 } 10287 10288 if (auto *CurE = dyn_cast<OMPArraySectionExpr>(E)) { 10289 E = CurE->getBase()->IgnoreParenImpCasts(); 10290 10291 auto CurType = 10292 OMPArraySectionExpr::getBaseOriginalType(E).getCanonicalType(); 10293 10294 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C++, p.1] 10295 // If the type of a list item is a reference to a type T then the type 10296 // will be considered to be T for all purposes of this clause. 10297 if (CurType->isReferenceType()) 10298 CurType = CurType->getPointeeType(); 10299 10300 bool IsPointer = CurType->isAnyPointerType(); 10301 10302 if (!IsPointer && !CurType->isArrayType()) { 10303 SemaRef.Diag(ELoc, diag::err_omp_expected_base_var_name) 10304 << 0 << CurE->getSourceRange(); 10305 break; 10306 } 10307 10308 bool NotWhole = 10309 CheckArrayExpressionDoesNotReferToWholeSize(SemaRef, CurE, CurType); 10310 bool NotUnity = 10311 CheckArrayExpressionDoesNotReferToUnitySize(SemaRef, CurE, CurType); 10312 10313 if (AllowWholeSizeArraySection) { 10314 // Any array section is currently allowed. Allowing a whole size array 10315 // section implies allowing a unity array section as well. 10316 // 10317 // If this array section refers to the whole dimension we can still 10318 // accept other array sections before this one, except if the base is a 10319 // pointer. Otherwise, only unitary sections are accepted. 10320 if (NotWhole || IsPointer) 10321 AllowWholeSizeArraySection = false; 10322 } else if (AllowUnitySizeArraySection && NotUnity) { 10323 // A unity or whole array section is not allowed and that is not 10324 // compatible with the properties of the current array section. 10325 SemaRef.Diag( 10326 ELoc, diag::err_array_section_does_not_specify_contiguous_storage) 10327 << CurE->getSourceRange(); 10328 break; 10329 } 10330 10331 // Record the component - we don't have any declaration associated. 10332 CurComponents.push_back( 10333 OMPClauseMappableExprCommon::MappableComponent(CurE, nullptr)); 10334 continue; 10335 } 10336 10337 // If nothing else worked, this is not a valid map clause expression. 10338 SemaRef.Diag(ELoc, 10339 diag::err_omp_expected_named_var_member_or_array_expression) 10340 << ERange; 10341 break; 10342 } 10343 10344 return RelevantExpr; 10345 } 10346 10347 // Return true if expression E associated with value VD has conflicts with other 10348 // map information. 10349 static bool CheckMapConflicts( 10350 Sema &SemaRef, DSAStackTy *DSAS, ValueDecl *VD, Expr *E, 10351 bool CurrentRegionOnly, 10352 OMPClauseMappableExprCommon::MappableExprComponentListRef CurComponents, 10353 OpenMPClauseKind CKind) { 10354 assert(VD && E); 10355 SourceLocation ELoc = E->getExprLoc(); 10356 SourceRange ERange = E->getSourceRange(); 10357 10358 // In order to easily check the conflicts we need to match each component of 10359 // the expression under test with the components of the expressions that are 10360 // already in the stack. 10361 10362 assert(!CurComponents.empty() && "Map clause expression with no components!"); 10363 assert(CurComponents.back().getAssociatedDeclaration() == VD && 10364 "Map clause expression with unexpected base!"); 10365 10366 // Variables to help detecting enclosing problems in data environment nests. 10367 bool IsEnclosedByDataEnvironmentExpr = false; 10368 const Expr *EnclosingExpr = nullptr; 10369 10370 bool FoundError = DSAS->checkMappableExprComponentListsForDecl( 10371 VD, CurrentRegionOnly, 10372 [&](OMPClauseMappableExprCommon::MappableExprComponentListRef 10373 StackComponents, 10374 OpenMPClauseKind) -> bool { 10375 10376 assert(!StackComponents.empty() && 10377 "Map clause expression with no components!"); 10378 assert(StackComponents.back().getAssociatedDeclaration() == VD && 10379 "Map clause expression with unexpected base!"); 10380 10381 // The whole expression in the stack. 10382 auto *RE = StackComponents.front().getAssociatedExpression(); 10383 10384 // Expressions must start from the same base. Here we detect at which 10385 // point both expressions diverge from each other and see if we can 10386 // detect if the memory referred to both expressions is contiguous and 10387 // do not overlap. 10388 auto CI = CurComponents.rbegin(); 10389 auto CE = CurComponents.rend(); 10390 auto SI = StackComponents.rbegin(); 10391 auto SE = StackComponents.rend(); 10392 for (; CI != CE && SI != SE; ++CI, ++SI) { 10393 10394 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.3] 10395 // At most one list item can be an array item derived from a given 10396 // variable in map clauses of the same construct. 10397 if (CurrentRegionOnly && 10398 (isa<ArraySubscriptExpr>(CI->getAssociatedExpression()) || 10399 isa<OMPArraySectionExpr>(CI->getAssociatedExpression())) && 10400 (isa<ArraySubscriptExpr>(SI->getAssociatedExpression()) || 10401 isa<OMPArraySectionExpr>(SI->getAssociatedExpression()))) { 10402 SemaRef.Diag(CI->getAssociatedExpression()->getExprLoc(), 10403 diag::err_omp_multiple_array_items_in_map_clause) 10404 << CI->getAssociatedExpression()->getSourceRange(); 10405 SemaRef.Diag(SI->getAssociatedExpression()->getExprLoc(), 10406 diag::note_used_here) 10407 << SI->getAssociatedExpression()->getSourceRange(); 10408 return true; 10409 } 10410 10411 // Do both expressions have the same kind? 10412 if (CI->getAssociatedExpression()->getStmtClass() != 10413 SI->getAssociatedExpression()->getStmtClass()) 10414 break; 10415 10416 // Are we dealing with different variables/fields? 10417 if (CI->getAssociatedDeclaration() != SI->getAssociatedDeclaration()) 10418 break; 10419 } 10420 // Check if the extra components of the expressions in the enclosing 10421 // data environment are redundant for the current base declaration. 10422 // If they are, the maps completely overlap, which is legal. 10423 for (; SI != SE; ++SI) { 10424 QualType Type; 10425 if (auto *ASE = 10426 dyn_cast<ArraySubscriptExpr>(SI->getAssociatedExpression())) { 10427 Type = ASE->getBase()->IgnoreParenImpCasts()->getType(); 10428 } else if (auto *OASE = dyn_cast<OMPArraySectionExpr>( 10429 SI->getAssociatedExpression())) { 10430 auto *E = OASE->getBase()->IgnoreParenImpCasts(); 10431 Type = 10432 OMPArraySectionExpr::getBaseOriginalType(E).getCanonicalType(); 10433 } 10434 if (Type.isNull() || Type->isAnyPointerType() || 10435 CheckArrayExpressionDoesNotReferToWholeSize( 10436 SemaRef, SI->getAssociatedExpression(), Type)) 10437 break; 10438 } 10439 10440 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.4] 10441 // List items of map clauses in the same construct must not share 10442 // original storage. 10443 // 10444 // If the expressions are exactly the same or one is a subset of the 10445 // other, it means they are sharing storage. 10446 if (CI == CE && SI == SE) { 10447 if (CurrentRegionOnly) { 10448 if (CKind == OMPC_map) 10449 SemaRef.Diag(ELoc, diag::err_omp_map_shared_storage) << ERange; 10450 else { 10451 assert(CKind == OMPC_to || CKind == OMPC_from); 10452 SemaRef.Diag(ELoc, diag::err_omp_once_referenced_in_target_update) 10453 << ERange; 10454 } 10455 SemaRef.Diag(RE->getExprLoc(), diag::note_used_here) 10456 << RE->getSourceRange(); 10457 return true; 10458 } else { 10459 // If we find the same expression in the enclosing data environment, 10460 // that is legal. 10461 IsEnclosedByDataEnvironmentExpr = true; 10462 return false; 10463 } 10464 } 10465 10466 QualType DerivedType = 10467 std::prev(CI)->getAssociatedDeclaration()->getType(); 10468 SourceLocation DerivedLoc = 10469 std::prev(CI)->getAssociatedExpression()->getExprLoc(); 10470 10471 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C++, p.1] 10472 // If the type of a list item is a reference to a type T then the type 10473 // will be considered to be T for all purposes of this clause. 10474 DerivedType = DerivedType.getNonReferenceType(); 10475 10476 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C/C++, p.1] 10477 // A variable for which the type is pointer and an array section 10478 // derived from that variable must not appear as list items of map 10479 // clauses of the same construct. 10480 // 10481 // Also, cover one of the cases in: 10482 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.5] 10483 // If any part of the original storage of a list item has corresponding 10484 // storage in the device data environment, all of the original storage 10485 // must have corresponding storage in the device data environment. 10486 // 10487 if (DerivedType->isAnyPointerType()) { 10488 if (CI == CE || SI == SE) { 10489 SemaRef.Diag( 10490 DerivedLoc, 10491 diag::err_omp_pointer_mapped_along_with_derived_section) 10492 << DerivedLoc; 10493 } else { 10494 assert(CI != CE && SI != SE); 10495 SemaRef.Diag(DerivedLoc, diag::err_omp_same_pointer_derreferenced) 10496 << DerivedLoc; 10497 } 10498 SemaRef.Diag(RE->getExprLoc(), diag::note_used_here) 10499 << RE->getSourceRange(); 10500 return true; 10501 } 10502 10503 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.4] 10504 // List items of map clauses in the same construct must not share 10505 // original storage. 10506 // 10507 // An expression is a subset of the other. 10508 if (CurrentRegionOnly && (CI == CE || SI == SE)) { 10509 if (CKind == OMPC_map) 10510 SemaRef.Diag(ELoc, diag::err_omp_map_shared_storage) << ERange; 10511 else { 10512 assert(CKind == OMPC_to || CKind == OMPC_from); 10513 SemaRef.Diag(ELoc, diag::err_omp_once_referenced_in_target_update) 10514 << ERange; 10515 } 10516 SemaRef.Diag(RE->getExprLoc(), diag::note_used_here) 10517 << RE->getSourceRange(); 10518 return true; 10519 } 10520 10521 // The current expression uses the same base as other expression in the 10522 // data environment but does not contain it completely. 10523 if (!CurrentRegionOnly && SI != SE) 10524 EnclosingExpr = RE; 10525 10526 // The current expression is a subset of the expression in the data 10527 // environment. 10528 IsEnclosedByDataEnvironmentExpr |= 10529 (!CurrentRegionOnly && CI != CE && SI == SE); 10530 10531 return false; 10532 }); 10533 10534 if (CurrentRegionOnly) 10535 return FoundError; 10536 10537 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.5] 10538 // If any part of the original storage of a list item has corresponding 10539 // storage in the device data environment, all of the original storage must 10540 // have corresponding storage in the device data environment. 10541 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.6] 10542 // If a list item is an element of a structure, and a different element of 10543 // the structure has a corresponding list item in the device data environment 10544 // prior to a task encountering the construct associated with the map clause, 10545 // then the list item must also have a corresponding list item in the device 10546 // data environment prior to the task encountering the construct. 10547 // 10548 if (EnclosingExpr && !IsEnclosedByDataEnvironmentExpr) { 10549 SemaRef.Diag(ELoc, 10550 diag::err_omp_original_storage_is_shared_and_does_not_contain) 10551 << ERange; 10552 SemaRef.Diag(EnclosingExpr->getExprLoc(), diag::note_used_here) 10553 << EnclosingExpr->getSourceRange(); 10554 return true; 10555 } 10556 10557 return FoundError; 10558 } 10559 10560 namespace { 10561 // Utility struct that gathers all the related lists associated with a mappable 10562 // expression. 10563 struct MappableVarListInfo final { 10564 // The list of expressions. 10565 ArrayRef<Expr *> VarList; 10566 // The list of processed expressions. 10567 SmallVector<Expr *, 16> ProcessedVarList; 10568 // The mappble components for each expression. 10569 OMPClauseMappableExprCommon::MappableExprComponentLists VarComponents; 10570 // The base declaration of the variable. 10571 SmallVector<ValueDecl *, 16> VarBaseDeclarations; 10572 10573 MappableVarListInfo(ArrayRef<Expr *> VarList) : VarList(VarList) { 10574 // We have a list of components and base declarations for each entry in the 10575 // variable list. 10576 VarComponents.reserve(VarList.size()); 10577 VarBaseDeclarations.reserve(VarList.size()); 10578 } 10579 }; 10580 } 10581 10582 // Check the validity of the provided variable list for the provided clause kind 10583 // \a CKind. In the check process the valid expressions, and mappable expression 10584 // components and variables are extracted and used to fill \a Vars, 10585 // \a ClauseComponents, and \a ClauseBaseDeclarations. \a MapType and 10586 // \a IsMapTypeImplicit are expected to be valid if the clause kind is 'map'. 10587 static void 10588 checkMappableExpressionList(Sema &SemaRef, DSAStackTy *DSAS, 10589 OpenMPClauseKind CKind, MappableVarListInfo &MVLI, 10590 SourceLocation StartLoc, 10591 OpenMPMapClauseKind MapType = OMPC_MAP_unknown, 10592 bool IsMapTypeImplicit = false) { 10593 // We only expect mappable expressions in 'to', 'from', and 'map' clauses. 10594 assert((CKind == OMPC_map || CKind == OMPC_to || CKind == OMPC_from) && 10595 "Unexpected clause kind with mappable expressions!"); 10596 10597 // Keep track of the mappable components and base declarations in this clause. 10598 // Each entry in the list is going to have a list of components associated. We 10599 // record each set of the components so that we can build the clause later on. 10600 // In the end we should have the same amount of declarations and component 10601 // lists. 10602 10603 for (auto &RE : MVLI.VarList) { 10604 assert(RE && "Null expr in omp to/from/map clause"); 10605 SourceLocation ELoc = RE->getExprLoc(); 10606 10607 auto *VE = RE->IgnoreParenLValueCasts(); 10608 10609 if (VE->isValueDependent() || VE->isTypeDependent() || 10610 VE->isInstantiationDependent() || 10611 VE->containsUnexpandedParameterPack()) { 10612 // We can only analyze this information once the missing information is 10613 // resolved. 10614 MVLI.ProcessedVarList.push_back(RE); 10615 continue; 10616 } 10617 10618 auto *SimpleExpr = RE->IgnoreParenCasts(); 10619 10620 if (!RE->IgnoreParenImpCasts()->isLValue()) { 10621 SemaRef.Diag(ELoc, 10622 diag::err_omp_expected_named_var_member_or_array_expression) 10623 << RE->getSourceRange(); 10624 continue; 10625 } 10626 10627 OMPClauseMappableExprCommon::MappableExprComponentList CurComponents; 10628 ValueDecl *CurDeclaration = nullptr; 10629 10630 // Obtain the array or member expression bases if required. Also, fill the 10631 // components array with all the components identified in the process. 10632 auto *BE = 10633 CheckMapClauseExpressionBase(SemaRef, SimpleExpr, CurComponents, CKind); 10634 if (!BE) 10635 continue; 10636 10637 assert(!CurComponents.empty() && 10638 "Invalid mappable expression information."); 10639 10640 // For the following checks, we rely on the base declaration which is 10641 // expected to be associated with the last component. The declaration is 10642 // expected to be a variable or a field (if 'this' is being mapped). 10643 CurDeclaration = CurComponents.back().getAssociatedDeclaration(); 10644 assert(CurDeclaration && "Null decl on map clause."); 10645 assert( 10646 CurDeclaration->isCanonicalDecl() && 10647 "Expecting components to have associated only canonical declarations."); 10648 10649 auto *VD = dyn_cast<VarDecl>(CurDeclaration); 10650 auto *FD = dyn_cast<FieldDecl>(CurDeclaration); 10651 10652 assert((VD || FD) && "Only variables or fields are expected here!"); 10653 (void)FD; 10654 10655 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.10] 10656 // threadprivate variables cannot appear in a map clause. 10657 // OpenMP 4.5 [2.10.5, target update Construct] 10658 // threadprivate variables cannot appear in a from clause. 10659 if (VD && DSAS->isThreadPrivate(VD)) { 10660 auto DVar = DSAS->getTopDSA(VD, false); 10661 SemaRef.Diag(ELoc, diag::err_omp_threadprivate_in_clause) 10662 << getOpenMPClauseName(CKind); 10663 ReportOriginalDSA(SemaRef, DSAS, VD, DVar); 10664 continue; 10665 } 10666 10667 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.9] 10668 // A list item cannot appear in both a map clause and a data-sharing 10669 // attribute clause on the same construct. 10670 10671 // Check conflicts with other map clause expressions. We check the conflicts 10672 // with the current construct separately from the enclosing data 10673 // environment, because the restrictions are different. We only have to 10674 // check conflicts across regions for the map clauses. 10675 if (CheckMapConflicts(SemaRef, DSAS, CurDeclaration, SimpleExpr, 10676 /*CurrentRegionOnly=*/true, CurComponents, CKind)) 10677 break; 10678 if (CKind == OMPC_map && 10679 CheckMapConflicts(SemaRef, DSAS, CurDeclaration, SimpleExpr, 10680 /*CurrentRegionOnly=*/false, CurComponents, CKind)) 10681 break; 10682 10683 // OpenMP 4.5 [2.10.5, target update Construct] 10684 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C++, p.1] 10685 // If the type of a list item is a reference to a type T then the type will 10686 // be considered to be T for all purposes of this clause. 10687 QualType Type = CurDeclaration->getType().getNonReferenceType(); 10688 10689 // OpenMP 4.5 [2.10.5, target update Construct, Restrictions, p.4] 10690 // A list item in a to or from clause must have a mappable type. 10691 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.9] 10692 // A list item must have a mappable type. 10693 if (!CheckTypeMappable(VE->getExprLoc(), VE->getSourceRange(), SemaRef, 10694 DSAS, Type)) 10695 continue; 10696 10697 if (CKind == OMPC_map) { 10698 // target enter data 10699 // OpenMP [2.10.2, Restrictions, p. 99] 10700 // A map-type must be specified in all map clauses and must be either 10701 // to or alloc. 10702 OpenMPDirectiveKind DKind = DSAS->getCurrentDirective(); 10703 if (DKind == OMPD_target_enter_data && 10704 !(MapType == OMPC_MAP_to || MapType == OMPC_MAP_alloc)) { 10705 SemaRef.Diag(StartLoc, diag::err_omp_invalid_map_type_for_directive) 10706 << (IsMapTypeImplicit ? 1 : 0) 10707 << getOpenMPSimpleClauseTypeName(OMPC_map, MapType) 10708 << getOpenMPDirectiveName(DKind); 10709 continue; 10710 } 10711 10712 // target exit_data 10713 // OpenMP [2.10.3, Restrictions, p. 102] 10714 // A map-type must be specified in all map clauses and must be either 10715 // from, release, or delete. 10716 if (DKind == OMPD_target_exit_data && 10717 !(MapType == OMPC_MAP_from || MapType == OMPC_MAP_release || 10718 MapType == OMPC_MAP_delete)) { 10719 SemaRef.Diag(StartLoc, diag::err_omp_invalid_map_type_for_directive) 10720 << (IsMapTypeImplicit ? 1 : 0) 10721 << getOpenMPSimpleClauseTypeName(OMPC_map, MapType) 10722 << getOpenMPDirectiveName(DKind); 10723 continue; 10724 } 10725 10726 // OpenMP 4.5 [2.15.5.1, Restrictions, p.3] 10727 // A list item cannot appear in both a map clause and a data-sharing 10728 // attribute clause on the same construct 10729 if ((DKind == OMPD_target || DKind == OMPD_target_teams || 10730 DKind == OMPD_target_teams_distribute || 10731 DKind == OMPD_target_teams_distribute_parallel_for || 10732 DKind == OMPD_target_teams_distribute_parallel_for_simd || 10733 DKind == OMPD_target_teams_distribute_simd) && VD) { 10734 auto DVar = DSAS->getTopDSA(VD, false); 10735 if (isOpenMPPrivate(DVar.CKind)) { 10736 SemaRef.Diag(ELoc, diag::err_omp_variable_in_given_clause_and_dsa) 10737 << getOpenMPClauseName(DVar.CKind) 10738 << getOpenMPClauseName(OMPC_map) 10739 << getOpenMPDirectiveName(DSAS->getCurrentDirective()); 10740 ReportOriginalDSA(SemaRef, DSAS, CurDeclaration, DVar); 10741 continue; 10742 } 10743 } 10744 } 10745 10746 // Save the current expression. 10747 MVLI.ProcessedVarList.push_back(RE); 10748 10749 // Store the components in the stack so that they can be used to check 10750 // against other clauses later on. 10751 DSAS->addMappableExpressionComponents(CurDeclaration, CurComponents, 10752 /*WhereFoundClauseKind=*/OMPC_map); 10753 10754 // Save the components and declaration to create the clause. For purposes of 10755 // the clause creation, any component list that has has base 'this' uses 10756 // null as base declaration. 10757 MVLI.VarComponents.resize(MVLI.VarComponents.size() + 1); 10758 MVLI.VarComponents.back().append(CurComponents.begin(), 10759 CurComponents.end()); 10760 MVLI.VarBaseDeclarations.push_back(isa<MemberExpr>(BE) ? nullptr 10761 : CurDeclaration); 10762 } 10763 } 10764 10765 OMPClause * 10766 Sema::ActOnOpenMPMapClause(OpenMPMapClauseKind MapTypeModifier, 10767 OpenMPMapClauseKind MapType, bool IsMapTypeImplicit, 10768 SourceLocation MapLoc, SourceLocation ColonLoc, 10769 ArrayRef<Expr *> VarList, SourceLocation StartLoc, 10770 SourceLocation LParenLoc, SourceLocation EndLoc) { 10771 MappableVarListInfo MVLI(VarList); 10772 checkMappableExpressionList(*this, DSAStack, OMPC_map, MVLI, StartLoc, 10773 MapType, IsMapTypeImplicit); 10774 10775 // We need to produce a map clause even if we don't have variables so that 10776 // other diagnostics related with non-existing map clauses are accurate. 10777 return OMPMapClause::Create(Context, StartLoc, LParenLoc, EndLoc, 10778 MVLI.ProcessedVarList, MVLI.VarBaseDeclarations, 10779 MVLI.VarComponents, MapTypeModifier, MapType, 10780 IsMapTypeImplicit, MapLoc); 10781 } 10782 10783 QualType Sema::ActOnOpenMPDeclareReductionType(SourceLocation TyLoc, 10784 TypeResult ParsedType) { 10785 assert(ParsedType.isUsable()); 10786 10787 QualType ReductionType = GetTypeFromParser(ParsedType.get()); 10788 if (ReductionType.isNull()) 10789 return QualType(); 10790 10791 // [OpenMP 4.0], 2.15 declare reduction Directive, Restrictions, C\C++ 10792 // A type name in a declare reduction directive cannot be a function type, an 10793 // array type, a reference type, or a type qualified with const, volatile or 10794 // restrict. 10795 if (ReductionType.hasQualifiers()) { 10796 Diag(TyLoc, diag::err_omp_reduction_wrong_type) << 0; 10797 return QualType(); 10798 } 10799 10800 if (ReductionType->isFunctionType()) { 10801 Diag(TyLoc, diag::err_omp_reduction_wrong_type) << 1; 10802 return QualType(); 10803 } 10804 if (ReductionType->isReferenceType()) { 10805 Diag(TyLoc, diag::err_omp_reduction_wrong_type) << 2; 10806 return QualType(); 10807 } 10808 if (ReductionType->isArrayType()) { 10809 Diag(TyLoc, diag::err_omp_reduction_wrong_type) << 3; 10810 return QualType(); 10811 } 10812 return ReductionType; 10813 } 10814 10815 Sema::DeclGroupPtrTy Sema::ActOnOpenMPDeclareReductionDirectiveStart( 10816 Scope *S, DeclContext *DC, DeclarationName Name, 10817 ArrayRef<std::pair<QualType, SourceLocation>> ReductionTypes, 10818 AccessSpecifier AS, Decl *PrevDeclInScope) { 10819 SmallVector<Decl *, 8> Decls; 10820 Decls.reserve(ReductionTypes.size()); 10821 10822 LookupResult Lookup(*this, Name, SourceLocation(), LookupOMPReductionName, 10823 ForRedeclaration); 10824 // [OpenMP 4.0], 2.15 declare reduction Directive, Restrictions 10825 // A reduction-identifier may not be re-declared in the current scope for the 10826 // same type or for a type that is compatible according to the base language 10827 // rules. 10828 llvm::DenseMap<QualType, SourceLocation> PreviousRedeclTypes; 10829 OMPDeclareReductionDecl *PrevDRD = nullptr; 10830 bool InCompoundScope = true; 10831 if (S != nullptr) { 10832 // Find previous declaration with the same name not referenced in other 10833 // declarations. 10834 FunctionScopeInfo *ParentFn = getEnclosingFunction(); 10835 InCompoundScope = 10836 (ParentFn != nullptr) && !ParentFn->CompoundScopes.empty(); 10837 LookupName(Lookup, S); 10838 FilterLookupForScope(Lookup, DC, S, /*ConsiderLinkage=*/false, 10839 /*AllowInlineNamespace=*/false); 10840 llvm::DenseMap<OMPDeclareReductionDecl *, bool> UsedAsPrevious; 10841 auto Filter = Lookup.makeFilter(); 10842 while (Filter.hasNext()) { 10843 auto *PrevDecl = cast<OMPDeclareReductionDecl>(Filter.next()); 10844 if (InCompoundScope) { 10845 auto I = UsedAsPrevious.find(PrevDecl); 10846 if (I == UsedAsPrevious.end()) 10847 UsedAsPrevious[PrevDecl] = false; 10848 if (auto *D = PrevDecl->getPrevDeclInScope()) 10849 UsedAsPrevious[D] = true; 10850 } 10851 PreviousRedeclTypes[PrevDecl->getType().getCanonicalType()] = 10852 PrevDecl->getLocation(); 10853 } 10854 Filter.done(); 10855 if (InCompoundScope) { 10856 for (auto &PrevData : UsedAsPrevious) { 10857 if (!PrevData.second) { 10858 PrevDRD = PrevData.first; 10859 break; 10860 } 10861 } 10862 } 10863 } else if (PrevDeclInScope != nullptr) { 10864 auto *PrevDRDInScope = PrevDRD = 10865 cast<OMPDeclareReductionDecl>(PrevDeclInScope); 10866 do { 10867 PreviousRedeclTypes[PrevDRDInScope->getType().getCanonicalType()] = 10868 PrevDRDInScope->getLocation(); 10869 PrevDRDInScope = PrevDRDInScope->getPrevDeclInScope(); 10870 } while (PrevDRDInScope != nullptr); 10871 } 10872 for (auto &TyData : ReductionTypes) { 10873 auto I = PreviousRedeclTypes.find(TyData.first.getCanonicalType()); 10874 bool Invalid = false; 10875 if (I != PreviousRedeclTypes.end()) { 10876 Diag(TyData.second, diag::err_omp_declare_reduction_redefinition) 10877 << TyData.first; 10878 Diag(I->second, diag::note_previous_definition); 10879 Invalid = true; 10880 } 10881 PreviousRedeclTypes[TyData.first.getCanonicalType()] = TyData.second; 10882 auto *DRD = OMPDeclareReductionDecl::Create(Context, DC, TyData.second, 10883 Name, TyData.first, PrevDRD); 10884 DC->addDecl(DRD); 10885 DRD->setAccess(AS); 10886 Decls.push_back(DRD); 10887 if (Invalid) 10888 DRD->setInvalidDecl(); 10889 else 10890 PrevDRD = DRD; 10891 } 10892 10893 return DeclGroupPtrTy::make( 10894 DeclGroupRef::Create(Context, Decls.begin(), Decls.size())); 10895 } 10896 10897 void Sema::ActOnOpenMPDeclareReductionCombinerStart(Scope *S, Decl *D) { 10898 auto *DRD = cast<OMPDeclareReductionDecl>(D); 10899 10900 // Enter new function scope. 10901 PushFunctionScope(); 10902 getCurFunction()->setHasBranchProtectedScope(); 10903 getCurFunction()->setHasOMPDeclareReductionCombiner(); 10904 10905 if (S != nullptr) 10906 PushDeclContext(S, DRD); 10907 else 10908 CurContext = DRD; 10909 10910 PushExpressionEvaluationContext(PotentiallyEvaluated); 10911 10912 QualType ReductionType = DRD->getType(); 10913 // Create 'T* omp_parm;T omp_in;'. All references to 'omp_in' will 10914 // be replaced by '*omp_parm' during codegen. This required because 'omp_in' 10915 // uses semantics of argument handles by value, but it should be passed by 10916 // reference. C lang does not support references, so pass all parameters as 10917 // pointers. 10918 // Create 'T omp_in;' variable. 10919 auto *OmpInParm = 10920 buildVarDecl(*this, D->getLocation(), ReductionType, "omp_in"); 10921 // Create 'T* omp_parm;T omp_out;'. All references to 'omp_out' will 10922 // be replaced by '*omp_parm' during codegen. This required because 'omp_out' 10923 // uses semantics of argument handles by value, but it should be passed by 10924 // reference. C lang does not support references, so pass all parameters as 10925 // pointers. 10926 // Create 'T omp_out;' variable. 10927 auto *OmpOutParm = 10928 buildVarDecl(*this, D->getLocation(), ReductionType, "omp_out"); 10929 if (S != nullptr) { 10930 PushOnScopeChains(OmpInParm, S); 10931 PushOnScopeChains(OmpOutParm, S); 10932 } else { 10933 DRD->addDecl(OmpInParm); 10934 DRD->addDecl(OmpOutParm); 10935 } 10936 } 10937 10938 void Sema::ActOnOpenMPDeclareReductionCombinerEnd(Decl *D, Expr *Combiner) { 10939 auto *DRD = cast<OMPDeclareReductionDecl>(D); 10940 DiscardCleanupsInEvaluationContext(); 10941 PopExpressionEvaluationContext(); 10942 10943 PopDeclContext(); 10944 PopFunctionScopeInfo(); 10945 10946 if (Combiner != nullptr) 10947 DRD->setCombiner(Combiner); 10948 else 10949 DRD->setInvalidDecl(); 10950 } 10951 10952 void Sema::ActOnOpenMPDeclareReductionInitializerStart(Scope *S, Decl *D) { 10953 auto *DRD = cast<OMPDeclareReductionDecl>(D); 10954 10955 // Enter new function scope. 10956 PushFunctionScope(); 10957 getCurFunction()->setHasBranchProtectedScope(); 10958 10959 if (S != nullptr) 10960 PushDeclContext(S, DRD); 10961 else 10962 CurContext = DRD; 10963 10964 PushExpressionEvaluationContext(PotentiallyEvaluated); 10965 10966 QualType ReductionType = DRD->getType(); 10967 // Create 'T* omp_parm;T omp_priv;'. All references to 'omp_priv' will 10968 // be replaced by '*omp_parm' during codegen. This required because 'omp_priv' 10969 // uses semantics of argument handles by value, but it should be passed by 10970 // reference. C lang does not support references, so pass all parameters as 10971 // pointers. 10972 // Create 'T omp_priv;' variable. 10973 auto *OmpPrivParm = 10974 buildVarDecl(*this, D->getLocation(), ReductionType, "omp_priv"); 10975 // Create 'T* omp_parm;T omp_orig;'. All references to 'omp_orig' will 10976 // be replaced by '*omp_parm' during codegen. This required because 'omp_orig' 10977 // uses semantics of argument handles by value, but it should be passed by 10978 // reference. C lang does not support references, so pass all parameters as 10979 // pointers. 10980 // Create 'T omp_orig;' variable. 10981 auto *OmpOrigParm = 10982 buildVarDecl(*this, D->getLocation(), ReductionType, "omp_orig"); 10983 if (S != nullptr) { 10984 PushOnScopeChains(OmpPrivParm, S); 10985 PushOnScopeChains(OmpOrigParm, S); 10986 } else { 10987 DRD->addDecl(OmpPrivParm); 10988 DRD->addDecl(OmpOrigParm); 10989 } 10990 } 10991 10992 void Sema::ActOnOpenMPDeclareReductionInitializerEnd(Decl *D, 10993 Expr *Initializer) { 10994 auto *DRD = cast<OMPDeclareReductionDecl>(D); 10995 DiscardCleanupsInEvaluationContext(); 10996 PopExpressionEvaluationContext(); 10997 10998 PopDeclContext(); 10999 PopFunctionScopeInfo(); 11000 11001 if (Initializer != nullptr) 11002 DRD->setInitializer(Initializer); 11003 else 11004 DRD->setInvalidDecl(); 11005 } 11006 11007 Sema::DeclGroupPtrTy Sema::ActOnOpenMPDeclareReductionDirectiveEnd( 11008 Scope *S, DeclGroupPtrTy DeclReductions, bool IsValid) { 11009 for (auto *D : DeclReductions.get()) { 11010 if (IsValid) { 11011 auto *DRD = cast<OMPDeclareReductionDecl>(D); 11012 if (S != nullptr) 11013 PushOnScopeChains(DRD, S, /*AddToContext=*/false); 11014 } else 11015 D->setInvalidDecl(); 11016 } 11017 return DeclReductions; 11018 } 11019 11020 OMPClause *Sema::ActOnOpenMPNumTeamsClause(Expr *NumTeams, 11021 SourceLocation StartLoc, 11022 SourceLocation LParenLoc, 11023 SourceLocation EndLoc) { 11024 Expr *ValExpr = NumTeams; 11025 Stmt *HelperValStmt = nullptr; 11026 OpenMPDirectiveKind CaptureRegion = OMPD_unknown; 11027 11028 // OpenMP [teams Constrcut, Restrictions] 11029 // The num_teams expression must evaluate to a positive integer value. 11030 if (!IsNonNegativeIntegerValue(ValExpr, *this, OMPC_num_teams, 11031 /*StrictlyPositive=*/true)) 11032 return nullptr; 11033 11034 OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective(); 11035 CaptureRegion = getOpenMPCaptureRegionForClause(DKind, OMPC_num_teams); 11036 if (CaptureRegion != OMPD_unknown) { 11037 llvm::MapVector<Expr *, DeclRefExpr *> Captures; 11038 ValExpr = tryBuildCapture(*this, ValExpr, Captures).get(); 11039 HelperValStmt = buildPreInits(Context, Captures); 11040 } 11041 11042 return new (Context) OMPNumTeamsClause(ValExpr, HelperValStmt, CaptureRegion, 11043 StartLoc, LParenLoc, EndLoc); 11044 } 11045 11046 OMPClause *Sema::ActOnOpenMPThreadLimitClause(Expr *ThreadLimit, 11047 SourceLocation StartLoc, 11048 SourceLocation LParenLoc, 11049 SourceLocation EndLoc) { 11050 Expr *ValExpr = ThreadLimit; 11051 Stmt *HelperValStmt = nullptr; 11052 OpenMPDirectiveKind CaptureRegion = OMPD_unknown; 11053 11054 // OpenMP [teams Constrcut, Restrictions] 11055 // The thread_limit expression must evaluate to a positive integer value. 11056 if (!IsNonNegativeIntegerValue(ValExpr, *this, OMPC_thread_limit, 11057 /*StrictlyPositive=*/true)) 11058 return nullptr; 11059 11060 OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective(); 11061 CaptureRegion = getOpenMPCaptureRegionForClause(DKind, OMPC_thread_limit); 11062 if (CaptureRegion != OMPD_unknown) { 11063 llvm::MapVector<Expr *, DeclRefExpr *> Captures; 11064 ValExpr = tryBuildCapture(*this, ValExpr, Captures).get(); 11065 HelperValStmt = buildPreInits(Context, Captures); 11066 } 11067 11068 return new (Context) OMPThreadLimitClause( 11069 ValExpr, HelperValStmt, CaptureRegion, StartLoc, LParenLoc, EndLoc); 11070 } 11071 11072 OMPClause *Sema::ActOnOpenMPPriorityClause(Expr *Priority, 11073 SourceLocation StartLoc, 11074 SourceLocation LParenLoc, 11075 SourceLocation EndLoc) { 11076 Expr *ValExpr = Priority; 11077 11078 // OpenMP [2.9.1, task Constrcut] 11079 // The priority-value is a non-negative numerical scalar expression. 11080 if (!IsNonNegativeIntegerValue(ValExpr, *this, OMPC_priority, 11081 /*StrictlyPositive=*/false)) 11082 return nullptr; 11083 11084 return new (Context) OMPPriorityClause(ValExpr, StartLoc, LParenLoc, EndLoc); 11085 } 11086 11087 OMPClause *Sema::ActOnOpenMPGrainsizeClause(Expr *Grainsize, 11088 SourceLocation StartLoc, 11089 SourceLocation LParenLoc, 11090 SourceLocation EndLoc) { 11091 Expr *ValExpr = Grainsize; 11092 11093 // OpenMP [2.9.2, taskloop Constrcut] 11094 // The parameter of the grainsize clause must be a positive integer 11095 // expression. 11096 if (!IsNonNegativeIntegerValue(ValExpr, *this, OMPC_grainsize, 11097 /*StrictlyPositive=*/true)) 11098 return nullptr; 11099 11100 return new (Context) OMPGrainsizeClause(ValExpr, StartLoc, LParenLoc, EndLoc); 11101 } 11102 11103 OMPClause *Sema::ActOnOpenMPNumTasksClause(Expr *NumTasks, 11104 SourceLocation StartLoc, 11105 SourceLocation LParenLoc, 11106 SourceLocation EndLoc) { 11107 Expr *ValExpr = NumTasks; 11108 11109 // OpenMP [2.9.2, taskloop Constrcut] 11110 // The parameter of the num_tasks clause must be a positive integer 11111 // expression. 11112 if (!IsNonNegativeIntegerValue(ValExpr, *this, OMPC_num_tasks, 11113 /*StrictlyPositive=*/true)) 11114 return nullptr; 11115 11116 return new (Context) OMPNumTasksClause(ValExpr, StartLoc, LParenLoc, EndLoc); 11117 } 11118 11119 OMPClause *Sema::ActOnOpenMPHintClause(Expr *Hint, SourceLocation StartLoc, 11120 SourceLocation LParenLoc, 11121 SourceLocation EndLoc) { 11122 // OpenMP [2.13.2, critical construct, Description] 11123 // ... where hint-expression is an integer constant expression that evaluates 11124 // to a valid lock hint. 11125 ExprResult HintExpr = VerifyPositiveIntegerConstantInClause(Hint, OMPC_hint); 11126 if (HintExpr.isInvalid()) 11127 return nullptr; 11128 return new (Context) 11129 OMPHintClause(HintExpr.get(), StartLoc, LParenLoc, EndLoc); 11130 } 11131 11132 OMPClause *Sema::ActOnOpenMPDistScheduleClause( 11133 OpenMPDistScheduleClauseKind Kind, Expr *ChunkSize, SourceLocation StartLoc, 11134 SourceLocation LParenLoc, SourceLocation KindLoc, SourceLocation CommaLoc, 11135 SourceLocation EndLoc) { 11136 if (Kind == OMPC_DIST_SCHEDULE_unknown) { 11137 std::string Values; 11138 Values += "'"; 11139 Values += getOpenMPSimpleClauseTypeName(OMPC_dist_schedule, 0); 11140 Values += "'"; 11141 Diag(KindLoc, diag::err_omp_unexpected_clause_value) 11142 << Values << getOpenMPClauseName(OMPC_dist_schedule); 11143 return nullptr; 11144 } 11145 Expr *ValExpr = ChunkSize; 11146 Stmt *HelperValStmt = nullptr; 11147 if (ChunkSize) { 11148 if (!ChunkSize->isValueDependent() && !ChunkSize->isTypeDependent() && 11149 !ChunkSize->isInstantiationDependent() && 11150 !ChunkSize->containsUnexpandedParameterPack()) { 11151 SourceLocation ChunkSizeLoc = ChunkSize->getLocStart(); 11152 ExprResult Val = 11153 PerformOpenMPImplicitIntegerConversion(ChunkSizeLoc, ChunkSize); 11154 if (Val.isInvalid()) 11155 return nullptr; 11156 11157 ValExpr = Val.get(); 11158 11159 // OpenMP [2.7.1, Restrictions] 11160 // chunk_size must be a loop invariant integer expression with a positive 11161 // value. 11162 llvm::APSInt Result; 11163 if (ValExpr->isIntegerConstantExpr(Result, Context)) { 11164 if (Result.isSigned() && !Result.isStrictlyPositive()) { 11165 Diag(ChunkSizeLoc, diag::err_omp_negative_expression_in_clause) 11166 << "dist_schedule" << ChunkSize->getSourceRange(); 11167 return nullptr; 11168 } 11169 } else if (isParallelOrTaskRegion(DSAStack->getCurrentDirective()) && 11170 !CurContext->isDependentContext()) { 11171 llvm::MapVector<Expr *, DeclRefExpr *> Captures; 11172 ValExpr = tryBuildCapture(*this, ValExpr, Captures).get(); 11173 HelperValStmt = buildPreInits(Context, Captures); 11174 } 11175 } 11176 } 11177 11178 return new (Context) 11179 OMPDistScheduleClause(StartLoc, LParenLoc, KindLoc, CommaLoc, EndLoc, 11180 Kind, ValExpr, HelperValStmt); 11181 } 11182 11183 OMPClause *Sema::ActOnOpenMPDefaultmapClause( 11184 OpenMPDefaultmapClauseModifier M, OpenMPDefaultmapClauseKind Kind, 11185 SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation MLoc, 11186 SourceLocation KindLoc, SourceLocation EndLoc) { 11187 // OpenMP 4.5 only supports 'defaultmap(tofrom: scalar)' 11188 if (M != OMPC_DEFAULTMAP_MODIFIER_tofrom || Kind != OMPC_DEFAULTMAP_scalar) { 11189 std::string Value; 11190 SourceLocation Loc; 11191 Value += "'"; 11192 if (M != OMPC_DEFAULTMAP_MODIFIER_tofrom) { 11193 Value += getOpenMPSimpleClauseTypeName(OMPC_defaultmap, 11194 OMPC_DEFAULTMAP_MODIFIER_tofrom); 11195 Loc = MLoc; 11196 } else { 11197 Value += getOpenMPSimpleClauseTypeName(OMPC_defaultmap, 11198 OMPC_DEFAULTMAP_scalar); 11199 Loc = KindLoc; 11200 } 11201 Value += "'"; 11202 Diag(Loc, diag::err_omp_unexpected_clause_value) 11203 << Value << getOpenMPClauseName(OMPC_defaultmap); 11204 return nullptr; 11205 } 11206 11207 return new (Context) 11208 OMPDefaultmapClause(StartLoc, LParenLoc, MLoc, KindLoc, EndLoc, Kind, M); 11209 } 11210 11211 bool Sema::ActOnStartOpenMPDeclareTargetDirective(SourceLocation Loc) { 11212 DeclContext *CurLexicalContext = getCurLexicalContext(); 11213 if (!CurLexicalContext->isFileContext() && 11214 !CurLexicalContext->isExternCContext() && 11215 !CurLexicalContext->isExternCXXContext()) { 11216 Diag(Loc, diag::err_omp_region_not_file_context); 11217 return false; 11218 } 11219 if (IsInOpenMPDeclareTargetContext) { 11220 Diag(Loc, diag::err_omp_enclosed_declare_target); 11221 return false; 11222 } 11223 11224 IsInOpenMPDeclareTargetContext = true; 11225 return true; 11226 } 11227 11228 void Sema::ActOnFinishOpenMPDeclareTargetDirective() { 11229 assert(IsInOpenMPDeclareTargetContext && 11230 "Unexpected ActOnFinishOpenMPDeclareTargetDirective"); 11231 11232 IsInOpenMPDeclareTargetContext = false; 11233 } 11234 11235 void Sema::ActOnOpenMPDeclareTargetName(Scope *CurScope, 11236 CXXScopeSpec &ScopeSpec, 11237 const DeclarationNameInfo &Id, 11238 OMPDeclareTargetDeclAttr::MapTypeTy MT, 11239 NamedDeclSetType &SameDirectiveDecls) { 11240 LookupResult Lookup(*this, Id, LookupOrdinaryName); 11241 LookupParsedName(Lookup, CurScope, &ScopeSpec, true); 11242 11243 if (Lookup.isAmbiguous()) 11244 return; 11245 Lookup.suppressDiagnostics(); 11246 11247 if (!Lookup.isSingleResult()) { 11248 if (TypoCorrection Corrected = 11249 CorrectTypo(Id, LookupOrdinaryName, CurScope, nullptr, 11250 llvm::make_unique<VarOrFuncDeclFilterCCC>(*this), 11251 CTK_ErrorRecovery)) { 11252 diagnoseTypo(Corrected, PDiag(diag::err_undeclared_var_use_suggest) 11253 << Id.getName()); 11254 checkDeclIsAllowedInOpenMPTarget(nullptr, Corrected.getCorrectionDecl()); 11255 return; 11256 } 11257 11258 Diag(Id.getLoc(), diag::err_undeclared_var_use) << Id.getName(); 11259 return; 11260 } 11261 11262 NamedDecl *ND = Lookup.getAsSingle<NamedDecl>(); 11263 if (isa<VarDecl>(ND) || isa<FunctionDecl>(ND)) { 11264 if (!SameDirectiveDecls.insert(cast<NamedDecl>(ND->getCanonicalDecl()))) 11265 Diag(Id.getLoc(), diag::err_omp_declare_target_multiple) << Id.getName(); 11266 11267 if (!ND->hasAttr<OMPDeclareTargetDeclAttr>()) { 11268 Attr *A = OMPDeclareTargetDeclAttr::CreateImplicit(Context, MT); 11269 ND->addAttr(A); 11270 if (ASTMutationListener *ML = Context.getASTMutationListener()) 11271 ML->DeclarationMarkedOpenMPDeclareTarget(ND, A); 11272 checkDeclIsAllowedInOpenMPTarget(nullptr, ND); 11273 } else if (ND->getAttr<OMPDeclareTargetDeclAttr>()->getMapType() != MT) { 11274 Diag(Id.getLoc(), diag::err_omp_declare_target_to_and_link) 11275 << Id.getName(); 11276 } 11277 } else 11278 Diag(Id.getLoc(), diag::err_omp_invalid_target_decl) << Id.getName(); 11279 } 11280 11281 static void checkDeclInTargetContext(SourceLocation SL, SourceRange SR, 11282 Sema &SemaRef, Decl *D) { 11283 if (!D) 11284 return; 11285 Decl *LD = nullptr; 11286 if (isa<TagDecl>(D)) { 11287 LD = cast<TagDecl>(D)->getDefinition(); 11288 } else if (isa<VarDecl>(D)) { 11289 LD = cast<VarDecl>(D)->getDefinition(); 11290 11291 // If this is an implicit variable that is legal and we do not need to do 11292 // anything. 11293 if (cast<VarDecl>(D)->isImplicit()) { 11294 Attr *A = OMPDeclareTargetDeclAttr::CreateImplicit( 11295 SemaRef.Context, OMPDeclareTargetDeclAttr::MT_To); 11296 D->addAttr(A); 11297 if (ASTMutationListener *ML = SemaRef.Context.getASTMutationListener()) 11298 ML->DeclarationMarkedOpenMPDeclareTarget(D, A); 11299 return; 11300 } 11301 11302 } else if (isa<FunctionDecl>(D)) { 11303 const FunctionDecl *FD = nullptr; 11304 if (cast<FunctionDecl>(D)->hasBody(FD)) 11305 LD = const_cast<FunctionDecl *>(FD); 11306 11307 // If the definition is associated with the current declaration in the 11308 // target region (it can be e.g. a lambda) that is legal and we do not need 11309 // to do anything else. 11310 if (LD == D) { 11311 Attr *A = OMPDeclareTargetDeclAttr::CreateImplicit( 11312 SemaRef.Context, OMPDeclareTargetDeclAttr::MT_To); 11313 D->addAttr(A); 11314 if (ASTMutationListener *ML = SemaRef.Context.getASTMutationListener()) 11315 ML->DeclarationMarkedOpenMPDeclareTarget(D, A); 11316 return; 11317 } 11318 } 11319 if (!LD) 11320 LD = D; 11321 if (LD && !LD->hasAttr<OMPDeclareTargetDeclAttr>() && 11322 (isa<VarDecl>(LD) || isa<FunctionDecl>(LD))) { 11323 // Outlined declaration is not declared target. 11324 if (LD->isOutOfLine()) { 11325 SemaRef.Diag(LD->getLocation(), diag::warn_omp_not_in_target_context); 11326 SemaRef.Diag(SL, diag::note_used_here) << SR; 11327 } else { 11328 DeclContext *DC = LD->getDeclContext(); 11329 while (DC) { 11330 if (isa<FunctionDecl>(DC) && 11331 cast<FunctionDecl>(DC)->hasAttr<OMPDeclareTargetDeclAttr>()) 11332 break; 11333 DC = DC->getParent(); 11334 } 11335 if (DC) 11336 return; 11337 11338 // Is not declared in target context. 11339 SemaRef.Diag(LD->getLocation(), diag::warn_omp_not_in_target_context); 11340 SemaRef.Diag(SL, diag::note_used_here) << SR; 11341 } 11342 // Mark decl as declared target to prevent further diagnostic. 11343 Attr *A = OMPDeclareTargetDeclAttr::CreateImplicit( 11344 SemaRef.Context, OMPDeclareTargetDeclAttr::MT_To); 11345 D->addAttr(A); 11346 if (ASTMutationListener *ML = SemaRef.Context.getASTMutationListener()) 11347 ML->DeclarationMarkedOpenMPDeclareTarget(D, A); 11348 } 11349 } 11350 11351 static bool checkValueDeclInTarget(SourceLocation SL, SourceRange SR, 11352 Sema &SemaRef, DSAStackTy *Stack, 11353 ValueDecl *VD) { 11354 if (VD->hasAttr<OMPDeclareTargetDeclAttr>()) 11355 return true; 11356 if (!CheckTypeMappable(SL, SR, SemaRef, Stack, VD->getType())) 11357 return false; 11358 return true; 11359 } 11360 11361 void Sema::checkDeclIsAllowedInOpenMPTarget(Expr *E, Decl *D) { 11362 if (!D || D->isInvalidDecl()) 11363 return; 11364 SourceRange SR = E ? E->getSourceRange() : D->getSourceRange(); 11365 SourceLocation SL = E ? E->getLocStart() : D->getLocation(); 11366 // 2.10.6: threadprivate variable cannot appear in a declare target directive. 11367 if (VarDecl *VD = dyn_cast<VarDecl>(D)) { 11368 if (DSAStack->isThreadPrivate(VD)) { 11369 Diag(SL, diag::err_omp_threadprivate_in_target); 11370 ReportOriginalDSA(*this, DSAStack, VD, DSAStack->getTopDSA(VD, false)); 11371 return; 11372 } 11373 } 11374 if (ValueDecl *VD = dyn_cast<ValueDecl>(D)) { 11375 // Problem if any with var declared with incomplete type will be reported 11376 // as normal, so no need to check it here. 11377 if ((E || !VD->getType()->isIncompleteType()) && 11378 !checkValueDeclInTarget(SL, SR, *this, DSAStack, VD)) { 11379 // Mark decl as declared target to prevent further diagnostic. 11380 if (isa<VarDecl>(VD) || isa<FunctionDecl>(VD)) { 11381 Attr *A = OMPDeclareTargetDeclAttr::CreateImplicit( 11382 Context, OMPDeclareTargetDeclAttr::MT_To); 11383 VD->addAttr(A); 11384 if (ASTMutationListener *ML = Context.getASTMutationListener()) 11385 ML->DeclarationMarkedOpenMPDeclareTarget(VD, A); 11386 } 11387 return; 11388 } 11389 } 11390 if (!E) { 11391 // Checking declaration inside declare target region. 11392 if (!D->hasAttr<OMPDeclareTargetDeclAttr>() && 11393 (isa<VarDecl>(D) || isa<FunctionDecl>(D))) { 11394 Attr *A = OMPDeclareTargetDeclAttr::CreateImplicit( 11395 Context, OMPDeclareTargetDeclAttr::MT_To); 11396 D->addAttr(A); 11397 if (ASTMutationListener *ML = Context.getASTMutationListener()) 11398 ML->DeclarationMarkedOpenMPDeclareTarget(D, A); 11399 } 11400 return; 11401 } 11402 checkDeclInTargetContext(E->getExprLoc(), E->getSourceRange(), *this, D); 11403 } 11404 11405 OMPClause *Sema::ActOnOpenMPToClause(ArrayRef<Expr *> VarList, 11406 SourceLocation StartLoc, 11407 SourceLocation LParenLoc, 11408 SourceLocation EndLoc) { 11409 MappableVarListInfo MVLI(VarList); 11410 checkMappableExpressionList(*this, DSAStack, OMPC_to, MVLI, StartLoc); 11411 if (MVLI.ProcessedVarList.empty()) 11412 return nullptr; 11413 11414 return OMPToClause::Create(Context, StartLoc, LParenLoc, EndLoc, 11415 MVLI.ProcessedVarList, MVLI.VarBaseDeclarations, 11416 MVLI.VarComponents); 11417 } 11418 11419 OMPClause *Sema::ActOnOpenMPFromClause(ArrayRef<Expr *> VarList, 11420 SourceLocation StartLoc, 11421 SourceLocation LParenLoc, 11422 SourceLocation EndLoc) { 11423 MappableVarListInfo MVLI(VarList); 11424 checkMappableExpressionList(*this, DSAStack, OMPC_from, MVLI, StartLoc); 11425 if (MVLI.ProcessedVarList.empty()) 11426 return nullptr; 11427 11428 return OMPFromClause::Create(Context, StartLoc, LParenLoc, EndLoc, 11429 MVLI.ProcessedVarList, MVLI.VarBaseDeclarations, 11430 MVLI.VarComponents); 11431 } 11432 11433 OMPClause *Sema::ActOnOpenMPUseDevicePtrClause(ArrayRef<Expr *> VarList, 11434 SourceLocation StartLoc, 11435 SourceLocation LParenLoc, 11436 SourceLocation EndLoc) { 11437 MappableVarListInfo MVLI(VarList); 11438 SmallVector<Expr *, 8> PrivateCopies; 11439 SmallVector<Expr *, 8> Inits; 11440 11441 for (auto &RefExpr : VarList) { 11442 assert(RefExpr && "NULL expr in OpenMP use_device_ptr clause."); 11443 SourceLocation ELoc; 11444 SourceRange ERange; 11445 Expr *SimpleRefExpr = RefExpr; 11446 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange); 11447 if (Res.second) { 11448 // It will be analyzed later. 11449 MVLI.ProcessedVarList.push_back(RefExpr); 11450 PrivateCopies.push_back(nullptr); 11451 Inits.push_back(nullptr); 11452 } 11453 ValueDecl *D = Res.first; 11454 if (!D) 11455 continue; 11456 11457 QualType Type = D->getType(); 11458 Type = Type.getNonReferenceType().getUnqualifiedType(); 11459 11460 auto *VD = dyn_cast<VarDecl>(D); 11461 11462 // Item should be a pointer or reference to pointer. 11463 if (!Type->isPointerType()) { 11464 Diag(ELoc, diag::err_omp_usedeviceptr_not_a_pointer) 11465 << 0 << RefExpr->getSourceRange(); 11466 continue; 11467 } 11468 11469 // Build the private variable and the expression that refers to it. 11470 auto VDPrivate = buildVarDecl(*this, ELoc, Type, D->getName(), 11471 D->hasAttrs() ? &D->getAttrs() : nullptr); 11472 if (VDPrivate->isInvalidDecl()) 11473 continue; 11474 11475 CurContext->addDecl(VDPrivate); 11476 auto VDPrivateRefExpr = buildDeclRefExpr( 11477 *this, VDPrivate, RefExpr->getType().getUnqualifiedType(), ELoc); 11478 11479 // Add temporary variable to initialize the private copy of the pointer. 11480 auto *VDInit = 11481 buildVarDecl(*this, RefExpr->getExprLoc(), Type, ".devptr.temp"); 11482 auto *VDInitRefExpr = buildDeclRefExpr(*this, VDInit, RefExpr->getType(), 11483 RefExpr->getExprLoc()); 11484 AddInitializerToDecl(VDPrivate, 11485 DefaultLvalueConversion(VDInitRefExpr).get(), 11486 /*DirectInit=*/false); 11487 11488 // If required, build a capture to implement the privatization initialized 11489 // with the current list item value. 11490 DeclRefExpr *Ref = nullptr; 11491 if (!VD) 11492 Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/true); 11493 MVLI.ProcessedVarList.push_back(VD ? RefExpr->IgnoreParens() : Ref); 11494 PrivateCopies.push_back(VDPrivateRefExpr); 11495 Inits.push_back(VDInitRefExpr); 11496 11497 // We need to add a data sharing attribute for this variable to make sure it 11498 // is correctly captured. A variable that shows up in a use_device_ptr has 11499 // similar properties of a first private variable. 11500 DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_firstprivate, Ref); 11501 11502 // Create a mappable component for the list item. List items in this clause 11503 // only need a component. 11504 MVLI.VarBaseDeclarations.push_back(D); 11505 MVLI.VarComponents.resize(MVLI.VarComponents.size() + 1); 11506 MVLI.VarComponents.back().push_back( 11507 OMPClauseMappableExprCommon::MappableComponent(SimpleRefExpr, D)); 11508 } 11509 11510 if (MVLI.ProcessedVarList.empty()) 11511 return nullptr; 11512 11513 return OMPUseDevicePtrClause::Create( 11514 Context, StartLoc, LParenLoc, EndLoc, MVLI.ProcessedVarList, 11515 PrivateCopies, Inits, MVLI.VarBaseDeclarations, MVLI.VarComponents); 11516 } 11517 11518 OMPClause *Sema::ActOnOpenMPIsDevicePtrClause(ArrayRef<Expr *> VarList, 11519 SourceLocation StartLoc, 11520 SourceLocation LParenLoc, 11521 SourceLocation EndLoc) { 11522 MappableVarListInfo MVLI(VarList); 11523 for (auto &RefExpr : VarList) { 11524 assert(RefExpr && "NULL expr in OpenMP is_device_ptr clause."); 11525 SourceLocation ELoc; 11526 SourceRange ERange; 11527 Expr *SimpleRefExpr = RefExpr; 11528 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange); 11529 if (Res.second) { 11530 // It will be analyzed later. 11531 MVLI.ProcessedVarList.push_back(RefExpr); 11532 } 11533 ValueDecl *D = Res.first; 11534 if (!D) 11535 continue; 11536 11537 QualType Type = D->getType(); 11538 // item should be a pointer or array or reference to pointer or array 11539 if (!Type.getNonReferenceType()->isPointerType() && 11540 !Type.getNonReferenceType()->isArrayType()) { 11541 Diag(ELoc, diag::err_omp_argument_type_isdeviceptr) 11542 << 0 << RefExpr->getSourceRange(); 11543 continue; 11544 } 11545 11546 // Check if the declaration in the clause does not show up in any data 11547 // sharing attribute. 11548 auto DVar = DSAStack->getTopDSA(D, false); 11549 if (isOpenMPPrivate(DVar.CKind)) { 11550 Diag(ELoc, diag::err_omp_variable_in_given_clause_and_dsa) 11551 << getOpenMPClauseName(DVar.CKind) 11552 << getOpenMPClauseName(OMPC_is_device_ptr) 11553 << getOpenMPDirectiveName(DSAStack->getCurrentDirective()); 11554 ReportOriginalDSA(*this, DSAStack, D, DVar); 11555 continue; 11556 } 11557 11558 Expr *ConflictExpr; 11559 if (DSAStack->checkMappableExprComponentListsForDecl( 11560 D, /*CurrentRegionOnly=*/true, 11561 [&ConflictExpr]( 11562 OMPClauseMappableExprCommon::MappableExprComponentListRef R, 11563 OpenMPClauseKind) -> bool { 11564 ConflictExpr = R.front().getAssociatedExpression(); 11565 return true; 11566 })) { 11567 Diag(ELoc, diag::err_omp_map_shared_storage) << RefExpr->getSourceRange(); 11568 Diag(ConflictExpr->getExprLoc(), diag::note_used_here) 11569 << ConflictExpr->getSourceRange(); 11570 continue; 11571 } 11572 11573 // Store the components in the stack so that they can be used to check 11574 // against other clauses later on. 11575 OMPClauseMappableExprCommon::MappableComponent MC(SimpleRefExpr, D); 11576 DSAStack->addMappableExpressionComponents( 11577 D, MC, /*WhereFoundClauseKind=*/OMPC_is_device_ptr); 11578 11579 // Record the expression we've just processed. 11580 MVLI.ProcessedVarList.push_back(SimpleRefExpr); 11581 11582 // Create a mappable component for the list item. List items in this clause 11583 // only need a component. We use a null declaration to signal fields in 11584 // 'this'. 11585 assert((isa<DeclRefExpr>(SimpleRefExpr) || 11586 isa<CXXThisExpr>(cast<MemberExpr>(SimpleRefExpr)->getBase())) && 11587 "Unexpected device pointer expression!"); 11588 MVLI.VarBaseDeclarations.push_back( 11589 isa<DeclRefExpr>(SimpleRefExpr) ? D : nullptr); 11590 MVLI.VarComponents.resize(MVLI.VarComponents.size() + 1); 11591 MVLI.VarComponents.back().push_back(MC); 11592 } 11593 11594 if (MVLI.ProcessedVarList.empty()) 11595 return nullptr; 11596 11597 return OMPIsDevicePtrClause::Create( 11598 Context, StartLoc, LParenLoc, EndLoc, MVLI.ProcessedVarList, 11599 MVLI.VarBaseDeclarations, MVLI.VarComponents); 11600 } 11601