1 //===--- SemaOpenMP.cpp - Semantic Analysis for OpenMP constructs ---------===// 2 // 3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 4 // See https://llvm.org/LICENSE.txt for license information. 5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 6 // 7 //===----------------------------------------------------------------------===// 8 /// \file 9 /// This file implements semantic analysis for OpenMP directives and 10 /// clauses. 11 /// 12 //===----------------------------------------------------------------------===// 13 14 #include "TreeTransform.h" 15 #include "clang/AST/ASTContext.h" 16 #include "clang/AST/ASTMutationListener.h" 17 #include "clang/AST/CXXInheritance.h" 18 #include "clang/AST/Decl.h" 19 #include "clang/AST/DeclCXX.h" 20 #include "clang/AST/DeclOpenMP.h" 21 #include "clang/AST/StmtCXX.h" 22 #include "clang/AST/StmtOpenMP.h" 23 #include "clang/AST/StmtVisitor.h" 24 #include "clang/AST/TypeOrdering.h" 25 #include "clang/Basic/OpenMPKinds.h" 26 #include "clang/Sema/Initialization.h" 27 #include "clang/Sema/Lookup.h" 28 #include "clang/Sema/Scope.h" 29 #include "clang/Sema/ScopeInfo.h" 30 #include "clang/Sema/SemaInternal.h" 31 #include "llvm/ADT/PointerEmbeddedInt.h" 32 using namespace clang; 33 34 //===----------------------------------------------------------------------===// 35 // Stack of data-sharing attributes for variables 36 //===----------------------------------------------------------------------===// 37 38 static const Expr *checkMapClauseExpressionBase( 39 Sema &SemaRef, Expr *E, 40 OMPClauseMappableExprCommon::MappableExprComponentList &CurComponents, 41 OpenMPClauseKind CKind, bool NoDiagnose); 42 43 namespace { 44 /// Default data sharing attributes, which can be applied to directive. 45 enum DefaultDataSharingAttributes { 46 DSA_unspecified = 0, /// Data sharing attribute not specified. 47 DSA_none = 1 << 0, /// Default data sharing attribute 'none'. 48 DSA_shared = 1 << 1, /// Default data sharing attribute 'shared'. 49 }; 50 51 /// Attributes of the defaultmap clause. 52 enum DefaultMapAttributes { 53 DMA_unspecified, /// Default mapping is not specified. 54 DMA_tofrom_scalar, /// Default mapping is 'tofrom:scalar'. 55 }; 56 57 /// Stack for tracking declarations used in OpenMP directives and 58 /// clauses and their data-sharing attributes. 59 class DSAStackTy { 60 public: 61 struct DSAVarData { 62 OpenMPDirectiveKind DKind = OMPD_unknown; 63 OpenMPClauseKind CKind = OMPC_unknown; 64 const Expr *RefExpr = nullptr; 65 DeclRefExpr *PrivateCopy = nullptr; 66 SourceLocation ImplicitDSALoc; 67 DSAVarData() = default; 68 DSAVarData(OpenMPDirectiveKind DKind, OpenMPClauseKind CKind, 69 const Expr *RefExpr, DeclRefExpr *PrivateCopy, 70 SourceLocation ImplicitDSALoc) 71 : DKind(DKind), CKind(CKind), RefExpr(RefExpr), 72 PrivateCopy(PrivateCopy), ImplicitDSALoc(ImplicitDSALoc) {} 73 }; 74 using OperatorOffsetTy = 75 llvm::SmallVector<std::pair<Expr *, OverloadedOperatorKind>, 4>; 76 using DoacrossDependMapTy = 77 llvm::DenseMap<OMPDependClause *, OperatorOffsetTy>; 78 79 private: 80 struct DSAInfo { 81 OpenMPClauseKind Attributes = OMPC_unknown; 82 /// Pointer to a reference expression and a flag which shows that the 83 /// variable is marked as lastprivate(true) or not (false). 84 llvm::PointerIntPair<const Expr *, 1, bool> RefExpr; 85 DeclRefExpr *PrivateCopy = nullptr; 86 }; 87 using DeclSAMapTy = llvm::SmallDenseMap<const ValueDecl *, DSAInfo, 8>; 88 using AlignedMapTy = llvm::SmallDenseMap<const ValueDecl *, const Expr *, 8>; 89 using LCDeclInfo = std::pair<unsigned, VarDecl *>; 90 using LoopControlVariablesMapTy = 91 llvm::SmallDenseMap<const ValueDecl *, LCDeclInfo, 8>; 92 /// Struct that associates a component with the clause kind where they are 93 /// found. 94 struct MappedExprComponentTy { 95 OMPClauseMappableExprCommon::MappableExprComponentLists Components; 96 OpenMPClauseKind Kind = OMPC_unknown; 97 }; 98 using MappedExprComponentsTy = 99 llvm::DenseMap<const ValueDecl *, MappedExprComponentTy>; 100 using CriticalsWithHintsTy = 101 llvm::StringMap<std::pair<const OMPCriticalDirective *, llvm::APSInt>>; 102 struct ReductionData { 103 using BOKPtrType = llvm::PointerEmbeddedInt<BinaryOperatorKind, 16>; 104 SourceRange ReductionRange; 105 llvm::PointerUnion<const Expr *, BOKPtrType> ReductionOp; 106 ReductionData() = default; 107 void set(BinaryOperatorKind BO, SourceRange RR) { 108 ReductionRange = RR; 109 ReductionOp = BO; 110 } 111 void set(const Expr *RefExpr, SourceRange RR) { 112 ReductionRange = RR; 113 ReductionOp = RefExpr; 114 } 115 }; 116 using DeclReductionMapTy = 117 llvm::SmallDenseMap<const ValueDecl *, ReductionData, 4>; 118 119 struct SharingMapTy { 120 DeclSAMapTy SharingMap; 121 DeclReductionMapTy ReductionMap; 122 AlignedMapTy AlignedMap; 123 MappedExprComponentsTy MappedExprComponents; 124 LoopControlVariablesMapTy LCVMap; 125 DefaultDataSharingAttributes DefaultAttr = DSA_unspecified; 126 SourceLocation DefaultAttrLoc; 127 DefaultMapAttributes DefaultMapAttr = DMA_unspecified; 128 SourceLocation DefaultMapAttrLoc; 129 OpenMPDirectiveKind Directive = OMPD_unknown; 130 DeclarationNameInfo DirectiveName; 131 Scope *CurScope = nullptr; 132 SourceLocation ConstructLoc; 133 /// Set of 'depend' clauses with 'sink|source' dependence kind. Required to 134 /// get the data (loop counters etc.) about enclosing loop-based construct. 135 /// This data is required during codegen. 136 DoacrossDependMapTy DoacrossDepends; 137 /// First argument (Expr *) contains optional argument of the 138 /// 'ordered' clause, the second one is true if the regions has 'ordered' 139 /// clause, false otherwise. 140 llvm::Optional<std::pair<const Expr *, OMPOrderedClause *>> OrderedRegion; 141 unsigned AssociatedLoops = 1; 142 const Decl *PossiblyLoopCounter = nullptr; 143 bool NowaitRegion = false; 144 bool CancelRegion = false; 145 bool LoopStart = false; 146 SourceLocation InnerTeamsRegionLoc; 147 /// Reference to the taskgroup task_reduction reference expression. 148 Expr *TaskgroupReductionRef = nullptr; 149 llvm::DenseSet<QualType> MappedClassesQualTypes; 150 SharingMapTy(OpenMPDirectiveKind DKind, DeclarationNameInfo Name, 151 Scope *CurScope, SourceLocation Loc) 152 : Directive(DKind), DirectiveName(Name), CurScope(CurScope), 153 ConstructLoc(Loc) {} 154 SharingMapTy() = default; 155 }; 156 157 using StackTy = SmallVector<SharingMapTy, 4>; 158 159 /// Stack of used declaration and their data-sharing attributes. 160 DeclSAMapTy Threadprivates; 161 const FunctionScopeInfo *CurrentNonCapturingFunctionScope = nullptr; 162 SmallVector<std::pair<StackTy, const FunctionScopeInfo *>, 4> Stack; 163 /// true, if check for DSA must be from parent directive, false, if 164 /// from current directive. 165 OpenMPClauseKind ClauseKindMode = OMPC_unknown; 166 Sema &SemaRef; 167 bool ForceCapturing = false; 168 /// true if all the vaiables in the target executable directives must be 169 /// captured by reference. 170 bool ForceCaptureByReferenceInTargetExecutable = false; 171 CriticalsWithHintsTy Criticals; 172 173 using iterator = StackTy::const_reverse_iterator; 174 175 DSAVarData getDSA(iterator &Iter, ValueDecl *D) const; 176 177 /// Checks if the variable is a local for OpenMP region. 178 bool isOpenMPLocal(VarDecl *D, iterator Iter) const; 179 180 bool isStackEmpty() const { 181 return Stack.empty() || 182 Stack.back().second != CurrentNonCapturingFunctionScope || 183 Stack.back().first.empty(); 184 } 185 186 /// Vector of previously declared requires directives 187 SmallVector<const OMPRequiresDecl *, 2> RequiresDecls; 188 189 public: 190 explicit DSAStackTy(Sema &S) : SemaRef(S) {} 191 192 bool isClauseParsingMode() const { return ClauseKindMode != OMPC_unknown; } 193 OpenMPClauseKind getClauseParsingMode() const { 194 assert(isClauseParsingMode() && "Must be in clause parsing mode."); 195 return ClauseKindMode; 196 } 197 void setClauseParsingMode(OpenMPClauseKind K) { ClauseKindMode = K; } 198 199 bool isForceVarCapturing() const { return ForceCapturing; } 200 void setForceVarCapturing(bool V) { ForceCapturing = V; } 201 202 void setForceCaptureByReferenceInTargetExecutable(bool V) { 203 ForceCaptureByReferenceInTargetExecutable = V; 204 } 205 bool isForceCaptureByReferenceInTargetExecutable() const { 206 return ForceCaptureByReferenceInTargetExecutable; 207 } 208 209 void push(OpenMPDirectiveKind DKind, const DeclarationNameInfo &DirName, 210 Scope *CurScope, SourceLocation Loc) { 211 if (Stack.empty() || 212 Stack.back().second != CurrentNonCapturingFunctionScope) 213 Stack.emplace_back(StackTy(), CurrentNonCapturingFunctionScope); 214 Stack.back().first.emplace_back(DKind, DirName, CurScope, Loc); 215 Stack.back().first.back().DefaultAttrLoc = Loc; 216 } 217 218 void pop() { 219 assert(!Stack.back().first.empty() && 220 "Data-sharing attributes stack is empty!"); 221 Stack.back().first.pop_back(); 222 } 223 224 /// Marks that we're started loop parsing. 225 void loopInit() { 226 assert(isOpenMPLoopDirective(getCurrentDirective()) && 227 "Expected loop-based directive."); 228 Stack.back().first.back().LoopStart = true; 229 } 230 /// Start capturing of the variables in the loop context. 231 void loopStart() { 232 assert(isOpenMPLoopDirective(getCurrentDirective()) && 233 "Expected loop-based directive."); 234 Stack.back().first.back().LoopStart = false; 235 } 236 /// true, if variables are captured, false otherwise. 237 bool isLoopStarted() const { 238 assert(isOpenMPLoopDirective(getCurrentDirective()) && 239 "Expected loop-based directive."); 240 return !Stack.back().first.back().LoopStart; 241 } 242 /// Marks (or clears) declaration as possibly loop counter. 243 void resetPossibleLoopCounter(const Decl *D = nullptr) { 244 Stack.back().first.back().PossiblyLoopCounter = 245 D ? D->getCanonicalDecl() : D; 246 } 247 /// Gets the possible loop counter decl. 248 const Decl *getPossiblyLoopCunter() const { 249 return Stack.back().first.back().PossiblyLoopCounter; 250 } 251 /// Start new OpenMP region stack in new non-capturing function. 252 void pushFunction() { 253 const FunctionScopeInfo *CurFnScope = SemaRef.getCurFunction(); 254 assert(!isa<CapturingScopeInfo>(CurFnScope)); 255 CurrentNonCapturingFunctionScope = CurFnScope; 256 } 257 /// Pop region stack for non-capturing function. 258 void popFunction(const FunctionScopeInfo *OldFSI) { 259 if (!Stack.empty() && Stack.back().second == OldFSI) { 260 assert(Stack.back().first.empty()); 261 Stack.pop_back(); 262 } 263 CurrentNonCapturingFunctionScope = nullptr; 264 for (const FunctionScopeInfo *FSI : llvm::reverse(SemaRef.FunctionScopes)) { 265 if (!isa<CapturingScopeInfo>(FSI)) { 266 CurrentNonCapturingFunctionScope = FSI; 267 break; 268 } 269 } 270 } 271 272 void addCriticalWithHint(const OMPCriticalDirective *D, llvm::APSInt Hint) { 273 Criticals.try_emplace(D->getDirectiveName().getAsString(), D, Hint); 274 } 275 const std::pair<const OMPCriticalDirective *, llvm::APSInt> 276 getCriticalWithHint(const DeclarationNameInfo &Name) const { 277 auto I = Criticals.find(Name.getAsString()); 278 if (I != Criticals.end()) 279 return I->second; 280 return std::make_pair(nullptr, llvm::APSInt()); 281 } 282 /// If 'aligned' declaration for given variable \a D was not seen yet, 283 /// add it and return NULL; otherwise return previous occurrence's expression 284 /// for diagnostics. 285 const Expr *addUniqueAligned(const ValueDecl *D, const Expr *NewDE); 286 287 /// Register specified variable as loop control variable. 288 void addLoopControlVariable(const ValueDecl *D, VarDecl *Capture); 289 /// Check if the specified variable is a loop control variable for 290 /// current region. 291 /// \return The index of the loop control variable in the list of associated 292 /// for-loops (from outer to inner). 293 const LCDeclInfo isLoopControlVariable(const ValueDecl *D) const; 294 /// Check if the specified variable is a loop control variable for 295 /// parent region. 296 /// \return The index of the loop control variable in the list of associated 297 /// for-loops (from outer to inner). 298 const LCDeclInfo isParentLoopControlVariable(const ValueDecl *D) const; 299 /// Get the loop control variable for the I-th loop (or nullptr) in 300 /// parent directive. 301 const ValueDecl *getParentLoopControlVariable(unsigned I) const; 302 303 /// Adds explicit data sharing attribute to the specified declaration. 304 void addDSA(const ValueDecl *D, const Expr *E, OpenMPClauseKind A, 305 DeclRefExpr *PrivateCopy = nullptr); 306 307 /// Adds additional information for the reduction items with the reduction id 308 /// represented as an operator. 309 void addTaskgroupReductionData(const ValueDecl *D, SourceRange SR, 310 BinaryOperatorKind BOK); 311 /// Adds additional information for the reduction items with the reduction id 312 /// represented as reduction identifier. 313 void addTaskgroupReductionData(const ValueDecl *D, SourceRange SR, 314 const Expr *ReductionRef); 315 /// Returns the location and reduction operation from the innermost parent 316 /// region for the given \p D. 317 const DSAVarData 318 getTopMostTaskgroupReductionData(const ValueDecl *D, SourceRange &SR, 319 BinaryOperatorKind &BOK, 320 Expr *&TaskgroupDescriptor) const; 321 /// Returns the location and reduction operation from the innermost parent 322 /// region for the given \p D. 323 const DSAVarData 324 getTopMostTaskgroupReductionData(const ValueDecl *D, SourceRange &SR, 325 const Expr *&ReductionRef, 326 Expr *&TaskgroupDescriptor) const; 327 /// Return reduction reference expression for the current taskgroup. 328 Expr *getTaskgroupReductionRef() const { 329 assert(Stack.back().first.back().Directive == OMPD_taskgroup && 330 "taskgroup reference expression requested for non taskgroup " 331 "directive."); 332 return Stack.back().first.back().TaskgroupReductionRef; 333 } 334 /// Checks if the given \p VD declaration is actually a taskgroup reduction 335 /// descriptor variable at the \p Level of OpenMP regions. 336 bool isTaskgroupReductionRef(const ValueDecl *VD, unsigned Level) const { 337 return Stack.back().first[Level].TaskgroupReductionRef && 338 cast<DeclRefExpr>(Stack.back().first[Level].TaskgroupReductionRef) 339 ->getDecl() == VD; 340 } 341 342 /// Returns data sharing attributes from top of the stack for the 343 /// specified declaration. 344 const DSAVarData getTopDSA(ValueDecl *D, bool FromParent); 345 /// Returns data-sharing attributes for the specified declaration. 346 const DSAVarData getImplicitDSA(ValueDecl *D, bool FromParent) const; 347 /// Checks if the specified variables has data-sharing attributes which 348 /// match specified \a CPred predicate in any directive which matches \a DPred 349 /// predicate. 350 const DSAVarData 351 hasDSA(ValueDecl *D, const llvm::function_ref<bool(OpenMPClauseKind)> CPred, 352 const llvm::function_ref<bool(OpenMPDirectiveKind)> DPred, 353 bool FromParent) const; 354 /// Checks if the specified variables has data-sharing attributes which 355 /// match specified \a CPred predicate in any innermost directive which 356 /// matches \a DPred predicate. 357 const DSAVarData 358 hasInnermostDSA(ValueDecl *D, 359 const llvm::function_ref<bool(OpenMPClauseKind)> CPred, 360 const llvm::function_ref<bool(OpenMPDirectiveKind)> DPred, 361 bool FromParent) const; 362 /// Checks if the specified variables has explicit data-sharing 363 /// attributes which match specified \a CPred predicate at the specified 364 /// OpenMP region. 365 bool hasExplicitDSA(const ValueDecl *D, 366 const llvm::function_ref<bool(OpenMPClauseKind)> CPred, 367 unsigned Level, bool NotLastprivate = false) const; 368 369 /// Returns true if the directive at level \Level matches in the 370 /// specified \a DPred predicate. 371 bool hasExplicitDirective( 372 const llvm::function_ref<bool(OpenMPDirectiveKind)> DPred, 373 unsigned Level) const; 374 375 /// Finds a directive which matches specified \a DPred predicate. 376 bool hasDirective( 377 const llvm::function_ref<bool( 378 OpenMPDirectiveKind, const DeclarationNameInfo &, SourceLocation)> 379 DPred, 380 bool FromParent) const; 381 382 /// Returns currently analyzed directive. 383 OpenMPDirectiveKind getCurrentDirective() const { 384 return isStackEmpty() ? OMPD_unknown : Stack.back().first.back().Directive; 385 } 386 /// Returns directive kind at specified level. 387 OpenMPDirectiveKind getDirective(unsigned Level) const { 388 assert(!isStackEmpty() && "No directive at specified level."); 389 return Stack.back().first[Level].Directive; 390 } 391 /// Returns parent directive. 392 OpenMPDirectiveKind getParentDirective() const { 393 if (isStackEmpty() || Stack.back().first.size() == 1) 394 return OMPD_unknown; 395 return std::next(Stack.back().first.rbegin())->Directive; 396 } 397 398 /// Add requires decl to internal vector 399 void addRequiresDecl(OMPRequiresDecl *RD) { 400 RequiresDecls.push_back(RD); 401 } 402 403 /// Checks for a duplicate clause amongst previously declared requires 404 /// directives 405 bool hasDuplicateRequiresClause(ArrayRef<OMPClause *> ClauseList) const { 406 bool IsDuplicate = false; 407 for (OMPClause *CNew : ClauseList) { 408 for (const OMPRequiresDecl *D : RequiresDecls) { 409 for (const OMPClause *CPrev : D->clauselists()) { 410 if (CNew->getClauseKind() == CPrev->getClauseKind()) { 411 SemaRef.Diag(CNew->getBeginLoc(), 412 diag::err_omp_requires_clause_redeclaration) 413 << getOpenMPClauseName(CNew->getClauseKind()); 414 SemaRef.Diag(CPrev->getBeginLoc(), 415 diag::note_omp_requires_previous_clause) 416 << getOpenMPClauseName(CPrev->getClauseKind()); 417 IsDuplicate = true; 418 } 419 } 420 } 421 } 422 return IsDuplicate; 423 } 424 425 /// Set default data sharing attribute to none. 426 void setDefaultDSANone(SourceLocation Loc) { 427 assert(!isStackEmpty()); 428 Stack.back().first.back().DefaultAttr = DSA_none; 429 Stack.back().first.back().DefaultAttrLoc = Loc; 430 } 431 /// Set default data sharing attribute to shared. 432 void setDefaultDSAShared(SourceLocation Loc) { 433 assert(!isStackEmpty()); 434 Stack.back().first.back().DefaultAttr = DSA_shared; 435 Stack.back().first.back().DefaultAttrLoc = Loc; 436 } 437 /// Set default data mapping attribute to 'tofrom:scalar'. 438 void setDefaultDMAToFromScalar(SourceLocation Loc) { 439 assert(!isStackEmpty()); 440 Stack.back().first.back().DefaultMapAttr = DMA_tofrom_scalar; 441 Stack.back().first.back().DefaultMapAttrLoc = Loc; 442 } 443 444 DefaultDataSharingAttributes getDefaultDSA() const { 445 return isStackEmpty() ? DSA_unspecified 446 : Stack.back().first.back().DefaultAttr; 447 } 448 SourceLocation getDefaultDSALocation() const { 449 return isStackEmpty() ? SourceLocation() 450 : Stack.back().first.back().DefaultAttrLoc; 451 } 452 DefaultMapAttributes getDefaultDMA() const { 453 return isStackEmpty() ? DMA_unspecified 454 : Stack.back().first.back().DefaultMapAttr; 455 } 456 DefaultMapAttributes getDefaultDMAAtLevel(unsigned Level) const { 457 return Stack.back().first[Level].DefaultMapAttr; 458 } 459 SourceLocation getDefaultDMALocation() const { 460 return isStackEmpty() ? SourceLocation() 461 : Stack.back().first.back().DefaultMapAttrLoc; 462 } 463 464 /// Checks if the specified variable is a threadprivate. 465 bool isThreadPrivate(VarDecl *D) { 466 const DSAVarData DVar = getTopDSA(D, false); 467 return isOpenMPThreadPrivate(DVar.CKind); 468 } 469 470 /// Marks current region as ordered (it has an 'ordered' clause). 471 void setOrderedRegion(bool IsOrdered, const Expr *Param, 472 OMPOrderedClause *Clause) { 473 assert(!isStackEmpty()); 474 if (IsOrdered) 475 Stack.back().first.back().OrderedRegion.emplace(Param, Clause); 476 else 477 Stack.back().first.back().OrderedRegion.reset(); 478 } 479 /// Returns true, if region is ordered (has associated 'ordered' clause), 480 /// false - otherwise. 481 bool isOrderedRegion() const { 482 if (isStackEmpty()) 483 return false; 484 return Stack.back().first.rbegin()->OrderedRegion.hasValue(); 485 } 486 /// Returns optional parameter for the ordered region. 487 std::pair<const Expr *, OMPOrderedClause *> getOrderedRegionParam() const { 488 if (isStackEmpty() || 489 !Stack.back().first.rbegin()->OrderedRegion.hasValue()) 490 return std::make_pair(nullptr, nullptr); 491 return Stack.back().first.rbegin()->OrderedRegion.getValue(); 492 } 493 /// Returns true, if parent region is ordered (has associated 494 /// 'ordered' clause), false - otherwise. 495 bool isParentOrderedRegion() const { 496 if (isStackEmpty() || Stack.back().first.size() == 1) 497 return false; 498 return std::next(Stack.back().first.rbegin())->OrderedRegion.hasValue(); 499 } 500 /// Returns optional parameter for the ordered region. 501 std::pair<const Expr *, OMPOrderedClause *> 502 getParentOrderedRegionParam() const { 503 if (isStackEmpty() || Stack.back().first.size() == 1 || 504 !std::next(Stack.back().first.rbegin())->OrderedRegion.hasValue()) 505 return std::make_pair(nullptr, nullptr); 506 return std::next(Stack.back().first.rbegin())->OrderedRegion.getValue(); 507 } 508 /// Marks current region as nowait (it has a 'nowait' clause). 509 void setNowaitRegion(bool IsNowait = true) { 510 assert(!isStackEmpty()); 511 Stack.back().first.back().NowaitRegion = IsNowait; 512 } 513 /// Returns true, if parent region is nowait (has associated 514 /// 'nowait' clause), false - otherwise. 515 bool isParentNowaitRegion() const { 516 if (isStackEmpty() || Stack.back().first.size() == 1) 517 return false; 518 return std::next(Stack.back().first.rbegin())->NowaitRegion; 519 } 520 /// Marks parent region as cancel region. 521 void setParentCancelRegion(bool Cancel = true) { 522 if (!isStackEmpty() && Stack.back().first.size() > 1) { 523 auto &StackElemRef = *std::next(Stack.back().first.rbegin()); 524 StackElemRef.CancelRegion |= StackElemRef.CancelRegion || Cancel; 525 } 526 } 527 /// Return true if current region has inner cancel construct. 528 bool isCancelRegion() const { 529 return isStackEmpty() ? false : Stack.back().first.back().CancelRegion; 530 } 531 532 /// Set collapse value for the region. 533 void setAssociatedLoops(unsigned Val) { 534 assert(!isStackEmpty()); 535 Stack.back().first.back().AssociatedLoops = Val; 536 } 537 /// Return collapse value for region. 538 unsigned getAssociatedLoops() const { 539 return isStackEmpty() ? 0 : Stack.back().first.back().AssociatedLoops; 540 } 541 542 /// Marks current target region as one with closely nested teams 543 /// region. 544 void setParentTeamsRegionLoc(SourceLocation TeamsRegionLoc) { 545 if (!isStackEmpty() && Stack.back().first.size() > 1) { 546 std::next(Stack.back().first.rbegin())->InnerTeamsRegionLoc = 547 TeamsRegionLoc; 548 } 549 } 550 /// Returns true, if current region has closely nested teams region. 551 bool hasInnerTeamsRegion() const { 552 return getInnerTeamsRegionLoc().isValid(); 553 } 554 /// Returns location of the nested teams region (if any). 555 SourceLocation getInnerTeamsRegionLoc() const { 556 return isStackEmpty() ? SourceLocation() 557 : Stack.back().first.back().InnerTeamsRegionLoc; 558 } 559 560 Scope *getCurScope() const { 561 return isStackEmpty() ? nullptr : Stack.back().first.back().CurScope; 562 } 563 SourceLocation getConstructLoc() const { 564 return isStackEmpty() ? SourceLocation() 565 : Stack.back().first.back().ConstructLoc; 566 } 567 568 /// Do the check specified in \a Check to all component lists and return true 569 /// if any issue is found. 570 bool checkMappableExprComponentListsForDecl( 571 const ValueDecl *VD, bool CurrentRegionOnly, 572 const llvm::function_ref< 573 bool(OMPClauseMappableExprCommon::MappableExprComponentListRef, 574 OpenMPClauseKind)> 575 Check) const { 576 if (isStackEmpty()) 577 return false; 578 auto SI = Stack.back().first.rbegin(); 579 auto SE = Stack.back().first.rend(); 580 581 if (SI == SE) 582 return false; 583 584 if (CurrentRegionOnly) 585 SE = std::next(SI); 586 else 587 std::advance(SI, 1); 588 589 for (; SI != SE; ++SI) { 590 auto MI = SI->MappedExprComponents.find(VD); 591 if (MI != SI->MappedExprComponents.end()) 592 for (OMPClauseMappableExprCommon::MappableExprComponentListRef L : 593 MI->second.Components) 594 if (Check(L, MI->second.Kind)) 595 return true; 596 } 597 return false; 598 } 599 600 /// Do the check specified in \a Check to all component lists at a given level 601 /// and return true if any issue is found. 602 bool checkMappableExprComponentListsForDeclAtLevel( 603 const ValueDecl *VD, unsigned Level, 604 const llvm::function_ref< 605 bool(OMPClauseMappableExprCommon::MappableExprComponentListRef, 606 OpenMPClauseKind)> 607 Check) const { 608 if (isStackEmpty()) 609 return false; 610 611 auto StartI = Stack.back().first.begin(); 612 auto EndI = Stack.back().first.end(); 613 if (std::distance(StartI, EndI) <= (int)Level) 614 return false; 615 std::advance(StartI, Level); 616 617 auto MI = StartI->MappedExprComponents.find(VD); 618 if (MI != StartI->MappedExprComponents.end()) 619 for (OMPClauseMappableExprCommon::MappableExprComponentListRef L : 620 MI->second.Components) 621 if (Check(L, MI->second.Kind)) 622 return true; 623 return false; 624 } 625 626 /// Create a new mappable expression component list associated with a given 627 /// declaration and initialize it with the provided list of components. 628 void addMappableExpressionComponents( 629 const ValueDecl *VD, 630 OMPClauseMappableExprCommon::MappableExprComponentListRef Components, 631 OpenMPClauseKind WhereFoundClauseKind) { 632 assert(!isStackEmpty() && 633 "Not expecting to retrieve components from a empty stack!"); 634 MappedExprComponentTy &MEC = 635 Stack.back().first.back().MappedExprComponents[VD]; 636 // Create new entry and append the new components there. 637 MEC.Components.resize(MEC.Components.size() + 1); 638 MEC.Components.back().append(Components.begin(), Components.end()); 639 MEC.Kind = WhereFoundClauseKind; 640 } 641 642 unsigned getNestingLevel() const { 643 assert(!isStackEmpty()); 644 return Stack.back().first.size() - 1; 645 } 646 void addDoacrossDependClause(OMPDependClause *C, 647 const OperatorOffsetTy &OpsOffs) { 648 assert(!isStackEmpty() && Stack.back().first.size() > 1); 649 SharingMapTy &StackElem = *std::next(Stack.back().first.rbegin()); 650 assert(isOpenMPWorksharingDirective(StackElem.Directive)); 651 StackElem.DoacrossDepends.try_emplace(C, OpsOffs); 652 } 653 llvm::iterator_range<DoacrossDependMapTy::const_iterator> 654 getDoacrossDependClauses() const { 655 assert(!isStackEmpty()); 656 const SharingMapTy &StackElem = Stack.back().first.back(); 657 if (isOpenMPWorksharingDirective(StackElem.Directive)) { 658 const DoacrossDependMapTy &Ref = StackElem.DoacrossDepends; 659 return llvm::make_range(Ref.begin(), Ref.end()); 660 } 661 return llvm::make_range(StackElem.DoacrossDepends.end(), 662 StackElem.DoacrossDepends.end()); 663 } 664 665 // Store types of classes which have been explicitly mapped 666 void addMappedClassesQualTypes(QualType QT) { 667 SharingMapTy &StackElem = Stack.back().first.back(); 668 StackElem.MappedClassesQualTypes.insert(QT); 669 } 670 671 // Return set of mapped classes types 672 bool isClassPreviouslyMapped(QualType QT) const { 673 const SharingMapTy &StackElem = Stack.back().first.back(); 674 return StackElem.MappedClassesQualTypes.count(QT) != 0; 675 } 676 677 }; 678 679 bool isImplicitTaskingRegion(OpenMPDirectiveKind DKind) { 680 return isOpenMPParallelDirective(DKind) || isOpenMPTeamsDirective(DKind); 681 } 682 683 bool isImplicitOrExplicitTaskingRegion(OpenMPDirectiveKind DKind) { 684 return isImplicitTaskingRegion(DKind) || isOpenMPTaskingDirective(DKind) || DKind == OMPD_unknown; 685 } 686 687 } // namespace 688 689 static const Expr *getExprAsWritten(const Expr *E) { 690 if (const auto *FE = dyn_cast<FullExpr>(E)) 691 E = FE->getSubExpr(); 692 693 if (const auto *MTE = dyn_cast<MaterializeTemporaryExpr>(E)) 694 E = MTE->GetTemporaryExpr(); 695 696 while (const auto *Binder = dyn_cast<CXXBindTemporaryExpr>(E)) 697 E = Binder->getSubExpr(); 698 699 if (const auto *ICE = dyn_cast<ImplicitCastExpr>(E)) 700 E = ICE->getSubExprAsWritten(); 701 return E->IgnoreParens(); 702 } 703 704 static Expr *getExprAsWritten(Expr *E) { 705 return const_cast<Expr *>(getExprAsWritten(const_cast<const Expr *>(E))); 706 } 707 708 static const ValueDecl *getCanonicalDecl(const ValueDecl *D) { 709 if (const auto *CED = dyn_cast<OMPCapturedExprDecl>(D)) 710 if (const auto *ME = dyn_cast<MemberExpr>(getExprAsWritten(CED->getInit()))) 711 D = ME->getMemberDecl(); 712 const auto *VD = dyn_cast<VarDecl>(D); 713 const auto *FD = dyn_cast<FieldDecl>(D); 714 if (VD != nullptr) { 715 VD = VD->getCanonicalDecl(); 716 D = VD; 717 } else { 718 assert(FD); 719 FD = FD->getCanonicalDecl(); 720 D = FD; 721 } 722 return D; 723 } 724 725 static ValueDecl *getCanonicalDecl(ValueDecl *D) { 726 return const_cast<ValueDecl *>( 727 getCanonicalDecl(const_cast<const ValueDecl *>(D))); 728 } 729 730 DSAStackTy::DSAVarData DSAStackTy::getDSA(iterator &Iter, 731 ValueDecl *D) const { 732 D = getCanonicalDecl(D); 733 auto *VD = dyn_cast<VarDecl>(D); 734 const auto *FD = dyn_cast<FieldDecl>(D); 735 DSAVarData DVar; 736 if (isStackEmpty() || Iter == Stack.back().first.rend()) { 737 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced 738 // in a region but not in construct] 739 // File-scope or namespace-scope variables referenced in called routines 740 // in the region are shared unless they appear in a threadprivate 741 // directive. 742 if (VD && !VD->isFunctionOrMethodVarDecl() && !isa<ParmVarDecl>(VD)) 743 DVar.CKind = OMPC_shared; 744 745 // OpenMP [2.9.1.2, Data-sharing Attribute Rules for Variables Referenced 746 // in a region but not in construct] 747 // Variables with static storage duration that are declared in called 748 // routines in the region are shared. 749 if (VD && VD->hasGlobalStorage()) 750 DVar.CKind = OMPC_shared; 751 752 // Non-static data members are shared by default. 753 if (FD) 754 DVar.CKind = OMPC_shared; 755 756 return DVar; 757 } 758 759 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced 760 // in a Construct, C/C++, predetermined, p.1] 761 // Variables with automatic storage duration that are declared in a scope 762 // inside the construct are private. 763 if (VD && isOpenMPLocal(VD, Iter) && VD->isLocalVarDecl() && 764 (VD->getStorageClass() == SC_Auto || VD->getStorageClass() == SC_None)) { 765 DVar.CKind = OMPC_private; 766 return DVar; 767 } 768 769 DVar.DKind = Iter->Directive; 770 // Explicitly specified attributes and local variables with predetermined 771 // attributes. 772 if (Iter->SharingMap.count(D)) { 773 const DSAInfo &Data = Iter->SharingMap.lookup(D); 774 DVar.RefExpr = Data.RefExpr.getPointer(); 775 DVar.PrivateCopy = Data.PrivateCopy; 776 DVar.CKind = Data.Attributes; 777 DVar.ImplicitDSALoc = Iter->DefaultAttrLoc; 778 return DVar; 779 } 780 781 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced 782 // in a Construct, C/C++, implicitly determined, p.1] 783 // In a parallel or task construct, the data-sharing attributes of these 784 // variables are determined by the default clause, if present. 785 switch (Iter->DefaultAttr) { 786 case DSA_shared: 787 DVar.CKind = OMPC_shared; 788 DVar.ImplicitDSALoc = Iter->DefaultAttrLoc; 789 return DVar; 790 case DSA_none: 791 return DVar; 792 case DSA_unspecified: 793 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced 794 // in a Construct, implicitly determined, p.2] 795 // In a parallel construct, if no default clause is present, these 796 // variables are shared. 797 DVar.ImplicitDSALoc = Iter->DefaultAttrLoc; 798 if (isOpenMPParallelDirective(DVar.DKind) || 799 isOpenMPTeamsDirective(DVar.DKind)) { 800 DVar.CKind = OMPC_shared; 801 return DVar; 802 } 803 804 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced 805 // in a Construct, implicitly determined, p.4] 806 // In a task construct, if no default clause is present, a variable that in 807 // the enclosing context is determined to be shared by all implicit tasks 808 // bound to the current team is shared. 809 if (isOpenMPTaskingDirective(DVar.DKind)) { 810 DSAVarData DVarTemp; 811 iterator I = Iter, E = Stack.back().first.rend(); 812 do { 813 ++I; 814 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables 815 // Referenced in a Construct, implicitly determined, p.6] 816 // In a task construct, if no default clause is present, a variable 817 // whose data-sharing attribute is not determined by the rules above is 818 // firstprivate. 819 DVarTemp = getDSA(I, D); 820 if (DVarTemp.CKind != OMPC_shared) { 821 DVar.RefExpr = nullptr; 822 DVar.CKind = OMPC_firstprivate; 823 return DVar; 824 } 825 } while (I != E && !isImplicitTaskingRegion(I->Directive)); 826 DVar.CKind = 827 (DVarTemp.CKind == OMPC_unknown) ? OMPC_firstprivate : OMPC_shared; 828 return DVar; 829 } 830 } 831 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced 832 // in a Construct, implicitly determined, p.3] 833 // For constructs other than task, if no default clause is present, these 834 // variables inherit their data-sharing attributes from the enclosing 835 // context. 836 return getDSA(++Iter, D); 837 } 838 839 const Expr *DSAStackTy::addUniqueAligned(const ValueDecl *D, 840 const Expr *NewDE) { 841 assert(!isStackEmpty() && "Data sharing attributes stack is empty"); 842 D = getCanonicalDecl(D); 843 SharingMapTy &StackElem = Stack.back().first.back(); 844 auto It = StackElem.AlignedMap.find(D); 845 if (It == StackElem.AlignedMap.end()) { 846 assert(NewDE && "Unexpected nullptr expr to be added into aligned map"); 847 StackElem.AlignedMap[D] = NewDE; 848 return nullptr; 849 } 850 assert(It->second && "Unexpected nullptr expr in the aligned map"); 851 return It->second; 852 } 853 854 void DSAStackTy::addLoopControlVariable(const ValueDecl *D, VarDecl *Capture) { 855 assert(!isStackEmpty() && "Data-sharing attributes stack is empty"); 856 D = getCanonicalDecl(D); 857 SharingMapTy &StackElem = Stack.back().first.back(); 858 StackElem.LCVMap.try_emplace( 859 D, LCDeclInfo(StackElem.LCVMap.size() + 1, Capture)); 860 } 861 862 const DSAStackTy::LCDeclInfo 863 DSAStackTy::isLoopControlVariable(const ValueDecl *D) const { 864 assert(!isStackEmpty() && "Data-sharing attributes stack is empty"); 865 D = getCanonicalDecl(D); 866 const SharingMapTy &StackElem = Stack.back().first.back(); 867 auto It = StackElem.LCVMap.find(D); 868 if (It != StackElem.LCVMap.end()) 869 return It->second; 870 return {0, nullptr}; 871 } 872 873 const DSAStackTy::LCDeclInfo 874 DSAStackTy::isParentLoopControlVariable(const ValueDecl *D) const { 875 assert(!isStackEmpty() && Stack.back().first.size() > 1 && 876 "Data-sharing attributes stack is empty"); 877 D = getCanonicalDecl(D); 878 const SharingMapTy &StackElem = *std::next(Stack.back().first.rbegin()); 879 auto It = StackElem.LCVMap.find(D); 880 if (It != StackElem.LCVMap.end()) 881 return It->second; 882 return {0, nullptr}; 883 } 884 885 const ValueDecl *DSAStackTy::getParentLoopControlVariable(unsigned I) const { 886 assert(!isStackEmpty() && Stack.back().first.size() > 1 && 887 "Data-sharing attributes stack is empty"); 888 const SharingMapTy &StackElem = *std::next(Stack.back().first.rbegin()); 889 if (StackElem.LCVMap.size() < I) 890 return nullptr; 891 for (const auto &Pair : StackElem.LCVMap) 892 if (Pair.second.first == I) 893 return Pair.first; 894 return nullptr; 895 } 896 897 void DSAStackTy::addDSA(const ValueDecl *D, const Expr *E, OpenMPClauseKind A, 898 DeclRefExpr *PrivateCopy) { 899 D = getCanonicalDecl(D); 900 if (A == OMPC_threadprivate) { 901 DSAInfo &Data = Threadprivates[D]; 902 Data.Attributes = A; 903 Data.RefExpr.setPointer(E); 904 Data.PrivateCopy = nullptr; 905 } else { 906 assert(!isStackEmpty() && "Data-sharing attributes stack is empty"); 907 DSAInfo &Data = Stack.back().first.back().SharingMap[D]; 908 assert(Data.Attributes == OMPC_unknown || (A == Data.Attributes) || 909 (A == OMPC_firstprivate && Data.Attributes == OMPC_lastprivate) || 910 (A == OMPC_lastprivate && Data.Attributes == OMPC_firstprivate) || 911 (isLoopControlVariable(D).first && A == OMPC_private)); 912 if (A == OMPC_lastprivate && Data.Attributes == OMPC_firstprivate) { 913 Data.RefExpr.setInt(/*IntVal=*/true); 914 return; 915 } 916 const bool IsLastprivate = 917 A == OMPC_lastprivate || Data.Attributes == OMPC_lastprivate; 918 Data.Attributes = A; 919 Data.RefExpr.setPointerAndInt(E, IsLastprivate); 920 Data.PrivateCopy = PrivateCopy; 921 if (PrivateCopy) { 922 DSAInfo &Data = 923 Stack.back().first.back().SharingMap[PrivateCopy->getDecl()]; 924 Data.Attributes = A; 925 Data.RefExpr.setPointerAndInt(PrivateCopy, IsLastprivate); 926 Data.PrivateCopy = nullptr; 927 } 928 } 929 } 930 931 /// Build a variable declaration for OpenMP loop iteration variable. 932 static VarDecl *buildVarDecl(Sema &SemaRef, SourceLocation Loc, QualType Type, 933 StringRef Name, const AttrVec *Attrs = nullptr, 934 DeclRefExpr *OrigRef = nullptr) { 935 DeclContext *DC = SemaRef.CurContext; 936 IdentifierInfo *II = &SemaRef.PP.getIdentifierTable().get(Name); 937 TypeSourceInfo *TInfo = SemaRef.Context.getTrivialTypeSourceInfo(Type, Loc); 938 auto *Decl = 939 VarDecl::Create(SemaRef.Context, DC, Loc, Loc, II, Type, TInfo, SC_None); 940 if (Attrs) { 941 for (specific_attr_iterator<AlignedAttr> I(Attrs->begin()), E(Attrs->end()); 942 I != E; ++I) 943 Decl->addAttr(*I); 944 } 945 Decl->setImplicit(); 946 if (OrigRef) { 947 Decl->addAttr( 948 OMPReferencedVarAttr::CreateImplicit(SemaRef.Context, OrigRef)); 949 } 950 return Decl; 951 } 952 953 static DeclRefExpr *buildDeclRefExpr(Sema &S, VarDecl *D, QualType Ty, 954 SourceLocation Loc, 955 bool RefersToCapture = false) { 956 D->setReferenced(); 957 D->markUsed(S.Context); 958 return DeclRefExpr::Create(S.getASTContext(), NestedNameSpecifierLoc(), 959 SourceLocation(), D, RefersToCapture, Loc, Ty, 960 VK_LValue); 961 } 962 963 void DSAStackTy::addTaskgroupReductionData(const ValueDecl *D, SourceRange SR, 964 BinaryOperatorKind BOK) { 965 D = getCanonicalDecl(D); 966 assert(!isStackEmpty() && "Data-sharing attributes stack is empty"); 967 assert( 968 Stack.back().first.back().SharingMap[D].Attributes == OMPC_reduction && 969 "Additional reduction info may be specified only for reduction items."); 970 ReductionData &ReductionData = Stack.back().first.back().ReductionMap[D]; 971 assert(ReductionData.ReductionRange.isInvalid() && 972 Stack.back().first.back().Directive == OMPD_taskgroup && 973 "Additional reduction info may be specified only once for reduction " 974 "items."); 975 ReductionData.set(BOK, SR); 976 Expr *&TaskgroupReductionRef = 977 Stack.back().first.back().TaskgroupReductionRef; 978 if (!TaskgroupReductionRef) { 979 VarDecl *VD = buildVarDecl(SemaRef, SR.getBegin(), 980 SemaRef.Context.VoidPtrTy, ".task_red."); 981 TaskgroupReductionRef = 982 buildDeclRefExpr(SemaRef, VD, SemaRef.Context.VoidPtrTy, SR.getBegin()); 983 } 984 } 985 986 void DSAStackTy::addTaskgroupReductionData(const ValueDecl *D, SourceRange SR, 987 const Expr *ReductionRef) { 988 D = getCanonicalDecl(D); 989 assert(!isStackEmpty() && "Data-sharing attributes stack is empty"); 990 assert( 991 Stack.back().first.back().SharingMap[D].Attributes == OMPC_reduction && 992 "Additional reduction info may be specified only for reduction items."); 993 ReductionData &ReductionData = Stack.back().first.back().ReductionMap[D]; 994 assert(ReductionData.ReductionRange.isInvalid() && 995 Stack.back().first.back().Directive == OMPD_taskgroup && 996 "Additional reduction info may be specified only once for reduction " 997 "items."); 998 ReductionData.set(ReductionRef, SR); 999 Expr *&TaskgroupReductionRef = 1000 Stack.back().first.back().TaskgroupReductionRef; 1001 if (!TaskgroupReductionRef) { 1002 VarDecl *VD = buildVarDecl(SemaRef, SR.getBegin(), 1003 SemaRef.Context.VoidPtrTy, ".task_red."); 1004 TaskgroupReductionRef = 1005 buildDeclRefExpr(SemaRef, VD, SemaRef.Context.VoidPtrTy, SR.getBegin()); 1006 } 1007 } 1008 1009 const DSAStackTy::DSAVarData DSAStackTy::getTopMostTaskgroupReductionData( 1010 const ValueDecl *D, SourceRange &SR, BinaryOperatorKind &BOK, 1011 Expr *&TaskgroupDescriptor) const { 1012 D = getCanonicalDecl(D); 1013 assert(!isStackEmpty() && "Data-sharing attributes stack is empty."); 1014 if (Stack.back().first.empty()) 1015 return DSAVarData(); 1016 for (iterator I = std::next(Stack.back().first.rbegin(), 1), 1017 E = Stack.back().first.rend(); 1018 I != E; std::advance(I, 1)) { 1019 const DSAInfo &Data = I->SharingMap.lookup(D); 1020 if (Data.Attributes != OMPC_reduction || I->Directive != OMPD_taskgroup) 1021 continue; 1022 const ReductionData &ReductionData = I->ReductionMap.lookup(D); 1023 if (!ReductionData.ReductionOp || 1024 ReductionData.ReductionOp.is<const Expr *>()) 1025 return DSAVarData(); 1026 SR = ReductionData.ReductionRange; 1027 BOK = ReductionData.ReductionOp.get<ReductionData::BOKPtrType>(); 1028 assert(I->TaskgroupReductionRef && "taskgroup reduction reference " 1029 "expression for the descriptor is not " 1030 "set."); 1031 TaskgroupDescriptor = I->TaskgroupReductionRef; 1032 return DSAVarData(OMPD_taskgroup, OMPC_reduction, Data.RefExpr.getPointer(), 1033 Data.PrivateCopy, I->DefaultAttrLoc); 1034 } 1035 return DSAVarData(); 1036 } 1037 1038 const DSAStackTy::DSAVarData DSAStackTy::getTopMostTaskgroupReductionData( 1039 const ValueDecl *D, SourceRange &SR, const Expr *&ReductionRef, 1040 Expr *&TaskgroupDescriptor) const { 1041 D = getCanonicalDecl(D); 1042 assert(!isStackEmpty() && "Data-sharing attributes stack is empty."); 1043 if (Stack.back().first.empty()) 1044 return DSAVarData(); 1045 for (iterator I = std::next(Stack.back().first.rbegin(), 1), 1046 E = Stack.back().first.rend(); 1047 I != E; std::advance(I, 1)) { 1048 const DSAInfo &Data = I->SharingMap.lookup(D); 1049 if (Data.Attributes != OMPC_reduction || I->Directive != OMPD_taskgroup) 1050 continue; 1051 const ReductionData &ReductionData = I->ReductionMap.lookup(D); 1052 if (!ReductionData.ReductionOp || 1053 !ReductionData.ReductionOp.is<const Expr *>()) 1054 return DSAVarData(); 1055 SR = ReductionData.ReductionRange; 1056 ReductionRef = ReductionData.ReductionOp.get<const Expr *>(); 1057 assert(I->TaskgroupReductionRef && "taskgroup reduction reference " 1058 "expression for the descriptor is not " 1059 "set."); 1060 TaskgroupDescriptor = I->TaskgroupReductionRef; 1061 return DSAVarData(OMPD_taskgroup, OMPC_reduction, Data.RefExpr.getPointer(), 1062 Data.PrivateCopy, I->DefaultAttrLoc); 1063 } 1064 return DSAVarData(); 1065 } 1066 1067 bool DSAStackTy::isOpenMPLocal(VarDecl *D, iterator Iter) const { 1068 D = D->getCanonicalDecl(); 1069 if (!isStackEmpty()) { 1070 iterator I = Iter, E = Stack.back().first.rend(); 1071 Scope *TopScope = nullptr; 1072 while (I != E && !isImplicitOrExplicitTaskingRegion(I->Directive) && 1073 !isOpenMPTargetExecutionDirective(I->Directive)) 1074 ++I; 1075 if (I == E) 1076 return false; 1077 TopScope = I->CurScope ? I->CurScope->getParent() : nullptr; 1078 Scope *CurScope = getCurScope(); 1079 while (CurScope != TopScope && !CurScope->isDeclScope(D)) 1080 CurScope = CurScope->getParent(); 1081 return CurScope != TopScope; 1082 } 1083 return false; 1084 } 1085 1086 static bool isConstNotMutableType(Sema &SemaRef, QualType Type, 1087 bool AcceptIfMutable = true, 1088 bool *IsClassType = nullptr) { 1089 ASTContext &Context = SemaRef.getASTContext(); 1090 Type = Type.getNonReferenceType().getCanonicalType(); 1091 bool IsConstant = Type.isConstant(Context); 1092 Type = Context.getBaseElementType(Type); 1093 const CXXRecordDecl *RD = AcceptIfMutable && SemaRef.getLangOpts().CPlusPlus 1094 ? Type->getAsCXXRecordDecl() 1095 : nullptr; 1096 if (const auto *CTSD = dyn_cast_or_null<ClassTemplateSpecializationDecl>(RD)) 1097 if (const ClassTemplateDecl *CTD = CTSD->getSpecializedTemplate()) 1098 RD = CTD->getTemplatedDecl(); 1099 if (IsClassType) 1100 *IsClassType = RD; 1101 return IsConstant && !(SemaRef.getLangOpts().CPlusPlus && RD && 1102 RD->hasDefinition() && RD->hasMutableFields()); 1103 } 1104 1105 static bool rejectConstNotMutableType(Sema &SemaRef, const ValueDecl *D, 1106 QualType Type, OpenMPClauseKind CKind, 1107 SourceLocation ELoc, 1108 bool AcceptIfMutable = true, 1109 bool ListItemNotVar = false) { 1110 ASTContext &Context = SemaRef.getASTContext(); 1111 bool IsClassType; 1112 if (isConstNotMutableType(SemaRef, Type, AcceptIfMutable, &IsClassType)) { 1113 unsigned Diag = ListItemNotVar 1114 ? diag::err_omp_const_list_item 1115 : IsClassType ? diag::err_omp_const_not_mutable_variable 1116 : diag::err_omp_const_variable; 1117 SemaRef.Diag(ELoc, Diag) << getOpenMPClauseName(CKind); 1118 if (!ListItemNotVar && D) { 1119 const VarDecl *VD = dyn_cast<VarDecl>(D); 1120 bool IsDecl = !VD || VD->isThisDeclarationADefinition(Context) == 1121 VarDecl::DeclarationOnly; 1122 SemaRef.Diag(D->getLocation(), 1123 IsDecl ? diag::note_previous_decl : diag::note_defined_here) 1124 << D; 1125 } 1126 return true; 1127 } 1128 return false; 1129 } 1130 1131 const DSAStackTy::DSAVarData DSAStackTy::getTopDSA(ValueDecl *D, 1132 bool FromParent) { 1133 D = getCanonicalDecl(D); 1134 DSAVarData DVar; 1135 1136 auto *VD = dyn_cast<VarDecl>(D); 1137 auto TI = Threadprivates.find(D); 1138 if (TI != Threadprivates.end()) { 1139 DVar.RefExpr = TI->getSecond().RefExpr.getPointer(); 1140 DVar.CKind = OMPC_threadprivate; 1141 return DVar; 1142 } 1143 if (VD && VD->hasAttr<OMPThreadPrivateDeclAttr>()) { 1144 DVar.RefExpr = buildDeclRefExpr( 1145 SemaRef, VD, D->getType().getNonReferenceType(), 1146 VD->getAttr<OMPThreadPrivateDeclAttr>()->getLocation()); 1147 DVar.CKind = OMPC_threadprivate; 1148 addDSA(D, DVar.RefExpr, OMPC_threadprivate); 1149 return DVar; 1150 } 1151 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced 1152 // in a Construct, C/C++, predetermined, p.1] 1153 // Variables appearing in threadprivate directives are threadprivate. 1154 if ((VD && VD->getTLSKind() != VarDecl::TLS_None && 1155 !(VD->hasAttr<OMPThreadPrivateDeclAttr>() && 1156 SemaRef.getLangOpts().OpenMPUseTLS && 1157 SemaRef.getASTContext().getTargetInfo().isTLSSupported())) || 1158 (VD && VD->getStorageClass() == SC_Register && 1159 VD->hasAttr<AsmLabelAttr>() && !VD->isLocalVarDecl())) { 1160 DVar.RefExpr = buildDeclRefExpr( 1161 SemaRef, VD, D->getType().getNonReferenceType(), D->getLocation()); 1162 DVar.CKind = OMPC_threadprivate; 1163 addDSA(D, DVar.RefExpr, OMPC_threadprivate); 1164 return DVar; 1165 } 1166 if (SemaRef.getLangOpts().OpenMPCUDAMode && VD && 1167 VD->isLocalVarDeclOrParm() && !isStackEmpty() && 1168 !isLoopControlVariable(D).first) { 1169 iterator IterTarget = 1170 std::find_if(Stack.back().first.rbegin(), Stack.back().first.rend(), 1171 [](const SharingMapTy &Data) { 1172 return isOpenMPTargetExecutionDirective(Data.Directive); 1173 }); 1174 if (IterTarget != Stack.back().first.rend()) { 1175 iterator ParentIterTarget = std::next(IterTarget, 1); 1176 for (iterator Iter = Stack.back().first.rbegin(); 1177 Iter != ParentIterTarget; std::advance(Iter, 1)) { 1178 if (isOpenMPLocal(VD, Iter)) { 1179 DVar.RefExpr = 1180 buildDeclRefExpr(SemaRef, VD, D->getType().getNonReferenceType(), 1181 D->getLocation()); 1182 DVar.CKind = OMPC_threadprivate; 1183 return DVar; 1184 } 1185 } 1186 if (!isClauseParsingMode() || IterTarget != Stack.back().first.rbegin()) { 1187 auto DSAIter = IterTarget->SharingMap.find(D); 1188 if (DSAIter != IterTarget->SharingMap.end() && 1189 isOpenMPPrivate(DSAIter->getSecond().Attributes)) { 1190 DVar.RefExpr = DSAIter->getSecond().RefExpr.getPointer(); 1191 DVar.CKind = OMPC_threadprivate; 1192 return DVar; 1193 } 1194 iterator End = Stack.back().first.rend(); 1195 if (!SemaRef.isOpenMPCapturedByRef( 1196 D, std::distance(ParentIterTarget, End))) { 1197 DVar.RefExpr = 1198 buildDeclRefExpr(SemaRef, VD, D->getType().getNonReferenceType(), 1199 IterTarget->ConstructLoc); 1200 DVar.CKind = OMPC_threadprivate; 1201 return DVar; 1202 } 1203 } 1204 } 1205 } 1206 1207 if (isStackEmpty()) 1208 // Not in OpenMP execution region and top scope was already checked. 1209 return DVar; 1210 1211 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced 1212 // in a Construct, C/C++, predetermined, p.4] 1213 // Static data members are shared. 1214 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced 1215 // in a Construct, C/C++, predetermined, p.7] 1216 // Variables with static storage duration that are declared in a scope 1217 // inside the construct are shared. 1218 auto &&MatchesAlways = [](OpenMPDirectiveKind) { return true; }; 1219 if (VD && VD->isStaticDataMember()) { 1220 DSAVarData DVarTemp = hasDSA(D, isOpenMPPrivate, MatchesAlways, FromParent); 1221 if (DVarTemp.CKind != OMPC_unknown && DVarTemp.RefExpr) 1222 return DVar; 1223 1224 DVar.CKind = OMPC_shared; 1225 return DVar; 1226 } 1227 1228 // The predetermined shared attribute for const-qualified types having no 1229 // mutable members was removed after OpenMP 3.1. 1230 if (SemaRef.LangOpts.OpenMP <= 31) { 1231 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced 1232 // in a Construct, C/C++, predetermined, p.6] 1233 // Variables with const qualified type having no mutable member are 1234 // shared. 1235 if (isConstNotMutableType(SemaRef, D->getType())) { 1236 // Variables with const-qualified type having no mutable member may be 1237 // listed in a firstprivate clause, even if they are static data members. 1238 DSAVarData DVarTemp = hasInnermostDSA( 1239 D, 1240 [](OpenMPClauseKind C) { 1241 return C == OMPC_firstprivate || C == OMPC_shared; 1242 }, 1243 MatchesAlways, FromParent); 1244 if (DVarTemp.CKind != OMPC_unknown && DVarTemp.RefExpr) 1245 return DVarTemp; 1246 1247 DVar.CKind = OMPC_shared; 1248 return DVar; 1249 } 1250 } 1251 1252 // Explicitly specified attributes and local variables with predetermined 1253 // attributes. 1254 iterator I = Stack.back().first.rbegin(); 1255 iterator EndI = Stack.back().first.rend(); 1256 if (FromParent && I != EndI) 1257 std::advance(I, 1); 1258 auto It = I->SharingMap.find(D); 1259 if (It != I->SharingMap.end()) { 1260 const DSAInfo &Data = It->getSecond(); 1261 DVar.RefExpr = Data.RefExpr.getPointer(); 1262 DVar.PrivateCopy = Data.PrivateCopy; 1263 DVar.CKind = Data.Attributes; 1264 DVar.ImplicitDSALoc = I->DefaultAttrLoc; 1265 DVar.DKind = I->Directive; 1266 } 1267 1268 return DVar; 1269 } 1270 1271 const DSAStackTy::DSAVarData DSAStackTy::getImplicitDSA(ValueDecl *D, 1272 bool FromParent) const { 1273 if (isStackEmpty()) { 1274 iterator I; 1275 return getDSA(I, D); 1276 } 1277 D = getCanonicalDecl(D); 1278 iterator StartI = Stack.back().first.rbegin(); 1279 iterator EndI = Stack.back().first.rend(); 1280 if (FromParent && StartI != EndI) 1281 std::advance(StartI, 1); 1282 return getDSA(StartI, D); 1283 } 1284 1285 const DSAStackTy::DSAVarData 1286 DSAStackTy::hasDSA(ValueDecl *D, 1287 const llvm::function_ref<bool(OpenMPClauseKind)> CPred, 1288 const llvm::function_ref<bool(OpenMPDirectiveKind)> DPred, 1289 bool FromParent) const { 1290 if (isStackEmpty()) 1291 return {}; 1292 D = getCanonicalDecl(D); 1293 iterator I = Stack.back().first.rbegin(); 1294 iterator EndI = Stack.back().first.rend(); 1295 if (FromParent && I != EndI) 1296 std::advance(I, 1); 1297 for (; I != EndI; std::advance(I, 1)) { 1298 if (!DPred(I->Directive) && !isImplicitOrExplicitTaskingRegion(I->Directive)) 1299 continue; 1300 iterator NewI = I; 1301 DSAVarData DVar = getDSA(NewI, D); 1302 if (I == NewI && CPred(DVar.CKind)) 1303 return DVar; 1304 } 1305 return {}; 1306 } 1307 1308 const DSAStackTy::DSAVarData DSAStackTy::hasInnermostDSA( 1309 ValueDecl *D, const llvm::function_ref<bool(OpenMPClauseKind)> CPred, 1310 const llvm::function_ref<bool(OpenMPDirectiveKind)> DPred, 1311 bool FromParent) const { 1312 if (isStackEmpty()) 1313 return {}; 1314 D = getCanonicalDecl(D); 1315 iterator StartI = Stack.back().first.rbegin(); 1316 iterator EndI = Stack.back().first.rend(); 1317 if (FromParent && StartI != EndI) 1318 std::advance(StartI, 1); 1319 if (StartI == EndI || !DPred(StartI->Directive)) 1320 return {}; 1321 iterator NewI = StartI; 1322 DSAVarData DVar = getDSA(NewI, D); 1323 return (NewI == StartI && CPred(DVar.CKind)) ? DVar : DSAVarData(); 1324 } 1325 1326 bool DSAStackTy::hasExplicitDSA( 1327 const ValueDecl *D, const llvm::function_ref<bool(OpenMPClauseKind)> CPred, 1328 unsigned Level, bool NotLastprivate) const { 1329 if (isStackEmpty()) 1330 return false; 1331 D = getCanonicalDecl(D); 1332 auto StartI = Stack.back().first.begin(); 1333 auto EndI = Stack.back().first.end(); 1334 if (std::distance(StartI, EndI) <= (int)Level) 1335 return false; 1336 std::advance(StartI, Level); 1337 auto I = StartI->SharingMap.find(D); 1338 if ((I != StartI->SharingMap.end()) && 1339 I->getSecond().RefExpr.getPointer() && 1340 CPred(I->getSecond().Attributes) && 1341 (!NotLastprivate || !I->getSecond().RefExpr.getInt())) 1342 return true; 1343 // Check predetermined rules for the loop control variables. 1344 auto LI = StartI->LCVMap.find(D); 1345 if (LI != StartI->LCVMap.end()) 1346 return CPred(OMPC_private); 1347 return false; 1348 } 1349 1350 bool DSAStackTy::hasExplicitDirective( 1351 const llvm::function_ref<bool(OpenMPDirectiveKind)> DPred, 1352 unsigned Level) const { 1353 if (isStackEmpty()) 1354 return false; 1355 auto StartI = Stack.back().first.begin(); 1356 auto EndI = Stack.back().first.end(); 1357 if (std::distance(StartI, EndI) <= (int)Level) 1358 return false; 1359 std::advance(StartI, Level); 1360 return DPred(StartI->Directive); 1361 } 1362 1363 bool DSAStackTy::hasDirective( 1364 const llvm::function_ref<bool(OpenMPDirectiveKind, 1365 const DeclarationNameInfo &, SourceLocation)> 1366 DPred, 1367 bool FromParent) const { 1368 // We look only in the enclosing region. 1369 if (isStackEmpty()) 1370 return false; 1371 auto StartI = std::next(Stack.back().first.rbegin()); 1372 auto EndI = Stack.back().first.rend(); 1373 if (FromParent && StartI != EndI) 1374 StartI = std::next(StartI); 1375 for (auto I = StartI, EE = EndI; I != EE; ++I) { 1376 if (DPred(I->Directive, I->DirectiveName, I->ConstructLoc)) 1377 return true; 1378 } 1379 return false; 1380 } 1381 1382 void Sema::InitDataSharingAttributesStack() { 1383 VarDataSharingAttributesStack = new DSAStackTy(*this); 1384 } 1385 1386 #define DSAStack static_cast<DSAStackTy *>(VarDataSharingAttributesStack) 1387 1388 void Sema::pushOpenMPFunctionRegion() { 1389 DSAStack->pushFunction(); 1390 } 1391 1392 void Sema::popOpenMPFunctionRegion(const FunctionScopeInfo *OldFSI) { 1393 DSAStack->popFunction(OldFSI); 1394 } 1395 1396 static bool isOpenMPDeviceDelayedContext(Sema &S) { 1397 assert(S.LangOpts.OpenMP && S.LangOpts.OpenMPIsDevice && 1398 "Expected OpenMP device compilation."); 1399 return !S.isInOpenMPTargetExecutionDirective() && 1400 !S.isInOpenMPDeclareTargetContext(); 1401 } 1402 1403 /// Do we know that we will eventually codegen the given function? 1404 static bool isKnownEmitted(Sema &S, FunctionDecl *FD) { 1405 assert(S.LangOpts.OpenMP && S.LangOpts.OpenMPIsDevice && 1406 "Expected OpenMP device compilation."); 1407 // Templates are emitted when they're instantiated. 1408 if (FD->isDependentContext()) 1409 return false; 1410 1411 if (OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration( 1412 FD->getCanonicalDecl())) 1413 return true; 1414 1415 // Otherwise, the function is known-emitted if it's in our set of 1416 // known-emitted functions. 1417 return S.DeviceKnownEmittedFns.count(FD) > 0; 1418 } 1419 1420 Sema::DeviceDiagBuilder Sema::diagIfOpenMPDeviceCode(SourceLocation Loc, 1421 unsigned DiagID) { 1422 assert(LangOpts.OpenMP && LangOpts.OpenMPIsDevice && 1423 "Expected OpenMP device compilation."); 1424 return DeviceDiagBuilder((isOpenMPDeviceDelayedContext(*this) && 1425 !isKnownEmitted(*this, getCurFunctionDecl())) 1426 ? DeviceDiagBuilder::K_Deferred 1427 : DeviceDiagBuilder::K_Immediate, 1428 Loc, DiagID, getCurFunctionDecl(), *this); 1429 } 1430 1431 void Sema::checkOpenMPDeviceFunction(SourceLocation Loc, FunctionDecl *Callee) { 1432 assert(LangOpts.OpenMP && LangOpts.OpenMPIsDevice && 1433 "Expected OpenMP device compilation."); 1434 assert(Callee && "Callee may not be null."); 1435 FunctionDecl *Caller = getCurFunctionDecl(); 1436 1437 // If the caller is known-emitted, mark the callee as known-emitted. 1438 // Otherwise, mark the call in our call graph so we can traverse it later. 1439 if (!isOpenMPDeviceDelayedContext(*this) || 1440 (Caller && isKnownEmitted(*this, Caller))) 1441 markKnownEmitted(*this, Caller, Callee, Loc, isKnownEmitted); 1442 else if (Caller) 1443 DeviceCallGraph[Caller].insert({Callee, Loc}); 1444 } 1445 1446 bool Sema::isOpenMPCapturedByRef(const ValueDecl *D, unsigned Level) const { 1447 assert(LangOpts.OpenMP && "OpenMP is not allowed"); 1448 1449 ASTContext &Ctx = getASTContext(); 1450 bool IsByRef = true; 1451 1452 // Find the directive that is associated with the provided scope. 1453 D = cast<ValueDecl>(D->getCanonicalDecl()); 1454 QualType Ty = D->getType(); 1455 1456 if (DSAStack->hasExplicitDirective(isOpenMPTargetExecutionDirective, Level)) { 1457 // This table summarizes how a given variable should be passed to the device 1458 // given its type and the clauses where it appears. This table is based on 1459 // the description in OpenMP 4.5 [2.10.4, target Construct] and 1460 // OpenMP 4.5 [2.15.5, Data-mapping Attribute Rules and Clauses]. 1461 // 1462 // ========================================================================= 1463 // | type | defaultmap | pvt | first | is_device_ptr | map | res. | 1464 // | |(tofrom:scalar)| | pvt | | | | 1465 // ========================================================================= 1466 // | scl | | | | - | | bycopy| 1467 // | scl | | - | x | - | - | bycopy| 1468 // | scl | | x | - | - | - | null | 1469 // | scl | x | | | - | | byref | 1470 // | scl | x | - | x | - | - | bycopy| 1471 // | scl | x | x | - | - | - | null | 1472 // | scl | | - | - | - | x | byref | 1473 // | scl | x | - | - | - | x | byref | 1474 // 1475 // | agg | n.a. | | | - | | byref | 1476 // | agg | n.a. | - | x | - | - | byref | 1477 // | agg | n.a. | x | - | - | - | null | 1478 // | agg | n.a. | - | - | - | x | byref | 1479 // | agg | n.a. | - | - | - | x[] | byref | 1480 // 1481 // | ptr | n.a. | | | - | | bycopy| 1482 // | ptr | n.a. | - | x | - | - | bycopy| 1483 // | ptr | n.a. | x | - | - | - | null | 1484 // | ptr | n.a. | - | - | - | x | byref | 1485 // | ptr | n.a. | - | - | - | x[] | bycopy| 1486 // | ptr | n.a. | - | - | x | | bycopy| 1487 // | ptr | n.a. | - | - | x | x | bycopy| 1488 // | ptr | n.a. | - | - | x | x[] | bycopy| 1489 // ========================================================================= 1490 // Legend: 1491 // scl - scalar 1492 // ptr - pointer 1493 // agg - aggregate 1494 // x - applies 1495 // - - invalid in this combination 1496 // [] - mapped with an array section 1497 // byref - should be mapped by reference 1498 // byval - should be mapped by value 1499 // null - initialize a local variable to null on the device 1500 // 1501 // Observations: 1502 // - All scalar declarations that show up in a map clause have to be passed 1503 // by reference, because they may have been mapped in the enclosing data 1504 // environment. 1505 // - If the scalar value does not fit the size of uintptr, it has to be 1506 // passed by reference, regardless the result in the table above. 1507 // - For pointers mapped by value that have either an implicit map or an 1508 // array section, the runtime library may pass the NULL value to the 1509 // device instead of the value passed to it by the compiler. 1510 1511 if (Ty->isReferenceType()) 1512 Ty = Ty->castAs<ReferenceType>()->getPointeeType(); 1513 1514 // Locate map clauses and see if the variable being captured is referred to 1515 // in any of those clauses. Here we only care about variables, not fields, 1516 // because fields are part of aggregates. 1517 bool IsVariableUsedInMapClause = false; 1518 bool IsVariableAssociatedWithSection = false; 1519 1520 DSAStack->checkMappableExprComponentListsForDeclAtLevel( 1521 D, Level, 1522 [&IsVariableUsedInMapClause, &IsVariableAssociatedWithSection, D]( 1523 OMPClauseMappableExprCommon::MappableExprComponentListRef 1524 MapExprComponents, 1525 OpenMPClauseKind WhereFoundClauseKind) { 1526 // Only the map clause information influences how a variable is 1527 // captured. E.g. is_device_ptr does not require changing the default 1528 // behavior. 1529 if (WhereFoundClauseKind != OMPC_map) 1530 return false; 1531 1532 auto EI = MapExprComponents.rbegin(); 1533 auto EE = MapExprComponents.rend(); 1534 1535 assert(EI != EE && "Invalid map expression!"); 1536 1537 if (isa<DeclRefExpr>(EI->getAssociatedExpression())) 1538 IsVariableUsedInMapClause |= EI->getAssociatedDeclaration() == D; 1539 1540 ++EI; 1541 if (EI == EE) 1542 return false; 1543 1544 if (isa<ArraySubscriptExpr>(EI->getAssociatedExpression()) || 1545 isa<OMPArraySectionExpr>(EI->getAssociatedExpression()) || 1546 isa<MemberExpr>(EI->getAssociatedExpression())) { 1547 IsVariableAssociatedWithSection = true; 1548 // There is nothing more we need to know about this variable. 1549 return true; 1550 } 1551 1552 // Keep looking for more map info. 1553 return false; 1554 }); 1555 1556 if (IsVariableUsedInMapClause) { 1557 // If variable is identified in a map clause it is always captured by 1558 // reference except if it is a pointer that is dereferenced somehow. 1559 IsByRef = !(Ty->isPointerType() && IsVariableAssociatedWithSection); 1560 } else { 1561 // By default, all the data that has a scalar type is mapped by copy 1562 // (except for reduction variables). 1563 IsByRef = 1564 (DSAStack->isForceCaptureByReferenceInTargetExecutable() && 1565 !Ty->isAnyPointerType()) || 1566 !Ty->isScalarType() || 1567 DSAStack->getDefaultDMAAtLevel(Level) == DMA_tofrom_scalar || 1568 DSAStack->hasExplicitDSA( 1569 D, [](OpenMPClauseKind K) { return K == OMPC_reduction; }, Level); 1570 } 1571 } 1572 1573 if (IsByRef && Ty.getNonReferenceType()->isScalarType()) { 1574 IsByRef = 1575 ((DSAStack->isForceCaptureByReferenceInTargetExecutable() && 1576 !Ty->isAnyPointerType()) || 1577 !DSAStack->hasExplicitDSA( 1578 D, 1579 [](OpenMPClauseKind K) -> bool { return K == OMPC_firstprivate; }, 1580 Level, /*NotLastprivate=*/true)) && 1581 // If the variable is artificial and must be captured by value - try to 1582 // capture by value. 1583 !(isa<OMPCapturedExprDecl>(D) && !D->hasAttr<OMPCaptureNoInitAttr>() && 1584 !cast<OMPCapturedExprDecl>(D)->getInit()->isGLValue()); 1585 } 1586 1587 // When passing data by copy, we need to make sure it fits the uintptr size 1588 // and alignment, because the runtime library only deals with uintptr types. 1589 // If it does not fit the uintptr size, we need to pass the data by reference 1590 // instead. 1591 if (!IsByRef && 1592 (Ctx.getTypeSizeInChars(Ty) > 1593 Ctx.getTypeSizeInChars(Ctx.getUIntPtrType()) || 1594 Ctx.getDeclAlign(D) > Ctx.getTypeAlignInChars(Ctx.getUIntPtrType()))) { 1595 IsByRef = true; 1596 } 1597 1598 return IsByRef; 1599 } 1600 1601 unsigned Sema::getOpenMPNestingLevel() const { 1602 assert(getLangOpts().OpenMP); 1603 return DSAStack->getNestingLevel(); 1604 } 1605 1606 bool Sema::isInOpenMPTargetExecutionDirective() const { 1607 return (isOpenMPTargetExecutionDirective(DSAStack->getCurrentDirective()) && 1608 !DSAStack->isClauseParsingMode()) || 1609 DSAStack->hasDirective( 1610 [](OpenMPDirectiveKind K, const DeclarationNameInfo &, 1611 SourceLocation) -> bool { 1612 return isOpenMPTargetExecutionDirective(K); 1613 }, 1614 false); 1615 } 1616 1617 VarDecl *Sema::isOpenMPCapturedDecl(ValueDecl *D) { 1618 assert(LangOpts.OpenMP && "OpenMP is not allowed"); 1619 D = getCanonicalDecl(D); 1620 1621 // If we are attempting to capture a global variable in a directive with 1622 // 'target' we return true so that this global is also mapped to the device. 1623 // 1624 auto *VD = dyn_cast<VarDecl>(D); 1625 if (VD && !VD->hasLocalStorage()) { 1626 if (isInOpenMPDeclareTargetContext() && 1627 (getCurCapturedRegion() || getCurBlock() || getCurLambda())) { 1628 // Try to mark variable as declare target if it is used in capturing 1629 // regions. 1630 if (!OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD)) 1631 checkDeclIsAllowedInOpenMPTarget(nullptr, VD); 1632 return nullptr; 1633 } else if (isInOpenMPTargetExecutionDirective()) { 1634 // If the declaration is enclosed in a 'declare target' directive, 1635 // then it should not be captured. 1636 // 1637 if (OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD)) 1638 return nullptr; 1639 return VD; 1640 } 1641 } 1642 // Capture variables captured by reference in lambdas for target-based 1643 // directives. 1644 if (VD && !DSAStack->isClauseParsingMode()) { 1645 if (const auto *RD = VD->getType() 1646 .getCanonicalType() 1647 .getNonReferenceType() 1648 ->getAsCXXRecordDecl()) { 1649 bool SavedForceCaptureByReferenceInTargetExecutable = 1650 DSAStack->isForceCaptureByReferenceInTargetExecutable(); 1651 DSAStack->setForceCaptureByReferenceInTargetExecutable(/*V=*/true); 1652 if (RD->isLambda()) { 1653 llvm::DenseMap<const VarDecl *, FieldDecl *> Captures; 1654 FieldDecl *ThisCapture; 1655 RD->getCaptureFields(Captures, ThisCapture); 1656 for (const LambdaCapture &LC : RD->captures()) { 1657 if (LC.getCaptureKind() == LCK_ByRef) { 1658 VarDecl *VD = LC.getCapturedVar(); 1659 DeclContext *VDC = VD->getDeclContext(); 1660 if (!VDC->Encloses(CurContext)) 1661 continue; 1662 DSAStackTy::DSAVarData DVarPrivate = 1663 DSAStack->getTopDSA(VD, /*FromParent=*/false); 1664 // Do not capture already captured variables. 1665 if (!OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD) && 1666 DVarPrivate.CKind == OMPC_unknown && 1667 !DSAStack->checkMappableExprComponentListsForDecl( 1668 D, /*CurrentRegionOnly=*/true, 1669 [](OMPClauseMappableExprCommon:: 1670 MappableExprComponentListRef, 1671 OpenMPClauseKind) { return true; })) 1672 MarkVariableReferenced(LC.getLocation(), LC.getCapturedVar()); 1673 } else if (LC.getCaptureKind() == LCK_This) { 1674 QualType ThisTy = getCurrentThisType(); 1675 if (!ThisTy.isNull() && 1676 Context.typesAreCompatible(ThisTy, ThisCapture->getType())) 1677 CheckCXXThisCapture(LC.getLocation()); 1678 } 1679 } 1680 } 1681 DSAStack->setForceCaptureByReferenceInTargetExecutable( 1682 SavedForceCaptureByReferenceInTargetExecutable); 1683 } 1684 } 1685 1686 if (DSAStack->getCurrentDirective() != OMPD_unknown && 1687 (!DSAStack->isClauseParsingMode() || 1688 DSAStack->getParentDirective() != OMPD_unknown)) { 1689 auto &&Info = DSAStack->isLoopControlVariable(D); 1690 if (Info.first || 1691 (VD && VD->hasLocalStorage() && 1692 isImplicitOrExplicitTaskingRegion(DSAStack->getCurrentDirective())) || 1693 (VD && DSAStack->isForceVarCapturing())) 1694 return VD ? VD : Info.second; 1695 DSAStackTy::DSAVarData DVarPrivate = 1696 DSAStack->getTopDSA(D, DSAStack->isClauseParsingMode()); 1697 if (DVarPrivate.CKind != OMPC_unknown && isOpenMPPrivate(DVarPrivate.CKind)) 1698 return VD ? VD : cast<VarDecl>(DVarPrivate.PrivateCopy->getDecl()); 1699 DVarPrivate = DSAStack->hasDSA(D, isOpenMPPrivate, 1700 [](OpenMPDirectiveKind) { return true; }, 1701 DSAStack->isClauseParsingMode()); 1702 if (DVarPrivate.CKind != OMPC_unknown) 1703 return VD ? VD : cast<VarDecl>(DVarPrivate.PrivateCopy->getDecl()); 1704 } 1705 return nullptr; 1706 } 1707 1708 void Sema::adjustOpenMPTargetScopeIndex(unsigned &FunctionScopesIndex, 1709 unsigned Level) const { 1710 SmallVector<OpenMPDirectiveKind, 4> Regions; 1711 getOpenMPCaptureRegions(Regions, DSAStack->getDirective(Level)); 1712 FunctionScopesIndex -= Regions.size(); 1713 } 1714 1715 void Sema::startOpenMPLoop() { 1716 assert(LangOpts.OpenMP && "OpenMP must be enabled."); 1717 if (isOpenMPLoopDirective(DSAStack->getCurrentDirective())) 1718 DSAStack->loopInit(); 1719 } 1720 1721 bool Sema::isOpenMPPrivateDecl(const ValueDecl *D, unsigned Level) const { 1722 assert(LangOpts.OpenMP && "OpenMP is not allowed"); 1723 if (isOpenMPLoopDirective(DSAStack->getCurrentDirective())) { 1724 if (DSAStack->getAssociatedLoops() > 0 && 1725 !DSAStack->isLoopStarted()) { 1726 DSAStack->resetPossibleLoopCounter(D); 1727 DSAStack->loopStart(); 1728 return true; 1729 } 1730 if ((DSAStack->getPossiblyLoopCunter() == D->getCanonicalDecl() || 1731 DSAStack->isLoopControlVariable(D).first) && 1732 !DSAStack->hasExplicitDSA( 1733 D, [](OpenMPClauseKind K) { return K != OMPC_private; }, Level) && 1734 !isOpenMPSimdDirective(DSAStack->getCurrentDirective())) 1735 return true; 1736 } 1737 return DSAStack->hasExplicitDSA( 1738 D, [](OpenMPClauseKind K) { return K == OMPC_private; }, Level) || 1739 (DSAStack->isClauseParsingMode() && 1740 DSAStack->getClauseParsingMode() == OMPC_private) || 1741 // Consider taskgroup reduction descriptor variable a private to avoid 1742 // possible capture in the region. 1743 (DSAStack->hasExplicitDirective( 1744 [](OpenMPDirectiveKind K) { return K == OMPD_taskgroup; }, 1745 Level) && 1746 DSAStack->isTaskgroupReductionRef(D, Level)); 1747 } 1748 1749 void Sema::setOpenMPCaptureKind(FieldDecl *FD, const ValueDecl *D, 1750 unsigned Level) { 1751 assert(LangOpts.OpenMP && "OpenMP is not allowed"); 1752 D = getCanonicalDecl(D); 1753 OpenMPClauseKind OMPC = OMPC_unknown; 1754 for (unsigned I = DSAStack->getNestingLevel() + 1; I > Level; --I) { 1755 const unsigned NewLevel = I - 1; 1756 if (DSAStack->hasExplicitDSA(D, 1757 [&OMPC](const OpenMPClauseKind K) { 1758 if (isOpenMPPrivate(K)) { 1759 OMPC = K; 1760 return true; 1761 } 1762 return false; 1763 }, 1764 NewLevel)) 1765 break; 1766 if (DSAStack->checkMappableExprComponentListsForDeclAtLevel( 1767 D, NewLevel, 1768 [](OMPClauseMappableExprCommon::MappableExprComponentListRef, 1769 OpenMPClauseKind) { return true; })) { 1770 OMPC = OMPC_map; 1771 break; 1772 } 1773 if (DSAStack->hasExplicitDirective(isOpenMPTargetExecutionDirective, 1774 NewLevel)) { 1775 OMPC = OMPC_map; 1776 if (D->getType()->isScalarType() && 1777 DSAStack->getDefaultDMAAtLevel(NewLevel) != 1778 DefaultMapAttributes::DMA_tofrom_scalar) 1779 OMPC = OMPC_firstprivate; 1780 break; 1781 } 1782 } 1783 if (OMPC != OMPC_unknown) 1784 FD->addAttr(OMPCaptureKindAttr::CreateImplicit(Context, OMPC)); 1785 } 1786 1787 bool Sema::isOpenMPTargetCapturedDecl(const ValueDecl *D, 1788 unsigned Level) const { 1789 assert(LangOpts.OpenMP && "OpenMP is not allowed"); 1790 // Return true if the current level is no longer enclosed in a target region. 1791 1792 const auto *VD = dyn_cast<VarDecl>(D); 1793 return VD && !VD->hasLocalStorage() && 1794 DSAStack->hasExplicitDirective(isOpenMPTargetExecutionDirective, 1795 Level); 1796 } 1797 1798 void Sema::DestroyDataSharingAttributesStack() { delete DSAStack; } 1799 1800 void Sema::StartOpenMPDSABlock(OpenMPDirectiveKind DKind, 1801 const DeclarationNameInfo &DirName, 1802 Scope *CurScope, SourceLocation Loc) { 1803 DSAStack->push(DKind, DirName, CurScope, Loc); 1804 PushExpressionEvaluationContext( 1805 ExpressionEvaluationContext::PotentiallyEvaluated); 1806 } 1807 1808 void Sema::StartOpenMPClause(OpenMPClauseKind K) { 1809 DSAStack->setClauseParsingMode(K); 1810 } 1811 1812 void Sema::EndOpenMPClause() { 1813 DSAStack->setClauseParsingMode(/*K=*/OMPC_unknown); 1814 } 1815 1816 void Sema::EndOpenMPDSABlock(Stmt *CurDirective) { 1817 // OpenMP [2.14.3.5, Restrictions, C/C++, p.1] 1818 // A variable of class type (or array thereof) that appears in a lastprivate 1819 // clause requires an accessible, unambiguous default constructor for the 1820 // class type, unless the list item is also specified in a firstprivate 1821 // clause. 1822 if (const auto *D = dyn_cast_or_null<OMPExecutableDirective>(CurDirective)) { 1823 for (OMPClause *C : D->clauses()) { 1824 if (auto *Clause = dyn_cast<OMPLastprivateClause>(C)) { 1825 SmallVector<Expr *, 8> PrivateCopies; 1826 for (Expr *DE : Clause->varlists()) { 1827 if (DE->isValueDependent() || DE->isTypeDependent()) { 1828 PrivateCopies.push_back(nullptr); 1829 continue; 1830 } 1831 auto *DRE = cast<DeclRefExpr>(DE->IgnoreParens()); 1832 auto *VD = cast<VarDecl>(DRE->getDecl()); 1833 QualType Type = VD->getType().getNonReferenceType(); 1834 const DSAStackTy::DSAVarData DVar = 1835 DSAStack->getTopDSA(VD, /*FromParent=*/false); 1836 if (DVar.CKind == OMPC_lastprivate) { 1837 // Generate helper private variable and initialize it with the 1838 // default value. The address of the original variable is replaced 1839 // by the address of the new private variable in CodeGen. This new 1840 // variable is not added to IdResolver, so the code in the OpenMP 1841 // region uses original variable for proper diagnostics. 1842 VarDecl *VDPrivate = buildVarDecl( 1843 *this, DE->getExprLoc(), Type.getUnqualifiedType(), 1844 VD->getName(), VD->hasAttrs() ? &VD->getAttrs() : nullptr, DRE); 1845 ActOnUninitializedDecl(VDPrivate); 1846 if (VDPrivate->isInvalidDecl()) 1847 continue; 1848 PrivateCopies.push_back(buildDeclRefExpr( 1849 *this, VDPrivate, DE->getType(), DE->getExprLoc())); 1850 } else { 1851 // The variable is also a firstprivate, so initialization sequence 1852 // for private copy is generated already. 1853 PrivateCopies.push_back(nullptr); 1854 } 1855 } 1856 // Set initializers to private copies if no errors were found. 1857 if (PrivateCopies.size() == Clause->varlist_size()) 1858 Clause->setPrivateCopies(PrivateCopies); 1859 } 1860 } 1861 } 1862 1863 DSAStack->pop(); 1864 DiscardCleanupsInEvaluationContext(); 1865 PopExpressionEvaluationContext(); 1866 } 1867 1868 static bool FinishOpenMPLinearClause(OMPLinearClause &Clause, DeclRefExpr *IV, 1869 Expr *NumIterations, Sema &SemaRef, 1870 Scope *S, DSAStackTy *Stack); 1871 1872 namespace { 1873 1874 class VarDeclFilterCCC final : public CorrectionCandidateCallback { 1875 private: 1876 Sema &SemaRef; 1877 1878 public: 1879 explicit VarDeclFilterCCC(Sema &S) : SemaRef(S) {} 1880 bool ValidateCandidate(const TypoCorrection &Candidate) override { 1881 NamedDecl *ND = Candidate.getCorrectionDecl(); 1882 if (const auto *VD = dyn_cast_or_null<VarDecl>(ND)) { 1883 return VD->hasGlobalStorage() && 1884 SemaRef.isDeclInScope(ND, SemaRef.getCurLexicalContext(), 1885 SemaRef.getCurScope()); 1886 } 1887 return false; 1888 } 1889 }; 1890 1891 class VarOrFuncDeclFilterCCC final : public CorrectionCandidateCallback { 1892 private: 1893 Sema &SemaRef; 1894 1895 public: 1896 explicit VarOrFuncDeclFilterCCC(Sema &S) : SemaRef(S) {} 1897 bool ValidateCandidate(const TypoCorrection &Candidate) override { 1898 NamedDecl *ND = Candidate.getCorrectionDecl(); 1899 if (ND && (isa<VarDecl>(ND) || isa<FunctionDecl>(ND))) { 1900 return SemaRef.isDeclInScope(ND, SemaRef.getCurLexicalContext(), 1901 SemaRef.getCurScope()); 1902 } 1903 return false; 1904 } 1905 }; 1906 1907 } // namespace 1908 1909 ExprResult Sema::ActOnOpenMPIdExpression(Scope *CurScope, 1910 CXXScopeSpec &ScopeSpec, 1911 const DeclarationNameInfo &Id) { 1912 LookupResult Lookup(*this, Id, LookupOrdinaryName); 1913 LookupParsedName(Lookup, CurScope, &ScopeSpec, true); 1914 1915 if (Lookup.isAmbiguous()) 1916 return ExprError(); 1917 1918 VarDecl *VD; 1919 if (!Lookup.isSingleResult()) { 1920 if (TypoCorrection Corrected = CorrectTypo( 1921 Id, LookupOrdinaryName, CurScope, nullptr, 1922 llvm::make_unique<VarDeclFilterCCC>(*this), CTK_ErrorRecovery)) { 1923 diagnoseTypo(Corrected, 1924 PDiag(Lookup.empty() 1925 ? diag::err_undeclared_var_use_suggest 1926 : diag::err_omp_expected_var_arg_suggest) 1927 << Id.getName()); 1928 VD = Corrected.getCorrectionDeclAs<VarDecl>(); 1929 } else { 1930 Diag(Id.getLoc(), Lookup.empty() ? diag::err_undeclared_var_use 1931 : diag::err_omp_expected_var_arg) 1932 << Id.getName(); 1933 return ExprError(); 1934 } 1935 } else if (!(VD = Lookup.getAsSingle<VarDecl>())) { 1936 Diag(Id.getLoc(), diag::err_omp_expected_var_arg) << Id.getName(); 1937 Diag(Lookup.getFoundDecl()->getLocation(), diag::note_declared_at); 1938 return ExprError(); 1939 } 1940 Lookup.suppressDiagnostics(); 1941 1942 // OpenMP [2.9.2, Syntax, C/C++] 1943 // Variables must be file-scope, namespace-scope, or static block-scope. 1944 if (!VD->hasGlobalStorage()) { 1945 Diag(Id.getLoc(), diag::err_omp_global_var_arg) 1946 << getOpenMPDirectiveName(OMPD_threadprivate) << !VD->isStaticLocal(); 1947 bool IsDecl = 1948 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly; 1949 Diag(VD->getLocation(), 1950 IsDecl ? diag::note_previous_decl : diag::note_defined_here) 1951 << VD; 1952 return ExprError(); 1953 } 1954 1955 VarDecl *CanonicalVD = VD->getCanonicalDecl(); 1956 NamedDecl *ND = CanonicalVD; 1957 // OpenMP [2.9.2, Restrictions, C/C++, p.2] 1958 // A threadprivate directive for file-scope variables must appear outside 1959 // any definition or declaration. 1960 if (CanonicalVD->getDeclContext()->isTranslationUnit() && 1961 !getCurLexicalContext()->isTranslationUnit()) { 1962 Diag(Id.getLoc(), diag::err_omp_var_scope) 1963 << getOpenMPDirectiveName(OMPD_threadprivate) << VD; 1964 bool IsDecl = 1965 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly; 1966 Diag(VD->getLocation(), 1967 IsDecl ? diag::note_previous_decl : diag::note_defined_here) 1968 << VD; 1969 return ExprError(); 1970 } 1971 // OpenMP [2.9.2, Restrictions, C/C++, p.3] 1972 // A threadprivate directive for static class member variables must appear 1973 // in the class definition, in the same scope in which the member 1974 // variables are declared. 1975 if (CanonicalVD->isStaticDataMember() && 1976 !CanonicalVD->getDeclContext()->Equals(getCurLexicalContext())) { 1977 Diag(Id.getLoc(), diag::err_omp_var_scope) 1978 << getOpenMPDirectiveName(OMPD_threadprivate) << VD; 1979 bool IsDecl = 1980 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly; 1981 Diag(VD->getLocation(), 1982 IsDecl ? diag::note_previous_decl : diag::note_defined_here) 1983 << VD; 1984 return ExprError(); 1985 } 1986 // OpenMP [2.9.2, Restrictions, C/C++, p.4] 1987 // A threadprivate directive for namespace-scope variables must appear 1988 // outside any definition or declaration other than the namespace 1989 // definition itself. 1990 if (CanonicalVD->getDeclContext()->isNamespace() && 1991 (!getCurLexicalContext()->isFileContext() || 1992 !getCurLexicalContext()->Encloses(CanonicalVD->getDeclContext()))) { 1993 Diag(Id.getLoc(), diag::err_omp_var_scope) 1994 << getOpenMPDirectiveName(OMPD_threadprivate) << VD; 1995 bool IsDecl = 1996 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly; 1997 Diag(VD->getLocation(), 1998 IsDecl ? diag::note_previous_decl : diag::note_defined_here) 1999 << VD; 2000 return ExprError(); 2001 } 2002 // OpenMP [2.9.2, Restrictions, C/C++, p.6] 2003 // A threadprivate directive for static block-scope variables must appear 2004 // in the scope of the variable and not in a nested scope. 2005 if (CanonicalVD->isStaticLocal() && CurScope && 2006 !isDeclInScope(ND, getCurLexicalContext(), CurScope)) { 2007 Diag(Id.getLoc(), diag::err_omp_var_scope) 2008 << getOpenMPDirectiveName(OMPD_threadprivate) << VD; 2009 bool IsDecl = 2010 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly; 2011 Diag(VD->getLocation(), 2012 IsDecl ? diag::note_previous_decl : diag::note_defined_here) 2013 << VD; 2014 return ExprError(); 2015 } 2016 2017 // OpenMP [2.9.2, Restrictions, C/C++, p.2-6] 2018 // A threadprivate directive must lexically precede all references to any 2019 // of the variables in its list. 2020 if (VD->isUsed() && !DSAStack->isThreadPrivate(VD)) { 2021 Diag(Id.getLoc(), diag::err_omp_var_used) 2022 << getOpenMPDirectiveName(OMPD_threadprivate) << VD; 2023 return ExprError(); 2024 } 2025 2026 QualType ExprType = VD->getType().getNonReferenceType(); 2027 return DeclRefExpr::Create(Context, NestedNameSpecifierLoc(), 2028 SourceLocation(), VD, 2029 /*RefersToEnclosingVariableOrCapture=*/false, 2030 Id.getLoc(), ExprType, VK_LValue); 2031 } 2032 2033 Sema::DeclGroupPtrTy 2034 Sema::ActOnOpenMPThreadprivateDirective(SourceLocation Loc, 2035 ArrayRef<Expr *> VarList) { 2036 if (OMPThreadPrivateDecl *D = CheckOMPThreadPrivateDecl(Loc, VarList)) { 2037 CurContext->addDecl(D); 2038 return DeclGroupPtrTy::make(DeclGroupRef(D)); 2039 } 2040 return nullptr; 2041 } 2042 2043 namespace { 2044 class LocalVarRefChecker final 2045 : public ConstStmtVisitor<LocalVarRefChecker, bool> { 2046 Sema &SemaRef; 2047 2048 public: 2049 bool VisitDeclRefExpr(const DeclRefExpr *E) { 2050 if (const auto *VD = dyn_cast<VarDecl>(E->getDecl())) { 2051 if (VD->hasLocalStorage()) { 2052 SemaRef.Diag(E->getBeginLoc(), 2053 diag::err_omp_local_var_in_threadprivate_init) 2054 << E->getSourceRange(); 2055 SemaRef.Diag(VD->getLocation(), diag::note_defined_here) 2056 << VD << VD->getSourceRange(); 2057 return true; 2058 } 2059 } 2060 return false; 2061 } 2062 bool VisitStmt(const Stmt *S) { 2063 for (const Stmt *Child : S->children()) { 2064 if (Child && Visit(Child)) 2065 return true; 2066 } 2067 return false; 2068 } 2069 explicit LocalVarRefChecker(Sema &SemaRef) : SemaRef(SemaRef) {} 2070 }; 2071 } // namespace 2072 2073 OMPThreadPrivateDecl * 2074 Sema::CheckOMPThreadPrivateDecl(SourceLocation Loc, ArrayRef<Expr *> VarList) { 2075 SmallVector<Expr *, 8> Vars; 2076 for (Expr *RefExpr : VarList) { 2077 auto *DE = cast<DeclRefExpr>(RefExpr); 2078 auto *VD = cast<VarDecl>(DE->getDecl()); 2079 SourceLocation ILoc = DE->getExprLoc(); 2080 2081 // Mark variable as used. 2082 VD->setReferenced(); 2083 VD->markUsed(Context); 2084 2085 QualType QType = VD->getType(); 2086 if (QType->isDependentType() || QType->isInstantiationDependentType()) { 2087 // It will be analyzed later. 2088 Vars.push_back(DE); 2089 continue; 2090 } 2091 2092 // OpenMP [2.9.2, Restrictions, C/C++, p.10] 2093 // A threadprivate variable must not have an incomplete type. 2094 if (RequireCompleteType(ILoc, VD->getType(), 2095 diag::err_omp_threadprivate_incomplete_type)) { 2096 continue; 2097 } 2098 2099 // OpenMP [2.9.2, Restrictions, C/C++, p.10] 2100 // A threadprivate variable must not have a reference type. 2101 if (VD->getType()->isReferenceType()) { 2102 Diag(ILoc, diag::err_omp_ref_type_arg) 2103 << getOpenMPDirectiveName(OMPD_threadprivate) << VD->getType(); 2104 bool IsDecl = 2105 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly; 2106 Diag(VD->getLocation(), 2107 IsDecl ? diag::note_previous_decl : diag::note_defined_here) 2108 << VD; 2109 continue; 2110 } 2111 2112 // Check if this is a TLS variable. If TLS is not being supported, produce 2113 // the corresponding diagnostic. 2114 if ((VD->getTLSKind() != VarDecl::TLS_None && 2115 !(VD->hasAttr<OMPThreadPrivateDeclAttr>() && 2116 getLangOpts().OpenMPUseTLS && 2117 getASTContext().getTargetInfo().isTLSSupported())) || 2118 (VD->getStorageClass() == SC_Register && VD->hasAttr<AsmLabelAttr>() && 2119 !VD->isLocalVarDecl())) { 2120 Diag(ILoc, diag::err_omp_var_thread_local) 2121 << VD << ((VD->getTLSKind() != VarDecl::TLS_None) ? 0 : 1); 2122 bool IsDecl = 2123 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly; 2124 Diag(VD->getLocation(), 2125 IsDecl ? diag::note_previous_decl : diag::note_defined_here) 2126 << VD; 2127 continue; 2128 } 2129 2130 // Check if initial value of threadprivate variable reference variable with 2131 // local storage (it is not supported by runtime). 2132 if (const Expr *Init = VD->getAnyInitializer()) { 2133 LocalVarRefChecker Checker(*this); 2134 if (Checker.Visit(Init)) 2135 continue; 2136 } 2137 2138 Vars.push_back(RefExpr); 2139 DSAStack->addDSA(VD, DE, OMPC_threadprivate); 2140 VD->addAttr(OMPThreadPrivateDeclAttr::CreateImplicit( 2141 Context, SourceRange(Loc, Loc))); 2142 if (ASTMutationListener *ML = Context.getASTMutationListener()) 2143 ML->DeclarationMarkedOpenMPThreadPrivate(VD); 2144 } 2145 OMPThreadPrivateDecl *D = nullptr; 2146 if (!Vars.empty()) { 2147 D = OMPThreadPrivateDecl::Create(Context, getCurLexicalContext(), Loc, 2148 Vars); 2149 D->setAccess(AS_public); 2150 } 2151 return D; 2152 } 2153 2154 Sema::DeclGroupPtrTy 2155 Sema::ActOnOpenMPRequiresDirective(SourceLocation Loc, 2156 ArrayRef<OMPClause *> ClauseList) { 2157 OMPRequiresDecl *D = nullptr; 2158 if (!CurContext->isFileContext()) { 2159 Diag(Loc, diag::err_omp_invalid_scope) << "requires"; 2160 } else { 2161 D = CheckOMPRequiresDecl(Loc, ClauseList); 2162 if (D) { 2163 CurContext->addDecl(D); 2164 DSAStack->addRequiresDecl(D); 2165 } 2166 } 2167 return DeclGroupPtrTy::make(DeclGroupRef(D)); 2168 } 2169 2170 OMPRequiresDecl *Sema::CheckOMPRequiresDecl(SourceLocation Loc, 2171 ArrayRef<OMPClause *> ClauseList) { 2172 if (!DSAStack->hasDuplicateRequiresClause(ClauseList)) 2173 return OMPRequiresDecl::Create(Context, getCurLexicalContext(), Loc, 2174 ClauseList); 2175 return nullptr; 2176 } 2177 2178 static void reportOriginalDsa(Sema &SemaRef, const DSAStackTy *Stack, 2179 const ValueDecl *D, 2180 const DSAStackTy::DSAVarData &DVar, 2181 bool IsLoopIterVar = false) { 2182 if (DVar.RefExpr) { 2183 SemaRef.Diag(DVar.RefExpr->getExprLoc(), diag::note_omp_explicit_dsa) 2184 << getOpenMPClauseName(DVar.CKind); 2185 return; 2186 } 2187 enum { 2188 PDSA_StaticMemberShared, 2189 PDSA_StaticLocalVarShared, 2190 PDSA_LoopIterVarPrivate, 2191 PDSA_LoopIterVarLinear, 2192 PDSA_LoopIterVarLastprivate, 2193 PDSA_ConstVarShared, 2194 PDSA_GlobalVarShared, 2195 PDSA_TaskVarFirstprivate, 2196 PDSA_LocalVarPrivate, 2197 PDSA_Implicit 2198 } Reason = PDSA_Implicit; 2199 bool ReportHint = false; 2200 auto ReportLoc = D->getLocation(); 2201 auto *VD = dyn_cast<VarDecl>(D); 2202 if (IsLoopIterVar) { 2203 if (DVar.CKind == OMPC_private) 2204 Reason = PDSA_LoopIterVarPrivate; 2205 else if (DVar.CKind == OMPC_lastprivate) 2206 Reason = PDSA_LoopIterVarLastprivate; 2207 else 2208 Reason = PDSA_LoopIterVarLinear; 2209 } else if (isOpenMPTaskingDirective(DVar.DKind) && 2210 DVar.CKind == OMPC_firstprivate) { 2211 Reason = PDSA_TaskVarFirstprivate; 2212 ReportLoc = DVar.ImplicitDSALoc; 2213 } else if (VD && VD->isStaticLocal()) 2214 Reason = PDSA_StaticLocalVarShared; 2215 else if (VD && VD->isStaticDataMember()) 2216 Reason = PDSA_StaticMemberShared; 2217 else if (VD && VD->isFileVarDecl()) 2218 Reason = PDSA_GlobalVarShared; 2219 else if (D->getType().isConstant(SemaRef.getASTContext())) 2220 Reason = PDSA_ConstVarShared; 2221 else if (VD && VD->isLocalVarDecl() && DVar.CKind == OMPC_private) { 2222 ReportHint = true; 2223 Reason = PDSA_LocalVarPrivate; 2224 } 2225 if (Reason != PDSA_Implicit) { 2226 SemaRef.Diag(ReportLoc, diag::note_omp_predetermined_dsa) 2227 << Reason << ReportHint 2228 << getOpenMPDirectiveName(Stack->getCurrentDirective()); 2229 } else if (DVar.ImplicitDSALoc.isValid()) { 2230 SemaRef.Diag(DVar.ImplicitDSALoc, diag::note_omp_implicit_dsa) 2231 << getOpenMPClauseName(DVar.CKind); 2232 } 2233 } 2234 2235 namespace { 2236 class DSAAttrChecker final : public StmtVisitor<DSAAttrChecker, void> { 2237 DSAStackTy *Stack; 2238 Sema &SemaRef; 2239 bool ErrorFound = false; 2240 CapturedStmt *CS = nullptr; 2241 llvm::SmallVector<Expr *, 4> ImplicitFirstprivate; 2242 llvm::SmallVector<Expr *, 4> ImplicitMap; 2243 Sema::VarsWithInheritedDSAType VarsWithInheritedDSA; 2244 llvm::SmallDenseSet<const ValueDecl *, 4> ImplicitDeclarations; 2245 2246 void VisitSubCaptures(OMPExecutableDirective *S) { 2247 // Check implicitly captured variables. 2248 if (!S->hasAssociatedStmt() || !S->getAssociatedStmt()) 2249 return; 2250 for (const CapturedStmt::Capture &Cap : 2251 S->getInnermostCapturedStmt()->captures()) { 2252 if (!Cap.capturesVariable()) 2253 continue; 2254 VarDecl *VD = Cap.getCapturedVar(); 2255 // Do not try to map the variable if it or its sub-component was mapped 2256 // already. 2257 if (isOpenMPTargetExecutionDirective(Stack->getCurrentDirective()) && 2258 Stack->checkMappableExprComponentListsForDecl( 2259 VD, /*CurrentRegionOnly=*/true, 2260 [](OMPClauseMappableExprCommon::MappableExprComponentListRef, 2261 OpenMPClauseKind) { return true; })) 2262 continue; 2263 DeclRefExpr *DRE = buildDeclRefExpr( 2264 SemaRef, VD, VD->getType().getNonLValueExprType(SemaRef.Context), 2265 Cap.getLocation(), /*RefersToCapture=*/true); 2266 Visit(DRE); 2267 } 2268 } 2269 2270 public: 2271 void VisitDeclRefExpr(DeclRefExpr *E) { 2272 if (E->isTypeDependent() || E->isValueDependent() || 2273 E->containsUnexpandedParameterPack() || E->isInstantiationDependent()) 2274 return; 2275 if (auto *VD = dyn_cast<VarDecl>(E->getDecl())) { 2276 VD = VD->getCanonicalDecl(); 2277 // Skip internally declared variables. 2278 if (VD->hasLocalStorage() && !CS->capturesVariable(VD)) 2279 return; 2280 2281 DSAStackTy::DSAVarData DVar = Stack->getTopDSA(VD, /*FromParent=*/false); 2282 // Check if the variable has explicit DSA set and stop analysis if it so. 2283 if (DVar.RefExpr || !ImplicitDeclarations.insert(VD).second) 2284 return; 2285 2286 // Skip internally declared static variables. 2287 llvm::Optional<OMPDeclareTargetDeclAttr::MapTypeTy> Res = 2288 OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD); 2289 if (VD->hasGlobalStorage() && !CS->capturesVariable(VD) && 2290 (!Res || *Res != OMPDeclareTargetDeclAttr::MT_Link)) 2291 return; 2292 2293 SourceLocation ELoc = E->getExprLoc(); 2294 OpenMPDirectiveKind DKind = Stack->getCurrentDirective(); 2295 // The default(none) clause requires that each variable that is referenced 2296 // in the construct, and does not have a predetermined data-sharing 2297 // attribute, must have its data-sharing attribute explicitly determined 2298 // by being listed in a data-sharing attribute clause. 2299 if (DVar.CKind == OMPC_unknown && Stack->getDefaultDSA() == DSA_none && 2300 isImplicitOrExplicitTaskingRegion(DKind) && 2301 VarsWithInheritedDSA.count(VD) == 0) { 2302 VarsWithInheritedDSA[VD] = E; 2303 return; 2304 } 2305 2306 if (isOpenMPTargetExecutionDirective(DKind) && 2307 !Stack->isLoopControlVariable(VD).first) { 2308 if (!Stack->checkMappableExprComponentListsForDecl( 2309 VD, /*CurrentRegionOnly=*/true, 2310 [](OMPClauseMappableExprCommon::MappableExprComponentListRef 2311 StackComponents, 2312 OpenMPClauseKind) { 2313 // Variable is used if it has been marked as an array, array 2314 // section or the variable iself. 2315 return StackComponents.size() == 1 || 2316 std::all_of( 2317 std::next(StackComponents.rbegin()), 2318 StackComponents.rend(), 2319 [](const OMPClauseMappableExprCommon:: 2320 MappableComponent &MC) { 2321 return MC.getAssociatedDeclaration() == 2322 nullptr && 2323 (isa<OMPArraySectionExpr>( 2324 MC.getAssociatedExpression()) || 2325 isa<ArraySubscriptExpr>( 2326 MC.getAssociatedExpression())); 2327 }); 2328 })) { 2329 bool IsFirstprivate = false; 2330 // By default lambdas are captured as firstprivates. 2331 if (const auto *RD = 2332 VD->getType().getNonReferenceType()->getAsCXXRecordDecl()) 2333 IsFirstprivate = RD->isLambda(); 2334 IsFirstprivate = 2335 IsFirstprivate || 2336 (VD->getType().getNonReferenceType()->isScalarType() && 2337 Stack->getDefaultDMA() != DMA_tofrom_scalar && !Res); 2338 if (IsFirstprivate) 2339 ImplicitFirstprivate.emplace_back(E); 2340 else 2341 ImplicitMap.emplace_back(E); 2342 return; 2343 } 2344 } 2345 2346 // OpenMP [2.9.3.6, Restrictions, p.2] 2347 // A list item that appears in a reduction clause of the innermost 2348 // enclosing worksharing or parallel construct may not be accessed in an 2349 // explicit task. 2350 DVar = Stack->hasInnermostDSA( 2351 VD, [](OpenMPClauseKind C) { return C == OMPC_reduction; }, 2352 [](OpenMPDirectiveKind K) { 2353 return isOpenMPParallelDirective(K) || 2354 isOpenMPWorksharingDirective(K) || isOpenMPTeamsDirective(K); 2355 }, 2356 /*FromParent=*/true); 2357 if (isOpenMPTaskingDirective(DKind) && DVar.CKind == OMPC_reduction) { 2358 ErrorFound = true; 2359 SemaRef.Diag(ELoc, diag::err_omp_reduction_in_task); 2360 reportOriginalDsa(SemaRef, Stack, VD, DVar); 2361 return; 2362 } 2363 2364 // Define implicit data-sharing attributes for task. 2365 DVar = Stack->getImplicitDSA(VD, /*FromParent=*/false); 2366 if (isOpenMPTaskingDirective(DKind) && DVar.CKind != OMPC_shared && 2367 !Stack->isLoopControlVariable(VD).first) 2368 ImplicitFirstprivate.push_back(E); 2369 } 2370 } 2371 void VisitMemberExpr(MemberExpr *E) { 2372 if (E->isTypeDependent() || E->isValueDependent() || 2373 E->containsUnexpandedParameterPack() || E->isInstantiationDependent()) 2374 return; 2375 auto *FD = dyn_cast<FieldDecl>(E->getMemberDecl()); 2376 OpenMPDirectiveKind DKind = Stack->getCurrentDirective(); 2377 if (auto *TE = dyn_cast<CXXThisExpr>(E->getBase()->IgnoreParens())) { 2378 if (!FD) 2379 return; 2380 DSAStackTy::DSAVarData DVar = Stack->getTopDSA(FD, /*FromParent=*/false); 2381 // Check if the variable has explicit DSA set and stop analysis if it 2382 // so. 2383 if (DVar.RefExpr || !ImplicitDeclarations.insert(FD).second) 2384 return; 2385 2386 if (isOpenMPTargetExecutionDirective(DKind) && 2387 !Stack->isLoopControlVariable(FD).first && 2388 !Stack->checkMappableExprComponentListsForDecl( 2389 FD, /*CurrentRegionOnly=*/true, 2390 [](OMPClauseMappableExprCommon::MappableExprComponentListRef 2391 StackComponents, 2392 OpenMPClauseKind) { 2393 return isa<CXXThisExpr>( 2394 cast<MemberExpr>( 2395 StackComponents.back().getAssociatedExpression()) 2396 ->getBase() 2397 ->IgnoreParens()); 2398 })) { 2399 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C/C++, p.3] 2400 // A bit-field cannot appear in a map clause. 2401 // 2402 if (FD->isBitField()) 2403 return; 2404 2405 // Check to see if the member expression is referencing a class that 2406 // has already been explicitly mapped 2407 if (Stack->isClassPreviouslyMapped(TE->getType())) 2408 return; 2409 2410 ImplicitMap.emplace_back(E); 2411 return; 2412 } 2413 2414 SourceLocation ELoc = E->getExprLoc(); 2415 // OpenMP [2.9.3.6, Restrictions, p.2] 2416 // A list item that appears in a reduction clause of the innermost 2417 // enclosing worksharing or parallel construct may not be accessed in 2418 // an explicit task. 2419 DVar = Stack->hasInnermostDSA( 2420 FD, [](OpenMPClauseKind C) { return C == OMPC_reduction; }, 2421 [](OpenMPDirectiveKind K) { 2422 return isOpenMPParallelDirective(K) || 2423 isOpenMPWorksharingDirective(K) || isOpenMPTeamsDirective(K); 2424 }, 2425 /*FromParent=*/true); 2426 if (isOpenMPTaskingDirective(DKind) && DVar.CKind == OMPC_reduction) { 2427 ErrorFound = true; 2428 SemaRef.Diag(ELoc, diag::err_omp_reduction_in_task); 2429 reportOriginalDsa(SemaRef, Stack, FD, DVar); 2430 return; 2431 } 2432 2433 // Define implicit data-sharing attributes for task. 2434 DVar = Stack->getImplicitDSA(FD, /*FromParent=*/false); 2435 if (isOpenMPTaskingDirective(DKind) && DVar.CKind != OMPC_shared && 2436 !Stack->isLoopControlVariable(FD).first) { 2437 // Check if there is a captured expression for the current field in the 2438 // region. Do not mark it as firstprivate unless there is no captured 2439 // expression. 2440 // TODO: try to make it firstprivate. 2441 if (DVar.CKind != OMPC_unknown) 2442 ImplicitFirstprivate.push_back(E); 2443 } 2444 return; 2445 } 2446 if (isOpenMPTargetExecutionDirective(DKind)) { 2447 OMPClauseMappableExprCommon::MappableExprComponentList CurComponents; 2448 if (!checkMapClauseExpressionBase(SemaRef, E, CurComponents, OMPC_map, 2449 /*NoDiagnose=*/true)) 2450 return; 2451 const auto *VD = cast<ValueDecl>( 2452 CurComponents.back().getAssociatedDeclaration()->getCanonicalDecl()); 2453 if (!Stack->checkMappableExprComponentListsForDecl( 2454 VD, /*CurrentRegionOnly=*/true, 2455 [&CurComponents]( 2456 OMPClauseMappableExprCommon::MappableExprComponentListRef 2457 StackComponents, 2458 OpenMPClauseKind) { 2459 auto CCI = CurComponents.rbegin(); 2460 auto CCE = CurComponents.rend(); 2461 for (const auto &SC : llvm::reverse(StackComponents)) { 2462 // Do both expressions have the same kind? 2463 if (CCI->getAssociatedExpression()->getStmtClass() != 2464 SC.getAssociatedExpression()->getStmtClass()) 2465 if (!(isa<OMPArraySectionExpr>( 2466 SC.getAssociatedExpression()) && 2467 isa<ArraySubscriptExpr>( 2468 CCI->getAssociatedExpression()))) 2469 return false; 2470 2471 const Decl *CCD = CCI->getAssociatedDeclaration(); 2472 const Decl *SCD = SC.getAssociatedDeclaration(); 2473 CCD = CCD ? CCD->getCanonicalDecl() : nullptr; 2474 SCD = SCD ? SCD->getCanonicalDecl() : nullptr; 2475 if (SCD != CCD) 2476 return false; 2477 std::advance(CCI, 1); 2478 if (CCI == CCE) 2479 break; 2480 } 2481 return true; 2482 })) { 2483 Visit(E->getBase()); 2484 } 2485 } else { 2486 Visit(E->getBase()); 2487 } 2488 } 2489 void VisitOMPExecutableDirective(OMPExecutableDirective *S) { 2490 for (OMPClause *C : S->clauses()) { 2491 // Skip analysis of arguments of implicitly defined firstprivate clause 2492 // for task|target directives. 2493 // Skip analysis of arguments of implicitly defined map clause for target 2494 // directives. 2495 if (C && !((isa<OMPFirstprivateClause>(C) || isa<OMPMapClause>(C)) && 2496 C->isImplicit())) { 2497 for (Stmt *CC : C->children()) { 2498 if (CC) 2499 Visit(CC); 2500 } 2501 } 2502 } 2503 // Check implicitly captured variables. 2504 VisitSubCaptures(S); 2505 } 2506 void VisitStmt(Stmt *S) { 2507 for (Stmt *C : S->children()) { 2508 if (C) { 2509 // Check implicitly captured variables in the task-based directives to 2510 // check if they must be firstprivatized. 2511 Visit(C); 2512 } 2513 } 2514 } 2515 2516 bool isErrorFound() const { return ErrorFound; } 2517 ArrayRef<Expr *> getImplicitFirstprivate() const { 2518 return ImplicitFirstprivate; 2519 } 2520 ArrayRef<Expr *> getImplicitMap() const { return ImplicitMap; } 2521 const Sema::VarsWithInheritedDSAType &getVarsWithInheritedDSA() const { 2522 return VarsWithInheritedDSA; 2523 } 2524 2525 DSAAttrChecker(DSAStackTy *S, Sema &SemaRef, CapturedStmt *CS) 2526 : Stack(S), SemaRef(SemaRef), ErrorFound(false), CS(CS) {} 2527 }; 2528 } // namespace 2529 2530 void Sema::ActOnOpenMPRegionStart(OpenMPDirectiveKind DKind, Scope *CurScope) { 2531 switch (DKind) { 2532 case OMPD_parallel: 2533 case OMPD_parallel_for: 2534 case OMPD_parallel_for_simd: 2535 case OMPD_parallel_sections: 2536 case OMPD_teams: 2537 case OMPD_teams_distribute: 2538 case OMPD_teams_distribute_simd: { 2539 QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1).withConst(); 2540 QualType KmpInt32PtrTy = 2541 Context.getPointerType(KmpInt32Ty).withConst().withRestrict(); 2542 Sema::CapturedParamNameType Params[] = { 2543 std::make_pair(".global_tid.", KmpInt32PtrTy), 2544 std::make_pair(".bound_tid.", KmpInt32PtrTy), 2545 std::make_pair(StringRef(), QualType()) // __context with shared vars 2546 }; 2547 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP, 2548 Params); 2549 break; 2550 } 2551 case OMPD_target_teams: 2552 case OMPD_target_parallel: 2553 case OMPD_target_parallel_for: 2554 case OMPD_target_parallel_for_simd: 2555 case OMPD_target_teams_distribute: 2556 case OMPD_target_teams_distribute_simd: { 2557 QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1).withConst(); 2558 QualType VoidPtrTy = Context.VoidPtrTy.withConst().withRestrict(); 2559 QualType KmpInt32PtrTy = 2560 Context.getPointerType(KmpInt32Ty).withConst().withRestrict(); 2561 QualType Args[] = {VoidPtrTy}; 2562 FunctionProtoType::ExtProtoInfo EPI; 2563 EPI.Variadic = true; 2564 QualType CopyFnType = Context.getFunctionType(Context.VoidTy, Args, EPI); 2565 Sema::CapturedParamNameType Params[] = { 2566 std::make_pair(".global_tid.", KmpInt32Ty), 2567 std::make_pair(".part_id.", KmpInt32PtrTy), 2568 std::make_pair(".privates.", VoidPtrTy), 2569 std::make_pair( 2570 ".copy_fn.", 2571 Context.getPointerType(CopyFnType).withConst().withRestrict()), 2572 std::make_pair(".task_t.", Context.VoidPtrTy.withConst()), 2573 std::make_pair(StringRef(), QualType()) // __context with shared vars 2574 }; 2575 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP, 2576 Params); 2577 // Mark this captured region as inlined, because we don't use outlined 2578 // function directly. 2579 getCurCapturedRegion()->TheCapturedDecl->addAttr( 2580 AlwaysInlineAttr::CreateImplicit( 2581 Context, AlwaysInlineAttr::Keyword_forceinline)); 2582 Sema::CapturedParamNameType ParamsTarget[] = { 2583 std::make_pair(StringRef(), QualType()) // __context with shared vars 2584 }; 2585 // Start a captured region for 'target' with no implicit parameters. 2586 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP, 2587 ParamsTarget); 2588 Sema::CapturedParamNameType ParamsTeamsOrParallel[] = { 2589 std::make_pair(".global_tid.", KmpInt32PtrTy), 2590 std::make_pair(".bound_tid.", KmpInt32PtrTy), 2591 std::make_pair(StringRef(), QualType()) // __context with shared vars 2592 }; 2593 // Start a captured region for 'teams' or 'parallel'. Both regions have 2594 // the same implicit parameters. 2595 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP, 2596 ParamsTeamsOrParallel); 2597 break; 2598 } 2599 case OMPD_target: 2600 case OMPD_target_simd: { 2601 QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1).withConst(); 2602 QualType VoidPtrTy = Context.VoidPtrTy.withConst().withRestrict(); 2603 QualType KmpInt32PtrTy = 2604 Context.getPointerType(KmpInt32Ty).withConst().withRestrict(); 2605 QualType Args[] = {VoidPtrTy}; 2606 FunctionProtoType::ExtProtoInfo EPI; 2607 EPI.Variadic = true; 2608 QualType CopyFnType = Context.getFunctionType(Context.VoidTy, Args, EPI); 2609 Sema::CapturedParamNameType Params[] = { 2610 std::make_pair(".global_tid.", KmpInt32Ty), 2611 std::make_pair(".part_id.", KmpInt32PtrTy), 2612 std::make_pair(".privates.", VoidPtrTy), 2613 std::make_pair( 2614 ".copy_fn.", 2615 Context.getPointerType(CopyFnType).withConst().withRestrict()), 2616 std::make_pair(".task_t.", Context.VoidPtrTy.withConst()), 2617 std::make_pair(StringRef(), QualType()) // __context with shared vars 2618 }; 2619 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP, 2620 Params); 2621 // Mark this captured region as inlined, because we don't use outlined 2622 // function directly. 2623 getCurCapturedRegion()->TheCapturedDecl->addAttr( 2624 AlwaysInlineAttr::CreateImplicit( 2625 Context, AlwaysInlineAttr::Keyword_forceinline)); 2626 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP, 2627 std::make_pair(StringRef(), QualType())); 2628 break; 2629 } 2630 case OMPD_simd: 2631 case OMPD_for: 2632 case OMPD_for_simd: 2633 case OMPD_sections: 2634 case OMPD_section: 2635 case OMPD_single: 2636 case OMPD_master: 2637 case OMPD_critical: 2638 case OMPD_taskgroup: 2639 case OMPD_distribute: 2640 case OMPD_distribute_simd: 2641 case OMPD_ordered: 2642 case OMPD_atomic: 2643 case OMPD_target_data: { 2644 Sema::CapturedParamNameType Params[] = { 2645 std::make_pair(StringRef(), QualType()) // __context with shared vars 2646 }; 2647 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP, 2648 Params); 2649 break; 2650 } 2651 case OMPD_task: { 2652 QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1).withConst(); 2653 QualType VoidPtrTy = Context.VoidPtrTy.withConst().withRestrict(); 2654 QualType KmpInt32PtrTy = 2655 Context.getPointerType(KmpInt32Ty).withConst().withRestrict(); 2656 QualType Args[] = {VoidPtrTy}; 2657 FunctionProtoType::ExtProtoInfo EPI; 2658 EPI.Variadic = true; 2659 QualType CopyFnType = Context.getFunctionType(Context.VoidTy, Args, EPI); 2660 Sema::CapturedParamNameType Params[] = { 2661 std::make_pair(".global_tid.", KmpInt32Ty), 2662 std::make_pair(".part_id.", KmpInt32PtrTy), 2663 std::make_pair(".privates.", VoidPtrTy), 2664 std::make_pair( 2665 ".copy_fn.", 2666 Context.getPointerType(CopyFnType).withConst().withRestrict()), 2667 std::make_pair(".task_t.", Context.VoidPtrTy.withConst()), 2668 std::make_pair(StringRef(), QualType()) // __context with shared vars 2669 }; 2670 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP, 2671 Params); 2672 // Mark this captured region as inlined, because we don't use outlined 2673 // function directly. 2674 getCurCapturedRegion()->TheCapturedDecl->addAttr( 2675 AlwaysInlineAttr::CreateImplicit( 2676 Context, AlwaysInlineAttr::Keyword_forceinline)); 2677 break; 2678 } 2679 case OMPD_taskloop: 2680 case OMPD_taskloop_simd: { 2681 QualType KmpInt32Ty = 2682 Context.getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/1) 2683 .withConst(); 2684 QualType KmpUInt64Ty = 2685 Context.getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/0) 2686 .withConst(); 2687 QualType KmpInt64Ty = 2688 Context.getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/1) 2689 .withConst(); 2690 QualType VoidPtrTy = Context.VoidPtrTy.withConst().withRestrict(); 2691 QualType KmpInt32PtrTy = 2692 Context.getPointerType(KmpInt32Ty).withConst().withRestrict(); 2693 QualType Args[] = {VoidPtrTy}; 2694 FunctionProtoType::ExtProtoInfo EPI; 2695 EPI.Variadic = true; 2696 QualType CopyFnType = Context.getFunctionType(Context.VoidTy, Args, EPI); 2697 Sema::CapturedParamNameType Params[] = { 2698 std::make_pair(".global_tid.", KmpInt32Ty), 2699 std::make_pair(".part_id.", KmpInt32PtrTy), 2700 std::make_pair(".privates.", VoidPtrTy), 2701 std::make_pair( 2702 ".copy_fn.", 2703 Context.getPointerType(CopyFnType).withConst().withRestrict()), 2704 std::make_pair(".task_t.", Context.VoidPtrTy.withConst()), 2705 std::make_pair(".lb.", KmpUInt64Ty), 2706 std::make_pair(".ub.", KmpUInt64Ty), 2707 std::make_pair(".st.", KmpInt64Ty), 2708 std::make_pair(".liter.", KmpInt32Ty), 2709 std::make_pair(".reductions.", VoidPtrTy), 2710 std::make_pair(StringRef(), QualType()) // __context with shared vars 2711 }; 2712 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP, 2713 Params); 2714 // Mark this captured region as inlined, because we don't use outlined 2715 // function directly. 2716 getCurCapturedRegion()->TheCapturedDecl->addAttr( 2717 AlwaysInlineAttr::CreateImplicit( 2718 Context, AlwaysInlineAttr::Keyword_forceinline)); 2719 break; 2720 } 2721 case OMPD_distribute_parallel_for_simd: 2722 case OMPD_distribute_parallel_for: { 2723 QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1).withConst(); 2724 QualType KmpInt32PtrTy = 2725 Context.getPointerType(KmpInt32Ty).withConst().withRestrict(); 2726 Sema::CapturedParamNameType Params[] = { 2727 std::make_pair(".global_tid.", KmpInt32PtrTy), 2728 std::make_pair(".bound_tid.", KmpInt32PtrTy), 2729 std::make_pair(".previous.lb.", Context.getSizeType().withConst()), 2730 std::make_pair(".previous.ub.", Context.getSizeType().withConst()), 2731 std::make_pair(StringRef(), QualType()) // __context with shared vars 2732 }; 2733 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP, 2734 Params); 2735 break; 2736 } 2737 case OMPD_target_teams_distribute_parallel_for: 2738 case OMPD_target_teams_distribute_parallel_for_simd: { 2739 QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1).withConst(); 2740 QualType KmpInt32PtrTy = 2741 Context.getPointerType(KmpInt32Ty).withConst().withRestrict(); 2742 QualType VoidPtrTy = Context.VoidPtrTy.withConst().withRestrict(); 2743 2744 QualType Args[] = {VoidPtrTy}; 2745 FunctionProtoType::ExtProtoInfo EPI; 2746 EPI.Variadic = true; 2747 QualType CopyFnType = Context.getFunctionType(Context.VoidTy, Args, EPI); 2748 Sema::CapturedParamNameType Params[] = { 2749 std::make_pair(".global_tid.", KmpInt32Ty), 2750 std::make_pair(".part_id.", KmpInt32PtrTy), 2751 std::make_pair(".privates.", VoidPtrTy), 2752 std::make_pair( 2753 ".copy_fn.", 2754 Context.getPointerType(CopyFnType).withConst().withRestrict()), 2755 std::make_pair(".task_t.", Context.VoidPtrTy.withConst()), 2756 std::make_pair(StringRef(), QualType()) // __context with shared vars 2757 }; 2758 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP, 2759 Params); 2760 // Mark this captured region as inlined, because we don't use outlined 2761 // function directly. 2762 getCurCapturedRegion()->TheCapturedDecl->addAttr( 2763 AlwaysInlineAttr::CreateImplicit( 2764 Context, AlwaysInlineAttr::Keyword_forceinline)); 2765 Sema::CapturedParamNameType ParamsTarget[] = { 2766 std::make_pair(StringRef(), QualType()) // __context with shared vars 2767 }; 2768 // Start a captured region for 'target' with no implicit parameters. 2769 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP, 2770 ParamsTarget); 2771 2772 Sema::CapturedParamNameType ParamsTeams[] = { 2773 std::make_pair(".global_tid.", KmpInt32PtrTy), 2774 std::make_pair(".bound_tid.", KmpInt32PtrTy), 2775 std::make_pair(StringRef(), QualType()) // __context with shared vars 2776 }; 2777 // Start a captured region for 'target' with no implicit parameters. 2778 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP, 2779 ParamsTeams); 2780 2781 Sema::CapturedParamNameType ParamsParallel[] = { 2782 std::make_pair(".global_tid.", KmpInt32PtrTy), 2783 std::make_pair(".bound_tid.", KmpInt32PtrTy), 2784 std::make_pair(".previous.lb.", Context.getSizeType().withConst()), 2785 std::make_pair(".previous.ub.", Context.getSizeType().withConst()), 2786 std::make_pair(StringRef(), QualType()) // __context with shared vars 2787 }; 2788 // Start a captured region for 'teams' or 'parallel'. Both regions have 2789 // the same implicit parameters. 2790 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP, 2791 ParamsParallel); 2792 break; 2793 } 2794 2795 case OMPD_teams_distribute_parallel_for: 2796 case OMPD_teams_distribute_parallel_for_simd: { 2797 QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1).withConst(); 2798 QualType KmpInt32PtrTy = 2799 Context.getPointerType(KmpInt32Ty).withConst().withRestrict(); 2800 2801 Sema::CapturedParamNameType ParamsTeams[] = { 2802 std::make_pair(".global_tid.", KmpInt32PtrTy), 2803 std::make_pair(".bound_tid.", KmpInt32PtrTy), 2804 std::make_pair(StringRef(), QualType()) // __context with shared vars 2805 }; 2806 // Start a captured region for 'target' with no implicit parameters. 2807 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP, 2808 ParamsTeams); 2809 2810 Sema::CapturedParamNameType ParamsParallel[] = { 2811 std::make_pair(".global_tid.", KmpInt32PtrTy), 2812 std::make_pair(".bound_tid.", KmpInt32PtrTy), 2813 std::make_pair(".previous.lb.", Context.getSizeType().withConst()), 2814 std::make_pair(".previous.ub.", Context.getSizeType().withConst()), 2815 std::make_pair(StringRef(), QualType()) // __context with shared vars 2816 }; 2817 // Start a captured region for 'teams' or 'parallel'. Both regions have 2818 // the same implicit parameters. 2819 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP, 2820 ParamsParallel); 2821 break; 2822 } 2823 case OMPD_target_update: 2824 case OMPD_target_enter_data: 2825 case OMPD_target_exit_data: { 2826 QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1).withConst(); 2827 QualType VoidPtrTy = Context.VoidPtrTy.withConst().withRestrict(); 2828 QualType KmpInt32PtrTy = 2829 Context.getPointerType(KmpInt32Ty).withConst().withRestrict(); 2830 QualType Args[] = {VoidPtrTy}; 2831 FunctionProtoType::ExtProtoInfo EPI; 2832 EPI.Variadic = true; 2833 QualType CopyFnType = Context.getFunctionType(Context.VoidTy, Args, EPI); 2834 Sema::CapturedParamNameType Params[] = { 2835 std::make_pair(".global_tid.", KmpInt32Ty), 2836 std::make_pair(".part_id.", KmpInt32PtrTy), 2837 std::make_pair(".privates.", VoidPtrTy), 2838 std::make_pair( 2839 ".copy_fn.", 2840 Context.getPointerType(CopyFnType).withConst().withRestrict()), 2841 std::make_pair(".task_t.", Context.VoidPtrTy.withConst()), 2842 std::make_pair(StringRef(), QualType()) // __context with shared vars 2843 }; 2844 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP, 2845 Params); 2846 // Mark this captured region as inlined, because we don't use outlined 2847 // function directly. 2848 getCurCapturedRegion()->TheCapturedDecl->addAttr( 2849 AlwaysInlineAttr::CreateImplicit( 2850 Context, AlwaysInlineAttr::Keyword_forceinline)); 2851 break; 2852 } 2853 case OMPD_threadprivate: 2854 case OMPD_taskyield: 2855 case OMPD_barrier: 2856 case OMPD_taskwait: 2857 case OMPD_cancellation_point: 2858 case OMPD_cancel: 2859 case OMPD_flush: 2860 case OMPD_declare_reduction: 2861 case OMPD_declare_mapper: 2862 case OMPD_declare_simd: 2863 case OMPD_declare_target: 2864 case OMPD_end_declare_target: 2865 case OMPD_requires: 2866 llvm_unreachable("OpenMP Directive is not allowed"); 2867 case OMPD_unknown: 2868 llvm_unreachable("Unknown OpenMP directive"); 2869 } 2870 } 2871 2872 int Sema::getOpenMPCaptureLevels(OpenMPDirectiveKind DKind) { 2873 SmallVector<OpenMPDirectiveKind, 4> CaptureRegions; 2874 getOpenMPCaptureRegions(CaptureRegions, DKind); 2875 return CaptureRegions.size(); 2876 } 2877 2878 static OMPCapturedExprDecl *buildCaptureDecl(Sema &S, IdentifierInfo *Id, 2879 Expr *CaptureExpr, bool WithInit, 2880 bool AsExpression) { 2881 assert(CaptureExpr); 2882 ASTContext &C = S.getASTContext(); 2883 Expr *Init = AsExpression ? CaptureExpr : CaptureExpr->IgnoreImpCasts(); 2884 QualType Ty = Init->getType(); 2885 if (CaptureExpr->getObjectKind() == OK_Ordinary && CaptureExpr->isGLValue()) { 2886 if (S.getLangOpts().CPlusPlus) { 2887 Ty = C.getLValueReferenceType(Ty); 2888 } else { 2889 Ty = C.getPointerType(Ty); 2890 ExprResult Res = 2891 S.CreateBuiltinUnaryOp(CaptureExpr->getExprLoc(), UO_AddrOf, Init); 2892 if (!Res.isUsable()) 2893 return nullptr; 2894 Init = Res.get(); 2895 } 2896 WithInit = true; 2897 } 2898 auto *CED = OMPCapturedExprDecl::Create(C, S.CurContext, Id, Ty, 2899 CaptureExpr->getBeginLoc()); 2900 if (!WithInit) 2901 CED->addAttr(OMPCaptureNoInitAttr::CreateImplicit(C)); 2902 S.CurContext->addHiddenDecl(CED); 2903 S.AddInitializerToDecl(CED, Init, /*DirectInit=*/false); 2904 return CED; 2905 } 2906 2907 static DeclRefExpr *buildCapture(Sema &S, ValueDecl *D, Expr *CaptureExpr, 2908 bool WithInit) { 2909 OMPCapturedExprDecl *CD; 2910 if (VarDecl *VD = S.isOpenMPCapturedDecl(D)) 2911 CD = cast<OMPCapturedExprDecl>(VD); 2912 else 2913 CD = buildCaptureDecl(S, D->getIdentifier(), CaptureExpr, WithInit, 2914 /*AsExpression=*/false); 2915 return buildDeclRefExpr(S, CD, CD->getType().getNonReferenceType(), 2916 CaptureExpr->getExprLoc()); 2917 } 2918 2919 static ExprResult buildCapture(Sema &S, Expr *CaptureExpr, DeclRefExpr *&Ref) { 2920 CaptureExpr = S.DefaultLvalueConversion(CaptureExpr).get(); 2921 if (!Ref) { 2922 OMPCapturedExprDecl *CD = buildCaptureDecl( 2923 S, &S.getASTContext().Idents.get(".capture_expr."), CaptureExpr, 2924 /*WithInit=*/true, /*AsExpression=*/true); 2925 Ref = buildDeclRefExpr(S, CD, CD->getType().getNonReferenceType(), 2926 CaptureExpr->getExprLoc()); 2927 } 2928 ExprResult Res = Ref; 2929 if (!S.getLangOpts().CPlusPlus && 2930 CaptureExpr->getObjectKind() == OK_Ordinary && CaptureExpr->isGLValue() && 2931 Ref->getType()->isPointerType()) { 2932 Res = S.CreateBuiltinUnaryOp(CaptureExpr->getExprLoc(), UO_Deref, Ref); 2933 if (!Res.isUsable()) 2934 return ExprError(); 2935 } 2936 return S.DefaultLvalueConversion(Res.get()); 2937 } 2938 2939 namespace { 2940 // OpenMP directives parsed in this section are represented as a 2941 // CapturedStatement with an associated statement. If a syntax error 2942 // is detected during the parsing of the associated statement, the 2943 // compiler must abort processing and close the CapturedStatement. 2944 // 2945 // Combined directives such as 'target parallel' have more than one 2946 // nested CapturedStatements. This RAII ensures that we unwind out 2947 // of all the nested CapturedStatements when an error is found. 2948 class CaptureRegionUnwinderRAII { 2949 private: 2950 Sema &S; 2951 bool &ErrorFound; 2952 OpenMPDirectiveKind DKind = OMPD_unknown; 2953 2954 public: 2955 CaptureRegionUnwinderRAII(Sema &S, bool &ErrorFound, 2956 OpenMPDirectiveKind DKind) 2957 : S(S), ErrorFound(ErrorFound), DKind(DKind) {} 2958 ~CaptureRegionUnwinderRAII() { 2959 if (ErrorFound) { 2960 int ThisCaptureLevel = S.getOpenMPCaptureLevels(DKind); 2961 while (--ThisCaptureLevel >= 0) 2962 S.ActOnCapturedRegionError(); 2963 } 2964 } 2965 }; 2966 } // namespace 2967 2968 StmtResult Sema::ActOnOpenMPRegionEnd(StmtResult S, 2969 ArrayRef<OMPClause *> Clauses) { 2970 bool ErrorFound = false; 2971 CaptureRegionUnwinderRAII CaptureRegionUnwinder( 2972 *this, ErrorFound, DSAStack->getCurrentDirective()); 2973 if (!S.isUsable()) { 2974 ErrorFound = true; 2975 return StmtError(); 2976 } 2977 2978 SmallVector<OpenMPDirectiveKind, 4> CaptureRegions; 2979 getOpenMPCaptureRegions(CaptureRegions, DSAStack->getCurrentDirective()); 2980 OMPOrderedClause *OC = nullptr; 2981 OMPScheduleClause *SC = nullptr; 2982 SmallVector<const OMPLinearClause *, 4> LCs; 2983 SmallVector<const OMPClauseWithPreInit *, 4> PICs; 2984 // This is required for proper codegen. 2985 for (OMPClause *Clause : Clauses) { 2986 if (isOpenMPTaskingDirective(DSAStack->getCurrentDirective()) && 2987 Clause->getClauseKind() == OMPC_in_reduction) { 2988 // Capture taskgroup task_reduction descriptors inside the tasking regions 2989 // with the corresponding in_reduction items. 2990 auto *IRC = cast<OMPInReductionClause>(Clause); 2991 for (Expr *E : IRC->taskgroup_descriptors()) 2992 if (E) 2993 MarkDeclarationsReferencedInExpr(E); 2994 } 2995 if (isOpenMPPrivate(Clause->getClauseKind()) || 2996 Clause->getClauseKind() == OMPC_copyprivate || 2997 (getLangOpts().OpenMPUseTLS && 2998 getASTContext().getTargetInfo().isTLSSupported() && 2999 Clause->getClauseKind() == OMPC_copyin)) { 3000 DSAStack->setForceVarCapturing(Clause->getClauseKind() == OMPC_copyin); 3001 // Mark all variables in private list clauses as used in inner region. 3002 for (Stmt *VarRef : Clause->children()) { 3003 if (auto *E = cast_or_null<Expr>(VarRef)) { 3004 MarkDeclarationsReferencedInExpr(E); 3005 } 3006 } 3007 DSAStack->setForceVarCapturing(/*V=*/false); 3008 } else if (CaptureRegions.size() > 1 || 3009 CaptureRegions.back() != OMPD_unknown) { 3010 if (auto *C = OMPClauseWithPreInit::get(Clause)) 3011 PICs.push_back(C); 3012 if (auto *C = OMPClauseWithPostUpdate::get(Clause)) { 3013 if (Expr *E = C->getPostUpdateExpr()) 3014 MarkDeclarationsReferencedInExpr(E); 3015 } 3016 } 3017 if (Clause->getClauseKind() == OMPC_schedule) 3018 SC = cast<OMPScheduleClause>(Clause); 3019 else if (Clause->getClauseKind() == OMPC_ordered) 3020 OC = cast<OMPOrderedClause>(Clause); 3021 else if (Clause->getClauseKind() == OMPC_linear) 3022 LCs.push_back(cast<OMPLinearClause>(Clause)); 3023 } 3024 // OpenMP, 2.7.1 Loop Construct, Restrictions 3025 // The nonmonotonic modifier cannot be specified if an ordered clause is 3026 // specified. 3027 if (SC && 3028 (SC->getFirstScheduleModifier() == OMPC_SCHEDULE_MODIFIER_nonmonotonic || 3029 SC->getSecondScheduleModifier() == 3030 OMPC_SCHEDULE_MODIFIER_nonmonotonic) && 3031 OC) { 3032 Diag(SC->getFirstScheduleModifier() == OMPC_SCHEDULE_MODIFIER_nonmonotonic 3033 ? SC->getFirstScheduleModifierLoc() 3034 : SC->getSecondScheduleModifierLoc(), 3035 diag::err_omp_schedule_nonmonotonic_ordered) 3036 << SourceRange(OC->getBeginLoc(), OC->getEndLoc()); 3037 ErrorFound = true; 3038 } 3039 if (!LCs.empty() && OC && OC->getNumForLoops()) { 3040 for (const OMPLinearClause *C : LCs) { 3041 Diag(C->getBeginLoc(), diag::err_omp_linear_ordered) 3042 << SourceRange(OC->getBeginLoc(), OC->getEndLoc()); 3043 } 3044 ErrorFound = true; 3045 } 3046 if (isOpenMPWorksharingDirective(DSAStack->getCurrentDirective()) && 3047 isOpenMPSimdDirective(DSAStack->getCurrentDirective()) && OC && 3048 OC->getNumForLoops()) { 3049 Diag(OC->getBeginLoc(), diag::err_omp_ordered_simd) 3050 << getOpenMPDirectiveName(DSAStack->getCurrentDirective()); 3051 ErrorFound = true; 3052 } 3053 if (ErrorFound) { 3054 return StmtError(); 3055 } 3056 StmtResult SR = S; 3057 for (OpenMPDirectiveKind ThisCaptureRegion : llvm::reverse(CaptureRegions)) { 3058 // Mark all variables in private list clauses as used in inner region. 3059 // Required for proper codegen of combined directives. 3060 // TODO: add processing for other clauses. 3061 if (ThisCaptureRegion != OMPD_unknown) { 3062 for (const clang::OMPClauseWithPreInit *C : PICs) { 3063 OpenMPDirectiveKind CaptureRegion = C->getCaptureRegion(); 3064 // Find the particular capture region for the clause if the 3065 // directive is a combined one with multiple capture regions. 3066 // If the directive is not a combined one, the capture region 3067 // associated with the clause is OMPD_unknown and is generated 3068 // only once. 3069 if (CaptureRegion == ThisCaptureRegion || 3070 CaptureRegion == OMPD_unknown) { 3071 if (auto *DS = cast_or_null<DeclStmt>(C->getPreInitStmt())) { 3072 for (Decl *D : DS->decls()) 3073 MarkVariableReferenced(D->getLocation(), cast<VarDecl>(D)); 3074 } 3075 } 3076 } 3077 } 3078 SR = ActOnCapturedRegionEnd(SR.get()); 3079 } 3080 return SR; 3081 } 3082 3083 static bool checkCancelRegion(Sema &SemaRef, OpenMPDirectiveKind CurrentRegion, 3084 OpenMPDirectiveKind CancelRegion, 3085 SourceLocation StartLoc) { 3086 // CancelRegion is only needed for cancel and cancellation_point. 3087 if (CurrentRegion != OMPD_cancel && CurrentRegion != OMPD_cancellation_point) 3088 return false; 3089 3090 if (CancelRegion == OMPD_parallel || CancelRegion == OMPD_for || 3091 CancelRegion == OMPD_sections || CancelRegion == OMPD_taskgroup) 3092 return false; 3093 3094 SemaRef.Diag(StartLoc, diag::err_omp_wrong_cancel_region) 3095 << getOpenMPDirectiveName(CancelRegion); 3096 return true; 3097 } 3098 3099 static bool checkNestingOfRegions(Sema &SemaRef, const DSAStackTy *Stack, 3100 OpenMPDirectiveKind CurrentRegion, 3101 const DeclarationNameInfo &CurrentName, 3102 OpenMPDirectiveKind CancelRegion, 3103 SourceLocation StartLoc) { 3104 if (Stack->getCurScope()) { 3105 OpenMPDirectiveKind ParentRegion = Stack->getParentDirective(); 3106 OpenMPDirectiveKind OffendingRegion = ParentRegion; 3107 bool NestingProhibited = false; 3108 bool CloseNesting = true; 3109 bool OrphanSeen = false; 3110 enum { 3111 NoRecommend, 3112 ShouldBeInParallelRegion, 3113 ShouldBeInOrderedRegion, 3114 ShouldBeInTargetRegion, 3115 ShouldBeInTeamsRegion 3116 } Recommend = NoRecommend; 3117 if (isOpenMPSimdDirective(ParentRegion) && CurrentRegion != OMPD_ordered) { 3118 // OpenMP [2.16, Nesting of Regions] 3119 // OpenMP constructs may not be nested inside a simd region. 3120 // OpenMP [2.8.1,simd Construct, Restrictions] 3121 // An ordered construct with the simd clause is the only OpenMP 3122 // construct that can appear in the simd region. 3123 // Allowing a SIMD construct nested in another SIMD construct is an 3124 // extension. The OpenMP 4.5 spec does not allow it. Issue a warning 3125 // message. 3126 SemaRef.Diag(StartLoc, (CurrentRegion != OMPD_simd) 3127 ? diag::err_omp_prohibited_region_simd 3128 : diag::warn_omp_nesting_simd); 3129 return CurrentRegion != OMPD_simd; 3130 } 3131 if (ParentRegion == OMPD_atomic) { 3132 // OpenMP [2.16, Nesting of Regions] 3133 // OpenMP constructs may not be nested inside an atomic region. 3134 SemaRef.Diag(StartLoc, diag::err_omp_prohibited_region_atomic); 3135 return true; 3136 } 3137 if (CurrentRegion == OMPD_section) { 3138 // OpenMP [2.7.2, sections Construct, Restrictions] 3139 // Orphaned section directives are prohibited. That is, the section 3140 // directives must appear within the sections construct and must not be 3141 // encountered elsewhere in the sections region. 3142 if (ParentRegion != OMPD_sections && 3143 ParentRegion != OMPD_parallel_sections) { 3144 SemaRef.Diag(StartLoc, diag::err_omp_orphaned_section_directive) 3145 << (ParentRegion != OMPD_unknown) 3146 << getOpenMPDirectiveName(ParentRegion); 3147 return true; 3148 } 3149 return false; 3150 } 3151 // Allow some constructs (except teams and cancellation constructs) to be 3152 // orphaned (they could be used in functions, called from OpenMP regions 3153 // with the required preconditions). 3154 if (ParentRegion == OMPD_unknown && 3155 !isOpenMPNestingTeamsDirective(CurrentRegion) && 3156 CurrentRegion != OMPD_cancellation_point && 3157 CurrentRegion != OMPD_cancel) 3158 return false; 3159 if (CurrentRegion == OMPD_cancellation_point || 3160 CurrentRegion == OMPD_cancel) { 3161 // OpenMP [2.16, Nesting of Regions] 3162 // A cancellation point construct for which construct-type-clause is 3163 // taskgroup must be nested inside a task construct. A cancellation 3164 // point construct for which construct-type-clause is not taskgroup must 3165 // be closely nested inside an OpenMP construct that matches the type 3166 // specified in construct-type-clause. 3167 // A cancel construct for which construct-type-clause is taskgroup must be 3168 // nested inside a task construct. A cancel construct for which 3169 // construct-type-clause is not taskgroup must be closely nested inside an 3170 // OpenMP construct that matches the type specified in 3171 // construct-type-clause. 3172 NestingProhibited = 3173 !((CancelRegion == OMPD_parallel && 3174 (ParentRegion == OMPD_parallel || 3175 ParentRegion == OMPD_target_parallel)) || 3176 (CancelRegion == OMPD_for && 3177 (ParentRegion == OMPD_for || ParentRegion == OMPD_parallel_for || 3178 ParentRegion == OMPD_target_parallel_for || 3179 ParentRegion == OMPD_distribute_parallel_for || 3180 ParentRegion == OMPD_teams_distribute_parallel_for || 3181 ParentRegion == OMPD_target_teams_distribute_parallel_for)) || 3182 (CancelRegion == OMPD_taskgroup && ParentRegion == OMPD_task) || 3183 (CancelRegion == OMPD_sections && 3184 (ParentRegion == OMPD_section || ParentRegion == OMPD_sections || 3185 ParentRegion == OMPD_parallel_sections))); 3186 OrphanSeen = ParentRegion == OMPD_unknown; 3187 } else if (CurrentRegion == OMPD_master) { 3188 // OpenMP [2.16, Nesting of Regions] 3189 // A master region may not be closely nested inside a worksharing, 3190 // atomic, or explicit task region. 3191 NestingProhibited = isOpenMPWorksharingDirective(ParentRegion) || 3192 isOpenMPTaskingDirective(ParentRegion); 3193 } else if (CurrentRegion == OMPD_critical && CurrentName.getName()) { 3194 // OpenMP [2.16, Nesting of Regions] 3195 // A critical region may not be nested (closely or otherwise) inside a 3196 // critical region with the same name. Note that this restriction is not 3197 // sufficient to prevent deadlock. 3198 SourceLocation PreviousCriticalLoc; 3199 bool DeadLock = Stack->hasDirective( 3200 [CurrentName, &PreviousCriticalLoc](OpenMPDirectiveKind K, 3201 const DeclarationNameInfo &DNI, 3202 SourceLocation Loc) { 3203 if (K == OMPD_critical && DNI.getName() == CurrentName.getName()) { 3204 PreviousCriticalLoc = Loc; 3205 return true; 3206 } 3207 return false; 3208 }, 3209 false /* skip top directive */); 3210 if (DeadLock) { 3211 SemaRef.Diag(StartLoc, 3212 diag::err_omp_prohibited_region_critical_same_name) 3213 << CurrentName.getName(); 3214 if (PreviousCriticalLoc.isValid()) 3215 SemaRef.Diag(PreviousCriticalLoc, 3216 diag::note_omp_previous_critical_region); 3217 return true; 3218 } 3219 } else if (CurrentRegion == OMPD_barrier) { 3220 // OpenMP [2.16, Nesting of Regions] 3221 // A barrier region may not be closely nested inside a worksharing, 3222 // explicit task, critical, ordered, atomic, or master region. 3223 NestingProhibited = isOpenMPWorksharingDirective(ParentRegion) || 3224 isOpenMPTaskingDirective(ParentRegion) || 3225 ParentRegion == OMPD_master || 3226 ParentRegion == OMPD_critical || 3227 ParentRegion == OMPD_ordered; 3228 } else if (isOpenMPWorksharingDirective(CurrentRegion) && 3229 !isOpenMPParallelDirective(CurrentRegion) && 3230 !isOpenMPTeamsDirective(CurrentRegion)) { 3231 // OpenMP [2.16, Nesting of Regions] 3232 // A worksharing region may not be closely nested inside a worksharing, 3233 // explicit task, critical, ordered, atomic, or master region. 3234 NestingProhibited = isOpenMPWorksharingDirective(ParentRegion) || 3235 isOpenMPTaskingDirective(ParentRegion) || 3236 ParentRegion == OMPD_master || 3237 ParentRegion == OMPD_critical || 3238 ParentRegion == OMPD_ordered; 3239 Recommend = ShouldBeInParallelRegion; 3240 } else if (CurrentRegion == OMPD_ordered) { 3241 // OpenMP [2.16, Nesting of Regions] 3242 // An ordered region may not be closely nested inside a critical, 3243 // atomic, or explicit task region. 3244 // An ordered region must be closely nested inside a loop region (or 3245 // parallel loop region) with an ordered clause. 3246 // OpenMP [2.8.1,simd Construct, Restrictions] 3247 // An ordered construct with the simd clause is the only OpenMP construct 3248 // that can appear in the simd region. 3249 NestingProhibited = ParentRegion == OMPD_critical || 3250 isOpenMPTaskingDirective(ParentRegion) || 3251 !(isOpenMPSimdDirective(ParentRegion) || 3252 Stack->isParentOrderedRegion()); 3253 Recommend = ShouldBeInOrderedRegion; 3254 } else if (isOpenMPNestingTeamsDirective(CurrentRegion)) { 3255 // OpenMP [2.16, Nesting of Regions] 3256 // If specified, a teams construct must be contained within a target 3257 // construct. 3258 NestingProhibited = ParentRegion != OMPD_target; 3259 OrphanSeen = ParentRegion == OMPD_unknown; 3260 Recommend = ShouldBeInTargetRegion; 3261 } 3262 if (!NestingProhibited && 3263 !isOpenMPTargetExecutionDirective(CurrentRegion) && 3264 !isOpenMPTargetDataManagementDirective(CurrentRegion) && 3265 (ParentRegion == OMPD_teams || ParentRegion == OMPD_target_teams)) { 3266 // OpenMP [2.16, Nesting of Regions] 3267 // distribute, parallel, parallel sections, parallel workshare, and the 3268 // parallel loop and parallel loop SIMD constructs are the only OpenMP 3269 // constructs that can be closely nested in the teams region. 3270 NestingProhibited = !isOpenMPParallelDirective(CurrentRegion) && 3271 !isOpenMPDistributeDirective(CurrentRegion); 3272 Recommend = ShouldBeInParallelRegion; 3273 } 3274 if (!NestingProhibited && 3275 isOpenMPNestingDistributeDirective(CurrentRegion)) { 3276 // OpenMP 4.5 [2.17 Nesting of Regions] 3277 // The region associated with the distribute construct must be strictly 3278 // nested inside a teams region 3279 NestingProhibited = 3280 (ParentRegion != OMPD_teams && ParentRegion != OMPD_target_teams); 3281 Recommend = ShouldBeInTeamsRegion; 3282 } 3283 if (!NestingProhibited && 3284 (isOpenMPTargetExecutionDirective(CurrentRegion) || 3285 isOpenMPTargetDataManagementDirective(CurrentRegion))) { 3286 // OpenMP 4.5 [2.17 Nesting of Regions] 3287 // If a target, target update, target data, target enter data, or 3288 // target exit data construct is encountered during execution of a 3289 // target region, the behavior is unspecified. 3290 NestingProhibited = Stack->hasDirective( 3291 [&OffendingRegion](OpenMPDirectiveKind K, const DeclarationNameInfo &, 3292 SourceLocation) { 3293 if (isOpenMPTargetExecutionDirective(K)) { 3294 OffendingRegion = K; 3295 return true; 3296 } 3297 return false; 3298 }, 3299 false /* don't skip top directive */); 3300 CloseNesting = false; 3301 } 3302 if (NestingProhibited) { 3303 if (OrphanSeen) { 3304 SemaRef.Diag(StartLoc, diag::err_omp_orphaned_device_directive) 3305 << getOpenMPDirectiveName(CurrentRegion) << Recommend; 3306 } else { 3307 SemaRef.Diag(StartLoc, diag::err_omp_prohibited_region) 3308 << CloseNesting << getOpenMPDirectiveName(OffendingRegion) 3309 << Recommend << getOpenMPDirectiveName(CurrentRegion); 3310 } 3311 return true; 3312 } 3313 } 3314 return false; 3315 } 3316 3317 static bool checkIfClauses(Sema &S, OpenMPDirectiveKind Kind, 3318 ArrayRef<OMPClause *> Clauses, 3319 ArrayRef<OpenMPDirectiveKind> AllowedNameModifiers) { 3320 bool ErrorFound = false; 3321 unsigned NamedModifiersNumber = 0; 3322 SmallVector<const OMPIfClause *, OMPC_unknown + 1> FoundNameModifiers( 3323 OMPD_unknown + 1); 3324 SmallVector<SourceLocation, 4> NameModifierLoc; 3325 for (const OMPClause *C : Clauses) { 3326 if (const auto *IC = dyn_cast_or_null<OMPIfClause>(C)) { 3327 // At most one if clause without a directive-name-modifier can appear on 3328 // the directive. 3329 OpenMPDirectiveKind CurNM = IC->getNameModifier(); 3330 if (FoundNameModifiers[CurNM]) { 3331 S.Diag(C->getBeginLoc(), diag::err_omp_more_one_clause) 3332 << getOpenMPDirectiveName(Kind) << getOpenMPClauseName(OMPC_if) 3333 << (CurNM != OMPD_unknown) << getOpenMPDirectiveName(CurNM); 3334 ErrorFound = true; 3335 } else if (CurNM != OMPD_unknown) { 3336 NameModifierLoc.push_back(IC->getNameModifierLoc()); 3337 ++NamedModifiersNumber; 3338 } 3339 FoundNameModifiers[CurNM] = IC; 3340 if (CurNM == OMPD_unknown) 3341 continue; 3342 // Check if the specified name modifier is allowed for the current 3343 // directive. 3344 // At most one if clause with the particular directive-name-modifier can 3345 // appear on the directive. 3346 bool MatchFound = false; 3347 for (auto NM : AllowedNameModifiers) { 3348 if (CurNM == NM) { 3349 MatchFound = true; 3350 break; 3351 } 3352 } 3353 if (!MatchFound) { 3354 S.Diag(IC->getNameModifierLoc(), 3355 diag::err_omp_wrong_if_directive_name_modifier) 3356 << getOpenMPDirectiveName(CurNM) << getOpenMPDirectiveName(Kind); 3357 ErrorFound = true; 3358 } 3359 } 3360 } 3361 // If any if clause on the directive includes a directive-name-modifier then 3362 // all if clauses on the directive must include a directive-name-modifier. 3363 if (FoundNameModifiers[OMPD_unknown] && NamedModifiersNumber > 0) { 3364 if (NamedModifiersNumber == AllowedNameModifiers.size()) { 3365 S.Diag(FoundNameModifiers[OMPD_unknown]->getBeginLoc(), 3366 diag::err_omp_no_more_if_clause); 3367 } else { 3368 std::string Values; 3369 std::string Sep(", "); 3370 unsigned AllowedCnt = 0; 3371 unsigned TotalAllowedNum = 3372 AllowedNameModifiers.size() - NamedModifiersNumber; 3373 for (unsigned Cnt = 0, End = AllowedNameModifiers.size(); Cnt < End; 3374 ++Cnt) { 3375 OpenMPDirectiveKind NM = AllowedNameModifiers[Cnt]; 3376 if (!FoundNameModifiers[NM]) { 3377 Values += "'"; 3378 Values += getOpenMPDirectiveName(NM); 3379 Values += "'"; 3380 if (AllowedCnt + 2 == TotalAllowedNum) 3381 Values += " or "; 3382 else if (AllowedCnt + 1 != TotalAllowedNum) 3383 Values += Sep; 3384 ++AllowedCnt; 3385 } 3386 } 3387 S.Diag(FoundNameModifiers[OMPD_unknown]->getCondition()->getBeginLoc(), 3388 diag::err_omp_unnamed_if_clause) 3389 << (TotalAllowedNum > 1) << Values; 3390 } 3391 for (SourceLocation Loc : NameModifierLoc) { 3392 S.Diag(Loc, diag::note_omp_previous_named_if_clause); 3393 } 3394 ErrorFound = true; 3395 } 3396 return ErrorFound; 3397 } 3398 3399 StmtResult Sema::ActOnOpenMPExecutableDirective( 3400 OpenMPDirectiveKind Kind, const DeclarationNameInfo &DirName, 3401 OpenMPDirectiveKind CancelRegion, ArrayRef<OMPClause *> Clauses, 3402 Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc) { 3403 StmtResult Res = StmtError(); 3404 // First check CancelRegion which is then used in checkNestingOfRegions. 3405 if (checkCancelRegion(*this, Kind, CancelRegion, StartLoc) || 3406 checkNestingOfRegions(*this, DSAStack, Kind, DirName, CancelRegion, 3407 StartLoc)) 3408 return StmtError(); 3409 3410 llvm::SmallVector<OMPClause *, 8> ClausesWithImplicit; 3411 VarsWithInheritedDSAType VarsWithInheritedDSA; 3412 bool ErrorFound = false; 3413 ClausesWithImplicit.append(Clauses.begin(), Clauses.end()); 3414 if (AStmt && !CurContext->isDependentContext()) { 3415 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected"); 3416 3417 // Check default data sharing attributes for referenced variables. 3418 DSAAttrChecker DSAChecker(DSAStack, *this, cast<CapturedStmt>(AStmt)); 3419 int ThisCaptureLevel = getOpenMPCaptureLevels(Kind); 3420 Stmt *S = AStmt; 3421 while (--ThisCaptureLevel >= 0) 3422 S = cast<CapturedStmt>(S)->getCapturedStmt(); 3423 DSAChecker.Visit(S); 3424 if (DSAChecker.isErrorFound()) 3425 return StmtError(); 3426 // Generate list of implicitly defined firstprivate variables. 3427 VarsWithInheritedDSA = DSAChecker.getVarsWithInheritedDSA(); 3428 3429 SmallVector<Expr *, 4> ImplicitFirstprivates( 3430 DSAChecker.getImplicitFirstprivate().begin(), 3431 DSAChecker.getImplicitFirstprivate().end()); 3432 SmallVector<Expr *, 4> ImplicitMaps(DSAChecker.getImplicitMap().begin(), 3433 DSAChecker.getImplicitMap().end()); 3434 // Mark taskgroup task_reduction descriptors as implicitly firstprivate. 3435 for (OMPClause *C : Clauses) { 3436 if (auto *IRC = dyn_cast<OMPInReductionClause>(C)) { 3437 for (Expr *E : IRC->taskgroup_descriptors()) 3438 if (E) 3439 ImplicitFirstprivates.emplace_back(E); 3440 } 3441 } 3442 if (!ImplicitFirstprivates.empty()) { 3443 if (OMPClause *Implicit = ActOnOpenMPFirstprivateClause( 3444 ImplicitFirstprivates, SourceLocation(), SourceLocation(), 3445 SourceLocation())) { 3446 ClausesWithImplicit.push_back(Implicit); 3447 ErrorFound = cast<OMPFirstprivateClause>(Implicit)->varlist_size() != 3448 ImplicitFirstprivates.size(); 3449 } else { 3450 ErrorFound = true; 3451 } 3452 } 3453 if (!ImplicitMaps.empty()) { 3454 CXXScopeSpec MapperIdScopeSpec; 3455 DeclarationNameInfo MapperId; 3456 if (OMPClause *Implicit = ActOnOpenMPMapClause( 3457 llvm::None, llvm::None, MapperIdScopeSpec, MapperId, 3458 OMPC_MAP_tofrom, /*IsMapTypeImplicit=*/true, SourceLocation(), 3459 SourceLocation(), ImplicitMaps, OMPVarListLocTy())) { 3460 ClausesWithImplicit.emplace_back(Implicit); 3461 ErrorFound |= 3462 cast<OMPMapClause>(Implicit)->varlist_size() != ImplicitMaps.size(); 3463 } else { 3464 ErrorFound = true; 3465 } 3466 } 3467 } 3468 3469 llvm::SmallVector<OpenMPDirectiveKind, 4> AllowedNameModifiers; 3470 switch (Kind) { 3471 case OMPD_parallel: 3472 Res = ActOnOpenMPParallelDirective(ClausesWithImplicit, AStmt, StartLoc, 3473 EndLoc); 3474 AllowedNameModifiers.push_back(OMPD_parallel); 3475 break; 3476 case OMPD_simd: 3477 Res = ActOnOpenMPSimdDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc, 3478 VarsWithInheritedDSA); 3479 break; 3480 case OMPD_for: 3481 Res = ActOnOpenMPForDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc, 3482 VarsWithInheritedDSA); 3483 break; 3484 case OMPD_for_simd: 3485 Res = ActOnOpenMPForSimdDirective(ClausesWithImplicit, AStmt, StartLoc, 3486 EndLoc, VarsWithInheritedDSA); 3487 break; 3488 case OMPD_sections: 3489 Res = ActOnOpenMPSectionsDirective(ClausesWithImplicit, AStmt, StartLoc, 3490 EndLoc); 3491 break; 3492 case OMPD_section: 3493 assert(ClausesWithImplicit.empty() && 3494 "No clauses are allowed for 'omp section' directive"); 3495 Res = ActOnOpenMPSectionDirective(AStmt, StartLoc, EndLoc); 3496 break; 3497 case OMPD_single: 3498 Res = ActOnOpenMPSingleDirective(ClausesWithImplicit, AStmt, StartLoc, 3499 EndLoc); 3500 break; 3501 case OMPD_master: 3502 assert(ClausesWithImplicit.empty() && 3503 "No clauses are allowed for 'omp master' directive"); 3504 Res = ActOnOpenMPMasterDirective(AStmt, StartLoc, EndLoc); 3505 break; 3506 case OMPD_critical: 3507 Res = ActOnOpenMPCriticalDirective(DirName, ClausesWithImplicit, AStmt, 3508 StartLoc, EndLoc); 3509 break; 3510 case OMPD_parallel_for: 3511 Res = ActOnOpenMPParallelForDirective(ClausesWithImplicit, AStmt, StartLoc, 3512 EndLoc, VarsWithInheritedDSA); 3513 AllowedNameModifiers.push_back(OMPD_parallel); 3514 break; 3515 case OMPD_parallel_for_simd: 3516 Res = ActOnOpenMPParallelForSimdDirective( 3517 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA); 3518 AllowedNameModifiers.push_back(OMPD_parallel); 3519 break; 3520 case OMPD_parallel_sections: 3521 Res = ActOnOpenMPParallelSectionsDirective(ClausesWithImplicit, AStmt, 3522 StartLoc, EndLoc); 3523 AllowedNameModifiers.push_back(OMPD_parallel); 3524 break; 3525 case OMPD_task: 3526 Res = 3527 ActOnOpenMPTaskDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc); 3528 AllowedNameModifiers.push_back(OMPD_task); 3529 break; 3530 case OMPD_taskyield: 3531 assert(ClausesWithImplicit.empty() && 3532 "No clauses are allowed for 'omp taskyield' directive"); 3533 assert(AStmt == nullptr && 3534 "No associated statement allowed for 'omp taskyield' directive"); 3535 Res = ActOnOpenMPTaskyieldDirective(StartLoc, EndLoc); 3536 break; 3537 case OMPD_barrier: 3538 assert(ClausesWithImplicit.empty() && 3539 "No clauses are allowed for 'omp barrier' directive"); 3540 assert(AStmt == nullptr && 3541 "No associated statement allowed for 'omp barrier' directive"); 3542 Res = ActOnOpenMPBarrierDirective(StartLoc, EndLoc); 3543 break; 3544 case OMPD_taskwait: 3545 assert(ClausesWithImplicit.empty() && 3546 "No clauses are allowed for 'omp taskwait' directive"); 3547 assert(AStmt == nullptr && 3548 "No associated statement allowed for 'omp taskwait' directive"); 3549 Res = ActOnOpenMPTaskwaitDirective(StartLoc, EndLoc); 3550 break; 3551 case OMPD_taskgroup: 3552 Res = ActOnOpenMPTaskgroupDirective(ClausesWithImplicit, AStmt, StartLoc, 3553 EndLoc); 3554 break; 3555 case OMPD_flush: 3556 assert(AStmt == nullptr && 3557 "No associated statement allowed for 'omp flush' directive"); 3558 Res = ActOnOpenMPFlushDirective(ClausesWithImplicit, StartLoc, EndLoc); 3559 break; 3560 case OMPD_ordered: 3561 Res = ActOnOpenMPOrderedDirective(ClausesWithImplicit, AStmt, StartLoc, 3562 EndLoc); 3563 break; 3564 case OMPD_atomic: 3565 Res = ActOnOpenMPAtomicDirective(ClausesWithImplicit, AStmt, StartLoc, 3566 EndLoc); 3567 break; 3568 case OMPD_teams: 3569 Res = 3570 ActOnOpenMPTeamsDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc); 3571 break; 3572 case OMPD_target: 3573 Res = ActOnOpenMPTargetDirective(ClausesWithImplicit, AStmt, StartLoc, 3574 EndLoc); 3575 AllowedNameModifiers.push_back(OMPD_target); 3576 break; 3577 case OMPD_target_parallel: 3578 Res = ActOnOpenMPTargetParallelDirective(ClausesWithImplicit, AStmt, 3579 StartLoc, EndLoc); 3580 AllowedNameModifiers.push_back(OMPD_target); 3581 AllowedNameModifiers.push_back(OMPD_parallel); 3582 break; 3583 case OMPD_target_parallel_for: 3584 Res = ActOnOpenMPTargetParallelForDirective( 3585 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA); 3586 AllowedNameModifiers.push_back(OMPD_target); 3587 AllowedNameModifiers.push_back(OMPD_parallel); 3588 break; 3589 case OMPD_cancellation_point: 3590 assert(ClausesWithImplicit.empty() && 3591 "No clauses are allowed for 'omp cancellation point' directive"); 3592 assert(AStmt == nullptr && "No associated statement allowed for 'omp " 3593 "cancellation point' directive"); 3594 Res = ActOnOpenMPCancellationPointDirective(StartLoc, EndLoc, CancelRegion); 3595 break; 3596 case OMPD_cancel: 3597 assert(AStmt == nullptr && 3598 "No associated statement allowed for 'omp cancel' directive"); 3599 Res = ActOnOpenMPCancelDirective(ClausesWithImplicit, StartLoc, EndLoc, 3600 CancelRegion); 3601 AllowedNameModifiers.push_back(OMPD_cancel); 3602 break; 3603 case OMPD_target_data: 3604 Res = ActOnOpenMPTargetDataDirective(ClausesWithImplicit, AStmt, StartLoc, 3605 EndLoc); 3606 AllowedNameModifiers.push_back(OMPD_target_data); 3607 break; 3608 case OMPD_target_enter_data: 3609 Res = ActOnOpenMPTargetEnterDataDirective(ClausesWithImplicit, StartLoc, 3610 EndLoc, AStmt); 3611 AllowedNameModifiers.push_back(OMPD_target_enter_data); 3612 break; 3613 case OMPD_target_exit_data: 3614 Res = ActOnOpenMPTargetExitDataDirective(ClausesWithImplicit, StartLoc, 3615 EndLoc, AStmt); 3616 AllowedNameModifiers.push_back(OMPD_target_exit_data); 3617 break; 3618 case OMPD_taskloop: 3619 Res = ActOnOpenMPTaskLoopDirective(ClausesWithImplicit, AStmt, StartLoc, 3620 EndLoc, VarsWithInheritedDSA); 3621 AllowedNameModifiers.push_back(OMPD_taskloop); 3622 break; 3623 case OMPD_taskloop_simd: 3624 Res = ActOnOpenMPTaskLoopSimdDirective(ClausesWithImplicit, AStmt, StartLoc, 3625 EndLoc, VarsWithInheritedDSA); 3626 AllowedNameModifiers.push_back(OMPD_taskloop); 3627 break; 3628 case OMPD_distribute: 3629 Res = ActOnOpenMPDistributeDirective(ClausesWithImplicit, AStmt, StartLoc, 3630 EndLoc, VarsWithInheritedDSA); 3631 break; 3632 case OMPD_target_update: 3633 Res = ActOnOpenMPTargetUpdateDirective(ClausesWithImplicit, StartLoc, 3634 EndLoc, AStmt); 3635 AllowedNameModifiers.push_back(OMPD_target_update); 3636 break; 3637 case OMPD_distribute_parallel_for: 3638 Res = ActOnOpenMPDistributeParallelForDirective( 3639 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA); 3640 AllowedNameModifiers.push_back(OMPD_parallel); 3641 break; 3642 case OMPD_distribute_parallel_for_simd: 3643 Res = ActOnOpenMPDistributeParallelForSimdDirective( 3644 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA); 3645 AllowedNameModifiers.push_back(OMPD_parallel); 3646 break; 3647 case OMPD_distribute_simd: 3648 Res = ActOnOpenMPDistributeSimdDirective( 3649 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA); 3650 break; 3651 case OMPD_target_parallel_for_simd: 3652 Res = ActOnOpenMPTargetParallelForSimdDirective( 3653 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA); 3654 AllowedNameModifiers.push_back(OMPD_target); 3655 AllowedNameModifiers.push_back(OMPD_parallel); 3656 break; 3657 case OMPD_target_simd: 3658 Res = ActOnOpenMPTargetSimdDirective(ClausesWithImplicit, AStmt, StartLoc, 3659 EndLoc, VarsWithInheritedDSA); 3660 AllowedNameModifiers.push_back(OMPD_target); 3661 break; 3662 case OMPD_teams_distribute: 3663 Res = ActOnOpenMPTeamsDistributeDirective( 3664 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA); 3665 break; 3666 case OMPD_teams_distribute_simd: 3667 Res = ActOnOpenMPTeamsDistributeSimdDirective( 3668 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA); 3669 break; 3670 case OMPD_teams_distribute_parallel_for_simd: 3671 Res = ActOnOpenMPTeamsDistributeParallelForSimdDirective( 3672 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA); 3673 AllowedNameModifiers.push_back(OMPD_parallel); 3674 break; 3675 case OMPD_teams_distribute_parallel_for: 3676 Res = ActOnOpenMPTeamsDistributeParallelForDirective( 3677 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA); 3678 AllowedNameModifiers.push_back(OMPD_parallel); 3679 break; 3680 case OMPD_target_teams: 3681 Res = ActOnOpenMPTargetTeamsDirective(ClausesWithImplicit, AStmt, StartLoc, 3682 EndLoc); 3683 AllowedNameModifiers.push_back(OMPD_target); 3684 break; 3685 case OMPD_target_teams_distribute: 3686 Res = ActOnOpenMPTargetTeamsDistributeDirective( 3687 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA); 3688 AllowedNameModifiers.push_back(OMPD_target); 3689 break; 3690 case OMPD_target_teams_distribute_parallel_for: 3691 Res = ActOnOpenMPTargetTeamsDistributeParallelForDirective( 3692 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA); 3693 AllowedNameModifiers.push_back(OMPD_target); 3694 AllowedNameModifiers.push_back(OMPD_parallel); 3695 break; 3696 case OMPD_target_teams_distribute_parallel_for_simd: 3697 Res = ActOnOpenMPTargetTeamsDistributeParallelForSimdDirective( 3698 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA); 3699 AllowedNameModifiers.push_back(OMPD_target); 3700 AllowedNameModifiers.push_back(OMPD_parallel); 3701 break; 3702 case OMPD_target_teams_distribute_simd: 3703 Res = ActOnOpenMPTargetTeamsDistributeSimdDirective( 3704 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA); 3705 AllowedNameModifiers.push_back(OMPD_target); 3706 break; 3707 case OMPD_declare_target: 3708 case OMPD_end_declare_target: 3709 case OMPD_threadprivate: 3710 case OMPD_declare_reduction: 3711 case OMPD_declare_mapper: 3712 case OMPD_declare_simd: 3713 case OMPD_requires: 3714 llvm_unreachable("OpenMP Directive is not allowed"); 3715 case OMPD_unknown: 3716 llvm_unreachable("Unknown OpenMP directive"); 3717 } 3718 3719 for (const auto &P : VarsWithInheritedDSA) { 3720 Diag(P.second->getExprLoc(), diag::err_omp_no_dsa_for_variable) 3721 << P.first << P.second->getSourceRange(); 3722 } 3723 ErrorFound = !VarsWithInheritedDSA.empty() || ErrorFound; 3724 3725 if (!AllowedNameModifiers.empty()) 3726 ErrorFound = checkIfClauses(*this, Kind, Clauses, AllowedNameModifiers) || 3727 ErrorFound; 3728 3729 if (ErrorFound) 3730 return StmtError(); 3731 return Res; 3732 } 3733 3734 Sema::DeclGroupPtrTy Sema::ActOnOpenMPDeclareSimdDirective( 3735 DeclGroupPtrTy DG, OMPDeclareSimdDeclAttr::BranchStateTy BS, Expr *Simdlen, 3736 ArrayRef<Expr *> Uniforms, ArrayRef<Expr *> Aligneds, 3737 ArrayRef<Expr *> Alignments, ArrayRef<Expr *> Linears, 3738 ArrayRef<unsigned> LinModifiers, ArrayRef<Expr *> Steps, SourceRange SR) { 3739 assert(Aligneds.size() == Alignments.size()); 3740 assert(Linears.size() == LinModifiers.size()); 3741 assert(Linears.size() == Steps.size()); 3742 if (!DG || DG.get().isNull()) 3743 return DeclGroupPtrTy(); 3744 3745 if (!DG.get().isSingleDecl()) { 3746 Diag(SR.getBegin(), diag::err_omp_single_decl_in_declare_simd); 3747 return DG; 3748 } 3749 Decl *ADecl = DG.get().getSingleDecl(); 3750 if (auto *FTD = dyn_cast<FunctionTemplateDecl>(ADecl)) 3751 ADecl = FTD->getTemplatedDecl(); 3752 3753 auto *FD = dyn_cast<FunctionDecl>(ADecl); 3754 if (!FD) { 3755 Diag(ADecl->getLocation(), diag::err_omp_function_expected); 3756 return DeclGroupPtrTy(); 3757 } 3758 3759 // OpenMP [2.8.2, declare simd construct, Description] 3760 // The parameter of the simdlen clause must be a constant positive integer 3761 // expression. 3762 ExprResult SL; 3763 if (Simdlen) 3764 SL = VerifyPositiveIntegerConstantInClause(Simdlen, OMPC_simdlen); 3765 // OpenMP [2.8.2, declare simd construct, Description] 3766 // The special this pointer can be used as if was one of the arguments to the 3767 // function in any of the linear, aligned, or uniform clauses. 3768 // The uniform clause declares one or more arguments to have an invariant 3769 // value for all concurrent invocations of the function in the execution of a 3770 // single SIMD loop. 3771 llvm::DenseMap<const Decl *, const Expr *> UniformedArgs; 3772 const Expr *UniformedLinearThis = nullptr; 3773 for (const Expr *E : Uniforms) { 3774 E = E->IgnoreParenImpCasts(); 3775 if (const auto *DRE = dyn_cast<DeclRefExpr>(E)) 3776 if (const auto *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl())) 3777 if (FD->getNumParams() > PVD->getFunctionScopeIndex() && 3778 FD->getParamDecl(PVD->getFunctionScopeIndex()) 3779 ->getCanonicalDecl() == PVD->getCanonicalDecl()) { 3780 UniformedArgs.try_emplace(PVD->getCanonicalDecl(), E); 3781 continue; 3782 } 3783 if (isa<CXXThisExpr>(E)) { 3784 UniformedLinearThis = E; 3785 continue; 3786 } 3787 Diag(E->getExprLoc(), diag::err_omp_param_or_this_in_clause) 3788 << FD->getDeclName() << (isa<CXXMethodDecl>(ADecl) ? 1 : 0); 3789 } 3790 // OpenMP [2.8.2, declare simd construct, Description] 3791 // The aligned clause declares that the object to which each list item points 3792 // is aligned to the number of bytes expressed in the optional parameter of 3793 // the aligned clause. 3794 // The special this pointer can be used as if was one of the arguments to the 3795 // function in any of the linear, aligned, or uniform clauses. 3796 // The type of list items appearing in the aligned clause must be array, 3797 // pointer, reference to array, or reference to pointer. 3798 llvm::DenseMap<const Decl *, const Expr *> AlignedArgs; 3799 const Expr *AlignedThis = nullptr; 3800 for (const Expr *E : Aligneds) { 3801 E = E->IgnoreParenImpCasts(); 3802 if (const auto *DRE = dyn_cast<DeclRefExpr>(E)) 3803 if (const auto *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl())) { 3804 const VarDecl *CanonPVD = PVD->getCanonicalDecl(); 3805 if (FD->getNumParams() > PVD->getFunctionScopeIndex() && 3806 FD->getParamDecl(PVD->getFunctionScopeIndex()) 3807 ->getCanonicalDecl() == CanonPVD) { 3808 // OpenMP [2.8.1, simd construct, Restrictions] 3809 // A list-item cannot appear in more than one aligned clause. 3810 if (AlignedArgs.count(CanonPVD) > 0) { 3811 Diag(E->getExprLoc(), diag::err_omp_aligned_twice) 3812 << 1 << E->getSourceRange(); 3813 Diag(AlignedArgs[CanonPVD]->getExprLoc(), 3814 diag::note_omp_explicit_dsa) 3815 << getOpenMPClauseName(OMPC_aligned); 3816 continue; 3817 } 3818 AlignedArgs[CanonPVD] = E; 3819 QualType QTy = PVD->getType() 3820 .getNonReferenceType() 3821 .getUnqualifiedType() 3822 .getCanonicalType(); 3823 const Type *Ty = QTy.getTypePtrOrNull(); 3824 if (!Ty || (!Ty->isArrayType() && !Ty->isPointerType())) { 3825 Diag(E->getExprLoc(), diag::err_omp_aligned_expected_array_or_ptr) 3826 << QTy << getLangOpts().CPlusPlus << E->getSourceRange(); 3827 Diag(PVD->getLocation(), diag::note_previous_decl) << PVD; 3828 } 3829 continue; 3830 } 3831 } 3832 if (isa<CXXThisExpr>(E)) { 3833 if (AlignedThis) { 3834 Diag(E->getExprLoc(), diag::err_omp_aligned_twice) 3835 << 2 << E->getSourceRange(); 3836 Diag(AlignedThis->getExprLoc(), diag::note_omp_explicit_dsa) 3837 << getOpenMPClauseName(OMPC_aligned); 3838 } 3839 AlignedThis = E; 3840 continue; 3841 } 3842 Diag(E->getExprLoc(), diag::err_omp_param_or_this_in_clause) 3843 << FD->getDeclName() << (isa<CXXMethodDecl>(ADecl) ? 1 : 0); 3844 } 3845 // The optional parameter of the aligned clause, alignment, must be a constant 3846 // positive integer expression. If no optional parameter is specified, 3847 // implementation-defined default alignments for SIMD instructions on the 3848 // target platforms are assumed. 3849 SmallVector<const Expr *, 4> NewAligns; 3850 for (Expr *E : Alignments) { 3851 ExprResult Align; 3852 if (E) 3853 Align = VerifyPositiveIntegerConstantInClause(E, OMPC_aligned); 3854 NewAligns.push_back(Align.get()); 3855 } 3856 // OpenMP [2.8.2, declare simd construct, Description] 3857 // The linear clause declares one or more list items to be private to a SIMD 3858 // lane and to have a linear relationship with respect to the iteration space 3859 // of a loop. 3860 // The special this pointer can be used as if was one of the arguments to the 3861 // function in any of the linear, aligned, or uniform clauses. 3862 // When a linear-step expression is specified in a linear clause it must be 3863 // either a constant integer expression or an integer-typed parameter that is 3864 // specified in a uniform clause on the directive. 3865 llvm::DenseMap<const Decl *, const Expr *> LinearArgs; 3866 const bool IsUniformedThis = UniformedLinearThis != nullptr; 3867 auto MI = LinModifiers.begin(); 3868 for (const Expr *E : Linears) { 3869 auto LinKind = static_cast<OpenMPLinearClauseKind>(*MI); 3870 ++MI; 3871 E = E->IgnoreParenImpCasts(); 3872 if (const auto *DRE = dyn_cast<DeclRefExpr>(E)) 3873 if (const auto *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl())) { 3874 const VarDecl *CanonPVD = PVD->getCanonicalDecl(); 3875 if (FD->getNumParams() > PVD->getFunctionScopeIndex() && 3876 FD->getParamDecl(PVD->getFunctionScopeIndex()) 3877 ->getCanonicalDecl() == CanonPVD) { 3878 // OpenMP [2.15.3.7, linear Clause, Restrictions] 3879 // A list-item cannot appear in more than one linear clause. 3880 if (LinearArgs.count(CanonPVD) > 0) { 3881 Diag(E->getExprLoc(), diag::err_omp_wrong_dsa) 3882 << getOpenMPClauseName(OMPC_linear) 3883 << getOpenMPClauseName(OMPC_linear) << E->getSourceRange(); 3884 Diag(LinearArgs[CanonPVD]->getExprLoc(), 3885 diag::note_omp_explicit_dsa) 3886 << getOpenMPClauseName(OMPC_linear); 3887 continue; 3888 } 3889 // Each argument can appear in at most one uniform or linear clause. 3890 if (UniformedArgs.count(CanonPVD) > 0) { 3891 Diag(E->getExprLoc(), diag::err_omp_wrong_dsa) 3892 << getOpenMPClauseName(OMPC_linear) 3893 << getOpenMPClauseName(OMPC_uniform) << E->getSourceRange(); 3894 Diag(UniformedArgs[CanonPVD]->getExprLoc(), 3895 diag::note_omp_explicit_dsa) 3896 << getOpenMPClauseName(OMPC_uniform); 3897 continue; 3898 } 3899 LinearArgs[CanonPVD] = E; 3900 if (E->isValueDependent() || E->isTypeDependent() || 3901 E->isInstantiationDependent() || 3902 E->containsUnexpandedParameterPack()) 3903 continue; 3904 (void)CheckOpenMPLinearDecl(CanonPVD, E->getExprLoc(), LinKind, 3905 PVD->getOriginalType()); 3906 continue; 3907 } 3908 } 3909 if (isa<CXXThisExpr>(E)) { 3910 if (UniformedLinearThis) { 3911 Diag(E->getExprLoc(), diag::err_omp_wrong_dsa) 3912 << getOpenMPClauseName(OMPC_linear) 3913 << getOpenMPClauseName(IsUniformedThis ? OMPC_uniform : OMPC_linear) 3914 << E->getSourceRange(); 3915 Diag(UniformedLinearThis->getExprLoc(), diag::note_omp_explicit_dsa) 3916 << getOpenMPClauseName(IsUniformedThis ? OMPC_uniform 3917 : OMPC_linear); 3918 continue; 3919 } 3920 UniformedLinearThis = E; 3921 if (E->isValueDependent() || E->isTypeDependent() || 3922 E->isInstantiationDependent() || E->containsUnexpandedParameterPack()) 3923 continue; 3924 (void)CheckOpenMPLinearDecl(/*D=*/nullptr, E->getExprLoc(), LinKind, 3925 E->getType()); 3926 continue; 3927 } 3928 Diag(E->getExprLoc(), diag::err_omp_param_or_this_in_clause) 3929 << FD->getDeclName() << (isa<CXXMethodDecl>(ADecl) ? 1 : 0); 3930 } 3931 Expr *Step = nullptr; 3932 Expr *NewStep = nullptr; 3933 SmallVector<Expr *, 4> NewSteps; 3934 for (Expr *E : Steps) { 3935 // Skip the same step expression, it was checked already. 3936 if (Step == E || !E) { 3937 NewSteps.push_back(E ? NewStep : nullptr); 3938 continue; 3939 } 3940 Step = E; 3941 if (const auto *DRE = dyn_cast<DeclRefExpr>(Step)) 3942 if (const auto *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl())) { 3943 const VarDecl *CanonPVD = PVD->getCanonicalDecl(); 3944 if (UniformedArgs.count(CanonPVD) == 0) { 3945 Diag(Step->getExprLoc(), diag::err_omp_expected_uniform_param) 3946 << Step->getSourceRange(); 3947 } else if (E->isValueDependent() || E->isTypeDependent() || 3948 E->isInstantiationDependent() || 3949 E->containsUnexpandedParameterPack() || 3950 CanonPVD->getType()->hasIntegerRepresentation()) { 3951 NewSteps.push_back(Step); 3952 } else { 3953 Diag(Step->getExprLoc(), diag::err_omp_expected_int_param) 3954 << Step->getSourceRange(); 3955 } 3956 continue; 3957 } 3958 NewStep = Step; 3959 if (Step && !Step->isValueDependent() && !Step->isTypeDependent() && 3960 !Step->isInstantiationDependent() && 3961 !Step->containsUnexpandedParameterPack()) { 3962 NewStep = PerformOpenMPImplicitIntegerConversion(Step->getExprLoc(), Step) 3963 .get(); 3964 if (NewStep) 3965 NewStep = VerifyIntegerConstantExpression(NewStep).get(); 3966 } 3967 NewSteps.push_back(NewStep); 3968 } 3969 auto *NewAttr = OMPDeclareSimdDeclAttr::CreateImplicit( 3970 Context, BS, SL.get(), const_cast<Expr **>(Uniforms.data()), 3971 Uniforms.size(), const_cast<Expr **>(Aligneds.data()), Aligneds.size(), 3972 const_cast<Expr **>(NewAligns.data()), NewAligns.size(), 3973 const_cast<Expr **>(Linears.data()), Linears.size(), 3974 const_cast<unsigned *>(LinModifiers.data()), LinModifiers.size(), 3975 NewSteps.data(), NewSteps.size(), SR); 3976 ADecl->addAttr(NewAttr); 3977 return ConvertDeclToDeclGroup(ADecl); 3978 } 3979 3980 StmtResult Sema::ActOnOpenMPParallelDirective(ArrayRef<OMPClause *> Clauses, 3981 Stmt *AStmt, 3982 SourceLocation StartLoc, 3983 SourceLocation EndLoc) { 3984 if (!AStmt) 3985 return StmtError(); 3986 3987 auto *CS = cast<CapturedStmt>(AStmt); 3988 // 1.2.2 OpenMP Language Terminology 3989 // Structured block - An executable statement with a single entry at the 3990 // top and a single exit at the bottom. 3991 // The point of exit cannot be a branch out of the structured block. 3992 // longjmp() and throw() must not violate the entry/exit criteria. 3993 CS->getCapturedDecl()->setNothrow(); 3994 3995 setFunctionHasBranchProtectedScope(); 3996 3997 return OMPParallelDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt, 3998 DSAStack->isCancelRegion()); 3999 } 4000 4001 namespace { 4002 /// Helper class for checking canonical form of the OpenMP loops and 4003 /// extracting iteration space of each loop in the loop nest, that will be used 4004 /// for IR generation. 4005 class OpenMPIterationSpaceChecker { 4006 /// Reference to Sema. 4007 Sema &SemaRef; 4008 /// A location for diagnostics (when there is no some better location). 4009 SourceLocation DefaultLoc; 4010 /// A location for diagnostics (when increment is not compatible). 4011 SourceLocation ConditionLoc; 4012 /// A source location for referring to loop init later. 4013 SourceRange InitSrcRange; 4014 /// A source location for referring to condition later. 4015 SourceRange ConditionSrcRange; 4016 /// A source location for referring to increment later. 4017 SourceRange IncrementSrcRange; 4018 /// Loop variable. 4019 ValueDecl *LCDecl = nullptr; 4020 /// Reference to loop variable. 4021 Expr *LCRef = nullptr; 4022 /// Lower bound (initializer for the var). 4023 Expr *LB = nullptr; 4024 /// Upper bound. 4025 Expr *UB = nullptr; 4026 /// Loop step (increment). 4027 Expr *Step = nullptr; 4028 /// This flag is true when condition is one of: 4029 /// Var < UB 4030 /// Var <= UB 4031 /// UB > Var 4032 /// UB >= Var 4033 /// This will have no value when the condition is != 4034 llvm::Optional<bool> TestIsLessOp; 4035 /// This flag is true when condition is strict ( < or > ). 4036 bool TestIsStrictOp = false; 4037 /// This flag is true when step is subtracted on each iteration. 4038 bool SubtractStep = false; 4039 4040 public: 4041 OpenMPIterationSpaceChecker(Sema &SemaRef, SourceLocation DefaultLoc) 4042 : SemaRef(SemaRef), DefaultLoc(DefaultLoc), ConditionLoc(DefaultLoc) {} 4043 /// Check init-expr for canonical loop form and save loop counter 4044 /// variable - #Var and its initialization value - #LB. 4045 bool checkAndSetInit(Stmt *S, bool EmitDiags = true); 4046 /// Check test-expr for canonical form, save upper-bound (#UB), flags 4047 /// for less/greater and for strict/non-strict comparison. 4048 bool checkAndSetCond(Expr *S); 4049 /// Check incr-expr for canonical loop form and return true if it 4050 /// does not conform, otherwise save loop step (#Step). 4051 bool checkAndSetInc(Expr *S); 4052 /// Return the loop counter variable. 4053 ValueDecl *getLoopDecl() const { return LCDecl; } 4054 /// Return the reference expression to loop counter variable. 4055 Expr *getLoopDeclRefExpr() const { return LCRef; } 4056 /// Source range of the loop init. 4057 SourceRange getInitSrcRange() const { return InitSrcRange; } 4058 /// Source range of the loop condition. 4059 SourceRange getConditionSrcRange() const { return ConditionSrcRange; } 4060 /// Source range of the loop increment. 4061 SourceRange getIncrementSrcRange() const { return IncrementSrcRange; } 4062 /// True if the step should be subtracted. 4063 bool shouldSubtractStep() const { return SubtractStep; } 4064 /// True, if the compare operator is strict (<, > or !=). 4065 bool isStrictTestOp() const { return TestIsStrictOp; } 4066 /// Build the expression to calculate the number of iterations. 4067 Expr *buildNumIterations( 4068 Scope *S, const bool LimitedType, 4069 llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) const; 4070 /// Build the precondition expression for the loops. 4071 Expr * 4072 buildPreCond(Scope *S, Expr *Cond, 4073 llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) const; 4074 /// Build reference expression to the counter be used for codegen. 4075 DeclRefExpr * 4076 buildCounterVar(llvm::MapVector<const Expr *, DeclRefExpr *> &Captures, 4077 DSAStackTy &DSA) const; 4078 /// Build reference expression to the private counter be used for 4079 /// codegen. 4080 Expr *buildPrivateCounterVar() const; 4081 /// Build initialization of the counter be used for codegen. 4082 Expr *buildCounterInit() const; 4083 /// Build step of the counter be used for codegen. 4084 Expr *buildCounterStep() const; 4085 /// Build loop data with counter value for depend clauses in ordered 4086 /// directives. 4087 Expr * 4088 buildOrderedLoopData(Scope *S, Expr *Counter, 4089 llvm::MapVector<const Expr *, DeclRefExpr *> &Captures, 4090 SourceLocation Loc, Expr *Inc = nullptr, 4091 OverloadedOperatorKind OOK = OO_Amp); 4092 /// Return true if any expression is dependent. 4093 bool dependent() const; 4094 4095 private: 4096 /// Check the right-hand side of an assignment in the increment 4097 /// expression. 4098 bool checkAndSetIncRHS(Expr *RHS); 4099 /// Helper to set loop counter variable and its initializer. 4100 bool setLCDeclAndLB(ValueDecl *NewLCDecl, Expr *NewDeclRefExpr, Expr *NewLB); 4101 /// Helper to set upper bound. 4102 bool setUB(Expr *NewUB, llvm::Optional<bool> LessOp, bool StrictOp, 4103 SourceRange SR, SourceLocation SL); 4104 /// Helper to set loop increment. 4105 bool setStep(Expr *NewStep, bool Subtract); 4106 }; 4107 4108 bool OpenMPIterationSpaceChecker::dependent() const { 4109 if (!LCDecl) { 4110 assert(!LB && !UB && !Step); 4111 return false; 4112 } 4113 return LCDecl->getType()->isDependentType() || 4114 (LB && LB->isValueDependent()) || (UB && UB->isValueDependent()) || 4115 (Step && Step->isValueDependent()); 4116 } 4117 4118 bool OpenMPIterationSpaceChecker::setLCDeclAndLB(ValueDecl *NewLCDecl, 4119 Expr *NewLCRefExpr, 4120 Expr *NewLB) { 4121 // State consistency checking to ensure correct usage. 4122 assert(LCDecl == nullptr && LB == nullptr && LCRef == nullptr && 4123 UB == nullptr && Step == nullptr && !TestIsLessOp && !TestIsStrictOp); 4124 if (!NewLCDecl || !NewLB) 4125 return true; 4126 LCDecl = getCanonicalDecl(NewLCDecl); 4127 LCRef = NewLCRefExpr; 4128 if (auto *CE = dyn_cast_or_null<CXXConstructExpr>(NewLB)) 4129 if (const CXXConstructorDecl *Ctor = CE->getConstructor()) 4130 if ((Ctor->isCopyOrMoveConstructor() || 4131 Ctor->isConvertingConstructor(/*AllowExplicit=*/false)) && 4132 CE->getNumArgs() > 0 && CE->getArg(0) != nullptr) 4133 NewLB = CE->getArg(0)->IgnoreParenImpCasts(); 4134 LB = NewLB; 4135 return false; 4136 } 4137 4138 bool OpenMPIterationSpaceChecker::setUB(Expr *NewUB, 4139 llvm::Optional<bool> LessOp, 4140 bool StrictOp, SourceRange SR, 4141 SourceLocation SL) { 4142 // State consistency checking to ensure correct usage. 4143 assert(LCDecl != nullptr && LB != nullptr && UB == nullptr && 4144 Step == nullptr && !TestIsLessOp && !TestIsStrictOp); 4145 if (!NewUB) 4146 return true; 4147 UB = NewUB; 4148 if (LessOp) 4149 TestIsLessOp = LessOp; 4150 TestIsStrictOp = StrictOp; 4151 ConditionSrcRange = SR; 4152 ConditionLoc = SL; 4153 return false; 4154 } 4155 4156 bool OpenMPIterationSpaceChecker::setStep(Expr *NewStep, bool Subtract) { 4157 // State consistency checking to ensure correct usage. 4158 assert(LCDecl != nullptr && LB != nullptr && Step == nullptr); 4159 if (!NewStep) 4160 return true; 4161 if (!NewStep->isValueDependent()) { 4162 // Check that the step is integer expression. 4163 SourceLocation StepLoc = NewStep->getBeginLoc(); 4164 ExprResult Val = SemaRef.PerformOpenMPImplicitIntegerConversion( 4165 StepLoc, getExprAsWritten(NewStep)); 4166 if (Val.isInvalid()) 4167 return true; 4168 NewStep = Val.get(); 4169 4170 // OpenMP [2.6, Canonical Loop Form, Restrictions] 4171 // If test-expr is of form var relational-op b and relational-op is < or 4172 // <= then incr-expr must cause var to increase on each iteration of the 4173 // loop. If test-expr is of form var relational-op b and relational-op is 4174 // > or >= then incr-expr must cause var to decrease on each iteration of 4175 // the loop. 4176 // If test-expr is of form b relational-op var and relational-op is < or 4177 // <= then incr-expr must cause var to decrease on each iteration of the 4178 // loop. If test-expr is of form b relational-op var and relational-op is 4179 // > or >= then incr-expr must cause var to increase on each iteration of 4180 // the loop. 4181 llvm::APSInt Result; 4182 bool IsConstant = NewStep->isIntegerConstantExpr(Result, SemaRef.Context); 4183 bool IsUnsigned = !NewStep->getType()->hasSignedIntegerRepresentation(); 4184 bool IsConstNeg = 4185 IsConstant && Result.isSigned() && (Subtract != Result.isNegative()); 4186 bool IsConstPos = 4187 IsConstant && Result.isSigned() && (Subtract == Result.isNegative()); 4188 bool IsConstZero = IsConstant && !Result.getBoolValue(); 4189 4190 // != with increment is treated as <; != with decrement is treated as > 4191 if (!TestIsLessOp.hasValue()) 4192 TestIsLessOp = IsConstPos || (IsUnsigned && !Subtract); 4193 if (UB && (IsConstZero || 4194 (TestIsLessOp.getValue() ? 4195 (IsConstNeg || (IsUnsigned && Subtract)) : 4196 (IsConstPos || (IsUnsigned && !Subtract))))) { 4197 SemaRef.Diag(NewStep->getExprLoc(), 4198 diag::err_omp_loop_incr_not_compatible) 4199 << LCDecl << TestIsLessOp.getValue() << NewStep->getSourceRange(); 4200 SemaRef.Diag(ConditionLoc, 4201 diag::note_omp_loop_cond_requres_compatible_incr) 4202 << TestIsLessOp.getValue() << ConditionSrcRange; 4203 return true; 4204 } 4205 if (TestIsLessOp.getValue() == Subtract) { 4206 NewStep = 4207 SemaRef.CreateBuiltinUnaryOp(NewStep->getExprLoc(), UO_Minus, NewStep) 4208 .get(); 4209 Subtract = !Subtract; 4210 } 4211 } 4212 4213 Step = NewStep; 4214 SubtractStep = Subtract; 4215 return false; 4216 } 4217 4218 bool OpenMPIterationSpaceChecker::checkAndSetInit(Stmt *S, bool EmitDiags) { 4219 // Check init-expr for canonical loop form and save loop counter 4220 // variable - #Var and its initialization value - #LB. 4221 // OpenMP [2.6] Canonical loop form. init-expr may be one of the following: 4222 // var = lb 4223 // integer-type var = lb 4224 // random-access-iterator-type var = lb 4225 // pointer-type var = lb 4226 // 4227 if (!S) { 4228 if (EmitDiags) { 4229 SemaRef.Diag(DefaultLoc, diag::err_omp_loop_not_canonical_init); 4230 } 4231 return true; 4232 } 4233 if (auto *ExprTemp = dyn_cast<ExprWithCleanups>(S)) 4234 if (!ExprTemp->cleanupsHaveSideEffects()) 4235 S = ExprTemp->getSubExpr(); 4236 4237 InitSrcRange = S->getSourceRange(); 4238 if (Expr *E = dyn_cast<Expr>(S)) 4239 S = E->IgnoreParens(); 4240 if (auto *BO = dyn_cast<BinaryOperator>(S)) { 4241 if (BO->getOpcode() == BO_Assign) { 4242 Expr *LHS = BO->getLHS()->IgnoreParens(); 4243 if (auto *DRE = dyn_cast<DeclRefExpr>(LHS)) { 4244 if (auto *CED = dyn_cast<OMPCapturedExprDecl>(DRE->getDecl())) 4245 if (auto *ME = dyn_cast<MemberExpr>(getExprAsWritten(CED->getInit()))) 4246 return setLCDeclAndLB(ME->getMemberDecl(), ME, BO->getRHS()); 4247 return setLCDeclAndLB(DRE->getDecl(), DRE, BO->getRHS()); 4248 } 4249 if (auto *ME = dyn_cast<MemberExpr>(LHS)) { 4250 if (ME->isArrow() && 4251 isa<CXXThisExpr>(ME->getBase()->IgnoreParenImpCasts())) 4252 return setLCDeclAndLB(ME->getMemberDecl(), ME, BO->getRHS()); 4253 } 4254 } 4255 } else if (auto *DS = dyn_cast<DeclStmt>(S)) { 4256 if (DS->isSingleDecl()) { 4257 if (auto *Var = dyn_cast_or_null<VarDecl>(DS->getSingleDecl())) { 4258 if (Var->hasInit() && !Var->getType()->isReferenceType()) { 4259 // Accept non-canonical init form here but emit ext. warning. 4260 if (Var->getInitStyle() != VarDecl::CInit && EmitDiags) 4261 SemaRef.Diag(S->getBeginLoc(), 4262 diag::ext_omp_loop_not_canonical_init) 4263 << S->getSourceRange(); 4264 return setLCDeclAndLB( 4265 Var, 4266 buildDeclRefExpr(SemaRef, Var, 4267 Var->getType().getNonReferenceType(), 4268 DS->getBeginLoc()), 4269 Var->getInit()); 4270 } 4271 } 4272 } 4273 } else if (auto *CE = dyn_cast<CXXOperatorCallExpr>(S)) { 4274 if (CE->getOperator() == OO_Equal) { 4275 Expr *LHS = CE->getArg(0); 4276 if (auto *DRE = dyn_cast<DeclRefExpr>(LHS)) { 4277 if (auto *CED = dyn_cast<OMPCapturedExprDecl>(DRE->getDecl())) 4278 if (auto *ME = dyn_cast<MemberExpr>(getExprAsWritten(CED->getInit()))) 4279 return setLCDeclAndLB(ME->getMemberDecl(), ME, BO->getRHS()); 4280 return setLCDeclAndLB(DRE->getDecl(), DRE, CE->getArg(1)); 4281 } 4282 if (auto *ME = dyn_cast<MemberExpr>(LHS)) { 4283 if (ME->isArrow() && 4284 isa<CXXThisExpr>(ME->getBase()->IgnoreParenImpCasts())) 4285 return setLCDeclAndLB(ME->getMemberDecl(), ME, BO->getRHS()); 4286 } 4287 } 4288 } 4289 4290 if (dependent() || SemaRef.CurContext->isDependentContext()) 4291 return false; 4292 if (EmitDiags) { 4293 SemaRef.Diag(S->getBeginLoc(), diag::err_omp_loop_not_canonical_init) 4294 << S->getSourceRange(); 4295 } 4296 return true; 4297 } 4298 4299 /// Ignore parenthesizes, implicit casts, copy constructor and return the 4300 /// variable (which may be the loop variable) if possible. 4301 static const ValueDecl *getInitLCDecl(const Expr *E) { 4302 if (!E) 4303 return nullptr; 4304 E = getExprAsWritten(E); 4305 if (const auto *CE = dyn_cast_or_null<CXXConstructExpr>(E)) 4306 if (const CXXConstructorDecl *Ctor = CE->getConstructor()) 4307 if ((Ctor->isCopyOrMoveConstructor() || 4308 Ctor->isConvertingConstructor(/*AllowExplicit=*/false)) && 4309 CE->getNumArgs() > 0 && CE->getArg(0) != nullptr) 4310 E = CE->getArg(0)->IgnoreParenImpCasts(); 4311 if (const auto *DRE = dyn_cast_or_null<DeclRefExpr>(E)) { 4312 if (const auto *VD = dyn_cast<VarDecl>(DRE->getDecl())) 4313 return getCanonicalDecl(VD); 4314 } 4315 if (const auto *ME = dyn_cast_or_null<MemberExpr>(E)) 4316 if (ME->isArrow() && isa<CXXThisExpr>(ME->getBase()->IgnoreParenImpCasts())) 4317 return getCanonicalDecl(ME->getMemberDecl()); 4318 return nullptr; 4319 } 4320 4321 bool OpenMPIterationSpaceChecker::checkAndSetCond(Expr *S) { 4322 // Check test-expr for canonical form, save upper-bound UB, flags for 4323 // less/greater and for strict/non-strict comparison. 4324 // OpenMP [2.6] Canonical loop form. Test-expr may be one of the following: 4325 // var relational-op b 4326 // b relational-op var 4327 // 4328 if (!S) { 4329 SemaRef.Diag(DefaultLoc, diag::err_omp_loop_not_canonical_cond) << LCDecl; 4330 return true; 4331 } 4332 S = getExprAsWritten(S); 4333 SourceLocation CondLoc = S->getBeginLoc(); 4334 if (auto *BO = dyn_cast<BinaryOperator>(S)) { 4335 if (BO->isRelationalOp()) { 4336 if (getInitLCDecl(BO->getLHS()) == LCDecl) 4337 return setUB(BO->getRHS(), 4338 (BO->getOpcode() == BO_LT || BO->getOpcode() == BO_LE), 4339 (BO->getOpcode() == BO_LT || BO->getOpcode() == BO_GT), 4340 BO->getSourceRange(), BO->getOperatorLoc()); 4341 if (getInitLCDecl(BO->getRHS()) == LCDecl) 4342 return setUB(BO->getLHS(), 4343 (BO->getOpcode() == BO_GT || BO->getOpcode() == BO_GE), 4344 (BO->getOpcode() == BO_LT || BO->getOpcode() == BO_GT), 4345 BO->getSourceRange(), BO->getOperatorLoc()); 4346 } else if (BO->getOpcode() == BO_NE) 4347 return setUB(getInitLCDecl(BO->getLHS()) == LCDecl ? 4348 BO->getRHS() : BO->getLHS(), 4349 /*LessOp=*/llvm::None, 4350 /*StrictOp=*/true, 4351 BO->getSourceRange(), BO->getOperatorLoc()); 4352 } else if (auto *CE = dyn_cast<CXXOperatorCallExpr>(S)) { 4353 if (CE->getNumArgs() == 2) { 4354 auto Op = CE->getOperator(); 4355 switch (Op) { 4356 case OO_Greater: 4357 case OO_GreaterEqual: 4358 case OO_Less: 4359 case OO_LessEqual: 4360 if (getInitLCDecl(CE->getArg(0)) == LCDecl) 4361 return setUB(CE->getArg(1), Op == OO_Less || Op == OO_LessEqual, 4362 Op == OO_Less || Op == OO_Greater, CE->getSourceRange(), 4363 CE->getOperatorLoc()); 4364 if (getInitLCDecl(CE->getArg(1)) == LCDecl) 4365 return setUB(CE->getArg(0), Op == OO_Greater || Op == OO_GreaterEqual, 4366 Op == OO_Less || Op == OO_Greater, CE->getSourceRange(), 4367 CE->getOperatorLoc()); 4368 break; 4369 case OO_ExclaimEqual: 4370 return setUB(getInitLCDecl(CE->getArg(0)) == LCDecl ? 4371 CE->getArg(1) : CE->getArg(0), 4372 /*LessOp=*/llvm::None, 4373 /*StrictOp=*/true, 4374 CE->getSourceRange(), 4375 CE->getOperatorLoc()); 4376 break; 4377 default: 4378 break; 4379 } 4380 } 4381 } 4382 if (dependent() || SemaRef.CurContext->isDependentContext()) 4383 return false; 4384 SemaRef.Diag(CondLoc, diag::err_omp_loop_not_canonical_cond) 4385 << S->getSourceRange() << LCDecl; 4386 return true; 4387 } 4388 4389 bool OpenMPIterationSpaceChecker::checkAndSetIncRHS(Expr *RHS) { 4390 // RHS of canonical loop form increment can be: 4391 // var + incr 4392 // incr + var 4393 // var - incr 4394 // 4395 RHS = RHS->IgnoreParenImpCasts(); 4396 if (auto *BO = dyn_cast<BinaryOperator>(RHS)) { 4397 if (BO->isAdditiveOp()) { 4398 bool IsAdd = BO->getOpcode() == BO_Add; 4399 if (getInitLCDecl(BO->getLHS()) == LCDecl) 4400 return setStep(BO->getRHS(), !IsAdd); 4401 if (IsAdd && getInitLCDecl(BO->getRHS()) == LCDecl) 4402 return setStep(BO->getLHS(), /*Subtract=*/false); 4403 } 4404 } else if (auto *CE = dyn_cast<CXXOperatorCallExpr>(RHS)) { 4405 bool IsAdd = CE->getOperator() == OO_Plus; 4406 if ((IsAdd || CE->getOperator() == OO_Minus) && CE->getNumArgs() == 2) { 4407 if (getInitLCDecl(CE->getArg(0)) == LCDecl) 4408 return setStep(CE->getArg(1), !IsAdd); 4409 if (IsAdd && getInitLCDecl(CE->getArg(1)) == LCDecl) 4410 return setStep(CE->getArg(0), /*Subtract=*/false); 4411 } 4412 } 4413 if (dependent() || SemaRef.CurContext->isDependentContext()) 4414 return false; 4415 SemaRef.Diag(RHS->getBeginLoc(), diag::err_omp_loop_not_canonical_incr) 4416 << RHS->getSourceRange() << LCDecl; 4417 return true; 4418 } 4419 4420 bool OpenMPIterationSpaceChecker::checkAndSetInc(Expr *S) { 4421 // Check incr-expr for canonical loop form and return true if it 4422 // does not conform. 4423 // OpenMP [2.6] Canonical loop form. Test-expr may be one of the following: 4424 // ++var 4425 // var++ 4426 // --var 4427 // var-- 4428 // var += incr 4429 // var -= incr 4430 // var = var + incr 4431 // var = incr + var 4432 // var = var - incr 4433 // 4434 if (!S) { 4435 SemaRef.Diag(DefaultLoc, diag::err_omp_loop_not_canonical_incr) << LCDecl; 4436 return true; 4437 } 4438 if (auto *ExprTemp = dyn_cast<ExprWithCleanups>(S)) 4439 if (!ExprTemp->cleanupsHaveSideEffects()) 4440 S = ExprTemp->getSubExpr(); 4441 4442 IncrementSrcRange = S->getSourceRange(); 4443 S = S->IgnoreParens(); 4444 if (auto *UO = dyn_cast<UnaryOperator>(S)) { 4445 if (UO->isIncrementDecrementOp() && 4446 getInitLCDecl(UO->getSubExpr()) == LCDecl) 4447 return setStep(SemaRef 4448 .ActOnIntegerConstant(UO->getBeginLoc(), 4449 (UO->isDecrementOp() ? -1 : 1)) 4450 .get(), 4451 /*Subtract=*/false); 4452 } else if (auto *BO = dyn_cast<BinaryOperator>(S)) { 4453 switch (BO->getOpcode()) { 4454 case BO_AddAssign: 4455 case BO_SubAssign: 4456 if (getInitLCDecl(BO->getLHS()) == LCDecl) 4457 return setStep(BO->getRHS(), BO->getOpcode() == BO_SubAssign); 4458 break; 4459 case BO_Assign: 4460 if (getInitLCDecl(BO->getLHS()) == LCDecl) 4461 return checkAndSetIncRHS(BO->getRHS()); 4462 break; 4463 default: 4464 break; 4465 } 4466 } else if (auto *CE = dyn_cast<CXXOperatorCallExpr>(S)) { 4467 switch (CE->getOperator()) { 4468 case OO_PlusPlus: 4469 case OO_MinusMinus: 4470 if (getInitLCDecl(CE->getArg(0)) == LCDecl) 4471 return setStep(SemaRef 4472 .ActOnIntegerConstant( 4473 CE->getBeginLoc(), 4474 ((CE->getOperator() == OO_MinusMinus) ? -1 : 1)) 4475 .get(), 4476 /*Subtract=*/false); 4477 break; 4478 case OO_PlusEqual: 4479 case OO_MinusEqual: 4480 if (getInitLCDecl(CE->getArg(0)) == LCDecl) 4481 return setStep(CE->getArg(1), CE->getOperator() == OO_MinusEqual); 4482 break; 4483 case OO_Equal: 4484 if (getInitLCDecl(CE->getArg(0)) == LCDecl) 4485 return checkAndSetIncRHS(CE->getArg(1)); 4486 break; 4487 default: 4488 break; 4489 } 4490 } 4491 if (dependent() || SemaRef.CurContext->isDependentContext()) 4492 return false; 4493 SemaRef.Diag(S->getBeginLoc(), diag::err_omp_loop_not_canonical_incr) 4494 << S->getSourceRange() << LCDecl; 4495 return true; 4496 } 4497 4498 static ExprResult 4499 tryBuildCapture(Sema &SemaRef, Expr *Capture, 4500 llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) { 4501 if (SemaRef.CurContext->isDependentContext()) 4502 return ExprResult(Capture); 4503 if (Capture->isEvaluatable(SemaRef.Context, Expr::SE_AllowSideEffects)) 4504 return SemaRef.PerformImplicitConversion( 4505 Capture->IgnoreImpCasts(), Capture->getType(), Sema::AA_Converting, 4506 /*AllowExplicit=*/true); 4507 auto I = Captures.find(Capture); 4508 if (I != Captures.end()) 4509 return buildCapture(SemaRef, Capture, I->second); 4510 DeclRefExpr *Ref = nullptr; 4511 ExprResult Res = buildCapture(SemaRef, Capture, Ref); 4512 Captures[Capture] = Ref; 4513 return Res; 4514 } 4515 4516 /// Build the expression to calculate the number of iterations. 4517 Expr *OpenMPIterationSpaceChecker::buildNumIterations( 4518 Scope *S, const bool LimitedType, 4519 llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) const { 4520 ExprResult Diff; 4521 QualType VarType = LCDecl->getType().getNonReferenceType(); 4522 if (VarType->isIntegerType() || VarType->isPointerType() || 4523 SemaRef.getLangOpts().CPlusPlus) { 4524 // Upper - Lower 4525 Expr *UBExpr = TestIsLessOp.getValue() ? UB : LB; 4526 Expr *LBExpr = TestIsLessOp.getValue() ? LB : UB; 4527 Expr *Upper = tryBuildCapture(SemaRef, UBExpr, Captures).get(); 4528 Expr *Lower = tryBuildCapture(SemaRef, LBExpr, Captures).get(); 4529 if (!Upper || !Lower) 4530 return nullptr; 4531 4532 Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Sub, Upper, Lower); 4533 4534 if (!Diff.isUsable() && VarType->getAsCXXRecordDecl()) { 4535 // BuildBinOp already emitted error, this one is to point user to upper 4536 // and lower bound, and to tell what is passed to 'operator-'. 4537 SemaRef.Diag(Upper->getBeginLoc(), diag::err_omp_loop_diff_cxx) 4538 << Upper->getSourceRange() << Lower->getSourceRange(); 4539 return nullptr; 4540 } 4541 } 4542 4543 if (!Diff.isUsable()) 4544 return nullptr; 4545 4546 // Upper - Lower [- 1] 4547 if (TestIsStrictOp) 4548 Diff = SemaRef.BuildBinOp( 4549 S, DefaultLoc, BO_Sub, Diff.get(), 4550 SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get()); 4551 if (!Diff.isUsable()) 4552 return nullptr; 4553 4554 // Upper - Lower [- 1] + Step 4555 ExprResult NewStep = tryBuildCapture(SemaRef, Step, Captures); 4556 if (!NewStep.isUsable()) 4557 return nullptr; 4558 Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Add, Diff.get(), NewStep.get()); 4559 if (!Diff.isUsable()) 4560 return nullptr; 4561 4562 // Parentheses (for dumping/debugging purposes only). 4563 Diff = SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, Diff.get()); 4564 if (!Diff.isUsable()) 4565 return nullptr; 4566 4567 // (Upper - Lower [- 1] + Step) / Step 4568 Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Div, Diff.get(), NewStep.get()); 4569 if (!Diff.isUsable()) 4570 return nullptr; 4571 4572 // OpenMP runtime requires 32-bit or 64-bit loop variables. 4573 QualType Type = Diff.get()->getType(); 4574 ASTContext &C = SemaRef.Context; 4575 bool UseVarType = VarType->hasIntegerRepresentation() && 4576 C.getTypeSize(Type) > C.getTypeSize(VarType); 4577 if (!Type->isIntegerType() || UseVarType) { 4578 unsigned NewSize = 4579 UseVarType ? C.getTypeSize(VarType) : C.getTypeSize(Type); 4580 bool IsSigned = UseVarType ? VarType->hasSignedIntegerRepresentation() 4581 : Type->hasSignedIntegerRepresentation(); 4582 Type = C.getIntTypeForBitwidth(NewSize, IsSigned); 4583 if (!SemaRef.Context.hasSameType(Diff.get()->getType(), Type)) { 4584 Diff = SemaRef.PerformImplicitConversion( 4585 Diff.get(), Type, Sema::AA_Converting, /*AllowExplicit=*/true); 4586 if (!Diff.isUsable()) 4587 return nullptr; 4588 } 4589 } 4590 if (LimitedType) { 4591 unsigned NewSize = (C.getTypeSize(Type) > 32) ? 64 : 32; 4592 if (NewSize != C.getTypeSize(Type)) { 4593 if (NewSize < C.getTypeSize(Type)) { 4594 assert(NewSize == 64 && "incorrect loop var size"); 4595 SemaRef.Diag(DefaultLoc, diag::warn_omp_loop_64_bit_var) 4596 << InitSrcRange << ConditionSrcRange; 4597 } 4598 QualType NewType = C.getIntTypeForBitwidth( 4599 NewSize, Type->hasSignedIntegerRepresentation() || 4600 C.getTypeSize(Type) < NewSize); 4601 if (!SemaRef.Context.hasSameType(Diff.get()->getType(), NewType)) { 4602 Diff = SemaRef.PerformImplicitConversion(Diff.get(), NewType, 4603 Sema::AA_Converting, true); 4604 if (!Diff.isUsable()) 4605 return nullptr; 4606 } 4607 } 4608 } 4609 4610 return Diff.get(); 4611 } 4612 4613 Expr *OpenMPIterationSpaceChecker::buildPreCond( 4614 Scope *S, Expr *Cond, 4615 llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) const { 4616 // Try to build LB <op> UB, where <op> is <, >, <=, or >=. 4617 bool Suppress = SemaRef.getDiagnostics().getSuppressAllDiagnostics(); 4618 SemaRef.getDiagnostics().setSuppressAllDiagnostics(/*Val=*/true); 4619 4620 ExprResult NewLB = tryBuildCapture(SemaRef, LB, Captures); 4621 ExprResult NewUB = tryBuildCapture(SemaRef, UB, Captures); 4622 if (!NewLB.isUsable() || !NewUB.isUsable()) 4623 return nullptr; 4624 4625 ExprResult CondExpr = 4626 SemaRef.BuildBinOp(S, DefaultLoc, 4627 TestIsLessOp.getValue() ? 4628 (TestIsStrictOp ? BO_LT : BO_LE) : 4629 (TestIsStrictOp ? BO_GT : BO_GE), 4630 NewLB.get(), NewUB.get()); 4631 if (CondExpr.isUsable()) { 4632 if (!SemaRef.Context.hasSameUnqualifiedType(CondExpr.get()->getType(), 4633 SemaRef.Context.BoolTy)) 4634 CondExpr = SemaRef.PerformImplicitConversion( 4635 CondExpr.get(), SemaRef.Context.BoolTy, /*Action=*/Sema::AA_Casting, 4636 /*AllowExplicit=*/true); 4637 } 4638 SemaRef.getDiagnostics().setSuppressAllDiagnostics(Suppress); 4639 // Otherwise use original loop condition and evaluate it in runtime. 4640 return CondExpr.isUsable() ? CondExpr.get() : Cond; 4641 } 4642 4643 /// Build reference expression to the counter be used for codegen. 4644 DeclRefExpr *OpenMPIterationSpaceChecker::buildCounterVar( 4645 llvm::MapVector<const Expr *, DeclRefExpr *> &Captures, 4646 DSAStackTy &DSA) const { 4647 auto *VD = dyn_cast<VarDecl>(LCDecl); 4648 if (!VD) { 4649 VD = SemaRef.isOpenMPCapturedDecl(LCDecl); 4650 DeclRefExpr *Ref = buildDeclRefExpr( 4651 SemaRef, VD, VD->getType().getNonReferenceType(), DefaultLoc); 4652 const DSAStackTy::DSAVarData Data = 4653 DSA.getTopDSA(LCDecl, /*FromParent=*/false); 4654 // If the loop control decl is explicitly marked as private, do not mark it 4655 // as captured again. 4656 if (!isOpenMPPrivate(Data.CKind) || !Data.RefExpr) 4657 Captures.insert(std::make_pair(LCRef, Ref)); 4658 return Ref; 4659 } 4660 return buildDeclRefExpr(SemaRef, VD, VD->getType().getNonReferenceType(), 4661 DefaultLoc); 4662 } 4663 4664 Expr *OpenMPIterationSpaceChecker::buildPrivateCounterVar() const { 4665 if (LCDecl && !LCDecl->isInvalidDecl()) { 4666 QualType Type = LCDecl->getType().getNonReferenceType(); 4667 VarDecl *PrivateVar = buildVarDecl( 4668 SemaRef, DefaultLoc, Type, LCDecl->getName(), 4669 LCDecl->hasAttrs() ? &LCDecl->getAttrs() : nullptr, 4670 isa<VarDecl>(LCDecl) 4671 ? buildDeclRefExpr(SemaRef, cast<VarDecl>(LCDecl), Type, DefaultLoc) 4672 : nullptr); 4673 if (PrivateVar->isInvalidDecl()) 4674 return nullptr; 4675 return buildDeclRefExpr(SemaRef, PrivateVar, Type, DefaultLoc); 4676 } 4677 return nullptr; 4678 } 4679 4680 /// Build initialization of the counter to be used for codegen. 4681 Expr *OpenMPIterationSpaceChecker::buildCounterInit() const { return LB; } 4682 4683 /// Build step of the counter be used for codegen. 4684 Expr *OpenMPIterationSpaceChecker::buildCounterStep() const { return Step; } 4685 4686 Expr *OpenMPIterationSpaceChecker::buildOrderedLoopData( 4687 Scope *S, Expr *Counter, 4688 llvm::MapVector<const Expr *, DeclRefExpr *> &Captures, SourceLocation Loc, 4689 Expr *Inc, OverloadedOperatorKind OOK) { 4690 Expr *Cnt = SemaRef.DefaultLvalueConversion(Counter).get(); 4691 if (!Cnt) 4692 return nullptr; 4693 if (Inc) { 4694 assert((OOK == OO_Plus || OOK == OO_Minus) && 4695 "Expected only + or - operations for depend clauses."); 4696 BinaryOperatorKind BOK = (OOK == OO_Plus) ? BO_Add : BO_Sub; 4697 Cnt = SemaRef.BuildBinOp(S, Loc, BOK, Cnt, Inc).get(); 4698 if (!Cnt) 4699 return nullptr; 4700 } 4701 ExprResult Diff; 4702 QualType VarType = LCDecl->getType().getNonReferenceType(); 4703 if (VarType->isIntegerType() || VarType->isPointerType() || 4704 SemaRef.getLangOpts().CPlusPlus) { 4705 // Upper - Lower 4706 Expr *Upper = TestIsLessOp.getValue() 4707 ? Cnt 4708 : tryBuildCapture(SemaRef, UB, Captures).get(); 4709 Expr *Lower = TestIsLessOp.getValue() 4710 ? tryBuildCapture(SemaRef, LB, Captures).get() 4711 : Cnt; 4712 if (!Upper || !Lower) 4713 return nullptr; 4714 4715 Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Sub, Upper, Lower); 4716 4717 if (!Diff.isUsable() && VarType->getAsCXXRecordDecl()) { 4718 // BuildBinOp already emitted error, this one is to point user to upper 4719 // and lower bound, and to tell what is passed to 'operator-'. 4720 SemaRef.Diag(Upper->getBeginLoc(), diag::err_omp_loop_diff_cxx) 4721 << Upper->getSourceRange() << Lower->getSourceRange(); 4722 return nullptr; 4723 } 4724 } 4725 4726 if (!Diff.isUsable()) 4727 return nullptr; 4728 4729 // Parentheses (for dumping/debugging purposes only). 4730 Diff = SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, Diff.get()); 4731 if (!Diff.isUsable()) 4732 return nullptr; 4733 4734 ExprResult NewStep = tryBuildCapture(SemaRef, Step, Captures); 4735 if (!NewStep.isUsable()) 4736 return nullptr; 4737 // (Upper - Lower) / Step 4738 Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Div, Diff.get(), NewStep.get()); 4739 if (!Diff.isUsable()) 4740 return nullptr; 4741 4742 return Diff.get(); 4743 } 4744 4745 /// Iteration space of a single for loop. 4746 struct LoopIterationSpace final { 4747 /// True if the condition operator is the strict compare operator (<, > or 4748 /// !=). 4749 bool IsStrictCompare = false; 4750 /// Condition of the loop. 4751 Expr *PreCond = nullptr; 4752 /// This expression calculates the number of iterations in the loop. 4753 /// It is always possible to calculate it before starting the loop. 4754 Expr *NumIterations = nullptr; 4755 /// The loop counter variable. 4756 Expr *CounterVar = nullptr; 4757 /// Private loop counter variable. 4758 Expr *PrivateCounterVar = nullptr; 4759 /// This is initializer for the initial value of #CounterVar. 4760 Expr *CounterInit = nullptr; 4761 /// This is step for the #CounterVar used to generate its update: 4762 /// #CounterVar = #CounterInit + #CounterStep * CurrentIteration. 4763 Expr *CounterStep = nullptr; 4764 /// Should step be subtracted? 4765 bool Subtract = false; 4766 /// Source range of the loop init. 4767 SourceRange InitSrcRange; 4768 /// Source range of the loop condition. 4769 SourceRange CondSrcRange; 4770 /// Source range of the loop increment. 4771 SourceRange IncSrcRange; 4772 }; 4773 4774 } // namespace 4775 4776 void Sema::ActOnOpenMPLoopInitialization(SourceLocation ForLoc, Stmt *Init) { 4777 assert(getLangOpts().OpenMP && "OpenMP is not active."); 4778 assert(Init && "Expected loop in canonical form."); 4779 unsigned AssociatedLoops = DSAStack->getAssociatedLoops(); 4780 if (AssociatedLoops > 0 && 4781 isOpenMPLoopDirective(DSAStack->getCurrentDirective())) { 4782 DSAStack->loopStart(); 4783 OpenMPIterationSpaceChecker ISC(*this, ForLoc); 4784 if (!ISC.checkAndSetInit(Init, /*EmitDiags=*/false)) { 4785 if (ValueDecl *D = ISC.getLoopDecl()) { 4786 auto *VD = dyn_cast<VarDecl>(D); 4787 if (!VD) { 4788 if (VarDecl *Private = isOpenMPCapturedDecl(D)) { 4789 VD = Private; 4790 } else { 4791 DeclRefExpr *Ref = buildCapture(*this, D, ISC.getLoopDeclRefExpr(), 4792 /*WithInit=*/false); 4793 VD = cast<VarDecl>(Ref->getDecl()); 4794 } 4795 } 4796 DSAStack->addLoopControlVariable(D, VD); 4797 const Decl *LD = DSAStack->getPossiblyLoopCunter(); 4798 if (LD != D->getCanonicalDecl()) { 4799 DSAStack->resetPossibleLoopCounter(); 4800 if (auto *Var = dyn_cast_or_null<VarDecl>(LD)) 4801 MarkDeclarationsReferencedInExpr( 4802 buildDeclRefExpr(*this, const_cast<VarDecl *>(Var), 4803 Var->getType().getNonLValueExprType(Context), 4804 ForLoc, /*RefersToCapture=*/true)); 4805 } 4806 } 4807 } 4808 DSAStack->setAssociatedLoops(AssociatedLoops - 1); 4809 } 4810 } 4811 4812 /// Called on a for stmt to check and extract its iteration space 4813 /// for further processing (such as collapsing). 4814 static bool checkOpenMPIterationSpace( 4815 OpenMPDirectiveKind DKind, Stmt *S, Sema &SemaRef, DSAStackTy &DSA, 4816 unsigned CurrentNestedLoopCount, unsigned NestedLoopCount, 4817 unsigned TotalNestedLoopCount, Expr *CollapseLoopCountExpr, 4818 Expr *OrderedLoopCountExpr, 4819 Sema::VarsWithInheritedDSAType &VarsWithImplicitDSA, 4820 LoopIterationSpace &ResultIterSpace, 4821 llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) { 4822 // OpenMP [2.6, Canonical Loop Form] 4823 // for (init-expr; test-expr; incr-expr) structured-block 4824 auto *For = dyn_cast_or_null<ForStmt>(S); 4825 if (!For) { 4826 SemaRef.Diag(S->getBeginLoc(), diag::err_omp_not_for) 4827 << (CollapseLoopCountExpr != nullptr || OrderedLoopCountExpr != nullptr) 4828 << getOpenMPDirectiveName(DKind) << TotalNestedLoopCount 4829 << (CurrentNestedLoopCount > 0) << CurrentNestedLoopCount; 4830 if (TotalNestedLoopCount > 1) { 4831 if (CollapseLoopCountExpr && OrderedLoopCountExpr) 4832 SemaRef.Diag(DSA.getConstructLoc(), 4833 diag::note_omp_collapse_ordered_expr) 4834 << 2 << CollapseLoopCountExpr->getSourceRange() 4835 << OrderedLoopCountExpr->getSourceRange(); 4836 else if (CollapseLoopCountExpr) 4837 SemaRef.Diag(CollapseLoopCountExpr->getExprLoc(), 4838 diag::note_omp_collapse_ordered_expr) 4839 << 0 << CollapseLoopCountExpr->getSourceRange(); 4840 else 4841 SemaRef.Diag(OrderedLoopCountExpr->getExprLoc(), 4842 diag::note_omp_collapse_ordered_expr) 4843 << 1 << OrderedLoopCountExpr->getSourceRange(); 4844 } 4845 return true; 4846 } 4847 assert(For->getBody()); 4848 4849 OpenMPIterationSpaceChecker ISC(SemaRef, For->getForLoc()); 4850 4851 // Check init. 4852 Stmt *Init = For->getInit(); 4853 if (ISC.checkAndSetInit(Init)) 4854 return true; 4855 4856 bool HasErrors = false; 4857 4858 // Check loop variable's type. 4859 if (ValueDecl *LCDecl = ISC.getLoopDecl()) { 4860 Expr *LoopDeclRefExpr = ISC.getLoopDeclRefExpr(); 4861 4862 // OpenMP [2.6, Canonical Loop Form] 4863 // Var is one of the following: 4864 // A variable of signed or unsigned integer type. 4865 // For C++, a variable of a random access iterator type. 4866 // For C, a variable of a pointer type. 4867 QualType VarType = LCDecl->getType().getNonReferenceType(); 4868 if (!VarType->isDependentType() && !VarType->isIntegerType() && 4869 !VarType->isPointerType() && 4870 !(SemaRef.getLangOpts().CPlusPlus && VarType->isOverloadableType())) { 4871 SemaRef.Diag(Init->getBeginLoc(), diag::err_omp_loop_variable_type) 4872 << SemaRef.getLangOpts().CPlusPlus; 4873 HasErrors = true; 4874 } 4875 4876 // OpenMP, 2.14.1.1 Data-sharing Attribute Rules for Variables Referenced in 4877 // a Construct 4878 // The loop iteration variable(s) in the associated for-loop(s) of a for or 4879 // parallel for construct is (are) private. 4880 // The loop iteration variable in the associated for-loop of a simd 4881 // construct with just one associated for-loop is linear with a 4882 // constant-linear-step that is the increment of the associated for-loop. 4883 // Exclude loop var from the list of variables with implicitly defined data 4884 // sharing attributes. 4885 VarsWithImplicitDSA.erase(LCDecl); 4886 4887 // OpenMP [2.14.1.1, Data-sharing Attribute Rules for Variables Referenced 4888 // in a Construct, C/C++]. 4889 // The loop iteration variable in the associated for-loop of a simd 4890 // construct with just one associated for-loop may be listed in a linear 4891 // clause with a constant-linear-step that is the increment of the 4892 // associated for-loop. 4893 // The loop iteration variable(s) in the associated for-loop(s) of a for or 4894 // parallel for construct may be listed in a private or lastprivate clause. 4895 DSAStackTy::DSAVarData DVar = DSA.getTopDSA(LCDecl, false); 4896 // If LoopVarRefExpr is nullptr it means the corresponding loop variable is 4897 // declared in the loop and it is predetermined as a private. 4898 OpenMPClauseKind PredeterminedCKind = 4899 isOpenMPSimdDirective(DKind) 4900 ? ((NestedLoopCount == 1) ? OMPC_linear : OMPC_lastprivate) 4901 : OMPC_private; 4902 if (((isOpenMPSimdDirective(DKind) && DVar.CKind != OMPC_unknown && 4903 DVar.CKind != PredeterminedCKind) || 4904 ((isOpenMPWorksharingDirective(DKind) || DKind == OMPD_taskloop || 4905 isOpenMPDistributeDirective(DKind)) && 4906 !isOpenMPSimdDirective(DKind) && DVar.CKind != OMPC_unknown && 4907 DVar.CKind != OMPC_private && DVar.CKind != OMPC_lastprivate)) && 4908 (DVar.CKind != OMPC_private || DVar.RefExpr != nullptr)) { 4909 SemaRef.Diag(Init->getBeginLoc(), diag::err_omp_loop_var_dsa) 4910 << getOpenMPClauseName(DVar.CKind) << getOpenMPDirectiveName(DKind) 4911 << getOpenMPClauseName(PredeterminedCKind); 4912 if (DVar.RefExpr == nullptr) 4913 DVar.CKind = PredeterminedCKind; 4914 reportOriginalDsa(SemaRef, &DSA, LCDecl, DVar, /*IsLoopIterVar=*/true); 4915 HasErrors = true; 4916 } else if (LoopDeclRefExpr != nullptr) { 4917 // Make the loop iteration variable private (for worksharing constructs), 4918 // linear (for simd directives with the only one associated loop) or 4919 // lastprivate (for simd directives with several collapsed or ordered 4920 // loops). 4921 if (DVar.CKind == OMPC_unknown) 4922 DSA.addDSA(LCDecl, LoopDeclRefExpr, PredeterminedCKind); 4923 } 4924 4925 assert(isOpenMPLoopDirective(DKind) && "DSA for non-loop vars"); 4926 4927 // Check test-expr. 4928 HasErrors |= ISC.checkAndSetCond(For->getCond()); 4929 4930 // Check incr-expr. 4931 HasErrors |= ISC.checkAndSetInc(For->getInc()); 4932 } 4933 4934 if (ISC.dependent() || SemaRef.CurContext->isDependentContext() || HasErrors) 4935 return HasErrors; 4936 4937 // Build the loop's iteration space representation. 4938 ResultIterSpace.PreCond = 4939 ISC.buildPreCond(DSA.getCurScope(), For->getCond(), Captures); 4940 ResultIterSpace.NumIterations = ISC.buildNumIterations( 4941 DSA.getCurScope(), 4942 (isOpenMPWorksharingDirective(DKind) || 4943 isOpenMPTaskLoopDirective(DKind) || isOpenMPDistributeDirective(DKind)), 4944 Captures); 4945 ResultIterSpace.CounterVar = ISC.buildCounterVar(Captures, DSA); 4946 ResultIterSpace.PrivateCounterVar = ISC.buildPrivateCounterVar(); 4947 ResultIterSpace.CounterInit = ISC.buildCounterInit(); 4948 ResultIterSpace.CounterStep = ISC.buildCounterStep(); 4949 ResultIterSpace.InitSrcRange = ISC.getInitSrcRange(); 4950 ResultIterSpace.CondSrcRange = ISC.getConditionSrcRange(); 4951 ResultIterSpace.IncSrcRange = ISC.getIncrementSrcRange(); 4952 ResultIterSpace.Subtract = ISC.shouldSubtractStep(); 4953 ResultIterSpace.IsStrictCompare = ISC.isStrictTestOp(); 4954 4955 HasErrors |= (ResultIterSpace.PreCond == nullptr || 4956 ResultIterSpace.NumIterations == nullptr || 4957 ResultIterSpace.CounterVar == nullptr || 4958 ResultIterSpace.PrivateCounterVar == nullptr || 4959 ResultIterSpace.CounterInit == nullptr || 4960 ResultIterSpace.CounterStep == nullptr); 4961 if (!HasErrors && DSA.isOrderedRegion()) { 4962 if (DSA.getOrderedRegionParam().second->getNumForLoops()) { 4963 if (CurrentNestedLoopCount < 4964 DSA.getOrderedRegionParam().second->getLoopNumIterations().size()) { 4965 DSA.getOrderedRegionParam().second->setLoopNumIterations( 4966 CurrentNestedLoopCount, ResultIterSpace.NumIterations); 4967 DSA.getOrderedRegionParam().second->setLoopCounter( 4968 CurrentNestedLoopCount, ResultIterSpace.CounterVar); 4969 } 4970 } 4971 for (auto &Pair : DSA.getDoacrossDependClauses()) { 4972 if (CurrentNestedLoopCount >= Pair.first->getNumLoops()) { 4973 // Erroneous case - clause has some problems. 4974 continue; 4975 } 4976 if (Pair.first->getDependencyKind() == OMPC_DEPEND_sink && 4977 Pair.second.size() <= CurrentNestedLoopCount) { 4978 // Erroneous case - clause has some problems. 4979 Pair.first->setLoopData(CurrentNestedLoopCount, nullptr); 4980 continue; 4981 } 4982 Expr *CntValue; 4983 if (Pair.first->getDependencyKind() == OMPC_DEPEND_source) 4984 CntValue = ISC.buildOrderedLoopData( 4985 DSA.getCurScope(), ResultIterSpace.CounterVar, Captures, 4986 Pair.first->getDependencyLoc()); 4987 else 4988 CntValue = ISC.buildOrderedLoopData( 4989 DSA.getCurScope(), ResultIterSpace.CounterVar, Captures, 4990 Pair.first->getDependencyLoc(), 4991 Pair.second[CurrentNestedLoopCount].first, 4992 Pair.second[CurrentNestedLoopCount].second); 4993 Pair.first->setLoopData(CurrentNestedLoopCount, CntValue); 4994 } 4995 } 4996 4997 return HasErrors; 4998 } 4999 5000 /// Build 'VarRef = Start. 5001 static ExprResult 5002 buildCounterInit(Sema &SemaRef, Scope *S, SourceLocation Loc, ExprResult VarRef, 5003 ExprResult Start, 5004 llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) { 5005 // Build 'VarRef = Start. 5006 ExprResult NewStart = tryBuildCapture(SemaRef, Start.get(), Captures); 5007 if (!NewStart.isUsable()) 5008 return ExprError(); 5009 if (!SemaRef.Context.hasSameType(NewStart.get()->getType(), 5010 VarRef.get()->getType())) { 5011 NewStart = SemaRef.PerformImplicitConversion( 5012 NewStart.get(), VarRef.get()->getType(), Sema::AA_Converting, 5013 /*AllowExplicit=*/true); 5014 if (!NewStart.isUsable()) 5015 return ExprError(); 5016 } 5017 5018 ExprResult Init = 5019 SemaRef.BuildBinOp(S, Loc, BO_Assign, VarRef.get(), NewStart.get()); 5020 return Init; 5021 } 5022 5023 /// Build 'VarRef = Start + Iter * Step'. 5024 static ExprResult buildCounterUpdate( 5025 Sema &SemaRef, Scope *S, SourceLocation Loc, ExprResult VarRef, 5026 ExprResult Start, ExprResult Iter, ExprResult Step, bool Subtract, 5027 llvm::MapVector<const Expr *, DeclRefExpr *> *Captures = nullptr) { 5028 // Add parentheses (for debugging purposes only). 5029 Iter = SemaRef.ActOnParenExpr(Loc, Loc, Iter.get()); 5030 if (!VarRef.isUsable() || !Start.isUsable() || !Iter.isUsable() || 5031 !Step.isUsable()) 5032 return ExprError(); 5033 5034 ExprResult NewStep = Step; 5035 if (Captures) 5036 NewStep = tryBuildCapture(SemaRef, Step.get(), *Captures); 5037 if (NewStep.isInvalid()) 5038 return ExprError(); 5039 ExprResult Update = 5040 SemaRef.BuildBinOp(S, Loc, BO_Mul, Iter.get(), NewStep.get()); 5041 if (!Update.isUsable()) 5042 return ExprError(); 5043 5044 // Try to build 'VarRef = Start, VarRef (+|-)= Iter * Step' or 5045 // 'VarRef = Start (+|-) Iter * Step'. 5046 ExprResult NewStart = Start; 5047 if (Captures) 5048 NewStart = tryBuildCapture(SemaRef, Start.get(), *Captures); 5049 if (NewStart.isInvalid()) 5050 return ExprError(); 5051 5052 // First attempt: try to build 'VarRef = Start, VarRef += Iter * Step'. 5053 ExprResult SavedUpdate = Update; 5054 ExprResult UpdateVal; 5055 if (VarRef.get()->getType()->isOverloadableType() || 5056 NewStart.get()->getType()->isOverloadableType() || 5057 Update.get()->getType()->isOverloadableType()) { 5058 bool Suppress = SemaRef.getDiagnostics().getSuppressAllDiagnostics(); 5059 SemaRef.getDiagnostics().setSuppressAllDiagnostics(/*Val=*/true); 5060 Update = 5061 SemaRef.BuildBinOp(S, Loc, BO_Assign, VarRef.get(), NewStart.get()); 5062 if (Update.isUsable()) { 5063 UpdateVal = 5064 SemaRef.BuildBinOp(S, Loc, Subtract ? BO_SubAssign : BO_AddAssign, 5065 VarRef.get(), SavedUpdate.get()); 5066 if (UpdateVal.isUsable()) { 5067 Update = SemaRef.CreateBuiltinBinOp(Loc, BO_Comma, Update.get(), 5068 UpdateVal.get()); 5069 } 5070 } 5071 SemaRef.getDiagnostics().setSuppressAllDiagnostics(Suppress); 5072 } 5073 5074 // Second attempt: try to build 'VarRef = Start (+|-) Iter * Step'. 5075 if (!Update.isUsable() || !UpdateVal.isUsable()) { 5076 Update = SemaRef.BuildBinOp(S, Loc, Subtract ? BO_Sub : BO_Add, 5077 NewStart.get(), SavedUpdate.get()); 5078 if (!Update.isUsable()) 5079 return ExprError(); 5080 5081 if (!SemaRef.Context.hasSameType(Update.get()->getType(), 5082 VarRef.get()->getType())) { 5083 Update = SemaRef.PerformImplicitConversion( 5084 Update.get(), VarRef.get()->getType(), Sema::AA_Converting, true); 5085 if (!Update.isUsable()) 5086 return ExprError(); 5087 } 5088 5089 Update = SemaRef.BuildBinOp(S, Loc, BO_Assign, VarRef.get(), Update.get()); 5090 } 5091 return Update; 5092 } 5093 5094 /// Convert integer expression \a E to make it have at least \a Bits 5095 /// bits. 5096 static ExprResult widenIterationCount(unsigned Bits, Expr *E, Sema &SemaRef) { 5097 if (E == nullptr) 5098 return ExprError(); 5099 ASTContext &C = SemaRef.Context; 5100 QualType OldType = E->getType(); 5101 unsigned HasBits = C.getTypeSize(OldType); 5102 if (HasBits >= Bits) 5103 return ExprResult(E); 5104 // OK to convert to signed, because new type has more bits than old. 5105 QualType NewType = C.getIntTypeForBitwidth(Bits, /* Signed */ true); 5106 return SemaRef.PerformImplicitConversion(E, NewType, Sema::AA_Converting, 5107 true); 5108 } 5109 5110 /// Check if the given expression \a E is a constant integer that fits 5111 /// into \a Bits bits. 5112 static bool fitsInto(unsigned Bits, bool Signed, const Expr *E, Sema &SemaRef) { 5113 if (E == nullptr) 5114 return false; 5115 llvm::APSInt Result; 5116 if (E->isIntegerConstantExpr(Result, SemaRef.Context)) 5117 return Signed ? Result.isSignedIntN(Bits) : Result.isIntN(Bits); 5118 return false; 5119 } 5120 5121 /// Build preinits statement for the given declarations. 5122 static Stmt *buildPreInits(ASTContext &Context, 5123 MutableArrayRef<Decl *> PreInits) { 5124 if (!PreInits.empty()) { 5125 return new (Context) DeclStmt( 5126 DeclGroupRef::Create(Context, PreInits.begin(), PreInits.size()), 5127 SourceLocation(), SourceLocation()); 5128 } 5129 return nullptr; 5130 } 5131 5132 /// Build preinits statement for the given declarations. 5133 static Stmt * 5134 buildPreInits(ASTContext &Context, 5135 const llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) { 5136 if (!Captures.empty()) { 5137 SmallVector<Decl *, 16> PreInits; 5138 for (const auto &Pair : Captures) 5139 PreInits.push_back(Pair.second->getDecl()); 5140 return buildPreInits(Context, PreInits); 5141 } 5142 return nullptr; 5143 } 5144 5145 /// Build postupdate expression for the given list of postupdates expressions. 5146 static Expr *buildPostUpdate(Sema &S, ArrayRef<Expr *> PostUpdates) { 5147 Expr *PostUpdate = nullptr; 5148 if (!PostUpdates.empty()) { 5149 for (Expr *E : PostUpdates) { 5150 Expr *ConvE = S.BuildCStyleCastExpr( 5151 E->getExprLoc(), 5152 S.Context.getTrivialTypeSourceInfo(S.Context.VoidTy), 5153 E->getExprLoc(), E) 5154 .get(); 5155 PostUpdate = PostUpdate 5156 ? S.CreateBuiltinBinOp(ConvE->getExprLoc(), BO_Comma, 5157 PostUpdate, ConvE) 5158 .get() 5159 : ConvE; 5160 } 5161 } 5162 return PostUpdate; 5163 } 5164 5165 /// Called on a for stmt to check itself and nested loops (if any). 5166 /// \return Returns 0 if one of the collapsed stmts is not canonical for loop, 5167 /// number of collapsed loops otherwise. 5168 static unsigned 5169 checkOpenMPLoop(OpenMPDirectiveKind DKind, Expr *CollapseLoopCountExpr, 5170 Expr *OrderedLoopCountExpr, Stmt *AStmt, Sema &SemaRef, 5171 DSAStackTy &DSA, 5172 Sema::VarsWithInheritedDSAType &VarsWithImplicitDSA, 5173 OMPLoopDirective::HelperExprs &Built) { 5174 unsigned NestedLoopCount = 1; 5175 if (CollapseLoopCountExpr) { 5176 // Found 'collapse' clause - calculate collapse number. 5177 Expr::EvalResult Result; 5178 if (CollapseLoopCountExpr->EvaluateAsInt(Result, SemaRef.getASTContext())) 5179 NestedLoopCount = Result.Val.getInt().getLimitedValue(); 5180 } 5181 unsigned OrderedLoopCount = 1; 5182 if (OrderedLoopCountExpr) { 5183 // Found 'ordered' clause - calculate collapse number. 5184 Expr::EvalResult EVResult; 5185 if (OrderedLoopCountExpr->EvaluateAsInt(EVResult, SemaRef.getASTContext())) { 5186 llvm::APSInt Result = EVResult.Val.getInt(); 5187 if (Result.getLimitedValue() < NestedLoopCount) { 5188 SemaRef.Diag(OrderedLoopCountExpr->getExprLoc(), 5189 diag::err_omp_wrong_ordered_loop_count) 5190 << OrderedLoopCountExpr->getSourceRange(); 5191 SemaRef.Diag(CollapseLoopCountExpr->getExprLoc(), 5192 diag::note_collapse_loop_count) 5193 << CollapseLoopCountExpr->getSourceRange(); 5194 } 5195 OrderedLoopCount = Result.getLimitedValue(); 5196 } 5197 } 5198 // This is helper routine for loop directives (e.g., 'for', 'simd', 5199 // 'for simd', etc.). 5200 llvm::MapVector<const Expr *, DeclRefExpr *> Captures; 5201 SmallVector<LoopIterationSpace, 4> IterSpaces( 5202 std::max(OrderedLoopCount, NestedLoopCount)); 5203 Stmt *CurStmt = AStmt->IgnoreContainers(/* IgnoreCaptured */ true); 5204 for (unsigned Cnt = 0; Cnt < NestedLoopCount; ++Cnt) { 5205 if (checkOpenMPIterationSpace( 5206 DKind, CurStmt, SemaRef, DSA, Cnt, NestedLoopCount, 5207 std::max(OrderedLoopCount, NestedLoopCount), CollapseLoopCountExpr, 5208 OrderedLoopCountExpr, VarsWithImplicitDSA, IterSpaces[Cnt], 5209 Captures)) 5210 return 0; 5211 // Move on to the next nested for loop, or to the loop body. 5212 // OpenMP [2.8.1, simd construct, Restrictions] 5213 // All loops associated with the construct must be perfectly nested; that 5214 // is, there must be no intervening code nor any OpenMP directive between 5215 // any two loops. 5216 CurStmt = cast<ForStmt>(CurStmt)->getBody()->IgnoreContainers(); 5217 } 5218 for (unsigned Cnt = NestedLoopCount; Cnt < OrderedLoopCount; ++Cnt) { 5219 if (checkOpenMPIterationSpace( 5220 DKind, CurStmt, SemaRef, DSA, Cnt, NestedLoopCount, 5221 std::max(OrderedLoopCount, NestedLoopCount), CollapseLoopCountExpr, 5222 OrderedLoopCountExpr, VarsWithImplicitDSA, IterSpaces[Cnt], 5223 Captures)) 5224 return 0; 5225 if (Cnt > 0 && IterSpaces[Cnt].CounterVar) { 5226 // Handle initialization of captured loop iterator variables. 5227 auto *DRE = cast<DeclRefExpr>(IterSpaces[Cnt].CounterVar); 5228 if (isa<OMPCapturedExprDecl>(DRE->getDecl())) { 5229 Captures[DRE] = DRE; 5230 } 5231 } 5232 // Move on to the next nested for loop, or to the loop body. 5233 // OpenMP [2.8.1, simd construct, Restrictions] 5234 // All loops associated with the construct must be perfectly nested; that 5235 // is, there must be no intervening code nor any OpenMP directive between 5236 // any two loops. 5237 CurStmt = cast<ForStmt>(CurStmt)->getBody()->IgnoreContainers(); 5238 } 5239 5240 Built.clear(/* size */ NestedLoopCount); 5241 5242 if (SemaRef.CurContext->isDependentContext()) 5243 return NestedLoopCount; 5244 5245 // An example of what is generated for the following code: 5246 // 5247 // #pragma omp simd collapse(2) ordered(2) 5248 // for (i = 0; i < NI; ++i) 5249 // for (k = 0; k < NK; ++k) 5250 // for (j = J0; j < NJ; j+=2) { 5251 // <loop body> 5252 // } 5253 // 5254 // We generate the code below. 5255 // Note: the loop body may be outlined in CodeGen. 5256 // Note: some counters may be C++ classes, operator- is used to find number of 5257 // iterations and operator+= to calculate counter value. 5258 // Note: decltype(NumIterations) must be integer type (in 'omp for', only i32 5259 // or i64 is currently supported). 5260 // 5261 // #define NumIterations (NI * ((NJ - J0 - 1 + 2) / 2)) 5262 // for (int[32|64]_t IV = 0; IV < NumIterations; ++IV ) { 5263 // .local.i = IV / ((NJ - J0 - 1 + 2) / 2); 5264 // .local.j = J0 + (IV % ((NJ - J0 - 1 + 2) / 2)) * 2; 5265 // // similar updates for vars in clauses (e.g. 'linear') 5266 // <loop body (using local i and j)> 5267 // } 5268 // i = NI; // assign final values of counters 5269 // j = NJ; 5270 // 5271 5272 // Last iteration number is (I1 * I2 * ... In) - 1, where I1, I2 ... In are 5273 // the iteration counts of the collapsed for loops. 5274 // Precondition tests if there is at least one iteration (all conditions are 5275 // true). 5276 auto PreCond = ExprResult(IterSpaces[0].PreCond); 5277 Expr *N0 = IterSpaces[0].NumIterations; 5278 ExprResult LastIteration32 = 5279 widenIterationCount(/*Bits=*/32, 5280 SemaRef 5281 .PerformImplicitConversion( 5282 N0->IgnoreImpCasts(), N0->getType(), 5283 Sema::AA_Converting, /*AllowExplicit=*/true) 5284 .get(), 5285 SemaRef); 5286 ExprResult LastIteration64 = widenIterationCount( 5287 /*Bits=*/64, 5288 SemaRef 5289 .PerformImplicitConversion(N0->IgnoreImpCasts(), N0->getType(), 5290 Sema::AA_Converting, 5291 /*AllowExplicit=*/true) 5292 .get(), 5293 SemaRef); 5294 5295 if (!LastIteration32.isUsable() || !LastIteration64.isUsable()) 5296 return NestedLoopCount; 5297 5298 ASTContext &C = SemaRef.Context; 5299 bool AllCountsNeedLessThan32Bits = C.getTypeSize(N0->getType()) < 32; 5300 5301 Scope *CurScope = DSA.getCurScope(); 5302 for (unsigned Cnt = 1; Cnt < NestedLoopCount; ++Cnt) { 5303 if (PreCond.isUsable()) { 5304 PreCond = 5305 SemaRef.BuildBinOp(CurScope, PreCond.get()->getExprLoc(), BO_LAnd, 5306 PreCond.get(), IterSpaces[Cnt].PreCond); 5307 } 5308 Expr *N = IterSpaces[Cnt].NumIterations; 5309 SourceLocation Loc = N->getExprLoc(); 5310 AllCountsNeedLessThan32Bits &= C.getTypeSize(N->getType()) < 32; 5311 if (LastIteration32.isUsable()) 5312 LastIteration32 = SemaRef.BuildBinOp( 5313 CurScope, Loc, BO_Mul, LastIteration32.get(), 5314 SemaRef 5315 .PerformImplicitConversion(N->IgnoreImpCasts(), N->getType(), 5316 Sema::AA_Converting, 5317 /*AllowExplicit=*/true) 5318 .get()); 5319 if (LastIteration64.isUsable()) 5320 LastIteration64 = SemaRef.BuildBinOp( 5321 CurScope, Loc, BO_Mul, LastIteration64.get(), 5322 SemaRef 5323 .PerformImplicitConversion(N->IgnoreImpCasts(), N->getType(), 5324 Sema::AA_Converting, 5325 /*AllowExplicit=*/true) 5326 .get()); 5327 } 5328 5329 // Choose either the 32-bit or 64-bit version. 5330 ExprResult LastIteration = LastIteration64; 5331 if (SemaRef.getLangOpts().OpenMPOptimisticCollapse || 5332 (LastIteration32.isUsable() && 5333 C.getTypeSize(LastIteration32.get()->getType()) == 32 && 5334 (AllCountsNeedLessThan32Bits || NestedLoopCount == 1 || 5335 fitsInto( 5336 /*Bits=*/32, 5337 LastIteration32.get()->getType()->hasSignedIntegerRepresentation(), 5338 LastIteration64.get(), SemaRef)))) 5339 LastIteration = LastIteration32; 5340 QualType VType = LastIteration.get()->getType(); 5341 QualType RealVType = VType; 5342 QualType StrideVType = VType; 5343 if (isOpenMPTaskLoopDirective(DKind)) { 5344 VType = 5345 SemaRef.Context.getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/0); 5346 StrideVType = 5347 SemaRef.Context.getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/1); 5348 } 5349 5350 if (!LastIteration.isUsable()) 5351 return 0; 5352 5353 // Save the number of iterations. 5354 ExprResult NumIterations = LastIteration; 5355 { 5356 LastIteration = SemaRef.BuildBinOp( 5357 CurScope, LastIteration.get()->getExprLoc(), BO_Sub, 5358 LastIteration.get(), 5359 SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get()); 5360 if (!LastIteration.isUsable()) 5361 return 0; 5362 } 5363 5364 // Calculate the last iteration number beforehand instead of doing this on 5365 // each iteration. Do not do this if the number of iterations may be kfold-ed. 5366 llvm::APSInt Result; 5367 bool IsConstant = 5368 LastIteration.get()->isIntegerConstantExpr(Result, SemaRef.Context); 5369 ExprResult CalcLastIteration; 5370 if (!IsConstant) { 5371 ExprResult SaveRef = 5372 tryBuildCapture(SemaRef, LastIteration.get(), Captures); 5373 LastIteration = SaveRef; 5374 5375 // Prepare SaveRef + 1. 5376 NumIterations = SemaRef.BuildBinOp( 5377 CurScope, SaveRef.get()->getExprLoc(), BO_Add, SaveRef.get(), 5378 SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get()); 5379 if (!NumIterations.isUsable()) 5380 return 0; 5381 } 5382 5383 SourceLocation InitLoc = IterSpaces[0].InitSrcRange.getBegin(); 5384 5385 // Build variables passed into runtime, necessary for worksharing directives. 5386 ExprResult LB, UB, IL, ST, EUB, CombLB, CombUB, PrevLB, PrevUB, CombEUB; 5387 if (isOpenMPWorksharingDirective(DKind) || isOpenMPTaskLoopDirective(DKind) || 5388 isOpenMPDistributeDirective(DKind)) { 5389 // Lower bound variable, initialized with zero. 5390 VarDecl *LBDecl = buildVarDecl(SemaRef, InitLoc, VType, ".omp.lb"); 5391 LB = buildDeclRefExpr(SemaRef, LBDecl, VType, InitLoc); 5392 SemaRef.AddInitializerToDecl(LBDecl, 5393 SemaRef.ActOnIntegerConstant(InitLoc, 0).get(), 5394 /*DirectInit*/ false); 5395 5396 // Upper bound variable, initialized with last iteration number. 5397 VarDecl *UBDecl = buildVarDecl(SemaRef, InitLoc, VType, ".omp.ub"); 5398 UB = buildDeclRefExpr(SemaRef, UBDecl, VType, InitLoc); 5399 SemaRef.AddInitializerToDecl(UBDecl, LastIteration.get(), 5400 /*DirectInit*/ false); 5401 5402 // A 32-bit variable-flag where runtime returns 1 for the last iteration. 5403 // This will be used to implement clause 'lastprivate'. 5404 QualType Int32Ty = SemaRef.Context.getIntTypeForBitwidth(32, true); 5405 VarDecl *ILDecl = buildVarDecl(SemaRef, InitLoc, Int32Ty, ".omp.is_last"); 5406 IL = buildDeclRefExpr(SemaRef, ILDecl, Int32Ty, InitLoc); 5407 SemaRef.AddInitializerToDecl(ILDecl, 5408 SemaRef.ActOnIntegerConstant(InitLoc, 0).get(), 5409 /*DirectInit*/ false); 5410 5411 // Stride variable returned by runtime (we initialize it to 1 by default). 5412 VarDecl *STDecl = 5413 buildVarDecl(SemaRef, InitLoc, StrideVType, ".omp.stride"); 5414 ST = buildDeclRefExpr(SemaRef, STDecl, StrideVType, InitLoc); 5415 SemaRef.AddInitializerToDecl(STDecl, 5416 SemaRef.ActOnIntegerConstant(InitLoc, 1).get(), 5417 /*DirectInit*/ false); 5418 5419 // Build expression: UB = min(UB, LastIteration) 5420 // It is necessary for CodeGen of directives with static scheduling. 5421 ExprResult IsUBGreater = SemaRef.BuildBinOp(CurScope, InitLoc, BO_GT, 5422 UB.get(), LastIteration.get()); 5423 ExprResult CondOp = SemaRef.ActOnConditionalOp( 5424 LastIteration.get()->getExprLoc(), InitLoc, IsUBGreater.get(), 5425 LastIteration.get(), UB.get()); 5426 EUB = SemaRef.BuildBinOp(CurScope, InitLoc, BO_Assign, UB.get(), 5427 CondOp.get()); 5428 EUB = SemaRef.ActOnFinishFullExpr(EUB.get(), /*DiscardedValue*/ false); 5429 5430 // If we have a combined directive that combines 'distribute', 'for' or 5431 // 'simd' we need to be able to access the bounds of the schedule of the 5432 // enclosing region. E.g. in 'distribute parallel for' the bounds obtained 5433 // by scheduling 'distribute' have to be passed to the schedule of 'for'. 5434 if (isOpenMPLoopBoundSharingDirective(DKind)) { 5435 // Lower bound variable, initialized with zero. 5436 VarDecl *CombLBDecl = 5437 buildVarDecl(SemaRef, InitLoc, VType, ".omp.comb.lb"); 5438 CombLB = buildDeclRefExpr(SemaRef, CombLBDecl, VType, InitLoc); 5439 SemaRef.AddInitializerToDecl( 5440 CombLBDecl, SemaRef.ActOnIntegerConstant(InitLoc, 0).get(), 5441 /*DirectInit*/ false); 5442 5443 // Upper bound variable, initialized with last iteration number. 5444 VarDecl *CombUBDecl = 5445 buildVarDecl(SemaRef, InitLoc, VType, ".omp.comb.ub"); 5446 CombUB = buildDeclRefExpr(SemaRef, CombUBDecl, VType, InitLoc); 5447 SemaRef.AddInitializerToDecl(CombUBDecl, LastIteration.get(), 5448 /*DirectInit*/ false); 5449 5450 ExprResult CombIsUBGreater = SemaRef.BuildBinOp( 5451 CurScope, InitLoc, BO_GT, CombUB.get(), LastIteration.get()); 5452 ExprResult CombCondOp = 5453 SemaRef.ActOnConditionalOp(InitLoc, InitLoc, CombIsUBGreater.get(), 5454 LastIteration.get(), CombUB.get()); 5455 CombEUB = SemaRef.BuildBinOp(CurScope, InitLoc, BO_Assign, CombUB.get(), 5456 CombCondOp.get()); 5457 CombEUB = 5458 SemaRef.ActOnFinishFullExpr(CombEUB.get(), /*DiscardedValue*/ false); 5459 5460 const CapturedDecl *CD = cast<CapturedStmt>(AStmt)->getCapturedDecl(); 5461 // We expect to have at least 2 more parameters than the 'parallel' 5462 // directive does - the lower and upper bounds of the previous schedule. 5463 assert(CD->getNumParams() >= 4 && 5464 "Unexpected number of parameters in loop combined directive"); 5465 5466 // Set the proper type for the bounds given what we learned from the 5467 // enclosed loops. 5468 ImplicitParamDecl *PrevLBDecl = CD->getParam(/*PrevLB=*/2); 5469 ImplicitParamDecl *PrevUBDecl = CD->getParam(/*PrevUB=*/3); 5470 5471 // Previous lower and upper bounds are obtained from the region 5472 // parameters. 5473 PrevLB = 5474 buildDeclRefExpr(SemaRef, PrevLBDecl, PrevLBDecl->getType(), InitLoc); 5475 PrevUB = 5476 buildDeclRefExpr(SemaRef, PrevUBDecl, PrevUBDecl->getType(), InitLoc); 5477 } 5478 } 5479 5480 // Build the iteration variable and its initialization before loop. 5481 ExprResult IV; 5482 ExprResult Init, CombInit; 5483 { 5484 VarDecl *IVDecl = buildVarDecl(SemaRef, InitLoc, RealVType, ".omp.iv"); 5485 IV = buildDeclRefExpr(SemaRef, IVDecl, RealVType, InitLoc); 5486 Expr *RHS = 5487 (isOpenMPWorksharingDirective(DKind) || 5488 isOpenMPTaskLoopDirective(DKind) || isOpenMPDistributeDirective(DKind)) 5489 ? LB.get() 5490 : SemaRef.ActOnIntegerConstant(SourceLocation(), 0).get(); 5491 Init = SemaRef.BuildBinOp(CurScope, InitLoc, BO_Assign, IV.get(), RHS); 5492 Init = SemaRef.ActOnFinishFullExpr(Init.get(), /*DiscardedValue*/ false); 5493 5494 if (isOpenMPLoopBoundSharingDirective(DKind)) { 5495 Expr *CombRHS = 5496 (isOpenMPWorksharingDirective(DKind) || 5497 isOpenMPTaskLoopDirective(DKind) || 5498 isOpenMPDistributeDirective(DKind)) 5499 ? CombLB.get() 5500 : SemaRef.ActOnIntegerConstant(SourceLocation(), 0).get(); 5501 CombInit = 5502 SemaRef.BuildBinOp(CurScope, InitLoc, BO_Assign, IV.get(), CombRHS); 5503 CombInit = 5504 SemaRef.ActOnFinishFullExpr(CombInit.get(), /*DiscardedValue*/ false); 5505 } 5506 } 5507 5508 bool UseStrictCompare = 5509 RealVType->hasUnsignedIntegerRepresentation() && 5510 llvm::all_of(IterSpaces, [](const LoopIterationSpace &LIS) { 5511 return LIS.IsStrictCompare; 5512 }); 5513 // Loop condition (IV < NumIterations) or (IV <= UB or IV < UB + 1 (for 5514 // unsigned IV)) for worksharing loops. 5515 SourceLocation CondLoc = AStmt->getBeginLoc(); 5516 Expr *BoundUB = UB.get(); 5517 if (UseStrictCompare) { 5518 BoundUB = 5519 SemaRef 5520 .BuildBinOp(CurScope, CondLoc, BO_Add, BoundUB, 5521 SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get()) 5522 .get(); 5523 BoundUB = 5524 SemaRef.ActOnFinishFullExpr(BoundUB, /*DiscardedValue*/ false).get(); 5525 } 5526 ExprResult Cond = 5527 (isOpenMPWorksharingDirective(DKind) || 5528 isOpenMPTaskLoopDirective(DKind) || isOpenMPDistributeDirective(DKind)) 5529 ? SemaRef.BuildBinOp(CurScope, CondLoc, 5530 UseStrictCompare ? BO_LT : BO_LE, IV.get(), 5531 BoundUB) 5532 : SemaRef.BuildBinOp(CurScope, CondLoc, BO_LT, IV.get(), 5533 NumIterations.get()); 5534 ExprResult CombDistCond; 5535 if (isOpenMPLoopBoundSharingDirective(DKind)) { 5536 CombDistCond = SemaRef.BuildBinOp(CurScope, CondLoc, BO_LT, IV.get(), 5537 NumIterations.get()); 5538 } 5539 5540 ExprResult CombCond; 5541 if (isOpenMPLoopBoundSharingDirective(DKind)) { 5542 Expr *BoundCombUB = CombUB.get(); 5543 if (UseStrictCompare) { 5544 BoundCombUB = 5545 SemaRef 5546 .BuildBinOp( 5547 CurScope, CondLoc, BO_Add, BoundCombUB, 5548 SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get()) 5549 .get(); 5550 BoundCombUB = 5551 SemaRef.ActOnFinishFullExpr(BoundCombUB, /*DiscardedValue*/ false) 5552 .get(); 5553 } 5554 CombCond = 5555 SemaRef.BuildBinOp(CurScope, CondLoc, UseStrictCompare ? BO_LT : BO_LE, 5556 IV.get(), BoundCombUB); 5557 } 5558 // Loop increment (IV = IV + 1) 5559 SourceLocation IncLoc = AStmt->getBeginLoc(); 5560 ExprResult Inc = 5561 SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, IV.get(), 5562 SemaRef.ActOnIntegerConstant(IncLoc, 1).get()); 5563 if (!Inc.isUsable()) 5564 return 0; 5565 Inc = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, IV.get(), Inc.get()); 5566 Inc = SemaRef.ActOnFinishFullExpr(Inc.get(), /*DiscardedValue*/ false); 5567 if (!Inc.isUsable()) 5568 return 0; 5569 5570 // Increments for worksharing loops (LB = LB + ST; UB = UB + ST). 5571 // Used for directives with static scheduling. 5572 // In combined construct, add combined version that use CombLB and CombUB 5573 // base variables for the update 5574 ExprResult NextLB, NextUB, CombNextLB, CombNextUB; 5575 if (isOpenMPWorksharingDirective(DKind) || isOpenMPTaskLoopDirective(DKind) || 5576 isOpenMPDistributeDirective(DKind)) { 5577 // LB + ST 5578 NextLB = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, LB.get(), ST.get()); 5579 if (!NextLB.isUsable()) 5580 return 0; 5581 // LB = LB + ST 5582 NextLB = 5583 SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, LB.get(), NextLB.get()); 5584 NextLB = 5585 SemaRef.ActOnFinishFullExpr(NextLB.get(), /*DiscardedValue*/ false); 5586 if (!NextLB.isUsable()) 5587 return 0; 5588 // UB + ST 5589 NextUB = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, UB.get(), ST.get()); 5590 if (!NextUB.isUsable()) 5591 return 0; 5592 // UB = UB + ST 5593 NextUB = 5594 SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, UB.get(), NextUB.get()); 5595 NextUB = 5596 SemaRef.ActOnFinishFullExpr(NextUB.get(), /*DiscardedValue*/ false); 5597 if (!NextUB.isUsable()) 5598 return 0; 5599 if (isOpenMPLoopBoundSharingDirective(DKind)) { 5600 CombNextLB = 5601 SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, CombLB.get(), ST.get()); 5602 if (!NextLB.isUsable()) 5603 return 0; 5604 // LB = LB + ST 5605 CombNextLB = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, CombLB.get(), 5606 CombNextLB.get()); 5607 CombNextLB = SemaRef.ActOnFinishFullExpr(CombNextLB.get(), 5608 /*DiscardedValue*/ false); 5609 if (!CombNextLB.isUsable()) 5610 return 0; 5611 // UB + ST 5612 CombNextUB = 5613 SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, CombUB.get(), ST.get()); 5614 if (!CombNextUB.isUsable()) 5615 return 0; 5616 // UB = UB + ST 5617 CombNextUB = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, CombUB.get(), 5618 CombNextUB.get()); 5619 CombNextUB = SemaRef.ActOnFinishFullExpr(CombNextUB.get(), 5620 /*DiscardedValue*/ false); 5621 if (!CombNextUB.isUsable()) 5622 return 0; 5623 } 5624 } 5625 5626 // Create increment expression for distribute loop when combined in a same 5627 // directive with for as IV = IV + ST; ensure upper bound expression based 5628 // on PrevUB instead of NumIterations - used to implement 'for' when found 5629 // in combination with 'distribute', like in 'distribute parallel for' 5630 SourceLocation DistIncLoc = AStmt->getBeginLoc(); 5631 ExprResult DistCond, DistInc, PrevEUB, ParForInDistCond; 5632 if (isOpenMPLoopBoundSharingDirective(DKind)) { 5633 DistCond = SemaRef.BuildBinOp( 5634 CurScope, CondLoc, UseStrictCompare ? BO_LT : BO_LE, IV.get(), BoundUB); 5635 assert(DistCond.isUsable() && "distribute cond expr was not built"); 5636 5637 DistInc = 5638 SemaRef.BuildBinOp(CurScope, DistIncLoc, BO_Add, IV.get(), ST.get()); 5639 assert(DistInc.isUsable() && "distribute inc expr was not built"); 5640 DistInc = SemaRef.BuildBinOp(CurScope, DistIncLoc, BO_Assign, IV.get(), 5641 DistInc.get()); 5642 DistInc = 5643 SemaRef.ActOnFinishFullExpr(DistInc.get(), /*DiscardedValue*/ false); 5644 assert(DistInc.isUsable() && "distribute inc expr was not built"); 5645 5646 // Build expression: UB = min(UB, prevUB) for #for in composite or combined 5647 // construct 5648 SourceLocation DistEUBLoc = AStmt->getBeginLoc(); 5649 ExprResult IsUBGreater = 5650 SemaRef.BuildBinOp(CurScope, DistEUBLoc, BO_GT, UB.get(), PrevUB.get()); 5651 ExprResult CondOp = SemaRef.ActOnConditionalOp( 5652 DistEUBLoc, DistEUBLoc, IsUBGreater.get(), PrevUB.get(), UB.get()); 5653 PrevEUB = SemaRef.BuildBinOp(CurScope, DistIncLoc, BO_Assign, UB.get(), 5654 CondOp.get()); 5655 PrevEUB = 5656 SemaRef.ActOnFinishFullExpr(PrevEUB.get(), /*DiscardedValue*/ false); 5657 5658 // Build IV <= PrevUB or IV < PrevUB + 1 for unsigned IV to be used in 5659 // parallel for is in combination with a distribute directive with 5660 // schedule(static, 1) 5661 Expr *BoundPrevUB = PrevUB.get(); 5662 if (UseStrictCompare) { 5663 BoundPrevUB = 5664 SemaRef 5665 .BuildBinOp( 5666 CurScope, CondLoc, BO_Add, BoundPrevUB, 5667 SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get()) 5668 .get(); 5669 BoundPrevUB = 5670 SemaRef.ActOnFinishFullExpr(BoundPrevUB, /*DiscardedValue*/ false) 5671 .get(); 5672 } 5673 ParForInDistCond = 5674 SemaRef.BuildBinOp(CurScope, CondLoc, UseStrictCompare ? BO_LT : BO_LE, 5675 IV.get(), BoundPrevUB); 5676 } 5677 5678 // Build updates and final values of the loop counters. 5679 bool HasErrors = false; 5680 Built.Counters.resize(NestedLoopCount); 5681 Built.Inits.resize(NestedLoopCount); 5682 Built.Updates.resize(NestedLoopCount); 5683 Built.Finals.resize(NestedLoopCount); 5684 { 5685 // We implement the following algorithm for obtaining the 5686 // original loop iteration variable values based on the 5687 // value of the collapsed loop iteration variable IV. 5688 // 5689 // Let n+1 be the number of collapsed loops in the nest. 5690 // Iteration variables (I0, I1, .... In) 5691 // Iteration counts (N0, N1, ... Nn) 5692 // 5693 // Acc = IV; 5694 // 5695 // To compute Ik for loop k, 0 <= k <= n, generate: 5696 // Prod = N(k+1) * N(k+2) * ... * Nn; 5697 // Ik = Acc / Prod; 5698 // Acc -= Ik * Prod; 5699 // 5700 ExprResult Acc = IV; 5701 for (unsigned int Cnt = 0; Cnt < NestedLoopCount; ++Cnt) { 5702 LoopIterationSpace &IS = IterSpaces[Cnt]; 5703 SourceLocation UpdLoc = IS.IncSrcRange.getBegin(); 5704 ExprResult Iter; 5705 5706 // Compute prod 5707 ExprResult Prod = 5708 SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get(); 5709 for (unsigned int K = Cnt+1; K < NestedLoopCount; ++K) 5710 Prod = SemaRef.BuildBinOp(CurScope, UpdLoc, BO_Mul, Prod.get(), 5711 IterSpaces[K].NumIterations); 5712 5713 // Iter = Acc / Prod 5714 // If there is at least one more inner loop to avoid 5715 // multiplication by 1. 5716 if (Cnt + 1 < NestedLoopCount) 5717 Iter = SemaRef.BuildBinOp(CurScope, UpdLoc, BO_Div, 5718 Acc.get(), Prod.get()); 5719 else 5720 Iter = Acc; 5721 if (!Iter.isUsable()) { 5722 HasErrors = true; 5723 break; 5724 } 5725 5726 // Update Acc: 5727 // Acc -= Iter * Prod 5728 // Check if there is at least one more inner loop to avoid 5729 // multiplication by 1. 5730 if (Cnt + 1 < NestedLoopCount) 5731 Prod = SemaRef.BuildBinOp(CurScope, UpdLoc, BO_Mul, 5732 Iter.get(), Prod.get()); 5733 else 5734 Prod = Iter; 5735 Acc = SemaRef.BuildBinOp(CurScope, UpdLoc, BO_Sub, 5736 Acc.get(), Prod.get()); 5737 5738 // Build update: IS.CounterVar(Private) = IS.Start + Iter * IS.Step 5739 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(IS.CounterVar)->getDecl()); 5740 DeclRefExpr *CounterVar = buildDeclRefExpr( 5741 SemaRef, VD, IS.CounterVar->getType(), IS.CounterVar->getExprLoc(), 5742 /*RefersToCapture=*/true); 5743 ExprResult Init = buildCounterInit(SemaRef, CurScope, UpdLoc, CounterVar, 5744 IS.CounterInit, Captures); 5745 if (!Init.isUsable()) { 5746 HasErrors = true; 5747 break; 5748 } 5749 ExprResult Update = buildCounterUpdate( 5750 SemaRef, CurScope, UpdLoc, CounterVar, IS.CounterInit, Iter, 5751 IS.CounterStep, IS.Subtract, &Captures); 5752 if (!Update.isUsable()) { 5753 HasErrors = true; 5754 break; 5755 } 5756 5757 // Build final: IS.CounterVar = IS.Start + IS.NumIters * IS.Step 5758 ExprResult Final = buildCounterUpdate( 5759 SemaRef, CurScope, UpdLoc, CounterVar, IS.CounterInit, 5760 IS.NumIterations, IS.CounterStep, IS.Subtract, &Captures); 5761 if (!Final.isUsable()) { 5762 HasErrors = true; 5763 break; 5764 } 5765 5766 if (!Update.isUsable() || !Final.isUsable()) { 5767 HasErrors = true; 5768 break; 5769 } 5770 // Save results 5771 Built.Counters[Cnt] = IS.CounterVar; 5772 Built.PrivateCounters[Cnt] = IS.PrivateCounterVar; 5773 Built.Inits[Cnt] = Init.get(); 5774 Built.Updates[Cnt] = Update.get(); 5775 Built.Finals[Cnt] = Final.get(); 5776 } 5777 } 5778 5779 if (HasErrors) 5780 return 0; 5781 5782 // Save results 5783 Built.IterationVarRef = IV.get(); 5784 Built.LastIteration = LastIteration.get(); 5785 Built.NumIterations = NumIterations.get(); 5786 Built.CalcLastIteration = SemaRef 5787 .ActOnFinishFullExpr(CalcLastIteration.get(), 5788 /*DiscardedValue*/ false) 5789 .get(); 5790 Built.PreCond = PreCond.get(); 5791 Built.PreInits = buildPreInits(C, Captures); 5792 Built.Cond = Cond.get(); 5793 Built.Init = Init.get(); 5794 Built.Inc = Inc.get(); 5795 Built.LB = LB.get(); 5796 Built.UB = UB.get(); 5797 Built.IL = IL.get(); 5798 Built.ST = ST.get(); 5799 Built.EUB = EUB.get(); 5800 Built.NLB = NextLB.get(); 5801 Built.NUB = NextUB.get(); 5802 Built.PrevLB = PrevLB.get(); 5803 Built.PrevUB = PrevUB.get(); 5804 Built.DistInc = DistInc.get(); 5805 Built.PrevEUB = PrevEUB.get(); 5806 Built.DistCombinedFields.LB = CombLB.get(); 5807 Built.DistCombinedFields.UB = CombUB.get(); 5808 Built.DistCombinedFields.EUB = CombEUB.get(); 5809 Built.DistCombinedFields.Init = CombInit.get(); 5810 Built.DistCombinedFields.Cond = CombCond.get(); 5811 Built.DistCombinedFields.NLB = CombNextLB.get(); 5812 Built.DistCombinedFields.NUB = CombNextUB.get(); 5813 Built.DistCombinedFields.DistCond = CombDistCond.get(); 5814 Built.DistCombinedFields.ParForInDistCond = ParForInDistCond.get(); 5815 5816 return NestedLoopCount; 5817 } 5818 5819 static Expr *getCollapseNumberExpr(ArrayRef<OMPClause *> Clauses) { 5820 auto CollapseClauses = 5821 OMPExecutableDirective::getClausesOfKind<OMPCollapseClause>(Clauses); 5822 if (CollapseClauses.begin() != CollapseClauses.end()) 5823 return (*CollapseClauses.begin())->getNumForLoops(); 5824 return nullptr; 5825 } 5826 5827 static Expr *getOrderedNumberExpr(ArrayRef<OMPClause *> Clauses) { 5828 auto OrderedClauses = 5829 OMPExecutableDirective::getClausesOfKind<OMPOrderedClause>(Clauses); 5830 if (OrderedClauses.begin() != OrderedClauses.end()) 5831 return (*OrderedClauses.begin())->getNumForLoops(); 5832 return nullptr; 5833 } 5834 5835 static bool checkSimdlenSafelenSpecified(Sema &S, 5836 const ArrayRef<OMPClause *> Clauses) { 5837 const OMPSafelenClause *Safelen = nullptr; 5838 const OMPSimdlenClause *Simdlen = nullptr; 5839 5840 for (const OMPClause *Clause : Clauses) { 5841 if (Clause->getClauseKind() == OMPC_safelen) 5842 Safelen = cast<OMPSafelenClause>(Clause); 5843 else if (Clause->getClauseKind() == OMPC_simdlen) 5844 Simdlen = cast<OMPSimdlenClause>(Clause); 5845 if (Safelen && Simdlen) 5846 break; 5847 } 5848 5849 if (Simdlen && Safelen) { 5850 const Expr *SimdlenLength = Simdlen->getSimdlen(); 5851 const Expr *SafelenLength = Safelen->getSafelen(); 5852 if (SimdlenLength->isValueDependent() || SimdlenLength->isTypeDependent() || 5853 SimdlenLength->isInstantiationDependent() || 5854 SimdlenLength->containsUnexpandedParameterPack()) 5855 return false; 5856 if (SafelenLength->isValueDependent() || SafelenLength->isTypeDependent() || 5857 SafelenLength->isInstantiationDependent() || 5858 SafelenLength->containsUnexpandedParameterPack()) 5859 return false; 5860 Expr::EvalResult SimdlenResult, SafelenResult; 5861 SimdlenLength->EvaluateAsInt(SimdlenResult, S.Context); 5862 SafelenLength->EvaluateAsInt(SafelenResult, S.Context); 5863 llvm::APSInt SimdlenRes = SimdlenResult.Val.getInt(); 5864 llvm::APSInt SafelenRes = SafelenResult.Val.getInt(); 5865 // OpenMP 4.5 [2.8.1, simd Construct, Restrictions] 5866 // If both simdlen and safelen clauses are specified, the value of the 5867 // simdlen parameter must be less than or equal to the value of the safelen 5868 // parameter. 5869 if (SimdlenRes > SafelenRes) { 5870 S.Diag(SimdlenLength->getExprLoc(), 5871 diag::err_omp_wrong_simdlen_safelen_values) 5872 << SimdlenLength->getSourceRange() << SafelenLength->getSourceRange(); 5873 return true; 5874 } 5875 } 5876 return false; 5877 } 5878 5879 StmtResult 5880 Sema::ActOnOpenMPSimdDirective(ArrayRef<OMPClause *> Clauses, Stmt *AStmt, 5881 SourceLocation StartLoc, SourceLocation EndLoc, 5882 VarsWithInheritedDSAType &VarsWithImplicitDSA) { 5883 if (!AStmt) 5884 return StmtError(); 5885 5886 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected"); 5887 OMPLoopDirective::HelperExprs B; 5888 // In presence of clause 'collapse' or 'ordered' with number of loops, it will 5889 // define the nested loops number. 5890 unsigned NestedLoopCount = checkOpenMPLoop( 5891 OMPD_simd, getCollapseNumberExpr(Clauses), getOrderedNumberExpr(Clauses), 5892 AStmt, *this, *DSAStack, VarsWithImplicitDSA, B); 5893 if (NestedLoopCount == 0) 5894 return StmtError(); 5895 5896 assert((CurContext->isDependentContext() || B.builtAll()) && 5897 "omp simd loop exprs were not built"); 5898 5899 if (!CurContext->isDependentContext()) { 5900 // Finalize the clauses that need pre-built expressions for CodeGen. 5901 for (OMPClause *C : Clauses) { 5902 if (auto *LC = dyn_cast<OMPLinearClause>(C)) 5903 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef), 5904 B.NumIterations, *this, CurScope, 5905 DSAStack)) 5906 return StmtError(); 5907 } 5908 } 5909 5910 if (checkSimdlenSafelenSpecified(*this, Clauses)) 5911 return StmtError(); 5912 5913 setFunctionHasBranchProtectedScope(); 5914 return OMPSimdDirective::Create(Context, StartLoc, EndLoc, NestedLoopCount, 5915 Clauses, AStmt, B); 5916 } 5917 5918 StmtResult 5919 Sema::ActOnOpenMPForDirective(ArrayRef<OMPClause *> Clauses, Stmt *AStmt, 5920 SourceLocation StartLoc, SourceLocation EndLoc, 5921 VarsWithInheritedDSAType &VarsWithImplicitDSA) { 5922 if (!AStmt) 5923 return StmtError(); 5924 5925 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected"); 5926 OMPLoopDirective::HelperExprs B; 5927 // In presence of clause 'collapse' or 'ordered' with number of loops, it will 5928 // define the nested loops number. 5929 unsigned NestedLoopCount = checkOpenMPLoop( 5930 OMPD_for, getCollapseNumberExpr(Clauses), getOrderedNumberExpr(Clauses), 5931 AStmt, *this, *DSAStack, VarsWithImplicitDSA, B); 5932 if (NestedLoopCount == 0) 5933 return StmtError(); 5934 5935 assert((CurContext->isDependentContext() || B.builtAll()) && 5936 "omp for loop exprs were not built"); 5937 5938 if (!CurContext->isDependentContext()) { 5939 // Finalize the clauses that need pre-built expressions for CodeGen. 5940 for (OMPClause *C : Clauses) { 5941 if (auto *LC = dyn_cast<OMPLinearClause>(C)) 5942 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef), 5943 B.NumIterations, *this, CurScope, 5944 DSAStack)) 5945 return StmtError(); 5946 } 5947 } 5948 5949 setFunctionHasBranchProtectedScope(); 5950 return OMPForDirective::Create(Context, StartLoc, EndLoc, NestedLoopCount, 5951 Clauses, AStmt, B, DSAStack->isCancelRegion()); 5952 } 5953 5954 StmtResult Sema::ActOnOpenMPForSimdDirective( 5955 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, 5956 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) { 5957 if (!AStmt) 5958 return StmtError(); 5959 5960 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected"); 5961 OMPLoopDirective::HelperExprs B; 5962 // In presence of clause 'collapse' or 'ordered' with number of loops, it will 5963 // define the nested loops number. 5964 unsigned NestedLoopCount = 5965 checkOpenMPLoop(OMPD_for_simd, getCollapseNumberExpr(Clauses), 5966 getOrderedNumberExpr(Clauses), AStmt, *this, *DSAStack, 5967 VarsWithImplicitDSA, B); 5968 if (NestedLoopCount == 0) 5969 return StmtError(); 5970 5971 assert((CurContext->isDependentContext() || B.builtAll()) && 5972 "omp for simd loop exprs were not built"); 5973 5974 if (!CurContext->isDependentContext()) { 5975 // Finalize the clauses that need pre-built expressions for CodeGen. 5976 for (OMPClause *C : Clauses) { 5977 if (auto *LC = dyn_cast<OMPLinearClause>(C)) 5978 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef), 5979 B.NumIterations, *this, CurScope, 5980 DSAStack)) 5981 return StmtError(); 5982 } 5983 } 5984 5985 if (checkSimdlenSafelenSpecified(*this, Clauses)) 5986 return StmtError(); 5987 5988 setFunctionHasBranchProtectedScope(); 5989 return OMPForSimdDirective::Create(Context, StartLoc, EndLoc, NestedLoopCount, 5990 Clauses, AStmt, B); 5991 } 5992 5993 StmtResult Sema::ActOnOpenMPSectionsDirective(ArrayRef<OMPClause *> Clauses, 5994 Stmt *AStmt, 5995 SourceLocation StartLoc, 5996 SourceLocation EndLoc) { 5997 if (!AStmt) 5998 return StmtError(); 5999 6000 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected"); 6001 auto BaseStmt = AStmt; 6002 while (auto *CS = dyn_cast_or_null<CapturedStmt>(BaseStmt)) 6003 BaseStmt = CS->getCapturedStmt(); 6004 if (auto *C = dyn_cast_or_null<CompoundStmt>(BaseStmt)) { 6005 auto S = C->children(); 6006 if (S.begin() == S.end()) 6007 return StmtError(); 6008 // All associated statements must be '#pragma omp section' except for 6009 // the first one. 6010 for (Stmt *SectionStmt : llvm::make_range(std::next(S.begin()), S.end())) { 6011 if (!SectionStmt || !isa<OMPSectionDirective>(SectionStmt)) { 6012 if (SectionStmt) 6013 Diag(SectionStmt->getBeginLoc(), 6014 diag::err_omp_sections_substmt_not_section); 6015 return StmtError(); 6016 } 6017 cast<OMPSectionDirective>(SectionStmt) 6018 ->setHasCancel(DSAStack->isCancelRegion()); 6019 } 6020 } else { 6021 Diag(AStmt->getBeginLoc(), diag::err_omp_sections_not_compound_stmt); 6022 return StmtError(); 6023 } 6024 6025 setFunctionHasBranchProtectedScope(); 6026 6027 return OMPSectionsDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt, 6028 DSAStack->isCancelRegion()); 6029 } 6030 6031 StmtResult Sema::ActOnOpenMPSectionDirective(Stmt *AStmt, 6032 SourceLocation StartLoc, 6033 SourceLocation EndLoc) { 6034 if (!AStmt) 6035 return StmtError(); 6036 6037 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected"); 6038 6039 setFunctionHasBranchProtectedScope(); 6040 DSAStack->setParentCancelRegion(DSAStack->isCancelRegion()); 6041 6042 return OMPSectionDirective::Create(Context, StartLoc, EndLoc, AStmt, 6043 DSAStack->isCancelRegion()); 6044 } 6045 6046 StmtResult Sema::ActOnOpenMPSingleDirective(ArrayRef<OMPClause *> Clauses, 6047 Stmt *AStmt, 6048 SourceLocation StartLoc, 6049 SourceLocation EndLoc) { 6050 if (!AStmt) 6051 return StmtError(); 6052 6053 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected"); 6054 6055 setFunctionHasBranchProtectedScope(); 6056 6057 // OpenMP [2.7.3, single Construct, Restrictions] 6058 // The copyprivate clause must not be used with the nowait clause. 6059 const OMPClause *Nowait = nullptr; 6060 const OMPClause *Copyprivate = nullptr; 6061 for (const OMPClause *Clause : Clauses) { 6062 if (Clause->getClauseKind() == OMPC_nowait) 6063 Nowait = Clause; 6064 else if (Clause->getClauseKind() == OMPC_copyprivate) 6065 Copyprivate = Clause; 6066 if (Copyprivate && Nowait) { 6067 Diag(Copyprivate->getBeginLoc(), 6068 diag::err_omp_single_copyprivate_with_nowait); 6069 Diag(Nowait->getBeginLoc(), diag::note_omp_nowait_clause_here); 6070 return StmtError(); 6071 } 6072 } 6073 6074 return OMPSingleDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt); 6075 } 6076 6077 StmtResult Sema::ActOnOpenMPMasterDirective(Stmt *AStmt, 6078 SourceLocation StartLoc, 6079 SourceLocation EndLoc) { 6080 if (!AStmt) 6081 return StmtError(); 6082 6083 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected"); 6084 6085 setFunctionHasBranchProtectedScope(); 6086 6087 return OMPMasterDirective::Create(Context, StartLoc, EndLoc, AStmt); 6088 } 6089 6090 StmtResult Sema::ActOnOpenMPCriticalDirective( 6091 const DeclarationNameInfo &DirName, ArrayRef<OMPClause *> Clauses, 6092 Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc) { 6093 if (!AStmt) 6094 return StmtError(); 6095 6096 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected"); 6097 6098 bool ErrorFound = false; 6099 llvm::APSInt Hint; 6100 SourceLocation HintLoc; 6101 bool DependentHint = false; 6102 for (const OMPClause *C : Clauses) { 6103 if (C->getClauseKind() == OMPC_hint) { 6104 if (!DirName.getName()) { 6105 Diag(C->getBeginLoc(), diag::err_omp_hint_clause_no_name); 6106 ErrorFound = true; 6107 } 6108 Expr *E = cast<OMPHintClause>(C)->getHint(); 6109 if (E->isTypeDependent() || E->isValueDependent() || 6110 E->isInstantiationDependent()) { 6111 DependentHint = true; 6112 } else { 6113 Hint = E->EvaluateKnownConstInt(Context); 6114 HintLoc = C->getBeginLoc(); 6115 } 6116 } 6117 } 6118 if (ErrorFound) 6119 return StmtError(); 6120 const auto Pair = DSAStack->getCriticalWithHint(DirName); 6121 if (Pair.first && DirName.getName() && !DependentHint) { 6122 if (llvm::APSInt::compareValues(Hint, Pair.second) != 0) { 6123 Diag(StartLoc, diag::err_omp_critical_with_hint); 6124 if (HintLoc.isValid()) 6125 Diag(HintLoc, diag::note_omp_critical_hint_here) 6126 << 0 << Hint.toString(/*Radix=*/10, /*Signed=*/false); 6127 else 6128 Diag(StartLoc, diag::note_omp_critical_no_hint) << 0; 6129 if (const auto *C = Pair.first->getSingleClause<OMPHintClause>()) { 6130 Diag(C->getBeginLoc(), diag::note_omp_critical_hint_here) 6131 << 1 6132 << C->getHint()->EvaluateKnownConstInt(Context).toString( 6133 /*Radix=*/10, /*Signed=*/false); 6134 } else { 6135 Diag(Pair.first->getBeginLoc(), diag::note_omp_critical_no_hint) << 1; 6136 } 6137 } 6138 } 6139 6140 setFunctionHasBranchProtectedScope(); 6141 6142 auto *Dir = OMPCriticalDirective::Create(Context, DirName, StartLoc, EndLoc, 6143 Clauses, AStmt); 6144 if (!Pair.first && DirName.getName() && !DependentHint) 6145 DSAStack->addCriticalWithHint(Dir, Hint); 6146 return Dir; 6147 } 6148 6149 StmtResult Sema::ActOnOpenMPParallelForDirective( 6150 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, 6151 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) { 6152 if (!AStmt) 6153 return StmtError(); 6154 6155 auto *CS = cast<CapturedStmt>(AStmt); 6156 // 1.2.2 OpenMP Language Terminology 6157 // Structured block - An executable statement with a single entry at the 6158 // top and a single exit at the bottom. 6159 // The point of exit cannot be a branch out of the structured block. 6160 // longjmp() and throw() must not violate the entry/exit criteria. 6161 CS->getCapturedDecl()->setNothrow(); 6162 6163 OMPLoopDirective::HelperExprs B; 6164 // In presence of clause 'collapse' or 'ordered' with number of loops, it will 6165 // define the nested loops number. 6166 unsigned NestedLoopCount = 6167 checkOpenMPLoop(OMPD_parallel_for, getCollapseNumberExpr(Clauses), 6168 getOrderedNumberExpr(Clauses), AStmt, *this, *DSAStack, 6169 VarsWithImplicitDSA, B); 6170 if (NestedLoopCount == 0) 6171 return StmtError(); 6172 6173 assert((CurContext->isDependentContext() || B.builtAll()) && 6174 "omp parallel for loop exprs were not built"); 6175 6176 if (!CurContext->isDependentContext()) { 6177 // Finalize the clauses that need pre-built expressions for CodeGen. 6178 for (OMPClause *C : Clauses) { 6179 if (auto *LC = dyn_cast<OMPLinearClause>(C)) 6180 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef), 6181 B.NumIterations, *this, CurScope, 6182 DSAStack)) 6183 return StmtError(); 6184 } 6185 } 6186 6187 setFunctionHasBranchProtectedScope(); 6188 return OMPParallelForDirective::Create(Context, StartLoc, EndLoc, 6189 NestedLoopCount, Clauses, AStmt, B, 6190 DSAStack->isCancelRegion()); 6191 } 6192 6193 StmtResult Sema::ActOnOpenMPParallelForSimdDirective( 6194 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, 6195 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) { 6196 if (!AStmt) 6197 return StmtError(); 6198 6199 auto *CS = cast<CapturedStmt>(AStmt); 6200 // 1.2.2 OpenMP Language Terminology 6201 // Structured block - An executable statement with a single entry at the 6202 // top and a single exit at the bottom. 6203 // The point of exit cannot be a branch out of the structured block. 6204 // longjmp() and throw() must not violate the entry/exit criteria. 6205 CS->getCapturedDecl()->setNothrow(); 6206 6207 OMPLoopDirective::HelperExprs B; 6208 // In presence of clause 'collapse' or 'ordered' with number of loops, it will 6209 // define the nested loops number. 6210 unsigned NestedLoopCount = 6211 checkOpenMPLoop(OMPD_parallel_for_simd, getCollapseNumberExpr(Clauses), 6212 getOrderedNumberExpr(Clauses), AStmt, *this, *DSAStack, 6213 VarsWithImplicitDSA, B); 6214 if (NestedLoopCount == 0) 6215 return StmtError(); 6216 6217 if (!CurContext->isDependentContext()) { 6218 // Finalize the clauses that need pre-built expressions for CodeGen. 6219 for (OMPClause *C : Clauses) { 6220 if (auto *LC = dyn_cast<OMPLinearClause>(C)) 6221 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef), 6222 B.NumIterations, *this, CurScope, 6223 DSAStack)) 6224 return StmtError(); 6225 } 6226 } 6227 6228 if (checkSimdlenSafelenSpecified(*this, Clauses)) 6229 return StmtError(); 6230 6231 setFunctionHasBranchProtectedScope(); 6232 return OMPParallelForSimdDirective::Create( 6233 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B); 6234 } 6235 6236 StmtResult 6237 Sema::ActOnOpenMPParallelSectionsDirective(ArrayRef<OMPClause *> Clauses, 6238 Stmt *AStmt, SourceLocation StartLoc, 6239 SourceLocation EndLoc) { 6240 if (!AStmt) 6241 return StmtError(); 6242 6243 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected"); 6244 auto BaseStmt = AStmt; 6245 while (auto *CS = dyn_cast_or_null<CapturedStmt>(BaseStmt)) 6246 BaseStmt = CS->getCapturedStmt(); 6247 if (auto *C = dyn_cast_or_null<CompoundStmt>(BaseStmt)) { 6248 auto S = C->children(); 6249 if (S.begin() == S.end()) 6250 return StmtError(); 6251 // All associated statements must be '#pragma omp section' except for 6252 // the first one. 6253 for (Stmt *SectionStmt : llvm::make_range(std::next(S.begin()), S.end())) { 6254 if (!SectionStmt || !isa<OMPSectionDirective>(SectionStmt)) { 6255 if (SectionStmt) 6256 Diag(SectionStmt->getBeginLoc(), 6257 diag::err_omp_parallel_sections_substmt_not_section); 6258 return StmtError(); 6259 } 6260 cast<OMPSectionDirective>(SectionStmt) 6261 ->setHasCancel(DSAStack->isCancelRegion()); 6262 } 6263 } else { 6264 Diag(AStmt->getBeginLoc(), 6265 diag::err_omp_parallel_sections_not_compound_stmt); 6266 return StmtError(); 6267 } 6268 6269 setFunctionHasBranchProtectedScope(); 6270 6271 return OMPParallelSectionsDirective::Create( 6272 Context, StartLoc, EndLoc, Clauses, AStmt, DSAStack->isCancelRegion()); 6273 } 6274 6275 StmtResult Sema::ActOnOpenMPTaskDirective(ArrayRef<OMPClause *> Clauses, 6276 Stmt *AStmt, SourceLocation StartLoc, 6277 SourceLocation EndLoc) { 6278 if (!AStmt) 6279 return StmtError(); 6280 6281 auto *CS = cast<CapturedStmt>(AStmt); 6282 // 1.2.2 OpenMP Language Terminology 6283 // Structured block - An executable statement with a single entry at the 6284 // top and a single exit at the bottom. 6285 // The point of exit cannot be a branch out of the structured block. 6286 // longjmp() and throw() must not violate the entry/exit criteria. 6287 CS->getCapturedDecl()->setNothrow(); 6288 6289 setFunctionHasBranchProtectedScope(); 6290 6291 return OMPTaskDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt, 6292 DSAStack->isCancelRegion()); 6293 } 6294 6295 StmtResult Sema::ActOnOpenMPTaskyieldDirective(SourceLocation StartLoc, 6296 SourceLocation EndLoc) { 6297 return OMPTaskyieldDirective::Create(Context, StartLoc, EndLoc); 6298 } 6299 6300 StmtResult Sema::ActOnOpenMPBarrierDirective(SourceLocation StartLoc, 6301 SourceLocation EndLoc) { 6302 return OMPBarrierDirective::Create(Context, StartLoc, EndLoc); 6303 } 6304 6305 StmtResult Sema::ActOnOpenMPTaskwaitDirective(SourceLocation StartLoc, 6306 SourceLocation EndLoc) { 6307 return OMPTaskwaitDirective::Create(Context, StartLoc, EndLoc); 6308 } 6309 6310 StmtResult Sema::ActOnOpenMPTaskgroupDirective(ArrayRef<OMPClause *> Clauses, 6311 Stmt *AStmt, 6312 SourceLocation StartLoc, 6313 SourceLocation EndLoc) { 6314 if (!AStmt) 6315 return StmtError(); 6316 6317 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected"); 6318 6319 setFunctionHasBranchProtectedScope(); 6320 6321 return OMPTaskgroupDirective::Create(Context, StartLoc, EndLoc, Clauses, 6322 AStmt, 6323 DSAStack->getTaskgroupReductionRef()); 6324 } 6325 6326 StmtResult Sema::ActOnOpenMPFlushDirective(ArrayRef<OMPClause *> Clauses, 6327 SourceLocation StartLoc, 6328 SourceLocation EndLoc) { 6329 assert(Clauses.size() <= 1 && "Extra clauses in flush directive"); 6330 return OMPFlushDirective::Create(Context, StartLoc, EndLoc, Clauses); 6331 } 6332 6333 StmtResult Sema::ActOnOpenMPOrderedDirective(ArrayRef<OMPClause *> Clauses, 6334 Stmt *AStmt, 6335 SourceLocation StartLoc, 6336 SourceLocation EndLoc) { 6337 const OMPClause *DependFound = nullptr; 6338 const OMPClause *DependSourceClause = nullptr; 6339 const OMPClause *DependSinkClause = nullptr; 6340 bool ErrorFound = false; 6341 const OMPThreadsClause *TC = nullptr; 6342 const OMPSIMDClause *SC = nullptr; 6343 for (const OMPClause *C : Clauses) { 6344 if (auto *DC = dyn_cast<OMPDependClause>(C)) { 6345 DependFound = C; 6346 if (DC->getDependencyKind() == OMPC_DEPEND_source) { 6347 if (DependSourceClause) { 6348 Diag(C->getBeginLoc(), diag::err_omp_more_one_clause) 6349 << getOpenMPDirectiveName(OMPD_ordered) 6350 << getOpenMPClauseName(OMPC_depend) << 2; 6351 ErrorFound = true; 6352 } else { 6353 DependSourceClause = C; 6354 } 6355 if (DependSinkClause) { 6356 Diag(C->getBeginLoc(), diag::err_omp_depend_sink_source_not_allowed) 6357 << 0; 6358 ErrorFound = true; 6359 } 6360 } else if (DC->getDependencyKind() == OMPC_DEPEND_sink) { 6361 if (DependSourceClause) { 6362 Diag(C->getBeginLoc(), diag::err_omp_depend_sink_source_not_allowed) 6363 << 1; 6364 ErrorFound = true; 6365 } 6366 DependSinkClause = C; 6367 } 6368 } else if (C->getClauseKind() == OMPC_threads) { 6369 TC = cast<OMPThreadsClause>(C); 6370 } else if (C->getClauseKind() == OMPC_simd) { 6371 SC = cast<OMPSIMDClause>(C); 6372 } 6373 } 6374 if (!ErrorFound && !SC && 6375 isOpenMPSimdDirective(DSAStack->getParentDirective())) { 6376 // OpenMP [2.8.1,simd Construct, Restrictions] 6377 // An ordered construct with the simd clause is the only OpenMP construct 6378 // that can appear in the simd region. 6379 Diag(StartLoc, diag::err_omp_prohibited_region_simd); 6380 ErrorFound = true; 6381 } else if (DependFound && (TC || SC)) { 6382 Diag(DependFound->getBeginLoc(), diag::err_omp_depend_clause_thread_simd) 6383 << getOpenMPClauseName(TC ? TC->getClauseKind() : SC->getClauseKind()); 6384 ErrorFound = true; 6385 } else if (DependFound && !DSAStack->getParentOrderedRegionParam().first) { 6386 Diag(DependFound->getBeginLoc(), 6387 diag::err_omp_ordered_directive_without_param); 6388 ErrorFound = true; 6389 } else if (TC || Clauses.empty()) { 6390 if (const Expr *Param = DSAStack->getParentOrderedRegionParam().first) { 6391 SourceLocation ErrLoc = TC ? TC->getBeginLoc() : StartLoc; 6392 Diag(ErrLoc, diag::err_omp_ordered_directive_with_param) 6393 << (TC != nullptr); 6394 Diag(Param->getBeginLoc(), diag::note_omp_ordered_param); 6395 ErrorFound = true; 6396 } 6397 } 6398 if ((!AStmt && !DependFound) || ErrorFound) 6399 return StmtError(); 6400 6401 if (AStmt) { 6402 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected"); 6403 6404 setFunctionHasBranchProtectedScope(); 6405 } 6406 6407 return OMPOrderedDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt); 6408 } 6409 6410 namespace { 6411 /// Helper class for checking expression in 'omp atomic [update]' 6412 /// construct. 6413 class OpenMPAtomicUpdateChecker { 6414 /// Error results for atomic update expressions. 6415 enum ExprAnalysisErrorCode { 6416 /// A statement is not an expression statement. 6417 NotAnExpression, 6418 /// Expression is not builtin binary or unary operation. 6419 NotABinaryOrUnaryExpression, 6420 /// Unary operation is not post-/pre- increment/decrement operation. 6421 NotAnUnaryIncDecExpression, 6422 /// An expression is not of scalar type. 6423 NotAScalarType, 6424 /// A binary operation is not an assignment operation. 6425 NotAnAssignmentOp, 6426 /// RHS part of the binary operation is not a binary expression. 6427 NotABinaryExpression, 6428 /// RHS part is not additive/multiplicative/shift/biwise binary 6429 /// expression. 6430 NotABinaryOperator, 6431 /// RHS binary operation does not have reference to the updated LHS 6432 /// part. 6433 NotAnUpdateExpression, 6434 /// No errors is found. 6435 NoError 6436 }; 6437 /// Reference to Sema. 6438 Sema &SemaRef; 6439 /// A location for note diagnostics (when error is found). 6440 SourceLocation NoteLoc; 6441 /// 'x' lvalue part of the source atomic expression. 6442 Expr *X; 6443 /// 'expr' rvalue part of the source atomic expression. 6444 Expr *E; 6445 /// Helper expression of the form 6446 /// 'OpaqueValueExpr(x) binop OpaqueValueExpr(expr)' or 6447 /// 'OpaqueValueExpr(expr) binop OpaqueValueExpr(x)'. 6448 Expr *UpdateExpr; 6449 /// Is 'x' a LHS in a RHS part of full update expression. It is 6450 /// important for non-associative operations. 6451 bool IsXLHSInRHSPart; 6452 BinaryOperatorKind Op; 6453 SourceLocation OpLoc; 6454 /// true if the source expression is a postfix unary operation, false 6455 /// if it is a prefix unary operation. 6456 bool IsPostfixUpdate; 6457 6458 public: 6459 OpenMPAtomicUpdateChecker(Sema &SemaRef) 6460 : SemaRef(SemaRef), X(nullptr), E(nullptr), UpdateExpr(nullptr), 6461 IsXLHSInRHSPart(false), Op(BO_PtrMemD), IsPostfixUpdate(false) {} 6462 /// Check specified statement that it is suitable for 'atomic update' 6463 /// constructs and extract 'x', 'expr' and Operation from the original 6464 /// expression. If DiagId and NoteId == 0, then only check is performed 6465 /// without error notification. 6466 /// \param DiagId Diagnostic which should be emitted if error is found. 6467 /// \param NoteId Diagnostic note for the main error message. 6468 /// \return true if statement is not an update expression, false otherwise. 6469 bool checkStatement(Stmt *S, unsigned DiagId = 0, unsigned NoteId = 0); 6470 /// Return the 'x' lvalue part of the source atomic expression. 6471 Expr *getX() const { return X; } 6472 /// Return the 'expr' rvalue part of the source atomic expression. 6473 Expr *getExpr() const { return E; } 6474 /// Return the update expression used in calculation of the updated 6475 /// value. Always has form 'OpaqueValueExpr(x) binop OpaqueValueExpr(expr)' or 6476 /// 'OpaqueValueExpr(expr) binop OpaqueValueExpr(x)'. 6477 Expr *getUpdateExpr() const { return UpdateExpr; } 6478 /// Return true if 'x' is LHS in RHS part of full update expression, 6479 /// false otherwise. 6480 bool isXLHSInRHSPart() const { return IsXLHSInRHSPart; } 6481 6482 /// true if the source expression is a postfix unary operation, false 6483 /// if it is a prefix unary operation. 6484 bool isPostfixUpdate() const { return IsPostfixUpdate; } 6485 6486 private: 6487 bool checkBinaryOperation(BinaryOperator *AtomicBinOp, unsigned DiagId = 0, 6488 unsigned NoteId = 0); 6489 }; 6490 } // namespace 6491 6492 bool OpenMPAtomicUpdateChecker::checkBinaryOperation( 6493 BinaryOperator *AtomicBinOp, unsigned DiagId, unsigned NoteId) { 6494 ExprAnalysisErrorCode ErrorFound = NoError; 6495 SourceLocation ErrorLoc, NoteLoc; 6496 SourceRange ErrorRange, NoteRange; 6497 // Allowed constructs are: 6498 // x = x binop expr; 6499 // x = expr binop x; 6500 if (AtomicBinOp->getOpcode() == BO_Assign) { 6501 X = AtomicBinOp->getLHS(); 6502 if (const auto *AtomicInnerBinOp = dyn_cast<BinaryOperator>( 6503 AtomicBinOp->getRHS()->IgnoreParenImpCasts())) { 6504 if (AtomicInnerBinOp->isMultiplicativeOp() || 6505 AtomicInnerBinOp->isAdditiveOp() || AtomicInnerBinOp->isShiftOp() || 6506 AtomicInnerBinOp->isBitwiseOp()) { 6507 Op = AtomicInnerBinOp->getOpcode(); 6508 OpLoc = AtomicInnerBinOp->getOperatorLoc(); 6509 Expr *LHS = AtomicInnerBinOp->getLHS(); 6510 Expr *RHS = AtomicInnerBinOp->getRHS(); 6511 llvm::FoldingSetNodeID XId, LHSId, RHSId; 6512 X->IgnoreParenImpCasts()->Profile(XId, SemaRef.getASTContext(), 6513 /*Canonical=*/true); 6514 LHS->IgnoreParenImpCasts()->Profile(LHSId, SemaRef.getASTContext(), 6515 /*Canonical=*/true); 6516 RHS->IgnoreParenImpCasts()->Profile(RHSId, SemaRef.getASTContext(), 6517 /*Canonical=*/true); 6518 if (XId == LHSId) { 6519 E = RHS; 6520 IsXLHSInRHSPart = true; 6521 } else if (XId == RHSId) { 6522 E = LHS; 6523 IsXLHSInRHSPart = false; 6524 } else { 6525 ErrorLoc = AtomicInnerBinOp->getExprLoc(); 6526 ErrorRange = AtomicInnerBinOp->getSourceRange(); 6527 NoteLoc = X->getExprLoc(); 6528 NoteRange = X->getSourceRange(); 6529 ErrorFound = NotAnUpdateExpression; 6530 } 6531 } else { 6532 ErrorLoc = AtomicInnerBinOp->getExprLoc(); 6533 ErrorRange = AtomicInnerBinOp->getSourceRange(); 6534 NoteLoc = AtomicInnerBinOp->getOperatorLoc(); 6535 NoteRange = SourceRange(NoteLoc, NoteLoc); 6536 ErrorFound = NotABinaryOperator; 6537 } 6538 } else { 6539 NoteLoc = ErrorLoc = AtomicBinOp->getRHS()->getExprLoc(); 6540 NoteRange = ErrorRange = AtomicBinOp->getRHS()->getSourceRange(); 6541 ErrorFound = NotABinaryExpression; 6542 } 6543 } else { 6544 ErrorLoc = AtomicBinOp->getExprLoc(); 6545 ErrorRange = AtomicBinOp->getSourceRange(); 6546 NoteLoc = AtomicBinOp->getOperatorLoc(); 6547 NoteRange = SourceRange(NoteLoc, NoteLoc); 6548 ErrorFound = NotAnAssignmentOp; 6549 } 6550 if (ErrorFound != NoError && DiagId != 0 && NoteId != 0) { 6551 SemaRef.Diag(ErrorLoc, DiagId) << ErrorRange; 6552 SemaRef.Diag(NoteLoc, NoteId) << ErrorFound << NoteRange; 6553 return true; 6554 } 6555 if (SemaRef.CurContext->isDependentContext()) 6556 E = X = UpdateExpr = nullptr; 6557 return ErrorFound != NoError; 6558 } 6559 6560 bool OpenMPAtomicUpdateChecker::checkStatement(Stmt *S, unsigned DiagId, 6561 unsigned NoteId) { 6562 ExprAnalysisErrorCode ErrorFound = NoError; 6563 SourceLocation ErrorLoc, NoteLoc; 6564 SourceRange ErrorRange, NoteRange; 6565 // Allowed constructs are: 6566 // x++; 6567 // x--; 6568 // ++x; 6569 // --x; 6570 // x binop= expr; 6571 // x = x binop expr; 6572 // x = expr binop x; 6573 if (auto *AtomicBody = dyn_cast<Expr>(S)) { 6574 AtomicBody = AtomicBody->IgnoreParenImpCasts(); 6575 if (AtomicBody->getType()->isScalarType() || 6576 AtomicBody->isInstantiationDependent()) { 6577 if (const auto *AtomicCompAssignOp = dyn_cast<CompoundAssignOperator>( 6578 AtomicBody->IgnoreParenImpCasts())) { 6579 // Check for Compound Assignment Operation 6580 Op = BinaryOperator::getOpForCompoundAssignment( 6581 AtomicCompAssignOp->getOpcode()); 6582 OpLoc = AtomicCompAssignOp->getOperatorLoc(); 6583 E = AtomicCompAssignOp->getRHS(); 6584 X = AtomicCompAssignOp->getLHS()->IgnoreParens(); 6585 IsXLHSInRHSPart = true; 6586 } else if (auto *AtomicBinOp = dyn_cast<BinaryOperator>( 6587 AtomicBody->IgnoreParenImpCasts())) { 6588 // Check for Binary Operation 6589 if (checkBinaryOperation(AtomicBinOp, DiagId, NoteId)) 6590 return true; 6591 } else if (const auto *AtomicUnaryOp = dyn_cast<UnaryOperator>( 6592 AtomicBody->IgnoreParenImpCasts())) { 6593 // Check for Unary Operation 6594 if (AtomicUnaryOp->isIncrementDecrementOp()) { 6595 IsPostfixUpdate = AtomicUnaryOp->isPostfix(); 6596 Op = AtomicUnaryOp->isIncrementOp() ? BO_Add : BO_Sub; 6597 OpLoc = AtomicUnaryOp->getOperatorLoc(); 6598 X = AtomicUnaryOp->getSubExpr()->IgnoreParens(); 6599 E = SemaRef.ActOnIntegerConstant(OpLoc, /*uint64_t Val=*/1).get(); 6600 IsXLHSInRHSPart = true; 6601 } else { 6602 ErrorFound = NotAnUnaryIncDecExpression; 6603 ErrorLoc = AtomicUnaryOp->getExprLoc(); 6604 ErrorRange = AtomicUnaryOp->getSourceRange(); 6605 NoteLoc = AtomicUnaryOp->getOperatorLoc(); 6606 NoteRange = SourceRange(NoteLoc, NoteLoc); 6607 } 6608 } else if (!AtomicBody->isInstantiationDependent()) { 6609 ErrorFound = NotABinaryOrUnaryExpression; 6610 NoteLoc = ErrorLoc = AtomicBody->getExprLoc(); 6611 NoteRange = ErrorRange = AtomicBody->getSourceRange(); 6612 } 6613 } else { 6614 ErrorFound = NotAScalarType; 6615 NoteLoc = ErrorLoc = AtomicBody->getBeginLoc(); 6616 NoteRange = ErrorRange = SourceRange(NoteLoc, NoteLoc); 6617 } 6618 } else { 6619 ErrorFound = NotAnExpression; 6620 NoteLoc = ErrorLoc = S->getBeginLoc(); 6621 NoteRange = ErrorRange = SourceRange(NoteLoc, NoteLoc); 6622 } 6623 if (ErrorFound != NoError && DiagId != 0 && NoteId != 0) { 6624 SemaRef.Diag(ErrorLoc, DiagId) << ErrorRange; 6625 SemaRef.Diag(NoteLoc, NoteId) << ErrorFound << NoteRange; 6626 return true; 6627 } 6628 if (SemaRef.CurContext->isDependentContext()) 6629 E = X = UpdateExpr = nullptr; 6630 if (ErrorFound == NoError && E && X) { 6631 // Build an update expression of form 'OpaqueValueExpr(x) binop 6632 // OpaqueValueExpr(expr)' or 'OpaqueValueExpr(expr) binop 6633 // OpaqueValueExpr(x)' and then cast it to the type of the 'x' expression. 6634 auto *OVEX = new (SemaRef.getASTContext()) 6635 OpaqueValueExpr(X->getExprLoc(), X->getType(), VK_RValue); 6636 auto *OVEExpr = new (SemaRef.getASTContext()) 6637 OpaqueValueExpr(E->getExprLoc(), E->getType(), VK_RValue); 6638 ExprResult Update = 6639 SemaRef.CreateBuiltinBinOp(OpLoc, Op, IsXLHSInRHSPart ? OVEX : OVEExpr, 6640 IsXLHSInRHSPart ? OVEExpr : OVEX); 6641 if (Update.isInvalid()) 6642 return true; 6643 Update = SemaRef.PerformImplicitConversion(Update.get(), X->getType(), 6644 Sema::AA_Casting); 6645 if (Update.isInvalid()) 6646 return true; 6647 UpdateExpr = Update.get(); 6648 } 6649 return ErrorFound != NoError; 6650 } 6651 6652 StmtResult Sema::ActOnOpenMPAtomicDirective(ArrayRef<OMPClause *> Clauses, 6653 Stmt *AStmt, 6654 SourceLocation StartLoc, 6655 SourceLocation EndLoc) { 6656 if (!AStmt) 6657 return StmtError(); 6658 6659 auto *CS = cast<CapturedStmt>(AStmt); 6660 // 1.2.2 OpenMP Language Terminology 6661 // Structured block - An executable statement with a single entry at the 6662 // top and a single exit at the bottom. 6663 // The point of exit cannot be a branch out of the structured block. 6664 // longjmp() and throw() must not violate the entry/exit criteria. 6665 OpenMPClauseKind AtomicKind = OMPC_unknown; 6666 SourceLocation AtomicKindLoc; 6667 for (const OMPClause *C : Clauses) { 6668 if (C->getClauseKind() == OMPC_read || C->getClauseKind() == OMPC_write || 6669 C->getClauseKind() == OMPC_update || 6670 C->getClauseKind() == OMPC_capture) { 6671 if (AtomicKind != OMPC_unknown) { 6672 Diag(C->getBeginLoc(), diag::err_omp_atomic_several_clauses) 6673 << SourceRange(C->getBeginLoc(), C->getEndLoc()); 6674 Diag(AtomicKindLoc, diag::note_omp_atomic_previous_clause) 6675 << getOpenMPClauseName(AtomicKind); 6676 } else { 6677 AtomicKind = C->getClauseKind(); 6678 AtomicKindLoc = C->getBeginLoc(); 6679 } 6680 } 6681 } 6682 6683 Stmt *Body = CS->getCapturedStmt(); 6684 if (auto *EWC = dyn_cast<ExprWithCleanups>(Body)) 6685 Body = EWC->getSubExpr(); 6686 6687 Expr *X = nullptr; 6688 Expr *V = nullptr; 6689 Expr *E = nullptr; 6690 Expr *UE = nullptr; 6691 bool IsXLHSInRHSPart = false; 6692 bool IsPostfixUpdate = false; 6693 // OpenMP [2.12.6, atomic Construct] 6694 // In the next expressions: 6695 // * x and v (as applicable) are both l-value expressions with scalar type. 6696 // * During the execution of an atomic region, multiple syntactic 6697 // occurrences of x must designate the same storage location. 6698 // * Neither of v and expr (as applicable) may access the storage location 6699 // designated by x. 6700 // * Neither of x and expr (as applicable) may access the storage location 6701 // designated by v. 6702 // * expr is an expression with scalar type. 6703 // * binop is one of +, *, -, /, &, ^, |, <<, or >>. 6704 // * binop, binop=, ++, and -- are not overloaded operators. 6705 // * The expression x binop expr must be numerically equivalent to x binop 6706 // (expr). This requirement is satisfied if the operators in expr have 6707 // precedence greater than binop, or by using parentheses around expr or 6708 // subexpressions of expr. 6709 // * The expression expr binop x must be numerically equivalent to (expr) 6710 // binop x. This requirement is satisfied if the operators in expr have 6711 // precedence equal to or greater than binop, or by using parentheses around 6712 // expr or subexpressions of expr. 6713 // * For forms that allow multiple occurrences of x, the number of times 6714 // that x is evaluated is unspecified. 6715 if (AtomicKind == OMPC_read) { 6716 enum { 6717 NotAnExpression, 6718 NotAnAssignmentOp, 6719 NotAScalarType, 6720 NotAnLValue, 6721 NoError 6722 } ErrorFound = NoError; 6723 SourceLocation ErrorLoc, NoteLoc; 6724 SourceRange ErrorRange, NoteRange; 6725 // If clause is read: 6726 // v = x; 6727 if (const auto *AtomicBody = dyn_cast<Expr>(Body)) { 6728 const auto *AtomicBinOp = 6729 dyn_cast<BinaryOperator>(AtomicBody->IgnoreParenImpCasts()); 6730 if (AtomicBinOp && AtomicBinOp->getOpcode() == BO_Assign) { 6731 X = AtomicBinOp->getRHS()->IgnoreParenImpCasts(); 6732 V = AtomicBinOp->getLHS()->IgnoreParenImpCasts(); 6733 if ((X->isInstantiationDependent() || X->getType()->isScalarType()) && 6734 (V->isInstantiationDependent() || V->getType()->isScalarType())) { 6735 if (!X->isLValue() || !V->isLValue()) { 6736 const Expr *NotLValueExpr = X->isLValue() ? V : X; 6737 ErrorFound = NotAnLValue; 6738 ErrorLoc = AtomicBinOp->getExprLoc(); 6739 ErrorRange = AtomicBinOp->getSourceRange(); 6740 NoteLoc = NotLValueExpr->getExprLoc(); 6741 NoteRange = NotLValueExpr->getSourceRange(); 6742 } 6743 } else if (!X->isInstantiationDependent() || 6744 !V->isInstantiationDependent()) { 6745 const Expr *NotScalarExpr = 6746 (X->isInstantiationDependent() || X->getType()->isScalarType()) 6747 ? V 6748 : X; 6749 ErrorFound = NotAScalarType; 6750 ErrorLoc = AtomicBinOp->getExprLoc(); 6751 ErrorRange = AtomicBinOp->getSourceRange(); 6752 NoteLoc = NotScalarExpr->getExprLoc(); 6753 NoteRange = NotScalarExpr->getSourceRange(); 6754 } 6755 } else if (!AtomicBody->isInstantiationDependent()) { 6756 ErrorFound = NotAnAssignmentOp; 6757 ErrorLoc = AtomicBody->getExprLoc(); 6758 ErrorRange = AtomicBody->getSourceRange(); 6759 NoteLoc = AtomicBinOp ? AtomicBinOp->getOperatorLoc() 6760 : AtomicBody->getExprLoc(); 6761 NoteRange = AtomicBinOp ? AtomicBinOp->getSourceRange() 6762 : AtomicBody->getSourceRange(); 6763 } 6764 } else { 6765 ErrorFound = NotAnExpression; 6766 NoteLoc = ErrorLoc = Body->getBeginLoc(); 6767 NoteRange = ErrorRange = SourceRange(NoteLoc, NoteLoc); 6768 } 6769 if (ErrorFound != NoError) { 6770 Diag(ErrorLoc, diag::err_omp_atomic_read_not_expression_statement) 6771 << ErrorRange; 6772 Diag(NoteLoc, diag::note_omp_atomic_read_write) << ErrorFound 6773 << NoteRange; 6774 return StmtError(); 6775 } 6776 if (CurContext->isDependentContext()) 6777 V = X = nullptr; 6778 } else if (AtomicKind == OMPC_write) { 6779 enum { 6780 NotAnExpression, 6781 NotAnAssignmentOp, 6782 NotAScalarType, 6783 NotAnLValue, 6784 NoError 6785 } ErrorFound = NoError; 6786 SourceLocation ErrorLoc, NoteLoc; 6787 SourceRange ErrorRange, NoteRange; 6788 // If clause is write: 6789 // x = expr; 6790 if (const auto *AtomicBody = dyn_cast<Expr>(Body)) { 6791 const auto *AtomicBinOp = 6792 dyn_cast<BinaryOperator>(AtomicBody->IgnoreParenImpCasts()); 6793 if (AtomicBinOp && AtomicBinOp->getOpcode() == BO_Assign) { 6794 X = AtomicBinOp->getLHS(); 6795 E = AtomicBinOp->getRHS(); 6796 if ((X->isInstantiationDependent() || X->getType()->isScalarType()) && 6797 (E->isInstantiationDependent() || E->getType()->isScalarType())) { 6798 if (!X->isLValue()) { 6799 ErrorFound = NotAnLValue; 6800 ErrorLoc = AtomicBinOp->getExprLoc(); 6801 ErrorRange = AtomicBinOp->getSourceRange(); 6802 NoteLoc = X->getExprLoc(); 6803 NoteRange = X->getSourceRange(); 6804 } 6805 } else if (!X->isInstantiationDependent() || 6806 !E->isInstantiationDependent()) { 6807 const Expr *NotScalarExpr = 6808 (X->isInstantiationDependent() || X->getType()->isScalarType()) 6809 ? E 6810 : X; 6811 ErrorFound = NotAScalarType; 6812 ErrorLoc = AtomicBinOp->getExprLoc(); 6813 ErrorRange = AtomicBinOp->getSourceRange(); 6814 NoteLoc = NotScalarExpr->getExprLoc(); 6815 NoteRange = NotScalarExpr->getSourceRange(); 6816 } 6817 } else if (!AtomicBody->isInstantiationDependent()) { 6818 ErrorFound = NotAnAssignmentOp; 6819 ErrorLoc = AtomicBody->getExprLoc(); 6820 ErrorRange = AtomicBody->getSourceRange(); 6821 NoteLoc = AtomicBinOp ? AtomicBinOp->getOperatorLoc() 6822 : AtomicBody->getExprLoc(); 6823 NoteRange = AtomicBinOp ? AtomicBinOp->getSourceRange() 6824 : AtomicBody->getSourceRange(); 6825 } 6826 } else { 6827 ErrorFound = NotAnExpression; 6828 NoteLoc = ErrorLoc = Body->getBeginLoc(); 6829 NoteRange = ErrorRange = SourceRange(NoteLoc, NoteLoc); 6830 } 6831 if (ErrorFound != NoError) { 6832 Diag(ErrorLoc, diag::err_omp_atomic_write_not_expression_statement) 6833 << ErrorRange; 6834 Diag(NoteLoc, diag::note_omp_atomic_read_write) << ErrorFound 6835 << NoteRange; 6836 return StmtError(); 6837 } 6838 if (CurContext->isDependentContext()) 6839 E = X = nullptr; 6840 } else if (AtomicKind == OMPC_update || AtomicKind == OMPC_unknown) { 6841 // If clause is update: 6842 // x++; 6843 // x--; 6844 // ++x; 6845 // --x; 6846 // x binop= expr; 6847 // x = x binop expr; 6848 // x = expr binop x; 6849 OpenMPAtomicUpdateChecker Checker(*this); 6850 if (Checker.checkStatement( 6851 Body, (AtomicKind == OMPC_update) 6852 ? diag::err_omp_atomic_update_not_expression_statement 6853 : diag::err_omp_atomic_not_expression_statement, 6854 diag::note_omp_atomic_update)) 6855 return StmtError(); 6856 if (!CurContext->isDependentContext()) { 6857 E = Checker.getExpr(); 6858 X = Checker.getX(); 6859 UE = Checker.getUpdateExpr(); 6860 IsXLHSInRHSPart = Checker.isXLHSInRHSPart(); 6861 } 6862 } else if (AtomicKind == OMPC_capture) { 6863 enum { 6864 NotAnAssignmentOp, 6865 NotACompoundStatement, 6866 NotTwoSubstatements, 6867 NotASpecificExpression, 6868 NoError 6869 } ErrorFound = NoError; 6870 SourceLocation ErrorLoc, NoteLoc; 6871 SourceRange ErrorRange, NoteRange; 6872 if (const auto *AtomicBody = dyn_cast<Expr>(Body)) { 6873 // If clause is a capture: 6874 // v = x++; 6875 // v = x--; 6876 // v = ++x; 6877 // v = --x; 6878 // v = x binop= expr; 6879 // v = x = x binop expr; 6880 // v = x = expr binop x; 6881 const auto *AtomicBinOp = 6882 dyn_cast<BinaryOperator>(AtomicBody->IgnoreParenImpCasts()); 6883 if (AtomicBinOp && AtomicBinOp->getOpcode() == BO_Assign) { 6884 V = AtomicBinOp->getLHS(); 6885 Body = AtomicBinOp->getRHS()->IgnoreParenImpCasts(); 6886 OpenMPAtomicUpdateChecker Checker(*this); 6887 if (Checker.checkStatement( 6888 Body, diag::err_omp_atomic_capture_not_expression_statement, 6889 diag::note_omp_atomic_update)) 6890 return StmtError(); 6891 E = Checker.getExpr(); 6892 X = Checker.getX(); 6893 UE = Checker.getUpdateExpr(); 6894 IsXLHSInRHSPart = Checker.isXLHSInRHSPart(); 6895 IsPostfixUpdate = Checker.isPostfixUpdate(); 6896 } else if (!AtomicBody->isInstantiationDependent()) { 6897 ErrorLoc = AtomicBody->getExprLoc(); 6898 ErrorRange = AtomicBody->getSourceRange(); 6899 NoteLoc = AtomicBinOp ? AtomicBinOp->getOperatorLoc() 6900 : AtomicBody->getExprLoc(); 6901 NoteRange = AtomicBinOp ? AtomicBinOp->getSourceRange() 6902 : AtomicBody->getSourceRange(); 6903 ErrorFound = NotAnAssignmentOp; 6904 } 6905 if (ErrorFound != NoError) { 6906 Diag(ErrorLoc, diag::err_omp_atomic_capture_not_expression_statement) 6907 << ErrorRange; 6908 Diag(NoteLoc, diag::note_omp_atomic_capture) << ErrorFound << NoteRange; 6909 return StmtError(); 6910 } 6911 if (CurContext->isDependentContext()) 6912 UE = V = E = X = nullptr; 6913 } else { 6914 // If clause is a capture: 6915 // { v = x; x = expr; } 6916 // { v = x; x++; } 6917 // { v = x; x--; } 6918 // { v = x; ++x; } 6919 // { v = x; --x; } 6920 // { v = x; x binop= expr; } 6921 // { v = x; x = x binop expr; } 6922 // { v = x; x = expr binop x; } 6923 // { x++; v = x; } 6924 // { x--; v = x; } 6925 // { ++x; v = x; } 6926 // { --x; v = x; } 6927 // { x binop= expr; v = x; } 6928 // { x = x binop expr; v = x; } 6929 // { x = expr binop x; v = x; } 6930 if (auto *CS = dyn_cast<CompoundStmt>(Body)) { 6931 // Check that this is { expr1; expr2; } 6932 if (CS->size() == 2) { 6933 Stmt *First = CS->body_front(); 6934 Stmt *Second = CS->body_back(); 6935 if (auto *EWC = dyn_cast<ExprWithCleanups>(First)) 6936 First = EWC->getSubExpr()->IgnoreParenImpCasts(); 6937 if (auto *EWC = dyn_cast<ExprWithCleanups>(Second)) 6938 Second = EWC->getSubExpr()->IgnoreParenImpCasts(); 6939 // Need to find what subexpression is 'v' and what is 'x'. 6940 OpenMPAtomicUpdateChecker Checker(*this); 6941 bool IsUpdateExprFound = !Checker.checkStatement(Second); 6942 BinaryOperator *BinOp = nullptr; 6943 if (IsUpdateExprFound) { 6944 BinOp = dyn_cast<BinaryOperator>(First); 6945 IsUpdateExprFound = BinOp && BinOp->getOpcode() == BO_Assign; 6946 } 6947 if (IsUpdateExprFound && !CurContext->isDependentContext()) { 6948 // { v = x; x++; } 6949 // { v = x; x--; } 6950 // { v = x; ++x; } 6951 // { v = x; --x; } 6952 // { v = x; x binop= expr; } 6953 // { v = x; x = x binop expr; } 6954 // { v = x; x = expr binop x; } 6955 // Check that the first expression has form v = x. 6956 Expr *PossibleX = BinOp->getRHS()->IgnoreParenImpCasts(); 6957 llvm::FoldingSetNodeID XId, PossibleXId; 6958 Checker.getX()->Profile(XId, Context, /*Canonical=*/true); 6959 PossibleX->Profile(PossibleXId, Context, /*Canonical=*/true); 6960 IsUpdateExprFound = XId == PossibleXId; 6961 if (IsUpdateExprFound) { 6962 V = BinOp->getLHS(); 6963 X = Checker.getX(); 6964 E = Checker.getExpr(); 6965 UE = Checker.getUpdateExpr(); 6966 IsXLHSInRHSPart = Checker.isXLHSInRHSPart(); 6967 IsPostfixUpdate = true; 6968 } 6969 } 6970 if (!IsUpdateExprFound) { 6971 IsUpdateExprFound = !Checker.checkStatement(First); 6972 BinOp = nullptr; 6973 if (IsUpdateExprFound) { 6974 BinOp = dyn_cast<BinaryOperator>(Second); 6975 IsUpdateExprFound = BinOp && BinOp->getOpcode() == BO_Assign; 6976 } 6977 if (IsUpdateExprFound && !CurContext->isDependentContext()) { 6978 // { x++; v = x; } 6979 // { x--; v = x; } 6980 // { ++x; v = x; } 6981 // { --x; v = x; } 6982 // { x binop= expr; v = x; } 6983 // { x = x binop expr; v = x; } 6984 // { x = expr binop x; v = x; } 6985 // Check that the second expression has form v = x. 6986 Expr *PossibleX = BinOp->getRHS()->IgnoreParenImpCasts(); 6987 llvm::FoldingSetNodeID XId, PossibleXId; 6988 Checker.getX()->Profile(XId, Context, /*Canonical=*/true); 6989 PossibleX->Profile(PossibleXId, Context, /*Canonical=*/true); 6990 IsUpdateExprFound = XId == PossibleXId; 6991 if (IsUpdateExprFound) { 6992 V = BinOp->getLHS(); 6993 X = Checker.getX(); 6994 E = Checker.getExpr(); 6995 UE = Checker.getUpdateExpr(); 6996 IsXLHSInRHSPart = Checker.isXLHSInRHSPart(); 6997 IsPostfixUpdate = false; 6998 } 6999 } 7000 } 7001 if (!IsUpdateExprFound) { 7002 // { v = x; x = expr; } 7003 auto *FirstExpr = dyn_cast<Expr>(First); 7004 auto *SecondExpr = dyn_cast<Expr>(Second); 7005 if (!FirstExpr || !SecondExpr || 7006 !(FirstExpr->isInstantiationDependent() || 7007 SecondExpr->isInstantiationDependent())) { 7008 auto *FirstBinOp = dyn_cast<BinaryOperator>(First); 7009 if (!FirstBinOp || FirstBinOp->getOpcode() != BO_Assign) { 7010 ErrorFound = NotAnAssignmentOp; 7011 NoteLoc = ErrorLoc = FirstBinOp ? FirstBinOp->getOperatorLoc() 7012 : First->getBeginLoc(); 7013 NoteRange = ErrorRange = FirstBinOp 7014 ? FirstBinOp->getSourceRange() 7015 : SourceRange(ErrorLoc, ErrorLoc); 7016 } else { 7017 auto *SecondBinOp = dyn_cast<BinaryOperator>(Second); 7018 if (!SecondBinOp || SecondBinOp->getOpcode() != BO_Assign) { 7019 ErrorFound = NotAnAssignmentOp; 7020 NoteLoc = ErrorLoc = SecondBinOp 7021 ? SecondBinOp->getOperatorLoc() 7022 : Second->getBeginLoc(); 7023 NoteRange = ErrorRange = 7024 SecondBinOp ? SecondBinOp->getSourceRange() 7025 : SourceRange(ErrorLoc, ErrorLoc); 7026 } else { 7027 Expr *PossibleXRHSInFirst = 7028 FirstBinOp->getRHS()->IgnoreParenImpCasts(); 7029 Expr *PossibleXLHSInSecond = 7030 SecondBinOp->getLHS()->IgnoreParenImpCasts(); 7031 llvm::FoldingSetNodeID X1Id, X2Id; 7032 PossibleXRHSInFirst->Profile(X1Id, Context, 7033 /*Canonical=*/true); 7034 PossibleXLHSInSecond->Profile(X2Id, Context, 7035 /*Canonical=*/true); 7036 IsUpdateExprFound = X1Id == X2Id; 7037 if (IsUpdateExprFound) { 7038 V = FirstBinOp->getLHS(); 7039 X = SecondBinOp->getLHS(); 7040 E = SecondBinOp->getRHS(); 7041 UE = nullptr; 7042 IsXLHSInRHSPart = false; 7043 IsPostfixUpdate = true; 7044 } else { 7045 ErrorFound = NotASpecificExpression; 7046 ErrorLoc = FirstBinOp->getExprLoc(); 7047 ErrorRange = FirstBinOp->getSourceRange(); 7048 NoteLoc = SecondBinOp->getLHS()->getExprLoc(); 7049 NoteRange = SecondBinOp->getRHS()->getSourceRange(); 7050 } 7051 } 7052 } 7053 } 7054 } 7055 } else { 7056 NoteLoc = ErrorLoc = Body->getBeginLoc(); 7057 NoteRange = ErrorRange = 7058 SourceRange(Body->getBeginLoc(), Body->getBeginLoc()); 7059 ErrorFound = NotTwoSubstatements; 7060 } 7061 } else { 7062 NoteLoc = ErrorLoc = Body->getBeginLoc(); 7063 NoteRange = ErrorRange = 7064 SourceRange(Body->getBeginLoc(), Body->getBeginLoc()); 7065 ErrorFound = NotACompoundStatement; 7066 } 7067 if (ErrorFound != NoError) { 7068 Diag(ErrorLoc, diag::err_omp_atomic_capture_not_compound_statement) 7069 << ErrorRange; 7070 Diag(NoteLoc, diag::note_omp_atomic_capture) << ErrorFound << NoteRange; 7071 return StmtError(); 7072 } 7073 if (CurContext->isDependentContext()) 7074 UE = V = E = X = nullptr; 7075 } 7076 } 7077 7078 setFunctionHasBranchProtectedScope(); 7079 7080 return OMPAtomicDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt, 7081 X, V, E, UE, IsXLHSInRHSPart, 7082 IsPostfixUpdate); 7083 } 7084 7085 StmtResult Sema::ActOnOpenMPTargetDirective(ArrayRef<OMPClause *> Clauses, 7086 Stmt *AStmt, 7087 SourceLocation StartLoc, 7088 SourceLocation EndLoc) { 7089 if (!AStmt) 7090 return StmtError(); 7091 7092 auto *CS = cast<CapturedStmt>(AStmt); 7093 // 1.2.2 OpenMP Language Terminology 7094 // Structured block - An executable statement with a single entry at the 7095 // top and a single exit at the bottom. 7096 // The point of exit cannot be a branch out of the structured block. 7097 // longjmp() and throw() must not violate the entry/exit criteria. 7098 CS->getCapturedDecl()->setNothrow(); 7099 for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target); 7100 ThisCaptureLevel > 1; --ThisCaptureLevel) { 7101 CS = cast<CapturedStmt>(CS->getCapturedStmt()); 7102 // 1.2.2 OpenMP Language Terminology 7103 // Structured block - An executable statement with a single entry at the 7104 // top and a single exit at the bottom. 7105 // The point of exit cannot be a branch out of the structured block. 7106 // longjmp() and throw() must not violate the entry/exit criteria. 7107 CS->getCapturedDecl()->setNothrow(); 7108 } 7109 7110 // OpenMP [2.16, Nesting of Regions] 7111 // If specified, a teams construct must be contained within a target 7112 // construct. That target construct must contain no statements or directives 7113 // outside of the teams construct. 7114 if (DSAStack->hasInnerTeamsRegion()) { 7115 const Stmt *S = CS->IgnoreContainers(/*IgnoreCaptured=*/true); 7116 bool OMPTeamsFound = true; 7117 if (const auto *CS = dyn_cast<CompoundStmt>(S)) { 7118 auto I = CS->body_begin(); 7119 while (I != CS->body_end()) { 7120 const auto *OED = dyn_cast<OMPExecutableDirective>(*I); 7121 if (!OED || !isOpenMPTeamsDirective(OED->getDirectiveKind()) || 7122 OMPTeamsFound) { 7123 7124 OMPTeamsFound = false; 7125 break; 7126 } 7127 ++I; 7128 } 7129 assert(I != CS->body_end() && "Not found statement"); 7130 S = *I; 7131 } else { 7132 const auto *OED = dyn_cast<OMPExecutableDirective>(S); 7133 OMPTeamsFound = OED && isOpenMPTeamsDirective(OED->getDirectiveKind()); 7134 } 7135 if (!OMPTeamsFound) { 7136 Diag(StartLoc, diag::err_omp_target_contains_not_only_teams); 7137 Diag(DSAStack->getInnerTeamsRegionLoc(), 7138 diag::note_omp_nested_teams_construct_here); 7139 Diag(S->getBeginLoc(), diag::note_omp_nested_statement_here) 7140 << isa<OMPExecutableDirective>(S); 7141 return StmtError(); 7142 } 7143 } 7144 7145 setFunctionHasBranchProtectedScope(); 7146 7147 return OMPTargetDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt); 7148 } 7149 7150 StmtResult 7151 Sema::ActOnOpenMPTargetParallelDirective(ArrayRef<OMPClause *> Clauses, 7152 Stmt *AStmt, SourceLocation StartLoc, 7153 SourceLocation EndLoc) { 7154 if (!AStmt) 7155 return StmtError(); 7156 7157 auto *CS = cast<CapturedStmt>(AStmt); 7158 // 1.2.2 OpenMP Language Terminology 7159 // Structured block - An executable statement with a single entry at the 7160 // top and a single exit at the bottom. 7161 // The point of exit cannot be a branch out of the structured block. 7162 // longjmp() and throw() must not violate the entry/exit criteria. 7163 CS->getCapturedDecl()->setNothrow(); 7164 for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_parallel); 7165 ThisCaptureLevel > 1; --ThisCaptureLevel) { 7166 CS = cast<CapturedStmt>(CS->getCapturedStmt()); 7167 // 1.2.2 OpenMP Language Terminology 7168 // Structured block - An executable statement with a single entry at the 7169 // top and a single exit at the bottom. 7170 // The point of exit cannot be a branch out of the structured block. 7171 // longjmp() and throw() must not violate the entry/exit criteria. 7172 CS->getCapturedDecl()->setNothrow(); 7173 } 7174 7175 setFunctionHasBranchProtectedScope(); 7176 7177 return OMPTargetParallelDirective::Create(Context, StartLoc, EndLoc, Clauses, 7178 AStmt); 7179 } 7180 7181 StmtResult Sema::ActOnOpenMPTargetParallelForDirective( 7182 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, 7183 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) { 7184 if (!AStmt) 7185 return StmtError(); 7186 7187 auto *CS = cast<CapturedStmt>(AStmt); 7188 // 1.2.2 OpenMP Language Terminology 7189 // Structured block - An executable statement with a single entry at the 7190 // top and a single exit at the bottom. 7191 // The point of exit cannot be a branch out of the structured block. 7192 // longjmp() and throw() must not violate the entry/exit criteria. 7193 CS->getCapturedDecl()->setNothrow(); 7194 for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_parallel_for); 7195 ThisCaptureLevel > 1; --ThisCaptureLevel) { 7196 CS = cast<CapturedStmt>(CS->getCapturedStmt()); 7197 // 1.2.2 OpenMP Language Terminology 7198 // Structured block - An executable statement with a single entry at the 7199 // top and a single exit at the bottom. 7200 // The point of exit cannot be a branch out of the structured block. 7201 // longjmp() and throw() must not violate the entry/exit criteria. 7202 CS->getCapturedDecl()->setNothrow(); 7203 } 7204 7205 OMPLoopDirective::HelperExprs B; 7206 // In presence of clause 'collapse' or 'ordered' with number of loops, it will 7207 // define the nested loops number. 7208 unsigned NestedLoopCount = 7209 checkOpenMPLoop(OMPD_target_parallel_for, getCollapseNumberExpr(Clauses), 7210 getOrderedNumberExpr(Clauses), CS, *this, *DSAStack, 7211 VarsWithImplicitDSA, B); 7212 if (NestedLoopCount == 0) 7213 return StmtError(); 7214 7215 assert((CurContext->isDependentContext() || B.builtAll()) && 7216 "omp target parallel for loop exprs were not built"); 7217 7218 if (!CurContext->isDependentContext()) { 7219 // Finalize the clauses that need pre-built expressions for CodeGen. 7220 for (OMPClause *C : Clauses) { 7221 if (auto *LC = dyn_cast<OMPLinearClause>(C)) 7222 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef), 7223 B.NumIterations, *this, CurScope, 7224 DSAStack)) 7225 return StmtError(); 7226 } 7227 } 7228 7229 setFunctionHasBranchProtectedScope(); 7230 return OMPTargetParallelForDirective::Create(Context, StartLoc, EndLoc, 7231 NestedLoopCount, Clauses, AStmt, 7232 B, DSAStack->isCancelRegion()); 7233 } 7234 7235 /// Check for existence of a map clause in the list of clauses. 7236 static bool hasClauses(ArrayRef<OMPClause *> Clauses, 7237 const OpenMPClauseKind K) { 7238 return llvm::any_of( 7239 Clauses, [K](const OMPClause *C) { return C->getClauseKind() == K; }); 7240 } 7241 7242 template <typename... Params> 7243 static bool hasClauses(ArrayRef<OMPClause *> Clauses, const OpenMPClauseKind K, 7244 const Params... ClauseTypes) { 7245 return hasClauses(Clauses, K) || hasClauses(Clauses, ClauseTypes...); 7246 } 7247 7248 StmtResult Sema::ActOnOpenMPTargetDataDirective(ArrayRef<OMPClause *> Clauses, 7249 Stmt *AStmt, 7250 SourceLocation StartLoc, 7251 SourceLocation EndLoc) { 7252 if (!AStmt) 7253 return StmtError(); 7254 7255 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected"); 7256 7257 // OpenMP [2.10.1, Restrictions, p. 97] 7258 // At least one map clause must appear on the directive. 7259 if (!hasClauses(Clauses, OMPC_map, OMPC_use_device_ptr)) { 7260 Diag(StartLoc, diag::err_omp_no_clause_for_directive) 7261 << "'map' or 'use_device_ptr'" 7262 << getOpenMPDirectiveName(OMPD_target_data); 7263 return StmtError(); 7264 } 7265 7266 setFunctionHasBranchProtectedScope(); 7267 7268 return OMPTargetDataDirective::Create(Context, StartLoc, EndLoc, Clauses, 7269 AStmt); 7270 } 7271 7272 StmtResult 7273 Sema::ActOnOpenMPTargetEnterDataDirective(ArrayRef<OMPClause *> Clauses, 7274 SourceLocation StartLoc, 7275 SourceLocation EndLoc, Stmt *AStmt) { 7276 if (!AStmt) 7277 return StmtError(); 7278 7279 auto *CS = cast<CapturedStmt>(AStmt); 7280 // 1.2.2 OpenMP Language Terminology 7281 // Structured block - An executable statement with a single entry at the 7282 // top and a single exit at the bottom. 7283 // The point of exit cannot be a branch out of the structured block. 7284 // longjmp() and throw() must not violate the entry/exit criteria. 7285 CS->getCapturedDecl()->setNothrow(); 7286 for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_enter_data); 7287 ThisCaptureLevel > 1; --ThisCaptureLevel) { 7288 CS = cast<CapturedStmt>(CS->getCapturedStmt()); 7289 // 1.2.2 OpenMP Language Terminology 7290 // Structured block - An executable statement with a single entry at the 7291 // top and a single exit at the bottom. 7292 // The point of exit cannot be a branch out of the structured block. 7293 // longjmp() and throw() must not violate the entry/exit criteria. 7294 CS->getCapturedDecl()->setNothrow(); 7295 } 7296 7297 // OpenMP [2.10.2, Restrictions, p. 99] 7298 // At least one map clause must appear on the directive. 7299 if (!hasClauses(Clauses, OMPC_map)) { 7300 Diag(StartLoc, diag::err_omp_no_clause_for_directive) 7301 << "'map'" << getOpenMPDirectiveName(OMPD_target_enter_data); 7302 return StmtError(); 7303 } 7304 7305 return OMPTargetEnterDataDirective::Create(Context, StartLoc, EndLoc, Clauses, 7306 AStmt); 7307 } 7308 7309 StmtResult 7310 Sema::ActOnOpenMPTargetExitDataDirective(ArrayRef<OMPClause *> Clauses, 7311 SourceLocation StartLoc, 7312 SourceLocation EndLoc, Stmt *AStmt) { 7313 if (!AStmt) 7314 return StmtError(); 7315 7316 auto *CS = cast<CapturedStmt>(AStmt); 7317 // 1.2.2 OpenMP Language Terminology 7318 // Structured block - An executable statement with a single entry at the 7319 // top and a single exit at the bottom. 7320 // The point of exit cannot be a branch out of the structured block. 7321 // longjmp() and throw() must not violate the entry/exit criteria. 7322 CS->getCapturedDecl()->setNothrow(); 7323 for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_exit_data); 7324 ThisCaptureLevel > 1; --ThisCaptureLevel) { 7325 CS = cast<CapturedStmt>(CS->getCapturedStmt()); 7326 // 1.2.2 OpenMP Language Terminology 7327 // Structured block - An executable statement with a single entry at the 7328 // top and a single exit at the bottom. 7329 // The point of exit cannot be a branch out of the structured block. 7330 // longjmp() and throw() must not violate the entry/exit criteria. 7331 CS->getCapturedDecl()->setNothrow(); 7332 } 7333 7334 // OpenMP [2.10.3, Restrictions, p. 102] 7335 // At least one map clause must appear on the directive. 7336 if (!hasClauses(Clauses, OMPC_map)) { 7337 Diag(StartLoc, diag::err_omp_no_clause_for_directive) 7338 << "'map'" << getOpenMPDirectiveName(OMPD_target_exit_data); 7339 return StmtError(); 7340 } 7341 7342 return OMPTargetExitDataDirective::Create(Context, StartLoc, EndLoc, Clauses, 7343 AStmt); 7344 } 7345 7346 StmtResult Sema::ActOnOpenMPTargetUpdateDirective(ArrayRef<OMPClause *> Clauses, 7347 SourceLocation StartLoc, 7348 SourceLocation EndLoc, 7349 Stmt *AStmt) { 7350 if (!AStmt) 7351 return StmtError(); 7352 7353 auto *CS = cast<CapturedStmt>(AStmt); 7354 // 1.2.2 OpenMP Language Terminology 7355 // Structured block - An executable statement with a single entry at the 7356 // top and a single exit at the bottom. 7357 // The point of exit cannot be a branch out of the structured block. 7358 // longjmp() and throw() must not violate the entry/exit criteria. 7359 CS->getCapturedDecl()->setNothrow(); 7360 for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_update); 7361 ThisCaptureLevel > 1; --ThisCaptureLevel) { 7362 CS = cast<CapturedStmt>(CS->getCapturedStmt()); 7363 // 1.2.2 OpenMP Language Terminology 7364 // Structured block - An executable statement with a single entry at the 7365 // top and a single exit at the bottom. 7366 // The point of exit cannot be a branch out of the structured block. 7367 // longjmp() and throw() must not violate the entry/exit criteria. 7368 CS->getCapturedDecl()->setNothrow(); 7369 } 7370 7371 if (!hasClauses(Clauses, OMPC_to, OMPC_from)) { 7372 Diag(StartLoc, diag::err_omp_at_least_one_motion_clause_required); 7373 return StmtError(); 7374 } 7375 return OMPTargetUpdateDirective::Create(Context, StartLoc, EndLoc, Clauses, 7376 AStmt); 7377 } 7378 7379 StmtResult Sema::ActOnOpenMPTeamsDirective(ArrayRef<OMPClause *> Clauses, 7380 Stmt *AStmt, SourceLocation StartLoc, 7381 SourceLocation EndLoc) { 7382 if (!AStmt) 7383 return StmtError(); 7384 7385 auto *CS = cast<CapturedStmt>(AStmt); 7386 // 1.2.2 OpenMP Language Terminology 7387 // Structured block - An executable statement with a single entry at the 7388 // top and a single exit at the bottom. 7389 // The point of exit cannot be a branch out of the structured block. 7390 // longjmp() and throw() must not violate the entry/exit criteria. 7391 CS->getCapturedDecl()->setNothrow(); 7392 7393 setFunctionHasBranchProtectedScope(); 7394 7395 DSAStack->setParentTeamsRegionLoc(StartLoc); 7396 7397 return OMPTeamsDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt); 7398 } 7399 7400 StmtResult 7401 Sema::ActOnOpenMPCancellationPointDirective(SourceLocation StartLoc, 7402 SourceLocation EndLoc, 7403 OpenMPDirectiveKind CancelRegion) { 7404 if (DSAStack->isParentNowaitRegion()) { 7405 Diag(StartLoc, diag::err_omp_parent_cancel_region_nowait) << 0; 7406 return StmtError(); 7407 } 7408 if (DSAStack->isParentOrderedRegion()) { 7409 Diag(StartLoc, diag::err_omp_parent_cancel_region_ordered) << 0; 7410 return StmtError(); 7411 } 7412 return OMPCancellationPointDirective::Create(Context, StartLoc, EndLoc, 7413 CancelRegion); 7414 } 7415 7416 StmtResult Sema::ActOnOpenMPCancelDirective(ArrayRef<OMPClause *> Clauses, 7417 SourceLocation StartLoc, 7418 SourceLocation EndLoc, 7419 OpenMPDirectiveKind CancelRegion) { 7420 if (DSAStack->isParentNowaitRegion()) { 7421 Diag(StartLoc, diag::err_omp_parent_cancel_region_nowait) << 1; 7422 return StmtError(); 7423 } 7424 if (DSAStack->isParentOrderedRegion()) { 7425 Diag(StartLoc, diag::err_omp_parent_cancel_region_ordered) << 1; 7426 return StmtError(); 7427 } 7428 DSAStack->setParentCancelRegion(/*Cancel=*/true); 7429 return OMPCancelDirective::Create(Context, StartLoc, EndLoc, Clauses, 7430 CancelRegion); 7431 } 7432 7433 static bool checkGrainsizeNumTasksClauses(Sema &S, 7434 ArrayRef<OMPClause *> Clauses) { 7435 const OMPClause *PrevClause = nullptr; 7436 bool ErrorFound = false; 7437 for (const OMPClause *C : Clauses) { 7438 if (C->getClauseKind() == OMPC_grainsize || 7439 C->getClauseKind() == OMPC_num_tasks) { 7440 if (!PrevClause) 7441 PrevClause = C; 7442 else if (PrevClause->getClauseKind() != C->getClauseKind()) { 7443 S.Diag(C->getBeginLoc(), 7444 diag::err_omp_grainsize_num_tasks_mutually_exclusive) 7445 << getOpenMPClauseName(C->getClauseKind()) 7446 << getOpenMPClauseName(PrevClause->getClauseKind()); 7447 S.Diag(PrevClause->getBeginLoc(), 7448 diag::note_omp_previous_grainsize_num_tasks) 7449 << getOpenMPClauseName(PrevClause->getClauseKind()); 7450 ErrorFound = true; 7451 } 7452 } 7453 } 7454 return ErrorFound; 7455 } 7456 7457 static bool checkReductionClauseWithNogroup(Sema &S, 7458 ArrayRef<OMPClause *> Clauses) { 7459 const OMPClause *ReductionClause = nullptr; 7460 const OMPClause *NogroupClause = nullptr; 7461 for (const OMPClause *C : Clauses) { 7462 if (C->getClauseKind() == OMPC_reduction) { 7463 ReductionClause = C; 7464 if (NogroupClause) 7465 break; 7466 continue; 7467 } 7468 if (C->getClauseKind() == OMPC_nogroup) { 7469 NogroupClause = C; 7470 if (ReductionClause) 7471 break; 7472 continue; 7473 } 7474 } 7475 if (ReductionClause && NogroupClause) { 7476 S.Diag(ReductionClause->getBeginLoc(), diag::err_omp_reduction_with_nogroup) 7477 << SourceRange(NogroupClause->getBeginLoc(), 7478 NogroupClause->getEndLoc()); 7479 return true; 7480 } 7481 return false; 7482 } 7483 7484 StmtResult Sema::ActOnOpenMPTaskLoopDirective( 7485 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, 7486 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) { 7487 if (!AStmt) 7488 return StmtError(); 7489 7490 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected"); 7491 OMPLoopDirective::HelperExprs B; 7492 // In presence of clause 'collapse' or 'ordered' with number of loops, it will 7493 // define the nested loops number. 7494 unsigned NestedLoopCount = 7495 checkOpenMPLoop(OMPD_taskloop, getCollapseNumberExpr(Clauses), 7496 /*OrderedLoopCountExpr=*/nullptr, AStmt, *this, *DSAStack, 7497 VarsWithImplicitDSA, B); 7498 if (NestedLoopCount == 0) 7499 return StmtError(); 7500 7501 assert((CurContext->isDependentContext() || B.builtAll()) && 7502 "omp for loop exprs were not built"); 7503 7504 // OpenMP, [2.9.2 taskloop Construct, Restrictions] 7505 // The grainsize clause and num_tasks clause are mutually exclusive and may 7506 // not appear on the same taskloop directive. 7507 if (checkGrainsizeNumTasksClauses(*this, Clauses)) 7508 return StmtError(); 7509 // OpenMP, [2.9.2 taskloop Construct, Restrictions] 7510 // If a reduction clause is present on the taskloop directive, the nogroup 7511 // clause must not be specified. 7512 if (checkReductionClauseWithNogroup(*this, Clauses)) 7513 return StmtError(); 7514 7515 setFunctionHasBranchProtectedScope(); 7516 return OMPTaskLoopDirective::Create(Context, StartLoc, EndLoc, 7517 NestedLoopCount, Clauses, AStmt, B); 7518 } 7519 7520 StmtResult Sema::ActOnOpenMPTaskLoopSimdDirective( 7521 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, 7522 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) { 7523 if (!AStmt) 7524 return StmtError(); 7525 7526 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected"); 7527 OMPLoopDirective::HelperExprs B; 7528 // In presence of clause 'collapse' or 'ordered' with number of loops, it will 7529 // define the nested loops number. 7530 unsigned NestedLoopCount = 7531 checkOpenMPLoop(OMPD_taskloop_simd, getCollapseNumberExpr(Clauses), 7532 /*OrderedLoopCountExpr=*/nullptr, AStmt, *this, *DSAStack, 7533 VarsWithImplicitDSA, B); 7534 if (NestedLoopCount == 0) 7535 return StmtError(); 7536 7537 assert((CurContext->isDependentContext() || B.builtAll()) && 7538 "omp for loop exprs were not built"); 7539 7540 if (!CurContext->isDependentContext()) { 7541 // Finalize the clauses that need pre-built expressions for CodeGen. 7542 for (OMPClause *C : Clauses) { 7543 if (auto *LC = dyn_cast<OMPLinearClause>(C)) 7544 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef), 7545 B.NumIterations, *this, CurScope, 7546 DSAStack)) 7547 return StmtError(); 7548 } 7549 } 7550 7551 // OpenMP, [2.9.2 taskloop Construct, Restrictions] 7552 // The grainsize clause and num_tasks clause are mutually exclusive and may 7553 // not appear on the same taskloop directive. 7554 if (checkGrainsizeNumTasksClauses(*this, Clauses)) 7555 return StmtError(); 7556 // OpenMP, [2.9.2 taskloop Construct, Restrictions] 7557 // If a reduction clause is present on the taskloop directive, the nogroup 7558 // clause must not be specified. 7559 if (checkReductionClauseWithNogroup(*this, Clauses)) 7560 return StmtError(); 7561 if (checkSimdlenSafelenSpecified(*this, Clauses)) 7562 return StmtError(); 7563 7564 setFunctionHasBranchProtectedScope(); 7565 return OMPTaskLoopSimdDirective::Create(Context, StartLoc, EndLoc, 7566 NestedLoopCount, Clauses, AStmt, B); 7567 } 7568 7569 StmtResult Sema::ActOnOpenMPDistributeDirective( 7570 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, 7571 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) { 7572 if (!AStmt) 7573 return StmtError(); 7574 7575 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected"); 7576 OMPLoopDirective::HelperExprs B; 7577 // In presence of clause 'collapse' with number of loops, it will 7578 // define the nested loops number. 7579 unsigned NestedLoopCount = 7580 checkOpenMPLoop(OMPD_distribute, getCollapseNumberExpr(Clauses), 7581 nullptr /*ordered not a clause on distribute*/, AStmt, 7582 *this, *DSAStack, VarsWithImplicitDSA, B); 7583 if (NestedLoopCount == 0) 7584 return StmtError(); 7585 7586 assert((CurContext->isDependentContext() || B.builtAll()) && 7587 "omp for loop exprs were not built"); 7588 7589 setFunctionHasBranchProtectedScope(); 7590 return OMPDistributeDirective::Create(Context, StartLoc, EndLoc, 7591 NestedLoopCount, Clauses, AStmt, B); 7592 } 7593 7594 StmtResult Sema::ActOnOpenMPDistributeParallelForDirective( 7595 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, 7596 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) { 7597 if (!AStmt) 7598 return StmtError(); 7599 7600 auto *CS = cast<CapturedStmt>(AStmt); 7601 // 1.2.2 OpenMP Language Terminology 7602 // Structured block - An executable statement with a single entry at the 7603 // top and a single exit at the bottom. 7604 // The point of exit cannot be a branch out of the structured block. 7605 // longjmp() and throw() must not violate the entry/exit criteria. 7606 CS->getCapturedDecl()->setNothrow(); 7607 for (int ThisCaptureLevel = 7608 getOpenMPCaptureLevels(OMPD_distribute_parallel_for); 7609 ThisCaptureLevel > 1; --ThisCaptureLevel) { 7610 CS = cast<CapturedStmt>(CS->getCapturedStmt()); 7611 // 1.2.2 OpenMP Language Terminology 7612 // Structured block - An executable statement with a single entry at the 7613 // top and a single exit at the bottom. 7614 // The point of exit cannot be a branch out of the structured block. 7615 // longjmp() and throw() must not violate the entry/exit criteria. 7616 CS->getCapturedDecl()->setNothrow(); 7617 } 7618 7619 OMPLoopDirective::HelperExprs B; 7620 // In presence of clause 'collapse' with number of loops, it will 7621 // define the nested loops number. 7622 unsigned NestedLoopCount = checkOpenMPLoop( 7623 OMPD_distribute_parallel_for, getCollapseNumberExpr(Clauses), 7624 nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStack, 7625 VarsWithImplicitDSA, B); 7626 if (NestedLoopCount == 0) 7627 return StmtError(); 7628 7629 assert((CurContext->isDependentContext() || B.builtAll()) && 7630 "omp for loop exprs were not built"); 7631 7632 setFunctionHasBranchProtectedScope(); 7633 return OMPDistributeParallelForDirective::Create( 7634 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B, 7635 DSAStack->isCancelRegion()); 7636 } 7637 7638 StmtResult Sema::ActOnOpenMPDistributeParallelForSimdDirective( 7639 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, 7640 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) { 7641 if (!AStmt) 7642 return StmtError(); 7643 7644 auto *CS = cast<CapturedStmt>(AStmt); 7645 // 1.2.2 OpenMP Language Terminology 7646 // Structured block - An executable statement with a single entry at the 7647 // top and a single exit at the bottom. 7648 // The point of exit cannot be a branch out of the structured block. 7649 // longjmp() and throw() must not violate the entry/exit criteria. 7650 CS->getCapturedDecl()->setNothrow(); 7651 for (int ThisCaptureLevel = 7652 getOpenMPCaptureLevels(OMPD_distribute_parallel_for_simd); 7653 ThisCaptureLevel > 1; --ThisCaptureLevel) { 7654 CS = cast<CapturedStmt>(CS->getCapturedStmt()); 7655 // 1.2.2 OpenMP Language Terminology 7656 // Structured block - An executable statement with a single entry at the 7657 // top and a single exit at the bottom. 7658 // The point of exit cannot be a branch out of the structured block. 7659 // longjmp() and throw() must not violate the entry/exit criteria. 7660 CS->getCapturedDecl()->setNothrow(); 7661 } 7662 7663 OMPLoopDirective::HelperExprs B; 7664 // In presence of clause 'collapse' with number of loops, it will 7665 // define the nested loops number. 7666 unsigned NestedLoopCount = checkOpenMPLoop( 7667 OMPD_distribute_parallel_for_simd, getCollapseNumberExpr(Clauses), 7668 nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStack, 7669 VarsWithImplicitDSA, B); 7670 if (NestedLoopCount == 0) 7671 return StmtError(); 7672 7673 assert((CurContext->isDependentContext() || B.builtAll()) && 7674 "omp for loop exprs were not built"); 7675 7676 if (!CurContext->isDependentContext()) { 7677 // Finalize the clauses that need pre-built expressions for CodeGen. 7678 for (OMPClause *C : Clauses) { 7679 if (auto *LC = dyn_cast<OMPLinearClause>(C)) 7680 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef), 7681 B.NumIterations, *this, CurScope, 7682 DSAStack)) 7683 return StmtError(); 7684 } 7685 } 7686 7687 if (checkSimdlenSafelenSpecified(*this, Clauses)) 7688 return StmtError(); 7689 7690 setFunctionHasBranchProtectedScope(); 7691 return OMPDistributeParallelForSimdDirective::Create( 7692 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B); 7693 } 7694 7695 StmtResult Sema::ActOnOpenMPDistributeSimdDirective( 7696 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, 7697 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) { 7698 if (!AStmt) 7699 return StmtError(); 7700 7701 auto *CS = cast<CapturedStmt>(AStmt); 7702 // 1.2.2 OpenMP Language Terminology 7703 // Structured block - An executable statement with a single entry at the 7704 // top and a single exit at the bottom. 7705 // The point of exit cannot be a branch out of the structured block. 7706 // longjmp() and throw() must not violate the entry/exit criteria. 7707 CS->getCapturedDecl()->setNothrow(); 7708 for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_distribute_simd); 7709 ThisCaptureLevel > 1; --ThisCaptureLevel) { 7710 CS = cast<CapturedStmt>(CS->getCapturedStmt()); 7711 // 1.2.2 OpenMP Language Terminology 7712 // Structured block - An executable statement with a single entry at the 7713 // top and a single exit at the bottom. 7714 // The point of exit cannot be a branch out of the structured block. 7715 // longjmp() and throw() must not violate the entry/exit criteria. 7716 CS->getCapturedDecl()->setNothrow(); 7717 } 7718 7719 OMPLoopDirective::HelperExprs B; 7720 // In presence of clause 'collapse' with number of loops, it will 7721 // define the nested loops number. 7722 unsigned NestedLoopCount = 7723 checkOpenMPLoop(OMPD_distribute_simd, getCollapseNumberExpr(Clauses), 7724 nullptr /*ordered not a clause on distribute*/, CS, *this, 7725 *DSAStack, VarsWithImplicitDSA, B); 7726 if (NestedLoopCount == 0) 7727 return StmtError(); 7728 7729 assert((CurContext->isDependentContext() || B.builtAll()) && 7730 "omp for loop exprs were not built"); 7731 7732 if (!CurContext->isDependentContext()) { 7733 // Finalize the clauses that need pre-built expressions for CodeGen. 7734 for (OMPClause *C : Clauses) { 7735 if (auto *LC = dyn_cast<OMPLinearClause>(C)) 7736 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef), 7737 B.NumIterations, *this, CurScope, 7738 DSAStack)) 7739 return StmtError(); 7740 } 7741 } 7742 7743 if (checkSimdlenSafelenSpecified(*this, Clauses)) 7744 return StmtError(); 7745 7746 setFunctionHasBranchProtectedScope(); 7747 return OMPDistributeSimdDirective::Create(Context, StartLoc, EndLoc, 7748 NestedLoopCount, Clauses, AStmt, B); 7749 } 7750 7751 StmtResult Sema::ActOnOpenMPTargetParallelForSimdDirective( 7752 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, 7753 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) { 7754 if (!AStmt) 7755 return StmtError(); 7756 7757 auto *CS = cast<CapturedStmt>(AStmt); 7758 // 1.2.2 OpenMP Language Terminology 7759 // Structured block - An executable statement with a single entry at the 7760 // top and a single exit at the bottom. 7761 // The point of exit cannot be a branch out of the structured block. 7762 // longjmp() and throw() must not violate the entry/exit criteria. 7763 CS->getCapturedDecl()->setNothrow(); 7764 for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_parallel_for); 7765 ThisCaptureLevel > 1; --ThisCaptureLevel) { 7766 CS = cast<CapturedStmt>(CS->getCapturedStmt()); 7767 // 1.2.2 OpenMP Language Terminology 7768 // Structured block - An executable statement with a single entry at the 7769 // top and a single exit at the bottom. 7770 // The point of exit cannot be a branch out of the structured block. 7771 // longjmp() and throw() must not violate the entry/exit criteria. 7772 CS->getCapturedDecl()->setNothrow(); 7773 } 7774 7775 OMPLoopDirective::HelperExprs B; 7776 // In presence of clause 'collapse' or 'ordered' with number of loops, it will 7777 // define the nested loops number. 7778 unsigned NestedLoopCount = checkOpenMPLoop( 7779 OMPD_target_parallel_for_simd, getCollapseNumberExpr(Clauses), 7780 getOrderedNumberExpr(Clauses), CS, *this, *DSAStack, 7781 VarsWithImplicitDSA, B); 7782 if (NestedLoopCount == 0) 7783 return StmtError(); 7784 7785 assert((CurContext->isDependentContext() || B.builtAll()) && 7786 "omp target parallel for simd loop exprs were not built"); 7787 7788 if (!CurContext->isDependentContext()) { 7789 // Finalize the clauses that need pre-built expressions for CodeGen. 7790 for (OMPClause *C : Clauses) { 7791 if (auto *LC = dyn_cast<OMPLinearClause>(C)) 7792 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef), 7793 B.NumIterations, *this, CurScope, 7794 DSAStack)) 7795 return StmtError(); 7796 } 7797 } 7798 if (checkSimdlenSafelenSpecified(*this, Clauses)) 7799 return StmtError(); 7800 7801 setFunctionHasBranchProtectedScope(); 7802 return OMPTargetParallelForSimdDirective::Create( 7803 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B); 7804 } 7805 7806 StmtResult Sema::ActOnOpenMPTargetSimdDirective( 7807 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, 7808 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) { 7809 if (!AStmt) 7810 return StmtError(); 7811 7812 auto *CS = cast<CapturedStmt>(AStmt); 7813 // 1.2.2 OpenMP Language Terminology 7814 // Structured block - An executable statement with a single entry at the 7815 // top and a single exit at the bottom. 7816 // The point of exit cannot be a branch out of the structured block. 7817 // longjmp() and throw() must not violate the entry/exit criteria. 7818 CS->getCapturedDecl()->setNothrow(); 7819 for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_simd); 7820 ThisCaptureLevel > 1; --ThisCaptureLevel) { 7821 CS = cast<CapturedStmt>(CS->getCapturedStmt()); 7822 // 1.2.2 OpenMP Language Terminology 7823 // Structured block - An executable statement with a single entry at the 7824 // top and a single exit at the bottom. 7825 // The point of exit cannot be a branch out of the structured block. 7826 // longjmp() and throw() must not violate the entry/exit criteria. 7827 CS->getCapturedDecl()->setNothrow(); 7828 } 7829 7830 OMPLoopDirective::HelperExprs B; 7831 // In presence of clause 'collapse' with number of loops, it will define the 7832 // nested loops number. 7833 unsigned NestedLoopCount = 7834 checkOpenMPLoop(OMPD_target_simd, getCollapseNumberExpr(Clauses), 7835 getOrderedNumberExpr(Clauses), CS, *this, *DSAStack, 7836 VarsWithImplicitDSA, B); 7837 if (NestedLoopCount == 0) 7838 return StmtError(); 7839 7840 assert((CurContext->isDependentContext() || B.builtAll()) && 7841 "omp target simd loop exprs were not built"); 7842 7843 if (!CurContext->isDependentContext()) { 7844 // Finalize the clauses that need pre-built expressions for CodeGen. 7845 for (OMPClause *C : Clauses) { 7846 if (auto *LC = dyn_cast<OMPLinearClause>(C)) 7847 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef), 7848 B.NumIterations, *this, CurScope, 7849 DSAStack)) 7850 return StmtError(); 7851 } 7852 } 7853 7854 if (checkSimdlenSafelenSpecified(*this, Clauses)) 7855 return StmtError(); 7856 7857 setFunctionHasBranchProtectedScope(); 7858 return OMPTargetSimdDirective::Create(Context, StartLoc, EndLoc, 7859 NestedLoopCount, Clauses, AStmt, B); 7860 } 7861 7862 StmtResult Sema::ActOnOpenMPTeamsDistributeDirective( 7863 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, 7864 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) { 7865 if (!AStmt) 7866 return StmtError(); 7867 7868 auto *CS = cast<CapturedStmt>(AStmt); 7869 // 1.2.2 OpenMP Language Terminology 7870 // Structured block - An executable statement with a single entry at the 7871 // top and a single exit at the bottom. 7872 // The point of exit cannot be a branch out of the structured block. 7873 // longjmp() and throw() must not violate the entry/exit criteria. 7874 CS->getCapturedDecl()->setNothrow(); 7875 for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_teams_distribute); 7876 ThisCaptureLevel > 1; --ThisCaptureLevel) { 7877 CS = cast<CapturedStmt>(CS->getCapturedStmt()); 7878 // 1.2.2 OpenMP Language Terminology 7879 // Structured block - An executable statement with a single entry at the 7880 // top and a single exit at the bottom. 7881 // The point of exit cannot be a branch out of the structured block. 7882 // longjmp() and throw() must not violate the entry/exit criteria. 7883 CS->getCapturedDecl()->setNothrow(); 7884 } 7885 7886 OMPLoopDirective::HelperExprs B; 7887 // In presence of clause 'collapse' with number of loops, it will 7888 // define the nested loops number. 7889 unsigned NestedLoopCount = 7890 checkOpenMPLoop(OMPD_teams_distribute, getCollapseNumberExpr(Clauses), 7891 nullptr /*ordered not a clause on distribute*/, CS, *this, 7892 *DSAStack, VarsWithImplicitDSA, B); 7893 if (NestedLoopCount == 0) 7894 return StmtError(); 7895 7896 assert((CurContext->isDependentContext() || B.builtAll()) && 7897 "omp teams distribute loop exprs were not built"); 7898 7899 setFunctionHasBranchProtectedScope(); 7900 7901 DSAStack->setParentTeamsRegionLoc(StartLoc); 7902 7903 return OMPTeamsDistributeDirective::Create( 7904 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B); 7905 } 7906 7907 StmtResult Sema::ActOnOpenMPTeamsDistributeSimdDirective( 7908 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, 7909 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) { 7910 if (!AStmt) 7911 return StmtError(); 7912 7913 auto *CS = cast<CapturedStmt>(AStmt); 7914 // 1.2.2 OpenMP Language Terminology 7915 // Structured block - An executable statement with a single entry at the 7916 // top and a single exit at the bottom. 7917 // The point of exit cannot be a branch out of the structured block. 7918 // longjmp() and throw() must not violate the entry/exit criteria. 7919 CS->getCapturedDecl()->setNothrow(); 7920 for (int ThisCaptureLevel = 7921 getOpenMPCaptureLevels(OMPD_teams_distribute_simd); 7922 ThisCaptureLevel > 1; --ThisCaptureLevel) { 7923 CS = cast<CapturedStmt>(CS->getCapturedStmt()); 7924 // 1.2.2 OpenMP Language Terminology 7925 // Structured block - An executable statement with a single entry at the 7926 // top and a single exit at the bottom. 7927 // The point of exit cannot be a branch out of the structured block. 7928 // longjmp() and throw() must not violate the entry/exit criteria. 7929 CS->getCapturedDecl()->setNothrow(); 7930 } 7931 7932 7933 OMPLoopDirective::HelperExprs B; 7934 // In presence of clause 'collapse' with number of loops, it will 7935 // define the nested loops number. 7936 unsigned NestedLoopCount = checkOpenMPLoop( 7937 OMPD_teams_distribute_simd, getCollapseNumberExpr(Clauses), 7938 nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStack, 7939 VarsWithImplicitDSA, B); 7940 7941 if (NestedLoopCount == 0) 7942 return StmtError(); 7943 7944 assert((CurContext->isDependentContext() || B.builtAll()) && 7945 "omp teams distribute simd loop exprs were not built"); 7946 7947 if (!CurContext->isDependentContext()) { 7948 // Finalize the clauses that need pre-built expressions for CodeGen. 7949 for (OMPClause *C : Clauses) { 7950 if (auto *LC = dyn_cast<OMPLinearClause>(C)) 7951 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef), 7952 B.NumIterations, *this, CurScope, 7953 DSAStack)) 7954 return StmtError(); 7955 } 7956 } 7957 7958 if (checkSimdlenSafelenSpecified(*this, Clauses)) 7959 return StmtError(); 7960 7961 setFunctionHasBranchProtectedScope(); 7962 7963 DSAStack->setParentTeamsRegionLoc(StartLoc); 7964 7965 return OMPTeamsDistributeSimdDirective::Create( 7966 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B); 7967 } 7968 7969 StmtResult Sema::ActOnOpenMPTeamsDistributeParallelForSimdDirective( 7970 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, 7971 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) { 7972 if (!AStmt) 7973 return StmtError(); 7974 7975 auto *CS = cast<CapturedStmt>(AStmt); 7976 // 1.2.2 OpenMP Language Terminology 7977 // Structured block - An executable statement with a single entry at the 7978 // top and a single exit at the bottom. 7979 // The point of exit cannot be a branch out of the structured block. 7980 // longjmp() and throw() must not violate the entry/exit criteria. 7981 CS->getCapturedDecl()->setNothrow(); 7982 7983 for (int ThisCaptureLevel = 7984 getOpenMPCaptureLevels(OMPD_teams_distribute_parallel_for_simd); 7985 ThisCaptureLevel > 1; --ThisCaptureLevel) { 7986 CS = cast<CapturedStmt>(CS->getCapturedStmt()); 7987 // 1.2.2 OpenMP Language Terminology 7988 // Structured block - An executable statement with a single entry at the 7989 // top and a single exit at the bottom. 7990 // The point of exit cannot be a branch out of the structured block. 7991 // longjmp() and throw() must not violate the entry/exit criteria. 7992 CS->getCapturedDecl()->setNothrow(); 7993 } 7994 7995 OMPLoopDirective::HelperExprs B; 7996 // In presence of clause 'collapse' with number of loops, it will 7997 // define the nested loops number. 7998 unsigned NestedLoopCount = checkOpenMPLoop( 7999 OMPD_teams_distribute_parallel_for_simd, getCollapseNumberExpr(Clauses), 8000 nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStack, 8001 VarsWithImplicitDSA, B); 8002 8003 if (NestedLoopCount == 0) 8004 return StmtError(); 8005 8006 assert((CurContext->isDependentContext() || B.builtAll()) && 8007 "omp for loop exprs were not built"); 8008 8009 if (!CurContext->isDependentContext()) { 8010 // Finalize the clauses that need pre-built expressions for CodeGen. 8011 for (OMPClause *C : Clauses) { 8012 if (auto *LC = dyn_cast<OMPLinearClause>(C)) 8013 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef), 8014 B.NumIterations, *this, CurScope, 8015 DSAStack)) 8016 return StmtError(); 8017 } 8018 } 8019 8020 if (checkSimdlenSafelenSpecified(*this, Clauses)) 8021 return StmtError(); 8022 8023 setFunctionHasBranchProtectedScope(); 8024 8025 DSAStack->setParentTeamsRegionLoc(StartLoc); 8026 8027 return OMPTeamsDistributeParallelForSimdDirective::Create( 8028 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B); 8029 } 8030 8031 StmtResult Sema::ActOnOpenMPTeamsDistributeParallelForDirective( 8032 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, 8033 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) { 8034 if (!AStmt) 8035 return StmtError(); 8036 8037 auto *CS = cast<CapturedStmt>(AStmt); 8038 // 1.2.2 OpenMP Language Terminology 8039 // Structured block - An executable statement with a single entry at the 8040 // top and a single exit at the bottom. 8041 // The point of exit cannot be a branch out of the structured block. 8042 // longjmp() and throw() must not violate the entry/exit criteria. 8043 CS->getCapturedDecl()->setNothrow(); 8044 8045 for (int ThisCaptureLevel = 8046 getOpenMPCaptureLevels(OMPD_teams_distribute_parallel_for); 8047 ThisCaptureLevel > 1; --ThisCaptureLevel) { 8048 CS = cast<CapturedStmt>(CS->getCapturedStmt()); 8049 // 1.2.2 OpenMP Language Terminology 8050 // Structured block - An executable statement with a single entry at the 8051 // top and a single exit at the bottom. 8052 // The point of exit cannot be a branch out of the structured block. 8053 // longjmp() and throw() must not violate the entry/exit criteria. 8054 CS->getCapturedDecl()->setNothrow(); 8055 } 8056 8057 OMPLoopDirective::HelperExprs B; 8058 // In presence of clause 'collapse' with number of loops, it will 8059 // define the nested loops number. 8060 unsigned NestedLoopCount = checkOpenMPLoop( 8061 OMPD_teams_distribute_parallel_for, getCollapseNumberExpr(Clauses), 8062 nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStack, 8063 VarsWithImplicitDSA, B); 8064 8065 if (NestedLoopCount == 0) 8066 return StmtError(); 8067 8068 assert((CurContext->isDependentContext() || B.builtAll()) && 8069 "omp for loop exprs were not built"); 8070 8071 setFunctionHasBranchProtectedScope(); 8072 8073 DSAStack->setParentTeamsRegionLoc(StartLoc); 8074 8075 return OMPTeamsDistributeParallelForDirective::Create( 8076 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B, 8077 DSAStack->isCancelRegion()); 8078 } 8079 8080 StmtResult Sema::ActOnOpenMPTargetTeamsDirective(ArrayRef<OMPClause *> Clauses, 8081 Stmt *AStmt, 8082 SourceLocation StartLoc, 8083 SourceLocation EndLoc) { 8084 if (!AStmt) 8085 return StmtError(); 8086 8087 auto *CS = cast<CapturedStmt>(AStmt); 8088 // 1.2.2 OpenMP Language Terminology 8089 // Structured block - An executable statement with a single entry at the 8090 // top and a single exit at the bottom. 8091 // The point of exit cannot be a branch out of the structured block. 8092 // longjmp() and throw() must not violate the entry/exit criteria. 8093 CS->getCapturedDecl()->setNothrow(); 8094 8095 for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_teams); 8096 ThisCaptureLevel > 1; --ThisCaptureLevel) { 8097 CS = cast<CapturedStmt>(CS->getCapturedStmt()); 8098 // 1.2.2 OpenMP Language Terminology 8099 // Structured block - An executable statement with a single entry at the 8100 // top and a single exit at the bottom. 8101 // The point of exit cannot be a branch out of the structured block. 8102 // longjmp() and throw() must not violate the entry/exit criteria. 8103 CS->getCapturedDecl()->setNothrow(); 8104 } 8105 setFunctionHasBranchProtectedScope(); 8106 8107 return OMPTargetTeamsDirective::Create(Context, StartLoc, EndLoc, Clauses, 8108 AStmt); 8109 } 8110 8111 StmtResult Sema::ActOnOpenMPTargetTeamsDistributeDirective( 8112 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, 8113 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) { 8114 if (!AStmt) 8115 return StmtError(); 8116 8117 auto *CS = cast<CapturedStmt>(AStmt); 8118 // 1.2.2 OpenMP Language Terminology 8119 // Structured block - An executable statement with a single entry at the 8120 // top and a single exit at the bottom. 8121 // The point of exit cannot be a branch out of the structured block. 8122 // longjmp() and throw() must not violate the entry/exit criteria. 8123 CS->getCapturedDecl()->setNothrow(); 8124 for (int ThisCaptureLevel = 8125 getOpenMPCaptureLevels(OMPD_target_teams_distribute); 8126 ThisCaptureLevel > 1; --ThisCaptureLevel) { 8127 CS = cast<CapturedStmt>(CS->getCapturedStmt()); 8128 // 1.2.2 OpenMP Language Terminology 8129 // Structured block - An executable statement with a single entry at the 8130 // top and a single exit at the bottom. 8131 // The point of exit cannot be a branch out of the structured block. 8132 // longjmp() and throw() must not violate the entry/exit criteria. 8133 CS->getCapturedDecl()->setNothrow(); 8134 } 8135 8136 OMPLoopDirective::HelperExprs B; 8137 // In presence of clause 'collapse' with number of loops, it will 8138 // define the nested loops number. 8139 unsigned NestedLoopCount = checkOpenMPLoop( 8140 OMPD_target_teams_distribute, getCollapseNumberExpr(Clauses), 8141 nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStack, 8142 VarsWithImplicitDSA, B); 8143 if (NestedLoopCount == 0) 8144 return StmtError(); 8145 8146 assert((CurContext->isDependentContext() || B.builtAll()) && 8147 "omp target teams distribute loop exprs were not built"); 8148 8149 setFunctionHasBranchProtectedScope(); 8150 return OMPTargetTeamsDistributeDirective::Create( 8151 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B); 8152 } 8153 8154 StmtResult Sema::ActOnOpenMPTargetTeamsDistributeParallelForDirective( 8155 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, 8156 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) { 8157 if (!AStmt) 8158 return StmtError(); 8159 8160 auto *CS = cast<CapturedStmt>(AStmt); 8161 // 1.2.2 OpenMP Language Terminology 8162 // Structured block - An executable statement with a single entry at the 8163 // top and a single exit at the bottom. 8164 // The point of exit cannot be a branch out of the structured block. 8165 // longjmp() and throw() must not violate the entry/exit criteria. 8166 CS->getCapturedDecl()->setNothrow(); 8167 for (int ThisCaptureLevel = 8168 getOpenMPCaptureLevels(OMPD_target_teams_distribute_parallel_for); 8169 ThisCaptureLevel > 1; --ThisCaptureLevel) { 8170 CS = cast<CapturedStmt>(CS->getCapturedStmt()); 8171 // 1.2.2 OpenMP Language Terminology 8172 // Structured block - An executable statement with a single entry at the 8173 // top and a single exit at the bottom. 8174 // The point of exit cannot be a branch out of the structured block. 8175 // longjmp() and throw() must not violate the entry/exit criteria. 8176 CS->getCapturedDecl()->setNothrow(); 8177 } 8178 8179 OMPLoopDirective::HelperExprs B; 8180 // In presence of clause 'collapse' with number of loops, it will 8181 // define the nested loops number. 8182 unsigned NestedLoopCount = checkOpenMPLoop( 8183 OMPD_target_teams_distribute_parallel_for, getCollapseNumberExpr(Clauses), 8184 nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStack, 8185 VarsWithImplicitDSA, B); 8186 if (NestedLoopCount == 0) 8187 return StmtError(); 8188 8189 assert((CurContext->isDependentContext() || B.builtAll()) && 8190 "omp target teams distribute parallel for loop exprs were not built"); 8191 8192 if (!CurContext->isDependentContext()) { 8193 // Finalize the clauses that need pre-built expressions for CodeGen. 8194 for (OMPClause *C : Clauses) { 8195 if (auto *LC = dyn_cast<OMPLinearClause>(C)) 8196 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef), 8197 B.NumIterations, *this, CurScope, 8198 DSAStack)) 8199 return StmtError(); 8200 } 8201 } 8202 8203 setFunctionHasBranchProtectedScope(); 8204 return OMPTargetTeamsDistributeParallelForDirective::Create( 8205 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B, 8206 DSAStack->isCancelRegion()); 8207 } 8208 8209 StmtResult Sema::ActOnOpenMPTargetTeamsDistributeParallelForSimdDirective( 8210 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, 8211 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) { 8212 if (!AStmt) 8213 return StmtError(); 8214 8215 auto *CS = cast<CapturedStmt>(AStmt); 8216 // 1.2.2 OpenMP Language Terminology 8217 // Structured block - An executable statement with a single entry at the 8218 // top and a single exit at the bottom. 8219 // The point of exit cannot be a branch out of the structured block. 8220 // longjmp() and throw() must not violate the entry/exit criteria. 8221 CS->getCapturedDecl()->setNothrow(); 8222 for (int ThisCaptureLevel = getOpenMPCaptureLevels( 8223 OMPD_target_teams_distribute_parallel_for_simd); 8224 ThisCaptureLevel > 1; --ThisCaptureLevel) { 8225 CS = cast<CapturedStmt>(CS->getCapturedStmt()); 8226 // 1.2.2 OpenMP Language Terminology 8227 // Structured block - An executable statement with a single entry at the 8228 // top and a single exit at the bottom. 8229 // The point of exit cannot be a branch out of the structured block. 8230 // longjmp() and throw() must not violate the entry/exit criteria. 8231 CS->getCapturedDecl()->setNothrow(); 8232 } 8233 8234 OMPLoopDirective::HelperExprs B; 8235 // In presence of clause 'collapse' with number of loops, it will 8236 // define the nested loops number. 8237 unsigned NestedLoopCount = 8238 checkOpenMPLoop(OMPD_target_teams_distribute_parallel_for_simd, 8239 getCollapseNumberExpr(Clauses), 8240 nullptr /*ordered not a clause on distribute*/, CS, *this, 8241 *DSAStack, VarsWithImplicitDSA, B); 8242 if (NestedLoopCount == 0) 8243 return StmtError(); 8244 8245 assert((CurContext->isDependentContext() || B.builtAll()) && 8246 "omp target teams distribute parallel for simd loop exprs were not " 8247 "built"); 8248 8249 if (!CurContext->isDependentContext()) { 8250 // Finalize the clauses that need pre-built expressions for CodeGen. 8251 for (OMPClause *C : Clauses) { 8252 if (auto *LC = dyn_cast<OMPLinearClause>(C)) 8253 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef), 8254 B.NumIterations, *this, CurScope, 8255 DSAStack)) 8256 return StmtError(); 8257 } 8258 } 8259 8260 if (checkSimdlenSafelenSpecified(*this, Clauses)) 8261 return StmtError(); 8262 8263 setFunctionHasBranchProtectedScope(); 8264 return OMPTargetTeamsDistributeParallelForSimdDirective::Create( 8265 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B); 8266 } 8267 8268 StmtResult Sema::ActOnOpenMPTargetTeamsDistributeSimdDirective( 8269 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, 8270 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) { 8271 if (!AStmt) 8272 return StmtError(); 8273 8274 auto *CS = cast<CapturedStmt>(AStmt); 8275 // 1.2.2 OpenMP Language Terminology 8276 // Structured block - An executable statement with a single entry at the 8277 // top and a single exit at the bottom. 8278 // The point of exit cannot be a branch out of the structured block. 8279 // longjmp() and throw() must not violate the entry/exit criteria. 8280 CS->getCapturedDecl()->setNothrow(); 8281 for (int ThisCaptureLevel = 8282 getOpenMPCaptureLevels(OMPD_target_teams_distribute_simd); 8283 ThisCaptureLevel > 1; --ThisCaptureLevel) { 8284 CS = cast<CapturedStmt>(CS->getCapturedStmt()); 8285 // 1.2.2 OpenMP Language Terminology 8286 // Structured block - An executable statement with a single entry at the 8287 // top and a single exit at the bottom. 8288 // The point of exit cannot be a branch out of the structured block. 8289 // longjmp() and throw() must not violate the entry/exit criteria. 8290 CS->getCapturedDecl()->setNothrow(); 8291 } 8292 8293 OMPLoopDirective::HelperExprs B; 8294 // In presence of clause 'collapse' with number of loops, it will 8295 // define the nested loops number. 8296 unsigned NestedLoopCount = checkOpenMPLoop( 8297 OMPD_target_teams_distribute_simd, getCollapseNumberExpr(Clauses), 8298 nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStack, 8299 VarsWithImplicitDSA, B); 8300 if (NestedLoopCount == 0) 8301 return StmtError(); 8302 8303 assert((CurContext->isDependentContext() || B.builtAll()) && 8304 "omp target teams distribute simd loop exprs were not built"); 8305 8306 if (!CurContext->isDependentContext()) { 8307 // Finalize the clauses that need pre-built expressions for CodeGen. 8308 for (OMPClause *C : Clauses) { 8309 if (auto *LC = dyn_cast<OMPLinearClause>(C)) 8310 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef), 8311 B.NumIterations, *this, CurScope, 8312 DSAStack)) 8313 return StmtError(); 8314 } 8315 } 8316 8317 if (checkSimdlenSafelenSpecified(*this, Clauses)) 8318 return StmtError(); 8319 8320 setFunctionHasBranchProtectedScope(); 8321 return OMPTargetTeamsDistributeSimdDirective::Create( 8322 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B); 8323 } 8324 8325 OMPClause *Sema::ActOnOpenMPSingleExprClause(OpenMPClauseKind Kind, Expr *Expr, 8326 SourceLocation StartLoc, 8327 SourceLocation LParenLoc, 8328 SourceLocation EndLoc) { 8329 OMPClause *Res = nullptr; 8330 switch (Kind) { 8331 case OMPC_final: 8332 Res = ActOnOpenMPFinalClause(Expr, StartLoc, LParenLoc, EndLoc); 8333 break; 8334 case OMPC_num_threads: 8335 Res = ActOnOpenMPNumThreadsClause(Expr, StartLoc, LParenLoc, EndLoc); 8336 break; 8337 case OMPC_safelen: 8338 Res = ActOnOpenMPSafelenClause(Expr, StartLoc, LParenLoc, EndLoc); 8339 break; 8340 case OMPC_simdlen: 8341 Res = ActOnOpenMPSimdlenClause(Expr, StartLoc, LParenLoc, EndLoc); 8342 break; 8343 case OMPC_collapse: 8344 Res = ActOnOpenMPCollapseClause(Expr, StartLoc, LParenLoc, EndLoc); 8345 break; 8346 case OMPC_ordered: 8347 Res = ActOnOpenMPOrderedClause(StartLoc, EndLoc, LParenLoc, Expr); 8348 break; 8349 case OMPC_device: 8350 Res = ActOnOpenMPDeviceClause(Expr, StartLoc, LParenLoc, EndLoc); 8351 break; 8352 case OMPC_num_teams: 8353 Res = ActOnOpenMPNumTeamsClause(Expr, StartLoc, LParenLoc, EndLoc); 8354 break; 8355 case OMPC_thread_limit: 8356 Res = ActOnOpenMPThreadLimitClause(Expr, StartLoc, LParenLoc, EndLoc); 8357 break; 8358 case OMPC_priority: 8359 Res = ActOnOpenMPPriorityClause(Expr, StartLoc, LParenLoc, EndLoc); 8360 break; 8361 case OMPC_grainsize: 8362 Res = ActOnOpenMPGrainsizeClause(Expr, StartLoc, LParenLoc, EndLoc); 8363 break; 8364 case OMPC_num_tasks: 8365 Res = ActOnOpenMPNumTasksClause(Expr, StartLoc, LParenLoc, EndLoc); 8366 break; 8367 case OMPC_hint: 8368 Res = ActOnOpenMPHintClause(Expr, StartLoc, LParenLoc, EndLoc); 8369 break; 8370 case OMPC_if: 8371 case OMPC_default: 8372 case OMPC_proc_bind: 8373 case OMPC_schedule: 8374 case OMPC_private: 8375 case OMPC_firstprivate: 8376 case OMPC_lastprivate: 8377 case OMPC_shared: 8378 case OMPC_reduction: 8379 case OMPC_task_reduction: 8380 case OMPC_in_reduction: 8381 case OMPC_linear: 8382 case OMPC_aligned: 8383 case OMPC_copyin: 8384 case OMPC_copyprivate: 8385 case OMPC_nowait: 8386 case OMPC_untied: 8387 case OMPC_mergeable: 8388 case OMPC_threadprivate: 8389 case OMPC_flush: 8390 case OMPC_read: 8391 case OMPC_write: 8392 case OMPC_update: 8393 case OMPC_capture: 8394 case OMPC_seq_cst: 8395 case OMPC_depend: 8396 case OMPC_threads: 8397 case OMPC_simd: 8398 case OMPC_map: 8399 case OMPC_nogroup: 8400 case OMPC_dist_schedule: 8401 case OMPC_defaultmap: 8402 case OMPC_unknown: 8403 case OMPC_uniform: 8404 case OMPC_to: 8405 case OMPC_from: 8406 case OMPC_use_device_ptr: 8407 case OMPC_is_device_ptr: 8408 case OMPC_unified_address: 8409 case OMPC_unified_shared_memory: 8410 case OMPC_reverse_offload: 8411 case OMPC_dynamic_allocators: 8412 case OMPC_atomic_default_mem_order: 8413 llvm_unreachable("Clause is not allowed."); 8414 } 8415 return Res; 8416 } 8417 8418 // An OpenMP directive such as 'target parallel' has two captured regions: 8419 // for the 'target' and 'parallel' respectively. This function returns 8420 // the region in which to capture expressions associated with a clause. 8421 // A return value of OMPD_unknown signifies that the expression should not 8422 // be captured. 8423 static OpenMPDirectiveKind getOpenMPCaptureRegionForClause( 8424 OpenMPDirectiveKind DKind, OpenMPClauseKind CKind, 8425 OpenMPDirectiveKind NameModifier = OMPD_unknown) { 8426 OpenMPDirectiveKind CaptureRegion = OMPD_unknown; 8427 switch (CKind) { 8428 case OMPC_if: 8429 switch (DKind) { 8430 case OMPD_target_parallel: 8431 case OMPD_target_parallel_for: 8432 case OMPD_target_parallel_for_simd: 8433 // If this clause applies to the nested 'parallel' region, capture within 8434 // the 'target' region, otherwise do not capture. 8435 if (NameModifier == OMPD_unknown || NameModifier == OMPD_parallel) 8436 CaptureRegion = OMPD_target; 8437 break; 8438 case OMPD_target_teams_distribute_parallel_for: 8439 case OMPD_target_teams_distribute_parallel_for_simd: 8440 // If this clause applies to the nested 'parallel' region, capture within 8441 // the 'teams' region, otherwise do not capture. 8442 if (NameModifier == OMPD_unknown || NameModifier == OMPD_parallel) 8443 CaptureRegion = OMPD_teams; 8444 break; 8445 case OMPD_teams_distribute_parallel_for: 8446 case OMPD_teams_distribute_parallel_for_simd: 8447 CaptureRegion = OMPD_teams; 8448 break; 8449 case OMPD_target_update: 8450 case OMPD_target_enter_data: 8451 case OMPD_target_exit_data: 8452 CaptureRegion = OMPD_task; 8453 break; 8454 case OMPD_cancel: 8455 case OMPD_parallel: 8456 case OMPD_parallel_sections: 8457 case OMPD_parallel_for: 8458 case OMPD_parallel_for_simd: 8459 case OMPD_target: 8460 case OMPD_target_simd: 8461 case OMPD_target_teams: 8462 case OMPD_target_teams_distribute: 8463 case OMPD_target_teams_distribute_simd: 8464 case OMPD_distribute_parallel_for: 8465 case OMPD_distribute_parallel_for_simd: 8466 case OMPD_task: 8467 case OMPD_taskloop: 8468 case OMPD_taskloop_simd: 8469 case OMPD_target_data: 8470 // Do not capture if-clause expressions. 8471 break; 8472 case OMPD_threadprivate: 8473 case OMPD_taskyield: 8474 case OMPD_barrier: 8475 case OMPD_taskwait: 8476 case OMPD_cancellation_point: 8477 case OMPD_flush: 8478 case OMPD_declare_reduction: 8479 case OMPD_declare_mapper: 8480 case OMPD_declare_simd: 8481 case OMPD_declare_target: 8482 case OMPD_end_declare_target: 8483 case OMPD_teams: 8484 case OMPD_simd: 8485 case OMPD_for: 8486 case OMPD_for_simd: 8487 case OMPD_sections: 8488 case OMPD_section: 8489 case OMPD_single: 8490 case OMPD_master: 8491 case OMPD_critical: 8492 case OMPD_taskgroup: 8493 case OMPD_distribute: 8494 case OMPD_ordered: 8495 case OMPD_atomic: 8496 case OMPD_distribute_simd: 8497 case OMPD_teams_distribute: 8498 case OMPD_teams_distribute_simd: 8499 case OMPD_requires: 8500 llvm_unreachable("Unexpected OpenMP directive with if-clause"); 8501 case OMPD_unknown: 8502 llvm_unreachable("Unknown OpenMP directive"); 8503 } 8504 break; 8505 case OMPC_num_threads: 8506 switch (DKind) { 8507 case OMPD_target_parallel: 8508 case OMPD_target_parallel_for: 8509 case OMPD_target_parallel_for_simd: 8510 CaptureRegion = OMPD_target; 8511 break; 8512 case OMPD_teams_distribute_parallel_for: 8513 case OMPD_teams_distribute_parallel_for_simd: 8514 case OMPD_target_teams_distribute_parallel_for: 8515 case OMPD_target_teams_distribute_parallel_for_simd: 8516 CaptureRegion = OMPD_teams; 8517 break; 8518 case OMPD_parallel: 8519 case OMPD_parallel_sections: 8520 case OMPD_parallel_for: 8521 case OMPD_parallel_for_simd: 8522 case OMPD_distribute_parallel_for: 8523 case OMPD_distribute_parallel_for_simd: 8524 // Do not capture num_threads-clause expressions. 8525 break; 8526 case OMPD_target_data: 8527 case OMPD_target_enter_data: 8528 case OMPD_target_exit_data: 8529 case OMPD_target_update: 8530 case OMPD_target: 8531 case OMPD_target_simd: 8532 case OMPD_target_teams: 8533 case OMPD_target_teams_distribute: 8534 case OMPD_target_teams_distribute_simd: 8535 case OMPD_cancel: 8536 case OMPD_task: 8537 case OMPD_taskloop: 8538 case OMPD_taskloop_simd: 8539 case OMPD_threadprivate: 8540 case OMPD_taskyield: 8541 case OMPD_barrier: 8542 case OMPD_taskwait: 8543 case OMPD_cancellation_point: 8544 case OMPD_flush: 8545 case OMPD_declare_reduction: 8546 case OMPD_declare_mapper: 8547 case OMPD_declare_simd: 8548 case OMPD_declare_target: 8549 case OMPD_end_declare_target: 8550 case OMPD_teams: 8551 case OMPD_simd: 8552 case OMPD_for: 8553 case OMPD_for_simd: 8554 case OMPD_sections: 8555 case OMPD_section: 8556 case OMPD_single: 8557 case OMPD_master: 8558 case OMPD_critical: 8559 case OMPD_taskgroup: 8560 case OMPD_distribute: 8561 case OMPD_ordered: 8562 case OMPD_atomic: 8563 case OMPD_distribute_simd: 8564 case OMPD_teams_distribute: 8565 case OMPD_teams_distribute_simd: 8566 case OMPD_requires: 8567 llvm_unreachable("Unexpected OpenMP directive with num_threads-clause"); 8568 case OMPD_unknown: 8569 llvm_unreachable("Unknown OpenMP directive"); 8570 } 8571 break; 8572 case OMPC_num_teams: 8573 switch (DKind) { 8574 case OMPD_target_teams: 8575 case OMPD_target_teams_distribute: 8576 case OMPD_target_teams_distribute_simd: 8577 case OMPD_target_teams_distribute_parallel_for: 8578 case OMPD_target_teams_distribute_parallel_for_simd: 8579 CaptureRegion = OMPD_target; 8580 break; 8581 case OMPD_teams_distribute_parallel_for: 8582 case OMPD_teams_distribute_parallel_for_simd: 8583 case OMPD_teams: 8584 case OMPD_teams_distribute: 8585 case OMPD_teams_distribute_simd: 8586 // Do not capture num_teams-clause expressions. 8587 break; 8588 case OMPD_distribute_parallel_for: 8589 case OMPD_distribute_parallel_for_simd: 8590 case OMPD_task: 8591 case OMPD_taskloop: 8592 case OMPD_taskloop_simd: 8593 case OMPD_target_data: 8594 case OMPD_target_enter_data: 8595 case OMPD_target_exit_data: 8596 case OMPD_target_update: 8597 case OMPD_cancel: 8598 case OMPD_parallel: 8599 case OMPD_parallel_sections: 8600 case OMPD_parallel_for: 8601 case OMPD_parallel_for_simd: 8602 case OMPD_target: 8603 case OMPD_target_simd: 8604 case OMPD_target_parallel: 8605 case OMPD_target_parallel_for: 8606 case OMPD_target_parallel_for_simd: 8607 case OMPD_threadprivate: 8608 case OMPD_taskyield: 8609 case OMPD_barrier: 8610 case OMPD_taskwait: 8611 case OMPD_cancellation_point: 8612 case OMPD_flush: 8613 case OMPD_declare_reduction: 8614 case OMPD_declare_mapper: 8615 case OMPD_declare_simd: 8616 case OMPD_declare_target: 8617 case OMPD_end_declare_target: 8618 case OMPD_simd: 8619 case OMPD_for: 8620 case OMPD_for_simd: 8621 case OMPD_sections: 8622 case OMPD_section: 8623 case OMPD_single: 8624 case OMPD_master: 8625 case OMPD_critical: 8626 case OMPD_taskgroup: 8627 case OMPD_distribute: 8628 case OMPD_ordered: 8629 case OMPD_atomic: 8630 case OMPD_distribute_simd: 8631 case OMPD_requires: 8632 llvm_unreachable("Unexpected OpenMP directive with num_teams-clause"); 8633 case OMPD_unknown: 8634 llvm_unreachable("Unknown OpenMP directive"); 8635 } 8636 break; 8637 case OMPC_thread_limit: 8638 switch (DKind) { 8639 case OMPD_target_teams: 8640 case OMPD_target_teams_distribute: 8641 case OMPD_target_teams_distribute_simd: 8642 case OMPD_target_teams_distribute_parallel_for: 8643 case OMPD_target_teams_distribute_parallel_for_simd: 8644 CaptureRegion = OMPD_target; 8645 break; 8646 case OMPD_teams_distribute_parallel_for: 8647 case OMPD_teams_distribute_parallel_for_simd: 8648 case OMPD_teams: 8649 case OMPD_teams_distribute: 8650 case OMPD_teams_distribute_simd: 8651 // Do not capture thread_limit-clause expressions. 8652 break; 8653 case OMPD_distribute_parallel_for: 8654 case OMPD_distribute_parallel_for_simd: 8655 case OMPD_task: 8656 case OMPD_taskloop: 8657 case OMPD_taskloop_simd: 8658 case OMPD_target_data: 8659 case OMPD_target_enter_data: 8660 case OMPD_target_exit_data: 8661 case OMPD_target_update: 8662 case OMPD_cancel: 8663 case OMPD_parallel: 8664 case OMPD_parallel_sections: 8665 case OMPD_parallel_for: 8666 case OMPD_parallel_for_simd: 8667 case OMPD_target: 8668 case OMPD_target_simd: 8669 case OMPD_target_parallel: 8670 case OMPD_target_parallel_for: 8671 case OMPD_target_parallel_for_simd: 8672 case OMPD_threadprivate: 8673 case OMPD_taskyield: 8674 case OMPD_barrier: 8675 case OMPD_taskwait: 8676 case OMPD_cancellation_point: 8677 case OMPD_flush: 8678 case OMPD_declare_reduction: 8679 case OMPD_declare_mapper: 8680 case OMPD_declare_simd: 8681 case OMPD_declare_target: 8682 case OMPD_end_declare_target: 8683 case OMPD_simd: 8684 case OMPD_for: 8685 case OMPD_for_simd: 8686 case OMPD_sections: 8687 case OMPD_section: 8688 case OMPD_single: 8689 case OMPD_master: 8690 case OMPD_critical: 8691 case OMPD_taskgroup: 8692 case OMPD_distribute: 8693 case OMPD_ordered: 8694 case OMPD_atomic: 8695 case OMPD_distribute_simd: 8696 case OMPD_requires: 8697 llvm_unreachable("Unexpected OpenMP directive with thread_limit-clause"); 8698 case OMPD_unknown: 8699 llvm_unreachable("Unknown OpenMP directive"); 8700 } 8701 break; 8702 case OMPC_schedule: 8703 switch (DKind) { 8704 case OMPD_parallel_for: 8705 case OMPD_parallel_for_simd: 8706 case OMPD_distribute_parallel_for: 8707 case OMPD_distribute_parallel_for_simd: 8708 case OMPD_teams_distribute_parallel_for: 8709 case OMPD_teams_distribute_parallel_for_simd: 8710 case OMPD_target_parallel_for: 8711 case OMPD_target_parallel_for_simd: 8712 case OMPD_target_teams_distribute_parallel_for: 8713 case OMPD_target_teams_distribute_parallel_for_simd: 8714 CaptureRegion = OMPD_parallel; 8715 break; 8716 case OMPD_for: 8717 case OMPD_for_simd: 8718 // Do not capture schedule-clause expressions. 8719 break; 8720 case OMPD_task: 8721 case OMPD_taskloop: 8722 case OMPD_taskloop_simd: 8723 case OMPD_target_data: 8724 case OMPD_target_enter_data: 8725 case OMPD_target_exit_data: 8726 case OMPD_target_update: 8727 case OMPD_teams: 8728 case OMPD_teams_distribute: 8729 case OMPD_teams_distribute_simd: 8730 case OMPD_target_teams_distribute: 8731 case OMPD_target_teams_distribute_simd: 8732 case OMPD_target: 8733 case OMPD_target_simd: 8734 case OMPD_target_parallel: 8735 case OMPD_cancel: 8736 case OMPD_parallel: 8737 case OMPD_parallel_sections: 8738 case OMPD_threadprivate: 8739 case OMPD_taskyield: 8740 case OMPD_barrier: 8741 case OMPD_taskwait: 8742 case OMPD_cancellation_point: 8743 case OMPD_flush: 8744 case OMPD_declare_reduction: 8745 case OMPD_declare_mapper: 8746 case OMPD_declare_simd: 8747 case OMPD_declare_target: 8748 case OMPD_end_declare_target: 8749 case OMPD_simd: 8750 case OMPD_sections: 8751 case OMPD_section: 8752 case OMPD_single: 8753 case OMPD_master: 8754 case OMPD_critical: 8755 case OMPD_taskgroup: 8756 case OMPD_distribute: 8757 case OMPD_ordered: 8758 case OMPD_atomic: 8759 case OMPD_distribute_simd: 8760 case OMPD_target_teams: 8761 case OMPD_requires: 8762 llvm_unreachable("Unexpected OpenMP directive with schedule clause"); 8763 case OMPD_unknown: 8764 llvm_unreachable("Unknown OpenMP directive"); 8765 } 8766 break; 8767 case OMPC_dist_schedule: 8768 switch (DKind) { 8769 case OMPD_teams_distribute_parallel_for: 8770 case OMPD_teams_distribute_parallel_for_simd: 8771 case OMPD_teams_distribute: 8772 case OMPD_teams_distribute_simd: 8773 case OMPD_target_teams_distribute_parallel_for: 8774 case OMPD_target_teams_distribute_parallel_for_simd: 8775 case OMPD_target_teams_distribute: 8776 case OMPD_target_teams_distribute_simd: 8777 CaptureRegion = OMPD_teams; 8778 break; 8779 case OMPD_distribute_parallel_for: 8780 case OMPD_distribute_parallel_for_simd: 8781 case OMPD_distribute: 8782 case OMPD_distribute_simd: 8783 // Do not capture thread_limit-clause expressions. 8784 break; 8785 case OMPD_parallel_for: 8786 case OMPD_parallel_for_simd: 8787 case OMPD_target_parallel_for_simd: 8788 case OMPD_target_parallel_for: 8789 case OMPD_task: 8790 case OMPD_taskloop: 8791 case OMPD_taskloop_simd: 8792 case OMPD_target_data: 8793 case OMPD_target_enter_data: 8794 case OMPD_target_exit_data: 8795 case OMPD_target_update: 8796 case OMPD_teams: 8797 case OMPD_target: 8798 case OMPD_target_simd: 8799 case OMPD_target_parallel: 8800 case OMPD_cancel: 8801 case OMPD_parallel: 8802 case OMPD_parallel_sections: 8803 case OMPD_threadprivate: 8804 case OMPD_taskyield: 8805 case OMPD_barrier: 8806 case OMPD_taskwait: 8807 case OMPD_cancellation_point: 8808 case OMPD_flush: 8809 case OMPD_declare_reduction: 8810 case OMPD_declare_mapper: 8811 case OMPD_declare_simd: 8812 case OMPD_declare_target: 8813 case OMPD_end_declare_target: 8814 case OMPD_simd: 8815 case OMPD_for: 8816 case OMPD_for_simd: 8817 case OMPD_sections: 8818 case OMPD_section: 8819 case OMPD_single: 8820 case OMPD_master: 8821 case OMPD_critical: 8822 case OMPD_taskgroup: 8823 case OMPD_ordered: 8824 case OMPD_atomic: 8825 case OMPD_target_teams: 8826 case OMPD_requires: 8827 llvm_unreachable("Unexpected OpenMP directive with schedule clause"); 8828 case OMPD_unknown: 8829 llvm_unreachable("Unknown OpenMP directive"); 8830 } 8831 break; 8832 case OMPC_device: 8833 switch (DKind) { 8834 case OMPD_target_update: 8835 case OMPD_target_enter_data: 8836 case OMPD_target_exit_data: 8837 case OMPD_target: 8838 case OMPD_target_simd: 8839 case OMPD_target_teams: 8840 case OMPD_target_parallel: 8841 case OMPD_target_teams_distribute: 8842 case OMPD_target_teams_distribute_simd: 8843 case OMPD_target_parallel_for: 8844 case OMPD_target_parallel_for_simd: 8845 case OMPD_target_teams_distribute_parallel_for: 8846 case OMPD_target_teams_distribute_parallel_for_simd: 8847 CaptureRegion = OMPD_task; 8848 break; 8849 case OMPD_target_data: 8850 // Do not capture device-clause expressions. 8851 break; 8852 case OMPD_teams_distribute_parallel_for: 8853 case OMPD_teams_distribute_parallel_for_simd: 8854 case OMPD_teams: 8855 case OMPD_teams_distribute: 8856 case OMPD_teams_distribute_simd: 8857 case OMPD_distribute_parallel_for: 8858 case OMPD_distribute_parallel_for_simd: 8859 case OMPD_task: 8860 case OMPD_taskloop: 8861 case OMPD_taskloop_simd: 8862 case OMPD_cancel: 8863 case OMPD_parallel: 8864 case OMPD_parallel_sections: 8865 case OMPD_parallel_for: 8866 case OMPD_parallel_for_simd: 8867 case OMPD_threadprivate: 8868 case OMPD_taskyield: 8869 case OMPD_barrier: 8870 case OMPD_taskwait: 8871 case OMPD_cancellation_point: 8872 case OMPD_flush: 8873 case OMPD_declare_reduction: 8874 case OMPD_declare_mapper: 8875 case OMPD_declare_simd: 8876 case OMPD_declare_target: 8877 case OMPD_end_declare_target: 8878 case OMPD_simd: 8879 case OMPD_for: 8880 case OMPD_for_simd: 8881 case OMPD_sections: 8882 case OMPD_section: 8883 case OMPD_single: 8884 case OMPD_master: 8885 case OMPD_critical: 8886 case OMPD_taskgroup: 8887 case OMPD_distribute: 8888 case OMPD_ordered: 8889 case OMPD_atomic: 8890 case OMPD_distribute_simd: 8891 case OMPD_requires: 8892 llvm_unreachable("Unexpected OpenMP directive with num_teams-clause"); 8893 case OMPD_unknown: 8894 llvm_unreachable("Unknown OpenMP directive"); 8895 } 8896 break; 8897 case OMPC_firstprivate: 8898 case OMPC_lastprivate: 8899 case OMPC_reduction: 8900 case OMPC_task_reduction: 8901 case OMPC_in_reduction: 8902 case OMPC_linear: 8903 case OMPC_default: 8904 case OMPC_proc_bind: 8905 case OMPC_final: 8906 case OMPC_safelen: 8907 case OMPC_simdlen: 8908 case OMPC_collapse: 8909 case OMPC_private: 8910 case OMPC_shared: 8911 case OMPC_aligned: 8912 case OMPC_copyin: 8913 case OMPC_copyprivate: 8914 case OMPC_ordered: 8915 case OMPC_nowait: 8916 case OMPC_untied: 8917 case OMPC_mergeable: 8918 case OMPC_threadprivate: 8919 case OMPC_flush: 8920 case OMPC_read: 8921 case OMPC_write: 8922 case OMPC_update: 8923 case OMPC_capture: 8924 case OMPC_seq_cst: 8925 case OMPC_depend: 8926 case OMPC_threads: 8927 case OMPC_simd: 8928 case OMPC_map: 8929 case OMPC_priority: 8930 case OMPC_grainsize: 8931 case OMPC_nogroup: 8932 case OMPC_num_tasks: 8933 case OMPC_hint: 8934 case OMPC_defaultmap: 8935 case OMPC_unknown: 8936 case OMPC_uniform: 8937 case OMPC_to: 8938 case OMPC_from: 8939 case OMPC_use_device_ptr: 8940 case OMPC_is_device_ptr: 8941 case OMPC_unified_address: 8942 case OMPC_unified_shared_memory: 8943 case OMPC_reverse_offload: 8944 case OMPC_dynamic_allocators: 8945 case OMPC_atomic_default_mem_order: 8946 llvm_unreachable("Unexpected OpenMP clause."); 8947 } 8948 return CaptureRegion; 8949 } 8950 8951 OMPClause *Sema::ActOnOpenMPIfClause(OpenMPDirectiveKind NameModifier, 8952 Expr *Condition, SourceLocation StartLoc, 8953 SourceLocation LParenLoc, 8954 SourceLocation NameModifierLoc, 8955 SourceLocation ColonLoc, 8956 SourceLocation EndLoc) { 8957 Expr *ValExpr = Condition; 8958 Stmt *HelperValStmt = nullptr; 8959 OpenMPDirectiveKind CaptureRegion = OMPD_unknown; 8960 if (!Condition->isValueDependent() && !Condition->isTypeDependent() && 8961 !Condition->isInstantiationDependent() && 8962 !Condition->containsUnexpandedParameterPack()) { 8963 ExprResult Val = CheckBooleanCondition(StartLoc, Condition); 8964 if (Val.isInvalid()) 8965 return nullptr; 8966 8967 ValExpr = Val.get(); 8968 8969 OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective(); 8970 CaptureRegion = 8971 getOpenMPCaptureRegionForClause(DKind, OMPC_if, NameModifier); 8972 if (CaptureRegion != OMPD_unknown && !CurContext->isDependentContext()) { 8973 ValExpr = MakeFullExpr(ValExpr).get(); 8974 llvm::MapVector<const Expr *, DeclRefExpr *> Captures; 8975 ValExpr = tryBuildCapture(*this, ValExpr, Captures).get(); 8976 HelperValStmt = buildPreInits(Context, Captures); 8977 } 8978 } 8979 8980 return new (Context) 8981 OMPIfClause(NameModifier, ValExpr, HelperValStmt, CaptureRegion, StartLoc, 8982 LParenLoc, NameModifierLoc, ColonLoc, EndLoc); 8983 } 8984 8985 OMPClause *Sema::ActOnOpenMPFinalClause(Expr *Condition, 8986 SourceLocation StartLoc, 8987 SourceLocation LParenLoc, 8988 SourceLocation EndLoc) { 8989 Expr *ValExpr = Condition; 8990 if (!Condition->isValueDependent() && !Condition->isTypeDependent() && 8991 !Condition->isInstantiationDependent() && 8992 !Condition->containsUnexpandedParameterPack()) { 8993 ExprResult Val = CheckBooleanCondition(StartLoc, Condition); 8994 if (Val.isInvalid()) 8995 return nullptr; 8996 8997 ValExpr = MakeFullExpr(Val.get()).get(); 8998 } 8999 9000 return new (Context) OMPFinalClause(ValExpr, StartLoc, LParenLoc, EndLoc); 9001 } 9002 ExprResult Sema::PerformOpenMPImplicitIntegerConversion(SourceLocation Loc, 9003 Expr *Op) { 9004 if (!Op) 9005 return ExprError(); 9006 9007 class IntConvertDiagnoser : public ICEConvertDiagnoser { 9008 public: 9009 IntConvertDiagnoser() 9010 : ICEConvertDiagnoser(/*AllowScopedEnumerations*/ false, false, true) {} 9011 SemaDiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc, 9012 QualType T) override { 9013 return S.Diag(Loc, diag::err_omp_not_integral) << T; 9014 } 9015 SemaDiagnosticBuilder diagnoseIncomplete(Sema &S, SourceLocation Loc, 9016 QualType T) override { 9017 return S.Diag(Loc, diag::err_omp_incomplete_type) << T; 9018 } 9019 SemaDiagnosticBuilder diagnoseExplicitConv(Sema &S, SourceLocation Loc, 9020 QualType T, 9021 QualType ConvTy) override { 9022 return S.Diag(Loc, diag::err_omp_explicit_conversion) << T << ConvTy; 9023 } 9024 SemaDiagnosticBuilder noteExplicitConv(Sema &S, CXXConversionDecl *Conv, 9025 QualType ConvTy) override { 9026 return S.Diag(Conv->getLocation(), diag::note_omp_conversion_here) 9027 << ConvTy->isEnumeralType() << ConvTy; 9028 } 9029 SemaDiagnosticBuilder diagnoseAmbiguous(Sema &S, SourceLocation Loc, 9030 QualType T) override { 9031 return S.Diag(Loc, diag::err_omp_ambiguous_conversion) << T; 9032 } 9033 SemaDiagnosticBuilder noteAmbiguous(Sema &S, CXXConversionDecl *Conv, 9034 QualType ConvTy) override { 9035 return S.Diag(Conv->getLocation(), diag::note_omp_conversion_here) 9036 << ConvTy->isEnumeralType() << ConvTy; 9037 } 9038 SemaDiagnosticBuilder diagnoseConversion(Sema &, SourceLocation, QualType, 9039 QualType) override { 9040 llvm_unreachable("conversion functions are permitted"); 9041 } 9042 } ConvertDiagnoser; 9043 return PerformContextualImplicitConversion(Loc, Op, ConvertDiagnoser); 9044 } 9045 9046 static bool isNonNegativeIntegerValue(Expr *&ValExpr, Sema &SemaRef, 9047 OpenMPClauseKind CKind, 9048 bool StrictlyPositive) { 9049 if (!ValExpr->isTypeDependent() && !ValExpr->isValueDependent() && 9050 !ValExpr->isInstantiationDependent()) { 9051 SourceLocation Loc = ValExpr->getExprLoc(); 9052 ExprResult Value = 9053 SemaRef.PerformOpenMPImplicitIntegerConversion(Loc, ValExpr); 9054 if (Value.isInvalid()) 9055 return false; 9056 9057 ValExpr = Value.get(); 9058 // The expression must evaluate to a non-negative integer value. 9059 llvm::APSInt Result; 9060 if (ValExpr->isIntegerConstantExpr(Result, SemaRef.Context) && 9061 Result.isSigned() && 9062 !((!StrictlyPositive && Result.isNonNegative()) || 9063 (StrictlyPositive && Result.isStrictlyPositive()))) { 9064 SemaRef.Diag(Loc, diag::err_omp_negative_expression_in_clause) 9065 << getOpenMPClauseName(CKind) << (StrictlyPositive ? 1 : 0) 9066 << ValExpr->getSourceRange(); 9067 return false; 9068 } 9069 } 9070 return true; 9071 } 9072 9073 OMPClause *Sema::ActOnOpenMPNumThreadsClause(Expr *NumThreads, 9074 SourceLocation StartLoc, 9075 SourceLocation LParenLoc, 9076 SourceLocation EndLoc) { 9077 Expr *ValExpr = NumThreads; 9078 Stmt *HelperValStmt = nullptr; 9079 9080 // OpenMP [2.5, Restrictions] 9081 // The num_threads expression must evaluate to a positive integer value. 9082 if (!isNonNegativeIntegerValue(ValExpr, *this, OMPC_num_threads, 9083 /*StrictlyPositive=*/true)) 9084 return nullptr; 9085 9086 OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective(); 9087 OpenMPDirectiveKind CaptureRegion = 9088 getOpenMPCaptureRegionForClause(DKind, OMPC_num_threads); 9089 if (CaptureRegion != OMPD_unknown && !CurContext->isDependentContext()) { 9090 ValExpr = MakeFullExpr(ValExpr).get(); 9091 llvm::MapVector<const Expr *, DeclRefExpr *> Captures; 9092 ValExpr = tryBuildCapture(*this, ValExpr, Captures).get(); 9093 HelperValStmt = buildPreInits(Context, Captures); 9094 } 9095 9096 return new (Context) OMPNumThreadsClause( 9097 ValExpr, HelperValStmt, CaptureRegion, StartLoc, LParenLoc, EndLoc); 9098 } 9099 9100 ExprResult Sema::VerifyPositiveIntegerConstantInClause(Expr *E, 9101 OpenMPClauseKind CKind, 9102 bool StrictlyPositive) { 9103 if (!E) 9104 return ExprError(); 9105 if (E->isValueDependent() || E->isTypeDependent() || 9106 E->isInstantiationDependent() || E->containsUnexpandedParameterPack()) 9107 return E; 9108 llvm::APSInt Result; 9109 ExprResult ICE = VerifyIntegerConstantExpression(E, &Result); 9110 if (ICE.isInvalid()) 9111 return ExprError(); 9112 if ((StrictlyPositive && !Result.isStrictlyPositive()) || 9113 (!StrictlyPositive && !Result.isNonNegative())) { 9114 Diag(E->getExprLoc(), diag::err_omp_negative_expression_in_clause) 9115 << getOpenMPClauseName(CKind) << (StrictlyPositive ? 1 : 0) 9116 << E->getSourceRange(); 9117 return ExprError(); 9118 } 9119 if (CKind == OMPC_aligned && !Result.isPowerOf2()) { 9120 Diag(E->getExprLoc(), diag::warn_omp_alignment_not_power_of_two) 9121 << E->getSourceRange(); 9122 return ExprError(); 9123 } 9124 if (CKind == OMPC_collapse && DSAStack->getAssociatedLoops() == 1) 9125 DSAStack->setAssociatedLoops(Result.getExtValue()); 9126 else if (CKind == OMPC_ordered) 9127 DSAStack->setAssociatedLoops(Result.getExtValue()); 9128 return ICE; 9129 } 9130 9131 OMPClause *Sema::ActOnOpenMPSafelenClause(Expr *Len, SourceLocation StartLoc, 9132 SourceLocation LParenLoc, 9133 SourceLocation EndLoc) { 9134 // OpenMP [2.8.1, simd construct, Description] 9135 // The parameter of the safelen clause must be a constant 9136 // positive integer expression. 9137 ExprResult Safelen = VerifyPositiveIntegerConstantInClause(Len, OMPC_safelen); 9138 if (Safelen.isInvalid()) 9139 return nullptr; 9140 return new (Context) 9141 OMPSafelenClause(Safelen.get(), StartLoc, LParenLoc, EndLoc); 9142 } 9143 9144 OMPClause *Sema::ActOnOpenMPSimdlenClause(Expr *Len, SourceLocation StartLoc, 9145 SourceLocation LParenLoc, 9146 SourceLocation EndLoc) { 9147 // OpenMP [2.8.1, simd construct, Description] 9148 // The parameter of the simdlen clause must be a constant 9149 // positive integer expression. 9150 ExprResult Simdlen = VerifyPositiveIntegerConstantInClause(Len, OMPC_simdlen); 9151 if (Simdlen.isInvalid()) 9152 return nullptr; 9153 return new (Context) 9154 OMPSimdlenClause(Simdlen.get(), StartLoc, LParenLoc, EndLoc); 9155 } 9156 9157 OMPClause *Sema::ActOnOpenMPCollapseClause(Expr *NumForLoops, 9158 SourceLocation StartLoc, 9159 SourceLocation LParenLoc, 9160 SourceLocation EndLoc) { 9161 // OpenMP [2.7.1, loop construct, Description] 9162 // OpenMP [2.8.1, simd construct, Description] 9163 // OpenMP [2.9.6, distribute construct, Description] 9164 // The parameter of the collapse clause must be a constant 9165 // positive integer expression. 9166 ExprResult NumForLoopsResult = 9167 VerifyPositiveIntegerConstantInClause(NumForLoops, OMPC_collapse); 9168 if (NumForLoopsResult.isInvalid()) 9169 return nullptr; 9170 return new (Context) 9171 OMPCollapseClause(NumForLoopsResult.get(), StartLoc, LParenLoc, EndLoc); 9172 } 9173 9174 OMPClause *Sema::ActOnOpenMPOrderedClause(SourceLocation StartLoc, 9175 SourceLocation EndLoc, 9176 SourceLocation LParenLoc, 9177 Expr *NumForLoops) { 9178 // OpenMP [2.7.1, loop construct, Description] 9179 // OpenMP [2.8.1, simd construct, Description] 9180 // OpenMP [2.9.6, distribute construct, Description] 9181 // The parameter of the ordered clause must be a constant 9182 // positive integer expression if any. 9183 if (NumForLoops && LParenLoc.isValid()) { 9184 ExprResult NumForLoopsResult = 9185 VerifyPositiveIntegerConstantInClause(NumForLoops, OMPC_ordered); 9186 if (NumForLoopsResult.isInvalid()) 9187 return nullptr; 9188 NumForLoops = NumForLoopsResult.get(); 9189 } else { 9190 NumForLoops = nullptr; 9191 } 9192 auto *Clause = OMPOrderedClause::Create( 9193 Context, NumForLoops, NumForLoops ? DSAStack->getAssociatedLoops() : 0, 9194 StartLoc, LParenLoc, EndLoc); 9195 DSAStack->setOrderedRegion(/*IsOrdered=*/true, NumForLoops, Clause); 9196 return Clause; 9197 } 9198 9199 OMPClause *Sema::ActOnOpenMPSimpleClause( 9200 OpenMPClauseKind Kind, unsigned Argument, SourceLocation ArgumentLoc, 9201 SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc) { 9202 OMPClause *Res = nullptr; 9203 switch (Kind) { 9204 case OMPC_default: 9205 Res = 9206 ActOnOpenMPDefaultClause(static_cast<OpenMPDefaultClauseKind>(Argument), 9207 ArgumentLoc, StartLoc, LParenLoc, EndLoc); 9208 break; 9209 case OMPC_proc_bind: 9210 Res = ActOnOpenMPProcBindClause( 9211 static_cast<OpenMPProcBindClauseKind>(Argument), ArgumentLoc, StartLoc, 9212 LParenLoc, EndLoc); 9213 break; 9214 case OMPC_atomic_default_mem_order: 9215 Res = ActOnOpenMPAtomicDefaultMemOrderClause( 9216 static_cast<OpenMPAtomicDefaultMemOrderClauseKind>(Argument), 9217 ArgumentLoc, StartLoc, LParenLoc, EndLoc); 9218 break; 9219 case OMPC_if: 9220 case OMPC_final: 9221 case OMPC_num_threads: 9222 case OMPC_safelen: 9223 case OMPC_simdlen: 9224 case OMPC_collapse: 9225 case OMPC_schedule: 9226 case OMPC_private: 9227 case OMPC_firstprivate: 9228 case OMPC_lastprivate: 9229 case OMPC_shared: 9230 case OMPC_reduction: 9231 case OMPC_task_reduction: 9232 case OMPC_in_reduction: 9233 case OMPC_linear: 9234 case OMPC_aligned: 9235 case OMPC_copyin: 9236 case OMPC_copyprivate: 9237 case OMPC_ordered: 9238 case OMPC_nowait: 9239 case OMPC_untied: 9240 case OMPC_mergeable: 9241 case OMPC_threadprivate: 9242 case OMPC_flush: 9243 case OMPC_read: 9244 case OMPC_write: 9245 case OMPC_update: 9246 case OMPC_capture: 9247 case OMPC_seq_cst: 9248 case OMPC_depend: 9249 case OMPC_device: 9250 case OMPC_threads: 9251 case OMPC_simd: 9252 case OMPC_map: 9253 case OMPC_num_teams: 9254 case OMPC_thread_limit: 9255 case OMPC_priority: 9256 case OMPC_grainsize: 9257 case OMPC_nogroup: 9258 case OMPC_num_tasks: 9259 case OMPC_hint: 9260 case OMPC_dist_schedule: 9261 case OMPC_defaultmap: 9262 case OMPC_unknown: 9263 case OMPC_uniform: 9264 case OMPC_to: 9265 case OMPC_from: 9266 case OMPC_use_device_ptr: 9267 case OMPC_is_device_ptr: 9268 case OMPC_unified_address: 9269 case OMPC_unified_shared_memory: 9270 case OMPC_reverse_offload: 9271 case OMPC_dynamic_allocators: 9272 llvm_unreachable("Clause is not allowed."); 9273 } 9274 return Res; 9275 } 9276 9277 static std::string 9278 getListOfPossibleValues(OpenMPClauseKind K, unsigned First, unsigned Last, 9279 ArrayRef<unsigned> Exclude = llvm::None) { 9280 SmallString<256> Buffer; 9281 llvm::raw_svector_ostream Out(Buffer); 9282 unsigned Bound = Last >= 2 ? Last - 2 : 0; 9283 unsigned Skipped = Exclude.size(); 9284 auto S = Exclude.begin(), E = Exclude.end(); 9285 for (unsigned I = First; I < Last; ++I) { 9286 if (std::find(S, E, I) != E) { 9287 --Skipped; 9288 continue; 9289 } 9290 Out << "'" << getOpenMPSimpleClauseTypeName(K, I) << "'"; 9291 if (I == Bound - Skipped) 9292 Out << " or "; 9293 else if (I != Bound + 1 - Skipped) 9294 Out << ", "; 9295 } 9296 return Out.str(); 9297 } 9298 9299 OMPClause *Sema::ActOnOpenMPDefaultClause(OpenMPDefaultClauseKind Kind, 9300 SourceLocation KindKwLoc, 9301 SourceLocation StartLoc, 9302 SourceLocation LParenLoc, 9303 SourceLocation EndLoc) { 9304 if (Kind == OMPC_DEFAULT_unknown) { 9305 static_assert(OMPC_DEFAULT_unknown > 0, 9306 "OMPC_DEFAULT_unknown not greater than 0"); 9307 Diag(KindKwLoc, diag::err_omp_unexpected_clause_value) 9308 << getListOfPossibleValues(OMPC_default, /*First=*/0, 9309 /*Last=*/OMPC_DEFAULT_unknown) 9310 << getOpenMPClauseName(OMPC_default); 9311 return nullptr; 9312 } 9313 switch (Kind) { 9314 case OMPC_DEFAULT_none: 9315 DSAStack->setDefaultDSANone(KindKwLoc); 9316 break; 9317 case OMPC_DEFAULT_shared: 9318 DSAStack->setDefaultDSAShared(KindKwLoc); 9319 break; 9320 case OMPC_DEFAULT_unknown: 9321 llvm_unreachable("Clause kind is not allowed."); 9322 break; 9323 } 9324 return new (Context) 9325 OMPDefaultClause(Kind, KindKwLoc, StartLoc, LParenLoc, EndLoc); 9326 } 9327 9328 OMPClause *Sema::ActOnOpenMPProcBindClause(OpenMPProcBindClauseKind Kind, 9329 SourceLocation KindKwLoc, 9330 SourceLocation StartLoc, 9331 SourceLocation LParenLoc, 9332 SourceLocation EndLoc) { 9333 if (Kind == OMPC_PROC_BIND_unknown) { 9334 Diag(KindKwLoc, diag::err_omp_unexpected_clause_value) 9335 << getListOfPossibleValues(OMPC_proc_bind, /*First=*/0, 9336 /*Last=*/OMPC_PROC_BIND_unknown) 9337 << getOpenMPClauseName(OMPC_proc_bind); 9338 return nullptr; 9339 } 9340 return new (Context) 9341 OMPProcBindClause(Kind, KindKwLoc, StartLoc, LParenLoc, EndLoc); 9342 } 9343 9344 OMPClause *Sema::ActOnOpenMPAtomicDefaultMemOrderClause( 9345 OpenMPAtomicDefaultMemOrderClauseKind Kind, SourceLocation KindKwLoc, 9346 SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc) { 9347 if (Kind == OMPC_ATOMIC_DEFAULT_MEM_ORDER_unknown) { 9348 Diag(KindKwLoc, diag::err_omp_unexpected_clause_value) 9349 << getListOfPossibleValues( 9350 OMPC_atomic_default_mem_order, /*First=*/0, 9351 /*Last=*/OMPC_ATOMIC_DEFAULT_MEM_ORDER_unknown) 9352 << getOpenMPClauseName(OMPC_atomic_default_mem_order); 9353 return nullptr; 9354 } 9355 return new (Context) OMPAtomicDefaultMemOrderClause(Kind, KindKwLoc, StartLoc, 9356 LParenLoc, EndLoc); 9357 } 9358 9359 OMPClause *Sema::ActOnOpenMPSingleExprWithArgClause( 9360 OpenMPClauseKind Kind, ArrayRef<unsigned> Argument, Expr *Expr, 9361 SourceLocation StartLoc, SourceLocation LParenLoc, 9362 ArrayRef<SourceLocation> ArgumentLoc, SourceLocation DelimLoc, 9363 SourceLocation EndLoc) { 9364 OMPClause *Res = nullptr; 9365 switch (Kind) { 9366 case OMPC_schedule: 9367 enum { Modifier1, Modifier2, ScheduleKind, NumberOfElements }; 9368 assert(Argument.size() == NumberOfElements && 9369 ArgumentLoc.size() == NumberOfElements); 9370 Res = ActOnOpenMPScheduleClause( 9371 static_cast<OpenMPScheduleClauseModifier>(Argument[Modifier1]), 9372 static_cast<OpenMPScheduleClauseModifier>(Argument[Modifier2]), 9373 static_cast<OpenMPScheduleClauseKind>(Argument[ScheduleKind]), Expr, 9374 StartLoc, LParenLoc, ArgumentLoc[Modifier1], ArgumentLoc[Modifier2], 9375 ArgumentLoc[ScheduleKind], DelimLoc, EndLoc); 9376 break; 9377 case OMPC_if: 9378 assert(Argument.size() == 1 && ArgumentLoc.size() == 1); 9379 Res = ActOnOpenMPIfClause(static_cast<OpenMPDirectiveKind>(Argument.back()), 9380 Expr, StartLoc, LParenLoc, ArgumentLoc.back(), 9381 DelimLoc, EndLoc); 9382 break; 9383 case OMPC_dist_schedule: 9384 Res = ActOnOpenMPDistScheduleClause( 9385 static_cast<OpenMPDistScheduleClauseKind>(Argument.back()), Expr, 9386 StartLoc, LParenLoc, ArgumentLoc.back(), DelimLoc, EndLoc); 9387 break; 9388 case OMPC_defaultmap: 9389 enum { Modifier, DefaultmapKind }; 9390 Res = ActOnOpenMPDefaultmapClause( 9391 static_cast<OpenMPDefaultmapClauseModifier>(Argument[Modifier]), 9392 static_cast<OpenMPDefaultmapClauseKind>(Argument[DefaultmapKind]), 9393 StartLoc, LParenLoc, ArgumentLoc[Modifier], ArgumentLoc[DefaultmapKind], 9394 EndLoc); 9395 break; 9396 case OMPC_final: 9397 case OMPC_num_threads: 9398 case OMPC_safelen: 9399 case OMPC_simdlen: 9400 case OMPC_collapse: 9401 case OMPC_default: 9402 case OMPC_proc_bind: 9403 case OMPC_private: 9404 case OMPC_firstprivate: 9405 case OMPC_lastprivate: 9406 case OMPC_shared: 9407 case OMPC_reduction: 9408 case OMPC_task_reduction: 9409 case OMPC_in_reduction: 9410 case OMPC_linear: 9411 case OMPC_aligned: 9412 case OMPC_copyin: 9413 case OMPC_copyprivate: 9414 case OMPC_ordered: 9415 case OMPC_nowait: 9416 case OMPC_untied: 9417 case OMPC_mergeable: 9418 case OMPC_threadprivate: 9419 case OMPC_flush: 9420 case OMPC_read: 9421 case OMPC_write: 9422 case OMPC_update: 9423 case OMPC_capture: 9424 case OMPC_seq_cst: 9425 case OMPC_depend: 9426 case OMPC_device: 9427 case OMPC_threads: 9428 case OMPC_simd: 9429 case OMPC_map: 9430 case OMPC_num_teams: 9431 case OMPC_thread_limit: 9432 case OMPC_priority: 9433 case OMPC_grainsize: 9434 case OMPC_nogroup: 9435 case OMPC_num_tasks: 9436 case OMPC_hint: 9437 case OMPC_unknown: 9438 case OMPC_uniform: 9439 case OMPC_to: 9440 case OMPC_from: 9441 case OMPC_use_device_ptr: 9442 case OMPC_is_device_ptr: 9443 case OMPC_unified_address: 9444 case OMPC_unified_shared_memory: 9445 case OMPC_reverse_offload: 9446 case OMPC_dynamic_allocators: 9447 case OMPC_atomic_default_mem_order: 9448 llvm_unreachable("Clause is not allowed."); 9449 } 9450 return Res; 9451 } 9452 9453 static bool checkScheduleModifiers(Sema &S, OpenMPScheduleClauseModifier M1, 9454 OpenMPScheduleClauseModifier M2, 9455 SourceLocation M1Loc, SourceLocation M2Loc) { 9456 if (M1 == OMPC_SCHEDULE_MODIFIER_unknown && M1Loc.isValid()) { 9457 SmallVector<unsigned, 2> Excluded; 9458 if (M2 != OMPC_SCHEDULE_MODIFIER_unknown) 9459 Excluded.push_back(M2); 9460 if (M2 == OMPC_SCHEDULE_MODIFIER_nonmonotonic) 9461 Excluded.push_back(OMPC_SCHEDULE_MODIFIER_monotonic); 9462 if (M2 == OMPC_SCHEDULE_MODIFIER_monotonic) 9463 Excluded.push_back(OMPC_SCHEDULE_MODIFIER_nonmonotonic); 9464 S.Diag(M1Loc, diag::err_omp_unexpected_clause_value) 9465 << getListOfPossibleValues(OMPC_schedule, 9466 /*First=*/OMPC_SCHEDULE_MODIFIER_unknown + 1, 9467 /*Last=*/OMPC_SCHEDULE_MODIFIER_last, 9468 Excluded) 9469 << getOpenMPClauseName(OMPC_schedule); 9470 return true; 9471 } 9472 return false; 9473 } 9474 9475 OMPClause *Sema::ActOnOpenMPScheduleClause( 9476 OpenMPScheduleClauseModifier M1, OpenMPScheduleClauseModifier M2, 9477 OpenMPScheduleClauseKind Kind, Expr *ChunkSize, SourceLocation StartLoc, 9478 SourceLocation LParenLoc, SourceLocation M1Loc, SourceLocation M2Loc, 9479 SourceLocation KindLoc, SourceLocation CommaLoc, SourceLocation EndLoc) { 9480 if (checkScheduleModifiers(*this, M1, M2, M1Loc, M2Loc) || 9481 checkScheduleModifiers(*this, M2, M1, M2Loc, M1Loc)) 9482 return nullptr; 9483 // OpenMP, 2.7.1, Loop Construct, Restrictions 9484 // Either the monotonic modifier or the nonmonotonic modifier can be specified 9485 // but not both. 9486 if ((M1 == M2 && M1 != OMPC_SCHEDULE_MODIFIER_unknown) || 9487 (M1 == OMPC_SCHEDULE_MODIFIER_monotonic && 9488 M2 == OMPC_SCHEDULE_MODIFIER_nonmonotonic) || 9489 (M1 == OMPC_SCHEDULE_MODIFIER_nonmonotonic && 9490 M2 == OMPC_SCHEDULE_MODIFIER_monotonic)) { 9491 Diag(M2Loc, diag::err_omp_unexpected_schedule_modifier) 9492 << getOpenMPSimpleClauseTypeName(OMPC_schedule, M2) 9493 << getOpenMPSimpleClauseTypeName(OMPC_schedule, M1); 9494 return nullptr; 9495 } 9496 if (Kind == OMPC_SCHEDULE_unknown) { 9497 std::string Values; 9498 if (M1Loc.isInvalid() && M2Loc.isInvalid()) { 9499 unsigned Exclude[] = {OMPC_SCHEDULE_unknown}; 9500 Values = getListOfPossibleValues(OMPC_schedule, /*First=*/0, 9501 /*Last=*/OMPC_SCHEDULE_MODIFIER_last, 9502 Exclude); 9503 } else { 9504 Values = getListOfPossibleValues(OMPC_schedule, /*First=*/0, 9505 /*Last=*/OMPC_SCHEDULE_unknown); 9506 } 9507 Diag(KindLoc, diag::err_omp_unexpected_clause_value) 9508 << Values << getOpenMPClauseName(OMPC_schedule); 9509 return nullptr; 9510 } 9511 // OpenMP, 2.7.1, Loop Construct, Restrictions 9512 // The nonmonotonic modifier can only be specified with schedule(dynamic) or 9513 // schedule(guided). 9514 if ((M1 == OMPC_SCHEDULE_MODIFIER_nonmonotonic || 9515 M2 == OMPC_SCHEDULE_MODIFIER_nonmonotonic) && 9516 Kind != OMPC_SCHEDULE_dynamic && Kind != OMPC_SCHEDULE_guided) { 9517 Diag(M1 == OMPC_SCHEDULE_MODIFIER_nonmonotonic ? M1Loc : M2Loc, 9518 diag::err_omp_schedule_nonmonotonic_static); 9519 return nullptr; 9520 } 9521 Expr *ValExpr = ChunkSize; 9522 Stmt *HelperValStmt = nullptr; 9523 if (ChunkSize) { 9524 if (!ChunkSize->isValueDependent() && !ChunkSize->isTypeDependent() && 9525 !ChunkSize->isInstantiationDependent() && 9526 !ChunkSize->containsUnexpandedParameterPack()) { 9527 SourceLocation ChunkSizeLoc = ChunkSize->getBeginLoc(); 9528 ExprResult Val = 9529 PerformOpenMPImplicitIntegerConversion(ChunkSizeLoc, ChunkSize); 9530 if (Val.isInvalid()) 9531 return nullptr; 9532 9533 ValExpr = Val.get(); 9534 9535 // OpenMP [2.7.1, Restrictions] 9536 // chunk_size must be a loop invariant integer expression with a positive 9537 // value. 9538 llvm::APSInt Result; 9539 if (ValExpr->isIntegerConstantExpr(Result, Context)) { 9540 if (Result.isSigned() && !Result.isStrictlyPositive()) { 9541 Diag(ChunkSizeLoc, diag::err_omp_negative_expression_in_clause) 9542 << "schedule" << 1 << ChunkSize->getSourceRange(); 9543 return nullptr; 9544 } 9545 } else if (getOpenMPCaptureRegionForClause( 9546 DSAStack->getCurrentDirective(), OMPC_schedule) != 9547 OMPD_unknown && 9548 !CurContext->isDependentContext()) { 9549 ValExpr = MakeFullExpr(ValExpr).get(); 9550 llvm::MapVector<const Expr *, DeclRefExpr *> Captures; 9551 ValExpr = tryBuildCapture(*this, ValExpr, Captures).get(); 9552 HelperValStmt = buildPreInits(Context, Captures); 9553 } 9554 } 9555 } 9556 9557 return new (Context) 9558 OMPScheduleClause(StartLoc, LParenLoc, KindLoc, CommaLoc, EndLoc, Kind, 9559 ValExpr, HelperValStmt, M1, M1Loc, M2, M2Loc); 9560 } 9561 9562 OMPClause *Sema::ActOnOpenMPClause(OpenMPClauseKind Kind, 9563 SourceLocation StartLoc, 9564 SourceLocation EndLoc) { 9565 OMPClause *Res = nullptr; 9566 switch (Kind) { 9567 case OMPC_ordered: 9568 Res = ActOnOpenMPOrderedClause(StartLoc, EndLoc); 9569 break; 9570 case OMPC_nowait: 9571 Res = ActOnOpenMPNowaitClause(StartLoc, EndLoc); 9572 break; 9573 case OMPC_untied: 9574 Res = ActOnOpenMPUntiedClause(StartLoc, EndLoc); 9575 break; 9576 case OMPC_mergeable: 9577 Res = ActOnOpenMPMergeableClause(StartLoc, EndLoc); 9578 break; 9579 case OMPC_read: 9580 Res = ActOnOpenMPReadClause(StartLoc, EndLoc); 9581 break; 9582 case OMPC_write: 9583 Res = ActOnOpenMPWriteClause(StartLoc, EndLoc); 9584 break; 9585 case OMPC_update: 9586 Res = ActOnOpenMPUpdateClause(StartLoc, EndLoc); 9587 break; 9588 case OMPC_capture: 9589 Res = ActOnOpenMPCaptureClause(StartLoc, EndLoc); 9590 break; 9591 case OMPC_seq_cst: 9592 Res = ActOnOpenMPSeqCstClause(StartLoc, EndLoc); 9593 break; 9594 case OMPC_threads: 9595 Res = ActOnOpenMPThreadsClause(StartLoc, EndLoc); 9596 break; 9597 case OMPC_simd: 9598 Res = ActOnOpenMPSIMDClause(StartLoc, EndLoc); 9599 break; 9600 case OMPC_nogroup: 9601 Res = ActOnOpenMPNogroupClause(StartLoc, EndLoc); 9602 break; 9603 case OMPC_unified_address: 9604 Res = ActOnOpenMPUnifiedAddressClause(StartLoc, EndLoc); 9605 break; 9606 case OMPC_unified_shared_memory: 9607 Res = ActOnOpenMPUnifiedSharedMemoryClause(StartLoc, EndLoc); 9608 break; 9609 case OMPC_reverse_offload: 9610 Res = ActOnOpenMPReverseOffloadClause(StartLoc, EndLoc); 9611 break; 9612 case OMPC_dynamic_allocators: 9613 Res = ActOnOpenMPDynamicAllocatorsClause(StartLoc, EndLoc); 9614 break; 9615 case OMPC_if: 9616 case OMPC_final: 9617 case OMPC_num_threads: 9618 case OMPC_safelen: 9619 case OMPC_simdlen: 9620 case OMPC_collapse: 9621 case OMPC_schedule: 9622 case OMPC_private: 9623 case OMPC_firstprivate: 9624 case OMPC_lastprivate: 9625 case OMPC_shared: 9626 case OMPC_reduction: 9627 case OMPC_task_reduction: 9628 case OMPC_in_reduction: 9629 case OMPC_linear: 9630 case OMPC_aligned: 9631 case OMPC_copyin: 9632 case OMPC_copyprivate: 9633 case OMPC_default: 9634 case OMPC_proc_bind: 9635 case OMPC_threadprivate: 9636 case OMPC_flush: 9637 case OMPC_depend: 9638 case OMPC_device: 9639 case OMPC_map: 9640 case OMPC_num_teams: 9641 case OMPC_thread_limit: 9642 case OMPC_priority: 9643 case OMPC_grainsize: 9644 case OMPC_num_tasks: 9645 case OMPC_hint: 9646 case OMPC_dist_schedule: 9647 case OMPC_defaultmap: 9648 case OMPC_unknown: 9649 case OMPC_uniform: 9650 case OMPC_to: 9651 case OMPC_from: 9652 case OMPC_use_device_ptr: 9653 case OMPC_is_device_ptr: 9654 case OMPC_atomic_default_mem_order: 9655 llvm_unreachable("Clause is not allowed."); 9656 } 9657 return Res; 9658 } 9659 9660 OMPClause *Sema::ActOnOpenMPNowaitClause(SourceLocation StartLoc, 9661 SourceLocation EndLoc) { 9662 DSAStack->setNowaitRegion(); 9663 return new (Context) OMPNowaitClause(StartLoc, EndLoc); 9664 } 9665 9666 OMPClause *Sema::ActOnOpenMPUntiedClause(SourceLocation StartLoc, 9667 SourceLocation EndLoc) { 9668 return new (Context) OMPUntiedClause(StartLoc, EndLoc); 9669 } 9670 9671 OMPClause *Sema::ActOnOpenMPMergeableClause(SourceLocation StartLoc, 9672 SourceLocation EndLoc) { 9673 return new (Context) OMPMergeableClause(StartLoc, EndLoc); 9674 } 9675 9676 OMPClause *Sema::ActOnOpenMPReadClause(SourceLocation StartLoc, 9677 SourceLocation EndLoc) { 9678 return new (Context) OMPReadClause(StartLoc, EndLoc); 9679 } 9680 9681 OMPClause *Sema::ActOnOpenMPWriteClause(SourceLocation StartLoc, 9682 SourceLocation EndLoc) { 9683 return new (Context) OMPWriteClause(StartLoc, EndLoc); 9684 } 9685 9686 OMPClause *Sema::ActOnOpenMPUpdateClause(SourceLocation StartLoc, 9687 SourceLocation EndLoc) { 9688 return new (Context) OMPUpdateClause(StartLoc, EndLoc); 9689 } 9690 9691 OMPClause *Sema::ActOnOpenMPCaptureClause(SourceLocation StartLoc, 9692 SourceLocation EndLoc) { 9693 return new (Context) OMPCaptureClause(StartLoc, EndLoc); 9694 } 9695 9696 OMPClause *Sema::ActOnOpenMPSeqCstClause(SourceLocation StartLoc, 9697 SourceLocation EndLoc) { 9698 return new (Context) OMPSeqCstClause(StartLoc, EndLoc); 9699 } 9700 9701 OMPClause *Sema::ActOnOpenMPThreadsClause(SourceLocation StartLoc, 9702 SourceLocation EndLoc) { 9703 return new (Context) OMPThreadsClause(StartLoc, EndLoc); 9704 } 9705 9706 OMPClause *Sema::ActOnOpenMPSIMDClause(SourceLocation StartLoc, 9707 SourceLocation EndLoc) { 9708 return new (Context) OMPSIMDClause(StartLoc, EndLoc); 9709 } 9710 9711 OMPClause *Sema::ActOnOpenMPNogroupClause(SourceLocation StartLoc, 9712 SourceLocation EndLoc) { 9713 return new (Context) OMPNogroupClause(StartLoc, EndLoc); 9714 } 9715 9716 OMPClause *Sema::ActOnOpenMPUnifiedAddressClause(SourceLocation StartLoc, 9717 SourceLocation EndLoc) { 9718 return new (Context) OMPUnifiedAddressClause(StartLoc, EndLoc); 9719 } 9720 9721 OMPClause *Sema::ActOnOpenMPUnifiedSharedMemoryClause(SourceLocation StartLoc, 9722 SourceLocation EndLoc) { 9723 return new (Context) OMPUnifiedSharedMemoryClause(StartLoc, EndLoc); 9724 } 9725 9726 OMPClause *Sema::ActOnOpenMPReverseOffloadClause(SourceLocation StartLoc, 9727 SourceLocation EndLoc) { 9728 return new (Context) OMPReverseOffloadClause(StartLoc, EndLoc); 9729 } 9730 9731 OMPClause *Sema::ActOnOpenMPDynamicAllocatorsClause(SourceLocation StartLoc, 9732 SourceLocation EndLoc) { 9733 return new (Context) OMPDynamicAllocatorsClause(StartLoc, EndLoc); 9734 } 9735 9736 OMPClause *Sema::ActOnOpenMPVarListClause( 9737 OpenMPClauseKind Kind, ArrayRef<Expr *> VarList, Expr *TailExpr, 9738 const OMPVarListLocTy &Locs, SourceLocation ColonLoc, 9739 CXXScopeSpec &ReductionOrMapperIdScopeSpec, 9740 DeclarationNameInfo &ReductionOrMapperId, OpenMPDependClauseKind DepKind, 9741 OpenMPLinearClauseKind LinKind, 9742 ArrayRef<OpenMPMapModifierKind> MapTypeModifiers, 9743 ArrayRef<SourceLocation> MapTypeModifiersLoc, OpenMPMapClauseKind MapType, 9744 bool IsMapTypeImplicit, SourceLocation DepLinMapLoc) { 9745 SourceLocation StartLoc = Locs.StartLoc; 9746 SourceLocation LParenLoc = Locs.LParenLoc; 9747 SourceLocation EndLoc = Locs.EndLoc; 9748 OMPClause *Res = nullptr; 9749 switch (Kind) { 9750 case OMPC_private: 9751 Res = ActOnOpenMPPrivateClause(VarList, StartLoc, LParenLoc, EndLoc); 9752 break; 9753 case OMPC_firstprivate: 9754 Res = ActOnOpenMPFirstprivateClause(VarList, StartLoc, LParenLoc, EndLoc); 9755 break; 9756 case OMPC_lastprivate: 9757 Res = ActOnOpenMPLastprivateClause(VarList, StartLoc, LParenLoc, EndLoc); 9758 break; 9759 case OMPC_shared: 9760 Res = ActOnOpenMPSharedClause(VarList, StartLoc, LParenLoc, EndLoc); 9761 break; 9762 case OMPC_reduction: 9763 Res = ActOnOpenMPReductionClause(VarList, StartLoc, LParenLoc, ColonLoc, 9764 EndLoc, ReductionOrMapperIdScopeSpec, 9765 ReductionOrMapperId); 9766 break; 9767 case OMPC_task_reduction: 9768 Res = ActOnOpenMPTaskReductionClause(VarList, StartLoc, LParenLoc, ColonLoc, 9769 EndLoc, ReductionOrMapperIdScopeSpec, 9770 ReductionOrMapperId); 9771 break; 9772 case OMPC_in_reduction: 9773 Res = ActOnOpenMPInReductionClause(VarList, StartLoc, LParenLoc, ColonLoc, 9774 EndLoc, ReductionOrMapperIdScopeSpec, 9775 ReductionOrMapperId); 9776 break; 9777 case OMPC_linear: 9778 Res = ActOnOpenMPLinearClause(VarList, TailExpr, StartLoc, LParenLoc, 9779 LinKind, DepLinMapLoc, ColonLoc, EndLoc); 9780 break; 9781 case OMPC_aligned: 9782 Res = ActOnOpenMPAlignedClause(VarList, TailExpr, StartLoc, LParenLoc, 9783 ColonLoc, EndLoc); 9784 break; 9785 case OMPC_copyin: 9786 Res = ActOnOpenMPCopyinClause(VarList, StartLoc, LParenLoc, EndLoc); 9787 break; 9788 case OMPC_copyprivate: 9789 Res = ActOnOpenMPCopyprivateClause(VarList, StartLoc, LParenLoc, EndLoc); 9790 break; 9791 case OMPC_flush: 9792 Res = ActOnOpenMPFlushClause(VarList, StartLoc, LParenLoc, EndLoc); 9793 break; 9794 case OMPC_depend: 9795 Res = ActOnOpenMPDependClause(DepKind, DepLinMapLoc, ColonLoc, VarList, 9796 StartLoc, LParenLoc, EndLoc); 9797 break; 9798 case OMPC_map: 9799 Res = ActOnOpenMPMapClause(MapTypeModifiers, MapTypeModifiersLoc, 9800 ReductionOrMapperIdScopeSpec, 9801 ReductionOrMapperId, MapType, IsMapTypeImplicit, 9802 DepLinMapLoc, ColonLoc, VarList, Locs); 9803 break; 9804 case OMPC_to: 9805 Res = ActOnOpenMPToClause(VarList, ReductionOrMapperIdScopeSpec, 9806 ReductionOrMapperId, Locs); 9807 break; 9808 case OMPC_from: 9809 Res = ActOnOpenMPFromClause(VarList, ReductionOrMapperIdScopeSpec, 9810 ReductionOrMapperId, Locs); 9811 break; 9812 case OMPC_use_device_ptr: 9813 Res = ActOnOpenMPUseDevicePtrClause(VarList, Locs); 9814 break; 9815 case OMPC_is_device_ptr: 9816 Res = ActOnOpenMPIsDevicePtrClause(VarList, Locs); 9817 break; 9818 case OMPC_if: 9819 case OMPC_final: 9820 case OMPC_num_threads: 9821 case OMPC_safelen: 9822 case OMPC_simdlen: 9823 case OMPC_collapse: 9824 case OMPC_default: 9825 case OMPC_proc_bind: 9826 case OMPC_schedule: 9827 case OMPC_ordered: 9828 case OMPC_nowait: 9829 case OMPC_untied: 9830 case OMPC_mergeable: 9831 case OMPC_threadprivate: 9832 case OMPC_read: 9833 case OMPC_write: 9834 case OMPC_update: 9835 case OMPC_capture: 9836 case OMPC_seq_cst: 9837 case OMPC_device: 9838 case OMPC_threads: 9839 case OMPC_simd: 9840 case OMPC_num_teams: 9841 case OMPC_thread_limit: 9842 case OMPC_priority: 9843 case OMPC_grainsize: 9844 case OMPC_nogroup: 9845 case OMPC_num_tasks: 9846 case OMPC_hint: 9847 case OMPC_dist_schedule: 9848 case OMPC_defaultmap: 9849 case OMPC_unknown: 9850 case OMPC_uniform: 9851 case OMPC_unified_address: 9852 case OMPC_unified_shared_memory: 9853 case OMPC_reverse_offload: 9854 case OMPC_dynamic_allocators: 9855 case OMPC_atomic_default_mem_order: 9856 llvm_unreachable("Clause is not allowed."); 9857 } 9858 return Res; 9859 } 9860 9861 ExprResult Sema::getOpenMPCapturedExpr(VarDecl *Capture, ExprValueKind VK, 9862 ExprObjectKind OK, SourceLocation Loc) { 9863 ExprResult Res = BuildDeclRefExpr( 9864 Capture, Capture->getType().getNonReferenceType(), VK_LValue, Loc); 9865 if (!Res.isUsable()) 9866 return ExprError(); 9867 if (OK == OK_Ordinary && !getLangOpts().CPlusPlus) { 9868 Res = CreateBuiltinUnaryOp(Loc, UO_Deref, Res.get()); 9869 if (!Res.isUsable()) 9870 return ExprError(); 9871 } 9872 if (VK != VK_LValue && Res.get()->isGLValue()) { 9873 Res = DefaultLvalueConversion(Res.get()); 9874 if (!Res.isUsable()) 9875 return ExprError(); 9876 } 9877 return Res; 9878 } 9879 9880 static std::pair<ValueDecl *, bool> 9881 getPrivateItem(Sema &S, Expr *&RefExpr, SourceLocation &ELoc, 9882 SourceRange &ERange, bool AllowArraySection = false) { 9883 if (RefExpr->isTypeDependent() || RefExpr->isValueDependent() || 9884 RefExpr->containsUnexpandedParameterPack()) 9885 return std::make_pair(nullptr, true); 9886 9887 // OpenMP [3.1, C/C++] 9888 // A list item is a variable name. 9889 // OpenMP [2.9.3.3, Restrictions, p.1] 9890 // A variable that is part of another variable (as an array or 9891 // structure element) cannot appear in a private clause. 9892 RefExpr = RefExpr->IgnoreParens(); 9893 enum { 9894 NoArrayExpr = -1, 9895 ArraySubscript = 0, 9896 OMPArraySection = 1 9897 } IsArrayExpr = NoArrayExpr; 9898 if (AllowArraySection) { 9899 if (auto *ASE = dyn_cast_or_null<ArraySubscriptExpr>(RefExpr)) { 9900 Expr *Base = ASE->getBase()->IgnoreParenImpCasts(); 9901 while (auto *TempASE = dyn_cast<ArraySubscriptExpr>(Base)) 9902 Base = TempASE->getBase()->IgnoreParenImpCasts(); 9903 RefExpr = Base; 9904 IsArrayExpr = ArraySubscript; 9905 } else if (auto *OASE = dyn_cast_or_null<OMPArraySectionExpr>(RefExpr)) { 9906 Expr *Base = OASE->getBase()->IgnoreParenImpCasts(); 9907 while (auto *TempOASE = dyn_cast<OMPArraySectionExpr>(Base)) 9908 Base = TempOASE->getBase()->IgnoreParenImpCasts(); 9909 while (auto *TempASE = dyn_cast<ArraySubscriptExpr>(Base)) 9910 Base = TempASE->getBase()->IgnoreParenImpCasts(); 9911 RefExpr = Base; 9912 IsArrayExpr = OMPArraySection; 9913 } 9914 } 9915 ELoc = RefExpr->getExprLoc(); 9916 ERange = RefExpr->getSourceRange(); 9917 RefExpr = RefExpr->IgnoreParenImpCasts(); 9918 auto *DE = dyn_cast_or_null<DeclRefExpr>(RefExpr); 9919 auto *ME = dyn_cast_or_null<MemberExpr>(RefExpr); 9920 if ((!DE || !isa<VarDecl>(DE->getDecl())) && 9921 (S.getCurrentThisType().isNull() || !ME || 9922 !isa<CXXThisExpr>(ME->getBase()->IgnoreParenImpCasts()) || 9923 !isa<FieldDecl>(ME->getMemberDecl()))) { 9924 if (IsArrayExpr != NoArrayExpr) { 9925 S.Diag(ELoc, diag::err_omp_expected_base_var_name) << IsArrayExpr 9926 << ERange; 9927 } else { 9928 S.Diag(ELoc, 9929 AllowArraySection 9930 ? diag::err_omp_expected_var_name_member_expr_or_array_item 9931 : diag::err_omp_expected_var_name_member_expr) 9932 << (S.getCurrentThisType().isNull() ? 0 : 1) << ERange; 9933 } 9934 return std::make_pair(nullptr, false); 9935 } 9936 return std::make_pair( 9937 getCanonicalDecl(DE ? DE->getDecl() : ME->getMemberDecl()), false); 9938 } 9939 9940 OMPClause *Sema::ActOnOpenMPPrivateClause(ArrayRef<Expr *> VarList, 9941 SourceLocation StartLoc, 9942 SourceLocation LParenLoc, 9943 SourceLocation EndLoc) { 9944 SmallVector<Expr *, 8> Vars; 9945 SmallVector<Expr *, 8> PrivateCopies; 9946 for (Expr *RefExpr : VarList) { 9947 assert(RefExpr && "NULL expr in OpenMP private clause."); 9948 SourceLocation ELoc; 9949 SourceRange ERange; 9950 Expr *SimpleRefExpr = RefExpr; 9951 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange); 9952 if (Res.second) { 9953 // It will be analyzed later. 9954 Vars.push_back(RefExpr); 9955 PrivateCopies.push_back(nullptr); 9956 } 9957 ValueDecl *D = Res.first; 9958 if (!D) 9959 continue; 9960 9961 QualType Type = D->getType(); 9962 auto *VD = dyn_cast<VarDecl>(D); 9963 9964 // OpenMP [2.9.3.3, Restrictions, C/C++, p.3] 9965 // A variable that appears in a private clause must not have an incomplete 9966 // type or a reference type. 9967 if (RequireCompleteType(ELoc, Type, diag::err_omp_private_incomplete_type)) 9968 continue; 9969 Type = Type.getNonReferenceType(); 9970 9971 // OpenMP 5.0 [2.19.3, List Item Privatization, Restrictions] 9972 // A variable that is privatized must not have a const-qualified type 9973 // unless it is of class type with a mutable member. This restriction does 9974 // not apply to the firstprivate clause. 9975 // 9976 // OpenMP 3.1 [2.9.3.3, private clause, Restrictions] 9977 // A variable that appears in a private clause must not have a 9978 // const-qualified type unless it is of class type with a mutable member. 9979 if (rejectConstNotMutableType(*this, D, Type, OMPC_private, ELoc)) 9980 continue; 9981 9982 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced 9983 // in a Construct] 9984 // Variables with the predetermined data-sharing attributes may not be 9985 // listed in data-sharing attributes clauses, except for the cases 9986 // listed below. For these exceptions only, listing a predetermined 9987 // variable in a data-sharing attribute clause is allowed and overrides 9988 // the variable's predetermined data-sharing attributes. 9989 DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, /*FromParent=*/false); 9990 if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_private) { 9991 Diag(ELoc, diag::err_omp_wrong_dsa) << getOpenMPClauseName(DVar.CKind) 9992 << getOpenMPClauseName(OMPC_private); 9993 reportOriginalDsa(*this, DSAStack, D, DVar); 9994 continue; 9995 } 9996 9997 OpenMPDirectiveKind CurrDir = DSAStack->getCurrentDirective(); 9998 // Variably modified types are not supported for tasks. 9999 if (!Type->isAnyPointerType() && Type->isVariablyModifiedType() && 10000 isOpenMPTaskingDirective(CurrDir)) { 10001 Diag(ELoc, diag::err_omp_variably_modified_type_not_supported) 10002 << getOpenMPClauseName(OMPC_private) << Type 10003 << getOpenMPDirectiveName(CurrDir); 10004 bool IsDecl = 10005 !VD || 10006 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly; 10007 Diag(D->getLocation(), 10008 IsDecl ? diag::note_previous_decl : diag::note_defined_here) 10009 << D; 10010 continue; 10011 } 10012 10013 // OpenMP 4.5 [2.15.5.1, Restrictions, p.3] 10014 // A list item cannot appear in both a map clause and a data-sharing 10015 // attribute clause on the same construct 10016 if (isOpenMPTargetExecutionDirective(CurrDir)) { 10017 OpenMPClauseKind ConflictKind; 10018 if (DSAStack->checkMappableExprComponentListsForDecl( 10019 VD, /*CurrentRegionOnly=*/true, 10020 [&](OMPClauseMappableExprCommon::MappableExprComponentListRef, 10021 OpenMPClauseKind WhereFoundClauseKind) -> bool { 10022 ConflictKind = WhereFoundClauseKind; 10023 return true; 10024 })) { 10025 Diag(ELoc, diag::err_omp_variable_in_given_clause_and_dsa) 10026 << getOpenMPClauseName(OMPC_private) 10027 << getOpenMPClauseName(ConflictKind) 10028 << getOpenMPDirectiveName(CurrDir); 10029 reportOriginalDsa(*this, DSAStack, D, DVar); 10030 continue; 10031 } 10032 } 10033 10034 // OpenMP [2.9.3.3, Restrictions, C/C++, p.1] 10035 // A variable of class type (or array thereof) that appears in a private 10036 // clause requires an accessible, unambiguous default constructor for the 10037 // class type. 10038 // Generate helper private variable and initialize it with the default 10039 // value. The address of the original variable is replaced by the address of 10040 // the new private variable in CodeGen. This new variable is not added to 10041 // IdResolver, so the code in the OpenMP region uses original variable for 10042 // proper diagnostics. 10043 Type = Type.getUnqualifiedType(); 10044 VarDecl *VDPrivate = 10045 buildVarDecl(*this, ELoc, Type, D->getName(), 10046 D->hasAttrs() ? &D->getAttrs() : nullptr, 10047 VD ? cast<DeclRefExpr>(SimpleRefExpr) : nullptr); 10048 ActOnUninitializedDecl(VDPrivate); 10049 if (VDPrivate->isInvalidDecl()) 10050 continue; 10051 DeclRefExpr *VDPrivateRefExpr = buildDeclRefExpr( 10052 *this, VDPrivate, RefExpr->getType().getUnqualifiedType(), ELoc); 10053 10054 DeclRefExpr *Ref = nullptr; 10055 if (!VD && !CurContext->isDependentContext()) 10056 Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/false); 10057 DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_private, Ref); 10058 Vars.push_back((VD || CurContext->isDependentContext()) 10059 ? RefExpr->IgnoreParens() 10060 : Ref); 10061 PrivateCopies.push_back(VDPrivateRefExpr); 10062 } 10063 10064 if (Vars.empty()) 10065 return nullptr; 10066 10067 return OMPPrivateClause::Create(Context, StartLoc, LParenLoc, EndLoc, Vars, 10068 PrivateCopies); 10069 } 10070 10071 namespace { 10072 class DiagsUninitializedSeveretyRAII { 10073 private: 10074 DiagnosticsEngine &Diags; 10075 SourceLocation SavedLoc; 10076 bool IsIgnored = false; 10077 10078 public: 10079 DiagsUninitializedSeveretyRAII(DiagnosticsEngine &Diags, SourceLocation Loc, 10080 bool IsIgnored) 10081 : Diags(Diags), SavedLoc(Loc), IsIgnored(IsIgnored) { 10082 if (!IsIgnored) { 10083 Diags.setSeverity(/*Diag*/ diag::warn_uninit_self_reference_in_init, 10084 /*Map*/ diag::Severity::Ignored, Loc); 10085 } 10086 } 10087 ~DiagsUninitializedSeveretyRAII() { 10088 if (!IsIgnored) 10089 Diags.popMappings(SavedLoc); 10090 } 10091 }; 10092 } 10093 10094 OMPClause *Sema::ActOnOpenMPFirstprivateClause(ArrayRef<Expr *> VarList, 10095 SourceLocation StartLoc, 10096 SourceLocation LParenLoc, 10097 SourceLocation EndLoc) { 10098 SmallVector<Expr *, 8> Vars; 10099 SmallVector<Expr *, 8> PrivateCopies; 10100 SmallVector<Expr *, 8> Inits; 10101 SmallVector<Decl *, 4> ExprCaptures; 10102 bool IsImplicitClause = 10103 StartLoc.isInvalid() && LParenLoc.isInvalid() && EndLoc.isInvalid(); 10104 SourceLocation ImplicitClauseLoc = DSAStack->getConstructLoc(); 10105 10106 for (Expr *RefExpr : VarList) { 10107 assert(RefExpr && "NULL expr in OpenMP firstprivate clause."); 10108 SourceLocation ELoc; 10109 SourceRange ERange; 10110 Expr *SimpleRefExpr = RefExpr; 10111 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange); 10112 if (Res.second) { 10113 // It will be analyzed later. 10114 Vars.push_back(RefExpr); 10115 PrivateCopies.push_back(nullptr); 10116 Inits.push_back(nullptr); 10117 } 10118 ValueDecl *D = Res.first; 10119 if (!D) 10120 continue; 10121 10122 ELoc = IsImplicitClause ? ImplicitClauseLoc : ELoc; 10123 QualType Type = D->getType(); 10124 auto *VD = dyn_cast<VarDecl>(D); 10125 10126 // OpenMP [2.9.3.3, Restrictions, C/C++, p.3] 10127 // A variable that appears in a private clause must not have an incomplete 10128 // type or a reference type. 10129 if (RequireCompleteType(ELoc, Type, 10130 diag::err_omp_firstprivate_incomplete_type)) 10131 continue; 10132 Type = Type.getNonReferenceType(); 10133 10134 // OpenMP [2.9.3.4, Restrictions, C/C++, p.1] 10135 // A variable of class type (or array thereof) that appears in a private 10136 // clause requires an accessible, unambiguous copy constructor for the 10137 // class type. 10138 QualType ElemType = Context.getBaseElementType(Type).getNonReferenceType(); 10139 10140 // If an implicit firstprivate variable found it was checked already. 10141 DSAStackTy::DSAVarData TopDVar; 10142 if (!IsImplicitClause) { 10143 DSAStackTy::DSAVarData DVar = 10144 DSAStack->getTopDSA(D, /*FromParent=*/false); 10145 TopDVar = DVar; 10146 OpenMPDirectiveKind CurrDir = DSAStack->getCurrentDirective(); 10147 bool IsConstant = ElemType.isConstant(Context); 10148 // OpenMP [2.4.13, Data-sharing Attribute Clauses] 10149 // A list item that specifies a given variable may not appear in more 10150 // than one clause on the same directive, except that a variable may be 10151 // specified in both firstprivate and lastprivate clauses. 10152 // OpenMP 4.5 [2.10.8, Distribute Construct, p.3] 10153 // A list item may appear in a firstprivate or lastprivate clause but not 10154 // both. 10155 if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_firstprivate && 10156 (isOpenMPDistributeDirective(CurrDir) || 10157 DVar.CKind != OMPC_lastprivate) && 10158 DVar.RefExpr) { 10159 Diag(ELoc, diag::err_omp_wrong_dsa) 10160 << getOpenMPClauseName(DVar.CKind) 10161 << getOpenMPClauseName(OMPC_firstprivate); 10162 reportOriginalDsa(*this, DSAStack, D, DVar); 10163 continue; 10164 } 10165 10166 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced 10167 // in a Construct] 10168 // Variables with the predetermined data-sharing attributes may not be 10169 // listed in data-sharing attributes clauses, except for the cases 10170 // listed below. For these exceptions only, listing a predetermined 10171 // variable in a data-sharing attribute clause is allowed and overrides 10172 // the variable's predetermined data-sharing attributes. 10173 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced 10174 // in a Construct, C/C++, p.2] 10175 // Variables with const-qualified type having no mutable member may be 10176 // listed in a firstprivate clause, even if they are static data members. 10177 if (!(IsConstant || (VD && VD->isStaticDataMember())) && !DVar.RefExpr && 10178 DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_shared) { 10179 Diag(ELoc, diag::err_omp_wrong_dsa) 10180 << getOpenMPClauseName(DVar.CKind) 10181 << getOpenMPClauseName(OMPC_firstprivate); 10182 reportOriginalDsa(*this, DSAStack, D, DVar); 10183 continue; 10184 } 10185 10186 // OpenMP [2.9.3.4, Restrictions, p.2] 10187 // A list item that is private within a parallel region must not appear 10188 // in a firstprivate clause on a worksharing construct if any of the 10189 // worksharing regions arising from the worksharing construct ever bind 10190 // to any of the parallel regions arising from the parallel construct. 10191 // OpenMP 4.5 [2.15.3.4, Restrictions, p.3] 10192 // A list item that is private within a teams region must not appear in a 10193 // firstprivate clause on a distribute construct if any of the distribute 10194 // regions arising from the distribute construct ever bind to any of the 10195 // teams regions arising from the teams construct. 10196 // OpenMP 4.5 [2.15.3.4, Restrictions, p.3] 10197 // A list item that appears in a reduction clause of a teams construct 10198 // must not appear in a firstprivate clause on a distribute construct if 10199 // any of the distribute regions arising from the distribute construct 10200 // ever bind to any of the teams regions arising from the teams construct. 10201 if ((isOpenMPWorksharingDirective(CurrDir) || 10202 isOpenMPDistributeDirective(CurrDir)) && 10203 !isOpenMPParallelDirective(CurrDir) && 10204 !isOpenMPTeamsDirective(CurrDir)) { 10205 DVar = DSAStack->getImplicitDSA(D, true); 10206 if (DVar.CKind != OMPC_shared && 10207 (isOpenMPParallelDirective(DVar.DKind) || 10208 isOpenMPTeamsDirective(DVar.DKind) || 10209 DVar.DKind == OMPD_unknown)) { 10210 Diag(ELoc, diag::err_omp_required_access) 10211 << getOpenMPClauseName(OMPC_firstprivate) 10212 << getOpenMPClauseName(OMPC_shared); 10213 reportOriginalDsa(*this, DSAStack, D, DVar); 10214 continue; 10215 } 10216 } 10217 // OpenMP [2.9.3.4, Restrictions, p.3] 10218 // A list item that appears in a reduction clause of a parallel construct 10219 // must not appear in a firstprivate clause on a worksharing or task 10220 // construct if any of the worksharing or task regions arising from the 10221 // worksharing or task construct ever bind to any of the parallel regions 10222 // arising from the parallel construct. 10223 // OpenMP [2.9.3.4, Restrictions, p.4] 10224 // A list item that appears in a reduction clause in worksharing 10225 // construct must not appear in a firstprivate clause in a task construct 10226 // encountered during execution of any of the worksharing regions arising 10227 // from the worksharing construct. 10228 if (isOpenMPTaskingDirective(CurrDir)) { 10229 DVar = DSAStack->hasInnermostDSA( 10230 D, [](OpenMPClauseKind C) { return C == OMPC_reduction; }, 10231 [](OpenMPDirectiveKind K) { 10232 return isOpenMPParallelDirective(K) || 10233 isOpenMPWorksharingDirective(K) || 10234 isOpenMPTeamsDirective(K); 10235 }, 10236 /*FromParent=*/true); 10237 if (DVar.CKind == OMPC_reduction && 10238 (isOpenMPParallelDirective(DVar.DKind) || 10239 isOpenMPWorksharingDirective(DVar.DKind) || 10240 isOpenMPTeamsDirective(DVar.DKind))) { 10241 Diag(ELoc, diag::err_omp_parallel_reduction_in_task_firstprivate) 10242 << getOpenMPDirectiveName(DVar.DKind); 10243 reportOriginalDsa(*this, DSAStack, D, DVar); 10244 continue; 10245 } 10246 } 10247 10248 // OpenMP 4.5 [2.15.5.1, Restrictions, p.3] 10249 // A list item cannot appear in both a map clause and a data-sharing 10250 // attribute clause on the same construct 10251 if (isOpenMPTargetExecutionDirective(CurrDir)) { 10252 OpenMPClauseKind ConflictKind; 10253 if (DSAStack->checkMappableExprComponentListsForDecl( 10254 VD, /*CurrentRegionOnly=*/true, 10255 [&ConflictKind]( 10256 OMPClauseMappableExprCommon::MappableExprComponentListRef, 10257 OpenMPClauseKind WhereFoundClauseKind) { 10258 ConflictKind = WhereFoundClauseKind; 10259 return true; 10260 })) { 10261 Diag(ELoc, diag::err_omp_variable_in_given_clause_and_dsa) 10262 << getOpenMPClauseName(OMPC_firstprivate) 10263 << getOpenMPClauseName(ConflictKind) 10264 << getOpenMPDirectiveName(DSAStack->getCurrentDirective()); 10265 reportOriginalDsa(*this, DSAStack, D, DVar); 10266 continue; 10267 } 10268 } 10269 } 10270 10271 // Variably modified types are not supported for tasks. 10272 if (!Type->isAnyPointerType() && Type->isVariablyModifiedType() && 10273 isOpenMPTaskingDirective(DSAStack->getCurrentDirective())) { 10274 Diag(ELoc, diag::err_omp_variably_modified_type_not_supported) 10275 << getOpenMPClauseName(OMPC_firstprivate) << Type 10276 << getOpenMPDirectiveName(DSAStack->getCurrentDirective()); 10277 bool IsDecl = 10278 !VD || 10279 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly; 10280 Diag(D->getLocation(), 10281 IsDecl ? diag::note_previous_decl : diag::note_defined_here) 10282 << D; 10283 continue; 10284 } 10285 10286 Type = Type.getUnqualifiedType(); 10287 VarDecl *VDPrivate = 10288 buildVarDecl(*this, ELoc, Type, D->getName(), 10289 D->hasAttrs() ? &D->getAttrs() : nullptr, 10290 VD ? cast<DeclRefExpr>(SimpleRefExpr) : nullptr); 10291 // Generate helper private variable and initialize it with the value of the 10292 // original variable. The address of the original variable is replaced by 10293 // the address of the new private variable in the CodeGen. This new variable 10294 // is not added to IdResolver, so the code in the OpenMP region uses 10295 // original variable for proper diagnostics and variable capturing. 10296 Expr *VDInitRefExpr = nullptr; 10297 // For arrays generate initializer for single element and replace it by the 10298 // original array element in CodeGen. 10299 if (Type->isArrayType()) { 10300 VarDecl *VDInit = 10301 buildVarDecl(*this, RefExpr->getExprLoc(), ElemType, D->getName()); 10302 VDInitRefExpr = buildDeclRefExpr(*this, VDInit, ElemType, ELoc); 10303 Expr *Init = DefaultLvalueConversion(VDInitRefExpr).get(); 10304 ElemType = ElemType.getUnqualifiedType(); 10305 VarDecl *VDInitTemp = buildVarDecl(*this, RefExpr->getExprLoc(), ElemType, 10306 ".firstprivate.temp"); 10307 InitializedEntity Entity = 10308 InitializedEntity::InitializeVariable(VDInitTemp); 10309 InitializationKind Kind = InitializationKind::CreateCopy(ELoc, ELoc); 10310 10311 InitializationSequence InitSeq(*this, Entity, Kind, Init); 10312 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Init); 10313 if (Result.isInvalid()) 10314 VDPrivate->setInvalidDecl(); 10315 else 10316 VDPrivate->setInit(Result.getAs<Expr>()); 10317 // Remove temp variable declaration. 10318 Context.Deallocate(VDInitTemp); 10319 } else { 10320 VarDecl *VDInit = buildVarDecl(*this, RefExpr->getExprLoc(), Type, 10321 ".firstprivate.temp"); 10322 VDInitRefExpr = buildDeclRefExpr(*this, VDInit, RefExpr->getType(), 10323 RefExpr->getExprLoc()); 10324 AddInitializerToDecl(VDPrivate, 10325 DefaultLvalueConversion(VDInitRefExpr).get(), 10326 /*DirectInit=*/false); 10327 } 10328 if (VDPrivate->isInvalidDecl()) { 10329 if (IsImplicitClause) { 10330 Diag(RefExpr->getExprLoc(), 10331 diag::note_omp_task_predetermined_firstprivate_here); 10332 } 10333 continue; 10334 } 10335 CurContext->addDecl(VDPrivate); 10336 DeclRefExpr *VDPrivateRefExpr = buildDeclRefExpr( 10337 *this, VDPrivate, RefExpr->getType().getUnqualifiedType(), 10338 RefExpr->getExprLoc()); 10339 DeclRefExpr *Ref = nullptr; 10340 if (!VD && !CurContext->isDependentContext()) { 10341 if (TopDVar.CKind == OMPC_lastprivate) { 10342 Ref = TopDVar.PrivateCopy; 10343 } else { 10344 Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/true); 10345 if (!isOpenMPCapturedDecl(D)) 10346 ExprCaptures.push_back(Ref->getDecl()); 10347 } 10348 } 10349 DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_firstprivate, Ref); 10350 Vars.push_back((VD || CurContext->isDependentContext()) 10351 ? RefExpr->IgnoreParens() 10352 : Ref); 10353 PrivateCopies.push_back(VDPrivateRefExpr); 10354 Inits.push_back(VDInitRefExpr); 10355 } 10356 10357 if (Vars.empty()) 10358 return nullptr; 10359 10360 return OMPFirstprivateClause::Create(Context, StartLoc, LParenLoc, EndLoc, 10361 Vars, PrivateCopies, Inits, 10362 buildPreInits(Context, ExprCaptures)); 10363 } 10364 10365 OMPClause *Sema::ActOnOpenMPLastprivateClause(ArrayRef<Expr *> VarList, 10366 SourceLocation StartLoc, 10367 SourceLocation LParenLoc, 10368 SourceLocation EndLoc) { 10369 SmallVector<Expr *, 8> Vars; 10370 SmallVector<Expr *, 8> SrcExprs; 10371 SmallVector<Expr *, 8> DstExprs; 10372 SmallVector<Expr *, 8> AssignmentOps; 10373 SmallVector<Decl *, 4> ExprCaptures; 10374 SmallVector<Expr *, 4> ExprPostUpdates; 10375 for (Expr *RefExpr : VarList) { 10376 assert(RefExpr && "NULL expr in OpenMP lastprivate clause."); 10377 SourceLocation ELoc; 10378 SourceRange ERange; 10379 Expr *SimpleRefExpr = RefExpr; 10380 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange); 10381 if (Res.second) { 10382 // It will be analyzed later. 10383 Vars.push_back(RefExpr); 10384 SrcExprs.push_back(nullptr); 10385 DstExprs.push_back(nullptr); 10386 AssignmentOps.push_back(nullptr); 10387 } 10388 ValueDecl *D = Res.first; 10389 if (!D) 10390 continue; 10391 10392 QualType Type = D->getType(); 10393 auto *VD = dyn_cast<VarDecl>(D); 10394 10395 // OpenMP [2.14.3.5, Restrictions, C/C++, p.2] 10396 // A variable that appears in a lastprivate clause must not have an 10397 // incomplete type or a reference type. 10398 if (RequireCompleteType(ELoc, Type, 10399 diag::err_omp_lastprivate_incomplete_type)) 10400 continue; 10401 Type = Type.getNonReferenceType(); 10402 10403 // OpenMP 5.0 [2.19.3, List Item Privatization, Restrictions] 10404 // A variable that is privatized must not have a const-qualified type 10405 // unless it is of class type with a mutable member. This restriction does 10406 // not apply to the firstprivate clause. 10407 // 10408 // OpenMP 3.1 [2.9.3.5, lastprivate clause, Restrictions] 10409 // A variable that appears in a lastprivate clause must not have a 10410 // const-qualified type unless it is of class type with a mutable member. 10411 if (rejectConstNotMutableType(*this, D, Type, OMPC_lastprivate, ELoc)) 10412 continue; 10413 10414 OpenMPDirectiveKind CurrDir = DSAStack->getCurrentDirective(); 10415 // OpenMP [2.14.1.1, Data-sharing Attribute Rules for Variables Referenced 10416 // in a Construct] 10417 // Variables with the predetermined data-sharing attributes may not be 10418 // listed in data-sharing attributes clauses, except for the cases 10419 // listed below. 10420 // OpenMP 4.5 [2.10.8, Distribute Construct, p.3] 10421 // A list item may appear in a firstprivate or lastprivate clause but not 10422 // both. 10423 DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, /*FromParent=*/false); 10424 if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_lastprivate && 10425 (isOpenMPDistributeDirective(CurrDir) || 10426 DVar.CKind != OMPC_firstprivate) && 10427 (DVar.CKind != OMPC_private || DVar.RefExpr != nullptr)) { 10428 Diag(ELoc, diag::err_omp_wrong_dsa) 10429 << getOpenMPClauseName(DVar.CKind) 10430 << getOpenMPClauseName(OMPC_lastprivate); 10431 reportOriginalDsa(*this, DSAStack, D, DVar); 10432 continue; 10433 } 10434 10435 // OpenMP [2.14.3.5, Restrictions, p.2] 10436 // A list item that is private within a parallel region, or that appears in 10437 // the reduction clause of a parallel construct, must not appear in a 10438 // lastprivate clause on a worksharing construct if any of the corresponding 10439 // worksharing regions ever binds to any of the corresponding parallel 10440 // regions. 10441 DSAStackTy::DSAVarData TopDVar = DVar; 10442 if (isOpenMPWorksharingDirective(CurrDir) && 10443 !isOpenMPParallelDirective(CurrDir) && 10444 !isOpenMPTeamsDirective(CurrDir)) { 10445 DVar = DSAStack->getImplicitDSA(D, true); 10446 if (DVar.CKind != OMPC_shared) { 10447 Diag(ELoc, diag::err_omp_required_access) 10448 << getOpenMPClauseName(OMPC_lastprivate) 10449 << getOpenMPClauseName(OMPC_shared); 10450 reportOriginalDsa(*this, DSAStack, D, DVar); 10451 continue; 10452 } 10453 } 10454 10455 // OpenMP [2.14.3.5, Restrictions, C++, p.1,2] 10456 // A variable of class type (or array thereof) that appears in a 10457 // lastprivate clause requires an accessible, unambiguous default 10458 // constructor for the class type, unless the list item is also specified 10459 // in a firstprivate clause. 10460 // A variable of class type (or array thereof) that appears in a 10461 // lastprivate clause requires an accessible, unambiguous copy assignment 10462 // operator for the class type. 10463 Type = Context.getBaseElementType(Type).getNonReferenceType(); 10464 VarDecl *SrcVD = buildVarDecl(*this, ERange.getBegin(), 10465 Type.getUnqualifiedType(), ".lastprivate.src", 10466 D->hasAttrs() ? &D->getAttrs() : nullptr); 10467 DeclRefExpr *PseudoSrcExpr = 10468 buildDeclRefExpr(*this, SrcVD, Type.getUnqualifiedType(), ELoc); 10469 VarDecl *DstVD = 10470 buildVarDecl(*this, ERange.getBegin(), Type, ".lastprivate.dst", 10471 D->hasAttrs() ? &D->getAttrs() : nullptr); 10472 DeclRefExpr *PseudoDstExpr = buildDeclRefExpr(*this, DstVD, Type, ELoc); 10473 // For arrays generate assignment operation for single element and replace 10474 // it by the original array element in CodeGen. 10475 ExprResult AssignmentOp = BuildBinOp(/*S=*/nullptr, ELoc, BO_Assign, 10476 PseudoDstExpr, PseudoSrcExpr); 10477 if (AssignmentOp.isInvalid()) 10478 continue; 10479 AssignmentOp = 10480 ActOnFinishFullExpr(AssignmentOp.get(), ELoc, /*DiscardedValue*/ false); 10481 if (AssignmentOp.isInvalid()) 10482 continue; 10483 10484 DeclRefExpr *Ref = nullptr; 10485 if (!VD && !CurContext->isDependentContext()) { 10486 if (TopDVar.CKind == OMPC_firstprivate) { 10487 Ref = TopDVar.PrivateCopy; 10488 } else { 10489 Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/false); 10490 if (!isOpenMPCapturedDecl(D)) 10491 ExprCaptures.push_back(Ref->getDecl()); 10492 } 10493 if (TopDVar.CKind == OMPC_firstprivate || 10494 (!isOpenMPCapturedDecl(D) && 10495 Ref->getDecl()->hasAttr<OMPCaptureNoInitAttr>())) { 10496 ExprResult RefRes = DefaultLvalueConversion(Ref); 10497 if (!RefRes.isUsable()) 10498 continue; 10499 ExprResult PostUpdateRes = 10500 BuildBinOp(DSAStack->getCurScope(), ELoc, BO_Assign, SimpleRefExpr, 10501 RefRes.get()); 10502 if (!PostUpdateRes.isUsable()) 10503 continue; 10504 ExprPostUpdates.push_back( 10505 IgnoredValueConversions(PostUpdateRes.get()).get()); 10506 } 10507 } 10508 DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_lastprivate, Ref); 10509 Vars.push_back((VD || CurContext->isDependentContext()) 10510 ? RefExpr->IgnoreParens() 10511 : Ref); 10512 SrcExprs.push_back(PseudoSrcExpr); 10513 DstExprs.push_back(PseudoDstExpr); 10514 AssignmentOps.push_back(AssignmentOp.get()); 10515 } 10516 10517 if (Vars.empty()) 10518 return nullptr; 10519 10520 return OMPLastprivateClause::Create(Context, StartLoc, LParenLoc, EndLoc, 10521 Vars, SrcExprs, DstExprs, AssignmentOps, 10522 buildPreInits(Context, ExprCaptures), 10523 buildPostUpdate(*this, ExprPostUpdates)); 10524 } 10525 10526 OMPClause *Sema::ActOnOpenMPSharedClause(ArrayRef<Expr *> VarList, 10527 SourceLocation StartLoc, 10528 SourceLocation LParenLoc, 10529 SourceLocation EndLoc) { 10530 SmallVector<Expr *, 8> Vars; 10531 for (Expr *RefExpr : VarList) { 10532 assert(RefExpr && "NULL expr in OpenMP lastprivate clause."); 10533 SourceLocation ELoc; 10534 SourceRange ERange; 10535 Expr *SimpleRefExpr = RefExpr; 10536 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange); 10537 if (Res.second) { 10538 // It will be analyzed later. 10539 Vars.push_back(RefExpr); 10540 } 10541 ValueDecl *D = Res.first; 10542 if (!D) 10543 continue; 10544 10545 auto *VD = dyn_cast<VarDecl>(D); 10546 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced 10547 // in a Construct] 10548 // Variables with the predetermined data-sharing attributes may not be 10549 // listed in data-sharing attributes clauses, except for the cases 10550 // listed below. For these exceptions only, listing a predetermined 10551 // variable in a data-sharing attribute clause is allowed and overrides 10552 // the variable's predetermined data-sharing attributes. 10553 DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, /*FromParent=*/false); 10554 if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_shared && 10555 DVar.RefExpr) { 10556 Diag(ELoc, diag::err_omp_wrong_dsa) << getOpenMPClauseName(DVar.CKind) 10557 << getOpenMPClauseName(OMPC_shared); 10558 reportOriginalDsa(*this, DSAStack, D, DVar); 10559 continue; 10560 } 10561 10562 DeclRefExpr *Ref = nullptr; 10563 if (!VD && isOpenMPCapturedDecl(D) && !CurContext->isDependentContext()) 10564 Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/true); 10565 DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_shared, Ref); 10566 Vars.push_back((VD || !Ref || CurContext->isDependentContext()) 10567 ? RefExpr->IgnoreParens() 10568 : Ref); 10569 } 10570 10571 if (Vars.empty()) 10572 return nullptr; 10573 10574 return OMPSharedClause::Create(Context, StartLoc, LParenLoc, EndLoc, Vars); 10575 } 10576 10577 namespace { 10578 class DSARefChecker : public StmtVisitor<DSARefChecker, bool> { 10579 DSAStackTy *Stack; 10580 10581 public: 10582 bool VisitDeclRefExpr(DeclRefExpr *E) { 10583 if (auto *VD = dyn_cast<VarDecl>(E->getDecl())) { 10584 DSAStackTy::DSAVarData DVar = Stack->getTopDSA(VD, /*FromParent=*/false); 10585 if (DVar.CKind == OMPC_shared && !DVar.RefExpr) 10586 return false; 10587 if (DVar.CKind != OMPC_unknown) 10588 return true; 10589 DSAStackTy::DSAVarData DVarPrivate = Stack->hasDSA( 10590 VD, isOpenMPPrivate, [](OpenMPDirectiveKind) { return true; }, 10591 /*FromParent=*/true); 10592 return DVarPrivate.CKind != OMPC_unknown; 10593 } 10594 return false; 10595 } 10596 bool VisitStmt(Stmt *S) { 10597 for (Stmt *Child : S->children()) { 10598 if (Child && Visit(Child)) 10599 return true; 10600 } 10601 return false; 10602 } 10603 explicit DSARefChecker(DSAStackTy *S) : Stack(S) {} 10604 }; 10605 } // namespace 10606 10607 namespace { 10608 // Transform MemberExpression for specified FieldDecl of current class to 10609 // DeclRefExpr to specified OMPCapturedExprDecl. 10610 class TransformExprToCaptures : public TreeTransform<TransformExprToCaptures> { 10611 typedef TreeTransform<TransformExprToCaptures> BaseTransform; 10612 ValueDecl *Field = nullptr; 10613 DeclRefExpr *CapturedExpr = nullptr; 10614 10615 public: 10616 TransformExprToCaptures(Sema &SemaRef, ValueDecl *FieldDecl) 10617 : BaseTransform(SemaRef), Field(FieldDecl), CapturedExpr(nullptr) {} 10618 10619 ExprResult TransformMemberExpr(MemberExpr *E) { 10620 if (isa<CXXThisExpr>(E->getBase()->IgnoreParenImpCasts()) && 10621 E->getMemberDecl() == Field) { 10622 CapturedExpr = buildCapture(SemaRef, Field, E, /*WithInit=*/false); 10623 return CapturedExpr; 10624 } 10625 return BaseTransform::TransformMemberExpr(E); 10626 } 10627 DeclRefExpr *getCapturedExpr() { return CapturedExpr; } 10628 }; 10629 } // namespace 10630 10631 template <typename T, typename U> 10632 static T filterLookupForUDReductionAndMapper( 10633 SmallVectorImpl<U> &Lookups, const llvm::function_ref<T(ValueDecl *)> Gen) { 10634 for (U &Set : Lookups) { 10635 for (auto *D : Set) { 10636 if (T Res = Gen(cast<ValueDecl>(D))) 10637 return Res; 10638 } 10639 } 10640 return T(); 10641 } 10642 10643 static NamedDecl *findAcceptableDecl(Sema &SemaRef, NamedDecl *D) { 10644 assert(!LookupResult::isVisible(SemaRef, D) && "not in slow case"); 10645 10646 for (auto RD : D->redecls()) { 10647 // Don't bother with extra checks if we already know this one isn't visible. 10648 if (RD == D) 10649 continue; 10650 10651 auto ND = cast<NamedDecl>(RD); 10652 if (LookupResult::isVisible(SemaRef, ND)) 10653 return ND; 10654 } 10655 10656 return nullptr; 10657 } 10658 10659 static void 10660 argumentDependentLookup(Sema &SemaRef, const DeclarationNameInfo &Id, 10661 SourceLocation Loc, QualType Ty, 10662 SmallVectorImpl<UnresolvedSet<8>> &Lookups) { 10663 // Find all of the associated namespaces and classes based on the 10664 // arguments we have. 10665 Sema::AssociatedNamespaceSet AssociatedNamespaces; 10666 Sema::AssociatedClassSet AssociatedClasses; 10667 OpaqueValueExpr OVE(Loc, Ty, VK_LValue); 10668 SemaRef.FindAssociatedClassesAndNamespaces(Loc, &OVE, AssociatedNamespaces, 10669 AssociatedClasses); 10670 10671 // C++ [basic.lookup.argdep]p3: 10672 // Let X be the lookup set produced by unqualified lookup (3.4.1) 10673 // and let Y be the lookup set produced by argument dependent 10674 // lookup (defined as follows). If X contains [...] then Y is 10675 // empty. Otherwise Y is the set of declarations found in the 10676 // namespaces associated with the argument types as described 10677 // below. The set of declarations found by the lookup of the name 10678 // is the union of X and Y. 10679 // 10680 // Here, we compute Y and add its members to the overloaded 10681 // candidate set. 10682 for (auto *NS : AssociatedNamespaces) { 10683 // When considering an associated namespace, the lookup is the 10684 // same as the lookup performed when the associated namespace is 10685 // used as a qualifier (3.4.3.2) except that: 10686 // 10687 // -- Any using-directives in the associated namespace are 10688 // ignored. 10689 // 10690 // -- Any namespace-scope friend functions declared in 10691 // associated classes are visible within their respective 10692 // namespaces even if they are not visible during an ordinary 10693 // lookup (11.4). 10694 DeclContext::lookup_result R = NS->lookup(Id.getName()); 10695 for (auto *D : R) { 10696 auto *Underlying = D; 10697 if (auto *USD = dyn_cast<UsingShadowDecl>(D)) 10698 Underlying = USD->getTargetDecl(); 10699 10700 if (!isa<OMPDeclareReductionDecl>(Underlying) && 10701 !isa<OMPDeclareMapperDecl>(Underlying)) 10702 continue; 10703 10704 if (!SemaRef.isVisible(D)) { 10705 D = findAcceptableDecl(SemaRef, D); 10706 if (!D) 10707 continue; 10708 if (auto *USD = dyn_cast<UsingShadowDecl>(D)) 10709 Underlying = USD->getTargetDecl(); 10710 } 10711 Lookups.emplace_back(); 10712 Lookups.back().addDecl(Underlying); 10713 } 10714 } 10715 } 10716 10717 static ExprResult 10718 buildDeclareReductionRef(Sema &SemaRef, SourceLocation Loc, SourceRange Range, 10719 Scope *S, CXXScopeSpec &ReductionIdScopeSpec, 10720 const DeclarationNameInfo &ReductionId, QualType Ty, 10721 CXXCastPath &BasePath, Expr *UnresolvedReduction) { 10722 if (ReductionIdScopeSpec.isInvalid()) 10723 return ExprError(); 10724 SmallVector<UnresolvedSet<8>, 4> Lookups; 10725 if (S) { 10726 LookupResult Lookup(SemaRef, ReductionId, Sema::LookupOMPReductionName); 10727 Lookup.suppressDiagnostics(); 10728 while (S && SemaRef.LookupParsedName(Lookup, S, &ReductionIdScopeSpec)) { 10729 NamedDecl *D = Lookup.getRepresentativeDecl(); 10730 do { 10731 S = S->getParent(); 10732 } while (S && !S->isDeclScope(D)); 10733 if (S) 10734 S = S->getParent(); 10735 Lookups.emplace_back(); 10736 Lookups.back().append(Lookup.begin(), Lookup.end()); 10737 Lookup.clear(); 10738 } 10739 } else if (auto *ULE = 10740 cast_or_null<UnresolvedLookupExpr>(UnresolvedReduction)) { 10741 Lookups.push_back(UnresolvedSet<8>()); 10742 Decl *PrevD = nullptr; 10743 for (NamedDecl *D : ULE->decls()) { 10744 if (D == PrevD) 10745 Lookups.push_back(UnresolvedSet<8>()); 10746 else if (auto *DRD = cast<OMPDeclareReductionDecl>(D)) 10747 Lookups.back().addDecl(DRD); 10748 PrevD = D; 10749 } 10750 } 10751 if (SemaRef.CurContext->isDependentContext() || Ty->isDependentType() || 10752 Ty->isInstantiationDependentType() || 10753 Ty->containsUnexpandedParameterPack() || 10754 filterLookupForUDReductionAndMapper<bool>(Lookups, [](ValueDecl *D) { 10755 return !D->isInvalidDecl() && 10756 (D->getType()->isDependentType() || 10757 D->getType()->isInstantiationDependentType() || 10758 D->getType()->containsUnexpandedParameterPack()); 10759 })) { 10760 UnresolvedSet<8> ResSet; 10761 for (const UnresolvedSet<8> &Set : Lookups) { 10762 if (Set.empty()) 10763 continue; 10764 ResSet.append(Set.begin(), Set.end()); 10765 // The last item marks the end of all declarations at the specified scope. 10766 ResSet.addDecl(Set[Set.size() - 1]); 10767 } 10768 return UnresolvedLookupExpr::Create( 10769 SemaRef.Context, /*NamingClass=*/nullptr, 10770 ReductionIdScopeSpec.getWithLocInContext(SemaRef.Context), ReductionId, 10771 /*ADL=*/true, /*Overloaded=*/true, ResSet.begin(), ResSet.end()); 10772 } 10773 // Lookup inside the classes. 10774 // C++ [over.match.oper]p3: 10775 // For a unary operator @ with an operand of a type whose 10776 // cv-unqualified version is T1, and for a binary operator @ with 10777 // a left operand of a type whose cv-unqualified version is T1 and 10778 // a right operand of a type whose cv-unqualified version is T2, 10779 // three sets of candidate functions, designated member 10780 // candidates, non-member candidates and built-in candidates, are 10781 // constructed as follows: 10782 // -- If T1 is a complete class type or a class currently being 10783 // defined, the set of member candidates is the result of the 10784 // qualified lookup of T1::operator@ (13.3.1.1.1); otherwise, 10785 // the set of member candidates is empty. 10786 LookupResult Lookup(SemaRef, ReductionId, Sema::LookupOMPReductionName); 10787 Lookup.suppressDiagnostics(); 10788 if (const auto *TyRec = Ty->getAs<RecordType>()) { 10789 // Complete the type if it can be completed. 10790 // If the type is neither complete nor being defined, bail out now. 10791 if (SemaRef.isCompleteType(Loc, Ty) || TyRec->isBeingDefined() || 10792 TyRec->getDecl()->getDefinition()) { 10793 Lookup.clear(); 10794 SemaRef.LookupQualifiedName(Lookup, TyRec->getDecl()); 10795 if (Lookup.empty()) { 10796 Lookups.emplace_back(); 10797 Lookups.back().append(Lookup.begin(), Lookup.end()); 10798 } 10799 } 10800 } 10801 // Perform ADL. 10802 argumentDependentLookup(SemaRef, ReductionId, Loc, Ty, Lookups); 10803 if (auto *VD = filterLookupForUDReductionAndMapper<ValueDecl *>( 10804 Lookups, [&SemaRef, Ty](ValueDecl *D) -> ValueDecl * { 10805 if (!D->isInvalidDecl() && 10806 SemaRef.Context.hasSameType(D->getType(), Ty)) 10807 return D; 10808 return nullptr; 10809 })) 10810 return SemaRef.BuildDeclRefExpr(VD, VD->getType().getNonReferenceType(), 10811 VK_LValue, Loc); 10812 if (auto *VD = filterLookupForUDReductionAndMapper<ValueDecl *>( 10813 Lookups, [&SemaRef, Ty, Loc](ValueDecl *D) -> ValueDecl * { 10814 if (!D->isInvalidDecl() && 10815 SemaRef.IsDerivedFrom(Loc, Ty, D->getType()) && 10816 !Ty.isMoreQualifiedThan(D->getType())) 10817 return D; 10818 return nullptr; 10819 })) { 10820 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true, 10821 /*DetectVirtual=*/false); 10822 if (SemaRef.IsDerivedFrom(Loc, Ty, VD->getType(), Paths)) { 10823 if (!Paths.isAmbiguous(SemaRef.Context.getCanonicalType( 10824 VD->getType().getUnqualifiedType()))) { 10825 if (SemaRef.CheckBaseClassAccess(Loc, VD->getType(), Ty, Paths.front(), 10826 /*DiagID=*/0) != 10827 Sema::AR_inaccessible) { 10828 SemaRef.BuildBasePathArray(Paths, BasePath); 10829 return SemaRef.BuildDeclRefExpr( 10830 VD, VD->getType().getNonReferenceType(), VK_LValue, Loc); 10831 } 10832 } 10833 } 10834 } 10835 if (ReductionIdScopeSpec.isSet()) { 10836 SemaRef.Diag(Loc, diag::err_omp_not_resolved_reduction_identifier) << Range; 10837 return ExprError(); 10838 } 10839 return ExprEmpty(); 10840 } 10841 10842 namespace { 10843 /// Data for the reduction-based clauses. 10844 struct ReductionData { 10845 /// List of original reduction items. 10846 SmallVector<Expr *, 8> Vars; 10847 /// List of private copies of the reduction items. 10848 SmallVector<Expr *, 8> Privates; 10849 /// LHS expressions for the reduction_op expressions. 10850 SmallVector<Expr *, 8> LHSs; 10851 /// RHS expressions for the reduction_op expressions. 10852 SmallVector<Expr *, 8> RHSs; 10853 /// Reduction operation expression. 10854 SmallVector<Expr *, 8> ReductionOps; 10855 /// Taskgroup descriptors for the corresponding reduction items in 10856 /// in_reduction clauses. 10857 SmallVector<Expr *, 8> TaskgroupDescriptors; 10858 /// List of captures for clause. 10859 SmallVector<Decl *, 4> ExprCaptures; 10860 /// List of postupdate expressions. 10861 SmallVector<Expr *, 4> ExprPostUpdates; 10862 ReductionData() = delete; 10863 /// Reserves required memory for the reduction data. 10864 ReductionData(unsigned Size) { 10865 Vars.reserve(Size); 10866 Privates.reserve(Size); 10867 LHSs.reserve(Size); 10868 RHSs.reserve(Size); 10869 ReductionOps.reserve(Size); 10870 TaskgroupDescriptors.reserve(Size); 10871 ExprCaptures.reserve(Size); 10872 ExprPostUpdates.reserve(Size); 10873 } 10874 /// Stores reduction item and reduction operation only (required for dependent 10875 /// reduction item). 10876 void push(Expr *Item, Expr *ReductionOp) { 10877 Vars.emplace_back(Item); 10878 Privates.emplace_back(nullptr); 10879 LHSs.emplace_back(nullptr); 10880 RHSs.emplace_back(nullptr); 10881 ReductionOps.emplace_back(ReductionOp); 10882 TaskgroupDescriptors.emplace_back(nullptr); 10883 } 10884 /// Stores reduction data. 10885 void push(Expr *Item, Expr *Private, Expr *LHS, Expr *RHS, Expr *ReductionOp, 10886 Expr *TaskgroupDescriptor) { 10887 Vars.emplace_back(Item); 10888 Privates.emplace_back(Private); 10889 LHSs.emplace_back(LHS); 10890 RHSs.emplace_back(RHS); 10891 ReductionOps.emplace_back(ReductionOp); 10892 TaskgroupDescriptors.emplace_back(TaskgroupDescriptor); 10893 } 10894 }; 10895 } // namespace 10896 10897 static bool checkOMPArraySectionConstantForReduction( 10898 ASTContext &Context, const OMPArraySectionExpr *OASE, bool &SingleElement, 10899 SmallVectorImpl<llvm::APSInt> &ArraySizes) { 10900 const Expr *Length = OASE->getLength(); 10901 if (Length == nullptr) { 10902 // For array sections of the form [1:] or [:], we would need to analyze 10903 // the lower bound... 10904 if (OASE->getColonLoc().isValid()) 10905 return false; 10906 10907 // This is an array subscript which has implicit length 1! 10908 SingleElement = true; 10909 ArraySizes.push_back(llvm::APSInt::get(1)); 10910 } else { 10911 Expr::EvalResult Result; 10912 if (!Length->EvaluateAsInt(Result, Context)) 10913 return false; 10914 10915 llvm::APSInt ConstantLengthValue = Result.Val.getInt(); 10916 SingleElement = (ConstantLengthValue.getSExtValue() == 1); 10917 ArraySizes.push_back(ConstantLengthValue); 10918 } 10919 10920 // Get the base of this array section and walk up from there. 10921 const Expr *Base = OASE->getBase()->IgnoreParenImpCasts(); 10922 10923 // We require length = 1 for all array sections except the right-most to 10924 // guarantee that the memory region is contiguous and has no holes in it. 10925 while (const auto *TempOASE = dyn_cast<OMPArraySectionExpr>(Base)) { 10926 Length = TempOASE->getLength(); 10927 if (Length == nullptr) { 10928 // For array sections of the form [1:] or [:], we would need to analyze 10929 // the lower bound... 10930 if (OASE->getColonLoc().isValid()) 10931 return false; 10932 10933 // This is an array subscript which has implicit length 1! 10934 ArraySizes.push_back(llvm::APSInt::get(1)); 10935 } else { 10936 Expr::EvalResult Result; 10937 if (!Length->EvaluateAsInt(Result, Context)) 10938 return false; 10939 10940 llvm::APSInt ConstantLengthValue = Result.Val.getInt(); 10941 if (ConstantLengthValue.getSExtValue() != 1) 10942 return false; 10943 10944 ArraySizes.push_back(ConstantLengthValue); 10945 } 10946 Base = TempOASE->getBase()->IgnoreParenImpCasts(); 10947 } 10948 10949 // If we have a single element, we don't need to add the implicit lengths. 10950 if (!SingleElement) { 10951 while (const auto *TempASE = dyn_cast<ArraySubscriptExpr>(Base)) { 10952 // Has implicit length 1! 10953 ArraySizes.push_back(llvm::APSInt::get(1)); 10954 Base = TempASE->getBase()->IgnoreParenImpCasts(); 10955 } 10956 } 10957 10958 // This array section can be privatized as a single value or as a constant 10959 // sized array. 10960 return true; 10961 } 10962 10963 static bool actOnOMPReductionKindClause( 10964 Sema &S, DSAStackTy *Stack, OpenMPClauseKind ClauseKind, 10965 ArrayRef<Expr *> VarList, SourceLocation StartLoc, SourceLocation LParenLoc, 10966 SourceLocation ColonLoc, SourceLocation EndLoc, 10967 CXXScopeSpec &ReductionIdScopeSpec, const DeclarationNameInfo &ReductionId, 10968 ArrayRef<Expr *> UnresolvedReductions, ReductionData &RD) { 10969 DeclarationName DN = ReductionId.getName(); 10970 OverloadedOperatorKind OOK = DN.getCXXOverloadedOperator(); 10971 BinaryOperatorKind BOK = BO_Comma; 10972 10973 ASTContext &Context = S.Context; 10974 // OpenMP [2.14.3.6, reduction clause] 10975 // C 10976 // reduction-identifier is either an identifier or one of the following 10977 // operators: +, -, *, &, |, ^, && and || 10978 // C++ 10979 // reduction-identifier is either an id-expression or one of the following 10980 // operators: +, -, *, &, |, ^, && and || 10981 switch (OOK) { 10982 case OO_Plus: 10983 case OO_Minus: 10984 BOK = BO_Add; 10985 break; 10986 case OO_Star: 10987 BOK = BO_Mul; 10988 break; 10989 case OO_Amp: 10990 BOK = BO_And; 10991 break; 10992 case OO_Pipe: 10993 BOK = BO_Or; 10994 break; 10995 case OO_Caret: 10996 BOK = BO_Xor; 10997 break; 10998 case OO_AmpAmp: 10999 BOK = BO_LAnd; 11000 break; 11001 case OO_PipePipe: 11002 BOK = BO_LOr; 11003 break; 11004 case OO_New: 11005 case OO_Delete: 11006 case OO_Array_New: 11007 case OO_Array_Delete: 11008 case OO_Slash: 11009 case OO_Percent: 11010 case OO_Tilde: 11011 case OO_Exclaim: 11012 case OO_Equal: 11013 case OO_Less: 11014 case OO_Greater: 11015 case OO_LessEqual: 11016 case OO_GreaterEqual: 11017 case OO_PlusEqual: 11018 case OO_MinusEqual: 11019 case OO_StarEqual: 11020 case OO_SlashEqual: 11021 case OO_PercentEqual: 11022 case OO_CaretEqual: 11023 case OO_AmpEqual: 11024 case OO_PipeEqual: 11025 case OO_LessLess: 11026 case OO_GreaterGreater: 11027 case OO_LessLessEqual: 11028 case OO_GreaterGreaterEqual: 11029 case OO_EqualEqual: 11030 case OO_ExclaimEqual: 11031 case OO_Spaceship: 11032 case OO_PlusPlus: 11033 case OO_MinusMinus: 11034 case OO_Comma: 11035 case OO_ArrowStar: 11036 case OO_Arrow: 11037 case OO_Call: 11038 case OO_Subscript: 11039 case OO_Conditional: 11040 case OO_Coawait: 11041 case NUM_OVERLOADED_OPERATORS: 11042 llvm_unreachable("Unexpected reduction identifier"); 11043 case OO_None: 11044 if (IdentifierInfo *II = DN.getAsIdentifierInfo()) { 11045 if (II->isStr("max")) 11046 BOK = BO_GT; 11047 else if (II->isStr("min")) 11048 BOK = BO_LT; 11049 } 11050 break; 11051 } 11052 SourceRange ReductionIdRange; 11053 if (ReductionIdScopeSpec.isValid()) 11054 ReductionIdRange.setBegin(ReductionIdScopeSpec.getBeginLoc()); 11055 else 11056 ReductionIdRange.setBegin(ReductionId.getBeginLoc()); 11057 ReductionIdRange.setEnd(ReductionId.getEndLoc()); 11058 11059 auto IR = UnresolvedReductions.begin(), ER = UnresolvedReductions.end(); 11060 bool FirstIter = true; 11061 for (Expr *RefExpr : VarList) { 11062 assert(RefExpr && "nullptr expr in OpenMP reduction clause."); 11063 // OpenMP [2.1, C/C++] 11064 // A list item is a variable or array section, subject to the restrictions 11065 // specified in Section 2.4 on page 42 and in each of the sections 11066 // describing clauses and directives for which a list appears. 11067 // OpenMP [2.14.3.3, Restrictions, p.1] 11068 // A variable that is part of another variable (as an array or 11069 // structure element) cannot appear in a private clause. 11070 if (!FirstIter && IR != ER) 11071 ++IR; 11072 FirstIter = false; 11073 SourceLocation ELoc; 11074 SourceRange ERange; 11075 Expr *SimpleRefExpr = RefExpr; 11076 auto Res = getPrivateItem(S, SimpleRefExpr, ELoc, ERange, 11077 /*AllowArraySection=*/true); 11078 if (Res.second) { 11079 // Try to find 'declare reduction' corresponding construct before using 11080 // builtin/overloaded operators. 11081 QualType Type = Context.DependentTy; 11082 CXXCastPath BasePath; 11083 ExprResult DeclareReductionRef = buildDeclareReductionRef( 11084 S, ELoc, ERange, Stack->getCurScope(), ReductionIdScopeSpec, 11085 ReductionId, Type, BasePath, IR == ER ? nullptr : *IR); 11086 Expr *ReductionOp = nullptr; 11087 if (S.CurContext->isDependentContext() && 11088 (DeclareReductionRef.isUnset() || 11089 isa<UnresolvedLookupExpr>(DeclareReductionRef.get()))) 11090 ReductionOp = DeclareReductionRef.get(); 11091 // It will be analyzed later. 11092 RD.push(RefExpr, ReductionOp); 11093 } 11094 ValueDecl *D = Res.first; 11095 if (!D) 11096 continue; 11097 11098 Expr *TaskgroupDescriptor = nullptr; 11099 QualType Type; 11100 auto *ASE = dyn_cast<ArraySubscriptExpr>(RefExpr->IgnoreParens()); 11101 auto *OASE = dyn_cast<OMPArraySectionExpr>(RefExpr->IgnoreParens()); 11102 if (ASE) { 11103 Type = ASE->getType().getNonReferenceType(); 11104 } else if (OASE) { 11105 QualType BaseType = 11106 OMPArraySectionExpr::getBaseOriginalType(OASE->getBase()); 11107 if (const auto *ATy = BaseType->getAsArrayTypeUnsafe()) 11108 Type = ATy->getElementType(); 11109 else 11110 Type = BaseType->getPointeeType(); 11111 Type = Type.getNonReferenceType(); 11112 } else { 11113 Type = Context.getBaseElementType(D->getType().getNonReferenceType()); 11114 } 11115 auto *VD = dyn_cast<VarDecl>(D); 11116 11117 // OpenMP [2.9.3.3, Restrictions, C/C++, p.3] 11118 // A variable that appears in a private clause must not have an incomplete 11119 // type or a reference type. 11120 if (S.RequireCompleteType(ELoc, D->getType(), 11121 diag::err_omp_reduction_incomplete_type)) 11122 continue; 11123 // OpenMP [2.14.3.6, reduction clause, Restrictions] 11124 // A list item that appears in a reduction clause must not be 11125 // const-qualified. 11126 if (rejectConstNotMutableType(S, D, Type, ClauseKind, ELoc, 11127 /*AcceptIfMutable*/ false, ASE || OASE)) 11128 continue; 11129 11130 OpenMPDirectiveKind CurrDir = Stack->getCurrentDirective(); 11131 // OpenMP [2.9.3.6, Restrictions, C/C++, p.4] 11132 // If a list-item is a reference type then it must bind to the same object 11133 // for all threads of the team. 11134 if (!ASE && !OASE) { 11135 if (VD) { 11136 VarDecl *VDDef = VD->getDefinition(); 11137 if (VD->getType()->isReferenceType() && VDDef && VDDef->hasInit()) { 11138 DSARefChecker Check(Stack); 11139 if (Check.Visit(VDDef->getInit())) { 11140 S.Diag(ELoc, diag::err_omp_reduction_ref_type_arg) 11141 << getOpenMPClauseName(ClauseKind) << ERange; 11142 S.Diag(VDDef->getLocation(), diag::note_defined_here) << VDDef; 11143 continue; 11144 } 11145 } 11146 } 11147 11148 // OpenMP [2.14.1.1, Data-sharing Attribute Rules for Variables Referenced 11149 // in a Construct] 11150 // Variables with the predetermined data-sharing attributes may not be 11151 // listed in data-sharing attributes clauses, except for the cases 11152 // listed below. For these exceptions only, listing a predetermined 11153 // variable in a data-sharing attribute clause is allowed and overrides 11154 // the variable's predetermined data-sharing attributes. 11155 // OpenMP [2.14.3.6, Restrictions, p.3] 11156 // Any number of reduction clauses can be specified on the directive, 11157 // but a list item can appear only once in the reduction clauses for that 11158 // directive. 11159 DSAStackTy::DSAVarData DVar = Stack->getTopDSA(D, /*FromParent=*/false); 11160 if (DVar.CKind == OMPC_reduction) { 11161 S.Diag(ELoc, diag::err_omp_once_referenced) 11162 << getOpenMPClauseName(ClauseKind); 11163 if (DVar.RefExpr) 11164 S.Diag(DVar.RefExpr->getExprLoc(), diag::note_omp_referenced); 11165 continue; 11166 } 11167 if (DVar.CKind != OMPC_unknown) { 11168 S.Diag(ELoc, diag::err_omp_wrong_dsa) 11169 << getOpenMPClauseName(DVar.CKind) 11170 << getOpenMPClauseName(OMPC_reduction); 11171 reportOriginalDsa(S, Stack, D, DVar); 11172 continue; 11173 } 11174 11175 // OpenMP [2.14.3.6, Restrictions, p.1] 11176 // A list item that appears in a reduction clause of a worksharing 11177 // construct must be shared in the parallel regions to which any of the 11178 // worksharing regions arising from the worksharing construct bind. 11179 if (isOpenMPWorksharingDirective(CurrDir) && 11180 !isOpenMPParallelDirective(CurrDir) && 11181 !isOpenMPTeamsDirective(CurrDir)) { 11182 DVar = Stack->getImplicitDSA(D, true); 11183 if (DVar.CKind != OMPC_shared) { 11184 S.Diag(ELoc, diag::err_omp_required_access) 11185 << getOpenMPClauseName(OMPC_reduction) 11186 << getOpenMPClauseName(OMPC_shared); 11187 reportOriginalDsa(S, Stack, D, DVar); 11188 continue; 11189 } 11190 } 11191 } 11192 11193 // Try to find 'declare reduction' corresponding construct before using 11194 // builtin/overloaded operators. 11195 CXXCastPath BasePath; 11196 ExprResult DeclareReductionRef = buildDeclareReductionRef( 11197 S, ELoc, ERange, Stack->getCurScope(), ReductionIdScopeSpec, 11198 ReductionId, Type, BasePath, IR == ER ? nullptr : *IR); 11199 if (DeclareReductionRef.isInvalid()) 11200 continue; 11201 if (S.CurContext->isDependentContext() && 11202 (DeclareReductionRef.isUnset() || 11203 isa<UnresolvedLookupExpr>(DeclareReductionRef.get()))) { 11204 RD.push(RefExpr, DeclareReductionRef.get()); 11205 continue; 11206 } 11207 if (BOK == BO_Comma && DeclareReductionRef.isUnset()) { 11208 // Not allowed reduction identifier is found. 11209 S.Diag(ReductionId.getBeginLoc(), 11210 diag::err_omp_unknown_reduction_identifier) 11211 << Type << ReductionIdRange; 11212 continue; 11213 } 11214 11215 // OpenMP [2.14.3.6, reduction clause, Restrictions] 11216 // The type of a list item that appears in a reduction clause must be valid 11217 // for the reduction-identifier. For a max or min reduction in C, the type 11218 // of the list item must be an allowed arithmetic data type: char, int, 11219 // float, double, or _Bool, possibly modified with long, short, signed, or 11220 // unsigned. For a max or min reduction in C++, the type of the list item 11221 // must be an allowed arithmetic data type: char, wchar_t, int, float, 11222 // double, or bool, possibly modified with long, short, signed, or unsigned. 11223 if (DeclareReductionRef.isUnset()) { 11224 if ((BOK == BO_GT || BOK == BO_LT) && 11225 !(Type->isScalarType() || 11226 (S.getLangOpts().CPlusPlus && Type->isArithmeticType()))) { 11227 S.Diag(ELoc, diag::err_omp_clause_not_arithmetic_type_arg) 11228 << getOpenMPClauseName(ClauseKind) << S.getLangOpts().CPlusPlus; 11229 if (!ASE && !OASE) { 11230 bool IsDecl = !VD || VD->isThisDeclarationADefinition(Context) == 11231 VarDecl::DeclarationOnly; 11232 S.Diag(D->getLocation(), 11233 IsDecl ? diag::note_previous_decl : diag::note_defined_here) 11234 << D; 11235 } 11236 continue; 11237 } 11238 if ((BOK == BO_OrAssign || BOK == BO_AndAssign || BOK == BO_XorAssign) && 11239 !S.getLangOpts().CPlusPlus && Type->isFloatingType()) { 11240 S.Diag(ELoc, diag::err_omp_clause_floating_type_arg) 11241 << getOpenMPClauseName(ClauseKind); 11242 if (!ASE && !OASE) { 11243 bool IsDecl = !VD || VD->isThisDeclarationADefinition(Context) == 11244 VarDecl::DeclarationOnly; 11245 S.Diag(D->getLocation(), 11246 IsDecl ? diag::note_previous_decl : diag::note_defined_here) 11247 << D; 11248 } 11249 continue; 11250 } 11251 } 11252 11253 Type = Type.getNonLValueExprType(Context).getUnqualifiedType(); 11254 VarDecl *LHSVD = buildVarDecl(S, ELoc, Type, ".reduction.lhs", 11255 D->hasAttrs() ? &D->getAttrs() : nullptr); 11256 VarDecl *RHSVD = buildVarDecl(S, ELoc, Type, D->getName(), 11257 D->hasAttrs() ? &D->getAttrs() : nullptr); 11258 QualType PrivateTy = Type; 11259 11260 // Try if we can determine constant lengths for all array sections and avoid 11261 // the VLA. 11262 bool ConstantLengthOASE = false; 11263 if (OASE) { 11264 bool SingleElement; 11265 llvm::SmallVector<llvm::APSInt, 4> ArraySizes; 11266 ConstantLengthOASE = checkOMPArraySectionConstantForReduction( 11267 Context, OASE, SingleElement, ArraySizes); 11268 11269 // If we don't have a single element, we must emit a constant array type. 11270 if (ConstantLengthOASE && !SingleElement) { 11271 for (llvm::APSInt &Size : ArraySizes) 11272 PrivateTy = Context.getConstantArrayType( 11273 PrivateTy, Size, ArrayType::Normal, /*IndexTypeQuals=*/0); 11274 } 11275 } 11276 11277 if ((OASE && !ConstantLengthOASE) || 11278 (!OASE && !ASE && 11279 D->getType().getNonReferenceType()->isVariablyModifiedType())) { 11280 if (!Context.getTargetInfo().isVLASupported() && 11281 S.shouldDiagnoseTargetSupportFromOpenMP()) { 11282 S.Diag(ELoc, diag::err_omp_reduction_vla_unsupported) << !!OASE; 11283 S.Diag(ELoc, diag::note_vla_unsupported); 11284 continue; 11285 } 11286 // For arrays/array sections only: 11287 // Create pseudo array type for private copy. The size for this array will 11288 // be generated during codegen. 11289 // For array subscripts or single variables Private Ty is the same as Type 11290 // (type of the variable or single array element). 11291 PrivateTy = Context.getVariableArrayType( 11292 Type, 11293 new (Context) OpaqueValueExpr(ELoc, Context.getSizeType(), VK_RValue), 11294 ArrayType::Normal, /*IndexTypeQuals=*/0, SourceRange()); 11295 } else if (!ASE && !OASE && 11296 Context.getAsArrayType(D->getType().getNonReferenceType())) { 11297 PrivateTy = D->getType().getNonReferenceType(); 11298 } 11299 // Private copy. 11300 VarDecl *PrivateVD = 11301 buildVarDecl(S, ELoc, PrivateTy, D->getName(), 11302 D->hasAttrs() ? &D->getAttrs() : nullptr, 11303 VD ? cast<DeclRefExpr>(SimpleRefExpr) : nullptr); 11304 // Add initializer for private variable. 11305 Expr *Init = nullptr; 11306 DeclRefExpr *LHSDRE = buildDeclRefExpr(S, LHSVD, Type, ELoc); 11307 DeclRefExpr *RHSDRE = buildDeclRefExpr(S, RHSVD, Type, ELoc); 11308 if (DeclareReductionRef.isUsable()) { 11309 auto *DRDRef = DeclareReductionRef.getAs<DeclRefExpr>(); 11310 auto *DRD = cast<OMPDeclareReductionDecl>(DRDRef->getDecl()); 11311 if (DRD->getInitializer()) { 11312 Init = DRDRef; 11313 RHSVD->setInit(DRDRef); 11314 RHSVD->setInitStyle(VarDecl::CallInit); 11315 } 11316 } else { 11317 switch (BOK) { 11318 case BO_Add: 11319 case BO_Xor: 11320 case BO_Or: 11321 case BO_LOr: 11322 // '+', '-', '^', '|', '||' reduction ops - initializer is '0'. 11323 if (Type->isScalarType() || Type->isAnyComplexType()) 11324 Init = S.ActOnIntegerConstant(ELoc, /*Val=*/0).get(); 11325 break; 11326 case BO_Mul: 11327 case BO_LAnd: 11328 if (Type->isScalarType() || Type->isAnyComplexType()) { 11329 // '*' and '&&' reduction ops - initializer is '1'. 11330 Init = S.ActOnIntegerConstant(ELoc, /*Val=*/1).get(); 11331 } 11332 break; 11333 case BO_And: { 11334 // '&' reduction op - initializer is '~0'. 11335 QualType OrigType = Type; 11336 if (auto *ComplexTy = OrigType->getAs<ComplexType>()) 11337 Type = ComplexTy->getElementType(); 11338 if (Type->isRealFloatingType()) { 11339 llvm::APFloat InitValue = 11340 llvm::APFloat::getAllOnesValue(Context.getTypeSize(Type), 11341 /*isIEEE=*/true); 11342 Init = FloatingLiteral::Create(Context, InitValue, /*isexact=*/true, 11343 Type, ELoc); 11344 } else if (Type->isScalarType()) { 11345 uint64_t Size = Context.getTypeSize(Type); 11346 QualType IntTy = Context.getIntTypeForBitwidth(Size, /*Signed=*/0); 11347 llvm::APInt InitValue = llvm::APInt::getAllOnesValue(Size); 11348 Init = IntegerLiteral::Create(Context, InitValue, IntTy, ELoc); 11349 } 11350 if (Init && OrigType->isAnyComplexType()) { 11351 // Init = 0xFFFF + 0xFFFFi; 11352 auto *Im = new (Context) ImaginaryLiteral(Init, OrigType); 11353 Init = S.CreateBuiltinBinOp(ELoc, BO_Add, Init, Im).get(); 11354 } 11355 Type = OrigType; 11356 break; 11357 } 11358 case BO_LT: 11359 case BO_GT: { 11360 // 'min' reduction op - initializer is 'Largest representable number in 11361 // the reduction list item type'. 11362 // 'max' reduction op - initializer is 'Least representable number in 11363 // the reduction list item type'. 11364 if (Type->isIntegerType() || Type->isPointerType()) { 11365 bool IsSigned = Type->hasSignedIntegerRepresentation(); 11366 uint64_t Size = Context.getTypeSize(Type); 11367 QualType IntTy = 11368 Context.getIntTypeForBitwidth(Size, /*Signed=*/IsSigned); 11369 llvm::APInt InitValue = 11370 (BOK != BO_LT) ? IsSigned ? llvm::APInt::getSignedMinValue(Size) 11371 : llvm::APInt::getMinValue(Size) 11372 : IsSigned ? llvm::APInt::getSignedMaxValue(Size) 11373 : llvm::APInt::getMaxValue(Size); 11374 Init = IntegerLiteral::Create(Context, InitValue, IntTy, ELoc); 11375 if (Type->isPointerType()) { 11376 // Cast to pointer type. 11377 ExprResult CastExpr = S.BuildCStyleCastExpr( 11378 ELoc, Context.getTrivialTypeSourceInfo(Type, ELoc), ELoc, Init); 11379 if (CastExpr.isInvalid()) 11380 continue; 11381 Init = CastExpr.get(); 11382 } 11383 } else if (Type->isRealFloatingType()) { 11384 llvm::APFloat InitValue = llvm::APFloat::getLargest( 11385 Context.getFloatTypeSemantics(Type), BOK != BO_LT); 11386 Init = FloatingLiteral::Create(Context, InitValue, /*isexact=*/true, 11387 Type, ELoc); 11388 } 11389 break; 11390 } 11391 case BO_PtrMemD: 11392 case BO_PtrMemI: 11393 case BO_MulAssign: 11394 case BO_Div: 11395 case BO_Rem: 11396 case BO_Sub: 11397 case BO_Shl: 11398 case BO_Shr: 11399 case BO_LE: 11400 case BO_GE: 11401 case BO_EQ: 11402 case BO_NE: 11403 case BO_Cmp: 11404 case BO_AndAssign: 11405 case BO_XorAssign: 11406 case BO_OrAssign: 11407 case BO_Assign: 11408 case BO_AddAssign: 11409 case BO_SubAssign: 11410 case BO_DivAssign: 11411 case BO_RemAssign: 11412 case BO_ShlAssign: 11413 case BO_ShrAssign: 11414 case BO_Comma: 11415 llvm_unreachable("Unexpected reduction operation"); 11416 } 11417 } 11418 if (Init && DeclareReductionRef.isUnset()) 11419 S.AddInitializerToDecl(RHSVD, Init, /*DirectInit=*/false); 11420 else if (!Init) 11421 S.ActOnUninitializedDecl(RHSVD); 11422 if (RHSVD->isInvalidDecl()) 11423 continue; 11424 if (!RHSVD->hasInit() && DeclareReductionRef.isUnset()) { 11425 S.Diag(ELoc, diag::err_omp_reduction_id_not_compatible) 11426 << Type << ReductionIdRange; 11427 bool IsDecl = !VD || VD->isThisDeclarationADefinition(Context) == 11428 VarDecl::DeclarationOnly; 11429 S.Diag(D->getLocation(), 11430 IsDecl ? diag::note_previous_decl : diag::note_defined_here) 11431 << D; 11432 continue; 11433 } 11434 // Store initializer for single element in private copy. Will be used during 11435 // codegen. 11436 PrivateVD->setInit(RHSVD->getInit()); 11437 PrivateVD->setInitStyle(RHSVD->getInitStyle()); 11438 DeclRefExpr *PrivateDRE = buildDeclRefExpr(S, PrivateVD, PrivateTy, ELoc); 11439 ExprResult ReductionOp; 11440 if (DeclareReductionRef.isUsable()) { 11441 QualType RedTy = DeclareReductionRef.get()->getType(); 11442 QualType PtrRedTy = Context.getPointerType(RedTy); 11443 ExprResult LHS = S.CreateBuiltinUnaryOp(ELoc, UO_AddrOf, LHSDRE); 11444 ExprResult RHS = S.CreateBuiltinUnaryOp(ELoc, UO_AddrOf, RHSDRE); 11445 if (!BasePath.empty()) { 11446 LHS = S.DefaultLvalueConversion(LHS.get()); 11447 RHS = S.DefaultLvalueConversion(RHS.get()); 11448 LHS = ImplicitCastExpr::Create(Context, PtrRedTy, 11449 CK_UncheckedDerivedToBase, LHS.get(), 11450 &BasePath, LHS.get()->getValueKind()); 11451 RHS = ImplicitCastExpr::Create(Context, PtrRedTy, 11452 CK_UncheckedDerivedToBase, RHS.get(), 11453 &BasePath, RHS.get()->getValueKind()); 11454 } 11455 FunctionProtoType::ExtProtoInfo EPI; 11456 QualType Params[] = {PtrRedTy, PtrRedTy}; 11457 QualType FnTy = Context.getFunctionType(Context.VoidTy, Params, EPI); 11458 auto *OVE = new (Context) OpaqueValueExpr( 11459 ELoc, Context.getPointerType(FnTy), VK_RValue, OK_Ordinary, 11460 S.DefaultLvalueConversion(DeclareReductionRef.get()).get()); 11461 Expr *Args[] = {LHS.get(), RHS.get()}; 11462 ReductionOp = 11463 CallExpr::Create(Context, OVE, Args, Context.VoidTy, VK_RValue, ELoc); 11464 } else { 11465 ReductionOp = S.BuildBinOp( 11466 Stack->getCurScope(), ReductionId.getBeginLoc(), BOK, LHSDRE, RHSDRE); 11467 if (ReductionOp.isUsable()) { 11468 if (BOK != BO_LT && BOK != BO_GT) { 11469 ReductionOp = 11470 S.BuildBinOp(Stack->getCurScope(), ReductionId.getBeginLoc(), 11471 BO_Assign, LHSDRE, ReductionOp.get()); 11472 } else { 11473 auto *ConditionalOp = new (Context) 11474 ConditionalOperator(ReductionOp.get(), ELoc, LHSDRE, ELoc, RHSDRE, 11475 Type, VK_LValue, OK_Ordinary); 11476 ReductionOp = 11477 S.BuildBinOp(Stack->getCurScope(), ReductionId.getBeginLoc(), 11478 BO_Assign, LHSDRE, ConditionalOp); 11479 } 11480 if (ReductionOp.isUsable()) 11481 ReductionOp = S.ActOnFinishFullExpr(ReductionOp.get(), 11482 /*DiscardedValue*/ false); 11483 } 11484 if (!ReductionOp.isUsable()) 11485 continue; 11486 } 11487 11488 // OpenMP [2.15.4.6, Restrictions, p.2] 11489 // A list item that appears in an in_reduction clause of a task construct 11490 // must appear in a task_reduction clause of a construct associated with a 11491 // taskgroup region that includes the participating task in its taskgroup 11492 // set. The construct associated with the innermost region that meets this 11493 // condition must specify the same reduction-identifier as the in_reduction 11494 // clause. 11495 if (ClauseKind == OMPC_in_reduction) { 11496 SourceRange ParentSR; 11497 BinaryOperatorKind ParentBOK; 11498 const Expr *ParentReductionOp; 11499 Expr *ParentBOKTD, *ParentReductionOpTD; 11500 DSAStackTy::DSAVarData ParentBOKDSA = 11501 Stack->getTopMostTaskgroupReductionData(D, ParentSR, ParentBOK, 11502 ParentBOKTD); 11503 DSAStackTy::DSAVarData ParentReductionOpDSA = 11504 Stack->getTopMostTaskgroupReductionData( 11505 D, ParentSR, ParentReductionOp, ParentReductionOpTD); 11506 bool IsParentBOK = ParentBOKDSA.DKind != OMPD_unknown; 11507 bool IsParentReductionOp = ParentReductionOpDSA.DKind != OMPD_unknown; 11508 if (!IsParentBOK && !IsParentReductionOp) { 11509 S.Diag(ELoc, diag::err_omp_in_reduction_not_task_reduction); 11510 continue; 11511 } 11512 if ((DeclareReductionRef.isUnset() && IsParentReductionOp) || 11513 (DeclareReductionRef.isUsable() && IsParentBOK) || BOK != ParentBOK || 11514 IsParentReductionOp) { 11515 bool EmitError = true; 11516 if (IsParentReductionOp && DeclareReductionRef.isUsable()) { 11517 llvm::FoldingSetNodeID RedId, ParentRedId; 11518 ParentReductionOp->Profile(ParentRedId, Context, /*Canonical=*/true); 11519 DeclareReductionRef.get()->Profile(RedId, Context, 11520 /*Canonical=*/true); 11521 EmitError = RedId != ParentRedId; 11522 } 11523 if (EmitError) { 11524 S.Diag(ReductionId.getBeginLoc(), 11525 diag::err_omp_reduction_identifier_mismatch) 11526 << ReductionIdRange << RefExpr->getSourceRange(); 11527 S.Diag(ParentSR.getBegin(), 11528 diag::note_omp_previous_reduction_identifier) 11529 << ParentSR 11530 << (IsParentBOK ? ParentBOKDSA.RefExpr 11531 : ParentReductionOpDSA.RefExpr) 11532 ->getSourceRange(); 11533 continue; 11534 } 11535 } 11536 TaskgroupDescriptor = IsParentBOK ? ParentBOKTD : ParentReductionOpTD; 11537 assert(TaskgroupDescriptor && "Taskgroup descriptor must be defined."); 11538 } 11539 11540 DeclRefExpr *Ref = nullptr; 11541 Expr *VarsExpr = RefExpr->IgnoreParens(); 11542 if (!VD && !S.CurContext->isDependentContext()) { 11543 if (ASE || OASE) { 11544 TransformExprToCaptures RebuildToCapture(S, D); 11545 VarsExpr = 11546 RebuildToCapture.TransformExpr(RefExpr->IgnoreParens()).get(); 11547 Ref = RebuildToCapture.getCapturedExpr(); 11548 } else { 11549 VarsExpr = Ref = buildCapture(S, D, SimpleRefExpr, /*WithInit=*/false); 11550 } 11551 if (!S.isOpenMPCapturedDecl(D)) { 11552 RD.ExprCaptures.emplace_back(Ref->getDecl()); 11553 if (Ref->getDecl()->hasAttr<OMPCaptureNoInitAttr>()) { 11554 ExprResult RefRes = S.DefaultLvalueConversion(Ref); 11555 if (!RefRes.isUsable()) 11556 continue; 11557 ExprResult PostUpdateRes = 11558 S.BuildBinOp(Stack->getCurScope(), ELoc, BO_Assign, SimpleRefExpr, 11559 RefRes.get()); 11560 if (!PostUpdateRes.isUsable()) 11561 continue; 11562 if (isOpenMPTaskingDirective(Stack->getCurrentDirective()) || 11563 Stack->getCurrentDirective() == OMPD_taskgroup) { 11564 S.Diag(RefExpr->getExprLoc(), 11565 diag::err_omp_reduction_non_addressable_expression) 11566 << RefExpr->getSourceRange(); 11567 continue; 11568 } 11569 RD.ExprPostUpdates.emplace_back( 11570 S.IgnoredValueConversions(PostUpdateRes.get()).get()); 11571 } 11572 } 11573 } 11574 // All reduction items are still marked as reduction (to do not increase 11575 // code base size). 11576 Stack->addDSA(D, RefExpr->IgnoreParens(), OMPC_reduction, Ref); 11577 if (CurrDir == OMPD_taskgroup) { 11578 if (DeclareReductionRef.isUsable()) 11579 Stack->addTaskgroupReductionData(D, ReductionIdRange, 11580 DeclareReductionRef.get()); 11581 else 11582 Stack->addTaskgroupReductionData(D, ReductionIdRange, BOK); 11583 } 11584 RD.push(VarsExpr, PrivateDRE, LHSDRE, RHSDRE, ReductionOp.get(), 11585 TaskgroupDescriptor); 11586 } 11587 return RD.Vars.empty(); 11588 } 11589 11590 OMPClause *Sema::ActOnOpenMPReductionClause( 11591 ArrayRef<Expr *> VarList, SourceLocation StartLoc, SourceLocation LParenLoc, 11592 SourceLocation ColonLoc, SourceLocation EndLoc, 11593 CXXScopeSpec &ReductionIdScopeSpec, const DeclarationNameInfo &ReductionId, 11594 ArrayRef<Expr *> UnresolvedReductions) { 11595 ReductionData RD(VarList.size()); 11596 if (actOnOMPReductionKindClause(*this, DSAStack, OMPC_reduction, VarList, 11597 StartLoc, LParenLoc, ColonLoc, EndLoc, 11598 ReductionIdScopeSpec, ReductionId, 11599 UnresolvedReductions, RD)) 11600 return nullptr; 11601 11602 return OMPReductionClause::Create( 11603 Context, StartLoc, LParenLoc, ColonLoc, EndLoc, RD.Vars, 11604 ReductionIdScopeSpec.getWithLocInContext(Context), ReductionId, 11605 RD.Privates, RD.LHSs, RD.RHSs, RD.ReductionOps, 11606 buildPreInits(Context, RD.ExprCaptures), 11607 buildPostUpdate(*this, RD.ExprPostUpdates)); 11608 } 11609 11610 OMPClause *Sema::ActOnOpenMPTaskReductionClause( 11611 ArrayRef<Expr *> VarList, SourceLocation StartLoc, SourceLocation LParenLoc, 11612 SourceLocation ColonLoc, SourceLocation EndLoc, 11613 CXXScopeSpec &ReductionIdScopeSpec, const DeclarationNameInfo &ReductionId, 11614 ArrayRef<Expr *> UnresolvedReductions) { 11615 ReductionData RD(VarList.size()); 11616 if (actOnOMPReductionKindClause(*this, DSAStack, OMPC_task_reduction, VarList, 11617 StartLoc, LParenLoc, ColonLoc, EndLoc, 11618 ReductionIdScopeSpec, ReductionId, 11619 UnresolvedReductions, RD)) 11620 return nullptr; 11621 11622 return OMPTaskReductionClause::Create( 11623 Context, StartLoc, LParenLoc, ColonLoc, EndLoc, RD.Vars, 11624 ReductionIdScopeSpec.getWithLocInContext(Context), ReductionId, 11625 RD.Privates, RD.LHSs, RD.RHSs, RD.ReductionOps, 11626 buildPreInits(Context, RD.ExprCaptures), 11627 buildPostUpdate(*this, RD.ExprPostUpdates)); 11628 } 11629 11630 OMPClause *Sema::ActOnOpenMPInReductionClause( 11631 ArrayRef<Expr *> VarList, SourceLocation StartLoc, SourceLocation LParenLoc, 11632 SourceLocation ColonLoc, SourceLocation EndLoc, 11633 CXXScopeSpec &ReductionIdScopeSpec, const DeclarationNameInfo &ReductionId, 11634 ArrayRef<Expr *> UnresolvedReductions) { 11635 ReductionData RD(VarList.size()); 11636 if (actOnOMPReductionKindClause(*this, DSAStack, OMPC_in_reduction, VarList, 11637 StartLoc, LParenLoc, ColonLoc, EndLoc, 11638 ReductionIdScopeSpec, ReductionId, 11639 UnresolvedReductions, RD)) 11640 return nullptr; 11641 11642 return OMPInReductionClause::Create( 11643 Context, StartLoc, LParenLoc, ColonLoc, EndLoc, RD.Vars, 11644 ReductionIdScopeSpec.getWithLocInContext(Context), ReductionId, 11645 RD.Privates, RD.LHSs, RD.RHSs, RD.ReductionOps, RD.TaskgroupDescriptors, 11646 buildPreInits(Context, RD.ExprCaptures), 11647 buildPostUpdate(*this, RD.ExprPostUpdates)); 11648 } 11649 11650 bool Sema::CheckOpenMPLinearModifier(OpenMPLinearClauseKind LinKind, 11651 SourceLocation LinLoc) { 11652 if ((!LangOpts.CPlusPlus && LinKind != OMPC_LINEAR_val) || 11653 LinKind == OMPC_LINEAR_unknown) { 11654 Diag(LinLoc, diag::err_omp_wrong_linear_modifier) << LangOpts.CPlusPlus; 11655 return true; 11656 } 11657 return false; 11658 } 11659 11660 bool Sema::CheckOpenMPLinearDecl(const ValueDecl *D, SourceLocation ELoc, 11661 OpenMPLinearClauseKind LinKind, 11662 QualType Type) { 11663 const auto *VD = dyn_cast_or_null<VarDecl>(D); 11664 // A variable must not have an incomplete type or a reference type. 11665 if (RequireCompleteType(ELoc, Type, diag::err_omp_linear_incomplete_type)) 11666 return true; 11667 if ((LinKind == OMPC_LINEAR_uval || LinKind == OMPC_LINEAR_ref) && 11668 !Type->isReferenceType()) { 11669 Diag(ELoc, diag::err_omp_wrong_linear_modifier_non_reference) 11670 << Type << getOpenMPSimpleClauseTypeName(OMPC_linear, LinKind); 11671 return true; 11672 } 11673 Type = Type.getNonReferenceType(); 11674 11675 // OpenMP 5.0 [2.19.3, List Item Privatization, Restrictions] 11676 // A variable that is privatized must not have a const-qualified type 11677 // unless it is of class type with a mutable member. This restriction does 11678 // not apply to the firstprivate clause. 11679 if (rejectConstNotMutableType(*this, D, Type, OMPC_linear, ELoc)) 11680 return true; 11681 11682 // A list item must be of integral or pointer type. 11683 Type = Type.getUnqualifiedType().getCanonicalType(); 11684 const auto *Ty = Type.getTypePtrOrNull(); 11685 if (!Ty || (!Ty->isDependentType() && !Ty->isIntegralType(Context) && 11686 !Ty->isPointerType())) { 11687 Diag(ELoc, diag::err_omp_linear_expected_int_or_ptr) << Type; 11688 if (D) { 11689 bool IsDecl = 11690 !VD || 11691 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly; 11692 Diag(D->getLocation(), 11693 IsDecl ? diag::note_previous_decl : diag::note_defined_here) 11694 << D; 11695 } 11696 return true; 11697 } 11698 return false; 11699 } 11700 11701 OMPClause *Sema::ActOnOpenMPLinearClause( 11702 ArrayRef<Expr *> VarList, Expr *Step, SourceLocation StartLoc, 11703 SourceLocation LParenLoc, OpenMPLinearClauseKind LinKind, 11704 SourceLocation LinLoc, SourceLocation ColonLoc, SourceLocation EndLoc) { 11705 SmallVector<Expr *, 8> Vars; 11706 SmallVector<Expr *, 8> Privates; 11707 SmallVector<Expr *, 8> Inits; 11708 SmallVector<Decl *, 4> ExprCaptures; 11709 SmallVector<Expr *, 4> ExprPostUpdates; 11710 if (CheckOpenMPLinearModifier(LinKind, LinLoc)) 11711 LinKind = OMPC_LINEAR_val; 11712 for (Expr *RefExpr : VarList) { 11713 assert(RefExpr && "NULL expr in OpenMP linear clause."); 11714 SourceLocation ELoc; 11715 SourceRange ERange; 11716 Expr *SimpleRefExpr = RefExpr; 11717 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange); 11718 if (Res.second) { 11719 // It will be analyzed later. 11720 Vars.push_back(RefExpr); 11721 Privates.push_back(nullptr); 11722 Inits.push_back(nullptr); 11723 } 11724 ValueDecl *D = Res.first; 11725 if (!D) 11726 continue; 11727 11728 QualType Type = D->getType(); 11729 auto *VD = dyn_cast<VarDecl>(D); 11730 11731 // OpenMP [2.14.3.7, linear clause] 11732 // A list-item cannot appear in more than one linear clause. 11733 // A list-item that appears in a linear clause cannot appear in any 11734 // other data-sharing attribute clause. 11735 DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, /*FromParent=*/false); 11736 if (DVar.RefExpr) { 11737 Diag(ELoc, diag::err_omp_wrong_dsa) << getOpenMPClauseName(DVar.CKind) 11738 << getOpenMPClauseName(OMPC_linear); 11739 reportOriginalDsa(*this, DSAStack, D, DVar); 11740 continue; 11741 } 11742 11743 if (CheckOpenMPLinearDecl(D, ELoc, LinKind, Type)) 11744 continue; 11745 Type = Type.getNonReferenceType().getUnqualifiedType().getCanonicalType(); 11746 11747 // Build private copy of original var. 11748 VarDecl *Private = 11749 buildVarDecl(*this, ELoc, Type, D->getName(), 11750 D->hasAttrs() ? &D->getAttrs() : nullptr, 11751 VD ? cast<DeclRefExpr>(SimpleRefExpr) : nullptr); 11752 DeclRefExpr *PrivateRef = buildDeclRefExpr(*this, Private, Type, ELoc); 11753 // Build var to save initial value. 11754 VarDecl *Init = buildVarDecl(*this, ELoc, Type, ".linear.start"); 11755 Expr *InitExpr; 11756 DeclRefExpr *Ref = nullptr; 11757 if (!VD && !CurContext->isDependentContext()) { 11758 Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/false); 11759 if (!isOpenMPCapturedDecl(D)) { 11760 ExprCaptures.push_back(Ref->getDecl()); 11761 if (Ref->getDecl()->hasAttr<OMPCaptureNoInitAttr>()) { 11762 ExprResult RefRes = DefaultLvalueConversion(Ref); 11763 if (!RefRes.isUsable()) 11764 continue; 11765 ExprResult PostUpdateRes = 11766 BuildBinOp(DSAStack->getCurScope(), ELoc, BO_Assign, 11767 SimpleRefExpr, RefRes.get()); 11768 if (!PostUpdateRes.isUsable()) 11769 continue; 11770 ExprPostUpdates.push_back( 11771 IgnoredValueConversions(PostUpdateRes.get()).get()); 11772 } 11773 } 11774 } 11775 if (LinKind == OMPC_LINEAR_uval) 11776 InitExpr = VD ? VD->getInit() : SimpleRefExpr; 11777 else 11778 InitExpr = VD ? SimpleRefExpr : Ref; 11779 AddInitializerToDecl(Init, DefaultLvalueConversion(InitExpr).get(), 11780 /*DirectInit=*/false); 11781 DeclRefExpr *InitRef = buildDeclRefExpr(*this, Init, Type, ELoc); 11782 11783 DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_linear, Ref); 11784 Vars.push_back((VD || CurContext->isDependentContext()) 11785 ? RefExpr->IgnoreParens() 11786 : Ref); 11787 Privates.push_back(PrivateRef); 11788 Inits.push_back(InitRef); 11789 } 11790 11791 if (Vars.empty()) 11792 return nullptr; 11793 11794 Expr *StepExpr = Step; 11795 Expr *CalcStepExpr = nullptr; 11796 if (Step && !Step->isValueDependent() && !Step->isTypeDependent() && 11797 !Step->isInstantiationDependent() && 11798 !Step->containsUnexpandedParameterPack()) { 11799 SourceLocation StepLoc = Step->getBeginLoc(); 11800 ExprResult Val = PerformOpenMPImplicitIntegerConversion(StepLoc, Step); 11801 if (Val.isInvalid()) 11802 return nullptr; 11803 StepExpr = Val.get(); 11804 11805 // Build var to save the step value. 11806 VarDecl *SaveVar = 11807 buildVarDecl(*this, StepLoc, StepExpr->getType(), ".linear.step"); 11808 ExprResult SaveRef = 11809 buildDeclRefExpr(*this, SaveVar, StepExpr->getType(), StepLoc); 11810 ExprResult CalcStep = 11811 BuildBinOp(CurScope, StepLoc, BO_Assign, SaveRef.get(), StepExpr); 11812 CalcStep = ActOnFinishFullExpr(CalcStep.get(), /*DiscardedValue*/ false); 11813 11814 // Warn about zero linear step (it would be probably better specified as 11815 // making corresponding variables 'const'). 11816 llvm::APSInt Result; 11817 bool IsConstant = StepExpr->isIntegerConstantExpr(Result, Context); 11818 if (IsConstant && !Result.isNegative() && !Result.isStrictlyPositive()) 11819 Diag(StepLoc, diag::warn_omp_linear_step_zero) << Vars[0] 11820 << (Vars.size() > 1); 11821 if (!IsConstant && CalcStep.isUsable()) { 11822 // Calculate the step beforehand instead of doing this on each iteration. 11823 // (This is not used if the number of iterations may be kfold-ed). 11824 CalcStepExpr = CalcStep.get(); 11825 } 11826 } 11827 11828 return OMPLinearClause::Create(Context, StartLoc, LParenLoc, LinKind, LinLoc, 11829 ColonLoc, EndLoc, Vars, Privates, Inits, 11830 StepExpr, CalcStepExpr, 11831 buildPreInits(Context, ExprCaptures), 11832 buildPostUpdate(*this, ExprPostUpdates)); 11833 } 11834 11835 static bool FinishOpenMPLinearClause(OMPLinearClause &Clause, DeclRefExpr *IV, 11836 Expr *NumIterations, Sema &SemaRef, 11837 Scope *S, DSAStackTy *Stack) { 11838 // Walk the vars and build update/final expressions for the CodeGen. 11839 SmallVector<Expr *, 8> Updates; 11840 SmallVector<Expr *, 8> Finals; 11841 Expr *Step = Clause.getStep(); 11842 Expr *CalcStep = Clause.getCalcStep(); 11843 // OpenMP [2.14.3.7, linear clause] 11844 // If linear-step is not specified it is assumed to be 1. 11845 if (!Step) 11846 Step = SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get(); 11847 else if (CalcStep) 11848 Step = cast<BinaryOperator>(CalcStep)->getLHS(); 11849 bool HasErrors = false; 11850 auto CurInit = Clause.inits().begin(); 11851 auto CurPrivate = Clause.privates().begin(); 11852 OpenMPLinearClauseKind LinKind = Clause.getModifier(); 11853 for (Expr *RefExpr : Clause.varlists()) { 11854 SourceLocation ELoc; 11855 SourceRange ERange; 11856 Expr *SimpleRefExpr = RefExpr; 11857 auto Res = getPrivateItem(SemaRef, SimpleRefExpr, ELoc, ERange); 11858 ValueDecl *D = Res.first; 11859 if (Res.second || !D) { 11860 Updates.push_back(nullptr); 11861 Finals.push_back(nullptr); 11862 HasErrors = true; 11863 continue; 11864 } 11865 auto &&Info = Stack->isLoopControlVariable(D); 11866 // OpenMP [2.15.11, distribute simd Construct] 11867 // A list item may not appear in a linear clause, unless it is the loop 11868 // iteration variable. 11869 if (isOpenMPDistributeDirective(Stack->getCurrentDirective()) && 11870 isOpenMPSimdDirective(Stack->getCurrentDirective()) && !Info.first) { 11871 SemaRef.Diag(ELoc, 11872 diag::err_omp_linear_distribute_var_non_loop_iteration); 11873 Updates.push_back(nullptr); 11874 Finals.push_back(nullptr); 11875 HasErrors = true; 11876 continue; 11877 } 11878 Expr *InitExpr = *CurInit; 11879 11880 // Build privatized reference to the current linear var. 11881 auto *DE = cast<DeclRefExpr>(SimpleRefExpr); 11882 Expr *CapturedRef; 11883 if (LinKind == OMPC_LINEAR_uval) 11884 CapturedRef = cast<VarDecl>(DE->getDecl())->getInit(); 11885 else 11886 CapturedRef = 11887 buildDeclRefExpr(SemaRef, cast<VarDecl>(DE->getDecl()), 11888 DE->getType().getUnqualifiedType(), DE->getExprLoc(), 11889 /*RefersToCapture=*/true); 11890 11891 // Build update: Var = InitExpr + IV * Step 11892 ExprResult Update; 11893 if (!Info.first) 11894 Update = 11895 buildCounterUpdate(SemaRef, S, RefExpr->getExprLoc(), *CurPrivate, 11896 InitExpr, IV, Step, /* Subtract */ false); 11897 else 11898 Update = *CurPrivate; 11899 Update = SemaRef.ActOnFinishFullExpr(Update.get(), DE->getBeginLoc(), 11900 /*DiscardedValue*/ false); 11901 11902 // Build final: Var = InitExpr + NumIterations * Step 11903 ExprResult Final; 11904 if (!Info.first) 11905 Final = 11906 buildCounterUpdate(SemaRef, S, RefExpr->getExprLoc(), CapturedRef, 11907 InitExpr, NumIterations, Step, /*Subtract=*/false); 11908 else 11909 Final = *CurPrivate; 11910 Final = SemaRef.ActOnFinishFullExpr(Final.get(), DE->getBeginLoc(), 11911 /*DiscardedValue*/ false); 11912 11913 if (!Update.isUsable() || !Final.isUsable()) { 11914 Updates.push_back(nullptr); 11915 Finals.push_back(nullptr); 11916 HasErrors = true; 11917 } else { 11918 Updates.push_back(Update.get()); 11919 Finals.push_back(Final.get()); 11920 } 11921 ++CurInit; 11922 ++CurPrivate; 11923 } 11924 Clause.setUpdates(Updates); 11925 Clause.setFinals(Finals); 11926 return HasErrors; 11927 } 11928 11929 OMPClause *Sema::ActOnOpenMPAlignedClause( 11930 ArrayRef<Expr *> VarList, Expr *Alignment, SourceLocation StartLoc, 11931 SourceLocation LParenLoc, SourceLocation ColonLoc, SourceLocation EndLoc) { 11932 SmallVector<Expr *, 8> Vars; 11933 for (Expr *RefExpr : VarList) { 11934 assert(RefExpr && "NULL expr in OpenMP linear clause."); 11935 SourceLocation ELoc; 11936 SourceRange ERange; 11937 Expr *SimpleRefExpr = RefExpr; 11938 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange); 11939 if (Res.second) { 11940 // It will be analyzed later. 11941 Vars.push_back(RefExpr); 11942 } 11943 ValueDecl *D = Res.first; 11944 if (!D) 11945 continue; 11946 11947 QualType QType = D->getType(); 11948 auto *VD = dyn_cast<VarDecl>(D); 11949 11950 // OpenMP [2.8.1, simd construct, Restrictions] 11951 // The type of list items appearing in the aligned clause must be 11952 // array, pointer, reference to array, or reference to pointer. 11953 QType = QType.getNonReferenceType().getUnqualifiedType().getCanonicalType(); 11954 const Type *Ty = QType.getTypePtrOrNull(); 11955 if (!Ty || (!Ty->isArrayType() && !Ty->isPointerType())) { 11956 Diag(ELoc, diag::err_omp_aligned_expected_array_or_ptr) 11957 << QType << getLangOpts().CPlusPlus << ERange; 11958 bool IsDecl = 11959 !VD || 11960 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly; 11961 Diag(D->getLocation(), 11962 IsDecl ? diag::note_previous_decl : diag::note_defined_here) 11963 << D; 11964 continue; 11965 } 11966 11967 // OpenMP [2.8.1, simd construct, Restrictions] 11968 // A list-item cannot appear in more than one aligned clause. 11969 if (const Expr *PrevRef = DSAStack->addUniqueAligned(D, SimpleRefExpr)) { 11970 Diag(ELoc, diag::err_omp_aligned_twice) << 0 << ERange; 11971 Diag(PrevRef->getExprLoc(), diag::note_omp_explicit_dsa) 11972 << getOpenMPClauseName(OMPC_aligned); 11973 continue; 11974 } 11975 11976 DeclRefExpr *Ref = nullptr; 11977 if (!VD && isOpenMPCapturedDecl(D)) 11978 Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/true); 11979 Vars.push_back(DefaultFunctionArrayConversion( 11980 (VD || !Ref) ? RefExpr->IgnoreParens() : Ref) 11981 .get()); 11982 } 11983 11984 // OpenMP [2.8.1, simd construct, Description] 11985 // The parameter of the aligned clause, alignment, must be a constant 11986 // positive integer expression. 11987 // If no optional parameter is specified, implementation-defined default 11988 // alignments for SIMD instructions on the target platforms are assumed. 11989 if (Alignment != nullptr) { 11990 ExprResult AlignResult = 11991 VerifyPositiveIntegerConstantInClause(Alignment, OMPC_aligned); 11992 if (AlignResult.isInvalid()) 11993 return nullptr; 11994 Alignment = AlignResult.get(); 11995 } 11996 if (Vars.empty()) 11997 return nullptr; 11998 11999 return OMPAlignedClause::Create(Context, StartLoc, LParenLoc, ColonLoc, 12000 EndLoc, Vars, Alignment); 12001 } 12002 12003 OMPClause *Sema::ActOnOpenMPCopyinClause(ArrayRef<Expr *> VarList, 12004 SourceLocation StartLoc, 12005 SourceLocation LParenLoc, 12006 SourceLocation EndLoc) { 12007 SmallVector<Expr *, 8> Vars; 12008 SmallVector<Expr *, 8> SrcExprs; 12009 SmallVector<Expr *, 8> DstExprs; 12010 SmallVector<Expr *, 8> AssignmentOps; 12011 for (Expr *RefExpr : VarList) { 12012 assert(RefExpr && "NULL expr in OpenMP copyin clause."); 12013 if (isa<DependentScopeDeclRefExpr>(RefExpr)) { 12014 // It will be analyzed later. 12015 Vars.push_back(RefExpr); 12016 SrcExprs.push_back(nullptr); 12017 DstExprs.push_back(nullptr); 12018 AssignmentOps.push_back(nullptr); 12019 continue; 12020 } 12021 12022 SourceLocation ELoc = RefExpr->getExprLoc(); 12023 // OpenMP [2.1, C/C++] 12024 // A list item is a variable name. 12025 // OpenMP [2.14.4.1, Restrictions, p.1] 12026 // A list item that appears in a copyin clause must be threadprivate. 12027 auto *DE = dyn_cast<DeclRefExpr>(RefExpr); 12028 if (!DE || !isa<VarDecl>(DE->getDecl())) { 12029 Diag(ELoc, diag::err_omp_expected_var_name_member_expr) 12030 << 0 << RefExpr->getSourceRange(); 12031 continue; 12032 } 12033 12034 Decl *D = DE->getDecl(); 12035 auto *VD = cast<VarDecl>(D); 12036 12037 QualType Type = VD->getType(); 12038 if (Type->isDependentType() || Type->isInstantiationDependentType()) { 12039 // It will be analyzed later. 12040 Vars.push_back(DE); 12041 SrcExprs.push_back(nullptr); 12042 DstExprs.push_back(nullptr); 12043 AssignmentOps.push_back(nullptr); 12044 continue; 12045 } 12046 12047 // OpenMP [2.14.4.1, Restrictions, C/C++, p.1] 12048 // A list item that appears in a copyin clause must be threadprivate. 12049 if (!DSAStack->isThreadPrivate(VD)) { 12050 Diag(ELoc, diag::err_omp_required_access) 12051 << getOpenMPClauseName(OMPC_copyin) 12052 << getOpenMPDirectiveName(OMPD_threadprivate); 12053 continue; 12054 } 12055 12056 // OpenMP [2.14.4.1, Restrictions, C/C++, p.2] 12057 // A variable of class type (or array thereof) that appears in a 12058 // copyin clause requires an accessible, unambiguous copy assignment 12059 // operator for the class type. 12060 QualType ElemType = Context.getBaseElementType(Type).getNonReferenceType(); 12061 VarDecl *SrcVD = 12062 buildVarDecl(*this, DE->getBeginLoc(), ElemType.getUnqualifiedType(), 12063 ".copyin.src", VD->hasAttrs() ? &VD->getAttrs() : nullptr); 12064 DeclRefExpr *PseudoSrcExpr = buildDeclRefExpr( 12065 *this, SrcVD, ElemType.getUnqualifiedType(), DE->getExprLoc()); 12066 VarDecl *DstVD = 12067 buildVarDecl(*this, DE->getBeginLoc(), ElemType, ".copyin.dst", 12068 VD->hasAttrs() ? &VD->getAttrs() : nullptr); 12069 DeclRefExpr *PseudoDstExpr = 12070 buildDeclRefExpr(*this, DstVD, ElemType, DE->getExprLoc()); 12071 // For arrays generate assignment operation for single element and replace 12072 // it by the original array element in CodeGen. 12073 ExprResult AssignmentOp = 12074 BuildBinOp(/*S=*/nullptr, DE->getExprLoc(), BO_Assign, PseudoDstExpr, 12075 PseudoSrcExpr); 12076 if (AssignmentOp.isInvalid()) 12077 continue; 12078 AssignmentOp = ActOnFinishFullExpr(AssignmentOp.get(), DE->getExprLoc(), 12079 /*DiscardedValue*/ false); 12080 if (AssignmentOp.isInvalid()) 12081 continue; 12082 12083 DSAStack->addDSA(VD, DE, OMPC_copyin); 12084 Vars.push_back(DE); 12085 SrcExprs.push_back(PseudoSrcExpr); 12086 DstExprs.push_back(PseudoDstExpr); 12087 AssignmentOps.push_back(AssignmentOp.get()); 12088 } 12089 12090 if (Vars.empty()) 12091 return nullptr; 12092 12093 return OMPCopyinClause::Create(Context, StartLoc, LParenLoc, EndLoc, Vars, 12094 SrcExprs, DstExprs, AssignmentOps); 12095 } 12096 12097 OMPClause *Sema::ActOnOpenMPCopyprivateClause(ArrayRef<Expr *> VarList, 12098 SourceLocation StartLoc, 12099 SourceLocation LParenLoc, 12100 SourceLocation EndLoc) { 12101 SmallVector<Expr *, 8> Vars; 12102 SmallVector<Expr *, 8> SrcExprs; 12103 SmallVector<Expr *, 8> DstExprs; 12104 SmallVector<Expr *, 8> AssignmentOps; 12105 for (Expr *RefExpr : VarList) { 12106 assert(RefExpr && "NULL expr in OpenMP linear clause."); 12107 SourceLocation ELoc; 12108 SourceRange ERange; 12109 Expr *SimpleRefExpr = RefExpr; 12110 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange); 12111 if (Res.second) { 12112 // It will be analyzed later. 12113 Vars.push_back(RefExpr); 12114 SrcExprs.push_back(nullptr); 12115 DstExprs.push_back(nullptr); 12116 AssignmentOps.push_back(nullptr); 12117 } 12118 ValueDecl *D = Res.first; 12119 if (!D) 12120 continue; 12121 12122 QualType Type = D->getType(); 12123 auto *VD = dyn_cast<VarDecl>(D); 12124 12125 // OpenMP [2.14.4.2, Restrictions, p.2] 12126 // A list item that appears in a copyprivate clause may not appear in a 12127 // private or firstprivate clause on the single construct. 12128 if (!VD || !DSAStack->isThreadPrivate(VD)) { 12129 DSAStackTy::DSAVarData DVar = 12130 DSAStack->getTopDSA(D, /*FromParent=*/false); 12131 if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_copyprivate && 12132 DVar.RefExpr) { 12133 Diag(ELoc, diag::err_omp_wrong_dsa) 12134 << getOpenMPClauseName(DVar.CKind) 12135 << getOpenMPClauseName(OMPC_copyprivate); 12136 reportOriginalDsa(*this, DSAStack, D, DVar); 12137 continue; 12138 } 12139 12140 // OpenMP [2.11.4.2, Restrictions, p.1] 12141 // All list items that appear in a copyprivate clause must be either 12142 // threadprivate or private in the enclosing context. 12143 if (DVar.CKind == OMPC_unknown) { 12144 DVar = DSAStack->getImplicitDSA(D, false); 12145 if (DVar.CKind == OMPC_shared) { 12146 Diag(ELoc, diag::err_omp_required_access) 12147 << getOpenMPClauseName(OMPC_copyprivate) 12148 << "threadprivate or private in the enclosing context"; 12149 reportOriginalDsa(*this, DSAStack, D, DVar); 12150 continue; 12151 } 12152 } 12153 } 12154 12155 // Variably modified types are not supported. 12156 if (!Type->isAnyPointerType() && Type->isVariablyModifiedType()) { 12157 Diag(ELoc, diag::err_omp_variably_modified_type_not_supported) 12158 << getOpenMPClauseName(OMPC_copyprivate) << Type 12159 << getOpenMPDirectiveName(DSAStack->getCurrentDirective()); 12160 bool IsDecl = 12161 !VD || 12162 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly; 12163 Diag(D->getLocation(), 12164 IsDecl ? diag::note_previous_decl : diag::note_defined_here) 12165 << D; 12166 continue; 12167 } 12168 12169 // OpenMP [2.14.4.1, Restrictions, C/C++, p.2] 12170 // A variable of class type (or array thereof) that appears in a 12171 // copyin clause requires an accessible, unambiguous copy assignment 12172 // operator for the class type. 12173 Type = Context.getBaseElementType(Type.getNonReferenceType()) 12174 .getUnqualifiedType(); 12175 VarDecl *SrcVD = 12176 buildVarDecl(*this, RefExpr->getBeginLoc(), Type, ".copyprivate.src", 12177 D->hasAttrs() ? &D->getAttrs() : nullptr); 12178 DeclRefExpr *PseudoSrcExpr = buildDeclRefExpr(*this, SrcVD, Type, ELoc); 12179 VarDecl *DstVD = 12180 buildVarDecl(*this, RefExpr->getBeginLoc(), Type, ".copyprivate.dst", 12181 D->hasAttrs() ? &D->getAttrs() : nullptr); 12182 DeclRefExpr *PseudoDstExpr = buildDeclRefExpr(*this, DstVD, Type, ELoc); 12183 ExprResult AssignmentOp = BuildBinOp( 12184 DSAStack->getCurScope(), ELoc, BO_Assign, PseudoDstExpr, PseudoSrcExpr); 12185 if (AssignmentOp.isInvalid()) 12186 continue; 12187 AssignmentOp = 12188 ActOnFinishFullExpr(AssignmentOp.get(), ELoc, /*DiscardedValue*/ false); 12189 if (AssignmentOp.isInvalid()) 12190 continue; 12191 12192 // No need to mark vars as copyprivate, they are already threadprivate or 12193 // implicitly private. 12194 assert(VD || isOpenMPCapturedDecl(D)); 12195 Vars.push_back( 12196 VD ? RefExpr->IgnoreParens() 12197 : buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/false)); 12198 SrcExprs.push_back(PseudoSrcExpr); 12199 DstExprs.push_back(PseudoDstExpr); 12200 AssignmentOps.push_back(AssignmentOp.get()); 12201 } 12202 12203 if (Vars.empty()) 12204 return nullptr; 12205 12206 return OMPCopyprivateClause::Create(Context, StartLoc, LParenLoc, EndLoc, 12207 Vars, SrcExprs, DstExprs, AssignmentOps); 12208 } 12209 12210 OMPClause *Sema::ActOnOpenMPFlushClause(ArrayRef<Expr *> VarList, 12211 SourceLocation StartLoc, 12212 SourceLocation LParenLoc, 12213 SourceLocation EndLoc) { 12214 if (VarList.empty()) 12215 return nullptr; 12216 12217 return OMPFlushClause::Create(Context, StartLoc, LParenLoc, EndLoc, VarList); 12218 } 12219 12220 OMPClause * 12221 Sema::ActOnOpenMPDependClause(OpenMPDependClauseKind DepKind, 12222 SourceLocation DepLoc, SourceLocation ColonLoc, 12223 ArrayRef<Expr *> VarList, SourceLocation StartLoc, 12224 SourceLocation LParenLoc, SourceLocation EndLoc) { 12225 if (DSAStack->getCurrentDirective() == OMPD_ordered && 12226 DepKind != OMPC_DEPEND_source && DepKind != OMPC_DEPEND_sink) { 12227 Diag(DepLoc, diag::err_omp_unexpected_clause_value) 12228 << "'source' or 'sink'" << getOpenMPClauseName(OMPC_depend); 12229 return nullptr; 12230 } 12231 if (DSAStack->getCurrentDirective() != OMPD_ordered && 12232 (DepKind == OMPC_DEPEND_unknown || DepKind == OMPC_DEPEND_source || 12233 DepKind == OMPC_DEPEND_sink)) { 12234 unsigned Except[] = {OMPC_DEPEND_source, OMPC_DEPEND_sink}; 12235 Diag(DepLoc, diag::err_omp_unexpected_clause_value) 12236 << getListOfPossibleValues(OMPC_depend, /*First=*/0, 12237 /*Last=*/OMPC_DEPEND_unknown, Except) 12238 << getOpenMPClauseName(OMPC_depend); 12239 return nullptr; 12240 } 12241 SmallVector<Expr *, 8> Vars; 12242 DSAStackTy::OperatorOffsetTy OpsOffs; 12243 llvm::APSInt DepCounter(/*BitWidth=*/32); 12244 llvm::APSInt TotalDepCount(/*BitWidth=*/32); 12245 if (DepKind == OMPC_DEPEND_sink || DepKind == OMPC_DEPEND_source) { 12246 if (const Expr *OrderedCountExpr = 12247 DSAStack->getParentOrderedRegionParam().first) { 12248 TotalDepCount = OrderedCountExpr->EvaluateKnownConstInt(Context); 12249 TotalDepCount.setIsUnsigned(/*Val=*/true); 12250 } 12251 } 12252 for (Expr *RefExpr : VarList) { 12253 assert(RefExpr && "NULL expr in OpenMP shared clause."); 12254 if (isa<DependentScopeDeclRefExpr>(RefExpr)) { 12255 // It will be analyzed later. 12256 Vars.push_back(RefExpr); 12257 continue; 12258 } 12259 12260 SourceLocation ELoc = RefExpr->getExprLoc(); 12261 Expr *SimpleExpr = RefExpr->IgnoreParenCasts(); 12262 if (DepKind == OMPC_DEPEND_sink) { 12263 if (DSAStack->getParentOrderedRegionParam().first && 12264 DepCounter >= TotalDepCount) { 12265 Diag(ELoc, diag::err_omp_depend_sink_unexpected_expr); 12266 continue; 12267 } 12268 ++DepCounter; 12269 // OpenMP [2.13.9, Summary] 12270 // depend(dependence-type : vec), where dependence-type is: 12271 // 'sink' and where vec is the iteration vector, which has the form: 12272 // x1 [+- d1], x2 [+- d2 ], . . . , xn [+- dn] 12273 // where n is the value specified by the ordered clause in the loop 12274 // directive, xi denotes the loop iteration variable of the i-th nested 12275 // loop associated with the loop directive, and di is a constant 12276 // non-negative integer. 12277 if (CurContext->isDependentContext()) { 12278 // It will be analyzed later. 12279 Vars.push_back(RefExpr); 12280 continue; 12281 } 12282 SimpleExpr = SimpleExpr->IgnoreImplicit(); 12283 OverloadedOperatorKind OOK = OO_None; 12284 SourceLocation OOLoc; 12285 Expr *LHS = SimpleExpr; 12286 Expr *RHS = nullptr; 12287 if (auto *BO = dyn_cast<BinaryOperator>(SimpleExpr)) { 12288 OOK = BinaryOperator::getOverloadedOperator(BO->getOpcode()); 12289 OOLoc = BO->getOperatorLoc(); 12290 LHS = BO->getLHS()->IgnoreParenImpCasts(); 12291 RHS = BO->getRHS()->IgnoreParenImpCasts(); 12292 } else if (auto *OCE = dyn_cast<CXXOperatorCallExpr>(SimpleExpr)) { 12293 OOK = OCE->getOperator(); 12294 OOLoc = OCE->getOperatorLoc(); 12295 LHS = OCE->getArg(/*Arg=*/0)->IgnoreParenImpCasts(); 12296 RHS = OCE->getArg(/*Arg=*/1)->IgnoreParenImpCasts(); 12297 } else if (auto *MCE = dyn_cast<CXXMemberCallExpr>(SimpleExpr)) { 12298 OOK = MCE->getMethodDecl() 12299 ->getNameInfo() 12300 .getName() 12301 .getCXXOverloadedOperator(); 12302 OOLoc = MCE->getCallee()->getExprLoc(); 12303 LHS = MCE->getImplicitObjectArgument()->IgnoreParenImpCasts(); 12304 RHS = MCE->getArg(/*Arg=*/0)->IgnoreParenImpCasts(); 12305 } 12306 SourceLocation ELoc; 12307 SourceRange ERange; 12308 auto Res = getPrivateItem(*this, LHS, ELoc, ERange); 12309 if (Res.second) { 12310 // It will be analyzed later. 12311 Vars.push_back(RefExpr); 12312 } 12313 ValueDecl *D = Res.first; 12314 if (!D) 12315 continue; 12316 12317 if (OOK != OO_Plus && OOK != OO_Minus && (RHS || OOK != OO_None)) { 12318 Diag(OOLoc, diag::err_omp_depend_sink_expected_plus_minus); 12319 continue; 12320 } 12321 if (RHS) { 12322 ExprResult RHSRes = VerifyPositiveIntegerConstantInClause( 12323 RHS, OMPC_depend, /*StrictlyPositive=*/false); 12324 if (RHSRes.isInvalid()) 12325 continue; 12326 } 12327 if (!CurContext->isDependentContext() && 12328 DSAStack->getParentOrderedRegionParam().first && 12329 DepCounter != DSAStack->isParentLoopControlVariable(D).first) { 12330 const ValueDecl *VD = 12331 DSAStack->getParentLoopControlVariable(DepCounter.getZExtValue()); 12332 if (VD) 12333 Diag(ELoc, diag::err_omp_depend_sink_expected_loop_iteration) 12334 << 1 << VD; 12335 else 12336 Diag(ELoc, diag::err_omp_depend_sink_expected_loop_iteration) << 0; 12337 continue; 12338 } 12339 OpsOffs.emplace_back(RHS, OOK); 12340 } else { 12341 auto *ASE = dyn_cast<ArraySubscriptExpr>(SimpleExpr); 12342 if (!RefExpr->IgnoreParenImpCasts()->isLValue() || 12343 (ASE && 12344 !ASE->getBase()->getType().getNonReferenceType()->isPointerType() && 12345 !ASE->getBase()->getType().getNonReferenceType()->isArrayType())) { 12346 Diag(ELoc, diag::err_omp_expected_addressable_lvalue_or_array_item) 12347 << RefExpr->getSourceRange(); 12348 continue; 12349 } 12350 bool Suppress = getDiagnostics().getSuppressAllDiagnostics(); 12351 getDiagnostics().setSuppressAllDiagnostics(/*Val=*/true); 12352 ExprResult Res = 12353 CreateBuiltinUnaryOp(ELoc, UO_AddrOf, RefExpr->IgnoreParenImpCasts()); 12354 getDiagnostics().setSuppressAllDiagnostics(Suppress); 12355 if (!Res.isUsable() && !isa<OMPArraySectionExpr>(SimpleExpr)) { 12356 Diag(ELoc, diag::err_omp_expected_addressable_lvalue_or_array_item) 12357 << RefExpr->getSourceRange(); 12358 continue; 12359 } 12360 } 12361 Vars.push_back(RefExpr->IgnoreParenImpCasts()); 12362 } 12363 12364 if (!CurContext->isDependentContext() && DepKind == OMPC_DEPEND_sink && 12365 TotalDepCount > VarList.size() && 12366 DSAStack->getParentOrderedRegionParam().first && 12367 DSAStack->getParentLoopControlVariable(VarList.size() + 1)) { 12368 Diag(EndLoc, diag::err_omp_depend_sink_expected_loop_iteration) 12369 << 1 << DSAStack->getParentLoopControlVariable(VarList.size() + 1); 12370 } 12371 if (DepKind != OMPC_DEPEND_source && DepKind != OMPC_DEPEND_sink && 12372 Vars.empty()) 12373 return nullptr; 12374 12375 auto *C = OMPDependClause::Create(Context, StartLoc, LParenLoc, EndLoc, 12376 DepKind, DepLoc, ColonLoc, Vars, 12377 TotalDepCount.getZExtValue()); 12378 if ((DepKind == OMPC_DEPEND_sink || DepKind == OMPC_DEPEND_source) && 12379 DSAStack->isParentOrderedRegion()) 12380 DSAStack->addDoacrossDependClause(C, OpsOffs); 12381 return C; 12382 } 12383 12384 OMPClause *Sema::ActOnOpenMPDeviceClause(Expr *Device, SourceLocation StartLoc, 12385 SourceLocation LParenLoc, 12386 SourceLocation EndLoc) { 12387 Expr *ValExpr = Device; 12388 Stmt *HelperValStmt = nullptr; 12389 12390 // OpenMP [2.9.1, Restrictions] 12391 // The device expression must evaluate to a non-negative integer value. 12392 if (!isNonNegativeIntegerValue(ValExpr, *this, OMPC_device, 12393 /*StrictlyPositive=*/false)) 12394 return nullptr; 12395 12396 OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective(); 12397 OpenMPDirectiveKind CaptureRegion = 12398 getOpenMPCaptureRegionForClause(DKind, OMPC_device); 12399 if (CaptureRegion != OMPD_unknown && !CurContext->isDependentContext()) { 12400 ValExpr = MakeFullExpr(ValExpr).get(); 12401 llvm::MapVector<const Expr *, DeclRefExpr *> Captures; 12402 ValExpr = tryBuildCapture(*this, ValExpr, Captures).get(); 12403 HelperValStmt = buildPreInits(Context, Captures); 12404 } 12405 12406 return new (Context) OMPDeviceClause(ValExpr, HelperValStmt, CaptureRegion, 12407 StartLoc, LParenLoc, EndLoc); 12408 } 12409 12410 static bool checkTypeMappable(SourceLocation SL, SourceRange SR, Sema &SemaRef, 12411 DSAStackTy *Stack, QualType QTy, 12412 bool FullCheck = true) { 12413 NamedDecl *ND; 12414 if (QTy->isIncompleteType(&ND)) { 12415 SemaRef.Diag(SL, diag::err_incomplete_type) << QTy << SR; 12416 return false; 12417 } 12418 if (FullCheck && !SemaRef.CurContext->isDependentContext() && 12419 !QTy.isTrivialType(SemaRef.Context)) 12420 SemaRef.Diag(SL, diag::warn_omp_non_trivial_type_mapped) << QTy << SR; 12421 return true; 12422 } 12423 12424 /// Return true if it can be proven that the provided array expression 12425 /// (array section or array subscript) does NOT specify the whole size of the 12426 /// array whose base type is \a BaseQTy. 12427 static bool checkArrayExpressionDoesNotReferToWholeSize(Sema &SemaRef, 12428 const Expr *E, 12429 QualType BaseQTy) { 12430 const auto *OASE = dyn_cast<OMPArraySectionExpr>(E); 12431 12432 // If this is an array subscript, it refers to the whole size if the size of 12433 // the dimension is constant and equals 1. Also, an array section assumes the 12434 // format of an array subscript if no colon is used. 12435 if (isa<ArraySubscriptExpr>(E) || (OASE && OASE->getColonLoc().isInvalid())) { 12436 if (const auto *ATy = dyn_cast<ConstantArrayType>(BaseQTy.getTypePtr())) 12437 return ATy->getSize().getSExtValue() != 1; 12438 // Size can't be evaluated statically. 12439 return false; 12440 } 12441 12442 assert(OASE && "Expecting array section if not an array subscript."); 12443 const Expr *LowerBound = OASE->getLowerBound(); 12444 const Expr *Length = OASE->getLength(); 12445 12446 // If there is a lower bound that does not evaluates to zero, we are not 12447 // covering the whole dimension. 12448 if (LowerBound) { 12449 Expr::EvalResult Result; 12450 if (!LowerBound->EvaluateAsInt(Result, SemaRef.getASTContext())) 12451 return false; // Can't get the integer value as a constant. 12452 12453 llvm::APSInt ConstLowerBound = Result.Val.getInt(); 12454 if (ConstLowerBound.getSExtValue()) 12455 return true; 12456 } 12457 12458 // If we don't have a length we covering the whole dimension. 12459 if (!Length) 12460 return false; 12461 12462 // If the base is a pointer, we don't have a way to get the size of the 12463 // pointee. 12464 if (BaseQTy->isPointerType()) 12465 return false; 12466 12467 // We can only check if the length is the same as the size of the dimension 12468 // if we have a constant array. 12469 const auto *CATy = dyn_cast<ConstantArrayType>(BaseQTy.getTypePtr()); 12470 if (!CATy) 12471 return false; 12472 12473 Expr::EvalResult Result; 12474 if (!Length->EvaluateAsInt(Result, SemaRef.getASTContext())) 12475 return false; // Can't get the integer value as a constant. 12476 12477 llvm::APSInt ConstLength = Result.Val.getInt(); 12478 return CATy->getSize().getSExtValue() != ConstLength.getSExtValue(); 12479 } 12480 12481 // Return true if it can be proven that the provided array expression (array 12482 // section or array subscript) does NOT specify a single element of the array 12483 // whose base type is \a BaseQTy. 12484 static bool checkArrayExpressionDoesNotReferToUnitySize(Sema &SemaRef, 12485 const Expr *E, 12486 QualType BaseQTy) { 12487 const auto *OASE = dyn_cast<OMPArraySectionExpr>(E); 12488 12489 // An array subscript always refer to a single element. Also, an array section 12490 // assumes the format of an array subscript if no colon is used. 12491 if (isa<ArraySubscriptExpr>(E) || (OASE && OASE->getColonLoc().isInvalid())) 12492 return false; 12493 12494 assert(OASE && "Expecting array section if not an array subscript."); 12495 const Expr *Length = OASE->getLength(); 12496 12497 // If we don't have a length we have to check if the array has unitary size 12498 // for this dimension. Also, we should always expect a length if the base type 12499 // is pointer. 12500 if (!Length) { 12501 if (const auto *ATy = dyn_cast<ConstantArrayType>(BaseQTy.getTypePtr())) 12502 return ATy->getSize().getSExtValue() != 1; 12503 // We cannot assume anything. 12504 return false; 12505 } 12506 12507 // Check if the length evaluates to 1. 12508 Expr::EvalResult Result; 12509 if (!Length->EvaluateAsInt(Result, SemaRef.getASTContext())) 12510 return false; // Can't get the integer value as a constant. 12511 12512 llvm::APSInt ConstLength = Result.Val.getInt(); 12513 return ConstLength.getSExtValue() != 1; 12514 } 12515 12516 // Return the expression of the base of the mappable expression or null if it 12517 // cannot be determined and do all the necessary checks to see if the expression 12518 // is valid as a standalone mappable expression. In the process, record all the 12519 // components of the expression. 12520 static const Expr *checkMapClauseExpressionBase( 12521 Sema &SemaRef, Expr *E, 12522 OMPClauseMappableExprCommon::MappableExprComponentList &CurComponents, 12523 OpenMPClauseKind CKind, bool NoDiagnose) { 12524 SourceLocation ELoc = E->getExprLoc(); 12525 SourceRange ERange = E->getSourceRange(); 12526 12527 // The base of elements of list in a map clause have to be either: 12528 // - a reference to variable or field. 12529 // - a member expression. 12530 // - an array expression. 12531 // 12532 // E.g. if we have the expression 'r.S.Arr[:12]', we want to retrieve the 12533 // reference to 'r'. 12534 // 12535 // If we have: 12536 // 12537 // struct SS { 12538 // Bla S; 12539 // foo() { 12540 // #pragma omp target map (S.Arr[:12]); 12541 // } 12542 // } 12543 // 12544 // We want to retrieve the member expression 'this->S'; 12545 12546 const Expr *RelevantExpr = nullptr; 12547 12548 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.2] 12549 // If a list item is an array section, it must specify contiguous storage. 12550 // 12551 // For this restriction it is sufficient that we make sure only references 12552 // to variables or fields and array expressions, and that no array sections 12553 // exist except in the rightmost expression (unless they cover the whole 12554 // dimension of the array). E.g. these would be invalid: 12555 // 12556 // r.ArrS[3:5].Arr[6:7] 12557 // 12558 // r.ArrS[3:5].x 12559 // 12560 // but these would be valid: 12561 // r.ArrS[3].Arr[6:7] 12562 // 12563 // r.ArrS[3].x 12564 12565 bool AllowUnitySizeArraySection = true; 12566 bool AllowWholeSizeArraySection = true; 12567 12568 while (!RelevantExpr) { 12569 E = E->IgnoreParenImpCasts(); 12570 12571 if (auto *CurE = dyn_cast<DeclRefExpr>(E)) { 12572 if (!isa<VarDecl>(CurE->getDecl())) 12573 return nullptr; 12574 12575 RelevantExpr = CurE; 12576 12577 // If we got a reference to a declaration, we should not expect any array 12578 // section before that. 12579 AllowUnitySizeArraySection = false; 12580 AllowWholeSizeArraySection = false; 12581 12582 // Record the component. 12583 CurComponents.emplace_back(CurE, CurE->getDecl()); 12584 } else if (auto *CurE = dyn_cast<MemberExpr>(E)) { 12585 Expr *BaseE = CurE->getBase()->IgnoreParenImpCasts(); 12586 12587 if (isa<CXXThisExpr>(BaseE)) 12588 // We found a base expression: this->Val. 12589 RelevantExpr = CurE; 12590 else 12591 E = BaseE; 12592 12593 if (!isa<FieldDecl>(CurE->getMemberDecl())) { 12594 if (!NoDiagnose) { 12595 SemaRef.Diag(ELoc, diag::err_omp_expected_access_to_data_field) 12596 << CurE->getSourceRange(); 12597 return nullptr; 12598 } 12599 if (RelevantExpr) 12600 return nullptr; 12601 continue; 12602 } 12603 12604 auto *FD = cast<FieldDecl>(CurE->getMemberDecl()); 12605 12606 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C/C++, p.3] 12607 // A bit-field cannot appear in a map clause. 12608 // 12609 if (FD->isBitField()) { 12610 if (!NoDiagnose) { 12611 SemaRef.Diag(ELoc, diag::err_omp_bit_fields_forbidden_in_clause) 12612 << CurE->getSourceRange() << getOpenMPClauseName(CKind); 12613 return nullptr; 12614 } 12615 if (RelevantExpr) 12616 return nullptr; 12617 continue; 12618 } 12619 12620 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C++, p.1] 12621 // If the type of a list item is a reference to a type T then the type 12622 // will be considered to be T for all purposes of this clause. 12623 QualType CurType = BaseE->getType().getNonReferenceType(); 12624 12625 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C/C++, p.2] 12626 // A list item cannot be a variable that is a member of a structure with 12627 // a union type. 12628 // 12629 if (CurType->isUnionType()) { 12630 if (!NoDiagnose) { 12631 SemaRef.Diag(ELoc, diag::err_omp_union_type_not_allowed) 12632 << CurE->getSourceRange(); 12633 return nullptr; 12634 } 12635 continue; 12636 } 12637 12638 // If we got a member expression, we should not expect any array section 12639 // before that: 12640 // 12641 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.7] 12642 // If a list item is an element of a structure, only the rightmost symbol 12643 // of the variable reference can be an array section. 12644 // 12645 AllowUnitySizeArraySection = false; 12646 AllowWholeSizeArraySection = false; 12647 12648 // Record the component. 12649 CurComponents.emplace_back(CurE, FD); 12650 } else if (auto *CurE = dyn_cast<ArraySubscriptExpr>(E)) { 12651 E = CurE->getBase()->IgnoreParenImpCasts(); 12652 12653 if (!E->getType()->isAnyPointerType() && !E->getType()->isArrayType()) { 12654 if (!NoDiagnose) { 12655 SemaRef.Diag(ELoc, diag::err_omp_expected_base_var_name) 12656 << 0 << CurE->getSourceRange(); 12657 return nullptr; 12658 } 12659 continue; 12660 } 12661 12662 // If we got an array subscript that express the whole dimension we 12663 // can have any array expressions before. If it only expressing part of 12664 // the dimension, we can only have unitary-size array expressions. 12665 if (checkArrayExpressionDoesNotReferToWholeSize(SemaRef, CurE, 12666 E->getType())) 12667 AllowWholeSizeArraySection = false; 12668 12669 if (const auto *TE = dyn_cast<CXXThisExpr>(E)) { 12670 Expr::EvalResult Result; 12671 if (CurE->getIdx()->EvaluateAsInt(Result, SemaRef.getASTContext())) { 12672 if (!Result.Val.getInt().isNullValue()) { 12673 SemaRef.Diag(CurE->getIdx()->getExprLoc(), 12674 diag::err_omp_invalid_map_this_expr); 12675 SemaRef.Diag(CurE->getIdx()->getExprLoc(), 12676 diag::note_omp_invalid_subscript_on_this_ptr_map); 12677 } 12678 } 12679 RelevantExpr = TE; 12680 } 12681 12682 // Record the component - we don't have any declaration associated. 12683 CurComponents.emplace_back(CurE, nullptr); 12684 } else if (auto *CurE = dyn_cast<OMPArraySectionExpr>(E)) { 12685 assert(!NoDiagnose && "Array sections cannot be implicitly mapped."); 12686 E = CurE->getBase()->IgnoreParenImpCasts(); 12687 12688 QualType CurType = 12689 OMPArraySectionExpr::getBaseOriginalType(E).getCanonicalType(); 12690 12691 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C++, p.1] 12692 // If the type of a list item is a reference to a type T then the type 12693 // will be considered to be T for all purposes of this clause. 12694 if (CurType->isReferenceType()) 12695 CurType = CurType->getPointeeType(); 12696 12697 bool IsPointer = CurType->isAnyPointerType(); 12698 12699 if (!IsPointer && !CurType->isArrayType()) { 12700 SemaRef.Diag(ELoc, diag::err_omp_expected_base_var_name) 12701 << 0 << CurE->getSourceRange(); 12702 return nullptr; 12703 } 12704 12705 bool NotWhole = 12706 checkArrayExpressionDoesNotReferToWholeSize(SemaRef, CurE, CurType); 12707 bool NotUnity = 12708 checkArrayExpressionDoesNotReferToUnitySize(SemaRef, CurE, CurType); 12709 12710 if (AllowWholeSizeArraySection) { 12711 // Any array section is currently allowed. Allowing a whole size array 12712 // section implies allowing a unity array section as well. 12713 // 12714 // If this array section refers to the whole dimension we can still 12715 // accept other array sections before this one, except if the base is a 12716 // pointer. Otherwise, only unitary sections are accepted. 12717 if (NotWhole || IsPointer) 12718 AllowWholeSizeArraySection = false; 12719 } else if (AllowUnitySizeArraySection && NotUnity) { 12720 // A unity or whole array section is not allowed and that is not 12721 // compatible with the properties of the current array section. 12722 SemaRef.Diag( 12723 ELoc, diag::err_array_section_does_not_specify_contiguous_storage) 12724 << CurE->getSourceRange(); 12725 return nullptr; 12726 } 12727 12728 if (const auto *TE = dyn_cast<CXXThisExpr>(E)) { 12729 Expr::EvalResult ResultR; 12730 Expr::EvalResult ResultL; 12731 if (CurE->getLength()->EvaluateAsInt(ResultR, 12732 SemaRef.getASTContext())) { 12733 if (!ResultR.Val.getInt().isOneValue()) { 12734 SemaRef.Diag(CurE->getLength()->getExprLoc(), 12735 diag::err_omp_invalid_map_this_expr); 12736 SemaRef.Diag(CurE->getLength()->getExprLoc(), 12737 diag::note_omp_invalid_length_on_this_ptr_mapping); 12738 } 12739 } 12740 if (CurE->getLowerBound() && CurE->getLowerBound()->EvaluateAsInt( 12741 ResultL, SemaRef.getASTContext())) { 12742 if (!ResultL.Val.getInt().isNullValue()) { 12743 SemaRef.Diag(CurE->getLowerBound()->getExprLoc(), 12744 diag::err_omp_invalid_map_this_expr); 12745 SemaRef.Diag(CurE->getLowerBound()->getExprLoc(), 12746 diag::note_omp_invalid_lower_bound_on_this_ptr_mapping); 12747 } 12748 } 12749 RelevantExpr = TE; 12750 } 12751 12752 // Record the component - we don't have any declaration associated. 12753 CurComponents.emplace_back(CurE, nullptr); 12754 } else { 12755 if (!NoDiagnose) { 12756 // If nothing else worked, this is not a valid map clause expression. 12757 SemaRef.Diag( 12758 ELoc, diag::err_omp_expected_named_var_member_or_array_expression) 12759 << ERange; 12760 } 12761 return nullptr; 12762 } 12763 } 12764 12765 return RelevantExpr; 12766 } 12767 12768 // Return true if expression E associated with value VD has conflicts with other 12769 // map information. 12770 static bool checkMapConflicts( 12771 Sema &SemaRef, DSAStackTy *DSAS, const ValueDecl *VD, const Expr *E, 12772 bool CurrentRegionOnly, 12773 OMPClauseMappableExprCommon::MappableExprComponentListRef CurComponents, 12774 OpenMPClauseKind CKind) { 12775 assert(VD && E); 12776 SourceLocation ELoc = E->getExprLoc(); 12777 SourceRange ERange = E->getSourceRange(); 12778 12779 // In order to easily check the conflicts we need to match each component of 12780 // the expression under test with the components of the expressions that are 12781 // already in the stack. 12782 12783 assert(!CurComponents.empty() && "Map clause expression with no components!"); 12784 assert(CurComponents.back().getAssociatedDeclaration() == VD && 12785 "Map clause expression with unexpected base!"); 12786 12787 // Variables to help detecting enclosing problems in data environment nests. 12788 bool IsEnclosedByDataEnvironmentExpr = false; 12789 const Expr *EnclosingExpr = nullptr; 12790 12791 bool FoundError = DSAS->checkMappableExprComponentListsForDecl( 12792 VD, CurrentRegionOnly, 12793 [&IsEnclosedByDataEnvironmentExpr, &SemaRef, VD, CurrentRegionOnly, ELoc, 12794 ERange, CKind, &EnclosingExpr, 12795 CurComponents](OMPClauseMappableExprCommon::MappableExprComponentListRef 12796 StackComponents, 12797 OpenMPClauseKind) { 12798 assert(!StackComponents.empty() && 12799 "Map clause expression with no components!"); 12800 assert(StackComponents.back().getAssociatedDeclaration() == VD && 12801 "Map clause expression with unexpected base!"); 12802 (void)VD; 12803 12804 // The whole expression in the stack. 12805 const Expr *RE = StackComponents.front().getAssociatedExpression(); 12806 12807 // Expressions must start from the same base. Here we detect at which 12808 // point both expressions diverge from each other and see if we can 12809 // detect if the memory referred to both expressions is contiguous and 12810 // do not overlap. 12811 auto CI = CurComponents.rbegin(); 12812 auto CE = CurComponents.rend(); 12813 auto SI = StackComponents.rbegin(); 12814 auto SE = StackComponents.rend(); 12815 for (; CI != CE && SI != SE; ++CI, ++SI) { 12816 12817 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.3] 12818 // At most one list item can be an array item derived from a given 12819 // variable in map clauses of the same construct. 12820 if (CurrentRegionOnly && 12821 (isa<ArraySubscriptExpr>(CI->getAssociatedExpression()) || 12822 isa<OMPArraySectionExpr>(CI->getAssociatedExpression())) && 12823 (isa<ArraySubscriptExpr>(SI->getAssociatedExpression()) || 12824 isa<OMPArraySectionExpr>(SI->getAssociatedExpression()))) { 12825 SemaRef.Diag(CI->getAssociatedExpression()->getExprLoc(), 12826 diag::err_omp_multiple_array_items_in_map_clause) 12827 << CI->getAssociatedExpression()->getSourceRange(); 12828 SemaRef.Diag(SI->getAssociatedExpression()->getExprLoc(), 12829 diag::note_used_here) 12830 << SI->getAssociatedExpression()->getSourceRange(); 12831 return true; 12832 } 12833 12834 // Do both expressions have the same kind? 12835 if (CI->getAssociatedExpression()->getStmtClass() != 12836 SI->getAssociatedExpression()->getStmtClass()) 12837 break; 12838 12839 // Are we dealing with different variables/fields? 12840 if (CI->getAssociatedDeclaration() != SI->getAssociatedDeclaration()) 12841 break; 12842 } 12843 // Check if the extra components of the expressions in the enclosing 12844 // data environment are redundant for the current base declaration. 12845 // If they are, the maps completely overlap, which is legal. 12846 for (; SI != SE; ++SI) { 12847 QualType Type; 12848 if (const auto *ASE = 12849 dyn_cast<ArraySubscriptExpr>(SI->getAssociatedExpression())) { 12850 Type = ASE->getBase()->IgnoreParenImpCasts()->getType(); 12851 } else if (const auto *OASE = dyn_cast<OMPArraySectionExpr>( 12852 SI->getAssociatedExpression())) { 12853 const Expr *E = OASE->getBase()->IgnoreParenImpCasts(); 12854 Type = 12855 OMPArraySectionExpr::getBaseOriginalType(E).getCanonicalType(); 12856 } 12857 if (Type.isNull() || Type->isAnyPointerType() || 12858 checkArrayExpressionDoesNotReferToWholeSize( 12859 SemaRef, SI->getAssociatedExpression(), Type)) 12860 break; 12861 } 12862 12863 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.4] 12864 // List items of map clauses in the same construct must not share 12865 // original storage. 12866 // 12867 // If the expressions are exactly the same or one is a subset of the 12868 // other, it means they are sharing storage. 12869 if (CI == CE && SI == SE) { 12870 if (CurrentRegionOnly) { 12871 if (CKind == OMPC_map) { 12872 SemaRef.Diag(ELoc, diag::err_omp_map_shared_storage) << ERange; 12873 } else { 12874 assert(CKind == OMPC_to || CKind == OMPC_from); 12875 SemaRef.Diag(ELoc, diag::err_omp_once_referenced_in_target_update) 12876 << ERange; 12877 } 12878 SemaRef.Diag(RE->getExprLoc(), diag::note_used_here) 12879 << RE->getSourceRange(); 12880 return true; 12881 } 12882 // If we find the same expression in the enclosing data environment, 12883 // that is legal. 12884 IsEnclosedByDataEnvironmentExpr = true; 12885 return false; 12886 } 12887 12888 QualType DerivedType = 12889 std::prev(CI)->getAssociatedDeclaration()->getType(); 12890 SourceLocation DerivedLoc = 12891 std::prev(CI)->getAssociatedExpression()->getExprLoc(); 12892 12893 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C++, p.1] 12894 // If the type of a list item is a reference to a type T then the type 12895 // will be considered to be T for all purposes of this clause. 12896 DerivedType = DerivedType.getNonReferenceType(); 12897 12898 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C/C++, p.1] 12899 // A variable for which the type is pointer and an array section 12900 // derived from that variable must not appear as list items of map 12901 // clauses of the same construct. 12902 // 12903 // Also, cover one of the cases in: 12904 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.5] 12905 // If any part of the original storage of a list item has corresponding 12906 // storage in the device data environment, all of the original storage 12907 // must have corresponding storage in the device data environment. 12908 // 12909 if (DerivedType->isAnyPointerType()) { 12910 if (CI == CE || SI == SE) { 12911 SemaRef.Diag( 12912 DerivedLoc, 12913 diag::err_omp_pointer_mapped_along_with_derived_section) 12914 << DerivedLoc; 12915 SemaRef.Diag(RE->getExprLoc(), diag::note_used_here) 12916 << RE->getSourceRange(); 12917 return true; 12918 } 12919 if (CI->getAssociatedExpression()->getStmtClass() != 12920 SI->getAssociatedExpression()->getStmtClass() || 12921 CI->getAssociatedDeclaration()->getCanonicalDecl() == 12922 SI->getAssociatedDeclaration()->getCanonicalDecl()) { 12923 assert(CI != CE && SI != SE); 12924 SemaRef.Diag(DerivedLoc, diag::err_omp_same_pointer_dereferenced) 12925 << DerivedLoc; 12926 SemaRef.Diag(RE->getExprLoc(), diag::note_used_here) 12927 << RE->getSourceRange(); 12928 return true; 12929 } 12930 } 12931 12932 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.4] 12933 // List items of map clauses in the same construct must not share 12934 // original storage. 12935 // 12936 // An expression is a subset of the other. 12937 if (CurrentRegionOnly && (CI == CE || SI == SE)) { 12938 if (CKind == OMPC_map) { 12939 if (CI != CE || SI != SE) { 12940 // Allow constructs like this: map(s, s.ptr[0:1]), where s.ptr is 12941 // a pointer. 12942 auto Begin = 12943 CI != CE ? CurComponents.begin() : StackComponents.begin(); 12944 auto End = CI != CE ? CurComponents.end() : StackComponents.end(); 12945 auto It = Begin; 12946 while (It != End && !It->getAssociatedDeclaration()) 12947 std::advance(It, 1); 12948 assert(It != End && 12949 "Expected at least one component with the declaration."); 12950 if (It != Begin && It->getAssociatedDeclaration() 12951 ->getType() 12952 .getCanonicalType() 12953 ->isAnyPointerType()) { 12954 IsEnclosedByDataEnvironmentExpr = false; 12955 EnclosingExpr = nullptr; 12956 return false; 12957 } 12958 } 12959 SemaRef.Diag(ELoc, diag::err_omp_map_shared_storage) << ERange; 12960 } else { 12961 assert(CKind == OMPC_to || CKind == OMPC_from); 12962 SemaRef.Diag(ELoc, diag::err_omp_once_referenced_in_target_update) 12963 << ERange; 12964 } 12965 SemaRef.Diag(RE->getExprLoc(), diag::note_used_here) 12966 << RE->getSourceRange(); 12967 return true; 12968 } 12969 12970 // The current expression uses the same base as other expression in the 12971 // data environment but does not contain it completely. 12972 if (!CurrentRegionOnly && SI != SE) 12973 EnclosingExpr = RE; 12974 12975 // The current expression is a subset of the expression in the data 12976 // environment. 12977 IsEnclosedByDataEnvironmentExpr |= 12978 (!CurrentRegionOnly && CI != CE && SI == SE); 12979 12980 return false; 12981 }); 12982 12983 if (CurrentRegionOnly) 12984 return FoundError; 12985 12986 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.5] 12987 // If any part of the original storage of a list item has corresponding 12988 // storage in the device data environment, all of the original storage must 12989 // have corresponding storage in the device data environment. 12990 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.6] 12991 // If a list item is an element of a structure, and a different element of 12992 // the structure has a corresponding list item in the device data environment 12993 // prior to a task encountering the construct associated with the map clause, 12994 // then the list item must also have a corresponding list item in the device 12995 // data environment prior to the task encountering the construct. 12996 // 12997 if (EnclosingExpr && !IsEnclosedByDataEnvironmentExpr) { 12998 SemaRef.Diag(ELoc, 12999 diag::err_omp_original_storage_is_shared_and_does_not_contain) 13000 << ERange; 13001 SemaRef.Diag(EnclosingExpr->getExprLoc(), diag::note_used_here) 13002 << EnclosingExpr->getSourceRange(); 13003 return true; 13004 } 13005 13006 return FoundError; 13007 } 13008 13009 // Look up the user-defined mapper given the mapper name and mapped type, and 13010 // build a reference to it. 13011 ExprResult buildUserDefinedMapperRef(Sema &SemaRef, Scope *S, 13012 CXXScopeSpec &MapperIdScopeSpec, 13013 const DeclarationNameInfo &MapperId, 13014 QualType Type, Expr *UnresolvedMapper) { 13015 if (MapperIdScopeSpec.isInvalid()) 13016 return ExprError(); 13017 // Find all user-defined mappers with the given MapperId. 13018 SmallVector<UnresolvedSet<8>, 4> Lookups; 13019 LookupResult Lookup(SemaRef, MapperId, Sema::LookupOMPMapperName); 13020 Lookup.suppressDiagnostics(); 13021 if (S) { 13022 while (S && SemaRef.LookupParsedName(Lookup, S, &MapperIdScopeSpec)) { 13023 NamedDecl *D = Lookup.getRepresentativeDecl(); 13024 while (S && !S->isDeclScope(D)) 13025 S = S->getParent(); 13026 if (S) 13027 S = S->getParent(); 13028 Lookups.emplace_back(); 13029 Lookups.back().append(Lookup.begin(), Lookup.end()); 13030 Lookup.clear(); 13031 } 13032 } else if (auto *ULE = cast_or_null<UnresolvedLookupExpr>(UnresolvedMapper)) { 13033 // Extract the user-defined mappers with the given MapperId. 13034 Lookups.push_back(UnresolvedSet<8>()); 13035 for (NamedDecl *D : ULE->decls()) { 13036 auto *DMD = cast<OMPDeclareMapperDecl>(D); 13037 assert(DMD && "Expect valid OMPDeclareMapperDecl during instantiation."); 13038 Lookups.back().addDecl(DMD); 13039 } 13040 } 13041 // Defer the lookup for dependent types. The results will be passed through 13042 // UnresolvedMapper on instantiation. 13043 if (SemaRef.CurContext->isDependentContext() || Type->isDependentType() || 13044 Type->isInstantiationDependentType() || 13045 Type->containsUnexpandedParameterPack() || 13046 filterLookupForUDReductionAndMapper<bool>(Lookups, [](ValueDecl *D) { 13047 return !D->isInvalidDecl() && 13048 (D->getType()->isDependentType() || 13049 D->getType()->isInstantiationDependentType() || 13050 D->getType()->containsUnexpandedParameterPack()); 13051 })) { 13052 UnresolvedSet<8> URS; 13053 for (const UnresolvedSet<8> &Set : Lookups) { 13054 if (Set.empty()) 13055 continue; 13056 URS.append(Set.begin(), Set.end()); 13057 } 13058 return UnresolvedLookupExpr::Create( 13059 SemaRef.Context, /*NamingClass=*/nullptr, 13060 MapperIdScopeSpec.getWithLocInContext(SemaRef.Context), MapperId, 13061 /*ADL=*/false, /*Overloaded=*/true, URS.begin(), URS.end()); 13062 } 13063 // [OpenMP 5.0], 2.19.7.3 declare mapper Directive, Restrictions 13064 // The type must be of struct, union or class type in C and C++ 13065 if (!Type->isStructureOrClassType() && !Type->isUnionType()) 13066 return ExprEmpty(); 13067 SourceLocation Loc = MapperId.getLoc(); 13068 // Perform argument dependent lookup. 13069 if (SemaRef.getLangOpts().CPlusPlus && !MapperIdScopeSpec.isSet()) 13070 argumentDependentLookup(SemaRef, MapperId, Loc, Type, Lookups); 13071 // Return the first user-defined mapper with the desired type. 13072 if (auto *VD = filterLookupForUDReductionAndMapper<ValueDecl *>( 13073 Lookups, [&SemaRef, Type](ValueDecl *D) -> ValueDecl * { 13074 if (!D->isInvalidDecl() && 13075 SemaRef.Context.hasSameType(D->getType(), Type)) 13076 return D; 13077 return nullptr; 13078 })) 13079 return SemaRef.BuildDeclRefExpr(VD, Type, VK_LValue, Loc); 13080 // Find the first user-defined mapper with a type derived from the desired 13081 // type. 13082 if (auto *VD = filterLookupForUDReductionAndMapper<ValueDecl *>( 13083 Lookups, [&SemaRef, Type, Loc](ValueDecl *D) -> ValueDecl * { 13084 if (!D->isInvalidDecl() && 13085 SemaRef.IsDerivedFrom(Loc, Type, D->getType()) && 13086 !Type.isMoreQualifiedThan(D->getType())) 13087 return D; 13088 return nullptr; 13089 })) { 13090 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true, 13091 /*DetectVirtual=*/false); 13092 if (SemaRef.IsDerivedFrom(Loc, Type, VD->getType(), Paths)) { 13093 if (!Paths.isAmbiguous(SemaRef.Context.getCanonicalType( 13094 VD->getType().getUnqualifiedType()))) { 13095 if (SemaRef.CheckBaseClassAccess( 13096 Loc, VD->getType(), Type, Paths.front(), 13097 /*DiagID=*/0) != Sema::AR_inaccessible) { 13098 return SemaRef.BuildDeclRefExpr(VD, Type, VK_LValue, Loc); 13099 } 13100 } 13101 } 13102 } 13103 // Report error if a mapper is specified, but cannot be found. 13104 if (MapperIdScopeSpec.isSet() || MapperId.getAsString() != "default") { 13105 SemaRef.Diag(Loc, diag::err_omp_invalid_mapper) 13106 << Type << MapperId.getName(); 13107 return ExprError(); 13108 } 13109 return ExprEmpty(); 13110 } 13111 13112 namespace { 13113 // Utility struct that gathers all the related lists associated with a mappable 13114 // expression. 13115 struct MappableVarListInfo { 13116 // The list of expressions. 13117 ArrayRef<Expr *> VarList; 13118 // The list of processed expressions. 13119 SmallVector<Expr *, 16> ProcessedVarList; 13120 // The mappble components for each expression. 13121 OMPClauseMappableExprCommon::MappableExprComponentLists VarComponents; 13122 // The base declaration of the variable. 13123 SmallVector<ValueDecl *, 16> VarBaseDeclarations; 13124 // The reference to the user-defined mapper associated with every expression. 13125 SmallVector<Expr *, 16> UDMapperList; 13126 13127 MappableVarListInfo(ArrayRef<Expr *> VarList) : VarList(VarList) { 13128 // We have a list of components and base declarations for each entry in the 13129 // variable list. 13130 VarComponents.reserve(VarList.size()); 13131 VarBaseDeclarations.reserve(VarList.size()); 13132 } 13133 }; 13134 } 13135 13136 // Check the validity of the provided variable list for the provided clause kind 13137 // \a CKind. In the check process the valid expressions, mappable expression 13138 // components, variables, and user-defined mappers are extracted and used to 13139 // fill \a ProcessedVarList, \a VarComponents, \a VarBaseDeclarations, and \a 13140 // UDMapperList in MVLI. \a MapType, \a IsMapTypeImplicit, \a MapperIdScopeSpec, 13141 // and \a MapperId are expected to be valid if the clause kind is 'map'. 13142 static void checkMappableExpressionList( 13143 Sema &SemaRef, DSAStackTy *DSAS, OpenMPClauseKind CKind, 13144 MappableVarListInfo &MVLI, SourceLocation StartLoc, 13145 CXXScopeSpec &MapperIdScopeSpec, DeclarationNameInfo MapperId, 13146 ArrayRef<Expr *> UnresolvedMappers, 13147 OpenMPMapClauseKind MapType = OMPC_MAP_unknown, 13148 bool IsMapTypeImplicit = false) { 13149 // We only expect mappable expressions in 'to', 'from', and 'map' clauses. 13150 assert((CKind == OMPC_map || CKind == OMPC_to || CKind == OMPC_from) && 13151 "Unexpected clause kind with mappable expressions!"); 13152 13153 // If the identifier of user-defined mapper is not specified, it is "default". 13154 // We do not change the actual name in this clause to distinguish whether a 13155 // mapper is specified explicitly, i.e., it is not explicitly specified when 13156 // MapperId.getName() is empty. 13157 if (!MapperId.getName() || MapperId.getName().isEmpty()) { 13158 auto &DeclNames = SemaRef.getASTContext().DeclarationNames; 13159 MapperId.setName(DeclNames.getIdentifier( 13160 &SemaRef.getASTContext().Idents.get("default"))); 13161 } 13162 13163 // Iterators to find the current unresolved mapper expression. 13164 auto UMIt = UnresolvedMappers.begin(), UMEnd = UnresolvedMappers.end(); 13165 bool UpdateUMIt = false; 13166 Expr *UnresolvedMapper = nullptr; 13167 13168 // Keep track of the mappable components and base declarations in this clause. 13169 // Each entry in the list is going to have a list of components associated. We 13170 // record each set of the components so that we can build the clause later on. 13171 // In the end we should have the same amount of declarations and component 13172 // lists. 13173 13174 for (Expr *RE : MVLI.VarList) { 13175 assert(RE && "Null expr in omp to/from/map clause"); 13176 SourceLocation ELoc = RE->getExprLoc(); 13177 13178 // Find the current unresolved mapper expression. 13179 if (UpdateUMIt && UMIt != UMEnd) { 13180 UMIt++; 13181 assert( 13182 UMIt != UMEnd && 13183 "Expect the size of UnresolvedMappers to match with that of VarList"); 13184 } 13185 UpdateUMIt = true; 13186 if (UMIt != UMEnd) 13187 UnresolvedMapper = *UMIt; 13188 13189 const Expr *VE = RE->IgnoreParenLValueCasts(); 13190 13191 if (VE->isValueDependent() || VE->isTypeDependent() || 13192 VE->isInstantiationDependent() || 13193 VE->containsUnexpandedParameterPack()) { 13194 // Try to find the associated user-defined mapper. 13195 ExprResult ER = buildUserDefinedMapperRef( 13196 SemaRef, DSAS->getCurScope(), MapperIdScopeSpec, MapperId, 13197 VE->getType().getCanonicalType(), UnresolvedMapper); 13198 if (ER.isInvalid()) 13199 continue; 13200 MVLI.UDMapperList.push_back(ER.get()); 13201 // We can only analyze this information once the missing information is 13202 // resolved. 13203 MVLI.ProcessedVarList.push_back(RE); 13204 continue; 13205 } 13206 13207 Expr *SimpleExpr = RE->IgnoreParenCasts(); 13208 13209 if (!RE->IgnoreParenImpCasts()->isLValue()) { 13210 SemaRef.Diag(ELoc, 13211 diag::err_omp_expected_named_var_member_or_array_expression) 13212 << RE->getSourceRange(); 13213 continue; 13214 } 13215 13216 OMPClauseMappableExprCommon::MappableExprComponentList CurComponents; 13217 ValueDecl *CurDeclaration = nullptr; 13218 13219 // Obtain the array or member expression bases if required. Also, fill the 13220 // components array with all the components identified in the process. 13221 const Expr *BE = checkMapClauseExpressionBase( 13222 SemaRef, SimpleExpr, CurComponents, CKind, /*NoDiagnose=*/false); 13223 if (!BE) 13224 continue; 13225 13226 assert(!CurComponents.empty() && 13227 "Invalid mappable expression information."); 13228 13229 if (const auto *TE = dyn_cast<CXXThisExpr>(BE)) { 13230 // Add store "this" pointer to class in DSAStackTy for future checking 13231 DSAS->addMappedClassesQualTypes(TE->getType()); 13232 // Try to find the associated user-defined mapper. 13233 ExprResult ER = buildUserDefinedMapperRef( 13234 SemaRef, DSAS->getCurScope(), MapperIdScopeSpec, MapperId, 13235 VE->getType().getCanonicalType(), UnresolvedMapper); 13236 if (ER.isInvalid()) 13237 continue; 13238 MVLI.UDMapperList.push_back(ER.get()); 13239 // Skip restriction checking for variable or field declarations 13240 MVLI.ProcessedVarList.push_back(RE); 13241 MVLI.VarComponents.resize(MVLI.VarComponents.size() + 1); 13242 MVLI.VarComponents.back().append(CurComponents.begin(), 13243 CurComponents.end()); 13244 MVLI.VarBaseDeclarations.push_back(nullptr); 13245 continue; 13246 } 13247 13248 // For the following checks, we rely on the base declaration which is 13249 // expected to be associated with the last component. The declaration is 13250 // expected to be a variable or a field (if 'this' is being mapped). 13251 CurDeclaration = CurComponents.back().getAssociatedDeclaration(); 13252 assert(CurDeclaration && "Null decl on map clause."); 13253 assert( 13254 CurDeclaration->isCanonicalDecl() && 13255 "Expecting components to have associated only canonical declarations."); 13256 13257 auto *VD = dyn_cast<VarDecl>(CurDeclaration); 13258 const auto *FD = dyn_cast<FieldDecl>(CurDeclaration); 13259 13260 assert((VD || FD) && "Only variables or fields are expected here!"); 13261 (void)FD; 13262 13263 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.10] 13264 // threadprivate variables cannot appear in a map clause. 13265 // OpenMP 4.5 [2.10.5, target update Construct] 13266 // threadprivate variables cannot appear in a from clause. 13267 if (VD && DSAS->isThreadPrivate(VD)) { 13268 DSAStackTy::DSAVarData DVar = DSAS->getTopDSA(VD, /*FromParent=*/false); 13269 SemaRef.Diag(ELoc, diag::err_omp_threadprivate_in_clause) 13270 << getOpenMPClauseName(CKind); 13271 reportOriginalDsa(SemaRef, DSAS, VD, DVar); 13272 continue; 13273 } 13274 13275 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.9] 13276 // A list item cannot appear in both a map clause and a data-sharing 13277 // attribute clause on the same construct. 13278 13279 // Check conflicts with other map clause expressions. We check the conflicts 13280 // with the current construct separately from the enclosing data 13281 // environment, because the restrictions are different. We only have to 13282 // check conflicts across regions for the map clauses. 13283 if (checkMapConflicts(SemaRef, DSAS, CurDeclaration, SimpleExpr, 13284 /*CurrentRegionOnly=*/true, CurComponents, CKind)) 13285 break; 13286 if (CKind == OMPC_map && 13287 checkMapConflicts(SemaRef, DSAS, CurDeclaration, SimpleExpr, 13288 /*CurrentRegionOnly=*/false, CurComponents, CKind)) 13289 break; 13290 13291 // OpenMP 4.5 [2.10.5, target update Construct] 13292 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C++, p.1] 13293 // If the type of a list item is a reference to a type T then the type will 13294 // be considered to be T for all purposes of this clause. 13295 auto I = llvm::find_if( 13296 CurComponents, 13297 [](const OMPClauseMappableExprCommon::MappableComponent &MC) { 13298 return MC.getAssociatedDeclaration(); 13299 }); 13300 assert(I != CurComponents.end() && "Null decl on map clause."); 13301 QualType Type = 13302 I->getAssociatedDeclaration()->getType().getNonReferenceType(); 13303 13304 // OpenMP 4.5 [2.10.5, target update Construct, Restrictions, p.4] 13305 // A list item in a to or from clause must have a mappable type. 13306 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.9] 13307 // A list item must have a mappable type. 13308 if (!checkTypeMappable(VE->getExprLoc(), VE->getSourceRange(), SemaRef, 13309 DSAS, Type)) 13310 continue; 13311 13312 if (CKind == OMPC_map) { 13313 // target enter data 13314 // OpenMP [2.10.2, Restrictions, p. 99] 13315 // A map-type must be specified in all map clauses and must be either 13316 // to or alloc. 13317 OpenMPDirectiveKind DKind = DSAS->getCurrentDirective(); 13318 if (DKind == OMPD_target_enter_data && 13319 !(MapType == OMPC_MAP_to || MapType == OMPC_MAP_alloc)) { 13320 SemaRef.Diag(StartLoc, diag::err_omp_invalid_map_type_for_directive) 13321 << (IsMapTypeImplicit ? 1 : 0) 13322 << getOpenMPSimpleClauseTypeName(OMPC_map, MapType) 13323 << getOpenMPDirectiveName(DKind); 13324 continue; 13325 } 13326 13327 // target exit_data 13328 // OpenMP [2.10.3, Restrictions, p. 102] 13329 // A map-type must be specified in all map clauses and must be either 13330 // from, release, or delete. 13331 if (DKind == OMPD_target_exit_data && 13332 !(MapType == OMPC_MAP_from || MapType == OMPC_MAP_release || 13333 MapType == OMPC_MAP_delete)) { 13334 SemaRef.Diag(StartLoc, diag::err_omp_invalid_map_type_for_directive) 13335 << (IsMapTypeImplicit ? 1 : 0) 13336 << getOpenMPSimpleClauseTypeName(OMPC_map, MapType) 13337 << getOpenMPDirectiveName(DKind); 13338 continue; 13339 } 13340 13341 // OpenMP 4.5 [2.15.5.1, Restrictions, p.3] 13342 // A list item cannot appear in both a map clause and a data-sharing 13343 // attribute clause on the same construct 13344 if (VD && isOpenMPTargetExecutionDirective(DKind)) { 13345 DSAStackTy::DSAVarData DVar = DSAS->getTopDSA(VD, /*FromParent=*/false); 13346 if (isOpenMPPrivate(DVar.CKind)) { 13347 SemaRef.Diag(ELoc, diag::err_omp_variable_in_given_clause_and_dsa) 13348 << getOpenMPClauseName(DVar.CKind) 13349 << getOpenMPClauseName(OMPC_map) 13350 << getOpenMPDirectiveName(DSAS->getCurrentDirective()); 13351 reportOriginalDsa(SemaRef, DSAS, CurDeclaration, DVar); 13352 continue; 13353 } 13354 } 13355 } 13356 13357 // Try to find the associated user-defined mapper. 13358 ExprResult ER = buildUserDefinedMapperRef( 13359 SemaRef, DSAS->getCurScope(), MapperIdScopeSpec, MapperId, 13360 Type.getCanonicalType(), UnresolvedMapper); 13361 if (ER.isInvalid()) 13362 continue; 13363 MVLI.UDMapperList.push_back(ER.get()); 13364 13365 // Save the current expression. 13366 MVLI.ProcessedVarList.push_back(RE); 13367 13368 // Store the components in the stack so that they can be used to check 13369 // against other clauses later on. 13370 DSAS->addMappableExpressionComponents(CurDeclaration, CurComponents, 13371 /*WhereFoundClauseKind=*/OMPC_map); 13372 13373 // Save the components and declaration to create the clause. For purposes of 13374 // the clause creation, any component list that has has base 'this' uses 13375 // null as base declaration. 13376 MVLI.VarComponents.resize(MVLI.VarComponents.size() + 1); 13377 MVLI.VarComponents.back().append(CurComponents.begin(), 13378 CurComponents.end()); 13379 MVLI.VarBaseDeclarations.push_back(isa<MemberExpr>(BE) ? nullptr 13380 : CurDeclaration); 13381 } 13382 } 13383 13384 OMPClause *Sema::ActOnOpenMPMapClause( 13385 ArrayRef<OpenMPMapModifierKind> MapTypeModifiers, 13386 ArrayRef<SourceLocation> MapTypeModifiersLoc, 13387 CXXScopeSpec &MapperIdScopeSpec, DeclarationNameInfo &MapperId, 13388 OpenMPMapClauseKind MapType, bool IsMapTypeImplicit, SourceLocation MapLoc, 13389 SourceLocation ColonLoc, ArrayRef<Expr *> VarList, 13390 const OMPVarListLocTy &Locs, ArrayRef<Expr *> UnresolvedMappers) { 13391 OpenMPMapModifierKind Modifiers[] = {OMPC_MAP_MODIFIER_unknown, 13392 OMPC_MAP_MODIFIER_unknown, 13393 OMPC_MAP_MODIFIER_unknown}; 13394 SourceLocation ModifiersLoc[OMPMapClause::NumberOfModifiers]; 13395 13396 // Process map-type-modifiers, flag errors for duplicate modifiers. 13397 unsigned Count = 0; 13398 for (unsigned I = 0, E = MapTypeModifiers.size(); I < E; ++I) { 13399 if (MapTypeModifiers[I] != OMPC_MAP_MODIFIER_unknown && 13400 llvm::find(Modifiers, MapTypeModifiers[I]) != std::end(Modifiers)) { 13401 Diag(MapTypeModifiersLoc[I], diag::err_omp_duplicate_map_type_modifier); 13402 continue; 13403 } 13404 assert(Count < OMPMapClause::NumberOfModifiers && 13405 "Modifiers exceed the allowed number of map type modifiers"); 13406 Modifiers[Count] = MapTypeModifiers[I]; 13407 ModifiersLoc[Count] = MapTypeModifiersLoc[I]; 13408 ++Count; 13409 } 13410 13411 MappableVarListInfo MVLI(VarList); 13412 checkMappableExpressionList(*this, DSAStack, OMPC_map, MVLI, Locs.StartLoc, 13413 MapperIdScopeSpec, MapperId, UnresolvedMappers, 13414 MapType, IsMapTypeImplicit); 13415 13416 // We need to produce a map clause even if we don't have variables so that 13417 // other diagnostics related with non-existing map clauses are accurate. 13418 return OMPMapClause::Create(Context, Locs, MVLI.ProcessedVarList, 13419 MVLI.VarBaseDeclarations, MVLI.VarComponents, 13420 MVLI.UDMapperList, Modifiers, ModifiersLoc, 13421 MapperIdScopeSpec.getWithLocInContext(Context), 13422 MapperId, MapType, IsMapTypeImplicit, MapLoc); 13423 } 13424 13425 QualType Sema::ActOnOpenMPDeclareReductionType(SourceLocation TyLoc, 13426 TypeResult ParsedType) { 13427 assert(ParsedType.isUsable()); 13428 13429 QualType ReductionType = GetTypeFromParser(ParsedType.get()); 13430 if (ReductionType.isNull()) 13431 return QualType(); 13432 13433 // [OpenMP 4.0], 2.15 declare reduction Directive, Restrictions, C\C++ 13434 // A type name in a declare reduction directive cannot be a function type, an 13435 // array type, a reference type, or a type qualified with const, volatile or 13436 // restrict. 13437 if (ReductionType.hasQualifiers()) { 13438 Diag(TyLoc, diag::err_omp_reduction_wrong_type) << 0; 13439 return QualType(); 13440 } 13441 13442 if (ReductionType->isFunctionType()) { 13443 Diag(TyLoc, diag::err_omp_reduction_wrong_type) << 1; 13444 return QualType(); 13445 } 13446 if (ReductionType->isReferenceType()) { 13447 Diag(TyLoc, diag::err_omp_reduction_wrong_type) << 2; 13448 return QualType(); 13449 } 13450 if (ReductionType->isArrayType()) { 13451 Diag(TyLoc, diag::err_omp_reduction_wrong_type) << 3; 13452 return QualType(); 13453 } 13454 return ReductionType; 13455 } 13456 13457 Sema::DeclGroupPtrTy Sema::ActOnOpenMPDeclareReductionDirectiveStart( 13458 Scope *S, DeclContext *DC, DeclarationName Name, 13459 ArrayRef<std::pair<QualType, SourceLocation>> ReductionTypes, 13460 AccessSpecifier AS, Decl *PrevDeclInScope) { 13461 SmallVector<Decl *, 8> Decls; 13462 Decls.reserve(ReductionTypes.size()); 13463 13464 LookupResult Lookup(*this, Name, SourceLocation(), LookupOMPReductionName, 13465 forRedeclarationInCurContext()); 13466 // [OpenMP 4.0], 2.15 declare reduction Directive, Restrictions 13467 // A reduction-identifier may not be re-declared in the current scope for the 13468 // same type or for a type that is compatible according to the base language 13469 // rules. 13470 llvm::DenseMap<QualType, SourceLocation> PreviousRedeclTypes; 13471 OMPDeclareReductionDecl *PrevDRD = nullptr; 13472 bool InCompoundScope = true; 13473 if (S != nullptr) { 13474 // Find previous declaration with the same name not referenced in other 13475 // declarations. 13476 FunctionScopeInfo *ParentFn = getEnclosingFunction(); 13477 InCompoundScope = 13478 (ParentFn != nullptr) && !ParentFn->CompoundScopes.empty(); 13479 LookupName(Lookup, S); 13480 FilterLookupForScope(Lookup, DC, S, /*ConsiderLinkage=*/false, 13481 /*AllowInlineNamespace=*/false); 13482 llvm::DenseMap<OMPDeclareReductionDecl *, bool> UsedAsPrevious; 13483 LookupResult::Filter Filter = Lookup.makeFilter(); 13484 while (Filter.hasNext()) { 13485 auto *PrevDecl = cast<OMPDeclareReductionDecl>(Filter.next()); 13486 if (InCompoundScope) { 13487 auto I = UsedAsPrevious.find(PrevDecl); 13488 if (I == UsedAsPrevious.end()) 13489 UsedAsPrevious[PrevDecl] = false; 13490 if (OMPDeclareReductionDecl *D = PrevDecl->getPrevDeclInScope()) 13491 UsedAsPrevious[D] = true; 13492 } 13493 PreviousRedeclTypes[PrevDecl->getType().getCanonicalType()] = 13494 PrevDecl->getLocation(); 13495 } 13496 Filter.done(); 13497 if (InCompoundScope) { 13498 for (const auto &PrevData : UsedAsPrevious) { 13499 if (!PrevData.second) { 13500 PrevDRD = PrevData.first; 13501 break; 13502 } 13503 } 13504 } 13505 } else if (PrevDeclInScope != nullptr) { 13506 auto *PrevDRDInScope = PrevDRD = 13507 cast<OMPDeclareReductionDecl>(PrevDeclInScope); 13508 do { 13509 PreviousRedeclTypes[PrevDRDInScope->getType().getCanonicalType()] = 13510 PrevDRDInScope->getLocation(); 13511 PrevDRDInScope = PrevDRDInScope->getPrevDeclInScope(); 13512 } while (PrevDRDInScope != nullptr); 13513 } 13514 for (const auto &TyData : ReductionTypes) { 13515 const auto I = PreviousRedeclTypes.find(TyData.first.getCanonicalType()); 13516 bool Invalid = false; 13517 if (I != PreviousRedeclTypes.end()) { 13518 Diag(TyData.second, diag::err_omp_declare_reduction_redefinition) 13519 << TyData.first; 13520 Diag(I->second, diag::note_previous_definition); 13521 Invalid = true; 13522 } 13523 PreviousRedeclTypes[TyData.first.getCanonicalType()] = TyData.second; 13524 auto *DRD = OMPDeclareReductionDecl::Create(Context, DC, TyData.second, 13525 Name, TyData.first, PrevDRD); 13526 DC->addDecl(DRD); 13527 DRD->setAccess(AS); 13528 Decls.push_back(DRD); 13529 if (Invalid) 13530 DRD->setInvalidDecl(); 13531 else 13532 PrevDRD = DRD; 13533 } 13534 13535 return DeclGroupPtrTy::make( 13536 DeclGroupRef::Create(Context, Decls.begin(), Decls.size())); 13537 } 13538 13539 void Sema::ActOnOpenMPDeclareReductionCombinerStart(Scope *S, Decl *D) { 13540 auto *DRD = cast<OMPDeclareReductionDecl>(D); 13541 13542 // Enter new function scope. 13543 PushFunctionScope(); 13544 setFunctionHasBranchProtectedScope(); 13545 getCurFunction()->setHasOMPDeclareReductionCombiner(); 13546 13547 if (S != nullptr) 13548 PushDeclContext(S, DRD); 13549 else 13550 CurContext = DRD; 13551 13552 PushExpressionEvaluationContext( 13553 ExpressionEvaluationContext::PotentiallyEvaluated); 13554 13555 QualType ReductionType = DRD->getType(); 13556 // Create 'T* omp_parm;T omp_in;'. All references to 'omp_in' will 13557 // be replaced by '*omp_parm' during codegen. This required because 'omp_in' 13558 // uses semantics of argument handles by value, but it should be passed by 13559 // reference. C lang does not support references, so pass all parameters as 13560 // pointers. 13561 // Create 'T omp_in;' variable. 13562 VarDecl *OmpInParm = 13563 buildVarDecl(*this, D->getLocation(), ReductionType, "omp_in"); 13564 // Create 'T* omp_parm;T omp_out;'. All references to 'omp_out' will 13565 // be replaced by '*omp_parm' during codegen. This required because 'omp_out' 13566 // uses semantics of argument handles by value, but it should be passed by 13567 // reference. C lang does not support references, so pass all parameters as 13568 // pointers. 13569 // Create 'T omp_out;' variable. 13570 VarDecl *OmpOutParm = 13571 buildVarDecl(*this, D->getLocation(), ReductionType, "omp_out"); 13572 if (S != nullptr) { 13573 PushOnScopeChains(OmpInParm, S); 13574 PushOnScopeChains(OmpOutParm, S); 13575 } else { 13576 DRD->addDecl(OmpInParm); 13577 DRD->addDecl(OmpOutParm); 13578 } 13579 Expr *InE = 13580 ::buildDeclRefExpr(*this, OmpInParm, ReductionType, D->getLocation()); 13581 Expr *OutE = 13582 ::buildDeclRefExpr(*this, OmpOutParm, ReductionType, D->getLocation()); 13583 DRD->setCombinerData(InE, OutE); 13584 } 13585 13586 void Sema::ActOnOpenMPDeclareReductionCombinerEnd(Decl *D, Expr *Combiner) { 13587 auto *DRD = cast<OMPDeclareReductionDecl>(D); 13588 DiscardCleanupsInEvaluationContext(); 13589 PopExpressionEvaluationContext(); 13590 13591 PopDeclContext(); 13592 PopFunctionScopeInfo(); 13593 13594 if (Combiner != nullptr) 13595 DRD->setCombiner(Combiner); 13596 else 13597 DRD->setInvalidDecl(); 13598 } 13599 13600 VarDecl *Sema::ActOnOpenMPDeclareReductionInitializerStart(Scope *S, Decl *D) { 13601 auto *DRD = cast<OMPDeclareReductionDecl>(D); 13602 13603 // Enter new function scope. 13604 PushFunctionScope(); 13605 setFunctionHasBranchProtectedScope(); 13606 13607 if (S != nullptr) 13608 PushDeclContext(S, DRD); 13609 else 13610 CurContext = DRD; 13611 13612 PushExpressionEvaluationContext( 13613 ExpressionEvaluationContext::PotentiallyEvaluated); 13614 13615 QualType ReductionType = DRD->getType(); 13616 // Create 'T* omp_parm;T omp_priv;'. All references to 'omp_priv' will 13617 // be replaced by '*omp_parm' during codegen. This required because 'omp_priv' 13618 // uses semantics of argument handles by value, but it should be passed by 13619 // reference. C lang does not support references, so pass all parameters as 13620 // pointers. 13621 // Create 'T omp_priv;' variable. 13622 VarDecl *OmpPrivParm = 13623 buildVarDecl(*this, D->getLocation(), ReductionType, "omp_priv"); 13624 // Create 'T* omp_parm;T omp_orig;'. All references to 'omp_orig' will 13625 // be replaced by '*omp_parm' during codegen. This required because 'omp_orig' 13626 // uses semantics of argument handles by value, but it should be passed by 13627 // reference. C lang does not support references, so pass all parameters as 13628 // pointers. 13629 // Create 'T omp_orig;' variable. 13630 VarDecl *OmpOrigParm = 13631 buildVarDecl(*this, D->getLocation(), ReductionType, "omp_orig"); 13632 if (S != nullptr) { 13633 PushOnScopeChains(OmpPrivParm, S); 13634 PushOnScopeChains(OmpOrigParm, S); 13635 } else { 13636 DRD->addDecl(OmpPrivParm); 13637 DRD->addDecl(OmpOrigParm); 13638 } 13639 Expr *OrigE = 13640 ::buildDeclRefExpr(*this, OmpOrigParm, ReductionType, D->getLocation()); 13641 Expr *PrivE = 13642 ::buildDeclRefExpr(*this, OmpPrivParm, ReductionType, D->getLocation()); 13643 DRD->setInitializerData(OrigE, PrivE); 13644 return OmpPrivParm; 13645 } 13646 13647 void Sema::ActOnOpenMPDeclareReductionInitializerEnd(Decl *D, Expr *Initializer, 13648 VarDecl *OmpPrivParm) { 13649 auto *DRD = cast<OMPDeclareReductionDecl>(D); 13650 DiscardCleanupsInEvaluationContext(); 13651 PopExpressionEvaluationContext(); 13652 13653 PopDeclContext(); 13654 PopFunctionScopeInfo(); 13655 13656 if (Initializer != nullptr) { 13657 DRD->setInitializer(Initializer, OMPDeclareReductionDecl::CallInit); 13658 } else if (OmpPrivParm->hasInit()) { 13659 DRD->setInitializer(OmpPrivParm->getInit(), 13660 OmpPrivParm->isDirectInit() 13661 ? OMPDeclareReductionDecl::DirectInit 13662 : OMPDeclareReductionDecl::CopyInit); 13663 } else { 13664 DRD->setInvalidDecl(); 13665 } 13666 } 13667 13668 Sema::DeclGroupPtrTy Sema::ActOnOpenMPDeclareReductionDirectiveEnd( 13669 Scope *S, DeclGroupPtrTy DeclReductions, bool IsValid) { 13670 for (Decl *D : DeclReductions.get()) { 13671 if (IsValid) { 13672 if (S) 13673 PushOnScopeChains(cast<OMPDeclareReductionDecl>(D), S, 13674 /*AddToContext=*/false); 13675 } else { 13676 D->setInvalidDecl(); 13677 } 13678 } 13679 return DeclReductions; 13680 } 13681 13682 TypeResult Sema::ActOnOpenMPDeclareMapperVarDecl(Scope *S, Declarator &D) { 13683 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); 13684 QualType T = TInfo->getType(); 13685 if (D.isInvalidType()) 13686 return true; 13687 13688 if (getLangOpts().CPlusPlus) { 13689 // Check that there are no default arguments (C++ only). 13690 CheckExtraCXXDefaultArguments(D); 13691 } 13692 13693 return CreateParsedType(T, TInfo); 13694 } 13695 13696 QualType Sema::ActOnOpenMPDeclareMapperType(SourceLocation TyLoc, 13697 TypeResult ParsedType) { 13698 assert(ParsedType.isUsable() && "Expect usable parsed mapper type"); 13699 13700 QualType MapperType = GetTypeFromParser(ParsedType.get()); 13701 assert(!MapperType.isNull() && "Expect valid mapper type"); 13702 13703 // [OpenMP 5.0], 2.19.7.3 declare mapper Directive, Restrictions 13704 // The type must be of struct, union or class type in C and C++ 13705 if (!MapperType->isStructureOrClassType() && !MapperType->isUnionType()) { 13706 Diag(TyLoc, diag::err_omp_mapper_wrong_type); 13707 return QualType(); 13708 } 13709 return MapperType; 13710 } 13711 13712 OMPDeclareMapperDecl *Sema::ActOnOpenMPDeclareMapperDirectiveStart( 13713 Scope *S, DeclContext *DC, DeclarationName Name, QualType MapperType, 13714 SourceLocation StartLoc, DeclarationName VN, AccessSpecifier AS, 13715 Decl *PrevDeclInScope) { 13716 LookupResult Lookup(*this, Name, SourceLocation(), LookupOMPMapperName, 13717 forRedeclarationInCurContext()); 13718 // [OpenMP 5.0], 2.19.7.3 declare mapper Directive, Restrictions 13719 // A mapper-identifier may not be redeclared in the current scope for the 13720 // same type or for a type that is compatible according to the base language 13721 // rules. 13722 llvm::DenseMap<QualType, SourceLocation> PreviousRedeclTypes; 13723 OMPDeclareMapperDecl *PrevDMD = nullptr; 13724 bool InCompoundScope = true; 13725 if (S != nullptr) { 13726 // Find previous declaration with the same name not referenced in other 13727 // declarations. 13728 FunctionScopeInfo *ParentFn = getEnclosingFunction(); 13729 InCompoundScope = 13730 (ParentFn != nullptr) && !ParentFn->CompoundScopes.empty(); 13731 LookupName(Lookup, S); 13732 FilterLookupForScope(Lookup, DC, S, /*ConsiderLinkage=*/false, 13733 /*AllowInlineNamespace=*/false); 13734 llvm::DenseMap<OMPDeclareMapperDecl *, bool> UsedAsPrevious; 13735 LookupResult::Filter Filter = Lookup.makeFilter(); 13736 while (Filter.hasNext()) { 13737 auto *PrevDecl = cast<OMPDeclareMapperDecl>(Filter.next()); 13738 if (InCompoundScope) { 13739 auto I = UsedAsPrevious.find(PrevDecl); 13740 if (I == UsedAsPrevious.end()) 13741 UsedAsPrevious[PrevDecl] = false; 13742 if (OMPDeclareMapperDecl *D = PrevDecl->getPrevDeclInScope()) 13743 UsedAsPrevious[D] = true; 13744 } 13745 PreviousRedeclTypes[PrevDecl->getType().getCanonicalType()] = 13746 PrevDecl->getLocation(); 13747 } 13748 Filter.done(); 13749 if (InCompoundScope) { 13750 for (const auto &PrevData : UsedAsPrevious) { 13751 if (!PrevData.second) { 13752 PrevDMD = PrevData.first; 13753 break; 13754 } 13755 } 13756 } 13757 } else if (PrevDeclInScope) { 13758 auto *PrevDMDInScope = PrevDMD = 13759 cast<OMPDeclareMapperDecl>(PrevDeclInScope); 13760 do { 13761 PreviousRedeclTypes[PrevDMDInScope->getType().getCanonicalType()] = 13762 PrevDMDInScope->getLocation(); 13763 PrevDMDInScope = PrevDMDInScope->getPrevDeclInScope(); 13764 } while (PrevDMDInScope != nullptr); 13765 } 13766 const auto I = PreviousRedeclTypes.find(MapperType.getCanonicalType()); 13767 bool Invalid = false; 13768 if (I != PreviousRedeclTypes.end()) { 13769 Diag(StartLoc, diag::err_omp_declare_mapper_redefinition) 13770 << MapperType << Name; 13771 Diag(I->second, diag::note_previous_definition); 13772 Invalid = true; 13773 } 13774 auto *DMD = OMPDeclareMapperDecl::Create(Context, DC, StartLoc, Name, 13775 MapperType, VN, PrevDMD); 13776 DC->addDecl(DMD); 13777 DMD->setAccess(AS); 13778 if (Invalid) 13779 DMD->setInvalidDecl(); 13780 13781 // Enter new function scope. 13782 PushFunctionScope(); 13783 setFunctionHasBranchProtectedScope(); 13784 13785 CurContext = DMD; 13786 13787 return DMD; 13788 } 13789 13790 void Sema::ActOnOpenMPDeclareMapperDirectiveVarDecl(OMPDeclareMapperDecl *DMD, 13791 Scope *S, 13792 QualType MapperType, 13793 SourceLocation StartLoc, 13794 DeclarationName VN) { 13795 VarDecl *VD = buildVarDecl(*this, StartLoc, MapperType, VN.getAsString()); 13796 if (S) 13797 PushOnScopeChains(VD, S); 13798 else 13799 DMD->addDecl(VD); 13800 Expr *MapperVarRefExpr = buildDeclRefExpr(*this, VD, MapperType, StartLoc); 13801 DMD->setMapperVarRef(MapperVarRefExpr); 13802 } 13803 13804 Sema::DeclGroupPtrTy 13805 Sema::ActOnOpenMPDeclareMapperDirectiveEnd(OMPDeclareMapperDecl *D, Scope *S, 13806 ArrayRef<OMPClause *> ClauseList) { 13807 PopDeclContext(); 13808 PopFunctionScopeInfo(); 13809 13810 if (D) { 13811 if (S) 13812 PushOnScopeChains(D, S, /*AddToContext=*/false); 13813 D->CreateClauses(Context, ClauseList); 13814 } 13815 13816 return DeclGroupPtrTy::make(DeclGroupRef(D)); 13817 } 13818 13819 OMPClause *Sema::ActOnOpenMPNumTeamsClause(Expr *NumTeams, 13820 SourceLocation StartLoc, 13821 SourceLocation LParenLoc, 13822 SourceLocation EndLoc) { 13823 Expr *ValExpr = NumTeams; 13824 Stmt *HelperValStmt = nullptr; 13825 13826 // OpenMP [teams Constrcut, Restrictions] 13827 // The num_teams expression must evaluate to a positive integer value. 13828 if (!isNonNegativeIntegerValue(ValExpr, *this, OMPC_num_teams, 13829 /*StrictlyPositive=*/true)) 13830 return nullptr; 13831 13832 OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective(); 13833 OpenMPDirectiveKind CaptureRegion = 13834 getOpenMPCaptureRegionForClause(DKind, OMPC_num_teams); 13835 if (CaptureRegion != OMPD_unknown && !CurContext->isDependentContext()) { 13836 ValExpr = MakeFullExpr(ValExpr).get(); 13837 llvm::MapVector<const Expr *, DeclRefExpr *> Captures; 13838 ValExpr = tryBuildCapture(*this, ValExpr, Captures).get(); 13839 HelperValStmt = buildPreInits(Context, Captures); 13840 } 13841 13842 return new (Context) OMPNumTeamsClause(ValExpr, HelperValStmt, CaptureRegion, 13843 StartLoc, LParenLoc, EndLoc); 13844 } 13845 13846 OMPClause *Sema::ActOnOpenMPThreadLimitClause(Expr *ThreadLimit, 13847 SourceLocation StartLoc, 13848 SourceLocation LParenLoc, 13849 SourceLocation EndLoc) { 13850 Expr *ValExpr = ThreadLimit; 13851 Stmt *HelperValStmt = nullptr; 13852 13853 // OpenMP [teams Constrcut, Restrictions] 13854 // The thread_limit expression must evaluate to a positive integer value. 13855 if (!isNonNegativeIntegerValue(ValExpr, *this, OMPC_thread_limit, 13856 /*StrictlyPositive=*/true)) 13857 return nullptr; 13858 13859 OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective(); 13860 OpenMPDirectiveKind CaptureRegion = 13861 getOpenMPCaptureRegionForClause(DKind, OMPC_thread_limit); 13862 if (CaptureRegion != OMPD_unknown && !CurContext->isDependentContext()) { 13863 ValExpr = MakeFullExpr(ValExpr).get(); 13864 llvm::MapVector<const Expr *, DeclRefExpr *> Captures; 13865 ValExpr = tryBuildCapture(*this, ValExpr, Captures).get(); 13866 HelperValStmt = buildPreInits(Context, Captures); 13867 } 13868 13869 return new (Context) OMPThreadLimitClause( 13870 ValExpr, HelperValStmt, CaptureRegion, StartLoc, LParenLoc, EndLoc); 13871 } 13872 13873 OMPClause *Sema::ActOnOpenMPPriorityClause(Expr *Priority, 13874 SourceLocation StartLoc, 13875 SourceLocation LParenLoc, 13876 SourceLocation EndLoc) { 13877 Expr *ValExpr = Priority; 13878 13879 // OpenMP [2.9.1, task Constrcut] 13880 // The priority-value is a non-negative numerical scalar expression. 13881 if (!isNonNegativeIntegerValue(ValExpr, *this, OMPC_priority, 13882 /*StrictlyPositive=*/false)) 13883 return nullptr; 13884 13885 return new (Context) OMPPriorityClause(ValExpr, StartLoc, LParenLoc, EndLoc); 13886 } 13887 13888 OMPClause *Sema::ActOnOpenMPGrainsizeClause(Expr *Grainsize, 13889 SourceLocation StartLoc, 13890 SourceLocation LParenLoc, 13891 SourceLocation EndLoc) { 13892 Expr *ValExpr = Grainsize; 13893 13894 // OpenMP [2.9.2, taskloop Constrcut] 13895 // The parameter of the grainsize clause must be a positive integer 13896 // expression. 13897 if (!isNonNegativeIntegerValue(ValExpr, *this, OMPC_grainsize, 13898 /*StrictlyPositive=*/true)) 13899 return nullptr; 13900 13901 return new (Context) OMPGrainsizeClause(ValExpr, StartLoc, LParenLoc, EndLoc); 13902 } 13903 13904 OMPClause *Sema::ActOnOpenMPNumTasksClause(Expr *NumTasks, 13905 SourceLocation StartLoc, 13906 SourceLocation LParenLoc, 13907 SourceLocation EndLoc) { 13908 Expr *ValExpr = NumTasks; 13909 13910 // OpenMP [2.9.2, taskloop Constrcut] 13911 // The parameter of the num_tasks clause must be a positive integer 13912 // expression. 13913 if (!isNonNegativeIntegerValue(ValExpr, *this, OMPC_num_tasks, 13914 /*StrictlyPositive=*/true)) 13915 return nullptr; 13916 13917 return new (Context) OMPNumTasksClause(ValExpr, StartLoc, LParenLoc, EndLoc); 13918 } 13919 13920 OMPClause *Sema::ActOnOpenMPHintClause(Expr *Hint, SourceLocation StartLoc, 13921 SourceLocation LParenLoc, 13922 SourceLocation EndLoc) { 13923 // OpenMP [2.13.2, critical construct, Description] 13924 // ... where hint-expression is an integer constant expression that evaluates 13925 // to a valid lock hint. 13926 ExprResult HintExpr = VerifyPositiveIntegerConstantInClause(Hint, OMPC_hint); 13927 if (HintExpr.isInvalid()) 13928 return nullptr; 13929 return new (Context) 13930 OMPHintClause(HintExpr.get(), StartLoc, LParenLoc, EndLoc); 13931 } 13932 13933 OMPClause *Sema::ActOnOpenMPDistScheduleClause( 13934 OpenMPDistScheduleClauseKind Kind, Expr *ChunkSize, SourceLocation StartLoc, 13935 SourceLocation LParenLoc, SourceLocation KindLoc, SourceLocation CommaLoc, 13936 SourceLocation EndLoc) { 13937 if (Kind == OMPC_DIST_SCHEDULE_unknown) { 13938 std::string Values; 13939 Values += "'"; 13940 Values += getOpenMPSimpleClauseTypeName(OMPC_dist_schedule, 0); 13941 Values += "'"; 13942 Diag(KindLoc, diag::err_omp_unexpected_clause_value) 13943 << Values << getOpenMPClauseName(OMPC_dist_schedule); 13944 return nullptr; 13945 } 13946 Expr *ValExpr = ChunkSize; 13947 Stmt *HelperValStmt = nullptr; 13948 if (ChunkSize) { 13949 if (!ChunkSize->isValueDependent() && !ChunkSize->isTypeDependent() && 13950 !ChunkSize->isInstantiationDependent() && 13951 !ChunkSize->containsUnexpandedParameterPack()) { 13952 SourceLocation ChunkSizeLoc = ChunkSize->getBeginLoc(); 13953 ExprResult Val = 13954 PerformOpenMPImplicitIntegerConversion(ChunkSizeLoc, ChunkSize); 13955 if (Val.isInvalid()) 13956 return nullptr; 13957 13958 ValExpr = Val.get(); 13959 13960 // OpenMP [2.7.1, Restrictions] 13961 // chunk_size must be a loop invariant integer expression with a positive 13962 // value. 13963 llvm::APSInt Result; 13964 if (ValExpr->isIntegerConstantExpr(Result, Context)) { 13965 if (Result.isSigned() && !Result.isStrictlyPositive()) { 13966 Diag(ChunkSizeLoc, diag::err_omp_negative_expression_in_clause) 13967 << "dist_schedule" << ChunkSize->getSourceRange(); 13968 return nullptr; 13969 } 13970 } else if (getOpenMPCaptureRegionForClause( 13971 DSAStack->getCurrentDirective(), OMPC_dist_schedule) != 13972 OMPD_unknown && 13973 !CurContext->isDependentContext()) { 13974 ValExpr = MakeFullExpr(ValExpr).get(); 13975 llvm::MapVector<const Expr *, DeclRefExpr *> Captures; 13976 ValExpr = tryBuildCapture(*this, ValExpr, Captures).get(); 13977 HelperValStmt = buildPreInits(Context, Captures); 13978 } 13979 } 13980 } 13981 13982 return new (Context) 13983 OMPDistScheduleClause(StartLoc, LParenLoc, KindLoc, CommaLoc, EndLoc, 13984 Kind, ValExpr, HelperValStmt); 13985 } 13986 13987 OMPClause *Sema::ActOnOpenMPDefaultmapClause( 13988 OpenMPDefaultmapClauseModifier M, OpenMPDefaultmapClauseKind Kind, 13989 SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation MLoc, 13990 SourceLocation KindLoc, SourceLocation EndLoc) { 13991 // OpenMP 4.5 only supports 'defaultmap(tofrom: scalar)' 13992 if (M != OMPC_DEFAULTMAP_MODIFIER_tofrom || Kind != OMPC_DEFAULTMAP_scalar) { 13993 std::string Value; 13994 SourceLocation Loc; 13995 Value += "'"; 13996 if (M != OMPC_DEFAULTMAP_MODIFIER_tofrom) { 13997 Value += getOpenMPSimpleClauseTypeName(OMPC_defaultmap, 13998 OMPC_DEFAULTMAP_MODIFIER_tofrom); 13999 Loc = MLoc; 14000 } else { 14001 Value += getOpenMPSimpleClauseTypeName(OMPC_defaultmap, 14002 OMPC_DEFAULTMAP_scalar); 14003 Loc = KindLoc; 14004 } 14005 Value += "'"; 14006 Diag(Loc, diag::err_omp_unexpected_clause_value) 14007 << Value << getOpenMPClauseName(OMPC_defaultmap); 14008 return nullptr; 14009 } 14010 DSAStack->setDefaultDMAToFromScalar(StartLoc); 14011 14012 return new (Context) 14013 OMPDefaultmapClause(StartLoc, LParenLoc, MLoc, KindLoc, EndLoc, Kind, M); 14014 } 14015 14016 bool Sema::ActOnStartOpenMPDeclareTargetDirective(SourceLocation Loc) { 14017 DeclContext *CurLexicalContext = getCurLexicalContext(); 14018 if (!CurLexicalContext->isFileContext() && 14019 !CurLexicalContext->isExternCContext() && 14020 !CurLexicalContext->isExternCXXContext() && 14021 !isa<CXXRecordDecl>(CurLexicalContext) && 14022 !isa<ClassTemplateDecl>(CurLexicalContext) && 14023 !isa<ClassTemplatePartialSpecializationDecl>(CurLexicalContext) && 14024 !isa<ClassTemplateSpecializationDecl>(CurLexicalContext)) { 14025 Diag(Loc, diag::err_omp_region_not_file_context); 14026 return false; 14027 } 14028 ++DeclareTargetNestingLevel; 14029 return true; 14030 } 14031 14032 void Sema::ActOnFinishOpenMPDeclareTargetDirective() { 14033 assert(DeclareTargetNestingLevel > 0 && 14034 "Unexpected ActOnFinishOpenMPDeclareTargetDirective"); 14035 --DeclareTargetNestingLevel; 14036 } 14037 14038 void Sema::ActOnOpenMPDeclareTargetName(Scope *CurScope, 14039 CXXScopeSpec &ScopeSpec, 14040 const DeclarationNameInfo &Id, 14041 OMPDeclareTargetDeclAttr::MapTypeTy MT, 14042 NamedDeclSetType &SameDirectiveDecls) { 14043 LookupResult Lookup(*this, Id, LookupOrdinaryName); 14044 LookupParsedName(Lookup, CurScope, &ScopeSpec, true); 14045 14046 if (Lookup.isAmbiguous()) 14047 return; 14048 Lookup.suppressDiagnostics(); 14049 14050 if (!Lookup.isSingleResult()) { 14051 if (TypoCorrection Corrected = 14052 CorrectTypo(Id, LookupOrdinaryName, CurScope, nullptr, 14053 llvm::make_unique<VarOrFuncDeclFilterCCC>(*this), 14054 CTK_ErrorRecovery)) { 14055 diagnoseTypo(Corrected, PDiag(diag::err_undeclared_var_use_suggest) 14056 << Id.getName()); 14057 checkDeclIsAllowedInOpenMPTarget(nullptr, Corrected.getCorrectionDecl()); 14058 return; 14059 } 14060 14061 Diag(Id.getLoc(), diag::err_undeclared_var_use) << Id.getName(); 14062 return; 14063 } 14064 14065 NamedDecl *ND = Lookup.getAsSingle<NamedDecl>(); 14066 if (isa<VarDecl>(ND) || isa<FunctionDecl>(ND) || 14067 isa<FunctionTemplateDecl>(ND)) { 14068 if (!SameDirectiveDecls.insert(cast<NamedDecl>(ND->getCanonicalDecl()))) 14069 Diag(Id.getLoc(), diag::err_omp_declare_target_multiple) << Id.getName(); 14070 llvm::Optional<OMPDeclareTargetDeclAttr::MapTypeTy> Res = 14071 OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration( 14072 cast<ValueDecl>(ND)); 14073 if (!Res) { 14074 auto *A = OMPDeclareTargetDeclAttr::CreateImplicit(Context, MT); 14075 ND->addAttr(A); 14076 if (ASTMutationListener *ML = Context.getASTMutationListener()) 14077 ML->DeclarationMarkedOpenMPDeclareTarget(ND, A); 14078 checkDeclIsAllowedInOpenMPTarget(nullptr, ND, Id.getLoc()); 14079 } else if (*Res != MT) { 14080 Diag(Id.getLoc(), diag::err_omp_declare_target_to_and_link) 14081 << Id.getName(); 14082 } 14083 } else { 14084 Diag(Id.getLoc(), diag::err_omp_invalid_target_decl) << Id.getName(); 14085 } 14086 } 14087 14088 static void checkDeclInTargetContext(SourceLocation SL, SourceRange SR, 14089 Sema &SemaRef, Decl *D) { 14090 if (!D || !isa<VarDecl>(D)) 14091 return; 14092 auto *VD = cast<VarDecl>(D); 14093 if (OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD)) 14094 return; 14095 SemaRef.Diag(VD->getLocation(), diag::warn_omp_not_in_target_context); 14096 SemaRef.Diag(SL, diag::note_used_here) << SR; 14097 } 14098 14099 static bool checkValueDeclInTarget(SourceLocation SL, SourceRange SR, 14100 Sema &SemaRef, DSAStackTy *Stack, 14101 ValueDecl *VD) { 14102 return VD->hasAttr<OMPDeclareTargetDeclAttr>() || 14103 checkTypeMappable(SL, SR, SemaRef, Stack, VD->getType(), 14104 /*FullCheck=*/false); 14105 } 14106 14107 void Sema::checkDeclIsAllowedInOpenMPTarget(Expr *E, Decl *D, 14108 SourceLocation IdLoc) { 14109 if (!D || D->isInvalidDecl()) 14110 return; 14111 SourceRange SR = E ? E->getSourceRange() : D->getSourceRange(); 14112 SourceLocation SL = E ? E->getBeginLoc() : D->getLocation(); 14113 if (auto *VD = dyn_cast<VarDecl>(D)) { 14114 // Only global variables can be marked as declare target. 14115 if (!VD->isFileVarDecl() && !VD->isStaticLocal() && 14116 !VD->isStaticDataMember()) 14117 return; 14118 // 2.10.6: threadprivate variable cannot appear in a declare target 14119 // directive. 14120 if (DSAStack->isThreadPrivate(VD)) { 14121 Diag(SL, diag::err_omp_threadprivate_in_target); 14122 reportOriginalDsa(*this, DSAStack, VD, DSAStack->getTopDSA(VD, false)); 14123 return; 14124 } 14125 } 14126 if (const auto *FTD = dyn_cast<FunctionTemplateDecl>(D)) 14127 D = FTD->getTemplatedDecl(); 14128 if (const auto *FD = dyn_cast<FunctionDecl>(D)) { 14129 llvm::Optional<OMPDeclareTargetDeclAttr::MapTypeTy> Res = 14130 OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(FD); 14131 if (Res && *Res == OMPDeclareTargetDeclAttr::MT_Link) { 14132 assert(IdLoc.isValid() && "Source location is expected"); 14133 Diag(IdLoc, diag::err_omp_function_in_link_clause); 14134 Diag(FD->getLocation(), diag::note_defined_here) << FD; 14135 return; 14136 } 14137 } 14138 if (auto *VD = dyn_cast<ValueDecl>(D)) { 14139 // Problem if any with var declared with incomplete type will be reported 14140 // as normal, so no need to check it here. 14141 if ((E || !VD->getType()->isIncompleteType()) && 14142 !checkValueDeclInTarget(SL, SR, *this, DSAStack, VD)) 14143 return; 14144 if (!E && !OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD)) { 14145 // Checking declaration inside declare target region. 14146 if (isa<VarDecl>(D) || isa<FunctionDecl>(D) || 14147 isa<FunctionTemplateDecl>(D)) { 14148 auto *A = OMPDeclareTargetDeclAttr::CreateImplicit( 14149 Context, OMPDeclareTargetDeclAttr::MT_To); 14150 D->addAttr(A); 14151 if (ASTMutationListener *ML = Context.getASTMutationListener()) 14152 ML->DeclarationMarkedOpenMPDeclareTarget(D, A); 14153 } 14154 return; 14155 } 14156 } 14157 if (!E) 14158 return; 14159 checkDeclInTargetContext(E->getExprLoc(), E->getSourceRange(), *this, D); 14160 } 14161 14162 OMPClause *Sema::ActOnOpenMPToClause(ArrayRef<Expr *> VarList, 14163 CXXScopeSpec &MapperIdScopeSpec, 14164 DeclarationNameInfo &MapperId, 14165 const OMPVarListLocTy &Locs, 14166 ArrayRef<Expr *> UnresolvedMappers) { 14167 MappableVarListInfo MVLI(VarList); 14168 checkMappableExpressionList(*this, DSAStack, OMPC_to, MVLI, Locs.StartLoc, 14169 MapperIdScopeSpec, MapperId, UnresolvedMappers); 14170 if (MVLI.ProcessedVarList.empty()) 14171 return nullptr; 14172 14173 return OMPToClause::Create( 14174 Context, Locs, MVLI.ProcessedVarList, MVLI.VarBaseDeclarations, 14175 MVLI.VarComponents, MVLI.UDMapperList, 14176 MapperIdScopeSpec.getWithLocInContext(Context), MapperId); 14177 } 14178 14179 OMPClause *Sema::ActOnOpenMPFromClause(ArrayRef<Expr *> VarList, 14180 CXXScopeSpec &MapperIdScopeSpec, 14181 DeclarationNameInfo &MapperId, 14182 const OMPVarListLocTy &Locs, 14183 ArrayRef<Expr *> UnresolvedMappers) { 14184 MappableVarListInfo MVLI(VarList); 14185 checkMappableExpressionList(*this, DSAStack, OMPC_from, MVLI, Locs.StartLoc, 14186 MapperIdScopeSpec, MapperId, UnresolvedMappers); 14187 if (MVLI.ProcessedVarList.empty()) 14188 return nullptr; 14189 14190 return OMPFromClause::Create( 14191 Context, Locs, MVLI.ProcessedVarList, MVLI.VarBaseDeclarations, 14192 MVLI.VarComponents, MVLI.UDMapperList, 14193 MapperIdScopeSpec.getWithLocInContext(Context), MapperId); 14194 } 14195 14196 OMPClause *Sema::ActOnOpenMPUseDevicePtrClause(ArrayRef<Expr *> VarList, 14197 const OMPVarListLocTy &Locs) { 14198 MappableVarListInfo MVLI(VarList); 14199 SmallVector<Expr *, 8> PrivateCopies; 14200 SmallVector<Expr *, 8> Inits; 14201 14202 for (Expr *RefExpr : VarList) { 14203 assert(RefExpr && "NULL expr in OpenMP use_device_ptr clause."); 14204 SourceLocation ELoc; 14205 SourceRange ERange; 14206 Expr *SimpleRefExpr = RefExpr; 14207 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange); 14208 if (Res.second) { 14209 // It will be analyzed later. 14210 MVLI.ProcessedVarList.push_back(RefExpr); 14211 PrivateCopies.push_back(nullptr); 14212 Inits.push_back(nullptr); 14213 } 14214 ValueDecl *D = Res.first; 14215 if (!D) 14216 continue; 14217 14218 QualType Type = D->getType(); 14219 Type = Type.getNonReferenceType().getUnqualifiedType(); 14220 14221 auto *VD = dyn_cast<VarDecl>(D); 14222 14223 // Item should be a pointer or reference to pointer. 14224 if (!Type->isPointerType()) { 14225 Diag(ELoc, diag::err_omp_usedeviceptr_not_a_pointer) 14226 << 0 << RefExpr->getSourceRange(); 14227 continue; 14228 } 14229 14230 // Build the private variable and the expression that refers to it. 14231 auto VDPrivate = 14232 buildVarDecl(*this, ELoc, Type, D->getName(), 14233 D->hasAttrs() ? &D->getAttrs() : nullptr, 14234 VD ? cast<DeclRefExpr>(SimpleRefExpr) : nullptr); 14235 if (VDPrivate->isInvalidDecl()) 14236 continue; 14237 14238 CurContext->addDecl(VDPrivate); 14239 DeclRefExpr *VDPrivateRefExpr = buildDeclRefExpr( 14240 *this, VDPrivate, RefExpr->getType().getUnqualifiedType(), ELoc); 14241 14242 // Add temporary variable to initialize the private copy of the pointer. 14243 VarDecl *VDInit = 14244 buildVarDecl(*this, RefExpr->getExprLoc(), Type, ".devptr.temp"); 14245 DeclRefExpr *VDInitRefExpr = buildDeclRefExpr( 14246 *this, VDInit, RefExpr->getType(), RefExpr->getExprLoc()); 14247 AddInitializerToDecl(VDPrivate, 14248 DefaultLvalueConversion(VDInitRefExpr).get(), 14249 /*DirectInit=*/false); 14250 14251 // If required, build a capture to implement the privatization initialized 14252 // with the current list item value. 14253 DeclRefExpr *Ref = nullptr; 14254 if (!VD) 14255 Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/true); 14256 MVLI.ProcessedVarList.push_back(VD ? RefExpr->IgnoreParens() : Ref); 14257 PrivateCopies.push_back(VDPrivateRefExpr); 14258 Inits.push_back(VDInitRefExpr); 14259 14260 // We need to add a data sharing attribute for this variable to make sure it 14261 // is correctly captured. A variable that shows up in a use_device_ptr has 14262 // similar properties of a first private variable. 14263 DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_firstprivate, Ref); 14264 14265 // Create a mappable component for the list item. List items in this clause 14266 // only need a component. 14267 MVLI.VarBaseDeclarations.push_back(D); 14268 MVLI.VarComponents.resize(MVLI.VarComponents.size() + 1); 14269 MVLI.VarComponents.back().push_back( 14270 OMPClauseMappableExprCommon::MappableComponent(SimpleRefExpr, D)); 14271 } 14272 14273 if (MVLI.ProcessedVarList.empty()) 14274 return nullptr; 14275 14276 return OMPUseDevicePtrClause::Create( 14277 Context, Locs, MVLI.ProcessedVarList, PrivateCopies, Inits, 14278 MVLI.VarBaseDeclarations, MVLI.VarComponents); 14279 } 14280 14281 OMPClause *Sema::ActOnOpenMPIsDevicePtrClause(ArrayRef<Expr *> VarList, 14282 const OMPVarListLocTy &Locs) { 14283 MappableVarListInfo MVLI(VarList); 14284 for (Expr *RefExpr : VarList) { 14285 assert(RefExpr && "NULL expr in OpenMP is_device_ptr clause."); 14286 SourceLocation ELoc; 14287 SourceRange ERange; 14288 Expr *SimpleRefExpr = RefExpr; 14289 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange); 14290 if (Res.second) { 14291 // It will be analyzed later. 14292 MVLI.ProcessedVarList.push_back(RefExpr); 14293 } 14294 ValueDecl *D = Res.first; 14295 if (!D) 14296 continue; 14297 14298 QualType Type = D->getType(); 14299 // item should be a pointer or array or reference to pointer or array 14300 if (!Type.getNonReferenceType()->isPointerType() && 14301 !Type.getNonReferenceType()->isArrayType()) { 14302 Diag(ELoc, diag::err_omp_argument_type_isdeviceptr) 14303 << 0 << RefExpr->getSourceRange(); 14304 continue; 14305 } 14306 14307 // Check if the declaration in the clause does not show up in any data 14308 // sharing attribute. 14309 DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, /*FromParent=*/false); 14310 if (isOpenMPPrivate(DVar.CKind)) { 14311 Diag(ELoc, diag::err_omp_variable_in_given_clause_and_dsa) 14312 << getOpenMPClauseName(DVar.CKind) 14313 << getOpenMPClauseName(OMPC_is_device_ptr) 14314 << getOpenMPDirectiveName(DSAStack->getCurrentDirective()); 14315 reportOriginalDsa(*this, DSAStack, D, DVar); 14316 continue; 14317 } 14318 14319 const Expr *ConflictExpr; 14320 if (DSAStack->checkMappableExprComponentListsForDecl( 14321 D, /*CurrentRegionOnly=*/true, 14322 [&ConflictExpr]( 14323 OMPClauseMappableExprCommon::MappableExprComponentListRef R, 14324 OpenMPClauseKind) -> bool { 14325 ConflictExpr = R.front().getAssociatedExpression(); 14326 return true; 14327 })) { 14328 Diag(ELoc, diag::err_omp_map_shared_storage) << RefExpr->getSourceRange(); 14329 Diag(ConflictExpr->getExprLoc(), diag::note_used_here) 14330 << ConflictExpr->getSourceRange(); 14331 continue; 14332 } 14333 14334 // Store the components in the stack so that they can be used to check 14335 // against other clauses later on. 14336 OMPClauseMappableExprCommon::MappableComponent MC(SimpleRefExpr, D); 14337 DSAStack->addMappableExpressionComponents( 14338 D, MC, /*WhereFoundClauseKind=*/OMPC_is_device_ptr); 14339 14340 // Record the expression we've just processed. 14341 MVLI.ProcessedVarList.push_back(SimpleRefExpr); 14342 14343 // Create a mappable component for the list item. List items in this clause 14344 // only need a component. We use a null declaration to signal fields in 14345 // 'this'. 14346 assert((isa<DeclRefExpr>(SimpleRefExpr) || 14347 isa<CXXThisExpr>(cast<MemberExpr>(SimpleRefExpr)->getBase())) && 14348 "Unexpected device pointer expression!"); 14349 MVLI.VarBaseDeclarations.push_back( 14350 isa<DeclRefExpr>(SimpleRefExpr) ? D : nullptr); 14351 MVLI.VarComponents.resize(MVLI.VarComponents.size() + 1); 14352 MVLI.VarComponents.back().push_back(MC); 14353 } 14354 14355 if (MVLI.ProcessedVarList.empty()) 14356 return nullptr; 14357 14358 return OMPIsDevicePtrClause::Create(Context, Locs, MVLI.ProcessedVarList, 14359 MVLI.VarBaseDeclarations, 14360 MVLI.VarComponents); 14361 } 14362