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 bool BodyComplete = false; 147 SourceLocation InnerTeamsRegionLoc; 148 /// Reference to the taskgroup task_reduction reference expression. 149 Expr *TaskgroupReductionRef = nullptr; 150 llvm::DenseSet<QualType> MappedClassesQualTypes; 151 /// List of globals marked as declare target link in this target region 152 /// (isOpenMPTargetExecutionDirective(Directive) == true). 153 llvm::SmallVector<DeclRefExpr *, 4> DeclareTargetLinkVarDecls; 154 SharingMapTy(OpenMPDirectiveKind DKind, DeclarationNameInfo Name, 155 Scope *CurScope, SourceLocation Loc) 156 : Directive(DKind), DirectiveName(Name), CurScope(CurScope), 157 ConstructLoc(Loc) {} 158 SharingMapTy() = default; 159 }; 160 161 using StackTy = SmallVector<SharingMapTy, 4>; 162 163 /// Stack of used declaration and their data-sharing attributes. 164 DeclSAMapTy Threadprivates; 165 const FunctionScopeInfo *CurrentNonCapturingFunctionScope = nullptr; 166 SmallVector<std::pair<StackTy, const FunctionScopeInfo *>, 4> Stack; 167 /// true, if check for DSA must be from parent directive, false, if 168 /// from current directive. 169 OpenMPClauseKind ClauseKindMode = OMPC_unknown; 170 Sema &SemaRef; 171 bool ForceCapturing = false; 172 /// true if all the vaiables in the target executable directives must be 173 /// captured by reference. 174 bool ForceCaptureByReferenceInTargetExecutable = false; 175 CriticalsWithHintsTy Criticals; 176 unsigned IgnoredStackElements = 0; 177 178 /// Iterators over the stack iterate in order from innermost to outermost 179 /// directive. 180 using const_iterator = StackTy::const_reverse_iterator; 181 const_iterator begin() const { 182 return Stack.empty() ? const_iterator() 183 : Stack.back().first.rbegin() + IgnoredStackElements; 184 } 185 const_iterator end() const { 186 return Stack.empty() ? const_iterator() : Stack.back().first.rend(); 187 } 188 using iterator = StackTy::reverse_iterator; 189 iterator begin() { 190 return Stack.empty() ? iterator() 191 : Stack.back().first.rbegin() + IgnoredStackElements; 192 } 193 iterator end() { 194 return Stack.empty() ? iterator() : Stack.back().first.rend(); 195 } 196 197 // Convenience operations to get at the elements of the stack. 198 199 bool isStackEmpty() const { 200 return Stack.empty() || 201 Stack.back().second != CurrentNonCapturingFunctionScope || 202 Stack.back().first.size() <= IgnoredStackElements; 203 } 204 size_t getStackSize() const { 205 return isStackEmpty() ? 0 206 : Stack.back().first.size() - IgnoredStackElements; 207 } 208 209 SharingMapTy *getTopOfStackOrNull() { 210 size_t Size = getStackSize(); 211 if (Size == 0) 212 return nullptr; 213 return &Stack.back().first[Size - 1]; 214 } 215 const SharingMapTy *getTopOfStackOrNull() const { 216 return const_cast<DSAStackTy&>(*this).getTopOfStackOrNull(); 217 } 218 SharingMapTy &getTopOfStack() { 219 assert(!isStackEmpty() && "no current directive"); 220 return *getTopOfStackOrNull(); 221 } 222 const SharingMapTy &getTopOfStack() const { 223 return const_cast<DSAStackTy&>(*this).getTopOfStack(); 224 } 225 226 SharingMapTy *getSecondOnStackOrNull() { 227 size_t Size = getStackSize(); 228 if (Size <= 1) 229 return nullptr; 230 return &Stack.back().first[Size - 2]; 231 } 232 const SharingMapTy *getSecondOnStackOrNull() const { 233 return const_cast<DSAStackTy&>(*this).getSecondOnStackOrNull(); 234 } 235 236 /// Get the stack element at a certain level (previously returned by 237 /// \c getNestingLevel). 238 /// 239 /// Note that nesting levels count from outermost to innermost, and this is 240 /// the reverse of our iteration order where new inner levels are pushed at 241 /// the front of the stack. 242 SharingMapTy &getStackElemAtLevel(unsigned Level) { 243 assert(Level < getStackSize() && "no such stack element"); 244 return Stack.back().first[Level]; 245 } 246 const SharingMapTy &getStackElemAtLevel(unsigned Level) const { 247 return const_cast<DSAStackTy&>(*this).getStackElemAtLevel(Level); 248 } 249 250 DSAVarData getDSA(const_iterator &Iter, ValueDecl *D) const; 251 252 /// Checks if the variable is a local for OpenMP region. 253 bool isOpenMPLocal(VarDecl *D, const_iterator Iter) const; 254 255 /// Vector of previously declared requires directives 256 SmallVector<const OMPRequiresDecl *, 2> RequiresDecls; 257 /// omp_allocator_handle_t type. 258 QualType OMPAllocatorHandleT; 259 /// Expression for the predefined allocators. 260 Expr *OMPPredefinedAllocators[OMPAllocateDeclAttr::OMPUserDefinedMemAlloc] = { 261 nullptr}; 262 /// Vector of previously encountered target directives 263 SmallVector<SourceLocation, 2> TargetLocations; 264 265 public: 266 explicit DSAStackTy(Sema &S) : SemaRef(S) {} 267 268 /// Sets omp_allocator_handle_t type. 269 void setOMPAllocatorHandleT(QualType Ty) { OMPAllocatorHandleT = Ty; } 270 /// Gets omp_allocator_handle_t type. 271 QualType getOMPAllocatorHandleT() const { return OMPAllocatorHandleT; } 272 /// Sets the given default allocator. 273 void setAllocator(OMPAllocateDeclAttr::AllocatorTypeTy AllocatorKind, 274 Expr *Allocator) { 275 OMPPredefinedAllocators[AllocatorKind] = Allocator; 276 } 277 /// Returns the specified default allocator. 278 Expr *getAllocator(OMPAllocateDeclAttr::AllocatorTypeTy AllocatorKind) const { 279 return OMPPredefinedAllocators[AllocatorKind]; 280 } 281 282 bool isClauseParsingMode() const { return ClauseKindMode != OMPC_unknown; } 283 OpenMPClauseKind getClauseParsingMode() const { 284 assert(isClauseParsingMode() && "Must be in clause parsing mode."); 285 return ClauseKindMode; 286 } 287 void setClauseParsingMode(OpenMPClauseKind K) { ClauseKindMode = K; } 288 289 bool isBodyComplete() const { 290 const SharingMapTy *Top = getTopOfStackOrNull(); 291 return Top && Top->BodyComplete; 292 } 293 void setBodyComplete() { 294 getTopOfStack().BodyComplete = true; 295 } 296 297 bool isForceVarCapturing() const { return ForceCapturing; } 298 void setForceVarCapturing(bool V) { ForceCapturing = V; } 299 300 void setForceCaptureByReferenceInTargetExecutable(bool V) { 301 ForceCaptureByReferenceInTargetExecutable = V; 302 } 303 bool isForceCaptureByReferenceInTargetExecutable() const { 304 return ForceCaptureByReferenceInTargetExecutable; 305 } 306 307 void push(OpenMPDirectiveKind DKind, const DeclarationNameInfo &DirName, 308 Scope *CurScope, SourceLocation Loc) { 309 assert(!IgnoredStackElements && 310 "cannot change stack while ignoring elements"); 311 if (Stack.empty() || 312 Stack.back().second != CurrentNonCapturingFunctionScope) 313 Stack.emplace_back(StackTy(), CurrentNonCapturingFunctionScope); 314 Stack.back().first.emplace_back(DKind, DirName, CurScope, Loc); 315 Stack.back().first.back().DefaultAttrLoc = Loc; 316 } 317 318 void pop() { 319 assert(!IgnoredStackElements && 320 "cannot change stack while ignoring elements"); 321 assert(!Stack.back().first.empty() && 322 "Data-sharing attributes stack is empty!"); 323 Stack.back().first.pop_back(); 324 } 325 326 /// RAII object to temporarily leave the scope of a directive when we want to 327 /// logically operate in its parent. 328 class ParentDirectiveScope { 329 DSAStackTy &Self; 330 bool Active; 331 public: 332 ParentDirectiveScope(DSAStackTy &Self, bool Activate) 333 : Self(Self), Active(false) { 334 if (Activate) 335 enable(); 336 } 337 ~ParentDirectiveScope() { disable(); } 338 void disable() { 339 if (Active) { 340 --Self.IgnoredStackElements; 341 Active = false; 342 } 343 } 344 void enable() { 345 if (!Active) { 346 ++Self.IgnoredStackElements; 347 Active = true; 348 } 349 } 350 }; 351 352 /// Marks that we're started loop parsing. 353 void loopInit() { 354 assert(isOpenMPLoopDirective(getCurrentDirective()) && 355 "Expected loop-based directive."); 356 getTopOfStack().LoopStart = true; 357 } 358 /// Start capturing of the variables in the loop context. 359 void loopStart() { 360 assert(isOpenMPLoopDirective(getCurrentDirective()) && 361 "Expected loop-based directive."); 362 getTopOfStack().LoopStart = false; 363 } 364 /// true, if variables are captured, false otherwise. 365 bool isLoopStarted() const { 366 assert(isOpenMPLoopDirective(getCurrentDirective()) && 367 "Expected loop-based directive."); 368 return !getTopOfStack().LoopStart; 369 } 370 /// Marks (or clears) declaration as possibly loop counter. 371 void resetPossibleLoopCounter(const Decl *D = nullptr) { 372 getTopOfStack().PossiblyLoopCounter = 373 D ? D->getCanonicalDecl() : D; 374 } 375 /// Gets the possible loop counter decl. 376 const Decl *getPossiblyLoopCunter() const { 377 return getTopOfStack().PossiblyLoopCounter; 378 } 379 /// Start new OpenMP region stack in new non-capturing function. 380 void pushFunction() { 381 assert(!IgnoredStackElements && 382 "cannot change stack while ignoring elements"); 383 const FunctionScopeInfo *CurFnScope = SemaRef.getCurFunction(); 384 assert(!isa<CapturingScopeInfo>(CurFnScope)); 385 CurrentNonCapturingFunctionScope = CurFnScope; 386 } 387 /// Pop region stack for non-capturing function. 388 void popFunction(const FunctionScopeInfo *OldFSI) { 389 assert(!IgnoredStackElements && 390 "cannot change stack while ignoring elements"); 391 if (!Stack.empty() && Stack.back().second == OldFSI) { 392 assert(Stack.back().first.empty()); 393 Stack.pop_back(); 394 } 395 CurrentNonCapturingFunctionScope = nullptr; 396 for (const FunctionScopeInfo *FSI : llvm::reverse(SemaRef.FunctionScopes)) { 397 if (!isa<CapturingScopeInfo>(FSI)) { 398 CurrentNonCapturingFunctionScope = FSI; 399 break; 400 } 401 } 402 } 403 404 void addCriticalWithHint(const OMPCriticalDirective *D, llvm::APSInt Hint) { 405 Criticals.try_emplace(D->getDirectiveName().getAsString(), D, Hint); 406 } 407 const std::pair<const OMPCriticalDirective *, llvm::APSInt> 408 getCriticalWithHint(const DeclarationNameInfo &Name) const { 409 auto I = Criticals.find(Name.getAsString()); 410 if (I != Criticals.end()) 411 return I->second; 412 return std::make_pair(nullptr, llvm::APSInt()); 413 } 414 /// If 'aligned' declaration for given variable \a D was not seen yet, 415 /// add it and return NULL; otherwise return previous occurrence's expression 416 /// for diagnostics. 417 const Expr *addUniqueAligned(const ValueDecl *D, const Expr *NewDE); 418 419 /// Register specified variable as loop control variable. 420 void addLoopControlVariable(const ValueDecl *D, VarDecl *Capture); 421 /// Check if the specified variable is a loop control variable for 422 /// current region. 423 /// \return The index of the loop control variable in the list of associated 424 /// for-loops (from outer to inner). 425 const LCDeclInfo isLoopControlVariable(const ValueDecl *D) const; 426 /// Check if the specified variable is a loop control variable for 427 /// parent region. 428 /// \return The index of the loop control variable in the list of associated 429 /// for-loops (from outer to inner). 430 const LCDeclInfo isParentLoopControlVariable(const ValueDecl *D) const; 431 /// Get the loop control variable for the I-th loop (or nullptr) in 432 /// parent directive. 433 const ValueDecl *getParentLoopControlVariable(unsigned I) const; 434 435 /// Adds explicit data sharing attribute to the specified declaration. 436 void addDSA(const ValueDecl *D, const Expr *E, OpenMPClauseKind A, 437 DeclRefExpr *PrivateCopy = nullptr); 438 439 /// Adds additional information for the reduction items with the reduction id 440 /// represented as an operator. 441 void addTaskgroupReductionData(const ValueDecl *D, SourceRange SR, 442 BinaryOperatorKind BOK); 443 /// Adds additional information for the reduction items with the reduction id 444 /// represented as reduction identifier. 445 void addTaskgroupReductionData(const ValueDecl *D, SourceRange SR, 446 const Expr *ReductionRef); 447 /// Returns the location and reduction operation from the innermost parent 448 /// region for the given \p D. 449 const DSAVarData 450 getTopMostTaskgroupReductionData(const ValueDecl *D, SourceRange &SR, 451 BinaryOperatorKind &BOK, 452 Expr *&TaskgroupDescriptor) const; 453 /// Returns the location and reduction operation from the innermost parent 454 /// region for the given \p D. 455 const DSAVarData 456 getTopMostTaskgroupReductionData(const ValueDecl *D, SourceRange &SR, 457 const Expr *&ReductionRef, 458 Expr *&TaskgroupDescriptor) const; 459 /// Return reduction reference expression for the current taskgroup. 460 Expr *getTaskgroupReductionRef() const { 461 assert(getTopOfStack().Directive == OMPD_taskgroup && 462 "taskgroup reference expression requested for non taskgroup " 463 "directive."); 464 return getTopOfStack().TaskgroupReductionRef; 465 } 466 /// Checks if the given \p VD declaration is actually a taskgroup reduction 467 /// descriptor variable at the \p Level of OpenMP regions. 468 bool isTaskgroupReductionRef(const ValueDecl *VD, unsigned Level) const { 469 return getStackElemAtLevel(Level).TaskgroupReductionRef && 470 cast<DeclRefExpr>(getStackElemAtLevel(Level).TaskgroupReductionRef) 471 ->getDecl() == VD; 472 } 473 474 /// Returns data sharing attributes from top of the stack for the 475 /// specified declaration. 476 const DSAVarData getTopDSA(ValueDecl *D, bool FromParent); 477 /// Returns data-sharing attributes for the specified declaration. 478 const DSAVarData getImplicitDSA(ValueDecl *D, bool FromParent) const; 479 /// Checks if the specified variables has data-sharing attributes which 480 /// match specified \a CPred predicate in any directive which matches \a DPred 481 /// predicate. 482 const DSAVarData 483 hasDSA(ValueDecl *D, const llvm::function_ref<bool(OpenMPClauseKind)> CPred, 484 const llvm::function_ref<bool(OpenMPDirectiveKind)> DPred, 485 bool FromParent) const; 486 /// Checks if the specified variables has data-sharing attributes which 487 /// match specified \a CPred predicate in any innermost directive which 488 /// matches \a DPred predicate. 489 const DSAVarData 490 hasInnermostDSA(ValueDecl *D, 491 const llvm::function_ref<bool(OpenMPClauseKind)> CPred, 492 const llvm::function_ref<bool(OpenMPDirectiveKind)> DPred, 493 bool FromParent) const; 494 /// Checks if the specified variables has explicit data-sharing 495 /// attributes which match specified \a CPred predicate at the specified 496 /// OpenMP region. 497 bool hasExplicitDSA(const ValueDecl *D, 498 const llvm::function_ref<bool(OpenMPClauseKind)> CPred, 499 unsigned Level, bool NotLastprivate = false) const; 500 501 /// Returns true if the directive at level \Level matches in the 502 /// specified \a DPred predicate. 503 bool hasExplicitDirective( 504 const llvm::function_ref<bool(OpenMPDirectiveKind)> DPred, 505 unsigned Level) const; 506 507 /// Finds a directive which matches specified \a DPred predicate. 508 bool hasDirective( 509 const llvm::function_ref<bool( 510 OpenMPDirectiveKind, const DeclarationNameInfo &, SourceLocation)> 511 DPred, 512 bool FromParent) const; 513 514 /// Returns currently analyzed directive. 515 OpenMPDirectiveKind getCurrentDirective() const { 516 const SharingMapTy *Top = getTopOfStackOrNull(); 517 return Top ? Top->Directive : OMPD_unknown; 518 } 519 /// Returns directive kind at specified level. 520 OpenMPDirectiveKind getDirective(unsigned Level) const { 521 assert(!isStackEmpty() && "No directive at specified level."); 522 return getStackElemAtLevel(Level).Directive; 523 } 524 /// Returns parent directive. 525 OpenMPDirectiveKind getParentDirective() const { 526 const SharingMapTy *Parent = getSecondOnStackOrNull(); 527 return Parent ? Parent->Directive : OMPD_unknown; 528 } 529 530 /// Add requires decl to internal vector 531 void addRequiresDecl(OMPRequiresDecl *RD) { 532 RequiresDecls.push_back(RD); 533 } 534 535 /// Checks if the defined 'requires' directive has specified type of clause. 536 template <typename ClauseType> 537 bool hasRequiresDeclWithClause() { 538 return llvm::any_of(RequiresDecls, [](const OMPRequiresDecl *D) { 539 return llvm::any_of(D->clauselists(), [](const OMPClause *C) { 540 return isa<ClauseType>(C); 541 }); 542 }); 543 } 544 545 /// Checks for a duplicate clause amongst previously declared requires 546 /// directives 547 bool hasDuplicateRequiresClause(ArrayRef<OMPClause *> ClauseList) const { 548 bool IsDuplicate = false; 549 for (OMPClause *CNew : ClauseList) { 550 for (const OMPRequiresDecl *D : RequiresDecls) { 551 for (const OMPClause *CPrev : D->clauselists()) { 552 if (CNew->getClauseKind() == CPrev->getClauseKind()) { 553 SemaRef.Diag(CNew->getBeginLoc(), 554 diag::err_omp_requires_clause_redeclaration) 555 << getOpenMPClauseName(CNew->getClauseKind()); 556 SemaRef.Diag(CPrev->getBeginLoc(), 557 diag::note_omp_requires_previous_clause) 558 << getOpenMPClauseName(CPrev->getClauseKind()); 559 IsDuplicate = true; 560 } 561 } 562 } 563 } 564 return IsDuplicate; 565 } 566 567 /// Add location of previously encountered target to internal vector 568 void addTargetDirLocation(SourceLocation LocStart) { 569 TargetLocations.push_back(LocStart); 570 } 571 572 // Return previously encountered target region locations. 573 ArrayRef<SourceLocation> getEncounteredTargetLocs() const { 574 return TargetLocations; 575 } 576 577 /// Set default data sharing attribute to none. 578 void setDefaultDSANone(SourceLocation Loc) { 579 getTopOfStack().DefaultAttr = DSA_none; 580 getTopOfStack().DefaultAttrLoc = Loc; 581 } 582 /// Set default data sharing attribute to shared. 583 void setDefaultDSAShared(SourceLocation Loc) { 584 getTopOfStack().DefaultAttr = DSA_shared; 585 getTopOfStack().DefaultAttrLoc = Loc; 586 } 587 /// Set default data mapping attribute to 'tofrom:scalar'. 588 void setDefaultDMAToFromScalar(SourceLocation Loc) { 589 getTopOfStack().DefaultMapAttr = DMA_tofrom_scalar; 590 getTopOfStack().DefaultMapAttrLoc = Loc; 591 } 592 593 DefaultDataSharingAttributes getDefaultDSA() const { 594 return isStackEmpty() ? DSA_unspecified 595 : getTopOfStack().DefaultAttr; 596 } 597 SourceLocation getDefaultDSALocation() const { 598 return isStackEmpty() ? SourceLocation() 599 : getTopOfStack().DefaultAttrLoc; 600 } 601 DefaultMapAttributes getDefaultDMA() const { 602 return isStackEmpty() ? DMA_unspecified 603 : getTopOfStack().DefaultMapAttr; 604 } 605 DefaultMapAttributes getDefaultDMAAtLevel(unsigned Level) const { 606 return getStackElemAtLevel(Level).DefaultMapAttr; 607 } 608 SourceLocation getDefaultDMALocation() const { 609 return isStackEmpty() ? SourceLocation() 610 : getTopOfStack().DefaultMapAttrLoc; 611 } 612 613 /// Checks if the specified variable is a threadprivate. 614 bool isThreadPrivate(VarDecl *D) { 615 const DSAVarData DVar = getTopDSA(D, false); 616 return isOpenMPThreadPrivate(DVar.CKind); 617 } 618 619 /// Marks current region as ordered (it has an 'ordered' clause). 620 void setOrderedRegion(bool IsOrdered, const Expr *Param, 621 OMPOrderedClause *Clause) { 622 if (IsOrdered) 623 getTopOfStack().OrderedRegion.emplace(Param, Clause); 624 else 625 getTopOfStack().OrderedRegion.reset(); 626 } 627 /// Returns true, if region is ordered (has associated 'ordered' clause), 628 /// false - otherwise. 629 bool isOrderedRegion() const { 630 if (const SharingMapTy *Top = getTopOfStackOrNull()) 631 return Top->OrderedRegion.hasValue(); 632 return false; 633 } 634 /// Returns optional parameter for the ordered region. 635 std::pair<const Expr *, OMPOrderedClause *> getOrderedRegionParam() const { 636 if (const SharingMapTy *Top = getTopOfStackOrNull()) 637 if (Top->OrderedRegion.hasValue()) 638 return Top->OrderedRegion.getValue(); 639 return std::make_pair(nullptr, nullptr); 640 } 641 /// Returns true, if parent region is ordered (has associated 642 /// 'ordered' clause), false - otherwise. 643 bool isParentOrderedRegion() const { 644 if (const SharingMapTy *Parent = getSecondOnStackOrNull()) 645 return Parent->OrderedRegion.hasValue(); 646 return false; 647 } 648 /// Returns optional parameter for the ordered region. 649 std::pair<const Expr *, OMPOrderedClause *> 650 getParentOrderedRegionParam() const { 651 if (const SharingMapTy *Parent = getSecondOnStackOrNull()) 652 if (Parent->OrderedRegion.hasValue()) 653 return Parent->OrderedRegion.getValue(); 654 return std::make_pair(nullptr, nullptr); 655 } 656 /// Marks current region as nowait (it has a 'nowait' clause). 657 void setNowaitRegion(bool IsNowait = true) { 658 getTopOfStack().NowaitRegion = IsNowait; 659 } 660 /// Returns true, if parent region is nowait (has associated 661 /// 'nowait' clause), false - otherwise. 662 bool isParentNowaitRegion() const { 663 if (const SharingMapTy *Parent = getSecondOnStackOrNull()) 664 return Parent->NowaitRegion; 665 return false; 666 } 667 /// Marks parent region as cancel region. 668 void setParentCancelRegion(bool Cancel = true) { 669 if (SharingMapTy *Parent = getSecondOnStackOrNull()) 670 Parent->CancelRegion |= Cancel; 671 } 672 /// Return true if current region has inner cancel construct. 673 bool isCancelRegion() const { 674 const SharingMapTy *Top = getTopOfStackOrNull(); 675 return Top ? Top->CancelRegion : false; 676 } 677 678 /// Set collapse value for the region. 679 void setAssociatedLoops(unsigned Val) { 680 getTopOfStack().AssociatedLoops = Val; 681 } 682 /// Return collapse value for region. 683 unsigned getAssociatedLoops() const { 684 const SharingMapTy *Top = getTopOfStackOrNull(); 685 return Top ? Top->AssociatedLoops : 0; 686 } 687 688 /// Marks current target region as one with closely nested teams 689 /// region. 690 void setParentTeamsRegionLoc(SourceLocation TeamsRegionLoc) { 691 if (SharingMapTy *Parent = getSecondOnStackOrNull()) 692 Parent->InnerTeamsRegionLoc = TeamsRegionLoc; 693 } 694 /// Returns true, if current region has closely nested teams region. 695 bool hasInnerTeamsRegion() const { 696 return getInnerTeamsRegionLoc().isValid(); 697 } 698 /// Returns location of the nested teams region (if any). 699 SourceLocation getInnerTeamsRegionLoc() const { 700 const SharingMapTy *Top = getTopOfStackOrNull(); 701 return Top ? Top->InnerTeamsRegionLoc : SourceLocation(); 702 } 703 704 Scope *getCurScope() const { 705 const SharingMapTy *Top = getTopOfStackOrNull(); 706 return Top ? Top->CurScope : nullptr; 707 } 708 SourceLocation getConstructLoc() const { 709 const SharingMapTy *Top = getTopOfStackOrNull(); 710 return Top ? Top->ConstructLoc : SourceLocation(); 711 } 712 713 /// Do the check specified in \a Check to all component lists and return true 714 /// if any issue is found. 715 bool checkMappableExprComponentListsForDecl( 716 const ValueDecl *VD, bool CurrentRegionOnly, 717 const llvm::function_ref< 718 bool(OMPClauseMappableExprCommon::MappableExprComponentListRef, 719 OpenMPClauseKind)> 720 Check) const { 721 if (isStackEmpty()) 722 return false; 723 auto SI = begin(); 724 auto SE = end(); 725 726 if (SI == SE) 727 return false; 728 729 if (CurrentRegionOnly) 730 SE = std::next(SI); 731 else 732 std::advance(SI, 1); 733 734 for (; SI != SE; ++SI) { 735 auto MI = SI->MappedExprComponents.find(VD); 736 if (MI != SI->MappedExprComponents.end()) 737 for (OMPClauseMappableExprCommon::MappableExprComponentListRef L : 738 MI->second.Components) 739 if (Check(L, MI->second.Kind)) 740 return true; 741 } 742 return false; 743 } 744 745 /// Do the check specified in \a Check to all component lists at a given level 746 /// and return true if any issue is found. 747 bool checkMappableExprComponentListsForDeclAtLevel( 748 const ValueDecl *VD, unsigned Level, 749 const llvm::function_ref< 750 bool(OMPClauseMappableExprCommon::MappableExprComponentListRef, 751 OpenMPClauseKind)> 752 Check) const { 753 if (getStackSize() <= Level) 754 return false; 755 756 const SharingMapTy &StackElem = getStackElemAtLevel(Level); 757 auto MI = StackElem.MappedExprComponents.find(VD); 758 if (MI != StackElem.MappedExprComponents.end()) 759 for (OMPClauseMappableExprCommon::MappableExprComponentListRef L : 760 MI->second.Components) 761 if (Check(L, MI->second.Kind)) 762 return true; 763 return false; 764 } 765 766 /// Create a new mappable expression component list associated with a given 767 /// declaration and initialize it with the provided list of components. 768 void addMappableExpressionComponents( 769 const ValueDecl *VD, 770 OMPClauseMappableExprCommon::MappableExprComponentListRef Components, 771 OpenMPClauseKind WhereFoundClauseKind) { 772 MappedExprComponentTy &MEC = getTopOfStack().MappedExprComponents[VD]; 773 // Create new entry and append the new components there. 774 MEC.Components.resize(MEC.Components.size() + 1); 775 MEC.Components.back().append(Components.begin(), Components.end()); 776 MEC.Kind = WhereFoundClauseKind; 777 } 778 779 unsigned getNestingLevel() const { 780 assert(!isStackEmpty()); 781 return getStackSize() - 1; 782 } 783 void addDoacrossDependClause(OMPDependClause *C, 784 const OperatorOffsetTy &OpsOffs) { 785 SharingMapTy *Parent = getSecondOnStackOrNull(); 786 assert(Parent && isOpenMPWorksharingDirective(Parent->Directive)); 787 Parent->DoacrossDepends.try_emplace(C, OpsOffs); 788 } 789 llvm::iterator_range<DoacrossDependMapTy::const_iterator> 790 getDoacrossDependClauses() const { 791 const SharingMapTy &StackElem = getTopOfStack(); 792 if (isOpenMPWorksharingDirective(StackElem.Directive)) { 793 const DoacrossDependMapTy &Ref = StackElem.DoacrossDepends; 794 return llvm::make_range(Ref.begin(), Ref.end()); 795 } 796 return llvm::make_range(StackElem.DoacrossDepends.end(), 797 StackElem.DoacrossDepends.end()); 798 } 799 800 // Store types of classes which have been explicitly mapped 801 void addMappedClassesQualTypes(QualType QT) { 802 SharingMapTy &StackElem = getTopOfStack(); 803 StackElem.MappedClassesQualTypes.insert(QT); 804 } 805 806 // Return set of mapped classes types 807 bool isClassPreviouslyMapped(QualType QT) const { 808 const SharingMapTy &StackElem = getTopOfStack(); 809 return StackElem.MappedClassesQualTypes.count(QT) != 0; 810 } 811 812 /// Adds global declare target to the parent target region. 813 void addToParentTargetRegionLinkGlobals(DeclRefExpr *E) { 814 assert(*OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration( 815 E->getDecl()) == OMPDeclareTargetDeclAttr::MT_Link && 816 "Expected declare target link global."); 817 for (auto &Elem : *this) { 818 if (isOpenMPTargetExecutionDirective(Elem.Directive)) { 819 Elem.DeclareTargetLinkVarDecls.push_back(E); 820 return; 821 } 822 } 823 } 824 825 /// Returns the list of globals with declare target link if current directive 826 /// is target. 827 ArrayRef<DeclRefExpr *> getLinkGlobals() const { 828 assert(isOpenMPTargetExecutionDirective(getCurrentDirective()) && 829 "Expected target executable directive."); 830 return getTopOfStack().DeclareTargetLinkVarDecls; 831 } 832 }; 833 834 bool isImplicitTaskingRegion(OpenMPDirectiveKind DKind) { 835 return isOpenMPParallelDirective(DKind) || isOpenMPTeamsDirective(DKind); 836 } 837 838 bool isImplicitOrExplicitTaskingRegion(OpenMPDirectiveKind DKind) { 839 return isImplicitTaskingRegion(DKind) || isOpenMPTaskingDirective(DKind) || 840 DKind == OMPD_unknown; 841 } 842 843 } // namespace 844 845 static const Expr *getExprAsWritten(const Expr *E) { 846 if (const auto *FE = dyn_cast<FullExpr>(E)) 847 E = FE->getSubExpr(); 848 849 if (const auto *MTE = dyn_cast<MaterializeTemporaryExpr>(E)) 850 E = MTE->GetTemporaryExpr(); 851 852 while (const auto *Binder = dyn_cast<CXXBindTemporaryExpr>(E)) 853 E = Binder->getSubExpr(); 854 855 if (const auto *ICE = dyn_cast<ImplicitCastExpr>(E)) 856 E = ICE->getSubExprAsWritten(); 857 return E->IgnoreParens(); 858 } 859 860 static Expr *getExprAsWritten(Expr *E) { 861 return const_cast<Expr *>(getExprAsWritten(const_cast<const Expr *>(E))); 862 } 863 864 static const ValueDecl *getCanonicalDecl(const ValueDecl *D) { 865 if (const auto *CED = dyn_cast<OMPCapturedExprDecl>(D)) 866 if (const auto *ME = dyn_cast<MemberExpr>(getExprAsWritten(CED->getInit()))) 867 D = ME->getMemberDecl(); 868 const auto *VD = dyn_cast<VarDecl>(D); 869 const auto *FD = dyn_cast<FieldDecl>(D); 870 if (VD != nullptr) { 871 VD = VD->getCanonicalDecl(); 872 D = VD; 873 } else { 874 assert(FD); 875 FD = FD->getCanonicalDecl(); 876 D = FD; 877 } 878 return D; 879 } 880 881 static ValueDecl *getCanonicalDecl(ValueDecl *D) { 882 return const_cast<ValueDecl *>( 883 getCanonicalDecl(const_cast<const ValueDecl *>(D))); 884 } 885 886 DSAStackTy::DSAVarData DSAStackTy::getDSA(const_iterator &Iter, 887 ValueDecl *D) const { 888 D = getCanonicalDecl(D); 889 auto *VD = dyn_cast<VarDecl>(D); 890 const auto *FD = dyn_cast<FieldDecl>(D); 891 DSAVarData DVar; 892 if (Iter == end()) { 893 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced 894 // in a region but not in construct] 895 // File-scope or namespace-scope variables referenced in called routines 896 // in the region are shared unless they appear in a threadprivate 897 // directive. 898 if (VD && !VD->isFunctionOrMethodVarDecl() && !isa<ParmVarDecl>(VD)) 899 DVar.CKind = OMPC_shared; 900 901 // OpenMP [2.9.1.2, Data-sharing Attribute Rules for Variables Referenced 902 // in a region but not in construct] 903 // Variables with static storage duration that are declared in called 904 // routines in the region are shared. 905 if (VD && VD->hasGlobalStorage()) 906 DVar.CKind = OMPC_shared; 907 908 // Non-static data members are shared by default. 909 if (FD) 910 DVar.CKind = OMPC_shared; 911 912 return DVar; 913 } 914 915 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced 916 // in a Construct, C/C++, predetermined, p.1] 917 // Variables with automatic storage duration that are declared in a scope 918 // inside the construct are private. 919 if (VD && isOpenMPLocal(VD, Iter) && VD->isLocalVarDecl() && 920 (VD->getStorageClass() == SC_Auto || VD->getStorageClass() == SC_None)) { 921 DVar.CKind = OMPC_private; 922 return DVar; 923 } 924 925 DVar.DKind = Iter->Directive; 926 // Explicitly specified attributes and local variables with predetermined 927 // attributes. 928 if (Iter->SharingMap.count(D)) { 929 const DSAInfo &Data = Iter->SharingMap.lookup(D); 930 DVar.RefExpr = Data.RefExpr.getPointer(); 931 DVar.PrivateCopy = Data.PrivateCopy; 932 DVar.CKind = Data.Attributes; 933 DVar.ImplicitDSALoc = Iter->DefaultAttrLoc; 934 return DVar; 935 } 936 937 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced 938 // in a Construct, C/C++, implicitly determined, p.1] 939 // In a parallel or task construct, the data-sharing attributes of these 940 // variables are determined by the default clause, if present. 941 switch (Iter->DefaultAttr) { 942 case DSA_shared: 943 DVar.CKind = OMPC_shared; 944 DVar.ImplicitDSALoc = Iter->DefaultAttrLoc; 945 return DVar; 946 case DSA_none: 947 return DVar; 948 case DSA_unspecified: 949 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced 950 // in a Construct, implicitly determined, p.2] 951 // In a parallel construct, if no default clause is present, these 952 // variables are shared. 953 DVar.ImplicitDSALoc = Iter->DefaultAttrLoc; 954 if (isOpenMPParallelDirective(DVar.DKind) || 955 isOpenMPTeamsDirective(DVar.DKind)) { 956 DVar.CKind = OMPC_shared; 957 return DVar; 958 } 959 960 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced 961 // in a Construct, implicitly determined, p.4] 962 // In a task construct, if no default clause is present, a variable that in 963 // the enclosing context is determined to be shared by all implicit tasks 964 // bound to the current team is shared. 965 if (isOpenMPTaskingDirective(DVar.DKind)) { 966 DSAVarData DVarTemp; 967 const_iterator I = Iter, E = end(); 968 do { 969 ++I; 970 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables 971 // Referenced in a Construct, implicitly determined, p.6] 972 // In a task construct, if no default clause is present, a variable 973 // whose data-sharing attribute is not determined by the rules above is 974 // firstprivate. 975 DVarTemp = getDSA(I, D); 976 if (DVarTemp.CKind != OMPC_shared) { 977 DVar.RefExpr = nullptr; 978 DVar.CKind = OMPC_firstprivate; 979 return DVar; 980 } 981 } while (I != E && !isImplicitTaskingRegion(I->Directive)); 982 DVar.CKind = 983 (DVarTemp.CKind == OMPC_unknown) ? OMPC_firstprivate : OMPC_shared; 984 return DVar; 985 } 986 } 987 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced 988 // in a Construct, implicitly determined, p.3] 989 // For constructs other than task, if no default clause is present, these 990 // variables inherit their data-sharing attributes from the enclosing 991 // context. 992 return getDSA(++Iter, D); 993 } 994 995 const Expr *DSAStackTy::addUniqueAligned(const ValueDecl *D, 996 const Expr *NewDE) { 997 assert(!isStackEmpty() && "Data sharing attributes stack is empty"); 998 D = getCanonicalDecl(D); 999 SharingMapTy &StackElem = getTopOfStack(); 1000 auto It = StackElem.AlignedMap.find(D); 1001 if (It == StackElem.AlignedMap.end()) { 1002 assert(NewDE && "Unexpected nullptr expr to be added into aligned map"); 1003 StackElem.AlignedMap[D] = NewDE; 1004 return nullptr; 1005 } 1006 assert(It->second && "Unexpected nullptr expr in the aligned map"); 1007 return It->second; 1008 } 1009 1010 void DSAStackTy::addLoopControlVariable(const ValueDecl *D, VarDecl *Capture) { 1011 assert(!isStackEmpty() && "Data-sharing attributes stack is empty"); 1012 D = getCanonicalDecl(D); 1013 SharingMapTy &StackElem = getTopOfStack(); 1014 StackElem.LCVMap.try_emplace( 1015 D, LCDeclInfo(StackElem.LCVMap.size() + 1, Capture)); 1016 } 1017 1018 const DSAStackTy::LCDeclInfo 1019 DSAStackTy::isLoopControlVariable(const ValueDecl *D) const { 1020 assert(!isStackEmpty() && "Data-sharing attributes stack is empty"); 1021 D = getCanonicalDecl(D); 1022 const SharingMapTy &StackElem = getTopOfStack(); 1023 auto It = StackElem.LCVMap.find(D); 1024 if (It != StackElem.LCVMap.end()) 1025 return It->second; 1026 return {0, nullptr}; 1027 } 1028 1029 const DSAStackTy::LCDeclInfo 1030 DSAStackTy::isParentLoopControlVariable(const ValueDecl *D) const { 1031 const SharingMapTy *Parent = getSecondOnStackOrNull(); 1032 assert(Parent && "Data-sharing attributes stack is empty"); 1033 D = getCanonicalDecl(D); 1034 auto It = Parent->LCVMap.find(D); 1035 if (It != Parent->LCVMap.end()) 1036 return It->second; 1037 return {0, nullptr}; 1038 } 1039 1040 const ValueDecl *DSAStackTy::getParentLoopControlVariable(unsigned I) const { 1041 const SharingMapTy *Parent = getSecondOnStackOrNull(); 1042 assert(Parent && "Data-sharing attributes stack is empty"); 1043 if (Parent->LCVMap.size() < I) 1044 return nullptr; 1045 for (const auto &Pair : Parent->LCVMap) 1046 if (Pair.second.first == I) 1047 return Pair.first; 1048 return nullptr; 1049 } 1050 1051 void DSAStackTy::addDSA(const ValueDecl *D, const Expr *E, OpenMPClauseKind A, 1052 DeclRefExpr *PrivateCopy) { 1053 D = getCanonicalDecl(D); 1054 if (A == OMPC_threadprivate) { 1055 DSAInfo &Data = Threadprivates[D]; 1056 Data.Attributes = A; 1057 Data.RefExpr.setPointer(E); 1058 Data.PrivateCopy = nullptr; 1059 } else { 1060 DSAInfo &Data = getTopOfStack().SharingMap[D]; 1061 assert(Data.Attributes == OMPC_unknown || (A == Data.Attributes) || 1062 (A == OMPC_firstprivate && Data.Attributes == OMPC_lastprivate) || 1063 (A == OMPC_lastprivate && Data.Attributes == OMPC_firstprivate) || 1064 (isLoopControlVariable(D).first && A == OMPC_private)); 1065 if (A == OMPC_lastprivate && Data.Attributes == OMPC_firstprivate) { 1066 Data.RefExpr.setInt(/*IntVal=*/true); 1067 return; 1068 } 1069 const bool IsLastprivate = 1070 A == OMPC_lastprivate || Data.Attributes == OMPC_lastprivate; 1071 Data.Attributes = A; 1072 Data.RefExpr.setPointerAndInt(E, IsLastprivate); 1073 Data.PrivateCopy = PrivateCopy; 1074 if (PrivateCopy) { 1075 DSAInfo &Data = getTopOfStack().SharingMap[PrivateCopy->getDecl()]; 1076 Data.Attributes = A; 1077 Data.RefExpr.setPointerAndInt(PrivateCopy, IsLastprivate); 1078 Data.PrivateCopy = nullptr; 1079 } 1080 } 1081 } 1082 1083 /// Build a variable declaration for OpenMP loop iteration variable. 1084 static VarDecl *buildVarDecl(Sema &SemaRef, SourceLocation Loc, QualType Type, 1085 StringRef Name, const AttrVec *Attrs = nullptr, 1086 DeclRefExpr *OrigRef = nullptr) { 1087 DeclContext *DC = SemaRef.CurContext; 1088 IdentifierInfo *II = &SemaRef.PP.getIdentifierTable().get(Name); 1089 TypeSourceInfo *TInfo = SemaRef.Context.getTrivialTypeSourceInfo(Type, Loc); 1090 auto *Decl = 1091 VarDecl::Create(SemaRef.Context, DC, Loc, Loc, II, Type, TInfo, SC_None); 1092 if (Attrs) { 1093 for (specific_attr_iterator<AlignedAttr> I(Attrs->begin()), E(Attrs->end()); 1094 I != E; ++I) 1095 Decl->addAttr(*I); 1096 } 1097 Decl->setImplicit(); 1098 if (OrigRef) { 1099 Decl->addAttr( 1100 OMPReferencedVarAttr::CreateImplicit(SemaRef.Context, OrigRef)); 1101 } 1102 return Decl; 1103 } 1104 1105 static DeclRefExpr *buildDeclRefExpr(Sema &S, VarDecl *D, QualType Ty, 1106 SourceLocation Loc, 1107 bool RefersToCapture = false) { 1108 D->setReferenced(); 1109 D->markUsed(S.Context); 1110 return DeclRefExpr::Create(S.getASTContext(), NestedNameSpecifierLoc(), 1111 SourceLocation(), D, RefersToCapture, Loc, Ty, 1112 VK_LValue); 1113 } 1114 1115 void DSAStackTy::addTaskgroupReductionData(const ValueDecl *D, SourceRange SR, 1116 BinaryOperatorKind BOK) { 1117 D = getCanonicalDecl(D); 1118 assert(!isStackEmpty() && "Data-sharing attributes stack is empty"); 1119 assert( 1120 getTopOfStack().SharingMap[D].Attributes == OMPC_reduction && 1121 "Additional reduction info may be specified only for reduction items."); 1122 ReductionData &ReductionData = getTopOfStack().ReductionMap[D]; 1123 assert(ReductionData.ReductionRange.isInvalid() && 1124 getTopOfStack().Directive == OMPD_taskgroup && 1125 "Additional reduction info may be specified only once for reduction " 1126 "items."); 1127 ReductionData.set(BOK, SR); 1128 Expr *&TaskgroupReductionRef = 1129 getTopOfStack().TaskgroupReductionRef; 1130 if (!TaskgroupReductionRef) { 1131 VarDecl *VD = buildVarDecl(SemaRef, SR.getBegin(), 1132 SemaRef.Context.VoidPtrTy, ".task_red."); 1133 TaskgroupReductionRef = 1134 buildDeclRefExpr(SemaRef, VD, SemaRef.Context.VoidPtrTy, SR.getBegin()); 1135 } 1136 } 1137 1138 void DSAStackTy::addTaskgroupReductionData(const ValueDecl *D, SourceRange SR, 1139 const Expr *ReductionRef) { 1140 D = getCanonicalDecl(D); 1141 assert(!isStackEmpty() && "Data-sharing attributes stack is empty"); 1142 assert( 1143 getTopOfStack().SharingMap[D].Attributes == OMPC_reduction && 1144 "Additional reduction info may be specified only for reduction items."); 1145 ReductionData &ReductionData = getTopOfStack().ReductionMap[D]; 1146 assert(ReductionData.ReductionRange.isInvalid() && 1147 getTopOfStack().Directive == OMPD_taskgroup && 1148 "Additional reduction info may be specified only once for reduction " 1149 "items."); 1150 ReductionData.set(ReductionRef, SR); 1151 Expr *&TaskgroupReductionRef = 1152 getTopOfStack().TaskgroupReductionRef; 1153 if (!TaskgroupReductionRef) { 1154 VarDecl *VD = buildVarDecl(SemaRef, SR.getBegin(), 1155 SemaRef.Context.VoidPtrTy, ".task_red."); 1156 TaskgroupReductionRef = 1157 buildDeclRefExpr(SemaRef, VD, SemaRef.Context.VoidPtrTy, SR.getBegin()); 1158 } 1159 } 1160 1161 const DSAStackTy::DSAVarData DSAStackTy::getTopMostTaskgroupReductionData( 1162 const ValueDecl *D, SourceRange &SR, BinaryOperatorKind &BOK, 1163 Expr *&TaskgroupDescriptor) const { 1164 D = getCanonicalDecl(D); 1165 assert(!isStackEmpty() && "Data-sharing attributes stack is empty."); 1166 for (const_iterator I = begin() + 1, E = end(); I != E; ++I) { 1167 const DSAInfo &Data = I->SharingMap.lookup(D); 1168 if (Data.Attributes != OMPC_reduction || I->Directive != OMPD_taskgroup) 1169 continue; 1170 const ReductionData &ReductionData = I->ReductionMap.lookup(D); 1171 if (!ReductionData.ReductionOp || 1172 ReductionData.ReductionOp.is<const Expr *>()) 1173 return DSAVarData(); 1174 SR = ReductionData.ReductionRange; 1175 BOK = ReductionData.ReductionOp.get<ReductionData::BOKPtrType>(); 1176 assert(I->TaskgroupReductionRef && "taskgroup reduction reference " 1177 "expression for the descriptor is not " 1178 "set."); 1179 TaskgroupDescriptor = I->TaskgroupReductionRef; 1180 return DSAVarData(OMPD_taskgroup, OMPC_reduction, Data.RefExpr.getPointer(), 1181 Data.PrivateCopy, I->DefaultAttrLoc); 1182 } 1183 return DSAVarData(); 1184 } 1185 1186 const DSAStackTy::DSAVarData DSAStackTy::getTopMostTaskgroupReductionData( 1187 const ValueDecl *D, SourceRange &SR, const Expr *&ReductionRef, 1188 Expr *&TaskgroupDescriptor) const { 1189 D = getCanonicalDecl(D); 1190 assert(!isStackEmpty() && "Data-sharing attributes stack is empty."); 1191 for (const_iterator I = begin() + 1, E = end(); I != E; ++I) { 1192 const DSAInfo &Data = I->SharingMap.lookup(D); 1193 if (Data.Attributes != OMPC_reduction || I->Directive != OMPD_taskgroup) 1194 continue; 1195 const ReductionData &ReductionData = I->ReductionMap.lookup(D); 1196 if (!ReductionData.ReductionOp || 1197 !ReductionData.ReductionOp.is<const Expr *>()) 1198 return DSAVarData(); 1199 SR = ReductionData.ReductionRange; 1200 ReductionRef = ReductionData.ReductionOp.get<const Expr *>(); 1201 assert(I->TaskgroupReductionRef && "taskgroup reduction reference " 1202 "expression for the descriptor is not " 1203 "set."); 1204 TaskgroupDescriptor = I->TaskgroupReductionRef; 1205 return DSAVarData(OMPD_taskgroup, OMPC_reduction, Data.RefExpr.getPointer(), 1206 Data.PrivateCopy, I->DefaultAttrLoc); 1207 } 1208 return DSAVarData(); 1209 } 1210 1211 bool DSAStackTy::isOpenMPLocal(VarDecl *D, const_iterator I) const { 1212 D = D->getCanonicalDecl(); 1213 for (const_iterator E = end(); I != E; ++I) { 1214 if (isImplicitOrExplicitTaskingRegion(I->Directive) || 1215 isOpenMPTargetExecutionDirective(I->Directive)) { 1216 Scope *TopScope = I->CurScope ? I->CurScope->getParent() : nullptr; 1217 Scope *CurScope = getCurScope(); 1218 while (CurScope && CurScope != TopScope && !CurScope->isDeclScope(D)) 1219 CurScope = CurScope->getParent(); 1220 return CurScope != TopScope; 1221 } 1222 } 1223 return false; 1224 } 1225 1226 static bool isConstNotMutableType(Sema &SemaRef, QualType Type, 1227 bool AcceptIfMutable = true, 1228 bool *IsClassType = nullptr) { 1229 ASTContext &Context = SemaRef.getASTContext(); 1230 Type = Type.getNonReferenceType().getCanonicalType(); 1231 bool IsConstant = Type.isConstant(Context); 1232 Type = Context.getBaseElementType(Type); 1233 const CXXRecordDecl *RD = AcceptIfMutable && SemaRef.getLangOpts().CPlusPlus 1234 ? Type->getAsCXXRecordDecl() 1235 : nullptr; 1236 if (const auto *CTSD = dyn_cast_or_null<ClassTemplateSpecializationDecl>(RD)) 1237 if (const ClassTemplateDecl *CTD = CTSD->getSpecializedTemplate()) 1238 RD = CTD->getTemplatedDecl(); 1239 if (IsClassType) 1240 *IsClassType = RD; 1241 return IsConstant && !(SemaRef.getLangOpts().CPlusPlus && RD && 1242 RD->hasDefinition() && RD->hasMutableFields()); 1243 } 1244 1245 static bool rejectConstNotMutableType(Sema &SemaRef, const ValueDecl *D, 1246 QualType Type, OpenMPClauseKind CKind, 1247 SourceLocation ELoc, 1248 bool AcceptIfMutable = true, 1249 bool ListItemNotVar = false) { 1250 ASTContext &Context = SemaRef.getASTContext(); 1251 bool IsClassType; 1252 if (isConstNotMutableType(SemaRef, Type, AcceptIfMutable, &IsClassType)) { 1253 unsigned Diag = ListItemNotVar 1254 ? diag::err_omp_const_list_item 1255 : IsClassType ? diag::err_omp_const_not_mutable_variable 1256 : diag::err_omp_const_variable; 1257 SemaRef.Diag(ELoc, Diag) << getOpenMPClauseName(CKind); 1258 if (!ListItemNotVar && D) { 1259 const VarDecl *VD = dyn_cast<VarDecl>(D); 1260 bool IsDecl = !VD || VD->isThisDeclarationADefinition(Context) == 1261 VarDecl::DeclarationOnly; 1262 SemaRef.Diag(D->getLocation(), 1263 IsDecl ? diag::note_previous_decl : diag::note_defined_here) 1264 << D; 1265 } 1266 return true; 1267 } 1268 return false; 1269 } 1270 1271 const DSAStackTy::DSAVarData DSAStackTy::getTopDSA(ValueDecl *D, 1272 bool FromParent) { 1273 D = getCanonicalDecl(D); 1274 DSAVarData DVar; 1275 1276 auto *VD = dyn_cast<VarDecl>(D); 1277 auto TI = Threadprivates.find(D); 1278 if (TI != Threadprivates.end()) { 1279 DVar.RefExpr = TI->getSecond().RefExpr.getPointer(); 1280 DVar.CKind = OMPC_threadprivate; 1281 return DVar; 1282 } 1283 if (VD && VD->hasAttr<OMPThreadPrivateDeclAttr>()) { 1284 DVar.RefExpr = buildDeclRefExpr( 1285 SemaRef, VD, D->getType().getNonReferenceType(), 1286 VD->getAttr<OMPThreadPrivateDeclAttr>()->getLocation()); 1287 DVar.CKind = OMPC_threadprivate; 1288 addDSA(D, DVar.RefExpr, OMPC_threadprivate); 1289 return DVar; 1290 } 1291 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced 1292 // in a Construct, C/C++, predetermined, p.1] 1293 // Variables appearing in threadprivate directives are threadprivate. 1294 if ((VD && VD->getTLSKind() != VarDecl::TLS_None && 1295 !(VD->hasAttr<OMPThreadPrivateDeclAttr>() && 1296 SemaRef.getLangOpts().OpenMPUseTLS && 1297 SemaRef.getASTContext().getTargetInfo().isTLSSupported())) || 1298 (VD && VD->getStorageClass() == SC_Register && 1299 VD->hasAttr<AsmLabelAttr>() && !VD->isLocalVarDecl())) { 1300 DVar.RefExpr = buildDeclRefExpr( 1301 SemaRef, VD, D->getType().getNonReferenceType(), D->getLocation()); 1302 DVar.CKind = OMPC_threadprivate; 1303 addDSA(D, DVar.RefExpr, OMPC_threadprivate); 1304 return DVar; 1305 } 1306 if (SemaRef.getLangOpts().OpenMPCUDAMode && VD && 1307 VD->isLocalVarDeclOrParm() && !isStackEmpty() && 1308 !isLoopControlVariable(D).first) { 1309 const_iterator IterTarget = 1310 std::find_if(begin(), end(), [](const SharingMapTy &Data) { 1311 return isOpenMPTargetExecutionDirective(Data.Directive); 1312 }); 1313 if (IterTarget != end()) { 1314 const_iterator ParentIterTarget = IterTarget + 1; 1315 for (const_iterator Iter = begin(); 1316 Iter != ParentIterTarget; ++Iter) { 1317 if (isOpenMPLocal(VD, Iter)) { 1318 DVar.RefExpr = 1319 buildDeclRefExpr(SemaRef, VD, D->getType().getNonReferenceType(), 1320 D->getLocation()); 1321 DVar.CKind = OMPC_threadprivate; 1322 return DVar; 1323 } 1324 } 1325 if (!isClauseParsingMode() || IterTarget != begin()) { 1326 auto DSAIter = IterTarget->SharingMap.find(D); 1327 if (DSAIter != IterTarget->SharingMap.end() && 1328 isOpenMPPrivate(DSAIter->getSecond().Attributes)) { 1329 DVar.RefExpr = DSAIter->getSecond().RefExpr.getPointer(); 1330 DVar.CKind = OMPC_threadprivate; 1331 return DVar; 1332 } 1333 const_iterator End = end(); 1334 if (!SemaRef.isOpenMPCapturedByRef( 1335 D, std::distance(ParentIterTarget, End))) { 1336 DVar.RefExpr = 1337 buildDeclRefExpr(SemaRef, VD, D->getType().getNonReferenceType(), 1338 IterTarget->ConstructLoc); 1339 DVar.CKind = OMPC_threadprivate; 1340 return DVar; 1341 } 1342 } 1343 } 1344 } 1345 1346 if (isStackEmpty()) 1347 // Not in OpenMP execution region and top scope was already checked. 1348 return DVar; 1349 1350 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced 1351 // in a Construct, C/C++, predetermined, p.4] 1352 // Static data members are shared. 1353 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced 1354 // in a Construct, C/C++, predetermined, p.7] 1355 // Variables with static storage duration that are declared in a scope 1356 // inside the construct are shared. 1357 if (VD && VD->isStaticDataMember()) { 1358 // Check for explicitly specified attributes. 1359 const_iterator I = begin(); 1360 const_iterator EndI = end(); 1361 if (FromParent && I != EndI) 1362 ++I; 1363 auto It = I->SharingMap.find(D); 1364 if (It != I->SharingMap.end()) { 1365 const DSAInfo &Data = It->getSecond(); 1366 DVar.RefExpr = Data.RefExpr.getPointer(); 1367 DVar.PrivateCopy = Data.PrivateCopy; 1368 DVar.CKind = Data.Attributes; 1369 DVar.ImplicitDSALoc = I->DefaultAttrLoc; 1370 DVar.DKind = I->Directive; 1371 return DVar; 1372 } 1373 1374 DVar.CKind = OMPC_shared; 1375 return DVar; 1376 } 1377 1378 auto &&MatchesAlways = [](OpenMPDirectiveKind) { return true; }; 1379 // The predetermined shared attribute for const-qualified types having no 1380 // mutable members was removed after OpenMP 3.1. 1381 if (SemaRef.LangOpts.OpenMP <= 31) { 1382 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced 1383 // in a Construct, C/C++, predetermined, p.6] 1384 // Variables with const qualified type having no mutable member are 1385 // shared. 1386 if (isConstNotMutableType(SemaRef, D->getType())) { 1387 // Variables with const-qualified type having no mutable member may be 1388 // listed in a firstprivate clause, even if they are static data members. 1389 DSAVarData DVarTemp = hasInnermostDSA( 1390 D, 1391 [](OpenMPClauseKind C) { 1392 return C == OMPC_firstprivate || C == OMPC_shared; 1393 }, 1394 MatchesAlways, FromParent); 1395 if (DVarTemp.CKind != OMPC_unknown && DVarTemp.RefExpr) 1396 return DVarTemp; 1397 1398 DVar.CKind = OMPC_shared; 1399 return DVar; 1400 } 1401 } 1402 1403 // Explicitly specified attributes and local variables with predetermined 1404 // attributes. 1405 const_iterator I = begin(); 1406 const_iterator EndI = end(); 1407 if (FromParent && I != EndI) 1408 ++I; 1409 auto It = I->SharingMap.find(D); 1410 if (It != I->SharingMap.end()) { 1411 const DSAInfo &Data = It->getSecond(); 1412 DVar.RefExpr = Data.RefExpr.getPointer(); 1413 DVar.PrivateCopy = Data.PrivateCopy; 1414 DVar.CKind = Data.Attributes; 1415 DVar.ImplicitDSALoc = I->DefaultAttrLoc; 1416 DVar.DKind = I->Directive; 1417 } 1418 1419 return DVar; 1420 } 1421 1422 const DSAStackTy::DSAVarData DSAStackTy::getImplicitDSA(ValueDecl *D, 1423 bool FromParent) const { 1424 if (isStackEmpty()) { 1425 const_iterator I; 1426 return getDSA(I, D); 1427 } 1428 D = getCanonicalDecl(D); 1429 const_iterator StartI = begin(); 1430 const_iterator EndI = end(); 1431 if (FromParent && StartI != EndI) 1432 ++StartI; 1433 return getDSA(StartI, D); 1434 } 1435 1436 const DSAStackTy::DSAVarData 1437 DSAStackTy::hasDSA(ValueDecl *D, 1438 const llvm::function_ref<bool(OpenMPClauseKind)> CPred, 1439 const llvm::function_ref<bool(OpenMPDirectiveKind)> DPred, 1440 bool FromParent) const { 1441 if (isStackEmpty()) 1442 return {}; 1443 D = getCanonicalDecl(D); 1444 const_iterator I = begin(); 1445 const_iterator EndI = end(); 1446 if (FromParent && I != EndI) 1447 ++I; 1448 for (; I != EndI; ++I) { 1449 if (!DPred(I->Directive) && 1450 !isImplicitOrExplicitTaskingRegion(I->Directive)) 1451 continue; 1452 const_iterator NewI = I; 1453 DSAVarData DVar = getDSA(NewI, D); 1454 if (I == NewI && CPred(DVar.CKind)) 1455 return DVar; 1456 } 1457 return {}; 1458 } 1459 1460 const DSAStackTy::DSAVarData DSAStackTy::hasInnermostDSA( 1461 ValueDecl *D, const llvm::function_ref<bool(OpenMPClauseKind)> CPred, 1462 const llvm::function_ref<bool(OpenMPDirectiveKind)> DPred, 1463 bool FromParent) const { 1464 if (isStackEmpty()) 1465 return {}; 1466 D = getCanonicalDecl(D); 1467 const_iterator StartI = begin(); 1468 const_iterator EndI = end(); 1469 if (FromParent && StartI != EndI) 1470 ++StartI; 1471 if (StartI == EndI || !DPred(StartI->Directive)) 1472 return {}; 1473 const_iterator NewI = StartI; 1474 DSAVarData DVar = getDSA(NewI, D); 1475 return (NewI == StartI && CPred(DVar.CKind)) ? DVar : DSAVarData(); 1476 } 1477 1478 bool DSAStackTy::hasExplicitDSA( 1479 const ValueDecl *D, const llvm::function_ref<bool(OpenMPClauseKind)> CPred, 1480 unsigned Level, bool NotLastprivate) const { 1481 if (getStackSize() <= Level) 1482 return false; 1483 D = getCanonicalDecl(D); 1484 const SharingMapTy &StackElem = getStackElemAtLevel(Level); 1485 auto I = StackElem.SharingMap.find(D); 1486 if (I != StackElem.SharingMap.end() && 1487 I->getSecond().RefExpr.getPointer() && 1488 CPred(I->getSecond().Attributes) && 1489 (!NotLastprivate || !I->getSecond().RefExpr.getInt())) 1490 return true; 1491 // Check predetermined rules for the loop control variables. 1492 auto LI = StackElem.LCVMap.find(D); 1493 if (LI != StackElem.LCVMap.end()) 1494 return CPred(OMPC_private); 1495 return false; 1496 } 1497 1498 bool DSAStackTy::hasExplicitDirective( 1499 const llvm::function_ref<bool(OpenMPDirectiveKind)> DPred, 1500 unsigned Level) const { 1501 if (getStackSize() <= Level) 1502 return false; 1503 const SharingMapTy &StackElem = getStackElemAtLevel(Level); 1504 return DPred(StackElem.Directive); 1505 } 1506 1507 bool DSAStackTy::hasDirective( 1508 const llvm::function_ref<bool(OpenMPDirectiveKind, 1509 const DeclarationNameInfo &, SourceLocation)> 1510 DPred, 1511 bool FromParent) const { 1512 // We look only in the enclosing region. 1513 size_t Skip = FromParent ? 2 : 1; 1514 for (const_iterator I = begin() + std::min(Skip, getStackSize()), E = end(); 1515 I != E; ++I) { 1516 if (DPred(I->Directive, I->DirectiveName, I->ConstructLoc)) 1517 return true; 1518 } 1519 return false; 1520 } 1521 1522 void Sema::InitDataSharingAttributesStack() { 1523 VarDataSharingAttributesStack = new DSAStackTy(*this); 1524 } 1525 1526 #define DSAStack static_cast<DSAStackTy *>(VarDataSharingAttributesStack) 1527 1528 void Sema::pushOpenMPFunctionRegion() { 1529 DSAStack->pushFunction(); 1530 } 1531 1532 void Sema::popOpenMPFunctionRegion(const FunctionScopeInfo *OldFSI) { 1533 DSAStack->popFunction(OldFSI); 1534 } 1535 1536 static bool isOpenMPDeviceDelayedContext(Sema &S) { 1537 assert(S.LangOpts.OpenMP && S.LangOpts.OpenMPIsDevice && 1538 "Expected OpenMP device compilation."); 1539 return !S.isInOpenMPTargetExecutionDirective() && 1540 !S.isInOpenMPDeclareTargetContext(); 1541 } 1542 1543 /// Do we know that we will eventually codegen the given function? 1544 static bool isKnownEmitted(Sema &S, FunctionDecl *FD) { 1545 assert(S.LangOpts.OpenMP && S.LangOpts.OpenMPIsDevice && 1546 "Expected OpenMP device compilation."); 1547 // Templates are emitted when they're instantiated. 1548 if (FD->isDependentContext()) 1549 return false; 1550 1551 if (OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration( 1552 FD->getCanonicalDecl())) 1553 return true; 1554 1555 // Otherwise, the function is known-emitted if it's in our set of 1556 // known-emitted functions. 1557 return S.DeviceKnownEmittedFns.count(FD) > 0; 1558 } 1559 1560 Sema::DeviceDiagBuilder Sema::diagIfOpenMPDeviceCode(SourceLocation Loc, 1561 unsigned DiagID) { 1562 assert(LangOpts.OpenMP && LangOpts.OpenMPIsDevice && 1563 "Expected OpenMP device compilation."); 1564 return DeviceDiagBuilder((isOpenMPDeviceDelayedContext(*this) && 1565 !isKnownEmitted(*this, getCurFunctionDecl())) 1566 ? DeviceDiagBuilder::K_Deferred 1567 : DeviceDiagBuilder::K_Immediate, 1568 Loc, DiagID, getCurFunctionDecl(), *this); 1569 } 1570 1571 void Sema::checkOpenMPDeviceFunction(SourceLocation Loc, FunctionDecl *Callee) { 1572 assert(LangOpts.OpenMP && LangOpts.OpenMPIsDevice && 1573 "Expected OpenMP device compilation."); 1574 assert(Callee && "Callee may not be null."); 1575 FunctionDecl *Caller = getCurFunctionDecl(); 1576 1577 // If the caller is known-emitted, mark the callee as known-emitted. 1578 // Otherwise, mark the call in our call graph so we can traverse it later. 1579 if (!isOpenMPDeviceDelayedContext(*this) || 1580 (Caller && isKnownEmitted(*this, Caller))) 1581 markKnownEmitted(*this, Caller, Callee, Loc, isKnownEmitted); 1582 else if (Caller) 1583 DeviceCallGraph[Caller].insert({Callee, Loc}); 1584 } 1585 1586 void Sema::checkOpenMPDeviceExpr(const Expr *E) { 1587 assert(getLangOpts().OpenMP && getLangOpts().OpenMPIsDevice && 1588 "OpenMP device compilation mode is expected."); 1589 QualType Ty = E->getType(); 1590 if ((Ty->isFloat16Type() && !Context.getTargetInfo().hasFloat16Type()) || 1591 ((Ty->isFloat128Type() || 1592 (Ty->isRealFloatingType() && Context.getTypeSize(Ty) == 128)) && 1593 !Context.getTargetInfo().hasFloat128Type()) || 1594 (Ty->isIntegerType() && Context.getTypeSize(Ty) == 128 && 1595 !Context.getTargetInfo().hasInt128Type())) 1596 targetDiag(E->getExprLoc(), diag::err_omp_unsupported_type) 1597 << static_cast<unsigned>(Context.getTypeSize(Ty)) << Ty 1598 << Context.getTargetInfo().getTriple().str() << E->getSourceRange(); 1599 } 1600 1601 bool Sema::isOpenMPCapturedByRef(const ValueDecl *D, unsigned Level) const { 1602 assert(LangOpts.OpenMP && "OpenMP is not allowed"); 1603 1604 ASTContext &Ctx = getASTContext(); 1605 bool IsByRef = true; 1606 1607 // Find the directive that is associated with the provided scope. 1608 D = cast<ValueDecl>(D->getCanonicalDecl()); 1609 QualType Ty = D->getType(); 1610 1611 if (DSAStack->hasExplicitDirective(isOpenMPTargetExecutionDirective, Level)) { 1612 // This table summarizes how a given variable should be passed to the device 1613 // given its type and the clauses where it appears. This table is based on 1614 // the description in OpenMP 4.5 [2.10.4, target Construct] and 1615 // OpenMP 4.5 [2.15.5, Data-mapping Attribute Rules and Clauses]. 1616 // 1617 // ========================================================================= 1618 // | type | defaultmap | pvt | first | is_device_ptr | map | res. | 1619 // | |(tofrom:scalar)| | pvt | | | | 1620 // ========================================================================= 1621 // | scl | | | | - | | bycopy| 1622 // | scl | | - | x | - | - | bycopy| 1623 // | scl | | x | - | - | - | null | 1624 // | scl | x | | | - | | byref | 1625 // | scl | x | - | x | - | - | bycopy| 1626 // | scl | x | x | - | - | - | null | 1627 // | scl | | - | - | - | x | byref | 1628 // | scl | x | - | - | - | x | byref | 1629 // 1630 // | agg | n.a. | | | - | | byref | 1631 // | agg | n.a. | - | x | - | - | byref | 1632 // | agg | n.a. | x | - | - | - | null | 1633 // | agg | n.a. | - | - | - | x | byref | 1634 // | agg | n.a. | - | - | - | x[] | byref | 1635 // 1636 // | ptr | n.a. | | | - | | bycopy| 1637 // | ptr | n.a. | - | x | - | - | bycopy| 1638 // | ptr | n.a. | x | - | - | - | null | 1639 // | ptr | n.a. | - | - | - | x | byref | 1640 // | ptr | n.a. | - | - | - | x[] | bycopy| 1641 // | ptr | n.a. | - | - | x | | bycopy| 1642 // | ptr | n.a. | - | - | x | x | bycopy| 1643 // | ptr | n.a. | - | - | x | x[] | bycopy| 1644 // ========================================================================= 1645 // Legend: 1646 // scl - scalar 1647 // ptr - pointer 1648 // agg - aggregate 1649 // x - applies 1650 // - - invalid in this combination 1651 // [] - mapped with an array section 1652 // byref - should be mapped by reference 1653 // byval - should be mapped by value 1654 // null - initialize a local variable to null on the device 1655 // 1656 // Observations: 1657 // - All scalar declarations that show up in a map clause have to be passed 1658 // by reference, because they may have been mapped in the enclosing data 1659 // environment. 1660 // - If the scalar value does not fit the size of uintptr, it has to be 1661 // passed by reference, regardless the result in the table above. 1662 // - For pointers mapped by value that have either an implicit map or an 1663 // array section, the runtime library may pass the NULL value to the 1664 // device instead of the value passed to it by the compiler. 1665 1666 if (Ty->isReferenceType()) 1667 Ty = Ty->castAs<ReferenceType>()->getPointeeType(); 1668 1669 // Locate map clauses and see if the variable being captured is referred to 1670 // in any of those clauses. Here we only care about variables, not fields, 1671 // because fields are part of aggregates. 1672 bool IsVariableUsedInMapClause = false; 1673 bool IsVariableAssociatedWithSection = false; 1674 1675 DSAStack->checkMappableExprComponentListsForDeclAtLevel( 1676 D, Level, 1677 [&IsVariableUsedInMapClause, &IsVariableAssociatedWithSection, D]( 1678 OMPClauseMappableExprCommon::MappableExprComponentListRef 1679 MapExprComponents, 1680 OpenMPClauseKind WhereFoundClauseKind) { 1681 // Only the map clause information influences how a variable is 1682 // captured. E.g. is_device_ptr does not require changing the default 1683 // behavior. 1684 if (WhereFoundClauseKind != OMPC_map) 1685 return false; 1686 1687 auto EI = MapExprComponents.rbegin(); 1688 auto EE = MapExprComponents.rend(); 1689 1690 assert(EI != EE && "Invalid map expression!"); 1691 1692 if (isa<DeclRefExpr>(EI->getAssociatedExpression())) 1693 IsVariableUsedInMapClause |= EI->getAssociatedDeclaration() == D; 1694 1695 ++EI; 1696 if (EI == EE) 1697 return false; 1698 1699 if (isa<ArraySubscriptExpr>(EI->getAssociatedExpression()) || 1700 isa<OMPArraySectionExpr>(EI->getAssociatedExpression()) || 1701 isa<MemberExpr>(EI->getAssociatedExpression())) { 1702 IsVariableAssociatedWithSection = true; 1703 // There is nothing more we need to know about this variable. 1704 return true; 1705 } 1706 1707 // Keep looking for more map info. 1708 return false; 1709 }); 1710 1711 if (IsVariableUsedInMapClause) { 1712 // If variable is identified in a map clause it is always captured by 1713 // reference except if it is a pointer that is dereferenced somehow. 1714 IsByRef = !(Ty->isPointerType() && IsVariableAssociatedWithSection); 1715 } else { 1716 // By default, all the data that has a scalar type is mapped by copy 1717 // (except for reduction variables). 1718 IsByRef = 1719 (DSAStack->isForceCaptureByReferenceInTargetExecutable() && 1720 !Ty->isAnyPointerType()) || 1721 !Ty->isScalarType() || 1722 DSAStack->getDefaultDMAAtLevel(Level) == DMA_tofrom_scalar || 1723 DSAStack->hasExplicitDSA( 1724 D, [](OpenMPClauseKind K) { return K == OMPC_reduction; }, Level); 1725 } 1726 } 1727 1728 if (IsByRef && Ty.getNonReferenceType()->isScalarType()) { 1729 IsByRef = 1730 !DSAStack->hasExplicitDSA( 1731 D, 1732 [](OpenMPClauseKind K) -> bool { return K == OMPC_firstprivate; }, 1733 Level, /*NotLastprivate=*/true) && 1734 // If the variable is artificial and must be captured by value - try to 1735 // capture by value. 1736 !(isa<OMPCapturedExprDecl>(D) && !D->hasAttr<OMPCaptureNoInitAttr>() && 1737 !cast<OMPCapturedExprDecl>(D)->getInit()->isGLValue()); 1738 } 1739 1740 // When passing data by copy, we need to make sure it fits the uintptr size 1741 // and alignment, because the runtime library only deals with uintptr types. 1742 // If it does not fit the uintptr size, we need to pass the data by reference 1743 // instead. 1744 if (!IsByRef && 1745 (Ctx.getTypeSizeInChars(Ty) > 1746 Ctx.getTypeSizeInChars(Ctx.getUIntPtrType()) || 1747 Ctx.getDeclAlign(D) > Ctx.getTypeAlignInChars(Ctx.getUIntPtrType()))) { 1748 IsByRef = true; 1749 } 1750 1751 return IsByRef; 1752 } 1753 1754 unsigned Sema::getOpenMPNestingLevel() const { 1755 assert(getLangOpts().OpenMP); 1756 return DSAStack->getNestingLevel(); 1757 } 1758 1759 bool Sema::isInOpenMPTargetExecutionDirective() const { 1760 return (isOpenMPTargetExecutionDirective(DSAStack->getCurrentDirective()) && 1761 !DSAStack->isClauseParsingMode()) || 1762 DSAStack->hasDirective( 1763 [](OpenMPDirectiveKind K, const DeclarationNameInfo &, 1764 SourceLocation) -> bool { 1765 return isOpenMPTargetExecutionDirective(K); 1766 }, 1767 false); 1768 } 1769 1770 VarDecl *Sema::isOpenMPCapturedDecl(ValueDecl *D, bool CheckScopeInfo, 1771 unsigned StopAt) { 1772 assert(LangOpts.OpenMP && "OpenMP is not allowed"); 1773 D = getCanonicalDecl(D); 1774 1775 // If we want to determine whether the variable should be captured from the 1776 // perspective of the current capturing scope, and we've already left all the 1777 // capturing scopes of the top directive on the stack, check from the 1778 // perspective of its parent directive (if any) instead. 1779 DSAStackTy::ParentDirectiveScope InParentDirectiveRAII( 1780 *DSAStack, CheckScopeInfo && DSAStack->isBodyComplete()); 1781 1782 // If we are attempting to capture a global variable in a directive with 1783 // 'target' we return true so that this global is also mapped to the device. 1784 // 1785 auto *VD = dyn_cast<VarDecl>(D); 1786 if (VD && !VD->hasLocalStorage() && 1787 (getCurCapturedRegion() || getCurBlock() || getCurLambda())) { 1788 if (isInOpenMPDeclareTargetContext()) { 1789 // Try to mark variable as declare target if it is used in capturing 1790 // regions. 1791 if (!OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD)) 1792 checkDeclIsAllowedInOpenMPTarget(nullptr, VD); 1793 return nullptr; 1794 } else if (isInOpenMPTargetExecutionDirective()) { 1795 // If the declaration is enclosed in a 'declare target' directive, 1796 // then it should not be captured. 1797 // 1798 if (OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD)) 1799 return nullptr; 1800 return VD; 1801 } 1802 } 1803 1804 if (CheckScopeInfo) { 1805 bool OpenMPFound = false; 1806 for (unsigned I = StopAt + 1; I > 0; --I) { 1807 FunctionScopeInfo *FSI = FunctionScopes[I - 1]; 1808 if(!isa<CapturingScopeInfo>(FSI)) 1809 return nullptr; 1810 if (auto *RSI = dyn_cast<CapturedRegionScopeInfo>(FSI)) 1811 if (RSI->CapRegionKind == CR_OpenMP) { 1812 OpenMPFound = true; 1813 break; 1814 } 1815 } 1816 if (!OpenMPFound) 1817 return nullptr; 1818 } 1819 1820 if (DSAStack->getCurrentDirective() != OMPD_unknown && 1821 (!DSAStack->isClauseParsingMode() || 1822 DSAStack->getParentDirective() != OMPD_unknown)) { 1823 auto &&Info = DSAStack->isLoopControlVariable(D); 1824 if (Info.first || 1825 (VD && VD->hasLocalStorage() && 1826 isImplicitOrExplicitTaskingRegion(DSAStack->getCurrentDirective())) || 1827 (VD && DSAStack->isForceVarCapturing())) 1828 return VD ? VD : Info.second; 1829 DSAStackTy::DSAVarData DVarPrivate = 1830 DSAStack->getTopDSA(D, DSAStack->isClauseParsingMode()); 1831 if (DVarPrivate.CKind != OMPC_unknown && isOpenMPPrivate(DVarPrivate.CKind)) 1832 return VD ? VD : cast<VarDecl>(DVarPrivate.PrivateCopy->getDecl()); 1833 // Threadprivate variables must not be captured. 1834 if (isOpenMPThreadPrivate(DVarPrivate.CKind)) 1835 return nullptr; 1836 // The variable is not private or it is the variable in the directive with 1837 // default(none) clause and not used in any clause. 1838 DVarPrivate = DSAStack->hasDSA(D, isOpenMPPrivate, 1839 [](OpenMPDirectiveKind) { return true; }, 1840 DSAStack->isClauseParsingMode()); 1841 if (DVarPrivate.CKind != OMPC_unknown || 1842 (VD && DSAStack->getDefaultDSA() == DSA_none)) 1843 return VD ? VD : cast<VarDecl>(DVarPrivate.PrivateCopy->getDecl()); 1844 } 1845 return nullptr; 1846 } 1847 1848 void Sema::adjustOpenMPTargetScopeIndex(unsigned &FunctionScopesIndex, 1849 unsigned Level) const { 1850 SmallVector<OpenMPDirectiveKind, 4> Regions; 1851 getOpenMPCaptureRegions(Regions, DSAStack->getDirective(Level)); 1852 FunctionScopesIndex -= Regions.size(); 1853 } 1854 1855 void Sema::startOpenMPLoop() { 1856 assert(LangOpts.OpenMP && "OpenMP must be enabled."); 1857 if (isOpenMPLoopDirective(DSAStack->getCurrentDirective())) 1858 DSAStack->loopInit(); 1859 } 1860 1861 bool Sema::isOpenMPPrivateDecl(const ValueDecl *D, unsigned Level) const { 1862 assert(LangOpts.OpenMP && "OpenMP is not allowed"); 1863 if (isOpenMPLoopDirective(DSAStack->getCurrentDirective())) { 1864 if (DSAStack->getAssociatedLoops() > 0 && 1865 !DSAStack->isLoopStarted()) { 1866 DSAStack->resetPossibleLoopCounter(D); 1867 DSAStack->loopStart(); 1868 return true; 1869 } 1870 if ((DSAStack->getPossiblyLoopCunter() == D->getCanonicalDecl() || 1871 DSAStack->isLoopControlVariable(D).first) && 1872 !DSAStack->hasExplicitDSA( 1873 D, [](OpenMPClauseKind K) { return K != OMPC_private; }, Level) && 1874 !isOpenMPSimdDirective(DSAStack->getCurrentDirective())) 1875 return true; 1876 } 1877 return DSAStack->hasExplicitDSA( 1878 D, [](OpenMPClauseKind K) { return K == OMPC_private; }, Level) || 1879 (DSAStack->isClauseParsingMode() && 1880 DSAStack->getClauseParsingMode() == OMPC_private) || 1881 // Consider taskgroup reduction descriptor variable a private to avoid 1882 // possible capture in the region. 1883 (DSAStack->hasExplicitDirective( 1884 [](OpenMPDirectiveKind K) { return K == OMPD_taskgroup; }, 1885 Level) && 1886 DSAStack->isTaskgroupReductionRef(D, Level)); 1887 } 1888 1889 void Sema::setOpenMPCaptureKind(FieldDecl *FD, const ValueDecl *D, 1890 unsigned Level) { 1891 assert(LangOpts.OpenMP && "OpenMP is not allowed"); 1892 D = getCanonicalDecl(D); 1893 OpenMPClauseKind OMPC = OMPC_unknown; 1894 for (unsigned I = DSAStack->getNestingLevel() + 1; I > Level; --I) { 1895 const unsigned NewLevel = I - 1; 1896 if (DSAStack->hasExplicitDSA(D, 1897 [&OMPC](const OpenMPClauseKind K) { 1898 if (isOpenMPPrivate(K)) { 1899 OMPC = K; 1900 return true; 1901 } 1902 return false; 1903 }, 1904 NewLevel)) 1905 break; 1906 if (DSAStack->checkMappableExprComponentListsForDeclAtLevel( 1907 D, NewLevel, 1908 [](OMPClauseMappableExprCommon::MappableExprComponentListRef, 1909 OpenMPClauseKind) { return true; })) { 1910 OMPC = OMPC_map; 1911 break; 1912 } 1913 if (DSAStack->hasExplicitDirective(isOpenMPTargetExecutionDirective, 1914 NewLevel)) { 1915 OMPC = OMPC_map; 1916 if (D->getType()->isScalarType() && 1917 DSAStack->getDefaultDMAAtLevel(NewLevel) != 1918 DefaultMapAttributes::DMA_tofrom_scalar) 1919 OMPC = OMPC_firstprivate; 1920 break; 1921 } 1922 } 1923 if (OMPC != OMPC_unknown) 1924 FD->addAttr(OMPCaptureKindAttr::CreateImplicit(Context, OMPC)); 1925 } 1926 1927 bool Sema::isOpenMPTargetCapturedDecl(const ValueDecl *D, 1928 unsigned Level) const { 1929 assert(LangOpts.OpenMP && "OpenMP is not allowed"); 1930 // Return true if the current level is no longer enclosed in a target region. 1931 1932 const auto *VD = dyn_cast<VarDecl>(D); 1933 return VD && !VD->hasLocalStorage() && 1934 DSAStack->hasExplicitDirective(isOpenMPTargetExecutionDirective, 1935 Level); 1936 } 1937 1938 void Sema::DestroyDataSharingAttributesStack() { delete DSAStack; } 1939 1940 void Sema::StartOpenMPDSABlock(OpenMPDirectiveKind DKind, 1941 const DeclarationNameInfo &DirName, 1942 Scope *CurScope, SourceLocation Loc) { 1943 DSAStack->push(DKind, DirName, CurScope, Loc); 1944 PushExpressionEvaluationContext( 1945 ExpressionEvaluationContext::PotentiallyEvaluated); 1946 } 1947 1948 void Sema::StartOpenMPClause(OpenMPClauseKind K) { 1949 DSAStack->setClauseParsingMode(K); 1950 } 1951 1952 void Sema::EndOpenMPClause() { 1953 DSAStack->setClauseParsingMode(/*K=*/OMPC_unknown); 1954 } 1955 1956 static void checkAllocateClauses(Sema &S, DSAStackTy *Stack, 1957 ArrayRef<OMPClause *> Clauses); 1958 1959 void Sema::EndOpenMPDSABlock(Stmt *CurDirective) { 1960 // OpenMP [2.14.3.5, Restrictions, C/C++, p.1] 1961 // A variable of class type (or array thereof) that appears in a lastprivate 1962 // clause requires an accessible, unambiguous default constructor for the 1963 // class type, unless the list item is also specified in a firstprivate 1964 // clause. 1965 if (const auto *D = dyn_cast_or_null<OMPExecutableDirective>(CurDirective)) { 1966 for (OMPClause *C : D->clauses()) { 1967 if (auto *Clause = dyn_cast<OMPLastprivateClause>(C)) { 1968 SmallVector<Expr *, 8> PrivateCopies; 1969 for (Expr *DE : Clause->varlists()) { 1970 if (DE->isValueDependent() || DE->isTypeDependent()) { 1971 PrivateCopies.push_back(nullptr); 1972 continue; 1973 } 1974 auto *DRE = cast<DeclRefExpr>(DE->IgnoreParens()); 1975 auto *VD = cast<VarDecl>(DRE->getDecl()); 1976 QualType Type = VD->getType().getNonReferenceType(); 1977 const DSAStackTy::DSAVarData DVar = 1978 DSAStack->getTopDSA(VD, /*FromParent=*/false); 1979 if (DVar.CKind == OMPC_lastprivate) { 1980 // Generate helper private variable and initialize it with the 1981 // default value. The address of the original variable is replaced 1982 // by the address of the new private variable in CodeGen. This new 1983 // variable is not added to IdResolver, so the code in the OpenMP 1984 // region uses original variable for proper diagnostics. 1985 VarDecl *VDPrivate = buildVarDecl( 1986 *this, DE->getExprLoc(), Type.getUnqualifiedType(), 1987 VD->getName(), VD->hasAttrs() ? &VD->getAttrs() : nullptr, DRE); 1988 ActOnUninitializedDecl(VDPrivate); 1989 if (VDPrivate->isInvalidDecl()) { 1990 PrivateCopies.push_back(nullptr); 1991 continue; 1992 } 1993 PrivateCopies.push_back(buildDeclRefExpr( 1994 *this, VDPrivate, DE->getType(), DE->getExprLoc())); 1995 } else { 1996 // The variable is also a firstprivate, so initialization sequence 1997 // for private copy is generated already. 1998 PrivateCopies.push_back(nullptr); 1999 } 2000 } 2001 Clause->setPrivateCopies(PrivateCopies); 2002 } 2003 } 2004 // Check allocate clauses. 2005 if (!CurContext->isDependentContext()) 2006 checkAllocateClauses(*this, DSAStack, D->clauses()); 2007 } 2008 2009 DSAStack->pop(); 2010 DiscardCleanupsInEvaluationContext(); 2011 PopExpressionEvaluationContext(); 2012 } 2013 2014 static bool FinishOpenMPLinearClause(OMPLinearClause &Clause, DeclRefExpr *IV, 2015 Expr *NumIterations, Sema &SemaRef, 2016 Scope *S, DSAStackTy *Stack); 2017 2018 namespace { 2019 2020 class VarDeclFilterCCC final : public CorrectionCandidateCallback { 2021 private: 2022 Sema &SemaRef; 2023 2024 public: 2025 explicit VarDeclFilterCCC(Sema &S) : SemaRef(S) {} 2026 bool ValidateCandidate(const TypoCorrection &Candidate) override { 2027 NamedDecl *ND = Candidate.getCorrectionDecl(); 2028 if (const auto *VD = dyn_cast_or_null<VarDecl>(ND)) { 2029 return VD->hasGlobalStorage() && 2030 SemaRef.isDeclInScope(ND, SemaRef.getCurLexicalContext(), 2031 SemaRef.getCurScope()); 2032 } 2033 return false; 2034 } 2035 2036 std::unique_ptr<CorrectionCandidateCallback> clone() override { 2037 return llvm::make_unique<VarDeclFilterCCC>(*this); 2038 } 2039 2040 }; 2041 2042 class VarOrFuncDeclFilterCCC final : public CorrectionCandidateCallback { 2043 private: 2044 Sema &SemaRef; 2045 2046 public: 2047 explicit VarOrFuncDeclFilterCCC(Sema &S) : SemaRef(S) {} 2048 bool ValidateCandidate(const TypoCorrection &Candidate) override { 2049 NamedDecl *ND = Candidate.getCorrectionDecl(); 2050 if (ND && ((isa<VarDecl>(ND) && ND->getKind() == Decl::Var) || 2051 isa<FunctionDecl>(ND))) { 2052 return SemaRef.isDeclInScope(ND, SemaRef.getCurLexicalContext(), 2053 SemaRef.getCurScope()); 2054 } 2055 return false; 2056 } 2057 2058 std::unique_ptr<CorrectionCandidateCallback> clone() override { 2059 return llvm::make_unique<VarOrFuncDeclFilterCCC>(*this); 2060 } 2061 }; 2062 2063 } // namespace 2064 2065 ExprResult Sema::ActOnOpenMPIdExpression(Scope *CurScope, 2066 CXXScopeSpec &ScopeSpec, 2067 const DeclarationNameInfo &Id, 2068 OpenMPDirectiveKind Kind) { 2069 LookupResult Lookup(*this, Id, LookupOrdinaryName); 2070 LookupParsedName(Lookup, CurScope, &ScopeSpec, true); 2071 2072 if (Lookup.isAmbiguous()) 2073 return ExprError(); 2074 2075 VarDecl *VD; 2076 if (!Lookup.isSingleResult()) { 2077 VarDeclFilterCCC CCC(*this); 2078 if (TypoCorrection Corrected = 2079 CorrectTypo(Id, LookupOrdinaryName, CurScope, nullptr, CCC, 2080 CTK_ErrorRecovery)) { 2081 diagnoseTypo(Corrected, 2082 PDiag(Lookup.empty() 2083 ? diag::err_undeclared_var_use_suggest 2084 : diag::err_omp_expected_var_arg_suggest) 2085 << Id.getName()); 2086 VD = Corrected.getCorrectionDeclAs<VarDecl>(); 2087 } else { 2088 Diag(Id.getLoc(), Lookup.empty() ? diag::err_undeclared_var_use 2089 : diag::err_omp_expected_var_arg) 2090 << Id.getName(); 2091 return ExprError(); 2092 } 2093 } else if (!(VD = Lookup.getAsSingle<VarDecl>())) { 2094 Diag(Id.getLoc(), diag::err_omp_expected_var_arg) << Id.getName(); 2095 Diag(Lookup.getFoundDecl()->getLocation(), diag::note_declared_at); 2096 return ExprError(); 2097 } 2098 Lookup.suppressDiagnostics(); 2099 2100 // OpenMP [2.9.2, Syntax, C/C++] 2101 // Variables must be file-scope, namespace-scope, or static block-scope. 2102 if (Kind == OMPD_threadprivate && !VD->hasGlobalStorage()) { 2103 Diag(Id.getLoc(), diag::err_omp_global_var_arg) 2104 << getOpenMPDirectiveName(Kind) << !VD->isStaticLocal(); 2105 bool IsDecl = 2106 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly; 2107 Diag(VD->getLocation(), 2108 IsDecl ? diag::note_previous_decl : diag::note_defined_here) 2109 << VD; 2110 return ExprError(); 2111 } 2112 2113 VarDecl *CanonicalVD = VD->getCanonicalDecl(); 2114 NamedDecl *ND = CanonicalVD; 2115 // OpenMP [2.9.2, Restrictions, C/C++, p.2] 2116 // A threadprivate directive for file-scope variables must appear outside 2117 // any definition or declaration. 2118 if (CanonicalVD->getDeclContext()->isTranslationUnit() && 2119 !getCurLexicalContext()->isTranslationUnit()) { 2120 Diag(Id.getLoc(), diag::err_omp_var_scope) 2121 << getOpenMPDirectiveName(Kind) << VD; 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 return ExprError(); 2128 } 2129 // OpenMP [2.9.2, Restrictions, C/C++, p.3] 2130 // A threadprivate directive for static class member variables must appear 2131 // in the class definition, in the same scope in which the member 2132 // variables are declared. 2133 if (CanonicalVD->isStaticDataMember() && 2134 !CanonicalVD->getDeclContext()->Equals(getCurLexicalContext())) { 2135 Diag(Id.getLoc(), diag::err_omp_var_scope) 2136 << getOpenMPDirectiveName(Kind) << VD; 2137 bool IsDecl = 2138 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly; 2139 Diag(VD->getLocation(), 2140 IsDecl ? diag::note_previous_decl : diag::note_defined_here) 2141 << VD; 2142 return ExprError(); 2143 } 2144 // OpenMP [2.9.2, Restrictions, C/C++, p.4] 2145 // A threadprivate directive for namespace-scope variables must appear 2146 // outside any definition or declaration other than the namespace 2147 // definition itself. 2148 if (CanonicalVD->getDeclContext()->isNamespace() && 2149 (!getCurLexicalContext()->isFileContext() || 2150 !getCurLexicalContext()->Encloses(CanonicalVD->getDeclContext()))) { 2151 Diag(Id.getLoc(), diag::err_omp_var_scope) 2152 << getOpenMPDirectiveName(Kind) << VD; 2153 bool IsDecl = 2154 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly; 2155 Diag(VD->getLocation(), 2156 IsDecl ? diag::note_previous_decl : diag::note_defined_here) 2157 << VD; 2158 return ExprError(); 2159 } 2160 // OpenMP [2.9.2, Restrictions, C/C++, p.6] 2161 // A threadprivate directive for static block-scope variables must appear 2162 // in the scope of the variable and not in a nested scope. 2163 if (CanonicalVD->isLocalVarDecl() && CurScope && 2164 !isDeclInScope(ND, getCurLexicalContext(), CurScope)) { 2165 Diag(Id.getLoc(), diag::err_omp_var_scope) 2166 << getOpenMPDirectiveName(Kind) << VD; 2167 bool IsDecl = 2168 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly; 2169 Diag(VD->getLocation(), 2170 IsDecl ? diag::note_previous_decl : diag::note_defined_here) 2171 << VD; 2172 return ExprError(); 2173 } 2174 2175 // OpenMP [2.9.2, Restrictions, C/C++, p.2-6] 2176 // A threadprivate directive must lexically precede all references to any 2177 // of the variables in its list. 2178 if (Kind == OMPD_threadprivate && VD->isUsed() && 2179 !DSAStack->isThreadPrivate(VD)) { 2180 Diag(Id.getLoc(), diag::err_omp_var_used) 2181 << getOpenMPDirectiveName(Kind) << VD; 2182 return ExprError(); 2183 } 2184 2185 QualType ExprType = VD->getType().getNonReferenceType(); 2186 return DeclRefExpr::Create(Context, NestedNameSpecifierLoc(), 2187 SourceLocation(), VD, 2188 /*RefersToEnclosingVariableOrCapture=*/false, 2189 Id.getLoc(), ExprType, VK_LValue); 2190 } 2191 2192 Sema::DeclGroupPtrTy 2193 Sema::ActOnOpenMPThreadprivateDirective(SourceLocation Loc, 2194 ArrayRef<Expr *> VarList) { 2195 if (OMPThreadPrivateDecl *D = CheckOMPThreadPrivateDecl(Loc, VarList)) { 2196 CurContext->addDecl(D); 2197 return DeclGroupPtrTy::make(DeclGroupRef(D)); 2198 } 2199 return nullptr; 2200 } 2201 2202 namespace { 2203 class LocalVarRefChecker final 2204 : public ConstStmtVisitor<LocalVarRefChecker, bool> { 2205 Sema &SemaRef; 2206 2207 public: 2208 bool VisitDeclRefExpr(const DeclRefExpr *E) { 2209 if (const auto *VD = dyn_cast<VarDecl>(E->getDecl())) { 2210 if (VD->hasLocalStorage()) { 2211 SemaRef.Diag(E->getBeginLoc(), 2212 diag::err_omp_local_var_in_threadprivate_init) 2213 << E->getSourceRange(); 2214 SemaRef.Diag(VD->getLocation(), diag::note_defined_here) 2215 << VD << VD->getSourceRange(); 2216 return true; 2217 } 2218 } 2219 return false; 2220 } 2221 bool VisitStmt(const Stmt *S) { 2222 for (const Stmt *Child : S->children()) { 2223 if (Child && Visit(Child)) 2224 return true; 2225 } 2226 return false; 2227 } 2228 explicit LocalVarRefChecker(Sema &SemaRef) : SemaRef(SemaRef) {} 2229 }; 2230 } // namespace 2231 2232 OMPThreadPrivateDecl * 2233 Sema::CheckOMPThreadPrivateDecl(SourceLocation Loc, ArrayRef<Expr *> VarList) { 2234 SmallVector<Expr *, 8> Vars; 2235 for (Expr *RefExpr : VarList) { 2236 auto *DE = cast<DeclRefExpr>(RefExpr); 2237 auto *VD = cast<VarDecl>(DE->getDecl()); 2238 SourceLocation ILoc = DE->getExprLoc(); 2239 2240 // Mark variable as used. 2241 VD->setReferenced(); 2242 VD->markUsed(Context); 2243 2244 QualType QType = VD->getType(); 2245 if (QType->isDependentType() || QType->isInstantiationDependentType()) { 2246 // It will be analyzed later. 2247 Vars.push_back(DE); 2248 continue; 2249 } 2250 2251 // OpenMP [2.9.2, Restrictions, C/C++, p.10] 2252 // A threadprivate variable must not have an incomplete type. 2253 if (RequireCompleteType(ILoc, VD->getType(), 2254 diag::err_omp_threadprivate_incomplete_type)) { 2255 continue; 2256 } 2257 2258 // OpenMP [2.9.2, Restrictions, C/C++, p.10] 2259 // A threadprivate variable must not have a reference type. 2260 if (VD->getType()->isReferenceType()) { 2261 Diag(ILoc, diag::err_omp_ref_type_arg) 2262 << getOpenMPDirectiveName(OMPD_threadprivate) << VD->getType(); 2263 bool IsDecl = 2264 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly; 2265 Diag(VD->getLocation(), 2266 IsDecl ? diag::note_previous_decl : diag::note_defined_here) 2267 << VD; 2268 continue; 2269 } 2270 2271 // Check if this is a TLS variable. If TLS is not being supported, produce 2272 // the corresponding diagnostic. 2273 if ((VD->getTLSKind() != VarDecl::TLS_None && 2274 !(VD->hasAttr<OMPThreadPrivateDeclAttr>() && 2275 getLangOpts().OpenMPUseTLS && 2276 getASTContext().getTargetInfo().isTLSSupported())) || 2277 (VD->getStorageClass() == SC_Register && VD->hasAttr<AsmLabelAttr>() && 2278 !VD->isLocalVarDecl())) { 2279 Diag(ILoc, diag::err_omp_var_thread_local) 2280 << VD << ((VD->getTLSKind() != VarDecl::TLS_None) ? 0 : 1); 2281 bool IsDecl = 2282 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly; 2283 Diag(VD->getLocation(), 2284 IsDecl ? diag::note_previous_decl : diag::note_defined_here) 2285 << VD; 2286 continue; 2287 } 2288 2289 // Check if initial value of threadprivate variable reference variable with 2290 // local storage (it is not supported by runtime). 2291 if (const Expr *Init = VD->getAnyInitializer()) { 2292 LocalVarRefChecker Checker(*this); 2293 if (Checker.Visit(Init)) 2294 continue; 2295 } 2296 2297 Vars.push_back(RefExpr); 2298 DSAStack->addDSA(VD, DE, OMPC_threadprivate); 2299 VD->addAttr(OMPThreadPrivateDeclAttr::CreateImplicit( 2300 Context, SourceRange(Loc, Loc))); 2301 if (ASTMutationListener *ML = Context.getASTMutationListener()) 2302 ML->DeclarationMarkedOpenMPThreadPrivate(VD); 2303 } 2304 OMPThreadPrivateDecl *D = nullptr; 2305 if (!Vars.empty()) { 2306 D = OMPThreadPrivateDecl::Create(Context, getCurLexicalContext(), Loc, 2307 Vars); 2308 D->setAccess(AS_public); 2309 } 2310 return D; 2311 } 2312 2313 static OMPAllocateDeclAttr::AllocatorTypeTy 2314 getAllocatorKind(Sema &S, DSAStackTy *Stack, Expr *Allocator) { 2315 if (!Allocator) 2316 return OMPAllocateDeclAttr::OMPDefaultMemAlloc; 2317 if (Allocator->isTypeDependent() || Allocator->isValueDependent() || 2318 Allocator->isInstantiationDependent() || 2319 Allocator->containsUnexpandedParameterPack()) 2320 return OMPAllocateDeclAttr::OMPUserDefinedMemAlloc; 2321 auto AllocatorKindRes = OMPAllocateDeclAttr::OMPUserDefinedMemAlloc; 2322 const Expr *AE = Allocator->IgnoreParenImpCasts(); 2323 for (int I = OMPAllocateDeclAttr::OMPDefaultMemAlloc; 2324 I < OMPAllocateDeclAttr::OMPUserDefinedMemAlloc; ++I) { 2325 auto AllocatorKind = static_cast<OMPAllocateDeclAttr::AllocatorTypeTy>(I); 2326 const Expr *DefAllocator = Stack->getAllocator(AllocatorKind); 2327 llvm::FoldingSetNodeID AEId, DAEId; 2328 AE->Profile(AEId, S.getASTContext(), /*Canonical=*/true); 2329 DefAllocator->Profile(DAEId, S.getASTContext(), /*Canonical=*/true); 2330 if (AEId == DAEId) { 2331 AllocatorKindRes = AllocatorKind; 2332 break; 2333 } 2334 } 2335 return AllocatorKindRes; 2336 } 2337 2338 static bool checkPreviousOMPAllocateAttribute( 2339 Sema &S, DSAStackTy *Stack, Expr *RefExpr, VarDecl *VD, 2340 OMPAllocateDeclAttr::AllocatorTypeTy AllocatorKind, Expr *Allocator) { 2341 if (!VD->hasAttr<OMPAllocateDeclAttr>()) 2342 return false; 2343 const auto *A = VD->getAttr<OMPAllocateDeclAttr>(); 2344 Expr *PrevAllocator = A->getAllocator(); 2345 OMPAllocateDeclAttr::AllocatorTypeTy PrevAllocatorKind = 2346 getAllocatorKind(S, Stack, PrevAllocator); 2347 bool AllocatorsMatch = AllocatorKind == PrevAllocatorKind; 2348 if (AllocatorsMatch && 2349 AllocatorKind == OMPAllocateDeclAttr::OMPUserDefinedMemAlloc && 2350 Allocator && PrevAllocator) { 2351 const Expr *AE = Allocator->IgnoreParenImpCasts(); 2352 const Expr *PAE = PrevAllocator->IgnoreParenImpCasts(); 2353 llvm::FoldingSetNodeID AEId, PAEId; 2354 AE->Profile(AEId, S.Context, /*Canonical=*/true); 2355 PAE->Profile(PAEId, S.Context, /*Canonical=*/true); 2356 AllocatorsMatch = AEId == PAEId; 2357 } 2358 if (!AllocatorsMatch) { 2359 SmallString<256> AllocatorBuffer; 2360 llvm::raw_svector_ostream AllocatorStream(AllocatorBuffer); 2361 if (Allocator) 2362 Allocator->printPretty(AllocatorStream, nullptr, S.getPrintingPolicy()); 2363 SmallString<256> PrevAllocatorBuffer; 2364 llvm::raw_svector_ostream PrevAllocatorStream(PrevAllocatorBuffer); 2365 if (PrevAllocator) 2366 PrevAllocator->printPretty(PrevAllocatorStream, nullptr, 2367 S.getPrintingPolicy()); 2368 2369 SourceLocation AllocatorLoc = 2370 Allocator ? Allocator->getExprLoc() : RefExpr->getExprLoc(); 2371 SourceRange AllocatorRange = 2372 Allocator ? Allocator->getSourceRange() : RefExpr->getSourceRange(); 2373 SourceLocation PrevAllocatorLoc = 2374 PrevAllocator ? PrevAllocator->getExprLoc() : A->getLocation(); 2375 SourceRange PrevAllocatorRange = 2376 PrevAllocator ? PrevAllocator->getSourceRange() : A->getRange(); 2377 S.Diag(AllocatorLoc, diag::warn_omp_used_different_allocator) 2378 << (Allocator ? 1 : 0) << AllocatorStream.str() 2379 << (PrevAllocator ? 1 : 0) << PrevAllocatorStream.str() 2380 << AllocatorRange; 2381 S.Diag(PrevAllocatorLoc, diag::note_omp_previous_allocator) 2382 << PrevAllocatorRange; 2383 return true; 2384 } 2385 return false; 2386 } 2387 2388 static void 2389 applyOMPAllocateAttribute(Sema &S, VarDecl *VD, 2390 OMPAllocateDeclAttr::AllocatorTypeTy AllocatorKind, 2391 Expr *Allocator, SourceRange SR) { 2392 if (VD->hasAttr<OMPAllocateDeclAttr>()) 2393 return; 2394 if (Allocator && 2395 (Allocator->isTypeDependent() || Allocator->isValueDependent() || 2396 Allocator->isInstantiationDependent() || 2397 Allocator->containsUnexpandedParameterPack())) 2398 return; 2399 auto *A = OMPAllocateDeclAttr::CreateImplicit(S.Context, AllocatorKind, 2400 Allocator, SR); 2401 VD->addAttr(A); 2402 if (ASTMutationListener *ML = S.Context.getASTMutationListener()) 2403 ML->DeclarationMarkedOpenMPAllocate(VD, A); 2404 } 2405 2406 Sema::DeclGroupPtrTy Sema::ActOnOpenMPAllocateDirective( 2407 SourceLocation Loc, ArrayRef<Expr *> VarList, 2408 ArrayRef<OMPClause *> Clauses, DeclContext *Owner) { 2409 assert(Clauses.size() <= 1 && "Expected at most one clause."); 2410 Expr *Allocator = nullptr; 2411 if (Clauses.empty()) { 2412 // OpenMP 5.0, 2.11.3 allocate Directive, Restrictions. 2413 // allocate directives that appear in a target region must specify an 2414 // allocator clause unless a requires directive with the dynamic_allocators 2415 // clause is present in the same compilation unit. 2416 if (LangOpts.OpenMPIsDevice && 2417 !DSAStack->hasRequiresDeclWithClause<OMPDynamicAllocatorsClause>()) 2418 targetDiag(Loc, diag::err_expected_allocator_clause); 2419 } else { 2420 Allocator = cast<OMPAllocatorClause>(Clauses.back())->getAllocator(); 2421 } 2422 OMPAllocateDeclAttr::AllocatorTypeTy AllocatorKind = 2423 getAllocatorKind(*this, DSAStack, Allocator); 2424 SmallVector<Expr *, 8> Vars; 2425 for (Expr *RefExpr : VarList) { 2426 auto *DE = cast<DeclRefExpr>(RefExpr); 2427 auto *VD = cast<VarDecl>(DE->getDecl()); 2428 2429 // Check if this is a TLS variable or global register. 2430 if (VD->getTLSKind() != VarDecl::TLS_None || 2431 VD->hasAttr<OMPThreadPrivateDeclAttr>() || 2432 (VD->getStorageClass() == SC_Register && VD->hasAttr<AsmLabelAttr>() && 2433 !VD->isLocalVarDecl())) 2434 continue; 2435 2436 // If the used several times in the allocate directive, the same allocator 2437 // must be used. 2438 if (checkPreviousOMPAllocateAttribute(*this, DSAStack, RefExpr, VD, 2439 AllocatorKind, Allocator)) 2440 continue; 2441 2442 // OpenMP, 2.11.3 allocate Directive, Restrictions, C / C++ 2443 // If a list item has a static storage type, the allocator expression in the 2444 // allocator clause must be a constant expression that evaluates to one of 2445 // the predefined memory allocator values. 2446 if (Allocator && VD->hasGlobalStorage()) { 2447 if (AllocatorKind == OMPAllocateDeclAttr::OMPUserDefinedMemAlloc) { 2448 Diag(Allocator->getExprLoc(), 2449 diag::err_omp_expected_predefined_allocator) 2450 << Allocator->getSourceRange(); 2451 bool IsDecl = VD->isThisDeclarationADefinition(Context) == 2452 VarDecl::DeclarationOnly; 2453 Diag(VD->getLocation(), 2454 IsDecl ? diag::note_previous_decl : diag::note_defined_here) 2455 << VD; 2456 continue; 2457 } 2458 } 2459 2460 Vars.push_back(RefExpr); 2461 applyOMPAllocateAttribute(*this, VD, AllocatorKind, Allocator, 2462 DE->getSourceRange()); 2463 } 2464 if (Vars.empty()) 2465 return nullptr; 2466 if (!Owner) 2467 Owner = getCurLexicalContext(); 2468 auto *D = OMPAllocateDecl::Create(Context, Owner, Loc, Vars, Clauses); 2469 D->setAccess(AS_public); 2470 Owner->addDecl(D); 2471 return DeclGroupPtrTy::make(DeclGroupRef(D)); 2472 } 2473 2474 Sema::DeclGroupPtrTy 2475 Sema::ActOnOpenMPRequiresDirective(SourceLocation Loc, 2476 ArrayRef<OMPClause *> ClauseList) { 2477 OMPRequiresDecl *D = nullptr; 2478 if (!CurContext->isFileContext()) { 2479 Diag(Loc, diag::err_omp_invalid_scope) << "requires"; 2480 } else { 2481 D = CheckOMPRequiresDecl(Loc, ClauseList); 2482 if (D) { 2483 CurContext->addDecl(D); 2484 DSAStack->addRequiresDecl(D); 2485 } 2486 } 2487 return DeclGroupPtrTy::make(DeclGroupRef(D)); 2488 } 2489 2490 OMPRequiresDecl *Sema::CheckOMPRequiresDecl(SourceLocation Loc, 2491 ArrayRef<OMPClause *> ClauseList) { 2492 /// For target specific clauses, the requires directive cannot be 2493 /// specified after the handling of any of the target regions in the 2494 /// current compilation unit. 2495 ArrayRef<SourceLocation> TargetLocations = 2496 DSAStack->getEncounteredTargetLocs(); 2497 if (!TargetLocations.empty()) { 2498 for (const OMPClause *CNew : ClauseList) { 2499 // Check if any of the requires clauses affect target regions. 2500 if (isa<OMPUnifiedSharedMemoryClause>(CNew) || 2501 isa<OMPUnifiedAddressClause>(CNew) || 2502 isa<OMPReverseOffloadClause>(CNew) || 2503 isa<OMPDynamicAllocatorsClause>(CNew)) { 2504 Diag(Loc, diag::err_omp_target_before_requires) 2505 << getOpenMPClauseName(CNew->getClauseKind()); 2506 for (SourceLocation TargetLoc : TargetLocations) { 2507 Diag(TargetLoc, diag::note_omp_requires_encountered_target); 2508 } 2509 } 2510 } 2511 } 2512 2513 if (!DSAStack->hasDuplicateRequiresClause(ClauseList)) 2514 return OMPRequiresDecl::Create(Context, getCurLexicalContext(), Loc, 2515 ClauseList); 2516 return nullptr; 2517 } 2518 2519 static void reportOriginalDsa(Sema &SemaRef, const DSAStackTy *Stack, 2520 const ValueDecl *D, 2521 const DSAStackTy::DSAVarData &DVar, 2522 bool IsLoopIterVar = false) { 2523 if (DVar.RefExpr) { 2524 SemaRef.Diag(DVar.RefExpr->getExprLoc(), diag::note_omp_explicit_dsa) 2525 << getOpenMPClauseName(DVar.CKind); 2526 return; 2527 } 2528 enum { 2529 PDSA_StaticMemberShared, 2530 PDSA_StaticLocalVarShared, 2531 PDSA_LoopIterVarPrivate, 2532 PDSA_LoopIterVarLinear, 2533 PDSA_LoopIterVarLastprivate, 2534 PDSA_ConstVarShared, 2535 PDSA_GlobalVarShared, 2536 PDSA_TaskVarFirstprivate, 2537 PDSA_LocalVarPrivate, 2538 PDSA_Implicit 2539 } Reason = PDSA_Implicit; 2540 bool ReportHint = false; 2541 auto ReportLoc = D->getLocation(); 2542 auto *VD = dyn_cast<VarDecl>(D); 2543 if (IsLoopIterVar) { 2544 if (DVar.CKind == OMPC_private) 2545 Reason = PDSA_LoopIterVarPrivate; 2546 else if (DVar.CKind == OMPC_lastprivate) 2547 Reason = PDSA_LoopIterVarLastprivate; 2548 else 2549 Reason = PDSA_LoopIterVarLinear; 2550 } else if (isOpenMPTaskingDirective(DVar.DKind) && 2551 DVar.CKind == OMPC_firstprivate) { 2552 Reason = PDSA_TaskVarFirstprivate; 2553 ReportLoc = DVar.ImplicitDSALoc; 2554 } else if (VD && VD->isStaticLocal()) 2555 Reason = PDSA_StaticLocalVarShared; 2556 else if (VD && VD->isStaticDataMember()) 2557 Reason = PDSA_StaticMemberShared; 2558 else if (VD && VD->isFileVarDecl()) 2559 Reason = PDSA_GlobalVarShared; 2560 else if (D->getType().isConstant(SemaRef.getASTContext())) 2561 Reason = PDSA_ConstVarShared; 2562 else if (VD && VD->isLocalVarDecl() && DVar.CKind == OMPC_private) { 2563 ReportHint = true; 2564 Reason = PDSA_LocalVarPrivate; 2565 } 2566 if (Reason != PDSA_Implicit) { 2567 SemaRef.Diag(ReportLoc, diag::note_omp_predetermined_dsa) 2568 << Reason << ReportHint 2569 << getOpenMPDirectiveName(Stack->getCurrentDirective()); 2570 } else if (DVar.ImplicitDSALoc.isValid()) { 2571 SemaRef.Diag(DVar.ImplicitDSALoc, diag::note_omp_implicit_dsa) 2572 << getOpenMPClauseName(DVar.CKind); 2573 } 2574 } 2575 2576 namespace { 2577 class DSAAttrChecker final : public StmtVisitor<DSAAttrChecker, void> { 2578 DSAStackTy *Stack; 2579 Sema &SemaRef; 2580 bool ErrorFound = false; 2581 CapturedStmt *CS = nullptr; 2582 llvm::SmallVector<Expr *, 4> ImplicitFirstprivate; 2583 llvm::SmallVector<Expr *, 4> ImplicitMap; 2584 Sema::VarsWithInheritedDSAType VarsWithInheritedDSA; 2585 llvm::SmallDenseSet<const ValueDecl *, 4> ImplicitDeclarations; 2586 2587 void VisitSubCaptures(OMPExecutableDirective *S) { 2588 // Check implicitly captured variables. 2589 if (!S->hasAssociatedStmt() || !S->getAssociatedStmt()) 2590 return; 2591 visitSubCaptures(S->getInnermostCapturedStmt()); 2592 } 2593 2594 public: 2595 void VisitDeclRefExpr(DeclRefExpr *E) { 2596 if (E->isTypeDependent() || E->isValueDependent() || 2597 E->containsUnexpandedParameterPack() || E->isInstantiationDependent()) 2598 return; 2599 if (auto *VD = dyn_cast<VarDecl>(E->getDecl())) { 2600 // Check the datasharing rules for the expressions in the clauses. 2601 if (!CS) { 2602 if (auto *CED = dyn_cast<OMPCapturedExprDecl>(VD)) 2603 if (!CED->hasAttr<OMPCaptureNoInitAttr>()) { 2604 Visit(CED->getInit()); 2605 return; 2606 } 2607 } else if (VD->isImplicit() || isa<OMPCapturedExprDecl>(VD)) 2608 // Do not analyze internal variables and do not enclose them into 2609 // implicit clauses. 2610 return; 2611 VD = VD->getCanonicalDecl(); 2612 // Skip internally declared variables. 2613 if (VD->hasLocalStorage() && CS && !CS->capturesVariable(VD)) 2614 return; 2615 2616 DSAStackTy::DSAVarData DVar = Stack->getTopDSA(VD, /*FromParent=*/false); 2617 // Check if the variable has explicit DSA set and stop analysis if it so. 2618 if (DVar.RefExpr || !ImplicitDeclarations.insert(VD).second) 2619 return; 2620 2621 // Skip internally declared static variables. 2622 llvm::Optional<OMPDeclareTargetDeclAttr::MapTypeTy> Res = 2623 OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD); 2624 if (VD->hasGlobalStorage() && CS && !CS->capturesVariable(VD) && 2625 (Stack->hasRequiresDeclWithClause<OMPUnifiedSharedMemoryClause>() || 2626 !Res || *Res != OMPDeclareTargetDeclAttr::MT_Link)) 2627 return; 2628 2629 SourceLocation ELoc = E->getExprLoc(); 2630 OpenMPDirectiveKind DKind = Stack->getCurrentDirective(); 2631 // The default(none) clause requires that each variable that is referenced 2632 // in the construct, and does not have a predetermined data-sharing 2633 // attribute, must have its data-sharing attribute explicitly determined 2634 // by being listed in a data-sharing attribute clause. 2635 if (DVar.CKind == OMPC_unknown && Stack->getDefaultDSA() == DSA_none && 2636 isImplicitOrExplicitTaskingRegion(DKind) && 2637 VarsWithInheritedDSA.count(VD) == 0) { 2638 VarsWithInheritedDSA[VD] = E; 2639 return; 2640 } 2641 2642 if (isOpenMPTargetExecutionDirective(DKind) && 2643 !Stack->isLoopControlVariable(VD).first) { 2644 if (!Stack->checkMappableExprComponentListsForDecl( 2645 VD, /*CurrentRegionOnly=*/true, 2646 [](OMPClauseMappableExprCommon::MappableExprComponentListRef 2647 StackComponents, 2648 OpenMPClauseKind) { 2649 // Variable is used if it has been marked as an array, array 2650 // section or the variable iself. 2651 return StackComponents.size() == 1 || 2652 std::all_of( 2653 std::next(StackComponents.rbegin()), 2654 StackComponents.rend(), 2655 [](const OMPClauseMappableExprCommon:: 2656 MappableComponent &MC) { 2657 return MC.getAssociatedDeclaration() == 2658 nullptr && 2659 (isa<OMPArraySectionExpr>( 2660 MC.getAssociatedExpression()) || 2661 isa<ArraySubscriptExpr>( 2662 MC.getAssociatedExpression())); 2663 }); 2664 })) { 2665 bool IsFirstprivate = false; 2666 // By default lambdas are captured as firstprivates. 2667 if (const auto *RD = 2668 VD->getType().getNonReferenceType()->getAsCXXRecordDecl()) 2669 IsFirstprivate = RD->isLambda(); 2670 IsFirstprivate = 2671 IsFirstprivate || 2672 (VD->getType().getNonReferenceType()->isScalarType() && 2673 Stack->getDefaultDMA() != DMA_tofrom_scalar && !Res); 2674 if (IsFirstprivate) 2675 ImplicitFirstprivate.emplace_back(E); 2676 else 2677 ImplicitMap.emplace_back(E); 2678 return; 2679 } 2680 } 2681 2682 // OpenMP [2.9.3.6, Restrictions, p.2] 2683 // A list item that appears in a reduction clause of the innermost 2684 // enclosing worksharing or parallel construct may not be accessed in an 2685 // explicit task. 2686 DVar = Stack->hasInnermostDSA( 2687 VD, [](OpenMPClauseKind C) { return C == OMPC_reduction; }, 2688 [](OpenMPDirectiveKind K) { 2689 return isOpenMPParallelDirective(K) || 2690 isOpenMPWorksharingDirective(K) || isOpenMPTeamsDirective(K); 2691 }, 2692 /*FromParent=*/true); 2693 if (isOpenMPTaskingDirective(DKind) && DVar.CKind == OMPC_reduction) { 2694 ErrorFound = true; 2695 SemaRef.Diag(ELoc, diag::err_omp_reduction_in_task); 2696 reportOriginalDsa(SemaRef, Stack, VD, DVar); 2697 return; 2698 } 2699 2700 // Define implicit data-sharing attributes for task. 2701 DVar = Stack->getImplicitDSA(VD, /*FromParent=*/false); 2702 if (isOpenMPTaskingDirective(DKind) && DVar.CKind != OMPC_shared && 2703 !Stack->isLoopControlVariable(VD).first) { 2704 ImplicitFirstprivate.push_back(E); 2705 return; 2706 } 2707 2708 // Store implicitly used globals with declare target link for parent 2709 // target. 2710 if (!isOpenMPTargetExecutionDirective(DKind) && Res && 2711 *Res == OMPDeclareTargetDeclAttr::MT_Link) { 2712 Stack->addToParentTargetRegionLinkGlobals(E); 2713 return; 2714 } 2715 } 2716 } 2717 void VisitMemberExpr(MemberExpr *E) { 2718 if (E->isTypeDependent() || E->isValueDependent() || 2719 E->containsUnexpandedParameterPack() || E->isInstantiationDependent()) 2720 return; 2721 auto *FD = dyn_cast<FieldDecl>(E->getMemberDecl()); 2722 OpenMPDirectiveKind DKind = Stack->getCurrentDirective(); 2723 if (auto *TE = dyn_cast<CXXThisExpr>(E->getBase()->IgnoreParens())) { 2724 if (!FD) 2725 return; 2726 DSAStackTy::DSAVarData DVar = Stack->getTopDSA(FD, /*FromParent=*/false); 2727 // Check if the variable has explicit DSA set and stop analysis if it 2728 // so. 2729 if (DVar.RefExpr || !ImplicitDeclarations.insert(FD).second) 2730 return; 2731 2732 if (isOpenMPTargetExecutionDirective(DKind) && 2733 !Stack->isLoopControlVariable(FD).first && 2734 !Stack->checkMappableExprComponentListsForDecl( 2735 FD, /*CurrentRegionOnly=*/true, 2736 [](OMPClauseMappableExprCommon::MappableExprComponentListRef 2737 StackComponents, 2738 OpenMPClauseKind) { 2739 return isa<CXXThisExpr>( 2740 cast<MemberExpr>( 2741 StackComponents.back().getAssociatedExpression()) 2742 ->getBase() 2743 ->IgnoreParens()); 2744 })) { 2745 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C/C++, p.3] 2746 // A bit-field cannot appear in a map clause. 2747 // 2748 if (FD->isBitField()) 2749 return; 2750 2751 // Check to see if the member expression is referencing a class that 2752 // has already been explicitly mapped 2753 if (Stack->isClassPreviouslyMapped(TE->getType())) 2754 return; 2755 2756 ImplicitMap.emplace_back(E); 2757 return; 2758 } 2759 2760 SourceLocation ELoc = E->getExprLoc(); 2761 // OpenMP [2.9.3.6, Restrictions, p.2] 2762 // A list item that appears in a reduction clause of the innermost 2763 // enclosing worksharing or parallel construct may not be accessed in 2764 // an explicit task. 2765 DVar = Stack->hasInnermostDSA( 2766 FD, [](OpenMPClauseKind C) { return C == OMPC_reduction; }, 2767 [](OpenMPDirectiveKind K) { 2768 return isOpenMPParallelDirective(K) || 2769 isOpenMPWorksharingDirective(K) || isOpenMPTeamsDirective(K); 2770 }, 2771 /*FromParent=*/true); 2772 if (isOpenMPTaskingDirective(DKind) && DVar.CKind == OMPC_reduction) { 2773 ErrorFound = true; 2774 SemaRef.Diag(ELoc, diag::err_omp_reduction_in_task); 2775 reportOriginalDsa(SemaRef, Stack, FD, DVar); 2776 return; 2777 } 2778 2779 // Define implicit data-sharing attributes for task. 2780 DVar = Stack->getImplicitDSA(FD, /*FromParent=*/false); 2781 if (isOpenMPTaskingDirective(DKind) && DVar.CKind != OMPC_shared && 2782 !Stack->isLoopControlVariable(FD).first) { 2783 // Check if there is a captured expression for the current field in the 2784 // region. Do not mark it as firstprivate unless there is no captured 2785 // expression. 2786 // TODO: try to make it firstprivate. 2787 if (DVar.CKind != OMPC_unknown) 2788 ImplicitFirstprivate.push_back(E); 2789 } 2790 return; 2791 } 2792 if (isOpenMPTargetExecutionDirective(DKind)) { 2793 OMPClauseMappableExprCommon::MappableExprComponentList CurComponents; 2794 if (!checkMapClauseExpressionBase(SemaRef, E, CurComponents, OMPC_map, 2795 /*NoDiagnose=*/true)) 2796 return; 2797 const auto *VD = cast<ValueDecl>( 2798 CurComponents.back().getAssociatedDeclaration()->getCanonicalDecl()); 2799 if (!Stack->checkMappableExprComponentListsForDecl( 2800 VD, /*CurrentRegionOnly=*/true, 2801 [&CurComponents]( 2802 OMPClauseMappableExprCommon::MappableExprComponentListRef 2803 StackComponents, 2804 OpenMPClauseKind) { 2805 auto CCI = CurComponents.rbegin(); 2806 auto CCE = CurComponents.rend(); 2807 for (const auto &SC : llvm::reverse(StackComponents)) { 2808 // Do both expressions have the same kind? 2809 if (CCI->getAssociatedExpression()->getStmtClass() != 2810 SC.getAssociatedExpression()->getStmtClass()) 2811 if (!(isa<OMPArraySectionExpr>( 2812 SC.getAssociatedExpression()) && 2813 isa<ArraySubscriptExpr>( 2814 CCI->getAssociatedExpression()))) 2815 return false; 2816 2817 const Decl *CCD = CCI->getAssociatedDeclaration(); 2818 const Decl *SCD = SC.getAssociatedDeclaration(); 2819 CCD = CCD ? CCD->getCanonicalDecl() : nullptr; 2820 SCD = SCD ? SCD->getCanonicalDecl() : nullptr; 2821 if (SCD != CCD) 2822 return false; 2823 std::advance(CCI, 1); 2824 if (CCI == CCE) 2825 break; 2826 } 2827 return true; 2828 })) { 2829 Visit(E->getBase()); 2830 } 2831 } else { 2832 Visit(E->getBase()); 2833 } 2834 } 2835 void VisitOMPExecutableDirective(OMPExecutableDirective *S) { 2836 for (OMPClause *C : S->clauses()) { 2837 // Skip analysis of arguments of implicitly defined firstprivate clause 2838 // for task|target directives. 2839 // Skip analysis of arguments of implicitly defined map clause for target 2840 // directives. 2841 if (C && !((isa<OMPFirstprivateClause>(C) || isa<OMPMapClause>(C)) && 2842 C->isImplicit())) { 2843 for (Stmt *CC : C->children()) { 2844 if (CC) 2845 Visit(CC); 2846 } 2847 } 2848 } 2849 // Check implicitly captured variables. 2850 VisitSubCaptures(S); 2851 } 2852 void VisitStmt(Stmt *S) { 2853 for (Stmt *C : S->children()) { 2854 if (C) { 2855 // Check implicitly captured variables in the task-based directives to 2856 // check if they must be firstprivatized. 2857 Visit(C); 2858 } 2859 } 2860 } 2861 2862 void visitSubCaptures(CapturedStmt *S) { 2863 for (const CapturedStmt::Capture &Cap : S->captures()) { 2864 if (!Cap.capturesVariable() && !Cap.capturesVariableByCopy()) 2865 continue; 2866 VarDecl *VD = Cap.getCapturedVar(); 2867 // Do not try to map the variable if it or its sub-component was mapped 2868 // already. 2869 if (isOpenMPTargetExecutionDirective(Stack->getCurrentDirective()) && 2870 Stack->checkMappableExprComponentListsForDecl( 2871 VD, /*CurrentRegionOnly=*/true, 2872 [](OMPClauseMappableExprCommon::MappableExprComponentListRef, 2873 OpenMPClauseKind) { return true; })) 2874 continue; 2875 DeclRefExpr *DRE = buildDeclRefExpr( 2876 SemaRef, VD, VD->getType().getNonLValueExprType(SemaRef.Context), 2877 Cap.getLocation(), /*RefersToCapture=*/true); 2878 Visit(DRE); 2879 } 2880 } 2881 bool isErrorFound() const { return ErrorFound; } 2882 ArrayRef<Expr *> getImplicitFirstprivate() const { 2883 return ImplicitFirstprivate; 2884 } 2885 ArrayRef<Expr *> getImplicitMap() const { return ImplicitMap; } 2886 const Sema::VarsWithInheritedDSAType &getVarsWithInheritedDSA() const { 2887 return VarsWithInheritedDSA; 2888 } 2889 2890 DSAAttrChecker(DSAStackTy *S, Sema &SemaRef, CapturedStmt *CS) 2891 : Stack(S), SemaRef(SemaRef), ErrorFound(false), CS(CS) { 2892 // Process declare target link variables for the target directives. 2893 if (isOpenMPTargetExecutionDirective(S->getCurrentDirective())) { 2894 for (DeclRefExpr *E : Stack->getLinkGlobals()) 2895 Visit(E); 2896 } 2897 } 2898 }; 2899 } // namespace 2900 2901 void Sema::ActOnOpenMPRegionStart(OpenMPDirectiveKind DKind, Scope *CurScope) { 2902 switch (DKind) { 2903 case OMPD_parallel: 2904 case OMPD_parallel_for: 2905 case OMPD_parallel_for_simd: 2906 case OMPD_parallel_sections: 2907 case OMPD_teams: 2908 case OMPD_teams_distribute: 2909 case OMPD_teams_distribute_simd: { 2910 QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1).withConst(); 2911 QualType KmpInt32PtrTy = 2912 Context.getPointerType(KmpInt32Ty).withConst().withRestrict(); 2913 Sema::CapturedParamNameType Params[] = { 2914 std::make_pair(".global_tid.", KmpInt32PtrTy), 2915 std::make_pair(".bound_tid.", KmpInt32PtrTy), 2916 std::make_pair(StringRef(), QualType()) // __context with shared vars 2917 }; 2918 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP, 2919 Params); 2920 break; 2921 } 2922 case OMPD_target_teams: 2923 case OMPD_target_parallel: 2924 case OMPD_target_parallel_for: 2925 case OMPD_target_parallel_for_simd: 2926 case OMPD_target_teams_distribute: 2927 case OMPD_target_teams_distribute_simd: { 2928 QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1).withConst(); 2929 QualType VoidPtrTy = Context.VoidPtrTy.withConst().withRestrict(); 2930 QualType KmpInt32PtrTy = 2931 Context.getPointerType(KmpInt32Ty).withConst().withRestrict(); 2932 QualType Args[] = {VoidPtrTy}; 2933 FunctionProtoType::ExtProtoInfo EPI; 2934 EPI.Variadic = true; 2935 QualType CopyFnType = Context.getFunctionType(Context.VoidTy, Args, EPI); 2936 Sema::CapturedParamNameType Params[] = { 2937 std::make_pair(".global_tid.", KmpInt32Ty), 2938 std::make_pair(".part_id.", KmpInt32PtrTy), 2939 std::make_pair(".privates.", VoidPtrTy), 2940 std::make_pair( 2941 ".copy_fn.", 2942 Context.getPointerType(CopyFnType).withConst().withRestrict()), 2943 std::make_pair(".task_t.", Context.VoidPtrTy.withConst()), 2944 std::make_pair(StringRef(), QualType()) // __context with shared vars 2945 }; 2946 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP, 2947 Params); 2948 // Mark this captured region as inlined, because we don't use outlined 2949 // function directly. 2950 getCurCapturedRegion()->TheCapturedDecl->addAttr( 2951 AlwaysInlineAttr::CreateImplicit( 2952 Context, AlwaysInlineAttr::Keyword_forceinline)); 2953 Sema::CapturedParamNameType ParamsTarget[] = { 2954 std::make_pair(StringRef(), QualType()) // __context with shared vars 2955 }; 2956 // Start a captured region for 'target' with no implicit parameters. 2957 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP, 2958 ParamsTarget); 2959 Sema::CapturedParamNameType ParamsTeamsOrParallel[] = { 2960 std::make_pair(".global_tid.", KmpInt32PtrTy), 2961 std::make_pair(".bound_tid.", KmpInt32PtrTy), 2962 std::make_pair(StringRef(), QualType()) // __context with shared vars 2963 }; 2964 // Start a captured region for 'teams' or 'parallel'. Both regions have 2965 // the same implicit parameters. 2966 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP, 2967 ParamsTeamsOrParallel); 2968 break; 2969 } 2970 case OMPD_target: 2971 case OMPD_target_simd: { 2972 QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1).withConst(); 2973 QualType VoidPtrTy = Context.VoidPtrTy.withConst().withRestrict(); 2974 QualType KmpInt32PtrTy = 2975 Context.getPointerType(KmpInt32Ty).withConst().withRestrict(); 2976 QualType Args[] = {VoidPtrTy}; 2977 FunctionProtoType::ExtProtoInfo EPI; 2978 EPI.Variadic = true; 2979 QualType CopyFnType = Context.getFunctionType(Context.VoidTy, Args, EPI); 2980 Sema::CapturedParamNameType Params[] = { 2981 std::make_pair(".global_tid.", KmpInt32Ty), 2982 std::make_pair(".part_id.", KmpInt32PtrTy), 2983 std::make_pair(".privates.", VoidPtrTy), 2984 std::make_pair( 2985 ".copy_fn.", 2986 Context.getPointerType(CopyFnType).withConst().withRestrict()), 2987 std::make_pair(".task_t.", Context.VoidPtrTy.withConst()), 2988 std::make_pair(StringRef(), QualType()) // __context with shared vars 2989 }; 2990 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP, 2991 Params); 2992 // Mark this captured region as inlined, because we don't use outlined 2993 // function directly. 2994 getCurCapturedRegion()->TheCapturedDecl->addAttr( 2995 AlwaysInlineAttr::CreateImplicit( 2996 Context, AlwaysInlineAttr::Keyword_forceinline)); 2997 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP, 2998 std::make_pair(StringRef(), QualType())); 2999 break; 3000 } 3001 case OMPD_simd: 3002 case OMPD_for: 3003 case OMPD_for_simd: 3004 case OMPD_sections: 3005 case OMPD_section: 3006 case OMPD_single: 3007 case OMPD_master: 3008 case OMPD_critical: 3009 case OMPD_taskgroup: 3010 case OMPD_distribute: 3011 case OMPD_distribute_simd: 3012 case OMPD_ordered: 3013 case OMPD_atomic: 3014 case OMPD_target_data: { 3015 Sema::CapturedParamNameType Params[] = { 3016 std::make_pair(StringRef(), QualType()) // __context with shared vars 3017 }; 3018 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP, 3019 Params); 3020 break; 3021 } 3022 case OMPD_task: { 3023 QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1).withConst(); 3024 QualType VoidPtrTy = Context.VoidPtrTy.withConst().withRestrict(); 3025 QualType KmpInt32PtrTy = 3026 Context.getPointerType(KmpInt32Ty).withConst().withRestrict(); 3027 QualType Args[] = {VoidPtrTy}; 3028 FunctionProtoType::ExtProtoInfo EPI; 3029 EPI.Variadic = true; 3030 QualType CopyFnType = Context.getFunctionType(Context.VoidTy, Args, EPI); 3031 Sema::CapturedParamNameType Params[] = { 3032 std::make_pair(".global_tid.", KmpInt32Ty), 3033 std::make_pair(".part_id.", KmpInt32PtrTy), 3034 std::make_pair(".privates.", VoidPtrTy), 3035 std::make_pair( 3036 ".copy_fn.", 3037 Context.getPointerType(CopyFnType).withConst().withRestrict()), 3038 std::make_pair(".task_t.", Context.VoidPtrTy.withConst()), 3039 std::make_pair(StringRef(), QualType()) // __context with shared vars 3040 }; 3041 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP, 3042 Params); 3043 // Mark this captured region as inlined, because we don't use outlined 3044 // function directly. 3045 getCurCapturedRegion()->TheCapturedDecl->addAttr( 3046 AlwaysInlineAttr::CreateImplicit( 3047 Context, AlwaysInlineAttr::Keyword_forceinline)); 3048 break; 3049 } 3050 case OMPD_taskloop: 3051 case OMPD_taskloop_simd: { 3052 QualType KmpInt32Ty = 3053 Context.getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/1) 3054 .withConst(); 3055 QualType KmpUInt64Ty = 3056 Context.getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/0) 3057 .withConst(); 3058 QualType KmpInt64Ty = 3059 Context.getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/1) 3060 .withConst(); 3061 QualType VoidPtrTy = Context.VoidPtrTy.withConst().withRestrict(); 3062 QualType KmpInt32PtrTy = 3063 Context.getPointerType(KmpInt32Ty).withConst().withRestrict(); 3064 QualType Args[] = {VoidPtrTy}; 3065 FunctionProtoType::ExtProtoInfo EPI; 3066 EPI.Variadic = true; 3067 QualType CopyFnType = Context.getFunctionType(Context.VoidTy, Args, EPI); 3068 Sema::CapturedParamNameType Params[] = { 3069 std::make_pair(".global_tid.", KmpInt32Ty), 3070 std::make_pair(".part_id.", KmpInt32PtrTy), 3071 std::make_pair(".privates.", VoidPtrTy), 3072 std::make_pair( 3073 ".copy_fn.", 3074 Context.getPointerType(CopyFnType).withConst().withRestrict()), 3075 std::make_pair(".task_t.", Context.VoidPtrTy.withConst()), 3076 std::make_pair(".lb.", KmpUInt64Ty), 3077 std::make_pair(".ub.", KmpUInt64Ty), 3078 std::make_pair(".st.", KmpInt64Ty), 3079 std::make_pair(".liter.", KmpInt32Ty), 3080 std::make_pair(".reductions.", VoidPtrTy), 3081 std::make_pair(StringRef(), QualType()) // __context with shared vars 3082 }; 3083 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP, 3084 Params); 3085 // Mark this captured region as inlined, because we don't use outlined 3086 // function directly. 3087 getCurCapturedRegion()->TheCapturedDecl->addAttr( 3088 AlwaysInlineAttr::CreateImplicit( 3089 Context, AlwaysInlineAttr::Keyword_forceinline)); 3090 break; 3091 } 3092 case OMPD_distribute_parallel_for_simd: 3093 case OMPD_distribute_parallel_for: { 3094 QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1).withConst(); 3095 QualType KmpInt32PtrTy = 3096 Context.getPointerType(KmpInt32Ty).withConst().withRestrict(); 3097 Sema::CapturedParamNameType Params[] = { 3098 std::make_pair(".global_tid.", KmpInt32PtrTy), 3099 std::make_pair(".bound_tid.", KmpInt32PtrTy), 3100 std::make_pair(".previous.lb.", Context.getSizeType().withConst()), 3101 std::make_pair(".previous.ub.", Context.getSizeType().withConst()), 3102 std::make_pair(StringRef(), QualType()) // __context with shared vars 3103 }; 3104 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP, 3105 Params); 3106 break; 3107 } 3108 case OMPD_target_teams_distribute_parallel_for: 3109 case OMPD_target_teams_distribute_parallel_for_simd: { 3110 QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1).withConst(); 3111 QualType KmpInt32PtrTy = 3112 Context.getPointerType(KmpInt32Ty).withConst().withRestrict(); 3113 QualType VoidPtrTy = Context.VoidPtrTy.withConst().withRestrict(); 3114 3115 QualType Args[] = {VoidPtrTy}; 3116 FunctionProtoType::ExtProtoInfo EPI; 3117 EPI.Variadic = true; 3118 QualType CopyFnType = Context.getFunctionType(Context.VoidTy, Args, EPI); 3119 Sema::CapturedParamNameType Params[] = { 3120 std::make_pair(".global_tid.", KmpInt32Ty), 3121 std::make_pair(".part_id.", KmpInt32PtrTy), 3122 std::make_pair(".privates.", VoidPtrTy), 3123 std::make_pair( 3124 ".copy_fn.", 3125 Context.getPointerType(CopyFnType).withConst().withRestrict()), 3126 std::make_pair(".task_t.", Context.VoidPtrTy.withConst()), 3127 std::make_pair(StringRef(), QualType()) // __context with shared vars 3128 }; 3129 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP, 3130 Params); 3131 // Mark this captured region as inlined, because we don't use outlined 3132 // function directly. 3133 getCurCapturedRegion()->TheCapturedDecl->addAttr( 3134 AlwaysInlineAttr::CreateImplicit( 3135 Context, AlwaysInlineAttr::Keyword_forceinline)); 3136 Sema::CapturedParamNameType ParamsTarget[] = { 3137 std::make_pair(StringRef(), QualType()) // __context with shared vars 3138 }; 3139 // Start a captured region for 'target' with no implicit parameters. 3140 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP, 3141 ParamsTarget); 3142 3143 Sema::CapturedParamNameType ParamsTeams[] = { 3144 std::make_pair(".global_tid.", KmpInt32PtrTy), 3145 std::make_pair(".bound_tid.", KmpInt32PtrTy), 3146 std::make_pair(StringRef(), QualType()) // __context with shared vars 3147 }; 3148 // Start a captured region for 'target' with no implicit parameters. 3149 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP, 3150 ParamsTeams); 3151 3152 Sema::CapturedParamNameType ParamsParallel[] = { 3153 std::make_pair(".global_tid.", KmpInt32PtrTy), 3154 std::make_pair(".bound_tid.", KmpInt32PtrTy), 3155 std::make_pair(".previous.lb.", Context.getSizeType().withConst()), 3156 std::make_pair(".previous.ub.", Context.getSizeType().withConst()), 3157 std::make_pair(StringRef(), QualType()) // __context with shared vars 3158 }; 3159 // Start a captured region for 'teams' or 'parallel'. Both regions have 3160 // the same implicit parameters. 3161 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP, 3162 ParamsParallel); 3163 break; 3164 } 3165 3166 case OMPD_teams_distribute_parallel_for: 3167 case OMPD_teams_distribute_parallel_for_simd: { 3168 QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1).withConst(); 3169 QualType KmpInt32PtrTy = 3170 Context.getPointerType(KmpInt32Ty).withConst().withRestrict(); 3171 3172 Sema::CapturedParamNameType ParamsTeams[] = { 3173 std::make_pair(".global_tid.", KmpInt32PtrTy), 3174 std::make_pair(".bound_tid.", KmpInt32PtrTy), 3175 std::make_pair(StringRef(), QualType()) // __context with shared vars 3176 }; 3177 // Start a captured region for 'target' with no implicit parameters. 3178 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP, 3179 ParamsTeams); 3180 3181 Sema::CapturedParamNameType ParamsParallel[] = { 3182 std::make_pair(".global_tid.", KmpInt32PtrTy), 3183 std::make_pair(".bound_tid.", KmpInt32PtrTy), 3184 std::make_pair(".previous.lb.", Context.getSizeType().withConst()), 3185 std::make_pair(".previous.ub.", Context.getSizeType().withConst()), 3186 std::make_pair(StringRef(), QualType()) // __context with shared vars 3187 }; 3188 // Start a captured region for 'teams' or 'parallel'. Both regions have 3189 // the same implicit parameters. 3190 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP, 3191 ParamsParallel); 3192 break; 3193 } 3194 case OMPD_target_update: 3195 case OMPD_target_enter_data: 3196 case OMPD_target_exit_data: { 3197 QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1).withConst(); 3198 QualType VoidPtrTy = Context.VoidPtrTy.withConst().withRestrict(); 3199 QualType KmpInt32PtrTy = 3200 Context.getPointerType(KmpInt32Ty).withConst().withRestrict(); 3201 QualType Args[] = {VoidPtrTy}; 3202 FunctionProtoType::ExtProtoInfo EPI; 3203 EPI.Variadic = true; 3204 QualType CopyFnType = Context.getFunctionType(Context.VoidTy, Args, EPI); 3205 Sema::CapturedParamNameType Params[] = { 3206 std::make_pair(".global_tid.", KmpInt32Ty), 3207 std::make_pair(".part_id.", KmpInt32PtrTy), 3208 std::make_pair(".privates.", VoidPtrTy), 3209 std::make_pair( 3210 ".copy_fn.", 3211 Context.getPointerType(CopyFnType).withConst().withRestrict()), 3212 std::make_pair(".task_t.", Context.VoidPtrTy.withConst()), 3213 std::make_pair(StringRef(), QualType()) // __context with shared vars 3214 }; 3215 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP, 3216 Params); 3217 // Mark this captured region as inlined, because we don't use outlined 3218 // function directly. 3219 getCurCapturedRegion()->TheCapturedDecl->addAttr( 3220 AlwaysInlineAttr::CreateImplicit( 3221 Context, AlwaysInlineAttr::Keyword_forceinline)); 3222 break; 3223 } 3224 case OMPD_threadprivate: 3225 case OMPD_allocate: 3226 case OMPD_taskyield: 3227 case OMPD_barrier: 3228 case OMPD_taskwait: 3229 case OMPD_cancellation_point: 3230 case OMPD_cancel: 3231 case OMPD_flush: 3232 case OMPD_declare_reduction: 3233 case OMPD_declare_mapper: 3234 case OMPD_declare_simd: 3235 case OMPD_declare_target: 3236 case OMPD_end_declare_target: 3237 case OMPD_requires: 3238 llvm_unreachable("OpenMP Directive is not allowed"); 3239 case OMPD_unknown: 3240 llvm_unreachable("Unknown OpenMP directive"); 3241 } 3242 } 3243 3244 int Sema::getOpenMPCaptureLevels(OpenMPDirectiveKind DKind) { 3245 SmallVector<OpenMPDirectiveKind, 4> CaptureRegions; 3246 getOpenMPCaptureRegions(CaptureRegions, DKind); 3247 return CaptureRegions.size(); 3248 } 3249 3250 static OMPCapturedExprDecl *buildCaptureDecl(Sema &S, IdentifierInfo *Id, 3251 Expr *CaptureExpr, bool WithInit, 3252 bool AsExpression) { 3253 assert(CaptureExpr); 3254 ASTContext &C = S.getASTContext(); 3255 Expr *Init = AsExpression ? CaptureExpr : CaptureExpr->IgnoreImpCasts(); 3256 QualType Ty = Init->getType(); 3257 if (CaptureExpr->getObjectKind() == OK_Ordinary && CaptureExpr->isGLValue()) { 3258 if (S.getLangOpts().CPlusPlus) { 3259 Ty = C.getLValueReferenceType(Ty); 3260 } else { 3261 Ty = C.getPointerType(Ty); 3262 ExprResult Res = 3263 S.CreateBuiltinUnaryOp(CaptureExpr->getExprLoc(), UO_AddrOf, Init); 3264 if (!Res.isUsable()) 3265 return nullptr; 3266 Init = Res.get(); 3267 } 3268 WithInit = true; 3269 } 3270 auto *CED = OMPCapturedExprDecl::Create(C, S.CurContext, Id, Ty, 3271 CaptureExpr->getBeginLoc()); 3272 if (!WithInit) 3273 CED->addAttr(OMPCaptureNoInitAttr::CreateImplicit(C)); 3274 S.CurContext->addHiddenDecl(CED); 3275 S.AddInitializerToDecl(CED, Init, /*DirectInit=*/false); 3276 return CED; 3277 } 3278 3279 static DeclRefExpr *buildCapture(Sema &S, ValueDecl *D, Expr *CaptureExpr, 3280 bool WithInit) { 3281 OMPCapturedExprDecl *CD; 3282 if (VarDecl *VD = S.isOpenMPCapturedDecl(D)) 3283 CD = cast<OMPCapturedExprDecl>(VD); 3284 else 3285 CD = buildCaptureDecl(S, D->getIdentifier(), CaptureExpr, WithInit, 3286 /*AsExpression=*/false); 3287 return buildDeclRefExpr(S, CD, CD->getType().getNonReferenceType(), 3288 CaptureExpr->getExprLoc()); 3289 } 3290 3291 static ExprResult buildCapture(Sema &S, Expr *CaptureExpr, DeclRefExpr *&Ref) { 3292 CaptureExpr = S.DefaultLvalueConversion(CaptureExpr).get(); 3293 if (!Ref) { 3294 OMPCapturedExprDecl *CD = buildCaptureDecl( 3295 S, &S.getASTContext().Idents.get(".capture_expr."), CaptureExpr, 3296 /*WithInit=*/true, /*AsExpression=*/true); 3297 Ref = buildDeclRefExpr(S, CD, CD->getType().getNonReferenceType(), 3298 CaptureExpr->getExprLoc()); 3299 } 3300 ExprResult Res = Ref; 3301 if (!S.getLangOpts().CPlusPlus && 3302 CaptureExpr->getObjectKind() == OK_Ordinary && CaptureExpr->isGLValue() && 3303 Ref->getType()->isPointerType()) { 3304 Res = S.CreateBuiltinUnaryOp(CaptureExpr->getExprLoc(), UO_Deref, Ref); 3305 if (!Res.isUsable()) 3306 return ExprError(); 3307 } 3308 return S.DefaultLvalueConversion(Res.get()); 3309 } 3310 3311 namespace { 3312 // OpenMP directives parsed in this section are represented as a 3313 // CapturedStatement with an associated statement. If a syntax error 3314 // is detected during the parsing of the associated statement, the 3315 // compiler must abort processing and close the CapturedStatement. 3316 // 3317 // Combined directives such as 'target parallel' have more than one 3318 // nested CapturedStatements. This RAII ensures that we unwind out 3319 // of all the nested CapturedStatements when an error is found. 3320 class CaptureRegionUnwinderRAII { 3321 private: 3322 Sema &S; 3323 bool &ErrorFound; 3324 OpenMPDirectiveKind DKind = OMPD_unknown; 3325 3326 public: 3327 CaptureRegionUnwinderRAII(Sema &S, bool &ErrorFound, 3328 OpenMPDirectiveKind DKind) 3329 : S(S), ErrorFound(ErrorFound), DKind(DKind) {} 3330 ~CaptureRegionUnwinderRAII() { 3331 if (ErrorFound) { 3332 int ThisCaptureLevel = S.getOpenMPCaptureLevels(DKind); 3333 while (--ThisCaptureLevel >= 0) 3334 S.ActOnCapturedRegionError(); 3335 } 3336 } 3337 }; 3338 } // namespace 3339 3340 void Sema::tryCaptureOpenMPLambdas(ValueDecl *V) { 3341 // Capture variables captured by reference in lambdas for target-based 3342 // directives. 3343 if (!CurContext->isDependentContext() && 3344 (isOpenMPTargetExecutionDirective(DSAStack->getCurrentDirective()) || 3345 isOpenMPTargetDataManagementDirective( 3346 DSAStack->getCurrentDirective()))) { 3347 QualType Type = V->getType(); 3348 if (const auto *RD = Type.getCanonicalType() 3349 .getNonReferenceType() 3350 ->getAsCXXRecordDecl()) { 3351 bool SavedForceCaptureByReferenceInTargetExecutable = 3352 DSAStack->isForceCaptureByReferenceInTargetExecutable(); 3353 DSAStack->setForceCaptureByReferenceInTargetExecutable( 3354 /*V=*/true); 3355 if (RD->isLambda()) { 3356 llvm::DenseMap<const VarDecl *, FieldDecl *> Captures; 3357 FieldDecl *ThisCapture; 3358 RD->getCaptureFields(Captures, ThisCapture); 3359 for (const LambdaCapture &LC : RD->captures()) { 3360 if (LC.getCaptureKind() == LCK_ByRef) { 3361 VarDecl *VD = LC.getCapturedVar(); 3362 DeclContext *VDC = VD->getDeclContext(); 3363 if (!VDC->Encloses(CurContext)) 3364 continue; 3365 MarkVariableReferenced(LC.getLocation(), VD); 3366 } else if (LC.getCaptureKind() == LCK_This) { 3367 QualType ThisTy = getCurrentThisType(); 3368 if (!ThisTy.isNull() && 3369 Context.typesAreCompatible(ThisTy, ThisCapture->getType())) 3370 CheckCXXThisCapture(LC.getLocation()); 3371 } 3372 } 3373 } 3374 DSAStack->setForceCaptureByReferenceInTargetExecutable( 3375 SavedForceCaptureByReferenceInTargetExecutable); 3376 } 3377 } 3378 } 3379 3380 StmtResult Sema::ActOnOpenMPRegionEnd(StmtResult S, 3381 ArrayRef<OMPClause *> Clauses) { 3382 bool ErrorFound = false; 3383 CaptureRegionUnwinderRAII CaptureRegionUnwinder( 3384 *this, ErrorFound, DSAStack->getCurrentDirective()); 3385 if (!S.isUsable()) { 3386 ErrorFound = true; 3387 return StmtError(); 3388 } 3389 3390 SmallVector<OpenMPDirectiveKind, 4> CaptureRegions; 3391 getOpenMPCaptureRegions(CaptureRegions, DSAStack->getCurrentDirective()); 3392 OMPOrderedClause *OC = nullptr; 3393 OMPScheduleClause *SC = nullptr; 3394 SmallVector<const OMPLinearClause *, 4> LCs; 3395 SmallVector<const OMPClauseWithPreInit *, 4> PICs; 3396 // This is required for proper codegen. 3397 for (OMPClause *Clause : Clauses) { 3398 if (isOpenMPTaskingDirective(DSAStack->getCurrentDirective()) && 3399 Clause->getClauseKind() == OMPC_in_reduction) { 3400 // Capture taskgroup task_reduction descriptors inside the tasking regions 3401 // with the corresponding in_reduction items. 3402 auto *IRC = cast<OMPInReductionClause>(Clause); 3403 for (Expr *E : IRC->taskgroup_descriptors()) 3404 if (E) 3405 MarkDeclarationsReferencedInExpr(E); 3406 } 3407 if (isOpenMPPrivate(Clause->getClauseKind()) || 3408 Clause->getClauseKind() == OMPC_copyprivate || 3409 (getLangOpts().OpenMPUseTLS && 3410 getASTContext().getTargetInfo().isTLSSupported() && 3411 Clause->getClauseKind() == OMPC_copyin)) { 3412 DSAStack->setForceVarCapturing(Clause->getClauseKind() == OMPC_copyin); 3413 // Mark all variables in private list clauses as used in inner region. 3414 for (Stmt *VarRef : Clause->children()) { 3415 if (auto *E = cast_or_null<Expr>(VarRef)) { 3416 MarkDeclarationsReferencedInExpr(E); 3417 } 3418 } 3419 DSAStack->setForceVarCapturing(/*V=*/false); 3420 } else if (CaptureRegions.size() > 1 || 3421 CaptureRegions.back() != OMPD_unknown) { 3422 if (auto *C = OMPClauseWithPreInit::get(Clause)) 3423 PICs.push_back(C); 3424 if (auto *C = OMPClauseWithPostUpdate::get(Clause)) { 3425 if (Expr *E = C->getPostUpdateExpr()) 3426 MarkDeclarationsReferencedInExpr(E); 3427 } 3428 } 3429 if (Clause->getClauseKind() == OMPC_schedule) 3430 SC = cast<OMPScheduleClause>(Clause); 3431 else if (Clause->getClauseKind() == OMPC_ordered) 3432 OC = cast<OMPOrderedClause>(Clause); 3433 else if (Clause->getClauseKind() == OMPC_linear) 3434 LCs.push_back(cast<OMPLinearClause>(Clause)); 3435 } 3436 // OpenMP, 2.7.1 Loop Construct, Restrictions 3437 // The nonmonotonic modifier cannot be specified if an ordered clause is 3438 // specified. 3439 if (SC && 3440 (SC->getFirstScheduleModifier() == OMPC_SCHEDULE_MODIFIER_nonmonotonic || 3441 SC->getSecondScheduleModifier() == 3442 OMPC_SCHEDULE_MODIFIER_nonmonotonic) && 3443 OC) { 3444 Diag(SC->getFirstScheduleModifier() == OMPC_SCHEDULE_MODIFIER_nonmonotonic 3445 ? SC->getFirstScheduleModifierLoc() 3446 : SC->getSecondScheduleModifierLoc(), 3447 diag::err_omp_schedule_nonmonotonic_ordered) 3448 << SourceRange(OC->getBeginLoc(), OC->getEndLoc()); 3449 ErrorFound = true; 3450 } 3451 if (!LCs.empty() && OC && OC->getNumForLoops()) { 3452 for (const OMPLinearClause *C : LCs) { 3453 Diag(C->getBeginLoc(), diag::err_omp_linear_ordered) 3454 << SourceRange(OC->getBeginLoc(), OC->getEndLoc()); 3455 } 3456 ErrorFound = true; 3457 } 3458 if (isOpenMPWorksharingDirective(DSAStack->getCurrentDirective()) && 3459 isOpenMPSimdDirective(DSAStack->getCurrentDirective()) && OC && 3460 OC->getNumForLoops()) { 3461 Diag(OC->getBeginLoc(), diag::err_omp_ordered_simd) 3462 << getOpenMPDirectiveName(DSAStack->getCurrentDirective()); 3463 ErrorFound = true; 3464 } 3465 if (ErrorFound) { 3466 return StmtError(); 3467 } 3468 StmtResult SR = S; 3469 unsigned CompletedRegions = 0; 3470 for (OpenMPDirectiveKind ThisCaptureRegion : llvm::reverse(CaptureRegions)) { 3471 // Mark all variables in private list clauses as used in inner region. 3472 // Required for proper codegen of combined directives. 3473 // TODO: add processing for other clauses. 3474 if (ThisCaptureRegion != OMPD_unknown) { 3475 for (const clang::OMPClauseWithPreInit *C : PICs) { 3476 OpenMPDirectiveKind CaptureRegion = C->getCaptureRegion(); 3477 // Find the particular capture region for the clause if the 3478 // directive is a combined one with multiple capture regions. 3479 // If the directive is not a combined one, the capture region 3480 // associated with the clause is OMPD_unknown and is generated 3481 // only once. 3482 if (CaptureRegion == ThisCaptureRegion || 3483 CaptureRegion == OMPD_unknown) { 3484 if (auto *DS = cast_or_null<DeclStmt>(C->getPreInitStmt())) { 3485 for (Decl *D : DS->decls()) 3486 MarkVariableReferenced(D->getLocation(), cast<VarDecl>(D)); 3487 } 3488 } 3489 } 3490 } 3491 if (++CompletedRegions == CaptureRegions.size()) 3492 DSAStack->setBodyComplete(); 3493 SR = ActOnCapturedRegionEnd(SR.get()); 3494 } 3495 return SR; 3496 } 3497 3498 static bool checkCancelRegion(Sema &SemaRef, OpenMPDirectiveKind CurrentRegion, 3499 OpenMPDirectiveKind CancelRegion, 3500 SourceLocation StartLoc) { 3501 // CancelRegion is only needed for cancel and cancellation_point. 3502 if (CurrentRegion != OMPD_cancel && CurrentRegion != OMPD_cancellation_point) 3503 return false; 3504 3505 if (CancelRegion == OMPD_parallel || CancelRegion == OMPD_for || 3506 CancelRegion == OMPD_sections || CancelRegion == OMPD_taskgroup) 3507 return false; 3508 3509 SemaRef.Diag(StartLoc, diag::err_omp_wrong_cancel_region) 3510 << getOpenMPDirectiveName(CancelRegion); 3511 return true; 3512 } 3513 3514 static bool checkNestingOfRegions(Sema &SemaRef, const DSAStackTy *Stack, 3515 OpenMPDirectiveKind CurrentRegion, 3516 const DeclarationNameInfo &CurrentName, 3517 OpenMPDirectiveKind CancelRegion, 3518 SourceLocation StartLoc) { 3519 if (Stack->getCurScope()) { 3520 OpenMPDirectiveKind ParentRegion = Stack->getParentDirective(); 3521 OpenMPDirectiveKind OffendingRegion = ParentRegion; 3522 bool NestingProhibited = false; 3523 bool CloseNesting = true; 3524 bool OrphanSeen = false; 3525 enum { 3526 NoRecommend, 3527 ShouldBeInParallelRegion, 3528 ShouldBeInOrderedRegion, 3529 ShouldBeInTargetRegion, 3530 ShouldBeInTeamsRegion 3531 } Recommend = NoRecommend; 3532 if (isOpenMPSimdDirective(ParentRegion) && CurrentRegion != OMPD_ordered) { 3533 // OpenMP [2.16, Nesting of Regions] 3534 // OpenMP constructs may not be nested inside a simd region. 3535 // OpenMP [2.8.1,simd Construct, Restrictions] 3536 // An ordered construct with the simd clause is the only OpenMP 3537 // construct that can appear in the simd region. 3538 // Allowing a SIMD construct nested in another SIMD construct is an 3539 // extension. The OpenMP 4.5 spec does not allow it. Issue a warning 3540 // message. 3541 SemaRef.Diag(StartLoc, (CurrentRegion != OMPD_simd) 3542 ? diag::err_omp_prohibited_region_simd 3543 : diag::warn_omp_nesting_simd); 3544 return CurrentRegion != OMPD_simd; 3545 } 3546 if (ParentRegion == OMPD_atomic) { 3547 // OpenMP [2.16, Nesting of Regions] 3548 // OpenMP constructs may not be nested inside an atomic region. 3549 SemaRef.Diag(StartLoc, diag::err_omp_prohibited_region_atomic); 3550 return true; 3551 } 3552 if (CurrentRegion == OMPD_section) { 3553 // OpenMP [2.7.2, sections Construct, Restrictions] 3554 // Orphaned section directives are prohibited. That is, the section 3555 // directives must appear within the sections construct and must not be 3556 // encountered elsewhere in the sections region. 3557 if (ParentRegion != OMPD_sections && 3558 ParentRegion != OMPD_parallel_sections) { 3559 SemaRef.Diag(StartLoc, diag::err_omp_orphaned_section_directive) 3560 << (ParentRegion != OMPD_unknown) 3561 << getOpenMPDirectiveName(ParentRegion); 3562 return true; 3563 } 3564 return false; 3565 } 3566 // Allow some constructs (except teams and cancellation constructs) to be 3567 // orphaned (they could be used in functions, called from OpenMP regions 3568 // with the required preconditions). 3569 if (ParentRegion == OMPD_unknown && 3570 !isOpenMPNestingTeamsDirective(CurrentRegion) && 3571 CurrentRegion != OMPD_cancellation_point && 3572 CurrentRegion != OMPD_cancel) 3573 return false; 3574 if (CurrentRegion == OMPD_cancellation_point || 3575 CurrentRegion == OMPD_cancel) { 3576 // OpenMP [2.16, Nesting of Regions] 3577 // A cancellation point construct for which construct-type-clause is 3578 // taskgroup must be nested inside a task construct. A cancellation 3579 // point construct for which construct-type-clause is not taskgroup must 3580 // be closely nested inside an OpenMP construct that matches the type 3581 // specified in construct-type-clause. 3582 // A cancel construct for which construct-type-clause is taskgroup must be 3583 // nested inside a task construct. A cancel construct for which 3584 // construct-type-clause is not taskgroup must be closely nested inside an 3585 // OpenMP construct that matches the type specified in 3586 // construct-type-clause. 3587 NestingProhibited = 3588 !((CancelRegion == OMPD_parallel && 3589 (ParentRegion == OMPD_parallel || 3590 ParentRegion == OMPD_target_parallel)) || 3591 (CancelRegion == OMPD_for && 3592 (ParentRegion == OMPD_for || ParentRegion == OMPD_parallel_for || 3593 ParentRegion == OMPD_target_parallel_for || 3594 ParentRegion == OMPD_distribute_parallel_for || 3595 ParentRegion == OMPD_teams_distribute_parallel_for || 3596 ParentRegion == OMPD_target_teams_distribute_parallel_for)) || 3597 (CancelRegion == OMPD_taskgroup && ParentRegion == OMPD_task) || 3598 (CancelRegion == OMPD_sections && 3599 (ParentRegion == OMPD_section || ParentRegion == OMPD_sections || 3600 ParentRegion == OMPD_parallel_sections))); 3601 OrphanSeen = ParentRegion == OMPD_unknown; 3602 } else if (CurrentRegion == OMPD_master) { 3603 // OpenMP [2.16, Nesting of Regions] 3604 // A master region may not be closely nested inside a worksharing, 3605 // atomic, or explicit task region. 3606 NestingProhibited = isOpenMPWorksharingDirective(ParentRegion) || 3607 isOpenMPTaskingDirective(ParentRegion); 3608 } else if (CurrentRegion == OMPD_critical && CurrentName.getName()) { 3609 // OpenMP [2.16, Nesting of Regions] 3610 // A critical region may not be nested (closely or otherwise) inside a 3611 // critical region with the same name. Note that this restriction is not 3612 // sufficient to prevent deadlock. 3613 SourceLocation PreviousCriticalLoc; 3614 bool DeadLock = Stack->hasDirective( 3615 [CurrentName, &PreviousCriticalLoc](OpenMPDirectiveKind K, 3616 const DeclarationNameInfo &DNI, 3617 SourceLocation Loc) { 3618 if (K == OMPD_critical && DNI.getName() == CurrentName.getName()) { 3619 PreviousCriticalLoc = Loc; 3620 return true; 3621 } 3622 return false; 3623 }, 3624 false /* skip top directive */); 3625 if (DeadLock) { 3626 SemaRef.Diag(StartLoc, 3627 diag::err_omp_prohibited_region_critical_same_name) 3628 << CurrentName.getName(); 3629 if (PreviousCriticalLoc.isValid()) 3630 SemaRef.Diag(PreviousCriticalLoc, 3631 diag::note_omp_previous_critical_region); 3632 return true; 3633 } 3634 } else if (CurrentRegion == OMPD_barrier) { 3635 // OpenMP [2.16, Nesting of Regions] 3636 // A barrier region may not be closely nested inside a worksharing, 3637 // explicit task, critical, ordered, atomic, or master region. 3638 NestingProhibited = isOpenMPWorksharingDirective(ParentRegion) || 3639 isOpenMPTaskingDirective(ParentRegion) || 3640 ParentRegion == OMPD_master || 3641 ParentRegion == OMPD_critical || 3642 ParentRegion == OMPD_ordered; 3643 } else if (isOpenMPWorksharingDirective(CurrentRegion) && 3644 !isOpenMPParallelDirective(CurrentRegion) && 3645 !isOpenMPTeamsDirective(CurrentRegion)) { 3646 // OpenMP [2.16, Nesting of Regions] 3647 // A worksharing region may not be closely nested inside a worksharing, 3648 // explicit task, critical, ordered, atomic, or master region. 3649 NestingProhibited = isOpenMPWorksharingDirective(ParentRegion) || 3650 isOpenMPTaskingDirective(ParentRegion) || 3651 ParentRegion == OMPD_master || 3652 ParentRegion == OMPD_critical || 3653 ParentRegion == OMPD_ordered; 3654 Recommend = ShouldBeInParallelRegion; 3655 } else if (CurrentRegion == OMPD_ordered) { 3656 // OpenMP [2.16, Nesting of Regions] 3657 // An ordered region may not be closely nested inside a critical, 3658 // atomic, or explicit task region. 3659 // An ordered region must be closely nested inside a loop region (or 3660 // parallel loop region) with an ordered clause. 3661 // OpenMP [2.8.1,simd Construct, Restrictions] 3662 // An ordered construct with the simd clause is the only OpenMP construct 3663 // that can appear in the simd region. 3664 NestingProhibited = ParentRegion == OMPD_critical || 3665 isOpenMPTaskingDirective(ParentRegion) || 3666 !(isOpenMPSimdDirective(ParentRegion) || 3667 Stack->isParentOrderedRegion()); 3668 Recommend = ShouldBeInOrderedRegion; 3669 } else if (isOpenMPNestingTeamsDirective(CurrentRegion)) { 3670 // OpenMP [2.16, Nesting of Regions] 3671 // If specified, a teams construct must be contained within a target 3672 // construct. 3673 NestingProhibited = ParentRegion != OMPD_target; 3674 OrphanSeen = ParentRegion == OMPD_unknown; 3675 Recommend = ShouldBeInTargetRegion; 3676 } 3677 if (!NestingProhibited && 3678 !isOpenMPTargetExecutionDirective(CurrentRegion) && 3679 !isOpenMPTargetDataManagementDirective(CurrentRegion) && 3680 (ParentRegion == OMPD_teams || ParentRegion == OMPD_target_teams)) { 3681 // OpenMP [2.16, Nesting of Regions] 3682 // distribute, parallel, parallel sections, parallel workshare, and the 3683 // parallel loop and parallel loop SIMD constructs are the only OpenMP 3684 // constructs that can be closely nested in the teams region. 3685 NestingProhibited = !isOpenMPParallelDirective(CurrentRegion) && 3686 !isOpenMPDistributeDirective(CurrentRegion); 3687 Recommend = ShouldBeInParallelRegion; 3688 } 3689 if (!NestingProhibited && 3690 isOpenMPNestingDistributeDirective(CurrentRegion)) { 3691 // OpenMP 4.5 [2.17 Nesting of Regions] 3692 // The region associated with the distribute construct must be strictly 3693 // nested inside a teams region 3694 NestingProhibited = 3695 (ParentRegion != OMPD_teams && ParentRegion != OMPD_target_teams); 3696 Recommend = ShouldBeInTeamsRegion; 3697 } 3698 if (!NestingProhibited && 3699 (isOpenMPTargetExecutionDirective(CurrentRegion) || 3700 isOpenMPTargetDataManagementDirective(CurrentRegion))) { 3701 // OpenMP 4.5 [2.17 Nesting of Regions] 3702 // If a target, target update, target data, target enter data, or 3703 // target exit data construct is encountered during execution of a 3704 // target region, the behavior is unspecified. 3705 NestingProhibited = Stack->hasDirective( 3706 [&OffendingRegion](OpenMPDirectiveKind K, const DeclarationNameInfo &, 3707 SourceLocation) { 3708 if (isOpenMPTargetExecutionDirective(K)) { 3709 OffendingRegion = K; 3710 return true; 3711 } 3712 return false; 3713 }, 3714 false /* don't skip top directive */); 3715 CloseNesting = false; 3716 } 3717 if (NestingProhibited) { 3718 if (OrphanSeen) { 3719 SemaRef.Diag(StartLoc, diag::err_omp_orphaned_device_directive) 3720 << getOpenMPDirectiveName(CurrentRegion) << Recommend; 3721 } else { 3722 SemaRef.Diag(StartLoc, diag::err_omp_prohibited_region) 3723 << CloseNesting << getOpenMPDirectiveName(OffendingRegion) 3724 << Recommend << getOpenMPDirectiveName(CurrentRegion); 3725 } 3726 return true; 3727 } 3728 } 3729 return false; 3730 } 3731 3732 static bool checkIfClauses(Sema &S, OpenMPDirectiveKind Kind, 3733 ArrayRef<OMPClause *> Clauses, 3734 ArrayRef<OpenMPDirectiveKind> AllowedNameModifiers) { 3735 bool ErrorFound = false; 3736 unsigned NamedModifiersNumber = 0; 3737 SmallVector<const OMPIfClause *, OMPC_unknown + 1> FoundNameModifiers( 3738 OMPD_unknown + 1); 3739 SmallVector<SourceLocation, 4> NameModifierLoc; 3740 for (const OMPClause *C : Clauses) { 3741 if (const auto *IC = dyn_cast_or_null<OMPIfClause>(C)) { 3742 // At most one if clause without a directive-name-modifier can appear on 3743 // the directive. 3744 OpenMPDirectiveKind CurNM = IC->getNameModifier(); 3745 if (FoundNameModifiers[CurNM]) { 3746 S.Diag(C->getBeginLoc(), diag::err_omp_more_one_clause) 3747 << getOpenMPDirectiveName(Kind) << getOpenMPClauseName(OMPC_if) 3748 << (CurNM != OMPD_unknown) << getOpenMPDirectiveName(CurNM); 3749 ErrorFound = true; 3750 } else if (CurNM != OMPD_unknown) { 3751 NameModifierLoc.push_back(IC->getNameModifierLoc()); 3752 ++NamedModifiersNumber; 3753 } 3754 FoundNameModifiers[CurNM] = IC; 3755 if (CurNM == OMPD_unknown) 3756 continue; 3757 // Check if the specified name modifier is allowed for the current 3758 // directive. 3759 // At most one if clause with the particular directive-name-modifier can 3760 // appear on the directive. 3761 bool MatchFound = false; 3762 for (auto NM : AllowedNameModifiers) { 3763 if (CurNM == NM) { 3764 MatchFound = true; 3765 break; 3766 } 3767 } 3768 if (!MatchFound) { 3769 S.Diag(IC->getNameModifierLoc(), 3770 diag::err_omp_wrong_if_directive_name_modifier) 3771 << getOpenMPDirectiveName(CurNM) << getOpenMPDirectiveName(Kind); 3772 ErrorFound = true; 3773 } 3774 } 3775 } 3776 // If any if clause on the directive includes a directive-name-modifier then 3777 // all if clauses on the directive must include a directive-name-modifier. 3778 if (FoundNameModifiers[OMPD_unknown] && NamedModifiersNumber > 0) { 3779 if (NamedModifiersNumber == AllowedNameModifiers.size()) { 3780 S.Diag(FoundNameModifiers[OMPD_unknown]->getBeginLoc(), 3781 diag::err_omp_no_more_if_clause); 3782 } else { 3783 std::string Values; 3784 std::string Sep(", "); 3785 unsigned AllowedCnt = 0; 3786 unsigned TotalAllowedNum = 3787 AllowedNameModifiers.size() - NamedModifiersNumber; 3788 for (unsigned Cnt = 0, End = AllowedNameModifiers.size(); Cnt < End; 3789 ++Cnt) { 3790 OpenMPDirectiveKind NM = AllowedNameModifiers[Cnt]; 3791 if (!FoundNameModifiers[NM]) { 3792 Values += "'"; 3793 Values += getOpenMPDirectiveName(NM); 3794 Values += "'"; 3795 if (AllowedCnt + 2 == TotalAllowedNum) 3796 Values += " or "; 3797 else if (AllowedCnt + 1 != TotalAllowedNum) 3798 Values += Sep; 3799 ++AllowedCnt; 3800 } 3801 } 3802 S.Diag(FoundNameModifiers[OMPD_unknown]->getCondition()->getBeginLoc(), 3803 diag::err_omp_unnamed_if_clause) 3804 << (TotalAllowedNum > 1) << Values; 3805 } 3806 for (SourceLocation Loc : NameModifierLoc) { 3807 S.Diag(Loc, diag::note_omp_previous_named_if_clause); 3808 } 3809 ErrorFound = true; 3810 } 3811 return ErrorFound; 3812 } 3813 3814 static std::pair<ValueDecl *, bool> 3815 getPrivateItem(Sema &S, Expr *&RefExpr, SourceLocation &ELoc, 3816 SourceRange &ERange, bool AllowArraySection = false) { 3817 if (RefExpr->isTypeDependent() || RefExpr->isValueDependent() || 3818 RefExpr->containsUnexpandedParameterPack()) 3819 return std::make_pair(nullptr, true); 3820 3821 // OpenMP [3.1, C/C++] 3822 // A list item is a variable name. 3823 // OpenMP [2.9.3.3, Restrictions, p.1] 3824 // A variable that is part of another variable (as an array or 3825 // structure element) cannot appear in a private clause. 3826 RefExpr = RefExpr->IgnoreParens(); 3827 enum { 3828 NoArrayExpr = -1, 3829 ArraySubscript = 0, 3830 OMPArraySection = 1 3831 } IsArrayExpr = NoArrayExpr; 3832 if (AllowArraySection) { 3833 if (auto *ASE = dyn_cast_or_null<ArraySubscriptExpr>(RefExpr)) { 3834 Expr *Base = ASE->getBase()->IgnoreParenImpCasts(); 3835 while (auto *TempASE = dyn_cast<ArraySubscriptExpr>(Base)) 3836 Base = TempASE->getBase()->IgnoreParenImpCasts(); 3837 RefExpr = Base; 3838 IsArrayExpr = ArraySubscript; 3839 } else if (auto *OASE = dyn_cast_or_null<OMPArraySectionExpr>(RefExpr)) { 3840 Expr *Base = OASE->getBase()->IgnoreParenImpCasts(); 3841 while (auto *TempOASE = dyn_cast<OMPArraySectionExpr>(Base)) 3842 Base = TempOASE->getBase()->IgnoreParenImpCasts(); 3843 while (auto *TempASE = dyn_cast<ArraySubscriptExpr>(Base)) 3844 Base = TempASE->getBase()->IgnoreParenImpCasts(); 3845 RefExpr = Base; 3846 IsArrayExpr = OMPArraySection; 3847 } 3848 } 3849 ELoc = RefExpr->getExprLoc(); 3850 ERange = RefExpr->getSourceRange(); 3851 RefExpr = RefExpr->IgnoreParenImpCasts(); 3852 auto *DE = dyn_cast_or_null<DeclRefExpr>(RefExpr); 3853 auto *ME = dyn_cast_or_null<MemberExpr>(RefExpr); 3854 if ((!DE || !isa<VarDecl>(DE->getDecl())) && 3855 (S.getCurrentThisType().isNull() || !ME || 3856 !isa<CXXThisExpr>(ME->getBase()->IgnoreParenImpCasts()) || 3857 !isa<FieldDecl>(ME->getMemberDecl()))) { 3858 if (IsArrayExpr != NoArrayExpr) { 3859 S.Diag(ELoc, diag::err_omp_expected_base_var_name) << IsArrayExpr 3860 << ERange; 3861 } else { 3862 S.Diag(ELoc, 3863 AllowArraySection 3864 ? diag::err_omp_expected_var_name_member_expr_or_array_item 3865 : diag::err_omp_expected_var_name_member_expr) 3866 << (S.getCurrentThisType().isNull() ? 0 : 1) << ERange; 3867 } 3868 return std::make_pair(nullptr, false); 3869 } 3870 return std::make_pair( 3871 getCanonicalDecl(DE ? DE->getDecl() : ME->getMemberDecl()), false); 3872 } 3873 3874 static void checkAllocateClauses(Sema &S, DSAStackTy *Stack, 3875 ArrayRef<OMPClause *> Clauses) { 3876 assert(!S.CurContext->isDependentContext() && 3877 "Expected non-dependent context."); 3878 auto AllocateRange = 3879 llvm::make_filter_range(Clauses, OMPAllocateClause::classof); 3880 llvm::DenseMap<CanonicalDeclPtr<Decl>, CanonicalDeclPtr<VarDecl>> 3881 DeclToCopy; 3882 auto PrivateRange = llvm::make_filter_range(Clauses, [](const OMPClause *C) { 3883 return isOpenMPPrivate(C->getClauseKind()); 3884 }); 3885 for (OMPClause *Cl : PrivateRange) { 3886 MutableArrayRef<Expr *>::iterator I, It, Et; 3887 if (Cl->getClauseKind() == OMPC_private) { 3888 auto *PC = cast<OMPPrivateClause>(Cl); 3889 I = PC->private_copies().begin(); 3890 It = PC->varlist_begin(); 3891 Et = PC->varlist_end(); 3892 } else if (Cl->getClauseKind() == OMPC_firstprivate) { 3893 auto *PC = cast<OMPFirstprivateClause>(Cl); 3894 I = PC->private_copies().begin(); 3895 It = PC->varlist_begin(); 3896 Et = PC->varlist_end(); 3897 } else if (Cl->getClauseKind() == OMPC_lastprivate) { 3898 auto *PC = cast<OMPLastprivateClause>(Cl); 3899 I = PC->private_copies().begin(); 3900 It = PC->varlist_begin(); 3901 Et = PC->varlist_end(); 3902 } else if (Cl->getClauseKind() == OMPC_linear) { 3903 auto *PC = cast<OMPLinearClause>(Cl); 3904 I = PC->privates().begin(); 3905 It = PC->varlist_begin(); 3906 Et = PC->varlist_end(); 3907 } else if (Cl->getClauseKind() == OMPC_reduction) { 3908 auto *PC = cast<OMPReductionClause>(Cl); 3909 I = PC->privates().begin(); 3910 It = PC->varlist_begin(); 3911 Et = PC->varlist_end(); 3912 } else if (Cl->getClauseKind() == OMPC_task_reduction) { 3913 auto *PC = cast<OMPTaskReductionClause>(Cl); 3914 I = PC->privates().begin(); 3915 It = PC->varlist_begin(); 3916 Et = PC->varlist_end(); 3917 } else if (Cl->getClauseKind() == OMPC_in_reduction) { 3918 auto *PC = cast<OMPInReductionClause>(Cl); 3919 I = PC->privates().begin(); 3920 It = PC->varlist_begin(); 3921 Et = PC->varlist_end(); 3922 } else { 3923 llvm_unreachable("Expected private clause."); 3924 } 3925 for (Expr *E : llvm::make_range(It, Et)) { 3926 if (!*I) { 3927 ++I; 3928 continue; 3929 } 3930 SourceLocation ELoc; 3931 SourceRange ERange; 3932 Expr *SimpleRefExpr = E; 3933 auto Res = getPrivateItem(S, SimpleRefExpr, ELoc, ERange, 3934 /*AllowArraySection=*/true); 3935 DeclToCopy.try_emplace(Res.first, 3936 cast<VarDecl>(cast<DeclRefExpr>(*I)->getDecl())); 3937 ++I; 3938 } 3939 } 3940 for (OMPClause *C : AllocateRange) { 3941 auto *AC = cast<OMPAllocateClause>(C); 3942 OMPAllocateDeclAttr::AllocatorTypeTy AllocatorKind = 3943 getAllocatorKind(S, Stack, AC->getAllocator()); 3944 // OpenMP, 2.11.4 allocate Clause, Restrictions. 3945 // For task, taskloop or target directives, allocation requests to memory 3946 // allocators with the trait access set to thread result in unspecified 3947 // behavior. 3948 if (AllocatorKind == OMPAllocateDeclAttr::OMPThreadMemAlloc && 3949 (isOpenMPTaskingDirective(Stack->getCurrentDirective()) || 3950 isOpenMPTargetExecutionDirective(Stack->getCurrentDirective()))) { 3951 S.Diag(AC->getAllocator()->getExprLoc(), 3952 diag::warn_omp_allocate_thread_on_task_target_directive) 3953 << getOpenMPDirectiveName(Stack->getCurrentDirective()); 3954 } 3955 for (Expr *E : AC->varlists()) { 3956 SourceLocation ELoc; 3957 SourceRange ERange; 3958 Expr *SimpleRefExpr = E; 3959 auto Res = getPrivateItem(S, SimpleRefExpr, ELoc, ERange); 3960 ValueDecl *VD = Res.first; 3961 DSAStackTy::DSAVarData Data = Stack->getTopDSA(VD, /*FromParent=*/false); 3962 if (!isOpenMPPrivate(Data.CKind)) { 3963 S.Diag(E->getExprLoc(), 3964 diag::err_omp_expected_private_copy_for_allocate); 3965 continue; 3966 } 3967 VarDecl *PrivateVD = DeclToCopy[VD]; 3968 if (checkPreviousOMPAllocateAttribute(S, Stack, E, PrivateVD, 3969 AllocatorKind, AC->getAllocator())) 3970 continue; 3971 applyOMPAllocateAttribute(S, PrivateVD, AllocatorKind, AC->getAllocator(), 3972 E->getSourceRange()); 3973 } 3974 } 3975 } 3976 3977 StmtResult Sema::ActOnOpenMPExecutableDirective( 3978 OpenMPDirectiveKind Kind, const DeclarationNameInfo &DirName, 3979 OpenMPDirectiveKind CancelRegion, ArrayRef<OMPClause *> Clauses, 3980 Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc) { 3981 StmtResult Res = StmtError(); 3982 // First check CancelRegion which is then used in checkNestingOfRegions. 3983 if (checkCancelRegion(*this, Kind, CancelRegion, StartLoc) || 3984 checkNestingOfRegions(*this, DSAStack, Kind, DirName, CancelRegion, 3985 StartLoc)) 3986 return StmtError(); 3987 3988 llvm::SmallVector<OMPClause *, 8> ClausesWithImplicit; 3989 VarsWithInheritedDSAType VarsWithInheritedDSA; 3990 bool ErrorFound = false; 3991 ClausesWithImplicit.append(Clauses.begin(), Clauses.end()); 3992 if (AStmt && !CurContext->isDependentContext()) { 3993 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected"); 3994 3995 // Check default data sharing attributes for referenced variables. 3996 DSAAttrChecker DSAChecker(DSAStack, *this, cast<CapturedStmt>(AStmt)); 3997 int ThisCaptureLevel = getOpenMPCaptureLevels(Kind); 3998 Stmt *S = AStmt; 3999 while (--ThisCaptureLevel >= 0) 4000 S = cast<CapturedStmt>(S)->getCapturedStmt(); 4001 DSAChecker.Visit(S); 4002 if (!isOpenMPTargetDataManagementDirective(Kind) && 4003 !isOpenMPTaskingDirective(Kind)) { 4004 // Visit subcaptures to generate implicit clauses for captured vars. 4005 auto *CS = cast<CapturedStmt>(AStmt); 4006 SmallVector<OpenMPDirectiveKind, 4> CaptureRegions; 4007 getOpenMPCaptureRegions(CaptureRegions, Kind); 4008 // Ignore outer tasking regions for target directives. 4009 if (CaptureRegions.size() > 1 && CaptureRegions.front() == OMPD_task) 4010 CS = cast<CapturedStmt>(CS->getCapturedStmt()); 4011 DSAChecker.visitSubCaptures(CS); 4012 } 4013 if (DSAChecker.isErrorFound()) 4014 return StmtError(); 4015 // Generate list of implicitly defined firstprivate variables. 4016 VarsWithInheritedDSA = DSAChecker.getVarsWithInheritedDSA(); 4017 4018 SmallVector<Expr *, 4> ImplicitFirstprivates( 4019 DSAChecker.getImplicitFirstprivate().begin(), 4020 DSAChecker.getImplicitFirstprivate().end()); 4021 SmallVector<Expr *, 4> ImplicitMaps(DSAChecker.getImplicitMap().begin(), 4022 DSAChecker.getImplicitMap().end()); 4023 // Mark taskgroup task_reduction descriptors as implicitly firstprivate. 4024 for (OMPClause *C : Clauses) { 4025 if (auto *IRC = dyn_cast<OMPInReductionClause>(C)) { 4026 for (Expr *E : IRC->taskgroup_descriptors()) 4027 if (E) 4028 ImplicitFirstprivates.emplace_back(E); 4029 } 4030 } 4031 if (!ImplicitFirstprivates.empty()) { 4032 if (OMPClause *Implicit = ActOnOpenMPFirstprivateClause( 4033 ImplicitFirstprivates, SourceLocation(), SourceLocation(), 4034 SourceLocation())) { 4035 ClausesWithImplicit.push_back(Implicit); 4036 ErrorFound = cast<OMPFirstprivateClause>(Implicit)->varlist_size() != 4037 ImplicitFirstprivates.size(); 4038 } else { 4039 ErrorFound = true; 4040 } 4041 } 4042 if (!ImplicitMaps.empty()) { 4043 CXXScopeSpec MapperIdScopeSpec; 4044 DeclarationNameInfo MapperId; 4045 if (OMPClause *Implicit = ActOnOpenMPMapClause( 4046 llvm::None, llvm::None, MapperIdScopeSpec, MapperId, 4047 OMPC_MAP_tofrom, /*IsMapTypeImplicit=*/true, SourceLocation(), 4048 SourceLocation(), ImplicitMaps, OMPVarListLocTy())) { 4049 ClausesWithImplicit.emplace_back(Implicit); 4050 ErrorFound |= 4051 cast<OMPMapClause>(Implicit)->varlist_size() != ImplicitMaps.size(); 4052 } else { 4053 ErrorFound = true; 4054 } 4055 } 4056 } 4057 4058 llvm::SmallVector<OpenMPDirectiveKind, 4> AllowedNameModifiers; 4059 switch (Kind) { 4060 case OMPD_parallel: 4061 Res = ActOnOpenMPParallelDirective(ClausesWithImplicit, AStmt, StartLoc, 4062 EndLoc); 4063 AllowedNameModifiers.push_back(OMPD_parallel); 4064 break; 4065 case OMPD_simd: 4066 Res = ActOnOpenMPSimdDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc, 4067 VarsWithInheritedDSA); 4068 break; 4069 case OMPD_for: 4070 Res = ActOnOpenMPForDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc, 4071 VarsWithInheritedDSA); 4072 break; 4073 case OMPD_for_simd: 4074 Res = ActOnOpenMPForSimdDirective(ClausesWithImplicit, AStmt, StartLoc, 4075 EndLoc, VarsWithInheritedDSA); 4076 break; 4077 case OMPD_sections: 4078 Res = ActOnOpenMPSectionsDirective(ClausesWithImplicit, AStmt, StartLoc, 4079 EndLoc); 4080 break; 4081 case OMPD_section: 4082 assert(ClausesWithImplicit.empty() && 4083 "No clauses are allowed for 'omp section' directive"); 4084 Res = ActOnOpenMPSectionDirective(AStmt, StartLoc, EndLoc); 4085 break; 4086 case OMPD_single: 4087 Res = ActOnOpenMPSingleDirective(ClausesWithImplicit, AStmt, StartLoc, 4088 EndLoc); 4089 break; 4090 case OMPD_master: 4091 assert(ClausesWithImplicit.empty() && 4092 "No clauses are allowed for 'omp master' directive"); 4093 Res = ActOnOpenMPMasterDirective(AStmt, StartLoc, EndLoc); 4094 break; 4095 case OMPD_critical: 4096 Res = ActOnOpenMPCriticalDirective(DirName, ClausesWithImplicit, AStmt, 4097 StartLoc, EndLoc); 4098 break; 4099 case OMPD_parallel_for: 4100 Res = ActOnOpenMPParallelForDirective(ClausesWithImplicit, AStmt, StartLoc, 4101 EndLoc, VarsWithInheritedDSA); 4102 AllowedNameModifiers.push_back(OMPD_parallel); 4103 break; 4104 case OMPD_parallel_for_simd: 4105 Res = ActOnOpenMPParallelForSimdDirective( 4106 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA); 4107 AllowedNameModifiers.push_back(OMPD_parallel); 4108 break; 4109 case OMPD_parallel_sections: 4110 Res = ActOnOpenMPParallelSectionsDirective(ClausesWithImplicit, AStmt, 4111 StartLoc, EndLoc); 4112 AllowedNameModifiers.push_back(OMPD_parallel); 4113 break; 4114 case OMPD_task: 4115 Res = 4116 ActOnOpenMPTaskDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc); 4117 AllowedNameModifiers.push_back(OMPD_task); 4118 break; 4119 case OMPD_taskyield: 4120 assert(ClausesWithImplicit.empty() && 4121 "No clauses are allowed for 'omp taskyield' directive"); 4122 assert(AStmt == nullptr && 4123 "No associated statement allowed for 'omp taskyield' directive"); 4124 Res = ActOnOpenMPTaskyieldDirective(StartLoc, EndLoc); 4125 break; 4126 case OMPD_barrier: 4127 assert(ClausesWithImplicit.empty() && 4128 "No clauses are allowed for 'omp barrier' directive"); 4129 assert(AStmt == nullptr && 4130 "No associated statement allowed for 'omp barrier' directive"); 4131 Res = ActOnOpenMPBarrierDirective(StartLoc, EndLoc); 4132 break; 4133 case OMPD_taskwait: 4134 assert(ClausesWithImplicit.empty() && 4135 "No clauses are allowed for 'omp taskwait' directive"); 4136 assert(AStmt == nullptr && 4137 "No associated statement allowed for 'omp taskwait' directive"); 4138 Res = ActOnOpenMPTaskwaitDirective(StartLoc, EndLoc); 4139 break; 4140 case OMPD_taskgroup: 4141 Res = ActOnOpenMPTaskgroupDirective(ClausesWithImplicit, AStmt, StartLoc, 4142 EndLoc); 4143 break; 4144 case OMPD_flush: 4145 assert(AStmt == nullptr && 4146 "No associated statement allowed for 'omp flush' directive"); 4147 Res = ActOnOpenMPFlushDirective(ClausesWithImplicit, StartLoc, EndLoc); 4148 break; 4149 case OMPD_ordered: 4150 Res = ActOnOpenMPOrderedDirective(ClausesWithImplicit, AStmt, StartLoc, 4151 EndLoc); 4152 break; 4153 case OMPD_atomic: 4154 Res = ActOnOpenMPAtomicDirective(ClausesWithImplicit, AStmt, StartLoc, 4155 EndLoc); 4156 break; 4157 case OMPD_teams: 4158 Res = 4159 ActOnOpenMPTeamsDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc); 4160 break; 4161 case OMPD_target: 4162 Res = ActOnOpenMPTargetDirective(ClausesWithImplicit, AStmt, StartLoc, 4163 EndLoc); 4164 AllowedNameModifiers.push_back(OMPD_target); 4165 break; 4166 case OMPD_target_parallel: 4167 Res = ActOnOpenMPTargetParallelDirective(ClausesWithImplicit, AStmt, 4168 StartLoc, EndLoc); 4169 AllowedNameModifiers.push_back(OMPD_target); 4170 AllowedNameModifiers.push_back(OMPD_parallel); 4171 break; 4172 case OMPD_target_parallel_for: 4173 Res = ActOnOpenMPTargetParallelForDirective( 4174 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA); 4175 AllowedNameModifiers.push_back(OMPD_target); 4176 AllowedNameModifiers.push_back(OMPD_parallel); 4177 break; 4178 case OMPD_cancellation_point: 4179 assert(ClausesWithImplicit.empty() && 4180 "No clauses are allowed for 'omp cancellation point' directive"); 4181 assert(AStmt == nullptr && "No associated statement allowed for 'omp " 4182 "cancellation point' directive"); 4183 Res = ActOnOpenMPCancellationPointDirective(StartLoc, EndLoc, CancelRegion); 4184 break; 4185 case OMPD_cancel: 4186 assert(AStmt == nullptr && 4187 "No associated statement allowed for 'omp cancel' directive"); 4188 Res = ActOnOpenMPCancelDirective(ClausesWithImplicit, StartLoc, EndLoc, 4189 CancelRegion); 4190 AllowedNameModifiers.push_back(OMPD_cancel); 4191 break; 4192 case OMPD_target_data: 4193 Res = ActOnOpenMPTargetDataDirective(ClausesWithImplicit, AStmt, StartLoc, 4194 EndLoc); 4195 AllowedNameModifiers.push_back(OMPD_target_data); 4196 break; 4197 case OMPD_target_enter_data: 4198 Res = ActOnOpenMPTargetEnterDataDirective(ClausesWithImplicit, StartLoc, 4199 EndLoc, AStmt); 4200 AllowedNameModifiers.push_back(OMPD_target_enter_data); 4201 break; 4202 case OMPD_target_exit_data: 4203 Res = ActOnOpenMPTargetExitDataDirective(ClausesWithImplicit, StartLoc, 4204 EndLoc, AStmt); 4205 AllowedNameModifiers.push_back(OMPD_target_exit_data); 4206 break; 4207 case OMPD_taskloop: 4208 Res = ActOnOpenMPTaskLoopDirective(ClausesWithImplicit, AStmt, StartLoc, 4209 EndLoc, VarsWithInheritedDSA); 4210 AllowedNameModifiers.push_back(OMPD_taskloop); 4211 break; 4212 case OMPD_taskloop_simd: 4213 Res = ActOnOpenMPTaskLoopSimdDirective(ClausesWithImplicit, AStmt, StartLoc, 4214 EndLoc, VarsWithInheritedDSA); 4215 AllowedNameModifiers.push_back(OMPD_taskloop); 4216 break; 4217 case OMPD_distribute: 4218 Res = ActOnOpenMPDistributeDirective(ClausesWithImplicit, AStmt, StartLoc, 4219 EndLoc, VarsWithInheritedDSA); 4220 break; 4221 case OMPD_target_update: 4222 Res = ActOnOpenMPTargetUpdateDirective(ClausesWithImplicit, StartLoc, 4223 EndLoc, AStmt); 4224 AllowedNameModifiers.push_back(OMPD_target_update); 4225 break; 4226 case OMPD_distribute_parallel_for: 4227 Res = ActOnOpenMPDistributeParallelForDirective( 4228 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA); 4229 AllowedNameModifiers.push_back(OMPD_parallel); 4230 break; 4231 case OMPD_distribute_parallel_for_simd: 4232 Res = ActOnOpenMPDistributeParallelForSimdDirective( 4233 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA); 4234 AllowedNameModifiers.push_back(OMPD_parallel); 4235 break; 4236 case OMPD_distribute_simd: 4237 Res = ActOnOpenMPDistributeSimdDirective( 4238 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA); 4239 break; 4240 case OMPD_target_parallel_for_simd: 4241 Res = ActOnOpenMPTargetParallelForSimdDirective( 4242 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA); 4243 AllowedNameModifiers.push_back(OMPD_target); 4244 AllowedNameModifiers.push_back(OMPD_parallel); 4245 break; 4246 case OMPD_target_simd: 4247 Res = ActOnOpenMPTargetSimdDirective(ClausesWithImplicit, AStmt, StartLoc, 4248 EndLoc, VarsWithInheritedDSA); 4249 AllowedNameModifiers.push_back(OMPD_target); 4250 break; 4251 case OMPD_teams_distribute: 4252 Res = ActOnOpenMPTeamsDistributeDirective( 4253 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA); 4254 break; 4255 case OMPD_teams_distribute_simd: 4256 Res = ActOnOpenMPTeamsDistributeSimdDirective( 4257 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA); 4258 break; 4259 case OMPD_teams_distribute_parallel_for_simd: 4260 Res = ActOnOpenMPTeamsDistributeParallelForSimdDirective( 4261 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA); 4262 AllowedNameModifiers.push_back(OMPD_parallel); 4263 break; 4264 case OMPD_teams_distribute_parallel_for: 4265 Res = ActOnOpenMPTeamsDistributeParallelForDirective( 4266 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA); 4267 AllowedNameModifiers.push_back(OMPD_parallel); 4268 break; 4269 case OMPD_target_teams: 4270 Res = ActOnOpenMPTargetTeamsDirective(ClausesWithImplicit, AStmt, StartLoc, 4271 EndLoc); 4272 AllowedNameModifiers.push_back(OMPD_target); 4273 break; 4274 case OMPD_target_teams_distribute: 4275 Res = ActOnOpenMPTargetTeamsDistributeDirective( 4276 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA); 4277 AllowedNameModifiers.push_back(OMPD_target); 4278 break; 4279 case OMPD_target_teams_distribute_parallel_for: 4280 Res = ActOnOpenMPTargetTeamsDistributeParallelForDirective( 4281 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA); 4282 AllowedNameModifiers.push_back(OMPD_target); 4283 AllowedNameModifiers.push_back(OMPD_parallel); 4284 break; 4285 case OMPD_target_teams_distribute_parallel_for_simd: 4286 Res = ActOnOpenMPTargetTeamsDistributeParallelForSimdDirective( 4287 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA); 4288 AllowedNameModifiers.push_back(OMPD_target); 4289 AllowedNameModifiers.push_back(OMPD_parallel); 4290 break; 4291 case OMPD_target_teams_distribute_simd: 4292 Res = ActOnOpenMPTargetTeamsDistributeSimdDirective( 4293 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA); 4294 AllowedNameModifiers.push_back(OMPD_target); 4295 break; 4296 case OMPD_declare_target: 4297 case OMPD_end_declare_target: 4298 case OMPD_threadprivate: 4299 case OMPD_allocate: 4300 case OMPD_declare_reduction: 4301 case OMPD_declare_mapper: 4302 case OMPD_declare_simd: 4303 case OMPD_requires: 4304 llvm_unreachable("OpenMP Directive is not allowed"); 4305 case OMPD_unknown: 4306 llvm_unreachable("Unknown OpenMP directive"); 4307 } 4308 4309 ErrorFound = Res.isInvalid() || ErrorFound; 4310 4311 // Check variables in the clauses if default(none) was specified. 4312 if (DSAStack->getDefaultDSA() == DSA_none) { 4313 DSAAttrChecker DSAChecker(DSAStack, *this, nullptr); 4314 for (OMPClause *C : Clauses) { 4315 switch (C->getClauseKind()) { 4316 case OMPC_num_threads: 4317 case OMPC_dist_schedule: 4318 // Do not analyse if no parent teams directive. 4319 if (isOpenMPTeamsDirective(DSAStack->getCurrentDirective())) 4320 break; 4321 continue; 4322 case OMPC_if: 4323 if (isOpenMPTeamsDirective(DSAStack->getCurrentDirective()) && 4324 cast<OMPIfClause>(C)->getNameModifier() != OMPD_target) 4325 break; 4326 continue; 4327 case OMPC_schedule: 4328 break; 4329 case OMPC_ordered: 4330 case OMPC_device: 4331 case OMPC_num_teams: 4332 case OMPC_thread_limit: 4333 case OMPC_priority: 4334 case OMPC_grainsize: 4335 case OMPC_num_tasks: 4336 case OMPC_hint: 4337 case OMPC_collapse: 4338 case OMPC_safelen: 4339 case OMPC_simdlen: 4340 case OMPC_final: 4341 case OMPC_default: 4342 case OMPC_proc_bind: 4343 case OMPC_private: 4344 case OMPC_firstprivate: 4345 case OMPC_lastprivate: 4346 case OMPC_shared: 4347 case OMPC_reduction: 4348 case OMPC_task_reduction: 4349 case OMPC_in_reduction: 4350 case OMPC_linear: 4351 case OMPC_aligned: 4352 case OMPC_copyin: 4353 case OMPC_copyprivate: 4354 case OMPC_nowait: 4355 case OMPC_untied: 4356 case OMPC_mergeable: 4357 case OMPC_allocate: 4358 case OMPC_read: 4359 case OMPC_write: 4360 case OMPC_update: 4361 case OMPC_capture: 4362 case OMPC_seq_cst: 4363 case OMPC_depend: 4364 case OMPC_threads: 4365 case OMPC_simd: 4366 case OMPC_map: 4367 case OMPC_nogroup: 4368 case OMPC_defaultmap: 4369 case OMPC_to: 4370 case OMPC_from: 4371 case OMPC_use_device_ptr: 4372 case OMPC_is_device_ptr: 4373 continue; 4374 case OMPC_allocator: 4375 case OMPC_flush: 4376 case OMPC_threadprivate: 4377 case OMPC_uniform: 4378 case OMPC_unknown: 4379 case OMPC_unified_address: 4380 case OMPC_unified_shared_memory: 4381 case OMPC_reverse_offload: 4382 case OMPC_dynamic_allocators: 4383 case OMPC_atomic_default_mem_order: 4384 llvm_unreachable("Unexpected clause"); 4385 } 4386 for (Stmt *CC : C->children()) { 4387 if (CC) 4388 DSAChecker.Visit(CC); 4389 } 4390 } 4391 for (auto &P : DSAChecker.getVarsWithInheritedDSA()) 4392 VarsWithInheritedDSA[P.getFirst()] = P.getSecond(); 4393 } 4394 for (const auto &P : VarsWithInheritedDSA) { 4395 if (P.getFirst()->isImplicit() || isa<OMPCapturedExprDecl>(P.getFirst())) 4396 continue; 4397 ErrorFound = true; 4398 Diag(P.second->getExprLoc(), diag::err_omp_no_dsa_for_variable) 4399 << P.first << P.second->getSourceRange(); 4400 Diag(DSAStack->getDefaultDSALocation(), diag::note_omp_default_dsa_none); 4401 } 4402 4403 if (!AllowedNameModifiers.empty()) 4404 ErrorFound = checkIfClauses(*this, Kind, Clauses, AllowedNameModifiers) || 4405 ErrorFound; 4406 4407 if (ErrorFound) 4408 return StmtError(); 4409 4410 if (!(Res.getAs<OMPExecutableDirective>()->isStandaloneDirective())) { 4411 Res.getAs<OMPExecutableDirective>() 4412 ->getStructuredBlock() 4413 ->setIsOMPStructuredBlock(true); 4414 } 4415 4416 if (!CurContext->isDependentContext() && 4417 isOpenMPTargetExecutionDirective(Kind) && 4418 !(DSAStack->hasRequiresDeclWithClause<OMPUnifiedSharedMemoryClause>() || 4419 DSAStack->hasRequiresDeclWithClause<OMPUnifiedAddressClause>() || 4420 DSAStack->hasRequiresDeclWithClause<OMPReverseOffloadClause>() || 4421 DSAStack->hasRequiresDeclWithClause<OMPDynamicAllocatorsClause>())) { 4422 // Register target to DSA Stack. 4423 DSAStack->addTargetDirLocation(StartLoc); 4424 } 4425 4426 return Res; 4427 } 4428 4429 Sema::DeclGroupPtrTy Sema::ActOnOpenMPDeclareSimdDirective( 4430 DeclGroupPtrTy DG, OMPDeclareSimdDeclAttr::BranchStateTy BS, Expr *Simdlen, 4431 ArrayRef<Expr *> Uniforms, ArrayRef<Expr *> Aligneds, 4432 ArrayRef<Expr *> Alignments, ArrayRef<Expr *> Linears, 4433 ArrayRef<unsigned> LinModifiers, ArrayRef<Expr *> Steps, SourceRange SR) { 4434 assert(Aligneds.size() == Alignments.size()); 4435 assert(Linears.size() == LinModifiers.size()); 4436 assert(Linears.size() == Steps.size()); 4437 if (!DG || DG.get().isNull()) 4438 return DeclGroupPtrTy(); 4439 4440 if (!DG.get().isSingleDecl()) { 4441 Diag(SR.getBegin(), diag::err_omp_single_decl_in_declare_simd); 4442 return DG; 4443 } 4444 Decl *ADecl = DG.get().getSingleDecl(); 4445 if (auto *FTD = dyn_cast<FunctionTemplateDecl>(ADecl)) 4446 ADecl = FTD->getTemplatedDecl(); 4447 4448 auto *FD = dyn_cast<FunctionDecl>(ADecl); 4449 if (!FD) { 4450 Diag(ADecl->getLocation(), diag::err_omp_function_expected); 4451 return DeclGroupPtrTy(); 4452 } 4453 4454 // OpenMP [2.8.2, declare simd construct, Description] 4455 // The parameter of the simdlen clause must be a constant positive integer 4456 // expression. 4457 ExprResult SL; 4458 if (Simdlen) 4459 SL = VerifyPositiveIntegerConstantInClause(Simdlen, OMPC_simdlen); 4460 // OpenMP [2.8.2, declare simd construct, Description] 4461 // The special this pointer can be used as if was one of the arguments to the 4462 // function in any of the linear, aligned, or uniform clauses. 4463 // The uniform clause declares one or more arguments to have an invariant 4464 // value for all concurrent invocations of the function in the execution of a 4465 // single SIMD loop. 4466 llvm::DenseMap<const Decl *, const Expr *> UniformedArgs; 4467 const Expr *UniformedLinearThis = nullptr; 4468 for (const Expr *E : Uniforms) { 4469 E = E->IgnoreParenImpCasts(); 4470 if (const auto *DRE = dyn_cast<DeclRefExpr>(E)) 4471 if (const auto *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl())) 4472 if (FD->getNumParams() > PVD->getFunctionScopeIndex() && 4473 FD->getParamDecl(PVD->getFunctionScopeIndex()) 4474 ->getCanonicalDecl() == PVD->getCanonicalDecl()) { 4475 UniformedArgs.try_emplace(PVD->getCanonicalDecl(), E); 4476 continue; 4477 } 4478 if (isa<CXXThisExpr>(E)) { 4479 UniformedLinearThis = E; 4480 continue; 4481 } 4482 Diag(E->getExprLoc(), diag::err_omp_param_or_this_in_clause) 4483 << FD->getDeclName() << (isa<CXXMethodDecl>(ADecl) ? 1 : 0); 4484 } 4485 // OpenMP [2.8.2, declare simd construct, Description] 4486 // The aligned clause declares that the object to which each list item points 4487 // is aligned to the number of bytes expressed in the optional parameter of 4488 // the aligned clause. 4489 // The special this pointer can be used as if was one of the arguments to the 4490 // function in any of the linear, aligned, or uniform clauses. 4491 // The type of list items appearing in the aligned clause must be array, 4492 // pointer, reference to array, or reference to pointer. 4493 llvm::DenseMap<const Decl *, const Expr *> AlignedArgs; 4494 const Expr *AlignedThis = nullptr; 4495 for (const Expr *E : Aligneds) { 4496 E = E->IgnoreParenImpCasts(); 4497 if (const auto *DRE = dyn_cast<DeclRefExpr>(E)) 4498 if (const auto *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl())) { 4499 const VarDecl *CanonPVD = PVD->getCanonicalDecl(); 4500 if (FD->getNumParams() > PVD->getFunctionScopeIndex() && 4501 FD->getParamDecl(PVD->getFunctionScopeIndex()) 4502 ->getCanonicalDecl() == CanonPVD) { 4503 // OpenMP [2.8.1, simd construct, Restrictions] 4504 // A list-item cannot appear in more than one aligned clause. 4505 if (AlignedArgs.count(CanonPVD) > 0) { 4506 Diag(E->getExprLoc(), diag::err_omp_aligned_twice) 4507 << 1 << E->getSourceRange(); 4508 Diag(AlignedArgs[CanonPVD]->getExprLoc(), 4509 diag::note_omp_explicit_dsa) 4510 << getOpenMPClauseName(OMPC_aligned); 4511 continue; 4512 } 4513 AlignedArgs[CanonPVD] = E; 4514 QualType QTy = PVD->getType() 4515 .getNonReferenceType() 4516 .getUnqualifiedType() 4517 .getCanonicalType(); 4518 const Type *Ty = QTy.getTypePtrOrNull(); 4519 if (!Ty || (!Ty->isArrayType() && !Ty->isPointerType())) { 4520 Diag(E->getExprLoc(), diag::err_omp_aligned_expected_array_or_ptr) 4521 << QTy << getLangOpts().CPlusPlus << E->getSourceRange(); 4522 Diag(PVD->getLocation(), diag::note_previous_decl) << PVD; 4523 } 4524 continue; 4525 } 4526 } 4527 if (isa<CXXThisExpr>(E)) { 4528 if (AlignedThis) { 4529 Diag(E->getExprLoc(), diag::err_omp_aligned_twice) 4530 << 2 << E->getSourceRange(); 4531 Diag(AlignedThis->getExprLoc(), diag::note_omp_explicit_dsa) 4532 << getOpenMPClauseName(OMPC_aligned); 4533 } 4534 AlignedThis = E; 4535 continue; 4536 } 4537 Diag(E->getExprLoc(), diag::err_omp_param_or_this_in_clause) 4538 << FD->getDeclName() << (isa<CXXMethodDecl>(ADecl) ? 1 : 0); 4539 } 4540 // The optional parameter of the aligned clause, alignment, must be a constant 4541 // positive integer expression. If no optional parameter is specified, 4542 // implementation-defined default alignments for SIMD instructions on the 4543 // target platforms are assumed. 4544 SmallVector<const Expr *, 4> NewAligns; 4545 for (Expr *E : Alignments) { 4546 ExprResult Align; 4547 if (E) 4548 Align = VerifyPositiveIntegerConstantInClause(E, OMPC_aligned); 4549 NewAligns.push_back(Align.get()); 4550 } 4551 // OpenMP [2.8.2, declare simd construct, Description] 4552 // The linear clause declares one or more list items to be private to a SIMD 4553 // lane and to have a linear relationship with respect to the iteration space 4554 // of a loop. 4555 // The special this pointer can be used as if was one of the arguments to the 4556 // function in any of the linear, aligned, or uniform clauses. 4557 // When a linear-step expression is specified in a linear clause it must be 4558 // either a constant integer expression or an integer-typed parameter that is 4559 // specified in a uniform clause on the directive. 4560 llvm::DenseMap<const Decl *, const Expr *> LinearArgs; 4561 const bool IsUniformedThis = UniformedLinearThis != nullptr; 4562 auto MI = LinModifiers.begin(); 4563 for (const Expr *E : Linears) { 4564 auto LinKind = static_cast<OpenMPLinearClauseKind>(*MI); 4565 ++MI; 4566 E = E->IgnoreParenImpCasts(); 4567 if (const auto *DRE = dyn_cast<DeclRefExpr>(E)) 4568 if (const auto *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl())) { 4569 const VarDecl *CanonPVD = PVD->getCanonicalDecl(); 4570 if (FD->getNumParams() > PVD->getFunctionScopeIndex() && 4571 FD->getParamDecl(PVD->getFunctionScopeIndex()) 4572 ->getCanonicalDecl() == CanonPVD) { 4573 // OpenMP [2.15.3.7, linear Clause, Restrictions] 4574 // A list-item cannot appear in more than one linear clause. 4575 if (LinearArgs.count(CanonPVD) > 0) { 4576 Diag(E->getExprLoc(), diag::err_omp_wrong_dsa) 4577 << getOpenMPClauseName(OMPC_linear) 4578 << getOpenMPClauseName(OMPC_linear) << E->getSourceRange(); 4579 Diag(LinearArgs[CanonPVD]->getExprLoc(), 4580 diag::note_omp_explicit_dsa) 4581 << getOpenMPClauseName(OMPC_linear); 4582 continue; 4583 } 4584 // Each argument can appear in at most one uniform or linear clause. 4585 if (UniformedArgs.count(CanonPVD) > 0) { 4586 Diag(E->getExprLoc(), diag::err_omp_wrong_dsa) 4587 << getOpenMPClauseName(OMPC_linear) 4588 << getOpenMPClauseName(OMPC_uniform) << E->getSourceRange(); 4589 Diag(UniformedArgs[CanonPVD]->getExprLoc(), 4590 diag::note_omp_explicit_dsa) 4591 << getOpenMPClauseName(OMPC_uniform); 4592 continue; 4593 } 4594 LinearArgs[CanonPVD] = E; 4595 if (E->isValueDependent() || E->isTypeDependent() || 4596 E->isInstantiationDependent() || 4597 E->containsUnexpandedParameterPack()) 4598 continue; 4599 (void)CheckOpenMPLinearDecl(CanonPVD, E->getExprLoc(), LinKind, 4600 PVD->getOriginalType()); 4601 continue; 4602 } 4603 } 4604 if (isa<CXXThisExpr>(E)) { 4605 if (UniformedLinearThis) { 4606 Diag(E->getExprLoc(), diag::err_omp_wrong_dsa) 4607 << getOpenMPClauseName(OMPC_linear) 4608 << getOpenMPClauseName(IsUniformedThis ? OMPC_uniform : OMPC_linear) 4609 << E->getSourceRange(); 4610 Diag(UniformedLinearThis->getExprLoc(), diag::note_omp_explicit_dsa) 4611 << getOpenMPClauseName(IsUniformedThis ? OMPC_uniform 4612 : OMPC_linear); 4613 continue; 4614 } 4615 UniformedLinearThis = E; 4616 if (E->isValueDependent() || E->isTypeDependent() || 4617 E->isInstantiationDependent() || E->containsUnexpandedParameterPack()) 4618 continue; 4619 (void)CheckOpenMPLinearDecl(/*D=*/nullptr, E->getExprLoc(), LinKind, 4620 E->getType()); 4621 continue; 4622 } 4623 Diag(E->getExprLoc(), diag::err_omp_param_or_this_in_clause) 4624 << FD->getDeclName() << (isa<CXXMethodDecl>(ADecl) ? 1 : 0); 4625 } 4626 Expr *Step = nullptr; 4627 Expr *NewStep = nullptr; 4628 SmallVector<Expr *, 4> NewSteps; 4629 for (Expr *E : Steps) { 4630 // Skip the same step expression, it was checked already. 4631 if (Step == E || !E) { 4632 NewSteps.push_back(E ? NewStep : nullptr); 4633 continue; 4634 } 4635 Step = E; 4636 if (const auto *DRE = dyn_cast<DeclRefExpr>(Step)) 4637 if (const auto *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl())) { 4638 const VarDecl *CanonPVD = PVD->getCanonicalDecl(); 4639 if (UniformedArgs.count(CanonPVD) == 0) { 4640 Diag(Step->getExprLoc(), diag::err_omp_expected_uniform_param) 4641 << Step->getSourceRange(); 4642 } else if (E->isValueDependent() || E->isTypeDependent() || 4643 E->isInstantiationDependent() || 4644 E->containsUnexpandedParameterPack() || 4645 CanonPVD->getType()->hasIntegerRepresentation()) { 4646 NewSteps.push_back(Step); 4647 } else { 4648 Diag(Step->getExprLoc(), diag::err_omp_expected_int_param) 4649 << Step->getSourceRange(); 4650 } 4651 continue; 4652 } 4653 NewStep = Step; 4654 if (Step && !Step->isValueDependent() && !Step->isTypeDependent() && 4655 !Step->isInstantiationDependent() && 4656 !Step->containsUnexpandedParameterPack()) { 4657 NewStep = PerformOpenMPImplicitIntegerConversion(Step->getExprLoc(), Step) 4658 .get(); 4659 if (NewStep) 4660 NewStep = VerifyIntegerConstantExpression(NewStep).get(); 4661 } 4662 NewSteps.push_back(NewStep); 4663 } 4664 auto *NewAttr = OMPDeclareSimdDeclAttr::CreateImplicit( 4665 Context, BS, SL.get(), const_cast<Expr **>(Uniforms.data()), 4666 Uniforms.size(), const_cast<Expr **>(Aligneds.data()), Aligneds.size(), 4667 const_cast<Expr **>(NewAligns.data()), NewAligns.size(), 4668 const_cast<Expr **>(Linears.data()), Linears.size(), 4669 const_cast<unsigned *>(LinModifiers.data()), LinModifiers.size(), 4670 NewSteps.data(), NewSteps.size(), SR); 4671 ADecl->addAttr(NewAttr); 4672 return ConvertDeclToDeclGroup(ADecl); 4673 } 4674 4675 StmtResult Sema::ActOnOpenMPParallelDirective(ArrayRef<OMPClause *> Clauses, 4676 Stmt *AStmt, 4677 SourceLocation StartLoc, 4678 SourceLocation EndLoc) { 4679 if (!AStmt) 4680 return StmtError(); 4681 4682 auto *CS = cast<CapturedStmt>(AStmt); 4683 // 1.2.2 OpenMP Language Terminology 4684 // Structured block - An executable statement with a single entry at the 4685 // top and a single exit at the bottom. 4686 // The point of exit cannot be a branch out of the structured block. 4687 // longjmp() and throw() must not violate the entry/exit criteria. 4688 CS->getCapturedDecl()->setNothrow(); 4689 4690 setFunctionHasBranchProtectedScope(); 4691 4692 return OMPParallelDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt, 4693 DSAStack->isCancelRegion()); 4694 } 4695 4696 namespace { 4697 /// Helper class for checking canonical form of the OpenMP loops and 4698 /// extracting iteration space of each loop in the loop nest, that will be used 4699 /// for IR generation. 4700 class OpenMPIterationSpaceChecker { 4701 /// Reference to Sema. 4702 Sema &SemaRef; 4703 /// Data-sharing stack. 4704 DSAStackTy &Stack; 4705 /// A location for diagnostics (when there is no some better location). 4706 SourceLocation DefaultLoc; 4707 /// A location for diagnostics (when increment is not compatible). 4708 SourceLocation ConditionLoc; 4709 /// A source location for referring to loop init later. 4710 SourceRange InitSrcRange; 4711 /// A source location for referring to condition later. 4712 SourceRange ConditionSrcRange; 4713 /// A source location for referring to increment later. 4714 SourceRange IncrementSrcRange; 4715 /// Loop variable. 4716 ValueDecl *LCDecl = nullptr; 4717 /// Reference to loop variable. 4718 Expr *LCRef = nullptr; 4719 /// Lower bound (initializer for the var). 4720 Expr *LB = nullptr; 4721 /// Upper bound. 4722 Expr *UB = nullptr; 4723 /// Loop step (increment). 4724 Expr *Step = nullptr; 4725 /// This flag is true when condition is one of: 4726 /// Var < UB 4727 /// Var <= UB 4728 /// UB > Var 4729 /// UB >= Var 4730 /// This will have no value when the condition is != 4731 llvm::Optional<bool> TestIsLessOp; 4732 /// This flag is true when condition is strict ( < or > ). 4733 bool TestIsStrictOp = false; 4734 /// This flag is true when step is subtracted on each iteration. 4735 bool SubtractStep = false; 4736 /// The outer loop counter this loop depends on (if any). 4737 const ValueDecl *DepDecl = nullptr; 4738 /// Contains number of loop (starts from 1) on which loop counter init 4739 /// expression of this loop depends on. 4740 Optional<unsigned> InitDependOnLC; 4741 /// Contains number of loop (starts from 1) on which loop counter condition 4742 /// expression of this loop depends on. 4743 Optional<unsigned> CondDependOnLC; 4744 /// Checks if the provide statement depends on the loop counter. 4745 Optional<unsigned> doesDependOnLoopCounter(const Stmt *S, bool IsInitializer); 4746 4747 public: 4748 OpenMPIterationSpaceChecker(Sema &SemaRef, DSAStackTy &Stack, 4749 SourceLocation DefaultLoc) 4750 : SemaRef(SemaRef), Stack(Stack), DefaultLoc(DefaultLoc), 4751 ConditionLoc(DefaultLoc) {} 4752 /// Check init-expr for canonical loop form and save loop counter 4753 /// variable - #Var and its initialization value - #LB. 4754 bool checkAndSetInit(Stmt *S, bool EmitDiags = true); 4755 /// Check test-expr for canonical form, save upper-bound (#UB), flags 4756 /// for less/greater and for strict/non-strict comparison. 4757 bool checkAndSetCond(Expr *S); 4758 /// Check incr-expr for canonical loop form and return true if it 4759 /// does not conform, otherwise save loop step (#Step). 4760 bool checkAndSetInc(Expr *S); 4761 /// Return the loop counter variable. 4762 ValueDecl *getLoopDecl() const { return LCDecl; } 4763 /// Return the reference expression to loop counter variable. 4764 Expr *getLoopDeclRefExpr() const { return LCRef; } 4765 /// Source range of the loop init. 4766 SourceRange getInitSrcRange() const { return InitSrcRange; } 4767 /// Source range of the loop condition. 4768 SourceRange getConditionSrcRange() const { return ConditionSrcRange; } 4769 /// Source range of the loop increment. 4770 SourceRange getIncrementSrcRange() const { return IncrementSrcRange; } 4771 /// True if the step should be subtracted. 4772 bool shouldSubtractStep() const { return SubtractStep; } 4773 /// True, if the compare operator is strict (<, > or !=). 4774 bool isStrictTestOp() const { return TestIsStrictOp; } 4775 /// Build the expression to calculate the number of iterations. 4776 Expr *buildNumIterations( 4777 Scope *S, const bool LimitedType, 4778 llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) const; 4779 /// Build the precondition expression for the loops. 4780 Expr * 4781 buildPreCond(Scope *S, Expr *Cond, 4782 llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) const; 4783 /// Build reference expression to the counter be used for codegen. 4784 DeclRefExpr * 4785 buildCounterVar(llvm::MapVector<const Expr *, DeclRefExpr *> &Captures, 4786 DSAStackTy &DSA) const; 4787 /// Build reference expression to the private counter be used for 4788 /// codegen. 4789 Expr *buildPrivateCounterVar() const; 4790 /// Build initialization of the counter be used for codegen. 4791 Expr *buildCounterInit() const; 4792 /// Build step of the counter be used for codegen. 4793 Expr *buildCounterStep() const; 4794 /// Build loop data with counter value for depend clauses in ordered 4795 /// directives. 4796 Expr * 4797 buildOrderedLoopData(Scope *S, Expr *Counter, 4798 llvm::MapVector<const Expr *, DeclRefExpr *> &Captures, 4799 SourceLocation Loc, Expr *Inc = nullptr, 4800 OverloadedOperatorKind OOK = OO_Amp); 4801 /// Return true if any expression is dependent. 4802 bool dependent() const; 4803 4804 private: 4805 /// Check the right-hand side of an assignment in the increment 4806 /// expression. 4807 bool checkAndSetIncRHS(Expr *RHS); 4808 /// Helper to set loop counter variable and its initializer. 4809 bool setLCDeclAndLB(ValueDecl *NewLCDecl, Expr *NewDeclRefExpr, Expr *NewLB, 4810 bool EmitDiags); 4811 /// Helper to set upper bound. 4812 bool setUB(Expr *NewUB, llvm::Optional<bool> LessOp, bool StrictOp, 4813 SourceRange SR, SourceLocation SL); 4814 /// Helper to set loop increment. 4815 bool setStep(Expr *NewStep, bool Subtract); 4816 }; 4817 4818 bool OpenMPIterationSpaceChecker::dependent() const { 4819 if (!LCDecl) { 4820 assert(!LB && !UB && !Step); 4821 return false; 4822 } 4823 return LCDecl->getType()->isDependentType() || 4824 (LB && LB->isValueDependent()) || (UB && UB->isValueDependent()) || 4825 (Step && Step->isValueDependent()); 4826 } 4827 4828 bool OpenMPIterationSpaceChecker::setLCDeclAndLB(ValueDecl *NewLCDecl, 4829 Expr *NewLCRefExpr, 4830 Expr *NewLB, bool EmitDiags) { 4831 // State consistency checking to ensure correct usage. 4832 assert(LCDecl == nullptr && LB == nullptr && LCRef == nullptr && 4833 UB == nullptr && Step == nullptr && !TestIsLessOp && !TestIsStrictOp); 4834 if (!NewLCDecl || !NewLB) 4835 return true; 4836 LCDecl = getCanonicalDecl(NewLCDecl); 4837 LCRef = NewLCRefExpr; 4838 if (auto *CE = dyn_cast_or_null<CXXConstructExpr>(NewLB)) 4839 if (const CXXConstructorDecl *Ctor = CE->getConstructor()) 4840 if ((Ctor->isCopyOrMoveConstructor() || 4841 Ctor->isConvertingConstructor(/*AllowExplicit=*/false)) && 4842 CE->getNumArgs() > 0 && CE->getArg(0) != nullptr) 4843 NewLB = CE->getArg(0)->IgnoreParenImpCasts(); 4844 LB = NewLB; 4845 if (EmitDiags) 4846 InitDependOnLC = doesDependOnLoopCounter(LB, /*IsInitializer=*/true); 4847 return false; 4848 } 4849 4850 bool OpenMPIterationSpaceChecker::setUB(Expr *NewUB, 4851 llvm::Optional<bool> LessOp, 4852 bool StrictOp, SourceRange SR, 4853 SourceLocation SL) { 4854 // State consistency checking to ensure correct usage. 4855 assert(LCDecl != nullptr && LB != nullptr && UB == nullptr && 4856 Step == nullptr && !TestIsLessOp && !TestIsStrictOp); 4857 if (!NewUB) 4858 return true; 4859 UB = NewUB; 4860 if (LessOp) 4861 TestIsLessOp = LessOp; 4862 TestIsStrictOp = StrictOp; 4863 ConditionSrcRange = SR; 4864 ConditionLoc = SL; 4865 CondDependOnLC = doesDependOnLoopCounter(UB, /*IsInitializer=*/false); 4866 return false; 4867 } 4868 4869 bool OpenMPIterationSpaceChecker::setStep(Expr *NewStep, bool Subtract) { 4870 // State consistency checking to ensure correct usage. 4871 assert(LCDecl != nullptr && LB != nullptr && Step == nullptr); 4872 if (!NewStep) 4873 return true; 4874 if (!NewStep->isValueDependent()) { 4875 // Check that the step is integer expression. 4876 SourceLocation StepLoc = NewStep->getBeginLoc(); 4877 ExprResult Val = SemaRef.PerformOpenMPImplicitIntegerConversion( 4878 StepLoc, getExprAsWritten(NewStep)); 4879 if (Val.isInvalid()) 4880 return true; 4881 NewStep = Val.get(); 4882 4883 // OpenMP [2.6, Canonical Loop Form, Restrictions] 4884 // If test-expr is of form var relational-op b and relational-op is < or 4885 // <= then incr-expr must cause var to increase on each iteration of the 4886 // loop. If test-expr is of form var relational-op b and relational-op is 4887 // > or >= then incr-expr must cause var to decrease on each iteration of 4888 // the loop. 4889 // If test-expr is of form b relational-op var and relational-op is < or 4890 // <= then incr-expr must cause var to decrease on each iteration of the 4891 // loop. If test-expr is of form b relational-op var and relational-op is 4892 // > or >= then incr-expr must cause var to increase on each iteration of 4893 // the loop. 4894 llvm::APSInt Result; 4895 bool IsConstant = NewStep->isIntegerConstantExpr(Result, SemaRef.Context); 4896 bool IsUnsigned = !NewStep->getType()->hasSignedIntegerRepresentation(); 4897 bool IsConstNeg = 4898 IsConstant && Result.isSigned() && (Subtract != Result.isNegative()); 4899 bool IsConstPos = 4900 IsConstant && Result.isSigned() && (Subtract == Result.isNegative()); 4901 bool IsConstZero = IsConstant && !Result.getBoolValue(); 4902 4903 // != with increment is treated as <; != with decrement is treated as > 4904 if (!TestIsLessOp.hasValue()) 4905 TestIsLessOp = IsConstPos || (IsUnsigned && !Subtract); 4906 if (UB && (IsConstZero || 4907 (TestIsLessOp.getValue() ? 4908 (IsConstNeg || (IsUnsigned && Subtract)) : 4909 (IsConstPos || (IsUnsigned && !Subtract))))) { 4910 SemaRef.Diag(NewStep->getExprLoc(), 4911 diag::err_omp_loop_incr_not_compatible) 4912 << LCDecl << TestIsLessOp.getValue() << NewStep->getSourceRange(); 4913 SemaRef.Diag(ConditionLoc, 4914 diag::note_omp_loop_cond_requres_compatible_incr) 4915 << TestIsLessOp.getValue() << ConditionSrcRange; 4916 return true; 4917 } 4918 if (TestIsLessOp.getValue() == Subtract) { 4919 NewStep = 4920 SemaRef.CreateBuiltinUnaryOp(NewStep->getExprLoc(), UO_Minus, NewStep) 4921 .get(); 4922 Subtract = !Subtract; 4923 } 4924 } 4925 4926 Step = NewStep; 4927 SubtractStep = Subtract; 4928 return false; 4929 } 4930 4931 namespace { 4932 /// Checker for the non-rectangular loops. Checks if the initializer or 4933 /// condition expression references loop counter variable. 4934 class LoopCounterRefChecker final 4935 : public ConstStmtVisitor<LoopCounterRefChecker, bool> { 4936 Sema &SemaRef; 4937 DSAStackTy &Stack; 4938 const ValueDecl *CurLCDecl = nullptr; 4939 const ValueDecl *DepDecl = nullptr; 4940 const ValueDecl *PrevDepDecl = nullptr; 4941 bool IsInitializer = true; 4942 unsigned BaseLoopId = 0; 4943 bool checkDecl(const Expr *E, const ValueDecl *VD) { 4944 if (getCanonicalDecl(VD) == getCanonicalDecl(CurLCDecl)) { 4945 SemaRef.Diag(E->getExprLoc(), diag::err_omp_stmt_depends_on_loop_counter) 4946 << (IsInitializer ? 0 : 1); 4947 return false; 4948 } 4949 const auto &&Data = Stack.isLoopControlVariable(VD); 4950 // OpenMP, 2.9.1 Canonical Loop Form, Restrictions. 4951 // The type of the loop iterator on which we depend may not have a random 4952 // access iterator type. 4953 if (Data.first && VD->getType()->isRecordType()) { 4954 SmallString<128> Name; 4955 llvm::raw_svector_ostream OS(Name); 4956 VD->getNameForDiagnostic(OS, SemaRef.getPrintingPolicy(), 4957 /*Qualified=*/true); 4958 SemaRef.Diag(E->getExprLoc(), 4959 diag::err_omp_wrong_dependency_iterator_type) 4960 << OS.str(); 4961 SemaRef.Diag(VD->getLocation(), diag::note_previous_decl) << VD; 4962 return false; 4963 } 4964 if (Data.first && 4965 (DepDecl || (PrevDepDecl && 4966 getCanonicalDecl(VD) != getCanonicalDecl(PrevDepDecl)))) { 4967 if (!DepDecl && PrevDepDecl) 4968 DepDecl = PrevDepDecl; 4969 SmallString<128> Name; 4970 llvm::raw_svector_ostream OS(Name); 4971 DepDecl->getNameForDiagnostic(OS, SemaRef.getPrintingPolicy(), 4972 /*Qualified=*/true); 4973 SemaRef.Diag(E->getExprLoc(), 4974 diag::err_omp_invariant_or_linear_dependency) 4975 << OS.str(); 4976 return false; 4977 } 4978 if (Data.first) { 4979 DepDecl = VD; 4980 BaseLoopId = Data.first; 4981 } 4982 return Data.first; 4983 } 4984 4985 public: 4986 bool VisitDeclRefExpr(const DeclRefExpr *E) { 4987 const ValueDecl *VD = E->getDecl(); 4988 if (isa<VarDecl>(VD)) 4989 return checkDecl(E, VD); 4990 return false; 4991 } 4992 bool VisitMemberExpr(const MemberExpr *E) { 4993 if (isa<CXXThisExpr>(E->getBase()->IgnoreParens())) { 4994 const ValueDecl *VD = E->getMemberDecl(); 4995 return checkDecl(E, VD); 4996 } 4997 return false; 4998 } 4999 bool VisitStmt(const Stmt *S) { 5000 bool Res = true; 5001 for (const Stmt *Child : S->children()) 5002 Res = Child && Visit(Child) && Res; 5003 return Res; 5004 } 5005 explicit LoopCounterRefChecker(Sema &SemaRef, DSAStackTy &Stack, 5006 const ValueDecl *CurLCDecl, bool IsInitializer, 5007 const ValueDecl *PrevDepDecl = nullptr) 5008 : SemaRef(SemaRef), Stack(Stack), CurLCDecl(CurLCDecl), 5009 PrevDepDecl(PrevDepDecl), IsInitializer(IsInitializer) {} 5010 unsigned getBaseLoopId() const { 5011 assert(CurLCDecl && "Expected loop dependency."); 5012 return BaseLoopId; 5013 } 5014 const ValueDecl *getDepDecl() const { 5015 assert(CurLCDecl && "Expected loop dependency."); 5016 return DepDecl; 5017 } 5018 }; 5019 } // namespace 5020 5021 Optional<unsigned> 5022 OpenMPIterationSpaceChecker::doesDependOnLoopCounter(const Stmt *S, 5023 bool IsInitializer) { 5024 // Check for the non-rectangular loops. 5025 LoopCounterRefChecker LoopStmtChecker(SemaRef, Stack, LCDecl, IsInitializer, 5026 DepDecl); 5027 if (LoopStmtChecker.Visit(S)) { 5028 DepDecl = LoopStmtChecker.getDepDecl(); 5029 return LoopStmtChecker.getBaseLoopId(); 5030 } 5031 return llvm::None; 5032 } 5033 5034 bool OpenMPIterationSpaceChecker::checkAndSetInit(Stmt *S, bool EmitDiags) { 5035 // Check init-expr for canonical loop form and save loop counter 5036 // variable - #Var and its initialization value - #LB. 5037 // OpenMP [2.6] Canonical loop form. init-expr may be one of the following: 5038 // var = lb 5039 // integer-type var = lb 5040 // random-access-iterator-type var = lb 5041 // pointer-type var = lb 5042 // 5043 if (!S) { 5044 if (EmitDiags) { 5045 SemaRef.Diag(DefaultLoc, diag::err_omp_loop_not_canonical_init); 5046 } 5047 return true; 5048 } 5049 if (auto *ExprTemp = dyn_cast<ExprWithCleanups>(S)) 5050 if (!ExprTemp->cleanupsHaveSideEffects()) 5051 S = ExprTemp->getSubExpr(); 5052 5053 InitSrcRange = S->getSourceRange(); 5054 if (Expr *E = dyn_cast<Expr>(S)) 5055 S = E->IgnoreParens(); 5056 if (auto *BO = dyn_cast<BinaryOperator>(S)) { 5057 if (BO->getOpcode() == BO_Assign) { 5058 Expr *LHS = BO->getLHS()->IgnoreParens(); 5059 if (auto *DRE = dyn_cast<DeclRefExpr>(LHS)) { 5060 if (auto *CED = dyn_cast<OMPCapturedExprDecl>(DRE->getDecl())) 5061 if (auto *ME = dyn_cast<MemberExpr>(getExprAsWritten(CED->getInit()))) 5062 return setLCDeclAndLB(ME->getMemberDecl(), ME, BO->getRHS(), 5063 EmitDiags); 5064 return setLCDeclAndLB(DRE->getDecl(), DRE, BO->getRHS(), EmitDiags); 5065 } 5066 if (auto *ME = dyn_cast<MemberExpr>(LHS)) { 5067 if (ME->isArrow() && 5068 isa<CXXThisExpr>(ME->getBase()->IgnoreParenImpCasts())) 5069 return setLCDeclAndLB(ME->getMemberDecl(), ME, BO->getRHS(), 5070 EmitDiags); 5071 } 5072 } 5073 } else if (auto *DS = dyn_cast<DeclStmt>(S)) { 5074 if (DS->isSingleDecl()) { 5075 if (auto *Var = dyn_cast_or_null<VarDecl>(DS->getSingleDecl())) { 5076 if (Var->hasInit() && !Var->getType()->isReferenceType()) { 5077 // Accept non-canonical init form here but emit ext. warning. 5078 if (Var->getInitStyle() != VarDecl::CInit && EmitDiags) 5079 SemaRef.Diag(S->getBeginLoc(), 5080 diag::ext_omp_loop_not_canonical_init) 5081 << S->getSourceRange(); 5082 return setLCDeclAndLB( 5083 Var, 5084 buildDeclRefExpr(SemaRef, Var, 5085 Var->getType().getNonReferenceType(), 5086 DS->getBeginLoc()), 5087 Var->getInit(), EmitDiags); 5088 } 5089 } 5090 } 5091 } else if (auto *CE = dyn_cast<CXXOperatorCallExpr>(S)) { 5092 if (CE->getOperator() == OO_Equal) { 5093 Expr *LHS = CE->getArg(0); 5094 if (auto *DRE = dyn_cast<DeclRefExpr>(LHS)) { 5095 if (auto *CED = dyn_cast<OMPCapturedExprDecl>(DRE->getDecl())) 5096 if (auto *ME = dyn_cast<MemberExpr>(getExprAsWritten(CED->getInit()))) 5097 return setLCDeclAndLB(ME->getMemberDecl(), ME, BO->getRHS(), 5098 EmitDiags); 5099 return setLCDeclAndLB(DRE->getDecl(), DRE, CE->getArg(1), EmitDiags); 5100 } 5101 if (auto *ME = dyn_cast<MemberExpr>(LHS)) { 5102 if (ME->isArrow() && 5103 isa<CXXThisExpr>(ME->getBase()->IgnoreParenImpCasts())) 5104 return setLCDeclAndLB(ME->getMemberDecl(), ME, BO->getRHS(), 5105 EmitDiags); 5106 } 5107 } 5108 } 5109 5110 if (dependent() || SemaRef.CurContext->isDependentContext()) 5111 return false; 5112 if (EmitDiags) { 5113 SemaRef.Diag(S->getBeginLoc(), diag::err_omp_loop_not_canonical_init) 5114 << S->getSourceRange(); 5115 } 5116 return true; 5117 } 5118 5119 /// Ignore parenthesizes, implicit casts, copy constructor and return the 5120 /// variable (which may be the loop variable) if possible. 5121 static const ValueDecl *getInitLCDecl(const Expr *E) { 5122 if (!E) 5123 return nullptr; 5124 E = getExprAsWritten(E); 5125 if (const auto *CE = dyn_cast_or_null<CXXConstructExpr>(E)) 5126 if (const CXXConstructorDecl *Ctor = CE->getConstructor()) 5127 if ((Ctor->isCopyOrMoveConstructor() || 5128 Ctor->isConvertingConstructor(/*AllowExplicit=*/false)) && 5129 CE->getNumArgs() > 0 && CE->getArg(0) != nullptr) 5130 E = CE->getArg(0)->IgnoreParenImpCasts(); 5131 if (const auto *DRE = dyn_cast_or_null<DeclRefExpr>(E)) { 5132 if (const auto *VD = dyn_cast<VarDecl>(DRE->getDecl())) 5133 return getCanonicalDecl(VD); 5134 } 5135 if (const auto *ME = dyn_cast_or_null<MemberExpr>(E)) 5136 if (ME->isArrow() && isa<CXXThisExpr>(ME->getBase()->IgnoreParenImpCasts())) 5137 return getCanonicalDecl(ME->getMemberDecl()); 5138 return nullptr; 5139 } 5140 5141 bool OpenMPIterationSpaceChecker::checkAndSetCond(Expr *S) { 5142 // Check test-expr for canonical form, save upper-bound UB, flags for 5143 // less/greater and for strict/non-strict comparison. 5144 // OpenMP [2.6] Canonical loop form. Test-expr may be one of the following: 5145 // var relational-op b 5146 // b relational-op var 5147 // 5148 if (!S) { 5149 SemaRef.Diag(DefaultLoc, diag::err_omp_loop_not_canonical_cond) << LCDecl; 5150 return true; 5151 } 5152 S = getExprAsWritten(S); 5153 SourceLocation CondLoc = S->getBeginLoc(); 5154 if (auto *BO = dyn_cast<BinaryOperator>(S)) { 5155 if (BO->isRelationalOp()) { 5156 if (getInitLCDecl(BO->getLHS()) == LCDecl) 5157 return setUB(BO->getRHS(), 5158 (BO->getOpcode() == BO_LT || BO->getOpcode() == BO_LE), 5159 (BO->getOpcode() == BO_LT || BO->getOpcode() == BO_GT), 5160 BO->getSourceRange(), BO->getOperatorLoc()); 5161 if (getInitLCDecl(BO->getRHS()) == LCDecl) 5162 return setUB(BO->getLHS(), 5163 (BO->getOpcode() == BO_GT || BO->getOpcode() == BO_GE), 5164 (BO->getOpcode() == BO_LT || BO->getOpcode() == BO_GT), 5165 BO->getSourceRange(), BO->getOperatorLoc()); 5166 } else if (BO->getOpcode() == BO_NE) 5167 return setUB(getInitLCDecl(BO->getLHS()) == LCDecl ? 5168 BO->getRHS() : BO->getLHS(), 5169 /*LessOp=*/llvm::None, 5170 /*StrictOp=*/true, 5171 BO->getSourceRange(), BO->getOperatorLoc()); 5172 } else if (auto *CE = dyn_cast<CXXOperatorCallExpr>(S)) { 5173 if (CE->getNumArgs() == 2) { 5174 auto Op = CE->getOperator(); 5175 switch (Op) { 5176 case OO_Greater: 5177 case OO_GreaterEqual: 5178 case OO_Less: 5179 case OO_LessEqual: 5180 if (getInitLCDecl(CE->getArg(0)) == LCDecl) 5181 return setUB(CE->getArg(1), Op == OO_Less || Op == OO_LessEqual, 5182 Op == OO_Less || Op == OO_Greater, CE->getSourceRange(), 5183 CE->getOperatorLoc()); 5184 if (getInitLCDecl(CE->getArg(1)) == LCDecl) 5185 return setUB(CE->getArg(0), Op == OO_Greater || Op == OO_GreaterEqual, 5186 Op == OO_Less || Op == OO_Greater, CE->getSourceRange(), 5187 CE->getOperatorLoc()); 5188 break; 5189 case OO_ExclaimEqual: 5190 return setUB(getInitLCDecl(CE->getArg(0)) == LCDecl ? 5191 CE->getArg(1) : CE->getArg(0), 5192 /*LessOp=*/llvm::None, 5193 /*StrictOp=*/true, 5194 CE->getSourceRange(), 5195 CE->getOperatorLoc()); 5196 break; 5197 default: 5198 break; 5199 } 5200 } 5201 } 5202 if (dependent() || SemaRef.CurContext->isDependentContext()) 5203 return false; 5204 SemaRef.Diag(CondLoc, diag::err_omp_loop_not_canonical_cond) 5205 << S->getSourceRange() << LCDecl; 5206 return true; 5207 } 5208 5209 bool OpenMPIterationSpaceChecker::checkAndSetIncRHS(Expr *RHS) { 5210 // RHS of canonical loop form increment can be: 5211 // var + incr 5212 // incr + var 5213 // var - incr 5214 // 5215 RHS = RHS->IgnoreParenImpCasts(); 5216 if (auto *BO = dyn_cast<BinaryOperator>(RHS)) { 5217 if (BO->isAdditiveOp()) { 5218 bool IsAdd = BO->getOpcode() == BO_Add; 5219 if (getInitLCDecl(BO->getLHS()) == LCDecl) 5220 return setStep(BO->getRHS(), !IsAdd); 5221 if (IsAdd && getInitLCDecl(BO->getRHS()) == LCDecl) 5222 return setStep(BO->getLHS(), /*Subtract=*/false); 5223 } 5224 } else if (auto *CE = dyn_cast<CXXOperatorCallExpr>(RHS)) { 5225 bool IsAdd = CE->getOperator() == OO_Plus; 5226 if ((IsAdd || CE->getOperator() == OO_Minus) && CE->getNumArgs() == 2) { 5227 if (getInitLCDecl(CE->getArg(0)) == LCDecl) 5228 return setStep(CE->getArg(1), !IsAdd); 5229 if (IsAdd && getInitLCDecl(CE->getArg(1)) == LCDecl) 5230 return setStep(CE->getArg(0), /*Subtract=*/false); 5231 } 5232 } 5233 if (dependent() || SemaRef.CurContext->isDependentContext()) 5234 return false; 5235 SemaRef.Diag(RHS->getBeginLoc(), diag::err_omp_loop_not_canonical_incr) 5236 << RHS->getSourceRange() << LCDecl; 5237 return true; 5238 } 5239 5240 bool OpenMPIterationSpaceChecker::checkAndSetInc(Expr *S) { 5241 // Check incr-expr for canonical loop form and return true if it 5242 // does not conform. 5243 // OpenMP [2.6] Canonical loop form. Test-expr may be one of the following: 5244 // ++var 5245 // var++ 5246 // --var 5247 // var-- 5248 // var += incr 5249 // var -= incr 5250 // var = var + incr 5251 // var = incr + var 5252 // var = var - incr 5253 // 5254 if (!S) { 5255 SemaRef.Diag(DefaultLoc, diag::err_omp_loop_not_canonical_incr) << LCDecl; 5256 return true; 5257 } 5258 if (auto *ExprTemp = dyn_cast<ExprWithCleanups>(S)) 5259 if (!ExprTemp->cleanupsHaveSideEffects()) 5260 S = ExprTemp->getSubExpr(); 5261 5262 IncrementSrcRange = S->getSourceRange(); 5263 S = S->IgnoreParens(); 5264 if (auto *UO = dyn_cast<UnaryOperator>(S)) { 5265 if (UO->isIncrementDecrementOp() && 5266 getInitLCDecl(UO->getSubExpr()) == LCDecl) 5267 return setStep(SemaRef 5268 .ActOnIntegerConstant(UO->getBeginLoc(), 5269 (UO->isDecrementOp() ? -1 : 1)) 5270 .get(), 5271 /*Subtract=*/false); 5272 } else if (auto *BO = dyn_cast<BinaryOperator>(S)) { 5273 switch (BO->getOpcode()) { 5274 case BO_AddAssign: 5275 case BO_SubAssign: 5276 if (getInitLCDecl(BO->getLHS()) == LCDecl) 5277 return setStep(BO->getRHS(), BO->getOpcode() == BO_SubAssign); 5278 break; 5279 case BO_Assign: 5280 if (getInitLCDecl(BO->getLHS()) == LCDecl) 5281 return checkAndSetIncRHS(BO->getRHS()); 5282 break; 5283 default: 5284 break; 5285 } 5286 } else if (auto *CE = dyn_cast<CXXOperatorCallExpr>(S)) { 5287 switch (CE->getOperator()) { 5288 case OO_PlusPlus: 5289 case OO_MinusMinus: 5290 if (getInitLCDecl(CE->getArg(0)) == LCDecl) 5291 return setStep(SemaRef 5292 .ActOnIntegerConstant( 5293 CE->getBeginLoc(), 5294 ((CE->getOperator() == OO_MinusMinus) ? -1 : 1)) 5295 .get(), 5296 /*Subtract=*/false); 5297 break; 5298 case OO_PlusEqual: 5299 case OO_MinusEqual: 5300 if (getInitLCDecl(CE->getArg(0)) == LCDecl) 5301 return setStep(CE->getArg(1), CE->getOperator() == OO_MinusEqual); 5302 break; 5303 case OO_Equal: 5304 if (getInitLCDecl(CE->getArg(0)) == LCDecl) 5305 return checkAndSetIncRHS(CE->getArg(1)); 5306 break; 5307 default: 5308 break; 5309 } 5310 } 5311 if (dependent() || SemaRef.CurContext->isDependentContext()) 5312 return false; 5313 SemaRef.Diag(S->getBeginLoc(), diag::err_omp_loop_not_canonical_incr) 5314 << S->getSourceRange() << LCDecl; 5315 return true; 5316 } 5317 5318 static ExprResult 5319 tryBuildCapture(Sema &SemaRef, Expr *Capture, 5320 llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) { 5321 if (SemaRef.CurContext->isDependentContext()) 5322 return ExprResult(Capture); 5323 if (Capture->isEvaluatable(SemaRef.Context, Expr::SE_AllowSideEffects)) 5324 return SemaRef.PerformImplicitConversion( 5325 Capture->IgnoreImpCasts(), Capture->getType(), Sema::AA_Converting, 5326 /*AllowExplicit=*/true); 5327 auto I = Captures.find(Capture); 5328 if (I != Captures.end()) 5329 return buildCapture(SemaRef, Capture, I->second); 5330 DeclRefExpr *Ref = nullptr; 5331 ExprResult Res = buildCapture(SemaRef, Capture, Ref); 5332 Captures[Capture] = Ref; 5333 return Res; 5334 } 5335 5336 /// Build the expression to calculate the number of iterations. 5337 Expr *OpenMPIterationSpaceChecker::buildNumIterations( 5338 Scope *S, const bool LimitedType, 5339 llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) const { 5340 ExprResult Diff; 5341 QualType VarType = LCDecl->getType().getNonReferenceType(); 5342 if (VarType->isIntegerType() || VarType->isPointerType() || 5343 SemaRef.getLangOpts().CPlusPlus) { 5344 // Upper - Lower 5345 Expr *UBExpr = TestIsLessOp.getValue() ? UB : LB; 5346 Expr *LBExpr = TestIsLessOp.getValue() ? LB : UB; 5347 Expr *Upper = tryBuildCapture(SemaRef, UBExpr, Captures).get(); 5348 Expr *Lower = tryBuildCapture(SemaRef, LBExpr, Captures).get(); 5349 if (!Upper || !Lower) 5350 return nullptr; 5351 5352 Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Sub, Upper, Lower); 5353 5354 if (!Diff.isUsable() && VarType->getAsCXXRecordDecl()) { 5355 // BuildBinOp already emitted error, this one is to point user to upper 5356 // and lower bound, and to tell what is passed to 'operator-'. 5357 SemaRef.Diag(Upper->getBeginLoc(), diag::err_omp_loop_diff_cxx) 5358 << Upper->getSourceRange() << Lower->getSourceRange(); 5359 return nullptr; 5360 } 5361 } 5362 5363 if (!Diff.isUsable()) 5364 return nullptr; 5365 5366 // Upper - Lower [- 1] 5367 if (TestIsStrictOp) 5368 Diff = SemaRef.BuildBinOp( 5369 S, DefaultLoc, BO_Sub, Diff.get(), 5370 SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get()); 5371 if (!Diff.isUsable()) 5372 return nullptr; 5373 5374 // Upper - Lower [- 1] + Step 5375 ExprResult NewStep = tryBuildCapture(SemaRef, Step, Captures); 5376 if (!NewStep.isUsable()) 5377 return nullptr; 5378 Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Add, Diff.get(), NewStep.get()); 5379 if (!Diff.isUsable()) 5380 return nullptr; 5381 5382 // Parentheses (for dumping/debugging purposes only). 5383 Diff = SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, Diff.get()); 5384 if (!Diff.isUsable()) 5385 return nullptr; 5386 5387 // (Upper - Lower [- 1] + Step) / Step 5388 Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Div, Diff.get(), NewStep.get()); 5389 if (!Diff.isUsable()) 5390 return nullptr; 5391 5392 // OpenMP runtime requires 32-bit or 64-bit loop variables. 5393 QualType Type = Diff.get()->getType(); 5394 ASTContext &C = SemaRef.Context; 5395 bool UseVarType = VarType->hasIntegerRepresentation() && 5396 C.getTypeSize(Type) > C.getTypeSize(VarType); 5397 if (!Type->isIntegerType() || UseVarType) { 5398 unsigned NewSize = 5399 UseVarType ? C.getTypeSize(VarType) : C.getTypeSize(Type); 5400 bool IsSigned = UseVarType ? VarType->hasSignedIntegerRepresentation() 5401 : Type->hasSignedIntegerRepresentation(); 5402 Type = C.getIntTypeForBitwidth(NewSize, IsSigned); 5403 if (!SemaRef.Context.hasSameType(Diff.get()->getType(), Type)) { 5404 Diff = SemaRef.PerformImplicitConversion( 5405 Diff.get(), Type, Sema::AA_Converting, /*AllowExplicit=*/true); 5406 if (!Diff.isUsable()) 5407 return nullptr; 5408 } 5409 } 5410 if (LimitedType) { 5411 unsigned NewSize = (C.getTypeSize(Type) > 32) ? 64 : 32; 5412 if (NewSize != C.getTypeSize(Type)) { 5413 if (NewSize < C.getTypeSize(Type)) { 5414 assert(NewSize == 64 && "incorrect loop var size"); 5415 SemaRef.Diag(DefaultLoc, diag::warn_omp_loop_64_bit_var) 5416 << InitSrcRange << ConditionSrcRange; 5417 } 5418 QualType NewType = C.getIntTypeForBitwidth( 5419 NewSize, Type->hasSignedIntegerRepresentation() || 5420 C.getTypeSize(Type) < NewSize); 5421 if (!SemaRef.Context.hasSameType(Diff.get()->getType(), NewType)) { 5422 Diff = SemaRef.PerformImplicitConversion(Diff.get(), NewType, 5423 Sema::AA_Converting, true); 5424 if (!Diff.isUsable()) 5425 return nullptr; 5426 } 5427 } 5428 } 5429 5430 return Diff.get(); 5431 } 5432 5433 Expr *OpenMPIterationSpaceChecker::buildPreCond( 5434 Scope *S, Expr *Cond, 5435 llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) const { 5436 // Try to build LB <op> UB, where <op> is <, >, <=, or >=. 5437 bool Suppress = SemaRef.getDiagnostics().getSuppressAllDiagnostics(); 5438 SemaRef.getDiagnostics().setSuppressAllDiagnostics(/*Val=*/true); 5439 5440 ExprResult NewLB = tryBuildCapture(SemaRef, LB, Captures); 5441 ExprResult NewUB = tryBuildCapture(SemaRef, UB, Captures); 5442 if (!NewLB.isUsable() || !NewUB.isUsable()) 5443 return nullptr; 5444 5445 ExprResult CondExpr = 5446 SemaRef.BuildBinOp(S, DefaultLoc, 5447 TestIsLessOp.getValue() ? 5448 (TestIsStrictOp ? BO_LT : BO_LE) : 5449 (TestIsStrictOp ? BO_GT : BO_GE), 5450 NewLB.get(), NewUB.get()); 5451 if (CondExpr.isUsable()) { 5452 if (!SemaRef.Context.hasSameUnqualifiedType(CondExpr.get()->getType(), 5453 SemaRef.Context.BoolTy)) 5454 CondExpr = SemaRef.PerformImplicitConversion( 5455 CondExpr.get(), SemaRef.Context.BoolTy, /*Action=*/Sema::AA_Casting, 5456 /*AllowExplicit=*/true); 5457 } 5458 SemaRef.getDiagnostics().setSuppressAllDiagnostics(Suppress); 5459 // Otherwise use original loop condition and evaluate it in runtime. 5460 return CondExpr.isUsable() ? CondExpr.get() : Cond; 5461 } 5462 5463 /// Build reference expression to the counter be used for codegen. 5464 DeclRefExpr *OpenMPIterationSpaceChecker::buildCounterVar( 5465 llvm::MapVector<const Expr *, DeclRefExpr *> &Captures, 5466 DSAStackTy &DSA) const { 5467 auto *VD = dyn_cast<VarDecl>(LCDecl); 5468 if (!VD) { 5469 VD = SemaRef.isOpenMPCapturedDecl(LCDecl); 5470 DeclRefExpr *Ref = buildDeclRefExpr( 5471 SemaRef, VD, VD->getType().getNonReferenceType(), DefaultLoc); 5472 const DSAStackTy::DSAVarData Data = 5473 DSA.getTopDSA(LCDecl, /*FromParent=*/false); 5474 // If the loop control decl is explicitly marked as private, do not mark it 5475 // as captured again. 5476 if (!isOpenMPPrivate(Data.CKind) || !Data.RefExpr) 5477 Captures.insert(std::make_pair(LCRef, Ref)); 5478 return Ref; 5479 } 5480 return cast<DeclRefExpr>(LCRef); 5481 } 5482 5483 Expr *OpenMPIterationSpaceChecker::buildPrivateCounterVar() const { 5484 if (LCDecl && !LCDecl->isInvalidDecl()) { 5485 QualType Type = LCDecl->getType().getNonReferenceType(); 5486 VarDecl *PrivateVar = buildVarDecl( 5487 SemaRef, DefaultLoc, Type, LCDecl->getName(), 5488 LCDecl->hasAttrs() ? &LCDecl->getAttrs() : nullptr, 5489 isa<VarDecl>(LCDecl) 5490 ? buildDeclRefExpr(SemaRef, cast<VarDecl>(LCDecl), Type, DefaultLoc) 5491 : nullptr); 5492 if (PrivateVar->isInvalidDecl()) 5493 return nullptr; 5494 return buildDeclRefExpr(SemaRef, PrivateVar, Type, DefaultLoc); 5495 } 5496 return nullptr; 5497 } 5498 5499 /// Build initialization of the counter to be used for codegen. 5500 Expr *OpenMPIterationSpaceChecker::buildCounterInit() const { return LB; } 5501 5502 /// Build step of the counter be used for codegen. 5503 Expr *OpenMPIterationSpaceChecker::buildCounterStep() const { return Step; } 5504 5505 Expr *OpenMPIterationSpaceChecker::buildOrderedLoopData( 5506 Scope *S, Expr *Counter, 5507 llvm::MapVector<const Expr *, DeclRefExpr *> &Captures, SourceLocation Loc, 5508 Expr *Inc, OverloadedOperatorKind OOK) { 5509 Expr *Cnt = SemaRef.DefaultLvalueConversion(Counter).get(); 5510 if (!Cnt) 5511 return nullptr; 5512 if (Inc) { 5513 assert((OOK == OO_Plus || OOK == OO_Minus) && 5514 "Expected only + or - operations for depend clauses."); 5515 BinaryOperatorKind BOK = (OOK == OO_Plus) ? BO_Add : BO_Sub; 5516 Cnt = SemaRef.BuildBinOp(S, Loc, BOK, Cnt, Inc).get(); 5517 if (!Cnt) 5518 return nullptr; 5519 } 5520 ExprResult Diff; 5521 QualType VarType = LCDecl->getType().getNonReferenceType(); 5522 if (VarType->isIntegerType() || VarType->isPointerType() || 5523 SemaRef.getLangOpts().CPlusPlus) { 5524 // Upper - Lower 5525 Expr *Upper = TestIsLessOp.getValue() 5526 ? Cnt 5527 : tryBuildCapture(SemaRef, UB, Captures).get(); 5528 Expr *Lower = TestIsLessOp.getValue() 5529 ? tryBuildCapture(SemaRef, LB, Captures).get() 5530 : Cnt; 5531 if (!Upper || !Lower) 5532 return nullptr; 5533 5534 Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Sub, Upper, Lower); 5535 5536 if (!Diff.isUsable() && VarType->getAsCXXRecordDecl()) { 5537 // BuildBinOp already emitted error, this one is to point user to upper 5538 // and lower bound, and to tell what is passed to 'operator-'. 5539 SemaRef.Diag(Upper->getBeginLoc(), diag::err_omp_loop_diff_cxx) 5540 << Upper->getSourceRange() << Lower->getSourceRange(); 5541 return nullptr; 5542 } 5543 } 5544 5545 if (!Diff.isUsable()) 5546 return nullptr; 5547 5548 // Parentheses (for dumping/debugging purposes only). 5549 Diff = SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, Diff.get()); 5550 if (!Diff.isUsable()) 5551 return nullptr; 5552 5553 ExprResult NewStep = tryBuildCapture(SemaRef, Step, Captures); 5554 if (!NewStep.isUsable()) 5555 return nullptr; 5556 // (Upper - Lower) / Step 5557 Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Div, Diff.get(), NewStep.get()); 5558 if (!Diff.isUsable()) 5559 return nullptr; 5560 5561 return Diff.get(); 5562 } 5563 5564 /// Iteration space of a single for loop. 5565 struct LoopIterationSpace final { 5566 /// True if the condition operator is the strict compare operator (<, > or 5567 /// !=). 5568 bool IsStrictCompare = false; 5569 /// Condition of the loop. 5570 Expr *PreCond = nullptr; 5571 /// This expression calculates the number of iterations in the loop. 5572 /// It is always possible to calculate it before starting the loop. 5573 Expr *NumIterations = nullptr; 5574 /// The loop counter variable. 5575 Expr *CounterVar = nullptr; 5576 /// Private loop counter variable. 5577 Expr *PrivateCounterVar = nullptr; 5578 /// This is initializer for the initial value of #CounterVar. 5579 Expr *CounterInit = nullptr; 5580 /// This is step for the #CounterVar used to generate its update: 5581 /// #CounterVar = #CounterInit + #CounterStep * CurrentIteration. 5582 Expr *CounterStep = nullptr; 5583 /// Should step be subtracted? 5584 bool Subtract = false; 5585 /// Source range of the loop init. 5586 SourceRange InitSrcRange; 5587 /// Source range of the loop condition. 5588 SourceRange CondSrcRange; 5589 /// Source range of the loop increment. 5590 SourceRange IncSrcRange; 5591 }; 5592 5593 } // namespace 5594 5595 void Sema::ActOnOpenMPLoopInitialization(SourceLocation ForLoc, Stmt *Init) { 5596 assert(getLangOpts().OpenMP && "OpenMP is not active."); 5597 assert(Init && "Expected loop in canonical form."); 5598 unsigned AssociatedLoops = DSAStack->getAssociatedLoops(); 5599 if (AssociatedLoops > 0 && 5600 isOpenMPLoopDirective(DSAStack->getCurrentDirective())) { 5601 DSAStack->loopStart(); 5602 OpenMPIterationSpaceChecker ISC(*this, *DSAStack, ForLoc); 5603 if (!ISC.checkAndSetInit(Init, /*EmitDiags=*/false)) { 5604 if (ValueDecl *D = ISC.getLoopDecl()) { 5605 auto *VD = dyn_cast<VarDecl>(D); 5606 if (!VD) { 5607 if (VarDecl *Private = isOpenMPCapturedDecl(D)) { 5608 VD = Private; 5609 } else { 5610 DeclRefExpr *Ref = buildCapture(*this, D, ISC.getLoopDeclRefExpr(), 5611 /*WithInit=*/false); 5612 VD = cast<VarDecl>(Ref->getDecl()); 5613 } 5614 } 5615 DSAStack->addLoopControlVariable(D, VD); 5616 const Decl *LD = DSAStack->getPossiblyLoopCunter(); 5617 if (LD != D->getCanonicalDecl()) { 5618 DSAStack->resetPossibleLoopCounter(); 5619 if (auto *Var = dyn_cast_or_null<VarDecl>(LD)) 5620 MarkDeclarationsReferencedInExpr( 5621 buildDeclRefExpr(*this, const_cast<VarDecl *>(Var), 5622 Var->getType().getNonLValueExprType(Context), 5623 ForLoc, /*RefersToCapture=*/true)); 5624 } 5625 } 5626 } 5627 DSAStack->setAssociatedLoops(AssociatedLoops - 1); 5628 } 5629 } 5630 5631 /// Called on a for stmt to check and extract its iteration space 5632 /// for further processing (such as collapsing). 5633 static bool checkOpenMPIterationSpace( 5634 OpenMPDirectiveKind DKind, Stmt *S, Sema &SemaRef, DSAStackTy &DSA, 5635 unsigned CurrentNestedLoopCount, unsigned NestedLoopCount, 5636 unsigned TotalNestedLoopCount, Expr *CollapseLoopCountExpr, 5637 Expr *OrderedLoopCountExpr, 5638 Sema::VarsWithInheritedDSAType &VarsWithImplicitDSA, 5639 LoopIterationSpace &ResultIterSpace, 5640 llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) { 5641 // OpenMP [2.6, Canonical Loop Form] 5642 // for (init-expr; test-expr; incr-expr) structured-block 5643 auto *For = dyn_cast_or_null<ForStmt>(S); 5644 if (!For) { 5645 SemaRef.Diag(S->getBeginLoc(), diag::err_omp_not_for) 5646 << (CollapseLoopCountExpr != nullptr || OrderedLoopCountExpr != nullptr) 5647 << getOpenMPDirectiveName(DKind) << TotalNestedLoopCount 5648 << (CurrentNestedLoopCount > 0) << CurrentNestedLoopCount; 5649 if (TotalNestedLoopCount > 1) { 5650 if (CollapseLoopCountExpr && OrderedLoopCountExpr) 5651 SemaRef.Diag(DSA.getConstructLoc(), 5652 diag::note_omp_collapse_ordered_expr) 5653 << 2 << CollapseLoopCountExpr->getSourceRange() 5654 << OrderedLoopCountExpr->getSourceRange(); 5655 else if (CollapseLoopCountExpr) 5656 SemaRef.Diag(CollapseLoopCountExpr->getExprLoc(), 5657 diag::note_omp_collapse_ordered_expr) 5658 << 0 << CollapseLoopCountExpr->getSourceRange(); 5659 else 5660 SemaRef.Diag(OrderedLoopCountExpr->getExprLoc(), 5661 diag::note_omp_collapse_ordered_expr) 5662 << 1 << OrderedLoopCountExpr->getSourceRange(); 5663 } 5664 return true; 5665 } 5666 assert(For->getBody()); 5667 5668 OpenMPIterationSpaceChecker ISC(SemaRef, DSA, For->getForLoc()); 5669 5670 // Check init. 5671 Stmt *Init = For->getInit(); 5672 if (ISC.checkAndSetInit(Init)) 5673 return true; 5674 5675 bool HasErrors = false; 5676 5677 // Check loop variable's type. 5678 if (ValueDecl *LCDecl = ISC.getLoopDecl()) { 5679 Expr *LoopDeclRefExpr = ISC.getLoopDeclRefExpr(); 5680 5681 // OpenMP [2.6, Canonical Loop Form] 5682 // Var is one of the following: 5683 // A variable of signed or unsigned integer type. 5684 // For C++, a variable of a random access iterator type. 5685 // For C, a variable of a pointer type. 5686 QualType VarType = LCDecl->getType().getNonReferenceType(); 5687 if (!VarType->isDependentType() && !VarType->isIntegerType() && 5688 !VarType->isPointerType() && 5689 !(SemaRef.getLangOpts().CPlusPlus && VarType->isOverloadableType())) { 5690 SemaRef.Diag(Init->getBeginLoc(), diag::err_omp_loop_variable_type) 5691 << SemaRef.getLangOpts().CPlusPlus; 5692 HasErrors = true; 5693 } 5694 5695 // OpenMP, 2.14.1.1 Data-sharing Attribute Rules for Variables Referenced in 5696 // a Construct 5697 // The loop iteration variable(s) in the associated for-loop(s) of a for or 5698 // parallel for construct is (are) private. 5699 // The loop iteration variable in the associated for-loop of a simd 5700 // construct with just one associated for-loop is linear with a 5701 // constant-linear-step that is the increment of the associated for-loop. 5702 // Exclude loop var from the list of variables with implicitly defined data 5703 // sharing attributes. 5704 VarsWithImplicitDSA.erase(LCDecl); 5705 5706 // OpenMP [2.14.1.1, Data-sharing Attribute Rules for Variables Referenced 5707 // in a Construct, C/C++]. 5708 // The loop iteration variable in the associated for-loop of a simd 5709 // construct with just one associated for-loop may be listed in a linear 5710 // clause with a constant-linear-step that is the increment of the 5711 // associated for-loop. 5712 // The loop iteration variable(s) in the associated for-loop(s) of a for or 5713 // parallel for construct may be listed in a private or lastprivate clause. 5714 DSAStackTy::DSAVarData DVar = DSA.getTopDSA(LCDecl, false); 5715 // If LoopVarRefExpr is nullptr it means the corresponding loop variable is 5716 // declared in the loop and it is predetermined as a private. 5717 OpenMPClauseKind PredeterminedCKind = 5718 isOpenMPSimdDirective(DKind) 5719 ? ((NestedLoopCount == 1) ? OMPC_linear : OMPC_lastprivate) 5720 : OMPC_private; 5721 if (((isOpenMPSimdDirective(DKind) && DVar.CKind != OMPC_unknown && 5722 DVar.CKind != PredeterminedCKind && DVar.RefExpr && 5723 (SemaRef.getLangOpts().OpenMP <= 45 || 5724 (DVar.CKind != OMPC_lastprivate && DVar.CKind != OMPC_private))) || 5725 ((isOpenMPWorksharingDirective(DKind) || DKind == OMPD_taskloop || 5726 isOpenMPDistributeDirective(DKind)) && 5727 !isOpenMPSimdDirective(DKind) && DVar.CKind != OMPC_unknown && 5728 DVar.CKind != OMPC_private && DVar.CKind != OMPC_lastprivate)) && 5729 (DVar.CKind != OMPC_private || DVar.RefExpr)) { 5730 SemaRef.Diag(Init->getBeginLoc(), diag::err_omp_loop_var_dsa) 5731 << getOpenMPClauseName(DVar.CKind) << getOpenMPDirectiveName(DKind) 5732 << getOpenMPClauseName(PredeterminedCKind); 5733 if (DVar.RefExpr == nullptr) 5734 DVar.CKind = PredeterminedCKind; 5735 reportOriginalDsa(SemaRef, &DSA, LCDecl, DVar, /*IsLoopIterVar=*/true); 5736 HasErrors = true; 5737 } else if (LoopDeclRefExpr != nullptr) { 5738 // Make the loop iteration variable private (for worksharing constructs), 5739 // linear (for simd directives with the only one associated loop) or 5740 // lastprivate (for simd directives with several collapsed or ordered 5741 // loops). 5742 if (DVar.CKind == OMPC_unknown) 5743 DSA.addDSA(LCDecl, LoopDeclRefExpr, PredeterminedCKind); 5744 } 5745 5746 assert(isOpenMPLoopDirective(DKind) && "DSA for non-loop vars"); 5747 5748 // Check test-expr. 5749 HasErrors |= ISC.checkAndSetCond(For->getCond()); 5750 5751 // Check incr-expr. 5752 HasErrors |= ISC.checkAndSetInc(For->getInc()); 5753 } 5754 5755 if (ISC.dependent() || SemaRef.CurContext->isDependentContext() || HasErrors) 5756 return HasErrors; 5757 5758 // Build the loop's iteration space representation. 5759 ResultIterSpace.PreCond = 5760 ISC.buildPreCond(DSA.getCurScope(), For->getCond(), Captures); 5761 ResultIterSpace.NumIterations = ISC.buildNumIterations( 5762 DSA.getCurScope(), 5763 (isOpenMPWorksharingDirective(DKind) || 5764 isOpenMPTaskLoopDirective(DKind) || isOpenMPDistributeDirective(DKind)), 5765 Captures); 5766 ResultIterSpace.CounterVar = ISC.buildCounterVar(Captures, DSA); 5767 ResultIterSpace.PrivateCounterVar = ISC.buildPrivateCounterVar(); 5768 ResultIterSpace.CounterInit = ISC.buildCounterInit(); 5769 ResultIterSpace.CounterStep = ISC.buildCounterStep(); 5770 ResultIterSpace.InitSrcRange = ISC.getInitSrcRange(); 5771 ResultIterSpace.CondSrcRange = ISC.getConditionSrcRange(); 5772 ResultIterSpace.IncSrcRange = ISC.getIncrementSrcRange(); 5773 ResultIterSpace.Subtract = ISC.shouldSubtractStep(); 5774 ResultIterSpace.IsStrictCompare = ISC.isStrictTestOp(); 5775 5776 HasErrors |= (ResultIterSpace.PreCond == nullptr || 5777 ResultIterSpace.NumIterations == nullptr || 5778 ResultIterSpace.CounterVar == nullptr || 5779 ResultIterSpace.PrivateCounterVar == nullptr || 5780 ResultIterSpace.CounterInit == nullptr || 5781 ResultIterSpace.CounterStep == nullptr); 5782 if (!HasErrors && DSA.isOrderedRegion()) { 5783 if (DSA.getOrderedRegionParam().second->getNumForLoops()) { 5784 if (CurrentNestedLoopCount < 5785 DSA.getOrderedRegionParam().second->getLoopNumIterations().size()) { 5786 DSA.getOrderedRegionParam().second->setLoopNumIterations( 5787 CurrentNestedLoopCount, ResultIterSpace.NumIterations); 5788 DSA.getOrderedRegionParam().second->setLoopCounter( 5789 CurrentNestedLoopCount, ResultIterSpace.CounterVar); 5790 } 5791 } 5792 for (auto &Pair : DSA.getDoacrossDependClauses()) { 5793 if (CurrentNestedLoopCount >= Pair.first->getNumLoops()) { 5794 // Erroneous case - clause has some problems. 5795 continue; 5796 } 5797 if (Pair.first->getDependencyKind() == OMPC_DEPEND_sink && 5798 Pair.second.size() <= CurrentNestedLoopCount) { 5799 // Erroneous case - clause has some problems. 5800 Pair.first->setLoopData(CurrentNestedLoopCount, nullptr); 5801 continue; 5802 } 5803 Expr *CntValue; 5804 if (Pair.first->getDependencyKind() == OMPC_DEPEND_source) 5805 CntValue = ISC.buildOrderedLoopData( 5806 DSA.getCurScope(), ResultIterSpace.CounterVar, Captures, 5807 Pair.first->getDependencyLoc()); 5808 else 5809 CntValue = ISC.buildOrderedLoopData( 5810 DSA.getCurScope(), ResultIterSpace.CounterVar, Captures, 5811 Pair.first->getDependencyLoc(), 5812 Pair.second[CurrentNestedLoopCount].first, 5813 Pair.second[CurrentNestedLoopCount].second); 5814 Pair.first->setLoopData(CurrentNestedLoopCount, CntValue); 5815 } 5816 } 5817 5818 return HasErrors; 5819 } 5820 5821 /// Build 'VarRef = Start. 5822 static ExprResult 5823 buildCounterInit(Sema &SemaRef, Scope *S, SourceLocation Loc, ExprResult VarRef, 5824 ExprResult Start, 5825 llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) { 5826 // Build 'VarRef = Start. 5827 ExprResult NewStart = tryBuildCapture(SemaRef, Start.get(), Captures); 5828 if (!NewStart.isUsable()) 5829 return ExprError(); 5830 if (!SemaRef.Context.hasSameType(NewStart.get()->getType(), 5831 VarRef.get()->getType())) { 5832 NewStart = SemaRef.PerformImplicitConversion( 5833 NewStart.get(), VarRef.get()->getType(), Sema::AA_Converting, 5834 /*AllowExplicit=*/true); 5835 if (!NewStart.isUsable()) 5836 return ExprError(); 5837 } 5838 5839 ExprResult Init = 5840 SemaRef.BuildBinOp(S, Loc, BO_Assign, VarRef.get(), NewStart.get()); 5841 return Init; 5842 } 5843 5844 /// Build 'VarRef = Start + Iter * Step'. 5845 static ExprResult buildCounterUpdate( 5846 Sema &SemaRef, Scope *S, SourceLocation Loc, ExprResult VarRef, 5847 ExprResult Start, ExprResult Iter, ExprResult Step, bool Subtract, 5848 llvm::MapVector<const Expr *, DeclRefExpr *> *Captures = nullptr) { 5849 // Add parentheses (for debugging purposes only). 5850 Iter = SemaRef.ActOnParenExpr(Loc, Loc, Iter.get()); 5851 if (!VarRef.isUsable() || !Start.isUsable() || !Iter.isUsable() || 5852 !Step.isUsable()) 5853 return ExprError(); 5854 5855 ExprResult NewStep = Step; 5856 if (Captures) 5857 NewStep = tryBuildCapture(SemaRef, Step.get(), *Captures); 5858 if (NewStep.isInvalid()) 5859 return ExprError(); 5860 ExprResult Update = 5861 SemaRef.BuildBinOp(S, Loc, BO_Mul, Iter.get(), NewStep.get()); 5862 if (!Update.isUsable()) 5863 return ExprError(); 5864 5865 // Try to build 'VarRef = Start, VarRef (+|-)= Iter * Step' or 5866 // 'VarRef = Start (+|-) Iter * Step'. 5867 ExprResult NewStart = Start; 5868 if (Captures) 5869 NewStart = tryBuildCapture(SemaRef, Start.get(), *Captures); 5870 if (NewStart.isInvalid()) 5871 return ExprError(); 5872 5873 // First attempt: try to build 'VarRef = Start, VarRef += Iter * Step'. 5874 ExprResult SavedUpdate = Update; 5875 ExprResult UpdateVal; 5876 if (VarRef.get()->getType()->isOverloadableType() || 5877 NewStart.get()->getType()->isOverloadableType() || 5878 Update.get()->getType()->isOverloadableType()) { 5879 bool Suppress = SemaRef.getDiagnostics().getSuppressAllDiagnostics(); 5880 SemaRef.getDiagnostics().setSuppressAllDiagnostics(/*Val=*/true); 5881 Update = 5882 SemaRef.BuildBinOp(S, Loc, BO_Assign, VarRef.get(), NewStart.get()); 5883 if (Update.isUsable()) { 5884 UpdateVal = 5885 SemaRef.BuildBinOp(S, Loc, Subtract ? BO_SubAssign : BO_AddAssign, 5886 VarRef.get(), SavedUpdate.get()); 5887 if (UpdateVal.isUsable()) { 5888 Update = SemaRef.CreateBuiltinBinOp(Loc, BO_Comma, Update.get(), 5889 UpdateVal.get()); 5890 } 5891 } 5892 SemaRef.getDiagnostics().setSuppressAllDiagnostics(Suppress); 5893 } 5894 5895 // Second attempt: try to build 'VarRef = Start (+|-) Iter * Step'. 5896 if (!Update.isUsable() || !UpdateVal.isUsable()) { 5897 Update = SemaRef.BuildBinOp(S, Loc, Subtract ? BO_Sub : BO_Add, 5898 NewStart.get(), SavedUpdate.get()); 5899 if (!Update.isUsable()) 5900 return ExprError(); 5901 5902 if (!SemaRef.Context.hasSameType(Update.get()->getType(), 5903 VarRef.get()->getType())) { 5904 Update = SemaRef.PerformImplicitConversion( 5905 Update.get(), VarRef.get()->getType(), Sema::AA_Converting, true); 5906 if (!Update.isUsable()) 5907 return ExprError(); 5908 } 5909 5910 Update = SemaRef.BuildBinOp(S, Loc, BO_Assign, VarRef.get(), Update.get()); 5911 } 5912 return Update; 5913 } 5914 5915 /// Convert integer expression \a E to make it have at least \a Bits 5916 /// bits. 5917 static ExprResult widenIterationCount(unsigned Bits, Expr *E, Sema &SemaRef) { 5918 if (E == nullptr) 5919 return ExprError(); 5920 ASTContext &C = SemaRef.Context; 5921 QualType OldType = E->getType(); 5922 unsigned HasBits = C.getTypeSize(OldType); 5923 if (HasBits >= Bits) 5924 return ExprResult(E); 5925 // OK to convert to signed, because new type has more bits than old. 5926 QualType NewType = C.getIntTypeForBitwidth(Bits, /* Signed */ true); 5927 return SemaRef.PerformImplicitConversion(E, NewType, Sema::AA_Converting, 5928 true); 5929 } 5930 5931 /// Check if the given expression \a E is a constant integer that fits 5932 /// into \a Bits bits. 5933 static bool fitsInto(unsigned Bits, bool Signed, const Expr *E, Sema &SemaRef) { 5934 if (E == nullptr) 5935 return false; 5936 llvm::APSInt Result; 5937 if (E->isIntegerConstantExpr(Result, SemaRef.Context)) 5938 return Signed ? Result.isSignedIntN(Bits) : Result.isIntN(Bits); 5939 return false; 5940 } 5941 5942 /// Build preinits statement for the given declarations. 5943 static Stmt *buildPreInits(ASTContext &Context, 5944 MutableArrayRef<Decl *> PreInits) { 5945 if (!PreInits.empty()) { 5946 return new (Context) DeclStmt( 5947 DeclGroupRef::Create(Context, PreInits.begin(), PreInits.size()), 5948 SourceLocation(), SourceLocation()); 5949 } 5950 return nullptr; 5951 } 5952 5953 /// Build preinits statement for the given declarations. 5954 static Stmt * 5955 buildPreInits(ASTContext &Context, 5956 const llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) { 5957 if (!Captures.empty()) { 5958 SmallVector<Decl *, 16> PreInits; 5959 for (const auto &Pair : Captures) 5960 PreInits.push_back(Pair.second->getDecl()); 5961 return buildPreInits(Context, PreInits); 5962 } 5963 return nullptr; 5964 } 5965 5966 /// Build postupdate expression for the given list of postupdates expressions. 5967 static Expr *buildPostUpdate(Sema &S, ArrayRef<Expr *> PostUpdates) { 5968 Expr *PostUpdate = nullptr; 5969 if (!PostUpdates.empty()) { 5970 for (Expr *E : PostUpdates) { 5971 Expr *ConvE = S.BuildCStyleCastExpr( 5972 E->getExprLoc(), 5973 S.Context.getTrivialTypeSourceInfo(S.Context.VoidTy), 5974 E->getExprLoc(), E) 5975 .get(); 5976 PostUpdate = PostUpdate 5977 ? S.CreateBuiltinBinOp(ConvE->getExprLoc(), BO_Comma, 5978 PostUpdate, ConvE) 5979 .get() 5980 : ConvE; 5981 } 5982 } 5983 return PostUpdate; 5984 } 5985 5986 /// Called on a for stmt to check itself and nested loops (if any). 5987 /// \return Returns 0 if one of the collapsed stmts is not canonical for loop, 5988 /// number of collapsed loops otherwise. 5989 static unsigned 5990 checkOpenMPLoop(OpenMPDirectiveKind DKind, Expr *CollapseLoopCountExpr, 5991 Expr *OrderedLoopCountExpr, Stmt *AStmt, Sema &SemaRef, 5992 DSAStackTy &DSA, 5993 Sema::VarsWithInheritedDSAType &VarsWithImplicitDSA, 5994 OMPLoopDirective::HelperExprs &Built) { 5995 unsigned NestedLoopCount = 1; 5996 if (CollapseLoopCountExpr) { 5997 // Found 'collapse' clause - calculate collapse number. 5998 Expr::EvalResult Result; 5999 if (!CollapseLoopCountExpr->isValueDependent() && 6000 CollapseLoopCountExpr->EvaluateAsInt(Result, SemaRef.getASTContext())) { 6001 NestedLoopCount = Result.Val.getInt().getLimitedValue(); 6002 } else { 6003 Built.clear(/*size=*/1); 6004 return 1; 6005 } 6006 } 6007 unsigned OrderedLoopCount = 1; 6008 if (OrderedLoopCountExpr) { 6009 // Found 'ordered' clause - calculate collapse number. 6010 Expr::EvalResult EVResult; 6011 if (!OrderedLoopCountExpr->isValueDependent() && 6012 OrderedLoopCountExpr->EvaluateAsInt(EVResult, 6013 SemaRef.getASTContext())) { 6014 llvm::APSInt Result = EVResult.Val.getInt(); 6015 if (Result.getLimitedValue() < NestedLoopCount) { 6016 SemaRef.Diag(OrderedLoopCountExpr->getExprLoc(), 6017 diag::err_omp_wrong_ordered_loop_count) 6018 << OrderedLoopCountExpr->getSourceRange(); 6019 SemaRef.Diag(CollapseLoopCountExpr->getExprLoc(), 6020 diag::note_collapse_loop_count) 6021 << CollapseLoopCountExpr->getSourceRange(); 6022 } 6023 OrderedLoopCount = Result.getLimitedValue(); 6024 } else { 6025 Built.clear(/*size=*/1); 6026 return 1; 6027 } 6028 } 6029 // This is helper routine for loop directives (e.g., 'for', 'simd', 6030 // 'for simd', etc.). 6031 llvm::MapVector<const Expr *, DeclRefExpr *> Captures; 6032 SmallVector<LoopIterationSpace, 4> IterSpaces( 6033 std::max(OrderedLoopCount, NestedLoopCount)); 6034 Stmt *CurStmt = AStmt->IgnoreContainers(/* IgnoreCaptured */ true); 6035 for (unsigned Cnt = 0; Cnt < NestedLoopCount; ++Cnt) { 6036 if (checkOpenMPIterationSpace( 6037 DKind, CurStmt, SemaRef, DSA, Cnt, NestedLoopCount, 6038 std::max(OrderedLoopCount, NestedLoopCount), CollapseLoopCountExpr, 6039 OrderedLoopCountExpr, VarsWithImplicitDSA, IterSpaces[Cnt], 6040 Captures)) 6041 return 0; 6042 // Move on to the next nested for loop, or to the loop body. 6043 // OpenMP [2.8.1, simd construct, Restrictions] 6044 // All loops associated with the construct must be perfectly nested; that 6045 // is, there must be no intervening code nor any OpenMP directive between 6046 // any two loops. 6047 CurStmt = cast<ForStmt>(CurStmt)->getBody()->IgnoreContainers(); 6048 } 6049 for (unsigned Cnt = NestedLoopCount; Cnt < OrderedLoopCount; ++Cnt) { 6050 if (checkOpenMPIterationSpace( 6051 DKind, CurStmt, SemaRef, DSA, Cnt, NestedLoopCount, 6052 std::max(OrderedLoopCount, NestedLoopCount), CollapseLoopCountExpr, 6053 OrderedLoopCountExpr, VarsWithImplicitDSA, IterSpaces[Cnt], 6054 Captures)) 6055 return 0; 6056 if (Cnt > 0 && IterSpaces[Cnt].CounterVar) { 6057 // Handle initialization of captured loop iterator variables. 6058 auto *DRE = cast<DeclRefExpr>(IterSpaces[Cnt].CounterVar); 6059 if (isa<OMPCapturedExprDecl>(DRE->getDecl())) { 6060 Captures[DRE] = DRE; 6061 } 6062 } 6063 // Move on to the next nested for loop, or to the loop body. 6064 // OpenMP [2.8.1, simd construct, Restrictions] 6065 // All loops associated with the construct must be perfectly nested; that 6066 // is, there must be no intervening code nor any OpenMP directive between 6067 // any two loops. 6068 CurStmt = cast<ForStmt>(CurStmt)->getBody()->IgnoreContainers(); 6069 } 6070 6071 Built.clear(/* size */ NestedLoopCount); 6072 6073 if (SemaRef.CurContext->isDependentContext()) 6074 return NestedLoopCount; 6075 6076 // An example of what is generated for the following code: 6077 // 6078 // #pragma omp simd collapse(2) ordered(2) 6079 // for (i = 0; i < NI; ++i) 6080 // for (k = 0; k < NK; ++k) 6081 // for (j = J0; j < NJ; j+=2) { 6082 // <loop body> 6083 // } 6084 // 6085 // We generate the code below. 6086 // Note: the loop body may be outlined in CodeGen. 6087 // Note: some counters may be C++ classes, operator- is used to find number of 6088 // iterations and operator+= to calculate counter value. 6089 // Note: decltype(NumIterations) must be integer type (in 'omp for', only i32 6090 // or i64 is currently supported). 6091 // 6092 // #define NumIterations (NI * ((NJ - J0 - 1 + 2) / 2)) 6093 // for (int[32|64]_t IV = 0; IV < NumIterations; ++IV ) { 6094 // .local.i = IV / ((NJ - J0 - 1 + 2) / 2); 6095 // .local.j = J0 + (IV % ((NJ - J0 - 1 + 2) / 2)) * 2; 6096 // // similar updates for vars in clauses (e.g. 'linear') 6097 // <loop body (using local i and j)> 6098 // } 6099 // i = NI; // assign final values of counters 6100 // j = NJ; 6101 // 6102 6103 // Last iteration number is (I1 * I2 * ... In) - 1, where I1, I2 ... In are 6104 // the iteration counts of the collapsed for loops. 6105 // Precondition tests if there is at least one iteration (all conditions are 6106 // true). 6107 auto PreCond = ExprResult(IterSpaces[0].PreCond); 6108 Expr *N0 = IterSpaces[0].NumIterations; 6109 ExprResult LastIteration32 = 6110 widenIterationCount(/*Bits=*/32, 6111 SemaRef 6112 .PerformImplicitConversion( 6113 N0->IgnoreImpCasts(), N0->getType(), 6114 Sema::AA_Converting, /*AllowExplicit=*/true) 6115 .get(), 6116 SemaRef); 6117 ExprResult LastIteration64 = widenIterationCount( 6118 /*Bits=*/64, 6119 SemaRef 6120 .PerformImplicitConversion(N0->IgnoreImpCasts(), N0->getType(), 6121 Sema::AA_Converting, 6122 /*AllowExplicit=*/true) 6123 .get(), 6124 SemaRef); 6125 6126 if (!LastIteration32.isUsable() || !LastIteration64.isUsable()) 6127 return NestedLoopCount; 6128 6129 ASTContext &C = SemaRef.Context; 6130 bool AllCountsNeedLessThan32Bits = C.getTypeSize(N0->getType()) < 32; 6131 6132 Scope *CurScope = DSA.getCurScope(); 6133 for (unsigned Cnt = 1; Cnt < NestedLoopCount; ++Cnt) { 6134 if (PreCond.isUsable()) { 6135 PreCond = 6136 SemaRef.BuildBinOp(CurScope, PreCond.get()->getExprLoc(), BO_LAnd, 6137 PreCond.get(), IterSpaces[Cnt].PreCond); 6138 } 6139 Expr *N = IterSpaces[Cnt].NumIterations; 6140 SourceLocation Loc = N->getExprLoc(); 6141 AllCountsNeedLessThan32Bits &= C.getTypeSize(N->getType()) < 32; 6142 if (LastIteration32.isUsable()) 6143 LastIteration32 = SemaRef.BuildBinOp( 6144 CurScope, Loc, BO_Mul, LastIteration32.get(), 6145 SemaRef 6146 .PerformImplicitConversion(N->IgnoreImpCasts(), N->getType(), 6147 Sema::AA_Converting, 6148 /*AllowExplicit=*/true) 6149 .get()); 6150 if (LastIteration64.isUsable()) 6151 LastIteration64 = SemaRef.BuildBinOp( 6152 CurScope, Loc, BO_Mul, LastIteration64.get(), 6153 SemaRef 6154 .PerformImplicitConversion(N->IgnoreImpCasts(), N->getType(), 6155 Sema::AA_Converting, 6156 /*AllowExplicit=*/true) 6157 .get()); 6158 } 6159 6160 // Choose either the 32-bit or 64-bit version. 6161 ExprResult LastIteration = LastIteration64; 6162 if (SemaRef.getLangOpts().OpenMPOptimisticCollapse || 6163 (LastIteration32.isUsable() && 6164 C.getTypeSize(LastIteration32.get()->getType()) == 32 && 6165 (AllCountsNeedLessThan32Bits || NestedLoopCount == 1 || 6166 fitsInto( 6167 /*Bits=*/32, 6168 LastIteration32.get()->getType()->hasSignedIntegerRepresentation(), 6169 LastIteration64.get(), SemaRef)))) 6170 LastIteration = LastIteration32; 6171 QualType VType = LastIteration.get()->getType(); 6172 QualType RealVType = VType; 6173 QualType StrideVType = VType; 6174 if (isOpenMPTaskLoopDirective(DKind)) { 6175 VType = 6176 SemaRef.Context.getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/0); 6177 StrideVType = 6178 SemaRef.Context.getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/1); 6179 } 6180 6181 if (!LastIteration.isUsable()) 6182 return 0; 6183 6184 // Save the number of iterations. 6185 ExprResult NumIterations = LastIteration; 6186 { 6187 LastIteration = SemaRef.BuildBinOp( 6188 CurScope, LastIteration.get()->getExprLoc(), BO_Sub, 6189 LastIteration.get(), 6190 SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get()); 6191 if (!LastIteration.isUsable()) 6192 return 0; 6193 } 6194 6195 // Calculate the last iteration number beforehand instead of doing this on 6196 // each iteration. Do not do this if the number of iterations may be kfold-ed. 6197 llvm::APSInt Result; 6198 bool IsConstant = 6199 LastIteration.get()->isIntegerConstantExpr(Result, SemaRef.Context); 6200 ExprResult CalcLastIteration; 6201 if (!IsConstant) { 6202 ExprResult SaveRef = 6203 tryBuildCapture(SemaRef, LastIteration.get(), Captures); 6204 LastIteration = SaveRef; 6205 6206 // Prepare SaveRef + 1. 6207 NumIterations = SemaRef.BuildBinOp( 6208 CurScope, SaveRef.get()->getExprLoc(), BO_Add, SaveRef.get(), 6209 SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get()); 6210 if (!NumIterations.isUsable()) 6211 return 0; 6212 } 6213 6214 SourceLocation InitLoc = IterSpaces[0].InitSrcRange.getBegin(); 6215 6216 // Build variables passed into runtime, necessary for worksharing directives. 6217 ExprResult LB, UB, IL, ST, EUB, CombLB, CombUB, PrevLB, PrevUB, CombEUB; 6218 if (isOpenMPWorksharingDirective(DKind) || isOpenMPTaskLoopDirective(DKind) || 6219 isOpenMPDistributeDirective(DKind)) { 6220 // Lower bound variable, initialized with zero. 6221 VarDecl *LBDecl = buildVarDecl(SemaRef, InitLoc, VType, ".omp.lb"); 6222 LB = buildDeclRefExpr(SemaRef, LBDecl, VType, InitLoc); 6223 SemaRef.AddInitializerToDecl(LBDecl, 6224 SemaRef.ActOnIntegerConstant(InitLoc, 0).get(), 6225 /*DirectInit*/ false); 6226 6227 // Upper bound variable, initialized with last iteration number. 6228 VarDecl *UBDecl = buildVarDecl(SemaRef, InitLoc, VType, ".omp.ub"); 6229 UB = buildDeclRefExpr(SemaRef, UBDecl, VType, InitLoc); 6230 SemaRef.AddInitializerToDecl(UBDecl, LastIteration.get(), 6231 /*DirectInit*/ false); 6232 6233 // A 32-bit variable-flag where runtime returns 1 for the last iteration. 6234 // This will be used to implement clause 'lastprivate'. 6235 QualType Int32Ty = SemaRef.Context.getIntTypeForBitwidth(32, true); 6236 VarDecl *ILDecl = buildVarDecl(SemaRef, InitLoc, Int32Ty, ".omp.is_last"); 6237 IL = buildDeclRefExpr(SemaRef, ILDecl, Int32Ty, InitLoc); 6238 SemaRef.AddInitializerToDecl(ILDecl, 6239 SemaRef.ActOnIntegerConstant(InitLoc, 0).get(), 6240 /*DirectInit*/ false); 6241 6242 // Stride variable returned by runtime (we initialize it to 1 by default). 6243 VarDecl *STDecl = 6244 buildVarDecl(SemaRef, InitLoc, StrideVType, ".omp.stride"); 6245 ST = buildDeclRefExpr(SemaRef, STDecl, StrideVType, InitLoc); 6246 SemaRef.AddInitializerToDecl(STDecl, 6247 SemaRef.ActOnIntegerConstant(InitLoc, 1).get(), 6248 /*DirectInit*/ false); 6249 6250 // Build expression: UB = min(UB, LastIteration) 6251 // It is necessary for CodeGen of directives with static scheduling. 6252 ExprResult IsUBGreater = SemaRef.BuildBinOp(CurScope, InitLoc, BO_GT, 6253 UB.get(), LastIteration.get()); 6254 ExprResult CondOp = SemaRef.ActOnConditionalOp( 6255 LastIteration.get()->getExprLoc(), InitLoc, IsUBGreater.get(), 6256 LastIteration.get(), UB.get()); 6257 EUB = SemaRef.BuildBinOp(CurScope, InitLoc, BO_Assign, UB.get(), 6258 CondOp.get()); 6259 EUB = SemaRef.ActOnFinishFullExpr(EUB.get(), /*DiscardedValue*/ false); 6260 6261 // If we have a combined directive that combines 'distribute', 'for' or 6262 // 'simd' we need to be able to access the bounds of the schedule of the 6263 // enclosing region. E.g. in 'distribute parallel for' the bounds obtained 6264 // by scheduling 'distribute' have to be passed to the schedule of 'for'. 6265 if (isOpenMPLoopBoundSharingDirective(DKind)) { 6266 // Lower bound variable, initialized with zero. 6267 VarDecl *CombLBDecl = 6268 buildVarDecl(SemaRef, InitLoc, VType, ".omp.comb.lb"); 6269 CombLB = buildDeclRefExpr(SemaRef, CombLBDecl, VType, InitLoc); 6270 SemaRef.AddInitializerToDecl( 6271 CombLBDecl, SemaRef.ActOnIntegerConstant(InitLoc, 0).get(), 6272 /*DirectInit*/ false); 6273 6274 // Upper bound variable, initialized with last iteration number. 6275 VarDecl *CombUBDecl = 6276 buildVarDecl(SemaRef, InitLoc, VType, ".omp.comb.ub"); 6277 CombUB = buildDeclRefExpr(SemaRef, CombUBDecl, VType, InitLoc); 6278 SemaRef.AddInitializerToDecl(CombUBDecl, LastIteration.get(), 6279 /*DirectInit*/ false); 6280 6281 ExprResult CombIsUBGreater = SemaRef.BuildBinOp( 6282 CurScope, InitLoc, BO_GT, CombUB.get(), LastIteration.get()); 6283 ExprResult CombCondOp = 6284 SemaRef.ActOnConditionalOp(InitLoc, InitLoc, CombIsUBGreater.get(), 6285 LastIteration.get(), CombUB.get()); 6286 CombEUB = SemaRef.BuildBinOp(CurScope, InitLoc, BO_Assign, CombUB.get(), 6287 CombCondOp.get()); 6288 CombEUB = 6289 SemaRef.ActOnFinishFullExpr(CombEUB.get(), /*DiscardedValue*/ false); 6290 6291 const CapturedDecl *CD = cast<CapturedStmt>(AStmt)->getCapturedDecl(); 6292 // We expect to have at least 2 more parameters than the 'parallel' 6293 // directive does - the lower and upper bounds of the previous schedule. 6294 assert(CD->getNumParams() >= 4 && 6295 "Unexpected number of parameters in loop combined directive"); 6296 6297 // Set the proper type for the bounds given what we learned from the 6298 // enclosed loops. 6299 ImplicitParamDecl *PrevLBDecl = CD->getParam(/*PrevLB=*/2); 6300 ImplicitParamDecl *PrevUBDecl = CD->getParam(/*PrevUB=*/3); 6301 6302 // Previous lower and upper bounds are obtained from the region 6303 // parameters. 6304 PrevLB = 6305 buildDeclRefExpr(SemaRef, PrevLBDecl, PrevLBDecl->getType(), InitLoc); 6306 PrevUB = 6307 buildDeclRefExpr(SemaRef, PrevUBDecl, PrevUBDecl->getType(), InitLoc); 6308 } 6309 } 6310 6311 // Build the iteration variable and its initialization before loop. 6312 ExprResult IV; 6313 ExprResult Init, CombInit; 6314 { 6315 VarDecl *IVDecl = buildVarDecl(SemaRef, InitLoc, RealVType, ".omp.iv"); 6316 IV = buildDeclRefExpr(SemaRef, IVDecl, RealVType, InitLoc); 6317 Expr *RHS = 6318 (isOpenMPWorksharingDirective(DKind) || 6319 isOpenMPTaskLoopDirective(DKind) || isOpenMPDistributeDirective(DKind)) 6320 ? LB.get() 6321 : SemaRef.ActOnIntegerConstant(SourceLocation(), 0).get(); 6322 Init = SemaRef.BuildBinOp(CurScope, InitLoc, BO_Assign, IV.get(), RHS); 6323 Init = SemaRef.ActOnFinishFullExpr(Init.get(), /*DiscardedValue*/ false); 6324 6325 if (isOpenMPLoopBoundSharingDirective(DKind)) { 6326 Expr *CombRHS = 6327 (isOpenMPWorksharingDirective(DKind) || 6328 isOpenMPTaskLoopDirective(DKind) || 6329 isOpenMPDistributeDirective(DKind)) 6330 ? CombLB.get() 6331 : SemaRef.ActOnIntegerConstant(SourceLocation(), 0).get(); 6332 CombInit = 6333 SemaRef.BuildBinOp(CurScope, InitLoc, BO_Assign, IV.get(), CombRHS); 6334 CombInit = 6335 SemaRef.ActOnFinishFullExpr(CombInit.get(), /*DiscardedValue*/ false); 6336 } 6337 } 6338 6339 bool UseStrictCompare = 6340 RealVType->hasUnsignedIntegerRepresentation() && 6341 llvm::all_of(IterSpaces, [](const LoopIterationSpace &LIS) { 6342 return LIS.IsStrictCompare; 6343 }); 6344 // Loop condition (IV < NumIterations) or (IV <= UB or IV < UB + 1 (for 6345 // unsigned IV)) for worksharing loops. 6346 SourceLocation CondLoc = AStmt->getBeginLoc(); 6347 Expr *BoundUB = UB.get(); 6348 if (UseStrictCompare) { 6349 BoundUB = 6350 SemaRef 6351 .BuildBinOp(CurScope, CondLoc, BO_Add, BoundUB, 6352 SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get()) 6353 .get(); 6354 BoundUB = 6355 SemaRef.ActOnFinishFullExpr(BoundUB, /*DiscardedValue*/ false).get(); 6356 } 6357 ExprResult Cond = 6358 (isOpenMPWorksharingDirective(DKind) || 6359 isOpenMPTaskLoopDirective(DKind) || isOpenMPDistributeDirective(DKind)) 6360 ? SemaRef.BuildBinOp(CurScope, CondLoc, 6361 UseStrictCompare ? BO_LT : BO_LE, IV.get(), 6362 BoundUB) 6363 : SemaRef.BuildBinOp(CurScope, CondLoc, BO_LT, IV.get(), 6364 NumIterations.get()); 6365 ExprResult CombDistCond; 6366 if (isOpenMPLoopBoundSharingDirective(DKind)) { 6367 CombDistCond = SemaRef.BuildBinOp(CurScope, CondLoc, BO_LT, IV.get(), 6368 NumIterations.get()); 6369 } 6370 6371 ExprResult CombCond; 6372 if (isOpenMPLoopBoundSharingDirective(DKind)) { 6373 Expr *BoundCombUB = CombUB.get(); 6374 if (UseStrictCompare) { 6375 BoundCombUB = 6376 SemaRef 6377 .BuildBinOp( 6378 CurScope, CondLoc, BO_Add, BoundCombUB, 6379 SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get()) 6380 .get(); 6381 BoundCombUB = 6382 SemaRef.ActOnFinishFullExpr(BoundCombUB, /*DiscardedValue*/ false) 6383 .get(); 6384 } 6385 CombCond = 6386 SemaRef.BuildBinOp(CurScope, CondLoc, UseStrictCompare ? BO_LT : BO_LE, 6387 IV.get(), BoundCombUB); 6388 } 6389 // Loop increment (IV = IV + 1) 6390 SourceLocation IncLoc = AStmt->getBeginLoc(); 6391 ExprResult Inc = 6392 SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, IV.get(), 6393 SemaRef.ActOnIntegerConstant(IncLoc, 1).get()); 6394 if (!Inc.isUsable()) 6395 return 0; 6396 Inc = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, IV.get(), Inc.get()); 6397 Inc = SemaRef.ActOnFinishFullExpr(Inc.get(), /*DiscardedValue*/ false); 6398 if (!Inc.isUsable()) 6399 return 0; 6400 6401 // Increments for worksharing loops (LB = LB + ST; UB = UB + ST). 6402 // Used for directives with static scheduling. 6403 // In combined construct, add combined version that use CombLB and CombUB 6404 // base variables for the update 6405 ExprResult NextLB, NextUB, CombNextLB, CombNextUB; 6406 if (isOpenMPWorksharingDirective(DKind) || isOpenMPTaskLoopDirective(DKind) || 6407 isOpenMPDistributeDirective(DKind)) { 6408 // LB + ST 6409 NextLB = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, LB.get(), ST.get()); 6410 if (!NextLB.isUsable()) 6411 return 0; 6412 // LB = LB + ST 6413 NextLB = 6414 SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, LB.get(), NextLB.get()); 6415 NextLB = 6416 SemaRef.ActOnFinishFullExpr(NextLB.get(), /*DiscardedValue*/ false); 6417 if (!NextLB.isUsable()) 6418 return 0; 6419 // UB + ST 6420 NextUB = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, UB.get(), ST.get()); 6421 if (!NextUB.isUsable()) 6422 return 0; 6423 // UB = UB + ST 6424 NextUB = 6425 SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, UB.get(), NextUB.get()); 6426 NextUB = 6427 SemaRef.ActOnFinishFullExpr(NextUB.get(), /*DiscardedValue*/ false); 6428 if (!NextUB.isUsable()) 6429 return 0; 6430 if (isOpenMPLoopBoundSharingDirective(DKind)) { 6431 CombNextLB = 6432 SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, CombLB.get(), ST.get()); 6433 if (!NextLB.isUsable()) 6434 return 0; 6435 // LB = LB + ST 6436 CombNextLB = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, CombLB.get(), 6437 CombNextLB.get()); 6438 CombNextLB = SemaRef.ActOnFinishFullExpr(CombNextLB.get(), 6439 /*DiscardedValue*/ false); 6440 if (!CombNextLB.isUsable()) 6441 return 0; 6442 // UB + ST 6443 CombNextUB = 6444 SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, CombUB.get(), ST.get()); 6445 if (!CombNextUB.isUsable()) 6446 return 0; 6447 // UB = UB + ST 6448 CombNextUB = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, CombUB.get(), 6449 CombNextUB.get()); 6450 CombNextUB = SemaRef.ActOnFinishFullExpr(CombNextUB.get(), 6451 /*DiscardedValue*/ false); 6452 if (!CombNextUB.isUsable()) 6453 return 0; 6454 } 6455 } 6456 6457 // Create increment expression for distribute loop when combined in a same 6458 // directive with for as IV = IV + ST; ensure upper bound expression based 6459 // on PrevUB instead of NumIterations - used to implement 'for' when found 6460 // in combination with 'distribute', like in 'distribute parallel for' 6461 SourceLocation DistIncLoc = AStmt->getBeginLoc(); 6462 ExprResult DistCond, DistInc, PrevEUB, ParForInDistCond; 6463 if (isOpenMPLoopBoundSharingDirective(DKind)) { 6464 DistCond = SemaRef.BuildBinOp( 6465 CurScope, CondLoc, UseStrictCompare ? BO_LT : BO_LE, IV.get(), BoundUB); 6466 assert(DistCond.isUsable() && "distribute cond expr was not built"); 6467 6468 DistInc = 6469 SemaRef.BuildBinOp(CurScope, DistIncLoc, BO_Add, IV.get(), ST.get()); 6470 assert(DistInc.isUsable() && "distribute inc expr was not built"); 6471 DistInc = SemaRef.BuildBinOp(CurScope, DistIncLoc, BO_Assign, IV.get(), 6472 DistInc.get()); 6473 DistInc = 6474 SemaRef.ActOnFinishFullExpr(DistInc.get(), /*DiscardedValue*/ false); 6475 assert(DistInc.isUsable() && "distribute inc expr was not built"); 6476 6477 // Build expression: UB = min(UB, prevUB) for #for in composite or combined 6478 // construct 6479 SourceLocation DistEUBLoc = AStmt->getBeginLoc(); 6480 ExprResult IsUBGreater = 6481 SemaRef.BuildBinOp(CurScope, DistEUBLoc, BO_GT, UB.get(), PrevUB.get()); 6482 ExprResult CondOp = SemaRef.ActOnConditionalOp( 6483 DistEUBLoc, DistEUBLoc, IsUBGreater.get(), PrevUB.get(), UB.get()); 6484 PrevEUB = SemaRef.BuildBinOp(CurScope, DistIncLoc, BO_Assign, UB.get(), 6485 CondOp.get()); 6486 PrevEUB = 6487 SemaRef.ActOnFinishFullExpr(PrevEUB.get(), /*DiscardedValue*/ false); 6488 6489 // Build IV <= PrevUB or IV < PrevUB + 1 for unsigned IV to be used in 6490 // parallel for is in combination with a distribute directive with 6491 // schedule(static, 1) 6492 Expr *BoundPrevUB = PrevUB.get(); 6493 if (UseStrictCompare) { 6494 BoundPrevUB = 6495 SemaRef 6496 .BuildBinOp( 6497 CurScope, CondLoc, BO_Add, BoundPrevUB, 6498 SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get()) 6499 .get(); 6500 BoundPrevUB = 6501 SemaRef.ActOnFinishFullExpr(BoundPrevUB, /*DiscardedValue*/ false) 6502 .get(); 6503 } 6504 ParForInDistCond = 6505 SemaRef.BuildBinOp(CurScope, CondLoc, UseStrictCompare ? BO_LT : BO_LE, 6506 IV.get(), BoundPrevUB); 6507 } 6508 6509 // Build updates and final values of the loop counters. 6510 bool HasErrors = false; 6511 Built.Counters.resize(NestedLoopCount); 6512 Built.Inits.resize(NestedLoopCount); 6513 Built.Updates.resize(NestedLoopCount); 6514 Built.Finals.resize(NestedLoopCount); 6515 { 6516 // We implement the following algorithm for obtaining the 6517 // original loop iteration variable values based on the 6518 // value of the collapsed loop iteration variable IV. 6519 // 6520 // Let n+1 be the number of collapsed loops in the nest. 6521 // Iteration variables (I0, I1, .... In) 6522 // Iteration counts (N0, N1, ... Nn) 6523 // 6524 // Acc = IV; 6525 // 6526 // To compute Ik for loop k, 0 <= k <= n, generate: 6527 // Prod = N(k+1) * N(k+2) * ... * Nn; 6528 // Ik = Acc / Prod; 6529 // Acc -= Ik * Prod; 6530 // 6531 ExprResult Acc = IV; 6532 for (unsigned int Cnt = 0; Cnt < NestedLoopCount; ++Cnt) { 6533 LoopIterationSpace &IS = IterSpaces[Cnt]; 6534 SourceLocation UpdLoc = IS.IncSrcRange.getBegin(); 6535 ExprResult Iter; 6536 6537 // Compute prod 6538 ExprResult Prod = 6539 SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get(); 6540 for (unsigned int K = Cnt+1; K < NestedLoopCount; ++K) 6541 Prod = SemaRef.BuildBinOp(CurScope, UpdLoc, BO_Mul, Prod.get(), 6542 IterSpaces[K].NumIterations); 6543 6544 // Iter = Acc / Prod 6545 // If there is at least one more inner loop to avoid 6546 // multiplication by 1. 6547 if (Cnt + 1 < NestedLoopCount) 6548 Iter = SemaRef.BuildBinOp(CurScope, UpdLoc, BO_Div, 6549 Acc.get(), Prod.get()); 6550 else 6551 Iter = Acc; 6552 if (!Iter.isUsable()) { 6553 HasErrors = true; 6554 break; 6555 } 6556 6557 // Update Acc: 6558 // Acc -= Iter * Prod 6559 // Check if there is at least one more inner loop to avoid 6560 // multiplication by 1. 6561 if (Cnt + 1 < NestedLoopCount) 6562 Prod = SemaRef.BuildBinOp(CurScope, UpdLoc, BO_Mul, 6563 Iter.get(), Prod.get()); 6564 else 6565 Prod = Iter; 6566 Acc = SemaRef.BuildBinOp(CurScope, UpdLoc, BO_Sub, 6567 Acc.get(), Prod.get()); 6568 6569 // Build update: IS.CounterVar(Private) = IS.Start + Iter * IS.Step 6570 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(IS.CounterVar)->getDecl()); 6571 DeclRefExpr *CounterVar = buildDeclRefExpr( 6572 SemaRef, VD, IS.CounterVar->getType(), IS.CounterVar->getExprLoc(), 6573 /*RefersToCapture=*/true); 6574 ExprResult Init = buildCounterInit(SemaRef, CurScope, UpdLoc, CounterVar, 6575 IS.CounterInit, Captures); 6576 if (!Init.isUsable()) { 6577 HasErrors = true; 6578 break; 6579 } 6580 ExprResult Update = buildCounterUpdate( 6581 SemaRef, CurScope, UpdLoc, CounterVar, IS.CounterInit, Iter, 6582 IS.CounterStep, IS.Subtract, &Captures); 6583 if (!Update.isUsable()) { 6584 HasErrors = true; 6585 break; 6586 } 6587 6588 // Build final: IS.CounterVar = IS.Start + IS.NumIters * IS.Step 6589 ExprResult Final = buildCounterUpdate( 6590 SemaRef, CurScope, UpdLoc, CounterVar, IS.CounterInit, 6591 IS.NumIterations, IS.CounterStep, IS.Subtract, &Captures); 6592 if (!Final.isUsable()) { 6593 HasErrors = true; 6594 break; 6595 } 6596 6597 if (!Update.isUsable() || !Final.isUsable()) { 6598 HasErrors = true; 6599 break; 6600 } 6601 // Save results 6602 Built.Counters[Cnt] = IS.CounterVar; 6603 Built.PrivateCounters[Cnt] = IS.PrivateCounterVar; 6604 Built.Inits[Cnt] = Init.get(); 6605 Built.Updates[Cnt] = Update.get(); 6606 Built.Finals[Cnt] = Final.get(); 6607 } 6608 } 6609 6610 if (HasErrors) 6611 return 0; 6612 6613 // Save results 6614 Built.IterationVarRef = IV.get(); 6615 Built.LastIteration = LastIteration.get(); 6616 Built.NumIterations = NumIterations.get(); 6617 Built.CalcLastIteration = SemaRef 6618 .ActOnFinishFullExpr(CalcLastIteration.get(), 6619 /*DiscardedValue*/ false) 6620 .get(); 6621 Built.PreCond = PreCond.get(); 6622 Built.PreInits = buildPreInits(C, Captures); 6623 Built.Cond = Cond.get(); 6624 Built.Init = Init.get(); 6625 Built.Inc = Inc.get(); 6626 Built.LB = LB.get(); 6627 Built.UB = UB.get(); 6628 Built.IL = IL.get(); 6629 Built.ST = ST.get(); 6630 Built.EUB = EUB.get(); 6631 Built.NLB = NextLB.get(); 6632 Built.NUB = NextUB.get(); 6633 Built.PrevLB = PrevLB.get(); 6634 Built.PrevUB = PrevUB.get(); 6635 Built.DistInc = DistInc.get(); 6636 Built.PrevEUB = PrevEUB.get(); 6637 Built.DistCombinedFields.LB = CombLB.get(); 6638 Built.DistCombinedFields.UB = CombUB.get(); 6639 Built.DistCombinedFields.EUB = CombEUB.get(); 6640 Built.DistCombinedFields.Init = CombInit.get(); 6641 Built.DistCombinedFields.Cond = CombCond.get(); 6642 Built.DistCombinedFields.NLB = CombNextLB.get(); 6643 Built.DistCombinedFields.NUB = CombNextUB.get(); 6644 Built.DistCombinedFields.DistCond = CombDistCond.get(); 6645 Built.DistCombinedFields.ParForInDistCond = ParForInDistCond.get(); 6646 6647 return NestedLoopCount; 6648 } 6649 6650 static Expr *getCollapseNumberExpr(ArrayRef<OMPClause *> Clauses) { 6651 auto CollapseClauses = 6652 OMPExecutableDirective::getClausesOfKind<OMPCollapseClause>(Clauses); 6653 if (CollapseClauses.begin() != CollapseClauses.end()) 6654 return (*CollapseClauses.begin())->getNumForLoops(); 6655 return nullptr; 6656 } 6657 6658 static Expr *getOrderedNumberExpr(ArrayRef<OMPClause *> Clauses) { 6659 auto OrderedClauses = 6660 OMPExecutableDirective::getClausesOfKind<OMPOrderedClause>(Clauses); 6661 if (OrderedClauses.begin() != OrderedClauses.end()) 6662 return (*OrderedClauses.begin())->getNumForLoops(); 6663 return nullptr; 6664 } 6665 6666 static bool checkSimdlenSafelenSpecified(Sema &S, 6667 const ArrayRef<OMPClause *> Clauses) { 6668 const OMPSafelenClause *Safelen = nullptr; 6669 const OMPSimdlenClause *Simdlen = nullptr; 6670 6671 for (const OMPClause *Clause : Clauses) { 6672 if (Clause->getClauseKind() == OMPC_safelen) 6673 Safelen = cast<OMPSafelenClause>(Clause); 6674 else if (Clause->getClauseKind() == OMPC_simdlen) 6675 Simdlen = cast<OMPSimdlenClause>(Clause); 6676 if (Safelen && Simdlen) 6677 break; 6678 } 6679 6680 if (Simdlen && Safelen) { 6681 const Expr *SimdlenLength = Simdlen->getSimdlen(); 6682 const Expr *SafelenLength = Safelen->getSafelen(); 6683 if (SimdlenLength->isValueDependent() || SimdlenLength->isTypeDependent() || 6684 SimdlenLength->isInstantiationDependent() || 6685 SimdlenLength->containsUnexpandedParameterPack()) 6686 return false; 6687 if (SafelenLength->isValueDependent() || SafelenLength->isTypeDependent() || 6688 SafelenLength->isInstantiationDependent() || 6689 SafelenLength->containsUnexpandedParameterPack()) 6690 return false; 6691 Expr::EvalResult SimdlenResult, SafelenResult; 6692 SimdlenLength->EvaluateAsInt(SimdlenResult, S.Context); 6693 SafelenLength->EvaluateAsInt(SafelenResult, S.Context); 6694 llvm::APSInt SimdlenRes = SimdlenResult.Val.getInt(); 6695 llvm::APSInt SafelenRes = SafelenResult.Val.getInt(); 6696 // OpenMP 4.5 [2.8.1, simd Construct, Restrictions] 6697 // If both simdlen and safelen clauses are specified, the value of the 6698 // simdlen parameter must be less than or equal to the value of the safelen 6699 // parameter. 6700 if (SimdlenRes > SafelenRes) { 6701 S.Diag(SimdlenLength->getExprLoc(), 6702 diag::err_omp_wrong_simdlen_safelen_values) 6703 << SimdlenLength->getSourceRange() << SafelenLength->getSourceRange(); 6704 return true; 6705 } 6706 } 6707 return false; 6708 } 6709 6710 StmtResult 6711 Sema::ActOnOpenMPSimdDirective(ArrayRef<OMPClause *> Clauses, Stmt *AStmt, 6712 SourceLocation StartLoc, SourceLocation EndLoc, 6713 VarsWithInheritedDSAType &VarsWithImplicitDSA) { 6714 if (!AStmt) 6715 return StmtError(); 6716 6717 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected"); 6718 OMPLoopDirective::HelperExprs B; 6719 // In presence of clause 'collapse' or 'ordered' with number of loops, it will 6720 // define the nested loops number. 6721 unsigned NestedLoopCount = checkOpenMPLoop( 6722 OMPD_simd, getCollapseNumberExpr(Clauses), getOrderedNumberExpr(Clauses), 6723 AStmt, *this, *DSAStack, VarsWithImplicitDSA, B); 6724 if (NestedLoopCount == 0) 6725 return StmtError(); 6726 6727 assert((CurContext->isDependentContext() || B.builtAll()) && 6728 "omp simd loop exprs were not built"); 6729 6730 if (!CurContext->isDependentContext()) { 6731 // Finalize the clauses that need pre-built expressions for CodeGen. 6732 for (OMPClause *C : Clauses) { 6733 if (auto *LC = dyn_cast<OMPLinearClause>(C)) 6734 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef), 6735 B.NumIterations, *this, CurScope, 6736 DSAStack)) 6737 return StmtError(); 6738 } 6739 } 6740 6741 if (checkSimdlenSafelenSpecified(*this, Clauses)) 6742 return StmtError(); 6743 6744 setFunctionHasBranchProtectedScope(); 6745 return OMPSimdDirective::Create(Context, StartLoc, EndLoc, NestedLoopCount, 6746 Clauses, AStmt, B); 6747 } 6748 6749 StmtResult 6750 Sema::ActOnOpenMPForDirective(ArrayRef<OMPClause *> Clauses, Stmt *AStmt, 6751 SourceLocation StartLoc, SourceLocation EndLoc, 6752 VarsWithInheritedDSAType &VarsWithImplicitDSA) { 6753 if (!AStmt) 6754 return StmtError(); 6755 6756 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected"); 6757 OMPLoopDirective::HelperExprs B; 6758 // In presence of clause 'collapse' or 'ordered' with number of loops, it will 6759 // define the nested loops number. 6760 unsigned NestedLoopCount = checkOpenMPLoop( 6761 OMPD_for, getCollapseNumberExpr(Clauses), getOrderedNumberExpr(Clauses), 6762 AStmt, *this, *DSAStack, VarsWithImplicitDSA, B); 6763 if (NestedLoopCount == 0) 6764 return StmtError(); 6765 6766 assert((CurContext->isDependentContext() || B.builtAll()) && 6767 "omp for loop exprs were not built"); 6768 6769 if (!CurContext->isDependentContext()) { 6770 // Finalize the clauses that need pre-built expressions for CodeGen. 6771 for (OMPClause *C : Clauses) { 6772 if (auto *LC = dyn_cast<OMPLinearClause>(C)) 6773 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef), 6774 B.NumIterations, *this, CurScope, 6775 DSAStack)) 6776 return StmtError(); 6777 } 6778 } 6779 6780 setFunctionHasBranchProtectedScope(); 6781 return OMPForDirective::Create(Context, StartLoc, EndLoc, NestedLoopCount, 6782 Clauses, AStmt, B, DSAStack->isCancelRegion()); 6783 } 6784 6785 StmtResult Sema::ActOnOpenMPForSimdDirective( 6786 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, 6787 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) { 6788 if (!AStmt) 6789 return StmtError(); 6790 6791 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected"); 6792 OMPLoopDirective::HelperExprs B; 6793 // In presence of clause 'collapse' or 'ordered' with number of loops, it will 6794 // define the nested loops number. 6795 unsigned NestedLoopCount = 6796 checkOpenMPLoop(OMPD_for_simd, getCollapseNumberExpr(Clauses), 6797 getOrderedNumberExpr(Clauses), AStmt, *this, *DSAStack, 6798 VarsWithImplicitDSA, B); 6799 if (NestedLoopCount == 0) 6800 return StmtError(); 6801 6802 assert((CurContext->isDependentContext() || B.builtAll()) && 6803 "omp for simd loop exprs were not built"); 6804 6805 if (!CurContext->isDependentContext()) { 6806 // Finalize the clauses that need pre-built expressions for CodeGen. 6807 for (OMPClause *C : Clauses) { 6808 if (auto *LC = dyn_cast<OMPLinearClause>(C)) 6809 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef), 6810 B.NumIterations, *this, CurScope, 6811 DSAStack)) 6812 return StmtError(); 6813 } 6814 } 6815 6816 if (checkSimdlenSafelenSpecified(*this, Clauses)) 6817 return StmtError(); 6818 6819 setFunctionHasBranchProtectedScope(); 6820 return OMPForSimdDirective::Create(Context, StartLoc, EndLoc, NestedLoopCount, 6821 Clauses, AStmt, B); 6822 } 6823 6824 StmtResult Sema::ActOnOpenMPSectionsDirective(ArrayRef<OMPClause *> Clauses, 6825 Stmt *AStmt, 6826 SourceLocation StartLoc, 6827 SourceLocation EndLoc) { 6828 if (!AStmt) 6829 return StmtError(); 6830 6831 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected"); 6832 auto BaseStmt = AStmt; 6833 while (auto *CS = dyn_cast_or_null<CapturedStmt>(BaseStmt)) 6834 BaseStmt = CS->getCapturedStmt(); 6835 if (auto *C = dyn_cast_or_null<CompoundStmt>(BaseStmt)) { 6836 auto S = C->children(); 6837 if (S.begin() == S.end()) 6838 return StmtError(); 6839 // All associated statements must be '#pragma omp section' except for 6840 // the first one. 6841 for (Stmt *SectionStmt : llvm::make_range(std::next(S.begin()), S.end())) { 6842 if (!SectionStmt || !isa<OMPSectionDirective>(SectionStmt)) { 6843 if (SectionStmt) 6844 Diag(SectionStmt->getBeginLoc(), 6845 diag::err_omp_sections_substmt_not_section); 6846 return StmtError(); 6847 } 6848 cast<OMPSectionDirective>(SectionStmt) 6849 ->setHasCancel(DSAStack->isCancelRegion()); 6850 } 6851 } else { 6852 Diag(AStmt->getBeginLoc(), diag::err_omp_sections_not_compound_stmt); 6853 return StmtError(); 6854 } 6855 6856 setFunctionHasBranchProtectedScope(); 6857 6858 return OMPSectionsDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt, 6859 DSAStack->isCancelRegion()); 6860 } 6861 6862 StmtResult Sema::ActOnOpenMPSectionDirective(Stmt *AStmt, 6863 SourceLocation StartLoc, 6864 SourceLocation EndLoc) { 6865 if (!AStmt) 6866 return StmtError(); 6867 6868 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected"); 6869 6870 setFunctionHasBranchProtectedScope(); 6871 DSAStack->setParentCancelRegion(DSAStack->isCancelRegion()); 6872 6873 return OMPSectionDirective::Create(Context, StartLoc, EndLoc, AStmt, 6874 DSAStack->isCancelRegion()); 6875 } 6876 6877 StmtResult Sema::ActOnOpenMPSingleDirective(ArrayRef<OMPClause *> Clauses, 6878 Stmt *AStmt, 6879 SourceLocation StartLoc, 6880 SourceLocation EndLoc) { 6881 if (!AStmt) 6882 return StmtError(); 6883 6884 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected"); 6885 6886 setFunctionHasBranchProtectedScope(); 6887 6888 // OpenMP [2.7.3, single Construct, Restrictions] 6889 // The copyprivate clause must not be used with the nowait clause. 6890 const OMPClause *Nowait = nullptr; 6891 const OMPClause *Copyprivate = nullptr; 6892 for (const OMPClause *Clause : Clauses) { 6893 if (Clause->getClauseKind() == OMPC_nowait) 6894 Nowait = Clause; 6895 else if (Clause->getClauseKind() == OMPC_copyprivate) 6896 Copyprivate = Clause; 6897 if (Copyprivate && Nowait) { 6898 Diag(Copyprivate->getBeginLoc(), 6899 diag::err_omp_single_copyprivate_with_nowait); 6900 Diag(Nowait->getBeginLoc(), diag::note_omp_nowait_clause_here); 6901 return StmtError(); 6902 } 6903 } 6904 6905 return OMPSingleDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt); 6906 } 6907 6908 StmtResult Sema::ActOnOpenMPMasterDirective(Stmt *AStmt, 6909 SourceLocation StartLoc, 6910 SourceLocation EndLoc) { 6911 if (!AStmt) 6912 return StmtError(); 6913 6914 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected"); 6915 6916 setFunctionHasBranchProtectedScope(); 6917 6918 return OMPMasterDirective::Create(Context, StartLoc, EndLoc, AStmt); 6919 } 6920 6921 StmtResult Sema::ActOnOpenMPCriticalDirective( 6922 const DeclarationNameInfo &DirName, ArrayRef<OMPClause *> Clauses, 6923 Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc) { 6924 if (!AStmt) 6925 return StmtError(); 6926 6927 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected"); 6928 6929 bool ErrorFound = false; 6930 llvm::APSInt Hint; 6931 SourceLocation HintLoc; 6932 bool DependentHint = false; 6933 for (const OMPClause *C : Clauses) { 6934 if (C->getClauseKind() == OMPC_hint) { 6935 if (!DirName.getName()) { 6936 Diag(C->getBeginLoc(), diag::err_omp_hint_clause_no_name); 6937 ErrorFound = true; 6938 } 6939 Expr *E = cast<OMPHintClause>(C)->getHint(); 6940 if (E->isTypeDependent() || E->isValueDependent() || 6941 E->isInstantiationDependent()) { 6942 DependentHint = true; 6943 } else { 6944 Hint = E->EvaluateKnownConstInt(Context); 6945 HintLoc = C->getBeginLoc(); 6946 } 6947 } 6948 } 6949 if (ErrorFound) 6950 return StmtError(); 6951 const auto Pair = DSAStack->getCriticalWithHint(DirName); 6952 if (Pair.first && DirName.getName() && !DependentHint) { 6953 if (llvm::APSInt::compareValues(Hint, Pair.second) != 0) { 6954 Diag(StartLoc, diag::err_omp_critical_with_hint); 6955 if (HintLoc.isValid()) 6956 Diag(HintLoc, diag::note_omp_critical_hint_here) 6957 << 0 << Hint.toString(/*Radix=*/10, /*Signed=*/false); 6958 else 6959 Diag(StartLoc, diag::note_omp_critical_no_hint) << 0; 6960 if (const auto *C = Pair.first->getSingleClause<OMPHintClause>()) { 6961 Diag(C->getBeginLoc(), diag::note_omp_critical_hint_here) 6962 << 1 6963 << C->getHint()->EvaluateKnownConstInt(Context).toString( 6964 /*Radix=*/10, /*Signed=*/false); 6965 } else { 6966 Diag(Pair.first->getBeginLoc(), diag::note_omp_critical_no_hint) << 1; 6967 } 6968 } 6969 } 6970 6971 setFunctionHasBranchProtectedScope(); 6972 6973 auto *Dir = OMPCriticalDirective::Create(Context, DirName, StartLoc, EndLoc, 6974 Clauses, AStmt); 6975 if (!Pair.first && DirName.getName() && !DependentHint) 6976 DSAStack->addCriticalWithHint(Dir, Hint); 6977 return Dir; 6978 } 6979 6980 StmtResult Sema::ActOnOpenMPParallelForDirective( 6981 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, 6982 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) { 6983 if (!AStmt) 6984 return StmtError(); 6985 6986 auto *CS = cast<CapturedStmt>(AStmt); 6987 // 1.2.2 OpenMP Language Terminology 6988 // Structured block - An executable statement with a single entry at the 6989 // top and a single exit at the bottom. 6990 // The point of exit cannot be a branch out of the structured block. 6991 // longjmp() and throw() must not violate the entry/exit criteria. 6992 CS->getCapturedDecl()->setNothrow(); 6993 6994 OMPLoopDirective::HelperExprs B; 6995 // In presence of clause 'collapse' or 'ordered' with number of loops, it will 6996 // define the nested loops number. 6997 unsigned NestedLoopCount = 6998 checkOpenMPLoop(OMPD_parallel_for, getCollapseNumberExpr(Clauses), 6999 getOrderedNumberExpr(Clauses), AStmt, *this, *DSAStack, 7000 VarsWithImplicitDSA, B); 7001 if (NestedLoopCount == 0) 7002 return StmtError(); 7003 7004 assert((CurContext->isDependentContext() || B.builtAll()) && 7005 "omp parallel for loop exprs were not built"); 7006 7007 if (!CurContext->isDependentContext()) { 7008 // Finalize the clauses that need pre-built expressions for CodeGen. 7009 for (OMPClause *C : Clauses) { 7010 if (auto *LC = dyn_cast<OMPLinearClause>(C)) 7011 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef), 7012 B.NumIterations, *this, CurScope, 7013 DSAStack)) 7014 return StmtError(); 7015 } 7016 } 7017 7018 setFunctionHasBranchProtectedScope(); 7019 return OMPParallelForDirective::Create(Context, StartLoc, EndLoc, 7020 NestedLoopCount, Clauses, AStmt, B, 7021 DSAStack->isCancelRegion()); 7022 } 7023 7024 StmtResult Sema::ActOnOpenMPParallelForSimdDirective( 7025 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, 7026 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) { 7027 if (!AStmt) 7028 return StmtError(); 7029 7030 auto *CS = cast<CapturedStmt>(AStmt); 7031 // 1.2.2 OpenMP Language Terminology 7032 // Structured block - An executable statement with a single entry at the 7033 // top and a single exit at the bottom. 7034 // The point of exit cannot be a branch out of the structured block. 7035 // longjmp() and throw() must not violate the entry/exit criteria. 7036 CS->getCapturedDecl()->setNothrow(); 7037 7038 OMPLoopDirective::HelperExprs B; 7039 // In presence of clause 'collapse' or 'ordered' with number of loops, it will 7040 // define the nested loops number. 7041 unsigned NestedLoopCount = 7042 checkOpenMPLoop(OMPD_parallel_for_simd, getCollapseNumberExpr(Clauses), 7043 getOrderedNumberExpr(Clauses), AStmt, *this, *DSAStack, 7044 VarsWithImplicitDSA, B); 7045 if (NestedLoopCount == 0) 7046 return StmtError(); 7047 7048 if (!CurContext->isDependentContext()) { 7049 // Finalize the clauses that need pre-built expressions for CodeGen. 7050 for (OMPClause *C : Clauses) { 7051 if (auto *LC = dyn_cast<OMPLinearClause>(C)) 7052 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef), 7053 B.NumIterations, *this, CurScope, 7054 DSAStack)) 7055 return StmtError(); 7056 } 7057 } 7058 7059 if (checkSimdlenSafelenSpecified(*this, Clauses)) 7060 return StmtError(); 7061 7062 setFunctionHasBranchProtectedScope(); 7063 return OMPParallelForSimdDirective::Create( 7064 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B); 7065 } 7066 7067 StmtResult 7068 Sema::ActOnOpenMPParallelSectionsDirective(ArrayRef<OMPClause *> Clauses, 7069 Stmt *AStmt, SourceLocation StartLoc, 7070 SourceLocation EndLoc) { 7071 if (!AStmt) 7072 return StmtError(); 7073 7074 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected"); 7075 auto BaseStmt = AStmt; 7076 while (auto *CS = dyn_cast_or_null<CapturedStmt>(BaseStmt)) 7077 BaseStmt = CS->getCapturedStmt(); 7078 if (auto *C = dyn_cast_or_null<CompoundStmt>(BaseStmt)) { 7079 auto S = C->children(); 7080 if (S.begin() == S.end()) 7081 return StmtError(); 7082 // All associated statements must be '#pragma omp section' except for 7083 // the first one. 7084 for (Stmt *SectionStmt : llvm::make_range(std::next(S.begin()), S.end())) { 7085 if (!SectionStmt || !isa<OMPSectionDirective>(SectionStmt)) { 7086 if (SectionStmt) 7087 Diag(SectionStmt->getBeginLoc(), 7088 diag::err_omp_parallel_sections_substmt_not_section); 7089 return StmtError(); 7090 } 7091 cast<OMPSectionDirective>(SectionStmt) 7092 ->setHasCancel(DSAStack->isCancelRegion()); 7093 } 7094 } else { 7095 Diag(AStmt->getBeginLoc(), 7096 diag::err_omp_parallel_sections_not_compound_stmt); 7097 return StmtError(); 7098 } 7099 7100 setFunctionHasBranchProtectedScope(); 7101 7102 return OMPParallelSectionsDirective::Create( 7103 Context, StartLoc, EndLoc, Clauses, AStmt, DSAStack->isCancelRegion()); 7104 } 7105 7106 StmtResult Sema::ActOnOpenMPTaskDirective(ArrayRef<OMPClause *> Clauses, 7107 Stmt *AStmt, SourceLocation StartLoc, 7108 SourceLocation EndLoc) { 7109 if (!AStmt) 7110 return StmtError(); 7111 7112 auto *CS = cast<CapturedStmt>(AStmt); 7113 // 1.2.2 OpenMP Language Terminology 7114 // Structured block - An executable statement with a single entry at the 7115 // top and a single exit at the bottom. 7116 // The point of exit cannot be a branch out of the structured block. 7117 // longjmp() and throw() must not violate the entry/exit criteria. 7118 CS->getCapturedDecl()->setNothrow(); 7119 7120 setFunctionHasBranchProtectedScope(); 7121 7122 return OMPTaskDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt, 7123 DSAStack->isCancelRegion()); 7124 } 7125 7126 StmtResult Sema::ActOnOpenMPTaskyieldDirective(SourceLocation StartLoc, 7127 SourceLocation EndLoc) { 7128 return OMPTaskyieldDirective::Create(Context, StartLoc, EndLoc); 7129 } 7130 7131 StmtResult Sema::ActOnOpenMPBarrierDirective(SourceLocation StartLoc, 7132 SourceLocation EndLoc) { 7133 return OMPBarrierDirective::Create(Context, StartLoc, EndLoc); 7134 } 7135 7136 StmtResult Sema::ActOnOpenMPTaskwaitDirective(SourceLocation StartLoc, 7137 SourceLocation EndLoc) { 7138 return OMPTaskwaitDirective::Create(Context, StartLoc, EndLoc); 7139 } 7140 7141 StmtResult Sema::ActOnOpenMPTaskgroupDirective(ArrayRef<OMPClause *> Clauses, 7142 Stmt *AStmt, 7143 SourceLocation StartLoc, 7144 SourceLocation EndLoc) { 7145 if (!AStmt) 7146 return StmtError(); 7147 7148 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected"); 7149 7150 setFunctionHasBranchProtectedScope(); 7151 7152 return OMPTaskgroupDirective::Create(Context, StartLoc, EndLoc, Clauses, 7153 AStmt, 7154 DSAStack->getTaskgroupReductionRef()); 7155 } 7156 7157 StmtResult Sema::ActOnOpenMPFlushDirective(ArrayRef<OMPClause *> Clauses, 7158 SourceLocation StartLoc, 7159 SourceLocation EndLoc) { 7160 assert(Clauses.size() <= 1 && "Extra clauses in flush directive"); 7161 return OMPFlushDirective::Create(Context, StartLoc, EndLoc, Clauses); 7162 } 7163 7164 StmtResult Sema::ActOnOpenMPOrderedDirective(ArrayRef<OMPClause *> Clauses, 7165 Stmt *AStmt, 7166 SourceLocation StartLoc, 7167 SourceLocation EndLoc) { 7168 const OMPClause *DependFound = nullptr; 7169 const OMPClause *DependSourceClause = nullptr; 7170 const OMPClause *DependSinkClause = nullptr; 7171 bool ErrorFound = false; 7172 const OMPThreadsClause *TC = nullptr; 7173 const OMPSIMDClause *SC = nullptr; 7174 for (const OMPClause *C : Clauses) { 7175 if (auto *DC = dyn_cast<OMPDependClause>(C)) { 7176 DependFound = C; 7177 if (DC->getDependencyKind() == OMPC_DEPEND_source) { 7178 if (DependSourceClause) { 7179 Diag(C->getBeginLoc(), diag::err_omp_more_one_clause) 7180 << getOpenMPDirectiveName(OMPD_ordered) 7181 << getOpenMPClauseName(OMPC_depend) << 2; 7182 ErrorFound = true; 7183 } else { 7184 DependSourceClause = C; 7185 } 7186 if (DependSinkClause) { 7187 Diag(C->getBeginLoc(), diag::err_omp_depend_sink_source_not_allowed) 7188 << 0; 7189 ErrorFound = true; 7190 } 7191 } else if (DC->getDependencyKind() == OMPC_DEPEND_sink) { 7192 if (DependSourceClause) { 7193 Diag(C->getBeginLoc(), diag::err_omp_depend_sink_source_not_allowed) 7194 << 1; 7195 ErrorFound = true; 7196 } 7197 DependSinkClause = C; 7198 } 7199 } else if (C->getClauseKind() == OMPC_threads) { 7200 TC = cast<OMPThreadsClause>(C); 7201 } else if (C->getClauseKind() == OMPC_simd) { 7202 SC = cast<OMPSIMDClause>(C); 7203 } 7204 } 7205 if (!ErrorFound && !SC && 7206 isOpenMPSimdDirective(DSAStack->getParentDirective())) { 7207 // OpenMP [2.8.1,simd Construct, Restrictions] 7208 // An ordered construct with the simd clause is the only OpenMP construct 7209 // that can appear in the simd region. 7210 Diag(StartLoc, diag::err_omp_prohibited_region_simd); 7211 ErrorFound = true; 7212 } else if (DependFound && (TC || SC)) { 7213 Diag(DependFound->getBeginLoc(), diag::err_omp_depend_clause_thread_simd) 7214 << getOpenMPClauseName(TC ? TC->getClauseKind() : SC->getClauseKind()); 7215 ErrorFound = true; 7216 } else if (DependFound && !DSAStack->getParentOrderedRegionParam().first) { 7217 Diag(DependFound->getBeginLoc(), 7218 diag::err_omp_ordered_directive_without_param); 7219 ErrorFound = true; 7220 } else if (TC || Clauses.empty()) { 7221 if (const Expr *Param = DSAStack->getParentOrderedRegionParam().first) { 7222 SourceLocation ErrLoc = TC ? TC->getBeginLoc() : StartLoc; 7223 Diag(ErrLoc, diag::err_omp_ordered_directive_with_param) 7224 << (TC != nullptr); 7225 Diag(Param->getBeginLoc(), diag::note_omp_ordered_param); 7226 ErrorFound = true; 7227 } 7228 } 7229 if ((!AStmt && !DependFound) || ErrorFound) 7230 return StmtError(); 7231 7232 if (AStmt) { 7233 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected"); 7234 7235 setFunctionHasBranchProtectedScope(); 7236 } 7237 7238 return OMPOrderedDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt); 7239 } 7240 7241 namespace { 7242 /// Helper class for checking expression in 'omp atomic [update]' 7243 /// construct. 7244 class OpenMPAtomicUpdateChecker { 7245 /// Error results for atomic update expressions. 7246 enum ExprAnalysisErrorCode { 7247 /// A statement is not an expression statement. 7248 NotAnExpression, 7249 /// Expression is not builtin binary or unary operation. 7250 NotABinaryOrUnaryExpression, 7251 /// Unary operation is not post-/pre- increment/decrement operation. 7252 NotAnUnaryIncDecExpression, 7253 /// An expression is not of scalar type. 7254 NotAScalarType, 7255 /// A binary operation is not an assignment operation. 7256 NotAnAssignmentOp, 7257 /// RHS part of the binary operation is not a binary expression. 7258 NotABinaryExpression, 7259 /// RHS part is not additive/multiplicative/shift/biwise binary 7260 /// expression. 7261 NotABinaryOperator, 7262 /// RHS binary operation does not have reference to the updated LHS 7263 /// part. 7264 NotAnUpdateExpression, 7265 /// No errors is found. 7266 NoError 7267 }; 7268 /// Reference to Sema. 7269 Sema &SemaRef; 7270 /// A location for note diagnostics (when error is found). 7271 SourceLocation NoteLoc; 7272 /// 'x' lvalue part of the source atomic expression. 7273 Expr *X; 7274 /// 'expr' rvalue part of the source atomic expression. 7275 Expr *E; 7276 /// Helper expression of the form 7277 /// 'OpaqueValueExpr(x) binop OpaqueValueExpr(expr)' or 7278 /// 'OpaqueValueExpr(expr) binop OpaqueValueExpr(x)'. 7279 Expr *UpdateExpr; 7280 /// Is 'x' a LHS in a RHS part of full update expression. It is 7281 /// important for non-associative operations. 7282 bool IsXLHSInRHSPart; 7283 BinaryOperatorKind Op; 7284 SourceLocation OpLoc; 7285 /// true if the source expression is a postfix unary operation, false 7286 /// if it is a prefix unary operation. 7287 bool IsPostfixUpdate; 7288 7289 public: 7290 OpenMPAtomicUpdateChecker(Sema &SemaRef) 7291 : SemaRef(SemaRef), X(nullptr), E(nullptr), UpdateExpr(nullptr), 7292 IsXLHSInRHSPart(false), Op(BO_PtrMemD), IsPostfixUpdate(false) {} 7293 /// Check specified statement that it is suitable for 'atomic update' 7294 /// constructs and extract 'x', 'expr' and Operation from the original 7295 /// expression. If DiagId and NoteId == 0, then only check is performed 7296 /// without error notification. 7297 /// \param DiagId Diagnostic which should be emitted if error is found. 7298 /// \param NoteId Diagnostic note for the main error message. 7299 /// \return true if statement is not an update expression, false otherwise. 7300 bool checkStatement(Stmt *S, unsigned DiagId = 0, unsigned NoteId = 0); 7301 /// Return the 'x' lvalue part of the source atomic expression. 7302 Expr *getX() const { return X; } 7303 /// Return the 'expr' rvalue part of the source atomic expression. 7304 Expr *getExpr() const { return E; } 7305 /// Return the update expression used in calculation of the updated 7306 /// value. Always has form 'OpaqueValueExpr(x) binop OpaqueValueExpr(expr)' or 7307 /// 'OpaqueValueExpr(expr) binop OpaqueValueExpr(x)'. 7308 Expr *getUpdateExpr() const { return UpdateExpr; } 7309 /// Return true if 'x' is LHS in RHS part of full update expression, 7310 /// false otherwise. 7311 bool isXLHSInRHSPart() const { return IsXLHSInRHSPart; } 7312 7313 /// true if the source expression is a postfix unary operation, false 7314 /// if it is a prefix unary operation. 7315 bool isPostfixUpdate() const { return IsPostfixUpdate; } 7316 7317 private: 7318 bool checkBinaryOperation(BinaryOperator *AtomicBinOp, unsigned DiagId = 0, 7319 unsigned NoteId = 0); 7320 }; 7321 } // namespace 7322 7323 bool OpenMPAtomicUpdateChecker::checkBinaryOperation( 7324 BinaryOperator *AtomicBinOp, unsigned DiagId, unsigned NoteId) { 7325 ExprAnalysisErrorCode ErrorFound = NoError; 7326 SourceLocation ErrorLoc, NoteLoc; 7327 SourceRange ErrorRange, NoteRange; 7328 // Allowed constructs are: 7329 // x = x binop expr; 7330 // x = expr binop x; 7331 if (AtomicBinOp->getOpcode() == BO_Assign) { 7332 X = AtomicBinOp->getLHS(); 7333 if (const auto *AtomicInnerBinOp = dyn_cast<BinaryOperator>( 7334 AtomicBinOp->getRHS()->IgnoreParenImpCasts())) { 7335 if (AtomicInnerBinOp->isMultiplicativeOp() || 7336 AtomicInnerBinOp->isAdditiveOp() || AtomicInnerBinOp->isShiftOp() || 7337 AtomicInnerBinOp->isBitwiseOp()) { 7338 Op = AtomicInnerBinOp->getOpcode(); 7339 OpLoc = AtomicInnerBinOp->getOperatorLoc(); 7340 Expr *LHS = AtomicInnerBinOp->getLHS(); 7341 Expr *RHS = AtomicInnerBinOp->getRHS(); 7342 llvm::FoldingSetNodeID XId, LHSId, RHSId; 7343 X->IgnoreParenImpCasts()->Profile(XId, SemaRef.getASTContext(), 7344 /*Canonical=*/true); 7345 LHS->IgnoreParenImpCasts()->Profile(LHSId, SemaRef.getASTContext(), 7346 /*Canonical=*/true); 7347 RHS->IgnoreParenImpCasts()->Profile(RHSId, SemaRef.getASTContext(), 7348 /*Canonical=*/true); 7349 if (XId == LHSId) { 7350 E = RHS; 7351 IsXLHSInRHSPart = true; 7352 } else if (XId == RHSId) { 7353 E = LHS; 7354 IsXLHSInRHSPart = false; 7355 } else { 7356 ErrorLoc = AtomicInnerBinOp->getExprLoc(); 7357 ErrorRange = AtomicInnerBinOp->getSourceRange(); 7358 NoteLoc = X->getExprLoc(); 7359 NoteRange = X->getSourceRange(); 7360 ErrorFound = NotAnUpdateExpression; 7361 } 7362 } else { 7363 ErrorLoc = AtomicInnerBinOp->getExprLoc(); 7364 ErrorRange = AtomicInnerBinOp->getSourceRange(); 7365 NoteLoc = AtomicInnerBinOp->getOperatorLoc(); 7366 NoteRange = SourceRange(NoteLoc, NoteLoc); 7367 ErrorFound = NotABinaryOperator; 7368 } 7369 } else { 7370 NoteLoc = ErrorLoc = AtomicBinOp->getRHS()->getExprLoc(); 7371 NoteRange = ErrorRange = AtomicBinOp->getRHS()->getSourceRange(); 7372 ErrorFound = NotABinaryExpression; 7373 } 7374 } else { 7375 ErrorLoc = AtomicBinOp->getExprLoc(); 7376 ErrorRange = AtomicBinOp->getSourceRange(); 7377 NoteLoc = AtomicBinOp->getOperatorLoc(); 7378 NoteRange = SourceRange(NoteLoc, NoteLoc); 7379 ErrorFound = NotAnAssignmentOp; 7380 } 7381 if (ErrorFound != NoError && DiagId != 0 && NoteId != 0) { 7382 SemaRef.Diag(ErrorLoc, DiagId) << ErrorRange; 7383 SemaRef.Diag(NoteLoc, NoteId) << ErrorFound << NoteRange; 7384 return true; 7385 } 7386 if (SemaRef.CurContext->isDependentContext()) 7387 E = X = UpdateExpr = nullptr; 7388 return ErrorFound != NoError; 7389 } 7390 7391 bool OpenMPAtomicUpdateChecker::checkStatement(Stmt *S, unsigned DiagId, 7392 unsigned NoteId) { 7393 ExprAnalysisErrorCode ErrorFound = NoError; 7394 SourceLocation ErrorLoc, NoteLoc; 7395 SourceRange ErrorRange, NoteRange; 7396 // Allowed constructs are: 7397 // x++; 7398 // x--; 7399 // ++x; 7400 // --x; 7401 // x binop= expr; 7402 // x = x binop expr; 7403 // x = expr binop x; 7404 if (auto *AtomicBody = dyn_cast<Expr>(S)) { 7405 AtomicBody = AtomicBody->IgnoreParenImpCasts(); 7406 if (AtomicBody->getType()->isScalarType() || 7407 AtomicBody->isInstantiationDependent()) { 7408 if (const auto *AtomicCompAssignOp = dyn_cast<CompoundAssignOperator>( 7409 AtomicBody->IgnoreParenImpCasts())) { 7410 // Check for Compound Assignment Operation 7411 Op = BinaryOperator::getOpForCompoundAssignment( 7412 AtomicCompAssignOp->getOpcode()); 7413 OpLoc = AtomicCompAssignOp->getOperatorLoc(); 7414 E = AtomicCompAssignOp->getRHS(); 7415 X = AtomicCompAssignOp->getLHS()->IgnoreParens(); 7416 IsXLHSInRHSPart = true; 7417 } else if (auto *AtomicBinOp = dyn_cast<BinaryOperator>( 7418 AtomicBody->IgnoreParenImpCasts())) { 7419 // Check for Binary Operation 7420 if (checkBinaryOperation(AtomicBinOp, DiagId, NoteId)) 7421 return true; 7422 } else if (const auto *AtomicUnaryOp = dyn_cast<UnaryOperator>( 7423 AtomicBody->IgnoreParenImpCasts())) { 7424 // Check for Unary Operation 7425 if (AtomicUnaryOp->isIncrementDecrementOp()) { 7426 IsPostfixUpdate = AtomicUnaryOp->isPostfix(); 7427 Op = AtomicUnaryOp->isIncrementOp() ? BO_Add : BO_Sub; 7428 OpLoc = AtomicUnaryOp->getOperatorLoc(); 7429 X = AtomicUnaryOp->getSubExpr()->IgnoreParens(); 7430 E = SemaRef.ActOnIntegerConstant(OpLoc, /*uint64_t Val=*/1).get(); 7431 IsXLHSInRHSPart = true; 7432 } else { 7433 ErrorFound = NotAnUnaryIncDecExpression; 7434 ErrorLoc = AtomicUnaryOp->getExprLoc(); 7435 ErrorRange = AtomicUnaryOp->getSourceRange(); 7436 NoteLoc = AtomicUnaryOp->getOperatorLoc(); 7437 NoteRange = SourceRange(NoteLoc, NoteLoc); 7438 } 7439 } else if (!AtomicBody->isInstantiationDependent()) { 7440 ErrorFound = NotABinaryOrUnaryExpression; 7441 NoteLoc = ErrorLoc = AtomicBody->getExprLoc(); 7442 NoteRange = ErrorRange = AtomicBody->getSourceRange(); 7443 } 7444 } else { 7445 ErrorFound = NotAScalarType; 7446 NoteLoc = ErrorLoc = AtomicBody->getBeginLoc(); 7447 NoteRange = ErrorRange = SourceRange(NoteLoc, NoteLoc); 7448 } 7449 } else { 7450 ErrorFound = NotAnExpression; 7451 NoteLoc = ErrorLoc = S->getBeginLoc(); 7452 NoteRange = ErrorRange = SourceRange(NoteLoc, NoteLoc); 7453 } 7454 if (ErrorFound != NoError && DiagId != 0 && NoteId != 0) { 7455 SemaRef.Diag(ErrorLoc, DiagId) << ErrorRange; 7456 SemaRef.Diag(NoteLoc, NoteId) << ErrorFound << NoteRange; 7457 return true; 7458 } 7459 if (SemaRef.CurContext->isDependentContext()) 7460 E = X = UpdateExpr = nullptr; 7461 if (ErrorFound == NoError && E && X) { 7462 // Build an update expression of form 'OpaqueValueExpr(x) binop 7463 // OpaqueValueExpr(expr)' or 'OpaqueValueExpr(expr) binop 7464 // OpaqueValueExpr(x)' and then cast it to the type of the 'x' expression. 7465 auto *OVEX = new (SemaRef.getASTContext()) 7466 OpaqueValueExpr(X->getExprLoc(), X->getType(), VK_RValue); 7467 auto *OVEExpr = new (SemaRef.getASTContext()) 7468 OpaqueValueExpr(E->getExprLoc(), E->getType(), VK_RValue); 7469 ExprResult Update = 7470 SemaRef.CreateBuiltinBinOp(OpLoc, Op, IsXLHSInRHSPart ? OVEX : OVEExpr, 7471 IsXLHSInRHSPart ? OVEExpr : OVEX); 7472 if (Update.isInvalid()) 7473 return true; 7474 Update = SemaRef.PerformImplicitConversion(Update.get(), X->getType(), 7475 Sema::AA_Casting); 7476 if (Update.isInvalid()) 7477 return true; 7478 UpdateExpr = Update.get(); 7479 } 7480 return ErrorFound != NoError; 7481 } 7482 7483 StmtResult Sema::ActOnOpenMPAtomicDirective(ArrayRef<OMPClause *> Clauses, 7484 Stmt *AStmt, 7485 SourceLocation StartLoc, 7486 SourceLocation EndLoc) { 7487 if (!AStmt) 7488 return StmtError(); 7489 7490 auto *CS = cast<CapturedStmt>(AStmt); 7491 // 1.2.2 OpenMP Language Terminology 7492 // Structured block - An executable statement with a single entry at the 7493 // top and a single exit at the bottom. 7494 // The point of exit cannot be a branch out of the structured block. 7495 // longjmp() and throw() must not violate the entry/exit criteria. 7496 OpenMPClauseKind AtomicKind = OMPC_unknown; 7497 SourceLocation AtomicKindLoc; 7498 for (const OMPClause *C : Clauses) { 7499 if (C->getClauseKind() == OMPC_read || C->getClauseKind() == OMPC_write || 7500 C->getClauseKind() == OMPC_update || 7501 C->getClauseKind() == OMPC_capture) { 7502 if (AtomicKind != OMPC_unknown) { 7503 Diag(C->getBeginLoc(), diag::err_omp_atomic_several_clauses) 7504 << SourceRange(C->getBeginLoc(), C->getEndLoc()); 7505 Diag(AtomicKindLoc, diag::note_omp_atomic_previous_clause) 7506 << getOpenMPClauseName(AtomicKind); 7507 } else { 7508 AtomicKind = C->getClauseKind(); 7509 AtomicKindLoc = C->getBeginLoc(); 7510 } 7511 } 7512 } 7513 7514 Stmt *Body = CS->getCapturedStmt(); 7515 if (auto *EWC = dyn_cast<ExprWithCleanups>(Body)) 7516 Body = EWC->getSubExpr(); 7517 7518 Expr *X = nullptr; 7519 Expr *V = nullptr; 7520 Expr *E = nullptr; 7521 Expr *UE = nullptr; 7522 bool IsXLHSInRHSPart = false; 7523 bool IsPostfixUpdate = false; 7524 // OpenMP [2.12.6, atomic Construct] 7525 // In the next expressions: 7526 // * x and v (as applicable) are both l-value expressions with scalar type. 7527 // * During the execution of an atomic region, multiple syntactic 7528 // occurrences of x must designate the same storage location. 7529 // * Neither of v and expr (as applicable) may access the storage location 7530 // designated by x. 7531 // * Neither of x and expr (as applicable) may access the storage location 7532 // designated by v. 7533 // * expr is an expression with scalar type. 7534 // * binop is one of +, *, -, /, &, ^, |, <<, or >>. 7535 // * binop, binop=, ++, and -- are not overloaded operators. 7536 // * The expression x binop expr must be numerically equivalent to x binop 7537 // (expr). This requirement is satisfied if the operators in expr have 7538 // precedence greater than binop, or by using parentheses around expr or 7539 // subexpressions of expr. 7540 // * The expression expr binop x must be numerically equivalent to (expr) 7541 // binop x. This requirement is satisfied if the operators in expr have 7542 // precedence equal to or greater than binop, or by using parentheses around 7543 // expr or subexpressions of expr. 7544 // * For forms that allow multiple occurrences of x, the number of times 7545 // that x is evaluated is unspecified. 7546 if (AtomicKind == OMPC_read) { 7547 enum { 7548 NotAnExpression, 7549 NotAnAssignmentOp, 7550 NotAScalarType, 7551 NotAnLValue, 7552 NoError 7553 } ErrorFound = NoError; 7554 SourceLocation ErrorLoc, NoteLoc; 7555 SourceRange ErrorRange, NoteRange; 7556 // If clause is read: 7557 // v = x; 7558 if (const auto *AtomicBody = dyn_cast<Expr>(Body)) { 7559 const auto *AtomicBinOp = 7560 dyn_cast<BinaryOperator>(AtomicBody->IgnoreParenImpCasts()); 7561 if (AtomicBinOp && AtomicBinOp->getOpcode() == BO_Assign) { 7562 X = AtomicBinOp->getRHS()->IgnoreParenImpCasts(); 7563 V = AtomicBinOp->getLHS()->IgnoreParenImpCasts(); 7564 if ((X->isInstantiationDependent() || X->getType()->isScalarType()) && 7565 (V->isInstantiationDependent() || V->getType()->isScalarType())) { 7566 if (!X->isLValue() || !V->isLValue()) { 7567 const Expr *NotLValueExpr = X->isLValue() ? V : X; 7568 ErrorFound = NotAnLValue; 7569 ErrorLoc = AtomicBinOp->getExprLoc(); 7570 ErrorRange = AtomicBinOp->getSourceRange(); 7571 NoteLoc = NotLValueExpr->getExprLoc(); 7572 NoteRange = NotLValueExpr->getSourceRange(); 7573 } 7574 } else if (!X->isInstantiationDependent() || 7575 !V->isInstantiationDependent()) { 7576 const Expr *NotScalarExpr = 7577 (X->isInstantiationDependent() || X->getType()->isScalarType()) 7578 ? V 7579 : X; 7580 ErrorFound = NotAScalarType; 7581 ErrorLoc = AtomicBinOp->getExprLoc(); 7582 ErrorRange = AtomicBinOp->getSourceRange(); 7583 NoteLoc = NotScalarExpr->getExprLoc(); 7584 NoteRange = NotScalarExpr->getSourceRange(); 7585 } 7586 } else if (!AtomicBody->isInstantiationDependent()) { 7587 ErrorFound = NotAnAssignmentOp; 7588 ErrorLoc = AtomicBody->getExprLoc(); 7589 ErrorRange = AtomicBody->getSourceRange(); 7590 NoteLoc = AtomicBinOp ? AtomicBinOp->getOperatorLoc() 7591 : AtomicBody->getExprLoc(); 7592 NoteRange = AtomicBinOp ? AtomicBinOp->getSourceRange() 7593 : AtomicBody->getSourceRange(); 7594 } 7595 } else { 7596 ErrorFound = NotAnExpression; 7597 NoteLoc = ErrorLoc = Body->getBeginLoc(); 7598 NoteRange = ErrorRange = SourceRange(NoteLoc, NoteLoc); 7599 } 7600 if (ErrorFound != NoError) { 7601 Diag(ErrorLoc, diag::err_omp_atomic_read_not_expression_statement) 7602 << ErrorRange; 7603 Diag(NoteLoc, diag::note_omp_atomic_read_write) << ErrorFound 7604 << NoteRange; 7605 return StmtError(); 7606 } 7607 if (CurContext->isDependentContext()) 7608 V = X = nullptr; 7609 } else if (AtomicKind == OMPC_write) { 7610 enum { 7611 NotAnExpression, 7612 NotAnAssignmentOp, 7613 NotAScalarType, 7614 NotAnLValue, 7615 NoError 7616 } ErrorFound = NoError; 7617 SourceLocation ErrorLoc, NoteLoc; 7618 SourceRange ErrorRange, NoteRange; 7619 // If clause is write: 7620 // x = expr; 7621 if (const auto *AtomicBody = dyn_cast<Expr>(Body)) { 7622 const auto *AtomicBinOp = 7623 dyn_cast<BinaryOperator>(AtomicBody->IgnoreParenImpCasts()); 7624 if (AtomicBinOp && AtomicBinOp->getOpcode() == BO_Assign) { 7625 X = AtomicBinOp->getLHS(); 7626 E = AtomicBinOp->getRHS(); 7627 if ((X->isInstantiationDependent() || X->getType()->isScalarType()) && 7628 (E->isInstantiationDependent() || E->getType()->isScalarType())) { 7629 if (!X->isLValue()) { 7630 ErrorFound = NotAnLValue; 7631 ErrorLoc = AtomicBinOp->getExprLoc(); 7632 ErrorRange = AtomicBinOp->getSourceRange(); 7633 NoteLoc = X->getExprLoc(); 7634 NoteRange = X->getSourceRange(); 7635 } 7636 } else if (!X->isInstantiationDependent() || 7637 !E->isInstantiationDependent()) { 7638 const Expr *NotScalarExpr = 7639 (X->isInstantiationDependent() || X->getType()->isScalarType()) 7640 ? E 7641 : X; 7642 ErrorFound = NotAScalarType; 7643 ErrorLoc = AtomicBinOp->getExprLoc(); 7644 ErrorRange = AtomicBinOp->getSourceRange(); 7645 NoteLoc = NotScalarExpr->getExprLoc(); 7646 NoteRange = NotScalarExpr->getSourceRange(); 7647 } 7648 } else if (!AtomicBody->isInstantiationDependent()) { 7649 ErrorFound = NotAnAssignmentOp; 7650 ErrorLoc = AtomicBody->getExprLoc(); 7651 ErrorRange = AtomicBody->getSourceRange(); 7652 NoteLoc = AtomicBinOp ? AtomicBinOp->getOperatorLoc() 7653 : AtomicBody->getExprLoc(); 7654 NoteRange = AtomicBinOp ? AtomicBinOp->getSourceRange() 7655 : AtomicBody->getSourceRange(); 7656 } 7657 } else { 7658 ErrorFound = NotAnExpression; 7659 NoteLoc = ErrorLoc = Body->getBeginLoc(); 7660 NoteRange = ErrorRange = SourceRange(NoteLoc, NoteLoc); 7661 } 7662 if (ErrorFound != NoError) { 7663 Diag(ErrorLoc, diag::err_omp_atomic_write_not_expression_statement) 7664 << ErrorRange; 7665 Diag(NoteLoc, diag::note_omp_atomic_read_write) << ErrorFound 7666 << NoteRange; 7667 return StmtError(); 7668 } 7669 if (CurContext->isDependentContext()) 7670 E = X = nullptr; 7671 } else if (AtomicKind == OMPC_update || AtomicKind == OMPC_unknown) { 7672 // If clause is update: 7673 // x++; 7674 // x--; 7675 // ++x; 7676 // --x; 7677 // x binop= expr; 7678 // x = x binop expr; 7679 // x = expr binop x; 7680 OpenMPAtomicUpdateChecker Checker(*this); 7681 if (Checker.checkStatement( 7682 Body, (AtomicKind == OMPC_update) 7683 ? diag::err_omp_atomic_update_not_expression_statement 7684 : diag::err_omp_atomic_not_expression_statement, 7685 diag::note_omp_atomic_update)) 7686 return StmtError(); 7687 if (!CurContext->isDependentContext()) { 7688 E = Checker.getExpr(); 7689 X = Checker.getX(); 7690 UE = Checker.getUpdateExpr(); 7691 IsXLHSInRHSPart = Checker.isXLHSInRHSPart(); 7692 } 7693 } else if (AtomicKind == OMPC_capture) { 7694 enum { 7695 NotAnAssignmentOp, 7696 NotACompoundStatement, 7697 NotTwoSubstatements, 7698 NotASpecificExpression, 7699 NoError 7700 } ErrorFound = NoError; 7701 SourceLocation ErrorLoc, NoteLoc; 7702 SourceRange ErrorRange, NoteRange; 7703 if (const auto *AtomicBody = dyn_cast<Expr>(Body)) { 7704 // If clause is a capture: 7705 // v = x++; 7706 // v = x--; 7707 // v = ++x; 7708 // v = --x; 7709 // v = x binop= expr; 7710 // v = x = x binop expr; 7711 // v = x = expr binop x; 7712 const auto *AtomicBinOp = 7713 dyn_cast<BinaryOperator>(AtomicBody->IgnoreParenImpCasts()); 7714 if (AtomicBinOp && AtomicBinOp->getOpcode() == BO_Assign) { 7715 V = AtomicBinOp->getLHS(); 7716 Body = AtomicBinOp->getRHS()->IgnoreParenImpCasts(); 7717 OpenMPAtomicUpdateChecker Checker(*this); 7718 if (Checker.checkStatement( 7719 Body, diag::err_omp_atomic_capture_not_expression_statement, 7720 diag::note_omp_atomic_update)) 7721 return StmtError(); 7722 E = Checker.getExpr(); 7723 X = Checker.getX(); 7724 UE = Checker.getUpdateExpr(); 7725 IsXLHSInRHSPart = Checker.isXLHSInRHSPart(); 7726 IsPostfixUpdate = Checker.isPostfixUpdate(); 7727 } else if (!AtomicBody->isInstantiationDependent()) { 7728 ErrorLoc = AtomicBody->getExprLoc(); 7729 ErrorRange = AtomicBody->getSourceRange(); 7730 NoteLoc = AtomicBinOp ? AtomicBinOp->getOperatorLoc() 7731 : AtomicBody->getExprLoc(); 7732 NoteRange = AtomicBinOp ? AtomicBinOp->getSourceRange() 7733 : AtomicBody->getSourceRange(); 7734 ErrorFound = NotAnAssignmentOp; 7735 } 7736 if (ErrorFound != NoError) { 7737 Diag(ErrorLoc, diag::err_omp_atomic_capture_not_expression_statement) 7738 << ErrorRange; 7739 Diag(NoteLoc, diag::note_omp_atomic_capture) << ErrorFound << NoteRange; 7740 return StmtError(); 7741 } 7742 if (CurContext->isDependentContext()) 7743 UE = V = E = X = nullptr; 7744 } else { 7745 // If clause is a capture: 7746 // { v = x; x = expr; } 7747 // { v = x; x++; } 7748 // { v = x; x--; } 7749 // { v = x; ++x; } 7750 // { v = x; --x; } 7751 // { v = x; x binop= expr; } 7752 // { v = x; x = x binop expr; } 7753 // { v = x; x = expr binop x; } 7754 // { x++; v = x; } 7755 // { x--; v = x; } 7756 // { ++x; v = x; } 7757 // { --x; v = x; } 7758 // { x binop= expr; v = x; } 7759 // { x = x binop expr; v = x; } 7760 // { x = expr binop x; v = x; } 7761 if (auto *CS = dyn_cast<CompoundStmt>(Body)) { 7762 // Check that this is { expr1; expr2; } 7763 if (CS->size() == 2) { 7764 Stmt *First = CS->body_front(); 7765 Stmt *Second = CS->body_back(); 7766 if (auto *EWC = dyn_cast<ExprWithCleanups>(First)) 7767 First = EWC->getSubExpr()->IgnoreParenImpCasts(); 7768 if (auto *EWC = dyn_cast<ExprWithCleanups>(Second)) 7769 Second = EWC->getSubExpr()->IgnoreParenImpCasts(); 7770 // Need to find what subexpression is 'v' and what is 'x'. 7771 OpenMPAtomicUpdateChecker Checker(*this); 7772 bool IsUpdateExprFound = !Checker.checkStatement(Second); 7773 BinaryOperator *BinOp = nullptr; 7774 if (IsUpdateExprFound) { 7775 BinOp = dyn_cast<BinaryOperator>(First); 7776 IsUpdateExprFound = BinOp && BinOp->getOpcode() == BO_Assign; 7777 } 7778 if (IsUpdateExprFound && !CurContext->isDependentContext()) { 7779 // { v = x; x++; } 7780 // { v = x; x--; } 7781 // { v = x; ++x; } 7782 // { v = x; --x; } 7783 // { v = x; x binop= expr; } 7784 // { v = x; x = x binop expr; } 7785 // { v = x; x = expr binop x; } 7786 // Check that the first expression has form v = x. 7787 Expr *PossibleX = BinOp->getRHS()->IgnoreParenImpCasts(); 7788 llvm::FoldingSetNodeID XId, PossibleXId; 7789 Checker.getX()->Profile(XId, Context, /*Canonical=*/true); 7790 PossibleX->Profile(PossibleXId, Context, /*Canonical=*/true); 7791 IsUpdateExprFound = XId == PossibleXId; 7792 if (IsUpdateExprFound) { 7793 V = BinOp->getLHS(); 7794 X = Checker.getX(); 7795 E = Checker.getExpr(); 7796 UE = Checker.getUpdateExpr(); 7797 IsXLHSInRHSPart = Checker.isXLHSInRHSPart(); 7798 IsPostfixUpdate = true; 7799 } 7800 } 7801 if (!IsUpdateExprFound) { 7802 IsUpdateExprFound = !Checker.checkStatement(First); 7803 BinOp = nullptr; 7804 if (IsUpdateExprFound) { 7805 BinOp = dyn_cast<BinaryOperator>(Second); 7806 IsUpdateExprFound = BinOp && BinOp->getOpcode() == BO_Assign; 7807 } 7808 if (IsUpdateExprFound && !CurContext->isDependentContext()) { 7809 // { x++; v = x; } 7810 // { x--; v = x; } 7811 // { ++x; v = x; } 7812 // { --x; v = x; } 7813 // { x binop= expr; v = x; } 7814 // { x = x binop expr; v = x; } 7815 // { x = expr binop x; v = x; } 7816 // Check that the second expression has form v = x. 7817 Expr *PossibleX = BinOp->getRHS()->IgnoreParenImpCasts(); 7818 llvm::FoldingSetNodeID XId, PossibleXId; 7819 Checker.getX()->Profile(XId, Context, /*Canonical=*/true); 7820 PossibleX->Profile(PossibleXId, Context, /*Canonical=*/true); 7821 IsUpdateExprFound = XId == PossibleXId; 7822 if (IsUpdateExprFound) { 7823 V = BinOp->getLHS(); 7824 X = Checker.getX(); 7825 E = Checker.getExpr(); 7826 UE = Checker.getUpdateExpr(); 7827 IsXLHSInRHSPart = Checker.isXLHSInRHSPart(); 7828 IsPostfixUpdate = false; 7829 } 7830 } 7831 } 7832 if (!IsUpdateExprFound) { 7833 // { v = x; x = expr; } 7834 auto *FirstExpr = dyn_cast<Expr>(First); 7835 auto *SecondExpr = dyn_cast<Expr>(Second); 7836 if (!FirstExpr || !SecondExpr || 7837 !(FirstExpr->isInstantiationDependent() || 7838 SecondExpr->isInstantiationDependent())) { 7839 auto *FirstBinOp = dyn_cast<BinaryOperator>(First); 7840 if (!FirstBinOp || FirstBinOp->getOpcode() != BO_Assign) { 7841 ErrorFound = NotAnAssignmentOp; 7842 NoteLoc = ErrorLoc = FirstBinOp ? FirstBinOp->getOperatorLoc() 7843 : First->getBeginLoc(); 7844 NoteRange = ErrorRange = FirstBinOp 7845 ? FirstBinOp->getSourceRange() 7846 : SourceRange(ErrorLoc, ErrorLoc); 7847 } else { 7848 auto *SecondBinOp = dyn_cast<BinaryOperator>(Second); 7849 if (!SecondBinOp || SecondBinOp->getOpcode() != BO_Assign) { 7850 ErrorFound = NotAnAssignmentOp; 7851 NoteLoc = ErrorLoc = SecondBinOp 7852 ? SecondBinOp->getOperatorLoc() 7853 : Second->getBeginLoc(); 7854 NoteRange = ErrorRange = 7855 SecondBinOp ? SecondBinOp->getSourceRange() 7856 : SourceRange(ErrorLoc, ErrorLoc); 7857 } else { 7858 Expr *PossibleXRHSInFirst = 7859 FirstBinOp->getRHS()->IgnoreParenImpCasts(); 7860 Expr *PossibleXLHSInSecond = 7861 SecondBinOp->getLHS()->IgnoreParenImpCasts(); 7862 llvm::FoldingSetNodeID X1Id, X2Id; 7863 PossibleXRHSInFirst->Profile(X1Id, Context, 7864 /*Canonical=*/true); 7865 PossibleXLHSInSecond->Profile(X2Id, Context, 7866 /*Canonical=*/true); 7867 IsUpdateExprFound = X1Id == X2Id; 7868 if (IsUpdateExprFound) { 7869 V = FirstBinOp->getLHS(); 7870 X = SecondBinOp->getLHS(); 7871 E = SecondBinOp->getRHS(); 7872 UE = nullptr; 7873 IsXLHSInRHSPart = false; 7874 IsPostfixUpdate = true; 7875 } else { 7876 ErrorFound = NotASpecificExpression; 7877 ErrorLoc = FirstBinOp->getExprLoc(); 7878 ErrorRange = FirstBinOp->getSourceRange(); 7879 NoteLoc = SecondBinOp->getLHS()->getExprLoc(); 7880 NoteRange = SecondBinOp->getRHS()->getSourceRange(); 7881 } 7882 } 7883 } 7884 } 7885 } 7886 } else { 7887 NoteLoc = ErrorLoc = Body->getBeginLoc(); 7888 NoteRange = ErrorRange = 7889 SourceRange(Body->getBeginLoc(), Body->getBeginLoc()); 7890 ErrorFound = NotTwoSubstatements; 7891 } 7892 } else { 7893 NoteLoc = ErrorLoc = Body->getBeginLoc(); 7894 NoteRange = ErrorRange = 7895 SourceRange(Body->getBeginLoc(), Body->getBeginLoc()); 7896 ErrorFound = NotACompoundStatement; 7897 } 7898 if (ErrorFound != NoError) { 7899 Diag(ErrorLoc, diag::err_omp_atomic_capture_not_compound_statement) 7900 << ErrorRange; 7901 Diag(NoteLoc, diag::note_omp_atomic_capture) << ErrorFound << NoteRange; 7902 return StmtError(); 7903 } 7904 if (CurContext->isDependentContext()) 7905 UE = V = E = X = nullptr; 7906 } 7907 } 7908 7909 setFunctionHasBranchProtectedScope(); 7910 7911 return OMPAtomicDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt, 7912 X, V, E, UE, IsXLHSInRHSPart, 7913 IsPostfixUpdate); 7914 } 7915 7916 StmtResult Sema::ActOnOpenMPTargetDirective(ArrayRef<OMPClause *> Clauses, 7917 Stmt *AStmt, 7918 SourceLocation StartLoc, 7919 SourceLocation EndLoc) { 7920 if (!AStmt) 7921 return StmtError(); 7922 7923 auto *CS = cast<CapturedStmt>(AStmt); 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 for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target); 7931 ThisCaptureLevel > 1; --ThisCaptureLevel) { 7932 CS = cast<CapturedStmt>(CS->getCapturedStmt()); 7933 // 1.2.2 OpenMP Language Terminology 7934 // Structured block - An executable statement with a single entry at the 7935 // top and a single exit at the bottom. 7936 // The point of exit cannot be a branch out of the structured block. 7937 // longjmp() and throw() must not violate the entry/exit criteria. 7938 CS->getCapturedDecl()->setNothrow(); 7939 } 7940 7941 // OpenMP [2.16, Nesting of Regions] 7942 // If specified, a teams construct must be contained within a target 7943 // construct. That target construct must contain no statements or directives 7944 // outside of the teams construct. 7945 if (DSAStack->hasInnerTeamsRegion()) { 7946 const Stmt *S = CS->IgnoreContainers(/*IgnoreCaptured=*/true); 7947 bool OMPTeamsFound = true; 7948 if (const auto *CS = dyn_cast<CompoundStmt>(S)) { 7949 auto I = CS->body_begin(); 7950 while (I != CS->body_end()) { 7951 const auto *OED = dyn_cast<OMPExecutableDirective>(*I); 7952 if (!OED || !isOpenMPTeamsDirective(OED->getDirectiveKind()) || 7953 OMPTeamsFound) { 7954 7955 OMPTeamsFound = false; 7956 break; 7957 } 7958 ++I; 7959 } 7960 assert(I != CS->body_end() && "Not found statement"); 7961 S = *I; 7962 } else { 7963 const auto *OED = dyn_cast<OMPExecutableDirective>(S); 7964 OMPTeamsFound = OED && isOpenMPTeamsDirective(OED->getDirectiveKind()); 7965 } 7966 if (!OMPTeamsFound) { 7967 Diag(StartLoc, diag::err_omp_target_contains_not_only_teams); 7968 Diag(DSAStack->getInnerTeamsRegionLoc(), 7969 diag::note_omp_nested_teams_construct_here); 7970 Diag(S->getBeginLoc(), diag::note_omp_nested_statement_here) 7971 << isa<OMPExecutableDirective>(S); 7972 return StmtError(); 7973 } 7974 } 7975 7976 setFunctionHasBranchProtectedScope(); 7977 7978 return OMPTargetDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt); 7979 } 7980 7981 StmtResult 7982 Sema::ActOnOpenMPTargetParallelDirective(ArrayRef<OMPClause *> Clauses, 7983 Stmt *AStmt, SourceLocation StartLoc, 7984 SourceLocation EndLoc) { 7985 if (!AStmt) 7986 return StmtError(); 7987 7988 auto *CS = cast<CapturedStmt>(AStmt); 7989 // 1.2.2 OpenMP Language Terminology 7990 // Structured block - An executable statement with a single entry at the 7991 // top and a single exit at the bottom. 7992 // The point of exit cannot be a branch out of the structured block. 7993 // longjmp() and throw() must not violate the entry/exit criteria. 7994 CS->getCapturedDecl()->setNothrow(); 7995 for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_parallel); 7996 ThisCaptureLevel > 1; --ThisCaptureLevel) { 7997 CS = cast<CapturedStmt>(CS->getCapturedStmt()); 7998 // 1.2.2 OpenMP Language Terminology 7999 // Structured block - An executable statement with a single entry at the 8000 // top and a single exit at the bottom. 8001 // The point of exit cannot be a branch out of the structured block. 8002 // longjmp() and throw() must not violate the entry/exit criteria. 8003 CS->getCapturedDecl()->setNothrow(); 8004 } 8005 8006 setFunctionHasBranchProtectedScope(); 8007 8008 return OMPTargetParallelDirective::Create(Context, StartLoc, EndLoc, Clauses, 8009 AStmt); 8010 } 8011 8012 StmtResult Sema::ActOnOpenMPTargetParallelForDirective( 8013 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, 8014 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) { 8015 if (!AStmt) 8016 return StmtError(); 8017 8018 auto *CS = cast<CapturedStmt>(AStmt); 8019 // 1.2.2 OpenMP Language Terminology 8020 // Structured block - An executable statement with a single entry at the 8021 // top and a single exit at the bottom. 8022 // The point of exit cannot be a branch out of the structured block. 8023 // longjmp() and throw() must not violate the entry/exit criteria. 8024 CS->getCapturedDecl()->setNothrow(); 8025 for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_parallel_for); 8026 ThisCaptureLevel > 1; --ThisCaptureLevel) { 8027 CS = cast<CapturedStmt>(CS->getCapturedStmt()); 8028 // 1.2.2 OpenMP Language Terminology 8029 // Structured block - An executable statement with a single entry at the 8030 // top and a single exit at the bottom. 8031 // The point of exit cannot be a branch out of the structured block. 8032 // longjmp() and throw() must not violate the entry/exit criteria. 8033 CS->getCapturedDecl()->setNothrow(); 8034 } 8035 8036 OMPLoopDirective::HelperExprs B; 8037 // In presence of clause 'collapse' or 'ordered' with number of loops, it will 8038 // define the nested loops number. 8039 unsigned NestedLoopCount = 8040 checkOpenMPLoop(OMPD_target_parallel_for, getCollapseNumberExpr(Clauses), 8041 getOrderedNumberExpr(Clauses), CS, *this, *DSAStack, 8042 VarsWithImplicitDSA, B); 8043 if (NestedLoopCount == 0) 8044 return StmtError(); 8045 8046 assert((CurContext->isDependentContext() || B.builtAll()) && 8047 "omp target parallel for loop exprs were not built"); 8048 8049 if (!CurContext->isDependentContext()) { 8050 // Finalize the clauses that need pre-built expressions for CodeGen. 8051 for (OMPClause *C : Clauses) { 8052 if (auto *LC = dyn_cast<OMPLinearClause>(C)) 8053 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef), 8054 B.NumIterations, *this, CurScope, 8055 DSAStack)) 8056 return StmtError(); 8057 } 8058 } 8059 8060 setFunctionHasBranchProtectedScope(); 8061 return OMPTargetParallelForDirective::Create(Context, StartLoc, EndLoc, 8062 NestedLoopCount, Clauses, AStmt, 8063 B, DSAStack->isCancelRegion()); 8064 } 8065 8066 /// Check for existence of a map clause in the list of clauses. 8067 static bool hasClauses(ArrayRef<OMPClause *> Clauses, 8068 const OpenMPClauseKind K) { 8069 return llvm::any_of( 8070 Clauses, [K](const OMPClause *C) { return C->getClauseKind() == K; }); 8071 } 8072 8073 template <typename... Params> 8074 static bool hasClauses(ArrayRef<OMPClause *> Clauses, const OpenMPClauseKind K, 8075 const Params... ClauseTypes) { 8076 return hasClauses(Clauses, K) || hasClauses(Clauses, ClauseTypes...); 8077 } 8078 8079 StmtResult Sema::ActOnOpenMPTargetDataDirective(ArrayRef<OMPClause *> Clauses, 8080 Stmt *AStmt, 8081 SourceLocation StartLoc, 8082 SourceLocation EndLoc) { 8083 if (!AStmt) 8084 return StmtError(); 8085 8086 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected"); 8087 8088 // OpenMP [2.10.1, Restrictions, p. 97] 8089 // At least one map clause must appear on the directive. 8090 if (!hasClauses(Clauses, OMPC_map, OMPC_use_device_ptr)) { 8091 Diag(StartLoc, diag::err_omp_no_clause_for_directive) 8092 << "'map' or 'use_device_ptr'" 8093 << getOpenMPDirectiveName(OMPD_target_data); 8094 return StmtError(); 8095 } 8096 8097 setFunctionHasBranchProtectedScope(); 8098 8099 return OMPTargetDataDirective::Create(Context, StartLoc, EndLoc, Clauses, 8100 AStmt); 8101 } 8102 8103 StmtResult 8104 Sema::ActOnOpenMPTargetEnterDataDirective(ArrayRef<OMPClause *> Clauses, 8105 SourceLocation StartLoc, 8106 SourceLocation EndLoc, Stmt *AStmt) { 8107 if (!AStmt) 8108 return StmtError(); 8109 8110 auto *CS = cast<CapturedStmt>(AStmt); 8111 // 1.2.2 OpenMP Language Terminology 8112 // Structured block - An executable statement with a single entry at the 8113 // top and a single exit at the bottom. 8114 // The point of exit cannot be a branch out of the structured block. 8115 // longjmp() and throw() must not violate the entry/exit criteria. 8116 CS->getCapturedDecl()->setNothrow(); 8117 for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_enter_data); 8118 ThisCaptureLevel > 1; --ThisCaptureLevel) { 8119 CS = cast<CapturedStmt>(CS->getCapturedStmt()); 8120 // 1.2.2 OpenMP Language Terminology 8121 // Structured block - An executable statement with a single entry at the 8122 // top and a single exit at the bottom. 8123 // The point of exit cannot be a branch out of the structured block. 8124 // longjmp() and throw() must not violate the entry/exit criteria. 8125 CS->getCapturedDecl()->setNothrow(); 8126 } 8127 8128 // OpenMP [2.10.2, Restrictions, p. 99] 8129 // At least one map clause must appear on the directive. 8130 if (!hasClauses(Clauses, OMPC_map)) { 8131 Diag(StartLoc, diag::err_omp_no_clause_for_directive) 8132 << "'map'" << getOpenMPDirectiveName(OMPD_target_enter_data); 8133 return StmtError(); 8134 } 8135 8136 return OMPTargetEnterDataDirective::Create(Context, StartLoc, EndLoc, Clauses, 8137 AStmt); 8138 } 8139 8140 StmtResult 8141 Sema::ActOnOpenMPTargetExitDataDirective(ArrayRef<OMPClause *> Clauses, 8142 SourceLocation StartLoc, 8143 SourceLocation EndLoc, Stmt *AStmt) { 8144 if (!AStmt) 8145 return StmtError(); 8146 8147 auto *CS = cast<CapturedStmt>(AStmt); 8148 // 1.2.2 OpenMP Language Terminology 8149 // Structured block - An executable statement with a single entry at the 8150 // top and a single exit at the bottom. 8151 // The point of exit cannot be a branch out of the structured block. 8152 // longjmp() and throw() must not violate the entry/exit criteria. 8153 CS->getCapturedDecl()->setNothrow(); 8154 for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_exit_data); 8155 ThisCaptureLevel > 1; --ThisCaptureLevel) { 8156 CS = cast<CapturedStmt>(CS->getCapturedStmt()); 8157 // 1.2.2 OpenMP Language Terminology 8158 // Structured block - An executable statement with a single entry at the 8159 // top and a single exit at the bottom. 8160 // The point of exit cannot be a branch out of the structured block. 8161 // longjmp() and throw() must not violate the entry/exit criteria. 8162 CS->getCapturedDecl()->setNothrow(); 8163 } 8164 8165 // OpenMP [2.10.3, Restrictions, p. 102] 8166 // At least one map clause must appear on the directive. 8167 if (!hasClauses(Clauses, OMPC_map)) { 8168 Diag(StartLoc, diag::err_omp_no_clause_for_directive) 8169 << "'map'" << getOpenMPDirectiveName(OMPD_target_exit_data); 8170 return StmtError(); 8171 } 8172 8173 return OMPTargetExitDataDirective::Create(Context, StartLoc, EndLoc, Clauses, 8174 AStmt); 8175 } 8176 8177 StmtResult Sema::ActOnOpenMPTargetUpdateDirective(ArrayRef<OMPClause *> Clauses, 8178 SourceLocation StartLoc, 8179 SourceLocation EndLoc, 8180 Stmt *AStmt) { 8181 if (!AStmt) 8182 return StmtError(); 8183 8184 auto *CS = cast<CapturedStmt>(AStmt); 8185 // 1.2.2 OpenMP Language Terminology 8186 // Structured block - An executable statement with a single entry at the 8187 // top and a single exit at the bottom. 8188 // The point of exit cannot be a branch out of the structured block. 8189 // longjmp() and throw() must not violate the entry/exit criteria. 8190 CS->getCapturedDecl()->setNothrow(); 8191 for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_update); 8192 ThisCaptureLevel > 1; --ThisCaptureLevel) { 8193 CS = cast<CapturedStmt>(CS->getCapturedStmt()); 8194 // 1.2.2 OpenMP Language Terminology 8195 // Structured block - An executable statement with a single entry at the 8196 // top and a single exit at the bottom. 8197 // The point of exit cannot be a branch out of the structured block. 8198 // longjmp() and throw() must not violate the entry/exit criteria. 8199 CS->getCapturedDecl()->setNothrow(); 8200 } 8201 8202 if (!hasClauses(Clauses, OMPC_to, OMPC_from)) { 8203 Diag(StartLoc, diag::err_omp_at_least_one_motion_clause_required); 8204 return StmtError(); 8205 } 8206 return OMPTargetUpdateDirective::Create(Context, StartLoc, EndLoc, Clauses, 8207 AStmt); 8208 } 8209 8210 StmtResult Sema::ActOnOpenMPTeamsDirective(ArrayRef<OMPClause *> Clauses, 8211 Stmt *AStmt, SourceLocation StartLoc, 8212 SourceLocation EndLoc) { 8213 if (!AStmt) 8214 return StmtError(); 8215 8216 auto *CS = cast<CapturedStmt>(AStmt); 8217 // 1.2.2 OpenMP Language Terminology 8218 // Structured block - An executable statement with a single entry at the 8219 // top and a single exit at the bottom. 8220 // The point of exit cannot be a branch out of the structured block. 8221 // longjmp() and throw() must not violate the entry/exit criteria. 8222 CS->getCapturedDecl()->setNothrow(); 8223 8224 setFunctionHasBranchProtectedScope(); 8225 8226 DSAStack->setParentTeamsRegionLoc(StartLoc); 8227 8228 return OMPTeamsDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt); 8229 } 8230 8231 StmtResult 8232 Sema::ActOnOpenMPCancellationPointDirective(SourceLocation StartLoc, 8233 SourceLocation EndLoc, 8234 OpenMPDirectiveKind CancelRegion) { 8235 if (DSAStack->isParentNowaitRegion()) { 8236 Diag(StartLoc, diag::err_omp_parent_cancel_region_nowait) << 0; 8237 return StmtError(); 8238 } 8239 if (DSAStack->isParentOrderedRegion()) { 8240 Diag(StartLoc, diag::err_omp_parent_cancel_region_ordered) << 0; 8241 return StmtError(); 8242 } 8243 return OMPCancellationPointDirective::Create(Context, StartLoc, EndLoc, 8244 CancelRegion); 8245 } 8246 8247 StmtResult Sema::ActOnOpenMPCancelDirective(ArrayRef<OMPClause *> Clauses, 8248 SourceLocation StartLoc, 8249 SourceLocation EndLoc, 8250 OpenMPDirectiveKind CancelRegion) { 8251 if (DSAStack->isParentNowaitRegion()) { 8252 Diag(StartLoc, diag::err_omp_parent_cancel_region_nowait) << 1; 8253 return StmtError(); 8254 } 8255 if (DSAStack->isParentOrderedRegion()) { 8256 Diag(StartLoc, diag::err_omp_parent_cancel_region_ordered) << 1; 8257 return StmtError(); 8258 } 8259 DSAStack->setParentCancelRegion(/*Cancel=*/true); 8260 return OMPCancelDirective::Create(Context, StartLoc, EndLoc, Clauses, 8261 CancelRegion); 8262 } 8263 8264 static bool checkGrainsizeNumTasksClauses(Sema &S, 8265 ArrayRef<OMPClause *> Clauses) { 8266 const OMPClause *PrevClause = nullptr; 8267 bool ErrorFound = false; 8268 for (const OMPClause *C : Clauses) { 8269 if (C->getClauseKind() == OMPC_grainsize || 8270 C->getClauseKind() == OMPC_num_tasks) { 8271 if (!PrevClause) 8272 PrevClause = C; 8273 else if (PrevClause->getClauseKind() != C->getClauseKind()) { 8274 S.Diag(C->getBeginLoc(), 8275 diag::err_omp_grainsize_num_tasks_mutually_exclusive) 8276 << getOpenMPClauseName(C->getClauseKind()) 8277 << getOpenMPClauseName(PrevClause->getClauseKind()); 8278 S.Diag(PrevClause->getBeginLoc(), 8279 diag::note_omp_previous_grainsize_num_tasks) 8280 << getOpenMPClauseName(PrevClause->getClauseKind()); 8281 ErrorFound = true; 8282 } 8283 } 8284 } 8285 return ErrorFound; 8286 } 8287 8288 static bool checkReductionClauseWithNogroup(Sema &S, 8289 ArrayRef<OMPClause *> Clauses) { 8290 const OMPClause *ReductionClause = nullptr; 8291 const OMPClause *NogroupClause = nullptr; 8292 for (const OMPClause *C : Clauses) { 8293 if (C->getClauseKind() == OMPC_reduction) { 8294 ReductionClause = C; 8295 if (NogroupClause) 8296 break; 8297 continue; 8298 } 8299 if (C->getClauseKind() == OMPC_nogroup) { 8300 NogroupClause = C; 8301 if (ReductionClause) 8302 break; 8303 continue; 8304 } 8305 } 8306 if (ReductionClause && NogroupClause) { 8307 S.Diag(ReductionClause->getBeginLoc(), diag::err_omp_reduction_with_nogroup) 8308 << SourceRange(NogroupClause->getBeginLoc(), 8309 NogroupClause->getEndLoc()); 8310 return true; 8311 } 8312 return false; 8313 } 8314 8315 StmtResult Sema::ActOnOpenMPTaskLoopDirective( 8316 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, 8317 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) { 8318 if (!AStmt) 8319 return StmtError(); 8320 8321 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected"); 8322 OMPLoopDirective::HelperExprs B; 8323 // In presence of clause 'collapse' or 'ordered' with number of loops, it will 8324 // define the nested loops number. 8325 unsigned NestedLoopCount = 8326 checkOpenMPLoop(OMPD_taskloop, getCollapseNumberExpr(Clauses), 8327 /*OrderedLoopCountExpr=*/nullptr, AStmt, *this, *DSAStack, 8328 VarsWithImplicitDSA, B); 8329 if (NestedLoopCount == 0) 8330 return StmtError(); 8331 8332 assert((CurContext->isDependentContext() || B.builtAll()) && 8333 "omp for loop exprs were not built"); 8334 8335 // OpenMP, [2.9.2 taskloop Construct, Restrictions] 8336 // The grainsize clause and num_tasks clause are mutually exclusive and may 8337 // not appear on the same taskloop directive. 8338 if (checkGrainsizeNumTasksClauses(*this, Clauses)) 8339 return StmtError(); 8340 // OpenMP, [2.9.2 taskloop Construct, Restrictions] 8341 // If a reduction clause is present on the taskloop directive, the nogroup 8342 // clause must not be specified. 8343 if (checkReductionClauseWithNogroup(*this, Clauses)) 8344 return StmtError(); 8345 8346 setFunctionHasBranchProtectedScope(); 8347 return OMPTaskLoopDirective::Create(Context, StartLoc, EndLoc, 8348 NestedLoopCount, Clauses, AStmt, B); 8349 } 8350 8351 StmtResult Sema::ActOnOpenMPTaskLoopSimdDirective( 8352 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, 8353 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) { 8354 if (!AStmt) 8355 return StmtError(); 8356 8357 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected"); 8358 OMPLoopDirective::HelperExprs B; 8359 // In presence of clause 'collapse' or 'ordered' with number of loops, it will 8360 // define the nested loops number. 8361 unsigned NestedLoopCount = 8362 checkOpenMPLoop(OMPD_taskloop_simd, getCollapseNumberExpr(Clauses), 8363 /*OrderedLoopCountExpr=*/nullptr, AStmt, *this, *DSAStack, 8364 VarsWithImplicitDSA, B); 8365 if (NestedLoopCount == 0) 8366 return StmtError(); 8367 8368 assert((CurContext->isDependentContext() || B.builtAll()) && 8369 "omp for loop exprs were not built"); 8370 8371 if (!CurContext->isDependentContext()) { 8372 // Finalize the clauses that need pre-built expressions for CodeGen. 8373 for (OMPClause *C : Clauses) { 8374 if (auto *LC = dyn_cast<OMPLinearClause>(C)) 8375 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef), 8376 B.NumIterations, *this, CurScope, 8377 DSAStack)) 8378 return StmtError(); 8379 } 8380 } 8381 8382 // OpenMP, [2.9.2 taskloop Construct, Restrictions] 8383 // The grainsize clause and num_tasks clause are mutually exclusive and may 8384 // not appear on the same taskloop directive. 8385 if (checkGrainsizeNumTasksClauses(*this, Clauses)) 8386 return StmtError(); 8387 // OpenMP, [2.9.2 taskloop Construct, Restrictions] 8388 // If a reduction clause is present on the taskloop directive, the nogroup 8389 // clause must not be specified. 8390 if (checkReductionClauseWithNogroup(*this, Clauses)) 8391 return StmtError(); 8392 if (checkSimdlenSafelenSpecified(*this, Clauses)) 8393 return StmtError(); 8394 8395 setFunctionHasBranchProtectedScope(); 8396 return OMPTaskLoopSimdDirective::Create(Context, StartLoc, EndLoc, 8397 NestedLoopCount, Clauses, AStmt, B); 8398 } 8399 8400 StmtResult Sema::ActOnOpenMPDistributeDirective( 8401 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, 8402 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) { 8403 if (!AStmt) 8404 return StmtError(); 8405 8406 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected"); 8407 OMPLoopDirective::HelperExprs B; 8408 // In presence of clause 'collapse' with number of loops, it will 8409 // define the nested loops number. 8410 unsigned NestedLoopCount = 8411 checkOpenMPLoop(OMPD_distribute, getCollapseNumberExpr(Clauses), 8412 nullptr /*ordered not a clause on distribute*/, AStmt, 8413 *this, *DSAStack, VarsWithImplicitDSA, B); 8414 if (NestedLoopCount == 0) 8415 return StmtError(); 8416 8417 assert((CurContext->isDependentContext() || B.builtAll()) && 8418 "omp for loop exprs were not built"); 8419 8420 setFunctionHasBranchProtectedScope(); 8421 return OMPDistributeDirective::Create(Context, StartLoc, EndLoc, 8422 NestedLoopCount, Clauses, AStmt, B); 8423 } 8424 8425 StmtResult Sema::ActOnOpenMPDistributeParallelForDirective( 8426 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, 8427 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) { 8428 if (!AStmt) 8429 return StmtError(); 8430 8431 auto *CS = cast<CapturedStmt>(AStmt); 8432 // 1.2.2 OpenMP Language Terminology 8433 // Structured block - An executable statement with a single entry at the 8434 // top and a single exit at the bottom. 8435 // The point of exit cannot be a branch out of the structured block. 8436 // longjmp() and throw() must not violate the entry/exit criteria. 8437 CS->getCapturedDecl()->setNothrow(); 8438 for (int ThisCaptureLevel = 8439 getOpenMPCaptureLevels(OMPD_distribute_parallel_for); 8440 ThisCaptureLevel > 1; --ThisCaptureLevel) { 8441 CS = cast<CapturedStmt>(CS->getCapturedStmt()); 8442 // 1.2.2 OpenMP Language Terminology 8443 // Structured block - An executable statement with a single entry at the 8444 // top and a single exit at the bottom. 8445 // The point of exit cannot be a branch out of the structured block. 8446 // longjmp() and throw() must not violate the entry/exit criteria. 8447 CS->getCapturedDecl()->setNothrow(); 8448 } 8449 8450 OMPLoopDirective::HelperExprs B; 8451 // In presence of clause 'collapse' with number of loops, it will 8452 // define the nested loops number. 8453 unsigned NestedLoopCount = checkOpenMPLoop( 8454 OMPD_distribute_parallel_for, getCollapseNumberExpr(Clauses), 8455 nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStack, 8456 VarsWithImplicitDSA, B); 8457 if (NestedLoopCount == 0) 8458 return StmtError(); 8459 8460 assert((CurContext->isDependentContext() || B.builtAll()) && 8461 "omp for loop exprs were not built"); 8462 8463 setFunctionHasBranchProtectedScope(); 8464 return OMPDistributeParallelForDirective::Create( 8465 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B, 8466 DSAStack->isCancelRegion()); 8467 } 8468 8469 StmtResult Sema::ActOnOpenMPDistributeParallelForSimdDirective( 8470 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, 8471 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) { 8472 if (!AStmt) 8473 return StmtError(); 8474 8475 auto *CS = cast<CapturedStmt>(AStmt); 8476 // 1.2.2 OpenMP Language Terminology 8477 // Structured block - An executable statement with a single entry at the 8478 // top and a single exit at the bottom. 8479 // The point of exit cannot be a branch out of the structured block. 8480 // longjmp() and throw() must not violate the entry/exit criteria. 8481 CS->getCapturedDecl()->setNothrow(); 8482 for (int ThisCaptureLevel = 8483 getOpenMPCaptureLevels(OMPD_distribute_parallel_for_simd); 8484 ThisCaptureLevel > 1; --ThisCaptureLevel) { 8485 CS = cast<CapturedStmt>(CS->getCapturedStmt()); 8486 // 1.2.2 OpenMP Language Terminology 8487 // Structured block - An executable statement with a single entry at the 8488 // top and a single exit at the bottom. 8489 // The point of exit cannot be a branch out of the structured block. 8490 // longjmp() and throw() must not violate the entry/exit criteria. 8491 CS->getCapturedDecl()->setNothrow(); 8492 } 8493 8494 OMPLoopDirective::HelperExprs B; 8495 // In presence of clause 'collapse' with number of loops, it will 8496 // define the nested loops number. 8497 unsigned NestedLoopCount = checkOpenMPLoop( 8498 OMPD_distribute_parallel_for_simd, getCollapseNumberExpr(Clauses), 8499 nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStack, 8500 VarsWithImplicitDSA, B); 8501 if (NestedLoopCount == 0) 8502 return StmtError(); 8503 8504 assert((CurContext->isDependentContext() || B.builtAll()) && 8505 "omp for loop exprs were not built"); 8506 8507 if (!CurContext->isDependentContext()) { 8508 // Finalize the clauses that need pre-built expressions for CodeGen. 8509 for (OMPClause *C : Clauses) { 8510 if (auto *LC = dyn_cast<OMPLinearClause>(C)) 8511 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef), 8512 B.NumIterations, *this, CurScope, 8513 DSAStack)) 8514 return StmtError(); 8515 } 8516 } 8517 8518 if (checkSimdlenSafelenSpecified(*this, Clauses)) 8519 return StmtError(); 8520 8521 setFunctionHasBranchProtectedScope(); 8522 return OMPDistributeParallelForSimdDirective::Create( 8523 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B); 8524 } 8525 8526 StmtResult Sema::ActOnOpenMPDistributeSimdDirective( 8527 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, 8528 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) { 8529 if (!AStmt) 8530 return StmtError(); 8531 8532 auto *CS = cast<CapturedStmt>(AStmt); 8533 // 1.2.2 OpenMP Language Terminology 8534 // Structured block - An executable statement with a single entry at the 8535 // top and a single exit at the bottom. 8536 // The point of exit cannot be a branch out of the structured block. 8537 // longjmp() and throw() must not violate the entry/exit criteria. 8538 CS->getCapturedDecl()->setNothrow(); 8539 for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_distribute_simd); 8540 ThisCaptureLevel > 1; --ThisCaptureLevel) { 8541 CS = cast<CapturedStmt>(CS->getCapturedStmt()); 8542 // 1.2.2 OpenMP Language Terminology 8543 // Structured block - An executable statement with a single entry at the 8544 // top and a single exit at the bottom. 8545 // The point of exit cannot be a branch out of the structured block. 8546 // longjmp() and throw() must not violate the entry/exit criteria. 8547 CS->getCapturedDecl()->setNothrow(); 8548 } 8549 8550 OMPLoopDirective::HelperExprs B; 8551 // In presence of clause 'collapse' with number of loops, it will 8552 // define the nested loops number. 8553 unsigned NestedLoopCount = 8554 checkOpenMPLoop(OMPD_distribute_simd, getCollapseNumberExpr(Clauses), 8555 nullptr /*ordered not a clause on distribute*/, CS, *this, 8556 *DSAStack, VarsWithImplicitDSA, B); 8557 if (NestedLoopCount == 0) 8558 return StmtError(); 8559 8560 assert((CurContext->isDependentContext() || B.builtAll()) && 8561 "omp for loop exprs were not built"); 8562 8563 if (!CurContext->isDependentContext()) { 8564 // Finalize the clauses that need pre-built expressions for CodeGen. 8565 for (OMPClause *C : Clauses) { 8566 if (auto *LC = dyn_cast<OMPLinearClause>(C)) 8567 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef), 8568 B.NumIterations, *this, CurScope, 8569 DSAStack)) 8570 return StmtError(); 8571 } 8572 } 8573 8574 if (checkSimdlenSafelenSpecified(*this, Clauses)) 8575 return StmtError(); 8576 8577 setFunctionHasBranchProtectedScope(); 8578 return OMPDistributeSimdDirective::Create(Context, StartLoc, EndLoc, 8579 NestedLoopCount, Clauses, AStmt, B); 8580 } 8581 8582 StmtResult Sema::ActOnOpenMPTargetParallelForSimdDirective( 8583 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, 8584 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) { 8585 if (!AStmt) 8586 return StmtError(); 8587 8588 auto *CS = cast<CapturedStmt>(AStmt); 8589 // 1.2.2 OpenMP Language Terminology 8590 // Structured block - An executable statement with a single entry at the 8591 // top and a single exit at the bottom. 8592 // The point of exit cannot be a branch out of the structured block. 8593 // longjmp() and throw() must not violate the entry/exit criteria. 8594 CS->getCapturedDecl()->setNothrow(); 8595 for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_parallel_for); 8596 ThisCaptureLevel > 1; --ThisCaptureLevel) { 8597 CS = cast<CapturedStmt>(CS->getCapturedStmt()); 8598 // 1.2.2 OpenMP Language Terminology 8599 // Structured block - An executable statement with a single entry at the 8600 // top and a single exit at the bottom. 8601 // The point of exit cannot be a branch out of the structured block. 8602 // longjmp() and throw() must not violate the entry/exit criteria. 8603 CS->getCapturedDecl()->setNothrow(); 8604 } 8605 8606 OMPLoopDirective::HelperExprs B; 8607 // In presence of clause 'collapse' or 'ordered' with number of loops, it will 8608 // define the nested loops number. 8609 unsigned NestedLoopCount = checkOpenMPLoop( 8610 OMPD_target_parallel_for_simd, getCollapseNumberExpr(Clauses), 8611 getOrderedNumberExpr(Clauses), CS, *this, *DSAStack, 8612 VarsWithImplicitDSA, B); 8613 if (NestedLoopCount == 0) 8614 return StmtError(); 8615 8616 assert((CurContext->isDependentContext() || B.builtAll()) && 8617 "omp target parallel for simd loop exprs were not built"); 8618 8619 if (!CurContext->isDependentContext()) { 8620 // Finalize the clauses that need pre-built expressions for CodeGen. 8621 for (OMPClause *C : Clauses) { 8622 if (auto *LC = dyn_cast<OMPLinearClause>(C)) 8623 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef), 8624 B.NumIterations, *this, CurScope, 8625 DSAStack)) 8626 return StmtError(); 8627 } 8628 } 8629 if (checkSimdlenSafelenSpecified(*this, Clauses)) 8630 return StmtError(); 8631 8632 setFunctionHasBranchProtectedScope(); 8633 return OMPTargetParallelForSimdDirective::Create( 8634 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B); 8635 } 8636 8637 StmtResult Sema::ActOnOpenMPTargetSimdDirective( 8638 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, 8639 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) { 8640 if (!AStmt) 8641 return StmtError(); 8642 8643 auto *CS = cast<CapturedStmt>(AStmt); 8644 // 1.2.2 OpenMP Language Terminology 8645 // Structured block - An executable statement with a single entry at the 8646 // top and a single exit at the bottom. 8647 // The point of exit cannot be a branch out of the structured block. 8648 // longjmp() and throw() must not violate the entry/exit criteria. 8649 CS->getCapturedDecl()->setNothrow(); 8650 for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_simd); 8651 ThisCaptureLevel > 1; --ThisCaptureLevel) { 8652 CS = cast<CapturedStmt>(CS->getCapturedStmt()); 8653 // 1.2.2 OpenMP Language Terminology 8654 // Structured block - An executable statement with a single entry at the 8655 // top and a single exit at the bottom. 8656 // The point of exit cannot be a branch out of the structured block. 8657 // longjmp() and throw() must not violate the entry/exit criteria. 8658 CS->getCapturedDecl()->setNothrow(); 8659 } 8660 8661 OMPLoopDirective::HelperExprs B; 8662 // In presence of clause 'collapse' with number of loops, it will define the 8663 // nested loops number. 8664 unsigned NestedLoopCount = 8665 checkOpenMPLoop(OMPD_target_simd, getCollapseNumberExpr(Clauses), 8666 getOrderedNumberExpr(Clauses), CS, *this, *DSAStack, 8667 VarsWithImplicitDSA, B); 8668 if (NestedLoopCount == 0) 8669 return StmtError(); 8670 8671 assert((CurContext->isDependentContext() || B.builtAll()) && 8672 "omp target simd loop exprs were not built"); 8673 8674 if (!CurContext->isDependentContext()) { 8675 // Finalize the clauses that need pre-built expressions for CodeGen. 8676 for (OMPClause *C : Clauses) { 8677 if (auto *LC = dyn_cast<OMPLinearClause>(C)) 8678 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef), 8679 B.NumIterations, *this, CurScope, 8680 DSAStack)) 8681 return StmtError(); 8682 } 8683 } 8684 8685 if (checkSimdlenSafelenSpecified(*this, Clauses)) 8686 return StmtError(); 8687 8688 setFunctionHasBranchProtectedScope(); 8689 return OMPTargetSimdDirective::Create(Context, StartLoc, EndLoc, 8690 NestedLoopCount, Clauses, AStmt, B); 8691 } 8692 8693 StmtResult Sema::ActOnOpenMPTeamsDistributeDirective( 8694 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, 8695 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) { 8696 if (!AStmt) 8697 return StmtError(); 8698 8699 auto *CS = cast<CapturedStmt>(AStmt); 8700 // 1.2.2 OpenMP Language Terminology 8701 // Structured block - An executable statement with a single entry at the 8702 // top and a single exit at the bottom. 8703 // The point of exit cannot be a branch out of the structured block. 8704 // longjmp() and throw() must not violate the entry/exit criteria. 8705 CS->getCapturedDecl()->setNothrow(); 8706 for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_teams_distribute); 8707 ThisCaptureLevel > 1; --ThisCaptureLevel) { 8708 CS = cast<CapturedStmt>(CS->getCapturedStmt()); 8709 // 1.2.2 OpenMP Language Terminology 8710 // Structured block - An executable statement with a single entry at the 8711 // top and a single exit at the bottom. 8712 // The point of exit cannot be a branch out of the structured block. 8713 // longjmp() and throw() must not violate the entry/exit criteria. 8714 CS->getCapturedDecl()->setNothrow(); 8715 } 8716 8717 OMPLoopDirective::HelperExprs B; 8718 // In presence of clause 'collapse' with number of loops, it will 8719 // define the nested loops number. 8720 unsigned NestedLoopCount = 8721 checkOpenMPLoop(OMPD_teams_distribute, getCollapseNumberExpr(Clauses), 8722 nullptr /*ordered not a clause on distribute*/, CS, *this, 8723 *DSAStack, VarsWithImplicitDSA, B); 8724 if (NestedLoopCount == 0) 8725 return StmtError(); 8726 8727 assert((CurContext->isDependentContext() || B.builtAll()) && 8728 "omp teams distribute loop exprs were not built"); 8729 8730 setFunctionHasBranchProtectedScope(); 8731 8732 DSAStack->setParentTeamsRegionLoc(StartLoc); 8733 8734 return OMPTeamsDistributeDirective::Create( 8735 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B); 8736 } 8737 8738 StmtResult Sema::ActOnOpenMPTeamsDistributeSimdDirective( 8739 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, 8740 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) { 8741 if (!AStmt) 8742 return StmtError(); 8743 8744 auto *CS = cast<CapturedStmt>(AStmt); 8745 // 1.2.2 OpenMP Language Terminology 8746 // Structured block - An executable statement with a single entry at the 8747 // top and a single exit at the bottom. 8748 // The point of exit cannot be a branch out of the structured block. 8749 // longjmp() and throw() must not violate the entry/exit criteria. 8750 CS->getCapturedDecl()->setNothrow(); 8751 for (int ThisCaptureLevel = 8752 getOpenMPCaptureLevels(OMPD_teams_distribute_simd); 8753 ThisCaptureLevel > 1; --ThisCaptureLevel) { 8754 CS = cast<CapturedStmt>(CS->getCapturedStmt()); 8755 // 1.2.2 OpenMP Language Terminology 8756 // Structured block - An executable statement with a single entry at the 8757 // top and a single exit at the bottom. 8758 // The point of exit cannot be a branch out of the structured block. 8759 // longjmp() and throw() must not violate the entry/exit criteria. 8760 CS->getCapturedDecl()->setNothrow(); 8761 } 8762 8763 8764 OMPLoopDirective::HelperExprs B; 8765 // In presence of clause 'collapse' with number of loops, it will 8766 // define the nested loops number. 8767 unsigned NestedLoopCount = checkOpenMPLoop( 8768 OMPD_teams_distribute_simd, getCollapseNumberExpr(Clauses), 8769 nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStack, 8770 VarsWithImplicitDSA, B); 8771 8772 if (NestedLoopCount == 0) 8773 return StmtError(); 8774 8775 assert((CurContext->isDependentContext() || B.builtAll()) && 8776 "omp teams distribute simd loop exprs were not built"); 8777 8778 if (!CurContext->isDependentContext()) { 8779 // Finalize the clauses that need pre-built expressions for CodeGen. 8780 for (OMPClause *C : Clauses) { 8781 if (auto *LC = dyn_cast<OMPLinearClause>(C)) 8782 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef), 8783 B.NumIterations, *this, CurScope, 8784 DSAStack)) 8785 return StmtError(); 8786 } 8787 } 8788 8789 if (checkSimdlenSafelenSpecified(*this, Clauses)) 8790 return StmtError(); 8791 8792 setFunctionHasBranchProtectedScope(); 8793 8794 DSAStack->setParentTeamsRegionLoc(StartLoc); 8795 8796 return OMPTeamsDistributeSimdDirective::Create( 8797 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B); 8798 } 8799 8800 StmtResult Sema::ActOnOpenMPTeamsDistributeParallelForSimdDirective( 8801 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, 8802 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) { 8803 if (!AStmt) 8804 return StmtError(); 8805 8806 auto *CS = cast<CapturedStmt>(AStmt); 8807 // 1.2.2 OpenMP Language Terminology 8808 // Structured block - An executable statement with a single entry at the 8809 // top and a single exit at the bottom. 8810 // The point of exit cannot be a branch out of the structured block. 8811 // longjmp() and throw() must not violate the entry/exit criteria. 8812 CS->getCapturedDecl()->setNothrow(); 8813 8814 for (int ThisCaptureLevel = 8815 getOpenMPCaptureLevels(OMPD_teams_distribute_parallel_for_simd); 8816 ThisCaptureLevel > 1; --ThisCaptureLevel) { 8817 CS = cast<CapturedStmt>(CS->getCapturedStmt()); 8818 // 1.2.2 OpenMP Language Terminology 8819 // Structured block - An executable statement with a single entry at the 8820 // top and a single exit at the bottom. 8821 // The point of exit cannot be a branch out of the structured block. 8822 // longjmp() and throw() must not violate the entry/exit criteria. 8823 CS->getCapturedDecl()->setNothrow(); 8824 } 8825 8826 OMPLoopDirective::HelperExprs B; 8827 // In presence of clause 'collapse' with number of loops, it will 8828 // define the nested loops number. 8829 unsigned NestedLoopCount = checkOpenMPLoop( 8830 OMPD_teams_distribute_parallel_for_simd, getCollapseNumberExpr(Clauses), 8831 nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStack, 8832 VarsWithImplicitDSA, B); 8833 8834 if (NestedLoopCount == 0) 8835 return StmtError(); 8836 8837 assert((CurContext->isDependentContext() || B.builtAll()) && 8838 "omp for loop exprs were not built"); 8839 8840 if (!CurContext->isDependentContext()) { 8841 // Finalize the clauses that need pre-built expressions for CodeGen. 8842 for (OMPClause *C : Clauses) { 8843 if (auto *LC = dyn_cast<OMPLinearClause>(C)) 8844 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef), 8845 B.NumIterations, *this, CurScope, 8846 DSAStack)) 8847 return StmtError(); 8848 } 8849 } 8850 8851 if (checkSimdlenSafelenSpecified(*this, Clauses)) 8852 return StmtError(); 8853 8854 setFunctionHasBranchProtectedScope(); 8855 8856 DSAStack->setParentTeamsRegionLoc(StartLoc); 8857 8858 return OMPTeamsDistributeParallelForSimdDirective::Create( 8859 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B); 8860 } 8861 8862 StmtResult Sema::ActOnOpenMPTeamsDistributeParallelForDirective( 8863 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, 8864 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) { 8865 if (!AStmt) 8866 return StmtError(); 8867 8868 auto *CS = cast<CapturedStmt>(AStmt); 8869 // 1.2.2 OpenMP Language Terminology 8870 // Structured block - An executable statement with a single entry at the 8871 // top and a single exit at the bottom. 8872 // The point of exit cannot be a branch out of the structured block. 8873 // longjmp() and throw() must not violate the entry/exit criteria. 8874 CS->getCapturedDecl()->setNothrow(); 8875 8876 for (int ThisCaptureLevel = 8877 getOpenMPCaptureLevels(OMPD_teams_distribute_parallel_for); 8878 ThisCaptureLevel > 1; --ThisCaptureLevel) { 8879 CS = cast<CapturedStmt>(CS->getCapturedStmt()); 8880 // 1.2.2 OpenMP Language Terminology 8881 // Structured block - An executable statement with a single entry at the 8882 // top and a single exit at the bottom. 8883 // The point of exit cannot be a branch out of the structured block. 8884 // longjmp() and throw() must not violate the entry/exit criteria. 8885 CS->getCapturedDecl()->setNothrow(); 8886 } 8887 8888 OMPLoopDirective::HelperExprs B; 8889 // In presence of clause 'collapse' with number of loops, it will 8890 // define the nested loops number. 8891 unsigned NestedLoopCount = checkOpenMPLoop( 8892 OMPD_teams_distribute_parallel_for, getCollapseNumberExpr(Clauses), 8893 nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStack, 8894 VarsWithImplicitDSA, B); 8895 8896 if (NestedLoopCount == 0) 8897 return StmtError(); 8898 8899 assert((CurContext->isDependentContext() || B.builtAll()) && 8900 "omp for loop exprs were not built"); 8901 8902 setFunctionHasBranchProtectedScope(); 8903 8904 DSAStack->setParentTeamsRegionLoc(StartLoc); 8905 8906 return OMPTeamsDistributeParallelForDirective::Create( 8907 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B, 8908 DSAStack->isCancelRegion()); 8909 } 8910 8911 StmtResult Sema::ActOnOpenMPTargetTeamsDirective(ArrayRef<OMPClause *> Clauses, 8912 Stmt *AStmt, 8913 SourceLocation StartLoc, 8914 SourceLocation EndLoc) { 8915 if (!AStmt) 8916 return StmtError(); 8917 8918 auto *CS = cast<CapturedStmt>(AStmt); 8919 // 1.2.2 OpenMP Language Terminology 8920 // Structured block - An executable statement with a single entry at the 8921 // top and a single exit at the bottom. 8922 // The point of exit cannot be a branch out of the structured block. 8923 // longjmp() and throw() must not violate the entry/exit criteria. 8924 CS->getCapturedDecl()->setNothrow(); 8925 8926 for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_teams); 8927 ThisCaptureLevel > 1; --ThisCaptureLevel) { 8928 CS = cast<CapturedStmt>(CS->getCapturedStmt()); 8929 // 1.2.2 OpenMP Language Terminology 8930 // Structured block - An executable statement with a single entry at the 8931 // top and a single exit at the bottom. 8932 // The point of exit cannot be a branch out of the structured block. 8933 // longjmp() and throw() must not violate the entry/exit criteria. 8934 CS->getCapturedDecl()->setNothrow(); 8935 } 8936 setFunctionHasBranchProtectedScope(); 8937 8938 return OMPTargetTeamsDirective::Create(Context, StartLoc, EndLoc, Clauses, 8939 AStmt); 8940 } 8941 8942 StmtResult Sema::ActOnOpenMPTargetTeamsDistributeDirective( 8943 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, 8944 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) { 8945 if (!AStmt) 8946 return StmtError(); 8947 8948 auto *CS = cast<CapturedStmt>(AStmt); 8949 // 1.2.2 OpenMP Language Terminology 8950 // Structured block - An executable statement with a single entry at the 8951 // top and a single exit at the bottom. 8952 // The point of exit cannot be a branch out of the structured block. 8953 // longjmp() and throw() must not violate the entry/exit criteria. 8954 CS->getCapturedDecl()->setNothrow(); 8955 for (int ThisCaptureLevel = 8956 getOpenMPCaptureLevels(OMPD_target_teams_distribute); 8957 ThisCaptureLevel > 1; --ThisCaptureLevel) { 8958 CS = cast<CapturedStmt>(CS->getCapturedStmt()); 8959 // 1.2.2 OpenMP Language Terminology 8960 // Structured block - An executable statement with a single entry at the 8961 // top and a single exit at the bottom. 8962 // The point of exit cannot be a branch out of the structured block. 8963 // longjmp() and throw() must not violate the entry/exit criteria. 8964 CS->getCapturedDecl()->setNothrow(); 8965 } 8966 8967 OMPLoopDirective::HelperExprs B; 8968 // In presence of clause 'collapse' with number of loops, it will 8969 // define the nested loops number. 8970 unsigned NestedLoopCount = checkOpenMPLoop( 8971 OMPD_target_teams_distribute, getCollapseNumberExpr(Clauses), 8972 nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStack, 8973 VarsWithImplicitDSA, B); 8974 if (NestedLoopCount == 0) 8975 return StmtError(); 8976 8977 assert((CurContext->isDependentContext() || B.builtAll()) && 8978 "omp target teams distribute loop exprs were not built"); 8979 8980 setFunctionHasBranchProtectedScope(); 8981 return OMPTargetTeamsDistributeDirective::Create( 8982 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B); 8983 } 8984 8985 StmtResult Sema::ActOnOpenMPTargetTeamsDistributeParallelForDirective( 8986 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, 8987 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) { 8988 if (!AStmt) 8989 return StmtError(); 8990 8991 auto *CS = cast<CapturedStmt>(AStmt); 8992 // 1.2.2 OpenMP Language Terminology 8993 // Structured block - An executable statement with a single entry at the 8994 // top and a single exit at the bottom. 8995 // The point of exit cannot be a branch out of the structured block. 8996 // longjmp() and throw() must not violate the entry/exit criteria. 8997 CS->getCapturedDecl()->setNothrow(); 8998 for (int ThisCaptureLevel = 8999 getOpenMPCaptureLevels(OMPD_target_teams_distribute_parallel_for); 9000 ThisCaptureLevel > 1; --ThisCaptureLevel) { 9001 CS = cast<CapturedStmt>(CS->getCapturedStmt()); 9002 // 1.2.2 OpenMP Language Terminology 9003 // Structured block - An executable statement with a single entry at the 9004 // top and a single exit at the bottom. 9005 // The point of exit cannot be a branch out of the structured block. 9006 // longjmp() and throw() must not violate the entry/exit criteria. 9007 CS->getCapturedDecl()->setNothrow(); 9008 } 9009 9010 OMPLoopDirective::HelperExprs B; 9011 // In presence of clause 'collapse' with number of loops, it will 9012 // define the nested loops number. 9013 unsigned NestedLoopCount = checkOpenMPLoop( 9014 OMPD_target_teams_distribute_parallel_for, getCollapseNumberExpr(Clauses), 9015 nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStack, 9016 VarsWithImplicitDSA, B); 9017 if (NestedLoopCount == 0) 9018 return StmtError(); 9019 9020 assert((CurContext->isDependentContext() || B.builtAll()) && 9021 "omp target teams distribute parallel for loop exprs were not built"); 9022 9023 if (!CurContext->isDependentContext()) { 9024 // Finalize the clauses that need pre-built expressions for CodeGen. 9025 for (OMPClause *C : Clauses) { 9026 if (auto *LC = dyn_cast<OMPLinearClause>(C)) 9027 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef), 9028 B.NumIterations, *this, CurScope, 9029 DSAStack)) 9030 return StmtError(); 9031 } 9032 } 9033 9034 setFunctionHasBranchProtectedScope(); 9035 return OMPTargetTeamsDistributeParallelForDirective::Create( 9036 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B, 9037 DSAStack->isCancelRegion()); 9038 } 9039 9040 StmtResult Sema::ActOnOpenMPTargetTeamsDistributeParallelForSimdDirective( 9041 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, 9042 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) { 9043 if (!AStmt) 9044 return StmtError(); 9045 9046 auto *CS = cast<CapturedStmt>(AStmt); 9047 // 1.2.2 OpenMP Language Terminology 9048 // Structured block - An executable statement with a single entry at the 9049 // top and a single exit at the bottom. 9050 // The point of exit cannot be a branch out of the structured block. 9051 // longjmp() and throw() must not violate the entry/exit criteria. 9052 CS->getCapturedDecl()->setNothrow(); 9053 for (int ThisCaptureLevel = getOpenMPCaptureLevels( 9054 OMPD_target_teams_distribute_parallel_for_simd); 9055 ThisCaptureLevel > 1; --ThisCaptureLevel) { 9056 CS = cast<CapturedStmt>(CS->getCapturedStmt()); 9057 // 1.2.2 OpenMP Language Terminology 9058 // Structured block - An executable statement with a single entry at the 9059 // top and a single exit at the bottom. 9060 // The point of exit cannot be a branch out of the structured block. 9061 // longjmp() and throw() must not violate the entry/exit criteria. 9062 CS->getCapturedDecl()->setNothrow(); 9063 } 9064 9065 OMPLoopDirective::HelperExprs B; 9066 // In presence of clause 'collapse' with number of loops, it will 9067 // define the nested loops number. 9068 unsigned NestedLoopCount = 9069 checkOpenMPLoop(OMPD_target_teams_distribute_parallel_for_simd, 9070 getCollapseNumberExpr(Clauses), 9071 nullptr /*ordered not a clause on distribute*/, CS, *this, 9072 *DSAStack, VarsWithImplicitDSA, B); 9073 if (NestedLoopCount == 0) 9074 return StmtError(); 9075 9076 assert((CurContext->isDependentContext() || B.builtAll()) && 9077 "omp target teams distribute parallel for simd loop exprs were not " 9078 "built"); 9079 9080 if (!CurContext->isDependentContext()) { 9081 // Finalize the clauses that need pre-built expressions for CodeGen. 9082 for (OMPClause *C : Clauses) { 9083 if (auto *LC = dyn_cast<OMPLinearClause>(C)) 9084 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef), 9085 B.NumIterations, *this, CurScope, 9086 DSAStack)) 9087 return StmtError(); 9088 } 9089 } 9090 9091 if (checkSimdlenSafelenSpecified(*this, Clauses)) 9092 return StmtError(); 9093 9094 setFunctionHasBranchProtectedScope(); 9095 return OMPTargetTeamsDistributeParallelForSimdDirective::Create( 9096 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B); 9097 } 9098 9099 StmtResult Sema::ActOnOpenMPTargetTeamsDistributeSimdDirective( 9100 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, 9101 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) { 9102 if (!AStmt) 9103 return StmtError(); 9104 9105 auto *CS = cast<CapturedStmt>(AStmt); 9106 // 1.2.2 OpenMP Language Terminology 9107 // Structured block - An executable statement with a single entry at the 9108 // top and a single exit at the bottom. 9109 // The point of exit cannot be a branch out of the structured block. 9110 // longjmp() and throw() must not violate the entry/exit criteria. 9111 CS->getCapturedDecl()->setNothrow(); 9112 for (int ThisCaptureLevel = 9113 getOpenMPCaptureLevels(OMPD_target_teams_distribute_simd); 9114 ThisCaptureLevel > 1; --ThisCaptureLevel) { 9115 CS = cast<CapturedStmt>(CS->getCapturedStmt()); 9116 // 1.2.2 OpenMP Language Terminology 9117 // Structured block - An executable statement with a single entry at the 9118 // top and a single exit at the bottom. 9119 // The point of exit cannot be a branch out of the structured block. 9120 // longjmp() and throw() must not violate the entry/exit criteria. 9121 CS->getCapturedDecl()->setNothrow(); 9122 } 9123 9124 OMPLoopDirective::HelperExprs B; 9125 // In presence of clause 'collapse' with number of loops, it will 9126 // define the nested loops number. 9127 unsigned NestedLoopCount = checkOpenMPLoop( 9128 OMPD_target_teams_distribute_simd, getCollapseNumberExpr(Clauses), 9129 nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStack, 9130 VarsWithImplicitDSA, B); 9131 if (NestedLoopCount == 0) 9132 return StmtError(); 9133 9134 assert((CurContext->isDependentContext() || B.builtAll()) && 9135 "omp target teams distribute simd loop exprs were not built"); 9136 9137 if (!CurContext->isDependentContext()) { 9138 // Finalize the clauses that need pre-built expressions for CodeGen. 9139 for (OMPClause *C : Clauses) { 9140 if (auto *LC = dyn_cast<OMPLinearClause>(C)) 9141 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef), 9142 B.NumIterations, *this, CurScope, 9143 DSAStack)) 9144 return StmtError(); 9145 } 9146 } 9147 9148 if (checkSimdlenSafelenSpecified(*this, Clauses)) 9149 return StmtError(); 9150 9151 setFunctionHasBranchProtectedScope(); 9152 return OMPTargetTeamsDistributeSimdDirective::Create( 9153 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B); 9154 } 9155 9156 OMPClause *Sema::ActOnOpenMPSingleExprClause(OpenMPClauseKind Kind, Expr *Expr, 9157 SourceLocation StartLoc, 9158 SourceLocation LParenLoc, 9159 SourceLocation EndLoc) { 9160 OMPClause *Res = nullptr; 9161 switch (Kind) { 9162 case OMPC_final: 9163 Res = ActOnOpenMPFinalClause(Expr, StartLoc, LParenLoc, EndLoc); 9164 break; 9165 case OMPC_num_threads: 9166 Res = ActOnOpenMPNumThreadsClause(Expr, StartLoc, LParenLoc, EndLoc); 9167 break; 9168 case OMPC_safelen: 9169 Res = ActOnOpenMPSafelenClause(Expr, StartLoc, LParenLoc, EndLoc); 9170 break; 9171 case OMPC_simdlen: 9172 Res = ActOnOpenMPSimdlenClause(Expr, StartLoc, LParenLoc, EndLoc); 9173 break; 9174 case OMPC_allocator: 9175 Res = ActOnOpenMPAllocatorClause(Expr, StartLoc, LParenLoc, EndLoc); 9176 break; 9177 case OMPC_collapse: 9178 Res = ActOnOpenMPCollapseClause(Expr, StartLoc, LParenLoc, EndLoc); 9179 break; 9180 case OMPC_ordered: 9181 Res = ActOnOpenMPOrderedClause(StartLoc, EndLoc, LParenLoc, Expr); 9182 break; 9183 case OMPC_device: 9184 Res = ActOnOpenMPDeviceClause(Expr, StartLoc, LParenLoc, EndLoc); 9185 break; 9186 case OMPC_num_teams: 9187 Res = ActOnOpenMPNumTeamsClause(Expr, StartLoc, LParenLoc, EndLoc); 9188 break; 9189 case OMPC_thread_limit: 9190 Res = ActOnOpenMPThreadLimitClause(Expr, StartLoc, LParenLoc, EndLoc); 9191 break; 9192 case OMPC_priority: 9193 Res = ActOnOpenMPPriorityClause(Expr, StartLoc, LParenLoc, EndLoc); 9194 break; 9195 case OMPC_grainsize: 9196 Res = ActOnOpenMPGrainsizeClause(Expr, StartLoc, LParenLoc, EndLoc); 9197 break; 9198 case OMPC_num_tasks: 9199 Res = ActOnOpenMPNumTasksClause(Expr, StartLoc, LParenLoc, EndLoc); 9200 break; 9201 case OMPC_hint: 9202 Res = ActOnOpenMPHintClause(Expr, StartLoc, LParenLoc, EndLoc); 9203 break; 9204 case OMPC_if: 9205 case OMPC_default: 9206 case OMPC_proc_bind: 9207 case OMPC_schedule: 9208 case OMPC_private: 9209 case OMPC_firstprivate: 9210 case OMPC_lastprivate: 9211 case OMPC_shared: 9212 case OMPC_reduction: 9213 case OMPC_task_reduction: 9214 case OMPC_in_reduction: 9215 case OMPC_linear: 9216 case OMPC_aligned: 9217 case OMPC_copyin: 9218 case OMPC_copyprivate: 9219 case OMPC_nowait: 9220 case OMPC_untied: 9221 case OMPC_mergeable: 9222 case OMPC_threadprivate: 9223 case OMPC_allocate: 9224 case OMPC_flush: 9225 case OMPC_read: 9226 case OMPC_write: 9227 case OMPC_update: 9228 case OMPC_capture: 9229 case OMPC_seq_cst: 9230 case OMPC_depend: 9231 case OMPC_threads: 9232 case OMPC_simd: 9233 case OMPC_map: 9234 case OMPC_nogroup: 9235 case OMPC_dist_schedule: 9236 case OMPC_defaultmap: 9237 case OMPC_unknown: 9238 case OMPC_uniform: 9239 case OMPC_to: 9240 case OMPC_from: 9241 case OMPC_use_device_ptr: 9242 case OMPC_is_device_ptr: 9243 case OMPC_unified_address: 9244 case OMPC_unified_shared_memory: 9245 case OMPC_reverse_offload: 9246 case OMPC_dynamic_allocators: 9247 case OMPC_atomic_default_mem_order: 9248 llvm_unreachable("Clause is not allowed."); 9249 } 9250 return Res; 9251 } 9252 9253 // An OpenMP directive such as 'target parallel' has two captured regions: 9254 // for the 'target' and 'parallel' respectively. This function returns 9255 // the region in which to capture expressions associated with a clause. 9256 // A return value of OMPD_unknown signifies that the expression should not 9257 // be captured. 9258 static OpenMPDirectiveKind getOpenMPCaptureRegionForClause( 9259 OpenMPDirectiveKind DKind, OpenMPClauseKind CKind, 9260 OpenMPDirectiveKind NameModifier = OMPD_unknown) { 9261 OpenMPDirectiveKind CaptureRegion = OMPD_unknown; 9262 switch (CKind) { 9263 case OMPC_if: 9264 switch (DKind) { 9265 case OMPD_target_parallel: 9266 case OMPD_target_parallel_for: 9267 case OMPD_target_parallel_for_simd: 9268 // If this clause applies to the nested 'parallel' region, capture within 9269 // the 'target' region, otherwise do not capture. 9270 if (NameModifier == OMPD_unknown || NameModifier == OMPD_parallel) 9271 CaptureRegion = OMPD_target; 9272 break; 9273 case OMPD_target_teams_distribute_parallel_for: 9274 case OMPD_target_teams_distribute_parallel_for_simd: 9275 // If this clause applies to the nested 'parallel' region, capture within 9276 // the 'teams' region, otherwise do not capture. 9277 if (NameModifier == OMPD_unknown || NameModifier == OMPD_parallel) 9278 CaptureRegion = OMPD_teams; 9279 break; 9280 case OMPD_teams_distribute_parallel_for: 9281 case OMPD_teams_distribute_parallel_for_simd: 9282 CaptureRegion = OMPD_teams; 9283 break; 9284 case OMPD_target_update: 9285 case OMPD_target_enter_data: 9286 case OMPD_target_exit_data: 9287 CaptureRegion = OMPD_task; 9288 break; 9289 case OMPD_cancel: 9290 case OMPD_parallel: 9291 case OMPD_parallel_sections: 9292 case OMPD_parallel_for: 9293 case OMPD_parallel_for_simd: 9294 case OMPD_target: 9295 case OMPD_target_simd: 9296 case OMPD_target_teams: 9297 case OMPD_target_teams_distribute: 9298 case OMPD_target_teams_distribute_simd: 9299 case OMPD_distribute_parallel_for: 9300 case OMPD_distribute_parallel_for_simd: 9301 case OMPD_task: 9302 case OMPD_taskloop: 9303 case OMPD_taskloop_simd: 9304 case OMPD_target_data: 9305 // Do not capture if-clause expressions. 9306 break; 9307 case OMPD_threadprivate: 9308 case OMPD_allocate: 9309 case OMPD_taskyield: 9310 case OMPD_barrier: 9311 case OMPD_taskwait: 9312 case OMPD_cancellation_point: 9313 case OMPD_flush: 9314 case OMPD_declare_reduction: 9315 case OMPD_declare_mapper: 9316 case OMPD_declare_simd: 9317 case OMPD_declare_target: 9318 case OMPD_end_declare_target: 9319 case OMPD_teams: 9320 case OMPD_simd: 9321 case OMPD_for: 9322 case OMPD_for_simd: 9323 case OMPD_sections: 9324 case OMPD_section: 9325 case OMPD_single: 9326 case OMPD_master: 9327 case OMPD_critical: 9328 case OMPD_taskgroup: 9329 case OMPD_distribute: 9330 case OMPD_ordered: 9331 case OMPD_atomic: 9332 case OMPD_distribute_simd: 9333 case OMPD_teams_distribute: 9334 case OMPD_teams_distribute_simd: 9335 case OMPD_requires: 9336 llvm_unreachable("Unexpected OpenMP directive with if-clause"); 9337 case OMPD_unknown: 9338 llvm_unreachable("Unknown OpenMP directive"); 9339 } 9340 break; 9341 case OMPC_num_threads: 9342 switch (DKind) { 9343 case OMPD_target_parallel: 9344 case OMPD_target_parallel_for: 9345 case OMPD_target_parallel_for_simd: 9346 CaptureRegion = OMPD_target; 9347 break; 9348 case OMPD_teams_distribute_parallel_for: 9349 case OMPD_teams_distribute_parallel_for_simd: 9350 case OMPD_target_teams_distribute_parallel_for: 9351 case OMPD_target_teams_distribute_parallel_for_simd: 9352 CaptureRegion = OMPD_teams; 9353 break; 9354 case OMPD_parallel: 9355 case OMPD_parallel_sections: 9356 case OMPD_parallel_for: 9357 case OMPD_parallel_for_simd: 9358 case OMPD_distribute_parallel_for: 9359 case OMPD_distribute_parallel_for_simd: 9360 // Do not capture num_threads-clause expressions. 9361 break; 9362 case OMPD_target_data: 9363 case OMPD_target_enter_data: 9364 case OMPD_target_exit_data: 9365 case OMPD_target_update: 9366 case OMPD_target: 9367 case OMPD_target_simd: 9368 case OMPD_target_teams: 9369 case OMPD_target_teams_distribute: 9370 case OMPD_target_teams_distribute_simd: 9371 case OMPD_cancel: 9372 case OMPD_task: 9373 case OMPD_taskloop: 9374 case OMPD_taskloop_simd: 9375 case OMPD_threadprivate: 9376 case OMPD_allocate: 9377 case OMPD_taskyield: 9378 case OMPD_barrier: 9379 case OMPD_taskwait: 9380 case OMPD_cancellation_point: 9381 case OMPD_flush: 9382 case OMPD_declare_reduction: 9383 case OMPD_declare_mapper: 9384 case OMPD_declare_simd: 9385 case OMPD_declare_target: 9386 case OMPD_end_declare_target: 9387 case OMPD_teams: 9388 case OMPD_simd: 9389 case OMPD_for: 9390 case OMPD_for_simd: 9391 case OMPD_sections: 9392 case OMPD_section: 9393 case OMPD_single: 9394 case OMPD_master: 9395 case OMPD_critical: 9396 case OMPD_taskgroup: 9397 case OMPD_distribute: 9398 case OMPD_ordered: 9399 case OMPD_atomic: 9400 case OMPD_distribute_simd: 9401 case OMPD_teams_distribute: 9402 case OMPD_teams_distribute_simd: 9403 case OMPD_requires: 9404 llvm_unreachable("Unexpected OpenMP directive with num_threads-clause"); 9405 case OMPD_unknown: 9406 llvm_unreachable("Unknown OpenMP directive"); 9407 } 9408 break; 9409 case OMPC_num_teams: 9410 switch (DKind) { 9411 case OMPD_target_teams: 9412 case OMPD_target_teams_distribute: 9413 case OMPD_target_teams_distribute_simd: 9414 case OMPD_target_teams_distribute_parallel_for: 9415 case OMPD_target_teams_distribute_parallel_for_simd: 9416 CaptureRegion = OMPD_target; 9417 break; 9418 case OMPD_teams_distribute_parallel_for: 9419 case OMPD_teams_distribute_parallel_for_simd: 9420 case OMPD_teams: 9421 case OMPD_teams_distribute: 9422 case OMPD_teams_distribute_simd: 9423 // Do not capture num_teams-clause expressions. 9424 break; 9425 case OMPD_distribute_parallel_for: 9426 case OMPD_distribute_parallel_for_simd: 9427 case OMPD_task: 9428 case OMPD_taskloop: 9429 case OMPD_taskloop_simd: 9430 case OMPD_target_data: 9431 case OMPD_target_enter_data: 9432 case OMPD_target_exit_data: 9433 case OMPD_target_update: 9434 case OMPD_cancel: 9435 case OMPD_parallel: 9436 case OMPD_parallel_sections: 9437 case OMPD_parallel_for: 9438 case OMPD_parallel_for_simd: 9439 case OMPD_target: 9440 case OMPD_target_simd: 9441 case OMPD_target_parallel: 9442 case OMPD_target_parallel_for: 9443 case OMPD_target_parallel_for_simd: 9444 case OMPD_threadprivate: 9445 case OMPD_allocate: 9446 case OMPD_taskyield: 9447 case OMPD_barrier: 9448 case OMPD_taskwait: 9449 case OMPD_cancellation_point: 9450 case OMPD_flush: 9451 case OMPD_declare_reduction: 9452 case OMPD_declare_mapper: 9453 case OMPD_declare_simd: 9454 case OMPD_declare_target: 9455 case OMPD_end_declare_target: 9456 case OMPD_simd: 9457 case OMPD_for: 9458 case OMPD_for_simd: 9459 case OMPD_sections: 9460 case OMPD_section: 9461 case OMPD_single: 9462 case OMPD_master: 9463 case OMPD_critical: 9464 case OMPD_taskgroup: 9465 case OMPD_distribute: 9466 case OMPD_ordered: 9467 case OMPD_atomic: 9468 case OMPD_distribute_simd: 9469 case OMPD_requires: 9470 llvm_unreachable("Unexpected OpenMP directive with num_teams-clause"); 9471 case OMPD_unknown: 9472 llvm_unreachable("Unknown OpenMP directive"); 9473 } 9474 break; 9475 case OMPC_thread_limit: 9476 switch (DKind) { 9477 case OMPD_target_teams: 9478 case OMPD_target_teams_distribute: 9479 case OMPD_target_teams_distribute_simd: 9480 case OMPD_target_teams_distribute_parallel_for: 9481 case OMPD_target_teams_distribute_parallel_for_simd: 9482 CaptureRegion = OMPD_target; 9483 break; 9484 case OMPD_teams_distribute_parallel_for: 9485 case OMPD_teams_distribute_parallel_for_simd: 9486 case OMPD_teams: 9487 case OMPD_teams_distribute: 9488 case OMPD_teams_distribute_simd: 9489 // Do not capture thread_limit-clause expressions. 9490 break; 9491 case OMPD_distribute_parallel_for: 9492 case OMPD_distribute_parallel_for_simd: 9493 case OMPD_task: 9494 case OMPD_taskloop: 9495 case OMPD_taskloop_simd: 9496 case OMPD_target_data: 9497 case OMPD_target_enter_data: 9498 case OMPD_target_exit_data: 9499 case OMPD_target_update: 9500 case OMPD_cancel: 9501 case OMPD_parallel: 9502 case OMPD_parallel_sections: 9503 case OMPD_parallel_for: 9504 case OMPD_parallel_for_simd: 9505 case OMPD_target: 9506 case OMPD_target_simd: 9507 case OMPD_target_parallel: 9508 case OMPD_target_parallel_for: 9509 case OMPD_target_parallel_for_simd: 9510 case OMPD_threadprivate: 9511 case OMPD_allocate: 9512 case OMPD_taskyield: 9513 case OMPD_barrier: 9514 case OMPD_taskwait: 9515 case OMPD_cancellation_point: 9516 case OMPD_flush: 9517 case OMPD_declare_reduction: 9518 case OMPD_declare_mapper: 9519 case OMPD_declare_simd: 9520 case OMPD_declare_target: 9521 case OMPD_end_declare_target: 9522 case OMPD_simd: 9523 case OMPD_for: 9524 case OMPD_for_simd: 9525 case OMPD_sections: 9526 case OMPD_section: 9527 case OMPD_single: 9528 case OMPD_master: 9529 case OMPD_critical: 9530 case OMPD_taskgroup: 9531 case OMPD_distribute: 9532 case OMPD_ordered: 9533 case OMPD_atomic: 9534 case OMPD_distribute_simd: 9535 case OMPD_requires: 9536 llvm_unreachable("Unexpected OpenMP directive with thread_limit-clause"); 9537 case OMPD_unknown: 9538 llvm_unreachable("Unknown OpenMP directive"); 9539 } 9540 break; 9541 case OMPC_schedule: 9542 switch (DKind) { 9543 case OMPD_parallel_for: 9544 case OMPD_parallel_for_simd: 9545 case OMPD_distribute_parallel_for: 9546 case OMPD_distribute_parallel_for_simd: 9547 case OMPD_teams_distribute_parallel_for: 9548 case OMPD_teams_distribute_parallel_for_simd: 9549 case OMPD_target_parallel_for: 9550 case OMPD_target_parallel_for_simd: 9551 case OMPD_target_teams_distribute_parallel_for: 9552 case OMPD_target_teams_distribute_parallel_for_simd: 9553 CaptureRegion = OMPD_parallel; 9554 break; 9555 case OMPD_for: 9556 case OMPD_for_simd: 9557 // Do not capture schedule-clause expressions. 9558 break; 9559 case OMPD_task: 9560 case OMPD_taskloop: 9561 case OMPD_taskloop_simd: 9562 case OMPD_target_data: 9563 case OMPD_target_enter_data: 9564 case OMPD_target_exit_data: 9565 case OMPD_target_update: 9566 case OMPD_teams: 9567 case OMPD_teams_distribute: 9568 case OMPD_teams_distribute_simd: 9569 case OMPD_target_teams_distribute: 9570 case OMPD_target_teams_distribute_simd: 9571 case OMPD_target: 9572 case OMPD_target_simd: 9573 case OMPD_target_parallel: 9574 case OMPD_cancel: 9575 case OMPD_parallel: 9576 case OMPD_parallel_sections: 9577 case OMPD_threadprivate: 9578 case OMPD_allocate: 9579 case OMPD_taskyield: 9580 case OMPD_barrier: 9581 case OMPD_taskwait: 9582 case OMPD_cancellation_point: 9583 case OMPD_flush: 9584 case OMPD_declare_reduction: 9585 case OMPD_declare_mapper: 9586 case OMPD_declare_simd: 9587 case OMPD_declare_target: 9588 case OMPD_end_declare_target: 9589 case OMPD_simd: 9590 case OMPD_sections: 9591 case OMPD_section: 9592 case OMPD_single: 9593 case OMPD_master: 9594 case OMPD_critical: 9595 case OMPD_taskgroup: 9596 case OMPD_distribute: 9597 case OMPD_ordered: 9598 case OMPD_atomic: 9599 case OMPD_distribute_simd: 9600 case OMPD_target_teams: 9601 case OMPD_requires: 9602 llvm_unreachable("Unexpected OpenMP directive with schedule clause"); 9603 case OMPD_unknown: 9604 llvm_unreachable("Unknown OpenMP directive"); 9605 } 9606 break; 9607 case OMPC_dist_schedule: 9608 switch (DKind) { 9609 case OMPD_teams_distribute_parallel_for: 9610 case OMPD_teams_distribute_parallel_for_simd: 9611 case OMPD_teams_distribute: 9612 case OMPD_teams_distribute_simd: 9613 case OMPD_target_teams_distribute_parallel_for: 9614 case OMPD_target_teams_distribute_parallel_for_simd: 9615 case OMPD_target_teams_distribute: 9616 case OMPD_target_teams_distribute_simd: 9617 CaptureRegion = OMPD_teams; 9618 break; 9619 case OMPD_distribute_parallel_for: 9620 case OMPD_distribute_parallel_for_simd: 9621 case OMPD_distribute: 9622 case OMPD_distribute_simd: 9623 // Do not capture thread_limit-clause expressions. 9624 break; 9625 case OMPD_parallel_for: 9626 case OMPD_parallel_for_simd: 9627 case OMPD_target_parallel_for_simd: 9628 case OMPD_target_parallel_for: 9629 case OMPD_task: 9630 case OMPD_taskloop: 9631 case OMPD_taskloop_simd: 9632 case OMPD_target_data: 9633 case OMPD_target_enter_data: 9634 case OMPD_target_exit_data: 9635 case OMPD_target_update: 9636 case OMPD_teams: 9637 case OMPD_target: 9638 case OMPD_target_simd: 9639 case OMPD_target_parallel: 9640 case OMPD_cancel: 9641 case OMPD_parallel: 9642 case OMPD_parallel_sections: 9643 case OMPD_threadprivate: 9644 case OMPD_allocate: 9645 case OMPD_taskyield: 9646 case OMPD_barrier: 9647 case OMPD_taskwait: 9648 case OMPD_cancellation_point: 9649 case OMPD_flush: 9650 case OMPD_declare_reduction: 9651 case OMPD_declare_mapper: 9652 case OMPD_declare_simd: 9653 case OMPD_declare_target: 9654 case OMPD_end_declare_target: 9655 case OMPD_simd: 9656 case OMPD_for: 9657 case OMPD_for_simd: 9658 case OMPD_sections: 9659 case OMPD_section: 9660 case OMPD_single: 9661 case OMPD_master: 9662 case OMPD_critical: 9663 case OMPD_taskgroup: 9664 case OMPD_ordered: 9665 case OMPD_atomic: 9666 case OMPD_target_teams: 9667 case OMPD_requires: 9668 llvm_unreachable("Unexpected OpenMP directive with schedule clause"); 9669 case OMPD_unknown: 9670 llvm_unreachable("Unknown OpenMP directive"); 9671 } 9672 break; 9673 case OMPC_device: 9674 switch (DKind) { 9675 case OMPD_target_update: 9676 case OMPD_target_enter_data: 9677 case OMPD_target_exit_data: 9678 case OMPD_target: 9679 case OMPD_target_simd: 9680 case OMPD_target_teams: 9681 case OMPD_target_parallel: 9682 case OMPD_target_teams_distribute: 9683 case OMPD_target_teams_distribute_simd: 9684 case OMPD_target_parallel_for: 9685 case OMPD_target_parallel_for_simd: 9686 case OMPD_target_teams_distribute_parallel_for: 9687 case OMPD_target_teams_distribute_parallel_for_simd: 9688 CaptureRegion = OMPD_task; 9689 break; 9690 case OMPD_target_data: 9691 // Do not capture device-clause expressions. 9692 break; 9693 case OMPD_teams_distribute_parallel_for: 9694 case OMPD_teams_distribute_parallel_for_simd: 9695 case OMPD_teams: 9696 case OMPD_teams_distribute: 9697 case OMPD_teams_distribute_simd: 9698 case OMPD_distribute_parallel_for: 9699 case OMPD_distribute_parallel_for_simd: 9700 case OMPD_task: 9701 case OMPD_taskloop: 9702 case OMPD_taskloop_simd: 9703 case OMPD_cancel: 9704 case OMPD_parallel: 9705 case OMPD_parallel_sections: 9706 case OMPD_parallel_for: 9707 case OMPD_parallel_for_simd: 9708 case OMPD_threadprivate: 9709 case OMPD_allocate: 9710 case OMPD_taskyield: 9711 case OMPD_barrier: 9712 case OMPD_taskwait: 9713 case OMPD_cancellation_point: 9714 case OMPD_flush: 9715 case OMPD_declare_reduction: 9716 case OMPD_declare_mapper: 9717 case OMPD_declare_simd: 9718 case OMPD_declare_target: 9719 case OMPD_end_declare_target: 9720 case OMPD_simd: 9721 case OMPD_for: 9722 case OMPD_for_simd: 9723 case OMPD_sections: 9724 case OMPD_section: 9725 case OMPD_single: 9726 case OMPD_master: 9727 case OMPD_critical: 9728 case OMPD_taskgroup: 9729 case OMPD_distribute: 9730 case OMPD_ordered: 9731 case OMPD_atomic: 9732 case OMPD_distribute_simd: 9733 case OMPD_requires: 9734 llvm_unreachable("Unexpected OpenMP directive with num_teams-clause"); 9735 case OMPD_unknown: 9736 llvm_unreachable("Unknown OpenMP directive"); 9737 } 9738 break; 9739 case OMPC_firstprivate: 9740 case OMPC_lastprivate: 9741 case OMPC_reduction: 9742 case OMPC_task_reduction: 9743 case OMPC_in_reduction: 9744 case OMPC_linear: 9745 case OMPC_default: 9746 case OMPC_proc_bind: 9747 case OMPC_final: 9748 case OMPC_safelen: 9749 case OMPC_simdlen: 9750 case OMPC_allocator: 9751 case OMPC_collapse: 9752 case OMPC_private: 9753 case OMPC_shared: 9754 case OMPC_aligned: 9755 case OMPC_copyin: 9756 case OMPC_copyprivate: 9757 case OMPC_ordered: 9758 case OMPC_nowait: 9759 case OMPC_untied: 9760 case OMPC_mergeable: 9761 case OMPC_threadprivate: 9762 case OMPC_allocate: 9763 case OMPC_flush: 9764 case OMPC_read: 9765 case OMPC_write: 9766 case OMPC_update: 9767 case OMPC_capture: 9768 case OMPC_seq_cst: 9769 case OMPC_depend: 9770 case OMPC_threads: 9771 case OMPC_simd: 9772 case OMPC_map: 9773 case OMPC_priority: 9774 case OMPC_grainsize: 9775 case OMPC_nogroup: 9776 case OMPC_num_tasks: 9777 case OMPC_hint: 9778 case OMPC_defaultmap: 9779 case OMPC_unknown: 9780 case OMPC_uniform: 9781 case OMPC_to: 9782 case OMPC_from: 9783 case OMPC_use_device_ptr: 9784 case OMPC_is_device_ptr: 9785 case OMPC_unified_address: 9786 case OMPC_unified_shared_memory: 9787 case OMPC_reverse_offload: 9788 case OMPC_dynamic_allocators: 9789 case OMPC_atomic_default_mem_order: 9790 llvm_unreachable("Unexpected OpenMP clause."); 9791 } 9792 return CaptureRegion; 9793 } 9794 9795 OMPClause *Sema::ActOnOpenMPIfClause(OpenMPDirectiveKind NameModifier, 9796 Expr *Condition, SourceLocation StartLoc, 9797 SourceLocation LParenLoc, 9798 SourceLocation NameModifierLoc, 9799 SourceLocation ColonLoc, 9800 SourceLocation EndLoc) { 9801 Expr *ValExpr = Condition; 9802 Stmt *HelperValStmt = nullptr; 9803 OpenMPDirectiveKind CaptureRegion = OMPD_unknown; 9804 if (!Condition->isValueDependent() && !Condition->isTypeDependent() && 9805 !Condition->isInstantiationDependent() && 9806 !Condition->containsUnexpandedParameterPack()) { 9807 ExprResult Val = CheckBooleanCondition(StartLoc, Condition); 9808 if (Val.isInvalid()) 9809 return nullptr; 9810 9811 ValExpr = Val.get(); 9812 9813 OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective(); 9814 CaptureRegion = 9815 getOpenMPCaptureRegionForClause(DKind, OMPC_if, NameModifier); 9816 if (CaptureRegion != OMPD_unknown && !CurContext->isDependentContext()) { 9817 ValExpr = MakeFullExpr(ValExpr).get(); 9818 llvm::MapVector<const Expr *, DeclRefExpr *> Captures; 9819 ValExpr = tryBuildCapture(*this, ValExpr, Captures).get(); 9820 HelperValStmt = buildPreInits(Context, Captures); 9821 } 9822 } 9823 9824 return new (Context) 9825 OMPIfClause(NameModifier, ValExpr, HelperValStmt, CaptureRegion, StartLoc, 9826 LParenLoc, NameModifierLoc, ColonLoc, EndLoc); 9827 } 9828 9829 OMPClause *Sema::ActOnOpenMPFinalClause(Expr *Condition, 9830 SourceLocation StartLoc, 9831 SourceLocation LParenLoc, 9832 SourceLocation EndLoc) { 9833 Expr *ValExpr = Condition; 9834 if (!Condition->isValueDependent() && !Condition->isTypeDependent() && 9835 !Condition->isInstantiationDependent() && 9836 !Condition->containsUnexpandedParameterPack()) { 9837 ExprResult Val = CheckBooleanCondition(StartLoc, Condition); 9838 if (Val.isInvalid()) 9839 return nullptr; 9840 9841 ValExpr = MakeFullExpr(Val.get()).get(); 9842 } 9843 9844 return new (Context) OMPFinalClause(ValExpr, StartLoc, LParenLoc, EndLoc); 9845 } 9846 ExprResult Sema::PerformOpenMPImplicitIntegerConversion(SourceLocation Loc, 9847 Expr *Op) { 9848 if (!Op) 9849 return ExprError(); 9850 9851 class IntConvertDiagnoser : public ICEConvertDiagnoser { 9852 public: 9853 IntConvertDiagnoser() 9854 : ICEConvertDiagnoser(/*AllowScopedEnumerations*/ false, false, true) {} 9855 SemaDiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc, 9856 QualType T) override { 9857 return S.Diag(Loc, diag::err_omp_not_integral) << T; 9858 } 9859 SemaDiagnosticBuilder diagnoseIncomplete(Sema &S, SourceLocation Loc, 9860 QualType T) override { 9861 return S.Diag(Loc, diag::err_omp_incomplete_type) << T; 9862 } 9863 SemaDiagnosticBuilder diagnoseExplicitConv(Sema &S, SourceLocation Loc, 9864 QualType T, 9865 QualType ConvTy) override { 9866 return S.Diag(Loc, diag::err_omp_explicit_conversion) << T << ConvTy; 9867 } 9868 SemaDiagnosticBuilder noteExplicitConv(Sema &S, CXXConversionDecl *Conv, 9869 QualType ConvTy) override { 9870 return S.Diag(Conv->getLocation(), diag::note_omp_conversion_here) 9871 << ConvTy->isEnumeralType() << ConvTy; 9872 } 9873 SemaDiagnosticBuilder diagnoseAmbiguous(Sema &S, SourceLocation Loc, 9874 QualType T) override { 9875 return S.Diag(Loc, diag::err_omp_ambiguous_conversion) << T; 9876 } 9877 SemaDiagnosticBuilder noteAmbiguous(Sema &S, CXXConversionDecl *Conv, 9878 QualType ConvTy) override { 9879 return S.Diag(Conv->getLocation(), diag::note_omp_conversion_here) 9880 << ConvTy->isEnumeralType() << ConvTy; 9881 } 9882 SemaDiagnosticBuilder diagnoseConversion(Sema &, SourceLocation, QualType, 9883 QualType) override { 9884 llvm_unreachable("conversion functions are permitted"); 9885 } 9886 } ConvertDiagnoser; 9887 return PerformContextualImplicitConversion(Loc, Op, ConvertDiagnoser); 9888 } 9889 9890 static bool isNonNegativeIntegerValue(Expr *&ValExpr, Sema &SemaRef, 9891 OpenMPClauseKind CKind, 9892 bool StrictlyPositive) { 9893 if (!ValExpr->isTypeDependent() && !ValExpr->isValueDependent() && 9894 !ValExpr->isInstantiationDependent()) { 9895 SourceLocation Loc = ValExpr->getExprLoc(); 9896 ExprResult Value = 9897 SemaRef.PerformOpenMPImplicitIntegerConversion(Loc, ValExpr); 9898 if (Value.isInvalid()) 9899 return false; 9900 9901 ValExpr = Value.get(); 9902 // The expression must evaluate to a non-negative integer value. 9903 llvm::APSInt Result; 9904 if (ValExpr->isIntegerConstantExpr(Result, SemaRef.Context) && 9905 Result.isSigned() && 9906 !((!StrictlyPositive && Result.isNonNegative()) || 9907 (StrictlyPositive && Result.isStrictlyPositive()))) { 9908 SemaRef.Diag(Loc, diag::err_omp_negative_expression_in_clause) 9909 << getOpenMPClauseName(CKind) << (StrictlyPositive ? 1 : 0) 9910 << ValExpr->getSourceRange(); 9911 return false; 9912 } 9913 } 9914 return true; 9915 } 9916 9917 OMPClause *Sema::ActOnOpenMPNumThreadsClause(Expr *NumThreads, 9918 SourceLocation StartLoc, 9919 SourceLocation LParenLoc, 9920 SourceLocation EndLoc) { 9921 Expr *ValExpr = NumThreads; 9922 Stmt *HelperValStmt = nullptr; 9923 9924 // OpenMP [2.5, Restrictions] 9925 // The num_threads expression must evaluate to a positive integer value. 9926 if (!isNonNegativeIntegerValue(ValExpr, *this, OMPC_num_threads, 9927 /*StrictlyPositive=*/true)) 9928 return nullptr; 9929 9930 OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective(); 9931 OpenMPDirectiveKind CaptureRegion = 9932 getOpenMPCaptureRegionForClause(DKind, OMPC_num_threads); 9933 if (CaptureRegion != OMPD_unknown && !CurContext->isDependentContext()) { 9934 ValExpr = MakeFullExpr(ValExpr).get(); 9935 llvm::MapVector<const Expr *, DeclRefExpr *> Captures; 9936 ValExpr = tryBuildCapture(*this, ValExpr, Captures).get(); 9937 HelperValStmt = buildPreInits(Context, Captures); 9938 } 9939 9940 return new (Context) OMPNumThreadsClause( 9941 ValExpr, HelperValStmt, CaptureRegion, StartLoc, LParenLoc, EndLoc); 9942 } 9943 9944 ExprResult Sema::VerifyPositiveIntegerConstantInClause(Expr *E, 9945 OpenMPClauseKind CKind, 9946 bool StrictlyPositive) { 9947 if (!E) 9948 return ExprError(); 9949 if (E->isValueDependent() || E->isTypeDependent() || 9950 E->isInstantiationDependent() || E->containsUnexpandedParameterPack()) 9951 return E; 9952 llvm::APSInt Result; 9953 ExprResult ICE = VerifyIntegerConstantExpression(E, &Result); 9954 if (ICE.isInvalid()) 9955 return ExprError(); 9956 if ((StrictlyPositive && !Result.isStrictlyPositive()) || 9957 (!StrictlyPositive && !Result.isNonNegative())) { 9958 Diag(E->getExprLoc(), diag::err_omp_negative_expression_in_clause) 9959 << getOpenMPClauseName(CKind) << (StrictlyPositive ? 1 : 0) 9960 << E->getSourceRange(); 9961 return ExprError(); 9962 } 9963 if (CKind == OMPC_aligned && !Result.isPowerOf2()) { 9964 Diag(E->getExprLoc(), diag::warn_omp_alignment_not_power_of_two) 9965 << E->getSourceRange(); 9966 return ExprError(); 9967 } 9968 if (CKind == OMPC_collapse && DSAStack->getAssociatedLoops() == 1) 9969 DSAStack->setAssociatedLoops(Result.getExtValue()); 9970 else if (CKind == OMPC_ordered) 9971 DSAStack->setAssociatedLoops(Result.getExtValue()); 9972 return ICE; 9973 } 9974 9975 OMPClause *Sema::ActOnOpenMPSafelenClause(Expr *Len, SourceLocation StartLoc, 9976 SourceLocation LParenLoc, 9977 SourceLocation EndLoc) { 9978 // OpenMP [2.8.1, simd construct, Description] 9979 // The parameter of the safelen clause must be a constant 9980 // positive integer expression. 9981 ExprResult Safelen = VerifyPositiveIntegerConstantInClause(Len, OMPC_safelen); 9982 if (Safelen.isInvalid()) 9983 return nullptr; 9984 return new (Context) 9985 OMPSafelenClause(Safelen.get(), StartLoc, LParenLoc, EndLoc); 9986 } 9987 9988 OMPClause *Sema::ActOnOpenMPSimdlenClause(Expr *Len, SourceLocation StartLoc, 9989 SourceLocation LParenLoc, 9990 SourceLocation EndLoc) { 9991 // OpenMP [2.8.1, simd construct, Description] 9992 // The parameter of the simdlen clause must be a constant 9993 // positive integer expression. 9994 ExprResult Simdlen = VerifyPositiveIntegerConstantInClause(Len, OMPC_simdlen); 9995 if (Simdlen.isInvalid()) 9996 return nullptr; 9997 return new (Context) 9998 OMPSimdlenClause(Simdlen.get(), StartLoc, LParenLoc, EndLoc); 9999 } 10000 10001 /// Tries to find omp_allocator_handle_t type. 10002 static bool findOMPAllocatorHandleT(Sema &S, SourceLocation Loc, 10003 DSAStackTy *Stack) { 10004 QualType OMPAllocatorHandleT = Stack->getOMPAllocatorHandleT(); 10005 if (!OMPAllocatorHandleT.isNull()) 10006 return true; 10007 // Build the predefined allocator expressions. 10008 bool ErrorFound = false; 10009 for (int I = OMPAllocateDeclAttr::OMPDefaultMemAlloc; 10010 I < OMPAllocateDeclAttr::OMPUserDefinedMemAlloc; ++I) { 10011 auto AllocatorKind = static_cast<OMPAllocateDeclAttr::AllocatorTypeTy>(I); 10012 StringRef Allocator = 10013 OMPAllocateDeclAttr::ConvertAllocatorTypeTyToStr(AllocatorKind); 10014 DeclarationName AllocatorName = &S.getASTContext().Idents.get(Allocator); 10015 auto *VD = dyn_cast_or_null<ValueDecl>( 10016 S.LookupSingleName(S.TUScope, AllocatorName, Loc, Sema::LookupAnyName)); 10017 if (!VD) { 10018 ErrorFound = true; 10019 break; 10020 } 10021 QualType AllocatorType = 10022 VD->getType().getNonLValueExprType(S.getASTContext()); 10023 ExprResult Res = S.BuildDeclRefExpr(VD, AllocatorType, VK_LValue, Loc); 10024 if (!Res.isUsable()) { 10025 ErrorFound = true; 10026 break; 10027 } 10028 if (OMPAllocatorHandleT.isNull()) 10029 OMPAllocatorHandleT = AllocatorType; 10030 if (!S.getASTContext().hasSameType(OMPAllocatorHandleT, AllocatorType)) { 10031 ErrorFound = true; 10032 break; 10033 } 10034 Stack->setAllocator(AllocatorKind, Res.get()); 10035 } 10036 if (ErrorFound) { 10037 S.Diag(Loc, diag::err_implied_omp_allocator_handle_t_not_found); 10038 return false; 10039 } 10040 OMPAllocatorHandleT.addConst(); 10041 Stack->setOMPAllocatorHandleT(OMPAllocatorHandleT); 10042 return true; 10043 } 10044 10045 OMPClause *Sema::ActOnOpenMPAllocatorClause(Expr *A, SourceLocation StartLoc, 10046 SourceLocation LParenLoc, 10047 SourceLocation EndLoc) { 10048 // OpenMP [2.11.3, allocate Directive, Description] 10049 // allocator is an expression of omp_allocator_handle_t type. 10050 if (!findOMPAllocatorHandleT(*this, A->getExprLoc(), DSAStack)) 10051 return nullptr; 10052 10053 ExprResult Allocator = DefaultLvalueConversion(A); 10054 if (Allocator.isInvalid()) 10055 return nullptr; 10056 Allocator = PerformImplicitConversion(Allocator.get(), 10057 DSAStack->getOMPAllocatorHandleT(), 10058 Sema::AA_Initializing, 10059 /*AllowExplicit=*/true); 10060 if (Allocator.isInvalid()) 10061 return nullptr; 10062 return new (Context) 10063 OMPAllocatorClause(Allocator.get(), StartLoc, LParenLoc, EndLoc); 10064 } 10065 10066 OMPClause *Sema::ActOnOpenMPCollapseClause(Expr *NumForLoops, 10067 SourceLocation StartLoc, 10068 SourceLocation LParenLoc, 10069 SourceLocation EndLoc) { 10070 // OpenMP [2.7.1, loop construct, Description] 10071 // OpenMP [2.8.1, simd construct, Description] 10072 // OpenMP [2.9.6, distribute construct, Description] 10073 // The parameter of the collapse clause must be a constant 10074 // positive integer expression. 10075 ExprResult NumForLoopsResult = 10076 VerifyPositiveIntegerConstantInClause(NumForLoops, OMPC_collapse); 10077 if (NumForLoopsResult.isInvalid()) 10078 return nullptr; 10079 return new (Context) 10080 OMPCollapseClause(NumForLoopsResult.get(), StartLoc, LParenLoc, EndLoc); 10081 } 10082 10083 OMPClause *Sema::ActOnOpenMPOrderedClause(SourceLocation StartLoc, 10084 SourceLocation EndLoc, 10085 SourceLocation LParenLoc, 10086 Expr *NumForLoops) { 10087 // OpenMP [2.7.1, loop construct, Description] 10088 // OpenMP [2.8.1, simd construct, Description] 10089 // OpenMP [2.9.6, distribute construct, Description] 10090 // The parameter of the ordered clause must be a constant 10091 // positive integer expression if any. 10092 if (NumForLoops && LParenLoc.isValid()) { 10093 ExprResult NumForLoopsResult = 10094 VerifyPositiveIntegerConstantInClause(NumForLoops, OMPC_ordered); 10095 if (NumForLoopsResult.isInvalid()) 10096 return nullptr; 10097 NumForLoops = NumForLoopsResult.get(); 10098 } else { 10099 NumForLoops = nullptr; 10100 } 10101 auto *Clause = OMPOrderedClause::Create( 10102 Context, NumForLoops, NumForLoops ? DSAStack->getAssociatedLoops() : 0, 10103 StartLoc, LParenLoc, EndLoc); 10104 DSAStack->setOrderedRegion(/*IsOrdered=*/true, NumForLoops, Clause); 10105 return Clause; 10106 } 10107 10108 OMPClause *Sema::ActOnOpenMPSimpleClause( 10109 OpenMPClauseKind Kind, unsigned Argument, SourceLocation ArgumentLoc, 10110 SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc) { 10111 OMPClause *Res = nullptr; 10112 switch (Kind) { 10113 case OMPC_default: 10114 Res = 10115 ActOnOpenMPDefaultClause(static_cast<OpenMPDefaultClauseKind>(Argument), 10116 ArgumentLoc, StartLoc, LParenLoc, EndLoc); 10117 break; 10118 case OMPC_proc_bind: 10119 Res = ActOnOpenMPProcBindClause( 10120 static_cast<OpenMPProcBindClauseKind>(Argument), ArgumentLoc, StartLoc, 10121 LParenLoc, EndLoc); 10122 break; 10123 case OMPC_atomic_default_mem_order: 10124 Res = ActOnOpenMPAtomicDefaultMemOrderClause( 10125 static_cast<OpenMPAtomicDefaultMemOrderClauseKind>(Argument), 10126 ArgumentLoc, StartLoc, LParenLoc, EndLoc); 10127 break; 10128 case OMPC_if: 10129 case OMPC_final: 10130 case OMPC_num_threads: 10131 case OMPC_safelen: 10132 case OMPC_simdlen: 10133 case OMPC_allocator: 10134 case OMPC_collapse: 10135 case OMPC_schedule: 10136 case OMPC_private: 10137 case OMPC_firstprivate: 10138 case OMPC_lastprivate: 10139 case OMPC_shared: 10140 case OMPC_reduction: 10141 case OMPC_task_reduction: 10142 case OMPC_in_reduction: 10143 case OMPC_linear: 10144 case OMPC_aligned: 10145 case OMPC_copyin: 10146 case OMPC_copyprivate: 10147 case OMPC_ordered: 10148 case OMPC_nowait: 10149 case OMPC_untied: 10150 case OMPC_mergeable: 10151 case OMPC_threadprivate: 10152 case OMPC_allocate: 10153 case OMPC_flush: 10154 case OMPC_read: 10155 case OMPC_write: 10156 case OMPC_update: 10157 case OMPC_capture: 10158 case OMPC_seq_cst: 10159 case OMPC_depend: 10160 case OMPC_device: 10161 case OMPC_threads: 10162 case OMPC_simd: 10163 case OMPC_map: 10164 case OMPC_num_teams: 10165 case OMPC_thread_limit: 10166 case OMPC_priority: 10167 case OMPC_grainsize: 10168 case OMPC_nogroup: 10169 case OMPC_num_tasks: 10170 case OMPC_hint: 10171 case OMPC_dist_schedule: 10172 case OMPC_defaultmap: 10173 case OMPC_unknown: 10174 case OMPC_uniform: 10175 case OMPC_to: 10176 case OMPC_from: 10177 case OMPC_use_device_ptr: 10178 case OMPC_is_device_ptr: 10179 case OMPC_unified_address: 10180 case OMPC_unified_shared_memory: 10181 case OMPC_reverse_offload: 10182 case OMPC_dynamic_allocators: 10183 llvm_unreachable("Clause is not allowed."); 10184 } 10185 return Res; 10186 } 10187 10188 static std::string 10189 getListOfPossibleValues(OpenMPClauseKind K, unsigned First, unsigned Last, 10190 ArrayRef<unsigned> Exclude = llvm::None) { 10191 SmallString<256> Buffer; 10192 llvm::raw_svector_ostream Out(Buffer); 10193 unsigned Bound = Last >= 2 ? Last - 2 : 0; 10194 unsigned Skipped = Exclude.size(); 10195 auto S = Exclude.begin(), E = Exclude.end(); 10196 for (unsigned I = First; I < Last; ++I) { 10197 if (std::find(S, E, I) != E) { 10198 --Skipped; 10199 continue; 10200 } 10201 Out << "'" << getOpenMPSimpleClauseTypeName(K, I) << "'"; 10202 if (I == Bound - Skipped) 10203 Out << " or "; 10204 else if (I != Bound + 1 - Skipped) 10205 Out << ", "; 10206 } 10207 return Out.str(); 10208 } 10209 10210 OMPClause *Sema::ActOnOpenMPDefaultClause(OpenMPDefaultClauseKind Kind, 10211 SourceLocation KindKwLoc, 10212 SourceLocation StartLoc, 10213 SourceLocation LParenLoc, 10214 SourceLocation EndLoc) { 10215 if (Kind == OMPC_DEFAULT_unknown) { 10216 static_assert(OMPC_DEFAULT_unknown > 0, 10217 "OMPC_DEFAULT_unknown not greater than 0"); 10218 Diag(KindKwLoc, diag::err_omp_unexpected_clause_value) 10219 << getListOfPossibleValues(OMPC_default, /*First=*/0, 10220 /*Last=*/OMPC_DEFAULT_unknown) 10221 << getOpenMPClauseName(OMPC_default); 10222 return nullptr; 10223 } 10224 switch (Kind) { 10225 case OMPC_DEFAULT_none: 10226 DSAStack->setDefaultDSANone(KindKwLoc); 10227 break; 10228 case OMPC_DEFAULT_shared: 10229 DSAStack->setDefaultDSAShared(KindKwLoc); 10230 break; 10231 case OMPC_DEFAULT_unknown: 10232 llvm_unreachable("Clause kind is not allowed."); 10233 break; 10234 } 10235 return new (Context) 10236 OMPDefaultClause(Kind, KindKwLoc, StartLoc, LParenLoc, EndLoc); 10237 } 10238 10239 OMPClause *Sema::ActOnOpenMPProcBindClause(OpenMPProcBindClauseKind Kind, 10240 SourceLocation KindKwLoc, 10241 SourceLocation StartLoc, 10242 SourceLocation LParenLoc, 10243 SourceLocation EndLoc) { 10244 if (Kind == OMPC_PROC_BIND_unknown) { 10245 Diag(KindKwLoc, diag::err_omp_unexpected_clause_value) 10246 << getListOfPossibleValues(OMPC_proc_bind, /*First=*/0, 10247 /*Last=*/OMPC_PROC_BIND_unknown) 10248 << getOpenMPClauseName(OMPC_proc_bind); 10249 return nullptr; 10250 } 10251 return new (Context) 10252 OMPProcBindClause(Kind, KindKwLoc, StartLoc, LParenLoc, EndLoc); 10253 } 10254 10255 OMPClause *Sema::ActOnOpenMPAtomicDefaultMemOrderClause( 10256 OpenMPAtomicDefaultMemOrderClauseKind Kind, SourceLocation KindKwLoc, 10257 SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc) { 10258 if (Kind == OMPC_ATOMIC_DEFAULT_MEM_ORDER_unknown) { 10259 Diag(KindKwLoc, diag::err_omp_unexpected_clause_value) 10260 << getListOfPossibleValues( 10261 OMPC_atomic_default_mem_order, /*First=*/0, 10262 /*Last=*/OMPC_ATOMIC_DEFAULT_MEM_ORDER_unknown) 10263 << getOpenMPClauseName(OMPC_atomic_default_mem_order); 10264 return nullptr; 10265 } 10266 return new (Context) OMPAtomicDefaultMemOrderClause(Kind, KindKwLoc, StartLoc, 10267 LParenLoc, EndLoc); 10268 } 10269 10270 OMPClause *Sema::ActOnOpenMPSingleExprWithArgClause( 10271 OpenMPClauseKind Kind, ArrayRef<unsigned> Argument, Expr *Expr, 10272 SourceLocation StartLoc, SourceLocation LParenLoc, 10273 ArrayRef<SourceLocation> ArgumentLoc, SourceLocation DelimLoc, 10274 SourceLocation EndLoc) { 10275 OMPClause *Res = nullptr; 10276 switch (Kind) { 10277 case OMPC_schedule: 10278 enum { Modifier1, Modifier2, ScheduleKind, NumberOfElements }; 10279 assert(Argument.size() == NumberOfElements && 10280 ArgumentLoc.size() == NumberOfElements); 10281 Res = ActOnOpenMPScheduleClause( 10282 static_cast<OpenMPScheduleClauseModifier>(Argument[Modifier1]), 10283 static_cast<OpenMPScheduleClauseModifier>(Argument[Modifier2]), 10284 static_cast<OpenMPScheduleClauseKind>(Argument[ScheduleKind]), Expr, 10285 StartLoc, LParenLoc, ArgumentLoc[Modifier1], ArgumentLoc[Modifier2], 10286 ArgumentLoc[ScheduleKind], DelimLoc, EndLoc); 10287 break; 10288 case OMPC_if: 10289 assert(Argument.size() == 1 && ArgumentLoc.size() == 1); 10290 Res = ActOnOpenMPIfClause(static_cast<OpenMPDirectiveKind>(Argument.back()), 10291 Expr, StartLoc, LParenLoc, ArgumentLoc.back(), 10292 DelimLoc, EndLoc); 10293 break; 10294 case OMPC_dist_schedule: 10295 Res = ActOnOpenMPDistScheduleClause( 10296 static_cast<OpenMPDistScheduleClauseKind>(Argument.back()), Expr, 10297 StartLoc, LParenLoc, ArgumentLoc.back(), DelimLoc, EndLoc); 10298 break; 10299 case OMPC_defaultmap: 10300 enum { Modifier, DefaultmapKind }; 10301 Res = ActOnOpenMPDefaultmapClause( 10302 static_cast<OpenMPDefaultmapClauseModifier>(Argument[Modifier]), 10303 static_cast<OpenMPDefaultmapClauseKind>(Argument[DefaultmapKind]), 10304 StartLoc, LParenLoc, ArgumentLoc[Modifier], ArgumentLoc[DefaultmapKind], 10305 EndLoc); 10306 break; 10307 case OMPC_final: 10308 case OMPC_num_threads: 10309 case OMPC_safelen: 10310 case OMPC_simdlen: 10311 case OMPC_allocator: 10312 case OMPC_collapse: 10313 case OMPC_default: 10314 case OMPC_proc_bind: 10315 case OMPC_private: 10316 case OMPC_firstprivate: 10317 case OMPC_lastprivate: 10318 case OMPC_shared: 10319 case OMPC_reduction: 10320 case OMPC_task_reduction: 10321 case OMPC_in_reduction: 10322 case OMPC_linear: 10323 case OMPC_aligned: 10324 case OMPC_copyin: 10325 case OMPC_copyprivate: 10326 case OMPC_ordered: 10327 case OMPC_nowait: 10328 case OMPC_untied: 10329 case OMPC_mergeable: 10330 case OMPC_threadprivate: 10331 case OMPC_allocate: 10332 case OMPC_flush: 10333 case OMPC_read: 10334 case OMPC_write: 10335 case OMPC_update: 10336 case OMPC_capture: 10337 case OMPC_seq_cst: 10338 case OMPC_depend: 10339 case OMPC_device: 10340 case OMPC_threads: 10341 case OMPC_simd: 10342 case OMPC_map: 10343 case OMPC_num_teams: 10344 case OMPC_thread_limit: 10345 case OMPC_priority: 10346 case OMPC_grainsize: 10347 case OMPC_nogroup: 10348 case OMPC_num_tasks: 10349 case OMPC_hint: 10350 case OMPC_unknown: 10351 case OMPC_uniform: 10352 case OMPC_to: 10353 case OMPC_from: 10354 case OMPC_use_device_ptr: 10355 case OMPC_is_device_ptr: 10356 case OMPC_unified_address: 10357 case OMPC_unified_shared_memory: 10358 case OMPC_reverse_offload: 10359 case OMPC_dynamic_allocators: 10360 case OMPC_atomic_default_mem_order: 10361 llvm_unreachable("Clause is not allowed."); 10362 } 10363 return Res; 10364 } 10365 10366 static bool checkScheduleModifiers(Sema &S, OpenMPScheduleClauseModifier M1, 10367 OpenMPScheduleClauseModifier M2, 10368 SourceLocation M1Loc, SourceLocation M2Loc) { 10369 if (M1 == OMPC_SCHEDULE_MODIFIER_unknown && M1Loc.isValid()) { 10370 SmallVector<unsigned, 2> Excluded; 10371 if (M2 != OMPC_SCHEDULE_MODIFIER_unknown) 10372 Excluded.push_back(M2); 10373 if (M2 == OMPC_SCHEDULE_MODIFIER_nonmonotonic) 10374 Excluded.push_back(OMPC_SCHEDULE_MODIFIER_monotonic); 10375 if (M2 == OMPC_SCHEDULE_MODIFIER_monotonic) 10376 Excluded.push_back(OMPC_SCHEDULE_MODIFIER_nonmonotonic); 10377 S.Diag(M1Loc, diag::err_omp_unexpected_clause_value) 10378 << getListOfPossibleValues(OMPC_schedule, 10379 /*First=*/OMPC_SCHEDULE_MODIFIER_unknown + 1, 10380 /*Last=*/OMPC_SCHEDULE_MODIFIER_last, 10381 Excluded) 10382 << getOpenMPClauseName(OMPC_schedule); 10383 return true; 10384 } 10385 return false; 10386 } 10387 10388 OMPClause *Sema::ActOnOpenMPScheduleClause( 10389 OpenMPScheduleClauseModifier M1, OpenMPScheduleClauseModifier M2, 10390 OpenMPScheduleClauseKind Kind, Expr *ChunkSize, SourceLocation StartLoc, 10391 SourceLocation LParenLoc, SourceLocation M1Loc, SourceLocation M2Loc, 10392 SourceLocation KindLoc, SourceLocation CommaLoc, SourceLocation EndLoc) { 10393 if (checkScheduleModifiers(*this, M1, M2, M1Loc, M2Loc) || 10394 checkScheduleModifiers(*this, M2, M1, M2Loc, M1Loc)) 10395 return nullptr; 10396 // OpenMP, 2.7.1, Loop Construct, Restrictions 10397 // Either the monotonic modifier or the nonmonotonic modifier can be specified 10398 // but not both. 10399 if ((M1 == M2 && M1 != OMPC_SCHEDULE_MODIFIER_unknown) || 10400 (M1 == OMPC_SCHEDULE_MODIFIER_monotonic && 10401 M2 == OMPC_SCHEDULE_MODIFIER_nonmonotonic) || 10402 (M1 == OMPC_SCHEDULE_MODIFIER_nonmonotonic && 10403 M2 == OMPC_SCHEDULE_MODIFIER_monotonic)) { 10404 Diag(M2Loc, diag::err_omp_unexpected_schedule_modifier) 10405 << getOpenMPSimpleClauseTypeName(OMPC_schedule, M2) 10406 << getOpenMPSimpleClauseTypeName(OMPC_schedule, M1); 10407 return nullptr; 10408 } 10409 if (Kind == OMPC_SCHEDULE_unknown) { 10410 std::string Values; 10411 if (M1Loc.isInvalid() && M2Loc.isInvalid()) { 10412 unsigned Exclude[] = {OMPC_SCHEDULE_unknown}; 10413 Values = getListOfPossibleValues(OMPC_schedule, /*First=*/0, 10414 /*Last=*/OMPC_SCHEDULE_MODIFIER_last, 10415 Exclude); 10416 } else { 10417 Values = getListOfPossibleValues(OMPC_schedule, /*First=*/0, 10418 /*Last=*/OMPC_SCHEDULE_unknown); 10419 } 10420 Diag(KindLoc, diag::err_omp_unexpected_clause_value) 10421 << Values << getOpenMPClauseName(OMPC_schedule); 10422 return nullptr; 10423 } 10424 // OpenMP, 2.7.1, Loop Construct, Restrictions 10425 // The nonmonotonic modifier can only be specified with schedule(dynamic) or 10426 // schedule(guided). 10427 if ((M1 == OMPC_SCHEDULE_MODIFIER_nonmonotonic || 10428 M2 == OMPC_SCHEDULE_MODIFIER_nonmonotonic) && 10429 Kind != OMPC_SCHEDULE_dynamic && Kind != OMPC_SCHEDULE_guided) { 10430 Diag(M1 == OMPC_SCHEDULE_MODIFIER_nonmonotonic ? M1Loc : M2Loc, 10431 diag::err_omp_schedule_nonmonotonic_static); 10432 return nullptr; 10433 } 10434 Expr *ValExpr = ChunkSize; 10435 Stmt *HelperValStmt = nullptr; 10436 if (ChunkSize) { 10437 if (!ChunkSize->isValueDependent() && !ChunkSize->isTypeDependent() && 10438 !ChunkSize->isInstantiationDependent() && 10439 !ChunkSize->containsUnexpandedParameterPack()) { 10440 SourceLocation ChunkSizeLoc = ChunkSize->getBeginLoc(); 10441 ExprResult Val = 10442 PerformOpenMPImplicitIntegerConversion(ChunkSizeLoc, ChunkSize); 10443 if (Val.isInvalid()) 10444 return nullptr; 10445 10446 ValExpr = Val.get(); 10447 10448 // OpenMP [2.7.1, Restrictions] 10449 // chunk_size must be a loop invariant integer expression with a positive 10450 // value. 10451 llvm::APSInt Result; 10452 if (ValExpr->isIntegerConstantExpr(Result, Context)) { 10453 if (Result.isSigned() && !Result.isStrictlyPositive()) { 10454 Diag(ChunkSizeLoc, diag::err_omp_negative_expression_in_clause) 10455 << "schedule" << 1 << ChunkSize->getSourceRange(); 10456 return nullptr; 10457 } 10458 } else if (getOpenMPCaptureRegionForClause( 10459 DSAStack->getCurrentDirective(), OMPC_schedule) != 10460 OMPD_unknown && 10461 !CurContext->isDependentContext()) { 10462 ValExpr = MakeFullExpr(ValExpr).get(); 10463 llvm::MapVector<const Expr *, DeclRefExpr *> Captures; 10464 ValExpr = tryBuildCapture(*this, ValExpr, Captures).get(); 10465 HelperValStmt = buildPreInits(Context, Captures); 10466 } 10467 } 10468 } 10469 10470 return new (Context) 10471 OMPScheduleClause(StartLoc, LParenLoc, KindLoc, CommaLoc, EndLoc, Kind, 10472 ValExpr, HelperValStmt, M1, M1Loc, M2, M2Loc); 10473 } 10474 10475 OMPClause *Sema::ActOnOpenMPClause(OpenMPClauseKind Kind, 10476 SourceLocation StartLoc, 10477 SourceLocation EndLoc) { 10478 OMPClause *Res = nullptr; 10479 switch (Kind) { 10480 case OMPC_ordered: 10481 Res = ActOnOpenMPOrderedClause(StartLoc, EndLoc); 10482 break; 10483 case OMPC_nowait: 10484 Res = ActOnOpenMPNowaitClause(StartLoc, EndLoc); 10485 break; 10486 case OMPC_untied: 10487 Res = ActOnOpenMPUntiedClause(StartLoc, EndLoc); 10488 break; 10489 case OMPC_mergeable: 10490 Res = ActOnOpenMPMergeableClause(StartLoc, EndLoc); 10491 break; 10492 case OMPC_read: 10493 Res = ActOnOpenMPReadClause(StartLoc, EndLoc); 10494 break; 10495 case OMPC_write: 10496 Res = ActOnOpenMPWriteClause(StartLoc, EndLoc); 10497 break; 10498 case OMPC_update: 10499 Res = ActOnOpenMPUpdateClause(StartLoc, EndLoc); 10500 break; 10501 case OMPC_capture: 10502 Res = ActOnOpenMPCaptureClause(StartLoc, EndLoc); 10503 break; 10504 case OMPC_seq_cst: 10505 Res = ActOnOpenMPSeqCstClause(StartLoc, EndLoc); 10506 break; 10507 case OMPC_threads: 10508 Res = ActOnOpenMPThreadsClause(StartLoc, EndLoc); 10509 break; 10510 case OMPC_simd: 10511 Res = ActOnOpenMPSIMDClause(StartLoc, EndLoc); 10512 break; 10513 case OMPC_nogroup: 10514 Res = ActOnOpenMPNogroupClause(StartLoc, EndLoc); 10515 break; 10516 case OMPC_unified_address: 10517 Res = ActOnOpenMPUnifiedAddressClause(StartLoc, EndLoc); 10518 break; 10519 case OMPC_unified_shared_memory: 10520 Res = ActOnOpenMPUnifiedSharedMemoryClause(StartLoc, EndLoc); 10521 break; 10522 case OMPC_reverse_offload: 10523 Res = ActOnOpenMPReverseOffloadClause(StartLoc, EndLoc); 10524 break; 10525 case OMPC_dynamic_allocators: 10526 Res = ActOnOpenMPDynamicAllocatorsClause(StartLoc, EndLoc); 10527 break; 10528 case OMPC_if: 10529 case OMPC_final: 10530 case OMPC_num_threads: 10531 case OMPC_safelen: 10532 case OMPC_simdlen: 10533 case OMPC_allocator: 10534 case OMPC_collapse: 10535 case OMPC_schedule: 10536 case OMPC_private: 10537 case OMPC_firstprivate: 10538 case OMPC_lastprivate: 10539 case OMPC_shared: 10540 case OMPC_reduction: 10541 case OMPC_task_reduction: 10542 case OMPC_in_reduction: 10543 case OMPC_linear: 10544 case OMPC_aligned: 10545 case OMPC_copyin: 10546 case OMPC_copyprivate: 10547 case OMPC_default: 10548 case OMPC_proc_bind: 10549 case OMPC_threadprivate: 10550 case OMPC_allocate: 10551 case OMPC_flush: 10552 case OMPC_depend: 10553 case OMPC_device: 10554 case OMPC_map: 10555 case OMPC_num_teams: 10556 case OMPC_thread_limit: 10557 case OMPC_priority: 10558 case OMPC_grainsize: 10559 case OMPC_num_tasks: 10560 case OMPC_hint: 10561 case OMPC_dist_schedule: 10562 case OMPC_defaultmap: 10563 case OMPC_unknown: 10564 case OMPC_uniform: 10565 case OMPC_to: 10566 case OMPC_from: 10567 case OMPC_use_device_ptr: 10568 case OMPC_is_device_ptr: 10569 case OMPC_atomic_default_mem_order: 10570 llvm_unreachable("Clause is not allowed."); 10571 } 10572 return Res; 10573 } 10574 10575 OMPClause *Sema::ActOnOpenMPNowaitClause(SourceLocation StartLoc, 10576 SourceLocation EndLoc) { 10577 DSAStack->setNowaitRegion(); 10578 return new (Context) OMPNowaitClause(StartLoc, EndLoc); 10579 } 10580 10581 OMPClause *Sema::ActOnOpenMPUntiedClause(SourceLocation StartLoc, 10582 SourceLocation EndLoc) { 10583 return new (Context) OMPUntiedClause(StartLoc, EndLoc); 10584 } 10585 10586 OMPClause *Sema::ActOnOpenMPMergeableClause(SourceLocation StartLoc, 10587 SourceLocation EndLoc) { 10588 return new (Context) OMPMergeableClause(StartLoc, EndLoc); 10589 } 10590 10591 OMPClause *Sema::ActOnOpenMPReadClause(SourceLocation StartLoc, 10592 SourceLocation EndLoc) { 10593 return new (Context) OMPReadClause(StartLoc, EndLoc); 10594 } 10595 10596 OMPClause *Sema::ActOnOpenMPWriteClause(SourceLocation StartLoc, 10597 SourceLocation EndLoc) { 10598 return new (Context) OMPWriteClause(StartLoc, EndLoc); 10599 } 10600 10601 OMPClause *Sema::ActOnOpenMPUpdateClause(SourceLocation StartLoc, 10602 SourceLocation EndLoc) { 10603 return new (Context) OMPUpdateClause(StartLoc, EndLoc); 10604 } 10605 10606 OMPClause *Sema::ActOnOpenMPCaptureClause(SourceLocation StartLoc, 10607 SourceLocation EndLoc) { 10608 return new (Context) OMPCaptureClause(StartLoc, EndLoc); 10609 } 10610 10611 OMPClause *Sema::ActOnOpenMPSeqCstClause(SourceLocation StartLoc, 10612 SourceLocation EndLoc) { 10613 return new (Context) OMPSeqCstClause(StartLoc, EndLoc); 10614 } 10615 10616 OMPClause *Sema::ActOnOpenMPThreadsClause(SourceLocation StartLoc, 10617 SourceLocation EndLoc) { 10618 return new (Context) OMPThreadsClause(StartLoc, EndLoc); 10619 } 10620 10621 OMPClause *Sema::ActOnOpenMPSIMDClause(SourceLocation StartLoc, 10622 SourceLocation EndLoc) { 10623 return new (Context) OMPSIMDClause(StartLoc, EndLoc); 10624 } 10625 10626 OMPClause *Sema::ActOnOpenMPNogroupClause(SourceLocation StartLoc, 10627 SourceLocation EndLoc) { 10628 return new (Context) OMPNogroupClause(StartLoc, EndLoc); 10629 } 10630 10631 OMPClause *Sema::ActOnOpenMPUnifiedAddressClause(SourceLocation StartLoc, 10632 SourceLocation EndLoc) { 10633 return new (Context) OMPUnifiedAddressClause(StartLoc, EndLoc); 10634 } 10635 10636 OMPClause *Sema::ActOnOpenMPUnifiedSharedMemoryClause(SourceLocation StartLoc, 10637 SourceLocation EndLoc) { 10638 return new (Context) OMPUnifiedSharedMemoryClause(StartLoc, EndLoc); 10639 } 10640 10641 OMPClause *Sema::ActOnOpenMPReverseOffloadClause(SourceLocation StartLoc, 10642 SourceLocation EndLoc) { 10643 return new (Context) OMPReverseOffloadClause(StartLoc, EndLoc); 10644 } 10645 10646 OMPClause *Sema::ActOnOpenMPDynamicAllocatorsClause(SourceLocation StartLoc, 10647 SourceLocation EndLoc) { 10648 return new (Context) OMPDynamicAllocatorsClause(StartLoc, EndLoc); 10649 } 10650 10651 OMPClause *Sema::ActOnOpenMPVarListClause( 10652 OpenMPClauseKind Kind, ArrayRef<Expr *> VarList, Expr *TailExpr, 10653 const OMPVarListLocTy &Locs, SourceLocation ColonLoc, 10654 CXXScopeSpec &ReductionOrMapperIdScopeSpec, 10655 DeclarationNameInfo &ReductionOrMapperId, OpenMPDependClauseKind DepKind, 10656 OpenMPLinearClauseKind LinKind, 10657 ArrayRef<OpenMPMapModifierKind> MapTypeModifiers, 10658 ArrayRef<SourceLocation> MapTypeModifiersLoc, OpenMPMapClauseKind MapType, 10659 bool IsMapTypeImplicit, SourceLocation DepLinMapLoc) { 10660 SourceLocation StartLoc = Locs.StartLoc; 10661 SourceLocation LParenLoc = Locs.LParenLoc; 10662 SourceLocation EndLoc = Locs.EndLoc; 10663 OMPClause *Res = nullptr; 10664 switch (Kind) { 10665 case OMPC_private: 10666 Res = ActOnOpenMPPrivateClause(VarList, StartLoc, LParenLoc, EndLoc); 10667 break; 10668 case OMPC_firstprivate: 10669 Res = ActOnOpenMPFirstprivateClause(VarList, StartLoc, LParenLoc, EndLoc); 10670 break; 10671 case OMPC_lastprivate: 10672 Res = ActOnOpenMPLastprivateClause(VarList, StartLoc, LParenLoc, EndLoc); 10673 break; 10674 case OMPC_shared: 10675 Res = ActOnOpenMPSharedClause(VarList, StartLoc, LParenLoc, EndLoc); 10676 break; 10677 case OMPC_reduction: 10678 Res = ActOnOpenMPReductionClause(VarList, StartLoc, LParenLoc, ColonLoc, 10679 EndLoc, ReductionOrMapperIdScopeSpec, 10680 ReductionOrMapperId); 10681 break; 10682 case OMPC_task_reduction: 10683 Res = ActOnOpenMPTaskReductionClause(VarList, StartLoc, LParenLoc, ColonLoc, 10684 EndLoc, ReductionOrMapperIdScopeSpec, 10685 ReductionOrMapperId); 10686 break; 10687 case OMPC_in_reduction: 10688 Res = ActOnOpenMPInReductionClause(VarList, StartLoc, LParenLoc, ColonLoc, 10689 EndLoc, ReductionOrMapperIdScopeSpec, 10690 ReductionOrMapperId); 10691 break; 10692 case OMPC_linear: 10693 Res = ActOnOpenMPLinearClause(VarList, TailExpr, StartLoc, LParenLoc, 10694 LinKind, DepLinMapLoc, ColonLoc, EndLoc); 10695 break; 10696 case OMPC_aligned: 10697 Res = ActOnOpenMPAlignedClause(VarList, TailExpr, StartLoc, LParenLoc, 10698 ColonLoc, EndLoc); 10699 break; 10700 case OMPC_copyin: 10701 Res = ActOnOpenMPCopyinClause(VarList, StartLoc, LParenLoc, EndLoc); 10702 break; 10703 case OMPC_copyprivate: 10704 Res = ActOnOpenMPCopyprivateClause(VarList, StartLoc, LParenLoc, EndLoc); 10705 break; 10706 case OMPC_flush: 10707 Res = ActOnOpenMPFlushClause(VarList, StartLoc, LParenLoc, EndLoc); 10708 break; 10709 case OMPC_depend: 10710 Res = ActOnOpenMPDependClause(DepKind, DepLinMapLoc, ColonLoc, VarList, 10711 StartLoc, LParenLoc, EndLoc); 10712 break; 10713 case OMPC_map: 10714 Res = ActOnOpenMPMapClause(MapTypeModifiers, MapTypeModifiersLoc, 10715 ReductionOrMapperIdScopeSpec, 10716 ReductionOrMapperId, MapType, IsMapTypeImplicit, 10717 DepLinMapLoc, ColonLoc, VarList, Locs); 10718 break; 10719 case OMPC_to: 10720 Res = ActOnOpenMPToClause(VarList, ReductionOrMapperIdScopeSpec, 10721 ReductionOrMapperId, Locs); 10722 break; 10723 case OMPC_from: 10724 Res = ActOnOpenMPFromClause(VarList, ReductionOrMapperIdScopeSpec, 10725 ReductionOrMapperId, Locs); 10726 break; 10727 case OMPC_use_device_ptr: 10728 Res = ActOnOpenMPUseDevicePtrClause(VarList, Locs); 10729 break; 10730 case OMPC_is_device_ptr: 10731 Res = ActOnOpenMPIsDevicePtrClause(VarList, Locs); 10732 break; 10733 case OMPC_allocate: 10734 Res = ActOnOpenMPAllocateClause(TailExpr, VarList, StartLoc, LParenLoc, 10735 ColonLoc, EndLoc); 10736 break; 10737 case OMPC_if: 10738 case OMPC_final: 10739 case OMPC_num_threads: 10740 case OMPC_safelen: 10741 case OMPC_simdlen: 10742 case OMPC_allocator: 10743 case OMPC_collapse: 10744 case OMPC_default: 10745 case OMPC_proc_bind: 10746 case OMPC_schedule: 10747 case OMPC_ordered: 10748 case OMPC_nowait: 10749 case OMPC_untied: 10750 case OMPC_mergeable: 10751 case OMPC_threadprivate: 10752 case OMPC_read: 10753 case OMPC_write: 10754 case OMPC_update: 10755 case OMPC_capture: 10756 case OMPC_seq_cst: 10757 case OMPC_device: 10758 case OMPC_threads: 10759 case OMPC_simd: 10760 case OMPC_num_teams: 10761 case OMPC_thread_limit: 10762 case OMPC_priority: 10763 case OMPC_grainsize: 10764 case OMPC_nogroup: 10765 case OMPC_num_tasks: 10766 case OMPC_hint: 10767 case OMPC_dist_schedule: 10768 case OMPC_defaultmap: 10769 case OMPC_unknown: 10770 case OMPC_uniform: 10771 case OMPC_unified_address: 10772 case OMPC_unified_shared_memory: 10773 case OMPC_reverse_offload: 10774 case OMPC_dynamic_allocators: 10775 case OMPC_atomic_default_mem_order: 10776 llvm_unreachable("Clause is not allowed."); 10777 } 10778 return Res; 10779 } 10780 10781 ExprResult Sema::getOpenMPCapturedExpr(VarDecl *Capture, ExprValueKind VK, 10782 ExprObjectKind OK, SourceLocation Loc) { 10783 ExprResult Res = BuildDeclRefExpr( 10784 Capture, Capture->getType().getNonReferenceType(), VK_LValue, Loc); 10785 if (!Res.isUsable()) 10786 return ExprError(); 10787 if (OK == OK_Ordinary && !getLangOpts().CPlusPlus) { 10788 Res = CreateBuiltinUnaryOp(Loc, UO_Deref, Res.get()); 10789 if (!Res.isUsable()) 10790 return ExprError(); 10791 } 10792 if (VK != VK_LValue && Res.get()->isGLValue()) { 10793 Res = DefaultLvalueConversion(Res.get()); 10794 if (!Res.isUsable()) 10795 return ExprError(); 10796 } 10797 return Res; 10798 } 10799 10800 OMPClause *Sema::ActOnOpenMPPrivateClause(ArrayRef<Expr *> VarList, 10801 SourceLocation StartLoc, 10802 SourceLocation LParenLoc, 10803 SourceLocation EndLoc) { 10804 SmallVector<Expr *, 8> Vars; 10805 SmallVector<Expr *, 8> PrivateCopies; 10806 for (Expr *RefExpr : VarList) { 10807 assert(RefExpr && "NULL expr in OpenMP private clause."); 10808 SourceLocation ELoc; 10809 SourceRange ERange; 10810 Expr *SimpleRefExpr = RefExpr; 10811 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange); 10812 if (Res.second) { 10813 // It will be analyzed later. 10814 Vars.push_back(RefExpr); 10815 PrivateCopies.push_back(nullptr); 10816 } 10817 ValueDecl *D = Res.first; 10818 if (!D) 10819 continue; 10820 10821 QualType Type = D->getType(); 10822 auto *VD = dyn_cast<VarDecl>(D); 10823 10824 // OpenMP [2.9.3.3, Restrictions, C/C++, p.3] 10825 // A variable that appears in a private clause must not have an incomplete 10826 // type or a reference type. 10827 if (RequireCompleteType(ELoc, Type, diag::err_omp_private_incomplete_type)) 10828 continue; 10829 Type = Type.getNonReferenceType(); 10830 10831 // OpenMP 5.0 [2.19.3, List Item Privatization, Restrictions] 10832 // A variable that is privatized must not have a const-qualified type 10833 // unless it is of class type with a mutable member. This restriction does 10834 // not apply to the firstprivate clause. 10835 // 10836 // OpenMP 3.1 [2.9.3.3, private clause, Restrictions] 10837 // A variable that appears in a private clause must not have a 10838 // const-qualified type unless it is of class type with a mutable member. 10839 if (rejectConstNotMutableType(*this, D, Type, OMPC_private, ELoc)) 10840 continue; 10841 10842 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced 10843 // in a Construct] 10844 // Variables with the predetermined data-sharing attributes may not be 10845 // listed in data-sharing attributes clauses, except for the cases 10846 // listed below. For these exceptions only, listing a predetermined 10847 // variable in a data-sharing attribute clause is allowed and overrides 10848 // the variable's predetermined data-sharing attributes. 10849 DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, /*FromParent=*/false); 10850 if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_private) { 10851 Diag(ELoc, diag::err_omp_wrong_dsa) << getOpenMPClauseName(DVar.CKind) 10852 << getOpenMPClauseName(OMPC_private); 10853 reportOriginalDsa(*this, DSAStack, D, DVar); 10854 continue; 10855 } 10856 10857 OpenMPDirectiveKind CurrDir = DSAStack->getCurrentDirective(); 10858 // Variably modified types are not supported for tasks. 10859 if (!Type->isAnyPointerType() && Type->isVariablyModifiedType() && 10860 isOpenMPTaskingDirective(CurrDir)) { 10861 Diag(ELoc, diag::err_omp_variably_modified_type_not_supported) 10862 << getOpenMPClauseName(OMPC_private) << Type 10863 << getOpenMPDirectiveName(CurrDir); 10864 bool IsDecl = 10865 !VD || 10866 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly; 10867 Diag(D->getLocation(), 10868 IsDecl ? diag::note_previous_decl : diag::note_defined_here) 10869 << D; 10870 continue; 10871 } 10872 10873 // OpenMP 4.5 [2.15.5.1, Restrictions, p.3] 10874 // A list item cannot appear in both a map clause and a data-sharing 10875 // attribute clause on the same construct 10876 if (isOpenMPTargetExecutionDirective(CurrDir)) { 10877 OpenMPClauseKind ConflictKind; 10878 if (DSAStack->checkMappableExprComponentListsForDecl( 10879 VD, /*CurrentRegionOnly=*/true, 10880 [&](OMPClauseMappableExprCommon::MappableExprComponentListRef, 10881 OpenMPClauseKind WhereFoundClauseKind) -> bool { 10882 ConflictKind = WhereFoundClauseKind; 10883 return true; 10884 })) { 10885 Diag(ELoc, diag::err_omp_variable_in_given_clause_and_dsa) 10886 << getOpenMPClauseName(OMPC_private) 10887 << getOpenMPClauseName(ConflictKind) 10888 << getOpenMPDirectiveName(CurrDir); 10889 reportOriginalDsa(*this, DSAStack, D, DVar); 10890 continue; 10891 } 10892 } 10893 10894 // OpenMP [2.9.3.3, Restrictions, C/C++, p.1] 10895 // A variable of class type (or array thereof) that appears in a private 10896 // clause requires an accessible, unambiguous default constructor for the 10897 // class type. 10898 // Generate helper private variable and initialize it with the default 10899 // value. The address of the original variable is replaced by the address of 10900 // the new private variable in CodeGen. This new variable is not added to 10901 // IdResolver, so the code in the OpenMP region uses original variable for 10902 // proper diagnostics. 10903 Type = Type.getUnqualifiedType(); 10904 VarDecl *VDPrivate = 10905 buildVarDecl(*this, ELoc, Type, D->getName(), 10906 D->hasAttrs() ? &D->getAttrs() : nullptr, 10907 VD ? cast<DeclRefExpr>(SimpleRefExpr) : nullptr); 10908 ActOnUninitializedDecl(VDPrivate); 10909 if (VDPrivate->isInvalidDecl()) 10910 continue; 10911 DeclRefExpr *VDPrivateRefExpr = buildDeclRefExpr( 10912 *this, VDPrivate, RefExpr->getType().getUnqualifiedType(), ELoc); 10913 10914 DeclRefExpr *Ref = nullptr; 10915 if (!VD && !CurContext->isDependentContext()) 10916 Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/false); 10917 DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_private, Ref); 10918 Vars.push_back((VD || CurContext->isDependentContext()) 10919 ? RefExpr->IgnoreParens() 10920 : Ref); 10921 PrivateCopies.push_back(VDPrivateRefExpr); 10922 } 10923 10924 if (Vars.empty()) 10925 return nullptr; 10926 10927 return OMPPrivateClause::Create(Context, StartLoc, LParenLoc, EndLoc, Vars, 10928 PrivateCopies); 10929 } 10930 10931 namespace { 10932 class DiagsUninitializedSeveretyRAII { 10933 private: 10934 DiagnosticsEngine &Diags; 10935 SourceLocation SavedLoc; 10936 bool IsIgnored = false; 10937 10938 public: 10939 DiagsUninitializedSeveretyRAII(DiagnosticsEngine &Diags, SourceLocation Loc, 10940 bool IsIgnored) 10941 : Diags(Diags), SavedLoc(Loc), IsIgnored(IsIgnored) { 10942 if (!IsIgnored) { 10943 Diags.setSeverity(/*Diag*/ diag::warn_uninit_self_reference_in_init, 10944 /*Map*/ diag::Severity::Ignored, Loc); 10945 } 10946 } 10947 ~DiagsUninitializedSeveretyRAII() { 10948 if (!IsIgnored) 10949 Diags.popMappings(SavedLoc); 10950 } 10951 }; 10952 } 10953 10954 OMPClause *Sema::ActOnOpenMPFirstprivateClause(ArrayRef<Expr *> VarList, 10955 SourceLocation StartLoc, 10956 SourceLocation LParenLoc, 10957 SourceLocation EndLoc) { 10958 SmallVector<Expr *, 8> Vars; 10959 SmallVector<Expr *, 8> PrivateCopies; 10960 SmallVector<Expr *, 8> Inits; 10961 SmallVector<Decl *, 4> ExprCaptures; 10962 bool IsImplicitClause = 10963 StartLoc.isInvalid() && LParenLoc.isInvalid() && EndLoc.isInvalid(); 10964 SourceLocation ImplicitClauseLoc = DSAStack->getConstructLoc(); 10965 10966 for (Expr *RefExpr : VarList) { 10967 assert(RefExpr && "NULL expr in OpenMP firstprivate clause."); 10968 SourceLocation ELoc; 10969 SourceRange ERange; 10970 Expr *SimpleRefExpr = RefExpr; 10971 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange); 10972 if (Res.second) { 10973 // It will be analyzed later. 10974 Vars.push_back(RefExpr); 10975 PrivateCopies.push_back(nullptr); 10976 Inits.push_back(nullptr); 10977 } 10978 ValueDecl *D = Res.first; 10979 if (!D) 10980 continue; 10981 10982 ELoc = IsImplicitClause ? ImplicitClauseLoc : ELoc; 10983 QualType Type = D->getType(); 10984 auto *VD = dyn_cast<VarDecl>(D); 10985 10986 // OpenMP [2.9.3.3, Restrictions, C/C++, p.3] 10987 // A variable that appears in a private clause must not have an incomplete 10988 // type or a reference type. 10989 if (RequireCompleteType(ELoc, Type, 10990 diag::err_omp_firstprivate_incomplete_type)) 10991 continue; 10992 Type = Type.getNonReferenceType(); 10993 10994 // OpenMP [2.9.3.4, Restrictions, C/C++, p.1] 10995 // A variable of class type (or array thereof) that appears in a private 10996 // clause requires an accessible, unambiguous copy constructor for the 10997 // class type. 10998 QualType ElemType = Context.getBaseElementType(Type).getNonReferenceType(); 10999 11000 // If an implicit firstprivate variable found it was checked already. 11001 DSAStackTy::DSAVarData TopDVar; 11002 if (!IsImplicitClause) { 11003 DSAStackTy::DSAVarData DVar = 11004 DSAStack->getTopDSA(D, /*FromParent=*/false); 11005 TopDVar = DVar; 11006 OpenMPDirectiveKind CurrDir = DSAStack->getCurrentDirective(); 11007 bool IsConstant = ElemType.isConstant(Context); 11008 // OpenMP [2.4.13, Data-sharing Attribute Clauses] 11009 // A list item that specifies a given variable may not appear in more 11010 // than one clause on the same directive, except that a variable may be 11011 // specified in both firstprivate and lastprivate clauses. 11012 // OpenMP 4.5 [2.10.8, Distribute Construct, p.3] 11013 // A list item may appear in a firstprivate or lastprivate clause but not 11014 // both. 11015 if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_firstprivate && 11016 (isOpenMPDistributeDirective(CurrDir) || 11017 DVar.CKind != OMPC_lastprivate) && 11018 DVar.RefExpr) { 11019 Diag(ELoc, diag::err_omp_wrong_dsa) 11020 << getOpenMPClauseName(DVar.CKind) 11021 << getOpenMPClauseName(OMPC_firstprivate); 11022 reportOriginalDsa(*this, DSAStack, D, DVar); 11023 continue; 11024 } 11025 11026 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced 11027 // in a Construct] 11028 // Variables with the predetermined data-sharing attributes may not be 11029 // listed in data-sharing attributes clauses, except for the cases 11030 // listed below. For these exceptions only, listing a predetermined 11031 // variable in a data-sharing attribute clause is allowed and overrides 11032 // the variable's predetermined data-sharing attributes. 11033 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced 11034 // in a Construct, C/C++, p.2] 11035 // Variables with const-qualified type having no mutable member may be 11036 // listed in a firstprivate clause, even if they are static data members. 11037 if (!(IsConstant || (VD && VD->isStaticDataMember())) && !DVar.RefExpr && 11038 DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_shared) { 11039 Diag(ELoc, diag::err_omp_wrong_dsa) 11040 << getOpenMPClauseName(DVar.CKind) 11041 << getOpenMPClauseName(OMPC_firstprivate); 11042 reportOriginalDsa(*this, DSAStack, D, DVar); 11043 continue; 11044 } 11045 11046 // OpenMP [2.9.3.4, Restrictions, p.2] 11047 // A list item that is private within a parallel region must not appear 11048 // in a firstprivate clause on a worksharing construct if any of the 11049 // worksharing regions arising from the worksharing construct ever bind 11050 // to any of the parallel regions arising from the parallel construct. 11051 // OpenMP 4.5 [2.15.3.4, Restrictions, p.3] 11052 // A list item that is private within a teams region must not appear in a 11053 // firstprivate clause on a distribute construct if any of the distribute 11054 // regions arising from the distribute construct ever bind to any of the 11055 // teams regions arising from the teams construct. 11056 // OpenMP 4.5 [2.15.3.4, Restrictions, p.3] 11057 // A list item that appears in a reduction clause of a teams construct 11058 // must not appear in a firstprivate clause on a distribute construct if 11059 // any of the distribute regions arising from the distribute construct 11060 // ever bind to any of the teams regions arising from the teams construct. 11061 if ((isOpenMPWorksharingDirective(CurrDir) || 11062 isOpenMPDistributeDirective(CurrDir)) && 11063 !isOpenMPParallelDirective(CurrDir) && 11064 !isOpenMPTeamsDirective(CurrDir)) { 11065 DVar = DSAStack->getImplicitDSA(D, true); 11066 if (DVar.CKind != OMPC_shared && 11067 (isOpenMPParallelDirective(DVar.DKind) || 11068 isOpenMPTeamsDirective(DVar.DKind) || 11069 DVar.DKind == OMPD_unknown)) { 11070 Diag(ELoc, diag::err_omp_required_access) 11071 << getOpenMPClauseName(OMPC_firstprivate) 11072 << getOpenMPClauseName(OMPC_shared); 11073 reportOriginalDsa(*this, DSAStack, D, DVar); 11074 continue; 11075 } 11076 } 11077 // OpenMP [2.9.3.4, Restrictions, p.3] 11078 // A list item that appears in a reduction clause of a parallel construct 11079 // must not appear in a firstprivate clause on a worksharing or task 11080 // construct if any of the worksharing or task regions arising from the 11081 // worksharing or task construct ever bind to any of the parallel regions 11082 // arising from the parallel construct. 11083 // OpenMP [2.9.3.4, Restrictions, p.4] 11084 // A list item that appears in a reduction clause in worksharing 11085 // construct must not appear in a firstprivate clause in a task construct 11086 // encountered during execution of any of the worksharing regions arising 11087 // from the worksharing construct. 11088 if (isOpenMPTaskingDirective(CurrDir)) { 11089 DVar = DSAStack->hasInnermostDSA( 11090 D, [](OpenMPClauseKind C) { return C == OMPC_reduction; }, 11091 [](OpenMPDirectiveKind K) { 11092 return isOpenMPParallelDirective(K) || 11093 isOpenMPWorksharingDirective(K) || 11094 isOpenMPTeamsDirective(K); 11095 }, 11096 /*FromParent=*/true); 11097 if (DVar.CKind == OMPC_reduction && 11098 (isOpenMPParallelDirective(DVar.DKind) || 11099 isOpenMPWorksharingDirective(DVar.DKind) || 11100 isOpenMPTeamsDirective(DVar.DKind))) { 11101 Diag(ELoc, diag::err_omp_parallel_reduction_in_task_firstprivate) 11102 << getOpenMPDirectiveName(DVar.DKind); 11103 reportOriginalDsa(*this, DSAStack, D, DVar); 11104 continue; 11105 } 11106 } 11107 11108 // OpenMP 4.5 [2.15.5.1, Restrictions, p.3] 11109 // A list item cannot appear in both a map clause and a data-sharing 11110 // attribute clause on the same construct 11111 if (isOpenMPTargetExecutionDirective(CurrDir)) { 11112 OpenMPClauseKind ConflictKind; 11113 if (DSAStack->checkMappableExprComponentListsForDecl( 11114 VD, /*CurrentRegionOnly=*/true, 11115 [&ConflictKind]( 11116 OMPClauseMappableExprCommon::MappableExprComponentListRef, 11117 OpenMPClauseKind WhereFoundClauseKind) { 11118 ConflictKind = WhereFoundClauseKind; 11119 return true; 11120 })) { 11121 Diag(ELoc, diag::err_omp_variable_in_given_clause_and_dsa) 11122 << getOpenMPClauseName(OMPC_firstprivate) 11123 << getOpenMPClauseName(ConflictKind) 11124 << getOpenMPDirectiveName(DSAStack->getCurrentDirective()); 11125 reportOriginalDsa(*this, DSAStack, D, DVar); 11126 continue; 11127 } 11128 } 11129 } 11130 11131 // Variably modified types are not supported for tasks. 11132 if (!Type->isAnyPointerType() && Type->isVariablyModifiedType() && 11133 isOpenMPTaskingDirective(DSAStack->getCurrentDirective())) { 11134 Diag(ELoc, diag::err_omp_variably_modified_type_not_supported) 11135 << getOpenMPClauseName(OMPC_firstprivate) << Type 11136 << getOpenMPDirectiveName(DSAStack->getCurrentDirective()); 11137 bool IsDecl = 11138 !VD || 11139 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly; 11140 Diag(D->getLocation(), 11141 IsDecl ? diag::note_previous_decl : diag::note_defined_here) 11142 << D; 11143 continue; 11144 } 11145 11146 Type = Type.getUnqualifiedType(); 11147 VarDecl *VDPrivate = 11148 buildVarDecl(*this, ELoc, Type, D->getName(), 11149 D->hasAttrs() ? &D->getAttrs() : nullptr, 11150 VD ? cast<DeclRefExpr>(SimpleRefExpr) : nullptr); 11151 // Generate helper private variable and initialize it with the value of the 11152 // original variable. The address of the original variable is replaced by 11153 // the address of the new private variable in the CodeGen. This new variable 11154 // is not added to IdResolver, so the code in the OpenMP region uses 11155 // original variable for proper diagnostics and variable capturing. 11156 Expr *VDInitRefExpr = nullptr; 11157 // For arrays generate initializer for single element and replace it by the 11158 // original array element in CodeGen. 11159 if (Type->isArrayType()) { 11160 VarDecl *VDInit = 11161 buildVarDecl(*this, RefExpr->getExprLoc(), ElemType, D->getName()); 11162 VDInitRefExpr = buildDeclRefExpr(*this, VDInit, ElemType, ELoc); 11163 Expr *Init = DefaultLvalueConversion(VDInitRefExpr).get(); 11164 ElemType = ElemType.getUnqualifiedType(); 11165 VarDecl *VDInitTemp = buildVarDecl(*this, RefExpr->getExprLoc(), ElemType, 11166 ".firstprivate.temp"); 11167 InitializedEntity Entity = 11168 InitializedEntity::InitializeVariable(VDInitTemp); 11169 InitializationKind Kind = InitializationKind::CreateCopy(ELoc, ELoc); 11170 11171 InitializationSequence InitSeq(*this, Entity, Kind, Init); 11172 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Init); 11173 if (Result.isInvalid()) 11174 VDPrivate->setInvalidDecl(); 11175 else 11176 VDPrivate->setInit(Result.getAs<Expr>()); 11177 // Remove temp variable declaration. 11178 Context.Deallocate(VDInitTemp); 11179 } else { 11180 VarDecl *VDInit = buildVarDecl(*this, RefExpr->getExprLoc(), Type, 11181 ".firstprivate.temp"); 11182 VDInitRefExpr = buildDeclRefExpr(*this, VDInit, RefExpr->getType(), 11183 RefExpr->getExprLoc()); 11184 AddInitializerToDecl(VDPrivate, 11185 DefaultLvalueConversion(VDInitRefExpr).get(), 11186 /*DirectInit=*/false); 11187 } 11188 if (VDPrivate->isInvalidDecl()) { 11189 if (IsImplicitClause) { 11190 Diag(RefExpr->getExprLoc(), 11191 diag::note_omp_task_predetermined_firstprivate_here); 11192 } 11193 continue; 11194 } 11195 CurContext->addDecl(VDPrivate); 11196 DeclRefExpr *VDPrivateRefExpr = buildDeclRefExpr( 11197 *this, VDPrivate, RefExpr->getType().getUnqualifiedType(), 11198 RefExpr->getExprLoc()); 11199 DeclRefExpr *Ref = nullptr; 11200 if (!VD && !CurContext->isDependentContext()) { 11201 if (TopDVar.CKind == OMPC_lastprivate) { 11202 Ref = TopDVar.PrivateCopy; 11203 } else { 11204 Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/true); 11205 if (!isOpenMPCapturedDecl(D)) 11206 ExprCaptures.push_back(Ref->getDecl()); 11207 } 11208 } 11209 DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_firstprivate, Ref); 11210 Vars.push_back((VD || CurContext->isDependentContext()) 11211 ? RefExpr->IgnoreParens() 11212 : Ref); 11213 PrivateCopies.push_back(VDPrivateRefExpr); 11214 Inits.push_back(VDInitRefExpr); 11215 } 11216 11217 if (Vars.empty()) 11218 return nullptr; 11219 11220 return OMPFirstprivateClause::Create(Context, StartLoc, LParenLoc, EndLoc, 11221 Vars, PrivateCopies, Inits, 11222 buildPreInits(Context, ExprCaptures)); 11223 } 11224 11225 OMPClause *Sema::ActOnOpenMPLastprivateClause(ArrayRef<Expr *> VarList, 11226 SourceLocation StartLoc, 11227 SourceLocation LParenLoc, 11228 SourceLocation EndLoc) { 11229 SmallVector<Expr *, 8> Vars; 11230 SmallVector<Expr *, 8> SrcExprs; 11231 SmallVector<Expr *, 8> DstExprs; 11232 SmallVector<Expr *, 8> AssignmentOps; 11233 SmallVector<Decl *, 4> ExprCaptures; 11234 SmallVector<Expr *, 4> ExprPostUpdates; 11235 for (Expr *RefExpr : VarList) { 11236 assert(RefExpr && "NULL expr in OpenMP lastprivate clause."); 11237 SourceLocation ELoc; 11238 SourceRange ERange; 11239 Expr *SimpleRefExpr = RefExpr; 11240 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange); 11241 if (Res.second) { 11242 // It will be analyzed later. 11243 Vars.push_back(RefExpr); 11244 SrcExprs.push_back(nullptr); 11245 DstExprs.push_back(nullptr); 11246 AssignmentOps.push_back(nullptr); 11247 } 11248 ValueDecl *D = Res.first; 11249 if (!D) 11250 continue; 11251 11252 QualType Type = D->getType(); 11253 auto *VD = dyn_cast<VarDecl>(D); 11254 11255 // OpenMP [2.14.3.5, Restrictions, C/C++, p.2] 11256 // A variable that appears in a lastprivate clause must not have an 11257 // incomplete type or a reference type. 11258 if (RequireCompleteType(ELoc, Type, 11259 diag::err_omp_lastprivate_incomplete_type)) 11260 continue; 11261 Type = Type.getNonReferenceType(); 11262 11263 // OpenMP 5.0 [2.19.3, List Item Privatization, Restrictions] 11264 // A variable that is privatized must not have a const-qualified type 11265 // unless it is of class type with a mutable member. This restriction does 11266 // not apply to the firstprivate clause. 11267 // 11268 // OpenMP 3.1 [2.9.3.5, lastprivate clause, Restrictions] 11269 // A variable that appears in a lastprivate clause must not have a 11270 // const-qualified type unless it is of class type with a mutable member. 11271 if (rejectConstNotMutableType(*this, D, Type, OMPC_lastprivate, ELoc)) 11272 continue; 11273 11274 OpenMPDirectiveKind CurrDir = DSAStack->getCurrentDirective(); 11275 // OpenMP [2.14.1.1, Data-sharing Attribute Rules for Variables Referenced 11276 // in a Construct] 11277 // Variables with the predetermined data-sharing attributes may not be 11278 // listed in data-sharing attributes clauses, except for the cases 11279 // listed below. 11280 // OpenMP 4.5 [2.10.8, Distribute Construct, p.3] 11281 // A list item may appear in a firstprivate or lastprivate clause but not 11282 // both. 11283 DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, /*FromParent=*/false); 11284 if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_lastprivate && 11285 (isOpenMPDistributeDirective(CurrDir) || 11286 DVar.CKind != OMPC_firstprivate) && 11287 (DVar.CKind != OMPC_private || DVar.RefExpr != nullptr)) { 11288 Diag(ELoc, diag::err_omp_wrong_dsa) 11289 << getOpenMPClauseName(DVar.CKind) 11290 << getOpenMPClauseName(OMPC_lastprivate); 11291 reportOriginalDsa(*this, DSAStack, D, DVar); 11292 continue; 11293 } 11294 11295 // OpenMP [2.14.3.5, Restrictions, p.2] 11296 // A list item that is private within a parallel region, or that appears in 11297 // the reduction clause of a parallel construct, must not appear in a 11298 // lastprivate clause on a worksharing construct if any of the corresponding 11299 // worksharing regions ever binds to any of the corresponding parallel 11300 // regions. 11301 DSAStackTy::DSAVarData TopDVar = DVar; 11302 if (isOpenMPWorksharingDirective(CurrDir) && 11303 !isOpenMPParallelDirective(CurrDir) && 11304 !isOpenMPTeamsDirective(CurrDir)) { 11305 DVar = DSAStack->getImplicitDSA(D, true); 11306 if (DVar.CKind != OMPC_shared) { 11307 Diag(ELoc, diag::err_omp_required_access) 11308 << getOpenMPClauseName(OMPC_lastprivate) 11309 << getOpenMPClauseName(OMPC_shared); 11310 reportOriginalDsa(*this, DSAStack, D, DVar); 11311 continue; 11312 } 11313 } 11314 11315 // OpenMP [2.14.3.5, Restrictions, C++, p.1,2] 11316 // A variable of class type (or array thereof) that appears in a 11317 // lastprivate clause requires an accessible, unambiguous default 11318 // constructor for the class type, unless the list item is also specified 11319 // in a firstprivate clause. 11320 // A variable of class type (or array thereof) that appears in a 11321 // lastprivate clause requires an accessible, unambiguous copy assignment 11322 // operator for the class type. 11323 Type = Context.getBaseElementType(Type).getNonReferenceType(); 11324 VarDecl *SrcVD = buildVarDecl(*this, ERange.getBegin(), 11325 Type.getUnqualifiedType(), ".lastprivate.src", 11326 D->hasAttrs() ? &D->getAttrs() : nullptr); 11327 DeclRefExpr *PseudoSrcExpr = 11328 buildDeclRefExpr(*this, SrcVD, Type.getUnqualifiedType(), ELoc); 11329 VarDecl *DstVD = 11330 buildVarDecl(*this, ERange.getBegin(), Type, ".lastprivate.dst", 11331 D->hasAttrs() ? &D->getAttrs() : nullptr); 11332 DeclRefExpr *PseudoDstExpr = buildDeclRefExpr(*this, DstVD, Type, ELoc); 11333 // For arrays generate assignment operation for single element and replace 11334 // it by the original array element in CodeGen. 11335 ExprResult AssignmentOp = BuildBinOp(/*S=*/nullptr, ELoc, BO_Assign, 11336 PseudoDstExpr, PseudoSrcExpr); 11337 if (AssignmentOp.isInvalid()) 11338 continue; 11339 AssignmentOp = 11340 ActOnFinishFullExpr(AssignmentOp.get(), ELoc, /*DiscardedValue*/ false); 11341 if (AssignmentOp.isInvalid()) 11342 continue; 11343 11344 DeclRefExpr *Ref = nullptr; 11345 if (!VD && !CurContext->isDependentContext()) { 11346 if (TopDVar.CKind == OMPC_firstprivate) { 11347 Ref = TopDVar.PrivateCopy; 11348 } else { 11349 Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/false); 11350 if (!isOpenMPCapturedDecl(D)) 11351 ExprCaptures.push_back(Ref->getDecl()); 11352 } 11353 if (TopDVar.CKind == OMPC_firstprivate || 11354 (!isOpenMPCapturedDecl(D) && 11355 Ref->getDecl()->hasAttr<OMPCaptureNoInitAttr>())) { 11356 ExprResult RefRes = DefaultLvalueConversion(Ref); 11357 if (!RefRes.isUsable()) 11358 continue; 11359 ExprResult PostUpdateRes = 11360 BuildBinOp(DSAStack->getCurScope(), ELoc, BO_Assign, SimpleRefExpr, 11361 RefRes.get()); 11362 if (!PostUpdateRes.isUsable()) 11363 continue; 11364 ExprPostUpdates.push_back( 11365 IgnoredValueConversions(PostUpdateRes.get()).get()); 11366 } 11367 } 11368 DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_lastprivate, Ref); 11369 Vars.push_back((VD || CurContext->isDependentContext()) 11370 ? RefExpr->IgnoreParens() 11371 : Ref); 11372 SrcExprs.push_back(PseudoSrcExpr); 11373 DstExprs.push_back(PseudoDstExpr); 11374 AssignmentOps.push_back(AssignmentOp.get()); 11375 } 11376 11377 if (Vars.empty()) 11378 return nullptr; 11379 11380 return OMPLastprivateClause::Create(Context, StartLoc, LParenLoc, EndLoc, 11381 Vars, SrcExprs, DstExprs, AssignmentOps, 11382 buildPreInits(Context, ExprCaptures), 11383 buildPostUpdate(*this, ExprPostUpdates)); 11384 } 11385 11386 OMPClause *Sema::ActOnOpenMPSharedClause(ArrayRef<Expr *> VarList, 11387 SourceLocation StartLoc, 11388 SourceLocation LParenLoc, 11389 SourceLocation EndLoc) { 11390 SmallVector<Expr *, 8> Vars; 11391 for (Expr *RefExpr : VarList) { 11392 assert(RefExpr && "NULL expr in OpenMP lastprivate clause."); 11393 SourceLocation ELoc; 11394 SourceRange ERange; 11395 Expr *SimpleRefExpr = RefExpr; 11396 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange); 11397 if (Res.second) { 11398 // It will be analyzed later. 11399 Vars.push_back(RefExpr); 11400 } 11401 ValueDecl *D = Res.first; 11402 if (!D) 11403 continue; 11404 11405 auto *VD = dyn_cast<VarDecl>(D); 11406 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced 11407 // in a Construct] 11408 // Variables with the predetermined data-sharing attributes may not be 11409 // listed in data-sharing attributes clauses, except for the cases 11410 // listed below. For these exceptions only, listing a predetermined 11411 // variable in a data-sharing attribute clause is allowed and overrides 11412 // the variable's predetermined data-sharing attributes. 11413 DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, /*FromParent=*/false); 11414 if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_shared && 11415 DVar.RefExpr) { 11416 Diag(ELoc, diag::err_omp_wrong_dsa) << getOpenMPClauseName(DVar.CKind) 11417 << getOpenMPClauseName(OMPC_shared); 11418 reportOriginalDsa(*this, DSAStack, D, DVar); 11419 continue; 11420 } 11421 11422 DeclRefExpr *Ref = nullptr; 11423 if (!VD && isOpenMPCapturedDecl(D) && !CurContext->isDependentContext()) 11424 Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/true); 11425 DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_shared, Ref); 11426 Vars.push_back((VD || !Ref || CurContext->isDependentContext()) 11427 ? RefExpr->IgnoreParens() 11428 : Ref); 11429 } 11430 11431 if (Vars.empty()) 11432 return nullptr; 11433 11434 return OMPSharedClause::Create(Context, StartLoc, LParenLoc, EndLoc, Vars); 11435 } 11436 11437 namespace { 11438 class DSARefChecker : public StmtVisitor<DSARefChecker, bool> { 11439 DSAStackTy *Stack; 11440 11441 public: 11442 bool VisitDeclRefExpr(DeclRefExpr *E) { 11443 if (auto *VD = dyn_cast<VarDecl>(E->getDecl())) { 11444 DSAStackTy::DSAVarData DVar = Stack->getTopDSA(VD, /*FromParent=*/false); 11445 if (DVar.CKind == OMPC_shared && !DVar.RefExpr) 11446 return false; 11447 if (DVar.CKind != OMPC_unknown) 11448 return true; 11449 DSAStackTy::DSAVarData DVarPrivate = Stack->hasDSA( 11450 VD, isOpenMPPrivate, [](OpenMPDirectiveKind) { return true; }, 11451 /*FromParent=*/true); 11452 return DVarPrivate.CKind != OMPC_unknown; 11453 } 11454 return false; 11455 } 11456 bool VisitStmt(Stmt *S) { 11457 for (Stmt *Child : S->children()) { 11458 if (Child && Visit(Child)) 11459 return true; 11460 } 11461 return false; 11462 } 11463 explicit DSARefChecker(DSAStackTy *S) : Stack(S) {} 11464 }; 11465 } // namespace 11466 11467 namespace { 11468 // Transform MemberExpression for specified FieldDecl of current class to 11469 // DeclRefExpr to specified OMPCapturedExprDecl. 11470 class TransformExprToCaptures : public TreeTransform<TransformExprToCaptures> { 11471 typedef TreeTransform<TransformExprToCaptures> BaseTransform; 11472 ValueDecl *Field = nullptr; 11473 DeclRefExpr *CapturedExpr = nullptr; 11474 11475 public: 11476 TransformExprToCaptures(Sema &SemaRef, ValueDecl *FieldDecl) 11477 : BaseTransform(SemaRef), Field(FieldDecl), CapturedExpr(nullptr) {} 11478 11479 ExprResult TransformMemberExpr(MemberExpr *E) { 11480 if (isa<CXXThisExpr>(E->getBase()->IgnoreParenImpCasts()) && 11481 E->getMemberDecl() == Field) { 11482 CapturedExpr = buildCapture(SemaRef, Field, E, /*WithInit=*/false); 11483 return CapturedExpr; 11484 } 11485 return BaseTransform::TransformMemberExpr(E); 11486 } 11487 DeclRefExpr *getCapturedExpr() { return CapturedExpr; } 11488 }; 11489 } // namespace 11490 11491 template <typename T, typename U> 11492 static T filterLookupForUDReductionAndMapper( 11493 SmallVectorImpl<U> &Lookups, const llvm::function_ref<T(ValueDecl *)> Gen) { 11494 for (U &Set : Lookups) { 11495 for (auto *D : Set) { 11496 if (T Res = Gen(cast<ValueDecl>(D))) 11497 return Res; 11498 } 11499 } 11500 return T(); 11501 } 11502 11503 static NamedDecl *findAcceptableDecl(Sema &SemaRef, NamedDecl *D) { 11504 assert(!LookupResult::isVisible(SemaRef, D) && "not in slow case"); 11505 11506 for (auto RD : D->redecls()) { 11507 // Don't bother with extra checks if we already know this one isn't visible. 11508 if (RD == D) 11509 continue; 11510 11511 auto ND = cast<NamedDecl>(RD); 11512 if (LookupResult::isVisible(SemaRef, ND)) 11513 return ND; 11514 } 11515 11516 return nullptr; 11517 } 11518 11519 static void 11520 argumentDependentLookup(Sema &SemaRef, const DeclarationNameInfo &Id, 11521 SourceLocation Loc, QualType Ty, 11522 SmallVectorImpl<UnresolvedSet<8>> &Lookups) { 11523 // Find all of the associated namespaces and classes based on the 11524 // arguments we have. 11525 Sema::AssociatedNamespaceSet AssociatedNamespaces; 11526 Sema::AssociatedClassSet AssociatedClasses; 11527 OpaqueValueExpr OVE(Loc, Ty, VK_LValue); 11528 SemaRef.FindAssociatedClassesAndNamespaces(Loc, &OVE, AssociatedNamespaces, 11529 AssociatedClasses); 11530 11531 // C++ [basic.lookup.argdep]p3: 11532 // Let X be the lookup set produced by unqualified lookup (3.4.1) 11533 // and let Y be the lookup set produced by argument dependent 11534 // lookup (defined as follows). If X contains [...] then Y is 11535 // empty. Otherwise Y is the set of declarations found in the 11536 // namespaces associated with the argument types as described 11537 // below. The set of declarations found by the lookup of the name 11538 // is the union of X and Y. 11539 // 11540 // Here, we compute Y and add its members to the overloaded 11541 // candidate set. 11542 for (auto *NS : AssociatedNamespaces) { 11543 // When considering an associated namespace, the lookup is the 11544 // same as the lookup performed when the associated namespace is 11545 // used as a qualifier (3.4.3.2) except that: 11546 // 11547 // -- Any using-directives in the associated namespace are 11548 // ignored. 11549 // 11550 // -- Any namespace-scope friend functions declared in 11551 // associated classes are visible within their respective 11552 // namespaces even if they are not visible during an ordinary 11553 // lookup (11.4). 11554 DeclContext::lookup_result R = NS->lookup(Id.getName()); 11555 for (auto *D : R) { 11556 auto *Underlying = D; 11557 if (auto *USD = dyn_cast<UsingShadowDecl>(D)) 11558 Underlying = USD->getTargetDecl(); 11559 11560 if (!isa<OMPDeclareReductionDecl>(Underlying) && 11561 !isa<OMPDeclareMapperDecl>(Underlying)) 11562 continue; 11563 11564 if (!SemaRef.isVisible(D)) { 11565 D = findAcceptableDecl(SemaRef, D); 11566 if (!D) 11567 continue; 11568 if (auto *USD = dyn_cast<UsingShadowDecl>(D)) 11569 Underlying = USD->getTargetDecl(); 11570 } 11571 Lookups.emplace_back(); 11572 Lookups.back().addDecl(Underlying); 11573 } 11574 } 11575 } 11576 11577 static ExprResult 11578 buildDeclareReductionRef(Sema &SemaRef, SourceLocation Loc, SourceRange Range, 11579 Scope *S, CXXScopeSpec &ReductionIdScopeSpec, 11580 const DeclarationNameInfo &ReductionId, QualType Ty, 11581 CXXCastPath &BasePath, Expr *UnresolvedReduction) { 11582 if (ReductionIdScopeSpec.isInvalid()) 11583 return ExprError(); 11584 SmallVector<UnresolvedSet<8>, 4> Lookups; 11585 if (S) { 11586 LookupResult Lookup(SemaRef, ReductionId, Sema::LookupOMPReductionName); 11587 Lookup.suppressDiagnostics(); 11588 while (S && SemaRef.LookupParsedName(Lookup, S, &ReductionIdScopeSpec)) { 11589 NamedDecl *D = Lookup.getRepresentativeDecl(); 11590 do { 11591 S = S->getParent(); 11592 } while (S && !S->isDeclScope(D)); 11593 if (S) 11594 S = S->getParent(); 11595 Lookups.emplace_back(); 11596 Lookups.back().append(Lookup.begin(), Lookup.end()); 11597 Lookup.clear(); 11598 } 11599 } else if (auto *ULE = 11600 cast_or_null<UnresolvedLookupExpr>(UnresolvedReduction)) { 11601 Lookups.push_back(UnresolvedSet<8>()); 11602 Decl *PrevD = nullptr; 11603 for (NamedDecl *D : ULE->decls()) { 11604 if (D == PrevD) 11605 Lookups.push_back(UnresolvedSet<8>()); 11606 else if (auto *DRD = dyn_cast<OMPDeclareReductionDecl>(D)) 11607 Lookups.back().addDecl(DRD); 11608 PrevD = D; 11609 } 11610 } 11611 if (SemaRef.CurContext->isDependentContext() || Ty->isDependentType() || 11612 Ty->isInstantiationDependentType() || 11613 Ty->containsUnexpandedParameterPack() || 11614 filterLookupForUDReductionAndMapper<bool>(Lookups, [](ValueDecl *D) { 11615 return !D->isInvalidDecl() && 11616 (D->getType()->isDependentType() || 11617 D->getType()->isInstantiationDependentType() || 11618 D->getType()->containsUnexpandedParameterPack()); 11619 })) { 11620 UnresolvedSet<8> ResSet; 11621 for (const UnresolvedSet<8> &Set : Lookups) { 11622 if (Set.empty()) 11623 continue; 11624 ResSet.append(Set.begin(), Set.end()); 11625 // The last item marks the end of all declarations at the specified scope. 11626 ResSet.addDecl(Set[Set.size() - 1]); 11627 } 11628 return UnresolvedLookupExpr::Create( 11629 SemaRef.Context, /*NamingClass=*/nullptr, 11630 ReductionIdScopeSpec.getWithLocInContext(SemaRef.Context), ReductionId, 11631 /*ADL=*/true, /*Overloaded=*/true, ResSet.begin(), ResSet.end()); 11632 } 11633 // Lookup inside the classes. 11634 // C++ [over.match.oper]p3: 11635 // For a unary operator @ with an operand of a type whose 11636 // cv-unqualified version is T1, and for a binary operator @ with 11637 // a left operand of a type whose cv-unqualified version is T1 and 11638 // a right operand of a type whose cv-unqualified version is T2, 11639 // three sets of candidate functions, designated member 11640 // candidates, non-member candidates and built-in candidates, are 11641 // constructed as follows: 11642 // -- If T1 is a complete class type or a class currently being 11643 // defined, the set of member candidates is the result of the 11644 // qualified lookup of T1::operator@ (13.3.1.1.1); otherwise, 11645 // the set of member candidates is empty. 11646 LookupResult Lookup(SemaRef, ReductionId, Sema::LookupOMPReductionName); 11647 Lookup.suppressDiagnostics(); 11648 if (const auto *TyRec = Ty->getAs<RecordType>()) { 11649 // Complete the type if it can be completed. 11650 // If the type is neither complete nor being defined, bail out now. 11651 if (SemaRef.isCompleteType(Loc, Ty) || TyRec->isBeingDefined() || 11652 TyRec->getDecl()->getDefinition()) { 11653 Lookup.clear(); 11654 SemaRef.LookupQualifiedName(Lookup, TyRec->getDecl()); 11655 if (Lookup.empty()) { 11656 Lookups.emplace_back(); 11657 Lookups.back().append(Lookup.begin(), Lookup.end()); 11658 } 11659 } 11660 } 11661 // Perform ADL. 11662 if (SemaRef.getLangOpts().CPlusPlus) 11663 argumentDependentLookup(SemaRef, ReductionId, Loc, Ty, Lookups); 11664 if (auto *VD = filterLookupForUDReductionAndMapper<ValueDecl *>( 11665 Lookups, [&SemaRef, Ty](ValueDecl *D) -> ValueDecl * { 11666 if (!D->isInvalidDecl() && 11667 SemaRef.Context.hasSameType(D->getType(), Ty)) 11668 return D; 11669 return nullptr; 11670 })) 11671 return SemaRef.BuildDeclRefExpr(VD, VD->getType().getNonReferenceType(), 11672 VK_LValue, Loc); 11673 if (SemaRef.getLangOpts().CPlusPlus) { 11674 if (auto *VD = filterLookupForUDReductionAndMapper<ValueDecl *>( 11675 Lookups, [&SemaRef, Ty, Loc](ValueDecl *D) -> ValueDecl * { 11676 if (!D->isInvalidDecl() && 11677 SemaRef.IsDerivedFrom(Loc, Ty, D->getType()) && 11678 !Ty.isMoreQualifiedThan(D->getType())) 11679 return D; 11680 return nullptr; 11681 })) { 11682 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true, 11683 /*DetectVirtual=*/false); 11684 if (SemaRef.IsDerivedFrom(Loc, Ty, VD->getType(), Paths)) { 11685 if (!Paths.isAmbiguous(SemaRef.Context.getCanonicalType( 11686 VD->getType().getUnqualifiedType()))) { 11687 if (SemaRef.CheckBaseClassAccess( 11688 Loc, VD->getType(), Ty, Paths.front(), 11689 /*DiagID=*/0) != Sema::AR_inaccessible) { 11690 SemaRef.BuildBasePathArray(Paths, BasePath); 11691 return SemaRef.BuildDeclRefExpr( 11692 VD, VD->getType().getNonReferenceType(), VK_LValue, Loc); 11693 } 11694 } 11695 } 11696 } 11697 } 11698 if (ReductionIdScopeSpec.isSet()) { 11699 SemaRef.Diag(Loc, diag::err_omp_not_resolved_reduction_identifier) << Range; 11700 return ExprError(); 11701 } 11702 return ExprEmpty(); 11703 } 11704 11705 namespace { 11706 /// Data for the reduction-based clauses. 11707 struct ReductionData { 11708 /// List of original reduction items. 11709 SmallVector<Expr *, 8> Vars; 11710 /// List of private copies of the reduction items. 11711 SmallVector<Expr *, 8> Privates; 11712 /// LHS expressions for the reduction_op expressions. 11713 SmallVector<Expr *, 8> LHSs; 11714 /// RHS expressions for the reduction_op expressions. 11715 SmallVector<Expr *, 8> RHSs; 11716 /// Reduction operation expression. 11717 SmallVector<Expr *, 8> ReductionOps; 11718 /// Taskgroup descriptors for the corresponding reduction items in 11719 /// in_reduction clauses. 11720 SmallVector<Expr *, 8> TaskgroupDescriptors; 11721 /// List of captures for clause. 11722 SmallVector<Decl *, 4> ExprCaptures; 11723 /// List of postupdate expressions. 11724 SmallVector<Expr *, 4> ExprPostUpdates; 11725 ReductionData() = delete; 11726 /// Reserves required memory for the reduction data. 11727 ReductionData(unsigned Size) { 11728 Vars.reserve(Size); 11729 Privates.reserve(Size); 11730 LHSs.reserve(Size); 11731 RHSs.reserve(Size); 11732 ReductionOps.reserve(Size); 11733 TaskgroupDescriptors.reserve(Size); 11734 ExprCaptures.reserve(Size); 11735 ExprPostUpdates.reserve(Size); 11736 } 11737 /// Stores reduction item and reduction operation only (required for dependent 11738 /// reduction item). 11739 void push(Expr *Item, Expr *ReductionOp) { 11740 Vars.emplace_back(Item); 11741 Privates.emplace_back(nullptr); 11742 LHSs.emplace_back(nullptr); 11743 RHSs.emplace_back(nullptr); 11744 ReductionOps.emplace_back(ReductionOp); 11745 TaskgroupDescriptors.emplace_back(nullptr); 11746 } 11747 /// Stores reduction data. 11748 void push(Expr *Item, Expr *Private, Expr *LHS, Expr *RHS, Expr *ReductionOp, 11749 Expr *TaskgroupDescriptor) { 11750 Vars.emplace_back(Item); 11751 Privates.emplace_back(Private); 11752 LHSs.emplace_back(LHS); 11753 RHSs.emplace_back(RHS); 11754 ReductionOps.emplace_back(ReductionOp); 11755 TaskgroupDescriptors.emplace_back(TaskgroupDescriptor); 11756 } 11757 }; 11758 } // namespace 11759 11760 static bool checkOMPArraySectionConstantForReduction( 11761 ASTContext &Context, const OMPArraySectionExpr *OASE, bool &SingleElement, 11762 SmallVectorImpl<llvm::APSInt> &ArraySizes) { 11763 const Expr *Length = OASE->getLength(); 11764 if (Length == nullptr) { 11765 // For array sections of the form [1:] or [:], we would need to analyze 11766 // the lower bound... 11767 if (OASE->getColonLoc().isValid()) 11768 return false; 11769 11770 // This is an array subscript which has implicit length 1! 11771 SingleElement = true; 11772 ArraySizes.push_back(llvm::APSInt::get(1)); 11773 } else { 11774 Expr::EvalResult Result; 11775 if (!Length->EvaluateAsInt(Result, Context)) 11776 return false; 11777 11778 llvm::APSInt ConstantLengthValue = Result.Val.getInt(); 11779 SingleElement = (ConstantLengthValue.getSExtValue() == 1); 11780 ArraySizes.push_back(ConstantLengthValue); 11781 } 11782 11783 // Get the base of this array section and walk up from there. 11784 const Expr *Base = OASE->getBase()->IgnoreParenImpCasts(); 11785 11786 // We require length = 1 for all array sections except the right-most to 11787 // guarantee that the memory region is contiguous and has no holes in it. 11788 while (const auto *TempOASE = dyn_cast<OMPArraySectionExpr>(Base)) { 11789 Length = TempOASE->getLength(); 11790 if (Length == nullptr) { 11791 // For array sections of the form [1:] or [:], we would need to analyze 11792 // the lower bound... 11793 if (OASE->getColonLoc().isValid()) 11794 return false; 11795 11796 // This is an array subscript which has implicit length 1! 11797 ArraySizes.push_back(llvm::APSInt::get(1)); 11798 } else { 11799 Expr::EvalResult Result; 11800 if (!Length->EvaluateAsInt(Result, Context)) 11801 return false; 11802 11803 llvm::APSInt ConstantLengthValue = Result.Val.getInt(); 11804 if (ConstantLengthValue.getSExtValue() != 1) 11805 return false; 11806 11807 ArraySizes.push_back(ConstantLengthValue); 11808 } 11809 Base = TempOASE->getBase()->IgnoreParenImpCasts(); 11810 } 11811 11812 // If we have a single element, we don't need to add the implicit lengths. 11813 if (!SingleElement) { 11814 while (const auto *TempASE = dyn_cast<ArraySubscriptExpr>(Base)) { 11815 // Has implicit length 1! 11816 ArraySizes.push_back(llvm::APSInt::get(1)); 11817 Base = TempASE->getBase()->IgnoreParenImpCasts(); 11818 } 11819 } 11820 11821 // This array section can be privatized as a single value or as a constant 11822 // sized array. 11823 return true; 11824 } 11825 11826 static bool actOnOMPReductionKindClause( 11827 Sema &S, DSAStackTy *Stack, OpenMPClauseKind ClauseKind, 11828 ArrayRef<Expr *> VarList, SourceLocation StartLoc, SourceLocation LParenLoc, 11829 SourceLocation ColonLoc, SourceLocation EndLoc, 11830 CXXScopeSpec &ReductionIdScopeSpec, const DeclarationNameInfo &ReductionId, 11831 ArrayRef<Expr *> UnresolvedReductions, ReductionData &RD) { 11832 DeclarationName DN = ReductionId.getName(); 11833 OverloadedOperatorKind OOK = DN.getCXXOverloadedOperator(); 11834 BinaryOperatorKind BOK = BO_Comma; 11835 11836 ASTContext &Context = S.Context; 11837 // OpenMP [2.14.3.6, reduction clause] 11838 // C 11839 // reduction-identifier is either an identifier or one of the following 11840 // operators: +, -, *, &, |, ^, && and || 11841 // C++ 11842 // reduction-identifier is either an id-expression or one of the following 11843 // operators: +, -, *, &, |, ^, && and || 11844 switch (OOK) { 11845 case OO_Plus: 11846 case OO_Minus: 11847 BOK = BO_Add; 11848 break; 11849 case OO_Star: 11850 BOK = BO_Mul; 11851 break; 11852 case OO_Amp: 11853 BOK = BO_And; 11854 break; 11855 case OO_Pipe: 11856 BOK = BO_Or; 11857 break; 11858 case OO_Caret: 11859 BOK = BO_Xor; 11860 break; 11861 case OO_AmpAmp: 11862 BOK = BO_LAnd; 11863 break; 11864 case OO_PipePipe: 11865 BOK = BO_LOr; 11866 break; 11867 case OO_New: 11868 case OO_Delete: 11869 case OO_Array_New: 11870 case OO_Array_Delete: 11871 case OO_Slash: 11872 case OO_Percent: 11873 case OO_Tilde: 11874 case OO_Exclaim: 11875 case OO_Equal: 11876 case OO_Less: 11877 case OO_Greater: 11878 case OO_LessEqual: 11879 case OO_GreaterEqual: 11880 case OO_PlusEqual: 11881 case OO_MinusEqual: 11882 case OO_StarEqual: 11883 case OO_SlashEqual: 11884 case OO_PercentEqual: 11885 case OO_CaretEqual: 11886 case OO_AmpEqual: 11887 case OO_PipeEqual: 11888 case OO_LessLess: 11889 case OO_GreaterGreater: 11890 case OO_LessLessEqual: 11891 case OO_GreaterGreaterEqual: 11892 case OO_EqualEqual: 11893 case OO_ExclaimEqual: 11894 case OO_Spaceship: 11895 case OO_PlusPlus: 11896 case OO_MinusMinus: 11897 case OO_Comma: 11898 case OO_ArrowStar: 11899 case OO_Arrow: 11900 case OO_Call: 11901 case OO_Subscript: 11902 case OO_Conditional: 11903 case OO_Coawait: 11904 case NUM_OVERLOADED_OPERATORS: 11905 llvm_unreachable("Unexpected reduction identifier"); 11906 case OO_None: 11907 if (IdentifierInfo *II = DN.getAsIdentifierInfo()) { 11908 if (II->isStr("max")) 11909 BOK = BO_GT; 11910 else if (II->isStr("min")) 11911 BOK = BO_LT; 11912 } 11913 break; 11914 } 11915 SourceRange ReductionIdRange; 11916 if (ReductionIdScopeSpec.isValid()) 11917 ReductionIdRange.setBegin(ReductionIdScopeSpec.getBeginLoc()); 11918 else 11919 ReductionIdRange.setBegin(ReductionId.getBeginLoc()); 11920 ReductionIdRange.setEnd(ReductionId.getEndLoc()); 11921 11922 auto IR = UnresolvedReductions.begin(), ER = UnresolvedReductions.end(); 11923 bool FirstIter = true; 11924 for (Expr *RefExpr : VarList) { 11925 assert(RefExpr && "nullptr expr in OpenMP reduction clause."); 11926 // OpenMP [2.1, C/C++] 11927 // A list item is a variable or array section, subject to the restrictions 11928 // specified in Section 2.4 on page 42 and in each of the sections 11929 // describing clauses and directives for which a list appears. 11930 // OpenMP [2.14.3.3, Restrictions, p.1] 11931 // A variable that is part of another variable (as an array or 11932 // structure element) cannot appear in a private clause. 11933 if (!FirstIter && IR != ER) 11934 ++IR; 11935 FirstIter = false; 11936 SourceLocation ELoc; 11937 SourceRange ERange; 11938 Expr *SimpleRefExpr = RefExpr; 11939 auto Res = getPrivateItem(S, SimpleRefExpr, ELoc, ERange, 11940 /*AllowArraySection=*/true); 11941 if (Res.second) { 11942 // Try to find 'declare reduction' corresponding construct before using 11943 // builtin/overloaded operators. 11944 QualType Type = Context.DependentTy; 11945 CXXCastPath BasePath; 11946 ExprResult DeclareReductionRef = buildDeclareReductionRef( 11947 S, ELoc, ERange, Stack->getCurScope(), ReductionIdScopeSpec, 11948 ReductionId, Type, BasePath, IR == ER ? nullptr : *IR); 11949 Expr *ReductionOp = nullptr; 11950 if (S.CurContext->isDependentContext() && 11951 (DeclareReductionRef.isUnset() || 11952 isa<UnresolvedLookupExpr>(DeclareReductionRef.get()))) 11953 ReductionOp = DeclareReductionRef.get(); 11954 // It will be analyzed later. 11955 RD.push(RefExpr, ReductionOp); 11956 } 11957 ValueDecl *D = Res.first; 11958 if (!D) 11959 continue; 11960 11961 Expr *TaskgroupDescriptor = nullptr; 11962 QualType Type; 11963 auto *ASE = dyn_cast<ArraySubscriptExpr>(RefExpr->IgnoreParens()); 11964 auto *OASE = dyn_cast<OMPArraySectionExpr>(RefExpr->IgnoreParens()); 11965 if (ASE) { 11966 Type = ASE->getType().getNonReferenceType(); 11967 } else if (OASE) { 11968 QualType BaseType = 11969 OMPArraySectionExpr::getBaseOriginalType(OASE->getBase()); 11970 if (const auto *ATy = BaseType->getAsArrayTypeUnsafe()) 11971 Type = ATy->getElementType(); 11972 else 11973 Type = BaseType->getPointeeType(); 11974 Type = Type.getNonReferenceType(); 11975 } else { 11976 Type = Context.getBaseElementType(D->getType().getNonReferenceType()); 11977 } 11978 auto *VD = dyn_cast<VarDecl>(D); 11979 11980 // OpenMP [2.9.3.3, Restrictions, C/C++, p.3] 11981 // A variable that appears in a private clause must not have an incomplete 11982 // type or a reference type. 11983 if (S.RequireCompleteType(ELoc, D->getType(), 11984 diag::err_omp_reduction_incomplete_type)) 11985 continue; 11986 // OpenMP [2.14.3.6, reduction clause, Restrictions] 11987 // A list item that appears in a reduction clause must not be 11988 // const-qualified. 11989 if (rejectConstNotMutableType(S, D, Type, ClauseKind, ELoc, 11990 /*AcceptIfMutable*/ false, ASE || OASE)) 11991 continue; 11992 11993 OpenMPDirectiveKind CurrDir = Stack->getCurrentDirective(); 11994 // OpenMP [2.9.3.6, Restrictions, C/C++, p.4] 11995 // If a list-item is a reference type then it must bind to the same object 11996 // for all threads of the team. 11997 if (!ASE && !OASE) { 11998 if (VD) { 11999 VarDecl *VDDef = VD->getDefinition(); 12000 if (VD->getType()->isReferenceType() && VDDef && VDDef->hasInit()) { 12001 DSARefChecker Check(Stack); 12002 if (Check.Visit(VDDef->getInit())) { 12003 S.Diag(ELoc, diag::err_omp_reduction_ref_type_arg) 12004 << getOpenMPClauseName(ClauseKind) << ERange; 12005 S.Diag(VDDef->getLocation(), diag::note_defined_here) << VDDef; 12006 continue; 12007 } 12008 } 12009 } 12010 12011 // OpenMP [2.14.1.1, Data-sharing Attribute Rules for Variables Referenced 12012 // in a Construct] 12013 // Variables with the predetermined data-sharing attributes may not be 12014 // listed in data-sharing attributes clauses, except for the cases 12015 // listed below. For these exceptions only, listing a predetermined 12016 // variable in a data-sharing attribute clause is allowed and overrides 12017 // the variable's predetermined data-sharing attributes. 12018 // OpenMP [2.14.3.6, Restrictions, p.3] 12019 // Any number of reduction clauses can be specified on the directive, 12020 // but a list item can appear only once in the reduction clauses for that 12021 // directive. 12022 DSAStackTy::DSAVarData DVar = Stack->getTopDSA(D, /*FromParent=*/false); 12023 if (DVar.CKind == OMPC_reduction) { 12024 S.Diag(ELoc, diag::err_omp_once_referenced) 12025 << getOpenMPClauseName(ClauseKind); 12026 if (DVar.RefExpr) 12027 S.Diag(DVar.RefExpr->getExprLoc(), diag::note_omp_referenced); 12028 continue; 12029 } 12030 if (DVar.CKind != OMPC_unknown) { 12031 S.Diag(ELoc, diag::err_omp_wrong_dsa) 12032 << getOpenMPClauseName(DVar.CKind) 12033 << getOpenMPClauseName(OMPC_reduction); 12034 reportOriginalDsa(S, Stack, D, DVar); 12035 continue; 12036 } 12037 12038 // OpenMP [2.14.3.6, Restrictions, p.1] 12039 // A list item that appears in a reduction clause of a worksharing 12040 // construct must be shared in the parallel regions to which any of the 12041 // worksharing regions arising from the worksharing construct bind. 12042 if (isOpenMPWorksharingDirective(CurrDir) && 12043 !isOpenMPParallelDirective(CurrDir) && 12044 !isOpenMPTeamsDirective(CurrDir)) { 12045 DVar = Stack->getImplicitDSA(D, true); 12046 if (DVar.CKind != OMPC_shared) { 12047 S.Diag(ELoc, diag::err_omp_required_access) 12048 << getOpenMPClauseName(OMPC_reduction) 12049 << getOpenMPClauseName(OMPC_shared); 12050 reportOriginalDsa(S, Stack, D, DVar); 12051 continue; 12052 } 12053 } 12054 } 12055 12056 // Try to find 'declare reduction' corresponding construct before using 12057 // builtin/overloaded operators. 12058 CXXCastPath BasePath; 12059 ExprResult DeclareReductionRef = buildDeclareReductionRef( 12060 S, ELoc, ERange, Stack->getCurScope(), ReductionIdScopeSpec, 12061 ReductionId, Type, BasePath, IR == ER ? nullptr : *IR); 12062 if (DeclareReductionRef.isInvalid()) 12063 continue; 12064 if (S.CurContext->isDependentContext() && 12065 (DeclareReductionRef.isUnset() || 12066 isa<UnresolvedLookupExpr>(DeclareReductionRef.get()))) { 12067 RD.push(RefExpr, DeclareReductionRef.get()); 12068 continue; 12069 } 12070 if (BOK == BO_Comma && DeclareReductionRef.isUnset()) { 12071 // Not allowed reduction identifier is found. 12072 S.Diag(ReductionId.getBeginLoc(), 12073 diag::err_omp_unknown_reduction_identifier) 12074 << Type << ReductionIdRange; 12075 continue; 12076 } 12077 12078 // OpenMP [2.14.3.6, reduction clause, Restrictions] 12079 // The type of a list item that appears in a reduction clause must be valid 12080 // for the reduction-identifier. For a max or min reduction in C, the type 12081 // of the list item must be an allowed arithmetic data type: char, int, 12082 // float, double, or _Bool, possibly modified with long, short, signed, or 12083 // unsigned. For a max or min reduction in C++, the type of the list item 12084 // must be an allowed arithmetic data type: char, wchar_t, int, float, 12085 // double, or bool, possibly modified with long, short, signed, or unsigned. 12086 if (DeclareReductionRef.isUnset()) { 12087 if ((BOK == BO_GT || BOK == BO_LT) && 12088 !(Type->isScalarType() || 12089 (S.getLangOpts().CPlusPlus && Type->isArithmeticType()))) { 12090 S.Diag(ELoc, diag::err_omp_clause_not_arithmetic_type_arg) 12091 << getOpenMPClauseName(ClauseKind) << S.getLangOpts().CPlusPlus; 12092 if (!ASE && !OASE) { 12093 bool IsDecl = !VD || VD->isThisDeclarationADefinition(Context) == 12094 VarDecl::DeclarationOnly; 12095 S.Diag(D->getLocation(), 12096 IsDecl ? diag::note_previous_decl : diag::note_defined_here) 12097 << D; 12098 } 12099 continue; 12100 } 12101 if ((BOK == BO_OrAssign || BOK == BO_AndAssign || BOK == BO_XorAssign) && 12102 !S.getLangOpts().CPlusPlus && Type->isFloatingType()) { 12103 S.Diag(ELoc, diag::err_omp_clause_floating_type_arg) 12104 << getOpenMPClauseName(ClauseKind); 12105 if (!ASE && !OASE) { 12106 bool IsDecl = !VD || VD->isThisDeclarationADefinition(Context) == 12107 VarDecl::DeclarationOnly; 12108 S.Diag(D->getLocation(), 12109 IsDecl ? diag::note_previous_decl : diag::note_defined_here) 12110 << D; 12111 } 12112 continue; 12113 } 12114 } 12115 12116 Type = Type.getNonLValueExprType(Context).getUnqualifiedType(); 12117 VarDecl *LHSVD = buildVarDecl(S, ELoc, Type, ".reduction.lhs", 12118 D->hasAttrs() ? &D->getAttrs() : nullptr); 12119 VarDecl *RHSVD = buildVarDecl(S, ELoc, Type, D->getName(), 12120 D->hasAttrs() ? &D->getAttrs() : nullptr); 12121 QualType PrivateTy = Type; 12122 12123 // Try if we can determine constant lengths for all array sections and avoid 12124 // the VLA. 12125 bool ConstantLengthOASE = false; 12126 if (OASE) { 12127 bool SingleElement; 12128 llvm::SmallVector<llvm::APSInt, 4> ArraySizes; 12129 ConstantLengthOASE = checkOMPArraySectionConstantForReduction( 12130 Context, OASE, SingleElement, ArraySizes); 12131 12132 // If we don't have a single element, we must emit a constant array type. 12133 if (ConstantLengthOASE && !SingleElement) { 12134 for (llvm::APSInt &Size : ArraySizes) 12135 PrivateTy = Context.getConstantArrayType( 12136 PrivateTy, Size, ArrayType::Normal, /*IndexTypeQuals=*/0); 12137 } 12138 } 12139 12140 if ((OASE && !ConstantLengthOASE) || 12141 (!OASE && !ASE && 12142 D->getType().getNonReferenceType()->isVariablyModifiedType())) { 12143 if (!Context.getTargetInfo().isVLASupported()) { 12144 if (isOpenMPTargetExecutionDirective(Stack->getCurrentDirective())) { 12145 S.Diag(ELoc, diag::err_omp_reduction_vla_unsupported) << !!OASE; 12146 S.Diag(ELoc, diag::note_vla_unsupported); 12147 } else { 12148 S.targetDiag(ELoc, diag::err_omp_reduction_vla_unsupported) << !!OASE; 12149 S.targetDiag(ELoc, diag::note_vla_unsupported); 12150 } 12151 continue; 12152 } 12153 // For arrays/array sections only: 12154 // Create pseudo array type for private copy. The size for this array will 12155 // be generated during codegen. 12156 // For array subscripts or single variables Private Ty is the same as Type 12157 // (type of the variable or single array element). 12158 PrivateTy = Context.getVariableArrayType( 12159 Type, 12160 new (Context) OpaqueValueExpr(ELoc, Context.getSizeType(), VK_RValue), 12161 ArrayType::Normal, /*IndexTypeQuals=*/0, SourceRange()); 12162 } else if (!ASE && !OASE && 12163 Context.getAsArrayType(D->getType().getNonReferenceType())) { 12164 PrivateTy = D->getType().getNonReferenceType(); 12165 } 12166 // Private copy. 12167 VarDecl *PrivateVD = 12168 buildVarDecl(S, ELoc, PrivateTy, D->getName(), 12169 D->hasAttrs() ? &D->getAttrs() : nullptr, 12170 VD ? cast<DeclRefExpr>(SimpleRefExpr) : nullptr); 12171 // Add initializer for private variable. 12172 Expr *Init = nullptr; 12173 DeclRefExpr *LHSDRE = buildDeclRefExpr(S, LHSVD, Type, ELoc); 12174 DeclRefExpr *RHSDRE = buildDeclRefExpr(S, RHSVD, Type, ELoc); 12175 if (DeclareReductionRef.isUsable()) { 12176 auto *DRDRef = DeclareReductionRef.getAs<DeclRefExpr>(); 12177 auto *DRD = cast<OMPDeclareReductionDecl>(DRDRef->getDecl()); 12178 if (DRD->getInitializer()) { 12179 Init = DRDRef; 12180 RHSVD->setInit(DRDRef); 12181 RHSVD->setInitStyle(VarDecl::CallInit); 12182 } 12183 } else { 12184 switch (BOK) { 12185 case BO_Add: 12186 case BO_Xor: 12187 case BO_Or: 12188 case BO_LOr: 12189 // '+', '-', '^', '|', '||' reduction ops - initializer is '0'. 12190 if (Type->isScalarType() || Type->isAnyComplexType()) 12191 Init = S.ActOnIntegerConstant(ELoc, /*Val=*/0).get(); 12192 break; 12193 case BO_Mul: 12194 case BO_LAnd: 12195 if (Type->isScalarType() || Type->isAnyComplexType()) { 12196 // '*' and '&&' reduction ops - initializer is '1'. 12197 Init = S.ActOnIntegerConstant(ELoc, /*Val=*/1).get(); 12198 } 12199 break; 12200 case BO_And: { 12201 // '&' reduction op - initializer is '~0'. 12202 QualType OrigType = Type; 12203 if (auto *ComplexTy = OrigType->getAs<ComplexType>()) 12204 Type = ComplexTy->getElementType(); 12205 if (Type->isRealFloatingType()) { 12206 llvm::APFloat InitValue = 12207 llvm::APFloat::getAllOnesValue(Context.getTypeSize(Type), 12208 /*isIEEE=*/true); 12209 Init = FloatingLiteral::Create(Context, InitValue, /*isexact=*/true, 12210 Type, ELoc); 12211 } else if (Type->isScalarType()) { 12212 uint64_t Size = Context.getTypeSize(Type); 12213 QualType IntTy = Context.getIntTypeForBitwidth(Size, /*Signed=*/0); 12214 llvm::APInt InitValue = llvm::APInt::getAllOnesValue(Size); 12215 Init = IntegerLiteral::Create(Context, InitValue, IntTy, ELoc); 12216 } 12217 if (Init && OrigType->isAnyComplexType()) { 12218 // Init = 0xFFFF + 0xFFFFi; 12219 auto *Im = new (Context) ImaginaryLiteral(Init, OrigType); 12220 Init = S.CreateBuiltinBinOp(ELoc, BO_Add, Init, Im).get(); 12221 } 12222 Type = OrigType; 12223 break; 12224 } 12225 case BO_LT: 12226 case BO_GT: { 12227 // 'min' reduction op - initializer is 'Largest representable number in 12228 // the reduction list item type'. 12229 // 'max' reduction op - initializer is 'Least representable number in 12230 // the reduction list item type'. 12231 if (Type->isIntegerType() || Type->isPointerType()) { 12232 bool IsSigned = Type->hasSignedIntegerRepresentation(); 12233 uint64_t Size = Context.getTypeSize(Type); 12234 QualType IntTy = 12235 Context.getIntTypeForBitwidth(Size, /*Signed=*/IsSigned); 12236 llvm::APInt InitValue = 12237 (BOK != BO_LT) ? IsSigned ? llvm::APInt::getSignedMinValue(Size) 12238 : llvm::APInt::getMinValue(Size) 12239 : IsSigned ? llvm::APInt::getSignedMaxValue(Size) 12240 : llvm::APInt::getMaxValue(Size); 12241 Init = IntegerLiteral::Create(Context, InitValue, IntTy, ELoc); 12242 if (Type->isPointerType()) { 12243 // Cast to pointer type. 12244 ExprResult CastExpr = S.BuildCStyleCastExpr( 12245 ELoc, Context.getTrivialTypeSourceInfo(Type, ELoc), ELoc, Init); 12246 if (CastExpr.isInvalid()) 12247 continue; 12248 Init = CastExpr.get(); 12249 } 12250 } else if (Type->isRealFloatingType()) { 12251 llvm::APFloat InitValue = llvm::APFloat::getLargest( 12252 Context.getFloatTypeSemantics(Type), BOK != BO_LT); 12253 Init = FloatingLiteral::Create(Context, InitValue, /*isexact=*/true, 12254 Type, ELoc); 12255 } 12256 break; 12257 } 12258 case BO_PtrMemD: 12259 case BO_PtrMemI: 12260 case BO_MulAssign: 12261 case BO_Div: 12262 case BO_Rem: 12263 case BO_Sub: 12264 case BO_Shl: 12265 case BO_Shr: 12266 case BO_LE: 12267 case BO_GE: 12268 case BO_EQ: 12269 case BO_NE: 12270 case BO_Cmp: 12271 case BO_AndAssign: 12272 case BO_XorAssign: 12273 case BO_OrAssign: 12274 case BO_Assign: 12275 case BO_AddAssign: 12276 case BO_SubAssign: 12277 case BO_DivAssign: 12278 case BO_RemAssign: 12279 case BO_ShlAssign: 12280 case BO_ShrAssign: 12281 case BO_Comma: 12282 llvm_unreachable("Unexpected reduction operation"); 12283 } 12284 } 12285 if (Init && DeclareReductionRef.isUnset()) 12286 S.AddInitializerToDecl(RHSVD, Init, /*DirectInit=*/false); 12287 else if (!Init) 12288 S.ActOnUninitializedDecl(RHSVD); 12289 if (RHSVD->isInvalidDecl()) 12290 continue; 12291 if (!RHSVD->hasInit() && 12292 (DeclareReductionRef.isUnset() || !S.LangOpts.CPlusPlus)) { 12293 S.Diag(ELoc, diag::err_omp_reduction_id_not_compatible) 12294 << Type << ReductionIdRange; 12295 bool IsDecl = !VD || VD->isThisDeclarationADefinition(Context) == 12296 VarDecl::DeclarationOnly; 12297 S.Diag(D->getLocation(), 12298 IsDecl ? diag::note_previous_decl : diag::note_defined_here) 12299 << D; 12300 continue; 12301 } 12302 // Store initializer for single element in private copy. Will be used during 12303 // codegen. 12304 PrivateVD->setInit(RHSVD->getInit()); 12305 PrivateVD->setInitStyle(RHSVD->getInitStyle()); 12306 DeclRefExpr *PrivateDRE = buildDeclRefExpr(S, PrivateVD, PrivateTy, ELoc); 12307 ExprResult ReductionOp; 12308 if (DeclareReductionRef.isUsable()) { 12309 QualType RedTy = DeclareReductionRef.get()->getType(); 12310 QualType PtrRedTy = Context.getPointerType(RedTy); 12311 ExprResult LHS = S.CreateBuiltinUnaryOp(ELoc, UO_AddrOf, LHSDRE); 12312 ExprResult RHS = S.CreateBuiltinUnaryOp(ELoc, UO_AddrOf, RHSDRE); 12313 if (!BasePath.empty()) { 12314 LHS = S.DefaultLvalueConversion(LHS.get()); 12315 RHS = S.DefaultLvalueConversion(RHS.get()); 12316 LHS = ImplicitCastExpr::Create(Context, PtrRedTy, 12317 CK_UncheckedDerivedToBase, LHS.get(), 12318 &BasePath, LHS.get()->getValueKind()); 12319 RHS = ImplicitCastExpr::Create(Context, PtrRedTy, 12320 CK_UncheckedDerivedToBase, RHS.get(), 12321 &BasePath, RHS.get()->getValueKind()); 12322 } 12323 FunctionProtoType::ExtProtoInfo EPI; 12324 QualType Params[] = {PtrRedTy, PtrRedTy}; 12325 QualType FnTy = Context.getFunctionType(Context.VoidTy, Params, EPI); 12326 auto *OVE = new (Context) OpaqueValueExpr( 12327 ELoc, Context.getPointerType(FnTy), VK_RValue, OK_Ordinary, 12328 S.DefaultLvalueConversion(DeclareReductionRef.get()).get()); 12329 Expr *Args[] = {LHS.get(), RHS.get()}; 12330 ReductionOp = 12331 CallExpr::Create(Context, OVE, Args, Context.VoidTy, VK_RValue, ELoc); 12332 } else { 12333 ReductionOp = S.BuildBinOp( 12334 Stack->getCurScope(), ReductionId.getBeginLoc(), BOK, LHSDRE, RHSDRE); 12335 if (ReductionOp.isUsable()) { 12336 if (BOK != BO_LT && BOK != BO_GT) { 12337 ReductionOp = 12338 S.BuildBinOp(Stack->getCurScope(), ReductionId.getBeginLoc(), 12339 BO_Assign, LHSDRE, ReductionOp.get()); 12340 } else { 12341 auto *ConditionalOp = new (Context) 12342 ConditionalOperator(ReductionOp.get(), ELoc, LHSDRE, ELoc, RHSDRE, 12343 Type, VK_LValue, OK_Ordinary); 12344 ReductionOp = 12345 S.BuildBinOp(Stack->getCurScope(), ReductionId.getBeginLoc(), 12346 BO_Assign, LHSDRE, ConditionalOp); 12347 } 12348 if (ReductionOp.isUsable()) 12349 ReductionOp = S.ActOnFinishFullExpr(ReductionOp.get(), 12350 /*DiscardedValue*/ false); 12351 } 12352 if (!ReductionOp.isUsable()) 12353 continue; 12354 } 12355 12356 // OpenMP [2.15.4.6, Restrictions, p.2] 12357 // A list item that appears in an in_reduction clause of a task construct 12358 // must appear in a task_reduction clause of a construct associated with a 12359 // taskgroup region that includes the participating task in its taskgroup 12360 // set. The construct associated with the innermost region that meets this 12361 // condition must specify the same reduction-identifier as the in_reduction 12362 // clause. 12363 if (ClauseKind == OMPC_in_reduction) { 12364 SourceRange ParentSR; 12365 BinaryOperatorKind ParentBOK; 12366 const Expr *ParentReductionOp; 12367 Expr *ParentBOKTD, *ParentReductionOpTD; 12368 DSAStackTy::DSAVarData ParentBOKDSA = 12369 Stack->getTopMostTaskgroupReductionData(D, ParentSR, ParentBOK, 12370 ParentBOKTD); 12371 DSAStackTy::DSAVarData ParentReductionOpDSA = 12372 Stack->getTopMostTaskgroupReductionData( 12373 D, ParentSR, ParentReductionOp, ParentReductionOpTD); 12374 bool IsParentBOK = ParentBOKDSA.DKind != OMPD_unknown; 12375 bool IsParentReductionOp = ParentReductionOpDSA.DKind != OMPD_unknown; 12376 if (!IsParentBOK && !IsParentReductionOp) { 12377 S.Diag(ELoc, diag::err_omp_in_reduction_not_task_reduction); 12378 continue; 12379 } 12380 if ((DeclareReductionRef.isUnset() && IsParentReductionOp) || 12381 (DeclareReductionRef.isUsable() && IsParentBOK) || BOK != ParentBOK || 12382 IsParentReductionOp) { 12383 bool EmitError = true; 12384 if (IsParentReductionOp && DeclareReductionRef.isUsable()) { 12385 llvm::FoldingSetNodeID RedId, ParentRedId; 12386 ParentReductionOp->Profile(ParentRedId, Context, /*Canonical=*/true); 12387 DeclareReductionRef.get()->Profile(RedId, Context, 12388 /*Canonical=*/true); 12389 EmitError = RedId != ParentRedId; 12390 } 12391 if (EmitError) { 12392 S.Diag(ReductionId.getBeginLoc(), 12393 diag::err_omp_reduction_identifier_mismatch) 12394 << ReductionIdRange << RefExpr->getSourceRange(); 12395 S.Diag(ParentSR.getBegin(), 12396 diag::note_omp_previous_reduction_identifier) 12397 << ParentSR 12398 << (IsParentBOK ? ParentBOKDSA.RefExpr 12399 : ParentReductionOpDSA.RefExpr) 12400 ->getSourceRange(); 12401 continue; 12402 } 12403 } 12404 TaskgroupDescriptor = IsParentBOK ? ParentBOKTD : ParentReductionOpTD; 12405 assert(TaskgroupDescriptor && "Taskgroup descriptor must be defined."); 12406 } 12407 12408 DeclRefExpr *Ref = nullptr; 12409 Expr *VarsExpr = RefExpr->IgnoreParens(); 12410 if (!VD && !S.CurContext->isDependentContext()) { 12411 if (ASE || OASE) { 12412 TransformExprToCaptures RebuildToCapture(S, D); 12413 VarsExpr = 12414 RebuildToCapture.TransformExpr(RefExpr->IgnoreParens()).get(); 12415 Ref = RebuildToCapture.getCapturedExpr(); 12416 } else { 12417 VarsExpr = Ref = buildCapture(S, D, SimpleRefExpr, /*WithInit=*/false); 12418 } 12419 if (!S.isOpenMPCapturedDecl(D)) { 12420 RD.ExprCaptures.emplace_back(Ref->getDecl()); 12421 if (Ref->getDecl()->hasAttr<OMPCaptureNoInitAttr>()) { 12422 ExprResult RefRes = S.DefaultLvalueConversion(Ref); 12423 if (!RefRes.isUsable()) 12424 continue; 12425 ExprResult PostUpdateRes = 12426 S.BuildBinOp(Stack->getCurScope(), ELoc, BO_Assign, SimpleRefExpr, 12427 RefRes.get()); 12428 if (!PostUpdateRes.isUsable()) 12429 continue; 12430 if (isOpenMPTaskingDirective(Stack->getCurrentDirective()) || 12431 Stack->getCurrentDirective() == OMPD_taskgroup) { 12432 S.Diag(RefExpr->getExprLoc(), 12433 diag::err_omp_reduction_non_addressable_expression) 12434 << RefExpr->getSourceRange(); 12435 continue; 12436 } 12437 RD.ExprPostUpdates.emplace_back( 12438 S.IgnoredValueConversions(PostUpdateRes.get()).get()); 12439 } 12440 } 12441 } 12442 // All reduction items are still marked as reduction (to do not increase 12443 // code base size). 12444 Stack->addDSA(D, RefExpr->IgnoreParens(), OMPC_reduction, Ref); 12445 if (CurrDir == OMPD_taskgroup) { 12446 if (DeclareReductionRef.isUsable()) 12447 Stack->addTaskgroupReductionData(D, ReductionIdRange, 12448 DeclareReductionRef.get()); 12449 else 12450 Stack->addTaskgroupReductionData(D, ReductionIdRange, BOK); 12451 } 12452 RD.push(VarsExpr, PrivateDRE, LHSDRE, RHSDRE, ReductionOp.get(), 12453 TaskgroupDescriptor); 12454 } 12455 return RD.Vars.empty(); 12456 } 12457 12458 OMPClause *Sema::ActOnOpenMPReductionClause( 12459 ArrayRef<Expr *> VarList, SourceLocation StartLoc, SourceLocation LParenLoc, 12460 SourceLocation ColonLoc, SourceLocation EndLoc, 12461 CXXScopeSpec &ReductionIdScopeSpec, const DeclarationNameInfo &ReductionId, 12462 ArrayRef<Expr *> UnresolvedReductions) { 12463 ReductionData RD(VarList.size()); 12464 if (actOnOMPReductionKindClause(*this, DSAStack, OMPC_reduction, VarList, 12465 StartLoc, LParenLoc, ColonLoc, EndLoc, 12466 ReductionIdScopeSpec, ReductionId, 12467 UnresolvedReductions, RD)) 12468 return nullptr; 12469 12470 return OMPReductionClause::Create( 12471 Context, StartLoc, LParenLoc, ColonLoc, EndLoc, RD.Vars, 12472 ReductionIdScopeSpec.getWithLocInContext(Context), ReductionId, 12473 RD.Privates, RD.LHSs, RD.RHSs, RD.ReductionOps, 12474 buildPreInits(Context, RD.ExprCaptures), 12475 buildPostUpdate(*this, RD.ExprPostUpdates)); 12476 } 12477 12478 OMPClause *Sema::ActOnOpenMPTaskReductionClause( 12479 ArrayRef<Expr *> VarList, SourceLocation StartLoc, SourceLocation LParenLoc, 12480 SourceLocation ColonLoc, SourceLocation EndLoc, 12481 CXXScopeSpec &ReductionIdScopeSpec, const DeclarationNameInfo &ReductionId, 12482 ArrayRef<Expr *> UnresolvedReductions) { 12483 ReductionData RD(VarList.size()); 12484 if (actOnOMPReductionKindClause(*this, DSAStack, OMPC_task_reduction, VarList, 12485 StartLoc, LParenLoc, ColonLoc, EndLoc, 12486 ReductionIdScopeSpec, ReductionId, 12487 UnresolvedReductions, RD)) 12488 return nullptr; 12489 12490 return OMPTaskReductionClause::Create( 12491 Context, StartLoc, LParenLoc, ColonLoc, EndLoc, RD.Vars, 12492 ReductionIdScopeSpec.getWithLocInContext(Context), ReductionId, 12493 RD.Privates, RD.LHSs, RD.RHSs, RD.ReductionOps, 12494 buildPreInits(Context, RD.ExprCaptures), 12495 buildPostUpdate(*this, RD.ExprPostUpdates)); 12496 } 12497 12498 OMPClause *Sema::ActOnOpenMPInReductionClause( 12499 ArrayRef<Expr *> VarList, SourceLocation StartLoc, SourceLocation LParenLoc, 12500 SourceLocation ColonLoc, SourceLocation EndLoc, 12501 CXXScopeSpec &ReductionIdScopeSpec, const DeclarationNameInfo &ReductionId, 12502 ArrayRef<Expr *> UnresolvedReductions) { 12503 ReductionData RD(VarList.size()); 12504 if (actOnOMPReductionKindClause(*this, DSAStack, OMPC_in_reduction, VarList, 12505 StartLoc, LParenLoc, ColonLoc, EndLoc, 12506 ReductionIdScopeSpec, ReductionId, 12507 UnresolvedReductions, RD)) 12508 return nullptr; 12509 12510 return OMPInReductionClause::Create( 12511 Context, StartLoc, LParenLoc, ColonLoc, EndLoc, RD.Vars, 12512 ReductionIdScopeSpec.getWithLocInContext(Context), ReductionId, 12513 RD.Privates, RD.LHSs, RD.RHSs, RD.ReductionOps, RD.TaskgroupDescriptors, 12514 buildPreInits(Context, RD.ExprCaptures), 12515 buildPostUpdate(*this, RD.ExprPostUpdates)); 12516 } 12517 12518 bool Sema::CheckOpenMPLinearModifier(OpenMPLinearClauseKind LinKind, 12519 SourceLocation LinLoc) { 12520 if ((!LangOpts.CPlusPlus && LinKind != OMPC_LINEAR_val) || 12521 LinKind == OMPC_LINEAR_unknown) { 12522 Diag(LinLoc, diag::err_omp_wrong_linear_modifier) << LangOpts.CPlusPlus; 12523 return true; 12524 } 12525 return false; 12526 } 12527 12528 bool Sema::CheckOpenMPLinearDecl(const ValueDecl *D, SourceLocation ELoc, 12529 OpenMPLinearClauseKind LinKind, 12530 QualType Type) { 12531 const auto *VD = dyn_cast_or_null<VarDecl>(D); 12532 // A variable must not have an incomplete type or a reference type. 12533 if (RequireCompleteType(ELoc, Type, diag::err_omp_linear_incomplete_type)) 12534 return true; 12535 if ((LinKind == OMPC_LINEAR_uval || LinKind == OMPC_LINEAR_ref) && 12536 !Type->isReferenceType()) { 12537 Diag(ELoc, diag::err_omp_wrong_linear_modifier_non_reference) 12538 << Type << getOpenMPSimpleClauseTypeName(OMPC_linear, LinKind); 12539 return true; 12540 } 12541 Type = Type.getNonReferenceType(); 12542 12543 // OpenMP 5.0 [2.19.3, List Item Privatization, Restrictions] 12544 // A variable that is privatized must not have a const-qualified type 12545 // unless it is of class type with a mutable member. This restriction does 12546 // not apply to the firstprivate clause. 12547 if (rejectConstNotMutableType(*this, D, Type, OMPC_linear, ELoc)) 12548 return true; 12549 12550 // A list item must be of integral or pointer type. 12551 Type = Type.getUnqualifiedType().getCanonicalType(); 12552 const auto *Ty = Type.getTypePtrOrNull(); 12553 if (!Ty || (!Ty->isDependentType() && !Ty->isIntegralType(Context) && 12554 !Ty->isPointerType())) { 12555 Diag(ELoc, diag::err_omp_linear_expected_int_or_ptr) << Type; 12556 if (D) { 12557 bool IsDecl = 12558 !VD || 12559 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly; 12560 Diag(D->getLocation(), 12561 IsDecl ? diag::note_previous_decl : diag::note_defined_here) 12562 << D; 12563 } 12564 return true; 12565 } 12566 return false; 12567 } 12568 12569 OMPClause *Sema::ActOnOpenMPLinearClause( 12570 ArrayRef<Expr *> VarList, Expr *Step, SourceLocation StartLoc, 12571 SourceLocation LParenLoc, OpenMPLinearClauseKind LinKind, 12572 SourceLocation LinLoc, SourceLocation ColonLoc, SourceLocation EndLoc) { 12573 SmallVector<Expr *, 8> Vars; 12574 SmallVector<Expr *, 8> Privates; 12575 SmallVector<Expr *, 8> Inits; 12576 SmallVector<Decl *, 4> ExprCaptures; 12577 SmallVector<Expr *, 4> ExprPostUpdates; 12578 if (CheckOpenMPLinearModifier(LinKind, LinLoc)) 12579 LinKind = OMPC_LINEAR_val; 12580 for (Expr *RefExpr : VarList) { 12581 assert(RefExpr && "NULL expr in OpenMP linear clause."); 12582 SourceLocation ELoc; 12583 SourceRange ERange; 12584 Expr *SimpleRefExpr = RefExpr; 12585 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange); 12586 if (Res.second) { 12587 // It will be analyzed later. 12588 Vars.push_back(RefExpr); 12589 Privates.push_back(nullptr); 12590 Inits.push_back(nullptr); 12591 } 12592 ValueDecl *D = Res.first; 12593 if (!D) 12594 continue; 12595 12596 QualType Type = D->getType(); 12597 auto *VD = dyn_cast<VarDecl>(D); 12598 12599 // OpenMP [2.14.3.7, linear clause] 12600 // A list-item cannot appear in more than one linear clause. 12601 // A list-item that appears in a linear clause cannot appear in any 12602 // other data-sharing attribute clause. 12603 DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, /*FromParent=*/false); 12604 if (DVar.RefExpr) { 12605 Diag(ELoc, diag::err_omp_wrong_dsa) << getOpenMPClauseName(DVar.CKind) 12606 << getOpenMPClauseName(OMPC_linear); 12607 reportOriginalDsa(*this, DSAStack, D, DVar); 12608 continue; 12609 } 12610 12611 if (CheckOpenMPLinearDecl(D, ELoc, LinKind, Type)) 12612 continue; 12613 Type = Type.getNonReferenceType().getUnqualifiedType().getCanonicalType(); 12614 12615 // Build private copy of original var. 12616 VarDecl *Private = 12617 buildVarDecl(*this, ELoc, Type, D->getName(), 12618 D->hasAttrs() ? &D->getAttrs() : nullptr, 12619 VD ? cast<DeclRefExpr>(SimpleRefExpr) : nullptr); 12620 DeclRefExpr *PrivateRef = buildDeclRefExpr(*this, Private, Type, ELoc); 12621 // Build var to save initial value. 12622 VarDecl *Init = buildVarDecl(*this, ELoc, Type, ".linear.start"); 12623 Expr *InitExpr; 12624 DeclRefExpr *Ref = nullptr; 12625 if (!VD && !CurContext->isDependentContext()) { 12626 Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/false); 12627 if (!isOpenMPCapturedDecl(D)) { 12628 ExprCaptures.push_back(Ref->getDecl()); 12629 if (Ref->getDecl()->hasAttr<OMPCaptureNoInitAttr>()) { 12630 ExprResult RefRes = DefaultLvalueConversion(Ref); 12631 if (!RefRes.isUsable()) 12632 continue; 12633 ExprResult PostUpdateRes = 12634 BuildBinOp(DSAStack->getCurScope(), ELoc, BO_Assign, 12635 SimpleRefExpr, RefRes.get()); 12636 if (!PostUpdateRes.isUsable()) 12637 continue; 12638 ExprPostUpdates.push_back( 12639 IgnoredValueConversions(PostUpdateRes.get()).get()); 12640 } 12641 } 12642 } 12643 if (LinKind == OMPC_LINEAR_uval) 12644 InitExpr = VD ? VD->getInit() : SimpleRefExpr; 12645 else 12646 InitExpr = VD ? SimpleRefExpr : Ref; 12647 AddInitializerToDecl(Init, DefaultLvalueConversion(InitExpr).get(), 12648 /*DirectInit=*/false); 12649 DeclRefExpr *InitRef = buildDeclRefExpr(*this, Init, Type, ELoc); 12650 12651 DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_linear, Ref); 12652 Vars.push_back((VD || CurContext->isDependentContext()) 12653 ? RefExpr->IgnoreParens() 12654 : Ref); 12655 Privates.push_back(PrivateRef); 12656 Inits.push_back(InitRef); 12657 } 12658 12659 if (Vars.empty()) 12660 return nullptr; 12661 12662 Expr *StepExpr = Step; 12663 Expr *CalcStepExpr = nullptr; 12664 if (Step && !Step->isValueDependent() && !Step->isTypeDependent() && 12665 !Step->isInstantiationDependent() && 12666 !Step->containsUnexpandedParameterPack()) { 12667 SourceLocation StepLoc = Step->getBeginLoc(); 12668 ExprResult Val = PerformOpenMPImplicitIntegerConversion(StepLoc, Step); 12669 if (Val.isInvalid()) 12670 return nullptr; 12671 StepExpr = Val.get(); 12672 12673 // Build var to save the step value. 12674 VarDecl *SaveVar = 12675 buildVarDecl(*this, StepLoc, StepExpr->getType(), ".linear.step"); 12676 ExprResult SaveRef = 12677 buildDeclRefExpr(*this, SaveVar, StepExpr->getType(), StepLoc); 12678 ExprResult CalcStep = 12679 BuildBinOp(CurScope, StepLoc, BO_Assign, SaveRef.get(), StepExpr); 12680 CalcStep = ActOnFinishFullExpr(CalcStep.get(), /*DiscardedValue*/ false); 12681 12682 // Warn about zero linear step (it would be probably better specified as 12683 // making corresponding variables 'const'). 12684 llvm::APSInt Result; 12685 bool IsConstant = StepExpr->isIntegerConstantExpr(Result, Context); 12686 if (IsConstant && !Result.isNegative() && !Result.isStrictlyPositive()) 12687 Diag(StepLoc, diag::warn_omp_linear_step_zero) << Vars[0] 12688 << (Vars.size() > 1); 12689 if (!IsConstant && CalcStep.isUsable()) { 12690 // Calculate the step beforehand instead of doing this on each iteration. 12691 // (This is not used if the number of iterations may be kfold-ed). 12692 CalcStepExpr = CalcStep.get(); 12693 } 12694 } 12695 12696 return OMPLinearClause::Create(Context, StartLoc, LParenLoc, LinKind, LinLoc, 12697 ColonLoc, EndLoc, Vars, Privates, Inits, 12698 StepExpr, CalcStepExpr, 12699 buildPreInits(Context, ExprCaptures), 12700 buildPostUpdate(*this, ExprPostUpdates)); 12701 } 12702 12703 static bool FinishOpenMPLinearClause(OMPLinearClause &Clause, DeclRefExpr *IV, 12704 Expr *NumIterations, Sema &SemaRef, 12705 Scope *S, DSAStackTy *Stack) { 12706 // Walk the vars and build update/final expressions for the CodeGen. 12707 SmallVector<Expr *, 8> Updates; 12708 SmallVector<Expr *, 8> Finals; 12709 Expr *Step = Clause.getStep(); 12710 Expr *CalcStep = Clause.getCalcStep(); 12711 // OpenMP [2.14.3.7, linear clause] 12712 // If linear-step is not specified it is assumed to be 1. 12713 if (!Step) 12714 Step = SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get(); 12715 else if (CalcStep) 12716 Step = cast<BinaryOperator>(CalcStep)->getLHS(); 12717 bool HasErrors = false; 12718 auto CurInit = Clause.inits().begin(); 12719 auto CurPrivate = Clause.privates().begin(); 12720 OpenMPLinearClauseKind LinKind = Clause.getModifier(); 12721 for (Expr *RefExpr : Clause.varlists()) { 12722 SourceLocation ELoc; 12723 SourceRange ERange; 12724 Expr *SimpleRefExpr = RefExpr; 12725 auto Res = getPrivateItem(SemaRef, SimpleRefExpr, ELoc, ERange); 12726 ValueDecl *D = Res.first; 12727 if (Res.second || !D) { 12728 Updates.push_back(nullptr); 12729 Finals.push_back(nullptr); 12730 HasErrors = true; 12731 continue; 12732 } 12733 auto &&Info = Stack->isLoopControlVariable(D); 12734 // OpenMP [2.15.11, distribute simd Construct] 12735 // A list item may not appear in a linear clause, unless it is the loop 12736 // iteration variable. 12737 if (isOpenMPDistributeDirective(Stack->getCurrentDirective()) && 12738 isOpenMPSimdDirective(Stack->getCurrentDirective()) && !Info.first) { 12739 SemaRef.Diag(ELoc, 12740 diag::err_omp_linear_distribute_var_non_loop_iteration); 12741 Updates.push_back(nullptr); 12742 Finals.push_back(nullptr); 12743 HasErrors = true; 12744 continue; 12745 } 12746 Expr *InitExpr = *CurInit; 12747 12748 // Build privatized reference to the current linear var. 12749 auto *DE = cast<DeclRefExpr>(SimpleRefExpr); 12750 Expr *CapturedRef; 12751 if (LinKind == OMPC_LINEAR_uval) 12752 CapturedRef = cast<VarDecl>(DE->getDecl())->getInit(); 12753 else 12754 CapturedRef = 12755 buildDeclRefExpr(SemaRef, cast<VarDecl>(DE->getDecl()), 12756 DE->getType().getUnqualifiedType(), DE->getExprLoc(), 12757 /*RefersToCapture=*/true); 12758 12759 // Build update: Var = InitExpr + IV * Step 12760 ExprResult Update; 12761 if (!Info.first) 12762 Update = 12763 buildCounterUpdate(SemaRef, S, RefExpr->getExprLoc(), *CurPrivate, 12764 InitExpr, IV, Step, /* Subtract */ false); 12765 else 12766 Update = *CurPrivate; 12767 Update = SemaRef.ActOnFinishFullExpr(Update.get(), DE->getBeginLoc(), 12768 /*DiscardedValue*/ false); 12769 12770 // Build final: Var = InitExpr + NumIterations * Step 12771 ExprResult Final; 12772 if (!Info.first) 12773 Final = 12774 buildCounterUpdate(SemaRef, S, RefExpr->getExprLoc(), CapturedRef, 12775 InitExpr, NumIterations, Step, /*Subtract=*/false); 12776 else 12777 Final = *CurPrivate; 12778 Final = SemaRef.ActOnFinishFullExpr(Final.get(), DE->getBeginLoc(), 12779 /*DiscardedValue*/ false); 12780 12781 if (!Update.isUsable() || !Final.isUsable()) { 12782 Updates.push_back(nullptr); 12783 Finals.push_back(nullptr); 12784 HasErrors = true; 12785 } else { 12786 Updates.push_back(Update.get()); 12787 Finals.push_back(Final.get()); 12788 } 12789 ++CurInit; 12790 ++CurPrivate; 12791 } 12792 Clause.setUpdates(Updates); 12793 Clause.setFinals(Finals); 12794 return HasErrors; 12795 } 12796 12797 OMPClause *Sema::ActOnOpenMPAlignedClause( 12798 ArrayRef<Expr *> VarList, Expr *Alignment, SourceLocation StartLoc, 12799 SourceLocation LParenLoc, SourceLocation ColonLoc, SourceLocation EndLoc) { 12800 SmallVector<Expr *, 8> Vars; 12801 for (Expr *RefExpr : VarList) { 12802 assert(RefExpr && "NULL expr in OpenMP linear clause."); 12803 SourceLocation ELoc; 12804 SourceRange ERange; 12805 Expr *SimpleRefExpr = RefExpr; 12806 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange); 12807 if (Res.second) { 12808 // It will be analyzed later. 12809 Vars.push_back(RefExpr); 12810 } 12811 ValueDecl *D = Res.first; 12812 if (!D) 12813 continue; 12814 12815 QualType QType = D->getType(); 12816 auto *VD = dyn_cast<VarDecl>(D); 12817 12818 // OpenMP [2.8.1, simd construct, Restrictions] 12819 // The type of list items appearing in the aligned clause must be 12820 // array, pointer, reference to array, or reference to pointer. 12821 QType = QType.getNonReferenceType().getUnqualifiedType().getCanonicalType(); 12822 const Type *Ty = QType.getTypePtrOrNull(); 12823 if (!Ty || (!Ty->isArrayType() && !Ty->isPointerType())) { 12824 Diag(ELoc, diag::err_omp_aligned_expected_array_or_ptr) 12825 << QType << getLangOpts().CPlusPlus << ERange; 12826 bool IsDecl = 12827 !VD || 12828 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly; 12829 Diag(D->getLocation(), 12830 IsDecl ? diag::note_previous_decl : diag::note_defined_here) 12831 << D; 12832 continue; 12833 } 12834 12835 // OpenMP [2.8.1, simd construct, Restrictions] 12836 // A list-item cannot appear in more than one aligned clause. 12837 if (const Expr *PrevRef = DSAStack->addUniqueAligned(D, SimpleRefExpr)) { 12838 Diag(ELoc, diag::err_omp_aligned_twice) << 0 << ERange; 12839 Diag(PrevRef->getExprLoc(), diag::note_omp_explicit_dsa) 12840 << getOpenMPClauseName(OMPC_aligned); 12841 continue; 12842 } 12843 12844 DeclRefExpr *Ref = nullptr; 12845 if (!VD && isOpenMPCapturedDecl(D)) 12846 Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/true); 12847 Vars.push_back(DefaultFunctionArrayConversion( 12848 (VD || !Ref) ? RefExpr->IgnoreParens() : Ref) 12849 .get()); 12850 } 12851 12852 // OpenMP [2.8.1, simd construct, Description] 12853 // The parameter of the aligned clause, alignment, must be a constant 12854 // positive integer expression. 12855 // If no optional parameter is specified, implementation-defined default 12856 // alignments for SIMD instructions on the target platforms are assumed. 12857 if (Alignment != nullptr) { 12858 ExprResult AlignResult = 12859 VerifyPositiveIntegerConstantInClause(Alignment, OMPC_aligned); 12860 if (AlignResult.isInvalid()) 12861 return nullptr; 12862 Alignment = AlignResult.get(); 12863 } 12864 if (Vars.empty()) 12865 return nullptr; 12866 12867 return OMPAlignedClause::Create(Context, StartLoc, LParenLoc, ColonLoc, 12868 EndLoc, Vars, Alignment); 12869 } 12870 12871 OMPClause *Sema::ActOnOpenMPCopyinClause(ArrayRef<Expr *> VarList, 12872 SourceLocation StartLoc, 12873 SourceLocation LParenLoc, 12874 SourceLocation EndLoc) { 12875 SmallVector<Expr *, 8> Vars; 12876 SmallVector<Expr *, 8> SrcExprs; 12877 SmallVector<Expr *, 8> DstExprs; 12878 SmallVector<Expr *, 8> AssignmentOps; 12879 for (Expr *RefExpr : VarList) { 12880 assert(RefExpr && "NULL expr in OpenMP copyin clause."); 12881 if (isa<DependentScopeDeclRefExpr>(RefExpr)) { 12882 // It will be analyzed later. 12883 Vars.push_back(RefExpr); 12884 SrcExprs.push_back(nullptr); 12885 DstExprs.push_back(nullptr); 12886 AssignmentOps.push_back(nullptr); 12887 continue; 12888 } 12889 12890 SourceLocation ELoc = RefExpr->getExprLoc(); 12891 // OpenMP [2.1, C/C++] 12892 // A list item is a variable name. 12893 // OpenMP [2.14.4.1, Restrictions, p.1] 12894 // A list item that appears in a copyin clause must be threadprivate. 12895 auto *DE = dyn_cast<DeclRefExpr>(RefExpr); 12896 if (!DE || !isa<VarDecl>(DE->getDecl())) { 12897 Diag(ELoc, diag::err_omp_expected_var_name_member_expr) 12898 << 0 << RefExpr->getSourceRange(); 12899 continue; 12900 } 12901 12902 Decl *D = DE->getDecl(); 12903 auto *VD = cast<VarDecl>(D); 12904 12905 QualType Type = VD->getType(); 12906 if (Type->isDependentType() || Type->isInstantiationDependentType()) { 12907 // It will be analyzed later. 12908 Vars.push_back(DE); 12909 SrcExprs.push_back(nullptr); 12910 DstExprs.push_back(nullptr); 12911 AssignmentOps.push_back(nullptr); 12912 continue; 12913 } 12914 12915 // OpenMP [2.14.4.1, Restrictions, C/C++, p.1] 12916 // A list item that appears in a copyin clause must be threadprivate. 12917 if (!DSAStack->isThreadPrivate(VD)) { 12918 Diag(ELoc, diag::err_omp_required_access) 12919 << getOpenMPClauseName(OMPC_copyin) 12920 << getOpenMPDirectiveName(OMPD_threadprivate); 12921 continue; 12922 } 12923 12924 // OpenMP [2.14.4.1, Restrictions, C/C++, p.2] 12925 // A variable of class type (or array thereof) that appears in a 12926 // copyin clause requires an accessible, unambiguous copy assignment 12927 // operator for the class type. 12928 QualType ElemType = Context.getBaseElementType(Type).getNonReferenceType(); 12929 VarDecl *SrcVD = 12930 buildVarDecl(*this, DE->getBeginLoc(), ElemType.getUnqualifiedType(), 12931 ".copyin.src", VD->hasAttrs() ? &VD->getAttrs() : nullptr); 12932 DeclRefExpr *PseudoSrcExpr = buildDeclRefExpr( 12933 *this, SrcVD, ElemType.getUnqualifiedType(), DE->getExprLoc()); 12934 VarDecl *DstVD = 12935 buildVarDecl(*this, DE->getBeginLoc(), ElemType, ".copyin.dst", 12936 VD->hasAttrs() ? &VD->getAttrs() : nullptr); 12937 DeclRefExpr *PseudoDstExpr = 12938 buildDeclRefExpr(*this, DstVD, ElemType, DE->getExprLoc()); 12939 // For arrays generate assignment operation for single element and replace 12940 // it by the original array element in CodeGen. 12941 ExprResult AssignmentOp = 12942 BuildBinOp(/*S=*/nullptr, DE->getExprLoc(), BO_Assign, PseudoDstExpr, 12943 PseudoSrcExpr); 12944 if (AssignmentOp.isInvalid()) 12945 continue; 12946 AssignmentOp = ActOnFinishFullExpr(AssignmentOp.get(), DE->getExprLoc(), 12947 /*DiscardedValue*/ false); 12948 if (AssignmentOp.isInvalid()) 12949 continue; 12950 12951 DSAStack->addDSA(VD, DE, OMPC_copyin); 12952 Vars.push_back(DE); 12953 SrcExprs.push_back(PseudoSrcExpr); 12954 DstExprs.push_back(PseudoDstExpr); 12955 AssignmentOps.push_back(AssignmentOp.get()); 12956 } 12957 12958 if (Vars.empty()) 12959 return nullptr; 12960 12961 return OMPCopyinClause::Create(Context, StartLoc, LParenLoc, EndLoc, Vars, 12962 SrcExprs, DstExprs, AssignmentOps); 12963 } 12964 12965 OMPClause *Sema::ActOnOpenMPCopyprivateClause(ArrayRef<Expr *> VarList, 12966 SourceLocation StartLoc, 12967 SourceLocation LParenLoc, 12968 SourceLocation EndLoc) { 12969 SmallVector<Expr *, 8> Vars; 12970 SmallVector<Expr *, 8> SrcExprs; 12971 SmallVector<Expr *, 8> DstExprs; 12972 SmallVector<Expr *, 8> AssignmentOps; 12973 for (Expr *RefExpr : VarList) { 12974 assert(RefExpr && "NULL expr in OpenMP linear clause."); 12975 SourceLocation ELoc; 12976 SourceRange ERange; 12977 Expr *SimpleRefExpr = RefExpr; 12978 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange); 12979 if (Res.second) { 12980 // It will be analyzed later. 12981 Vars.push_back(RefExpr); 12982 SrcExprs.push_back(nullptr); 12983 DstExprs.push_back(nullptr); 12984 AssignmentOps.push_back(nullptr); 12985 } 12986 ValueDecl *D = Res.first; 12987 if (!D) 12988 continue; 12989 12990 QualType Type = D->getType(); 12991 auto *VD = dyn_cast<VarDecl>(D); 12992 12993 // OpenMP [2.14.4.2, Restrictions, p.2] 12994 // A list item that appears in a copyprivate clause may not appear in a 12995 // private or firstprivate clause on the single construct. 12996 if (!VD || !DSAStack->isThreadPrivate(VD)) { 12997 DSAStackTy::DSAVarData DVar = 12998 DSAStack->getTopDSA(D, /*FromParent=*/false); 12999 if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_copyprivate && 13000 DVar.RefExpr) { 13001 Diag(ELoc, diag::err_omp_wrong_dsa) 13002 << getOpenMPClauseName(DVar.CKind) 13003 << getOpenMPClauseName(OMPC_copyprivate); 13004 reportOriginalDsa(*this, DSAStack, D, DVar); 13005 continue; 13006 } 13007 13008 // OpenMP [2.11.4.2, Restrictions, p.1] 13009 // All list items that appear in a copyprivate clause must be either 13010 // threadprivate or private in the enclosing context. 13011 if (DVar.CKind == OMPC_unknown) { 13012 DVar = DSAStack->getImplicitDSA(D, false); 13013 if (DVar.CKind == OMPC_shared) { 13014 Diag(ELoc, diag::err_omp_required_access) 13015 << getOpenMPClauseName(OMPC_copyprivate) 13016 << "threadprivate or private in the enclosing context"; 13017 reportOriginalDsa(*this, DSAStack, D, DVar); 13018 continue; 13019 } 13020 } 13021 } 13022 13023 // Variably modified types are not supported. 13024 if (!Type->isAnyPointerType() && Type->isVariablyModifiedType()) { 13025 Diag(ELoc, diag::err_omp_variably_modified_type_not_supported) 13026 << getOpenMPClauseName(OMPC_copyprivate) << Type 13027 << getOpenMPDirectiveName(DSAStack->getCurrentDirective()); 13028 bool IsDecl = 13029 !VD || 13030 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly; 13031 Diag(D->getLocation(), 13032 IsDecl ? diag::note_previous_decl : diag::note_defined_here) 13033 << D; 13034 continue; 13035 } 13036 13037 // OpenMP [2.14.4.1, Restrictions, C/C++, p.2] 13038 // A variable of class type (or array thereof) that appears in a 13039 // copyin clause requires an accessible, unambiguous copy assignment 13040 // operator for the class type. 13041 Type = Context.getBaseElementType(Type.getNonReferenceType()) 13042 .getUnqualifiedType(); 13043 VarDecl *SrcVD = 13044 buildVarDecl(*this, RefExpr->getBeginLoc(), Type, ".copyprivate.src", 13045 D->hasAttrs() ? &D->getAttrs() : nullptr); 13046 DeclRefExpr *PseudoSrcExpr = buildDeclRefExpr(*this, SrcVD, Type, ELoc); 13047 VarDecl *DstVD = 13048 buildVarDecl(*this, RefExpr->getBeginLoc(), Type, ".copyprivate.dst", 13049 D->hasAttrs() ? &D->getAttrs() : nullptr); 13050 DeclRefExpr *PseudoDstExpr = buildDeclRefExpr(*this, DstVD, Type, ELoc); 13051 ExprResult AssignmentOp = BuildBinOp( 13052 DSAStack->getCurScope(), ELoc, BO_Assign, PseudoDstExpr, PseudoSrcExpr); 13053 if (AssignmentOp.isInvalid()) 13054 continue; 13055 AssignmentOp = 13056 ActOnFinishFullExpr(AssignmentOp.get(), ELoc, /*DiscardedValue*/ false); 13057 if (AssignmentOp.isInvalid()) 13058 continue; 13059 13060 // No need to mark vars as copyprivate, they are already threadprivate or 13061 // implicitly private. 13062 assert(VD || isOpenMPCapturedDecl(D)); 13063 Vars.push_back( 13064 VD ? RefExpr->IgnoreParens() 13065 : buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/false)); 13066 SrcExprs.push_back(PseudoSrcExpr); 13067 DstExprs.push_back(PseudoDstExpr); 13068 AssignmentOps.push_back(AssignmentOp.get()); 13069 } 13070 13071 if (Vars.empty()) 13072 return nullptr; 13073 13074 return OMPCopyprivateClause::Create(Context, StartLoc, LParenLoc, EndLoc, 13075 Vars, SrcExprs, DstExprs, AssignmentOps); 13076 } 13077 13078 OMPClause *Sema::ActOnOpenMPFlushClause(ArrayRef<Expr *> VarList, 13079 SourceLocation StartLoc, 13080 SourceLocation LParenLoc, 13081 SourceLocation EndLoc) { 13082 if (VarList.empty()) 13083 return nullptr; 13084 13085 return OMPFlushClause::Create(Context, StartLoc, LParenLoc, EndLoc, VarList); 13086 } 13087 13088 OMPClause * 13089 Sema::ActOnOpenMPDependClause(OpenMPDependClauseKind DepKind, 13090 SourceLocation DepLoc, SourceLocation ColonLoc, 13091 ArrayRef<Expr *> VarList, SourceLocation StartLoc, 13092 SourceLocation LParenLoc, SourceLocation EndLoc) { 13093 if (DSAStack->getCurrentDirective() == OMPD_ordered && 13094 DepKind != OMPC_DEPEND_source && DepKind != OMPC_DEPEND_sink) { 13095 Diag(DepLoc, diag::err_omp_unexpected_clause_value) 13096 << "'source' or 'sink'" << getOpenMPClauseName(OMPC_depend); 13097 return nullptr; 13098 } 13099 if (DSAStack->getCurrentDirective() != OMPD_ordered && 13100 (DepKind == OMPC_DEPEND_unknown || DepKind == OMPC_DEPEND_source || 13101 DepKind == OMPC_DEPEND_sink)) { 13102 unsigned Except[] = {OMPC_DEPEND_source, OMPC_DEPEND_sink}; 13103 Diag(DepLoc, diag::err_omp_unexpected_clause_value) 13104 << getListOfPossibleValues(OMPC_depend, /*First=*/0, 13105 /*Last=*/OMPC_DEPEND_unknown, Except) 13106 << getOpenMPClauseName(OMPC_depend); 13107 return nullptr; 13108 } 13109 SmallVector<Expr *, 8> Vars; 13110 DSAStackTy::OperatorOffsetTy OpsOffs; 13111 llvm::APSInt DepCounter(/*BitWidth=*/32); 13112 llvm::APSInt TotalDepCount(/*BitWidth=*/32); 13113 if (DepKind == OMPC_DEPEND_sink || DepKind == OMPC_DEPEND_source) { 13114 if (const Expr *OrderedCountExpr = 13115 DSAStack->getParentOrderedRegionParam().first) { 13116 TotalDepCount = OrderedCountExpr->EvaluateKnownConstInt(Context); 13117 TotalDepCount.setIsUnsigned(/*Val=*/true); 13118 } 13119 } 13120 for (Expr *RefExpr : VarList) { 13121 assert(RefExpr && "NULL expr in OpenMP shared clause."); 13122 if (isa<DependentScopeDeclRefExpr>(RefExpr)) { 13123 // It will be analyzed later. 13124 Vars.push_back(RefExpr); 13125 continue; 13126 } 13127 13128 SourceLocation ELoc = RefExpr->getExprLoc(); 13129 Expr *SimpleExpr = RefExpr->IgnoreParenCasts(); 13130 if (DepKind == OMPC_DEPEND_sink) { 13131 if (DSAStack->getParentOrderedRegionParam().first && 13132 DepCounter >= TotalDepCount) { 13133 Diag(ELoc, diag::err_omp_depend_sink_unexpected_expr); 13134 continue; 13135 } 13136 ++DepCounter; 13137 // OpenMP [2.13.9, Summary] 13138 // depend(dependence-type : vec), where dependence-type is: 13139 // 'sink' and where vec is the iteration vector, which has the form: 13140 // x1 [+- d1], x2 [+- d2 ], . . . , xn [+- dn] 13141 // where n is the value specified by the ordered clause in the loop 13142 // directive, xi denotes the loop iteration variable of the i-th nested 13143 // loop associated with the loop directive, and di is a constant 13144 // non-negative integer. 13145 if (CurContext->isDependentContext()) { 13146 // It will be analyzed later. 13147 Vars.push_back(RefExpr); 13148 continue; 13149 } 13150 SimpleExpr = SimpleExpr->IgnoreImplicit(); 13151 OverloadedOperatorKind OOK = OO_None; 13152 SourceLocation OOLoc; 13153 Expr *LHS = SimpleExpr; 13154 Expr *RHS = nullptr; 13155 if (auto *BO = dyn_cast<BinaryOperator>(SimpleExpr)) { 13156 OOK = BinaryOperator::getOverloadedOperator(BO->getOpcode()); 13157 OOLoc = BO->getOperatorLoc(); 13158 LHS = BO->getLHS()->IgnoreParenImpCasts(); 13159 RHS = BO->getRHS()->IgnoreParenImpCasts(); 13160 } else if (auto *OCE = dyn_cast<CXXOperatorCallExpr>(SimpleExpr)) { 13161 OOK = OCE->getOperator(); 13162 OOLoc = OCE->getOperatorLoc(); 13163 LHS = OCE->getArg(/*Arg=*/0)->IgnoreParenImpCasts(); 13164 RHS = OCE->getArg(/*Arg=*/1)->IgnoreParenImpCasts(); 13165 } else if (auto *MCE = dyn_cast<CXXMemberCallExpr>(SimpleExpr)) { 13166 OOK = MCE->getMethodDecl() 13167 ->getNameInfo() 13168 .getName() 13169 .getCXXOverloadedOperator(); 13170 OOLoc = MCE->getCallee()->getExprLoc(); 13171 LHS = MCE->getImplicitObjectArgument()->IgnoreParenImpCasts(); 13172 RHS = MCE->getArg(/*Arg=*/0)->IgnoreParenImpCasts(); 13173 } 13174 SourceLocation ELoc; 13175 SourceRange ERange; 13176 auto Res = getPrivateItem(*this, LHS, ELoc, ERange); 13177 if (Res.second) { 13178 // It will be analyzed later. 13179 Vars.push_back(RefExpr); 13180 } 13181 ValueDecl *D = Res.first; 13182 if (!D) 13183 continue; 13184 13185 if (OOK != OO_Plus && OOK != OO_Minus && (RHS || OOK != OO_None)) { 13186 Diag(OOLoc, diag::err_omp_depend_sink_expected_plus_minus); 13187 continue; 13188 } 13189 if (RHS) { 13190 ExprResult RHSRes = VerifyPositiveIntegerConstantInClause( 13191 RHS, OMPC_depend, /*StrictlyPositive=*/false); 13192 if (RHSRes.isInvalid()) 13193 continue; 13194 } 13195 if (!CurContext->isDependentContext() && 13196 DSAStack->getParentOrderedRegionParam().first && 13197 DepCounter != DSAStack->isParentLoopControlVariable(D).first) { 13198 const ValueDecl *VD = 13199 DSAStack->getParentLoopControlVariable(DepCounter.getZExtValue()); 13200 if (VD) 13201 Diag(ELoc, diag::err_omp_depend_sink_expected_loop_iteration) 13202 << 1 << VD; 13203 else 13204 Diag(ELoc, diag::err_omp_depend_sink_expected_loop_iteration) << 0; 13205 continue; 13206 } 13207 OpsOffs.emplace_back(RHS, OOK); 13208 } else { 13209 auto *ASE = dyn_cast<ArraySubscriptExpr>(SimpleExpr); 13210 if (!RefExpr->IgnoreParenImpCasts()->isLValue() || 13211 (ASE && 13212 !ASE->getBase()->getType().getNonReferenceType()->isPointerType() && 13213 !ASE->getBase()->getType().getNonReferenceType()->isArrayType())) { 13214 Diag(ELoc, diag::err_omp_expected_addressable_lvalue_or_array_item) 13215 << RefExpr->getSourceRange(); 13216 continue; 13217 } 13218 bool Suppress = getDiagnostics().getSuppressAllDiagnostics(); 13219 getDiagnostics().setSuppressAllDiagnostics(/*Val=*/true); 13220 ExprResult Res = 13221 CreateBuiltinUnaryOp(ELoc, UO_AddrOf, RefExpr->IgnoreParenImpCasts()); 13222 getDiagnostics().setSuppressAllDiagnostics(Suppress); 13223 if (!Res.isUsable() && !isa<OMPArraySectionExpr>(SimpleExpr)) { 13224 Diag(ELoc, diag::err_omp_expected_addressable_lvalue_or_array_item) 13225 << RefExpr->getSourceRange(); 13226 continue; 13227 } 13228 } 13229 Vars.push_back(RefExpr->IgnoreParenImpCasts()); 13230 } 13231 13232 if (!CurContext->isDependentContext() && DepKind == OMPC_DEPEND_sink && 13233 TotalDepCount > VarList.size() && 13234 DSAStack->getParentOrderedRegionParam().first && 13235 DSAStack->getParentLoopControlVariable(VarList.size() + 1)) { 13236 Diag(EndLoc, diag::err_omp_depend_sink_expected_loop_iteration) 13237 << 1 << DSAStack->getParentLoopControlVariable(VarList.size() + 1); 13238 } 13239 if (DepKind != OMPC_DEPEND_source && DepKind != OMPC_DEPEND_sink && 13240 Vars.empty()) 13241 return nullptr; 13242 13243 auto *C = OMPDependClause::Create(Context, StartLoc, LParenLoc, EndLoc, 13244 DepKind, DepLoc, ColonLoc, Vars, 13245 TotalDepCount.getZExtValue()); 13246 if ((DepKind == OMPC_DEPEND_sink || DepKind == OMPC_DEPEND_source) && 13247 DSAStack->isParentOrderedRegion()) 13248 DSAStack->addDoacrossDependClause(C, OpsOffs); 13249 return C; 13250 } 13251 13252 OMPClause *Sema::ActOnOpenMPDeviceClause(Expr *Device, SourceLocation StartLoc, 13253 SourceLocation LParenLoc, 13254 SourceLocation EndLoc) { 13255 Expr *ValExpr = Device; 13256 Stmt *HelperValStmt = nullptr; 13257 13258 // OpenMP [2.9.1, Restrictions] 13259 // The device expression must evaluate to a non-negative integer value. 13260 if (!isNonNegativeIntegerValue(ValExpr, *this, OMPC_device, 13261 /*StrictlyPositive=*/false)) 13262 return nullptr; 13263 13264 OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective(); 13265 OpenMPDirectiveKind CaptureRegion = 13266 getOpenMPCaptureRegionForClause(DKind, OMPC_device); 13267 if (CaptureRegion != OMPD_unknown && !CurContext->isDependentContext()) { 13268 ValExpr = MakeFullExpr(ValExpr).get(); 13269 llvm::MapVector<const Expr *, DeclRefExpr *> Captures; 13270 ValExpr = tryBuildCapture(*this, ValExpr, Captures).get(); 13271 HelperValStmt = buildPreInits(Context, Captures); 13272 } 13273 13274 return new (Context) OMPDeviceClause(ValExpr, HelperValStmt, CaptureRegion, 13275 StartLoc, LParenLoc, EndLoc); 13276 } 13277 13278 static bool checkTypeMappable(SourceLocation SL, SourceRange SR, Sema &SemaRef, 13279 DSAStackTy *Stack, QualType QTy, 13280 bool FullCheck = true) { 13281 NamedDecl *ND; 13282 if (QTy->isIncompleteType(&ND)) { 13283 SemaRef.Diag(SL, diag::err_incomplete_type) << QTy << SR; 13284 return false; 13285 } 13286 if (FullCheck && !SemaRef.CurContext->isDependentContext() && 13287 !QTy.isTrivialType(SemaRef.Context)) 13288 SemaRef.Diag(SL, diag::warn_omp_non_trivial_type_mapped) << QTy << SR; 13289 return true; 13290 } 13291 13292 /// Return true if it can be proven that the provided array expression 13293 /// (array section or array subscript) does NOT specify the whole size of the 13294 /// array whose base type is \a BaseQTy. 13295 static bool checkArrayExpressionDoesNotReferToWholeSize(Sema &SemaRef, 13296 const Expr *E, 13297 QualType BaseQTy) { 13298 const auto *OASE = dyn_cast<OMPArraySectionExpr>(E); 13299 13300 // If this is an array subscript, it refers to the whole size if the size of 13301 // the dimension is constant and equals 1. Also, an array section assumes the 13302 // format of an array subscript if no colon is used. 13303 if (isa<ArraySubscriptExpr>(E) || (OASE && OASE->getColonLoc().isInvalid())) { 13304 if (const auto *ATy = dyn_cast<ConstantArrayType>(BaseQTy.getTypePtr())) 13305 return ATy->getSize().getSExtValue() != 1; 13306 // Size can't be evaluated statically. 13307 return false; 13308 } 13309 13310 assert(OASE && "Expecting array section if not an array subscript."); 13311 const Expr *LowerBound = OASE->getLowerBound(); 13312 const Expr *Length = OASE->getLength(); 13313 13314 // If there is a lower bound that does not evaluates to zero, we are not 13315 // covering the whole dimension. 13316 if (LowerBound) { 13317 Expr::EvalResult Result; 13318 if (!LowerBound->EvaluateAsInt(Result, SemaRef.getASTContext())) 13319 return false; // Can't get the integer value as a constant. 13320 13321 llvm::APSInt ConstLowerBound = Result.Val.getInt(); 13322 if (ConstLowerBound.getSExtValue()) 13323 return true; 13324 } 13325 13326 // If we don't have a length we covering the whole dimension. 13327 if (!Length) 13328 return false; 13329 13330 // If the base is a pointer, we don't have a way to get the size of the 13331 // pointee. 13332 if (BaseQTy->isPointerType()) 13333 return false; 13334 13335 // We can only check if the length is the same as the size of the dimension 13336 // if we have a constant array. 13337 const auto *CATy = dyn_cast<ConstantArrayType>(BaseQTy.getTypePtr()); 13338 if (!CATy) 13339 return false; 13340 13341 Expr::EvalResult Result; 13342 if (!Length->EvaluateAsInt(Result, SemaRef.getASTContext())) 13343 return false; // Can't get the integer value as a constant. 13344 13345 llvm::APSInt ConstLength = Result.Val.getInt(); 13346 return CATy->getSize().getSExtValue() != ConstLength.getSExtValue(); 13347 } 13348 13349 // Return true if it can be proven that the provided array expression (array 13350 // section or array subscript) does NOT specify a single element of the array 13351 // whose base type is \a BaseQTy. 13352 static bool checkArrayExpressionDoesNotReferToUnitySize(Sema &SemaRef, 13353 const Expr *E, 13354 QualType BaseQTy) { 13355 const auto *OASE = dyn_cast<OMPArraySectionExpr>(E); 13356 13357 // An array subscript always refer to a single element. Also, an array section 13358 // assumes the format of an array subscript if no colon is used. 13359 if (isa<ArraySubscriptExpr>(E) || (OASE && OASE->getColonLoc().isInvalid())) 13360 return false; 13361 13362 assert(OASE && "Expecting array section if not an array subscript."); 13363 const Expr *Length = OASE->getLength(); 13364 13365 // If we don't have a length we have to check if the array has unitary size 13366 // for this dimension. Also, we should always expect a length if the base type 13367 // is pointer. 13368 if (!Length) { 13369 if (const auto *ATy = dyn_cast<ConstantArrayType>(BaseQTy.getTypePtr())) 13370 return ATy->getSize().getSExtValue() != 1; 13371 // We cannot assume anything. 13372 return false; 13373 } 13374 13375 // Check if the length evaluates to 1. 13376 Expr::EvalResult Result; 13377 if (!Length->EvaluateAsInt(Result, SemaRef.getASTContext())) 13378 return false; // Can't get the integer value as a constant. 13379 13380 llvm::APSInt ConstLength = Result.Val.getInt(); 13381 return ConstLength.getSExtValue() != 1; 13382 } 13383 13384 // Return the expression of the base of the mappable expression or null if it 13385 // cannot be determined and do all the necessary checks to see if the expression 13386 // is valid as a standalone mappable expression. In the process, record all the 13387 // components of the expression. 13388 static const Expr *checkMapClauseExpressionBase( 13389 Sema &SemaRef, Expr *E, 13390 OMPClauseMappableExprCommon::MappableExprComponentList &CurComponents, 13391 OpenMPClauseKind CKind, bool NoDiagnose) { 13392 SourceLocation ELoc = E->getExprLoc(); 13393 SourceRange ERange = E->getSourceRange(); 13394 13395 // The base of elements of list in a map clause have to be either: 13396 // - a reference to variable or field. 13397 // - a member expression. 13398 // - an array expression. 13399 // 13400 // E.g. if we have the expression 'r.S.Arr[:12]', we want to retrieve the 13401 // reference to 'r'. 13402 // 13403 // If we have: 13404 // 13405 // struct SS { 13406 // Bla S; 13407 // foo() { 13408 // #pragma omp target map (S.Arr[:12]); 13409 // } 13410 // } 13411 // 13412 // We want to retrieve the member expression 'this->S'; 13413 13414 const Expr *RelevantExpr = nullptr; 13415 13416 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.2] 13417 // If a list item is an array section, it must specify contiguous storage. 13418 // 13419 // For this restriction it is sufficient that we make sure only references 13420 // to variables or fields and array expressions, and that no array sections 13421 // exist except in the rightmost expression (unless they cover the whole 13422 // dimension of the array). E.g. these would be invalid: 13423 // 13424 // r.ArrS[3:5].Arr[6:7] 13425 // 13426 // r.ArrS[3:5].x 13427 // 13428 // but these would be valid: 13429 // r.ArrS[3].Arr[6:7] 13430 // 13431 // r.ArrS[3].x 13432 13433 bool AllowUnitySizeArraySection = true; 13434 bool AllowWholeSizeArraySection = true; 13435 13436 while (!RelevantExpr) { 13437 E = E->IgnoreParenImpCasts(); 13438 13439 if (auto *CurE = dyn_cast<DeclRefExpr>(E)) { 13440 if (!isa<VarDecl>(CurE->getDecl())) 13441 return nullptr; 13442 13443 RelevantExpr = CurE; 13444 13445 // If we got a reference to a declaration, we should not expect any array 13446 // section before that. 13447 AllowUnitySizeArraySection = false; 13448 AllowWholeSizeArraySection = false; 13449 13450 // Record the component. 13451 CurComponents.emplace_back(CurE, CurE->getDecl()); 13452 } else if (auto *CurE = dyn_cast<MemberExpr>(E)) { 13453 Expr *BaseE = CurE->getBase()->IgnoreParenImpCasts(); 13454 13455 if (isa<CXXThisExpr>(BaseE)) 13456 // We found a base expression: this->Val. 13457 RelevantExpr = CurE; 13458 else 13459 E = BaseE; 13460 13461 if (!isa<FieldDecl>(CurE->getMemberDecl())) { 13462 if (!NoDiagnose) { 13463 SemaRef.Diag(ELoc, diag::err_omp_expected_access_to_data_field) 13464 << CurE->getSourceRange(); 13465 return nullptr; 13466 } 13467 if (RelevantExpr) 13468 return nullptr; 13469 continue; 13470 } 13471 13472 auto *FD = cast<FieldDecl>(CurE->getMemberDecl()); 13473 13474 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C/C++, p.3] 13475 // A bit-field cannot appear in a map clause. 13476 // 13477 if (FD->isBitField()) { 13478 if (!NoDiagnose) { 13479 SemaRef.Diag(ELoc, diag::err_omp_bit_fields_forbidden_in_clause) 13480 << CurE->getSourceRange() << getOpenMPClauseName(CKind); 13481 return nullptr; 13482 } 13483 if (RelevantExpr) 13484 return nullptr; 13485 continue; 13486 } 13487 13488 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C++, p.1] 13489 // If the type of a list item is a reference to a type T then the type 13490 // will be considered to be T for all purposes of this clause. 13491 QualType CurType = BaseE->getType().getNonReferenceType(); 13492 13493 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C/C++, p.2] 13494 // A list item cannot be a variable that is a member of a structure with 13495 // a union type. 13496 // 13497 if (CurType->isUnionType()) { 13498 if (!NoDiagnose) { 13499 SemaRef.Diag(ELoc, diag::err_omp_union_type_not_allowed) 13500 << CurE->getSourceRange(); 13501 return nullptr; 13502 } 13503 continue; 13504 } 13505 13506 // If we got a member expression, we should not expect any array section 13507 // before that: 13508 // 13509 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.7] 13510 // If a list item is an element of a structure, only the rightmost symbol 13511 // of the variable reference can be an array section. 13512 // 13513 AllowUnitySizeArraySection = false; 13514 AllowWholeSizeArraySection = false; 13515 13516 // Record the component. 13517 CurComponents.emplace_back(CurE, FD); 13518 } else if (auto *CurE = dyn_cast<ArraySubscriptExpr>(E)) { 13519 E = CurE->getBase()->IgnoreParenImpCasts(); 13520 13521 if (!E->getType()->isAnyPointerType() && !E->getType()->isArrayType()) { 13522 if (!NoDiagnose) { 13523 SemaRef.Diag(ELoc, diag::err_omp_expected_base_var_name) 13524 << 0 << CurE->getSourceRange(); 13525 return nullptr; 13526 } 13527 continue; 13528 } 13529 13530 // If we got an array subscript that express the whole dimension we 13531 // can have any array expressions before. If it only expressing part of 13532 // the dimension, we can only have unitary-size array expressions. 13533 if (checkArrayExpressionDoesNotReferToWholeSize(SemaRef, CurE, 13534 E->getType())) 13535 AllowWholeSizeArraySection = false; 13536 13537 if (const auto *TE = dyn_cast<CXXThisExpr>(E)) { 13538 Expr::EvalResult Result; 13539 if (CurE->getIdx()->EvaluateAsInt(Result, SemaRef.getASTContext())) { 13540 if (!Result.Val.getInt().isNullValue()) { 13541 SemaRef.Diag(CurE->getIdx()->getExprLoc(), 13542 diag::err_omp_invalid_map_this_expr); 13543 SemaRef.Diag(CurE->getIdx()->getExprLoc(), 13544 diag::note_omp_invalid_subscript_on_this_ptr_map); 13545 } 13546 } 13547 RelevantExpr = TE; 13548 } 13549 13550 // Record the component - we don't have any declaration associated. 13551 CurComponents.emplace_back(CurE, nullptr); 13552 } else if (auto *CurE = dyn_cast<OMPArraySectionExpr>(E)) { 13553 assert(!NoDiagnose && "Array sections cannot be implicitly mapped."); 13554 E = CurE->getBase()->IgnoreParenImpCasts(); 13555 13556 QualType CurType = 13557 OMPArraySectionExpr::getBaseOriginalType(E).getCanonicalType(); 13558 13559 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C++, p.1] 13560 // If the type of a list item is a reference to a type T then the type 13561 // will be considered to be T for all purposes of this clause. 13562 if (CurType->isReferenceType()) 13563 CurType = CurType->getPointeeType(); 13564 13565 bool IsPointer = CurType->isAnyPointerType(); 13566 13567 if (!IsPointer && !CurType->isArrayType()) { 13568 SemaRef.Diag(ELoc, diag::err_omp_expected_base_var_name) 13569 << 0 << CurE->getSourceRange(); 13570 return nullptr; 13571 } 13572 13573 bool NotWhole = 13574 checkArrayExpressionDoesNotReferToWholeSize(SemaRef, CurE, CurType); 13575 bool NotUnity = 13576 checkArrayExpressionDoesNotReferToUnitySize(SemaRef, CurE, CurType); 13577 13578 if (AllowWholeSizeArraySection) { 13579 // Any array section is currently allowed. Allowing a whole size array 13580 // section implies allowing a unity array section as well. 13581 // 13582 // If this array section refers to the whole dimension we can still 13583 // accept other array sections before this one, except if the base is a 13584 // pointer. Otherwise, only unitary sections are accepted. 13585 if (NotWhole || IsPointer) 13586 AllowWholeSizeArraySection = false; 13587 } else if (AllowUnitySizeArraySection && NotUnity) { 13588 // A unity or whole array section is not allowed and that is not 13589 // compatible with the properties of the current array section. 13590 SemaRef.Diag( 13591 ELoc, diag::err_array_section_does_not_specify_contiguous_storage) 13592 << CurE->getSourceRange(); 13593 return nullptr; 13594 } 13595 13596 if (const auto *TE = dyn_cast<CXXThisExpr>(E)) { 13597 Expr::EvalResult ResultR; 13598 Expr::EvalResult ResultL; 13599 if (CurE->getLength()->EvaluateAsInt(ResultR, 13600 SemaRef.getASTContext())) { 13601 if (!ResultR.Val.getInt().isOneValue()) { 13602 SemaRef.Diag(CurE->getLength()->getExprLoc(), 13603 diag::err_omp_invalid_map_this_expr); 13604 SemaRef.Diag(CurE->getLength()->getExprLoc(), 13605 diag::note_omp_invalid_length_on_this_ptr_mapping); 13606 } 13607 } 13608 if (CurE->getLowerBound() && CurE->getLowerBound()->EvaluateAsInt( 13609 ResultL, SemaRef.getASTContext())) { 13610 if (!ResultL.Val.getInt().isNullValue()) { 13611 SemaRef.Diag(CurE->getLowerBound()->getExprLoc(), 13612 diag::err_omp_invalid_map_this_expr); 13613 SemaRef.Diag(CurE->getLowerBound()->getExprLoc(), 13614 diag::note_omp_invalid_lower_bound_on_this_ptr_mapping); 13615 } 13616 } 13617 RelevantExpr = TE; 13618 } 13619 13620 // Record the component - we don't have any declaration associated. 13621 CurComponents.emplace_back(CurE, nullptr); 13622 } else { 13623 if (!NoDiagnose) { 13624 // If nothing else worked, this is not a valid map clause expression. 13625 SemaRef.Diag( 13626 ELoc, diag::err_omp_expected_named_var_member_or_array_expression) 13627 << ERange; 13628 } 13629 return nullptr; 13630 } 13631 } 13632 13633 return RelevantExpr; 13634 } 13635 13636 // Return true if expression E associated with value VD has conflicts with other 13637 // map information. 13638 static bool checkMapConflicts( 13639 Sema &SemaRef, DSAStackTy *DSAS, const ValueDecl *VD, const Expr *E, 13640 bool CurrentRegionOnly, 13641 OMPClauseMappableExprCommon::MappableExprComponentListRef CurComponents, 13642 OpenMPClauseKind CKind) { 13643 assert(VD && E); 13644 SourceLocation ELoc = E->getExprLoc(); 13645 SourceRange ERange = E->getSourceRange(); 13646 13647 // In order to easily check the conflicts we need to match each component of 13648 // the expression under test with the components of the expressions that are 13649 // already in the stack. 13650 13651 assert(!CurComponents.empty() && "Map clause expression with no components!"); 13652 assert(CurComponents.back().getAssociatedDeclaration() == VD && 13653 "Map clause expression with unexpected base!"); 13654 13655 // Variables to help detecting enclosing problems in data environment nests. 13656 bool IsEnclosedByDataEnvironmentExpr = false; 13657 const Expr *EnclosingExpr = nullptr; 13658 13659 bool FoundError = DSAS->checkMappableExprComponentListsForDecl( 13660 VD, CurrentRegionOnly, 13661 [&IsEnclosedByDataEnvironmentExpr, &SemaRef, VD, CurrentRegionOnly, ELoc, 13662 ERange, CKind, &EnclosingExpr, 13663 CurComponents](OMPClauseMappableExprCommon::MappableExprComponentListRef 13664 StackComponents, 13665 OpenMPClauseKind) { 13666 assert(!StackComponents.empty() && 13667 "Map clause expression with no components!"); 13668 assert(StackComponents.back().getAssociatedDeclaration() == VD && 13669 "Map clause expression with unexpected base!"); 13670 (void)VD; 13671 13672 // The whole expression in the stack. 13673 const Expr *RE = StackComponents.front().getAssociatedExpression(); 13674 13675 // Expressions must start from the same base. Here we detect at which 13676 // point both expressions diverge from each other and see if we can 13677 // detect if the memory referred to both expressions is contiguous and 13678 // do not overlap. 13679 auto CI = CurComponents.rbegin(); 13680 auto CE = CurComponents.rend(); 13681 auto SI = StackComponents.rbegin(); 13682 auto SE = StackComponents.rend(); 13683 for (; CI != CE && SI != SE; ++CI, ++SI) { 13684 13685 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.3] 13686 // At most one list item can be an array item derived from a given 13687 // variable in map clauses of the same construct. 13688 if (CurrentRegionOnly && 13689 (isa<ArraySubscriptExpr>(CI->getAssociatedExpression()) || 13690 isa<OMPArraySectionExpr>(CI->getAssociatedExpression())) && 13691 (isa<ArraySubscriptExpr>(SI->getAssociatedExpression()) || 13692 isa<OMPArraySectionExpr>(SI->getAssociatedExpression()))) { 13693 SemaRef.Diag(CI->getAssociatedExpression()->getExprLoc(), 13694 diag::err_omp_multiple_array_items_in_map_clause) 13695 << CI->getAssociatedExpression()->getSourceRange(); 13696 SemaRef.Diag(SI->getAssociatedExpression()->getExprLoc(), 13697 diag::note_used_here) 13698 << SI->getAssociatedExpression()->getSourceRange(); 13699 return true; 13700 } 13701 13702 // Do both expressions have the same kind? 13703 if (CI->getAssociatedExpression()->getStmtClass() != 13704 SI->getAssociatedExpression()->getStmtClass()) 13705 break; 13706 13707 // Are we dealing with different variables/fields? 13708 if (CI->getAssociatedDeclaration() != SI->getAssociatedDeclaration()) 13709 break; 13710 } 13711 // Check if the extra components of the expressions in the enclosing 13712 // data environment are redundant for the current base declaration. 13713 // If they are, the maps completely overlap, which is legal. 13714 for (; SI != SE; ++SI) { 13715 QualType Type; 13716 if (const auto *ASE = 13717 dyn_cast<ArraySubscriptExpr>(SI->getAssociatedExpression())) { 13718 Type = ASE->getBase()->IgnoreParenImpCasts()->getType(); 13719 } else if (const auto *OASE = dyn_cast<OMPArraySectionExpr>( 13720 SI->getAssociatedExpression())) { 13721 const Expr *E = OASE->getBase()->IgnoreParenImpCasts(); 13722 Type = 13723 OMPArraySectionExpr::getBaseOriginalType(E).getCanonicalType(); 13724 } 13725 if (Type.isNull() || Type->isAnyPointerType() || 13726 checkArrayExpressionDoesNotReferToWholeSize( 13727 SemaRef, SI->getAssociatedExpression(), Type)) 13728 break; 13729 } 13730 13731 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.4] 13732 // List items of map clauses in the same construct must not share 13733 // original storage. 13734 // 13735 // If the expressions are exactly the same or one is a subset of the 13736 // other, it means they are sharing storage. 13737 if (CI == CE && SI == SE) { 13738 if (CurrentRegionOnly) { 13739 if (CKind == OMPC_map) { 13740 SemaRef.Diag(ELoc, diag::err_omp_map_shared_storage) << ERange; 13741 } else { 13742 assert(CKind == OMPC_to || CKind == OMPC_from); 13743 SemaRef.Diag(ELoc, diag::err_omp_once_referenced_in_target_update) 13744 << ERange; 13745 } 13746 SemaRef.Diag(RE->getExprLoc(), diag::note_used_here) 13747 << RE->getSourceRange(); 13748 return true; 13749 } 13750 // If we find the same expression in the enclosing data environment, 13751 // that is legal. 13752 IsEnclosedByDataEnvironmentExpr = true; 13753 return false; 13754 } 13755 13756 QualType DerivedType = 13757 std::prev(CI)->getAssociatedDeclaration()->getType(); 13758 SourceLocation DerivedLoc = 13759 std::prev(CI)->getAssociatedExpression()->getExprLoc(); 13760 13761 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C++, p.1] 13762 // If the type of a list item is a reference to a type T then the type 13763 // will be considered to be T for all purposes of this clause. 13764 DerivedType = DerivedType.getNonReferenceType(); 13765 13766 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C/C++, p.1] 13767 // A variable for which the type is pointer and an array section 13768 // derived from that variable must not appear as list items of map 13769 // clauses of the same construct. 13770 // 13771 // Also, cover one of the cases in: 13772 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.5] 13773 // If any part of the original storage of a list item has corresponding 13774 // storage in the device data environment, all of the original storage 13775 // must have corresponding storage in the device data environment. 13776 // 13777 if (DerivedType->isAnyPointerType()) { 13778 if (CI == CE || SI == SE) { 13779 SemaRef.Diag( 13780 DerivedLoc, 13781 diag::err_omp_pointer_mapped_along_with_derived_section) 13782 << DerivedLoc; 13783 SemaRef.Diag(RE->getExprLoc(), diag::note_used_here) 13784 << RE->getSourceRange(); 13785 return true; 13786 } 13787 if (CI->getAssociatedExpression()->getStmtClass() != 13788 SI->getAssociatedExpression()->getStmtClass() || 13789 CI->getAssociatedDeclaration()->getCanonicalDecl() == 13790 SI->getAssociatedDeclaration()->getCanonicalDecl()) { 13791 assert(CI != CE && SI != SE); 13792 SemaRef.Diag(DerivedLoc, diag::err_omp_same_pointer_dereferenced) 13793 << DerivedLoc; 13794 SemaRef.Diag(RE->getExprLoc(), diag::note_used_here) 13795 << RE->getSourceRange(); 13796 return true; 13797 } 13798 } 13799 13800 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.4] 13801 // List items of map clauses in the same construct must not share 13802 // original storage. 13803 // 13804 // An expression is a subset of the other. 13805 if (CurrentRegionOnly && (CI == CE || SI == SE)) { 13806 if (CKind == OMPC_map) { 13807 if (CI != CE || SI != SE) { 13808 // Allow constructs like this: map(s, s.ptr[0:1]), where s.ptr is 13809 // a pointer. 13810 auto Begin = 13811 CI != CE ? CurComponents.begin() : StackComponents.begin(); 13812 auto End = CI != CE ? CurComponents.end() : StackComponents.end(); 13813 auto It = Begin; 13814 while (It != End && !It->getAssociatedDeclaration()) 13815 std::advance(It, 1); 13816 assert(It != End && 13817 "Expected at least one component with the declaration."); 13818 if (It != Begin && It->getAssociatedDeclaration() 13819 ->getType() 13820 .getCanonicalType() 13821 ->isAnyPointerType()) { 13822 IsEnclosedByDataEnvironmentExpr = false; 13823 EnclosingExpr = nullptr; 13824 return false; 13825 } 13826 } 13827 SemaRef.Diag(ELoc, diag::err_omp_map_shared_storage) << ERange; 13828 } else { 13829 assert(CKind == OMPC_to || CKind == OMPC_from); 13830 SemaRef.Diag(ELoc, diag::err_omp_once_referenced_in_target_update) 13831 << ERange; 13832 } 13833 SemaRef.Diag(RE->getExprLoc(), diag::note_used_here) 13834 << RE->getSourceRange(); 13835 return true; 13836 } 13837 13838 // The current expression uses the same base as other expression in the 13839 // data environment but does not contain it completely. 13840 if (!CurrentRegionOnly && SI != SE) 13841 EnclosingExpr = RE; 13842 13843 // The current expression is a subset of the expression in the data 13844 // environment. 13845 IsEnclosedByDataEnvironmentExpr |= 13846 (!CurrentRegionOnly && CI != CE && SI == SE); 13847 13848 return false; 13849 }); 13850 13851 if (CurrentRegionOnly) 13852 return FoundError; 13853 13854 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.5] 13855 // If any part of the original storage of a list item has corresponding 13856 // storage in the device data environment, all of the original storage must 13857 // have corresponding storage in the device data environment. 13858 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.6] 13859 // If a list item is an element of a structure, and a different element of 13860 // the structure has a corresponding list item in the device data environment 13861 // prior to a task encountering the construct associated with the map clause, 13862 // then the list item must also have a corresponding list item in the device 13863 // data environment prior to the task encountering the construct. 13864 // 13865 if (EnclosingExpr && !IsEnclosedByDataEnvironmentExpr) { 13866 SemaRef.Diag(ELoc, 13867 diag::err_omp_original_storage_is_shared_and_does_not_contain) 13868 << ERange; 13869 SemaRef.Diag(EnclosingExpr->getExprLoc(), diag::note_used_here) 13870 << EnclosingExpr->getSourceRange(); 13871 return true; 13872 } 13873 13874 return FoundError; 13875 } 13876 13877 // Look up the user-defined mapper given the mapper name and mapped type, and 13878 // build a reference to it. 13879 static ExprResult buildUserDefinedMapperRef(Sema &SemaRef, Scope *S, 13880 CXXScopeSpec &MapperIdScopeSpec, 13881 const DeclarationNameInfo &MapperId, 13882 QualType Type, 13883 Expr *UnresolvedMapper) { 13884 if (MapperIdScopeSpec.isInvalid()) 13885 return ExprError(); 13886 // Find all user-defined mappers with the given MapperId. 13887 SmallVector<UnresolvedSet<8>, 4> Lookups; 13888 LookupResult Lookup(SemaRef, MapperId, Sema::LookupOMPMapperName); 13889 Lookup.suppressDiagnostics(); 13890 if (S) { 13891 while (S && SemaRef.LookupParsedName(Lookup, S, &MapperIdScopeSpec)) { 13892 NamedDecl *D = Lookup.getRepresentativeDecl(); 13893 while (S && !S->isDeclScope(D)) 13894 S = S->getParent(); 13895 if (S) 13896 S = S->getParent(); 13897 Lookups.emplace_back(); 13898 Lookups.back().append(Lookup.begin(), Lookup.end()); 13899 Lookup.clear(); 13900 } 13901 } else if (auto *ULE = cast_or_null<UnresolvedLookupExpr>(UnresolvedMapper)) { 13902 // Extract the user-defined mappers with the given MapperId. 13903 Lookups.push_back(UnresolvedSet<8>()); 13904 for (NamedDecl *D : ULE->decls()) { 13905 auto *DMD = cast<OMPDeclareMapperDecl>(D); 13906 assert(DMD && "Expect valid OMPDeclareMapperDecl during instantiation."); 13907 Lookups.back().addDecl(DMD); 13908 } 13909 } 13910 // Defer the lookup for dependent types. The results will be passed through 13911 // UnresolvedMapper on instantiation. 13912 if (SemaRef.CurContext->isDependentContext() || Type->isDependentType() || 13913 Type->isInstantiationDependentType() || 13914 Type->containsUnexpandedParameterPack() || 13915 filterLookupForUDReductionAndMapper<bool>(Lookups, [](ValueDecl *D) { 13916 return !D->isInvalidDecl() && 13917 (D->getType()->isDependentType() || 13918 D->getType()->isInstantiationDependentType() || 13919 D->getType()->containsUnexpandedParameterPack()); 13920 })) { 13921 UnresolvedSet<8> URS; 13922 for (const UnresolvedSet<8> &Set : Lookups) { 13923 if (Set.empty()) 13924 continue; 13925 URS.append(Set.begin(), Set.end()); 13926 } 13927 return UnresolvedLookupExpr::Create( 13928 SemaRef.Context, /*NamingClass=*/nullptr, 13929 MapperIdScopeSpec.getWithLocInContext(SemaRef.Context), MapperId, 13930 /*ADL=*/false, /*Overloaded=*/true, URS.begin(), URS.end()); 13931 } 13932 // [OpenMP 5.0], 2.19.7.3 declare mapper Directive, Restrictions 13933 // The type must be of struct, union or class type in C and C++ 13934 if (!Type->isStructureOrClassType() && !Type->isUnionType()) 13935 return ExprEmpty(); 13936 SourceLocation Loc = MapperId.getLoc(); 13937 // Perform argument dependent lookup. 13938 if (SemaRef.getLangOpts().CPlusPlus && !MapperIdScopeSpec.isSet()) 13939 argumentDependentLookup(SemaRef, MapperId, Loc, Type, Lookups); 13940 // Return the first user-defined mapper with the desired type. 13941 if (auto *VD = filterLookupForUDReductionAndMapper<ValueDecl *>( 13942 Lookups, [&SemaRef, Type](ValueDecl *D) -> ValueDecl * { 13943 if (!D->isInvalidDecl() && 13944 SemaRef.Context.hasSameType(D->getType(), Type)) 13945 return D; 13946 return nullptr; 13947 })) 13948 return SemaRef.BuildDeclRefExpr(VD, Type, VK_LValue, Loc); 13949 // Find the first user-defined mapper with a type derived from the desired 13950 // type. 13951 if (auto *VD = filterLookupForUDReductionAndMapper<ValueDecl *>( 13952 Lookups, [&SemaRef, Type, Loc](ValueDecl *D) -> ValueDecl * { 13953 if (!D->isInvalidDecl() && 13954 SemaRef.IsDerivedFrom(Loc, Type, D->getType()) && 13955 !Type.isMoreQualifiedThan(D->getType())) 13956 return D; 13957 return nullptr; 13958 })) { 13959 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true, 13960 /*DetectVirtual=*/false); 13961 if (SemaRef.IsDerivedFrom(Loc, Type, VD->getType(), Paths)) { 13962 if (!Paths.isAmbiguous(SemaRef.Context.getCanonicalType( 13963 VD->getType().getUnqualifiedType()))) { 13964 if (SemaRef.CheckBaseClassAccess( 13965 Loc, VD->getType(), Type, Paths.front(), 13966 /*DiagID=*/0) != Sema::AR_inaccessible) { 13967 return SemaRef.BuildDeclRefExpr(VD, Type, VK_LValue, Loc); 13968 } 13969 } 13970 } 13971 } 13972 // Report error if a mapper is specified, but cannot be found. 13973 if (MapperIdScopeSpec.isSet() || MapperId.getAsString() != "default") { 13974 SemaRef.Diag(Loc, diag::err_omp_invalid_mapper) 13975 << Type << MapperId.getName(); 13976 return ExprError(); 13977 } 13978 return ExprEmpty(); 13979 } 13980 13981 namespace { 13982 // Utility struct that gathers all the related lists associated with a mappable 13983 // expression. 13984 struct MappableVarListInfo { 13985 // The list of expressions. 13986 ArrayRef<Expr *> VarList; 13987 // The list of processed expressions. 13988 SmallVector<Expr *, 16> ProcessedVarList; 13989 // The mappble components for each expression. 13990 OMPClauseMappableExprCommon::MappableExprComponentLists VarComponents; 13991 // The base declaration of the variable. 13992 SmallVector<ValueDecl *, 16> VarBaseDeclarations; 13993 // The reference to the user-defined mapper associated with every expression. 13994 SmallVector<Expr *, 16> UDMapperList; 13995 13996 MappableVarListInfo(ArrayRef<Expr *> VarList) : VarList(VarList) { 13997 // We have a list of components and base declarations for each entry in the 13998 // variable list. 13999 VarComponents.reserve(VarList.size()); 14000 VarBaseDeclarations.reserve(VarList.size()); 14001 } 14002 }; 14003 } 14004 14005 // Check the validity of the provided variable list for the provided clause kind 14006 // \a CKind. In the check process the valid expressions, mappable expression 14007 // components, variables, and user-defined mappers are extracted and used to 14008 // fill \a ProcessedVarList, \a VarComponents, \a VarBaseDeclarations, and \a 14009 // UDMapperList in MVLI. \a MapType, \a IsMapTypeImplicit, \a MapperIdScopeSpec, 14010 // and \a MapperId are expected to be valid if the clause kind is 'map'. 14011 static void checkMappableExpressionList( 14012 Sema &SemaRef, DSAStackTy *DSAS, OpenMPClauseKind CKind, 14013 MappableVarListInfo &MVLI, SourceLocation StartLoc, 14014 CXXScopeSpec &MapperIdScopeSpec, DeclarationNameInfo MapperId, 14015 ArrayRef<Expr *> UnresolvedMappers, 14016 OpenMPMapClauseKind MapType = OMPC_MAP_unknown, 14017 bool IsMapTypeImplicit = false) { 14018 // We only expect mappable expressions in 'to', 'from', and 'map' clauses. 14019 assert((CKind == OMPC_map || CKind == OMPC_to || CKind == OMPC_from) && 14020 "Unexpected clause kind with mappable expressions!"); 14021 14022 // If the identifier of user-defined mapper is not specified, it is "default". 14023 // We do not change the actual name in this clause to distinguish whether a 14024 // mapper is specified explicitly, i.e., it is not explicitly specified when 14025 // MapperId.getName() is empty. 14026 if (!MapperId.getName() || MapperId.getName().isEmpty()) { 14027 auto &DeclNames = SemaRef.getASTContext().DeclarationNames; 14028 MapperId.setName(DeclNames.getIdentifier( 14029 &SemaRef.getASTContext().Idents.get("default"))); 14030 } 14031 14032 // Iterators to find the current unresolved mapper expression. 14033 auto UMIt = UnresolvedMappers.begin(), UMEnd = UnresolvedMappers.end(); 14034 bool UpdateUMIt = false; 14035 Expr *UnresolvedMapper = nullptr; 14036 14037 // Keep track of the mappable components and base declarations in this clause. 14038 // Each entry in the list is going to have a list of components associated. We 14039 // record each set of the components so that we can build the clause later on. 14040 // In the end we should have the same amount of declarations and component 14041 // lists. 14042 14043 for (Expr *RE : MVLI.VarList) { 14044 assert(RE && "Null expr in omp to/from/map clause"); 14045 SourceLocation ELoc = RE->getExprLoc(); 14046 14047 // Find the current unresolved mapper expression. 14048 if (UpdateUMIt && UMIt != UMEnd) { 14049 UMIt++; 14050 assert( 14051 UMIt != UMEnd && 14052 "Expect the size of UnresolvedMappers to match with that of VarList"); 14053 } 14054 UpdateUMIt = true; 14055 if (UMIt != UMEnd) 14056 UnresolvedMapper = *UMIt; 14057 14058 const Expr *VE = RE->IgnoreParenLValueCasts(); 14059 14060 if (VE->isValueDependent() || VE->isTypeDependent() || 14061 VE->isInstantiationDependent() || 14062 VE->containsUnexpandedParameterPack()) { 14063 // Try to find the associated user-defined mapper. 14064 ExprResult ER = buildUserDefinedMapperRef( 14065 SemaRef, DSAS->getCurScope(), MapperIdScopeSpec, MapperId, 14066 VE->getType().getCanonicalType(), UnresolvedMapper); 14067 if (ER.isInvalid()) 14068 continue; 14069 MVLI.UDMapperList.push_back(ER.get()); 14070 // We can only analyze this information once the missing information is 14071 // resolved. 14072 MVLI.ProcessedVarList.push_back(RE); 14073 continue; 14074 } 14075 14076 Expr *SimpleExpr = RE->IgnoreParenCasts(); 14077 14078 if (!RE->IgnoreParenImpCasts()->isLValue()) { 14079 SemaRef.Diag(ELoc, 14080 diag::err_omp_expected_named_var_member_or_array_expression) 14081 << RE->getSourceRange(); 14082 continue; 14083 } 14084 14085 OMPClauseMappableExprCommon::MappableExprComponentList CurComponents; 14086 ValueDecl *CurDeclaration = nullptr; 14087 14088 // Obtain the array or member expression bases if required. Also, fill the 14089 // components array with all the components identified in the process. 14090 const Expr *BE = checkMapClauseExpressionBase( 14091 SemaRef, SimpleExpr, CurComponents, CKind, /*NoDiagnose=*/false); 14092 if (!BE) 14093 continue; 14094 14095 assert(!CurComponents.empty() && 14096 "Invalid mappable expression information."); 14097 14098 if (const auto *TE = dyn_cast<CXXThisExpr>(BE)) { 14099 // Add store "this" pointer to class in DSAStackTy for future checking 14100 DSAS->addMappedClassesQualTypes(TE->getType()); 14101 // Try to find the associated user-defined mapper. 14102 ExprResult ER = buildUserDefinedMapperRef( 14103 SemaRef, DSAS->getCurScope(), MapperIdScopeSpec, MapperId, 14104 VE->getType().getCanonicalType(), UnresolvedMapper); 14105 if (ER.isInvalid()) 14106 continue; 14107 MVLI.UDMapperList.push_back(ER.get()); 14108 // Skip restriction checking for variable or field declarations 14109 MVLI.ProcessedVarList.push_back(RE); 14110 MVLI.VarComponents.resize(MVLI.VarComponents.size() + 1); 14111 MVLI.VarComponents.back().append(CurComponents.begin(), 14112 CurComponents.end()); 14113 MVLI.VarBaseDeclarations.push_back(nullptr); 14114 continue; 14115 } 14116 14117 // For the following checks, we rely on the base declaration which is 14118 // expected to be associated with the last component. The declaration is 14119 // expected to be a variable or a field (if 'this' is being mapped). 14120 CurDeclaration = CurComponents.back().getAssociatedDeclaration(); 14121 assert(CurDeclaration && "Null decl on map clause."); 14122 assert( 14123 CurDeclaration->isCanonicalDecl() && 14124 "Expecting components to have associated only canonical declarations."); 14125 14126 auto *VD = dyn_cast<VarDecl>(CurDeclaration); 14127 const auto *FD = dyn_cast<FieldDecl>(CurDeclaration); 14128 14129 assert((VD || FD) && "Only variables or fields are expected here!"); 14130 (void)FD; 14131 14132 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.10] 14133 // threadprivate variables cannot appear in a map clause. 14134 // OpenMP 4.5 [2.10.5, target update Construct] 14135 // threadprivate variables cannot appear in a from clause. 14136 if (VD && DSAS->isThreadPrivate(VD)) { 14137 DSAStackTy::DSAVarData DVar = DSAS->getTopDSA(VD, /*FromParent=*/false); 14138 SemaRef.Diag(ELoc, diag::err_omp_threadprivate_in_clause) 14139 << getOpenMPClauseName(CKind); 14140 reportOriginalDsa(SemaRef, DSAS, VD, DVar); 14141 continue; 14142 } 14143 14144 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.9] 14145 // A list item cannot appear in both a map clause and a data-sharing 14146 // attribute clause on the same construct. 14147 14148 // Check conflicts with other map clause expressions. We check the conflicts 14149 // with the current construct separately from the enclosing data 14150 // environment, because the restrictions are different. We only have to 14151 // check conflicts across regions for the map clauses. 14152 if (checkMapConflicts(SemaRef, DSAS, CurDeclaration, SimpleExpr, 14153 /*CurrentRegionOnly=*/true, CurComponents, CKind)) 14154 break; 14155 if (CKind == OMPC_map && 14156 checkMapConflicts(SemaRef, DSAS, CurDeclaration, SimpleExpr, 14157 /*CurrentRegionOnly=*/false, CurComponents, CKind)) 14158 break; 14159 14160 // OpenMP 4.5 [2.10.5, target update Construct] 14161 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C++, p.1] 14162 // If the type of a list item is a reference to a type T then the type will 14163 // be considered to be T for all purposes of this clause. 14164 auto I = llvm::find_if( 14165 CurComponents, 14166 [](const OMPClauseMappableExprCommon::MappableComponent &MC) { 14167 return MC.getAssociatedDeclaration(); 14168 }); 14169 assert(I != CurComponents.end() && "Null decl on map clause."); 14170 QualType Type = 14171 I->getAssociatedDeclaration()->getType().getNonReferenceType(); 14172 14173 // OpenMP 4.5 [2.10.5, target update Construct, Restrictions, p.4] 14174 // A list item in a to or from clause must have a mappable type. 14175 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.9] 14176 // A list item must have a mappable type. 14177 if (!checkTypeMappable(VE->getExprLoc(), VE->getSourceRange(), SemaRef, 14178 DSAS, Type)) 14179 continue; 14180 14181 if (CKind == OMPC_map) { 14182 // target enter data 14183 // OpenMP [2.10.2, Restrictions, p. 99] 14184 // A map-type must be specified in all map clauses and must be either 14185 // to or alloc. 14186 OpenMPDirectiveKind DKind = DSAS->getCurrentDirective(); 14187 if (DKind == OMPD_target_enter_data && 14188 !(MapType == OMPC_MAP_to || MapType == OMPC_MAP_alloc)) { 14189 SemaRef.Diag(StartLoc, diag::err_omp_invalid_map_type_for_directive) 14190 << (IsMapTypeImplicit ? 1 : 0) 14191 << getOpenMPSimpleClauseTypeName(OMPC_map, MapType) 14192 << getOpenMPDirectiveName(DKind); 14193 continue; 14194 } 14195 14196 // target exit_data 14197 // OpenMP [2.10.3, Restrictions, p. 102] 14198 // A map-type must be specified in all map clauses and must be either 14199 // from, release, or delete. 14200 if (DKind == OMPD_target_exit_data && 14201 !(MapType == OMPC_MAP_from || MapType == OMPC_MAP_release || 14202 MapType == OMPC_MAP_delete)) { 14203 SemaRef.Diag(StartLoc, diag::err_omp_invalid_map_type_for_directive) 14204 << (IsMapTypeImplicit ? 1 : 0) 14205 << getOpenMPSimpleClauseTypeName(OMPC_map, MapType) 14206 << getOpenMPDirectiveName(DKind); 14207 continue; 14208 } 14209 14210 // OpenMP 4.5 [2.15.5.1, Restrictions, p.3] 14211 // A list item cannot appear in both a map clause and a data-sharing 14212 // attribute clause on the same construct 14213 if (VD && isOpenMPTargetExecutionDirective(DKind)) { 14214 DSAStackTy::DSAVarData DVar = DSAS->getTopDSA(VD, /*FromParent=*/false); 14215 if (isOpenMPPrivate(DVar.CKind)) { 14216 SemaRef.Diag(ELoc, diag::err_omp_variable_in_given_clause_and_dsa) 14217 << getOpenMPClauseName(DVar.CKind) 14218 << getOpenMPClauseName(OMPC_map) 14219 << getOpenMPDirectiveName(DSAS->getCurrentDirective()); 14220 reportOriginalDsa(SemaRef, DSAS, CurDeclaration, DVar); 14221 continue; 14222 } 14223 } 14224 } 14225 14226 // Try to find the associated user-defined mapper. 14227 ExprResult ER = buildUserDefinedMapperRef( 14228 SemaRef, DSAS->getCurScope(), MapperIdScopeSpec, MapperId, 14229 Type.getCanonicalType(), UnresolvedMapper); 14230 if (ER.isInvalid()) 14231 continue; 14232 MVLI.UDMapperList.push_back(ER.get()); 14233 14234 // Save the current expression. 14235 MVLI.ProcessedVarList.push_back(RE); 14236 14237 // Store the components in the stack so that they can be used to check 14238 // against other clauses later on. 14239 DSAS->addMappableExpressionComponents(CurDeclaration, CurComponents, 14240 /*WhereFoundClauseKind=*/OMPC_map); 14241 14242 // Save the components and declaration to create the clause. For purposes of 14243 // the clause creation, any component list that has has base 'this' uses 14244 // null as base declaration. 14245 MVLI.VarComponents.resize(MVLI.VarComponents.size() + 1); 14246 MVLI.VarComponents.back().append(CurComponents.begin(), 14247 CurComponents.end()); 14248 MVLI.VarBaseDeclarations.push_back(isa<MemberExpr>(BE) ? nullptr 14249 : CurDeclaration); 14250 } 14251 } 14252 14253 OMPClause *Sema::ActOnOpenMPMapClause( 14254 ArrayRef<OpenMPMapModifierKind> MapTypeModifiers, 14255 ArrayRef<SourceLocation> MapTypeModifiersLoc, 14256 CXXScopeSpec &MapperIdScopeSpec, DeclarationNameInfo &MapperId, 14257 OpenMPMapClauseKind MapType, bool IsMapTypeImplicit, SourceLocation MapLoc, 14258 SourceLocation ColonLoc, ArrayRef<Expr *> VarList, 14259 const OMPVarListLocTy &Locs, ArrayRef<Expr *> UnresolvedMappers) { 14260 OpenMPMapModifierKind Modifiers[] = {OMPC_MAP_MODIFIER_unknown, 14261 OMPC_MAP_MODIFIER_unknown, 14262 OMPC_MAP_MODIFIER_unknown}; 14263 SourceLocation ModifiersLoc[OMPMapClause::NumberOfModifiers]; 14264 14265 // Process map-type-modifiers, flag errors for duplicate modifiers. 14266 unsigned Count = 0; 14267 for (unsigned I = 0, E = MapTypeModifiers.size(); I < E; ++I) { 14268 if (MapTypeModifiers[I] != OMPC_MAP_MODIFIER_unknown && 14269 llvm::find(Modifiers, MapTypeModifiers[I]) != std::end(Modifiers)) { 14270 Diag(MapTypeModifiersLoc[I], diag::err_omp_duplicate_map_type_modifier); 14271 continue; 14272 } 14273 assert(Count < OMPMapClause::NumberOfModifiers && 14274 "Modifiers exceed the allowed number of map type modifiers"); 14275 Modifiers[Count] = MapTypeModifiers[I]; 14276 ModifiersLoc[Count] = MapTypeModifiersLoc[I]; 14277 ++Count; 14278 } 14279 14280 MappableVarListInfo MVLI(VarList); 14281 checkMappableExpressionList(*this, DSAStack, OMPC_map, MVLI, Locs.StartLoc, 14282 MapperIdScopeSpec, MapperId, UnresolvedMappers, 14283 MapType, IsMapTypeImplicit); 14284 14285 // We need to produce a map clause even if we don't have variables so that 14286 // other diagnostics related with non-existing map clauses are accurate. 14287 return OMPMapClause::Create(Context, Locs, MVLI.ProcessedVarList, 14288 MVLI.VarBaseDeclarations, MVLI.VarComponents, 14289 MVLI.UDMapperList, Modifiers, ModifiersLoc, 14290 MapperIdScopeSpec.getWithLocInContext(Context), 14291 MapperId, MapType, IsMapTypeImplicit, MapLoc); 14292 } 14293 14294 QualType Sema::ActOnOpenMPDeclareReductionType(SourceLocation TyLoc, 14295 TypeResult ParsedType) { 14296 assert(ParsedType.isUsable()); 14297 14298 QualType ReductionType = GetTypeFromParser(ParsedType.get()); 14299 if (ReductionType.isNull()) 14300 return QualType(); 14301 14302 // [OpenMP 4.0], 2.15 declare reduction Directive, Restrictions, C\C++ 14303 // A type name in a declare reduction directive cannot be a function type, an 14304 // array type, a reference type, or a type qualified with const, volatile or 14305 // restrict. 14306 if (ReductionType.hasQualifiers()) { 14307 Diag(TyLoc, diag::err_omp_reduction_wrong_type) << 0; 14308 return QualType(); 14309 } 14310 14311 if (ReductionType->isFunctionType()) { 14312 Diag(TyLoc, diag::err_omp_reduction_wrong_type) << 1; 14313 return QualType(); 14314 } 14315 if (ReductionType->isReferenceType()) { 14316 Diag(TyLoc, diag::err_omp_reduction_wrong_type) << 2; 14317 return QualType(); 14318 } 14319 if (ReductionType->isArrayType()) { 14320 Diag(TyLoc, diag::err_omp_reduction_wrong_type) << 3; 14321 return QualType(); 14322 } 14323 return ReductionType; 14324 } 14325 14326 Sema::DeclGroupPtrTy Sema::ActOnOpenMPDeclareReductionDirectiveStart( 14327 Scope *S, DeclContext *DC, DeclarationName Name, 14328 ArrayRef<std::pair<QualType, SourceLocation>> ReductionTypes, 14329 AccessSpecifier AS, Decl *PrevDeclInScope) { 14330 SmallVector<Decl *, 8> Decls; 14331 Decls.reserve(ReductionTypes.size()); 14332 14333 LookupResult Lookup(*this, Name, SourceLocation(), LookupOMPReductionName, 14334 forRedeclarationInCurContext()); 14335 // [OpenMP 4.0], 2.15 declare reduction Directive, Restrictions 14336 // A reduction-identifier may not be re-declared in the current scope for the 14337 // same type or for a type that is compatible according to the base language 14338 // rules. 14339 llvm::DenseMap<QualType, SourceLocation> PreviousRedeclTypes; 14340 OMPDeclareReductionDecl *PrevDRD = nullptr; 14341 bool InCompoundScope = true; 14342 if (S != nullptr) { 14343 // Find previous declaration with the same name not referenced in other 14344 // declarations. 14345 FunctionScopeInfo *ParentFn = getEnclosingFunction(); 14346 InCompoundScope = 14347 (ParentFn != nullptr) && !ParentFn->CompoundScopes.empty(); 14348 LookupName(Lookup, S); 14349 FilterLookupForScope(Lookup, DC, S, /*ConsiderLinkage=*/false, 14350 /*AllowInlineNamespace=*/false); 14351 llvm::DenseMap<OMPDeclareReductionDecl *, bool> UsedAsPrevious; 14352 LookupResult::Filter Filter = Lookup.makeFilter(); 14353 while (Filter.hasNext()) { 14354 auto *PrevDecl = cast<OMPDeclareReductionDecl>(Filter.next()); 14355 if (InCompoundScope) { 14356 auto I = UsedAsPrevious.find(PrevDecl); 14357 if (I == UsedAsPrevious.end()) 14358 UsedAsPrevious[PrevDecl] = false; 14359 if (OMPDeclareReductionDecl *D = PrevDecl->getPrevDeclInScope()) 14360 UsedAsPrevious[D] = true; 14361 } 14362 PreviousRedeclTypes[PrevDecl->getType().getCanonicalType()] = 14363 PrevDecl->getLocation(); 14364 } 14365 Filter.done(); 14366 if (InCompoundScope) { 14367 for (const auto &PrevData : UsedAsPrevious) { 14368 if (!PrevData.second) { 14369 PrevDRD = PrevData.first; 14370 break; 14371 } 14372 } 14373 } 14374 } else if (PrevDeclInScope != nullptr) { 14375 auto *PrevDRDInScope = PrevDRD = 14376 cast<OMPDeclareReductionDecl>(PrevDeclInScope); 14377 do { 14378 PreviousRedeclTypes[PrevDRDInScope->getType().getCanonicalType()] = 14379 PrevDRDInScope->getLocation(); 14380 PrevDRDInScope = PrevDRDInScope->getPrevDeclInScope(); 14381 } while (PrevDRDInScope != nullptr); 14382 } 14383 for (const auto &TyData : ReductionTypes) { 14384 const auto I = PreviousRedeclTypes.find(TyData.first.getCanonicalType()); 14385 bool Invalid = false; 14386 if (I != PreviousRedeclTypes.end()) { 14387 Diag(TyData.second, diag::err_omp_declare_reduction_redefinition) 14388 << TyData.first; 14389 Diag(I->second, diag::note_previous_definition); 14390 Invalid = true; 14391 } 14392 PreviousRedeclTypes[TyData.first.getCanonicalType()] = TyData.second; 14393 auto *DRD = OMPDeclareReductionDecl::Create(Context, DC, TyData.second, 14394 Name, TyData.first, PrevDRD); 14395 DC->addDecl(DRD); 14396 DRD->setAccess(AS); 14397 Decls.push_back(DRD); 14398 if (Invalid) 14399 DRD->setInvalidDecl(); 14400 else 14401 PrevDRD = DRD; 14402 } 14403 14404 return DeclGroupPtrTy::make( 14405 DeclGroupRef::Create(Context, Decls.begin(), Decls.size())); 14406 } 14407 14408 void Sema::ActOnOpenMPDeclareReductionCombinerStart(Scope *S, Decl *D) { 14409 auto *DRD = cast<OMPDeclareReductionDecl>(D); 14410 14411 // Enter new function scope. 14412 PushFunctionScope(); 14413 setFunctionHasBranchProtectedScope(); 14414 getCurFunction()->setHasOMPDeclareReductionCombiner(); 14415 14416 if (S != nullptr) 14417 PushDeclContext(S, DRD); 14418 else 14419 CurContext = DRD; 14420 14421 PushExpressionEvaluationContext( 14422 ExpressionEvaluationContext::PotentiallyEvaluated); 14423 14424 QualType ReductionType = DRD->getType(); 14425 // Create 'T* omp_parm;T omp_in;'. All references to 'omp_in' will 14426 // be replaced by '*omp_parm' during codegen. This required because 'omp_in' 14427 // uses semantics of argument handles by value, but it should be passed by 14428 // reference. C lang does not support references, so pass all parameters as 14429 // pointers. 14430 // Create 'T omp_in;' variable. 14431 VarDecl *OmpInParm = 14432 buildVarDecl(*this, D->getLocation(), ReductionType, "omp_in"); 14433 // Create 'T* omp_parm;T omp_out;'. All references to 'omp_out' will 14434 // be replaced by '*omp_parm' during codegen. This required because 'omp_out' 14435 // uses semantics of argument handles by value, but it should be passed by 14436 // reference. C lang does not support references, so pass all parameters as 14437 // pointers. 14438 // Create 'T omp_out;' variable. 14439 VarDecl *OmpOutParm = 14440 buildVarDecl(*this, D->getLocation(), ReductionType, "omp_out"); 14441 if (S != nullptr) { 14442 PushOnScopeChains(OmpInParm, S); 14443 PushOnScopeChains(OmpOutParm, S); 14444 } else { 14445 DRD->addDecl(OmpInParm); 14446 DRD->addDecl(OmpOutParm); 14447 } 14448 Expr *InE = 14449 ::buildDeclRefExpr(*this, OmpInParm, ReductionType, D->getLocation()); 14450 Expr *OutE = 14451 ::buildDeclRefExpr(*this, OmpOutParm, ReductionType, D->getLocation()); 14452 DRD->setCombinerData(InE, OutE); 14453 } 14454 14455 void Sema::ActOnOpenMPDeclareReductionCombinerEnd(Decl *D, Expr *Combiner) { 14456 auto *DRD = cast<OMPDeclareReductionDecl>(D); 14457 DiscardCleanupsInEvaluationContext(); 14458 PopExpressionEvaluationContext(); 14459 14460 PopDeclContext(); 14461 PopFunctionScopeInfo(); 14462 14463 if (Combiner != nullptr) 14464 DRD->setCombiner(Combiner); 14465 else 14466 DRD->setInvalidDecl(); 14467 } 14468 14469 VarDecl *Sema::ActOnOpenMPDeclareReductionInitializerStart(Scope *S, Decl *D) { 14470 auto *DRD = cast<OMPDeclareReductionDecl>(D); 14471 14472 // Enter new function scope. 14473 PushFunctionScope(); 14474 setFunctionHasBranchProtectedScope(); 14475 14476 if (S != nullptr) 14477 PushDeclContext(S, DRD); 14478 else 14479 CurContext = DRD; 14480 14481 PushExpressionEvaluationContext( 14482 ExpressionEvaluationContext::PotentiallyEvaluated); 14483 14484 QualType ReductionType = DRD->getType(); 14485 // Create 'T* omp_parm;T omp_priv;'. All references to 'omp_priv' will 14486 // be replaced by '*omp_parm' during codegen. This required because 'omp_priv' 14487 // uses semantics of argument handles by value, but it should be passed by 14488 // reference. C lang does not support references, so pass all parameters as 14489 // pointers. 14490 // Create 'T omp_priv;' variable. 14491 VarDecl *OmpPrivParm = 14492 buildVarDecl(*this, D->getLocation(), ReductionType, "omp_priv"); 14493 // Create 'T* omp_parm;T omp_orig;'. All references to 'omp_orig' will 14494 // be replaced by '*omp_parm' during codegen. This required because 'omp_orig' 14495 // uses semantics of argument handles by value, but it should be passed by 14496 // reference. C lang does not support references, so pass all parameters as 14497 // pointers. 14498 // Create 'T omp_orig;' variable. 14499 VarDecl *OmpOrigParm = 14500 buildVarDecl(*this, D->getLocation(), ReductionType, "omp_orig"); 14501 if (S != nullptr) { 14502 PushOnScopeChains(OmpPrivParm, S); 14503 PushOnScopeChains(OmpOrigParm, S); 14504 } else { 14505 DRD->addDecl(OmpPrivParm); 14506 DRD->addDecl(OmpOrigParm); 14507 } 14508 Expr *OrigE = 14509 ::buildDeclRefExpr(*this, OmpOrigParm, ReductionType, D->getLocation()); 14510 Expr *PrivE = 14511 ::buildDeclRefExpr(*this, OmpPrivParm, ReductionType, D->getLocation()); 14512 DRD->setInitializerData(OrigE, PrivE); 14513 return OmpPrivParm; 14514 } 14515 14516 void Sema::ActOnOpenMPDeclareReductionInitializerEnd(Decl *D, Expr *Initializer, 14517 VarDecl *OmpPrivParm) { 14518 auto *DRD = cast<OMPDeclareReductionDecl>(D); 14519 DiscardCleanupsInEvaluationContext(); 14520 PopExpressionEvaluationContext(); 14521 14522 PopDeclContext(); 14523 PopFunctionScopeInfo(); 14524 14525 if (Initializer != nullptr) { 14526 DRD->setInitializer(Initializer, OMPDeclareReductionDecl::CallInit); 14527 } else if (OmpPrivParm->hasInit()) { 14528 DRD->setInitializer(OmpPrivParm->getInit(), 14529 OmpPrivParm->isDirectInit() 14530 ? OMPDeclareReductionDecl::DirectInit 14531 : OMPDeclareReductionDecl::CopyInit); 14532 } else { 14533 DRD->setInvalidDecl(); 14534 } 14535 } 14536 14537 Sema::DeclGroupPtrTy Sema::ActOnOpenMPDeclareReductionDirectiveEnd( 14538 Scope *S, DeclGroupPtrTy DeclReductions, bool IsValid) { 14539 for (Decl *D : DeclReductions.get()) { 14540 if (IsValid) { 14541 if (S) 14542 PushOnScopeChains(cast<OMPDeclareReductionDecl>(D), S, 14543 /*AddToContext=*/false); 14544 } else { 14545 D->setInvalidDecl(); 14546 } 14547 } 14548 return DeclReductions; 14549 } 14550 14551 TypeResult Sema::ActOnOpenMPDeclareMapperVarDecl(Scope *S, Declarator &D) { 14552 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); 14553 QualType T = TInfo->getType(); 14554 if (D.isInvalidType()) 14555 return true; 14556 14557 if (getLangOpts().CPlusPlus) { 14558 // Check that there are no default arguments (C++ only). 14559 CheckExtraCXXDefaultArguments(D); 14560 } 14561 14562 return CreateParsedType(T, TInfo); 14563 } 14564 14565 QualType Sema::ActOnOpenMPDeclareMapperType(SourceLocation TyLoc, 14566 TypeResult ParsedType) { 14567 assert(ParsedType.isUsable() && "Expect usable parsed mapper type"); 14568 14569 QualType MapperType = GetTypeFromParser(ParsedType.get()); 14570 assert(!MapperType.isNull() && "Expect valid mapper type"); 14571 14572 // [OpenMP 5.0], 2.19.7.3 declare mapper Directive, Restrictions 14573 // The type must be of struct, union or class type in C and C++ 14574 if (!MapperType->isStructureOrClassType() && !MapperType->isUnionType()) { 14575 Diag(TyLoc, diag::err_omp_mapper_wrong_type); 14576 return QualType(); 14577 } 14578 return MapperType; 14579 } 14580 14581 OMPDeclareMapperDecl *Sema::ActOnOpenMPDeclareMapperDirectiveStart( 14582 Scope *S, DeclContext *DC, DeclarationName Name, QualType MapperType, 14583 SourceLocation StartLoc, DeclarationName VN, AccessSpecifier AS, 14584 Decl *PrevDeclInScope) { 14585 LookupResult Lookup(*this, Name, SourceLocation(), LookupOMPMapperName, 14586 forRedeclarationInCurContext()); 14587 // [OpenMP 5.0], 2.19.7.3 declare mapper Directive, Restrictions 14588 // A mapper-identifier may not be redeclared in the current scope for the 14589 // same type or for a type that is compatible according to the base language 14590 // rules. 14591 llvm::DenseMap<QualType, SourceLocation> PreviousRedeclTypes; 14592 OMPDeclareMapperDecl *PrevDMD = nullptr; 14593 bool InCompoundScope = true; 14594 if (S != nullptr) { 14595 // Find previous declaration with the same name not referenced in other 14596 // declarations. 14597 FunctionScopeInfo *ParentFn = getEnclosingFunction(); 14598 InCompoundScope = 14599 (ParentFn != nullptr) && !ParentFn->CompoundScopes.empty(); 14600 LookupName(Lookup, S); 14601 FilterLookupForScope(Lookup, DC, S, /*ConsiderLinkage=*/false, 14602 /*AllowInlineNamespace=*/false); 14603 llvm::DenseMap<OMPDeclareMapperDecl *, bool> UsedAsPrevious; 14604 LookupResult::Filter Filter = Lookup.makeFilter(); 14605 while (Filter.hasNext()) { 14606 auto *PrevDecl = cast<OMPDeclareMapperDecl>(Filter.next()); 14607 if (InCompoundScope) { 14608 auto I = UsedAsPrevious.find(PrevDecl); 14609 if (I == UsedAsPrevious.end()) 14610 UsedAsPrevious[PrevDecl] = false; 14611 if (OMPDeclareMapperDecl *D = PrevDecl->getPrevDeclInScope()) 14612 UsedAsPrevious[D] = true; 14613 } 14614 PreviousRedeclTypes[PrevDecl->getType().getCanonicalType()] = 14615 PrevDecl->getLocation(); 14616 } 14617 Filter.done(); 14618 if (InCompoundScope) { 14619 for (const auto &PrevData : UsedAsPrevious) { 14620 if (!PrevData.second) { 14621 PrevDMD = PrevData.first; 14622 break; 14623 } 14624 } 14625 } 14626 } else if (PrevDeclInScope) { 14627 auto *PrevDMDInScope = PrevDMD = 14628 cast<OMPDeclareMapperDecl>(PrevDeclInScope); 14629 do { 14630 PreviousRedeclTypes[PrevDMDInScope->getType().getCanonicalType()] = 14631 PrevDMDInScope->getLocation(); 14632 PrevDMDInScope = PrevDMDInScope->getPrevDeclInScope(); 14633 } while (PrevDMDInScope != nullptr); 14634 } 14635 const auto I = PreviousRedeclTypes.find(MapperType.getCanonicalType()); 14636 bool Invalid = false; 14637 if (I != PreviousRedeclTypes.end()) { 14638 Diag(StartLoc, diag::err_omp_declare_mapper_redefinition) 14639 << MapperType << Name; 14640 Diag(I->second, diag::note_previous_definition); 14641 Invalid = true; 14642 } 14643 auto *DMD = OMPDeclareMapperDecl::Create(Context, DC, StartLoc, Name, 14644 MapperType, VN, PrevDMD); 14645 DC->addDecl(DMD); 14646 DMD->setAccess(AS); 14647 if (Invalid) 14648 DMD->setInvalidDecl(); 14649 14650 // Enter new function scope. 14651 PushFunctionScope(); 14652 setFunctionHasBranchProtectedScope(); 14653 14654 CurContext = DMD; 14655 14656 return DMD; 14657 } 14658 14659 void Sema::ActOnOpenMPDeclareMapperDirectiveVarDecl(OMPDeclareMapperDecl *DMD, 14660 Scope *S, 14661 QualType MapperType, 14662 SourceLocation StartLoc, 14663 DeclarationName VN) { 14664 VarDecl *VD = buildVarDecl(*this, StartLoc, MapperType, VN.getAsString()); 14665 if (S) 14666 PushOnScopeChains(VD, S); 14667 else 14668 DMD->addDecl(VD); 14669 Expr *MapperVarRefExpr = buildDeclRefExpr(*this, VD, MapperType, StartLoc); 14670 DMD->setMapperVarRef(MapperVarRefExpr); 14671 } 14672 14673 Sema::DeclGroupPtrTy 14674 Sema::ActOnOpenMPDeclareMapperDirectiveEnd(OMPDeclareMapperDecl *D, Scope *S, 14675 ArrayRef<OMPClause *> ClauseList) { 14676 PopDeclContext(); 14677 PopFunctionScopeInfo(); 14678 14679 if (D) { 14680 if (S) 14681 PushOnScopeChains(D, S, /*AddToContext=*/false); 14682 D->CreateClauses(Context, ClauseList); 14683 } 14684 14685 return DeclGroupPtrTy::make(DeclGroupRef(D)); 14686 } 14687 14688 OMPClause *Sema::ActOnOpenMPNumTeamsClause(Expr *NumTeams, 14689 SourceLocation StartLoc, 14690 SourceLocation LParenLoc, 14691 SourceLocation EndLoc) { 14692 Expr *ValExpr = NumTeams; 14693 Stmt *HelperValStmt = nullptr; 14694 14695 // OpenMP [teams Constrcut, Restrictions] 14696 // The num_teams expression must evaluate to a positive integer value. 14697 if (!isNonNegativeIntegerValue(ValExpr, *this, OMPC_num_teams, 14698 /*StrictlyPositive=*/true)) 14699 return nullptr; 14700 14701 OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective(); 14702 OpenMPDirectiveKind CaptureRegion = 14703 getOpenMPCaptureRegionForClause(DKind, OMPC_num_teams); 14704 if (CaptureRegion != OMPD_unknown && !CurContext->isDependentContext()) { 14705 ValExpr = MakeFullExpr(ValExpr).get(); 14706 llvm::MapVector<const Expr *, DeclRefExpr *> Captures; 14707 ValExpr = tryBuildCapture(*this, ValExpr, Captures).get(); 14708 HelperValStmt = buildPreInits(Context, Captures); 14709 } 14710 14711 return new (Context) OMPNumTeamsClause(ValExpr, HelperValStmt, CaptureRegion, 14712 StartLoc, LParenLoc, EndLoc); 14713 } 14714 14715 OMPClause *Sema::ActOnOpenMPThreadLimitClause(Expr *ThreadLimit, 14716 SourceLocation StartLoc, 14717 SourceLocation LParenLoc, 14718 SourceLocation EndLoc) { 14719 Expr *ValExpr = ThreadLimit; 14720 Stmt *HelperValStmt = nullptr; 14721 14722 // OpenMP [teams Constrcut, Restrictions] 14723 // The thread_limit expression must evaluate to a positive integer value. 14724 if (!isNonNegativeIntegerValue(ValExpr, *this, OMPC_thread_limit, 14725 /*StrictlyPositive=*/true)) 14726 return nullptr; 14727 14728 OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective(); 14729 OpenMPDirectiveKind CaptureRegion = 14730 getOpenMPCaptureRegionForClause(DKind, OMPC_thread_limit); 14731 if (CaptureRegion != OMPD_unknown && !CurContext->isDependentContext()) { 14732 ValExpr = MakeFullExpr(ValExpr).get(); 14733 llvm::MapVector<const Expr *, DeclRefExpr *> Captures; 14734 ValExpr = tryBuildCapture(*this, ValExpr, Captures).get(); 14735 HelperValStmt = buildPreInits(Context, Captures); 14736 } 14737 14738 return new (Context) OMPThreadLimitClause( 14739 ValExpr, HelperValStmt, CaptureRegion, StartLoc, LParenLoc, EndLoc); 14740 } 14741 14742 OMPClause *Sema::ActOnOpenMPPriorityClause(Expr *Priority, 14743 SourceLocation StartLoc, 14744 SourceLocation LParenLoc, 14745 SourceLocation EndLoc) { 14746 Expr *ValExpr = Priority; 14747 14748 // OpenMP [2.9.1, task Constrcut] 14749 // The priority-value is a non-negative numerical scalar expression. 14750 if (!isNonNegativeIntegerValue(ValExpr, *this, OMPC_priority, 14751 /*StrictlyPositive=*/false)) 14752 return nullptr; 14753 14754 return new (Context) OMPPriorityClause(ValExpr, StartLoc, LParenLoc, EndLoc); 14755 } 14756 14757 OMPClause *Sema::ActOnOpenMPGrainsizeClause(Expr *Grainsize, 14758 SourceLocation StartLoc, 14759 SourceLocation LParenLoc, 14760 SourceLocation EndLoc) { 14761 Expr *ValExpr = Grainsize; 14762 14763 // OpenMP [2.9.2, taskloop Constrcut] 14764 // The parameter of the grainsize clause must be a positive integer 14765 // expression. 14766 if (!isNonNegativeIntegerValue(ValExpr, *this, OMPC_grainsize, 14767 /*StrictlyPositive=*/true)) 14768 return nullptr; 14769 14770 return new (Context) OMPGrainsizeClause(ValExpr, StartLoc, LParenLoc, EndLoc); 14771 } 14772 14773 OMPClause *Sema::ActOnOpenMPNumTasksClause(Expr *NumTasks, 14774 SourceLocation StartLoc, 14775 SourceLocation LParenLoc, 14776 SourceLocation EndLoc) { 14777 Expr *ValExpr = NumTasks; 14778 14779 // OpenMP [2.9.2, taskloop Constrcut] 14780 // The parameter of the num_tasks clause must be a positive integer 14781 // expression. 14782 if (!isNonNegativeIntegerValue(ValExpr, *this, OMPC_num_tasks, 14783 /*StrictlyPositive=*/true)) 14784 return nullptr; 14785 14786 return new (Context) OMPNumTasksClause(ValExpr, StartLoc, LParenLoc, EndLoc); 14787 } 14788 14789 OMPClause *Sema::ActOnOpenMPHintClause(Expr *Hint, SourceLocation StartLoc, 14790 SourceLocation LParenLoc, 14791 SourceLocation EndLoc) { 14792 // OpenMP [2.13.2, critical construct, Description] 14793 // ... where hint-expression is an integer constant expression that evaluates 14794 // to a valid lock hint. 14795 ExprResult HintExpr = VerifyPositiveIntegerConstantInClause(Hint, OMPC_hint); 14796 if (HintExpr.isInvalid()) 14797 return nullptr; 14798 return new (Context) 14799 OMPHintClause(HintExpr.get(), StartLoc, LParenLoc, EndLoc); 14800 } 14801 14802 OMPClause *Sema::ActOnOpenMPDistScheduleClause( 14803 OpenMPDistScheduleClauseKind Kind, Expr *ChunkSize, SourceLocation StartLoc, 14804 SourceLocation LParenLoc, SourceLocation KindLoc, SourceLocation CommaLoc, 14805 SourceLocation EndLoc) { 14806 if (Kind == OMPC_DIST_SCHEDULE_unknown) { 14807 std::string Values; 14808 Values += "'"; 14809 Values += getOpenMPSimpleClauseTypeName(OMPC_dist_schedule, 0); 14810 Values += "'"; 14811 Diag(KindLoc, diag::err_omp_unexpected_clause_value) 14812 << Values << getOpenMPClauseName(OMPC_dist_schedule); 14813 return nullptr; 14814 } 14815 Expr *ValExpr = ChunkSize; 14816 Stmt *HelperValStmt = nullptr; 14817 if (ChunkSize) { 14818 if (!ChunkSize->isValueDependent() && !ChunkSize->isTypeDependent() && 14819 !ChunkSize->isInstantiationDependent() && 14820 !ChunkSize->containsUnexpandedParameterPack()) { 14821 SourceLocation ChunkSizeLoc = ChunkSize->getBeginLoc(); 14822 ExprResult Val = 14823 PerformOpenMPImplicitIntegerConversion(ChunkSizeLoc, ChunkSize); 14824 if (Val.isInvalid()) 14825 return nullptr; 14826 14827 ValExpr = Val.get(); 14828 14829 // OpenMP [2.7.1, Restrictions] 14830 // chunk_size must be a loop invariant integer expression with a positive 14831 // value. 14832 llvm::APSInt Result; 14833 if (ValExpr->isIntegerConstantExpr(Result, Context)) { 14834 if (Result.isSigned() && !Result.isStrictlyPositive()) { 14835 Diag(ChunkSizeLoc, diag::err_omp_negative_expression_in_clause) 14836 << "dist_schedule" << ChunkSize->getSourceRange(); 14837 return nullptr; 14838 } 14839 } else if (getOpenMPCaptureRegionForClause( 14840 DSAStack->getCurrentDirective(), OMPC_dist_schedule) != 14841 OMPD_unknown && 14842 !CurContext->isDependentContext()) { 14843 ValExpr = MakeFullExpr(ValExpr).get(); 14844 llvm::MapVector<const Expr *, DeclRefExpr *> Captures; 14845 ValExpr = tryBuildCapture(*this, ValExpr, Captures).get(); 14846 HelperValStmt = buildPreInits(Context, Captures); 14847 } 14848 } 14849 } 14850 14851 return new (Context) 14852 OMPDistScheduleClause(StartLoc, LParenLoc, KindLoc, CommaLoc, EndLoc, 14853 Kind, ValExpr, HelperValStmt); 14854 } 14855 14856 OMPClause *Sema::ActOnOpenMPDefaultmapClause( 14857 OpenMPDefaultmapClauseModifier M, OpenMPDefaultmapClauseKind Kind, 14858 SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation MLoc, 14859 SourceLocation KindLoc, SourceLocation EndLoc) { 14860 // OpenMP 4.5 only supports 'defaultmap(tofrom: scalar)' 14861 if (M != OMPC_DEFAULTMAP_MODIFIER_tofrom || Kind != OMPC_DEFAULTMAP_scalar) { 14862 std::string Value; 14863 SourceLocation Loc; 14864 Value += "'"; 14865 if (M != OMPC_DEFAULTMAP_MODIFIER_tofrom) { 14866 Value += getOpenMPSimpleClauseTypeName(OMPC_defaultmap, 14867 OMPC_DEFAULTMAP_MODIFIER_tofrom); 14868 Loc = MLoc; 14869 } else { 14870 Value += getOpenMPSimpleClauseTypeName(OMPC_defaultmap, 14871 OMPC_DEFAULTMAP_scalar); 14872 Loc = KindLoc; 14873 } 14874 Value += "'"; 14875 Diag(Loc, diag::err_omp_unexpected_clause_value) 14876 << Value << getOpenMPClauseName(OMPC_defaultmap); 14877 return nullptr; 14878 } 14879 DSAStack->setDefaultDMAToFromScalar(StartLoc); 14880 14881 return new (Context) 14882 OMPDefaultmapClause(StartLoc, LParenLoc, MLoc, KindLoc, EndLoc, Kind, M); 14883 } 14884 14885 bool Sema::ActOnStartOpenMPDeclareTargetDirective(SourceLocation Loc) { 14886 DeclContext *CurLexicalContext = getCurLexicalContext(); 14887 if (!CurLexicalContext->isFileContext() && 14888 !CurLexicalContext->isExternCContext() && 14889 !CurLexicalContext->isExternCXXContext() && 14890 !isa<CXXRecordDecl>(CurLexicalContext) && 14891 !isa<ClassTemplateDecl>(CurLexicalContext) && 14892 !isa<ClassTemplatePartialSpecializationDecl>(CurLexicalContext) && 14893 !isa<ClassTemplateSpecializationDecl>(CurLexicalContext)) { 14894 Diag(Loc, diag::err_omp_region_not_file_context); 14895 return false; 14896 } 14897 ++DeclareTargetNestingLevel; 14898 return true; 14899 } 14900 14901 void Sema::ActOnFinishOpenMPDeclareTargetDirective() { 14902 assert(DeclareTargetNestingLevel > 0 && 14903 "Unexpected ActOnFinishOpenMPDeclareTargetDirective"); 14904 --DeclareTargetNestingLevel; 14905 } 14906 14907 void Sema::ActOnOpenMPDeclareTargetName(Scope *CurScope, 14908 CXXScopeSpec &ScopeSpec, 14909 const DeclarationNameInfo &Id, 14910 OMPDeclareTargetDeclAttr::MapTypeTy MT, 14911 NamedDeclSetType &SameDirectiveDecls) { 14912 LookupResult Lookup(*this, Id, LookupOrdinaryName); 14913 LookupParsedName(Lookup, CurScope, &ScopeSpec, true); 14914 14915 if (Lookup.isAmbiguous()) 14916 return; 14917 Lookup.suppressDiagnostics(); 14918 14919 if (!Lookup.isSingleResult()) { 14920 VarOrFuncDeclFilterCCC CCC(*this); 14921 if (TypoCorrection Corrected = 14922 CorrectTypo(Id, LookupOrdinaryName, CurScope, nullptr, CCC, 14923 CTK_ErrorRecovery)) { 14924 diagnoseTypo(Corrected, PDiag(diag::err_undeclared_var_use_suggest) 14925 << Id.getName()); 14926 checkDeclIsAllowedInOpenMPTarget(nullptr, Corrected.getCorrectionDecl()); 14927 return; 14928 } 14929 14930 Diag(Id.getLoc(), diag::err_undeclared_var_use) << Id.getName(); 14931 return; 14932 } 14933 14934 NamedDecl *ND = Lookup.getAsSingle<NamedDecl>(); 14935 if (isa<VarDecl>(ND) || isa<FunctionDecl>(ND) || 14936 isa<FunctionTemplateDecl>(ND)) { 14937 if (!SameDirectiveDecls.insert(cast<NamedDecl>(ND->getCanonicalDecl()))) 14938 Diag(Id.getLoc(), diag::err_omp_declare_target_multiple) << Id.getName(); 14939 llvm::Optional<OMPDeclareTargetDeclAttr::MapTypeTy> Res = 14940 OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration( 14941 cast<ValueDecl>(ND)); 14942 if (!Res) { 14943 auto *A = OMPDeclareTargetDeclAttr::CreateImplicit(Context, MT); 14944 ND->addAttr(A); 14945 if (ASTMutationListener *ML = Context.getASTMutationListener()) 14946 ML->DeclarationMarkedOpenMPDeclareTarget(ND, A); 14947 checkDeclIsAllowedInOpenMPTarget(nullptr, ND, Id.getLoc()); 14948 } else if (*Res != MT) { 14949 Diag(Id.getLoc(), diag::err_omp_declare_target_to_and_link) 14950 << Id.getName(); 14951 } 14952 } else { 14953 Diag(Id.getLoc(), diag::err_omp_invalid_target_decl) << Id.getName(); 14954 } 14955 } 14956 14957 static void checkDeclInTargetContext(SourceLocation SL, SourceRange SR, 14958 Sema &SemaRef, Decl *D) { 14959 if (!D || !isa<VarDecl>(D)) 14960 return; 14961 auto *VD = cast<VarDecl>(D); 14962 if (OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD)) 14963 return; 14964 SemaRef.Diag(VD->getLocation(), diag::warn_omp_not_in_target_context); 14965 SemaRef.Diag(SL, diag::note_used_here) << SR; 14966 } 14967 14968 static bool checkValueDeclInTarget(SourceLocation SL, SourceRange SR, 14969 Sema &SemaRef, DSAStackTy *Stack, 14970 ValueDecl *VD) { 14971 return VD->hasAttr<OMPDeclareTargetDeclAttr>() || 14972 checkTypeMappable(SL, SR, SemaRef, Stack, VD->getType(), 14973 /*FullCheck=*/false); 14974 } 14975 14976 void Sema::checkDeclIsAllowedInOpenMPTarget(Expr *E, Decl *D, 14977 SourceLocation IdLoc) { 14978 if (!D || D->isInvalidDecl()) 14979 return; 14980 SourceRange SR = E ? E->getSourceRange() : D->getSourceRange(); 14981 SourceLocation SL = E ? E->getBeginLoc() : D->getLocation(); 14982 if (auto *VD = dyn_cast<VarDecl>(D)) { 14983 // Only global variables can be marked as declare target. 14984 if (!VD->isFileVarDecl() && !VD->isStaticLocal() && 14985 !VD->isStaticDataMember()) 14986 return; 14987 // 2.10.6: threadprivate variable cannot appear in a declare target 14988 // directive. 14989 if (DSAStack->isThreadPrivate(VD)) { 14990 Diag(SL, diag::err_omp_threadprivate_in_target); 14991 reportOriginalDsa(*this, DSAStack, VD, DSAStack->getTopDSA(VD, false)); 14992 return; 14993 } 14994 } 14995 if (const auto *FTD = dyn_cast<FunctionTemplateDecl>(D)) 14996 D = FTD->getTemplatedDecl(); 14997 if (const auto *FD = dyn_cast<FunctionDecl>(D)) { 14998 llvm::Optional<OMPDeclareTargetDeclAttr::MapTypeTy> Res = 14999 OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(FD); 15000 if (Res && *Res == OMPDeclareTargetDeclAttr::MT_Link) { 15001 assert(IdLoc.isValid() && "Source location is expected"); 15002 Diag(IdLoc, diag::err_omp_function_in_link_clause); 15003 Diag(FD->getLocation(), diag::note_defined_here) << FD; 15004 return; 15005 } 15006 } 15007 if (auto *VD = dyn_cast<ValueDecl>(D)) { 15008 // Problem if any with var declared with incomplete type will be reported 15009 // as normal, so no need to check it here. 15010 if ((E || !VD->getType()->isIncompleteType()) && 15011 !checkValueDeclInTarget(SL, SR, *this, DSAStack, VD)) 15012 return; 15013 if (!E && !OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD)) { 15014 // Checking declaration inside declare target region. 15015 if (isa<VarDecl>(D) || isa<FunctionDecl>(D) || 15016 isa<FunctionTemplateDecl>(D)) { 15017 auto *A = OMPDeclareTargetDeclAttr::CreateImplicit( 15018 Context, OMPDeclareTargetDeclAttr::MT_To); 15019 D->addAttr(A); 15020 if (ASTMutationListener *ML = Context.getASTMutationListener()) 15021 ML->DeclarationMarkedOpenMPDeclareTarget(D, A); 15022 } 15023 return; 15024 } 15025 } 15026 if (!E) 15027 return; 15028 checkDeclInTargetContext(E->getExprLoc(), E->getSourceRange(), *this, D); 15029 } 15030 15031 OMPClause *Sema::ActOnOpenMPToClause(ArrayRef<Expr *> VarList, 15032 CXXScopeSpec &MapperIdScopeSpec, 15033 DeclarationNameInfo &MapperId, 15034 const OMPVarListLocTy &Locs, 15035 ArrayRef<Expr *> UnresolvedMappers) { 15036 MappableVarListInfo MVLI(VarList); 15037 checkMappableExpressionList(*this, DSAStack, OMPC_to, MVLI, Locs.StartLoc, 15038 MapperIdScopeSpec, MapperId, UnresolvedMappers); 15039 if (MVLI.ProcessedVarList.empty()) 15040 return nullptr; 15041 15042 return OMPToClause::Create( 15043 Context, Locs, MVLI.ProcessedVarList, MVLI.VarBaseDeclarations, 15044 MVLI.VarComponents, MVLI.UDMapperList, 15045 MapperIdScopeSpec.getWithLocInContext(Context), MapperId); 15046 } 15047 15048 OMPClause *Sema::ActOnOpenMPFromClause(ArrayRef<Expr *> VarList, 15049 CXXScopeSpec &MapperIdScopeSpec, 15050 DeclarationNameInfo &MapperId, 15051 const OMPVarListLocTy &Locs, 15052 ArrayRef<Expr *> UnresolvedMappers) { 15053 MappableVarListInfo MVLI(VarList); 15054 checkMappableExpressionList(*this, DSAStack, OMPC_from, MVLI, Locs.StartLoc, 15055 MapperIdScopeSpec, MapperId, UnresolvedMappers); 15056 if (MVLI.ProcessedVarList.empty()) 15057 return nullptr; 15058 15059 return OMPFromClause::Create( 15060 Context, Locs, MVLI.ProcessedVarList, MVLI.VarBaseDeclarations, 15061 MVLI.VarComponents, MVLI.UDMapperList, 15062 MapperIdScopeSpec.getWithLocInContext(Context), MapperId); 15063 } 15064 15065 OMPClause *Sema::ActOnOpenMPUseDevicePtrClause(ArrayRef<Expr *> VarList, 15066 const OMPVarListLocTy &Locs) { 15067 MappableVarListInfo MVLI(VarList); 15068 SmallVector<Expr *, 8> PrivateCopies; 15069 SmallVector<Expr *, 8> Inits; 15070 15071 for (Expr *RefExpr : VarList) { 15072 assert(RefExpr && "NULL expr in OpenMP use_device_ptr clause."); 15073 SourceLocation ELoc; 15074 SourceRange ERange; 15075 Expr *SimpleRefExpr = RefExpr; 15076 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange); 15077 if (Res.second) { 15078 // It will be analyzed later. 15079 MVLI.ProcessedVarList.push_back(RefExpr); 15080 PrivateCopies.push_back(nullptr); 15081 Inits.push_back(nullptr); 15082 } 15083 ValueDecl *D = Res.first; 15084 if (!D) 15085 continue; 15086 15087 QualType Type = D->getType(); 15088 Type = Type.getNonReferenceType().getUnqualifiedType(); 15089 15090 auto *VD = dyn_cast<VarDecl>(D); 15091 15092 // Item should be a pointer or reference to pointer. 15093 if (!Type->isPointerType()) { 15094 Diag(ELoc, diag::err_omp_usedeviceptr_not_a_pointer) 15095 << 0 << RefExpr->getSourceRange(); 15096 continue; 15097 } 15098 15099 // Build the private variable and the expression that refers to it. 15100 auto VDPrivate = 15101 buildVarDecl(*this, ELoc, Type, D->getName(), 15102 D->hasAttrs() ? &D->getAttrs() : nullptr, 15103 VD ? cast<DeclRefExpr>(SimpleRefExpr) : nullptr); 15104 if (VDPrivate->isInvalidDecl()) 15105 continue; 15106 15107 CurContext->addDecl(VDPrivate); 15108 DeclRefExpr *VDPrivateRefExpr = buildDeclRefExpr( 15109 *this, VDPrivate, RefExpr->getType().getUnqualifiedType(), ELoc); 15110 15111 // Add temporary variable to initialize the private copy of the pointer. 15112 VarDecl *VDInit = 15113 buildVarDecl(*this, RefExpr->getExprLoc(), Type, ".devptr.temp"); 15114 DeclRefExpr *VDInitRefExpr = buildDeclRefExpr( 15115 *this, VDInit, RefExpr->getType(), RefExpr->getExprLoc()); 15116 AddInitializerToDecl(VDPrivate, 15117 DefaultLvalueConversion(VDInitRefExpr).get(), 15118 /*DirectInit=*/false); 15119 15120 // If required, build a capture to implement the privatization initialized 15121 // with the current list item value. 15122 DeclRefExpr *Ref = nullptr; 15123 if (!VD) 15124 Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/true); 15125 MVLI.ProcessedVarList.push_back(VD ? RefExpr->IgnoreParens() : Ref); 15126 PrivateCopies.push_back(VDPrivateRefExpr); 15127 Inits.push_back(VDInitRefExpr); 15128 15129 // We need to add a data sharing attribute for this variable to make sure it 15130 // is correctly captured. A variable that shows up in a use_device_ptr has 15131 // similar properties of a first private variable. 15132 DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_firstprivate, Ref); 15133 15134 // Create a mappable component for the list item. List items in this clause 15135 // only need a component. 15136 MVLI.VarBaseDeclarations.push_back(D); 15137 MVLI.VarComponents.resize(MVLI.VarComponents.size() + 1); 15138 MVLI.VarComponents.back().push_back( 15139 OMPClauseMappableExprCommon::MappableComponent(SimpleRefExpr, D)); 15140 } 15141 15142 if (MVLI.ProcessedVarList.empty()) 15143 return nullptr; 15144 15145 return OMPUseDevicePtrClause::Create( 15146 Context, Locs, MVLI.ProcessedVarList, PrivateCopies, Inits, 15147 MVLI.VarBaseDeclarations, MVLI.VarComponents); 15148 } 15149 15150 OMPClause *Sema::ActOnOpenMPIsDevicePtrClause(ArrayRef<Expr *> VarList, 15151 const OMPVarListLocTy &Locs) { 15152 MappableVarListInfo MVLI(VarList); 15153 for (Expr *RefExpr : VarList) { 15154 assert(RefExpr && "NULL expr in OpenMP is_device_ptr clause."); 15155 SourceLocation ELoc; 15156 SourceRange ERange; 15157 Expr *SimpleRefExpr = RefExpr; 15158 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange); 15159 if (Res.second) { 15160 // It will be analyzed later. 15161 MVLI.ProcessedVarList.push_back(RefExpr); 15162 } 15163 ValueDecl *D = Res.first; 15164 if (!D) 15165 continue; 15166 15167 QualType Type = D->getType(); 15168 // item should be a pointer or array or reference to pointer or array 15169 if (!Type.getNonReferenceType()->isPointerType() && 15170 !Type.getNonReferenceType()->isArrayType()) { 15171 Diag(ELoc, diag::err_omp_argument_type_isdeviceptr) 15172 << 0 << RefExpr->getSourceRange(); 15173 continue; 15174 } 15175 15176 // Check if the declaration in the clause does not show up in any data 15177 // sharing attribute. 15178 DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, /*FromParent=*/false); 15179 if (isOpenMPPrivate(DVar.CKind)) { 15180 Diag(ELoc, diag::err_omp_variable_in_given_clause_and_dsa) 15181 << getOpenMPClauseName(DVar.CKind) 15182 << getOpenMPClauseName(OMPC_is_device_ptr) 15183 << getOpenMPDirectiveName(DSAStack->getCurrentDirective()); 15184 reportOriginalDsa(*this, DSAStack, D, DVar); 15185 continue; 15186 } 15187 15188 const Expr *ConflictExpr; 15189 if (DSAStack->checkMappableExprComponentListsForDecl( 15190 D, /*CurrentRegionOnly=*/true, 15191 [&ConflictExpr]( 15192 OMPClauseMappableExprCommon::MappableExprComponentListRef R, 15193 OpenMPClauseKind) -> bool { 15194 ConflictExpr = R.front().getAssociatedExpression(); 15195 return true; 15196 })) { 15197 Diag(ELoc, diag::err_omp_map_shared_storage) << RefExpr->getSourceRange(); 15198 Diag(ConflictExpr->getExprLoc(), diag::note_used_here) 15199 << ConflictExpr->getSourceRange(); 15200 continue; 15201 } 15202 15203 // Store the components in the stack so that they can be used to check 15204 // against other clauses later on. 15205 OMPClauseMappableExprCommon::MappableComponent MC(SimpleRefExpr, D); 15206 DSAStack->addMappableExpressionComponents( 15207 D, MC, /*WhereFoundClauseKind=*/OMPC_is_device_ptr); 15208 15209 // Record the expression we've just processed. 15210 MVLI.ProcessedVarList.push_back(SimpleRefExpr); 15211 15212 // Create a mappable component for the list item. List items in this clause 15213 // only need a component. We use a null declaration to signal fields in 15214 // 'this'. 15215 assert((isa<DeclRefExpr>(SimpleRefExpr) || 15216 isa<CXXThisExpr>(cast<MemberExpr>(SimpleRefExpr)->getBase())) && 15217 "Unexpected device pointer expression!"); 15218 MVLI.VarBaseDeclarations.push_back( 15219 isa<DeclRefExpr>(SimpleRefExpr) ? D : nullptr); 15220 MVLI.VarComponents.resize(MVLI.VarComponents.size() + 1); 15221 MVLI.VarComponents.back().push_back(MC); 15222 } 15223 15224 if (MVLI.ProcessedVarList.empty()) 15225 return nullptr; 15226 15227 return OMPIsDevicePtrClause::Create(Context, Locs, MVLI.ProcessedVarList, 15228 MVLI.VarBaseDeclarations, 15229 MVLI.VarComponents); 15230 } 15231 15232 OMPClause *Sema::ActOnOpenMPAllocateClause( 15233 Expr *Allocator, ArrayRef<Expr *> VarList, SourceLocation StartLoc, 15234 SourceLocation ColonLoc, SourceLocation LParenLoc, SourceLocation EndLoc) { 15235 if (Allocator) { 15236 // OpenMP [2.11.4 allocate Clause, Description] 15237 // allocator is an expression of omp_allocator_handle_t type. 15238 if (!findOMPAllocatorHandleT(*this, Allocator->getExprLoc(), DSAStack)) 15239 return nullptr; 15240 15241 ExprResult AllocatorRes = DefaultLvalueConversion(Allocator); 15242 if (AllocatorRes.isInvalid()) 15243 return nullptr; 15244 AllocatorRes = PerformImplicitConversion(AllocatorRes.get(), 15245 DSAStack->getOMPAllocatorHandleT(), 15246 Sema::AA_Initializing, 15247 /*AllowExplicit=*/true); 15248 if (AllocatorRes.isInvalid()) 15249 return nullptr; 15250 Allocator = AllocatorRes.get(); 15251 } else { 15252 // OpenMP 5.0, 2.11.4 allocate Clause, Restrictions. 15253 // allocate clauses that appear on a target construct or on constructs in a 15254 // target region must specify an allocator expression unless a requires 15255 // directive with the dynamic_allocators clause is present in the same 15256 // compilation unit. 15257 if (LangOpts.OpenMPIsDevice && 15258 !DSAStack->hasRequiresDeclWithClause<OMPDynamicAllocatorsClause>()) 15259 targetDiag(StartLoc, diag::err_expected_allocator_expression); 15260 } 15261 // Analyze and build list of variables. 15262 SmallVector<Expr *, 8> Vars; 15263 for (Expr *RefExpr : VarList) { 15264 assert(RefExpr && "NULL expr in OpenMP private clause."); 15265 SourceLocation ELoc; 15266 SourceRange ERange; 15267 Expr *SimpleRefExpr = RefExpr; 15268 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange); 15269 if (Res.second) { 15270 // It will be analyzed later. 15271 Vars.push_back(RefExpr); 15272 } 15273 ValueDecl *D = Res.first; 15274 if (!D) 15275 continue; 15276 15277 auto *VD = dyn_cast<VarDecl>(D); 15278 DeclRefExpr *Ref = nullptr; 15279 if (!VD && !CurContext->isDependentContext()) 15280 Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/false); 15281 Vars.push_back((VD || CurContext->isDependentContext()) 15282 ? RefExpr->IgnoreParens() 15283 : Ref); 15284 } 15285 15286 if (Vars.empty()) 15287 return nullptr; 15288 15289 return OMPAllocateClause::Create(Context, StartLoc, LParenLoc, Allocator, 15290 ColonLoc, EndLoc, Vars); 15291 } 15292