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/OpenMPClause.h" 22 #include "clang/AST/StmtCXX.h" 23 #include "clang/AST/StmtOpenMP.h" 24 #include "clang/AST/StmtVisitor.h" 25 #include "clang/AST/TypeOrdering.h" 26 #include "clang/Basic/DiagnosticSema.h" 27 #include "clang/Basic/OpenMPKinds.h" 28 #include "clang/Basic/PartialDiagnostic.h" 29 #include "clang/Basic/TargetInfo.h" 30 #include "clang/Sema/Initialization.h" 31 #include "clang/Sema/Lookup.h" 32 #include "clang/Sema/Scope.h" 33 #include "clang/Sema/ScopeInfo.h" 34 #include "clang/Sema/SemaInternal.h" 35 #include "llvm/ADT/IndexedMap.h" 36 #include "llvm/ADT/PointerEmbeddedInt.h" 37 #include "llvm/ADT/STLExtras.h" 38 #include "llvm/Frontend/OpenMP/OMPConstants.h" 39 #include <set> 40 41 using namespace clang; 42 using namespace llvm::omp; 43 44 //===----------------------------------------------------------------------===// 45 // Stack of data-sharing attributes for variables 46 //===----------------------------------------------------------------------===// 47 48 static const Expr *checkMapClauseExpressionBase( 49 Sema &SemaRef, Expr *E, 50 OMPClauseMappableExprCommon::MappableExprComponentList &CurComponents, 51 OpenMPClauseKind CKind, bool NoDiagnose); 52 53 namespace { 54 /// Default data sharing attributes, which can be applied to directive. 55 enum DefaultDataSharingAttributes { 56 DSA_unspecified = 0, /// Data sharing attribute not specified. 57 DSA_none = 1 << 0, /// Default data sharing attribute 'none'. 58 DSA_shared = 1 << 1, /// Default data sharing attribute 'shared'. 59 DSA_firstprivate = 1 << 2, /// Default data sharing attribute 'firstprivate'. 60 }; 61 62 /// Stack for tracking declarations used in OpenMP directives and 63 /// clauses and their data-sharing attributes. 64 class DSAStackTy { 65 public: 66 struct DSAVarData { 67 OpenMPDirectiveKind DKind = OMPD_unknown; 68 OpenMPClauseKind CKind = OMPC_unknown; 69 unsigned Modifier = 0; 70 const Expr *RefExpr = nullptr; 71 DeclRefExpr *PrivateCopy = nullptr; 72 SourceLocation ImplicitDSALoc; 73 DSAVarData() = default; 74 DSAVarData(OpenMPDirectiveKind DKind, OpenMPClauseKind CKind, 75 const Expr *RefExpr, DeclRefExpr *PrivateCopy, 76 SourceLocation ImplicitDSALoc, unsigned Modifier) 77 : DKind(DKind), CKind(CKind), Modifier(Modifier), RefExpr(RefExpr), 78 PrivateCopy(PrivateCopy), ImplicitDSALoc(ImplicitDSALoc) {} 79 }; 80 using OperatorOffsetTy = 81 llvm::SmallVector<std::pair<Expr *, OverloadedOperatorKind>, 4>; 82 using DoacrossDependMapTy = 83 llvm::DenseMap<OMPDependClause *, OperatorOffsetTy>; 84 /// Kind of the declaration used in the uses_allocators clauses. 85 enum class UsesAllocatorsDeclKind { 86 /// Predefined allocator 87 PredefinedAllocator, 88 /// User-defined allocator 89 UserDefinedAllocator, 90 /// The declaration that represent allocator trait 91 AllocatorTrait, 92 }; 93 94 private: 95 struct DSAInfo { 96 OpenMPClauseKind Attributes = OMPC_unknown; 97 unsigned Modifier = 0; 98 /// Pointer to a reference expression and a flag which shows that the 99 /// variable is marked as lastprivate(true) or not (false). 100 llvm::PointerIntPair<const Expr *, 1, bool> RefExpr; 101 DeclRefExpr *PrivateCopy = nullptr; 102 }; 103 using DeclSAMapTy = llvm::SmallDenseMap<const ValueDecl *, DSAInfo, 8>; 104 using UsedRefMapTy = llvm::SmallDenseMap<const ValueDecl *, const Expr *, 8>; 105 using LCDeclInfo = std::pair<unsigned, VarDecl *>; 106 using LoopControlVariablesMapTy = 107 llvm::SmallDenseMap<const ValueDecl *, LCDeclInfo, 8>; 108 /// Struct that associates a component with the clause kind where they are 109 /// found. 110 struct MappedExprComponentTy { 111 OMPClauseMappableExprCommon::MappableExprComponentLists Components; 112 OpenMPClauseKind Kind = OMPC_unknown; 113 }; 114 using MappedExprComponentsTy = 115 llvm::DenseMap<const ValueDecl *, MappedExprComponentTy>; 116 using CriticalsWithHintsTy = 117 llvm::StringMap<std::pair<const OMPCriticalDirective *, llvm::APSInt>>; 118 struct ReductionData { 119 using BOKPtrType = llvm::PointerEmbeddedInt<BinaryOperatorKind, 16>; 120 SourceRange ReductionRange; 121 llvm::PointerUnion<const Expr *, BOKPtrType> ReductionOp; 122 ReductionData() = default; 123 void set(BinaryOperatorKind BO, SourceRange RR) { 124 ReductionRange = RR; 125 ReductionOp = BO; 126 } 127 void set(const Expr *RefExpr, SourceRange RR) { 128 ReductionRange = RR; 129 ReductionOp = RefExpr; 130 } 131 }; 132 using DeclReductionMapTy = 133 llvm::SmallDenseMap<const ValueDecl *, ReductionData, 4>; 134 struct DefaultmapInfo { 135 OpenMPDefaultmapClauseModifier ImplicitBehavior = 136 OMPC_DEFAULTMAP_MODIFIER_unknown; 137 SourceLocation SLoc; 138 DefaultmapInfo() = default; 139 DefaultmapInfo(OpenMPDefaultmapClauseModifier M, SourceLocation Loc) 140 : ImplicitBehavior(M), SLoc(Loc) {} 141 }; 142 143 struct SharingMapTy { 144 DeclSAMapTy SharingMap; 145 DeclReductionMapTy ReductionMap; 146 UsedRefMapTy AlignedMap; 147 UsedRefMapTy NontemporalMap; 148 MappedExprComponentsTy MappedExprComponents; 149 LoopControlVariablesMapTy LCVMap; 150 DefaultDataSharingAttributes DefaultAttr = DSA_unspecified; 151 SourceLocation DefaultAttrLoc; 152 DefaultmapInfo DefaultmapMap[OMPC_DEFAULTMAP_unknown]; 153 OpenMPDirectiveKind Directive = OMPD_unknown; 154 DeclarationNameInfo DirectiveName; 155 Scope *CurScope = nullptr; 156 SourceLocation ConstructLoc; 157 /// Set of 'depend' clauses with 'sink|source' dependence kind. Required to 158 /// get the data (loop counters etc.) about enclosing loop-based construct. 159 /// This data is required during codegen. 160 DoacrossDependMapTy DoacrossDepends; 161 /// First argument (Expr *) contains optional argument of the 162 /// 'ordered' clause, the second one is true if the regions has 'ordered' 163 /// clause, false otherwise. 164 llvm::Optional<std::pair<const Expr *, OMPOrderedClause *>> OrderedRegion; 165 unsigned AssociatedLoops = 1; 166 bool HasMutipleLoops = false; 167 const Decl *PossiblyLoopCounter = nullptr; 168 bool NowaitRegion = false; 169 bool CancelRegion = false; 170 bool LoopStart = false; 171 bool BodyComplete = false; 172 SourceLocation PrevScanLocation; 173 SourceLocation PrevOrderedLocation; 174 SourceLocation InnerTeamsRegionLoc; 175 /// Reference to the taskgroup task_reduction reference expression. 176 Expr *TaskgroupReductionRef = nullptr; 177 llvm::DenseSet<QualType> MappedClassesQualTypes; 178 SmallVector<Expr *, 4> InnerUsedAllocators; 179 llvm::DenseSet<CanonicalDeclPtr<Decl>> ImplicitTaskFirstprivates; 180 /// List of globals marked as declare target link in this target region 181 /// (isOpenMPTargetExecutionDirective(Directive) == true). 182 llvm::SmallVector<DeclRefExpr *, 4> DeclareTargetLinkVarDecls; 183 /// List of decls used in inclusive/exclusive clauses of the scan directive. 184 llvm::DenseSet<CanonicalDeclPtr<Decl>> UsedInScanDirective; 185 llvm::DenseMap<CanonicalDeclPtr<const Decl>, UsesAllocatorsDeclKind> 186 UsesAllocatorsDecls; 187 SharingMapTy(OpenMPDirectiveKind DKind, DeclarationNameInfo Name, 188 Scope *CurScope, SourceLocation Loc) 189 : Directive(DKind), DirectiveName(Name), CurScope(CurScope), 190 ConstructLoc(Loc) {} 191 SharingMapTy() = default; 192 }; 193 194 using StackTy = SmallVector<SharingMapTy, 4>; 195 196 /// Stack of used declaration and their data-sharing attributes. 197 DeclSAMapTy Threadprivates; 198 const FunctionScopeInfo *CurrentNonCapturingFunctionScope = nullptr; 199 SmallVector<std::pair<StackTy, const FunctionScopeInfo *>, 4> Stack; 200 /// true, if check for DSA must be from parent directive, false, if 201 /// from current directive. 202 OpenMPClauseKind ClauseKindMode = OMPC_unknown; 203 Sema &SemaRef; 204 bool ForceCapturing = false; 205 /// true if all the variables in the target executable directives must be 206 /// captured by reference. 207 bool ForceCaptureByReferenceInTargetExecutable = false; 208 CriticalsWithHintsTy Criticals; 209 unsigned IgnoredStackElements = 0; 210 211 /// Iterators over the stack iterate in order from innermost to outermost 212 /// directive. 213 using const_iterator = StackTy::const_reverse_iterator; 214 const_iterator begin() const { 215 return Stack.empty() ? const_iterator() 216 : Stack.back().first.rbegin() + IgnoredStackElements; 217 } 218 const_iterator end() const { 219 return Stack.empty() ? const_iterator() : Stack.back().first.rend(); 220 } 221 using iterator = StackTy::reverse_iterator; 222 iterator begin() { 223 return Stack.empty() ? iterator() 224 : Stack.back().first.rbegin() + IgnoredStackElements; 225 } 226 iterator end() { 227 return Stack.empty() ? iterator() : Stack.back().first.rend(); 228 } 229 230 // Convenience operations to get at the elements of the stack. 231 232 bool isStackEmpty() const { 233 return Stack.empty() || 234 Stack.back().second != CurrentNonCapturingFunctionScope || 235 Stack.back().first.size() <= IgnoredStackElements; 236 } 237 size_t getStackSize() const { 238 return isStackEmpty() ? 0 239 : Stack.back().first.size() - IgnoredStackElements; 240 } 241 242 SharingMapTy *getTopOfStackOrNull() { 243 size_t Size = getStackSize(); 244 if (Size == 0) 245 return nullptr; 246 return &Stack.back().first[Size - 1]; 247 } 248 const SharingMapTy *getTopOfStackOrNull() const { 249 return const_cast<DSAStackTy&>(*this).getTopOfStackOrNull(); 250 } 251 SharingMapTy &getTopOfStack() { 252 assert(!isStackEmpty() && "no current directive"); 253 return *getTopOfStackOrNull(); 254 } 255 const SharingMapTy &getTopOfStack() const { 256 return const_cast<DSAStackTy&>(*this).getTopOfStack(); 257 } 258 259 SharingMapTy *getSecondOnStackOrNull() { 260 size_t Size = getStackSize(); 261 if (Size <= 1) 262 return nullptr; 263 return &Stack.back().first[Size - 2]; 264 } 265 const SharingMapTy *getSecondOnStackOrNull() const { 266 return const_cast<DSAStackTy&>(*this).getSecondOnStackOrNull(); 267 } 268 269 /// Get the stack element at a certain level (previously returned by 270 /// \c getNestingLevel). 271 /// 272 /// Note that nesting levels count from outermost to innermost, and this is 273 /// the reverse of our iteration order where new inner levels are pushed at 274 /// the front of the stack. 275 SharingMapTy &getStackElemAtLevel(unsigned Level) { 276 assert(Level < getStackSize() && "no such stack element"); 277 return Stack.back().first[Level]; 278 } 279 const SharingMapTy &getStackElemAtLevel(unsigned Level) const { 280 return const_cast<DSAStackTy&>(*this).getStackElemAtLevel(Level); 281 } 282 283 DSAVarData getDSA(const_iterator &Iter, ValueDecl *D) const; 284 285 /// Checks if the variable is a local for OpenMP region. 286 bool isOpenMPLocal(VarDecl *D, const_iterator Iter) const; 287 288 /// Vector of previously declared requires directives 289 SmallVector<const OMPRequiresDecl *, 2> RequiresDecls; 290 /// omp_allocator_handle_t type. 291 QualType OMPAllocatorHandleT; 292 /// omp_depend_t type. 293 QualType OMPDependT; 294 /// omp_event_handle_t type. 295 QualType OMPEventHandleT; 296 /// omp_alloctrait_t type. 297 QualType OMPAlloctraitT; 298 /// Expression for the predefined allocators. 299 Expr *OMPPredefinedAllocators[OMPAllocateDeclAttr::OMPUserDefinedMemAlloc] = { 300 nullptr}; 301 /// Vector of previously encountered target directives 302 SmallVector<SourceLocation, 2> TargetLocations; 303 SourceLocation AtomicLocation; 304 305 public: 306 explicit DSAStackTy(Sema &S) : SemaRef(S) {} 307 308 /// Sets omp_allocator_handle_t type. 309 void setOMPAllocatorHandleT(QualType Ty) { OMPAllocatorHandleT = Ty; } 310 /// Gets omp_allocator_handle_t type. 311 QualType getOMPAllocatorHandleT() const { return OMPAllocatorHandleT; } 312 /// Sets omp_alloctrait_t type. 313 void setOMPAlloctraitT(QualType Ty) { OMPAlloctraitT = Ty; } 314 /// Gets omp_alloctrait_t type. 315 QualType getOMPAlloctraitT() const { return OMPAlloctraitT; } 316 /// Sets the given default allocator. 317 void setAllocator(OMPAllocateDeclAttr::AllocatorTypeTy AllocatorKind, 318 Expr *Allocator) { 319 OMPPredefinedAllocators[AllocatorKind] = Allocator; 320 } 321 /// Returns the specified default allocator. 322 Expr *getAllocator(OMPAllocateDeclAttr::AllocatorTypeTy AllocatorKind) const { 323 return OMPPredefinedAllocators[AllocatorKind]; 324 } 325 /// Sets omp_depend_t type. 326 void setOMPDependT(QualType Ty) { OMPDependT = Ty; } 327 /// Gets omp_depend_t type. 328 QualType getOMPDependT() const { return OMPDependT; } 329 330 /// Sets omp_event_handle_t type. 331 void setOMPEventHandleT(QualType Ty) { OMPEventHandleT = Ty; } 332 /// Gets omp_event_handle_t type. 333 QualType getOMPEventHandleT() const { return OMPEventHandleT; } 334 335 bool isClauseParsingMode() const { return ClauseKindMode != OMPC_unknown; } 336 OpenMPClauseKind getClauseParsingMode() const { 337 assert(isClauseParsingMode() && "Must be in clause parsing mode."); 338 return ClauseKindMode; 339 } 340 void setClauseParsingMode(OpenMPClauseKind K) { ClauseKindMode = K; } 341 342 bool isBodyComplete() const { 343 const SharingMapTy *Top = getTopOfStackOrNull(); 344 return Top && Top->BodyComplete; 345 } 346 void setBodyComplete() { 347 getTopOfStack().BodyComplete = true; 348 } 349 350 bool isForceVarCapturing() const { return ForceCapturing; } 351 void setForceVarCapturing(bool V) { ForceCapturing = V; } 352 353 void setForceCaptureByReferenceInTargetExecutable(bool V) { 354 ForceCaptureByReferenceInTargetExecutable = V; 355 } 356 bool isForceCaptureByReferenceInTargetExecutable() const { 357 return ForceCaptureByReferenceInTargetExecutable; 358 } 359 360 void push(OpenMPDirectiveKind DKind, const DeclarationNameInfo &DirName, 361 Scope *CurScope, SourceLocation Loc) { 362 assert(!IgnoredStackElements && 363 "cannot change stack while ignoring elements"); 364 if (Stack.empty() || 365 Stack.back().second != CurrentNonCapturingFunctionScope) 366 Stack.emplace_back(StackTy(), CurrentNonCapturingFunctionScope); 367 Stack.back().first.emplace_back(DKind, DirName, CurScope, Loc); 368 Stack.back().first.back().DefaultAttrLoc = Loc; 369 } 370 371 void pop() { 372 assert(!IgnoredStackElements && 373 "cannot change stack while ignoring elements"); 374 assert(!Stack.back().first.empty() && 375 "Data-sharing attributes stack is empty!"); 376 Stack.back().first.pop_back(); 377 } 378 379 /// RAII object to temporarily leave the scope of a directive when we want to 380 /// logically operate in its parent. 381 class ParentDirectiveScope { 382 DSAStackTy &Self; 383 bool Active; 384 public: 385 ParentDirectiveScope(DSAStackTy &Self, bool Activate) 386 : Self(Self), Active(false) { 387 if (Activate) 388 enable(); 389 } 390 ~ParentDirectiveScope() { disable(); } 391 void disable() { 392 if (Active) { 393 --Self.IgnoredStackElements; 394 Active = false; 395 } 396 } 397 void enable() { 398 if (!Active) { 399 ++Self.IgnoredStackElements; 400 Active = true; 401 } 402 } 403 }; 404 405 /// Marks that we're started loop parsing. 406 void loopInit() { 407 assert(isOpenMPLoopDirective(getCurrentDirective()) && 408 "Expected loop-based directive."); 409 getTopOfStack().LoopStart = true; 410 } 411 /// Start capturing of the variables in the loop context. 412 void loopStart() { 413 assert(isOpenMPLoopDirective(getCurrentDirective()) && 414 "Expected loop-based directive."); 415 getTopOfStack().LoopStart = false; 416 } 417 /// true, if variables are captured, false otherwise. 418 bool isLoopStarted() const { 419 assert(isOpenMPLoopDirective(getCurrentDirective()) && 420 "Expected loop-based directive."); 421 return !getTopOfStack().LoopStart; 422 } 423 /// Marks (or clears) declaration as possibly loop counter. 424 void resetPossibleLoopCounter(const Decl *D = nullptr) { 425 getTopOfStack().PossiblyLoopCounter = 426 D ? D->getCanonicalDecl() : D; 427 } 428 /// Gets the possible loop counter decl. 429 const Decl *getPossiblyLoopCunter() const { 430 return getTopOfStack().PossiblyLoopCounter; 431 } 432 /// Start new OpenMP region stack in new non-capturing function. 433 void pushFunction() { 434 assert(!IgnoredStackElements && 435 "cannot change stack while ignoring elements"); 436 const FunctionScopeInfo *CurFnScope = SemaRef.getCurFunction(); 437 assert(!isa<CapturingScopeInfo>(CurFnScope)); 438 CurrentNonCapturingFunctionScope = CurFnScope; 439 } 440 /// Pop region stack for non-capturing function. 441 void popFunction(const FunctionScopeInfo *OldFSI) { 442 assert(!IgnoredStackElements && 443 "cannot change stack while ignoring elements"); 444 if (!Stack.empty() && Stack.back().second == OldFSI) { 445 assert(Stack.back().first.empty()); 446 Stack.pop_back(); 447 } 448 CurrentNonCapturingFunctionScope = nullptr; 449 for (const FunctionScopeInfo *FSI : llvm::reverse(SemaRef.FunctionScopes)) { 450 if (!isa<CapturingScopeInfo>(FSI)) { 451 CurrentNonCapturingFunctionScope = FSI; 452 break; 453 } 454 } 455 } 456 457 void addCriticalWithHint(const OMPCriticalDirective *D, llvm::APSInt Hint) { 458 Criticals.try_emplace(D->getDirectiveName().getAsString(), D, Hint); 459 } 460 const std::pair<const OMPCriticalDirective *, llvm::APSInt> 461 getCriticalWithHint(const DeclarationNameInfo &Name) const { 462 auto I = Criticals.find(Name.getAsString()); 463 if (I != Criticals.end()) 464 return I->second; 465 return std::make_pair(nullptr, llvm::APSInt()); 466 } 467 /// If 'aligned' declaration for given variable \a D was not seen yet, 468 /// add it and return NULL; otherwise return previous occurrence's expression 469 /// for diagnostics. 470 const Expr *addUniqueAligned(const ValueDecl *D, const Expr *NewDE); 471 /// If 'nontemporal' declaration for given variable \a D was not seen yet, 472 /// add it and return NULL; otherwise return previous occurrence's expression 473 /// for diagnostics. 474 const Expr *addUniqueNontemporal(const ValueDecl *D, const Expr *NewDE); 475 476 /// Register specified variable as loop control variable. 477 void addLoopControlVariable(const ValueDecl *D, VarDecl *Capture); 478 /// Check if the specified variable is a loop control variable for 479 /// current region. 480 /// \return The index of the loop control variable in the list of associated 481 /// for-loops (from outer to inner). 482 const LCDeclInfo isLoopControlVariable(const ValueDecl *D) const; 483 /// Check if the specified variable is a loop control variable for 484 /// parent region. 485 /// \return The index of the loop control variable in the list of associated 486 /// for-loops (from outer to inner). 487 const LCDeclInfo isParentLoopControlVariable(const ValueDecl *D) const; 488 /// Check if the specified variable is a loop control variable for 489 /// current region. 490 /// \return The index of the loop control variable in the list of associated 491 /// for-loops (from outer to inner). 492 const LCDeclInfo isLoopControlVariable(const ValueDecl *D, 493 unsigned Level) const; 494 /// Get the loop control variable for the I-th loop (or nullptr) in 495 /// parent directive. 496 const ValueDecl *getParentLoopControlVariable(unsigned I) const; 497 498 /// Marks the specified decl \p D as used in scan directive. 499 void markDeclAsUsedInScanDirective(ValueDecl *D) { 500 if (SharingMapTy *Stack = getSecondOnStackOrNull()) 501 Stack->UsedInScanDirective.insert(D); 502 } 503 504 /// Checks if the specified declaration was used in the inner scan directive. 505 bool isUsedInScanDirective(ValueDecl *D) const { 506 if (const SharingMapTy *Stack = getTopOfStackOrNull()) 507 return Stack->UsedInScanDirective.count(D) > 0; 508 return false; 509 } 510 511 /// Adds explicit data sharing attribute to the specified declaration. 512 void addDSA(const ValueDecl *D, const Expr *E, OpenMPClauseKind A, 513 DeclRefExpr *PrivateCopy = nullptr, unsigned Modifier = 0); 514 515 /// Adds additional information for the reduction items with the reduction id 516 /// represented as an operator. 517 void addTaskgroupReductionData(const ValueDecl *D, SourceRange SR, 518 BinaryOperatorKind BOK); 519 /// Adds additional information for the reduction items with the reduction id 520 /// represented as reduction identifier. 521 void addTaskgroupReductionData(const ValueDecl *D, SourceRange SR, 522 const Expr *ReductionRef); 523 /// Returns the location and reduction operation from the innermost parent 524 /// region for the given \p D. 525 const DSAVarData 526 getTopMostTaskgroupReductionData(const ValueDecl *D, SourceRange &SR, 527 BinaryOperatorKind &BOK, 528 Expr *&TaskgroupDescriptor) const; 529 /// Returns the location and reduction operation from the innermost parent 530 /// region for the given \p D. 531 const DSAVarData 532 getTopMostTaskgroupReductionData(const ValueDecl *D, SourceRange &SR, 533 const Expr *&ReductionRef, 534 Expr *&TaskgroupDescriptor) const; 535 /// Return reduction reference expression for the current taskgroup or 536 /// parallel/worksharing directives with task reductions. 537 Expr *getTaskgroupReductionRef() const { 538 assert((getTopOfStack().Directive == OMPD_taskgroup || 539 ((isOpenMPParallelDirective(getTopOfStack().Directive) || 540 isOpenMPWorksharingDirective(getTopOfStack().Directive)) && 541 !isOpenMPSimdDirective(getTopOfStack().Directive))) && 542 "taskgroup reference expression requested for non taskgroup or " 543 "parallel/worksharing directive."); 544 return getTopOfStack().TaskgroupReductionRef; 545 } 546 /// Checks if the given \p VD declaration is actually a taskgroup reduction 547 /// descriptor variable at the \p Level of OpenMP regions. 548 bool isTaskgroupReductionRef(const ValueDecl *VD, unsigned Level) const { 549 return getStackElemAtLevel(Level).TaskgroupReductionRef && 550 cast<DeclRefExpr>(getStackElemAtLevel(Level).TaskgroupReductionRef) 551 ->getDecl() == VD; 552 } 553 554 /// Returns data sharing attributes from top of the stack for the 555 /// specified declaration. 556 const DSAVarData getTopDSA(ValueDecl *D, bool FromParent); 557 /// Returns data-sharing attributes for the specified declaration. 558 const DSAVarData getImplicitDSA(ValueDecl *D, bool FromParent) const; 559 /// Returns data-sharing attributes for the specified declaration. 560 const DSAVarData getImplicitDSA(ValueDecl *D, unsigned Level) const; 561 /// Checks if the specified variables has data-sharing attributes which 562 /// match specified \a CPred predicate in any directive which matches \a DPred 563 /// predicate. 564 const DSAVarData 565 hasDSA(ValueDecl *D, const llvm::function_ref<bool(OpenMPClauseKind)> CPred, 566 const llvm::function_ref<bool(OpenMPDirectiveKind)> DPred, 567 bool FromParent) const; 568 /// Checks if the specified variables has data-sharing attributes which 569 /// match specified \a CPred predicate in any innermost directive which 570 /// matches \a DPred predicate. 571 const DSAVarData 572 hasInnermostDSA(ValueDecl *D, 573 const llvm::function_ref<bool(OpenMPClauseKind)> CPred, 574 const llvm::function_ref<bool(OpenMPDirectiveKind)> DPred, 575 bool FromParent) const; 576 /// Checks if the specified variables has explicit data-sharing 577 /// attributes which match specified \a CPred predicate at the specified 578 /// OpenMP region. 579 bool hasExplicitDSA(const ValueDecl *D, 580 const llvm::function_ref<bool(OpenMPClauseKind)> CPred, 581 unsigned Level, bool NotLastprivate = false) const; 582 583 /// Returns true if the directive at level \Level matches in the 584 /// specified \a DPred predicate. 585 bool hasExplicitDirective( 586 const llvm::function_ref<bool(OpenMPDirectiveKind)> DPred, 587 unsigned Level) const; 588 589 /// Finds a directive which matches specified \a DPred predicate. 590 bool hasDirective( 591 const llvm::function_ref<bool( 592 OpenMPDirectiveKind, const DeclarationNameInfo &, SourceLocation)> 593 DPred, 594 bool FromParent) const; 595 596 /// Returns currently analyzed directive. 597 OpenMPDirectiveKind getCurrentDirective() const { 598 const SharingMapTy *Top = getTopOfStackOrNull(); 599 return Top ? Top->Directive : OMPD_unknown; 600 } 601 /// Returns directive kind at specified level. 602 OpenMPDirectiveKind getDirective(unsigned Level) const { 603 assert(!isStackEmpty() && "No directive at specified level."); 604 return getStackElemAtLevel(Level).Directive; 605 } 606 /// Returns the capture region at the specified level. 607 OpenMPDirectiveKind getCaptureRegion(unsigned Level, 608 unsigned OpenMPCaptureLevel) const { 609 SmallVector<OpenMPDirectiveKind, 4> CaptureRegions; 610 getOpenMPCaptureRegions(CaptureRegions, getDirective(Level)); 611 return CaptureRegions[OpenMPCaptureLevel]; 612 } 613 /// Returns parent directive. 614 OpenMPDirectiveKind getParentDirective() const { 615 const SharingMapTy *Parent = getSecondOnStackOrNull(); 616 return Parent ? Parent->Directive : OMPD_unknown; 617 } 618 619 /// Add requires decl to internal vector 620 void addRequiresDecl(OMPRequiresDecl *RD) { 621 RequiresDecls.push_back(RD); 622 } 623 624 /// Checks if the defined 'requires' directive has specified type of clause. 625 template <typename ClauseType> 626 bool hasRequiresDeclWithClause() const { 627 return llvm::any_of(RequiresDecls, [](const OMPRequiresDecl *D) { 628 return llvm::any_of(D->clauselists(), [](const OMPClause *C) { 629 return isa<ClauseType>(C); 630 }); 631 }); 632 } 633 634 /// Checks for a duplicate clause amongst previously declared requires 635 /// directives 636 bool hasDuplicateRequiresClause(ArrayRef<OMPClause *> ClauseList) const { 637 bool IsDuplicate = false; 638 for (OMPClause *CNew : ClauseList) { 639 for (const OMPRequiresDecl *D : RequiresDecls) { 640 for (const OMPClause *CPrev : D->clauselists()) { 641 if (CNew->getClauseKind() == CPrev->getClauseKind()) { 642 SemaRef.Diag(CNew->getBeginLoc(), 643 diag::err_omp_requires_clause_redeclaration) 644 << getOpenMPClauseName(CNew->getClauseKind()); 645 SemaRef.Diag(CPrev->getBeginLoc(), 646 diag::note_omp_requires_previous_clause) 647 << getOpenMPClauseName(CPrev->getClauseKind()); 648 IsDuplicate = true; 649 } 650 } 651 } 652 } 653 return IsDuplicate; 654 } 655 656 /// Add location of previously encountered target to internal vector 657 void addTargetDirLocation(SourceLocation LocStart) { 658 TargetLocations.push_back(LocStart); 659 } 660 661 /// Add location for the first encountered atomicc directive. 662 void addAtomicDirectiveLoc(SourceLocation Loc) { 663 if (AtomicLocation.isInvalid()) 664 AtomicLocation = Loc; 665 } 666 667 /// Returns the location of the first encountered atomic directive in the 668 /// module. 669 SourceLocation getAtomicDirectiveLoc() const { 670 return AtomicLocation; 671 } 672 673 // Return previously encountered target region locations. 674 ArrayRef<SourceLocation> getEncounteredTargetLocs() const { 675 return TargetLocations; 676 } 677 678 /// Set default data sharing attribute to none. 679 void setDefaultDSANone(SourceLocation Loc) { 680 getTopOfStack().DefaultAttr = DSA_none; 681 getTopOfStack().DefaultAttrLoc = Loc; 682 } 683 /// Set default data sharing attribute to shared. 684 void setDefaultDSAShared(SourceLocation Loc) { 685 getTopOfStack().DefaultAttr = DSA_shared; 686 getTopOfStack().DefaultAttrLoc = Loc; 687 } 688 /// Set default data sharing attribute to firstprivate. 689 void setDefaultDSAFirstPrivate(SourceLocation Loc) { 690 getTopOfStack().DefaultAttr = DSA_firstprivate; 691 getTopOfStack().DefaultAttrLoc = Loc; 692 } 693 /// Set default data mapping attribute to Modifier:Kind 694 void setDefaultDMAAttr(OpenMPDefaultmapClauseModifier M, 695 OpenMPDefaultmapClauseKind Kind, 696 SourceLocation Loc) { 697 DefaultmapInfo &DMI = getTopOfStack().DefaultmapMap[Kind]; 698 DMI.ImplicitBehavior = M; 699 DMI.SLoc = Loc; 700 } 701 /// Check whether the implicit-behavior has been set in defaultmap 702 bool checkDefaultmapCategory(OpenMPDefaultmapClauseKind VariableCategory) { 703 if (VariableCategory == OMPC_DEFAULTMAP_unknown) 704 return getTopOfStack() 705 .DefaultmapMap[OMPC_DEFAULTMAP_aggregate] 706 .ImplicitBehavior != OMPC_DEFAULTMAP_MODIFIER_unknown || 707 getTopOfStack() 708 .DefaultmapMap[OMPC_DEFAULTMAP_scalar] 709 .ImplicitBehavior != OMPC_DEFAULTMAP_MODIFIER_unknown || 710 getTopOfStack() 711 .DefaultmapMap[OMPC_DEFAULTMAP_pointer] 712 .ImplicitBehavior != OMPC_DEFAULTMAP_MODIFIER_unknown; 713 return getTopOfStack().DefaultmapMap[VariableCategory].ImplicitBehavior != 714 OMPC_DEFAULTMAP_MODIFIER_unknown; 715 } 716 717 DefaultDataSharingAttributes getDefaultDSA(unsigned Level) const { 718 return getStackSize() <= Level ? DSA_unspecified 719 : getStackElemAtLevel(Level).DefaultAttr; 720 } 721 DefaultDataSharingAttributes getDefaultDSA() const { 722 return isStackEmpty() ? DSA_unspecified 723 : getTopOfStack().DefaultAttr; 724 } 725 SourceLocation getDefaultDSALocation() const { 726 return isStackEmpty() ? SourceLocation() 727 : getTopOfStack().DefaultAttrLoc; 728 } 729 OpenMPDefaultmapClauseModifier 730 getDefaultmapModifier(OpenMPDefaultmapClauseKind Kind) const { 731 return isStackEmpty() 732 ? OMPC_DEFAULTMAP_MODIFIER_unknown 733 : getTopOfStack().DefaultmapMap[Kind].ImplicitBehavior; 734 } 735 OpenMPDefaultmapClauseModifier 736 getDefaultmapModifierAtLevel(unsigned Level, 737 OpenMPDefaultmapClauseKind Kind) const { 738 return getStackElemAtLevel(Level).DefaultmapMap[Kind].ImplicitBehavior; 739 } 740 bool isDefaultmapCapturedByRef(unsigned Level, 741 OpenMPDefaultmapClauseKind Kind) const { 742 OpenMPDefaultmapClauseModifier M = 743 getDefaultmapModifierAtLevel(Level, Kind); 744 if (Kind == OMPC_DEFAULTMAP_scalar || Kind == OMPC_DEFAULTMAP_pointer) { 745 return (M == OMPC_DEFAULTMAP_MODIFIER_alloc) || 746 (M == OMPC_DEFAULTMAP_MODIFIER_to) || 747 (M == OMPC_DEFAULTMAP_MODIFIER_from) || 748 (M == OMPC_DEFAULTMAP_MODIFIER_tofrom); 749 } 750 return true; 751 } 752 static bool mustBeFirstprivateBase(OpenMPDefaultmapClauseModifier M, 753 OpenMPDefaultmapClauseKind Kind) { 754 switch (Kind) { 755 case OMPC_DEFAULTMAP_scalar: 756 case OMPC_DEFAULTMAP_pointer: 757 return (M == OMPC_DEFAULTMAP_MODIFIER_unknown) || 758 (M == OMPC_DEFAULTMAP_MODIFIER_firstprivate) || 759 (M == OMPC_DEFAULTMAP_MODIFIER_default); 760 case OMPC_DEFAULTMAP_aggregate: 761 return M == OMPC_DEFAULTMAP_MODIFIER_firstprivate; 762 default: 763 break; 764 } 765 llvm_unreachable("Unexpected OpenMPDefaultmapClauseKind enum"); 766 } 767 bool mustBeFirstprivateAtLevel(unsigned Level, 768 OpenMPDefaultmapClauseKind Kind) const { 769 OpenMPDefaultmapClauseModifier M = 770 getDefaultmapModifierAtLevel(Level, Kind); 771 return mustBeFirstprivateBase(M, Kind); 772 } 773 bool mustBeFirstprivate(OpenMPDefaultmapClauseKind Kind) const { 774 OpenMPDefaultmapClauseModifier M = getDefaultmapModifier(Kind); 775 return mustBeFirstprivateBase(M, Kind); 776 } 777 778 /// Checks if the specified variable is a threadprivate. 779 bool isThreadPrivate(VarDecl *D) { 780 const DSAVarData DVar = getTopDSA(D, false); 781 return isOpenMPThreadPrivate(DVar.CKind); 782 } 783 784 /// Marks current region as ordered (it has an 'ordered' clause). 785 void setOrderedRegion(bool IsOrdered, const Expr *Param, 786 OMPOrderedClause *Clause) { 787 if (IsOrdered) 788 getTopOfStack().OrderedRegion.emplace(Param, Clause); 789 else 790 getTopOfStack().OrderedRegion.reset(); 791 } 792 /// Returns true, if region is ordered (has associated 'ordered' clause), 793 /// false - otherwise. 794 bool isOrderedRegion() const { 795 if (const SharingMapTy *Top = getTopOfStackOrNull()) 796 return Top->OrderedRegion.hasValue(); 797 return false; 798 } 799 /// Returns optional parameter for the ordered region. 800 std::pair<const Expr *, OMPOrderedClause *> getOrderedRegionParam() const { 801 if (const SharingMapTy *Top = getTopOfStackOrNull()) 802 if (Top->OrderedRegion.hasValue()) 803 return Top->OrderedRegion.getValue(); 804 return std::make_pair(nullptr, nullptr); 805 } 806 /// Returns true, if parent region is ordered (has associated 807 /// 'ordered' clause), false - otherwise. 808 bool isParentOrderedRegion() const { 809 if (const SharingMapTy *Parent = getSecondOnStackOrNull()) 810 return Parent->OrderedRegion.hasValue(); 811 return false; 812 } 813 /// Returns optional parameter for the ordered region. 814 std::pair<const Expr *, OMPOrderedClause *> 815 getParentOrderedRegionParam() const { 816 if (const SharingMapTy *Parent = getSecondOnStackOrNull()) 817 if (Parent->OrderedRegion.hasValue()) 818 return Parent->OrderedRegion.getValue(); 819 return std::make_pair(nullptr, nullptr); 820 } 821 /// Marks current region as nowait (it has a 'nowait' clause). 822 void setNowaitRegion(bool IsNowait = true) { 823 getTopOfStack().NowaitRegion = IsNowait; 824 } 825 /// Returns true, if parent region is nowait (has associated 826 /// 'nowait' clause), false - otherwise. 827 bool isParentNowaitRegion() const { 828 if (const SharingMapTy *Parent = getSecondOnStackOrNull()) 829 return Parent->NowaitRegion; 830 return false; 831 } 832 /// Marks parent region as cancel region. 833 void setParentCancelRegion(bool Cancel = true) { 834 if (SharingMapTy *Parent = getSecondOnStackOrNull()) 835 Parent->CancelRegion |= Cancel; 836 } 837 /// Return true if current region has inner cancel construct. 838 bool isCancelRegion() const { 839 const SharingMapTy *Top = getTopOfStackOrNull(); 840 return Top ? Top->CancelRegion : false; 841 } 842 843 /// Mark that parent region already has scan directive. 844 void setParentHasScanDirective(SourceLocation Loc) { 845 if (SharingMapTy *Parent = getSecondOnStackOrNull()) 846 Parent->PrevScanLocation = Loc; 847 } 848 /// Return true if current region has inner cancel construct. 849 bool doesParentHasScanDirective() const { 850 const SharingMapTy *Top = getSecondOnStackOrNull(); 851 return Top ? Top->PrevScanLocation.isValid() : false; 852 } 853 /// Return true if current region has inner cancel construct. 854 SourceLocation getParentScanDirectiveLoc() const { 855 const SharingMapTy *Top = getSecondOnStackOrNull(); 856 return Top ? Top->PrevScanLocation : SourceLocation(); 857 } 858 /// Mark that parent region already has ordered directive. 859 void setParentHasOrderedDirective(SourceLocation Loc) { 860 if (SharingMapTy *Parent = getSecondOnStackOrNull()) 861 Parent->PrevOrderedLocation = Loc; 862 } 863 /// Return true if current region has inner ordered construct. 864 bool doesParentHasOrderedDirective() const { 865 const SharingMapTy *Top = getSecondOnStackOrNull(); 866 return Top ? Top->PrevOrderedLocation.isValid() : false; 867 } 868 /// Returns the location of the previously specified ordered directive. 869 SourceLocation getParentOrderedDirectiveLoc() const { 870 const SharingMapTy *Top = getSecondOnStackOrNull(); 871 return Top ? Top->PrevOrderedLocation : SourceLocation(); 872 } 873 874 /// Set collapse value for the region. 875 void setAssociatedLoops(unsigned Val) { 876 getTopOfStack().AssociatedLoops = Val; 877 if (Val > 1) 878 getTopOfStack().HasMutipleLoops = true; 879 } 880 /// Return collapse value for region. 881 unsigned getAssociatedLoops() const { 882 const SharingMapTy *Top = getTopOfStackOrNull(); 883 return Top ? Top->AssociatedLoops : 0; 884 } 885 /// Returns true if the construct is associated with multiple loops. 886 bool hasMutipleLoops() const { 887 const SharingMapTy *Top = getTopOfStackOrNull(); 888 return Top ? Top->HasMutipleLoops : false; 889 } 890 891 /// Marks current target region as one with closely nested teams 892 /// region. 893 void setParentTeamsRegionLoc(SourceLocation TeamsRegionLoc) { 894 if (SharingMapTy *Parent = getSecondOnStackOrNull()) 895 Parent->InnerTeamsRegionLoc = TeamsRegionLoc; 896 } 897 /// Returns true, if current region has closely nested teams region. 898 bool hasInnerTeamsRegion() const { 899 return getInnerTeamsRegionLoc().isValid(); 900 } 901 /// Returns location of the nested teams region (if any). 902 SourceLocation getInnerTeamsRegionLoc() const { 903 const SharingMapTy *Top = getTopOfStackOrNull(); 904 return Top ? Top->InnerTeamsRegionLoc : SourceLocation(); 905 } 906 907 Scope *getCurScope() const { 908 const SharingMapTy *Top = getTopOfStackOrNull(); 909 return Top ? Top->CurScope : nullptr; 910 } 911 SourceLocation getConstructLoc() const { 912 const SharingMapTy *Top = getTopOfStackOrNull(); 913 return Top ? Top->ConstructLoc : SourceLocation(); 914 } 915 916 /// Do the check specified in \a Check to all component lists and return true 917 /// if any issue is found. 918 bool checkMappableExprComponentListsForDecl( 919 const ValueDecl *VD, bool CurrentRegionOnly, 920 const llvm::function_ref< 921 bool(OMPClauseMappableExprCommon::MappableExprComponentListRef, 922 OpenMPClauseKind)> 923 Check) const { 924 if (isStackEmpty()) 925 return false; 926 auto SI = begin(); 927 auto SE = end(); 928 929 if (SI == SE) 930 return false; 931 932 if (CurrentRegionOnly) 933 SE = std::next(SI); 934 else 935 std::advance(SI, 1); 936 937 for (; SI != SE; ++SI) { 938 auto MI = SI->MappedExprComponents.find(VD); 939 if (MI != SI->MappedExprComponents.end()) 940 for (OMPClauseMappableExprCommon::MappableExprComponentListRef L : 941 MI->second.Components) 942 if (Check(L, MI->second.Kind)) 943 return true; 944 } 945 return false; 946 } 947 948 /// Do the check specified in \a Check to all component lists at a given level 949 /// and return true if any issue is found. 950 bool checkMappableExprComponentListsForDeclAtLevel( 951 const ValueDecl *VD, unsigned Level, 952 const llvm::function_ref< 953 bool(OMPClauseMappableExprCommon::MappableExprComponentListRef, 954 OpenMPClauseKind)> 955 Check) const { 956 if (getStackSize() <= Level) 957 return false; 958 959 const SharingMapTy &StackElem = getStackElemAtLevel(Level); 960 auto MI = StackElem.MappedExprComponents.find(VD); 961 if (MI != StackElem.MappedExprComponents.end()) 962 for (OMPClauseMappableExprCommon::MappableExprComponentListRef L : 963 MI->second.Components) 964 if (Check(L, MI->second.Kind)) 965 return true; 966 return false; 967 } 968 969 /// Create a new mappable expression component list associated with a given 970 /// declaration and initialize it with the provided list of components. 971 void addMappableExpressionComponents( 972 const ValueDecl *VD, 973 OMPClauseMappableExprCommon::MappableExprComponentListRef Components, 974 OpenMPClauseKind WhereFoundClauseKind) { 975 MappedExprComponentTy &MEC = getTopOfStack().MappedExprComponents[VD]; 976 // Create new entry and append the new components there. 977 MEC.Components.resize(MEC.Components.size() + 1); 978 MEC.Components.back().append(Components.begin(), Components.end()); 979 MEC.Kind = WhereFoundClauseKind; 980 } 981 982 unsigned getNestingLevel() const { 983 assert(!isStackEmpty()); 984 return getStackSize() - 1; 985 } 986 void addDoacrossDependClause(OMPDependClause *C, 987 const OperatorOffsetTy &OpsOffs) { 988 SharingMapTy *Parent = getSecondOnStackOrNull(); 989 assert(Parent && isOpenMPWorksharingDirective(Parent->Directive)); 990 Parent->DoacrossDepends.try_emplace(C, OpsOffs); 991 } 992 llvm::iterator_range<DoacrossDependMapTy::const_iterator> 993 getDoacrossDependClauses() const { 994 const SharingMapTy &StackElem = getTopOfStack(); 995 if (isOpenMPWorksharingDirective(StackElem.Directive)) { 996 const DoacrossDependMapTy &Ref = StackElem.DoacrossDepends; 997 return llvm::make_range(Ref.begin(), Ref.end()); 998 } 999 return llvm::make_range(StackElem.DoacrossDepends.end(), 1000 StackElem.DoacrossDepends.end()); 1001 } 1002 1003 // Store types of classes which have been explicitly mapped 1004 void addMappedClassesQualTypes(QualType QT) { 1005 SharingMapTy &StackElem = getTopOfStack(); 1006 StackElem.MappedClassesQualTypes.insert(QT); 1007 } 1008 1009 // Return set of mapped classes types 1010 bool isClassPreviouslyMapped(QualType QT) const { 1011 const SharingMapTy &StackElem = getTopOfStack(); 1012 return StackElem.MappedClassesQualTypes.count(QT) != 0; 1013 } 1014 1015 /// Adds global declare target to the parent target region. 1016 void addToParentTargetRegionLinkGlobals(DeclRefExpr *E) { 1017 assert(*OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration( 1018 E->getDecl()) == OMPDeclareTargetDeclAttr::MT_Link && 1019 "Expected declare target link global."); 1020 for (auto &Elem : *this) { 1021 if (isOpenMPTargetExecutionDirective(Elem.Directive)) { 1022 Elem.DeclareTargetLinkVarDecls.push_back(E); 1023 return; 1024 } 1025 } 1026 } 1027 1028 /// Returns the list of globals with declare target link if current directive 1029 /// is target. 1030 ArrayRef<DeclRefExpr *> getLinkGlobals() const { 1031 assert(isOpenMPTargetExecutionDirective(getCurrentDirective()) && 1032 "Expected target executable directive."); 1033 return getTopOfStack().DeclareTargetLinkVarDecls; 1034 } 1035 1036 /// Adds list of allocators expressions. 1037 void addInnerAllocatorExpr(Expr *E) { 1038 getTopOfStack().InnerUsedAllocators.push_back(E); 1039 } 1040 /// Return list of used allocators. 1041 ArrayRef<Expr *> getInnerAllocators() const { 1042 return getTopOfStack().InnerUsedAllocators; 1043 } 1044 /// Marks the declaration as implicitly firstprivate nin the task-based 1045 /// regions. 1046 void addImplicitTaskFirstprivate(unsigned Level, Decl *D) { 1047 getStackElemAtLevel(Level).ImplicitTaskFirstprivates.insert(D); 1048 } 1049 /// Checks if the decl is implicitly firstprivate in the task-based region. 1050 bool isImplicitTaskFirstprivate(Decl *D) const { 1051 return getTopOfStack().ImplicitTaskFirstprivates.count(D) > 0; 1052 } 1053 1054 /// Marks decl as used in uses_allocators clause as the allocator. 1055 void addUsesAllocatorsDecl(const Decl *D, UsesAllocatorsDeclKind Kind) { 1056 getTopOfStack().UsesAllocatorsDecls.try_emplace(D, Kind); 1057 } 1058 /// Checks if specified decl is used in uses allocator clause as the 1059 /// allocator. 1060 Optional<UsesAllocatorsDeclKind> isUsesAllocatorsDecl(unsigned Level, 1061 const Decl *D) const { 1062 const SharingMapTy &StackElem = getTopOfStack(); 1063 auto I = StackElem.UsesAllocatorsDecls.find(D); 1064 if (I == StackElem.UsesAllocatorsDecls.end()) 1065 return None; 1066 return I->getSecond(); 1067 } 1068 Optional<UsesAllocatorsDeclKind> isUsesAllocatorsDecl(const Decl *D) const { 1069 const SharingMapTy &StackElem = getTopOfStack(); 1070 auto I = StackElem.UsesAllocatorsDecls.find(D); 1071 if (I == StackElem.UsesAllocatorsDecls.end()) 1072 return None; 1073 return I->getSecond(); 1074 } 1075 }; 1076 1077 bool isImplicitTaskingRegion(OpenMPDirectiveKind DKind) { 1078 return isOpenMPParallelDirective(DKind) || isOpenMPTeamsDirective(DKind); 1079 } 1080 1081 bool isImplicitOrExplicitTaskingRegion(OpenMPDirectiveKind DKind) { 1082 return isImplicitTaskingRegion(DKind) || isOpenMPTaskingDirective(DKind) || 1083 DKind == OMPD_unknown; 1084 } 1085 1086 } // namespace 1087 1088 static const Expr *getExprAsWritten(const Expr *E) { 1089 if (const auto *FE = dyn_cast<FullExpr>(E)) 1090 E = FE->getSubExpr(); 1091 1092 if (const auto *MTE = dyn_cast<MaterializeTemporaryExpr>(E)) 1093 E = MTE->getSubExpr(); 1094 1095 while (const auto *Binder = dyn_cast<CXXBindTemporaryExpr>(E)) 1096 E = Binder->getSubExpr(); 1097 1098 if (const auto *ICE = dyn_cast<ImplicitCastExpr>(E)) 1099 E = ICE->getSubExprAsWritten(); 1100 return E->IgnoreParens(); 1101 } 1102 1103 static Expr *getExprAsWritten(Expr *E) { 1104 return const_cast<Expr *>(getExprAsWritten(const_cast<const Expr *>(E))); 1105 } 1106 1107 static const ValueDecl *getCanonicalDecl(const ValueDecl *D) { 1108 if (const auto *CED = dyn_cast<OMPCapturedExprDecl>(D)) 1109 if (const auto *ME = dyn_cast<MemberExpr>(getExprAsWritten(CED->getInit()))) 1110 D = ME->getMemberDecl(); 1111 const auto *VD = dyn_cast<VarDecl>(D); 1112 const auto *FD = dyn_cast<FieldDecl>(D); 1113 if (VD != nullptr) { 1114 VD = VD->getCanonicalDecl(); 1115 D = VD; 1116 } else { 1117 assert(FD); 1118 FD = FD->getCanonicalDecl(); 1119 D = FD; 1120 } 1121 return D; 1122 } 1123 1124 static ValueDecl *getCanonicalDecl(ValueDecl *D) { 1125 return const_cast<ValueDecl *>( 1126 getCanonicalDecl(const_cast<const ValueDecl *>(D))); 1127 } 1128 1129 DSAStackTy::DSAVarData DSAStackTy::getDSA(const_iterator &Iter, 1130 ValueDecl *D) const { 1131 D = getCanonicalDecl(D); 1132 auto *VD = dyn_cast<VarDecl>(D); 1133 const auto *FD = dyn_cast<FieldDecl>(D); 1134 DSAVarData DVar; 1135 if (Iter == end()) { 1136 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced 1137 // in a region but not in construct] 1138 // File-scope or namespace-scope variables referenced in called routines 1139 // in the region are shared unless they appear in a threadprivate 1140 // directive. 1141 if (VD && !VD->isFunctionOrMethodVarDecl() && !isa<ParmVarDecl>(VD)) 1142 DVar.CKind = OMPC_shared; 1143 1144 // OpenMP [2.9.1.2, Data-sharing Attribute Rules for Variables Referenced 1145 // in a region but not in construct] 1146 // Variables with static storage duration that are declared in called 1147 // routines in the region are shared. 1148 if (VD && VD->hasGlobalStorage()) 1149 DVar.CKind = OMPC_shared; 1150 1151 // Non-static data members are shared by default. 1152 if (FD) 1153 DVar.CKind = OMPC_shared; 1154 1155 return DVar; 1156 } 1157 1158 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced 1159 // in a Construct, C/C++, predetermined, p.1] 1160 // Variables with automatic storage duration that are declared in a scope 1161 // inside the construct are private. 1162 if (VD && isOpenMPLocal(VD, Iter) && VD->isLocalVarDecl() && 1163 (VD->getStorageClass() == SC_Auto || VD->getStorageClass() == SC_None)) { 1164 DVar.CKind = OMPC_private; 1165 return DVar; 1166 } 1167 1168 DVar.DKind = Iter->Directive; 1169 // Explicitly specified attributes and local variables with predetermined 1170 // attributes. 1171 if (Iter->SharingMap.count(D)) { 1172 const DSAInfo &Data = Iter->SharingMap.lookup(D); 1173 DVar.RefExpr = Data.RefExpr.getPointer(); 1174 DVar.PrivateCopy = Data.PrivateCopy; 1175 DVar.CKind = Data.Attributes; 1176 DVar.ImplicitDSALoc = Iter->DefaultAttrLoc; 1177 DVar.Modifier = Data.Modifier; 1178 return DVar; 1179 } 1180 1181 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced 1182 // in a Construct, C/C++, implicitly determined, p.1] 1183 // In a parallel or task construct, the data-sharing attributes of these 1184 // variables are determined by the default clause, if present. 1185 switch (Iter->DefaultAttr) { 1186 case DSA_shared: 1187 DVar.CKind = OMPC_shared; 1188 DVar.ImplicitDSALoc = Iter->DefaultAttrLoc; 1189 return DVar; 1190 case DSA_none: 1191 return DVar; 1192 case DSA_firstprivate: 1193 if (VD->getStorageDuration() == SD_Static && 1194 VD->getDeclContext()->isFileContext()) { 1195 DVar.CKind = OMPC_unknown; 1196 } else { 1197 DVar.CKind = OMPC_firstprivate; 1198 } 1199 DVar.ImplicitDSALoc = Iter->DefaultAttrLoc; 1200 return DVar; 1201 case DSA_unspecified: 1202 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced 1203 // in a Construct, implicitly determined, p.2] 1204 // In a parallel construct, if no default clause is present, these 1205 // variables are shared. 1206 DVar.ImplicitDSALoc = Iter->DefaultAttrLoc; 1207 if ((isOpenMPParallelDirective(DVar.DKind) && 1208 !isOpenMPTaskLoopDirective(DVar.DKind)) || 1209 isOpenMPTeamsDirective(DVar.DKind)) { 1210 DVar.CKind = OMPC_shared; 1211 return DVar; 1212 } 1213 1214 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced 1215 // in a Construct, implicitly determined, p.4] 1216 // In a task construct, if no default clause is present, a variable that in 1217 // the enclosing context is determined to be shared by all implicit tasks 1218 // bound to the current team is shared. 1219 if (isOpenMPTaskingDirective(DVar.DKind)) { 1220 DSAVarData DVarTemp; 1221 const_iterator I = Iter, E = end(); 1222 do { 1223 ++I; 1224 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables 1225 // Referenced in a Construct, implicitly determined, p.6] 1226 // In a task construct, if no default clause is present, a variable 1227 // whose data-sharing attribute is not determined by the rules above is 1228 // firstprivate. 1229 DVarTemp = getDSA(I, D); 1230 if (DVarTemp.CKind != OMPC_shared) { 1231 DVar.RefExpr = nullptr; 1232 DVar.CKind = OMPC_firstprivate; 1233 return DVar; 1234 } 1235 } while (I != E && !isImplicitTaskingRegion(I->Directive)); 1236 DVar.CKind = 1237 (DVarTemp.CKind == OMPC_unknown) ? OMPC_firstprivate : OMPC_shared; 1238 return DVar; 1239 } 1240 } 1241 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced 1242 // in a Construct, implicitly determined, p.3] 1243 // For constructs other than task, if no default clause is present, these 1244 // variables inherit their data-sharing attributes from the enclosing 1245 // context. 1246 return getDSA(++Iter, D); 1247 } 1248 1249 const Expr *DSAStackTy::addUniqueAligned(const ValueDecl *D, 1250 const Expr *NewDE) { 1251 assert(!isStackEmpty() && "Data sharing attributes stack is empty"); 1252 D = getCanonicalDecl(D); 1253 SharingMapTy &StackElem = getTopOfStack(); 1254 auto It = StackElem.AlignedMap.find(D); 1255 if (It == StackElem.AlignedMap.end()) { 1256 assert(NewDE && "Unexpected nullptr expr to be added into aligned map"); 1257 StackElem.AlignedMap[D] = NewDE; 1258 return nullptr; 1259 } 1260 assert(It->second && "Unexpected nullptr expr in the aligned map"); 1261 return It->second; 1262 } 1263 1264 const Expr *DSAStackTy::addUniqueNontemporal(const ValueDecl *D, 1265 const Expr *NewDE) { 1266 assert(!isStackEmpty() && "Data sharing attributes stack is empty"); 1267 D = getCanonicalDecl(D); 1268 SharingMapTy &StackElem = getTopOfStack(); 1269 auto It = StackElem.NontemporalMap.find(D); 1270 if (It == StackElem.NontemporalMap.end()) { 1271 assert(NewDE && "Unexpected nullptr expr to be added into aligned map"); 1272 StackElem.NontemporalMap[D] = NewDE; 1273 return nullptr; 1274 } 1275 assert(It->second && "Unexpected nullptr expr in the aligned map"); 1276 return It->second; 1277 } 1278 1279 void DSAStackTy::addLoopControlVariable(const ValueDecl *D, VarDecl *Capture) { 1280 assert(!isStackEmpty() && "Data-sharing attributes stack is empty"); 1281 D = getCanonicalDecl(D); 1282 SharingMapTy &StackElem = getTopOfStack(); 1283 StackElem.LCVMap.try_emplace( 1284 D, LCDeclInfo(StackElem.LCVMap.size() + 1, Capture)); 1285 } 1286 1287 const DSAStackTy::LCDeclInfo 1288 DSAStackTy::isLoopControlVariable(const ValueDecl *D) const { 1289 assert(!isStackEmpty() && "Data-sharing attributes stack is empty"); 1290 D = getCanonicalDecl(D); 1291 const SharingMapTy &StackElem = getTopOfStack(); 1292 auto It = StackElem.LCVMap.find(D); 1293 if (It != StackElem.LCVMap.end()) 1294 return It->second; 1295 return {0, nullptr}; 1296 } 1297 1298 const DSAStackTy::LCDeclInfo 1299 DSAStackTy::isLoopControlVariable(const ValueDecl *D, unsigned Level) const { 1300 assert(!isStackEmpty() && "Data-sharing attributes stack is empty"); 1301 D = getCanonicalDecl(D); 1302 for (unsigned I = Level + 1; I > 0; --I) { 1303 const SharingMapTy &StackElem = getStackElemAtLevel(I - 1); 1304 auto It = StackElem.LCVMap.find(D); 1305 if (It != StackElem.LCVMap.end()) 1306 return It->second; 1307 } 1308 return {0, nullptr}; 1309 } 1310 1311 const DSAStackTy::LCDeclInfo 1312 DSAStackTy::isParentLoopControlVariable(const ValueDecl *D) const { 1313 const SharingMapTy *Parent = getSecondOnStackOrNull(); 1314 assert(Parent && "Data-sharing attributes stack is empty"); 1315 D = getCanonicalDecl(D); 1316 auto It = Parent->LCVMap.find(D); 1317 if (It != Parent->LCVMap.end()) 1318 return It->second; 1319 return {0, nullptr}; 1320 } 1321 1322 const ValueDecl *DSAStackTy::getParentLoopControlVariable(unsigned I) const { 1323 const SharingMapTy *Parent = getSecondOnStackOrNull(); 1324 assert(Parent && "Data-sharing attributes stack is empty"); 1325 if (Parent->LCVMap.size() < I) 1326 return nullptr; 1327 for (const auto &Pair : Parent->LCVMap) 1328 if (Pair.second.first == I) 1329 return Pair.first; 1330 return nullptr; 1331 } 1332 1333 void DSAStackTy::addDSA(const ValueDecl *D, const Expr *E, OpenMPClauseKind A, 1334 DeclRefExpr *PrivateCopy, unsigned Modifier) { 1335 D = getCanonicalDecl(D); 1336 if (A == OMPC_threadprivate) { 1337 DSAInfo &Data = Threadprivates[D]; 1338 Data.Attributes = A; 1339 Data.RefExpr.setPointer(E); 1340 Data.PrivateCopy = nullptr; 1341 Data.Modifier = Modifier; 1342 } else { 1343 DSAInfo &Data = getTopOfStack().SharingMap[D]; 1344 assert(Data.Attributes == OMPC_unknown || (A == Data.Attributes) || 1345 (A == OMPC_firstprivate && Data.Attributes == OMPC_lastprivate) || 1346 (A == OMPC_lastprivate && Data.Attributes == OMPC_firstprivate) || 1347 (isLoopControlVariable(D).first && A == OMPC_private)); 1348 Data.Modifier = Modifier; 1349 if (A == OMPC_lastprivate && Data.Attributes == OMPC_firstprivate) { 1350 Data.RefExpr.setInt(/*IntVal=*/true); 1351 return; 1352 } 1353 const bool IsLastprivate = 1354 A == OMPC_lastprivate || Data.Attributes == OMPC_lastprivate; 1355 Data.Attributes = A; 1356 Data.RefExpr.setPointerAndInt(E, IsLastprivate); 1357 Data.PrivateCopy = PrivateCopy; 1358 if (PrivateCopy) { 1359 DSAInfo &Data = getTopOfStack().SharingMap[PrivateCopy->getDecl()]; 1360 Data.Modifier = Modifier; 1361 Data.Attributes = A; 1362 Data.RefExpr.setPointerAndInt(PrivateCopy, IsLastprivate); 1363 Data.PrivateCopy = nullptr; 1364 } 1365 } 1366 } 1367 1368 /// Build a variable declaration for OpenMP loop iteration variable. 1369 static VarDecl *buildVarDecl(Sema &SemaRef, SourceLocation Loc, QualType Type, 1370 StringRef Name, const AttrVec *Attrs = nullptr, 1371 DeclRefExpr *OrigRef = nullptr) { 1372 DeclContext *DC = SemaRef.CurContext; 1373 IdentifierInfo *II = &SemaRef.PP.getIdentifierTable().get(Name); 1374 TypeSourceInfo *TInfo = SemaRef.Context.getTrivialTypeSourceInfo(Type, Loc); 1375 auto *Decl = 1376 VarDecl::Create(SemaRef.Context, DC, Loc, Loc, II, Type, TInfo, SC_None); 1377 if (Attrs) { 1378 for (specific_attr_iterator<AlignedAttr> I(Attrs->begin()), E(Attrs->end()); 1379 I != E; ++I) 1380 Decl->addAttr(*I); 1381 } 1382 Decl->setImplicit(); 1383 if (OrigRef) { 1384 Decl->addAttr( 1385 OMPReferencedVarAttr::CreateImplicit(SemaRef.Context, OrigRef)); 1386 } 1387 return Decl; 1388 } 1389 1390 static DeclRefExpr *buildDeclRefExpr(Sema &S, VarDecl *D, QualType Ty, 1391 SourceLocation Loc, 1392 bool RefersToCapture = false) { 1393 D->setReferenced(); 1394 D->markUsed(S.Context); 1395 return DeclRefExpr::Create(S.getASTContext(), NestedNameSpecifierLoc(), 1396 SourceLocation(), D, RefersToCapture, Loc, Ty, 1397 VK_LValue); 1398 } 1399 1400 void DSAStackTy::addTaskgroupReductionData(const ValueDecl *D, SourceRange SR, 1401 BinaryOperatorKind BOK) { 1402 D = getCanonicalDecl(D); 1403 assert(!isStackEmpty() && "Data-sharing attributes stack is empty"); 1404 assert( 1405 getTopOfStack().SharingMap[D].Attributes == OMPC_reduction && 1406 "Additional reduction info may be specified only for reduction items."); 1407 ReductionData &ReductionData = getTopOfStack().ReductionMap[D]; 1408 assert(ReductionData.ReductionRange.isInvalid() && 1409 (getTopOfStack().Directive == OMPD_taskgroup || 1410 ((isOpenMPParallelDirective(getTopOfStack().Directive) || 1411 isOpenMPWorksharingDirective(getTopOfStack().Directive)) && 1412 !isOpenMPSimdDirective(getTopOfStack().Directive))) && 1413 "Additional reduction info may be specified only once for reduction " 1414 "items."); 1415 ReductionData.set(BOK, SR); 1416 Expr *&TaskgroupReductionRef = 1417 getTopOfStack().TaskgroupReductionRef; 1418 if (!TaskgroupReductionRef) { 1419 VarDecl *VD = buildVarDecl(SemaRef, SR.getBegin(), 1420 SemaRef.Context.VoidPtrTy, ".task_red."); 1421 TaskgroupReductionRef = 1422 buildDeclRefExpr(SemaRef, VD, SemaRef.Context.VoidPtrTy, SR.getBegin()); 1423 } 1424 } 1425 1426 void DSAStackTy::addTaskgroupReductionData(const ValueDecl *D, SourceRange SR, 1427 const Expr *ReductionRef) { 1428 D = getCanonicalDecl(D); 1429 assert(!isStackEmpty() && "Data-sharing attributes stack is empty"); 1430 assert( 1431 getTopOfStack().SharingMap[D].Attributes == OMPC_reduction && 1432 "Additional reduction info may be specified only for reduction items."); 1433 ReductionData &ReductionData = getTopOfStack().ReductionMap[D]; 1434 assert(ReductionData.ReductionRange.isInvalid() && 1435 (getTopOfStack().Directive == OMPD_taskgroup || 1436 ((isOpenMPParallelDirective(getTopOfStack().Directive) || 1437 isOpenMPWorksharingDirective(getTopOfStack().Directive)) && 1438 !isOpenMPSimdDirective(getTopOfStack().Directive))) && 1439 "Additional reduction info may be specified only once for reduction " 1440 "items."); 1441 ReductionData.set(ReductionRef, SR); 1442 Expr *&TaskgroupReductionRef = 1443 getTopOfStack().TaskgroupReductionRef; 1444 if (!TaskgroupReductionRef) { 1445 VarDecl *VD = buildVarDecl(SemaRef, SR.getBegin(), 1446 SemaRef.Context.VoidPtrTy, ".task_red."); 1447 TaskgroupReductionRef = 1448 buildDeclRefExpr(SemaRef, VD, SemaRef.Context.VoidPtrTy, SR.getBegin()); 1449 } 1450 } 1451 1452 const DSAStackTy::DSAVarData DSAStackTy::getTopMostTaskgroupReductionData( 1453 const ValueDecl *D, SourceRange &SR, BinaryOperatorKind &BOK, 1454 Expr *&TaskgroupDescriptor) const { 1455 D = getCanonicalDecl(D); 1456 assert(!isStackEmpty() && "Data-sharing attributes stack is empty."); 1457 for (const_iterator I = begin() + 1, E = end(); I != E; ++I) { 1458 const DSAInfo &Data = I->SharingMap.lookup(D); 1459 if (Data.Attributes != OMPC_reduction || 1460 Data.Modifier != OMPC_REDUCTION_task) 1461 continue; 1462 const ReductionData &ReductionData = I->ReductionMap.lookup(D); 1463 if (!ReductionData.ReductionOp || 1464 ReductionData.ReductionOp.is<const Expr *>()) 1465 return DSAVarData(); 1466 SR = ReductionData.ReductionRange; 1467 BOK = ReductionData.ReductionOp.get<ReductionData::BOKPtrType>(); 1468 assert(I->TaskgroupReductionRef && "taskgroup reduction reference " 1469 "expression for the descriptor is not " 1470 "set."); 1471 TaskgroupDescriptor = I->TaskgroupReductionRef; 1472 return DSAVarData(I->Directive, OMPC_reduction, Data.RefExpr.getPointer(), 1473 Data.PrivateCopy, I->DefaultAttrLoc, OMPC_REDUCTION_task); 1474 } 1475 return DSAVarData(); 1476 } 1477 1478 const DSAStackTy::DSAVarData DSAStackTy::getTopMostTaskgroupReductionData( 1479 const ValueDecl *D, SourceRange &SR, const Expr *&ReductionRef, 1480 Expr *&TaskgroupDescriptor) const { 1481 D = getCanonicalDecl(D); 1482 assert(!isStackEmpty() && "Data-sharing attributes stack is empty."); 1483 for (const_iterator I = begin() + 1, E = end(); I != E; ++I) { 1484 const DSAInfo &Data = I->SharingMap.lookup(D); 1485 if (Data.Attributes != OMPC_reduction || 1486 Data.Modifier != OMPC_REDUCTION_task) 1487 continue; 1488 const ReductionData &ReductionData = I->ReductionMap.lookup(D); 1489 if (!ReductionData.ReductionOp || 1490 !ReductionData.ReductionOp.is<const Expr *>()) 1491 return DSAVarData(); 1492 SR = ReductionData.ReductionRange; 1493 ReductionRef = ReductionData.ReductionOp.get<const Expr *>(); 1494 assert(I->TaskgroupReductionRef && "taskgroup reduction reference " 1495 "expression for the descriptor is not " 1496 "set."); 1497 TaskgroupDescriptor = I->TaskgroupReductionRef; 1498 return DSAVarData(I->Directive, OMPC_reduction, Data.RefExpr.getPointer(), 1499 Data.PrivateCopy, I->DefaultAttrLoc, OMPC_REDUCTION_task); 1500 } 1501 return DSAVarData(); 1502 } 1503 1504 bool DSAStackTy::isOpenMPLocal(VarDecl *D, const_iterator I) const { 1505 D = D->getCanonicalDecl(); 1506 for (const_iterator E = end(); I != E; ++I) { 1507 if (isImplicitOrExplicitTaskingRegion(I->Directive) || 1508 isOpenMPTargetExecutionDirective(I->Directive)) { 1509 Scope *TopScope = I->CurScope ? I->CurScope->getParent() : nullptr; 1510 Scope *CurScope = getCurScope(); 1511 while (CurScope && CurScope != TopScope && !CurScope->isDeclScope(D)) 1512 CurScope = CurScope->getParent(); 1513 return CurScope != TopScope; 1514 } 1515 } 1516 return false; 1517 } 1518 1519 static bool isConstNotMutableType(Sema &SemaRef, QualType Type, 1520 bool AcceptIfMutable = true, 1521 bool *IsClassType = nullptr) { 1522 ASTContext &Context = SemaRef.getASTContext(); 1523 Type = Type.getNonReferenceType().getCanonicalType(); 1524 bool IsConstant = Type.isConstant(Context); 1525 Type = Context.getBaseElementType(Type); 1526 const CXXRecordDecl *RD = AcceptIfMutable && SemaRef.getLangOpts().CPlusPlus 1527 ? Type->getAsCXXRecordDecl() 1528 : nullptr; 1529 if (const auto *CTSD = dyn_cast_or_null<ClassTemplateSpecializationDecl>(RD)) 1530 if (const ClassTemplateDecl *CTD = CTSD->getSpecializedTemplate()) 1531 RD = CTD->getTemplatedDecl(); 1532 if (IsClassType) 1533 *IsClassType = RD; 1534 return IsConstant && !(SemaRef.getLangOpts().CPlusPlus && RD && 1535 RD->hasDefinition() && RD->hasMutableFields()); 1536 } 1537 1538 static bool rejectConstNotMutableType(Sema &SemaRef, const ValueDecl *D, 1539 QualType Type, OpenMPClauseKind CKind, 1540 SourceLocation ELoc, 1541 bool AcceptIfMutable = true, 1542 bool ListItemNotVar = false) { 1543 ASTContext &Context = SemaRef.getASTContext(); 1544 bool IsClassType; 1545 if (isConstNotMutableType(SemaRef, Type, AcceptIfMutable, &IsClassType)) { 1546 unsigned Diag = ListItemNotVar 1547 ? diag::err_omp_const_list_item 1548 : IsClassType ? diag::err_omp_const_not_mutable_variable 1549 : diag::err_omp_const_variable; 1550 SemaRef.Diag(ELoc, Diag) << getOpenMPClauseName(CKind); 1551 if (!ListItemNotVar && D) { 1552 const VarDecl *VD = dyn_cast<VarDecl>(D); 1553 bool IsDecl = !VD || VD->isThisDeclarationADefinition(Context) == 1554 VarDecl::DeclarationOnly; 1555 SemaRef.Diag(D->getLocation(), 1556 IsDecl ? diag::note_previous_decl : diag::note_defined_here) 1557 << D; 1558 } 1559 return true; 1560 } 1561 return false; 1562 } 1563 1564 const DSAStackTy::DSAVarData DSAStackTy::getTopDSA(ValueDecl *D, 1565 bool FromParent) { 1566 D = getCanonicalDecl(D); 1567 DSAVarData DVar; 1568 1569 auto *VD = dyn_cast<VarDecl>(D); 1570 auto TI = Threadprivates.find(D); 1571 if (TI != Threadprivates.end()) { 1572 DVar.RefExpr = TI->getSecond().RefExpr.getPointer(); 1573 DVar.CKind = OMPC_threadprivate; 1574 DVar.Modifier = TI->getSecond().Modifier; 1575 return DVar; 1576 } 1577 if (VD && VD->hasAttr<OMPThreadPrivateDeclAttr>()) { 1578 DVar.RefExpr = buildDeclRefExpr( 1579 SemaRef, VD, D->getType().getNonReferenceType(), 1580 VD->getAttr<OMPThreadPrivateDeclAttr>()->getLocation()); 1581 DVar.CKind = OMPC_threadprivate; 1582 addDSA(D, DVar.RefExpr, OMPC_threadprivate); 1583 return DVar; 1584 } 1585 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced 1586 // in a Construct, C/C++, predetermined, p.1] 1587 // Variables appearing in threadprivate directives are threadprivate. 1588 if ((VD && VD->getTLSKind() != VarDecl::TLS_None && 1589 !(VD->hasAttr<OMPThreadPrivateDeclAttr>() && 1590 SemaRef.getLangOpts().OpenMPUseTLS && 1591 SemaRef.getASTContext().getTargetInfo().isTLSSupported())) || 1592 (VD && VD->getStorageClass() == SC_Register && 1593 VD->hasAttr<AsmLabelAttr>() && !VD->isLocalVarDecl())) { 1594 DVar.RefExpr = buildDeclRefExpr( 1595 SemaRef, VD, D->getType().getNonReferenceType(), D->getLocation()); 1596 DVar.CKind = OMPC_threadprivate; 1597 addDSA(D, DVar.RefExpr, OMPC_threadprivate); 1598 return DVar; 1599 } 1600 if (SemaRef.getLangOpts().OpenMPCUDAMode && VD && 1601 VD->isLocalVarDeclOrParm() && !isStackEmpty() && 1602 !isLoopControlVariable(D).first) { 1603 const_iterator IterTarget = 1604 std::find_if(begin(), end(), [](const SharingMapTy &Data) { 1605 return isOpenMPTargetExecutionDirective(Data.Directive); 1606 }); 1607 if (IterTarget != end()) { 1608 const_iterator ParentIterTarget = IterTarget + 1; 1609 for (const_iterator Iter = begin(); 1610 Iter != ParentIterTarget; ++Iter) { 1611 if (isOpenMPLocal(VD, Iter)) { 1612 DVar.RefExpr = 1613 buildDeclRefExpr(SemaRef, VD, D->getType().getNonReferenceType(), 1614 D->getLocation()); 1615 DVar.CKind = OMPC_threadprivate; 1616 return DVar; 1617 } 1618 } 1619 if (!isClauseParsingMode() || IterTarget != begin()) { 1620 auto DSAIter = IterTarget->SharingMap.find(D); 1621 if (DSAIter != IterTarget->SharingMap.end() && 1622 isOpenMPPrivate(DSAIter->getSecond().Attributes)) { 1623 DVar.RefExpr = DSAIter->getSecond().RefExpr.getPointer(); 1624 DVar.CKind = OMPC_threadprivate; 1625 return DVar; 1626 } 1627 const_iterator End = end(); 1628 if (!SemaRef.isOpenMPCapturedByRef( 1629 D, std::distance(ParentIterTarget, End), 1630 /*OpenMPCaptureLevel=*/0)) { 1631 DVar.RefExpr = 1632 buildDeclRefExpr(SemaRef, VD, D->getType().getNonReferenceType(), 1633 IterTarget->ConstructLoc); 1634 DVar.CKind = OMPC_threadprivate; 1635 return DVar; 1636 } 1637 } 1638 } 1639 } 1640 1641 if (isStackEmpty()) 1642 // Not in OpenMP execution region and top scope was already checked. 1643 return DVar; 1644 1645 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced 1646 // in a Construct, C/C++, predetermined, p.4] 1647 // Static data members are shared. 1648 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced 1649 // in a Construct, C/C++, predetermined, p.7] 1650 // Variables with static storage duration that are declared in a scope 1651 // inside the construct are shared. 1652 if (VD && VD->isStaticDataMember()) { 1653 // Check for explicitly specified attributes. 1654 const_iterator I = begin(); 1655 const_iterator EndI = end(); 1656 if (FromParent && I != EndI) 1657 ++I; 1658 if (I != EndI) { 1659 auto It = I->SharingMap.find(D); 1660 if (It != I->SharingMap.end()) { 1661 const DSAInfo &Data = It->getSecond(); 1662 DVar.RefExpr = Data.RefExpr.getPointer(); 1663 DVar.PrivateCopy = Data.PrivateCopy; 1664 DVar.CKind = Data.Attributes; 1665 DVar.ImplicitDSALoc = I->DefaultAttrLoc; 1666 DVar.DKind = I->Directive; 1667 DVar.Modifier = Data.Modifier; 1668 return DVar; 1669 } 1670 } 1671 1672 DVar.CKind = OMPC_shared; 1673 return DVar; 1674 } 1675 1676 auto &&MatchesAlways = [](OpenMPDirectiveKind) { return true; }; 1677 // The predetermined shared attribute for const-qualified types having no 1678 // mutable members was removed after OpenMP 3.1. 1679 if (SemaRef.LangOpts.OpenMP <= 31) { 1680 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced 1681 // in a Construct, C/C++, predetermined, p.6] 1682 // Variables with const qualified type having no mutable member are 1683 // shared. 1684 if (isConstNotMutableType(SemaRef, D->getType())) { 1685 // Variables with const-qualified type having no mutable member may be 1686 // listed in a firstprivate clause, even if they are static data members. 1687 DSAVarData DVarTemp = hasInnermostDSA( 1688 D, 1689 [](OpenMPClauseKind C) { 1690 return C == OMPC_firstprivate || C == OMPC_shared; 1691 }, 1692 MatchesAlways, FromParent); 1693 if (DVarTemp.CKind != OMPC_unknown && DVarTemp.RefExpr) 1694 return DVarTemp; 1695 1696 DVar.CKind = OMPC_shared; 1697 return DVar; 1698 } 1699 } 1700 1701 // Explicitly specified attributes and local variables with predetermined 1702 // attributes. 1703 const_iterator I = begin(); 1704 const_iterator EndI = end(); 1705 if (FromParent && I != EndI) 1706 ++I; 1707 if (I == EndI) 1708 return DVar; 1709 auto It = I->SharingMap.find(D); 1710 if (It != I->SharingMap.end()) { 1711 const DSAInfo &Data = It->getSecond(); 1712 DVar.RefExpr = Data.RefExpr.getPointer(); 1713 DVar.PrivateCopy = Data.PrivateCopy; 1714 DVar.CKind = Data.Attributes; 1715 DVar.ImplicitDSALoc = I->DefaultAttrLoc; 1716 DVar.DKind = I->Directive; 1717 DVar.Modifier = Data.Modifier; 1718 } 1719 1720 return DVar; 1721 } 1722 1723 const DSAStackTy::DSAVarData DSAStackTy::getImplicitDSA(ValueDecl *D, 1724 bool FromParent) const { 1725 if (isStackEmpty()) { 1726 const_iterator I; 1727 return getDSA(I, D); 1728 } 1729 D = getCanonicalDecl(D); 1730 const_iterator StartI = begin(); 1731 const_iterator EndI = end(); 1732 if (FromParent && StartI != EndI) 1733 ++StartI; 1734 return getDSA(StartI, D); 1735 } 1736 1737 const DSAStackTy::DSAVarData DSAStackTy::getImplicitDSA(ValueDecl *D, 1738 unsigned Level) const { 1739 if (getStackSize() <= Level) 1740 return DSAVarData(); 1741 D = getCanonicalDecl(D); 1742 const_iterator StartI = std::next(begin(), getStackSize() - 1 - Level); 1743 return getDSA(StartI, D); 1744 } 1745 1746 const DSAStackTy::DSAVarData 1747 DSAStackTy::hasDSA(ValueDecl *D, 1748 const llvm::function_ref<bool(OpenMPClauseKind)> CPred, 1749 const llvm::function_ref<bool(OpenMPDirectiveKind)> DPred, 1750 bool FromParent) const { 1751 if (isStackEmpty()) 1752 return {}; 1753 D = getCanonicalDecl(D); 1754 const_iterator I = begin(); 1755 const_iterator EndI = end(); 1756 if (FromParent && I != EndI) 1757 ++I; 1758 for (; I != EndI; ++I) { 1759 if (!DPred(I->Directive) && 1760 !isImplicitOrExplicitTaskingRegion(I->Directive)) 1761 continue; 1762 const_iterator NewI = I; 1763 DSAVarData DVar = getDSA(NewI, D); 1764 if (I == NewI && CPred(DVar.CKind)) 1765 return DVar; 1766 } 1767 return {}; 1768 } 1769 1770 const DSAStackTy::DSAVarData DSAStackTy::hasInnermostDSA( 1771 ValueDecl *D, const llvm::function_ref<bool(OpenMPClauseKind)> CPred, 1772 const llvm::function_ref<bool(OpenMPDirectiveKind)> DPred, 1773 bool FromParent) const { 1774 if (isStackEmpty()) 1775 return {}; 1776 D = getCanonicalDecl(D); 1777 const_iterator StartI = begin(); 1778 const_iterator EndI = end(); 1779 if (FromParent && StartI != EndI) 1780 ++StartI; 1781 if (StartI == EndI || !DPred(StartI->Directive)) 1782 return {}; 1783 const_iterator NewI = StartI; 1784 DSAVarData DVar = getDSA(NewI, D); 1785 return (NewI == StartI && CPred(DVar.CKind)) ? DVar : DSAVarData(); 1786 } 1787 1788 bool DSAStackTy::hasExplicitDSA( 1789 const ValueDecl *D, const llvm::function_ref<bool(OpenMPClauseKind)> CPred, 1790 unsigned Level, bool NotLastprivate) const { 1791 if (getStackSize() <= Level) 1792 return false; 1793 D = getCanonicalDecl(D); 1794 const SharingMapTy &StackElem = getStackElemAtLevel(Level); 1795 auto I = StackElem.SharingMap.find(D); 1796 if (I != StackElem.SharingMap.end() && 1797 I->getSecond().RefExpr.getPointer() && 1798 CPred(I->getSecond().Attributes) && 1799 (!NotLastprivate || !I->getSecond().RefExpr.getInt())) 1800 return true; 1801 // Check predetermined rules for the loop control variables. 1802 auto LI = StackElem.LCVMap.find(D); 1803 if (LI != StackElem.LCVMap.end()) 1804 return CPred(OMPC_private); 1805 return false; 1806 } 1807 1808 bool DSAStackTy::hasExplicitDirective( 1809 const llvm::function_ref<bool(OpenMPDirectiveKind)> DPred, 1810 unsigned Level) const { 1811 if (getStackSize() <= Level) 1812 return false; 1813 const SharingMapTy &StackElem = getStackElemAtLevel(Level); 1814 return DPred(StackElem.Directive); 1815 } 1816 1817 bool DSAStackTy::hasDirective( 1818 const llvm::function_ref<bool(OpenMPDirectiveKind, 1819 const DeclarationNameInfo &, SourceLocation)> 1820 DPred, 1821 bool FromParent) const { 1822 // We look only in the enclosing region. 1823 size_t Skip = FromParent ? 2 : 1; 1824 for (const_iterator I = begin() + std::min(Skip, getStackSize()), E = end(); 1825 I != E; ++I) { 1826 if (DPred(I->Directive, I->DirectiveName, I->ConstructLoc)) 1827 return true; 1828 } 1829 return false; 1830 } 1831 1832 void Sema::InitDataSharingAttributesStack() { 1833 VarDataSharingAttributesStack = new DSAStackTy(*this); 1834 } 1835 1836 #define DSAStack static_cast<DSAStackTy *>(VarDataSharingAttributesStack) 1837 1838 void Sema::pushOpenMPFunctionRegion() { 1839 DSAStack->pushFunction(); 1840 } 1841 1842 void Sema::popOpenMPFunctionRegion(const FunctionScopeInfo *OldFSI) { 1843 DSAStack->popFunction(OldFSI); 1844 } 1845 1846 static bool isOpenMPDeviceDelayedContext(Sema &S) { 1847 assert(S.LangOpts.OpenMP && S.LangOpts.OpenMPIsDevice && 1848 "Expected OpenMP device compilation."); 1849 return !S.isInOpenMPTargetExecutionDirective() && 1850 !S.isInOpenMPDeclareTargetContext(); 1851 } 1852 1853 namespace { 1854 /// Status of the function emission on the host/device. 1855 enum class FunctionEmissionStatus { 1856 Emitted, 1857 Discarded, 1858 Unknown, 1859 }; 1860 } // anonymous namespace 1861 1862 Sema::DeviceDiagBuilder Sema::diagIfOpenMPDeviceCode(SourceLocation Loc, 1863 unsigned DiagID) { 1864 assert(LangOpts.OpenMP && LangOpts.OpenMPIsDevice && 1865 "Expected OpenMP device compilation."); 1866 1867 FunctionDecl *FD = getCurFunctionDecl(); 1868 DeviceDiagBuilder::Kind Kind = DeviceDiagBuilder::K_Nop; 1869 if (FD) { 1870 FunctionEmissionStatus FES = getEmissionStatus(FD); 1871 switch (FES) { 1872 case FunctionEmissionStatus::Emitted: 1873 Kind = DeviceDiagBuilder::K_Immediate; 1874 break; 1875 case FunctionEmissionStatus::Unknown: 1876 Kind = isOpenMPDeviceDelayedContext(*this) 1877 ? DeviceDiagBuilder::K_Deferred 1878 : DeviceDiagBuilder::K_Immediate; 1879 break; 1880 case FunctionEmissionStatus::TemplateDiscarded: 1881 case FunctionEmissionStatus::OMPDiscarded: 1882 Kind = DeviceDiagBuilder::K_Nop; 1883 break; 1884 case FunctionEmissionStatus::CUDADiscarded: 1885 llvm_unreachable("CUDADiscarded unexpected in OpenMP device compilation"); 1886 break; 1887 } 1888 } 1889 1890 return DeviceDiagBuilder(Kind, Loc, DiagID, getCurFunctionDecl(), *this); 1891 } 1892 1893 Sema::DeviceDiagBuilder Sema::diagIfOpenMPHostCode(SourceLocation Loc, 1894 unsigned DiagID) { 1895 assert(LangOpts.OpenMP && !LangOpts.OpenMPIsDevice && 1896 "Expected OpenMP host compilation."); 1897 FunctionEmissionStatus FES = getEmissionStatus(getCurFunctionDecl()); 1898 DeviceDiagBuilder::Kind Kind = DeviceDiagBuilder::K_Nop; 1899 switch (FES) { 1900 case FunctionEmissionStatus::Emitted: 1901 Kind = DeviceDiagBuilder::K_Immediate; 1902 break; 1903 case FunctionEmissionStatus::Unknown: 1904 Kind = DeviceDiagBuilder::K_Deferred; 1905 break; 1906 case FunctionEmissionStatus::TemplateDiscarded: 1907 case FunctionEmissionStatus::OMPDiscarded: 1908 case FunctionEmissionStatus::CUDADiscarded: 1909 Kind = DeviceDiagBuilder::K_Nop; 1910 break; 1911 } 1912 1913 return DeviceDiagBuilder(Kind, Loc, DiagID, getCurFunctionDecl(), *this); 1914 } 1915 1916 static OpenMPDefaultmapClauseKind 1917 getVariableCategoryFromDecl(const LangOptions &LO, const ValueDecl *VD) { 1918 if (LO.OpenMP <= 45) { 1919 if (VD->getType().getNonReferenceType()->isScalarType()) 1920 return OMPC_DEFAULTMAP_scalar; 1921 return OMPC_DEFAULTMAP_aggregate; 1922 } 1923 if (VD->getType().getNonReferenceType()->isAnyPointerType()) 1924 return OMPC_DEFAULTMAP_pointer; 1925 if (VD->getType().getNonReferenceType()->isScalarType()) 1926 return OMPC_DEFAULTMAP_scalar; 1927 return OMPC_DEFAULTMAP_aggregate; 1928 } 1929 1930 bool Sema::isOpenMPCapturedByRef(const ValueDecl *D, unsigned Level, 1931 unsigned OpenMPCaptureLevel) const { 1932 assert(LangOpts.OpenMP && "OpenMP is not allowed"); 1933 1934 ASTContext &Ctx = getASTContext(); 1935 bool IsByRef = true; 1936 1937 // Find the directive that is associated with the provided scope. 1938 D = cast<ValueDecl>(D->getCanonicalDecl()); 1939 QualType Ty = D->getType(); 1940 1941 bool IsVariableUsedInMapClause = false; 1942 if (DSAStack->hasExplicitDirective(isOpenMPTargetExecutionDirective, Level)) { 1943 // This table summarizes how a given variable should be passed to the device 1944 // given its type and the clauses where it appears. This table is based on 1945 // the description in OpenMP 4.5 [2.10.4, target Construct] and 1946 // OpenMP 4.5 [2.15.5, Data-mapping Attribute Rules and Clauses]. 1947 // 1948 // ========================================================================= 1949 // | type | defaultmap | pvt | first | is_device_ptr | map | res. | 1950 // | |(tofrom:scalar)| | pvt | | | | 1951 // ========================================================================= 1952 // | scl | | | | - | | bycopy| 1953 // | scl | | - | x | - | - | bycopy| 1954 // | scl | | x | - | - | - | null | 1955 // | scl | x | | | - | | byref | 1956 // | scl | x | - | x | - | - | bycopy| 1957 // | scl | x | x | - | - | - | null | 1958 // | scl | | - | - | - | x | byref | 1959 // | scl | x | - | - | - | x | byref | 1960 // 1961 // | agg | n.a. | | | - | | byref | 1962 // | agg | n.a. | - | x | - | - | byref | 1963 // | agg | n.a. | x | - | - | - | null | 1964 // | agg | n.a. | - | - | - | x | byref | 1965 // | agg | n.a. | - | - | - | x[] | byref | 1966 // 1967 // | ptr | n.a. | | | - | | bycopy| 1968 // | ptr | n.a. | - | x | - | - | bycopy| 1969 // | ptr | n.a. | x | - | - | - | null | 1970 // | ptr | n.a. | - | - | - | x | byref | 1971 // | ptr | n.a. | - | - | - | x[] | bycopy| 1972 // | ptr | n.a. | - | - | x | | bycopy| 1973 // | ptr | n.a. | - | - | x | x | bycopy| 1974 // | ptr | n.a. | - | - | x | x[] | bycopy| 1975 // ========================================================================= 1976 // Legend: 1977 // scl - scalar 1978 // ptr - pointer 1979 // agg - aggregate 1980 // x - applies 1981 // - - invalid in this combination 1982 // [] - mapped with an array section 1983 // byref - should be mapped by reference 1984 // byval - should be mapped by value 1985 // null - initialize a local variable to null on the device 1986 // 1987 // Observations: 1988 // - All scalar declarations that show up in a map clause have to be passed 1989 // by reference, because they may have been mapped in the enclosing data 1990 // environment. 1991 // - If the scalar value does not fit the size of uintptr, it has to be 1992 // passed by reference, regardless the result in the table above. 1993 // - For pointers mapped by value that have either an implicit map or an 1994 // array section, the runtime library may pass the NULL value to the 1995 // device instead of the value passed to it by the compiler. 1996 1997 if (Ty->isReferenceType()) 1998 Ty = Ty->castAs<ReferenceType>()->getPointeeType(); 1999 2000 // Locate map clauses and see if the variable being captured is referred to 2001 // in any of those clauses. Here we only care about variables, not fields, 2002 // because fields are part of aggregates. 2003 bool IsVariableAssociatedWithSection = false; 2004 2005 DSAStack->checkMappableExprComponentListsForDeclAtLevel( 2006 D, Level, 2007 [&IsVariableUsedInMapClause, &IsVariableAssociatedWithSection, D]( 2008 OMPClauseMappableExprCommon::MappableExprComponentListRef 2009 MapExprComponents, 2010 OpenMPClauseKind WhereFoundClauseKind) { 2011 // Only the map clause information influences how a variable is 2012 // captured. E.g. is_device_ptr does not require changing the default 2013 // behavior. 2014 if (WhereFoundClauseKind != OMPC_map) 2015 return false; 2016 2017 auto EI = MapExprComponents.rbegin(); 2018 auto EE = MapExprComponents.rend(); 2019 2020 assert(EI != EE && "Invalid map expression!"); 2021 2022 if (isa<DeclRefExpr>(EI->getAssociatedExpression())) 2023 IsVariableUsedInMapClause |= EI->getAssociatedDeclaration() == D; 2024 2025 ++EI; 2026 if (EI == EE) 2027 return false; 2028 2029 if (isa<ArraySubscriptExpr>(EI->getAssociatedExpression()) || 2030 isa<OMPArraySectionExpr>(EI->getAssociatedExpression()) || 2031 isa<MemberExpr>(EI->getAssociatedExpression()) || 2032 isa<OMPArrayShapingExpr>(EI->getAssociatedExpression())) { 2033 IsVariableAssociatedWithSection = true; 2034 // There is nothing more we need to know about this variable. 2035 return true; 2036 } 2037 2038 // Keep looking for more map info. 2039 return false; 2040 }); 2041 2042 if (IsVariableUsedInMapClause) { 2043 // If variable is identified in a map clause it is always captured by 2044 // reference except if it is a pointer that is dereferenced somehow. 2045 IsByRef = !(Ty->isPointerType() && IsVariableAssociatedWithSection); 2046 } else { 2047 // By default, all the data that has a scalar type is mapped by copy 2048 // (except for reduction variables). 2049 // Defaultmap scalar is mutual exclusive to defaultmap pointer 2050 IsByRef = 2051 (DSAStack->isForceCaptureByReferenceInTargetExecutable() && 2052 !Ty->isAnyPointerType()) || 2053 !Ty->isScalarType() || 2054 DSAStack->isDefaultmapCapturedByRef( 2055 Level, getVariableCategoryFromDecl(LangOpts, D)) || 2056 DSAStack->hasExplicitDSA( 2057 D, [](OpenMPClauseKind K) { return K == OMPC_reduction; }, Level); 2058 } 2059 } 2060 2061 if (IsByRef && Ty.getNonReferenceType()->isScalarType()) { 2062 IsByRef = 2063 ((IsVariableUsedInMapClause && 2064 DSAStack->getCaptureRegion(Level, OpenMPCaptureLevel) == 2065 OMPD_target) || 2066 !(DSAStack->hasExplicitDSA( 2067 D, 2068 [](OpenMPClauseKind K) -> bool { 2069 return K == OMPC_firstprivate; 2070 }, 2071 Level, /*NotLastprivate=*/true) || 2072 DSAStack->isUsesAllocatorsDecl(Level, D))) && 2073 // If the variable is artificial and must be captured by value - try to 2074 // capture by value. 2075 !(isa<OMPCapturedExprDecl>(D) && !D->hasAttr<OMPCaptureNoInitAttr>() && 2076 !cast<OMPCapturedExprDecl>(D)->getInit()->isGLValue()) && 2077 // If the variable is implicitly firstprivate and scalar - capture by 2078 // copy 2079 !(DSAStack->getDefaultDSA() == DSA_firstprivate && 2080 !DSAStack->hasExplicitDSA( 2081 D, [](OpenMPClauseKind K) { return K != OMPC_unknown; }, Level) && 2082 !DSAStack->isLoopControlVariable(D, Level).first); 2083 } 2084 2085 // When passing data by copy, we need to make sure it fits the uintptr size 2086 // and alignment, because the runtime library only deals with uintptr types. 2087 // If it does not fit the uintptr size, we need to pass the data by reference 2088 // instead. 2089 if (!IsByRef && 2090 (Ctx.getTypeSizeInChars(Ty) > 2091 Ctx.getTypeSizeInChars(Ctx.getUIntPtrType()) || 2092 Ctx.getDeclAlign(D) > Ctx.getTypeAlignInChars(Ctx.getUIntPtrType()))) { 2093 IsByRef = true; 2094 } 2095 2096 return IsByRef; 2097 } 2098 2099 unsigned Sema::getOpenMPNestingLevel() const { 2100 assert(getLangOpts().OpenMP); 2101 return DSAStack->getNestingLevel(); 2102 } 2103 2104 bool Sema::isInOpenMPTargetExecutionDirective() const { 2105 return (isOpenMPTargetExecutionDirective(DSAStack->getCurrentDirective()) && 2106 !DSAStack->isClauseParsingMode()) || 2107 DSAStack->hasDirective( 2108 [](OpenMPDirectiveKind K, const DeclarationNameInfo &, 2109 SourceLocation) -> bool { 2110 return isOpenMPTargetExecutionDirective(K); 2111 }, 2112 false); 2113 } 2114 2115 VarDecl *Sema::isOpenMPCapturedDecl(ValueDecl *D, bool CheckScopeInfo, 2116 unsigned StopAt) { 2117 assert(LangOpts.OpenMP && "OpenMP is not allowed"); 2118 D = getCanonicalDecl(D); 2119 2120 auto *VD = dyn_cast<VarDecl>(D); 2121 // Do not capture constexpr variables. 2122 if (VD && VD->isConstexpr()) 2123 return nullptr; 2124 2125 // If we want to determine whether the variable should be captured from the 2126 // perspective of the current capturing scope, and we've already left all the 2127 // capturing scopes of the top directive on the stack, check from the 2128 // perspective of its parent directive (if any) instead. 2129 DSAStackTy::ParentDirectiveScope InParentDirectiveRAII( 2130 *DSAStack, CheckScopeInfo && DSAStack->isBodyComplete()); 2131 2132 // If we are attempting to capture a global variable in a directive with 2133 // 'target' we return true so that this global is also mapped to the device. 2134 // 2135 if (VD && !VD->hasLocalStorage() && 2136 (getCurCapturedRegion() || getCurBlock() || getCurLambda())) { 2137 if (isInOpenMPDeclareTargetContext()) { 2138 // Try to mark variable as declare target if it is used in capturing 2139 // regions. 2140 if (LangOpts.OpenMP <= 45 && 2141 !OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD)) 2142 checkDeclIsAllowedInOpenMPTarget(nullptr, VD); 2143 return nullptr; 2144 } else if (isInOpenMPTargetExecutionDirective()) { 2145 // If the declaration is enclosed in a 'declare target' directive, 2146 // then it should not be captured. 2147 // 2148 if (OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD)) 2149 return nullptr; 2150 CapturedRegionScopeInfo *CSI = nullptr; 2151 for (FunctionScopeInfo *FSI : llvm::drop_begin( 2152 llvm::reverse(FunctionScopes), 2153 CheckScopeInfo ? (FunctionScopes.size() - (StopAt + 1)) : 0)) { 2154 if (!isa<CapturingScopeInfo>(FSI)) 2155 return nullptr; 2156 if (auto *RSI = dyn_cast<CapturedRegionScopeInfo>(FSI)) 2157 if (RSI->CapRegionKind == CR_OpenMP) { 2158 CSI = RSI; 2159 break; 2160 } 2161 } 2162 SmallVector<OpenMPDirectiveKind, 4> Regions; 2163 getOpenMPCaptureRegions(Regions, 2164 DSAStack->getDirective(CSI->OpenMPLevel)); 2165 if (Regions[CSI->OpenMPCaptureLevel] != OMPD_task) 2166 return VD; 2167 } 2168 } 2169 2170 if (CheckScopeInfo) { 2171 bool OpenMPFound = false; 2172 for (unsigned I = StopAt + 1; I > 0; --I) { 2173 FunctionScopeInfo *FSI = FunctionScopes[I - 1]; 2174 if(!isa<CapturingScopeInfo>(FSI)) 2175 return nullptr; 2176 if (auto *RSI = dyn_cast<CapturedRegionScopeInfo>(FSI)) 2177 if (RSI->CapRegionKind == CR_OpenMP) { 2178 OpenMPFound = true; 2179 break; 2180 } 2181 } 2182 if (!OpenMPFound) 2183 return nullptr; 2184 } 2185 2186 if (DSAStack->getCurrentDirective() != OMPD_unknown && 2187 (!DSAStack->isClauseParsingMode() || 2188 DSAStack->getParentDirective() != OMPD_unknown)) { 2189 auto &&Info = DSAStack->isLoopControlVariable(D); 2190 if (Info.first || 2191 (VD && VD->hasLocalStorage() && 2192 isImplicitOrExplicitTaskingRegion(DSAStack->getCurrentDirective())) || 2193 (VD && DSAStack->isForceVarCapturing())) 2194 return VD ? VD : Info.second; 2195 DSAStackTy::DSAVarData DVarTop = 2196 DSAStack->getTopDSA(D, DSAStack->isClauseParsingMode()); 2197 if (DVarTop.CKind != OMPC_unknown && isOpenMPPrivate(DVarTop.CKind)) 2198 return VD ? VD : cast<VarDecl>(DVarTop.PrivateCopy->getDecl()); 2199 // Threadprivate variables must not be captured. 2200 if (isOpenMPThreadPrivate(DVarTop.CKind)) 2201 return nullptr; 2202 // The variable is not private or it is the variable in the directive with 2203 // default(none) clause and not used in any clause. 2204 DSAStackTy::DSAVarData DVarPrivate = DSAStack->hasDSA( 2205 D, isOpenMPPrivate, [](OpenMPDirectiveKind) { return true; }, 2206 DSAStack->isClauseParsingMode()); 2207 // Global shared must not be captured. 2208 if (VD && !VD->hasLocalStorage() && DVarPrivate.CKind == OMPC_unknown && 2209 ((DSAStack->getDefaultDSA() != DSA_none && 2210 DSAStack->getDefaultDSA() != DSA_firstprivate) || 2211 DVarTop.CKind == OMPC_shared)) 2212 return nullptr; 2213 if (DVarPrivate.CKind != OMPC_unknown || 2214 (VD && (DSAStack->getDefaultDSA() == DSA_none || 2215 DSAStack->getDefaultDSA() == DSA_firstprivate))) 2216 return VD ? VD : cast<VarDecl>(DVarPrivate.PrivateCopy->getDecl()); 2217 } 2218 return nullptr; 2219 } 2220 2221 void Sema::adjustOpenMPTargetScopeIndex(unsigned &FunctionScopesIndex, 2222 unsigned Level) const { 2223 FunctionScopesIndex -= getOpenMPCaptureLevels(DSAStack->getDirective(Level)); 2224 } 2225 2226 void Sema::startOpenMPLoop() { 2227 assert(LangOpts.OpenMP && "OpenMP must be enabled."); 2228 if (isOpenMPLoopDirective(DSAStack->getCurrentDirective())) 2229 DSAStack->loopInit(); 2230 } 2231 2232 void Sema::startOpenMPCXXRangeFor() { 2233 assert(LangOpts.OpenMP && "OpenMP must be enabled."); 2234 if (isOpenMPLoopDirective(DSAStack->getCurrentDirective())) { 2235 DSAStack->resetPossibleLoopCounter(); 2236 DSAStack->loopStart(); 2237 } 2238 } 2239 2240 OpenMPClauseKind Sema::isOpenMPPrivateDecl(ValueDecl *D, unsigned Level, 2241 unsigned CapLevel) const { 2242 assert(LangOpts.OpenMP && "OpenMP is not allowed"); 2243 if (DSAStack->hasExplicitDirective( 2244 [](OpenMPDirectiveKind K) { return isOpenMPTaskingDirective(K); }, 2245 Level)) { 2246 bool IsTriviallyCopyable = 2247 D->getType().getNonReferenceType().isTriviallyCopyableType(Context); 2248 OpenMPDirectiveKind DKind = DSAStack->getDirective(Level); 2249 SmallVector<OpenMPDirectiveKind, 4> CaptureRegions; 2250 getOpenMPCaptureRegions(CaptureRegions, DKind); 2251 if (isOpenMPTaskingDirective(CaptureRegions[CapLevel]) && 2252 (IsTriviallyCopyable || 2253 !isOpenMPTaskLoopDirective(CaptureRegions[CapLevel]))) { 2254 if (DSAStack->hasExplicitDSA( 2255 D, [](OpenMPClauseKind K) { return K == OMPC_firstprivate; }, 2256 Level, /*NotLastprivate=*/true)) 2257 return OMPC_firstprivate; 2258 DSAStackTy::DSAVarData DVar = DSAStack->getImplicitDSA(D, Level); 2259 if (DVar.CKind != OMPC_shared && 2260 !DSAStack->isLoopControlVariable(D, Level).first && !DVar.RefExpr) { 2261 DSAStack->addImplicitTaskFirstprivate(Level, D); 2262 return OMPC_firstprivate; 2263 } 2264 } 2265 } 2266 if (isOpenMPLoopDirective(DSAStack->getCurrentDirective())) { 2267 if (DSAStack->getAssociatedLoops() > 0 && 2268 !DSAStack->isLoopStarted()) { 2269 DSAStack->resetPossibleLoopCounter(D); 2270 DSAStack->loopStart(); 2271 return OMPC_private; 2272 } 2273 if ((DSAStack->getPossiblyLoopCunter() == D->getCanonicalDecl() || 2274 DSAStack->isLoopControlVariable(D).first) && 2275 !DSAStack->hasExplicitDSA( 2276 D, [](OpenMPClauseKind K) { return K != OMPC_private; }, Level) && 2277 !isOpenMPSimdDirective(DSAStack->getCurrentDirective())) 2278 return OMPC_private; 2279 } 2280 if (const auto *VD = dyn_cast<VarDecl>(D)) { 2281 if (DSAStack->isThreadPrivate(const_cast<VarDecl *>(VD)) && 2282 DSAStack->isForceVarCapturing() && 2283 !DSAStack->hasExplicitDSA( 2284 D, [](OpenMPClauseKind K) { return K == OMPC_copyin; }, Level)) 2285 return OMPC_private; 2286 } 2287 // User-defined allocators are private since they must be defined in the 2288 // context of target region. 2289 if (DSAStack->hasExplicitDirective(isOpenMPTargetExecutionDirective, Level) && 2290 DSAStack->isUsesAllocatorsDecl(Level, D).getValueOr( 2291 DSAStackTy::UsesAllocatorsDeclKind::AllocatorTrait) == 2292 DSAStackTy::UsesAllocatorsDeclKind::UserDefinedAllocator) 2293 return OMPC_private; 2294 return (DSAStack->hasExplicitDSA( 2295 D, [](OpenMPClauseKind K) { return K == OMPC_private; }, Level) || 2296 (DSAStack->isClauseParsingMode() && 2297 DSAStack->getClauseParsingMode() == OMPC_private) || 2298 // Consider taskgroup reduction descriptor variable a private 2299 // to avoid possible capture in the region. 2300 (DSAStack->hasExplicitDirective( 2301 [](OpenMPDirectiveKind K) { 2302 return K == OMPD_taskgroup || 2303 ((isOpenMPParallelDirective(K) || 2304 isOpenMPWorksharingDirective(K)) && 2305 !isOpenMPSimdDirective(K)); 2306 }, 2307 Level) && 2308 DSAStack->isTaskgroupReductionRef(D, Level))) 2309 ? OMPC_private 2310 : OMPC_unknown; 2311 } 2312 2313 void Sema::setOpenMPCaptureKind(FieldDecl *FD, const ValueDecl *D, 2314 unsigned Level) { 2315 assert(LangOpts.OpenMP && "OpenMP is not allowed"); 2316 D = getCanonicalDecl(D); 2317 OpenMPClauseKind OMPC = OMPC_unknown; 2318 for (unsigned I = DSAStack->getNestingLevel() + 1; I > Level; --I) { 2319 const unsigned NewLevel = I - 1; 2320 if (DSAStack->hasExplicitDSA(D, 2321 [&OMPC](const OpenMPClauseKind K) { 2322 if (isOpenMPPrivate(K)) { 2323 OMPC = K; 2324 return true; 2325 } 2326 return false; 2327 }, 2328 NewLevel)) 2329 break; 2330 if (DSAStack->checkMappableExprComponentListsForDeclAtLevel( 2331 D, NewLevel, 2332 [](OMPClauseMappableExprCommon::MappableExprComponentListRef, 2333 OpenMPClauseKind) { return true; })) { 2334 OMPC = OMPC_map; 2335 break; 2336 } 2337 if (DSAStack->hasExplicitDirective(isOpenMPTargetExecutionDirective, 2338 NewLevel)) { 2339 OMPC = OMPC_map; 2340 if (DSAStack->mustBeFirstprivateAtLevel( 2341 NewLevel, getVariableCategoryFromDecl(LangOpts, D))) 2342 OMPC = OMPC_firstprivate; 2343 break; 2344 } 2345 } 2346 if (OMPC != OMPC_unknown) 2347 FD->addAttr(OMPCaptureKindAttr::CreateImplicit(Context, unsigned(OMPC))); 2348 } 2349 2350 bool Sema::isOpenMPTargetCapturedDecl(const ValueDecl *D, unsigned Level, 2351 unsigned CaptureLevel) const { 2352 assert(LangOpts.OpenMP && "OpenMP is not allowed"); 2353 // Return true if the current level is no longer enclosed in a target region. 2354 2355 SmallVector<OpenMPDirectiveKind, 4> Regions; 2356 getOpenMPCaptureRegions(Regions, DSAStack->getDirective(Level)); 2357 const auto *VD = dyn_cast<VarDecl>(D); 2358 return VD && !VD->hasLocalStorage() && 2359 DSAStack->hasExplicitDirective(isOpenMPTargetExecutionDirective, 2360 Level) && 2361 Regions[CaptureLevel] != OMPD_task; 2362 } 2363 2364 bool Sema::isOpenMPGlobalCapturedDecl(ValueDecl *D, unsigned Level, 2365 unsigned CaptureLevel) const { 2366 assert(LangOpts.OpenMP && "OpenMP is not allowed"); 2367 // Return true if the current level is no longer enclosed in a target region. 2368 2369 if (const auto *VD = dyn_cast<VarDecl>(D)) { 2370 if (!VD->hasLocalStorage()) { 2371 DSAStackTy::DSAVarData TopDVar = 2372 DSAStack->getTopDSA(D, /*FromParent=*/false); 2373 unsigned NumLevels = 2374 getOpenMPCaptureLevels(DSAStack->getDirective(Level)); 2375 if (Level == 0) 2376 return (NumLevels == CaptureLevel + 1) && TopDVar.CKind != OMPC_shared; 2377 DSAStackTy::DSAVarData DVar = DSAStack->getImplicitDSA(D, Level - 1); 2378 return DVar.CKind != OMPC_shared || 2379 isOpenMPGlobalCapturedDecl( 2380 D, Level - 1, 2381 getOpenMPCaptureLevels(DSAStack->getDirective(Level - 1)) - 1); 2382 } 2383 } 2384 return true; 2385 } 2386 2387 void Sema::DestroyDataSharingAttributesStack() { delete DSAStack; } 2388 2389 void Sema::ActOnOpenMPBeginDeclareVariant(SourceLocation Loc, 2390 OMPTraitInfo &TI) { 2391 if (!OMPDeclareVariantScopes.empty()) { 2392 Diag(Loc, diag::warn_nested_declare_variant); 2393 return; 2394 } 2395 OMPDeclareVariantScopes.push_back(OMPDeclareVariantScope(TI)); 2396 } 2397 2398 void Sema::ActOnOpenMPEndDeclareVariant() { 2399 assert(isInOpenMPDeclareVariantScope() && 2400 "Not in OpenMP declare variant scope!"); 2401 2402 OMPDeclareVariantScopes.pop_back(); 2403 } 2404 2405 void Sema::finalizeOpenMPDelayedAnalysis(const FunctionDecl *Caller, 2406 const FunctionDecl *Callee, 2407 SourceLocation Loc) { 2408 assert(LangOpts.OpenMP && "Expected OpenMP compilation mode."); 2409 Optional<OMPDeclareTargetDeclAttr::DevTypeTy> DevTy = 2410 OMPDeclareTargetDeclAttr::getDeviceType(Caller->getMostRecentDecl()); 2411 // Ignore host functions during device analyzis. 2412 if (LangOpts.OpenMPIsDevice && DevTy && 2413 *DevTy == OMPDeclareTargetDeclAttr::DT_Host) 2414 return; 2415 // Ignore nohost functions during host analyzis. 2416 if (!LangOpts.OpenMPIsDevice && DevTy && 2417 *DevTy == OMPDeclareTargetDeclAttr::DT_NoHost) 2418 return; 2419 const FunctionDecl *FD = Callee->getMostRecentDecl(); 2420 DevTy = OMPDeclareTargetDeclAttr::getDeviceType(FD); 2421 if (LangOpts.OpenMPIsDevice && DevTy && 2422 *DevTy == OMPDeclareTargetDeclAttr::DT_Host) { 2423 // Diagnose host function called during device codegen. 2424 StringRef HostDevTy = 2425 getOpenMPSimpleClauseTypeName(OMPC_device_type, OMPC_DEVICE_TYPE_host); 2426 Diag(Loc, diag::err_omp_wrong_device_function_call) << HostDevTy << 0; 2427 Diag(FD->getAttr<OMPDeclareTargetDeclAttr>()->getLocation(), 2428 diag::note_omp_marked_device_type_here) 2429 << HostDevTy; 2430 return; 2431 } 2432 if (!LangOpts.OpenMPIsDevice && DevTy && 2433 *DevTy == OMPDeclareTargetDeclAttr::DT_NoHost) { 2434 // Diagnose nohost function called during host codegen. 2435 StringRef NoHostDevTy = getOpenMPSimpleClauseTypeName( 2436 OMPC_device_type, OMPC_DEVICE_TYPE_nohost); 2437 Diag(Loc, diag::err_omp_wrong_device_function_call) << NoHostDevTy << 1; 2438 Diag(FD->getAttr<OMPDeclareTargetDeclAttr>()->getLocation(), 2439 diag::note_omp_marked_device_type_here) 2440 << NoHostDevTy; 2441 } 2442 } 2443 2444 void Sema::StartOpenMPDSABlock(OpenMPDirectiveKind DKind, 2445 const DeclarationNameInfo &DirName, 2446 Scope *CurScope, SourceLocation Loc) { 2447 DSAStack->push(DKind, DirName, CurScope, Loc); 2448 PushExpressionEvaluationContext( 2449 ExpressionEvaluationContext::PotentiallyEvaluated); 2450 } 2451 2452 void Sema::StartOpenMPClause(OpenMPClauseKind K) { 2453 DSAStack->setClauseParsingMode(K); 2454 } 2455 2456 void Sema::EndOpenMPClause() { 2457 DSAStack->setClauseParsingMode(/*K=*/OMPC_unknown); 2458 } 2459 2460 static std::pair<ValueDecl *, bool> 2461 getPrivateItem(Sema &S, Expr *&RefExpr, SourceLocation &ELoc, 2462 SourceRange &ERange, bool AllowArraySection = false); 2463 2464 /// Check consistency of the reduction clauses. 2465 static void checkReductionClauses(Sema &S, DSAStackTy *Stack, 2466 ArrayRef<OMPClause *> Clauses) { 2467 bool InscanFound = false; 2468 SourceLocation InscanLoc; 2469 // OpenMP 5.0, 2.19.5.4 reduction Clause, Restrictions. 2470 // A reduction clause without the inscan reduction-modifier may not appear on 2471 // a construct on which a reduction clause with the inscan reduction-modifier 2472 // appears. 2473 for (OMPClause *C : Clauses) { 2474 if (C->getClauseKind() != OMPC_reduction) 2475 continue; 2476 auto *RC = cast<OMPReductionClause>(C); 2477 if (RC->getModifier() == OMPC_REDUCTION_inscan) { 2478 InscanFound = true; 2479 InscanLoc = RC->getModifierLoc(); 2480 continue; 2481 } 2482 if (RC->getModifier() == OMPC_REDUCTION_task) { 2483 // OpenMP 5.0, 2.19.5.4 reduction Clause. 2484 // A reduction clause with the task reduction-modifier may only appear on 2485 // a parallel construct, a worksharing construct or a combined or 2486 // composite construct for which any of the aforementioned constructs is a 2487 // constituent construct and simd or loop are not constituent constructs. 2488 OpenMPDirectiveKind CurDir = Stack->getCurrentDirective(); 2489 if (!(isOpenMPParallelDirective(CurDir) || 2490 isOpenMPWorksharingDirective(CurDir)) || 2491 isOpenMPSimdDirective(CurDir)) 2492 S.Diag(RC->getModifierLoc(), 2493 diag::err_omp_reduction_task_not_parallel_or_worksharing); 2494 continue; 2495 } 2496 } 2497 if (InscanFound) { 2498 for (OMPClause *C : Clauses) { 2499 if (C->getClauseKind() != OMPC_reduction) 2500 continue; 2501 auto *RC = cast<OMPReductionClause>(C); 2502 if (RC->getModifier() != OMPC_REDUCTION_inscan) { 2503 S.Diag(RC->getModifier() == OMPC_REDUCTION_unknown 2504 ? RC->getBeginLoc() 2505 : RC->getModifierLoc(), 2506 diag::err_omp_inscan_reduction_expected); 2507 S.Diag(InscanLoc, diag::note_omp_previous_inscan_reduction); 2508 continue; 2509 } 2510 for (Expr *Ref : RC->varlists()) { 2511 assert(Ref && "NULL expr in OpenMP nontemporal clause."); 2512 SourceLocation ELoc; 2513 SourceRange ERange; 2514 Expr *SimpleRefExpr = Ref; 2515 auto Res = getPrivateItem(S, SimpleRefExpr, ELoc, ERange, 2516 /*AllowArraySection=*/true); 2517 ValueDecl *D = Res.first; 2518 if (!D) 2519 continue; 2520 if (!Stack->isUsedInScanDirective(getCanonicalDecl(D))) { 2521 S.Diag(Ref->getExprLoc(), 2522 diag::err_omp_reduction_not_inclusive_exclusive) 2523 << Ref->getSourceRange(); 2524 } 2525 } 2526 } 2527 } 2528 } 2529 2530 static void checkAllocateClauses(Sema &S, DSAStackTy *Stack, 2531 ArrayRef<OMPClause *> Clauses); 2532 static DeclRefExpr *buildCapture(Sema &S, ValueDecl *D, Expr *CaptureExpr, 2533 bool WithInit); 2534 2535 static void reportOriginalDsa(Sema &SemaRef, const DSAStackTy *Stack, 2536 const ValueDecl *D, 2537 const DSAStackTy::DSAVarData &DVar, 2538 bool IsLoopIterVar = false); 2539 2540 void Sema::EndOpenMPDSABlock(Stmt *CurDirective) { 2541 // OpenMP [2.14.3.5, Restrictions, C/C++, p.1] 2542 // A variable of class type (or array thereof) that appears in a lastprivate 2543 // clause requires an accessible, unambiguous default constructor for the 2544 // class type, unless the list item is also specified in a firstprivate 2545 // clause. 2546 if (const auto *D = dyn_cast_or_null<OMPExecutableDirective>(CurDirective)) { 2547 for (OMPClause *C : D->clauses()) { 2548 if (auto *Clause = dyn_cast<OMPLastprivateClause>(C)) { 2549 SmallVector<Expr *, 8> PrivateCopies; 2550 for (Expr *DE : Clause->varlists()) { 2551 if (DE->isValueDependent() || DE->isTypeDependent()) { 2552 PrivateCopies.push_back(nullptr); 2553 continue; 2554 } 2555 auto *DRE = cast<DeclRefExpr>(DE->IgnoreParens()); 2556 auto *VD = cast<VarDecl>(DRE->getDecl()); 2557 QualType Type = VD->getType().getNonReferenceType(); 2558 const DSAStackTy::DSAVarData DVar = 2559 DSAStack->getTopDSA(VD, /*FromParent=*/false); 2560 if (DVar.CKind == OMPC_lastprivate) { 2561 // Generate helper private variable and initialize it with the 2562 // default value. The address of the original variable is replaced 2563 // by the address of the new private variable in CodeGen. This new 2564 // variable is not added to IdResolver, so the code in the OpenMP 2565 // region uses original variable for proper diagnostics. 2566 VarDecl *VDPrivate = buildVarDecl( 2567 *this, DE->getExprLoc(), Type.getUnqualifiedType(), 2568 VD->getName(), VD->hasAttrs() ? &VD->getAttrs() : nullptr, DRE); 2569 ActOnUninitializedDecl(VDPrivate); 2570 if (VDPrivate->isInvalidDecl()) { 2571 PrivateCopies.push_back(nullptr); 2572 continue; 2573 } 2574 PrivateCopies.push_back(buildDeclRefExpr( 2575 *this, VDPrivate, DE->getType(), DE->getExprLoc())); 2576 } else { 2577 // The variable is also a firstprivate, so initialization sequence 2578 // for private copy is generated already. 2579 PrivateCopies.push_back(nullptr); 2580 } 2581 } 2582 Clause->setPrivateCopies(PrivateCopies); 2583 continue; 2584 } 2585 // Finalize nontemporal clause by handling private copies, if any. 2586 if (auto *Clause = dyn_cast<OMPNontemporalClause>(C)) { 2587 SmallVector<Expr *, 8> PrivateRefs; 2588 for (Expr *RefExpr : Clause->varlists()) { 2589 assert(RefExpr && "NULL expr in OpenMP nontemporal clause."); 2590 SourceLocation ELoc; 2591 SourceRange ERange; 2592 Expr *SimpleRefExpr = RefExpr; 2593 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange); 2594 if (Res.second) 2595 // It will be analyzed later. 2596 PrivateRefs.push_back(RefExpr); 2597 ValueDecl *D = Res.first; 2598 if (!D) 2599 continue; 2600 2601 const DSAStackTy::DSAVarData DVar = 2602 DSAStack->getTopDSA(D, /*FromParent=*/false); 2603 PrivateRefs.push_back(DVar.PrivateCopy ? DVar.PrivateCopy 2604 : SimpleRefExpr); 2605 } 2606 Clause->setPrivateRefs(PrivateRefs); 2607 continue; 2608 } 2609 if (auto *Clause = dyn_cast<OMPUsesAllocatorsClause>(C)) { 2610 for (unsigned I = 0, E = Clause->getNumberOfAllocators(); I < E; ++I) { 2611 OMPUsesAllocatorsClause::Data D = Clause->getAllocatorData(I); 2612 auto *DRE = dyn_cast<DeclRefExpr>(D.Allocator->IgnoreParenImpCasts()); 2613 if (!DRE) 2614 continue; 2615 ValueDecl *VD = DRE->getDecl(); 2616 if (!VD || !isa<VarDecl>(VD)) 2617 continue; 2618 DSAStackTy::DSAVarData DVar = 2619 DSAStack->getTopDSA(VD, /*FromParent=*/false); 2620 // OpenMP [2.12.5, target Construct] 2621 // Memory allocators that appear in a uses_allocators clause cannot 2622 // appear in other data-sharing attribute clauses or data-mapping 2623 // attribute clauses in the same construct. 2624 Expr *MapExpr = nullptr; 2625 if (DVar.RefExpr || 2626 DSAStack->checkMappableExprComponentListsForDecl( 2627 VD, /*CurrentRegionOnly=*/true, 2628 [VD, &MapExpr]( 2629 OMPClauseMappableExprCommon::MappableExprComponentListRef 2630 MapExprComponents, 2631 OpenMPClauseKind C) { 2632 auto MI = MapExprComponents.rbegin(); 2633 auto ME = MapExprComponents.rend(); 2634 if (MI != ME && 2635 MI->getAssociatedDeclaration()->getCanonicalDecl() == 2636 VD->getCanonicalDecl()) { 2637 MapExpr = MI->getAssociatedExpression(); 2638 return true; 2639 } 2640 return false; 2641 })) { 2642 Diag(D.Allocator->getExprLoc(), 2643 diag::err_omp_allocator_used_in_clauses) 2644 << D.Allocator->getSourceRange(); 2645 if (DVar.RefExpr) 2646 reportOriginalDsa(*this, DSAStack, VD, DVar); 2647 else 2648 Diag(MapExpr->getExprLoc(), diag::note_used_here) 2649 << MapExpr->getSourceRange(); 2650 } 2651 } 2652 continue; 2653 } 2654 } 2655 // Check allocate clauses. 2656 if (!CurContext->isDependentContext()) 2657 checkAllocateClauses(*this, DSAStack, D->clauses()); 2658 checkReductionClauses(*this, DSAStack, D->clauses()); 2659 } 2660 2661 DSAStack->pop(); 2662 DiscardCleanupsInEvaluationContext(); 2663 PopExpressionEvaluationContext(); 2664 } 2665 2666 static bool FinishOpenMPLinearClause(OMPLinearClause &Clause, DeclRefExpr *IV, 2667 Expr *NumIterations, Sema &SemaRef, 2668 Scope *S, DSAStackTy *Stack); 2669 2670 namespace { 2671 2672 class VarDeclFilterCCC final : public CorrectionCandidateCallback { 2673 private: 2674 Sema &SemaRef; 2675 2676 public: 2677 explicit VarDeclFilterCCC(Sema &S) : SemaRef(S) {} 2678 bool ValidateCandidate(const TypoCorrection &Candidate) override { 2679 NamedDecl *ND = Candidate.getCorrectionDecl(); 2680 if (const auto *VD = dyn_cast_or_null<VarDecl>(ND)) { 2681 return VD->hasGlobalStorage() && 2682 SemaRef.isDeclInScope(ND, SemaRef.getCurLexicalContext(), 2683 SemaRef.getCurScope()); 2684 } 2685 return false; 2686 } 2687 2688 std::unique_ptr<CorrectionCandidateCallback> clone() override { 2689 return std::make_unique<VarDeclFilterCCC>(*this); 2690 } 2691 2692 }; 2693 2694 class VarOrFuncDeclFilterCCC final : public CorrectionCandidateCallback { 2695 private: 2696 Sema &SemaRef; 2697 2698 public: 2699 explicit VarOrFuncDeclFilterCCC(Sema &S) : SemaRef(S) {} 2700 bool ValidateCandidate(const TypoCorrection &Candidate) override { 2701 NamedDecl *ND = Candidate.getCorrectionDecl(); 2702 if (ND && ((isa<VarDecl>(ND) && ND->getKind() == Decl::Var) || 2703 isa<FunctionDecl>(ND))) { 2704 return SemaRef.isDeclInScope(ND, SemaRef.getCurLexicalContext(), 2705 SemaRef.getCurScope()); 2706 } 2707 return false; 2708 } 2709 2710 std::unique_ptr<CorrectionCandidateCallback> clone() override { 2711 return std::make_unique<VarOrFuncDeclFilterCCC>(*this); 2712 } 2713 }; 2714 2715 } // namespace 2716 2717 ExprResult Sema::ActOnOpenMPIdExpression(Scope *CurScope, 2718 CXXScopeSpec &ScopeSpec, 2719 const DeclarationNameInfo &Id, 2720 OpenMPDirectiveKind Kind) { 2721 LookupResult Lookup(*this, Id, LookupOrdinaryName); 2722 LookupParsedName(Lookup, CurScope, &ScopeSpec, true); 2723 2724 if (Lookup.isAmbiguous()) 2725 return ExprError(); 2726 2727 VarDecl *VD; 2728 if (!Lookup.isSingleResult()) { 2729 VarDeclFilterCCC CCC(*this); 2730 if (TypoCorrection Corrected = 2731 CorrectTypo(Id, LookupOrdinaryName, CurScope, nullptr, CCC, 2732 CTK_ErrorRecovery)) { 2733 diagnoseTypo(Corrected, 2734 PDiag(Lookup.empty() 2735 ? diag::err_undeclared_var_use_suggest 2736 : diag::err_omp_expected_var_arg_suggest) 2737 << Id.getName()); 2738 VD = Corrected.getCorrectionDeclAs<VarDecl>(); 2739 } else { 2740 Diag(Id.getLoc(), Lookup.empty() ? diag::err_undeclared_var_use 2741 : diag::err_omp_expected_var_arg) 2742 << Id.getName(); 2743 return ExprError(); 2744 } 2745 } else if (!(VD = Lookup.getAsSingle<VarDecl>())) { 2746 Diag(Id.getLoc(), diag::err_omp_expected_var_arg) << Id.getName(); 2747 Diag(Lookup.getFoundDecl()->getLocation(), diag::note_declared_at); 2748 return ExprError(); 2749 } 2750 Lookup.suppressDiagnostics(); 2751 2752 // OpenMP [2.9.2, Syntax, C/C++] 2753 // Variables must be file-scope, namespace-scope, or static block-scope. 2754 if (Kind == OMPD_threadprivate && !VD->hasGlobalStorage()) { 2755 Diag(Id.getLoc(), diag::err_omp_global_var_arg) 2756 << getOpenMPDirectiveName(Kind) << !VD->isStaticLocal(); 2757 bool IsDecl = 2758 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly; 2759 Diag(VD->getLocation(), 2760 IsDecl ? diag::note_previous_decl : diag::note_defined_here) 2761 << VD; 2762 return ExprError(); 2763 } 2764 2765 VarDecl *CanonicalVD = VD->getCanonicalDecl(); 2766 NamedDecl *ND = CanonicalVD; 2767 // OpenMP [2.9.2, Restrictions, C/C++, p.2] 2768 // A threadprivate directive for file-scope variables must appear outside 2769 // any definition or declaration. 2770 if (CanonicalVD->getDeclContext()->isTranslationUnit() && 2771 !getCurLexicalContext()->isTranslationUnit()) { 2772 Diag(Id.getLoc(), diag::err_omp_var_scope) 2773 << getOpenMPDirectiveName(Kind) << VD; 2774 bool IsDecl = 2775 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly; 2776 Diag(VD->getLocation(), 2777 IsDecl ? diag::note_previous_decl : diag::note_defined_here) 2778 << VD; 2779 return ExprError(); 2780 } 2781 // OpenMP [2.9.2, Restrictions, C/C++, p.3] 2782 // A threadprivate directive for static class member variables must appear 2783 // in the class definition, in the same scope in which the member 2784 // variables are declared. 2785 if (CanonicalVD->isStaticDataMember() && 2786 !CanonicalVD->getDeclContext()->Equals(getCurLexicalContext())) { 2787 Diag(Id.getLoc(), diag::err_omp_var_scope) 2788 << getOpenMPDirectiveName(Kind) << VD; 2789 bool IsDecl = 2790 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly; 2791 Diag(VD->getLocation(), 2792 IsDecl ? diag::note_previous_decl : diag::note_defined_here) 2793 << VD; 2794 return ExprError(); 2795 } 2796 // OpenMP [2.9.2, Restrictions, C/C++, p.4] 2797 // A threadprivate directive for namespace-scope variables must appear 2798 // outside any definition or declaration other than the namespace 2799 // definition itself. 2800 if (CanonicalVD->getDeclContext()->isNamespace() && 2801 (!getCurLexicalContext()->isFileContext() || 2802 !getCurLexicalContext()->Encloses(CanonicalVD->getDeclContext()))) { 2803 Diag(Id.getLoc(), diag::err_omp_var_scope) 2804 << getOpenMPDirectiveName(Kind) << VD; 2805 bool IsDecl = 2806 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly; 2807 Diag(VD->getLocation(), 2808 IsDecl ? diag::note_previous_decl : diag::note_defined_here) 2809 << VD; 2810 return ExprError(); 2811 } 2812 // OpenMP [2.9.2, Restrictions, C/C++, p.6] 2813 // A threadprivate directive for static block-scope variables must appear 2814 // in the scope of the variable and not in a nested scope. 2815 if (CanonicalVD->isLocalVarDecl() && CurScope && 2816 !isDeclInScope(ND, getCurLexicalContext(), CurScope)) { 2817 Diag(Id.getLoc(), diag::err_omp_var_scope) 2818 << getOpenMPDirectiveName(Kind) << VD; 2819 bool IsDecl = 2820 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly; 2821 Diag(VD->getLocation(), 2822 IsDecl ? diag::note_previous_decl : diag::note_defined_here) 2823 << VD; 2824 return ExprError(); 2825 } 2826 2827 // OpenMP [2.9.2, Restrictions, C/C++, p.2-6] 2828 // A threadprivate directive must lexically precede all references to any 2829 // of the variables in its list. 2830 if (Kind == OMPD_threadprivate && VD->isUsed() && 2831 !DSAStack->isThreadPrivate(VD)) { 2832 Diag(Id.getLoc(), diag::err_omp_var_used) 2833 << getOpenMPDirectiveName(Kind) << VD; 2834 return ExprError(); 2835 } 2836 2837 QualType ExprType = VD->getType().getNonReferenceType(); 2838 return DeclRefExpr::Create(Context, NestedNameSpecifierLoc(), 2839 SourceLocation(), VD, 2840 /*RefersToEnclosingVariableOrCapture=*/false, 2841 Id.getLoc(), ExprType, VK_LValue); 2842 } 2843 2844 Sema::DeclGroupPtrTy 2845 Sema::ActOnOpenMPThreadprivateDirective(SourceLocation Loc, 2846 ArrayRef<Expr *> VarList) { 2847 if (OMPThreadPrivateDecl *D = CheckOMPThreadPrivateDecl(Loc, VarList)) { 2848 CurContext->addDecl(D); 2849 return DeclGroupPtrTy::make(DeclGroupRef(D)); 2850 } 2851 return nullptr; 2852 } 2853 2854 namespace { 2855 class LocalVarRefChecker final 2856 : public ConstStmtVisitor<LocalVarRefChecker, bool> { 2857 Sema &SemaRef; 2858 2859 public: 2860 bool VisitDeclRefExpr(const DeclRefExpr *E) { 2861 if (const auto *VD = dyn_cast<VarDecl>(E->getDecl())) { 2862 if (VD->hasLocalStorage()) { 2863 SemaRef.Diag(E->getBeginLoc(), 2864 diag::err_omp_local_var_in_threadprivate_init) 2865 << E->getSourceRange(); 2866 SemaRef.Diag(VD->getLocation(), diag::note_defined_here) 2867 << VD << VD->getSourceRange(); 2868 return true; 2869 } 2870 } 2871 return false; 2872 } 2873 bool VisitStmt(const Stmt *S) { 2874 for (const Stmt *Child : S->children()) { 2875 if (Child && Visit(Child)) 2876 return true; 2877 } 2878 return false; 2879 } 2880 explicit LocalVarRefChecker(Sema &SemaRef) : SemaRef(SemaRef) {} 2881 }; 2882 } // namespace 2883 2884 OMPThreadPrivateDecl * 2885 Sema::CheckOMPThreadPrivateDecl(SourceLocation Loc, ArrayRef<Expr *> VarList) { 2886 SmallVector<Expr *, 8> Vars; 2887 for (Expr *RefExpr : VarList) { 2888 auto *DE = cast<DeclRefExpr>(RefExpr); 2889 auto *VD = cast<VarDecl>(DE->getDecl()); 2890 SourceLocation ILoc = DE->getExprLoc(); 2891 2892 // Mark variable as used. 2893 VD->setReferenced(); 2894 VD->markUsed(Context); 2895 2896 QualType QType = VD->getType(); 2897 if (QType->isDependentType() || QType->isInstantiationDependentType()) { 2898 // It will be analyzed later. 2899 Vars.push_back(DE); 2900 continue; 2901 } 2902 2903 // OpenMP [2.9.2, Restrictions, C/C++, p.10] 2904 // A threadprivate variable must not have an incomplete type. 2905 if (RequireCompleteType(ILoc, VD->getType(), 2906 diag::err_omp_threadprivate_incomplete_type)) { 2907 continue; 2908 } 2909 2910 // OpenMP [2.9.2, Restrictions, C/C++, p.10] 2911 // A threadprivate variable must not have a reference type. 2912 if (VD->getType()->isReferenceType()) { 2913 Diag(ILoc, diag::err_omp_ref_type_arg) 2914 << getOpenMPDirectiveName(OMPD_threadprivate) << VD->getType(); 2915 bool IsDecl = 2916 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly; 2917 Diag(VD->getLocation(), 2918 IsDecl ? diag::note_previous_decl : diag::note_defined_here) 2919 << VD; 2920 continue; 2921 } 2922 2923 // Check if this is a TLS variable. If TLS is not being supported, produce 2924 // the corresponding diagnostic. 2925 if ((VD->getTLSKind() != VarDecl::TLS_None && 2926 !(VD->hasAttr<OMPThreadPrivateDeclAttr>() && 2927 getLangOpts().OpenMPUseTLS && 2928 getASTContext().getTargetInfo().isTLSSupported())) || 2929 (VD->getStorageClass() == SC_Register && VD->hasAttr<AsmLabelAttr>() && 2930 !VD->isLocalVarDecl())) { 2931 Diag(ILoc, diag::err_omp_var_thread_local) 2932 << VD << ((VD->getTLSKind() != VarDecl::TLS_None) ? 0 : 1); 2933 bool IsDecl = 2934 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly; 2935 Diag(VD->getLocation(), 2936 IsDecl ? diag::note_previous_decl : diag::note_defined_here) 2937 << VD; 2938 continue; 2939 } 2940 2941 // Check if initial value of threadprivate variable reference variable with 2942 // local storage (it is not supported by runtime). 2943 if (const Expr *Init = VD->getAnyInitializer()) { 2944 LocalVarRefChecker Checker(*this); 2945 if (Checker.Visit(Init)) 2946 continue; 2947 } 2948 2949 Vars.push_back(RefExpr); 2950 DSAStack->addDSA(VD, DE, OMPC_threadprivate); 2951 VD->addAttr(OMPThreadPrivateDeclAttr::CreateImplicit( 2952 Context, SourceRange(Loc, Loc))); 2953 if (ASTMutationListener *ML = Context.getASTMutationListener()) 2954 ML->DeclarationMarkedOpenMPThreadPrivate(VD); 2955 } 2956 OMPThreadPrivateDecl *D = nullptr; 2957 if (!Vars.empty()) { 2958 D = OMPThreadPrivateDecl::Create(Context, getCurLexicalContext(), Loc, 2959 Vars); 2960 D->setAccess(AS_public); 2961 } 2962 return D; 2963 } 2964 2965 static OMPAllocateDeclAttr::AllocatorTypeTy 2966 getAllocatorKind(Sema &S, DSAStackTy *Stack, Expr *Allocator) { 2967 if (!Allocator) 2968 return OMPAllocateDeclAttr::OMPNullMemAlloc; 2969 if (Allocator->isTypeDependent() || Allocator->isValueDependent() || 2970 Allocator->isInstantiationDependent() || 2971 Allocator->containsUnexpandedParameterPack()) 2972 return OMPAllocateDeclAttr::OMPUserDefinedMemAlloc; 2973 auto AllocatorKindRes = OMPAllocateDeclAttr::OMPUserDefinedMemAlloc; 2974 const Expr *AE = Allocator->IgnoreParenImpCasts(); 2975 for (int I = 0; I < OMPAllocateDeclAttr::OMPUserDefinedMemAlloc; ++I) { 2976 auto AllocatorKind = static_cast<OMPAllocateDeclAttr::AllocatorTypeTy>(I); 2977 const Expr *DefAllocator = Stack->getAllocator(AllocatorKind); 2978 llvm::FoldingSetNodeID AEId, DAEId; 2979 AE->Profile(AEId, S.getASTContext(), /*Canonical=*/true); 2980 DefAllocator->Profile(DAEId, S.getASTContext(), /*Canonical=*/true); 2981 if (AEId == DAEId) { 2982 AllocatorKindRes = AllocatorKind; 2983 break; 2984 } 2985 } 2986 return AllocatorKindRes; 2987 } 2988 2989 static bool checkPreviousOMPAllocateAttribute( 2990 Sema &S, DSAStackTy *Stack, Expr *RefExpr, VarDecl *VD, 2991 OMPAllocateDeclAttr::AllocatorTypeTy AllocatorKind, Expr *Allocator) { 2992 if (!VD->hasAttr<OMPAllocateDeclAttr>()) 2993 return false; 2994 const auto *A = VD->getAttr<OMPAllocateDeclAttr>(); 2995 Expr *PrevAllocator = A->getAllocator(); 2996 OMPAllocateDeclAttr::AllocatorTypeTy PrevAllocatorKind = 2997 getAllocatorKind(S, Stack, PrevAllocator); 2998 bool AllocatorsMatch = AllocatorKind == PrevAllocatorKind; 2999 if (AllocatorsMatch && 3000 AllocatorKind == OMPAllocateDeclAttr::OMPUserDefinedMemAlloc && 3001 Allocator && PrevAllocator) { 3002 const Expr *AE = Allocator->IgnoreParenImpCasts(); 3003 const Expr *PAE = PrevAllocator->IgnoreParenImpCasts(); 3004 llvm::FoldingSetNodeID AEId, PAEId; 3005 AE->Profile(AEId, S.Context, /*Canonical=*/true); 3006 PAE->Profile(PAEId, S.Context, /*Canonical=*/true); 3007 AllocatorsMatch = AEId == PAEId; 3008 } 3009 if (!AllocatorsMatch) { 3010 SmallString<256> AllocatorBuffer; 3011 llvm::raw_svector_ostream AllocatorStream(AllocatorBuffer); 3012 if (Allocator) 3013 Allocator->printPretty(AllocatorStream, nullptr, S.getPrintingPolicy()); 3014 SmallString<256> PrevAllocatorBuffer; 3015 llvm::raw_svector_ostream PrevAllocatorStream(PrevAllocatorBuffer); 3016 if (PrevAllocator) 3017 PrevAllocator->printPretty(PrevAllocatorStream, nullptr, 3018 S.getPrintingPolicy()); 3019 3020 SourceLocation AllocatorLoc = 3021 Allocator ? Allocator->getExprLoc() : RefExpr->getExprLoc(); 3022 SourceRange AllocatorRange = 3023 Allocator ? Allocator->getSourceRange() : RefExpr->getSourceRange(); 3024 SourceLocation PrevAllocatorLoc = 3025 PrevAllocator ? PrevAllocator->getExprLoc() : A->getLocation(); 3026 SourceRange PrevAllocatorRange = 3027 PrevAllocator ? PrevAllocator->getSourceRange() : A->getRange(); 3028 S.Diag(AllocatorLoc, diag::warn_omp_used_different_allocator) 3029 << (Allocator ? 1 : 0) << AllocatorStream.str() 3030 << (PrevAllocator ? 1 : 0) << PrevAllocatorStream.str() 3031 << AllocatorRange; 3032 S.Diag(PrevAllocatorLoc, diag::note_omp_previous_allocator) 3033 << PrevAllocatorRange; 3034 return true; 3035 } 3036 return false; 3037 } 3038 3039 static void 3040 applyOMPAllocateAttribute(Sema &S, VarDecl *VD, 3041 OMPAllocateDeclAttr::AllocatorTypeTy AllocatorKind, 3042 Expr *Allocator, SourceRange SR) { 3043 if (VD->hasAttr<OMPAllocateDeclAttr>()) 3044 return; 3045 if (Allocator && 3046 (Allocator->isTypeDependent() || Allocator->isValueDependent() || 3047 Allocator->isInstantiationDependent() || 3048 Allocator->containsUnexpandedParameterPack())) 3049 return; 3050 auto *A = OMPAllocateDeclAttr::CreateImplicit(S.Context, AllocatorKind, 3051 Allocator, SR); 3052 VD->addAttr(A); 3053 if (ASTMutationListener *ML = S.Context.getASTMutationListener()) 3054 ML->DeclarationMarkedOpenMPAllocate(VD, A); 3055 } 3056 3057 Sema::DeclGroupPtrTy Sema::ActOnOpenMPAllocateDirective( 3058 SourceLocation Loc, ArrayRef<Expr *> VarList, 3059 ArrayRef<OMPClause *> Clauses, DeclContext *Owner) { 3060 assert(Clauses.size() <= 1 && "Expected at most one clause."); 3061 Expr *Allocator = nullptr; 3062 if (Clauses.empty()) { 3063 // OpenMP 5.0, 2.11.3 allocate Directive, Restrictions. 3064 // allocate directives that appear in a target region must specify an 3065 // allocator clause unless a requires directive with the dynamic_allocators 3066 // clause is present in the same compilation unit. 3067 if (LangOpts.OpenMPIsDevice && 3068 !DSAStack->hasRequiresDeclWithClause<OMPDynamicAllocatorsClause>()) 3069 targetDiag(Loc, diag::err_expected_allocator_clause); 3070 } else { 3071 Allocator = cast<OMPAllocatorClause>(Clauses.back())->getAllocator(); 3072 } 3073 OMPAllocateDeclAttr::AllocatorTypeTy AllocatorKind = 3074 getAllocatorKind(*this, DSAStack, Allocator); 3075 SmallVector<Expr *, 8> Vars; 3076 for (Expr *RefExpr : VarList) { 3077 auto *DE = cast<DeclRefExpr>(RefExpr); 3078 auto *VD = cast<VarDecl>(DE->getDecl()); 3079 3080 // Check if this is a TLS variable or global register. 3081 if (VD->getTLSKind() != VarDecl::TLS_None || 3082 VD->hasAttr<OMPThreadPrivateDeclAttr>() || 3083 (VD->getStorageClass() == SC_Register && VD->hasAttr<AsmLabelAttr>() && 3084 !VD->isLocalVarDecl())) 3085 continue; 3086 3087 // If the used several times in the allocate directive, the same allocator 3088 // must be used. 3089 if (checkPreviousOMPAllocateAttribute(*this, DSAStack, RefExpr, VD, 3090 AllocatorKind, Allocator)) 3091 continue; 3092 3093 // OpenMP, 2.11.3 allocate Directive, Restrictions, C / C++ 3094 // If a list item has a static storage type, the allocator expression in the 3095 // allocator clause must be a constant expression that evaluates to one of 3096 // the predefined memory allocator values. 3097 if (Allocator && VD->hasGlobalStorage()) { 3098 if (AllocatorKind == OMPAllocateDeclAttr::OMPUserDefinedMemAlloc) { 3099 Diag(Allocator->getExprLoc(), 3100 diag::err_omp_expected_predefined_allocator) 3101 << Allocator->getSourceRange(); 3102 bool IsDecl = VD->isThisDeclarationADefinition(Context) == 3103 VarDecl::DeclarationOnly; 3104 Diag(VD->getLocation(), 3105 IsDecl ? diag::note_previous_decl : diag::note_defined_here) 3106 << VD; 3107 continue; 3108 } 3109 } 3110 3111 Vars.push_back(RefExpr); 3112 applyOMPAllocateAttribute(*this, VD, AllocatorKind, Allocator, 3113 DE->getSourceRange()); 3114 } 3115 if (Vars.empty()) 3116 return nullptr; 3117 if (!Owner) 3118 Owner = getCurLexicalContext(); 3119 auto *D = OMPAllocateDecl::Create(Context, Owner, Loc, Vars, Clauses); 3120 D->setAccess(AS_public); 3121 Owner->addDecl(D); 3122 return DeclGroupPtrTy::make(DeclGroupRef(D)); 3123 } 3124 3125 Sema::DeclGroupPtrTy 3126 Sema::ActOnOpenMPRequiresDirective(SourceLocation Loc, 3127 ArrayRef<OMPClause *> ClauseList) { 3128 OMPRequiresDecl *D = nullptr; 3129 if (!CurContext->isFileContext()) { 3130 Diag(Loc, diag::err_omp_invalid_scope) << "requires"; 3131 } else { 3132 D = CheckOMPRequiresDecl(Loc, ClauseList); 3133 if (D) { 3134 CurContext->addDecl(D); 3135 DSAStack->addRequiresDecl(D); 3136 } 3137 } 3138 return DeclGroupPtrTy::make(DeclGroupRef(D)); 3139 } 3140 3141 OMPRequiresDecl *Sema::CheckOMPRequiresDecl(SourceLocation Loc, 3142 ArrayRef<OMPClause *> ClauseList) { 3143 /// For target specific clauses, the requires directive cannot be 3144 /// specified after the handling of any of the target regions in the 3145 /// current compilation unit. 3146 ArrayRef<SourceLocation> TargetLocations = 3147 DSAStack->getEncounteredTargetLocs(); 3148 SourceLocation AtomicLoc = DSAStack->getAtomicDirectiveLoc(); 3149 if (!TargetLocations.empty() || !AtomicLoc.isInvalid()) { 3150 for (const OMPClause *CNew : ClauseList) { 3151 // Check if any of the requires clauses affect target regions. 3152 if (isa<OMPUnifiedSharedMemoryClause>(CNew) || 3153 isa<OMPUnifiedAddressClause>(CNew) || 3154 isa<OMPReverseOffloadClause>(CNew) || 3155 isa<OMPDynamicAllocatorsClause>(CNew)) { 3156 Diag(Loc, diag::err_omp_directive_before_requires) 3157 << "target" << getOpenMPClauseName(CNew->getClauseKind()); 3158 for (SourceLocation TargetLoc : TargetLocations) { 3159 Diag(TargetLoc, diag::note_omp_requires_encountered_directive) 3160 << "target"; 3161 } 3162 } else if (!AtomicLoc.isInvalid() && 3163 isa<OMPAtomicDefaultMemOrderClause>(CNew)) { 3164 Diag(Loc, diag::err_omp_directive_before_requires) 3165 << "atomic" << getOpenMPClauseName(CNew->getClauseKind()); 3166 Diag(AtomicLoc, diag::note_omp_requires_encountered_directive) 3167 << "atomic"; 3168 } 3169 } 3170 } 3171 3172 if (!DSAStack->hasDuplicateRequiresClause(ClauseList)) 3173 return OMPRequiresDecl::Create(Context, getCurLexicalContext(), Loc, 3174 ClauseList); 3175 return nullptr; 3176 } 3177 3178 static void reportOriginalDsa(Sema &SemaRef, const DSAStackTy *Stack, 3179 const ValueDecl *D, 3180 const DSAStackTy::DSAVarData &DVar, 3181 bool IsLoopIterVar) { 3182 if (DVar.RefExpr) { 3183 SemaRef.Diag(DVar.RefExpr->getExprLoc(), diag::note_omp_explicit_dsa) 3184 << getOpenMPClauseName(DVar.CKind); 3185 return; 3186 } 3187 enum { 3188 PDSA_StaticMemberShared, 3189 PDSA_StaticLocalVarShared, 3190 PDSA_LoopIterVarPrivate, 3191 PDSA_LoopIterVarLinear, 3192 PDSA_LoopIterVarLastprivate, 3193 PDSA_ConstVarShared, 3194 PDSA_GlobalVarShared, 3195 PDSA_TaskVarFirstprivate, 3196 PDSA_LocalVarPrivate, 3197 PDSA_Implicit 3198 } Reason = PDSA_Implicit; 3199 bool ReportHint = false; 3200 auto ReportLoc = D->getLocation(); 3201 auto *VD = dyn_cast<VarDecl>(D); 3202 if (IsLoopIterVar) { 3203 if (DVar.CKind == OMPC_private) 3204 Reason = PDSA_LoopIterVarPrivate; 3205 else if (DVar.CKind == OMPC_lastprivate) 3206 Reason = PDSA_LoopIterVarLastprivate; 3207 else 3208 Reason = PDSA_LoopIterVarLinear; 3209 } else if (isOpenMPTaskingDirective(DVar.DKind) && 3210 DVar.CKind == OMPC_firstprivate) { 3211 Reason = PDSA_TaskVarFirstprivate; 3212 ReportLoc = DVar.ImplicitDSALoc; 3213 } else if (VD && VD->isStaticLocal()) 3214 Reason = PDSA_StaticLocalVarShared; 3215 else if (VD && VD->isStaticDataMember()) 3216 Reason = PDSA_StaticMemberShared; 3217 else if (VD && VD->isFileVarDecl()) 3218 Reason = PDSA_GlobalVarShared; 3219 else if (D->getType().isConstant(SemaRef.getASTContext())) 3220 Reason = PDSA_ConstVarShared; 3221 else if (VD && VD->isLocalVarDecl() && DVar.CKind == OMPC_private) { 3222 ReportHint = true; 3223 Reason = PDSA_LocalVarPrivate; 3224 } 3225 if (Reason != PDSA_Implicit) { 3226 SemaRef.Diag(ReportLoc, diag::note_omp_predetermined_dsa) 3227 << Reason << ReportHint 3228 << getOpenMPDirectiveName(Stack->getCurrentDirective()); 3229 } else if (DVar.ImplicitDSALoc.isValid()) { 3230 SemaRef.Diag(DVar.ImplicitDSALoc, diag::note_omp_implicit_dsa) 3231 << getOpenMPClauseName(DVar.CKind); 3232 } 3233 } 3234 3235 static OpenMPMapClauseKind 3236 getMapClauseKindFromModifier(OpenMPDefaultmapClauseModifier M, 3237 bool IsAggregateOrDeclareTarget) { 3238 OpenMPMapClauseKind Kind = OMPC_MAP_unknown; 3239 switch (M) { 3240 case OMPC_DEFAULTMAP_MODIFIER_alloc: 3241 Kind = OMPC_MAP_alloc; 3242 break; 3243 case OMPC_DEFAULTMAP_MODIFIER_to: 3244 Kind = OMPC_MAP_to; 3245 break; 3246 case OMPC_DEFAULTMAP_MODIFIER_from: 3247 Kind = OMPC_MAP_from; 3248 break; 3249 case OMPC_DEFAULTMAP_MODIFIER_tofrom: 3250 Kind = OMPC_MAP_tofrom; 3251 break; 3252 case OMPC_DEFAULTMAP_MODIFIER_firstprivate: 3253 case OMPC_DEFAULTMAP_MODIFIER_last: 3254 llvm_unreachable("Unexpected defaultmap implicit behavior"); 3255 case OMPC_DEFAULTMAP_MODIFIER_none: 3256 case OMPC_DEFAULTMAP_MODIFIER_default: 3257 case OMPC_DEFAULTMAP_MODIFIER_unknown: 3258 // IsAggregateOrDeclareTarget could be true if: 3259 // 1. the implicit behavior for aggregate is tofrom 3260 // 2. it's a declare target link 3261 if (IsAggregateOrDeclareTarget) { 3262 Kind = OMPC_MAP_tofrom; 3263 break; 3264 } 3265 llvm_unreachable("Unexpected defaultmap implicit behavior"); 3266 } 3267 assert(Kind != OMPC_MAP_unknown && "Expect map kind to be known"); 3268 return Kind; 3269 } 3270 3271 namespace { 3272 class DSAAttrChecker final : public StmtVisitor<DSAAttrChecker, void> { 3273 DSAStackTy *Stack; 3274 Sema &SemaRef; 3275 bool ErrorFound = false; 3276 bool TryCaptureCXXThisMembers = false; 3277 CapturedStmt *CS = nullptr; 3278 llvm::SmallVector<Expr *, 4> ImplicitFirstprivate; 3279 llvm::SmallVector<Expr *, 4> ImplicitMap[OMPC_MAP_delete]; 3280 Sema::VarsWithInheritedDSAType VarsWithInheritedDSA; 3281 llvm::SmallDenseSet<const ValueDecl *, 4> ImplicitDeclarations; 3282 3283 void VisitSubCaptures(OMPExecutableDirective *S) { 3284 // Check implicitly captured variables. 3285 if (!S->hasAssociatedStmt() || !S->getAssociatedStmt()) 3286 return; 3287 visitSubCaptures(S->getInnermostCapturedStmt()); 3288 // Try to capture inner this->member references to generate correct mappings 3289 // and diagnostics. 3290 if (TryCaptureCXXThisMembers || 3291 (isOpenMPTargetExecutionDirective(Stack->getCurrentDirective()) && 3292 llvm::any_of(S->getInnermostCapturedStmt()->captures(), 3293 [](const CapturedStmt::Capture &C) { 3294 return C.capturesThis(); 3295 }))) { 3296 bool SavedTryCaptureCXXThisMembers = TryCaptureCXXThisMembers; 3297 TryCaptureCXXThisMembers = true; 3298 Visit(S->getInnermostCapturedStmt()->getCapturedStmt()); 3299 TryCaptureCXXThisMembers = SavedTryCaptureCXXThisMembers; 3300 } 3301 // In tasks firstprivates are not captured anymore, need to analyze them 3302 // explicitly. 3303 if (isOpenMPTaskingDirective(S->getDirectiveKind()) && 3304 !isOpenMPTaskLoopDirective(S->getDirectiveKind())) { 3305 for (OMPClause *C : S->clauses()) 3306 if (auto *FC = dyn_cast<OMPFirstprivateClause>(C)) { 3307 for (Expr *Ref : FC->varlists()) 3308 Visit(Ref); 3309 } 3310 } 3311 } 3312 3313 public: 3314 void VisitDeclRefExpr(DeclRefExpr *E) { 3315 if (TryCaptureCXXThisMembers || E->isTypeDependent() || 3316 E->isValueDependent() || E->containsUnexpandedParameterPack() || 3317 E->isInstantiationDependent()) 3318 return; 3319 if (auto *VD = dyn_cast<VarDecl>(E->getDecl())) { 3320 // Check the datasharing rules for the expressions in the clauses. 3321 if (!CS) { 3322 if (auto *CED = dyn_cast<OMPCapturedExprDecl>(VD)) 3323 if (!CED->hasAttr<OMPCaptureNoInitAttr>()) { 3324 Visit(CED->getInit()); 3325 return; 3326 } 3327 } else if (VD->isImplicit() || isa<OMPCapturedExprDecl>(VD)) 3328 // Do not analyze internal variables and do not enclose them into 3329 // implicit clauses. 3330 return; 3331 VD = VD->getCanonicalDecl(); 3332 // Skip internally declared variables. 3333 if (VD->hasLocalStorage() && CS && !CS->capturesVariable(VD) && 3334 !Stack->isImplicitTaskFirstprivate(VD)) 3335 return; 3336 // Skip allocators in uses_allocators clauses. 3337 if (Stack->isUsesAllocatorsDecl(VD).hasValue()) 3338 return; 3339 3340 DSAStackTy::DSAVarData DVar = Stack->getTopDSA(VD, /*FromParent=*/false); 3341 // Check if the variable has explicit DSA set and stop analysis if it so. 3342 if (DVar.RefExpr || !ImplicitDeclarations.insert(VD).second) 3343 return; 3344 3345 // Skip internally declared static variables. 3346 llvm::Optional<OMPDeclareTargetDeclAttr::MapTypeTy> Res = 3347 OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD); 3348 if (VD->hasGlobalStorage() && CS && !CS->capturesVariable(VD) && 3349 (Stack->hasRequiresDeclWithClause<OMPUnifiedSharedMemoryClause>() || 3350 !Res || *Res != OMPDeclareTargetDeclAttr::MT_Link) && 3351 !Stack->isImplicitTaskFirstprivate(VD)) 3352 return; 3353 3354 SourceLocation ELoc = E->getExprLoc(); 3355 OpenMPDirectiveKind DKind = Stack->getCurrentDirective(); 3356 // The default(none) clause requires that each variable that is referenced 3357 // in the construct, and does not have a predetermined data-sharing 3358 // attribute, must have its data-sharing attribute explicitly determined 3359 // by being listed in a data-sharing attribute clause. 3360 if (DVar.CKind == OMPC_unknown && 3361 (Stack->getDefaultDSA() == DSA_none || 3362 Stack->getDefaultDSA() == DSA_firstprivate) && 3363 isImplicitOrExplicitTaskingRegion(DKind) && 3364 VarsWithInheritedDSA.count(VD) == 0) { 3365 bool InheritedDSA = Stack->getDefaultDSA() == DSA_none; 3366 if (!InheritedDSA && Stack->getDefaultDSA() == DSA_firstprivate) { 3367 DSAStackTy::DSAVarData DVar = 3368 Stack->getImplicitDSA(VD, /*FromParent=*/false); 3369 InheritedDSA = DVar.CKind == OMPC_unknown; 3370 } 3371 if (InheritedDSA) 3372 VarsWithInheritedDSA[VD] = E; 3373 return; 3374 } 3375 3376 // OpenMP 5.0 [2.19.7.2, defaultmap clause, Description] 3377 // If implicit-behavior is none, each variable referenced in the 3378 // construct that does not have a predetermined data-sharing attribute 3379 // and does not appear in a to or link clause on a declare target 3380 // directive must be listed in a data-mapping attribute clause, a 3381 // data-haring attribute clause (including a data-sharing attribute 3382 // clause on a combined construct where target. is one of the 3383 // constituent constructs), or an is_device_ptr clause. 3384 OpenMPDefaultmapClauseKind ClauseKind = 3385 getVariableCategoryFromDecl(SemaRef.getLangOpts(), VD); 3386 if (SemaRef.getLangOpts().OpenMP >= 50) { 3387 bool IsModifierNone = Stack->getDefaultmapModifier(ClauseKind) == 3388 OMPC_DEFAULTMAP_MODIFIER_none; 3389 if (DVar.CKind == OMPC_unknown && IsModifierNone && 3390 VarsWithInheritedDSA.count(VD) == 0 && !Res) { 3391 // Only check for data-mapping attribute and is_device_ptr here 3392 // since we have already make sure that the declaration does not 3393 // have a data-sharing attribute above 3394 if (!Stack->checkMappableExprComponentListsForDecl( 3395 VD, /*CurrentRegionOnly=*/true, 3396 [VD](OMPClauseMappableExprCommon::MappableExprComponentListRef 3397 MapExprComponents, 3398 OpenMPClauseKind) { 3399 auto MI = MapExprComponents.rbegin(); 3400 auto ME = MapExprComponents.rend(); 3401 return MI != ME && MI->getAssociatedDeclaration() == VD; 3402 })) { 3403 VarsWithInheritedDSA[VD] = E; 3404 return; 3405 } 3406 } 3407 } 3408 3409 if (isOpenMPTargetExecutionDirective(DKind) && 3410 !Stack->isLoopControlVariable(VD).first) { 3411 if (!Stack->checkMappableExprComponentListsForDecl( 3412 VD, /*CurrentRegionOnly=*/true, 3413 [](OMPClauseMappableExprCommon::MappableExprComponentListRef 3414 StackComponents, 3415 OpenMPClauseKind) { 3416 // Variable is used if it has been marked as an array, array 3417 // section, array shaping or the variable iself. 3418 return StackComponents.size() == 1 || 3419 std::all_of( 3420 std::next(StackComponents.rbegin()), 3421 StackComponents.rend(), 3422 [](const OMPClauseMappableExprCommon:: 3423 MappableComponent &MC) { 3424 return MC.getAssociatedDeclaration() == 3425 nullptr && 3426 (isa<OMPArraySectionExpr>( 3427 MC.getAssociatedExpression()) || 3428 isa<OMPArrayShapingExpr>( 3429 MC.getAssociatedExpression()) || 3430 isa<ArraySubscriptExpr>( 3431 MC.getAssociatedExpression())); 3432 }); 3433 })) { 3434 bool IsFirstprivate = false; 3435 // By default lambdas are captured as firstprivates. 3436 if (const auto *RD = 3437 VD->getType().getNonReferenceType()->getAsCXXRecordDecl()) 3438 IsFirstprivate = RD->isLambda(); 3439 IsFirstprivate = 3440 IsFirstprivate || (Stack->mustBeFirstprivate(ClauseKind) && !Res); 3441 if (IsFirstprivate) { 3442 ImplicitFirstprivate.emplace_back(E); 3443 } else { 3444 OpenMPDefaultmapClauseModifier M = 3445 Stack->getDefaultmapModifier(ClauseKind); 3446 OpenMPMapClauseKind Kind = getMapClauseKindFromModifier( 3447 M, ClauseKind == OMPC_DEFAULTMAP_aggregate || Res); 3448 ImplicitMap[Kind].emplace_back(E); 3449 } 3450 return; 3451 } 3452 } 3453 3454 // OpenMP [2.9.3.6, Restrictions, p.2] 3455 // A list item that appears in a reduction clause of the innermost 3456 // enclosing worksharing or parallel construct may not be accessed in an 3457 // explicit task. 3458 DVar = Stack->hasInnermostDSA( 3459 VD, [](OpenMPClauseKind C) { return C == OMPC_reduction; }, 3460 [](OpenMPDirectiveKind K) { 3461 return isOpenMPParallelDirective(K) || 3462 isOpenMPWorksharingDirective(K) || isOpenMPTeamsDirective(K); 3463 }, 3464 /*FromParent=*/true); 3465 if (isOpenMPTaskingDirective(DKind) && DVar.CKind == OMPC_reduction) { 3466 ErrorFound = true; 3467 SemaRef.Diag(ELoc, diag::err_omp_reduction_in_task); 3468 reportOriginalDsa(SemaRef, Stack, VD, DVar); 3469 return; 3470 } 3471 3472 // Define implicit data-sharing attributes for task. 3473 DVar = Stack->getImplicitDSA(VD, /*FromParent=*/false); 3474 if (((isOpenMPTaskingDirective(DKind) && DVar.CKind != OMPC_shared) || 3475 (Stack->getDefaultDSA() == DSA_firstprivate && 3476 DVar.CKind == OMPC_firstprivate && !DVar.RefExpr)) && 3477 !Stack->isLoopControlVariable(VD).first) { 3478 ImplicitFirstprivate.push_back(E); 3479 return; 3480 } 3481 3482 // Store implicitly used globals with declare target link for parent 3483 // target. 3484 if (!isOpenMPTargetExecutionDirective(DKind) && Res && 3485 *Res == OMPDeclareTargetDeclAttr::MT_Link) { 3486 Stack->addToParentTargetRegionLinkGlobals(E); 3487 return; 3488 } 3489 } 3490 } 3491 void VisitMemberExpr(MemberExpr *E) { 3492 if (E->isTypeDependent() || E->isValueDependent() || 3493 E->containsUnexpandedParameterPack() || E->isInstantiationDependent()) 3494 return; 3495 auto *FD = dyn_cast<FieldDecl>(E->getMemberDecl()); 3496 OpenMPDirectiveKind DKind = Stack->getCurrentDirective(); 3497 if (auto *TE = dyn_cast<CXXThisExpr>(E->getBase()->IgnoreParenCasts())) { 3498 if (!FD) 3499 return; 3500 DSAStackTy::DSAVarData DVar = Stack->getTopDSA(FD, /*FromParent=*/false); 3501 // Check if the variable has explicit DSA set and stop analysis if it 3502 // so. 3503 if (DVar.RefExpr || !ImplicitDeclarations.insert(FD).second) 3504 return; 3505 3506 if (isOpenMPTargetExecutionDirective(DKind) && 3507 !Stack->isLoopControlVariable(FD).first && 3508 !Stack->checkMappableExprComponentListsForDecl( 3509 FD, /*CurrentRegionOnly=*/true, 3510 [](OMPClauseMappableExprCommon::MappableExprComponentListRef 3511 StackComponents, 3512 OpenMPClauseKind) { 3513 return isa<CXXThisExpr>( 3514 cast<MemberExpr>( 3515 StackComponents.back().getAssociatedExpression()) 3516 ->getBase() 3517 ->IgnoreParens()); 3518 })) { 3519 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C/C++, p.3] 3520 // A bit-field cannot appear in a map clause. 3521 // 3522 if (FD->isBitField()) 3523 return; 3524 3525 // Check to see if the member expression is referencing a class that 3526 // has already been explicitly mapped 3527 if (Stack->isClassPreviouslyMapped(TE->getType())) 3528 return; 3529 3530 OpenMPDefaultmapClauseModifier Modifier = 3531 Stack->getDefaultmapModifier(OMPC_DEFAULTMAP_aggregate); 3532 OpenMPMapClauseKind Kind = getMapClauseKindFromModifier( 3533 Modifier, /*IsAggregateOrDeclareTarget*/ true); 3534 ImplicitMap[Kind].emplace_back(E); 3535 return; 3536 } 3537 3538 SourceLocation ELoc = E->getExprLoc(); 3539 // OpenMP [2.9.3.6, Restrictions, p.2] 3540 // A list item that appears in a reduction clause of the innermost 3541 // enclosing worksharing or parallel construct may not be accessed in 3542 // an explicit task. 3543 DVar = Stack->hasInnermostDSA( 3544 FD, [](OpenMPClauseKind C) { return C == OMPC_reduction; }, 3545 [](OpenMPDirectiveKind K) { 3546 return isOpenMPParallelDirective(K) || 3547 isOpenMPWorksharingDirective(K) || isOpenMPTeamsDirective(K); 3548 }, 3549 /*FromParent=*/true); 3550 if (isOpenMPTaskingDirective(DKind) && DVar.CKind == OMPC_reduction) { 3551 ErrorFound = true; 3552 SemaRef.Diag(ELoc, diag::err_omp_reduction_in_task); 3553 reportOriginalDsa(SemaRef, Stack, FD, DVar); 3554 return; 3555 } 3556 3557 // Define implicit data-sharing attributes for task. 3558 DVar = Stack->getImplicitDSA(FD, /*FromParent=*/false); 3559 if (isOpenMPTaskingDirective(DKind) && DVar.CKind != OMPC_shared && 3560 !Stack->isLoopControlVariable(FD).first) { 3561 // Check if there is a captured expression for the current field in the 3562 // region. Do not mark it as firstprivate unless there is no captured 3563 // expression. 3564 // TODO: try to make it firstprivate. 3565 if (DVar.CKind != OMPC_unknown) 3566 ImplicitFirstprivate.push_back(E); 3567 } 3568 return; 3569 } 3570 if (isOpenMPTargetExecutionDirective(DKind)) { 3571 OMPClauseMappableExprCommon::MappableExprComponentList CurComponents; 3572 if (!checkMapClauseExpressionBase(SemaRef, E, CurComponents, OMPC_map, 3573 /*NoDiagnose=*/true)) 3574 return; 3575 const auto *VD = cast<ValueDecl>( 3576 CurComponents.back().getAssociatedDeclaration()->getCanonicalDecl()); 3577 if (!Stack->checkMappableExprComponentListsForDecl( 3578 VD, /*CurrentRegionOnly=*/true, 3579 [&CurComponents]( 3580 OMPClauseMappableExprCommon::MappableExprComponentListRef 3581 StackComponents, 3582 OpenMPClauseKind) { 3583 auto CCI = CurComponents.rbegin(); 3584 auto CCE = CurComponents.rend(); 3585 for (const auto &SC : llvm::reverse(StackComponents)) { 3586 // Do both expressions have the same kind? 3587 if (CCI->getAssociatedExpression()->getStmtClass() != 3588 SC.getAssociatedExpression()->getStmtClass()) 3589 if (!((isa<OMPArraySectionExpr>( 3590 SC.getAssociatedExpression()) || 3591 isa<OMPArrayShapingExpr>( 3592 SC.getAssociatedExpression())) && 3593 isa<ArraySubscriptExpr>( 3594 CCI->getAssociatedExpression()))) 3595 return false; 3596 3597 const Decl *CCD = CCI->getAssociatedDeclaration(); 3598 const Decl *SCD = SC.getAssociatedDeclaration(); 3599 CCD = CCD ? CCD->getCanonicalDecl() : nullptr; 3600 SCD = SCD ? SCD->getCanonicalDecl() : nullptr; 3601 if (SCD != CCD) 3602 return false; 3603 std::advance(CCI, 1); 3604 if (CCI == CCE) 3605 break; 3606 } 3607 return true; 3608 })) { 3609 Visit(E->getBase()); 3610 } 3611 } else if (!TryCaptureCXXThisMembers) { 3612 Visit(E->getBase()); 3613 } 3614 } 3615 void VisitOMPExecutableDirective(OMPExecutableDirective *S) { 3616 for (OMPClause *C : S->clauses()) { 3617 // Skip analysis of arguments of implicitly defined firstprivate clause 3618 // for task|target directives. 3619 // Skip analysis of arguments of implicitly defined map clause for target 3620 // directives. 3621 if (C && !((isa<OMPFirstprivateClause>(C) || isa<OMPMapClause>(C)) && 3622 C->isImplicit())) { 3623 for (Stmt *CC : C->children()) { 3624 if (CC) 3625 Visit(CC); 3626 } 3627 } 3628 } 3629 // Check implicitly captured variables. 3630 VisitSubCaptures(S); 3631 } 3632 void VisitStmt(Stmt *S) { 3633 for (Stmt *C : S->children()) { 3634 if (C) { 3635 // Check implicitly captured variables in the task-based directives to 3636 // check if they must be firstprivatized. 3637 Visit(C); 3638 } 3639 } 3640 } 3641 3642 void visitSubCaptures(CapturedStmt *S) { 3643 for (const CapturedStmt::Capture &Cap : S->captures()) { 3644 if (!Cap.capturesVariable() && !Cap.capturesVariableByCopy()) 3645 continue; 3646 VarDecl *VD = Cap.getCapturedVar(); 3647 // Do not try to map the variable if it or its sub-component was mapped 3648 // already. 3649 if (isOpenMPTargetExecutionDirective(Stack->getCurrentDirective()) && 3650 Stack->checkMappableExprComponentListsForDecl( 3651 VD, /*CurrentRegionOnly=*/true, 3652 [](OMPClauseMappableExprCommon::MappableExprComponentListRef, 3653 OpenMPClauseKind) { return true; })) 3654 continue; 3655 DeclRefExpr *DRE = buildDeclRefExpr( 3656 SemaRef, VD, VD->getType().getNonLValueExprType(SemaRef.Context), 3657 Cap.getLocation(), /*RefersToCapture=*/true); 3658 Visit(DRE); 3659 } 3660 } 3661 bool isErrorFound() const { return ErrorFound; } 3662 ArrayRef<Expr *> getImplicitFirstprivate() const { 3663 return ImplicitFirstprivate; 3664 } 3665 ArrayRef<Expr *> getImplicitMap(OpenMPDefaultmapClauseKind Kind) const { 3666 return ImplicitMap[Kind]; 3667 } 3668 const Sema::VarsWithInheritedDSAType &getVarsWithInheritedDSA() const { 3669 return VarsWithInheritedDSA; 3670 } 3671 3672 DSAAttrChecker(DSAStackTy *S, Sema &SemaRef, CapturedStmt *CS) 3673 : Stack(S), SemaRef(SemaRef), ErrorFound(false), CS(CS) { 3674 // Process declare target link variables for the target directives. 3675 if (isOpenMPTargetExecutionDirective(S->getCurrentDirective())) { 3676 for (DeclRefExpr *E : Stack->getLinkGlobals()) 3677 Visit(E); 3678 } 3679 } 3680 }; 3681 } // namespace 3682 3683 void Sema::ActOnOpenMPRegionStart(OpenMPDirectiveKind DKind, Scope *CurScope) { 3684 switch (DKind) { 3685 case OMPD_parallel: 3686 case OMPD_parallel_for: 3687 case OMPD_parallel_for_simd: 3688 case OMPD_parallel_sections: 3689 case OMPD_parallel_master: 3690 case OMPD_teams: 3691 case OMPD_teams_distribute: 3692 case OMPD_teams_distribute_simd: { 3693 QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1).withConst(); 3694 QualType KmpInt32PtrTy = 3695 Context.getPointerType(KmpInt32Ty).withConst().withRestrict(); 3696 Sema::CapturedParamNameType Params[] = { 3697 std::make_pair(".global_tid.", KmpInt32PtrTy), 3698 std::make_pair(".bound_tid.", KmpInt32PtrTy), 3699 std::make_pair(StringRef(), QualType()) // __context with shared vars 3700 }; 3701 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP, 3702 Params); 3703 break; 3704 } 3705 case OMPD_target_teams: 3706 case OMPD_target_parallel: 3707 case OMPD_target_parallel_for: 3708 case OMPD_target_parallel_for_simd: 3709 case OMPD_target_teams_distribute: 3710 case OMPD_target_teams_distribute_simd: { 3711 QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1).withConst(); 3712 QualType VoidPtrTy = Context.VoidPtrTy.withConst().withRestrict(); 3713 QualType KmpInt32PtrTy = 3714 Context.getPointerType(KmpInt32Ty).withConst().withRestrict(); 3715 QualType Args[] = {VoidPtrTy}; 3716 FunctionProtoType::ExtProtoInfo EPI; 3717 EPI.Variadic = true; 3718 QualType CopyFnType = Context.getFunctionType(Context.VoidTy, Args, EPI); 3719 Sema::CapturedParamNameType Params[] = { 3720 std::make_pair(".global_tid.", KmpInt32Ty), 3721 std::make_pair(".part_id.", KmpInt32PtrTy), 3722 std::make_pair(".privates.", VoidPtrTy), 3723 std::make_pair( 3724 ".copy_fn.", 3725 Context.getPointerType(CopyFnType).withConst().withRestrict()), 3726 std::make_pair(".task_t.", Context.VoidPtrTy.withConst()), 3727 std::make_pair(StringRef(), QualType()) // __context with shared vars 3728 }; 3729 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP, 3730 Params, /*OpenMPCaptureLevel=*/0); 3731 // Mark this captured region as inlined, because we don't use outlined 3732 // function directly. 3733 getCurCapturedRegion()->TheCapturedDecl->addAttr( 3734 AlwaysInlineAttr::CreateImplicit( 3735 Context, {}, AttributeCommonInfo::AS_Keyword, 3736 AlwaysInlineAttr::Keyword_forceinline)); 3737 Sema::CapturedParamNameType ParamsTarget[] = { 3738 std::make_pair(StringRef(), QualType()) // __context with shared vars 3739 }; 3740 // Start a captured region for 'target' with no implicit parameters. 3741 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP, 3742 ParamsTarget, /*OpenMPCaptureLevel=*/1); 3743 Sema::CapturedParamNameType ParamsTeamsOrParallel[] = { 3744 std::make_pair(".global_tid.", KmpInt32PtrTy), 3745 std::make_pair(".bound_tid.", KmpInt32PtrTy), 3746 std::make_pair(StringRef(), QualType()) // __context with shared vars 3747 }; 3748 // Start a captured region for 'teams' or 'parallel'. Both regions have 3749 // the same implicit parameters. 3750 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP, 3751 ParamsTeamsOrParallel, /*OpenMPCaptureLevel=*/2); 3752 break; 3753 } 3754 case OMPD_target: 3755 case OMPD_target_simd: { 3756 QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1).withConst(); 3757 QualType VoidPtrTy = Context.VoidPtrTy.withConst().withRestrict(); 3758 QualType KmpInt32PtrTy = 3759 Context.getPointerType(KmpInt32Ty).withConst().withRestrict(); 3760 QualType Args[] = {VoidPtrTy}; 3761 FunctionProtoType::ExtProtoInfo EPI; 3762 EPI.Variadic = true; 3763 QualType CopyFnType = Context.getFunctionType(Context.VoidTy, Args, EPI); 3764 Sema::CapturedParamNameType Params[] = { 3765 std::make_pair(".global_tid.", KmpInt32Ty), 3766 std::make_pair(".part_id.", KmpInt32PtrTy), 3767 std::make_pair(".privates.", VoidPtrTy), 3768 std::make_pair( 3769 ".copy_fn.", 3770 Context.getPointerType(CopyFnType).withConst().withRestrict()), 3771 std::make_pair(".task_t.", Context.VoidPtrTy.withConst()), 3772 std::make_pair(StringRef(), QualType()) // __context with shared vars 3773 }; 3774 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP, 3775 Params, /*OpenMPCaptureLevel=*/0); 3776 // Mark this captured region as inlined, because we don't use outlined 3777 // function directly. 3778 getCurCapturedRegion()->TheCapturedDecl->addAttr( 3779 AlwaysInlineAttr::CreateImplicit( 3780 Context, {}, AttributeCommonInfo::AS_Keyword, 3781 AlwaysInlineAttr::Keyword_forceinline)); 3782 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP, 3783 std::make_pair(StringRef(), QualType()), 3784 /*OpenMPCaptureLevel=*/1); 3785 break; 3786 } 3787 case OMPD_simd: 3788 case OMPD_for: 3789 case OMPD_for_simd: 3790 case OMPD_sections: 3791 case OMPD_section: 3792 case OMPD_single: 3793 case OMPD_master: 3794 case OMPD_critical: 3795 case OMPD_taskgroup: 3796 case OMPD_distribute: 3797 case OMPD_distribute_simd: 3798 case OMPD_ordered: 3799 case OMPD_atomic: 3800 case OMPD_target_data: { 3801 Sema::CapturedParamNameType Params[] = { 3802 std::make_pair(StringRef(), QualType()) // __context with shared vars 3803 }; 3804 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP, 3805 Params); 3806 break; 3807 } 3808 case OMPD_task: { 3809 QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1).withConst(); 3810 QualType VoidPtrTy = Context.VoidPtrTy.withConst().withRestrict(); 3811 QualType KmpInt32PtrTy = 3812 Context.getPointerType(KmpInt32Ty).withConst().withRestrict(); 3813 QualType Args[] = {VoidPtrTy}; 3814 FunctionProtoType::ExtProtoInfo EPI; 3815 EPI.Variadic = true; 3816 QualType CopyFnType = Context.getFunctionType(Context.VoidTy, Args, EPI); 3817 Sema::CapturedParamNameType Params[] = { 3818 std::make_pair(".global_tid.", KmpInt32Ty), 3819 std::make_pair(".part_id.", KmpInt32PtrTy), 3820 std::make_pair(".privates.", VoidPtrTy), 3821 std::make_pair( 3822 ".copy_fn.", 3823 Context.getPointerType(CopyFnType).withConst().withRestrict()), 3824 std::make_pair(".task_t.", Context.VoidPtrTy.withConst()), 3825 std::make_pair(StringRef(), QualType()) // __context with shared vars 3826 }; 3827 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP, 3828 Params); 3829 // Mark this captured region as inlined, because we don't use outlined 3830 // function directly. 3831 getCurCapturedRegion()->TheCapturedDecl->addAttr( 3832 AlwaysInlineAttr::CreateImplicit( 3833 Context, {}, AttributeCommonInfo::AS_Keyword, 3834 AlwaysInlineAttr::Keyword_forceinline)); 3835 break; 3836 } 3837 case OMPD_taskloop: 3838 case OMPD_taskloop_simd: 3839 case OMPD_master_taskloop: 3840 case OMPD_master_taskloop_simd: { 3841 QualType KmpInt32Ty = 3842 Context.getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/1) 3843 .withConst(); 3844 QualType KmpUInt64Ty = 3845 Context.getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/0) 3846 .withConst(); 3847 QualType KmpInt64Ty = 3848 Context.getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/1) 3849 .withConst(); 3850 QualType VoidPtrTy = Context.VoidPtrTy.withConst().withRestrict(); 3851 QualType KmpInt32PtrTy = 3852 Context.getPointerType(KmpInt32Ty).withConst().withRestrict(); 3853 QualType Args[] = {VoidPtrTy}; 3854 FunctionProtoType::ExtProtoInfo EPI; 3855 EPI.Variadic = true; 3856 QualType CopyFnType = Context.getFunctionType(Context.VoidTy, Args, EPI); 3857 Sema::CapturedParamNameType Params[] = { 3858 std::make_pair(".global_tid.", KmpInt32Ty), 3859 std::make_pair(".part_id.", KmpInt32PtrTy), 3860 std::make_pair(".privates.", VoidPtrTy), 3861 std::make_pair( 3862 ".copy_fn.", 3863 Context.getPointerType(CopyFnType).withConst().withRestrict()), 3864 std::make_pair(".task_t.", Context.VoidPtrTy.withConst()), 3865 std::make_pair(".lb.", KmpUInt64Ty), 3866 std::make_pair(".ub.", KmpUInt64Ty), 3867 std::make_pair(".st.", KmpInt64Ty), 3868 std::make_pair(".liter.", KmpInt32Ty), 3869 std::make_pair(".reductions.", VoidPtrTy), 3870 std::make_pair(StringRef(), QualType()) // __context with shared vars 3871 }; 3872 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP, 3873 Params); 3874 // Mark this captured region as inlined, because we don't use outlined 3875 // function directly. 3876 getCurCapturedRegion()->TheCapturedDecl->addAttr( 3877 AlwaysInlineAttr::CreateImplicit( 3878 Context, {}, AttributeCommonInfo::AS_Keyword, 3879 AlwaysInlineAttr::Keyword_forceinline)); 3880 break; 3881 } 3882 case OMPD_parallel_master_taskloop: 3883 case OMPD_parallel_master_taskloop_simd: { 3884 QualType KmpInt32Ty = 3885 Context.getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/1) 3886 .withConst(); 3887 QualType KmpUInt64Ty = 3888 Context.getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/0) 3889 .withConst(); 3890 QualType KmpInt64Ty = 3891 Context.getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/1) 3892 .withConst(); 3893 QualType VoidPtrTy = Context.VoidPtrTy.withConst().withRestrict(); 3894 QualType KmpInt32PtrTy = 3895 Context.getPointerType(KmpInt32Ty).withConst().withRestrict(); 3896 Sema::CapturedParamNameType ParamsParallel[] = { 3897 std::make_pair(".global_tid.", KmpInt32PtrTy), 3898 std::make_pair(".bound_tid.", KmpInt32PtrTy), 3899 std::make_pair(StringRef(), QualType()) // __context with shared vars 3900 }; 3901 // Start a captured region for 'parallel'. 3902 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP, 3903 ParamsParallel, /*OpenMPCaptureLevel=*/0); 3904 QualType Args[] = {VoidPtrTy}; 3905 FunctionProtoType::ExtProtoInfo EPI; 3906 EPI.Variadic = true; 3907 QualType CopyFnType = Context.getFunctionType(Context.VoidTy, Args, EPI); 3908 Sema::CapturedParamNameType Params[] = { 3909 std::make_pair(".global_tid.", KmpInt32Ty), 3910 std::make_pair(".part_id.", KmpInt32PtrTy), 3911 std::make_pair(".privates.", VoidPtrTy), 3912 std::make_pair( 3913 ".copy_fn.", 3914 Context.getPointerType(CopyFnType).withConst().withRestrict()), 3915 std::make_pair(".task_t.", Context.VoidPtrTy.withConst()), 3916 std::make_pair(".lb.", KmpUInt64Ty), 3917 std::make_pair(".ub.", KmpUInt64Ty), 3918 std::make_pair(".st.", KmpInt64Ty), 3919 std::make_pair(".liter.", KmpInt32Ty), 3920 std::make_pair(".reductions.", VoidPtrTy), 3921 std::make_pair(StringRef(), QualType()) // __context with shared vars 3922 }; 3923 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP, 3924 Params, /*OpenMPCaptureLevel=*/1); 3925 // Mark this captured region as inlined, because we don't use outlined 3926 // function directly. 3927 getCurCapturedRegion()->TheCapturedDecl->addAttr( 3928 AlwaysInlineAttr::CreateImplicit( 3929 Context, {}, AttributeCommonInfo::AS_Keyword, 3930 AlwaysInlineAttr::Keyword_forceinline)); 3931 break; 3932 } 3933 case OMPD_distribute_parallel_for_simd: 3934 case OMPD_distribute_parallel_for: { 3935 QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1).withConst(); 3936 QualType KmpInt32PtrTy = 3937 Context.getPointerType(KmpInt32Ty).withConst().withRestrict(); 3938 Sema::CapturedParamNameType Params[] = { 3939 std::make_pair(".global_tid.", KmpInt32PtrTy), 3940 std::make_pair(".bound_tid.", KmpInt32PtrTy), 3941 std::make_pair(".previous.lb.", Context.getSizeType().withConst()), 3942 std::make_pair(".previous.ub.", Context.getSizeType().withConst()), 3943 std::make_pair(StringRef(), QualType()) // __context with shared vars 3944 }; 3945 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP, 3946 Params); 3947 break; 3948 } 3949 case OMPD_target_teams_distribute_parallel_for: 3950 case OMPD_target_teams_distribute_parallel_for_simd: { 3951 QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1).withConst(); 3952 QualType KmpInt32PtrTy = 3953 Context.getPointerType(KmpInt32Ty).withConst().withRestrict(); 3954 QualType VoidPtrTy = Context.VoidPtrTy.withConst().withRestrict(); 3955 3956 QualType Args[] = {VoidPtrTy}; 3957 FunctionProtoType::ExtProtoInfo EPI; 3958 EPI.Variadic = true; 3959 QualType CopyFnType = Context.getFunctionType(Context.VoidTy, Args, EPI); 3960 Sema::CapturedParamNameType Params[] = { 3961 std::make_pair(".global_tid.", KmpInt32Ty), 3962 std::make_pair(".part_id.", KmpInt32PtrTy), 3963 std::make_pair(".privates.", VoidPtrTy), 3964 std::make_pair( 3965 ".copy_fn.", 3966 Context.getPointerType(CopyFnType).withConst().withRestrict()), 3967 std::make_pair(".task_t.", Context.VoidPtrTy.withConst()), 3968 std::make_pair(StringRef(), QualType()) // __context with shared vars 3969 }; 3970 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP, 3971 Params, /*OpenMPCaptureLevel=*/0); 3972 // Mark this captured region as inlined, because we don't use outlined 3973 // function directly. 3974 getCurCapturedRegion()->TheCapturedDecl->addAttr( 3975 AlwaysInlineAttr::CreateImplicit( 3976 Context, {}, AttributeCommonInfo::AS_Keyword, 3977 AlwaysInlineAttr::Keyword_forceinline)); 3978 Sema::CapturedParamNameType ParamsTarget[] = { 3979 std::make_pair(StringRef(), QualType()) // __context with shared vars 3980 }; 3981 // Start a captured region for 'target' with no implicit parameters. 3982 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP, 3983 ParamsTarget, /*OpenMPCaptureLevel=*/1); 3984 3985 Sema::CapturedParamNameType ParamsTeams[] = { 3986 std::make_pair(".global_tid.", KmpInt32PtrTy), 3987 std::make_pair(".bound_tid.", KmpInt32PtrTy), 3988 std::make_pair(StringRef(), QualType()) // __context with shared vars 3989 }; 3990 // Start a captured region for 'target' with no implicit parameters. 3991 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP, 3992 ParamsTeams, /*OpenMPCaptureLevel=*/2); 3993 3994 Sema::CapturedParamNameType ParamsParallel[] = { 3995 std::make_pair(".global_tid.", KmpInt32PtrTy), 3996 std::make_pair(".bound_tid.", KmpInt32PtrTy), 3997 std::make_pair(".previous.lb.", Context.getSizeType().withConst()), 3998 std::make_pair(".previous.ub.", Context.getSizeType().withConst()), 3999 std::make_pair(StringRef(), QualType()) // __context with shared vars 4000 }; 4001 // Start a captured region for 'teams' or 'parallel'. Both regions have 4002 // the same implicit parameters. 4003 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP, 4004 ParamsParallel, /*OpenMPCaptureLevel=*/3); 4005 break; 4006 } 4007 4008 case OMPD_teams_distribute_parallel_for: 4009 case OMPD_teams_distribute_parallel_for_simd: { 4010 QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1).withConst(); 4011 QualType KmpInt32PtrTy = 4012 Context.getPointerType(KmpInt32Ty).withConst().withRestrict(); 4013 4014 Sema::CapturedParamNameType ParamsTeams[] = { 4015 std::make_pair(".global_tid.", KmpInt32PtrTy), 4016 std::make_pair(".bound_tid.", KmpInt32PtrTy), 4017 std::make_pair(StringRef(), QualType()) // __context with shared vars 4018 }; 4019 // Start a captured region for 'target' with no implicit parameters. 4020 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP, 4021 ParamsTeams, /*OpenMPCaptureLevel=*/0); 4022 4023 Sema::CapturedParamNameType ParamsParallel[] = { 4024 std::make_pair(".global_tid.", KmpInt32PtrTy), 4025 std::make_pair(".bound_tid.", KmpInt32PtrTy), 4026 std::make_pair(".previous.lb.", Context.getSizeType().withConst()), 4027 std::make_pair(".previous.ub.", Context.getSizeType().withConst()), 4028 std::make_pair(StringRef(), QualType()) // __context with shared vars 4029 }; 4030 // Start a captured region for 'teams' or 'parallel'. Both regions have 4031 // the same implicit parameters. 4032 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP, 4033 ParamsParallel, /*OpenMPCaptureLevel=*/1); 4034 break; 4035 } 4036 case OMPD_target_update: 4037 case OMPD_target_enter_data: 4038 case OMPD_target_exit_data: { 4039 QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1).withConst(); 4040 QualType VoidPtrTy = Context.VoidPtrTy.withConst().withRestrict(); 4041 QualType KmpInt32PtrTy = 4042 Context.getPointerType(KmpInt32Ty).withConst().withRestrict(); 4043 QualType Args[] = {VoidPtrTy}; 4044 FunctionProtoType::ExtProtoInfo EPI; 4045 EPI.Variadic = true; 4046 QualType CopyFnType = Context.getFunctionType(Context.VoidTy, Args, EPI); 4047 Sema::CapturedParamNameType Params[] = { 4048 std::make_pair(".global_tid.", KmpInt32Ty), 4049 std::make_pair(".part_id.", KmpInt32PtrTy), 4050 std::make_pair(".privates.", VoidPtrTy), 4051 std::make_pair( 4052 ".copy_fn.", 4053 Context.getPointerType(CopyFnType).withConst().withRestrict()), 4054 std::make_pair(".task_t.", Context.VoidPtrTy.withConst()), 4055 std::make_pair(StringRef(), QualType()) // __context with shared vars 4056 }; 4057 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP, 4058 Params); 4059 // Mark this captured region as inlined, because we don't use outlined 4060 // function directly. 4061 getCurCapturedRegion()->TheCapturedDecl->addAttr( 4062 AlwaysInlineAttr::CreateImplicit( 4063 Context, {}, AttributeCommonInfo::AS_Keyword, 4064 AlwaysInlineAttr::Keyword_forceinline)); 4065 break; 4066 } 4067 case OMPD_threadprivate: 4068 case OMPD_allocate: 4069 case OMPD_taskyield: 4070 case OMPD_barrier: 4071 case OMPD_taskwait: 4072 case OMPD_cancellation_point: 4073 case OMPD_cancel: 4074 case OMPD_flush: 4075 case OMPD_depobj: 4076 case OMPD_scan: 4077 case OMPD_declare_reduction: 4078 case OMPD_declare_mapper: 4079 case OMPD_declare_simd: 4080 case OMPD_declare_target: 4081 case OMPD_end_declare_target: 4082 case OMPD_requires: 4083 case OMPD_declare_variant: 4084 case OMPD_begin_declare_variant: 4085 case OMPD_end_declare_variant: 4086 llvm_unreachable("OpenMP Directive is not allowed"); 4087 case OMPD_unknown: 4088 default: 4089 llvm_unreachable("Unknown OpenMP directive"); 4090 } 4091 } 4092 4093 int Sema::getNumberOfConstructScopes(unsigned Level) const { 4094 return getOpenMPCaptureLevels(DSAStack->getDirective(Level)); 4095 } 4096 4097 int Sema::getOpenMPCaptureLevels(OpenMPDirectiveKind DKind) { 4098 SmallVector<OpenMPDirectiveKind, 4> CaptureRegions; 4099 getOpenMPCaptureRegions(CaptureRegions, DKind); 4100 return CaptureRegions.size(); 4101 } 4102 4103 static OMPCapturedExprDecl *buildCaptureDecl(Sema &S, IdentifierInfo *Id, 4104 Expr *CaptureExpr, bool WithInit, 4105 bool AsExpression) { 4106 assert(CaptureExpr); 4107 ASTContext &C = S.getASTContext(); 4108 Expr *Init = AsExpression ? CaptureExpr : CaptureExpr->IgnoreImpCasts(); 4109 QualType Ty = Init->getType(); 4110 if (CaptureExpr->getObjectKind() == OK_Ordinary && CaptureExpr->isGLValue()) { 4111 if (S.getLangOpts().CPlusPlus) { 4112 Ty = C.getLValueReferenceType(Ty); 4113 } else { 4114 Ty = C.getPointerType(Ty); 4115 ExprResult Res = 4116 S.CreateBuiltinUnaryOp(CaptureExpr->getExprLoc(), UO_AddrOf, Init); 4117 if (!Res.isUsable()) 4118 return nullptr; 4119 Init = Res.get(); 4120 } 4121 WithInit = true; 4122 } 4123 auto *CED = OMPCapturedExprDecl::Create(C, S.CurContext, Id, Ty, 4124 CaptureExpr->getBeginLoc()); 4125 if (!WithInit) 4126 CED->addAttr(OMPCaptureNoInitAttr::CreateImplicit(C)); 4127 S.CurContext->addHiddenDecl(CED); 4128 S.AddInitializerToDecl(CED, Init, /*DirectInit=*/false); 4129 return CED; 4130 } 4131 4132 static DeclRefExpr *buildCapture(Sema &S, ValueDecl *D, Expr *CaptureExpr, 4133 bool WithInit) { 4134 OMPCapturedExprDecl *CD; 4135 if (VarDecl *VD = S.isOpenMPCapturedDecl(D)) 4136 CD = cast<OMPCapturedExprDecl>(VD); 4137 else 4138 CD = buildCaptureDecl(S, D->getIdentifier(), CaptureExpr, WithInit, 4139 /*AsExpression=*/false); 4140 return buildDeclRefExpr(S, CD, CD->getType().getNonReferenceType(), 4141 CaptureExpr->getExprLoc()); 4142 } 4143 4144 static ExprResult buildCapture(Sema &S, Expr *CaptureExpr, DeclRefExpr *&Ref) { 4145 CaptureExpr = S.DefaultLvalueConversion(CaptureExpr).get(); 4146 if (!Ref) { 4147 OMPCapturedExprDecl *CD = buildCaptureDecl( 4148 S, &S.getASTContext().Idents.get(".capture_expr."), CaptureExpr, 4149 /*WithInit=*/true, /*AsExpression=*/true); 4150 Ref = buildDeclRefExpr(S, CD, CD->getType().getNonReferenceType(), 4151 CaptureExpr->getExprLoc()); 4152 } 4153 ExprResult Res = Ref; 4154 if (!S.getLangOpts().CPlusPlus && 4155 CaptureExpr->getObjectKind() == OK_Ordinary && CaptureExpr->isGLValue() && 4156 Ref->getType()->isPointerType()) { 4157 Res = S.CreateBuiltinUnaryOp(CaptureExpr->getExprLoc(), UO_Deref, Ref); 4158 if (!Res.isUsable()) 4159 return ExprError(); 4160 } 4161 return S.DefaultLvalueConversion(Res.get()); 4162 } 4163 4164 namespace { 4165 // OpenMP directives parsed in this section are represented as a 4166 // CapturedStatement with an associated statement. If a syntax error 4167 // is detected during the parsing of the associated statement, the 4168 // compiler must abort processing and close the CapturedStatement. 4169 // 4170 // Combined directives such as 'target parallel' have more than one 4171 // nested CapturedStatements. This RAII ensures that we unwind out 4172 // of all the nested CapturedStatements when an error is found. 4173 class CaptureRegionUnwinderRAII { 4174 private: 4175 Sema &S; 4176 bool &ErrorFound; 4177 OpenMPDirectiveKind DKind = OMPD_unknown; 4178 4179 public: 4180 CaptureRegionUnwinderRAII(Sema &S, bool &ErrorFound, 4181 OpenMPDirectiveKind DKind) 4182 : S(S), ErrorFound(ErrorFound), DKind(DKind) {} 4183 ~CaptureRegionUnwinderRAII() { 4184 if (ErrorFound) { 4185 int ThisCaptureLevel = S.getOpenMPCaptureLevels(DKind); 4186 while (--ThisCaptureLevel >= 0) 4187 S.ActOnCapturedRegionError(); 4188 } 4189 } 4190 }; 4191 } // namespace 4192 4193 void Sema::tryCaptureOpenMPLambdas(ValueDecl *V) { 4194 // Capture variables captured by reference in lambdas for target-based 4195 // directives. 4196 if (!CurContext->isDependentContext() && 4197 (isOpenMPTargetExecutionDirective(DSAStack->getCurrentDirective()) || 4198 isOpenMPTargetDataManagementDirective( 4199 DSAStack->getCurrentDirective()))) { 4200 QualType Type = V->getType(); 4201 if (const auto *RD = Type.getCanonicalType() 4202 .getNonReferenceType() 4203 ->getAsCXXRecordDecl()) { 4204 bool SavedForceCaptureByReferenceInTargetExecutable = 4205 DSAStack->isForceCaptureByReferenceInTargetExecutable(); 4206 DSAStack->setForceCaptureByReferenceInTargetExecutable( 4207 /*V=*/true); 4208 if (RD->isLambda()) { 4209 llvm::DenseMap<const VarDecl *, FieldDecl *> Captures; 4210 FieldDecl *ThisCapture; 4211 RD->getCaptureFields(Captures, ThisCapture); 4212 for (const LambdaCapture &LC : RD->captures()) { 4213 if (LC.getCaptureKind() == LCK_ByRef) { 4214 VarDecl *VD = LC.getCapturedVar(); 4215 DeclContext *VDC = VD->getDeclContext(); 4216 if (!VDC->Encloses(CurContext)) 4217 continue; 4218 MarkVariableReferenced(LC.getLocation(), VD); 4219 } else if (LC.getCaptureKind() == LCK_This) { 4220 QualType ThisTy = getCurrentThisType(); 4221 if (!ThisTy.isNull() && 4222 Context.typesAreCompatible(ThisTy, ThisCapture->getType())) 4223 CheckCXXThisCapture(LC.getLocation()); 4224 } 4225 } 4226 } 4227 DSAStack->setForceCaptureByReferenceInTargetExecutable( 4228 SavedForceCaptureByReferenceInTargetExecutable); 4229 } 4230 } 4231 } 4232 4233 static bool checkOrderedOrderSpecified(Sema &S, 4234 const ArrayRef<OMPClause *> Clauses) { 4235 const OMPOrderedClause *Ordered = nullptr; 4236 const OMPOrderClause *Order = nullptr; 4237 4238 for (const OMPClause *Clause : Clauses) { 4239 if (Clause->getClauseKind() == OMPC_ordered) 4240 Ordered = cast<OMPOrderedClause>(Clause); 4241 else if (Clause->getClauseKind() == OMPC_order) { 4242 Order = cast<OMPOrderClause>(Clause); 4243 if (Order->getKind() != OMPC_ORDER_concurrent) 4244 Order = nullptr; 4245 } 4246 if (Ordered && Order) 4247 break; 4248 } 4249 4250 if (Ordered && Order) { 4251 S.Diag(Order->getKindKwLoc(), 4252 diag::err_omp_simple_clause_incompatible_with_ordered) 4253 << getOpenMPClauseName(OMPC_order) 4254 << getOpenMPSimpleClauseTypeName(OMPC_order, OMPC_ORDER_concurrent) 4255 << SourceRange(Order->getBeginLoc(), Order->getEndLoc()); 4256 S.Diag(Ordered->getBeginLoc(), diag::note_omp_ordered_param) 4257 << 0 << SourceRange(Ordered->getBeginLoc(), Ordered->getEndLoc()); 4258 return true; 4259 } 4260 return false; 4261 } 4262 4263 StmtResult Sema::ActOnOpenMPRegionEnd(StmtResult S, 4264 ArrayRef<OMPClause *> Clauses) { 4265 bool ErrorFound = false; 4266 CaptureRegionUnwinderRAII CaptureRegionUnwinder( 4267 *this, ErrorFound, DSAStack->getCurrentDirective()); 4268 if (!S.isUsable()) { 4269 ErrorFound = true; 4270 return StmtError(); 4271 } 4272 4273 SmallVector<OpenMPDirectiveKind, 4> CaptureRegions; 4274 getOpenMPCaptureRegions(CaptureRegions, DSAStack->getCurrentDirective()); 4275 OMPOrderedClause *OC = nullptr; 4276 OMPScheduleClause *SC = nullptr; 4277 SmallVector<const OMPLinearClause *, 4> LCs; 4278 SmallVector<const OMPClauseWithPreInit *, 4> PICs; 4279 // This is required for proper codegen. 4280 for (OMPClause *Clause : Clauses) { 4281 if (!LangOpts.OpenMPSimd && 4282 isOpenMPTaskingDirective(DSAStack->getCurrentDirective()) && 4283 Clause->getClauseKind() == OMPC_in_reduction) { 4284 // Capture taskgroup task_reduction descriptors inside the tasking regions 4285 // with the corresponding in_reduction items. 4286 auto *IRC = cast<OMPInReductionClause>(Clause); 4287 for (Expr *E : IRC->taskgroup_descriptors()) 4288 if (E) 4289 MarkDeclarationsReferencedInExpr(E); 4290 } 4291 if (isOpenMPPrivate(Clause->getClauseKind()) || 4292 Clause->getClauseKind() == OMPC_copyprivate || 4293 (getLangOpts().OpenMPUseTLS && 4294 getASTContext().getTargetInfo().isTLSSupported() && 4295 Clause->getClauseKind() == OMPC_copyin)) { 4296 DSAStack->setForceVarCapturing(Clause->getClauseKind() == OMPC_copyin); 4297 // Mark all variables in private list clauses as used in inner region. 4298 for (Stmt *VarRef : Clause->children()) { 4299 if (auto *E = cast_or_null<Expr>(VarRef)) { 4300 MarkDeclarationsReferencedInExpr(E); 4301 } 4302 } 4303 DSAStack->setForceVarCapturing(/*V=*/false); 4304 } else if (CaptureRegions.size() > 1 || 4305 CaptureRegions.back() != OMPD_unknown) { 4306 if (auto *C = OMPClauseWithPreInit::get(Clause)) 4307 PICs.push_back(C); 4308 if (auto *C = OMPClauseWithPostUpdate::get(Clause)) { 4309 if (Expr *E = C->getPostUpdateExpr()) 4310 MarkDeclarationsReferencedInExpr(E); 4311 } 4312 } 4313 if (Clause->getClauseKind() == OMPC_schedule) 4314 SC = cast<OMPScheduleClause>(Clause); 4315 else if (Clause->getClauseKind() == OMPC_ordered) 4316 OC = cast<OMPOrderedClause>(Clause); 4317 else if (Clause->getClauseKind() == OMPC_linear) 4318 LCs.push_back(cast<OMPLinearClause>(Clause)); 4319 } 4320 // Capture allocator expressions if used. 4321 for (Expr *E : DSAStack->getInnerAllocators()) 4322 MarkDeclarationsReferencedInExpr(E); 4323 // OpenMP, 2.7.1 Loop Construct, Restrictions 4324 // The nonmonotonic modifier cannot be specified if an ordered clause is 4325 // specified. 4326 if (SC && 4327 (SC->getFirstScheduleModifier() == OMPC_SCHEDULE_MODIFIER_nonmonotonic || 4328 SC->getSecondScheduleModifier() == 4329 OMPC_SCHEDULE_MODIFIER_nonmonotonic) && 4330 OC) { 4331 Diag(SC->getFirstScheduleModifier() == OMPC_SCHEDULE_MODIFIER_nonmonotonic 4332 ? SC->getFirstScheduleModifierLoc() 4333 : SC->getSecondScheduleModifierLoc(), 4334 diag::err_omp_simple_clause_incompatible_with_ordered) 4335 << getOpenMPClauseName(OMPC_schedule) 4336 << getOpenMPSimpleClauseTypeName(OMPC_schedule, 4337 OMPC_SCHEDULE_MODIFIER_nonmonotonic) 4338 << SourceRange(OC->getBeginLoc(), OC->getEndLoc()); 4339 ErrorFound = true; 4340 } 4341 // OpenMP 5.0, 2.9.2 Worksharing-Loop Construct, Restrictions. 4342 // If an order(concurrent) clause is present, an ordered clause may not appear 4343 // on the same directive. 4344 if (checkOrderedOrderSpecified(*this, Clauses)) 4345 ErrorFound = true; 4346 if (!LCs.empty() && OC && OC->getNumForLoops()) { 4347 for (const OMPLinearClause *C : LCs) { 4348 Diag(C->getBeginLoc(), diag::err_omp_linear_ordered) 4349 << SourceRange(OC->getBeginLoc(), OC->getEndLoc()); 4350 } 4351 ErrorFound = true; 4352 } 4353 if (isOpenMPWorksharingDirective(DSAStack->getCurrentDirective()) && 4354 isOpenMPSimdDirective(DSAStack->getCurrentDirective()) && OC && 4355 OC->getNumForLoops()) { 4356 Diag(OC->getBeginLoc(), diag::err_omp_ordered_simd) 4357 << getOpenMPDirectiveName(DSAStack->getCurrentDirective()); 4358 ErrorFound = true; 4359 } 4360 if (ErrorFound) { 4361 return StmtError(); 4362 } 4363 StmtResult SR = S; 4364 unsigned CompletedRegions = 0; 4365 for (OpenMPDirectiveKind ThisCaptureRegion : llvm::reverse(CaptureRegions)) { 4366 // Mark all variables in private list clauses as used in inner region. 4367 // Required for proper codegen of combined directives. 4368 // TODO: add processing for other clauses. 4369 if (ThisCaptureRegion != OMPD_unknown) { 4370 for (const clang::OMPClauseWithPreInit *C : PICs) { 4371 OpenMPDirectiveKind CaptureRegion = C->getCaptureRegion(); 4372 // Find the particular capture region for the clause if the 4373 // directive is a combined one with multiple capture regions. 4374 // If the directive is not a combined one, the capture region 4375 // associated with the clause is OMPD_unknown and is generated 4376 // only once. 4377 if (CaptureRegion == ThisCaptureRegion || 4378 CaptureRegion == OMPD_unknown) { 4379 if (auto *DS = cast_or_null<DeclStmt>(C->getPreInitStmt())) { 4380 for (Decl *D : DS->decls()) 4381 MarkVariableReferenced(D->getLocation(), cast<VarDecl>(D)); 4382 } 4383 } 4384 } 4385 } 4386 if (ThisCaptureRegion == OMPD_target) { 4387 // Capture allocator traits in the target region. They are used implicitly 4388 // and, thus, are not captured by default. 4389 for (OMPClause *C : Clauses) { 4390 if (const auto *UAC = dyn_cast<OMPUsesAllocatorsClause>(C)) { 4391 for (unsigned I = 0, End = UAC->getNumberOfAllocators(); I < End; 4392 ++I) { 4393 OMPUsesAllocatorsClause::Data D = UAC->getAllocatorData(I); 4394 if (Expr *E = D.AllocatorTraits) 4395 MarkDeclarationsReferencedInExpr(E); 4396 } 4397 continue; 4398 } 4399 } 4400 } 4401 if (++CompletedRegions == CaptureRegions.size()) 4402 DSAStack->setBodyComplete(); 4403 SR = ActOnCapturedRegionEnd(SR.get()); 4404 } 4405 return SR; 4406 } 4407 4408 static bool checkCancelRegion(Sema &SemaRef, OpenMPDirectiveKind CurrentRegion, 4409 OpenMPDirectiveKind CancelRegion, 4410 SourceLocation StartLoc) { 4411 // CancelRegion is only needed for cancel and cancellation_point. 4412 if (CurrentRegion != OMPD_cancel && CurrentRegion != OMPD_cancellation_point) 4413 return false; 4414 4415 if (CancelRegion == OMPD_parallel || CancelRegion == OMPD_for || 4416 CancelRegion == OMPD_sections || CancelRegion == OMPD_taskgroup) 4417 return false; 4418 4419 SemaRef.Diag(StartLoc, diag::err_omp_wrong_cancel_region) 4420 << getOpenMPDirectiveName(CancelRegion); 4421 return true; 4422 } 4423 4424 static bool checkNestingOfRegions(Sema &SemaRef, const DSAStackTy *Stack, 4425 OpenMPDirectiveKind CurrentRegion, 4426 const DeclarationNameInfo &CurrentName, 4427 OpenMPDirectiveKind CancelRegion, 4428 SourceLocation StartLoc) { 4429 if (Stack->getCurScope()) { 4430 OpenMPDirectiveKind ParentRegion = Stack->getParentDirective(); 4431 OpenMPDirectiveKind OffendingRegion = ParentRegion; 4432 bool NestingProhibited = false; 4433 bool CloseNesting = true; 4434 bool OrphanSeen = false; 4435 enum { 4436 NoRecommend, 4437 ShouldBeInParallelRegion, 4438 ShouldBeInOrderedRegion, 4439 ShouldBeInTargetRegion, 4440 ShouldBeInTeamsRegion, 4441 ShouldBeInLoopSimdRegion, 4442 } Recommend = NoRecommend; 4443 if (isOpenMPSimdDirective(ParentRegion) && 4444 ((SemaRef.LangOpts.OpenMP <= 45 && CurrentRegion != OMPD_ordered) || 4445 (SemaRef.LangOpts.OpenMP >= 50 && CurrentRegion != OMPD_ordered && 4446 CurrentRegion != OMPD_simd && CurrentRegion != OMPD_atomic && 4447 CurrentRegion != OMPD_scan))) { 4448 // OpenMP [2.16, Nesting of Regions] 4449 // OpenMP constructs may not be nested inside a simd region. 4450 // OpenMP [2.8.1,simd Construct, Restrictions] 4451 // An ordered construct with the simd clause is the only OpenMP 4452 // construct that can appear in the simd region. 4453 // Allowing a SIMD construct nested in another SIMD construct is an 4454 // extension. The OpenMP 4.5 spec does not allow it. Issue a warning 4455 // message. 4456 // OpenMP 5.0 [2.9.3.1, simd Construct, Restrictions] 4457 // The only OpenMP constructs that can be encountered during execution of 4458 // a simd region are the atomic construct, the loop construct, the simd 4459 // construct and the ordered construct with the simd clause. 4460 SemaRef.Diag(StartLoc, (CurrentRegion != OMPD_simd) 4461 ? diag::err_omp_prohibited_region_simd 4462 : diag::warn_omp_nesting_simd) 4463 << (SemaRef.LangOpts.OpenMP >= 50 ? 1 : 0); 4464 return CurrentRegion != OMPD_simd; 4465 } 4466 if (ParentRegion == OMPD_atomic) { 4467 // OpenMP [2.16, Nesting of Regions] 4468 // OpenMP constructs may not be nested inside an atomic region. 4469 SemaRef.Diag(StartLoc, diag::err_omp_prohibited_region_atomic); 4470 return true; 4471 } 4472 if (CurrentRegion == OMPD_section) { 4473 // OpenMP [2.7.2, sections Construct, Restrictions] 4474 // Orphaned section directives are prohibited. That is, the section 4475 // directives must appear within the sections construct and must not be 4476 // encountered elsewhere in the sections region. 4477 if (ParentRegion != OMPD_sections && 4478 ParentRegion != OMPD_parallel_sections) { 4479 SemaRef.Diag(StartLoc, diag::err_omp_orphaned_section_directive) 4480 << (ParentRegion != OMPD_unknown) 4481 << getOpenMPDirectiveName(ParentRegion); 4482 return true; 4483 } 4484 return false; 4485 } 4486 // Allow some constructs (except teams and cancellation constructs) to be 4487 // orphaned (they could be used in functions, called from OpenMP regions 4488 // with the required preconditions). 4489 if (ParentRegion == OMPD_unknown && 4490 !isOpenMPNestingTeamsDirective(CurrentRegion) && 4491 CurrentRegion != OMPD_cancellation_point && 4492 CurrentRegion != OMPD_cancel && CurrentRegion != OMPD_scan) 4493 return false; 4494 if (CurrentRegion == OMPD_cancellation_point || 4495 CurrentRegion == OMPD_cancel) { 4496 // OpenMP [2.16, Nesting of Regions] 4497 // A cancellation point construct for which construct-type-clause is 4498 // taskgroup must be nested inside a task construct. A cancellation 4499 // point construct for which construct-type-clause is not taskgroup must 4500 // be closely nested inside an OpenMP construct that matches the type 4501 // specified in construct-type-clause. 4502 // A cancel construct for which construct-type-clause is taskgroup must be 4503 // nested inside a task construct. A cancel construct for which 4504 // construct-type-clause is not taskgroup must be closely nested inside an 4505 // OpenMP construct that matches the type specified in 4506 // construct-type-clause. 4507 NestingProhibited = 4508 !((CancelRegion == OMPD_parallel && 4509 (ParentRegion == OMPD_parallel || 4510 ParentRegion == OMPD_target_parallel)) || 4511 (CancelRegion == OMPD_for && 4512 (ParentRegion == OMPD_for || ParentRegion == OMPD_parallel_for || 4513 ParentRegion == OMPD_target_parallel_for || 4514 ParentRegion == OMPD_distribute_parallel_for || 4515 ParentRegion == OMPD_teams_distribute_parallel_for || 4516 ParentRegion == OMPD_target_teams_distribute_parallel_for)) || 4517 (CancelRegion == OMPD_taskgroup && 4518 (ParentRegion == OMPD_task || 4519 (SemaRef.getLangOpts().OpenMP >= 50 && 4520 (ParentRegion == OMPD_taskloop || 4521 ParentRegion == OMPD_master_taskloop || 4522 ParentRegion == OMPD_parallel_master_taskloop)))) || 4523 (CancelRegion == OMPD_sections && 4524 (ParentRegion == OMPD_section || ParentRegion == OMPD_sections || 4525 ParentRegion == OMPD_parallel_sections))); 4526 OrphanSeen = ParentRegion == OMPD_unknown; 4527 } else if (CurrentRegion == OMPD_master) { 4528 // OpenMP [2.16, Nesting of Regions] 4529 // A master region may not be closely nested inside a worksharing, 4530 // atomic, or explicit task region. 4531 NestingProhibited = isOpenMPWorksharingDirective(ParentRegion) || 4532 isOpenMPTaskingDirective(ParentRegion); 4533 } else if (CurrentRegion == OMPD_critical && CurrentName.getName()) { 4534 // OpenMP [2.16, Nesting of Regions] 4535 // A critical region may not be nested (closely or otherwise) inside a 4536 // critical region with the same name. Note that this restriction is not 4537 // sufficient to prevent deadlock. 4538 SourceLocation PreviousCriticalLoc; 4539 bool DeadLock = Stack->hasDirective( 4540 [CurrentName, &PreviousCriticalLoc](OpenMPDirectiveKind K, 4541 const DeclarationNameInfo &DNI, 4542 SourceLocation Loc) { 4543 if (K == OMPD_critical && DNI.getName() == CurrentName.getName()) { 4544 PreviousCriticalLoc = Loc; 4545 return true; 4546 } 4547 return false; 4548 }, 4549 false /* skip top directive */); 4550 if (DeadLock) { 4551 SemaRef.Diag(StartLoc, 4552 diag::err_omp_prohibited_region_critical_same_name) 4553 << CurrentName.getName(); 4554 if (PreviousCriticalLoc.isValid()) 4555 SemaRef.Diag(PreviousCriticalLoc, 4556 diag::note_omp_previous_critical_region); 4557 return true; 4558 } 4559 } else if (CurrentRegion == OMPD_barrier) { 4560 // OpenMP [2.16, Nesting of Regions] 4561 // A barrier region may not be closely nested inside a worksharing, 4562 // explicit task, critical, ordered, atomic, or master region. 4563 NestingProhibited = isOpenMPWorksharingDirective(ParentRegion) || 4564 isOpenMPTaskingDirective(ParentRegion) || 4565 ParentRegion == OMPD_master || 4566 ParentRegion == OMPD_parallel_master || 4567 ParentRegion == OMPD_critical || 4568 ParentRegion == OMPD_ordered; 4569 } else if (isOpenMPWorksharingDirective(CurrentRegion) && 4570 !isOpenMPParallelDirective(CurrentRegion) && 4571 !isOpenMPTeamsDirective(CurrentRegion)) { 4572 // OpenMP [2.16, Nesting of Regions] 4573 // A worksharing region may not be closely nested inside a worksharing, 4574 // explicit task, critical, ordered, atomic, or master region. 4575 NestingProhibited = isOpenMPWorksharingDirective(ParentRegion) || 4576 isOpenMPTaskingDirective(ParentRegion) || 4577 ParentRegion == OMPD_master || 4578 ParentRegion == OMPD_parallel_master || 4579 ParentRegion == OMPD_critical || 4580 ParentRegion == OMPD_ordered; 4581 Recommend = ShouldBeInParallelRegion; 4582 } else if (CurrentRegion == OMPD_ordered) { 4583 // OpenMP [2.16, Nesting of Regions] 4584 // An ordered region may not be closely nested inside a critical, 4585 // atomic, or explicit task region. 4586 // An ordered region must be closely nested inside a loop region (or 4587 // parallel loop region) with an ordered clause. 4588 // OpenMP [2.8.1,simd Construct, Restrictions] 4589 // An ordered construct with the simd clause is the only OpenMP construct 4590 // that can appear in the simd region. 4591 NestingProhibited = ParentRegion == OMPD_critical || 4592 isOpenMPTaskingDirective(ParentRegion) || 4593 !(isOpenMPSimdDirective(ParentRegion) || 4594 Stack->isParentOrderedRegion()); 4595 Recommend = ShouldBeInOrderedRegion; 4596 } else if (isOpenMPNestingTeamsDirective(CurrentRegion)) { 4597 // OpenMP [2.16, Nesting of Regions] 4598 // If specified, a teams construct must be contained within a target 4599 // construct. 4600 NestingProhibited = 4601 (SemaRef.LangOpts.OpenMP <= 45 && ParentRegion != OMPD_target) || 4602 (SemaRef.LangOpts.OpenMP >= 50 && ParentRegion != OMPD_unknown && 4603 ParentRegion != OMPD_target); 4604 OrphanSeen = ParentRegion == OMPD_unknown; 4605 Recommend = ShouldBeInTargetRegion; 4606 } else if (CurrentRegion == OMPD_scan) { 4607 // OpenMP [2.16, Nesting of Regions] 4608 // If specified, a teams construct must be contained within a target 4609 // construct. 4610 NestingProhibited = 4611 SemaRef.LangOpts.OpenMP < 50 || 4612 (ParentRegion != OMPD_simd && ParentRegion != OMPD_for && 4613 ParentRegion != OMPD_for_simd && ParentRegion != OMPD_parallel_for && 4614 ParentRegion != OMPD_parallel_for_simd); 4615 OrphanSeen = ParentRegion == OMPD_unknown; 4616 Recommend = ShouldBeInLoopSimdRegion; 4617 } 4618 if (!NestingProhibited && 4619 !isOpenMPTargetExecutionDirective(CurrentRegion) && 4620 !isOpenMPTargetDataManagementDirective(CurrentRegion) && 4621 (ParentRegion == OMPD_teams || ParentRegion == OMPD_target_teams)) { 4622 // OpenMP [2.16, Nesting of Regions] 4623 // distribute, parallel, parallel sections, parallel workshare, and the 4624 // parallel loop and parallel loop SIMD constructs are the only OpenMP 4625 // constructs that can be closely nested in the teams region. 4626 NestingProhibited = !isOpenMPParallelDirective(CurrentRegion) && 4627 !isOpenMPDistributeDirective(CurrentRegion); 4628 Recommend = ShouldBeInParallelRegion; 4629 } 4630 if (!NestingProhibited && 4631 isOpenMPNestingDistributeDirective(CurrentRegion)) { 4632 // OpenMP 4.5 [2.17 Nesting of Regions] 4633 // The region associated with the distribute construct must be strictly 4634 // nested inside a teams region 4635 NestingProhibited = 4636 (ParentRegion != OMPD_teams && ParentRegion != OMPD_target_teams); 4637 Recommend = ShouldBeInTeamsRegion; 4638 } 4639 if (!NestingProhibited && 4640 (isOpenMPTargetExecutionDirective(CurrentRegion) || 4641 isOpenMPTargetDataManagementDirective(CurrentRegion))) { 4642 // OpenMP 4.5 [2.17 Nesting of Regions] 4643 // If a target, target update, target data, target enter data, or 4644 // target exit data construct is encountered during execution of a 4645 // target region, the behavior is unspecified. 4646 NestingProhibited = Stack->hasDirective( 4647 [&OffendingRegion](OpenMPDirectiveKind K, const DeclarationNameInfo &, 4648 SourceLocation) { 4649 if (isOpenMPTargetExecutionDirective(K)) { 4650 OffendingRegion = K; 4651 return true; 4652 } 4653 return false; 4654 }, 4655 false /* don't skip top directive */); 4656 CloseNesting = false; 4657 } 4658 if (NestingProhibited) { 4659 if (OrphanSeen) { 4660 SemaRef.Diag(StartLoc, diag::err_omp_orphaned_device_directive) 4661 << getOpenMPDirectiveName(CurrentRegion) << Recommend; 4662 } else { 4663 SemaRef.Diag(StartLoc, diag::err_omp_prohibited_region) 4664 << CloseNesting << getOpenMPDirectiveName(OffendingRegion) 4665 << Recommend << getOpenMPDirectiveName(CurrentRegion); 4666 } 4667 return true; 4668 } 4669 } 4670 return false; 4671 } 4672 4673 struct Kind2Unsigned { 4674 using argument_type = OpenMPDirectiveKind; 4675 unsigned operator()(argument_type DK) { return unsigned(DK); } 4676 }; 4677 static bool checkIfClauses(Sema &S, OpenMPDirectiveKind Kind, 4678 ArrayRef<OMPClause *> Clauses, 4679 ArrayRef<OpenMPDirectiveKind> AllowedNameModifiers) { 4680 bool ErrorFound = false; 4681 unsigned NamedModifiersNumber = 0; 4682 llvm::IndexedMap<const OMPIfClause *, Kind2Unsigned> FoundNameModifiers; 4683 FoundNameModifiers.resize(llvm::omp::Directive_enumSize + 1); 4684 SmallVector<SourceLocation, 4> NameModifierLoc; 4685 for (const OMPClause *C : Clauses) { 4686 if (const auto *IC = dyn_cast_or_null<OMPIfClause>(C)) { 4687 // At most one if clause without a directive-name-modifier can appear on 4688 // the directive. 4689 OpenMPDirectiveKind CurNM = IC->getNameModifier(); 4690 if (FoundNameModifiers[CurNM]) { 4691 S.Diag(C->getBeginLoc(), diag::err_omp_more_one_clause) 4692 << getOpenMPDirectiveName(Kind) << getOpenMPClauseName(OMPC_if) 4693 << (CurNM != OMPD_unknown) << getOpenMPDirectiveName(CurNM); 4694 ErrorFound = true; 4695 } else if (CurNM != OMPD_unknown) { 4696 NameModifierLoc.push_back(IC->getNameModifierLoc()); 4697 ++NamedModifiersNumber; 4698 } 4699 FoundNameModifiers[CurNM] = IC; 4700 if (CurNM == OMPD_unknown) 4701 continue; 4702 // Check if the specified name modifier is allowed for the current 4703 // directive. 4704 // At most one if clause with the particular directive-name-modifier can 4705 // appear on the directive. 4706 bool MatchFound = false; 4707 for (auto NM : AllowedNameModifiers) { 4708 if (CurNM == NM) { 4709 MatchFound = true; 4710 break; 4711 } 4712 } 4713 if (!MatchFound) { 4714 S.Diag(IC->getNameModifierLoc(), 4715 diag::err_omp_wrong_if_directive_name_modifier) 4716 << getOpenMPDirectiveName(CurNM) << getOpenMPDirectiveName(Kind); 4717 ErrorFound = true; 4718 } 4719 } 4720 } 4721 // If any if clause on the directive includes a directive-name-modifier then 4722 // all if clauses on the directive must include a directive-name-modifier. 4723 if (FoundNameModifiers[OMPD_unknown] && NamedModifiersNumber > 0) { 4724 if (NamedModifiersNumber == AllowedNameModifiers.size()) { 4725 S.Diag(FoundNameModifiers[OMPD_unknown]->getBeginLoc(), 4726 diag::err_omp_no_more_if_clause); 4727 } else { 4728 std::string Values; 4729 std::string Sep(", "); 4730 unsigned AllowedCnt = 0; 4731 unsigned TotalAllowedNum = 4732 AllowedNameModifiers.size() - NamedModifiersNumber; 4733 for (unsigned Cnt = 0, End = AllowedNameModifiers.size(); Cnt < End; 4734 ++Cnt) { 4735 OpenMPDirectiveKind NM = AllowedNameModifiers[Cnt]; 4736 if (!FoundNameModifiers[NM]) { 4737 Values += "'"; 4738 Values += getOpenMPDirectiveName(NM); 4739 Values += "'"; 4740 if (AllowedCnt + 2 == TotalAllowedNum) 4741 Values += " or "; 4742 else if (AllowedCnt + 1 != TotalAllowedNum) 4743 Values += Sep; 4744 ++AllowedCnt; 4745 } 4746 } 4747 S.Diag(FoundNameModifiers[OMPD_unknown]->getCondition()->getBeginLoc(), 4748 diag::err_omp_unnamed_if_clause) 4749 << (TotalAllowedNum > 1) << Values; 4750 } 4751 for (SourceLocation Loc : NameModifierLoc) { 4752 S.Diag(Loc, diag::note_omp_previous_named_if_clause); 4753 } 4754 ErrorFound = true; 4755 } 4756 return ErrorFound; 4757 } 4758 4759 static std::pair<ValueDecl *, bool> getPrivateItem(Sema &S, Expr *&RefExpr, 4760 SourceLocation &ELoc, 4761 SourceRange &ERange, 4762 bool AllowArraySection) { 4763 if (RefExpr->isTypeDependent() || RefExpr->isValueDependent() || 4764 RefExpr->containsUnexpandedParameterPack()) 4765 return std::make_pair(nullptr, true); 4766 4767 // OpenMP [3.1, C/C++] 4768 // A list item is a variable name. 4769 // OpenMP [2.9.3.3, Restrictions, p.1] 4770 // A variable that is part of another variable (as an array or 4771 // structure element) cannot appear in a private clause. 4772 RefExpr = RefExpr->IgnoreParens(); 4773 enum { 4774 NoArrayExpr = -1, 4775 ArraySubscript = 0, 4776 OMPArraySection = 1 4777 } IsArrayExpr = NoArrayExpr; 4778 if (AllowArraySection) { 4779 if (auto *ASE = dyn_cast_or_null<ArraySubscriptExpr>(RefExpr)) { 4780 Expr *Base = ASE->getBase()->IgnoreParenImpCasts(); 4781 while (auto *TempASE = dyn_cast<ArraySubscriptExpr>(Base)) 4782 Base = TempASE->getBase()->IgnoreParenImpCasts(); 4783 RefExpr = Base; 4784 IsArrayExpr = ArraySubscript; 4785 } else if (auto *OASE = dyn_cast_or_null<OMPArraySectionExpr>(RefExpr)) { 4786 Expr *Base = OASE->getBase()->IgnoreParenImpCasts(); 4787 while (auto *TempOASE = dyn_cast<OMPArraySectionExpr>(Base)) 4788 Base = TempOASE->getBase()->IgnoreParenImpCasts(); 4789 while (auto *TempASE = dyn_cast<ArraySubscriptExpr>(Base)) 4790 Base = TempASE->getBase()->IgnoreParenImpCasts(); 4791 RefExpr = Base; 4792 IsArrayExpr = OMPArraySection; 4793 } 4794 } 4795 ELoc = RefExpr->getExprLoc(); 4796 ERange = RefExpr->getSourceRange(); 4797 RefExpr = RefExpr->IgnoreParenImpCasts(); 4798 auto *DE = dyn_cast_or_null<DeclRefExpr>(RefExpr); 4799 auto *ME = dyn_cast_or_null<MemberExpr>(RefExpr); 4800 if ((!DE || !isa<VarDecl>(DE->getDecl())) && 4801 (S.getCurrentThisType().isNull() || !ME || 4802 !isa<CXXThisExpr>(ME->getBase()->IgnoreParenImpCasts()) || 4803 !isa<FieldDecl>(ME->getMemberDecl()))) { 4804 if (IsArrayExpr != NoArrayExpr) { 4805 S.Diag(ELoc, diag::err_omp_expected_base_var_name) << IsArrayExpr 4806 << ERange; 4807 } else { 4808 S.Diag(ELoc, 4809 AllowArraySection 4810 ? diag::err_omp_expected_var_name_member_expr_or_array_item 4811 : diag::err_omp_expected_var_name_member_expr) 4812 << (S.getCurrentThisType().isNull() ? 0 : 1) << ERange; 4813 } 4814 return std::make_pair(nullptr, false); 4815 } 4816 return std::make_pair( 4817 getCanonicalDecl(DE ? DE->getDecl() : ME->getMemberDecl()), false); 4818 } 4819 4820 namespace { 4821 /// Checks if the allocator is used in uses_allocators clause to be allowed in 4822 /// target regions. 4823 class AllocatorChecker final : public ConstStmtVisitor<AllocatorChecker, bool> { 4824 DSAStackTy *S = nullptr; 4825 4826 public: 4827 bool VisitDeclRefExpr(const DeclRefExpr *E) { 4828 return S->isUsesAllocatorsDecl(E->getDecl()) 4829 .getValueOr( 4830 DSAStackTy::UsesAllocatorsDeclKind::AllocatorTrait) == 4831 DSAStackTy::UsesAllocatorsDeclKind::AllocatorTrait; 4832 } 4833 bool VisitStmt(const Stmt *S) { 4834 for (const Stmt *Child : S->children()) { 4835 if (Child && Visit(Child)) 4836 return true; 4837 } 4838 return false; 4839 } 4840 explicit AllocatorChecker(DSAStackTy *S) : S(S) {} 4841 }; 4842 } // namespace 4843 4844 static void checkAllocateClauses(Sema &S, DSAStackTy *Stack, 4845 ArrayRef<OMPClause *> Clauses) { 4846 assert(!S.CurContext->isDependentContext() && 4847 "Expected non-dependent context."); 4848 auto AllocateRange = 4849 llvm::make_filter_range(Clauses, OMPAllocateClause::classof); 4850 llvm::DenseMap<CanonicalDeclPtr<Decl>, CanonicalDeclPtr<VarDecl>> 4851 DeclToCopy; 4852 auto PrivateRange = llvm::make_filter_range(Clauses, [](const OMPClause *C) { 4853 return isOpenMPPrivate(C->getClauseKind()); 4854 }); 4855 for (OMPClause *Cl : PrivateRange) { 4856 MutableArrayRef<Expr *>::iterator I, It, Et; 4857 if (Cl->getClauseKind() == OMPC_private) { 4858 auto *PC = cast<OMPPrivateClause>(Cl); 4859 I = PC->private_copies().begin(); 4860 It = PC->varlist_begin(); 4861 Et = PC->varlist_end(); 4862 } else if (Cl->getClauseKind() == OMPC_firstprivate) { 4863 auto *PC = cast<OMPFirstprivateClause>(Cl); 4864 I = PC->private_copies().begin(); 4865 It = PC->varlist_begin(); 4866 Et = PC->varlist_end(); 4867 } else if (Cl->getClauseKind() == OMPC_lastprivate) { 4868 auto *PC = cast<OMPLastprivateClause>(Cl); 4869 I = PC->private_copies().begin(); 4870 It = PC->varlist_begin(); 4871 Et = PC->varlist_end(); 4872 } else if (Cl->getClauseKind() == OMPC_linear) { 4873 auto *PC = cast<OMPLinearClause>(Cl); 4874 I = PC->privates().begin(); 4875 It = PC->varlist_begin(); 4876 Et = PC->varlist_end(); 4877 } else if (Cl->getClauseKind() == OMPC_reduction) { 4878 auto *PC = cast<OMPReductionClause>(Cl); 4879 I = PC->privates().begin(); 4880 It = PC->varlist_begin(); 4881 Et = PC->varlist_end(); 4882 } else if (Cl->getClauseKind() == OMPC_task_reduction) { 4883 auto *PC = cast<OMPTaskReductionClause>(Cl); 4884 I = PC->privates().begin(); 4885 It = PC->varlist_begin(); 4886 Et = PC->varlist_end(); 4887 } else if (Cl->getClauseKind() == OMPC_in_reduction) { 4888 auto *PC = cast<OMPInReductionClause>(Cl); 4889 I = PC->privates().begin(); 4890 It = PC->varlist_begin(); 4891 Et = PC->varlist_end(); 4892 } else { 4893 llvm_unreachable("Expected private clause."); 4894 } 4895 for (Expr *E : llvm::make_range(It, Et)) { 4896 if (!*I) { 4897 ++I; 4898 continue; 4899 } 4900 SourceLocation ELoc; 4901 SourceRange ERange; 4902 Expr *SimpleRefExpr = E; 4903 auto Res = getPrivateItem(S, SimpleRefExpr, ELoc, ERange, 4904 /*AllowArraySection=*/true); 4905 DeclToCopy.try_emplace(Res.first, 4906 cast<VarDecl>(cast<DeclRefExpr>(*I)->getDecl())); 4907 ++I; 4908 } 4909 } 4910 for (OMPClause *C : AllocateRange) { 4911 auto *AC = cast<OMPAllocateClause>(C); 4912 if (S.getLangOpts().OpenMP >= 50 && 4913 !Stack->hasRequiresDeclWithClause<OMPDynamicAllocatorsClause>() && 4914 isOpenMPTargetExecutionDirective(Stack->getCurrentDirective()) && 4915 AC->getAllocator()) { 4916 Expr *Allocator = AC->getAllocator(); 4917 // OpenMP, 2.12.5 target Construct 4918 // Memory allocators that do not appear in a uses_allocators clause cannot 4919 // appear as an allocator in an allocate clause or be used in the target 4920 // region unless a requires directive with the dynamic_allocators clause 4921 // is present in the same compilation unit. 4922 AllocatorChecker Checker(Stack); 4923 if (Checker.Visit(Allocator)) 4924 S.Diag(Allocator->getExprLoc(), 4925 diag::err_omp_allocator_not_in_uses_allocators) 4926 << Allocator->getSourceRange(); 4927 } 4928 OMPAllocateDeclAttr::AllocatorTypeTy AllocatorKind = 4929 getAllocatorKind(S, Stack, AC->getAllocator()); 4930 // OpenMP, 2.11.4 allocate Clause, Restrictions. 4931 // For task, taskloop or target directives, allocation requests to memory 4932 // allocators with the trait access set to thread result in unspecified 4933 // behavior. 4934 if (AllocatorKind == OMPAllocateDeclAttr::OMPThreadMemAlloc && 4935 (isOpenMPTaskingDirective(Stack->getCurrentDirective()) || 4936 isOpenMPTargetExecutionDirective(Stack->getCurrentDirective()))) { 4937 S.Diag(AC->getAllocator()->getExprLoc(), 4938 diag::warn_omp_allocate_thread_on_task_target_directive) 4939 << getOpenMPDirectiveName(Stack->getCurrentDirective()); 4940 } 4941 for (Expr *E : AC->varlists()) { 4942 SourceLocation ELoc; 4943 SourceRange ERange; 4944 Expr *SimpleRefExpr = E; 4945 auto Res = getPrivateItem(S, SimpleRefExpr, ELoc, ERange); 4946 ValueDecl *VD = Res.first; 4947 DSAStackTy::DSAVarData Data = Stack->getTopDSA(VD, /*FromParent=*/false); 4948 if (!isOpenMPPrivate(Data.CKind)) { 4949 S.Diag(E->getExprLoc(), 4950 diag::err_omp_expected_private_copy_for_allocate); 4951 continue; 4952 } 4953 VarDecl *PrivateVD = DeclToCopy[VD]; 4954 if (checkPreviousOMPAllocateAttribute(S, Stack, E, PrivateVD, 4955 AllocatorKind, AC->getAllocator())) 4956 continue; 4957 applyOMPAllocateAttribute(S, PrivateVD, AllocatorKind, AC->getAllocator(), 4958 E->getSourceRange()); 4959 } 4960 } 4961 } 4962 4963 StmtResult Sema::ActOnOpenMPExecutableDirective( 4964 OpenMPDirectiveKind Kind, const DeclarationNameInfo &DirName, 4965 OpenMPDirectiveKind CancelRegion, ArrayRef<OMPClause *> Clauses, 4966 Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc) { 4967 StmtResult Res = StmtError(); 4968 // First check CancelRegion which is then used in checkNestingOfRegions. 4969 if (checkCancelRegion(*this, Kind, CancelRegion, StartLoc) || 4970 checkNestingOfRegions(*this, DSAStack, Kind, DirName, CancelRegion, 4971 StartLoc)) 4972 return StmtError(); 4973 4974 llvm::SmallVector<OMPClause *, 8> ClausesWithImplicit; 4975 VarsWithInheritedDSAType VarsWithInheritedDSA; 4976 bool ErrorFound = false; 4977 ClausesWithImplicit.append(Clauses.begin(), Clauses.end()); 4978 if (AStmt && !CurContext->isDependentContext()) { 4979 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected"); 4980 4981 // Check default data sharing attributes for referenced variables. 4982 DSAAttrChecker DSAChecker(DSAStack, *this, cast<CapturedStmt>(AStmt)); 4983 int ThisCaptureLevel = getOpenMPCaptureLevels(Kind); 4984 Stmt *S = AStmt; 4985 while (--ThisCaptureLevel >= 0) 4986 S = cast<CapturedStmt>(S)->getCapturedStmt(); 4987 DSAChecker.Visit(S); 4988 if (!isOpenMPTargetDataManagementDirective(Kind) && 4989 !isOpenMPTaskingDirective(Kind)) { 4990 // Visit subcaptures to generate implicit clauses for captured vars. 4991 auto *CS = cast<CapturedStmt>(AStmt); 4992 SmallVector<OpenMPDirectiveKind, 4> CaptureRegions; 4993 getOpenMPCaptureRegions(CaptureRegions, Kind); 4994 // Ignore outer tasking regions for target directives. 4995 if (CaptureRegions.size() > 1 && CaptureRegions.front() == OMPD_task) 4996 CS = cast<CapturedStmt>(CS->getCapturedStmt()); 4997 DSAChecker.visitSubCaptures(CS); 4998 } 4999 if (DSAChecker.isErrorFound()) 5000 return StmtError(); 5001 // Generate list of implicitly defined firstprivate variables. 5002 VarsWithInheritedDSA = DSAChecker.getVarsWithInheritedDSA(); 5003 5004 SmallVector<Expr *, 4> ImplicitFirstprivates( 5005 DSAChecker.getImplicitFirstprivate().begin(), 5006 DSAChecker.getImplicitFirstprivate().end()); 5007 SmallVector<Expr *, 4> ImplicitMaps[OMPC_MAP_delete]; 5008 for (unsigned I = 0; I < OMPC_MAP_delete; ++I) { 5009 ArrayRef<Expr *> ImplicitMap = 5010 DSAChecker.getImplicitMap(static_cast<OpenMPDefaultmapClauseKind>(I)); 5011 ImplicitMaps[I].append(ImplicitMap.begin(), ImplicitMap.end()); 5012 } 5013 // Mark taskgroup task_reduction descriptors as implicitly firstprivate. 5014 for (OMPClause *C : Clauses) { 5015 if (auto *IRC = dyn_cast<OMPInReductionClause>(C)) { 5016 for (Expr *E : IRC->taskgroup_descriptors()) 5017 if (E) 5018 ImplicitFirstprivates.emplace_back(E); 5019 } 5020 // OpenMP 5.0, 2.10.1 task Construct 5021 // [detach clause]... The event-handle will be considered as if it was 5022 // specified on a firstprivate clause. 5023 if (auto *DC = dyn_cast<OMPDetachClause>(C)) 5024 ImplicitFirstprivates.push_back(DC->getEventHandler()); 5025 } 5026 if (!ImplicitFirstprivates.empty()) { 5027 if (OMPClause *Implicit = ActOnOpenMPFirstprivateClause( 5028 ImplicitFirstprivates, SourceLocation(), SourceLocation(), 5029 SourceLocation())) { 5030 ClausesWithImplicit.push_back(Implicit); 5031 ErrorFound = cast<OMPFirstprivateClause>(Implicit)->varlist_size() != 5032 ImplicitFirstprivates.size(); 5033 } else { 5034 ErrorFound = true; 5035 } 5036 } 5037 int ClauseKindCnt = -1; 5038 for (ArrayRef<Expr *> ImplicitMap : ImplicitMaps) { 5039 ++ClauseKindCnt; 5040 if (ImplicitMap.empty()) 5041 continue; 5042 CXXScopeSpec MapperIdScopeSpec; 5043 DeclarationNameInfo MapperId; 5044 auto Kind = static_cast<OpenMPMapClauseKind>(ClauseKindCnt); 5045 if (OMPClause *Implicit = ActOnOpenMPMapClause( 5046 llvm::None, llvm::None, MapperIdScopeSpec, MapperId, Kind, 5047 /*IsMapTypeImplicit=*/true, SourceLocation(), SourceLocation(), 5048 ImplicitMap, OMPVarListLocTy())) { 5049 ClausesWithImplicit.emplace_back(Implicit); 5050 ErrorFound |= 5051 cast<OMPMapClause>(Implicit)->varlist_size() != ImplicitMap.size(); 5052 } else { 5053 ErrorFound = true; 5054 } 5055 } 5056 } 5057 5058 llvm::SmallVector<OpenMPDirectiveKind, 4> AllowedNameModifiers; 5059 switch (Kind) { 5060 case OMPD_parallel: 5061 Res = ActOnOpenMPParallelDirective(ClausesWithImplicit, AStmt, StartLoc, 5062 EndLoc); 5063 AllowedNameModifiers.push_back(OMPD_parallel); 5064 break; 5065 case OMPD_simd: 5066 Res = ActOnOpenMPSimdDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc, 5067 VarsWithInheritedDSA); 5068 if (LangOpts.OpenMP >= 50) 5069 AllowedNameModifiers.push_back(OMPD_simd); 5070 break; 5071 case OMPD_for: 5072 Res = ActOnOpenMPForDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc, 5073 VarsWithInheritedDSA); 5074 break; 5075 case OMPD_for_simd: 5076 Res = ActOnOpenMPForSimdDirective(ClausesWithImplicit, AStmt, StartLoc, 5077 EndLoc, VarsWithInheritedDSA); 5078 if (LangOpts.OpenMP >= 50) 5079 AllowedNameModifiers.push_back(OMPD_simd); 5080 break; 5081 case OMPD_sections: 5082 Res = ActOnOpenMPSectionsDirective(ClausesWithImplicit, AStmt, StartLoc, 5083 EndLoc); 5084 break; 5085 case OMPD_section: 5086 assert(ClausesWithImplicit.empty() && 5087 "No clauses are allowed for 'omp section' directive"); 5088 Res = ActOnOpenMPSectionDirective(AStmt, StartLoc, EndLoc); 5089 break; 5090 case OMPD_single: 5091 Res = ActOnOpenMPSingleDirective(ClausesWithImplicit, AStmt, StartLoc, 5092 EndLoc); 5093 break; 5094 case OMPD_master: 5095 assert(ClausesWithImplicit.empty() && 5096 "No clauses are allowed for 'omp master' directive"); 5097 Res = ActOnOpenMPMasterDirective(AStmt, StartLoc, EndLoc); 5098 break; 5099 case OMPD_critical: 5100 Res = ActOnOpenMPCriticalDirective(DirName, ClausesWithImplicit, AStmt, 5101 StartLoc, EndLoc); 5102 break; 5103 case OMPD_parallel_for: 5104 Res = ActOnOpenMPParallelForDirective(ClausesWithImplicit, AStmt, StartLoc, 5105 EndLoc, VarsWithInheritedDSA); 5106 AllowedNameModifiers.push_back(OMPD_parallel); 5107 break; 5108 case OMPD_parallel_for_simd: 5109 Res = ActOnOpenMPParallelForSimdDirective( 5110 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA); 5111 AllowedNameModifiers.push_back(OMPD_parallel); 5112 if (LangOpts.OpenMP >= 50) 5113 AllowedNameModifiers.push_back(OMPD_simd); 5114 break; 5115 case OMPD_parallel_master: 5116 Res = ActOnOpenMPParallelMasterDirective(ClausesWithImplicit, AStmt, 5117 StartLoc, EndLoc); 5118 AllowedNameModifiers.push_back(OMPD_parallel); 5119 break; 5120 case OMPD_parallel_sections: 5121 Res = ActOnOpenMPParallelSectionsDirective(ClausesWithImplicit, AStmt, 5122 StartLoc, EndLoc); 5123 AllowedNameModifiers.push_back(OMPD_parallel); 5124 break; 5125 case OMPD_task: 5126 Res = 5127 ActOnOpenMPTaskDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc); 5128 AllowedNameModifiers.push_back(OMPD_task); 5129 break; 5130 case OMPD_taskyield: 5131 assert(ClausesWithImplicit.empty() && 5132 "No clauses are allowed for 'omp taskyield' directive"); 5133 assert(AStmt == nullptr && 5134 "No associated statement allowed for 'omp taskyield' directive"); 5135 Res = ActOnOpenMPTaskyieldDirective(StartLoc, EndLoc); 5136 break; 5137 case OMPD_barrier: 5138 assert(ClausesWithImplicit.empty() && 5139 "No clauses are allowed for 'omp barrier' directive"); 5140 assert(AStmt == nullptr && 5141 "No associated statement allowed for 'omp barrier' directive"); 5142 Res = ActOnOpenMPBarrierDirective(StartLoc, EndLoc); 5143 break; 5144 case OMPD_taskwait: 5145 assert(ClausesWithImplicit.empty() && 5146 "No clauses are allowed for 'omp taskwait' directive"); 5147 assert(AStmt == nullptr && 5148 "No associated statement allowed for 'omp taskwait' directive"); 5149 Res = ActOnOpenMPTaskwaitDirective(StartLoc, EndLoc); 5150 break; 5151 case OMPD_taskgroup: 5152 Res = ActOnOpenMPTaskgroupDirective(ClausesWithImplicit, AStmt, StartLoc, 5153 EndLoc); 5154 break; 5155 case OMPD_flush: 5156 assert(AStmt == nullptr && 5157 "No associated statement allowed for 'omp flush' directive"); 5158 Res = ActOnOpenMPFlushDirective(ClausesWithImplicit, StartLoc, EndLoc); 5159 break; 5160 case OMPD_depobj: 5161 assert(AStmt == nullptr && 5162 "No associated statement allowed for 'omp depobj' directive"); 5163 Res = ActOnOpenMPDepobjDirective(ClausesWithImplicit, StartLoc, EndLoc); 5164 break; 5165 case OMPD_scan: 5166 assert(AStmt == nullptr && 5167 "No associated statement allowed for 'omp scan' directive"); 5168 Res = ActOnOpenMPScanDirective(ClausesWithImplicit, StartLoc, EndLoc); 5169 break; 5170 case OMPD_ordered: 5171 Res = ActOnOpenMPOrderedDirective(ClausesWithImplicit, AStmt, StartLoc, 5172 EndLoc); 5173 break; 5174 case OMPD_atomic: 5175 Res = ActOnOpenMPAtomicDirective(ClausesWithImplicit, AStmt, StartLoc, 5176 EndLoc); 5177 break; 5178 case OMPD_teams: 5179 Res = 5180 ActOnOpenMPTeamsDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc); 5181 break; 5182 case OMPD_target: 5183 Res = ActOnOpenMPTargetDirective(ClausesWithImplicit, AStmt, StartLoc, 5184 EndLoc); 5185 AllowedNameModifiers.push_back(OMPD_target); 5186 break; 5187 case OMPD_target_parallel: 5188 Res = ActOnOpenMPTargetParallelDirective(ClausesWithImplicit, AStmt, 5189 StartLoc, EndLoc); 5190 AllowedNameModifiers.push_back(OMPD_target); 5191 AllowedNameModifiers.push_back(OMPD_parallel); 5192 break; 5193 case OMPD_target_parallel_for: 5194 Res = ActOnOpenMPTargetParallelForDirective( 5195 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA); 5196 AllowedNameModifiers.push_back(OMPD_target); 5197 AllowedNameModifiers.push_back(OMPD_parallel); 5198 break; 5199 case OMPD_cancellation_point: 5200 assert(ClausesWithImplicit.empty() && 5201 "No clauses are allowed for 'omp cancellation point' directive"); 5202 assert(AStmt == nullptr && "No associated statement allowed for 'omp " 5203 "cancellation point' directive"); 5204 Res = ActOnOpenMPCancellationPointDirective(StartLoc, EndLoc, CancelRegion); 5205 break; 5206 case OMPD_cancel: 5207 assert(AStmt == nullptr && 5208 "No associated statement allowed for 'omp cancel' directive"); 5209 Res = ActOnOpenMPCancelDirective(ClausesWithImplicit, StartLoc, EndLoc, 5210 CancelRegion); 5211 AllowedNameModifiers.push_back(OMPD_cancel); 5212 break; 5213 case OMPD_target_data: 5214 Res = ActOnOpenMPTargetDataDirective(ClausesWithImplicit, AStmt, StartLoc, 5215 EndLoc); 5216 AllowedNameModifiers.push_back(OMPD_target_data); 5217 break; 5218 case OMPD_target_enter_data: 5219 Res = ActOnOpenMPTargetEnterDataDirective(ClausesWithImplicit, StartLoc, 5220 EndLoc, AStmt); 5221 AllowedNameModifiers.push_back(OMPD_target_enter_data); 5222 break; 5223 case OMPD_target_exit_data: 5224 Res = ActOnOpenMPTargetExitDataDirective(ClausesWithImplicit, StartLoc, 5225 EndLoc, AStmt); 5226 AllowedNameModifiers.push_back(OMPD_target_exit_data); 5227 break; 5228 case OMPD_taskloop: 5229 Res = ActOnOpenMPTaskLoopDirective(ClausesWithImplicit, AStmt, StartLoc, 5230 EndLoc, VarsWithInheritedDSA); 5231 AllowedNameModifiers.push_back(OMPD_taskloop); 5232 break; 5233 case OMPD_taskloop_simd: 5234 Res = ActOnOpenMPTaskLoopSimdDirective(ClausesWithImplicit, AStmt, StartLoc, 5235 EndLoc, VarsWithInheritedDSA); 5236 AllowedNameModifiers.push_back(OMPD_taskloop); 5237 if (LangOpts.OpenMP >= 50) 5238 AllowedNameModifiers.push_back(OMPD_simd); 5239 break; 5240 case OMPD_master_taskloop: 5241 Res = ActOnOpenMPMasterTaskLoopDirective( 5242 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA); 5243 AllowedNameModifiers.push_back(OMPD_taskloop); 5244 break; 5245 case OMPD_master_taskloop_simd: 5246 Res = ActOnOpenMPMasterTaskLoopSimdDirective( 5247 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA); 5248 AllowedNameModifiers.push_back(OMPD_taskloop); 5249 if (LangOpts.OpenMP >= 50) 5250 AllowedNameModifiers.push_back(OMPD_simd); 5251 break; 5252 case OMPD_parallel_master_taskloop: 5253 Res = ActOnOpenMPParallelMasterTaskLoopDirective( 5254 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA); 5255 AllowedNameModifiers.push_back(OMPD_taskloop); 5256 AllowedNameModifiers.push_back(OMPD_parallel); 5257 break; 5258 case OMPD_parallel_master_taskloop_simd: 5259 Res = ActOnOpenMPParallelMasterTaskLoopSimdDirective( 5260 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA); 5261 AllowedNameModifiers.push_back(OMPD_taskloop); 5262 AllowedNameModifiers.push_back(OMPD_parallel); 5263 if (LangOpts.OpenMP >= 50) 5264 AllowedNameModifiers.push_back(OMPD_simd); 5265 break; 5266 case OMPD_distribute: 5267 Res = ActOnOpenMPDistributeDirective(ClausesWithImplicit, AStmt, StartLoc, 5268 EndLoc, VarsWithInheritedDSA); 5269 break; 5270 case OMPD_target_update: 5271 Res = ActOnOpenMPTargetUpdateDirective(ClausesWithImplicit, StartLoc, 5272 EndLoc, AStmt); 5273 AllowedNameModifiers.push_back(OMPD_target_update); 5274 break; 5275 case OMPD_distribute_parallel_for: 5276 Res = ActOnOpenMPDistributeParallelForDirective( 5277 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA); 5278 AllowedNameModifiers.push_back(OMPD_parallel); 5279 break; 5280 case OMPD_distribute_parallel_for_simd: 5281 Res = ActOnOpenMPDistributeParallelForSimdDirective( 5282 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA); 5283 AllowedNameModifiers.push_back(OMPD_parallel); 5284 if (LangOpts.OpenMP >= 50) 5285 AllowedNameModifiers.push_back(OMPD_simd); 5286 break; 5287 case OMPD_distribute_simd: 5288 Res = ActOnOpenMPDistributeSimdDirective( 5289 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA); 5290 if (LangOpts.OpenMP >= 50) 5291 AllowedNameModifiers.push_back(OMPD_simd); 5292 break; 5293 case OMPD_target_parallel_for_simd: 5294 Res = ActOnOpenMPTargetParallelForSimdDirective( 5295 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA); 5296 AllowedNameModifiers.push_back(OMPD_target); 5297 AllowedNameModifiers.push_back(OMPD_parallel); 5298 if (LangOpts.OpenMP >= 50) 5299 AllowedNameModifiers.push_back(OMPD_simd); 5300 break; 5301 case OMPD_target_simd: 5302 Res = ActOnOpenMPTargetSimdDirective(ClausesWithImplicit, AStmt, StartLoc, 5303 EndLoc, VarsWithInheritedDSA); 5304 AllowedNameModifiers.push_back(OMPD_target); 5305 if (LangOpts.OpenMP >= 50) 5306 AllowedNameModifiers.push_back(OMPD_simd); 5307 break; 5308 case OMPD_teams_distribute: 5309 Res = ActOnOpenMPTeamsDistributeDirective( 5310 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA); 5311 break; 5312 case OMPD_teams_distribute_simd: 5313 Res = ActOnOpenMPTeamsDistributeSimdDirective( 5314 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA); 5315 if (LangOpts.OpenMP >= 50) 5316 AllowedNameModifiers.push_back(OMPD_simd); 5317 break; 5318 case OMPD_teams_distribute_parallel_for_simd: 5319 Res = ActOnOpenMPTeamsDistributeParallelForSimdDirective( 5320 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA); 5321 AllowedNameModifiers.push_back(OMPD_parallel); 5322 if (LangOpts.OpenMP >= 50) 5323 AllowedNameModifiers.push_back(OMPD_simd); 5324 break; 5325 case OMPD_teams_distribute_parallel_for: 5326 Res = ActOnOpenMPTeamsDistributeParallelForDirective( 5327 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA); 5328 AllowedNameModifiers.push_back(OMPD_parallel); 5329 break; 5330 case OMPD_target_teams: 5331 Res = ActOnOpenMPTargetTeamsDirective(ClausesWithImplicit, AStmt, StartLoc, 5332 EndLoc); 5333 AllowedNameModifiers.push_back(OMPD_target); 5334 break; 5335 case OMPD_target_teams_distribute: 5336 Res = ActOnOpenMPTargetTeamsDistributeDirective( 5337 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA); 5338 AllowedNameModifiers.push_back(OMPD_target); 5339 break; 5340 case OMPD_target_teams_distribute_parallel_for: 5341 Res = ActOnOpenMPTargetTeamsDistributeParallelForDirective( 5342 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA); 5343 AllowedNameModifiers.push_back(OMPD_target); 5344 AllowedNameModifiers.push_back(OMPD_parallel); 5345 break; 5346 case OMPD_target_teams_distribute_parallel_for_simd: 5347 Res = ActOnOpenMPTargetTeamsDistributeParallelForSimdDirective( 5348 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA); 5349 AllowedNameModifiers.push_back(OMPD_target); 5350 AllowedNameModifiers.push_back(OMPD_parallel); 5351 if (LangOpts.OpenMP >= 50) 5352 AllowedNameModifiers.push_back(OMPD_simd); 5353 break; 5354 case OMPD_target_teams_distribute_simd: 5355 Res = ActOnOpenMPTargetTeamsDistributeSimdDirective( 5356 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA); 5357 AllowedNameModifiers.push_back(OMPD_target); 5358 if (LangOpts.OpenMP >= 50) 5359 AllowedNameModifiers.push_back(OMPD_simd); 5360 break; 5361 case OMPD_declare_target: 5362 case OMPD_end_declare_target: 5363 case OMPD_threadprivate: 5364 case OMPD_allocate: 5365 case OMPD_declare_reduction: 5366 case OMPD_declare_mapper: 5367 case OMPD_declare_simd: 5368 case OMPD_requires: 5369 case OMPD_declare_variant: 5370 case OMPD_begin_declare_variant: 5371 case OMPD_end_declare_variant: 5372 llvm_unreachable("OpenMP Directive is not allowed"); 5373 case OMPD_unknown: 5374 default: 5375 llvm_unreachable("Unknown OpenMP directive"); 5376 } 5377 5378 ErrorFound = Res.isInvalid() || ErrorFound; 5379 5380 // Check variables in the clauses if default(none) or 5381 // default(firstprivate) was specified. 5382 if (DSAStack->getDefaultDSA() == DSA_none || 5383 DSAStack->getDefaultDSA() == DSA_firstprivate) { 5384 DSAAttrChecker DSAChecker(DSAStack, *this, nullptr); 5385 for (OMPClause *C : Clauses) { 5386 switch (C->getClauseKind()) { 5387 case OMPC_num_threads: 5388 case OMPC_dist_schedule: 5389 // Do not analyse if no parent teams directive. 5390 if (isOpenMPTeamsDirective(Kind)) 5391 break; 5392 continue; 5393 case OMPC_if: 5394 if (isOpenMPTeamsDirective(Kind) && 5395 cast<OMPIfClause>(C)->getNameModifier() != OMPD_target) 5396 break; 5397 if (isOpenMPParallelDirective(Kind) && 5398 isOpenMPTaskLoopDirective(Kind) && 5399 cast<OMPIfClause>(C)->getNameModifier() != OMPD_parallel) 5400 break; 5401 continue; 5402 case OMPC_schedule: 5403 case OMPC_detach: 5404 break; 5405 case OMPC_grainsize: 5406 case OMPC_num_tasks: 5407 case OMPC_final: 5408 case OMPC_priority: 5409 // Do not analyze if no parent parallel directive. 5410 if (isOpenMPParallelDirective(Kind)) 5411 break; 5412 continue; 5413 case OMPC_ordered: 5414 case OMPC_device: 5415 case OMPC_num_teams: 5416 case OMPC_thread_limit: 5417 case OMPC_hint: 5418 case OMPC_collapse: 5419 case OMPC_safelen: 5420 case OMPC_simdlen: 5421 case OMPC_default: 5422 case OMPC_proc_bind: 5423 case OMPC_private: 5424 case OMPC_firstprivate: 5425 case OMPC_lastprivate: 5426 case OMPC_shared: 5427 case OMPC_reduction: 5428 case OMPC_task_reduction: 5429 case OMPC_in_reduction: 5430 case OMPC_linear: 5431 case OMPC_aligned: 5432 case OMPC_copyin: 5433 case OMPC_copyprivate: 5434 case OMPC_nowait: 5435 case OMPC_untied: 5436 case OMPC_mergeable: 5437 case OMPC_allocate: 5438 case OMPC_read: 5439 case OMPC_write: 5440 case OMPC_update: 5441 case OMPC_capture: 5442 case OMPC_seq_cst: 5443 case OMPC_acq_rel: 5444 case OMPC_acquire: 5445 case OMPC_release: 5446 case OMPC_relaxed: 5447 case OMPC_depend: 5448 case OMPC_threads: 5449 case OMPC_simd: 5450 case OMPC_map: 5451 case OMPC_nogroup: 5452 case OMPC_defaultmap: 5453 case OMPC_to: 5454 case OMPC_from: 5455 case OMPC_use_device_ptr: 5456 case OMPC_use_device_addr: 5457 case OMPC_is_device_ptr: 5458 case OMPC_nontemporal: 5459 case OMPC_order: 5460 case OMPC_destroy: 5461 case OMPC_inclusive: 5462 case OMPC_exclusive: 5463 case OMPC_uses_allocators: 5464 case OMPC_affinity: 5465 continue; 5466 case OMPC_allocator: 5467 case OMPC_flush: 5468 case OMPC_depobj: 5469 case OMPC_threadprivate: 5470 case OMPC_uniform: 5471 case OMPC_unknown: 5472 case OMPC_unified_address: 5473 case OMPC_unified_shared_memory: 5474 case OMPC_reverse_offload: 5475 case OMPC_dynamic_allocators: 5476 case OMPC_atomic_default_mem_order: 5477 case OMPC_device_type: 5478 case OMPC_match: 5479 default: 5480 llvm_unreachable("Unexpected clause"); 5481 } 5482 for (Stmt *CC : C->children()) { 5483 if (CC) 5484 DSAChecker.Visit(CC); 5485 } 5486 } 5487 for (const auto &P : DSAChecker.getVarsWithInheritedDSA()) 5488 VarsWithInheritedDSA[P.getFirst()] = P.getSecond(); 5489 } 5490 for (const auto &P : VarsWithInheritedDSA) { 5491 if (P.getFirst()->isImplicit() || isa<OMPCapturedExprDecl>(P.getFirst())) 5492 continue; 5493 ErrorFound = true; 5494 if (DSAStack->getDefaultDSA() == DSA_none || 5495 DSAStack->getDefaultDSA() == DSA_firstprivate) { 5496 Diag(P.second->getExprLoc(), diag::err_omp_no_dsa_for_variable) 5497 << P.first << P.second->getSourceRange(); 5498 Diag(DSAStack->getDefaultDSALocation(), diag::note_omp_default_dsa_none); 5499 } else if (getLangOpts().OpenMP >= 50) { 5500 Diag(P.second->getExprLoc(), 5501 diag::err_omp_defaultmap_no_attr_for_variable) 5502 << P.first << P.second->getSourceRange(); 5503 Diag(DSAStack->getDefaultDSALocation(), 5504 diag::note_omp_defaultmap_attr_none); 5505 } 5506 } 5507 5508 if (!AllowedNameModifiers.empty()) 5509 ErrorFound = checkIfClauses(*this, Kind, Clauses, AllowedNameModifiers) || 5510 ErrorFound; 5511 5512 if (ErrorFound) 5513 return StmtError(); 5514 5515 if (!CurContext->isDependentContext() && 5516 isOpenMPTargetExecutionDirective(Kind) && 5517 !(DSAStack->hasRequiresDeclWithClause<OMPUnifiedSharedMemoryClause>() || 5518 DSAStack->hasRequiresDeclWithClause<OMPUnifiedAddressClause>() || 5519 DSAStack->hasRequiresDeclWithClause<OMPReverseOffloadClause>() || 5520 DSAStack->hasRequiresDeclWithClause<OMPDynamicAllocatorsClause>())) { 5521 // Register target to DSA Stack. 5522 DSAStack->addTargetDirLocation(StartLoc); 5523 } 5524 5525 return Res; 5526 } 5527 5528 Sema::DeclGroupPtrTy Sema::ActOnOpenMPDeclareSimdDirective( 5529 DeclGroupPtrTy DG, OMPDeclareSimdDeclAttr::BranchStateTy BS, Expr *Simdlen, 5530 ArrayRef<Expr *> Uniforms, ArrayRef<Expr *> Aligneds, 5531 ArrayRef<Expr *> Alignments, ArrayRef<Expr *> Linears, 5532 ArrayRef<unsigned> LinModifiers, ArrayRef<Expr *> Steps, SourceRange SR) { 5533 assert(Aligneds.size() == Alignments.size()); 5534 assert(Linears.size() == LinModifiers.size()); 5535 assert(Linears.size() == Steps.size()); 5536 if (!DG || DG.get().isNull()) 5537 return DeclGroupPtrTy(); 5538 5539 const int SimdId = 0; 5540 if (!DG.get().isSingleDecl()) { 5541 Diag(SR.getBegin(), diag::err_omp_single_decl_in_declare_simd_variant) 5542 << SimdId; 5543 return DG; 5544 } 5545 Decl *ADecl = DG.get().getSingleDecl(); 5546 if (auto *FTD = dyn_cast<FunctionTemplateDecl>(ADecl)) 5547 ADecl = FTD->getTemplatedDecl(); 5548 5549 auto *FD = dyn_cast<FunctionDecl>(ADecl); 5550 if (!FD) { 5551 Diag(ADecl->getLocation(), diag::err_omp_function_expected) << SimdId; 5552 return DeclGroupPtrTy(); 5553 } 5554 5555 // OpenMP [2.8.2, declare simd construct, Description] 5556 // The parameter of the simdlen clause must be a constant positive integer 5557 // expression. 5558 ExprResult SL; 5559 if (Simdlen) 5560 SL = VerifyPositiveIntegerConstantInClause(Simdlen, OMPC_simdlen); 5561 // OpenMP [2.8.2, declare simd construct, Description] 5562 // The special this pointer can be used as if was one of the arguments to the 5563 // function in any of the linear, aligned, or uniform clauses. 5564 // The uniform clause declares one or more arguments to have an invariant 5565 // value for all concurrent invocations of the function in the execution of a 5566 // single SIMD loop. 5567 llvm::DenseMap<const Decl *, const Expr *> UniformedArgs; 5568 const Expr *UniformedLinearThis = nullptr; 5569 for (const Expr *E : Uniforms) { 5570 E = E->IgnoreParenImpCasts(); 5571 if (const auto *DRE = dyn_cast<DeclRefExpr>(E)) 5572 if (const auto *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl())) 5573 if (FD->getNumParams() > PVD->getFunctionScopeIndex() && 5574 FD->getParamDecl(PVD->getFunctionScopeIndex()) 5575 ->getCanonicalDecl() == PVD->getCanonicalDecl()) { 5576 UniformedArgs.try_emplace(PVD->getCanonicalDecl(), E); 5577 continue; 5578 } 5579 if (isa<CXXThisExpr>(E)) { 5580 UniformedLinearThis = E; 5581 continue; 5582 } 5583 Diag(E->getExprLoc(), diag::err_omp_param_or_this_in_clause) 5584 << FD->getDeclName() << (isa<CXXMethodDecl>(ADecl) ? 1 : 0); 5585 } 5586 // OpenMP [2.8.2, declare simd construct, Description] 5587 // The aligned clause declares that the object to which each list item points 5588 // is aligned to the number of bytes expressed in the optional parameter of 5589 // the aligned clause. 5590 // The special this pointer can be used as if was one of the arguments to the 5591 // function in any of the linear, aligned, or uniform clauses. 5592 // The type of list items appearing in the aligned clause must be array, 5593 // pointer, reference to array, or reference to pointer. 5594 llvm::DenseMap<const Decl *, const Expr *> AlignedArgs; 5595 const Expr *AlignedThis = nullptr; 5596 for (const Expr *E : Aligneds) { 5597 E = E->IgnoreParenImpCasts(); 5598 if (const auto *DRE = dyn_cast<DeclRefExpr>(E)) 5599 if (const auto *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl())) { 5600 const VarDecl *CanonPVD = PVD->getCanonicalDecl(); 5601 if (FD->getNumParams() > PVD->getFunctionScopeIndex() && 5602 FD->getParamDecl(PVD->getFunctionScopeIndex()) 5603 ->getCanonicalDecl() == CanonPVD) { 5604 // OpenMP [2.8.1, simd construct, Restrictions] 5605 // A list-item cannot appear in more than one aligned clause. 5606 if (AlignedArgs.count(CanonPVD) > 0) { 5607 Diag(E->getExprLoc(), diag::err_omp_used_in_clause_twice) 5608 << 1 << getOpenMPClauseName(OMPC_aligned) 5609 << E->getSourceRange(); 5610 Diag(AlignedArgs[CanonPVD]->getExprLoc(), 5611 diag::note_omp_explicit_dsa) 5612 << getOpenMPClauseName(OMPC_aligned); 5613 continue; 5614 } 5615 AlignedArgs[CanonPVD] = E; 5616 QualType QTy = PVD->getType() 5617 .getNonReferenceType() 5618 .getUnqualifiedType() 5619 .getCanonicalType(); 5620 const Type *Ty = QTy.getTypePtrOrNull(); 5621 if (!Ty || (!Ty->isArrayType() && !Ty->isPointerType())) { 5622 Diag(E->getExprLoc(), diag::err_omp_aligned_expected_array_or_ptr) 5623 << QTy << getLangOpts().CPlusPlus << E->getSourceRange(); 5624 Diag(PVD->getLocation(), diag::note_previous_decl) << PVD; 5625 } 5626 continue; 5627 } 5628 } 5629 if (isa<CXXThisExpr>(E)) { 5630 if (AlignedThis) { 5631 Diag(E->getExprLoc(), diag::err_omp_used_in_clause_twice) 5632 << 2 << getOpenMPClauseName(OMPC_aligned) << E->getSourceRange(); 5633 Diag(AlignedThis->getExprLoc(), diag::note_omp_explicit_dsa) 5634 << getOpenMPClauseName(OMPC_aligned); 5635 } 5636 AlignedThis = E; 5637 continue; 5638 } 5639 Diag(E->getExprLoc(), diag::err_omp_param_or_this_in_clause) 5640 << FD->getDeclName() << (isa<CXXMethodDecl>(ADecl) ? 1 : 0); 5641 } 5642 // The optional parameter of the aligned clause, alignment, must be a constant 5643 // positive integer expression. If no optional parameter is specified, 5644 // implementation-defined default alignments for SIMD instructions on the 5645 // target platforms are assumed. 5646 SmallVector<const Expr *, 4> NewAligns; 5647 for (Expr *E : Alignments) { 5648 ExprResult Align; 5649 if (E) 5650 Align = VerifyPositiveIntegerConstantInClause(E, OMPC_aligned); 5651 NewAligns.push_back(Align.get()); 5652 } 5653 // OpenMP [2.8.2, declare simd construct, Description] 5654 // The linear clause declares one or more list items to be private to a SIMD 5655 // lane and to have a linear relationship with respect to the iteration space 5656 // of a loop. 5657 // The special this pointer can be used as if was one of the arguments to the 5658 // function in any of the linear, aligned, or uniform clauses. 5659 // When a linear-step expression is specified in a linear clause it must be 5660 // either a constant integer expression or an integer-typed parameter that is 5661 // specified in a uniform clause on the directive. 5662 llvm::DenseMap<const Decl *, const Expr *> LinearArgs; 5663 const bool IsUniformedThis = UniformedLinearThis != nullptr; 5664 auto MI = LinModifiers.begin(); 5665 for (const Expr *E : Linears) { 5666 auto LinKind = static_cast<OpenMPLinearClauseKind>(*MI); 5667 ++MI; 5668 E = E->IgnoreParenImpCasts(); 5669 if (const auto *DRE = dyn_cast<DeclRefExpr>(E)) 5670 if (const auto *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl())) { 5671 const VarDecl *CanonPVD = PVD->getCanonicalDecl(); 5672 if (FD->getNumParams() > PVD->getFunctionScopeIndex() && 5673 FD->getParamDecl(PVD->getFunctionScopeIndex()) 5674 ->getCanonicalDecl() == CanonPVD) { 5675 // OpenMP [2.15.3.7, linear Clause, Restrictions] 5676 // A list-item cannot appear in more than one linear clause. 5677 if (LinearArgs.count(CanonPVD) > 0) { 5678 Diag(E->getExprLoc(), diag::err_omp_wrong_dsa) 5679 << getOpenMPClauseName(OMPC_linear) 5680 << getOpenMPClauseName(OMPC_linear) << E->getSourceRange(); 5681 Diag(LinearArgs[CanonPVD]->getExprLoc(), 5682 diag::note_omp_explicit_dsa) 5683 << getOpenMPClauseName(OMPC_linear); 5684 continue; 5685 } 5686 // Each argument can appear in at most one uniform or linear clause. 5687 if (UniformedArgs.count(CanonPVD) > 0) { 5688 Diag(E->getExprLoc(), diag::err_omp_wrong_dsa) 5689 << getOpenMPClauseName(OMPC_linear) 5690 << getOpenMPClauseName(OMPC_uniform) << E->getSourceRange(); 5691 Diag(UniformedArgs[CanonPVD]->getExprLoc(), 5692 diag::note_omp_explicit_dsa) 5693 << getOpenMPClauseName(OMPC_uniform); 5694 continue; 5695 } 5696 LinearArgs[CanonPVD] = E; 5697 if (E->isValueDependent() || E->isTypeDependent() || 5698 E->isInstantiationDependent() || 5699 E->containsUnexpandedParameterPack()) 5700 continue; 5701 (void)CheckOpenMPLinearDecl(CanonPVD, E->getExprLoc(), LinKind, 5702 PVD->getOriginalType(), 5703 /*IsDeclareSimd=*/true); 5704 continue; 5705 } 5706 } 5707 if (isa<CXXThisExpr>(E)) { 5708 if (UniformedLinearThis) { 5709 Diag(E->getExprLoc(), diag::err_omp_wrong_dsa) 5710 << getOpenMPClauseName(OMPC_linear) 5711 << getOpenMPClauseName(IsUniformedThis ? OMPC_uniform : OMPC_linear) 5712 << E->getSourceRange(); 5713 Diag(UniformedLinearThis->getExprLoc(), diag::note_omp_explicit_dsa) 5714 << getOpenMPClauseName(IsUniformedThis ? OMPC_uniform 5715 : OMPC_linear); 5716 continue; 5717 } 5718 UniformedLinearThis = E; 5719 if (E->isValueDependent() || E->isTypeDependent() || 5720 E->isInstantiationDependent() || E->containsUnexpandedParameterPack()) 5721 continue; 5722 (void)CheckOpenMPLinearDecl(/*D=*/nullptr, E->getExprLoc(), LinKind, 5723 E->getType(), /*IsDeclareSimd=*/true); 5724 continue; 5725 } 5726 Diag(E->getExprLoc(), diag::err_omp_param_or_this_in_clause) 5727 << FD->getDeclName() << (isa<CXXMethodDecl>(ADecl) ? 1 : 0); 5728 } 5729 Expr *Step = nullptr; 5730 Expr *NewStep = nullptr; 5731 SmallVector<Expr *, 4> NewSteps; 5732 for (Expr *E : Steps) { 5733 // Skip the same step expression, it was checked already. 5734 if (Step == E || !E) { 5735 NewSteps.push_back(E ? NewStep : nullptr); 5736 continue; 5737 } 5738 Step = E; 5739 if (const auto *DRE = dyn_cast<DeclRefExpr>(Step)) 5740 if (const auto *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl())) { 5741 const VarDecl *CanonPVD = PVD->getCanonicalDecl(); 5742 if (UniformedArgs.count(CanonPVD) == 0) { 5743 Diag(Step->getExprLoc(), diag::err_omp_expected_uniform_param) 5744 << Step->getSourceRange(); 5745 } else if (E->isValueDependent() || E->isTypeDependent() || 5746 E->isInstantiationDependent() || 5747 E->containsUnexpandedParameterPack() || 5748 CanonPVD->getType()->hasIntegerRepresentation()) { 5749 NewSteps.push_back(Step); 5750 } else { 5751 Diag(Step->getExprLoc(), diag::err_omp_expected_int_param) 5752 << Step->getSourceRange(); 5753 } 5754 continue; 5755 } 5756 NewStep = Step; 5757 if (Step && !Step->isValueDependent() && !Step->isTypeDependent() && 5758 !Step->isInstantiationDependent() && 5759 !Step->containsUnexpandedParameterPack()) { 5760 NewStep = PerformOpenMPImplicitIntegerConversion(Step->getExprLoc(), Step) 5761 .get(); 5762 if (NewStep) 5763 NewStep = VerifyIntegerConstantExpression(NewStep).get(); 5764 } 5765 NewSteps.push_back(NewStep); 5766 } 5767 auto *NewAttr = OMPDeclareSimdDeclAttr::CreateImplicit( 5768 Context, BS, SL.get(), const_cast<Expr **>(Uniforms.data()), 5769 Uniforms.size(), const_cast<Expr **>(Aligneds.data()), Aligneds.size(), 5770 const_cast<Expr **>(NewAligns.data()), NewAligns.size(), 5771 const_cast<Expr **>(Linears.data()), Linears.size(), 5772 const_cast<unsigned *>(LinModifiers.data()), LinModifiers.size(), 5773 NewSteps.data(), NewSteps.size(), SR); 5774 ADecl->addAttr(NewAttr); 5775 return DG; 5776 } 5777 5778 static void setPrototype(Sema &S, FunctionDecl *FD, FunctionDecl *FDWithProto, 5779 QualType NewType) { 5780 assert(NewType->isFunctionProtoType() && 5781 "Expected function type with prototype."); 5782 assert(FD->getType()->isFunctionNoProtoType() && 5783 "Expected function with type with no prototype."); 5784 assert(FDWithProto->getType()->isFunctionProtoType() && 5785 "Expected function with prototype."); 5786 // Synthesize parameters with the same types. 5787 FD->setType(NewType); 5788 SmallVector<ParmVarDecl *, 16> Params; 5789 for (const ParmVarDecl *P : FDWithProto->parameters()) { 5790 auto *Param = ParmVarDecl::Create(S.getASTContext(), FD, SourceLocation(), 5791 SourceLocation(), nullptr, P->getType(), 5792 /*TInfo=*/nullptr, SC_None, nullptr); 5793 Param->setScopeInfo(0, Params.size()); 5794 Param->setImplicit(); 5795 Params.push_back(Param); 5796 } 5797 5798 FD->setParams(Params); 5799 } 5800 5801 Sema::OMPDeclareVariantScope::OMPDeclareVariantScope(OMPTraitInfo &TI) 5802 : TI(&TI), NameSuffix(TI.getMangledName()) {} 5803 5804 FunctionDecl * 5805 Sema::ActOnStartOfFunctionDefinitionInOpenMPDeclareVariantScope(Scope *S, 5806 Declarator &D) { 5807 IdentifierInfo *BaseII = D.getIdentifier(); 5808 LookupResult Lookup(*this, DeclarationName(BaseII), D.getIdentifierLoc(), 5809 LookupOrdinaryName); 5810 LookupParsedName(Lookup, S, &D.getCXXScopeSpec()); 5811 5812 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); 5813 QualType FType = TInfo->getType(); 5814 5815 bool IsConstexpr = D.getDeclSpec().getConstexprSpecifier() == CSK_constexpr; 5816 bool IsConsteval = D.getDeclSpec().getConstexprSpecifier() == CSK_consteval; 5817 5818 FunctionDecl *BaseFD = nullptr; 5819 for (auto *Candidate : Lookup) { 5820 auto *UDecl = dyn_cast<FunctionDecl>(Candidate->getUnderlyingDecl()); 5821 if (!UDecl) 5822 continue; 5823 5824 // Don't specialize constexpr/consteval functions with 5825 // non-constexpr/consteval functions. 5826 if (UDecl->isConstexpr() && !IsConstexpr) 5827 continue; 5828 if (UDecl->isConsteval() && !IsConsteval) 5829 continue; 5830 5831 QualType NewType = Context.mergeFunctionTypes( 5832 FType, UDecl->getType(), /* OfBlockPointer */ false, 5833 /* Unqualified */ false, /* AllowCXX */ true); 5834 if (NewType.isNull()) 5835 continue; 5836 5837 // Found a base! 5838 BaseFD = UDecl; 5839 break; 5840 } 5841 if (!BaseFD) { 5842 BaseFD = cast<FunctionDecl>(ActOnDeclarator(S, D)); 5843 BaseFD->setImplicit(true); 5844 } 5845 5846 OMPDeclareVariantScope &DVScope = OMPDeclareVariantScopes.back(); 5847 std::string MangledName; 5848 MangledName += D.getIdentifier()->getName(); 5849 MangledName += getOpenMPVariantManglingSeparatorStr(); 5850 MangledName += DVScope.NameSuffix; 5851 IdentifierInfo &VariantII = Context.Idents.get(MangledName); 5852 5853 VariantII.setMangledOpenMPVariantName(true); 5854 D.SetIdentifier(&VariantII, D.getBeginLoc()); 5855 return BaseFD; 5856 } 5857 5858 void Sema::ActOnFinishedFunctionDefinitionInOpenMPDeclareVariantScope( 5859 FunctionDecl *FD, FunctionDecl *BaseFD) { 5860 // Do not mark function as is used to prevent its emission if this is the 5861 // only place where it is used. 5862 EnterExpressionEvaluationContext Unevaluated( 5863 *this, Sema::ExpressionEvaluationContext::Unevaluated); 5864 5865 Expr *VariantFuncRef = DeclRefExpr::Create( 5866 Context, NestedNameSpecifierLoc(), SourceLocation(), FD, 5867 /* RefersToEnclosingVariableOrCapture */ false, 5868 /* NameLoc */ FD->getLocation(), FD->getType(), ExprValueKind::VK_RValue); 5869 5870 OMPDeclareVariantScope &DVScope = OMPDeclareVariantScopes.back(); 5871 auto *OMPDeclareVariantA = OMPDeclareVariantAttr::CreateImplicit( 5872 Context, VariantFuncRef, DVScope.TI); 5873 BaseFD->addAttr(OMPDeclareVariantA); 5874 } 5875 5876 ExprResult Sema::ActOnOpenMPCall(ExprResult Call, Scope *Scope, 5877 SourceLocation LParenLoc, 5878 MultiExprArg ArgExprs, 5879 SourceLocation RParenLoc, Expr *ExecConfig) { 5880 // The common case is a regular call we do not want to specialize at all. Try 5881 // to make that case fast by bailing early. 5882 CallExpr *CE = dyn_cast<CallExpr>(Call.get()); 5883 if (!CE) 5884 return Call; 5885 5886 FunctionDecl *CalleeFnDecl = CE->getDirectCallee(); 5887 if (!CalleeFnDecl) 5888 return Call; 5889 5890 if (!CalleeFnDecl->hasAttr<OMPDeclareVariantAttr>()) 5891 return Call; 5892 5893 ASTContext &Context = getASTContext(); 5894 OMPContext OMPCtx(getLangOpts().OpenMPIsDevice, 5895 Context.getTargetInfo().getTriple()); 5896 5897 SmallVector<Expr *, 4> Exprs; 5898 SmallVector<VariantMatchInfo, 4> VMIs; 5899 while (CalleeFnDecl) { 5900 for (OMPDeclareVariantAttr *A : 5901 CalleeFnDecl->specific_attrs<OMPDeclareVariantAttr>()) { 5902 Expr *VariantRef = A->getVariantFuncRef(); 5903 5904 VariantMatchInfo VMI; 5905 OMPTraitInfo &TI = A->getTraitInfo(); 5906 TI.getAsVariantMatchInfo(Context, VMI); 5907 if (!isVariantApplicableInContext(VMI, OMPCtx, /* DeviceSetOnly */ false)) 5908 continue; 5909 5910 VMIs.push_back(VMI); 5911 Exprs.push_back(VariantRef); 5912 } 5913 5914 CalleeFnDecl = CalleeFnDecl->getPreviousDecl(); 5915 } 5916 5917 ExprResult NewCall; 5918 do { 5919 int BestIdx = getBestVariantMatchForContext(VMIs, OMPCtx); 5920 if (BestIdx < 0) 5921 return Call; 5922 Expr *BestExpr = cast<DeclRefExpr>(Exprs[BestIdx]); 5923 Decl *BestDecl = cast<DeclRefExpr>(BestExpr)->getDecl(); 5924 5925 { 5926 // Try to build a (member) call expression for the current best applicable 5927 // variant expression. We allow this to fail in which case we continue 5928 // with the next best variant expression. The fail case is part of the 5929 // implementation defined behavior in the OpenMP standard when it talks 5930 // about what differences in the function prototypes: "Any differences 5931 // that the specific OpenMP context requires in the prototype of the 5932 // variant from the base function prototype are implementation defined." 5933 // This wording is there to allow the specialized variant to have a 5934 // different type than the base function. This is intended and OK but if 5935 // we cannot create a call the difference is not in the "implementation 5936 // defined range" we allow. 5937 Sema::TentativeAnalysisScope Trap(*this); 5938 5939 if (auto *SpecializedMethod = dyn_cast<CXXMethodDecl>(BestDecl)) { 5940 auto *MemberCall = dyn_cast<CXXMemberCallExpr>(CE); 5941 BestExpr = MemberExpr::CreateImplicit( 5942 Context, MemberCall->getImplicitObjectArgument(), 5943 /* IsArrow */ false, SpecializedMethod, Context.BoundMemberTy, 5944 MemberCall->getValueKind(), MemberCall->getObjectKind()); 5945 } 5946 NewCall = BuildCallExpr(Scope, BestExpr, LParenLoc, ArgExprs, RParenLoc, 5947 ExecConfig); 5948 if (NewCall.isUsable()) 5949 break; 5950 } 5951 5952 VMIs.erase(VMIs.begin() + BestIdx); 5953 Exprs.erase(Exprs.begin() + BestIdx); 5954 } while (!VMIs.empty()); 5955 5956 if (!NewCall.isUsable()) 5957 return Call; 5958 return PseudoObjectExpr::Create(Context, CE, {NewCall.get()}, 0); 5959 } 5960 5961 Optional<std::pair<FunctionDecl *, Expr *>> 5962 Sema::checkOpenMPDeclareVariantFunction(Sema::DeclGroupPtrTy DG, 5963 Expr *VariantRef, OMPTraitInfo &TI, 5964 SourceRange SR) { 5965 if (!DG || DG.get().isNull()) 5966 return None; 5967 5968 const int VariantId = 1; 5969 // Must be applied only to single decl. 5970 if (!DG.get().isSingleDecl()) { 5971 Diag(SR.getBegin(), diag::err_omp_single_decl_in_declare_simd_variant) 5972 << VariantId << SR; 5973 return None; 5974 } 5975 Decl *ADecl = DG.get().getSingleDecl(); 5976 if (auto *FTD = dyn_cast<FunctionTemplateDecl>(ADecl)) 5977 ADecl = FTD->getTemplatedDecl(); 5978 5979 // Decl must be a function. 5980 auto *FD = dyn_cast<FunctionDecl>(ADecl); 5981 if (!FD) { 5982 Diag(ADecl->getLocation(), diag::err_omp_function_expected) 5983 << VariantId << SR; 5984 return None; 5985 } 5986 5987 auto &&HasMultiVersionAttributes = [](const FunctionDecl *FD) { 5988 return FD->hasAttrs() && 5989 (FD->hasAttr<CPUDispatchAttr>() || FD->hasAttr<CPUSpecificAttr>() || 5990 FD->hasAttr<TargetAttr>()); 5991 }; 5992 // OpenMP is not compatible with CPU-specific attributes. 5993 if (HasMultiVersionAttributes(FD)) { 5994 Diag(FD->getLocation(), diag::err_omp_declare_variant_incompat_attributes) 5995 << SR; 5996 return None; 5997 } 5998 5999 // Allow #pragma omp declare variant only if the function is not used. 6000 if (FD->isUsed(false)) 6001 Diag(SR.getBegin(), diag::warn_omp_declare_variant_after_used) 6002 << FD->getLocation(); 6003 6004 // Check if the function was emitted already. 6005 const FunctionDecl *Definition; 6006 if (!FD->isThisDeclarationADefinition() && FD->isDefined(Definition) && 6007 (LangOpts.EmitAllDecls || Context.DeclMustBeEmitted(Definition))) 6008 Diag(SR.getBegin(), diag::warn_omp_declare_variant_after_emitted) 6009 << FD->getLocation(); 6010 6011 // The VariantRef must point to function. 6012 if (!VariantRef) { 6013 Diag(SR.getBegin(), diag::err_omp_function_expected) << VariantId; 6014 return None; 6015 } 6016 6017 auto ShouldDelayChecks = [](Expr *&E, bool) { 6018 return E && (E->isTypeDependent() || E->isValueDependent() || 6019 E->containsUnexpandedParameterPack() || 6020 E->isInstantiationDependent()); 6021 }; 6022 // Do not check templates, wait until instantiation. 6023 if (FD->isDependentContext() || ShouldDelayChecks(VariantRef, false) || 6024 TI.anyScoreOrCondition(ShouldDelayChecks)) 6025 return std::make_pair(FD, VariantRef); 6026 6027 // Deal with non-constant score and user condition expressions. 6028 auto HandleNonConstantScoresAndConditions = [this](Expr *&E, 6029 bool IsScore) -> bool { 6030 if (!E || E->isIntegerConstantExpr(Context)) 6031 return false; 6032 6033 if (IsScore) { 6034 // We warn on non-constant scores and pretend they were not present. 6035 Diag(E->getExprLoc(), diag::warn_omp_declare_variant_score_not_constant) 6036 << E; 6037 E = nullptr; 6038 } else { 6039 // We could replace a non-constant user condition with "false" but we 6040 // will soon need to handle these anyway for the dynamic version of 6041 // OpenMP context selectors. 6042 Diag(E->getExprLoc(), 6043 diag::err_omp_declare_variant_user_condition_not_constant) 6044 << E; 6045 } 6046 return true; 6047 }; 6048 if (TI.anyScoreOrCondition(HandleNonConstantScoresAndConditions)) 6049 return None; 6050 6051 // Convert VariantRef expression to the type of the original function to 6052 // resolve possible conflicts. 6053 ExprResult VariantRefCast; 6054 if (LangOpts.CPlusPlus) { 6055 QualType FnPtrType; 6056 auto *Method = dyn_cast<CXXMethodDecl>(FD); 6057 if (Method && !Method->isStatic()) { 6058 const Type *ClassType = 6059 Context.getTypeDeclType(Method->getParent()).getTypePtr(); 6060 FnPtrType = Context.getMemberPointerType(FD->getType(), ClassType); 6061 ExprResult ER; 6062 { 6063 // Build adrr_of unary op to correctly handle type checks for member 6064 // functions. 6065 Sema::TentativeAnalysisScope Trap(*this); 6066 ER = CreateBuiltinUnaryOp(VariantRef->getBeginLoc(), UO_AddrOf, 6067 VariantRef); 6068 } 6069 if (!ER.isUsable()) { 6070 Diag(VariantRef->getExprLoc(), diag::err_omp_function_expected) 6071 << VariantId << VariantRef->getSourceRange(); 6072 return None; 6073 } 6074 VariantRef = ER.get(); 6075 } else { 6076 FnPtrType = Context.getPointerType(FD->getType()); 6077 } 6078 ImplicitConversionSequence ICS = 6079 TryImplicitConversion(VariantRef, FnPtrType.getUnqualifiedType(), 6080 /*SuppressUserConversions=*/false, 6081 AllowedExplicit::None, 6082 /*InOverloadResolution=*/false, 6083 /*CStyle=*/false, 6084 /*AllowObjCWritebackConversion=*/false); 6085 if (ICS.isFailure()) { 6086 Diag(VariantRef->getExprLoc(), 6087 diag::err_omp_declare_variant_incompat_types) 6088 << VariantRef->getType() 6089 << ((Method && !Method->isStatic()) ? FnPtrType : FD->getType()) 6090 << VariantRef->getSourceRange(); 6091 return None; 6092 } 6093 VariantRefCast = PerformImplicitConversion( 6094 VariantRef, FnPtrType.getUnqualifiedType(), AA_Converting); 6095 if (!VariantRefCast.isUsable()) 6096 return None; 6097 // Drop previously built artificial addr_of unary op for member functions. 6098 if (Method && !Method->isStatic()) { 6099 Expr *PossibleAddrOfVariantRef = VariantRefCast.get(); 6100 if (auto *UO = dyn_cast<UnaryOperator>( 6101 PossibleAddrOfVariantRef->IgnoreImplicit())) 6102 VariantRefCast = UO->getSubExpr(); 6103 } 6104 } else { 6105 VariantRefCast = VariantRef; 6106 } 6107 6108 ExprResult ER = CheckPlaceholderExpr(VariantRefCast.get()); 6109 if (!ER.isUsable() || 6110 !ER.get()->IgnoreParenImpCasts()->getType()->isFunctionType()) { 6111 Diag(VariantRef->getExprLoc(), diag::err_omp_function_expected) 6112 << VariantId << VariantRef->getSourceRange(); 6113 return None; 6114 } 6115 6116 // The VariantRef must point to function. 6117 auto *DRE = dyn_cast<DeclRefExpr>(ER.get()->IgnoreParenImpCasts()); 6118 if (!DRE) { 6119 Diag(VariantRef->getExprLoc(), diag::err_omp_function_expected) 6120 << VariantId << VariantRef->getSourceRange(); 6121 return None; 6122 } 6123 auto *NewFD = dyn_cast_or_null<FunctionDecl>(DRE->getDecl()); 6124 if (!NewFD) { 6125 Diag(VariantRef->getExprLoc(), diag::err_omp_function_expected) 6126 << VariantId << VariantRef->getSourceRange(); 6127 return None; 6128 } 6129 6130 // Check if function types are compatible in C. 6131 if (!LangOpts.CPlusPlus) { 6132 QualType NewType = 6133 Context.mergeFunctionTypes(FD->getType(), NewFD->getType()); 6134 if (NewType.isNull()) { 6135 Diag(VariantRef->getExprLoc(), 6136 diag::err_omp_declare_variant_incompat_types) 6137 << NewFD->getType() << FD->getType() << VariantRef->getSourceRange(); 6138 return None; 6139 } 6140 if (NewType->isFunctionProtoType()) { 6141 if (FD->getType()->isFunctionNoProtoType()) 6142 setPrototype(*this, FD, NewFD, NewType); 6143 else if (NewFD->getType()->isFunctionNoProtoType()) 6144 setPrototype(*this, NewFD, FD, NewType); 6145 } 6146 } 6147 6148 // Check if variant function is not marked with declare variant directive. 6149 if (NewFD->hasAttrs() && NewFD->hasAttr<OMPDeclareVariantAttr>()) { 6150 Diag(VariantRef->getExprLoc(), 6151 diag::warn_omp_declare_variant_marked_as_declare_variant) 6152 << VariantRef->getSourceRange(); 6153 SourceRange SR = 6154 NewFD->specific_attr_begin<OMPDeclareVariantAttr>()->getRange(); 6155 Diag(SR.getBegin(), diag::note_omp_marked_declare_variant_here) << SR; 6156 return None; 6157 } 6158 6159 enum DoesntSupport { 6160 VirtFuncs = 1, 6161 Constructors = 3, 6162 Destructors = 4, 6163 DeletedFuncs = 5, 6164 DefaultedFuncs = 6, 6165 ConstexprFuncs = 7, 6166 ConstevalFuncs = 8, 6167 }; 6168 if (const auto *CXXFD = dyn_cast<CXXMethodDecl>(FD)) { 6169 if (CXXFD->isVirtual()) { 6170 Diag(FD->getLocation(), diag::err_omp_declare_variant_doesnt_support) 6171 << VirtFuncs; 6172 return None; 6173 } 6174 6175 if (isa<CXXConstructorDecl>(FD)) { 6176 Diag(FD->getLocation(), diag::err_omp_declare_variant_doesnt_support) 6177 << Constructors; 6178 return None; 6179 } 6180 6181 if (isa<CXXDestructorDecl>(FD)) { 6182 Diag(FD->getLocation(), diag::err_omp_declare_variant_doesnt_support) 6183 << Destructors; 6184 return None; 6185 } 6186 } 6187 6188 if (FD->isDeleted()) { 6189 Diag(FD->getLocation(), diag::err_omp_declare_variant_doesnt_support) 6190 << DeletedFuncs; 6191 return None; 6192 } 6193 6194 if (FD->isDefaulted()) { 6195 Diag(FD->getLocation(), diag::err_omp_declare_variant_doesnt_support) 6196 << DefaultedFuncs; 6197 return None; 6198 } 6199 6200 if (FD->isConstexpr()) { 6201 Diag(FD->getLocation(), diag::err_omp_declare_variant_doesnt_support) 6202 << (NewFD->isConsteval() ? ConstevalFuncs : ConstexprFuncs); 6203 return None; 6204 } 6205 6206 // Check general compatibility. 6207 if (areMultiversionVariantFunctionsCompatible( 6208 FD, NewFD, PartialDiagnostic::NullDiagnostic(), 6209 PartialDiagnosticAt(SourceLocation(), 6210 PartialDiagnostic::NullDiagnostic()), 6211 PartialDiagnosticAt( 6212 VariantRef->getExprLoc(), 6213 PDiag(diag::err_omp_declare_variant_doesnt_support)), 6214 PartialDiagnosticAt(VariantRef->getExprLoc(), 6215 PDiag(diag::err_omp_declare_variant_diff) 6216 << FD->getLocation()), 6217 /*TemplatesSupported=*/true, /*ConstexprSupported=*/false, 6218 /*CLinkageMayDiffer=*/true)) 6219 return None; 6220 return std::make_pair(FD, cast<Expr>(DRE)); 6221 } 6222 6223 void Sema::ActOnOpenMPDeclareVariantDirective(FunctionDecl *FD, 6224 Expr *VariantRef, 6225 OMPTraitInfo &TI, 6226 SourceRange SR) { 6227 auto *NewAttr = 6228 OMPDeclareVariantAttr::CreateImplicit(Context, VariantRef, &TI, SR); 6229 FD->addAttr(NewAttr); 6230 } 6231 6232 StmtResult Sema::ActOnOpenMPParallelDirective(ArrayRef<OMPClause *> Clauses, 6233 Stmt *AStmt, 6234 SourceLocation StartLoc, 6235 SourceLocation EndLoc) { 6236 if (!AStmt) 6237 return StmtError(); 6238 6239 auto *CS = cast<CapturedStmt>(AStmt); 6240 // 1.2.2 OpenMP Language Terminology 6241 // Structured block - An executable statement with a single entry at the 6242 // top and a single exit at the bottom. 6243 // The point of exit cannot be a branch out of the structured block. 6244 // longjmp() and throw() must not violate the entry/exit criteria. 6245 CS->getCapturedDecl()->setNothrow(); 6246 6247 setFunctionHasBranchProtectedScope(); 6248 6249 return OMPParallelDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt, 6250 DSAStack->getTaskgroupReductionRef(), 6251 DSAStack->isCancelRegion()); 6252 } 6253 6254 namespace { 6255 /// Iteration space of a single for loop. 6256 struct LoopIterationSpace final { 6257 /// True if the condition operator is the strict compare operator (<, > or 6258 /// !=). 6259 bool IsStrictCompare = false; 6260 /// Condition of the loop. 6261 Expr *PreCond = nullptr; 6262 /// This expression calculates the number of iterations in the loop. 6263 /// It is always possible to calculate it before starting the loop. 6264 Expr *NumIterations = nullptr; 6265 /// The loop counter variable. 6266 Expr *CounterVar = nullptr; 6267 /// Private loop counter variable. 6268 Expr *PrivateCounterVar = nullptr; 6269 /// This is initializer for the initial value of #CounterVar. 6270 Expr *CounterInit = nullptr; 6271 /// This is step for the #CounterVar used to generate its update: 6272 /// #CounterVar = #CounterInit + #CounterStep * CurrentIteration. 6273 Expr *CounterStep = nullptr; 6274 /// Should step be subtracted? 6275 bool Subtract = false; 6276 /// Source range of the loop init. 6277 SourceRange InitSrcRange; 6278 /// Source range of the loop condition. 6279 SourceRange CondSrcRange; 6280 /// Source range of the loop increment. 6281 SourceRange IncSrcRange; 6282 /// Minimum value that can have the loop control variable. Used to support 6283 /// non-rectangular loops. Applied only for LCV with the non-iterator types, 6284 /// since only such variables can be used in non-loop invariant expressions. 6285 Expr *MinValue = nullptr; 6286 /// Maximum value that can have the loop control variable. Used to support 6287 /// non-rectangular loops. Applied only for LCV with the non-iterator type, 6288 /// since only such variables can be used in non-loop invariant expressions. 6289 Expr *MaxValue = nullptr; 6290 /// true, if the lower bound depends on the outer loop control var. 6291 bool IsNonRectangularLB = false; 6292 /// true, if the upper bound depends on the outer loop control var. 6293 bool IsNonRectangularUB = false; 6294 /// Index of the loop this loop depends on and forms non-rectangular loop 6295 /// nest. 6296 unsigned LoopDependentIdx = 0; 6297 /// Final condition for the non-rectangular loop nest support. It is used to 6298 /// check that the number of iterations for this particular counter must be 6299 /// finished. 6300 Expr *FinalCondition = nullptr; 6301 }; 6302 6303 /// Helper class for checking canonical form of the OpenMP loops and 6304 /// extracting iteration space of each loop in the loop nest, that will be used 6305 /// for IR generation. 6306 class OpenMPIterationSpaceChecker { 6307 /// Reference to Sema. 6308 Sema &SemaRef; 6309 /// Data-sharing stack. 6310 DSAStackTy &Stack; 6311 /// A location for diagnostics (when there is no some better location). 6312 SourceLocation DefaultLoc; 6313 /// A location for diagnostics (when increment is not compatible). 6314 SourceLocation ConditionLoc; 6315 /// A source location for referring to loop init later. 6316 SourceRange InitSrcRange; 6317 /// A source location for referring to condition later. 6318 SourceRange ConditionSrcRange; 6319 /// A source location for referring to increment later. 6320 SourceRange IncrementSrcRange; 6321 /// Loop variable. 6322 ValueDecl *LCDecl = nullptr; 6323 /// Reference to loop variable. 6324 Expr *LCRef = nullptr; 6325 /// Lower bound (initializer for the var). 6326 Expr *LB = nullptr; 6327 /// Upper bound. 6328 Expr *UB = nullptr; 6329 /// Loop step (increment). 6330 Expr *Step = nullptr; 6331 /// This flag is true when condition is one of: 6332 /// Var < UB 6333 /// Var <= UB 6334 /// UB > Var 6335 /// UB >= Var 6336 /// This will have no value when the condition is != 6337 llvm::Optional<bool> TestIsLessOp; 6338 /// This flag is true when condition is strict ( < or > ). 6339 bool TestIsStrictOp = false; 6340 /// This flag is true when step is subtracted on each iteration. 6341 bool SubtractStep = false; 6342 /// The outer loop counter this loop depends on (if any). 6343 const ValueDecl *DepDecl = nullptr; 6344 /// Contains number of loop (starts from 1) on which loop counter init 6345 /// expression of this loop depends on. 6346 Optional<unsigned> InitDependOnLC; 6347 /// Contains number of loop (starts from 1) on which loop counter condition 6348 /// expression of this loop depends on. 6349 Optional<unsigned> CondDependOnLC; 6350 /// Checks if the provide statement depends on the loop counter. 6351 Optional<unsigned> doesDependOnLoopCounter(const Stmt *S, bool IsInitializer); 6352 /// Original condition required for checking of the exit condition for 6353 /// non-rectangular loop. 6354 Expr *Condition = nullptr; 6355 6356 public: 6357 OpenMPIterationSpaceChecker(Sema &SemaRef, DSAStackTy &Stack, 6358 SourceLocation DefaultLoc) 6359 : SemaRef(SemaRef), Stack(Stack), DefaultLoc(DefaultLoc), 6360 ConditionLoc(DefaultLoc) {} 6361 /// Check init-expr for canonical loop form and save loop counter 6362 /// variable - #Var and its initialization value - #LB. 6363 bool checkAndSetInit(Stmt *S, bool EmitDiags = true); 6364 /// Check test-expr for canonical form, save upper-bound (#UB), flags 6365 /// for less/greater and for strict/non-strict comparison. 6366 bool checkAndSetCond(Expr *S); 6367 /// Check incr-expr for canonical loop form and return true if it 6368 /// does not conform, otherwise save loop step (#Step). 6369 bool checkAndSetInc(Expr *S); 6370 /// Return the loop counter variable. 6371 ValueDecl *getLoopDecl() const { return LCDecl; } 6372 /// Return the reference expression to loop counter variable. 6373 Expr *getLoopDeclRefExpr() const { return LCRef; } 6374 /// Source range of the loop init. 6375 SourceRange getInitSrcRange() const { return InitSrcRange; } 6376 /// Source range of the loop condition. 6377 SourceRange getConditionSrcRange() const { return ConditionSrcRange; } 6378 /// Source range of the loop increment. 6379 SourceRange getIncrementSrcRange() const { return IncrementSrcRange; } 6380 /// True if the step should be subtracted. 6381 bool shouldSubtractStep() const { return SubtractStep; } 6382 /// True, if the compare operator is strict (<, > or !=). 6383 bool isStrictTestOp() const { return TestIsStrictOp; } 6384 /// Build the expression to calculate the number of iterations. 6385 Expr *buildNumIterations( 6386 Scope *S, ArrayRef<LoopIterationSpace> ResultIterSpaces, bool LimitedType, 6387 llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) const; 6388 /// Build the precondition expression for the loops. 6389 Expr * 6390 buildPreCond(Scope *S, Expr *Cond, 6391 llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) const; 6392 /// Build reference expression to the counter be used for codegen. 6393 DeclRefExpr * 6394 buildCounterVar(llvm::MapVector<const Expr *, DeclRefExpr *> &Captures, 6395 DSAStackTy &DSA) const; 6396 /// Build reference expression to the private counter be used for 6397 /// codegen. 6398 Expr *buildPrivateCounterVar() const; 6399 /// Build initialization of the counter be used for codegen. 6400 Expr *buildCounterInit() const; 6401 /// Build step of the counter be used for codegen. 6402 Expr *buildCounterStep() const; 6403 /// Build loop data with counter value for depend clauses in ordered 6404 /// directives. 6405 Expr * 6406 buildOrderedLoopData(Scope *S, Expr *Counter, 6407 llvm::MapVector<const Expr *, DeclRefExpr *> &Captures, 6408 SourceLocation Loc, Expr *Inc = nullptr, 6409 OverloadedOperatorKind OOK = OO_Amp); 6410 /// Builds the minimum value for the loop counter. 6411 std::pair<Expr *, Expr *> buildMinMaxValues( 6412 Scope *S, llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) const; 6413 /// Builds final condition for the non-rectangular loops. 6414 Expr *buildFinalCondition(Scope *S) const; 6415 /// Return true if any expression is dependent. 6416 bool dependent() const; 6417 /// Returns true if the initializer forms non-rectangular loop. 6418 bool doesInitDependOnLC() const { return InitDependOnLC.hasValue(); } 6419 /// Returns true if the condition forms non-rectangular loop. 6420 bool doesCondDependOnLC() const { return CondDependOnLC.hasValue(); } 6421 /// Returns index of the loop we depend on (starting from 1), or 0 otherwise. 6422 unsigned getLoopDependentIdx() const { 6423 return InitDependOnLC.getValueOr(CondDependOnLC.getValueOr(0)); 6424 } 6425 6426 private: 6427 /// Check the right-hand side of an assignment in the increment 6428 /// expression. 6429 bool checkAndSetIncRHS(Expr *RHS); 6430 /// Helper to set loop counter variable and its initializer. 6431 bool setLCDeclAndLB(ValueDecl *NewLCDecl, Expr *NewDeclRefExpr, Expr *NewLB, 6432 bool EmitDiags); 6433 /// Helper to set upper bound. 6434 bool setUB(Expr *NewUB, llvm::Optional<bool> LessOp, bool StrictOp, 6435 SourceRange SR, SourceLocation SL); 6436 /// Helper to set loop increment. 6437 bool setStep(Expr *NewStep, bool Subtract); 6438 }; 6439 6440 bool OpenMPIterationSpaceChecker::dependent() const { 6441 if (!LCDecl) { 6442 assert(!LB && !UB && !Step); 6443 return false; 6444 } 6445 return LCDecl->getType()->isDependentType() || 6446 (LB && LB->isValueDependent()) || (UB && UB->isValueDependent()) || 6447 (Step && Step->isValueDependent()); 6448 } 6449 6450 bool OpenMPIterationSpaceChecker::setLCDeclAndLB(ValueDecl *NewLCDecl, 6451 Expr *NewLCRefExpr, 6452 Expr *NewLB, bool EmitDiags) { 6453 // State consistency checking to ensure correct usage. 6454 assert(LCDecl == nullptr && LB == nullptr && LCRef == nullptr && 6455 UB == nullptr && Step == nullptr && !TestIsLessOp && !TestIsStrictOp); 6456 if (!NewLCDecl || !NewLB) 6457 return true; 6458 LCDecl = getCanonicalDecl(NewLCDecl); 6459 LCRef = NewLCRefExpr; 6460 if (auto *CE = dyn_cast_or_null<CXXConstructExpr>(NewLB)) 6461 if (const CXXConstructorDecl *Ctor = CE->getConstructor()) 6462 if ((Ctor->isCopyOrMoveConstructor() || 6463 Ctor->isConvertingConstructor(/*AllowExplicit=*/false)) && 6464 CE->getNumArgs() > 0 && CE->getArg(0) != nullptr) 6465 NewLB = CE->getArg(0)->IgnoreParenImpCasts(); 6466 LB = NewLB; 6467 if (EmitDiags) 6468 InitDependOnLC = doesDependOnLoopCounter(LB, /*IsInitializer=*/true); 6469 return false; 6470 } 6471 6472 bool OpenMPIterationSpaceChecker::setUB(Expr *NewUB, 6473 llvm::Optional<bool> LessOp, 6474 bool StrictOp, SourceRange SR, 6475 SourceLocation SL) { 6476 // State consistency checking to ensure correct usage. 6477 assert(LCDecl != nullptr && LB != nullptr && UB == nullptr && 6478 Step == nullptr && !TestIsLessOp && !TestIsStrictOp); 6479 if (!NewUB) 6480 return true; 6481 UB = NewUB; 6482 if (LessOp) 6483 TestIsLessOp = LessOp; 6484 TestIsStrictOp = StrictOp; 6485 ConditionSrcRange = SR; 6486 ConditionLoc = SL; 6487 CondDependOnLC = doesDependOnLoopCounter(UB, /*IsInitializer=*/false); 6488 return false; 6489 } 6490 6491 bool OpenMPIterationSpaceChecker::setStep(Expr *NewStep, bool Subtract) { 6492 // State consistency checking to ensure correct usage. 6493 assert(LCDecl != nullptr && LB != nullptr && Step == nullptr); 6494 if (!NewStep) 6495 return true; 6496 if (!NewStep->isValueDependent()) { 6497 // Check that the step is integer expression. 6498 SourceLocation StepLoc = NewStep->getBeginLoc(); 6499 ExprResult Val = SemaRef.PerformOpenMPImplicitIntegerConversion( 6500 StepLoc, getExprAsWritten(NewStep)); 6501 if (Val.isInvalid()) 6502 return true; 6503 NewStep = Val.get(); 6504 6505 // OpenMP [2.6, Canonical Loop Form, Restrictions] 6506 // If test-expr is of form var relational-op b and relational-op is < or 6507 // <= then incr-expr must cause var to increase on each iteration of the 6508 // loop. If test-expr is of form var relational-op b and relational-op is 6509 // > or >= then incr-expr must cause var to decrease on each iteration of 6510 // the loop. 6511 // If test-expr is of form b relational-op var and relational-op is < or 6512 // <= then incr-expr must cause var to decrease on each iteration of the 6513 // loop. If test-expr is of form b relational-op var and relational-op is 6514 // > or >= then incr-expr must cause var to increase on each iteration of 6515 // the loop. 6516 Optional<llvm::APSInt> Result = 6517 NewStep->getIntegerConstantExpr(SemaRef.Context); 6518 bool IsUnsigned = !NewStep->getType()->hasSignedIntegerRepresentation(); 6519 bool IsConstNeg = 6520 Result && Result->isSigned() && (Subtract != Result->isNegative()); 6521 bool IsConstPos = 6522 Result && Result->isSigned() && (Subtract == Result->isNegative()); 6523 bool IsConstZero = Result && !Result->getBoolValue(); 6524 6525 // != with increment is treated as <; != with decrement is treated as > 6526 if (!TestIsLessOp.hasValue()) 6527 TestIsLessOp = IsConstPos || (IsUnsigned && !Subtract); 6528 if (UB && (IsConstZero || 6529 (TestIsLessOp.getValue() ? 6530 (IsConstNeg || (IsUnsigned && Subtract)) : 6531 (IsConstPos || (IsUnsigned && !Subtract))))) { 6532 SemaRef.Diag(NewStep->getExprLoc(), 6533 diag::err_omp_loop_incr_not_compatible) 6534 << LCDecl << TestIsLessOp.getValue() << NewStep->getSourceRange(); 6535 SemaRef.Diag(ConditionLoc, 6536 diag::note_omp_loop_cond_requres_compatible_incr) 6537 << TestIsLessOp.getValue() << ConditionSrcRange; 6538 return true; 6539 } 6540 if (TestIsLessOp.getValue() == Subtract) { 6541 NewStep = 6542 SemaRef.CreateBuiltinUnaryOp(NewStep->getExprLoc(), UO_Minus, NewStep) 6543 .get(); 6544 Subtract = !Subtract; 6545 } 6546 } 6547 6548 Step = NewStep; 6549 SubtractStep = Subtract; 6550 return false; 6551 } 6552 6553 namespace { 6554 /// Checker for the non-rectangular loops. Checks if the initializer or 6555 /// condition expression references loop counter variable. 6556 class LoopCounterRefChecker final 6557 : public ConstStmtVisitor<LoopCounterRefChecker, bool> { 6558 Sema &SemaRef; 6559 DSAStackTy &Stack; 6560 const ValueDecl *CurLCDecl = nullptr; 6561 const ValueDecl *DepDecl = nullptr; 6562 const ValueDecl *PrevDepDecl = nullptr; 6563 bool IsInitializer = true; 6564 unsigned BaseLoopId = 0; 6565 bool checkDecl(const Expr *E, const ValueDecl *VD) { 6566 if (getCanonicalDecl(VD) == getCanonicalDecl(CurLCDecl)) { 6567 SemaRef.Diag(E->getExprLoc(), diag::err_omp_stmt_depends_on_loop_counter) 6568 << (IsInitializer ? 0 : 1); 6569 return false; 6570 } 6571 const auto &&Data = Stack.isLoopControlVariable(VD); 6572 // OpenMP, 2.9.1 Canonical Loop Form, Restrictions. 6573 // The type of the loop iterator on which we depend may not have a random 6574 // access iterator type. 6575 if (Data.first && VD->getType()->isRecordType()) { 6576 SmallString<128> Name; 6577 llvm::raw_svector_ostream OS(Name); 6578 VD->getNameForDiagnostic(OS, SemaRef.getPrintingPolicy(), 6579 /*Qualified=*/true); 6580 SemaRef.Diag(E->getExprLoc(), 6581 diag::err_omp_wrong_dependency_iterator_type) 6582 << OS.str(); 6583 SemaRef.Diag(VD->getLocation(), diag::note_previous_decl) << VD; 6584 return false; 6585 } 6586 if (Data.first && 6587 (DepDecl || (PrevDepDecl && 6588 getCanonicalDecl(VD) != getCanonicalDecl(PrevDepDecl)))) { 6589 if (!DepDecl && PrevDepDecl) 6590 DepDecl = PrevDepDecl; 6591 SmallString<128> Name; 6592 llvm::raw_svector_ostream OS(Name); 6593 DepDecl->getNameForDiagnostic(OS, SemaRef.getPrintingPolicy(), 6594 /*Qualified=*/true); 6595 SemaRef.Diag(E->getExprLoc(), 6596 diag::err_omp_invariant_or_linear_dependency) 6597 << OS.str(); 6598 return false; 6599 } 6600 if (Data.first) { 6601 DepDecl = VD; 6602 BaseLoopId = Data.first; 6603 } 6604 return Data.first; 6605 } 6606 6607 public: 6608 bool VisitDeclRefExpr(const DeclRefExpr *E) { 6609 const ValueDecl *VD = E->getDecl(); 6610 if (isa<VarDecl>(VD)) 6611 return checkDecl(E, VD); 6612 return false; 6613 } 6614 bool VisitMemberExpr(const MemberExpr *E) { 6615 if (isa<CXXThisExpr>(E->getBase()->IgnoreParens())) { 6616 const ValueDecl *VD = E->getMemberDecl(); 6617 if (isa<VarDecl>(VD) || isa<FieldDecl>(VD)) 6618 return checkDecl(E, VD); 6619 } 6620 return false; 6621 } 6622 bool VisitStmt(const Stmt *S) { 6623 bool Res = false; 6624 for (const Stmt *Child : S->children()) 6625 Res = (Child && Visit(Child)) || Res; 6626 return Res; 6627 } 6628 explicit LoopCounterRefChecker(Sema &SemaRef, DSAStackTy &Stack, 6629 const ValueDecl *CurLCDecl, bool IsInitializer, 6630 const ValueDecl *PrevDepDecl = nullptr) 6631 : SemaRef(SemaRef), Stack(Stack), CurLCDecl(CurLCDecl), 6632 PrevDepDecl(PrevDepDecl), IsInitializer(IsInitializer) {} 6633 unsigned getBaseLoopId() const { 6634 assert(CurLCDecl && "Expected loop dependency."); 6635 return BaseLoopId; 6636 } 6637 const ValueDecl *getDepDecl() const { 6638 assert(CurLCDecl && "Expected loop dependency."); 6639 return DepDecl; 6640 } 6641 }; 6642 } // namespace 6643 6644 Optional<unsigned> 6645 OpenMPIterationSpaceChecker::doesDependOnLoopCounter(const Stmt *S, 6646 bool IsInitializer) { 6647 // Check for the non-rectangular loops. 6648 LoopCounterRefChecker LoopStmtChecker(SemaRef, Stack, LCDecl, IsInitializer, 6649 DepDecl); 6650 if (LoopStmtChecker.Visit(S)) { 6651 DepDecl = LoopStmtChecker.getDepDecl(); 6652 return LoopStmtChecker.getBaseLoopId(); 6653 } 6654 return llvm::None; 6655 } 6656 6657 bool OpenMPIterationSpaceChecker::checkAndSetInit(Stmt *S, bool EmitDiags) { 6658 // Check init-expr for canonical loop form and save loop counter 6659 // variable - #Var and its initialization value - #LB. 6660 // OpenMP [2.6] Canonical loop form. init-expr may be one of the following: 6661 // var = lb 6662 // integer-type var = lb 6663 // random-access-iterator-type var = lb 6664 // pointer-type var = lb 6665 // 6666 if (!S) { 6667 if (EmitDiags) { 6668 SemaRef.Diag(DefaultLoc, diag::err_omp_loop_not_canonical_init); 6669 } 6670 return true; 6671 } 6672 if (auto *ExprTemp = dyn_cast<ExprWithCleanups>(S)) 6673 if (!ExprTemp->cleanupsHaveSideEffects()) 6674 S = ExprTemp->getSubExpr(); 6675 6676 InitSrcRange = S->getSourceRange(); 6677 if (Expr *E = dyn_cast<Expr>(S)) 6678 S = E->IgnoreParens(); 6679 if (auto *BO = dyn_cast<BinaryOperator>(S)) { 6680 if (BO->getOpcode() == BO_Assign) { 6681 Expr *LHS = BO->getLHS()->IgnoreParens(); 6682 if (auto *DRE = dyn_cast<DeclRefExpr>(LHS)) { 6683 if (auto *CED = dyn_cast<OMPCapturedExprDecl>(DRE->getDecl())) 6684 if (auto *ME = dyn_cast<MemberExpr>(getExprAsWritten(CED->getInit()))) 6685 return setLCDeclAndLB(ME->getMemberDecl(), ME, BO->getRHS(), 6686 EmitDiags); 6687 return setLCDeclAndLB(DRE->getDecl(), DRE, BO->getRHS(), EmitDiags); 6688 } 6689 if (auto *ME = dyn_cast<MemberExpr>(LHS)) { 6690 if (ME->isArrow() && 6691 isa<CXXThisExpr>(ME->getBase()->IgnoreParenImpCasts())) 6692 return setLCDeclAndLB(ME->getMemberDecl(), ME, BO->getRHS(), 6693 EmitDiags); 6694 } 6695 } 6696 } else if (auto *DS = dyn_cast<DeclStmt>(S)) { 6697 if (DS->isSingleDecl()) { 6698 if (auto *Var = dyn_cast_or_null<VarDecl>(DS->getSingleDecl())) { 6699 if (Var->hasInit() && !Var->getType()->isReferenceType()) { 6700 // Accept non-canonical init form here but emit ext. warning. 6701 if (Var->getInitStyle() != VarDecl::CInit && EmitDiags) 6702 SemaRef.Diag(S->getBeginLoc(), 6703 diag::ext_omp_loop_not_canonical_init) 6704 << S->getSourceRange(); 6705 return setLCDeclAndLB( 6706 Var, 6707 buildDeclRefExpr(SemaRef, Var, 6708 Var->getType().getNonReferenceType(), 6709 DS->getBeginLoc()), 6710 Var->getInit(), EmitDiags); 6711 } 6712 } 6713 } 6714 } else if (auto *CE = dyn_cast<CXXOperatorCallExpr>(S)) { 6715 if (CE->getOperator() == OO_Equal) { 6716 Expr *LHS = CE->getArg(0); 6717 if (auto *DRE = dyn_cast<DeclRefExpr>(LHS)) { 6718 if (auto *CED = dyn_cast<OMPCapturedExprDecl>(DRE->getDecl())) 6719 if (auto *ME = dyn_cast<MemberExpr>(getExprAsWritten(CED->getInit()))) 6720 return setLCDeclAndLB(ME->getMemberDecl(), ME, BO->getRHS(), 6721 EmitDiags); 6722 return setLCDeclAndLB(DRE->getDecl(), DRE, CE->getArg(1), EmitDiags); 6723 } 6724 if (auto *ME = dyn_cast<MemberExpr>(LHS)) { 6725 if (ME->isArrow() && 6726 isa<CXXThisExpr>(ME->getBase()->IgnoreParenImpCasts())) 6727 return setLCDeclAndLB(ME->getMemberDecl(), ME, BO->getRHS(), 6728 EmitDiags); 6729 } 6730 } 6731 } 6732 6733 if (dependent() || SemaRef.CurContext->isDependentContext()) 6734 return false; 6735 if (EmitDiags) { 6736 SemaRef.Diag(S->getBeginLoc(), diag::err_omp_loop_not_canonical_init) 6737 << S->getSourceRange(); 6738 } 6739 return true; 6740 } 6741 6742 /// Ignore parenthesizes, implicit casts, copy constructor and return the 6743 /// variable (which may be the loop variable) if possible. 6744 static const ValueDecl *getInitLCDecl(const Expr *E) { 6745 if (!E) 6746 return nullptr; 6747 E = getExprAsWritten(E); 6748 if (const auto *CE = dyn_cast_or_null<CXXConstructExpr>(E)) 6749 if (const CXXConstructorDecl *Ctor = CE->getConstructor()) 6750 if ((Ctor->isCopyOrMoveConstructor() || 6751 Ctor->isConvertingConstructor(/*AllowExplicit=*/false)) && 6752 CE->getNumArgs() > 0 && CE->getArg(0) != nullptr) 6753 E = CE->getArg(0)->IgnoreParenImpCasts(); 6754 if (const auto *DRE = dyn_cast_or_null<DeclRefExpr>(E)) { 6755 if (const auto *VD = dyn_cast<VarDecl>(DRE->getDecl())) 6756 return getCanonicalDecl(VD); 6757 } 6758 if (const auto *ME = dyn_cast_or_null<MemberExpr>(E)) 6759 if (ME->isArrow() && isa<CXXThisExpr>(ME->getBase()->IgnoreParenImpCasts())) 6760 return getCanonicalDecl(ME->getMemberDecl()); 6761 return nullptr; 6762 } 6763 6764 bool OpenMPIterationSpaceChecker::checkAndSetCond(Expr *S) { 6765 // Check test-expr for canonical form, save upper-bound UB, flags for 6766 // less/greater and for strict/non-strict comparison. 6767 // OpenMP [2.9] Canonical loop form. Test-expr may be one of the following: 6768 // var relational-op b 6769 // b relational-op var 6770 // 6771 bool IneqCondIsCanonical = SemaRef.getLangOpts().OpenMP >= 50; 6772 if (!S) { 6773 SemaRef.Diag(DefaultLoc, diag::err_omp_loop_not_canonical_cond) 6774 << (IneqCondIsCanonical ? 1 : 0) << LCDecl; 6775 return true; 6776 } 6777 Condition = S; 6778 S = getExprAsWritten(S); 6779 SourceLocation CondLoc = S->getBeginLoc(); 6780 if (auto *BO = dyn_cast<BinaryOperator>(S)) { 6781 if (BO->isRelationalOp()) { 6782 if (getInitLCDecl(BO->getLHS()) == LCDecl) 6783 return setUB(BO->getRHS(), 6784 (BO->getOpcode() == BO_LT || BO->getOpcode() == BO_LE), 6785 (BO->getOpcode() == BO_LT || BO->getOpcode() == BO_GT), 6786 BO->getSourceRange(), BO->getOperatorLoc()); 6787 if (getInitLCDecl(BO->getRHS()) == LCDecl) 6788 return setUB(BO->getLHS(), 6789 (BO->getOpcode() == BO_GT || BO->getOpcode() == BO_GE), 6790 (BO->getOpcode() == BO_LT || BO->getOpcode() == BO_GT), 6791 BO->getSourceRange(), BO->getOperatorLoc()); 6792 } else if (IneqCondIsCanonical && BO->getOpcode() == BO_NE) 6793 return setUB( 6794 getInitLCDecl(BO->getLHS()) == LCDecl ? BO->getRHS() : BO->getLHS(), 6795 /*LessOp=*/llvm::None, 6796 /*StrictOp=*/true, BO->getSourceRange(), BO->getOperatorLoc()); 6797 } else if (auto *CE = dyn_cast<CXXOperatorCallExpr>(S)) { 6798 if (CE->getNumArgs() == 2) { 6799 auto Op = CE->getOperator(); 6800 switch (Op) { 6801 case OO_Greater: 6802 case OO_GreaterEqual: 6803 case OO_Less: 6804 case OO_LessEqual: 6805 if (getInitLCDecl(CE->getArg(0)) == LCDecl) 6806 return setUB(CE->getArg(1), Op == OO_Less || Op == OO_LessEqual, 6807 Op == OO_Less || Op == OO_Greater, CE->getSourceRange(), 6808 CE->getOperatorLoc()); 6809 if (getInitLCDecl(CE->getArg(1)) == LCDecl) 6810 return setUB(CE->getArg(0), Op == OO_Greater || Op == OO_GreaterEqual, 6811 Op == OO_Less || Op == OO_Greater, CE->getSourceRange(), 6812 CE->getOperatorLoc()); 6813 break; 6814 case OO_ExclaimEqual: 6815 if (IneqCondIsCanonical) 6816 return setUB(getInitLCDecl(CE->getArg(0)) == LCDecl ? CE->getArg(1) 6817 : CE->getArg(0), 6818 /*LessOp=*/llvm::None, 6819 /*StrictOp=*/true, CE->getSourceRange(), 6820 CE->getOperatorLoc()); 6821 break; 6822 default: 6823 break; 6824 } 6825 } 6826 } 6827 if (dependent() || SemaRef.CurContext->isDependentContext()) 6828 return false; 6829 SemaRef.Diag(CondLoc, diag::err_omp_loop_not_canonical_cond) 6830 << (IneqCondIsCanonical ? 1 : 0) << S->getSourceRange() << LCDecl; 6831 return true; 6832 } 6833 6834 bool OpenMPIterationSpaceChecker::checkAndSetIncRHS(Expr *RHS) { 6835 // RHS of canonical loop form increment can be: 6836 // var + incr 6837 // incr + var 6838 // var - incr 6839 // 6840 RHS = RHS->IgnoreParenImpCasts(); 6841 if (auto *BO = dyn_cast<BinaryOperator>(RHS)) { 6842 if (BO->isAdditiveOp()) { 6843 bool IsAdd = BO->getOpcode() == BO_Add; 6844 if (getInitLCDecl(BO->getLHS()) == LCDecl) 6845 return setStep(BO->getRHS(), !IsAdd); 6846 if (IsAdd && getInitLCDecl(BO->getRHS()) == LCDecl) 6847 return setStep(BO->getLHS(), /*Subtract=*/false); 6848 } 6849 } else if (auto *CE = dyn_cast<CXXOperatorCallExpr>(RHS)) { 6850 bool IsAdd = CE->getOperator() == OO_Plus; 6851 if ((IsAdd || CE->getOperator() == OO_Minus) && CE->getNumArgs() == 2) { 6852 if (getInitLCDecl(CE->getArg(0)) == LCDecl) 6853 return setStep(CE->getArg(1), !IsAdd); 6854 if (IsAdd && getInitLCDecl(CE->getArg(1)) == LCDecl) 6855 return setStep(CE->getArg(0), /*Subtract=*/false); 6856 } 6857 } 6858 if (dependent() || SemaRef.CurContext->isDependentContext()) 6859 return false; 6860 SemaRef.Diag(RHS->getBeginLoc(), diag::err_omp_loop_not_canonical_incr) 6861 << RHS->getSourceRange() << LCDecl; 6862 return true; 6863 } 6864 6865 bool OpenMPIterationSpaceChecker::checkAndSetInc(Expr *S) { 6866 // Check incr-expr for canonical loop form and return true if it 6867 // does not conform. 6868 // OpenMP [2.6] Canonical loop form. Test-expr may be one of the following: 6869 // ++var 6870 // var++ 6871 // --var 6872 // var-- 6873 // var += incr 6874 // var -= incr 6875 // var = var + incr 6876 // var = incr + var 6877 // var = var - incr 6878 // 6879 if (!S) { 6880 SemaRef.Diag(DefaultLoc, diag::err_omp_loop_not_canonical_incr) << LCDecl; 6881 return true; 6882 } 6883 if (auto *ExprTemp = dyn_cast<ExprWithCleanups>(S)) 6884 if (!ExprTemp->cleanupsHaveSideEffects()) 6885 S = ExprTemp->getSubExpr(); 6886 6887 IncrementSrcRange = S->getSourceRange(); 6888 S = S->IgnoreParens(); 6889 if (auto *UO = dyn_cast<UnaryOperator>(S)) { 6890 if (UO->isIncrementDecrementOp() && 6891 getInitLCDecl(UO->getSubExpr()) == LCDecl) 6892 return setStep(SemaRef 6893 .ActOnIntegerConstant(UO->getBeginLoc(), 6894 (UO->isDecrementOp() ? -1 : 1)) 6895 .get(), 6896 /*Subtract=*/false); 6897 } else if (auto *BO = dyn_cast<BinaryOperator>(S)) { 6898 switch (BO->getOpcode()) { 6899 case BO_AddAssign: 6900 case BO_SubAssign: 6901 if (getInitLCDecl(BO->getLHS()) == LCDecl) 6902 return setStep(BO->getRHS(), BO->getOpcode() == BO_SubAssign); 6903 break; 6904 case BO_Assign: 6905 if (getInitLCDecl(BO->getLHS()) == LCDecl) 6906 return checkAndSetIncRHS(BO->getRHS()); 6907 break; 6908 default: 6909 break; 6910 } 6911 } else if (auto *CE = dyn_cast<CXXOperatorCallExpr>(S)) { 6912 switch (CE->getOperator()) { 6913 case OO_PlusPlus: 6914 case OO_MinusMinus: 6915 if (getInitLCDecl(CE->getArg(0)) == LCDecl) 6916 return setStep(SemaRef 6917 .ActOnIntegerConstant( 6918 CE->getBeginLoc(), 6919 ((CE->getOperator() == OO_MinusMinus) ? -1 : 1)) 6920 .get(), 6921 /*Subtract=*/false); 6922 break; 6923 case OO_PlusEqual: 6924 case OO_MinusEqual: 6925 if (getInitLCDecl(CE->getArg(0)) == LCDecl) 6926 return setStep(CE->getArg(1), CE->getOperator() == OO_MinusEqual); 6927 break; 6928 case OO_Equal: 6929 if (getInitLCDecl(CE->getArg(0)) == LCDecl) 6930 return checkAndSetIncRHS(CE->getArg(1)); 6931 break; 6932 default: 6933 break; 6934 } 6935 } 6936 if (dependent() || SemaRef.CurContext->isDependentContext()) 6937 return false; 6938 SemaRef.Diag(S->getBeginLoc(), diag::err_omp_loop_not_canonical_incr) 6939 << S->getSourceRange() << LCDecl; 6940 return true; 6941 } 6942 6943 static ExprResult 6944 tryBuildCapture(Sema &SemaRef, Expr *Capture, 6945 llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) { 6946 if (SemaRef.CurContext->isDependentContext() || Capture->containsErrors()) 6947 return Capture; 6948 if (Capture->isEvaluatable(SemaRef.Context, Expr::SE_AllowSideEffects)) 6949 return SemaRef.PerformImplicitConversion( 6950 Capture->IgnoreImpCasts(), Capture->getType(), Sema::AA_Converting, 6951 /*AllowExplicit=*/true); 6952 auto I = Captures.find(Capture); 6953 if (I != Captures.end()) 6954 return buildCapture(SemaRef, Capture, I->second); 6955 DeclRefExpr *Ref = nullptr; 6956 ExprResult Res = buildCapture(SemaRef, Capture, Ref); 6957 Captures[Capture] = Ref; 6958 return Res; 6959 } 6960 6961 /// Calculate number of iterations, transforming to unsigned, if number of 6962 /// iterations may be larger than the original type. 6963 static Expr * 6964 calculateNumIters(Sema &SemaRef, Scope *S, SourceLocation DefaultLoc, 6965 Expr *Lower, Expr *Upper, Expr *Step, QualType LCTy, 6966 bool TestIsStrictOp, bool RoundToStep, 6967 llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) { 6968 ExprResult NewStep = tryBuildCapture(SemaRef, Step, Captures); 6969 if (!NewStep.isUsable()) 6970 return nullptr; 6971 llvm::APSInt LRes, SRes; 6972 bool IsLowerConst = false, IsStepConst = false; 6973 if (Optional<llvm::APSInt> Res = Lower->getIntegerConstantExpr(SemaRef.Context)) { 6974 LRes = *Res; 6975 IsLowerConst = true; 6976 } 6977 if (Optional<llvm::APSInt> Res = Step->getIntegerConstantExpr(SemaRef.Context)) { 6978 SRes = *Res; 6979 IsStepConst = true; 6980 } 6981 bool NoNeedToConvert = IsLowerConst && !RoundToStep && 6982 ((!TestIsStrictOp && LRes.isNonNegative()) || 6983 (TestIsStrictOp && LRes.isStrictlyPositive())); 6984 bool NeedToReorganize = false; 6985 // Check if any subexpressions in Lower -Step [+ 1] lead to overflow. 6986 if (!NoNeedToConvert && IsLowerConst && 6987 (TestIsStrictOp || (RoundToStep && IsStepConst))) { 6988 NoNeedToConvert = true; 6989 if (RoundToStep) { 6990 unsigned BW = LRes.getBitWidth() > SRes.getBitWidth() 6991 ? LRes.getBitWidth() 6992 : SRes.getBitWidth(); 6993 LRes = LRes.extend(BW + 1); 6994 LRes.setIsSigned(true); 6995 SRes = SRes.extend(BW + 1); 6996 SRes.setIsSigned(true); 6997 LRes -= SRes; 6998 NoNeedToConvert = LRes.trunc(BW).extend(BW + 1) == LRes; 6999 LRes = LRes.trunc(BW); 7000 } 7001 if (TestIsStrictOp) { 7002 unsigned BW = LRes.getBitWidth(); 7003 LRes = LRes.extend(BW + 1); 7004 LRes.setIsSigned(true); 7005 ++LRes; 7006 NoNeedToConvert = 7007 NoNeedToConvert && LRes.trunc(BW).extend(BW + 1) == LRes; 7008 // truncate to the original bitwidth. 7009 LRes = LRes.trunc(BW); 7010 } 7011 NeedToReorganize = NoNeedToConvert; 7012 } 7013 llvm::APSInt URes; 7014 bool IsUpperConst = false; 7015 if (Optional<llvm::APSInt> Res = Upper->getIntegerConstantExpr(SemaRef.Context)) { 7016 URes = *Res; 7017 IsUpperConst = true; 7018 } 7019 if (NoNeedToConvert && IsLowerConst && IsUpperConst && 7020 (!RoundToStep || IsStepConst)) { 7021 unsigned BW = LRes.getBitWidth() > URes.getBitWidth() ? LRes.getBitWidth() 7022 : URes.getBitWidth(); 7023 LRes = LRes.extend(BW + 1); 7024 LRes.setIsSigned(true); 7025 URes = URes.extend(BW + 1); 7026 URes.setIsSigned(true); 7027 URes -= LRes; 7028 NoNeedToConvert = URes.trunc(BW).extend(BW + 1) == URes; 7029 NeedToReorganize = NoNeedToConvert; 7030 } 7031 // If the boundaries are not constant or (Lower - Step [+ 1]) is not constant 7032 // or less than zero (Upper - (Lower - Step [+ 1]) may overflow) - promote to 7033 // unsigned. 7034 if ((!NoNeedToConvert || (LRes.isNegative() && !IsUpperConst)) && 7035 !LCTy->isDependentType() && LCTy->isIntegerType()) { 7036 QualType LowerTy = Lower->getType(); 7037 QualType UpperTy = Upper->getType(); 7038 uint64_t LowerSize = SemaRef.Context.getTypeSize(LowerTy); 7039 uint64_t UpperSize = SemaRef.Context.getTypeSize(UpperTy); 7040 if ((LowerSize <= UpperSize && UpperTy->hasSignedIntegerRepresentation()) || 7041 (LowerSize > UpperSize && LowerTy->hasSignedIntegerRepresentation())) { 7042 QualType CastType = SemaRef.Context.getIntTypeForBitwidth( 7043 LowerSize > UpperSize ? LowerSize : UpperSize, /*Signed=*/0); 7044 Upper = 7045 SemaRef 7046 .PerformImplicitConversion( 7047 SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, Upper).get(), 7048 CastType, Sema::AA_Converting) 7049 .get(); 7050 Lower = SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, Lower).get(); 7051 NewStep = SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, NewStep.get()); 7052 } 7053 } 7054 if (!Lower || !Upper || NewStep.isInvalid()) 7055 return nullptr; 7056 7057 ExprResult Diff; 7058 // If need to reorganize, then calculate the form as Upper - (Lower - Step [+ 7059 // 1]). 7060 if (NeedToReorganize) { 7061 Diff = Lower; 7062 7063 if (RoundToStep) { 7064 // Lower - Step 7065 Diff = 7066 SemaRef.BuildBinOp(S, DefaultLoc, BO_Sub, Diff.get(), NewStep.get()); 7067 if (!Diff.isUsable()) 7068 return nullptr; 7069 } 7070 7071 // Lower - Step [+ 1] 7072 if (TestIsStrictOp) 7073 Diff = SemaRef.BuildBinOp( 7074 S, DefaultLoc, BO_Add, Diff.get(), 7075 SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get()); 7076 if (!Diff.isUsable()) 7077 return nullptr; 7078 7079 Diff = SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, Diff.get()); 7080 if (!Diff.isUsable()) 7081 return nullptr; 7082 7083 // Upper - (Lower - Step [+ 1]). 7084 Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Sub, Upper, Diff.get()); 7085 if (!Diff.isUsable()) 7086 return nullptr; 7087 } else { 7088 Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Sub, Upper, Lower); 7089 7090 if (!Diff.isUsable() && LCTy->getAsCXXRecordDecl()) { 7091 // BuildBinOp already emitted error, this one is to point user to upper 7092 // and lower bound, and to tell what is passed to 'operator-'. 7093 SemaRef.Diag(Upper->getBeginLoc(), diag::err_omp_loop_diff_cxx) 7094 << Upper->getSourceRange() << Lower->getSourceRange(); 7095 return nullptr; 7096 } 7097 7098 if (!Diff.isUsable()) 7099 return nullptr; 7100 7101 // Upper - Lower [- 1] 7102 if (TestIsStrictOp) 7103 Diff = SemaRef.BuildBinOp( 7104 S, DefaultLoc, BO_Sub, Diff.get(), 7105 SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get()); 7106 if (!Diff.isUsable()) 7107 return nullptr; 7108 7109 if (RoundToStep) { 7110 // Upper - Lower [- 1] + Step 7111 Diff = 7112 SemaRef.BuildBinOp(S, DefaultLoc, BO_Add, Diff.get(), NewStep.get()); 7113 if (!Diff.isUsable()) 7114 return nullptr; 7115 } 7116 } 7117 7118 // Parentheses (for dumping/debugging purposes only). 7119 Diff = SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, Diff.get()); 7120 if (!Diff.isUsable()) 7121 return nullptr; 7122 7123 // (Upper - Lower [- 1] + Step) / Step or (Upper - Lower) / Step 7124 Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Div, Diff.get(), NewStep.get()); 7125 if (!Diff.isUsable()) 7126 return nullptr; 7127 7128 return Diff.get(); 7129 } 7130 7131 /// Build the expression to calculate the number of iterations. 7132 Expr *OpenMPIterationSpaceChecker::buildNumIterations( 7133 Scope *S, ArrayRef<LoopIterationSpace> ResultIterSpaces, bool LimitedType, 7134 llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) const { 7135 QualType VarType = LCDecl->getType().getNonReferenceType(); 7136 if (!VarType->isIntegerType() && !VarType->isPointerType() && 7137 !SemaRef.getLangOpts().CPlusPlus) 7138 return nullptr; 7139 Expr *LBVal = LB; 7140 Expr *UBVal = UB; 7141 // LB = TestIsLessOp.getValue() ? min(LB(MinVal), LB(MaxVal)) : 7142 // max(LB(MinVal), LB(MaxVal)) 7143 if (InitDependOnLC) { 7144 const LoopIterationSpace &IS = 7145 ResultIterSpaces[ResultIterSpaces.size() - 1 - 7146 InitDependOnLC.getValueOr( 7147 CondDependOnLC.getValueOr(0))]; 7148 if (!IS.MinValue || !IS.MaxValue) 7149 return nullptr; 7150 // OuterVar = Min 7151 ExprResult MinValue = 7152 SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, IS.MinValue); 7153 if (!MinValue.isUsable()) 7154 return nullptr; 7155 7156 ExprResult LBMinVal = SemaRef.BuildBinOp(S, DefaultLoc, BO_Assign, 7157 IS.CounterVar, MinValue.get()); 7158 if (!LBMinVal.isUsable()) 7159 return nullptr; 7160 // OuterVar = Min, LBVal 7161 LBMinVal = 7162 SemaRef.BuildBinOp(S, DefaultLoc, BO_Comma, LBMinVal.get(), LBVal); 7163 if (!LBMinVal.isUsable()) 7164 return nullptr; 7165 // (OuterVar = Min, LBVal) 7166 LBMinVal = SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, LBMinVal.get()); 7167 if (!LBMinVal.isUsable()) 7168 return nullptr; 7169 7170 // OuterVar = Max 7171 ExprResult MaxValue = 7172 SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, IS.MaxValue); 7173 if (!MaxValue.isUsable()) 7174 return nullptr; 7175 7176 ExprResult LBMaxVal = SemaRef.BuildBinOp(S, DefaultLoc, BO_Assign, 7177 IS.CounterVar, MaxValue.get()); 7178 if (!LBMaxVal.isUsable()) 7179 return nullptr; 7180 // OuterVar = Max, LBVal 7181 LBMaxVal = 7182 SemaRef.BuildBinOp(S, DefaultLoc, BO_Comma, LBMaxVal.get(), LBVal); 7183 if (!LBMaxVal.isUsable()) 7184 return nullptr; 7185 // (OuterVar = Max, LBVal) 7186 LBMaxVal = SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, LBMaxVal.get()); 7187 if (!LBMaxVal.isUsable()) 7188 return nullptr; 7189 7190 Expr *LBMin = tryBuildCapture(SemaRef, LBMinVal.get(), Captures).get(); 7191 Expr *LBMax = tryBuildCapture(SemaRef, LBMaxVal.get(), Captures).get(); 7192 if (!LBMin || !LBMax) 7193 return nullptr; 7194 // LB(MinVal) < LB(MaxVal) 7195 ExprResult MinLessMaxRes = 7196 SemaRef.BuildBinOp(S, DefaultLoc, BO_LT, LBMin, LBMax); 7197 if (!MinLessMaxRes.isUsable()) 7198 return nullptr; 7199 Expr *MinLessMax = 7200 tryBuildCapture(SemaRef, MinLessMaxRes.get(), Captures).get(); 7201 if (!MinLessMax) 7202 return nullptr; 7203 if (TestIsLessOp.getValue()) { 7204 // LB(MinVal) < LB(MaxVal) ? LB(MinVal) : LB(MaxVal) - min(LB(MinVal), 7205 // LB(MaxVal)) 7206 ExprResult MinLB = SemaRef.ActOnConditionalOp(DefaultLoc, DefaultLoc, 7207 MinLessMax, LBMin, LBMax); 7208 if (!MinLB.isUsable()) 7209 return nullptr; 7210 LBVal = MinLB.get(); 7211 } else { 7212 // LB(MinVal) < LB(MaxVal) ? LB(MaxVal) : LB(MinVal) - max(LB(MinVal), 7213 // LB(MaxVal)) 7214 ExprResult MaxLB = SemaRef.ActOnConditionalOp(DefaultLoc, DefaultLoc, 7215 MinLessMax, LBMax, LBMin); 7216 if (!MaxLB.isUsable()) 7217 return nullptr; 7218 LBVal = MaxLB.get(); 7219 } 7220 } 7221 // UB = TestIsLessOp.getValue() ? max(UB(MinVal), UB(MaxVal)) : 7222 // min(UB(MinVal), UB(MaxVal)) 7223 if (CondDependOnLC) { 7224 const LoopIterationSpace &IS = 7225 ResultIterSpaces[ResultIterSpaces.size() - 1 - 7226 InitDependOnLC.getValueOr( 7227 CondDependOnLC.getValueOr(0))]; 7228 if (!IS.MinValue || !IS.MaxValue) 7229 return nullptr; 7230 // OuterVar = Min 7231 ExprResult MinValue = 7232 SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, IS.MinValue); 7233 if (!MinValue.isUsable()) 7234 return nullptr; 7235 7236 ExprResult UBMinVal = SemaRef.BuildBinOp(S, DefaultLoc, BO_Assign, 7237 IS.CounterVar, MinValue.get()); 7238 if (!UBMinVal.isUsable()) 7239 return nullptr; 7240 // OuterVar = Min, UBVal 7241 UBMinVal = 7242 SemaRef.BuildBinOp(S, DefaultLoc, BO_Comma, UBMinVal.get(), UBVal); 7243 if (!UBMinVal.isUsable()) 7244 return nullptr; 7245 // (OuterVar = Min, UBVal) 7246 UBMinVal = SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, UBMinVal.get()); 7247 if (!UBMinVal.isUsable()) 7248 return nullptr; 7249 7250 // OuterVar = Max 7251 ExprResult MaxValue = 7252 SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, IS.MaxValue); 7253 if (!MaxValue.isUsable()) 7254 return nullptr; 7255 7256 ExprResult UBMaxVal = SemaRef.BuildBinOp(S, DefaultLoc, BO_Assign, 7257 IS.CounterVar, MaxValue.get()); 7258 if (!UBMaxVal.isUsable()) 7259 return nullptr; 7260 // OuterVar = Max, UBVal 7261 UBMaxVal = 7262 SemaRef.BuildBinOp(S, DefaultLoc, BO_Comma, UBMaxVal.get(), UBVal); 7263 if (!UBMaxVal.isUsable()) 7264 return nullptr; 7265 // (OuterVar = Max, UBVal) 7266 UBMaxVal = SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, UBMaxVal.get()); 7267 if (!UBMaxVal.isUsable()) 7268 return nullptr; 7269 7270 Expr *UBMin = tryBuildCapture(SemaRef, UBMinVal.get(), Captures).get(); 7271 Expr *UBMax = tryBuildCapture(SemaRef, UBMaxVal.get(), Captures).get(); 7272 if (!UBMin || !UBMax) 7273 return nullptr; 7274 // UB(MinVal) > UB(MaxVal) 7275 ExprResult MinGreaterMaxRes = 7276 SemaRef.BuildBinOp(S, DefaultLoc, BO_GT, UBMin, UBMax); 7277 if (!MinGreaterMaxRes.isUsable()) 7278 return nullptr; 7279 Expr *MinGreaterMax = 7280 tryBuildCapture(SemaRef, MinGreaterMaxRes.get(), Captures).get(); 7281 if (!MinGreaterMax) 7282 return nullptr; 7283 if (TestIsLessOp.getValue()) { 7284 // UB(MinVal) > UB(MaxVal) ? UB(MinVal) : UB(MaxVal) - max(UB(MinVal), 7285 // UB(MaxVal)) 7286 ExprResult MaxUB = SemaRef.ActOnConditionalOp( 7287 DefaultLoc, DefaultLoc, MinGreaterMax, UBMin, UBMax); 7288 if (!MaxUB.isUsable()) 7289 return nullptr; 7290 UBVal = MaxUB.get(); 7291 } else { 7292 // UB(MinVal) > UB(MaxVal) ? UB(MaxVal) : UB(MinVal) - min(UB(MinVal), 7293 // UB(MaxVal)) 7294 ExprResult MinUB = SemaRef.ActOnConditionalOp( 7295 DefaultLoc, DefaultLoc, MinGreaterMax, UBMax, UBMin); 7296 if (!MinUB.isUsable()) 7297 return nullptr; 7298 UBVal = MinUB.get(); 7299 } 7300 } 7301 Expr *UBExpr = TestIsLessOp.getValue() ? UBVal : LBVal; 7302 Expr *LBExpr = TestIsLessOp.getValue() ? LBVal : UBVal; 7303 Expr *Upper = tryBuildCapture(SemaRef, UBExpr, Captures).get(); 7304 Expr *Lower = tryBuildCapture(SemaRef, LBExpr, Captures).get(); 7305 if (!Upper || !Lower) 7306 return nullptr; 7307 7308 ExprResult Diff = 7309 calculateNumIters(SemaRef, S, DefaultLoc, Lower, Upper, Step, VarType, 7310 TestIsStrictOp, /*RoundToStep=*/true, Captures); 7311 if (!Diff.isUsable()) 7312 return nullptr; 7313 7314 // OpenMP runtime requires 32-bit or 64-bit loop variables. 7315 QualType Type = Diff.get()->getType(); 7316 ASTContext &C = SemaRef.Context; 7317 bool UseVarType = VarType->hasIntegerRepresentation() && 7318 C.getTypeSize(Type) > C.getTypeSize(VarType); 7319 if (!Type->isIntegerType() || UseVarType) { 7320 unsigned NewSize = 7321 UseVarType ? C.getTypeSize(VarType) : C.getTypeSize(Type); 7322 bool IsSigned = UseVarType ? VarType->hasSignedIntegerRepresentation() 7323 : Type->hasSignedIntegerRepresentation(); 7324 Type = C.getIntTypeForBitwidth(NewSize, IsSigned); 7325 if (!SemaRef.Context.hasSameType(Diff.get()->getType(), Type)) { 7326 Diff = SemaRef.PerformImplicitConversion( 7327 Diff.get(), Type, Sema::AA_Converting, /*AllowExplicit=*/true); 7328 if (!Diff.isUsable()) 7329 return nullptr; 7330 } 7331 } 7332 if (LimitedType) { 7333 unsigned NewSize = (C.getTypeSize(Type) > 32) ? 64 : 32; 7334 if (NewSize != C.getTypeSize(Type)) { 7335 if (NewSize < C.getTypeSize(Type)) { 7336 assert(NewSize == 64 && "incorrect loop var size"); 7337 SemaRef.Diag(DefaultLoc, diag::warn_omp_loop_64_bit_var) 7338 << InitSrcRange << ConditionSrcRange; 7339 } 7340 QualType NewType = C.getIntTypeForBitwidth( 7341 NewSize, Type->hasSignedIntegerRepresentation() || 7342 C.getTypeSize(Type) < NewSize); 7343 if (!SemaRef.Context.hasSameType(Diff.get()->getType(), NewType)) { 7344 Diff = SemaRef.PerformImplicitConversion(Diff.get(), NewType, 7345 Sema::AA_Converting, true); 7346 if (!Diff.isUsable()) 7347 return nullptr; 7348 } 7349 } 7350 } 7351 7352 return Diff.get(); 7353 } 7354 7355 std::pair<Expr *, Expr *> OpenMPIterationSpaceChecker::buildMinMaxValues( 7356 Scope *S, llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) const { 7357 // Do not build for iterators, they cannot be used in non-rectangular loop 7358 // nests. 7359 if (LCDecl->getType()->isRecordType()) 7360 return std::make_pair(nullptr, nullptr); 7361 // If we subtract, the min is in the condition, otherwise the min is in the 7362 // init value. 7363 Expr *MinExpr = nullptr; 7364 Expr *MaxExpr = nullptr; 7365 Expr *LBExpr = TestIsLessOp.getValue() ? LB : UB; 7366 Expr *UBExpr = TestIsLessOp.getValue() ? UB : LB; 7367 bool LBNonRect = TestIsLessOp.getValue() ? InitDependOnLC.hasValue() 7368 : CondDependOnLC.hasValue(); 7369 bool UBNonRect = TestIsLessOp.getValue() ? CondDependOnLC.hasValue() 7370 : InitDependOnLC.hasValue(); 7371 Expr *Lower = 7372 LBNonRect ? LBExpr : tryBuildCapture(SemaRef, LBExpr, Captures).get(); 7373 Expr *Upper = 7374 UBNonRect ? UBExpr : tryBuildCapture(SemaRef, UBExpr, Captures).get(); 7375 if (!Upper || !Lower) 7376 return std::make_pair(nullptr, nullptr); 7377 7378 if (TestIsLessOp.getValue()) 7379 MinExpr = Lower; 7380 else 7381 MaxExpr = Upper; 7382 7383 // Build minimum/maximum value based on number of iterations. 7384 QualType VarType = LCDecl->getType().getNonReferenceType(); 7385 7386 ExprResult Diff = 7387 calculateNumIters(SemaRef, S, DefaultLoc, Lower, Upper, Step, VarType, 7388 TestIsStrictOp, /*RoundToStep=*/false, Captures); 7389 if (!Diff.isUsable()) 7390 return std::make_pair(nullptr, nullptr); 7391 7392 // ((Upper - Lower [- 1]) / Step) * Step 7393 // Parentheses (for dumping/debugging purposes only). 7394 Diff = SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, Diff.get()); 7395 if (!Diff.isUsable()) 7396 return std::make_pair(nullptr, nullptr); 7397 7398 ExprResult NewStep = tryBuildCapture(SemaRef, Step, Captures); 7399 if (!NewStep.isUsable()) 7400 return std::make_pair(nullptr, nullptr); 7401 Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Mul, Diff.get(), NewStep.get()); 7402 if (!Diff.isUsable()) 7403 return std::make_pair(nullptr, nullptr); 7404 7405 // Parentheses (for dumping/debugging purposes only). 7406 Diff = SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, Diff.get()); 7407 if (!Diff.isUsable()) 7408 return std::make_pair(nullptr, nullptr); 7409 7410 // Convert to the ptrdiff_t, if original type is pointer. 7411 if (VarType->isAnyPointerType() && 7412 !SemaRef.Context.hasSameType( 7413 Diff.get()->getType(), 7414 SemaRef.Context.getUnsignedPointerDiffType())) { 7415 Diff = SemaRef.PerformImplicitConversion( 7416 Diff.get(), SemaRef.Context.getUnsignedPointerDiffType(), 7417 Sema::AA_Converting, /*AllowExplicit=*/true); 7418 } 7419 if (!Diff.isUsable()) 7420 return std::make_pair(nullptr, nullptr); 7421 7422 if (TestIsLessOp.getValue()) { 7423 // MinExpr = Lower; 7424 // MaxExpr = Lower + (((Upper - Lower [- 1]) / Step) * Step) 7425 Diff = SemaRef.BuildBinOp( 7426 S, DefaultLoc, BO_Add, 7427 SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, Lower).get(), 7428 Diff.get()); 7429 if (!Diff.isUsable()) 7430 return std::make_pair(nullptr, nullptr); 7431 } else { 7432 // MaxExpr = Upper; 7433 // MinExpr = Upper - (((Upper - Lower [- 1]) / Step) * Step) 7434 Diff = SemaRef.BuildBinOp( 7435 S, DefaultLoc, BO_Sub, 7436 SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, Upper).get(), 7437 Diff.get()); 7438 if (!Diff.isUsable()) 7439 return std::make_pair(nullptr, nullptr); 7440 } 7441 7442 // Convert to the original type. 7443 if (SemaRef.Context.hasSameType(Diff.get()->getType(), VarType)) 7444 Diff = SemaRef.PerformImplicitConversion(Diff.get(), VarType, 7445 Sema::AA_Converting, 7446 /*AllowExplicit=*/true); 7447 if (!Diff.isUsable()) 7448 return std::make_pair(nullptr, nullptr); 7449 7450 Diff = SemaRef.ActOnFinishFullExpr(Diff.get(), /*DiscardedValue=*/false); 7451 if (!Diff.isUsable()) 7452 return std::make_pair(nullptr, nullptr); 7453 7454 if (TestIsLessOp.getValue()) 7455 MaxExpr = Diff.get(); 7456 else 7457 MinExpr = Diff.get(); 7458 7459 return std::make_pair(MinExpr, MaxExpr); 7460 } 7461 7462 Expr *OpenMPIterationSpaceChecker::buildFinalCondition(Scope *S) const { 7463 if (InitDependOnLC || CondDependOnLC) 7464 return Condition; 7465 return nullptr; 7466 } 7467 7468 Expr *OpenMPIterationSpaceChecker::buildPreCond( 7469 Scope *S, Expr *Cond, 7470 llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) const { 7471 // Do not build a precondition when the condition/initialization is dependent 7472 // to prevent pessimistic early loop exit. 7473 // TODO: this can be improved by calculating min/max values but not sure that 7474 // it will be very effective. 7475 if (CondDependOnLC || InitDependOnLC) 7476 return SemaRef.PerformImplicitConversion( 7477 SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get(), 7478 SemaRef.Context.BoolTy, /*Action=*/Sema::AA_Casting, 7479 /*AllowExplicit=*/true).get(); 7480 7481 // Try to build LB <op> UB, where <op> is <, >, <=, or >=. 7482 Sema::TentativeAnalysisScope Trap(SemaRef); 7483 7484 ExprResult NewLB = tryBuildCapture(SemaRef, LB, Captures); 7485 ExprResult NewUB = tryBuildCapture(SemaRef, UB, Captures); 7486 if (!NewLB.isUsable() || !NewUB.isUsable()) 7487 return nullptr; 7488 7489 ExprResult CondExpr = 7490 SemaRef.BuildBinOp(S, DefaultLoc, 7491 TestIsLessOp.getValue() ? 7492 (TestIsStrictOp ? BO_LT : BO_LE) : 7493 (TestIsStrictOp ? BO_GT : BO_GE), 7494 NewLB.get(), NewUB.get()); 7495 if (CondExpr.isUsable()) { 7496 if (!SemaRef.Context.hasSameUnqualifiedType(CondExpr.get()->getType(), 7497 SemaRef.Context.BoolTy)) 7498 CondExpr = SemaRef.PerformImplicitConversion( 7499 CondExpr.get(), SemaRef.Context.BoolTy, /*Action=*/Sema::AA_Casting, 7500 /*AllowExplicit=*/true); 7501 } 7502 7503 // Otherwise use original loop condition and evaluate it in runtime. 7504 return CondExpr.isUsable() ? CondExpr.get() : Cond; 7505 } 7506 7507 /// Build reference expression to the counter be used for codegen. 7508 DeclRefExpr *OpenMPIterationSpaceChecker::buildCounterVar( 7509 llvm::MapVector<const Expr *, DeclRefExpr *> &Captures, 7510 DSAStackTy &DSA) const { 7511 auto *VD = dyn_cast<VarDecl>(LCDecl); 7512 if (!VD) { 7513 VD = SemaRef.isOpenMPCapturedDecl(LCDecl); 7514 DeclRefExpr *Ref = buildDeclRefExpr( 7515 SemaRef, VD, VD->getType().getNonReferenceType(), DefaultLoc); 7516 const DSAStackTy::DSAVarData Data = 7517 DSA.getTopDSA(LCDecl, /*FromParent=*/false); 7518 // If the loop control decl is explicitly marked as private, do not mark it 7519 // as captured again. 7520 if (!isOpenMPPrivate(Data.CKind) || !Data.RefExpr) 7521 Captures.insert(std::make_pair(LCRef, Ref)); 7522 return Ref; 7523 } 7524 return cast<DeclRefExpr>(LCRef); 7525 } 7526 7527 Expr *OpenMPIterationSpaceChecker::buildPrivateCounterVar() const { 7528 if (LCDecl && !LCDecl->isInvalidDecl()) { 7529 QualType Type = LCDecl->getType().getNonReferenceType(); 7530 VarDecl *PrivateVar = buildVarDecl( 7531 SemaRef, DefaultLoc, Type, LCDecl->getName(), 7532 LCDecl->hasAttrs() ? &LCDecl->getAttrs() : nullptr, 7533 isa<VarDecl>(LCDecl) 7534 ? buildDeclRefExpr(SemaRef, cast<VarDecl>(LCDecl), Type, DefaultLoc) 7535 : nullptr); 7536 if (PrivateVar->isInvalidDecl()) 7537 return nullptr; 7538 return buildDeclRefExpr(SemaRef, PrivateVar, Type, DefaultLoc); 7539 } 7540 return nullptr; 7541 } 7542 7543 /// Build initialization of the counter to be used for codegen. 7544 Expr *OpenMPIterationSpaceChecker::buildCounterInit() const { return LB; } 7545 7546 /// Build step of the counter be used for codegen. 7547 Expr *OpenMPIterationSpaceChecker::buildCounterStep() const { return Step; } 7548 7549 Expr *OpenMPIterationSpaceChecker::buildOrderedLoopData( 7550 Scope *S, Expr *Counter, 7551 llvm::MapVector<const Expr *, DeclRefExpr *> &Captures, SourceLocation Loc, 7552 Expr *Inc, OverloadedOperatorKind OOK) { 7553 Expr *Cnt = SemaRef.DefaultLvalueConversion(Counter).get(); 7554 if (!Cnt) 7555 return nullptr; 7556 if (Inc) { 7557 assert((OOK == OO_Plus || OOK == OO_Minus) && 7558 "Expected only + or - operations for depend clauses."); 7559 BinaryOperatorKind BOK = (OOK == OO_Plus) ? BO_Add : BO_Sub; 7560 Cnt = SemaRef.BuildBinOp(S, Loc, BOK, Cnt, Inc).get(); 7561 if (!Cnt) 7562 return nullptr; 7563 } 7564 QualType VarType = LCDecl->getType().getNonReferenceType(); 7565 if (!VarType->isIntegerType() && !VarType->isPointerType() && 7566 !SemaRef.getLangOpts().CPlusPlus) 7567 return nullptr; 7568 // Upper - Lower 7569 Expr *Upper = TestIsLessOp.getValue() 7570 ? Cnt 7571 : tryBuildCapture(SemaRef, LB, Captures).get(); 7572 Expr *Lower = TestIsLessOp.getValue() 7573 ? tryBuildCapture(SemaRef, LB, Captures).get() 7574 : Cnt; 7575 if (!Upper || !Lower) 7576 return nullptr; 7577 7578 ExprResult Diff = calculateNumIters(SemaRef, S, DefaultLoc, Lower, Upper, 7579 Step, VarType, /*TestIsStrictOp=*/false, 7580 /*RoundToStep=*/false, Captures); 7581 if (!Diff.isUsable()) 7582 return nullptr; 7583 7584 return Diff.get(); 7585 } 7586 } // namespace 7587 7588 void Sema::ActOnOpenMPLoopInitialization(SourceLocation ForLoc, Stmt *Init) { 7589 assert(getLangOpts().OpenMP && "OpenMP is not active."); 7590 assert(Init && "Expected loop in canonical form."); 7591 unsigned AssociatedLoops = DSAStack->getAssociatedLoops(); 7592 if (AssociatedLoops > 0 && 7593 isOpenMPLoopDirective(DSAStack->getCurrentDirective())) { 7594 DSAStack->loopStart(); 7595 OpenMPIterationSpaceChecker ISC(*this, *DSAStack, ForLoc); 7596 if (!ISC.checkAndSetInit(Init, /*EmitDiags=*/false)) { 7597 if (ValueDecl *D = ISC.getLoopDecl()) { 7598 auto *VD = dyn_cast<VarDecl>(D); 7599 DeclRefExpr *PrivateRef = nullptr; 7600 if (!VD) { 7601 if (VarDecl *Private = isOpenMPCapturedDecl(D)) { 7602 VD = Private; 7603 } else { 7604 PrivateRef = buildCapture(*this, D, ISC.getLoopDeclRefExpr(), 7605 /*WithInit=*/false); 7606 VD = cast<VarDecl>(PrivateRef->getDecl()); 7607 } 7608 } 7609 DSAStack->addLoopControlVariable(D, VD); 7610 const Decl *LD = DSAStack->getPossiblyLoopCunter(); 7611 if (LD != D->getCanonicalDecl()) { 7612 DSAStack->resetPossibleLoopCounter(); 7613 if (auto *Var = dyn_cast_or_null<VarDecl>(LD)) 7614 MarkDeclarationsReferencedInExpr( 7615 buildDeclRefExpr(*this, const_cast<VarDecl *>(Var), 7616 Var->getType().getNonLValueExprType(Context), 7617 ForLoc, /*RefersToCapture=*/true)); 7618 } 7619 OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective(); 7620 // OpenMP [2.14.1.1, Data-sharing Attribute Rules for Variables 7621 // Referenced in a Construct, C/C++]. The loop iteration variable in the 7622 // associated for-loop of a simd construct with just one associated 7623 // for-loop may be listed in a linear clause with a constant-linear-step 7624 // that is the increment of the associated for-loop. The loop iteration 7625 // variable(s) in the associated for-loop(s) of a for or parallel for 7626 // construct may be listed in a private or lastprivate clause. 7627 DSAStackTy::DSAVarData DVar = 7628 DSAStack->getTopDSA(D, /*FromParent=*/false); 7629 // If LoopVarRefExpr is nullptr it means the corresponding loop variable 7630 // is declared in the loop and it is predetermined as a private. 7631 Expr *LoopDeclRefExpr = ISC.getLoopDeclRefExpr(); 7632 OpenMPClauseKind PredeterminedCKind = 7633 isOpenMPSimdDirective(DKind) 7634 ? (DSAStack->hasMutipleLoops() ? OMPC_lastprivate : OMPC_linear) 7635 : OMPC_private; 7636 if (((isOpenMPSimdDirective(DKind) && DVar.CKind != OMPC_unknown && 7637 DVar.CKind != PredeterminedCKind && DVar.RefExpr && 7638 (LangOpts.OpenMP <= 45 || (DVar.CKind != OMPC_lastprivate && 7639 DVar.CKind != OMPC_private))) || 7640 ((isOpenMPWorksharingDirective(DKind) || DKind == OMPD_taskloop || 7641 DKind == OMPD_master_taskloop || 7642 DKind == OMPD_parallel_master_taskloop || 7643 isOpenMPDistributeDirective(DKind)) && 7644 !isOpenMPSimdDirective(DKind) && DVar.CKind != OMPC_unknown && 7645 DVar.CKind != OMPC_private && DVar.CKind != OMPC_lastprivate)) && 7646 (DVar.CKind != OMPC_private || DVar.RefExpr)) { 7647 Diag(Init->getBeginLoc(), diag::err_omp_loop_var_dsa) 7648 << getOpenMPClauseName(DVar.CKind) 7649 << getOpenMPDirectiveName(DKind) 7650 << getOpenMPClauseName(PredeterminedCKind); 7651 if (DVar.RefExpr == nullptr) 7652 DVar.CKind = PredeterminedCKind; 7653 reportOriginalDsa(*this, DSAStack, D, DVar, 7654 /*IsLoopIterVar=*/true); 7655 } else if (LoopDeclRefExpr) { 7656 // Make the loop iteration variable private (for worksharing 7657 // constructs), linear (for simd directives with the only one 7658 // associated loop) or lastprivate (for simd directives with several 7659 // collapsed or ordered loops). 7660 if (DVar.CKind == OMPC_unknown) 7661 DSAStack->addDSA(D, LoopDeclRefExpr, PredeterminedCKind, 7662 PrivateRef); 7663 } 7664 } 7665 } 7666 DSAStack->setAssociatedLoops(AssociatedLoops - 1); 7667 } 7668 } 7669 7670 /// Called on a for stmt to check and extract its iteration space 7671 /// for further processing (such as collapsing). 7672 static bool checkOpenMPIterationSpace( 7673 OpenMPDirectiveKind DKind, Stmt *S, Sema &SemaRef, DSAStackTy &DSA, 7674 unsigned CurrentNestedLoopCount, unsigned NestedLoopCount, 7675 unsigned TotalNestedLoopCount, Expr *CollapseLoopCountExpr, 7676 Expr *OrderedLoopCountExpr, 7677 Sema::VarsWithInheritedDSAType &VarsWithImplicitDSA, 7678 llvm::MutableArrayRef<LoopIterationSpace> ResultIterSpaces, 7679 llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) { 7680 // OpenMP [2.9.1, Canonical Loop Form] 7681 // for (init-expr; test-expr; incr-expr) structured-block 7682 // for (range-decl: range-expr) structured-block 7683 auto *For = dyn_cast_or_null<ForStmt>(S); 7684 auto *CXXFor = dyn_cast_or_null<CXXForRangeStmt>(S); 7685 // Ranged for is supported only in OpenMP 5.0. 7686 if (!For && (SemaRef.LangOpts.OpenMP <= 45 || !CXXFor)) { 7687 SemaRef.Diag(S->getBeginLoc(), diag::err_omp_not_for) 7688 << (CollapseLoopCountExpr != nullptr || OrderedLoopCountExpr != nullptr) 7689 << getOpenMPDirectiveName(DKind) << TotalNestedLoopCount 7690 << (CurrentNestedLoopCount > 0) << CurrentNestedLoopCount; 7691 if (TotalNestedLoopCount > 1) { 7692 if (CollapseLoopCountExpr && OrderedLoopCountExpr) 7693 SemaRef.Diag(DSA.getConstructLoc(), 7694 diag::note_omp_collapse_ordered_expr) 7695 << 2 << CollapseLoopCountExpr->getSourceRange() 7696 << OrderedLoopCountExpr->getSourceRange(); 7697 else if (CollapseLoopCountExpr) 7698 SemaRef.Diag(CollapseLoopCountExpr->getExprLoc(), 7699 diag::note_omp_collapse_ordered_expr) 7700 << 0 << CollapseLoopCountExpr->getSourceRange(); 7701 else 7702 SemaRef.Diag(OrderedLoopCountExpr->getExprLoc(), 7703 diag::note_omp_collapse_ordered_expr) 7704 << 1 << OrderedLoopCountExpr->getSourceRange(); 7705 } 7706 return true; 7707 } 7708 assert(((For && For->getBody()) || (CXXFor && CXXFor->getBody())) && 7709 "No loop body."); 7710 7711 OpenMPIterationSpaceChecker ISC(SemaRef, DSA, 7712 For ? For->getForLoc() : CXXFor->getForLoc()); 7713 7714 // Check init. 7715 Stmt *Init = For ? For->getInit() : CXXFor->getBeginStmt(); 7716 if (ISC.checkAndSetInit(Init)) 7717 return true; 7718 7719 bool HasErrors = false; 7720 7721 // Check loop variable's type. 7722 if (ValueDecl *LCDecl = ISC.getLoopDecl()) { 7723 // OpenMP [2.6, Canonical Loop Form] 7724 // Var is one of the following: 7725 // A variable of signed or unsigned integer type. 7726 // For C++, a variable of a random access iterator type. 7727 // For C, a variable of a pointer type. 7728 QualType VarType = LCDecl->getType().getNonReferenceType(); 7729 if (!VarType->isDependentType() && !VarType->isIntegerType() && 7730 !VarType->isPointerType() && 7731 !(SemaRef.getLangOpts().CPlusPlus && VarType->isOverloadableType())) { 7732 SemaRef.Diag(Init->getBeginLoc(), diag::err_omp_loop_variable_type) 7733 << SemaRef.getLangOpts().CPlusPlus; 7734 HasErrors = true; 7735 } 7736 7737 // OpenMP, 2.14.1.1 Data-sharing Attribute Rules for Variables Referenced in 7738 // a Construct 7739 // The loop iteration variable(s) in the associated for-loop(s) of a for or 7740 // parallel for construct is (are) private. 7741 // The loop iteration variable in the associated for-loop of a simd 7742 // construct with just one associated for-loop is linear with a 7743 // constant-linear-step that is the increment of the associated for-loop. 7744 // Exclude loop var from the list of variables with implicitly defined data 7745 // sharing attributes. 7746 VarsWithImplicitDSA.erase(LCDecl); 7747 7748 assert(isOpenMPLoopDirective(DKind) && "DSA for non-loop vars"); 7749 7750 // Check test-expr. 7751 HasErrors |= ISC.checkAndSetCond(For ? For->getCond() : CXXFor->getCond()); 7752 7753 // Check incr-expr. 7754 HasErrors |= ISC.checkAndSetInc(For ? For->getInc() : CXXFor->getInc()); 7755 } 7756 7757 if (ISC.dependent() || SemaRef.CurContext->isDependentContext() || HasErrors) 7758 return HasErrors; 7759 7760 // Build the loop's iteration space representation. 7761 ResultIterSpaces[CurrentNestedLoopCount].PreCond = ISC.buildPreCond( 7762 DSA.getCurScope(), For ? For->getCond() : CXXFor->getCond(), Captures); 7763 ResultIterSpaces[CurrentNestedLoopCount].NumIterations = 7764 ISC.buildNumIterations(DSA.getCurScope(), ResultIterSpaces, 7765 (isOpenMPWorksharingDirective(DKind) || 7766 isOpenMPTaskLoopDirective(DKind) || 7767 isOpenMPDistributeDirective(DKind)), 7768 Captures); 7769 ResultIterSpaces[CurrentNestedLoopCount].CounterVar = 7770 ISC.buildCounterVar(Captures, DSA); 7771 ResultIterSpaces[CurrentNestedLoopCount].PrivateCounterVar = 7772 ISC.buildPrivateCounterVar(); 7773 ResultIterSpaces[CurrentNestedLoopCount].CounterInit = ISC.buildCounterInit(); 7774 ResultIterSpaces[CurrentNestedLoopCount].CounterStep = ISC.buildCounterStep(); 7775 ResultIterSpaces[CurrentNestedLoopCount].InitSrcRange = ISC.getInitSrcRange(); 7776 ResultIterSpaces[CurrentNestedLoopCount].CondSrcRange = 7777 ISC.getConditionSrcRange(); 7778 ResultIterSpaces[CurrentNestedLoopCount].IncSrcRange = 7779 ISC.getIncrementSrcRange(); 7780 ResultIterSpaces[CurrentNestedLoopCount].Subtract = ISC.shouldSubtractStep(); 7781 ResultIterSpaces[CurrentNestedLoopCount].IsStrictCompare = 7782 ISC.isStrictTestOp(); 7783 std::tie(ResultIterSpaces[CurrentNestedLoopCount].MinValue, 7784 ResultIterSpaces[CurrentNestedLoopCount].MaxValue) = 7785 ISC.buildMinMaxValues(DSA.getCurScope(), Captures); 7786 ResultIterSpaces[CurrentNestedLoopCount].FinalCondition = 7787 ISC.buildFinalCondition(DSA.getCurScope()); 7788 ResultIterSpaces[CurrentNestedLoopCount].IsNonRectangularLB = 7789 ISC.doesInitDependOnLC(); 7790 ResultIterSpaces[CurrentNestedLoopCount].IsNonRectangularUB = 7791 ISC.doesCondDependOnLC(); 7792 ResultIterSpaces[CurrentNestedLoopCount].LoopDependentIdx = 7793 ISC.getLoopDependentIdx(); 7794 7795 HasErrors |= 7796 (ResultIterSpaces[CurrentNestedLoopCount].PreCond == nullptr || 7797 ResultIterSpaces[CurrentNestedLoopCount].NumIterations == nullptr || 7798 ResultIterSpaces[CurrentNestedLoopCount].CounterVar == nullptr || 7799 ResultIterSpaces[CurrentNestedLoopCount].PrivateCounterVar == nullptr || 7800 ResultIterSpaces[CurrentNestedLoopCount].CounterInit == nullptr || 7801 ResultIterSpaces[CurrentNestedLoopCount].CounterStep == nullptr); 7802 if (!HasErrors && DSA.isOrderedRegion()) { 7803 if (DSA.getOrderedRegionParam().second->getNumForLoops()) { 7804 if (CurrentNestedLoopCount < 7805 DSA.getOrderedRegionParam().second->getLoopNumIterations().size()) { 7806 DSA.getOrderedRegionParam().second->setLoopNumIterations( 7807 CurrentNestedLoopCount, 7808 ResultIterSpaces[CurrentNestedLoopCount].NumIterations); 7809 DSA.getOrderedRegionParam().second->setLoopCounter( 7810 CurrentNestedLoopCount, 7811 ResultIterSpaces[CurrentNestedLoopCount].CounterVar); 7812 } 7813 } 7814 for (auto &Pair : DSA.getDoacrossDependClauses()) { 7815 if (CurrentNestedLoopCount >= Pair.first->getNumLoops()) { 7816 // Erroneous case - clause has some problems. 7817 continue; 7818 } 7819 if (Pair.first->getDependencyKind() == OMPC_DEPEND_sink && 7820 Pair.second.size() <= CurrentNestedLoopCount) { 7821 // Erroneous case - clause has some problems. 7822 Pair.first->setLoopData(CurrentNestedLoopCount, nullptr); 7823 continue; 7824 } 7825 Expr *CntValue; 7826 if (Pair.first->getDependencyKind() == OMPC_DEPEND_source) 7827 CntValue = ISC.buildOrderedLoopData( 7828 DSA.getCurScope(), 7829 ResultIterSpaces[CurrentNestedLoopCount].CounterVar, Captures, 7830 Pair.first->getDependencyLoc()); 7831 else 7832 CntValue = ISC.buildOrderedLoopData( 7833 DSA.getCurScope(), 7834 ResultIterSpaces[CurrentNestedLoopCount].CounterVar, Captures, 7835 Pair.first->getDependencyLoc(), 7836 Pair.second[CurrentNestedLoopCount].first, 7837 Pair.second[CurrentNestedLoopCount].second); 7838 Pair.first->setLoopData(CurrentNestedLoopCount, CntValue); 7839 } 7840 } 7841 7842 return HasErrors; 7843 } 7844 7845 /// Build 'VarRef = Start. 7846 static ExprResult 7847 buildCounterInit(Sema &SemaRef, Scope *S, SourceLocation Loc, ExprResult VarRef, 7848 ExprResult Start, bool IsNonRectangularLB, 7849 llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) { 7850 // Build 'VarRef = Start. 7851 ExprResult NewStart = IsNonRectangularLB 7852 ? Start.get() 7853 : tryBuildCapture(SemaRef, Start.get(), Captures); 7854 if (!NewStart.isUsable()) 7855 return ExprError(); 7856 if (!SemaRef.Context.hasSameType(NewStart.get()->getType(), 7857 VarRef.get()->getType())) { 7858 NewStart = SemaRef.PerformImplicitConversion( 7859 NewStart.get(), VarRef.get()->getType(), Sema::AA_Converting, 7860 /*AllowExplicit=*/true); 7861 if (!NewStart.isUsable()) 7862 return ExprError(); 7863 } 7864 7865 ExprResult Init = 7866 SemaRef.BuildBinOp(S, Loc, BO_Assign, VarRef.get(), NewStart.get()); 7867 return Init; 7868 } 7869 7870 /// Build 'VarRef = Start + Iter * Step'. 7871 static ExprResult buildCounterUpdate( 7872 Sema &SemaRef, Scope *S, SourceLocation Loc, ExprResult VarRef, 7873 ExprResult Start, ExprResult Iter, ExprResult Step, bool Subtract, 7874 bool IsNonRectangularLB, 7875 llvm::MapVector<const Expr *, DeclRefExpr *> *Captures = nullptr) { 7876 // Add parentheses (for debugging purposes only). 7877 Iter = SemaRef.ActOnParenExpr(Loc, Loc, Iter.get()); 7878 if (!VarRef.isUsable() || !Start.isUsable() || !Iter.isUsable() || 7879 !Step.isUsable()) 7880 return ExprError(); 7881 7882 ExprResult NewStep = Step; 7883 if (Captures) 7884 NewStep = tryBuildCapture(SemaRef, Step.get(), *Captures); 7885 if (NewStep.isInvalid()) 7886 return ExprError(); 7887 ExprResult Update = 7888 SemaRef.BuildBinOp(S, Loc, BO_Mul, Iter.get(), NewStep.get()); 7889 if (!Update.isUsable()) 7890 return ExprError(); 7891 7892 // Try to build 'VarRef = Start, VarRef (+|-)= Iter * Step' or 7893 // 'VarRef = Start (+|-) Iter * Step'. 7894 if (!Start.isUsable()) 7895 return ExprError(); 7896 ExprResult NewStart = SemaRef.ActOnParenExpr(Loc, Loc, Start.get()); 7897 if (!NewStart.isUsable()) 7898 return ExprError(); 7899 if (Captures && !IsNonRectangularLB) 7900 NewStart = tryBuildCapture(SemaRef, Start.get(), *Captures); 7901 if (NewStart.isInvalid()) 7902 return ExprError(); 7903 7904 // First attempt: try to build 'VarRef = Start, VarRef += Iter * Step'. 7905 ExprResult SavedUpdate = Update; 7906 ExprResult UpdateVal; 7907 if (VarRef.get()->getType()->isOverloadableType() || 7908 NewStart.get()->getType()->isOverloadableType() || 7909 Update.get()->getType()->isOverloadableType()) { 7910 Sema::TentativeAnalysisScope Trap(SemaRef); 7911 7912 Update = 7913 SemaRef.BuildBinOp(S, Loc, BO_Assign, VarRef.get(), NewStart.get()); 7914 if (Update.isUsable()) { 7915 UpdateVal = 7916 SemaRef.BuildBinOp(S, Loc, Subtract ? BO_SubAssign : BO_AddAssign, 7917 VarRef.get(), SavedUpdate.get()); 7918 if (UpdateVal.isUsable()) { 7919 Update = SemaRef.CreateBuiltinBinOp(Loc, BO_Comma, Update.get(), 7920 UpdateVal.get()); 7921 } 7922 } 7923 } 7924 7925 // Second attempt: try to build 'VarRef = Start (+|-) Iter * Step'. 7926 if (!Update.isUsable() || !UpdateVal.isUsable()) { 7927 Update = SemaRef.BuildBinOp(S, Loc, Subtract ? BO_Sub : BO_Add, 7928 NewStart.get(), SavedUpdate.get()); 7929 if (!Update.isUsable()) 7930 return ExprError(); 7931 7932 if (!SemaRef.Context.hasSameType(Update.get()->getType(), 7933 VarRef.get()->getType())) { 7934 Update = SemaRef.PerformImplicitConversion( 7935 Update.get(), VarRef.get()->getType(), Sema::AA_Converting, true); 7936 if (!Update.isUsable()) 7937 return ExprError(); 7938 } 7939 7940 Update = SemaRef.BuildBinOp(S, Loc, BO_Assign, VarRef.get(), Update.get()); 7941 } 7942 return Update; 7943 } 7944 7945 /// Convert integer expression \a E to make it have at least \a Bits 7946 /// bits. 7947 static ExprResult widenIterationCount(unsigned Bits, Expr *E, Sema &SemaRef) { 7948 if (E == nullptr) 7949 return ExprError(); 7950 ASTContext &C = SemaRef.Context; 7951 QualType OldType = E->getType(); 7952 unsigned HasBits = C.getTypeSize(OldType); 7953 if (HasBits >= Bits) 7954 return ExprResult(E); 7955 // OK to convert to signed, because new type has more bits than old. 7956 QualType NewType = C.getIntTypeForBitwidth(Bits, /* Signed */ true); 7957 return SemaRef.PerformImplicitConversion(E, NewType, Sema::AA_Converting, 7958 true); 7959 } 7960 7961 /// Check if the given expression \a E is a constant integer that fits 7962 /// into \a Bits bits. 7963 static bool fitsInto(unsigned Bits, bool Signed, const Expr *E, Sema &SemaRef) { 7964 if (E == nullptr) 7965 return false; 7966 if (Optional<llvm::APSInt> Result = 7967 E->getIntegerConstantExpr(SemaRef.Context)) 7968 return Signed ? Result->isSignedIntN(Bits) : Result->isIntN(Bits); 7969 return false; 7970 } 7971 7972 /// Build preinits statement for the given declarations. 7973 static Stmt *buildPreInits(ASTContext &Context, 7974 MutableArrayRef<Decl *> PreInits) { 7975 if (!PreInits.empty()) { 7976 return new (Context) DeclStmt( 7977 DeclGroupRef::Create(Context, PreInits.begin(), PreInits.size()), 7978 SourceLocation(), SourceLocation()); 7979 } 7980 return nullptr; 7981 } 7982 7983 /// Build preinits statement for the given declarations. 7984 static Stmt * 7985 buildPreInits(ASTContext &Context, 7986 const llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) { 7987 if (!Captures.empty()) { 7988 SmallVector<Decl *, 16> PreInits; 7989 for (const auto &Pair : Captures) 7990 PreInits.push_back(Pair.second->getDecl()); 7991 return buildPreInits(Context, PreInits); 7992 } 7993 return nullptr; 7994 } 7995 7996 /// Build postupdate expression for the given list of postupdates expressions. 7997 static Expr *buildPostUpdate(Sema &S, ArrayRef<Expr *> PostUpdates) { 7998 Expr *PostUpdate = nullptr; 7999 if (!PostUpdates.empty()) { 8000 for (Expr *E : PostUpdates) { 8001 Expr *ConvE = S.BuildCStyleCastExpr( 8002 E->getExprLoc(), 8003 S.Context.getTrivialTypeSourceInfo(S.Context.VoidTy), 8004 E->getExprLoc(), E) 8005 .get(); 8006 PostUpdate = PostUpdate 8007 ? S.CreateBuiltinBinOp(ConvE->getExprLoc(), BO_Comma, 8008 PostUpdate, ConvE) 8009 .get() 8010 : ConvE; 8011 } 8012 } 8013 return PostUpdate; 8014 } 8015 8016 /// Called on a for stmt to check itself and nested loops (if any). 8017 /// \return Returns 0 if one of the collapsed stmts is not canonical for loop, 8018 /// number of collapsed loops otherwise. 8019 static unsigned 8020 checkOpenMPLoop(OpenMPDirectiveKind DKind, Expr *CollapseLoopCountExpr, 8021 Expr *OrderedLoopCountExpr, Stmt *AStmt, Sema &SemaRef, 8022 DSAStackTy &DSA, 8023 Sema::VarsWithInheritedDSAType &VarsWithImplicitDSA, 8024 OMPLoopDirective::HelperExprs &Built) { 8025 unsigned NestedLoopCount = 1; 8026 if (CollapseLoopCountExpr) { 8027 // Found 'collapse' clause - calculate collapse number. 8028 Expr::EvalResult Result; 8029 if (!CollapseLoopCountExpr->isValueDependent() && 8030 CollapseLoopCountExpr->EvaluateAsInt(Result, SemaRef.getASTContext())) { 8031 NestedLoopCount = Result.Val.getInt().getLimitedValue(); 8032 } else { 8033 Built.clear(/*Size=*/1); 8034 return 1; 8035 } 8036 } 8037 unsigned OrderedLoopCount = 1; 8038 if (OrderedLoopCountExpr) { 8039 // Found 'ordered' clause - calculate collapse number. 8040 Expr::EvalResult EVResult; 8041 if (!OrderedLoopCountExpr->isValueDependent() && 8042 OrderedLoopCountExpr->EvaluateAsInt(EVResult, 8043 SemaRef.getASTContext())) { 8044 llvm::APSInt Result = EVResult.Val.getInt(); 8045 if (Result.getLimitedValue() < NestedLoopCount) { 8046 SemaRef.Diag(OrderedLoopCountExpr->getExprLoc(), 8047 diag::err_omp_wrong_ordered_loop_count) 8048 << OrderedLoopCountExpr->getSourceRange(); 8049 SemaRef.Diag(CollapseLoopCountExpr->getExprLoc(), 8050 diag::note_collapse_loop_count) 8051 << CollapseLoopCountExpr->getSourceRange(); 8052 } 8053 OrderedLoopCount = Result.getLimitedValue(); 8054 } else { 8055 Built.clear(/*Size=*/1); 8056 return 1; 8057 } 8058 } 8059 // This is helper routine for loop directives (e.g., 'for', 'simd', 8060 // 'for simd', etc.). 8061 llvm::MapVector<const Expr *, DeclRefExpr *> Captures; 8062 SmallVector<LoopIterationSpace, 4> IterSpaces( 8063 std::max(OrderedLoopCount, NestedLoopCount)); 8064 Stmt *CurStmt = AStmt->IgnoreContainers(/* IgnoreCaptured */ true); 8065 for (unsigned Cnt = 0; Cnt < NestedLoopCount; ++Cnt) { 8066 if (checkOpenMPIterationSpace( 8067 DKind, CurStmt, SemaRef, DSA, Cnt, NestedLoopCount, 8068 std::max(OrderedLoopCount, NestedLoopCount), CollapseLoopCountExpr, 8069 OrderedLoopCountExpr, VarsWithImplicitDSA, IterSpaces, Captures)) 8070 return 0; 8071 // Move on to the next nested for loop, or to the loop body. 8072 // OpenMP [2.8.1, simd construct, Restrictions] 8073 // All loops associated with the construct must be perfectly nested; that 8074 // is, there must be no intervening code nor any OpenMP directive between 8075 // any two loops. 8076 if (auto *For = dyn_cast<ForStmt>(CurStmt)) { 8077 CurStmt = For->getBody(); 8078 } else { 8079 assert(isa<CXXForRangeStmt>(CurStmt) && 8080 "Expected canonical for or range-based for loops."); 8081 CurStmt = cast<CXXForRangeStmt>(CurStmt)->getBody(); 8082 } 8083 CurStmt = OMPLoopDirective::tryToFindNextInnerLoop( 8084 CurStmt, SemaRef.LangOpts.OpenMP >= 50); 8085 } 8086 for (unsigned Cnt = NestedLoopCount; Cnt < OrderedLoopCount; ++Cnt) { 8087 if (checkOpenMPIterationSpace( 8088 DKind, CurStmt, SemaRef, DSA, Cnt, NestedLoopCount, 8089 std::max(OrderedLoopCount, NestedLoopCount), CollapseLoopCountExpr, 8090 OrderedLoopCountExpr, VarsWithImplicitDSA, IterSpaces, Captures)) 8091 return 0; 8092 if (Cnt > 0 && IterSpaces[Cnt].CounterVar) { 8093 // Handle initialization of captured loop iterator variables. 8094 auto *DRE = cast<DeclRefExpr>(IterSpaces[Cnt].CounterVar); 8095 if (isa<OMPCapturedExprDecl>(DRE->getDecl())) { 8096 Captures[DRE] = DRE; 8097 } 8098 } 8099 // Move on to the next nested for loop, or to the loop body. 8100 // OpenMP [2.8.1, simd construct, Restrictions] 8101 // All loops associated with the construct must be perfectly nested; that 8102 // is, there must be no intervening code nor any OpenMP directive between 8103 // any two loops. 8104 if (auto *For = dyn_cast<ForStmt>(CurStmt)) { 8105 CurStmt = For->getBody(); 8106 } else { 8107 assert(isa<CXXForRangeStmt>(CurStmt) && 8108 "Expected canonical for or range-based for loops."); 8109 CurStmt = cast<CXXForRangeStmt>(CurStmt)->getBody(); 8110 } 8111 CurStmt = OMPLoopDirective::tryToFindNextInnerLoop( 8112 CurStmt, SemaRef.LangOpts.OpenMP >= 50); 8113 } 8114 8115 Built.clear(/* size */ NestedLoopCount); 8116 8117 if (SemaRef.CurContext->isDependentContext()) 8118 return NestedLoopCount; 8119 8120 // An example of what is generated for the following code: 8121 // 8122 // #pragma omp simd collapse(2) ordered(2) 8123 // for (i = 0; i < NI; ++i) 8124 // for (k = 0; k < NK; ++k) 8125 // for (j = J0; j < NJ; j+=2) { 8126 // <loop body> 8127 // } 8128 // 8129 // We generate the code below. 8130 // Note: the loop body may be outlined in CodeGen. 8131 // Note: some counters may be C++ classes, operator- is used to find number of 8132 // iterations and operator+= to calculate counter value. 8133 // Note: decltype(NumIterations) must be integer type (in 'omp for', only i32 8134 // or i64 is currently supported). 8135 // 8136 // #define NumIterations (NI * ((NJ - J0 - 1 + 2) / 2)) 8137 // for (int[32|64]_t IV = 0; IV < NumIterations; ++IV ) { 8138 // .local.i = IV / ((NJ - J0 - 1 + 2) / 2); 8139 // .local.j = J0 + (IV % ((NJ - J0 - 1 + 2) / 2)) * 2; 8140 // // similar updates for vars in clauses (e.g. 'linear') 8141 // <loop body (using local i and j)> 8142 // } 8143 // i = NI; // assign final values of counters 8144 // j = NJ; 8145 // 8146 8147 // Last iteration number is (I1 * I2 * ... In) - 1, where I1, I2 ... In are 8148 // the iteration counts of the collapsed for loops. 8149 // Precondition tests if there is at least one iteration (all conditions are 8150 // true). 8151 auto PreCond = ExprResult(IterSpaces[0].PreCond); 8152 Expr *N0 = IterSpaces[0].NumIterations; 8153 ExprResult LastIteration32 = 8154 widenIterationCount(/*Bits=*/32, 8155 SemaRef 8156 .PerformImplicitConversion( 8157 N0->IgnoreImpCasts(), N0->getType(), 8158 Sema::AA_Converting, /*AllowExplicit=*/true) 8159 .get(), 8160 SemaRef); 8161 ExprResult LastIteration64 = widenIterationCount( 8162 /*Bits=*/64, 8163 SemaRef 8164 .PerformImplicitConversion(N0->IgnoreImpCasts(), N0->getType(), 8165 Sema::AA_Converting, 8166 /*AllowExplicit=*/true) 8167 .get(), 8168 SemaRef); 8169 8170 if (!LastIteration32.isUsable() || !LastIteration64.isUsable()) 8171 return NestedLoopCount; 8172 8173 ASTContext &C = SemaRef.Context; 8174 bool AllCountsNeedLessThan32Bits = C.getTypeSize(N0->getType()) < 32; 8175 8176 Scope *CurScope = DSA.getCurScope(); 8177 for (unsigned Cnt = 1; Cnt < NestedLoopCount; ++Cnt) { 8178 if (PreCond.isUsable()) { 8179 PreCond = 8180 SemaRef.BuildBinOp(CurScope, PreCond.get()->getExprLoc(), BO_LAnd, 8181 PreCond.get(), IterSpaces[Cnt].PreCond); 8182 } 8183 Expr *N = IterSpaces[Cnt].NumIterations; 8184 SourceLocation Loc = N->getExprLoc(); 8185 AllCountsNeedLessThan32Bits &= C.getTypeSize(N->getType()) < 32; 8186 if (LastIteration32.isUsable()) 8187 LastIteration32 = SemaRef.BuildBinOp( 8188 CurScope, Loc, BO_Mul, LastIteration32.get(), 8189 SemaRef 8190 .PerformImplicitConversion(N->IgnoreImpCasts(), N->getType(), 8191 Sema::AA_Converting, 8192 /*AllowExplicit=*/true) 8193 .get()); 8194 if (LastIteration64.isUsable()) 8195 LastIteration64 = SemaRef.BuildBinOp( 8196 CurScope, Loc, BO_Mul, LastIteration64.get(), 8197 SemaRef 8198 .PerformImplicitConversion(N->IgnoreImpCasts(), N->getType(), 8199 Sema::AA_Converting, 8200 /*AllowExplicit=*/true) 8201 .get()); 8202 } 8203 8204 // Choose either the 32-bit or 64-bit version. 8205 ExprResult LastIteration = LastIteration64; 8206 if (SemaRef.getLangOpts().OpenMPOptimisticCollapse || 8207 (LastIteration32.isUsable() && 8208 C.getTypeSize(LastIteration32.get()->getType()) == 32 && 8209 (AllCountsNeedLessThan32Bits || NestedLoopCount == 1 || 8210 fitsInto( 8211 /*Bits=*/32, 8212 LastIteration32.get()->getType()->hasSignedIntegerRepresentation(), 8213 LastIteration64.get(), SemaRef)))) 8214 LastIteration = LastIteration32; 8215 QualType VType = LastIteration.get()->getType(); 8216 QualType RealVType = VType; 8217 QualType StrideVType = VType; 8218 if (isOpenMPTaskLoopDirective(DKind)) { 8219 VType = 8220 SemaRef.Context.getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/0); 8221 StrideVType = 8222 SemaRef.Context.getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/1); 8223 } 8224 8225 if (!LastIteration.isUsable()) 8226 return 0; 8227 8228 // Save the number of iterations. 8229 ExprResult NumIterations = LastIteration; 8230 { 8231 LastIteration = SemaRef.BuildBinOp( 8232 CurScope, LastIteration.get()->getExprLoc(), BO_Sub, 8233 LastIteration.get(), 8234 SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get()); 8235 if (!LastIteration.isUsable()) 8236 return 0; 8237 } 8238 8239 // Calculate the last iteration number beforehand instead of doing this on 8240 // each iteration. Do not do this if the number of iterations may be kfold-ed. 8241 bool IsConstant = LastIteration.get()->isIntegerConstantExpr(SemaRef.Context); 8242 ExprResult CalcLastIteration; 8243 if (!IsConstant) { 8244 ExprResult SaveRef = 8245 tryBuildCapture(SemaRef, LastIteration.get(), Captures); 8246 LastIteration = SaveRef; 8247 8248 // Prepare SaveRef + 1. 8249 NumIterations = SemaRef.BuildBinOp( 8250 CurScope, SaveRef.get()->getExprLoc(), BO_Add, SaveRef.get(), 8251 SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get()); 8252 if (!NumIterations.isUsable()) 8253 return 0; 8254 } 8255 8256 SourceLocation InitLoc = IterSpaces[0].InitSrcRange.getBegin(); 8257 8258 // Build variables passed into runtime, necessary for worksharing directives. 8259 ExprResult LB, UB, IL, ST, EUB, CombLB, CombUB, PrevLB, PrevUB, CombEUB; 8260 if (isOpenMPWorksharingDirective(DKind) || isOpenMPTaskLoopDirective(DKind) || 8261 isOpenMPDistributeDirective(DKind)) { 8262 // Lower bound variable, initialized with zero. 8263 VarDecl *LBDecl = buildVarDecl(SemaRef, InitLoc, VType, ".omp.lb"); 8264 LB = buildDeclRefExpr(SemaRef, LBDecl, VType, InitLoc); 8265 SemaRef.AddInitializerToDecl(LBDecl, 8266 SemaRef.ActOnIntegerConstant(InitLoc, 0).get(), 8267 /*DirectInit*/ false); 8268 8269 // Upper bound variable, initialized with last iteration number. 8270 VarDecl *UBDecl = buildVarDecl(SemaRef, InitLoc, VType, ".omp.ub"); 8271 UB = buildDeclRefExpr(SemaRef, UBDecl, VType, InitLoc); 8272 SemaRef.AddInitializerToDecl(UBDecl, LastIteration.get(), 8273 /*DirectInit*/ false); 8274 8275 // A 32-bit variable-flag where runtime returns 1 for the last iteration. 8276 // This will be used to implement clause 'lastprivate'. 8277 QualType Int32Ty = SemaRef.Context.getIntTypeForBitwidth(32, true); 8278 VarDecl *ILDecl = buildVarDecl(SemaRef, InitLoc, Int32Ty, ".omp.is_last"); 8279 IL = buildDeclRefExpr(SemaRef, ILDecl, Int32Ty, InitLoc); 8280 SemaRef.AddInitializerToDecl(ILDecl, 8281 SemaRef.ActOnIntegerConstant(InitLoc, 0).get(), 8282 /*DirectInit*/ false); 8283 8284 // Stride variable returned by runtime (we initialize it to 1 by default). 8285 VarDecl *STDecl = 8286 buildVarDecl(SemaRef, InitLoc, StrideVType, ".omp.stride"); 8287 ST = buildDeclRefExpr(SemaRef, STDecl, StrideVType, InitLoc); 8288 SemaRef.AddInitializerToDecl(STDecl, 8289 SemaRef.ActOnIntegerConstant(InitLoc, 1).get(), 8290 /*DirectInit*/ false); 8291 8292 // Build expression: UB = min(UB, LastIteration) 8293 // It is necessary for CodeGen of directives with static scheduling. 8294 ExprResult IsUBGreater = SemaRef.BuildBinOp(CurScope, InitLoc, BO_GT, 8295 UB.get(), LastIteration.get()); 8296 ExprResult CondOp = SemaRef.ActOnConditionalOp( 8297 LastIteration.get()->getExprLoc(), InitLoc, IsUBGreater.get(), 8298 LastIteration.get(), UB.get()); 8299 EUB = SemaRef.BuildBinOp(CurScope, InitLoc, BO_Assign, UB.get(), 8300 CondOp.get()); 8301 EUB = SemaRef.ActOnFinishFullExpr(EUB.get(), /*DiscardedValue*/ false); 8302 8303 // If we have a combined directive that combines 'distribute', 'for' or 8304 // 'simd' we need to be able to access the bounds of the schedule of the 8305 // enclosing region. E.g. in 'distribute parallel for' the bounds obtained 8306 // by scheduling 'distribute' have to be passed to the schedule of 'for'. 8307 if (isOpenMPLoopBoundSharingDirective(DKind)) { 8308 // Lower bound variable, initialized with zero. 8309 VarDecl *CombLBDecl = 8310 buildVarDecl(SemaRef, InitLoc, VType, ".omp.comb.lb"); 8311 CombLB = buildDeclRefExpr(SemaRef, CombLBDecl, VType, InitLoc); 8312 SemaRef.AddInitializerToDecl( 8313 CombLBDecl, SemaRef.ActOnIntegerConstant(InitLoc, 0).get(), 8314 /*DirectInit*/ false); 8315 8316 // Upper bound variable, initialized with last iteration number. 8317 VarDecl *CombUBDecl = 8318 buildVarDecl(SemaRef, InitLoc, VType, ".omp.comb.ub"); 8319 CombUB = buildDeclRefExpr(SemaRef, CombUBDecl, VType, InitLoc); 8320 SemaRef.AddInitializerToDecl(CombUBDecl, LastIteration.get(), 8321 /*DirectInit*/ false); 8322 8323 ExprResult CombIsUBGreater = SemaRef.BuildBinOp( 8324 CurScope, InitLoc, BO_GT, CombUB.get(), LastIteration.get()); 8325 ExprResult CombCondOp = 8326 SemaRef.ActOnConditionalOp(InitLoc, InitLoc, CombIsUBGreater.get(), 8327 LastIteration.get(), CombUB.get()); 8328 CombEUB = SemaRef.BuildBinOp(CurScope, InitLoc, BO_Assign, CombUB.get(), 8329 CombCondOp.get()); 8330 CombEUB = 8331 SemaRef.ActOnFinishFullExpr(CombEUB.get(), /*DiscardedValue*/ false); 8332 8333 const CapturedDecl *CD = cast<CapturedStmt>(AStmt)->getCapturedDecl(); 8334 // We expect to have at least 2 more parameters than the 'parallel' 8335 // directive does - the lower and upper bounds of the previous schedule. 8336 assert(CD->getNumParams() >= 4 && 8337 "Unexpected number of parameters in loop combined directive"); 8338 8339 // Set the proper type for the bounds given what we learned from the 8340 // enclosed loops. 8341 ImplicitParamDecl *PrevLBDecl = CD->getParam(/*PrevLB=*/2); 8342 ImplicitParamDecl *PrevUBDecl = CD->getParam(/*PrevUB=*/3); 8343 8344 // Previous lower and upper bounds are obtained from the region 8345 // parameters. 8346 PrevLB = 8347 buildDeclRefExpr(SemaRef, PrevLBDecl, PrevLBDecl->getType(), InitLoc); 8348 PrevUB = 8349 buildDeclRefExpr(SemaRef, PrevUBDecl, PrevUBDecl->getType(), InitLoc); 8350 } 8351 } 8352 8353 // Build the iteration variable and its initialization before loop. 8354 ExprResult IV; 8355 ExprResult Init, CombInit; 8356 { 8357 VarDecl *IVDecl = buildVarDecl(SemaRef, InitLoc, RealVType, ".omp.iv"); 8358 IV = buildDeclRefExpr(SemaRef, IVDecl, RealVType, InitLoc); 8359 Expr *RHS = 8360 (isOpenMPWorksharingDirective(DKind) || 8361 isOpenMPTaskLoopDirective(DKind) || isOpenMPDistributeDirective(DKind)) 8362 ? LB.get() 8363 : SemaRef.ActOnIntegerConstant(SourceLocation(), 0).get(); 8364 Init = SemaRef.BuildBinOp(CurScope, InitLoc, BO_Assign, IV.get(), RHS); 8365 Init = SemaRef.ActOnFinishFullExpr(Init.get(), /*DiscardedValue*/ false); 8366 8367 if (isOpenMPLoopBoundSharingDirective(DKind)) { 8368 Expr *CombRHS = 8369 (isOpenMPWorksharingDirective(DKind) || 8370 isOpenMPTaskLoopDirective(DKind) || 8371 isOpenMPDistributeDirective(DKind)) 8372 ? CombLB.get() 8373 : SemaRef.ActOnIntegerConstant(SourceLocation(), 0).get(); 8374 CombInit = 8375 SemaRef.BuildBinOp(CurScope, InitLoc, BO_Assign, IV.get(), CombRHS); 8376 CombInit = 8377 SemaRef.ActOnFinishFullExpr(CombInit.get(), /*DiscardedValue*/ false); 8378 } 8379 } 8380 8381 bool UseStrictCompare = 8382 RealVType->hasUnsignedIntegerRepresentation() && 8383 llvm::all_of(IterSpaces, [](const LoopIterationSpace &LIS) { 8384 return LIS.IsStrictCompare; 8385 }); 8386 // Loop condition (IV < NumIterations) or (IV <= UB or IV < UB + 1 (for 8387 // unsigned IV)) for worksharing loops. 8388 SourceLocation CondLoc = AStmt->getBeginLoc(); 8389 Expr *BoundUB = UB.get(); 8390 if (UseStrictCompare) { 8391 BoundUB = 8392 SemaRef 8393 .BuildBinOp(CurScope, CondLoc, BO_Add, BoundUB, 8394 SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get()) 8395 .get(); 8396 BoundUB = 8397 SemaRef.ActOnFinishFullExpr(BoundUB, /*DiscardedValue*/ false).get(); 8398 } 8399 ExprResult Cond = 8400 (isOpenMPWorksharingDirective(DKind) || 8401 isOpenMPTaskLoopDirective(DKind) || isOpenMPDistributeDirective(DKind)) 8402 ? SemaRef.BuildBinOp(CurScope, CondLoc, 8403 UseStrictCompare ? BO_LT : BO_LE, IV.get(), 8404 BoundUB) 8405 : SemaRef.BuildBinOp(CurScope, CondLoc, BO_LT, IV.get(), 8406 NumIterations.get()); 8407 ExprResult CombDistCond; 8408 if (isOpenMPLoopBoundSharingDirective(DKind)) { 8409 CombDistCond = SemaRef.BuildBinOp(CurScope, CondLoc, BO_LT, IV.get(), 8410 NumIterations.get()); 8411 } 8412 8413 ExprResult CombCond; 8414 if (isOpenMPLoopBoundSharingDirective(DKind)) { 8415 Expr *BoundCombUB = CombUB.get(); 8416 if (UseStrictCompare) { 8417 BoundCombUB = 8418 SemaRef 8419 .BuildBinOp( 8420 CurScope, CondLoc, BO_Add, BoundCombUB, 8421 SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get()) 8422 .get(); 8423 BoundCombUB = 8424 SemaRef.ActOnFinishFullExpr(BoundCombUB, /*DiscardedValue*/ false) 8425 .get(); 8426 } 8427 CombCond = 8428 SemaRef.BuildBinOp(CurScope, CondLoc, UseStrictCompare ? BO_LT : BO_LE, 8429 IV.get(), BoundCombUB); 8430 } 8431 // Loop increment (IV = IV + 1) 8432 SourceLocation IncLoc = AStmt->getBeginLoc(); 8433 ExprResult Inc = 8434 SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, IV.get(), 8435 SemaRef.ActOnIntegerConstant(IncLoc, 1).get()); 8436 if (!Inc.isUsable()) 8437 return 0; 8438 Inc = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, IV.get(), Inc.get()); 8439 Inc = SemaRef.ActOnFinishFullExpr(Inc.get(), /*DiscardedValue*/ false); 8440 if (!Inc.isUsable()) 8441 return 0; 8442 8443 // Increments for worksharing loops (LB = LB + ST; UB = UB + ST). 8444 // Used for directives with static scheduling. 8445 // In combined construct, add combined version that use CombLB and CombUB 8446 // base variables for the update 8447 ExprResult NextLB, NextUB, CombNextLB, CombNextUB; 8448 if (isOpenMPWorksharingDirective(DKind) || isOpenMPTaskLoopDirective(DKind) || 8449 isOpenMPDistributeDirective(DKind)) { 8450 // LB + ST 8451 NextLB = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, LB.get(), ST.get()); 8452 if (!NextLB.isUsable()) 8453 return 0; 8454 // LB = LB + ST 8455 NextLB = 8456 SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, LB.get(), NextLB.get()); 8457 NextLB = 8458 SemaRef.ActOnFinishFullExpr(NextLB.get(), /*DiscardedValue*/ false); 8459 if (!NextLB.isUsable()) 8460 return 0; 8461 // UB + ST 8462 NextUB = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, UB.get(), ST.get()); 8463 if (!NextUB.isUsable()) 8464 return 0; 8465 // UB = UB + ST 8466 NextUB = 8467 SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, UB.get(), NextUB.get()); 8468 NextUB = 8469 SemaRef.ActOnFinishFullExpr(NextUB.get(), /*DiscardedValue*/ false); 8470 if (!NextUB.isUsable()) 8471 return 0; 8472 if (isOpenMPLoopBoundSharingDirective(DKind)) { 8473 CombNextLB = 8474 SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, CombLB.get(), ST.get()); 8475 if (!NextLB.isUsable()) 8476 return 0; 8477 // LB = LB + ST 8478 CombNextLB = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, CombLB.get(), 8479 CombNextLB.get()); 8480 CombNextLB = SemaRef.ActOnFinishFullExpr(CombNextLB.get(), 8481 /*DiscardedValue*/ false); 8482 if (!CombNextLB.isUsable()) 8483 return 0; 8484 // UB + ST 8485 CombNextUB = 8486 SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, CombUB.get(), ST.get()); 8487 if (!CombNextUB.isUsable()) 8488 return 0; 8489 // UB = UB + ST 8490 CombNextUB = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, CombUB.get(), 8491 CombNextUB.get()); 8492 CombNextUB = SemaRef.ActOnFinishFullExpr(CombNextUB.get(), 8493 /*DiscardedValue*/ false); 8494 if (!CombNextUB.isUsable()) 8495 return 0; 8496 } 8497 } 8498 8499 // Create increment expression for distribute loop when combined in a same 8500 // directive with for as IV = IV + ST; ensure upper bound expression based 8501 // on PrevUB instead of NumIterations - used to implement 'for' when found 8502 // in combination with 'distribute', like in 'distribute parallel for' 8503 SourceLocation DistIncLoc = AStmt->getBeginLoc(); 8504 ExprResult DistCond, DistInc, PrevEUB, ParForInDistCond; 8505 if (isOpenMPLoopBoundSharingDirective(DKind)) { 8506 DistCond = SemaRef.BuildBinOp( 8507 CurScope, CondLoc, UseStrictCompare ? BO_LT : BO_LE, IV.get(), BoundUB); 8508 assert(DistCond.isUsable() && "distribute cond expr was not built"); 8509 8510 DistInc = 8511 SemaRef.BuildBinOp(CurScope, DistIncLoc, BO_Add, IV.get(), ST.get()); 8512 assert(DistInc.isUsable() && "distribute inc expr was not built"); 8513 DistInc = SemaRef.BuildBinOp(CurScope, DistIncLoc, BO_Assign, IV.get(), 8514 DistInc.get()); 8515 DistInc = 8516 SemaRef.ActOnFinishFullExpr(DistInc.get(), /*DiscardedValue*/ false); 8517 assert(DistInc.isUsable() && "distribute inc expr was not built"); 8518 8519 // Build expression: UB = min(UB, prevUB) for #for in composite or combined 8520 // construct 8521 SourceLocation DistEUBLoc = AStmt->getBeginLoc(); 8522 ExprResult IsUBGreater = 8523 SemaRef.BuildBinOp(CurScope, DistEUBLoc, BO_GT, UB.get(), PrevUB.get()); 8524 ExprResult CondOp = SemaRef.ActOnConditionalOp( 8525 DistEUBLoc, DistEUBLoc, IsUBGreater.get(), PrevUB.get(), UB.get()); 8526 PrevEUB = SemaRef.BuildBinOp(CurScope, DistIncLoc, BO_Assign, UB.get(), 8527 CondOp.get()); 8528 PrevEUB = 8529 SemaRef.ActOnFinishFullExpr(PrevEUB.get(), /*DiscardedValue*/ false); 8530 8531 // Build IV <= PrevUB or IV < PrevUB + 1 for unsigned IV to be used in 8532 // parallel for is in combination with a distribute directive with 8533 // schedule(static, 1) 8534 Expr *BoundPrevUB = PrevUB.get(); 8535 if (UseStrictCompare) { 8536 BoundPrevUB = 8537 SemaRef 8538 .BuildBinOp( 8539 CurScope, CondLoc, BO_Add, BoundPrevUB, 8540 SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get()) 8541 .get(); 8542 BoundPrevUB = 8543 SemaRef.ActOnFinishFullExpr(BoundPrevUB, /*DiscardedValue*/ false) 8544 .get(); 8545 } 8546 ParForInDistCond = 8547 SemaRef.BuildBinOp(CurScope, CondLoc, UseStrictCompare ? BO_LT : BO_LE, 8548 IV.get(), BoundPrevUB); 8549 } 8550 8551 // Build updates and final values of the loop counters. 8552 bool HasErrors = false; 8553 Built.Counters.resize(NestedLoopCount); 8554 Built.Inits.resize(NestedLoopCount); 8555 Built.Updates.resize(NestedLoopCount); 8556 Built.Finals.resize(NestedLoopCount); 8557 Built.DependentCounters.resize(NestedLoopCount); 8558 Built.DependentInits.resize(NestedLoopCount); 8559 Built.FinalsConditions.resize(NestedLoopCount); 8560 { 8561 // We implement the following algorithm for obtaining the 8562 // original loop iteration variable values based on the 8563 // value of the collapsed loop iteration variable IV. 8564 // 8565 // Let n+1 be the number of collapsed loops in the nest. 8566 // Iteration variables (I0, I1, .... In) 8567 // Iteration counts (N0, N1, ... Nn) 8568 // 8569 // Acc = IV; 8570 // 8571 // To compute Ik for loop k, 0 <= k <= n, generate: 8572 // Prod = N(k+1) * N(k+2) * ... * Nn; 8573 // Ik = Acc / Prod; 8574 // Acc -= Ik * Prod; 8575 // 8576 ExprResult Acc = IV; 8577 for (unsigned int Cnt = 0; Cnt < NestedLoopCount; ++Cnt) { 8578 LoopIterationSpace &IS = IterSpaces[Cnt]; 8579 SourceLocation UpdLoc = IS.IncSrcRange.getBegin(); 8580 ExprResult Iter; 8581 8582 // Compute prod 8583 ExprResult Prod = 8584 SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get(); 8585 for (unsigned int K = Cnt+1; K < NestedLoopCount; ++K) 8586 Prod = SemaRef.BuildBinOp(CurScope, UpdLoc, BO_Mul, Prod.get(), 8587 IterSpaces[K].NumIterations); 8588 8589 // Iter = Acc / Prod 8590 // If there is at least one more inner loop to avoid 8591 // multiplication by 1. 8592 if (Cnt + 1 < NestedLoopCount) 8593 Iter = SemaRef.BuildBinOp(CurScope, UpdLoc, BO_Div, 8594 Acc.get(), Prod.get()); 8595 else 8596 Iter = Acc; 8597 if (!Iter.isUsable()) { 8598 HasErrors = true; 8599 break; 8600 } 8601 8602 // Update Acc: 8603 // Acc -= Iter * Prod 8604 // Check if there is at least one more inner loop to avoid 8605 // multiplication by 1. 8606 if (Cnt + 1 < NestedLoopCount) 8607 Prod = SemaRef.BuildBinOp(CurScope, UpdLoc, BO_Mul, 8608 Iter.get(), Prod.get()); 8609 else 8610 Prod = Iter; 8611 Acc = SemaRef.BuildBinOp(CurScope, UpdLoc, BO_Sub, 8612 Acc.get(), Prod.get()); 8613 8614 // Build update: IS.CounterVar(Private) = IS.Start + Iter * IS.Step 8615 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(IS.CounterVar)->getDecl()); 8616 DeclRefExpr *CounterVar = buildDeclRefExpr( 8617 SemaRef, VD, IS.CounterVar->getType(), IS.CounterVar->getExprLoc(), 8618 /*RefersToCapture=*/true); 8619 ExprResult Init = 8620 buildCounterInit(SemaRef, CurScope, UpdLoc, CounterVar, 8621 IS.CounterInit, IS.IsNonRectangularLB, Captures); 8622 if (!Init.isUsable()) { 8623 HasErrors = true; 8624 break; 8625 } 8626 ExprResult Update = buildCounterUpdate( 8627 SemaRef, CurScope, UpdLoc, CounterVar, IS.CounterInit, Iter, 8628 IS.CounterStep, IS.Subtract, IS.IsNonRectangularLB, &Captures); 8629 if (!Update.isUsable()) { 8630 HasErrors = true; 8631 break; 8632 } 8633 8634 // Build final: IS.CounterVar = IS.Start + IS.NumIters * IS.Step 8635 ExprResult Final = 8636 buildCounterUpdate(SemaRef, CurScope, UpdLoc, CounterVar, 8637 IS.CounterInit, IS.NumIterations, IS.CounterStep, 8638 IS.Subtract, IS.IsNonRectangularLB, &Captures); 8639 if (!Final.isUsable()) { 8640 HasErrors = true; 8641 break; 8642 } 8643 8644 if (!Update.isUsable() || !Final.isUsable()) { 8645 HasErrors = true; 8646 break; 8647 } 8648 // Save results 8649 Built.Counters[Cnt] = IS.CounterVar; 8650 Built.PrivateCounters[Cnt] = IS.PrivateCounterVar; 8651 Built.Inits[Cnt] = Init.get(); 8652 Built.Updates[Cnt] = Update.get(); 8653 Built.Finals[Cnt] = Final.get(); 8654 Built.DependentCounters[Cnt] = nullptr; 8655 Built.DependentInits[Cnt] = nullptr; 8656 Built.FinalsConditions[Cnt] = nullptr; 8657 if (IS.IsNonRectangularLB || IS.IsNonRectangularUB) { 8658 Built.DependentCounters[Cnt] = 8659 Built.Counters[NestedLoopCount - 1 - IS.LoopDependentIdx]; 8660 Built.DependentInits[Cnt] = 8661 Built.Inits[NestedLoopCount - 1 - IS.LoopDependentIdx]; 8662 Built.FinalsConditions[Cnt] = IS.FinalCondition; 8663 } 8664 } 8665 } 8666 8667 if (HasErrors) 8668 return 0; 8669 8670 // Save results 8671 Built.IterationVarRef = IV.get(); 8672 Built.LastIteration = LastIteration.get(); 8673 Built.NumIterations = NumIterations.get(); 8674 Built.CalcLastIteration = SemaRef 8675 .ActOnFinishFullExpr(CalcLastIteration.get(), 8676 /*DiscardedValue=*/false) 8677 .get(); 8678 Built.PreCond = PreCond.get(); 8679 Built.PreInits = buildPreInits(C, Captures); 8680 Built.Cond = Cond.get(); 8681 Built.Init = Init.get(); 8682 Built.Inc = Inc.get(); 8683 Built.LB = LB.get(); 8684 Built.UB = UB.get(); 8685 Built.IL = IL.get(); 8686 Built.ST = ST.get(); 8687 Built.EUB = EUB.get(); 8688 Built.NLB = NextLB.get(); 8689 Built.NUB = NextUB.get(); 8690 Built.PrevLB = PrevLB.get(); 8691 Built.PrevUB = PrevUB.get(); 8692 Built.DistInc = DistInc.get(); 8693 Built.PrevEUB = PrevEUB.get(); 8694 Built.DistCombinedFields.LB = CombLB.get(); 8695 Built.DistCombinedFields.UB = CombUB.get(); 8696 Built.DistCombinedFields.EUB = CombEUB.get(); 8697 Built.DistCombinedFields.Init = CombInit.get(); 8698 Built.DistCombinedFields.Cond = CombCond.get(); 8699 Built.DistCombinedFields.NLB = CombNextLB.get(); 8700 Built.DistCombinedFields.NUB = CombNextUB.get(); 8701 Built.DistCombinedFields.DistCond = CombDistCond.get(); 8702 Built.DistCombinedFields.ParForInDistCond = ParForInDistCond.get(); 8703 8704 return NestedLoopCount; 8705 } 8706 8707 static Expr *getCollapseNumberExpr(ArrayRef<OMPClause *> Clauses) { 8708 auto CollapseClauses = 8709 OMPExecutableDirective::getClausesOfKind<OMPCollapseClause>(Clauses); 8710 if (CollapseClauses.begin() != CollapseClauses.end()) 8711 return (*CollapseClauses.begin())->getNumForLoops(); 8712 return nullptr; 8713 } 8714 8715 static Expr *getOrderedNumberExpr(ArrayRef<OMPClause *> Clauses) { 8716 auto OrderedClauses = 8717 OMPExecutableDirective::getClausesOfKind<OMPOrderedClause>(Clauses); 8718 if (OrderedClauses.begin() != OrderedClauses.end()) 8719 return (*OrderedClauses.begin())->getNumForLoops(); 8720 return nullptr; 8721 } 8722 8723 static bool checkSimdlenSafelenSpecified(Sema &S, 8724 const ArrayRef<OMPClause *> Clauses) { 8725 const OMPSafelenClause *Safelen = nullptr; 8726 const OMPSimdlenClause *Simdlen = nullptr; 8727 8728 for (const OMPClause *Clause : Clauses) { 8729 if (Clause->getClauseKind() == OMPC_safelen) 8730 Safelen = cast<OMPSafelenClause>(Clause); 8731 else if (Clause->getClauseKind() == OMPC_simdlen) 8732 Simdlen = cast<OMPSimdlenClause>(Clause); 8733 if (Safelen && Simdlen) 8734 break; 8735 } 8736 8737 if (Simdlen && Safelen) { 8738 const Expr *SimdlenLength = Simdlen->getSimdlen(); 8739 const Expr *SafelenLength = Safelen->getSafelen(); 8740 if (SimdlenLength->isValueDependent() || SimdlenLength->isTypeDependent() || 8741 SimdlenLength->isInstantiationDependent() || 8742 SimdlenLength->containsUnexpandedParameterPack()) 8743 return false; 8744 if (SafelenLength->isValueDependent() || SafelenLength->isTypeDependent() || 8745 SafelenLength->isInstantiationDependent() || 8746 SafelenLength->containsUnexpandedParameterPack()) 8747 return false; 8748 Expr::EvalResult SimdlenResult, SafelenResult; 8749 SimdlenLength->EvaluateAsInt(SimdlenResult, S.Context); 8750 SafelenLength->EvaluateAsInt(SafelenResult, S.Context); 8751 llvm::APSInt SimdlenRes = SimdlenResult.Val.getInt(); 8752 llvm::APSInt SafelenRes = SafelenResult.Val.getInt(); 8753 // OpenMP 4.5 [2.8.1, simd Construct, Restrictions] 8754 // If both simdlen and safelen clauses are specified, the value of the 8755 // simdlen parameter must be less than or equal to the value of the safelen 8756 // parameter. 8757 if (SimdlenRes > SafelenRes) { 8758 S.Diag(SimdlenLength->getExprLoc(), 8759 diag::err_omp_wrong_simdlen_safelen_values) 8760 << SimdlenLength->getSourceRange() << SafelenLength->getSourceRange(); 8761 return true; 8762 } 8763 } 8764 return false; 8765 } 8766 8767 StmtResult 8768 Sema::ActOnOpenMPSimdDirective(ArrayRef<OMPClause *> Clauses, Stmt *AStmt, 8769 SourceLocation StartLoc, SourceLocation EndLoc, 8770 VarsWithInheritedDSAType &VarsWithImplicitDSA) { 8771 if (!AStmt) 8772 return StmtError(); 8773 8774 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected"); 8775 OMPLoopDirective::HelperExprs B; 8776 // In presence of clause 'collapse' or 'ordered' with number of loops, it will 8777 // define the nested loops number. 8778 unsigned NestedLoopCount = checkOpenMPLoop( 8779 OMPD_simd, getCollapseNumberExpr(Clauses), getOrderedNumberExpr(Clauses), 8780 AStmt, *this, *DSAStack, VarsWithImplicitDSA, B); 8781 if (NestedLoopCount == 0) 8782 return StmtError(); 8783 8784 assert((CurContext->isDependentContext() || B.builtAll()) && 8785 "omp simd loop exprs were not built"); 8786 8787 if (!CurContext->isDependentContext()) { 8788 // Finalize the clauses that need pre-built expressions for CodeGen. 8789 for (OMPClause *C : Clauses) { 8790 if (auto *LC = dyn_cast<OMPLinearClause>(C)) 8791 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef), 8792 B.NumIterations, *this, CurScope, 8793 DSAStack)) 8794 return StmtError(); 8795 } 8796 } 8797 8798 if (checkSimdlenSafelenSpecified(*this, Clauses)) 8799 return StmtError(); 8800 8801 setFunctionHasBranchProtectedScope(); 8802 return OMPSimdDirective::Create(Context, StartLoc, EndLoc, NestedLoopCount, 8803 Clauses, AStmt, B); 8804 } 8805 8806 StmtResult 8807 Sema::ActOnOpenMPForDirective(ArrayRef<OMPClause *> Clauses, Stmt *AStmt, 8808 SourceLocation StartLoc, SourceLocation EndLoc, 8809 VarsWithInheritedDSAType &VarsWithImplicitDSA) { 8810 if (!AStmt) 8811 return StmtError(); 8812 8813 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected"); 8814 OMPLoopDirective::HelperExprs B; 8815 // In presence of clause 'collapse' or 'ordered' with number of loops, it will 8816 // define the nested loops number. 8817 unsigned NestedLoopCount = checkOpenMPLoop( 8818 OMPD_for, getCollapseNumberExpr(Clauses), getOrderedNumberExpr(Clauses), 8819 AStmt, *this, *DSAStack, VarsWithImplicitDSA, B); 8820 if (NestedLoopCount == 0) 8821 return StmtError(); 8822 8823 assert((CurContext->isDependentContext() || B.builtAll()) && 8824 "omp for loop exprs were not built"); 8825 8826 if (!CurContext->isDependentContext()) { 8827 // Finalize the clauses that need pre-built expressions for CodeGen. 8828 for (OMPClause *C : Clauses) { 8829 if (auto *LC = dyn_cast<OMPLinearClause>(C)) 8830 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef), 8831 B.NumIterations, *this, CurScope, 8832 DSAStack)) 8833 return StmtError(); 8834 } 8835 } 8836 8837 setFunctionHasBranchProtectedScope(); 8838 return OMPForDirective::Create( 8839 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B, 8840 DSAStack->getTaskgroupReductionRef(), DSAStack->isCancelRegion()); 8841 } 8842 8843 StmtResult Sema::ActOnOpenMPForSimdDirective( 8844 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, 8845 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) { 8846 if (!AStmt) 8847 return StmtError(); 8848 8849 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected"); 8850 OMPLoopDirective::HelperExprs B; 8851 // In presence of clause 'collapse' or 'ordered' with number of loops, it will 8852 // define the nested loops number. 8853 unsigned NestedLoopCount = 8854 checkOpenMPLoop(OMPD_for_simd, getCollapseNumberExpr(Clauses), 8855 getOrderedNumberExpr(Clauses), AStmt, *this, *DSAStack, 8856 VarsWithImplicitDSA, B); 8857 if (NestedLoopCount == 0) 8858 return StmtError(); 8859 8860 assert((CurContext->isDependentContext() || B.builtAll()) && 8861 "omp for simd loop exprs were not built"); 8862 8863 if (!CurContext->isDependentContext()) { 8864 // Finalize the clauses that need pre-built expressions for CodeGen. 8865 for (OMPClause *C : Clauses) { 8866 if (auto *LC = dyn_cast<OMPLinearClause>(C)) 8867 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef), 8868 B.NumIterations, *this, CurScope, 8869 DSAStack)) 8870 return StmtError(); 8871 } 8872 } 8873 8874 if (checkSimdlenSafelenSpecified(*this, Clauses)) 8875 return StmtError(); 8876 8877 setFunctionHasBranchProtectedScope(); 8878 return OMPForSimdDirective::Create(Context, StartLoc, EndLoc, NestedLoopCount, 8879 Clauses, AStmt, B); 8880 } 8881 8882 StmtResult Sema::ActOnOpenMPSectionsDirective(ArrayRef<OMPClause *> Clauses, 8883 Stmt *AStmt, 8884 SourceLocation StartLoc, 8885 SourceLocation EndLoc) { 8886 if (!AStmt) 8887 return StmtError(); 8888 8889 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected"); 8890 auto BaseStmt = AStmt; 8891 while (auto *CS = dyn_cast_or_null<CapturedStmt>(BaseStmt)) 8892 BaseStmt = CS->getCapturedStmt(); 8893 if (auto *C = dyn_cast_or_null<CompoundStmt>(BaseStmt)) { 8894 auto S = C->children(); 8895 if (S.begin() == S.end()) 8896 return StmtError(); 8897 // All associated statements must be '#pragma omp section' except for 8898 // the first one. 8899 for (Stmt *SectionStmt : llvm::make_range(std::next(S.begin()), S.end())) { 8900 if (!SectionStmt || !isa<OMPSectionDirective>(SectionStmt)) { 8901 if (SectionStmt) 8902 Diag(SectionStmt->getBeginLoc(), 8903 diag::err_omp_sections_substmt_not_section); 8904 return StmtError(); 8905 } 8906 cast<OMPSectionDirective>(SectionStmt) 8907 ->setHasCancel(DSAStack->isCancelRegion()); 8908 } 8909 } else { 8910 Diag(AStmt->getBeginLoc(), diag::err_omp_sections_not_compound_stmt); 8911 return StmtError(); 8912 } 8913 8914 setFunctionHasBranchProtectedScope(); 8915 8916 return OMPSectionsDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt, 8917 DSAStack->getTaskgroupReductionRef(), 8918 DSAStack->isCancelRegion()); 8919 } 8920 8921 StmtResult Sema::ActOnOpenMPSectionDirective(Stmt *AStmt, 8922 SourceLocation StartLoc, 8923 SourceLocation EndLoc) { 8924 if (!AStmt) 8925 return StmtError(); 8926 8927 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected"); 8928 8929 setFunctionHasBranchProtectedScope(); 8930 DSAStack->setParentCancelRegion(DSAStack->isCancelRegion()); 8931 8932 return OMPSectionDirective::Create(Context, StartLoc, EndLoc, AStmt, 8933 DSAStack->isCancelRegion()); 8934 } 8935 8936 StmtResult Sema::ActOnOpenMPSingleDirective(ArrayRef<OMPClause *> Clauses, 8937 Stmt *AStmt, 8938 SourceLocation StartLoc, 8939 SourceLocation EndLoc) { 8940 if (!AStmt) 8941 return StmtError(); 8942 8943 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected"); 8944 8945 setFunctionHasBranchProtectedScope(); 8946 8947 // OpenMP [2.7.3, single Construct, Restrictions] 8948 // The copyprivate clause must not be used with the nowait clause. 8949 const OMPClause *Nowait = nullptr; 8950 const OMPClause *Copyprivate = nullptr; 8951 for (const OMPClause *Clause : Clauses) { 8952 if (Clause->getClauseKind() == OMPC_nowait) 8953 Nowait = Clause; 8954 else if (Clause->getClauseKind() == OMPC_copyprivate) 8955 Copyprivate = Clause; 8956 if (Copyprivate && Nowait) { 8957 Diag(Copyprivate->getBeginLoc(), 8958 diag::err_omp_single_copyprivate_with_nowait); 8959 Diag(Nowait->getBeginLoc(), diag::note_omp_nowait_clause_here); 8960 return StmtError(); 8961 } 8962 } 8963 8964 return OMPSingleDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt); 8965 } 8966 8967 StmtResult Sema::ActOnOpenMPMasterDirective(Stmt *AStmt, 8968 SourceLocation StartLoc, 8969 SourceLocation EndLoc) { 8970 if (!AStmt) 8971 return StmtError(); 8972 8973 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected"); 8974 8975 setFunctionHasBranchProtectedScope(); 8976 8977 return OMPMasterDirective::Create(Context, StartLoc, EndLoc, AStmt); 8978 } 8979 8980 StmtResult Sema::ActOnOpenMPCriticalDirective( 8981 const DeclarationNameInfo &DirName, ArrayRef<OMPClause *> Clauses, 8982 Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc) { 8983 if (!AStmt) 8984 return StmtError(); 8985 8986 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected"); 8987 8988 bool ErrorFound = false; 8989 llvm::APSInt Hint; 8990 SourceLocation HintLoc; 8991 bool DependentHint = false; 8992 for (const OMPClause *C : Clauses) { 8993 if (C->getClauseKind() == OMPC_hint) { 8994 if (!DirName.getName()) { 8995 Diag(C->getBeginLoc(), diag::err_omp_hint_clause_no_name); 8996 ErrorFound = true; 8997 } 8998 Expr *E = cast<OMPHintClause>(C)->getHint(); 8999 if (E->isTypeDependent() || E->isValueDependent() || 9000 E->isInstantiationDependent()) { 9001 DependentHint = true; 9002 } else { 9003 Hint = E->EvaluateKnownConstInt(Context); 9004 HintLoc = C->getBeginLoc(); 9005 } 9006 } 9007 } 9008 if (ErrorFound) 9009 return StmtError(); 9010 const auto Pair = DSAStack->getCriticalWithHint(DirName); 9011 if (Pair.first && DirName.getName() && !DependentHint) { 9012 if (llvm::APSInt::compareValues(Hint, Pair.second) != 0) { 9013 Diag(StartLoc, diag::err_omp_critical_with_hint); 9014 if (HintLoc.isValid()) 9015 Diag(HintLoc, diag::note_omp_critical_hint_here) 9016 << 0 << Hint.toString(/*Radix=*/10, /*Signed=*/false); 9017 else 9018 Diag(StartLoc, diag::note_omp_critical_no_hint) << 0; 9019 if (const auto *C = Pair.first->getSingleClause<OMPHintClause>()) { 9020 Diag(C->getBeginLoc(), diag::note_omp_critical_hint_here) 9021 << 1 9022 << C->getHint()->EvaluateKnownConstInt(Context).toString( 9023 /*Radix=*/10, /*Signed=*/false); 9024 } else { 9025 Diag(Pair.first->getBeginLoc(), diag::note_omp_critical_no_hint) << 1; 9026 } 9027 } 9028 } 9029 9030 setFunctionHasBranchProtectedScope(); 9031 9032 auto *Dir = OMPCriticalDirective::Create(Context, DirName, StartLoc, EndLoc, 9033 Clauses, AStmt); 9034 if (!Pair.first && DirName.getName() && !DependentHint) 9035 DSAStack->addCriticalWithHint(Dir, Hint); 9036 return Dir; 9037 } 9038 9039 StmtResult Sema::ActOnOpenMPParallelForDirective( 9040 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, 9041 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) { 9042 if (!AStmt) 9043 return StmtError(); 9044 9045 auto *CS = cast<CapturedStmt>(AStmt); 9046 // 1.2.2 OpenMP Language Terminology 9047 // Structured block - An executable statement with a single entry at the 9048 // top and a single exit at the bottom. 9049 // The point of exit cannot be a branch out of the structured block. 9050 // longjmp() and throw() must not violate the entry/exit criteria. 9051 CS->getCapturedDecl()->setNothrow(); 9052 9053 OMPLoopDirective::HelperExprs B; 9054 // In presence of clause 'collapse' or 'ordered' with number of loops, it will 9055 // define the nested loops number. 9056 unsigned NestedLoopCount = 9057 checkOpenMPLoop(OMPD_parallel_for, getCollapseNumberExpr(Clauses), 9058 getOrderedNumberExpr(Clauses), AStmt, *this, *DSAStack, 9059 VarsWithImplicitDSA, B); 9060 if (NestedLoopCount == 0) 9061 return StmtError(); 9062 9063 assert((CurContext->isDependentContext() || B.builtAll()) && 9064 "omp parallel for loop exprs were not built"); 9065 9066 if (!CurContext->isDependentContext()) { 9067 // Finalize the clauses that need pre-built expressions for CodeGen. 9068 for (OMPClause *C : Clauses) { 9069 if (auto *LC = dyn_cast<OMPLinearClause>(C)) 9070 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef), 9071 B.NumIterations, *this, CurScope, 9072 DSAStack)) 9073 return StmtError(); 9074 } 9075 } 9076 9077 setFunctionHasBranchProtectedScope(); 9078 return OMPParallelForDirective::Create( 9079 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B, 9080 DSAStack->getTaskgroupReductionRef(), DSAStack->isCancelRegion()); 9081 } 9082 9083 StmtResult Sema::ActOnOpenMPParallelForSimdDirective( 9084 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, 9085 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) { 9086 if (!AStmt) 9087 return StmtError(); 9088 9089 auto *CS = cast<CapturedStmt>(AStmt); 9090 // 1.2.2 OpenMP Language Terminology 9091 // Structured block - An executable statement with a single entry at the 9092 // top and a single exit at the bottom. 9093 // The point of exit cannot be a branch out of the structured block. 9094 // longjmp() and throw() must not violate the entry/exit criteria. 9095 CS->getCapturedDecl()->setNothrow(); 9096 9097 OMPLoopDirective::HelperExprs B; 9098 // In presence of clause 'collapse' or 'ordered' with number of loops, it will 9099 // define the nested loops number. 9100 unsigned NestedLoopCount = 9101 checkOpenMPLoop(OMPD_parallel_for_simd, getCollapseNumberExpr(Clauses), 9102 getOrderedNumberExpr(Clauses), AStmt, *this, *DSAStack, 9103 VarsWithImplicitDSA, B); 9104 if (NestedLoopCount == 0) 9105 return StmtError(); 9106 9107 if (!CurContext->isDependentContext()) { 9108 // Finalize the clauses that need pre-built expressions for CodeGen. 9109 for (OMPClause *C : Clauses) { 9110 if (auto *LC = dyn_cast<OMPLinearClause>(C)) 9111 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef), 9112 B.NumIterations, *this, CurScope, 9113 DSAStack)) 9114 return StmtError(); 9115 } 9116 } 9117 9118 if (checkSimdlenSafelenSpecified(*this, Clauses)) 9119 return StmtError(); 9120 9121 setFunctionHasBranchProtectedScope(); 9122 return OMPParallelForSimdDirective::Create( 9123 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B); 9124 } 9125 9126 StmtResult 9127 Sema::ActOnOpenMPParallelMasterDirective(ArrayRef<OMPClause *> Clauses, 9128 Stmt *AStmt, SourceLocation StartLoc, 9129 SourceLocation EndLoc) { 9130 if (!AStmt) 9131 return StmtError(); 9132 9133 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected"); 9134 auto *CS = cast<CapturedStmt>(AStmt); 9135 // 1.2.2 OpenMP Language Terminology 9136 // Structured block - An executable statement with a single entry at the 9137 // top and a single exit at the bottom. 9138 // The point of exit cannot be a branch out of the structured block. 9139 // longjmp() and throw() must not violate the entry/exit criteria. 9140 CS->getCapturedDecl()->setNothrow(); 9141 9142 setFunctionHasBranchProtectedScope(); 9143 9144 return OMPParallelMasterDirective::Create( 9145 Context, StartLoc, EndLoc, Clauses, AStmt, 9146 DSAStack->getTaskgroupReductionRef()); 9147 } 9148 9149 StmtResult 9150 Sema::ActOnOpenMPParallelSectionsDirective(ArrayRef<OMPClause *> Clauses, 9151 Stmt *AStmt, SourceLocation StartLoc, 9152 SourceLocation EndLoc) { 9153 if (!AStmt) 9154 return StmtError(); 9155 9156 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected"); 9157 auto BaseStmt = AStmt; 9158 while (auto *CS = dyn_cast_or_null<CapturedStmt>(BaseStmt)) 9159 BaseStmt = CS->getCapturedStmt(); 9160 if (auto *C = dyn_cast_or_null<CompoundStmt>(BaseStmt)) { 9161 auto S = C->children(); 9162 if (S.begin() == S.end()) 9163 return StmtError(); 9164 // All associated statements must be '#pragma omp section' except for 9165 // the first one. 9166 for (Stmt *SectionStmt : llvm::make_range(std::next(S.begin()), S.end())) { 9167 if (!SectionStmt || !isa<OMPSectionDirective>(SectionStmt)) { 9168 if (SectionStmt) 9169 Diag(SectionStmt->getBeginLoc(), 9170 diag::err_omp_parallel_sections_substmt_not_section); 9171 return StmtError(); 9172 } 9173 cast<OMPSectionDirective>(SectionStmt) 9174 ->setHasCancel(DSAStack->isCancelRegion()); 9175 } 9176 } else { 9177 Diag(AStmt->getBeginLoc(), 9178 diag::err_omp_parallel_sections_not_compound_stmt); 9179 return StmtError(); 9180 } 9181 9182 setFunctionHasBranchProtectedScope(); 9183 9184 return OMPParallelSectionsDirective::Create( 9185 Context, StartLoc, EndLoc, Clauses, AStmt, 9186 DSAStack->getTaskgroupReductionRef(), DSAStack->isCancelRegion()); 9187 } 9188 9189 /// detach and mergeable clauses are mutially exclusive, check for it. 9190 static bool checkDetachMergeableClauses(Sema &S, 9191 ArrayRef<OMPClause *> Clauses) { 9192 const OMPClause *PrevClause = nullptr; 9193 bool ErrorFound = false; 9194 for (const OMPClause *C : Clauses) { 9195 if (C->getClauseKind() == OMPC_detach || 9196 C->getClauseKind() == OMPC_mergeable) { 9197 if (!PrevClause) { 9198 PrevClause = C; 9199 } else if (PrevClause->getClauseKind() != C->getClauseKind()) { 9200 S.Diag(C->getBeginLoc(), diag::err_omp_clauses_mutually_exclusive) 9201 << getOpenMPClauseName(C->getClauseKind()) 9202 << getOpenMPClauseName(PrevClause->getClauseKind()); 9203 S.Diag(PrevClause->getBeginLoc(), diag::note_omp_previous_clause) 9204 << getOpenMPClauseName(PrevClause->getClauseKind()); 9205 ErrorFound = true; 9206 } 9207 } 9208 } 9209 return ErrorFound; 9210 } 9211 9212 StmtResult Sema::ActOnOpenMPTaskDirective(ArrayRef<OMPClause *> Clauses, 9213 Stmt *AStmt, SourceLocation StartLoc, 9214 SourceLocation EndLoc) { 9215 if (!AStmt) 9216 return StmtError(); 9217 9218 // OpenMP 5.0, 2.10.1 task Construct 9219 // If a detach clause appears on the directive, then a mergeable clause cannot 9220 // appear on the same directive. 9221 if (checkDetachMergeableClauses(*this, Clauses)) 9222 return StmtError(); 9223 9224 auto *CS = cast<CapturedStmt>(AStmt); 9225 // 1.2.2 OpenMP Language Terminology 9226 // Structured block - An executable statement with a single entry at the 9227 // top and a single exit at the bottom. 9228 // The point of exit cannot be a branch out of the structured block. 9229 // longjmp() and throw() must not violate the entry/exit criteria. 9230 CS->getCapturedDecl()->setNothrow(); 9231 9232 setFunctionHasBranchProtectedScope(); 9233 9234 return OMPTaskDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt, 9235 DSAStack->isCancelRegion()); 9236 } 9237 9238 StmtResult Sema::ActOnOpenMPTaskyieldDirective(SourceLocation StartLoc, 9239 SourceLocation EndLoc) { 9240 return OMPTaskyieldDirective::Create(Context, StartLoc, EndLoc); 9241 } 9242 9243 StmtResult Sema::ActOnOpenMPBarrierDirective(SourceLocation StartLoc, 9244 SourceLocation EndLoc) { 9245 return OMPBarrierDirective::Create(Context, StartLoc, EndLoc); 9246 } 9247 9248 StmtResult Sema::ActOnOpenMPTaskwaitDirective(SourceLocation StartLoc, 9249 SourceLocation EndLoc) { 9250 return OMPTaskwaitDirective::Create(Context, StartLoc, EndLoc); 9251 } 9252 9253 StmtResult Sema::ActOnOpenMPTaskgroupDirective(ArrayRef<OMPClause *> Clauses, 9254 Stmt *AStmt, 9255 SourceLocation StartLoc, 9256 SourceLocation EndLoc) { 9257 if (!AStmt) 9258 return StmtError(); 9259 9260 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected"); 9261 9262 setFunctionHasBranchProtectedScope(); 9263 9264 return OMPTaskgroupDirective::Create(Context, StartLoc, EndLoc, Clauses, 9265 AStmt, 9266 DSAStack->getTaskgroupReductionRef()); 9267 } 9268 9269 StmtResult Sema::ActOnOpenMPFlushDirective(ArrayRef<OMPClause *> Clauses, 9270 SourceLocation StartLoc, 9271 SourceLocation EndLoc) { 9272 OMPFlushClause *FC = nullptr; 9273 OMPClause *OrderClause = nullptr; 9274 for (OMPClause *C : Clauses) { 9275 if (C->getClauseKind() == OMPC_flush) 9276 FC = cast<OMPFlushClause>(C); 9277 else 9278 OrderClause = C; 9279 } 9280 OpenMPClauseKind MemOrderKind = OMPC_unknown; 9281 SourceLocation MemOrderLoc; 9282 for (const OMPClause *C : Clauses) { 9283 if (C->getClauseKind() == OMPC_acq_rel || 9284 C->getClauseKind() == OMPC_acquire || 9285 C->getClauseKind() == OMPC_release) { 9286 if (MemOrderKind != OMPC_unknown) { 9287 Diag(C->getBeginLoc(), diag::err_omp_several_mem_order_clauses) 9288 << getOpenMPDirectiveName(OMPD_flush) << 1 9289 << SourceRange(C->getBeginLoc(), C->getEndLoc()); 9290 Diag(MemOrderLoc, diag::note_omp_previous_mem_order_clause) 9291 << getOpenMPClauseName(MemOrderKind); 9292 } else { 9293 MemOrderKind = C->getClauseKind(); 9294 MemOrderLoc = C->getBeginLoc(); 9295 } 9296 } 9297 } 9298 if (FC && OrderClause) { 9299 Diag(FC->getLParenLoc(), diag::err_omp_flush_order_clause_and_list) 9300 << getOpenMPClauseName(OrderClause->getClauseKind()); 9301 Diag(OrderClause->getBeginLoc(), diag::note_omp_flush_order_clause_here) 9302 << getOpenMPClauseName(OrderClause->getClauseKind()); 9303 return StmtError(); 9304 } 9305 return OMPFlushDirective::Create(Context, StartLoc, EndLoc, Clauses); 9306 } 9307 9308 StmtResult Sema::ActOnOpenMPDepobjDirective(ArrayRef<OMPClause *> Clauses, 9309 SourceLocation StartLoc, 9310 SourceLocation EndLoc) { 9311 if (Clauses.empty()) { 9312 Diag(StartLoc, diag::err_omp_depobj_expected); 9313 return StmtError(); 9314 } else if (Clauses[0]->getClauseKind() != OMPC_depobj) { 9315 Diag(Clauses[0]->getBeginLoc(), diag::err_omp_depobj_expected); 9316 return StmtError(); 9317 } 9318 // Only depobj expression and another single clause is allowed. 9319 if (Clauses.size() > 2) { 9320 Diag(Clauses[2]->getBeginLoc(), 9321 diag::err_omp_depobj_single_clause_expected); 9322 return StmtError(); 9323 } else if (Clauses.size() < 1) { 9324 Diag(Clauses[0]->getEndLoc(), diag::err_omp_depobj_single_clause_expected); 9325 return StmtError(); 9326 } 9327 return OMPDepobjDirective::Create(Context, StartLoc, EndLoc, Clauses); 9328 } 9329 9330 StmtResult Sema::ActOnOpenMPScanDirective(ArrayRef<OMPClause *> Clauses, 9331 SourceLocation StartLoc, 9332 SourceLocation EndLoc) { 9333 // Check that exactly one clause is specified. 9334 if (Clauses.size() != 1) { 9335 Diag(Clauses.empty() ? EndLoc : Clauses[1]->getBeginLoc(), 9336 diag::err_omp_scan_single_clause_expected); 9337 return StmtError(); 9338 } 9339 // Check that scan directive is used in the scopeof the OpenMP loop body. 9340 if (Scope *S = DSAStack->getCurScope()) { 9341 Scope *ParentS = S->getParent(); 9342 if (!ParentS || ParentS->getParent() != ParentS->getBreakParent() || 9343 !ParentS->getBreakParent()->isOpenMPLoopScope()) 9344 return StmtError(Diag(StartLoc, diag::err_omp_orphaned_device_directive) 9345 << getOpenMPDirectiveName(OMPD_scan) << 5); 9346 } 9347 // Check that only one instance of scan directives is used in the same outer 9348 // region. 9349 if (DSAStack->doesParentHasScanDirective()) { 9350 Diag(StartLoc, diag::err_omp_several_directives_in_region) << "scan"; 9351 Diag(DSAStack->getParentScanDirectiveLoc(), 9352 diag::note_omp_previous_directive) 9353 << "scan"; 9354 return StmtError(); 9355 } 9356 DSAStack->setParentHasScanDirective(StartLoc); 9357 return OMPScanDirective::Create(Context, StartLoc, EndLoc, Clauses); 9358 } 9359 9360 StmtResult Sema::ActOnOpenMPOrderedDirective(ArrayRef<OMPClause *> Clauses, 9361 Stmt *AStmt, 9362 SourceLocation StartLoc, 9363 SourceLocation EndLoc) { 9364 const OMPClause *DependFound = nullptr; 9365 const OMPClause *DependSourceClause = nullptr; 9366 const OMPClause *DependSinkClause = nullptr; 9367 bool ErrorFound = false; 9368 const OMPThreadsClause *TC = nullptr; 9369 const OMPSIMDClause *SC = nullptr; 9370 for (const OMPClause *C : Clauses) { 9371 if (auto *DC = dyn_cast<OMPDependClause>(C)) { 9372 DependFound = C; 9373 if (DC->getDependencyKind() == OMPC_DEPEND_source) { 9374 if (DependSourceClause) { 9375 Diag(C->getBeginLoc(), diag::err_omp_more_one_clause) 9376 << getOpenMPDirectiveName(OMPD_ordered) 9377 << getOpenMPClauseName(OMPC_depend) << 2; 9378 ErrorFound = true; 9379 } else { 9380 DependSourceClause = C; 9381 } 9382 if (DependSinkClause) { 9383 Diag(C->getBeginLoc(), diag::err_omp_depend_sink_source_not_allowed) 9384 << 0; 9385 ErrorFound = true; 9386 } 9387 } else if (DC->getDependencyKind() == OMPC_DEPEND_sink) { 9388 if (DependSourceClause) { 9389 Diag(C->getBeginLoc(), diag::err_omp_depend_sink_source_not_allowed) 9390 << 1; 9391 ErrorFound = true; 9392 } 9393 DependSinkClause = C; 9394 } 9395 } else if (C->getClauseKind() == OMPC_threads) { 9396 TC = cast<OMPThreadsClause>(C); 9397 } else if (C->getClauseKind() == OMPC_simd) { 9398 SC = cast<OMPSIMDClause>(C); 9399 } 9400 } 9401 if (!ErrorFound && !SC && 9402 isOpenMPSimdDirective(DSAStack->getParentDirective())) { 9403 // OpenMP [2.8.1,simd Construct, Restrictions] 9404 // An ordered construct with the simd clause is the only OpenMP construct 9405 // that can appear in the simd region. 9406 Diag(StartLoc, diag::err_omp_prohibited_region_simd) 9407 << (LangOpts.OpenMP >= 50 ? 1 : 0); 9408 ErrorFound = true; 9409 } else if (DependFound && (TC || SC)) { 9410 Diag(DependFound->getBeginLoc(), diag::err_omp_depend_clause_thread_simd) 9411 << getOpenMPClauseName(TC ? TC->getClauseKind() : SC->getClauseKind()); 9412 ErrorFound = true; 9413 } else if (DependFound && !DSAStack->getParentOrderedRegionParam().first) { 9414 Diag(DependFound->getBeginLoc(), 9415 diag::err_omp_ordered_directive_without_param); 9416 ErrorFound = true; 9417 } else if (TC || Clauses.empty()) { 9418 if (const Expr *Param = DSAStack->getParentOrderedRegionParam().first) { 9419 SourceLocation ErrLoc = TC ? TC->getBeginLoc() : StartLoc; 9420 Diag(ErrLoc, diag::err_omp_ordered_directive_with_param) 9421 << (TC != nullptr); 9422 Diag(Param->getBeginLoc(), diag::note_omp_ordered_param) << 1; 9423 ErrorFound = true; 9424 } 9425 } 9426 if ((!AStmt && !DependFound) || ErrorFound) 9427 return StmtError(); 9428 9429 // OpenMP 5.0, 2.17.9, ordered Construct, Restrictions. 9430 // During execution of an iteration of a worksharing-loop or a loop nest 9431 // within a worksharing-loop, simd, or worksharing-loop SIMD region, a thread 9432 // must not execute more than one ordered region corresponding to an ordered 9433 // construct without a depend clause. 9434 if (!DependFound) { 9435 if (DSAStack->doesParentHasOrderedDirective()) { 9436 Diag(StartLoc, diag::err_omp_several_directives_in_region) << "ordered"; 9437 Diag(DSAStack->getParentOrderedDirectiveLoc(), 9438 diag::note_omp_previous_directive) 9439 << "ordered"; 9440 return StmtError(); 9441 } 9442 DSAStack->setParentHasOrderedDirective(StartLoc); 9443 } 9444 9445 if (AStmt) { 9446 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected"); 9447 9448 setFunctionHasBranchProtectedScope(); 9449 } 9450 9451 return OMPOrderedDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt); 9452 } 9453 9454 namespace { 9455 /// Helper class for checking expression in 'omp atomic [update]' 9456 /// construct. 9457 class OpenMPAtomicUpdateChecker { 9458 /// Error results for atomic update expressions. 9459 enum ExprAnalysisErrorCode { 9460 /// A statement is not an expression statement. 9461 NotAnExpression, 9462 /// Expression is not builtin binary or unary operation. 9463 NotABinaryOrUnaryExpression, 9464 /// Unary operation is not post-/pre- increment/decrement operation. 9465 NotAnUnaryIncDecExpression, 9466 /// An expression is not of scalar type. 9467 NotAScalarType, 9468 /// A binary operation is not an assignment operation. 9469 NotAnAssignmentOp, 9470 /// RHS part of the binary operation is not a binary expression. 9471 NotABinaryExpression, 9472 /// RHS part is not additive/multiplicative/shift/biwise binary 9473 /// expression. 9474 NotABinaryOperator, 9475 /// RHS binary operation does not have reference to the updated LHS 9476 /// part. 9477 NotAnUpdateExpression, 9478 /// No errors is found. 9479 NoError 9480 }; 9481 /// Reference to Sema. 9482 Sema &SemaRef; 9483 /// A location for note diagnostics (when error is found). 9484 SourceLocation NoteLoc; 9485 /// 'x' lvalue part of the source atomic expression. 9486 Expr *X; 9487 /// 'expr' rvalue part of the source atomic expression. 9488 Expr *E; 9489 /// Helper expression of the form 9490 /// 'OpaqueValueExpr(x) binop OpaqueValueExpr(expr)' or 9491 /// 'OpaqueValueExpr(expr) binop OpaqueValueExpr(x)'. 9492 Expr *UpdateExpr; 9493 /// Is 'x' a LHS in a RHS part of full update expression. It is 9494 /// important for non-associative operations. 9495 bool IsXLHSInRHSPart; 9496 BinaryOperatorKind Op; 9497 SourceLocation OpLoc; 9498 /// true if the source expression is a postfix unary operation, false 9499 /// if it is a prefix unary operation. 9500 bool IsPostfixUpdate; 9501 9502 public: 9503 OpenMPAtomicUpdateChecker(Sema &SemaRef) 9504 : SemaRef(SemaRef), X(nullptr), E(nullptr), UpdateExpr(nullptr), 9505 IsXLHSInRHSPart(false), Op(BO_PtrMemD), IsPostfixUpdate(false) {} 9506 /// Check specified statement that it is suitable for 'atomic update' 9507 /// constructs and extract 'x', 'expr' and Operation from the original 9508 /// expression. If DiagId and NoteId == 0, then only check is performed 9509 /// without error notification. 9510 /// \param DiagId Diagnostic which should be emitted if error is found. 9511 /// \param NoteId Diagnostic note for the main error message. 9512 /// \return true if statement is not an update expression, false otherwise. 9513 bool checkStatement(Stmt *S, unsigned DiagId = 0, unsigned NoteId = 0); 9514 /// Return the 'x' lvalue part of the source atomic expression. 9515 Expr *getX() const { return X; } 9516 /// Return the 'expr' rvalue part of the source atomic expression. 9517 Expr *getExpr() const { return E; } 9518 /// Return the update expression used in calculation of the updated 9519 /// value. Always has form 'OpaqueValueExpr(x) binop OpaqueValueExpr(expr)' or 9520 /// 'OpaqueValueExpr(expr) binop OpaqueValueExpr(x)'. 9521 Expr *getUpdateExpr() const { return UpdateExpr; } 9522 /// Return true if 'x' is LHS in RHS part of full update expression, 9523 /// false otherwise. 9524 bool isXLHSInRHSPart() const { return IsXLHSInRHSPart; } 9525 9526 /// true if the source expression is a postfix unary operation, false 9527 /// if it is a prefix unary operation. 9528 bool isPostfixUpdate() const { return IsPostfixUpdate; } 9529 9530 private: 9531 bool checkBinaryOperation(BinaryOperator *AtomicBinOp, unsigned DiagId = 0, 9532 unsigned NoteId = 0); 9533 }; 9534 } // namespace 9535 9536 bool OpenMPAtomicUpdateChecker::checkBinaryOperation( 9537 BinaryOperator *AtomicBinOp, unsigned DiagId, unsigned NoteId) { 9538 ExprAnalysisErrorCode ErrorFound = NoError; 9539 SourceLocation ErrorLoc, NoteLoc; 9540 SourceRange ErrorRange, NoteRange; 9541 // Allowed constructs are: 9542 // x = x binop expr; 9543 // x = expr binop x; 9544 if (AtomicBinOp->getOpcode() == BO_Assign) { 9545 X = AtomicBinOp->getLHS(); 9546 if (const auto *AtomicInnerBinOp = dyn_cast<BinaryOperator>( 9547 AtomicBinOp->getRHS()->IgnoreParenImpCasts())) { 9548 if (AtomicInnerBinOp->isMultiplicativeOp() || 9549 AtomicInnerBinOp->isAdditiveOp() || AtomicInnerBinOp->isShiftOp() || 9550 AtomicInnerBinOp->isBitwiseOp()) { 9551 Op = AtomicInnerBinOp->getOpcode(); 9552 OpLoc = AtomicInnerBinOp->getOperatorLoc(); 9553 Expr *LHS = AtomicInnerBinOp->getLHS(); 9554 Expr *RHS = AtomicInnerBinOp->getRHS(); 9555 llvm::FoldingSetNodeID XId, LHSId, RHSId; 9556 X->IgnoreParenImpCasts()->Profile(XId, SemaRef.getASTContext(), 9557 /*Canonical=*/true); 9558 LHS->IgnoreParenImpCasts()->Profile(LHSId, SemaRef.getASTContext(), 9559 /*Canonical=*/true); 9560 RHS->IgnoreParenImpCasts()->Profile(RHSId, SemaRef.getASTContext(), 9561 /*Canonical=*/true); 9562 if (XId == LHSId) { 9563 E = RHS; 9564 IsXLHSInRHSPart = true; 9565 } else if (XId == RHSId) { 9566 E = LHS; 9567 IsXLHSInRHSPart = false; 9568 } else { 9569 ErrorLoc = AtomicInnerBinOp->getExprLoc(); 9570 ErrorRange = AtomicInnerBinOp->getSourceRange(); 9571 NoteLoc = X->getExprLoc(); 9572 NoteRange = X->getSourceRange(); 9573 ErrorFound = NotAnUpdateExpression; 9574 } 9575 } else { 9576 ErrorLoc = AtomicInnerBinOp->getExprLoc(); 9577 ErrorRange = AtomicInnerBinOp->getSourceRange(); 9578 NoteLoc = AtomicInnerBinOp->getOperatorLoc(); 9579 NoteRange = SourceRange(NoteLoc, NoteLoc); 9580 ErrorFound = NotABinaryOperator; 9581 } 9582 } else { 9583 NoteLoc = ErrorLoc = AtomicBinOp->getRHS()->getExprLoc(); 9584 NoteRange = ErrorRange = AtomicBinOp->getRHS()->getSourceRange(); 9585 ErrorFound = NotABinaryExpression; 9586 } 9587 } else { 9588 ErrorLoc = AtomicBinOp->getExprLoc(); 9589 ErrorRange = AtomicBinOp->getSourceRange(); 9590 NoteLoc = AtomicBinOp->getOperatorLoc(); 9591 NoteRange = SourceRange(NoteLoc, NoteLoc); 9592 ErrorFound = NotAnAssignmentOp; 9593 } 9594 if (ErrorFound != NoError && DiagId != 0 && NoteId != 0) { 9595 SemaRef.Diag(ErrorLoc, DiagId) << ErrorRange; 9596 SemaRef.Diag(NoteLoc, NoteId) << ErrorFound << NoteRange; 9597 return true; 9598 } 9599 if (SemaRef.CurContext->isDependentContext()) 9600 E = X = UpdateExpr = nullptr; 9601 return ErrorFound != NoError; 9602 } 9603 9604 bool OpenMPAtomicUpdateChecker::checkStatement(Stmt *S, unsigned DiagId, 9605 unsigned NoteId) { 9606 ExprAnalysisErrorCode ErrorFound = NoError; 9607 SourceLocation ErrorLoc, NoteLoc; 9608 SourceRange ErrorRange, NoteRange; 9609 // Allowed constructs are: 9610 // x++; 9611 // x--; 9612 // ++x; 9613 // --x; 9614 // x binop= expr; 9615 // x = x binop expr; 9616 // x = expr binop x; 9617 if (auto *AtomicBody = dyn_cast<Expr>(S)) { 9618 AtomicBody = AtomicBody->IgnoreParenImpCasts(); 9619 if (AtomicBody->getType()->isScalarType() || 9620 AtomicBody->isInstantiationDependent()) { 9621 if (const auto *AtomicCompAssignOp = dyn_cast<CompoundAssignOperator>( 9622 AtomicBody->IgnoreParenImpCasts())) { 9623 // Check for Compound Assignment Operation 9624 Op = BinaryOperator::getOpForCompoundAssignment( 9625 AtomicCompAssignOp->getOpcode()); 9626 OpLoc = AtomicCompAssignOp->getOperatorLoc(); 9627 E = AtomicCompAssignOp->getRHS(); 9628 X = AtomicCompAssignOp->getLHS()->IgnoreParens(); 9629 IsXLHSInRHSPart = true; 9630 } else if (auto *AtomicBinOp = dyn_cast<BinaryOperator>( 9631 AtomicBody->IgnoreParenImpCasts())) { 9632 // Check for Binary Operation 9633 if (checkBinaryOperation(AtomicBinOp, DiagId, NoteId)) 9634 return true; 9635 } else if (const auto *AtomicUnaryOp = dyn_cast<UnaryOperator>( 9636 AtomicBody->IgnoreParenImpCasts())) { 9637 // Check for Unary Operation 9638 if (AtomicUnaryOp->isIncrementDecrementOp()) { 9639 IsPostfixUpdate = AtomicUnaryOp->isPostfix(); 9640 Op = AtomicUnaryOp->isIncrementOp() ? BO_Add : BO_Sub; 9641 OpLoc = AtomicUnaryOp->getOperatorLoc(); 9642 X = AtomicUnaryOp->getSubExpr()->IgnoreParens(); 9643 E = SemaRef.ActOnIntegerConstant(OpLoc, /*uint64_t Val=*/1).get(); 9644 IsXLHSInRHSPart = true; 9645 } else { 9646 ErrorFound = NotAnUnaryIncDecExpression; 9647 ErrorLoc = AtomicUnaryOp->getExprLoc(); 9648 ErrorRange = AtomicUnaryOp->getSourceRange(); 9649 NoteLoc = AtomicUnaryOp->getOperatorLoc(); 9650 NoteRange = SourceRange(NoteLoc, NoteLoc); 9651 } 9652 } else if (!AtomicBody->isInstantiationDependent()) { 9653 ErrorFound = NotABinaryOrUnaryExpression; 9654 NoteLoc = ErrorLoc = AtomicBody->getExprLoc(); 9655 NoteRange = ErrorRange = AtomicBody->getSourceRange(); 9656 } 9657 } else { 9658 ErrorFound = NotAScalarType; 9659 NoteLoc = ErrorLoc = AtomicBody->getBeginLoc(); 9660 NoteRange = ErrorRange = SourceRange(NoteLoc, NoteLoc); 9661 } 9662 } else { 9663 ErrorFound = NotAnExpression; 9664 NoteLoc = ErrorLoc = S->getBeginLoc(); 9665 NoteRange = ErrorRange = SourceRange(NoteLoc, NoteLoc); 9666 } 9667 if (ErrorFound != NoError && DiagId != 0 && NoteId != 0) { 9668 SemaRef.Diag(ErrorLoc, DiagId) << ErrorRange; 9669 SemaRef.Diag(NoteLoc, NoteId) << ErrorFound << NoteRange; 9670 return true; 9671 } 9672 if (SemaRef.CurContext->isDependentContext()) 9673 E = X = UpdateExpr = nullptr; 9674 if (ErrorFound == NoError && E && X) { 9675 // Build an update expression of form 'OpaqueValueExpr(x) binop 9676 // OpaqueValueExpr(expr)' or 'OpaqueValueExpr(expr) binop 9677 // OpaqueValueExpr(x)' and then cast it to the type of the 'x' expression. 9678 auto *OVEX = new (SemaRef.getASTContext()) 9679 OpaqueValueExpr(X->getExprLoc(), X->getType(), VK_RValue); 9680 auto *OVEExpr = new (SemaRef.getASTContext()) 9681 OpaqueValueExpr(E->getExprLoc(), E->getType(), VK_RValue); 9682 ExprResult Update = 9683 SemaRef.CreateBuiltinBinOp(OpLoc, Op, IsXLHSInRHSPart ? OVEX : OVEExpr, 9684 IsXLHSInRHSPart ? OVEExpr : OVEX); 9685 if (Update.isInvalid()) 9686 return true; 9687 Update = SemaRef.PerformImplicitConversion(Update.get(), X->getType(), 9688 Sema::AA_Casting); 9689 if (Update.isInvalid()) 9690 return true; 9691 UpdateExpr = Update.get(); 9692 } 9693 return ErrorFound != NoError; 9694 } 9695 9696 StmtResult Sema::ActOnOpenMPAtomicDirective(ArrayRef<OMPClause *> Clauses, 9697 Stmt *AStmt, 9698 SourceLocation StartLoc, 9699 SourceLocation EndLoc) { 9700 // Register location of the first atomic directive. 9701 DSAStack->addAtomicDirectiveLoc(StartLoc); 9702 if (!AStmt) 9703 return StmtError(); 9704 9705 auto *CS = cast<CapturedStmt>(AStmt); 9706 // 1.2.2 OpenMP Language Terminology 9707 // Structured block - An executable statement with a single entry at the 9708 // top and a single exit at the bottom. 9709 // The point of exit cannot be a branch out of the structured block. 9710 // longjmp() and throw() must not violate the entry/exit criteria. 9711 OpenMPClauseKind AtomicKind = OMPC_unknown; 9712 SourceLocation AtomicKindLoc; 9713 OpenMPClauseKind MemOrderKind = OMPC_unknown; 9714 SourceLocation MemOrderLoc; 9715 for (const OMPClause *C : Clauses) { 9716 if (C->getClauseKind() == OMPC_read || C->getClauseKind() == OMPC_write || 9717 C->getClauseKind() == OMPC_update || 9718 C->getClauseKind() == OMPC_capture) { 9719 if (AtomicKind != OMPC_unknown) { 9720 Diag(C->getBeginLoc(), diag::err_omp_atomic_several_clauses) 9721 << SourceRange(C->getBeginLoc(), C->getEndLoc()); 9722 Diag(AtomicKindLoc, diag::note_omp_previous_mem_order_clause) 9723 << getOpenMPClauseName(AtomicKind); 9724 } else { 9725 AtomicKind = C->getClauseKind(); 9726 AtomicKindLoc = C->getBeginLoc(); 9727 } 9728 } 9729 if (C->getClauseKind() == OMPC_seq_cst || 9730 C->getClauseKind() == OMPC_acq_rel || 9731 C->getClauseKind() == OMPC_acquire || 9732 C->getClauseKind() == OMPC_release || 9733 C->getClauseKind() == OMPC_relaxed) { 9734 if (MemOrderKind != OMPC_unknown) { 9735 Diag(C->getBeginLoc(), diag::err_omp_several_mem_order_clauses) 9736 << getOpenMPDirectiveName(OMPD_atomic) << 0 9737 << SourceRange(C->getBeginLoc(), C->getEndLoc()); 9738 Diag(MemOrderLoc, diag::note_omp_previous_mem_order_clause) 9739 << getOpenMPClauseName(MemOrderKind); 9740 } else { 9741 MemOrderKind = C->getClauseKind(); 9742 MemOrderLoc = C->getBeginLoc(); 9743 } 9744 } 9745 } 9746 // OpenMP 5.0, 2.17.7 atomic Construct, Restrictions 9747 // If atomic-clause is read then memory-order-clause must not be acq_rel or 9748 // release. 9749 // If atomic-clause is write then memory-order-clause must not be acq_rel or 9750 // acquire. 9751 // If atomic-clause is update or not present then memory-order-clause must not 9752 // be acq_rel or acquire. 9753 if ((AtomicKind == OMPC_read && 9754 (MemOrderKind == OMPC_acq_rel || MemOrderKind == OMPC_release)) || 9755 ((AtomicKind == OMPC_write || AtomicKind == OMPC_update || 9756 AtomicKind == OMPC_unknown) && 9757 (MemOrderKind == OMPC_acq_rel || MemOrderKind == OMPC_acquire))) { 9758 SourceLocation Loc = AtomicKindLoc; 9759 if (AtomicKind == OMPC_unknown) 9760 Loc = StartLoc; 9761 Diag(Loc, diag::err_omp_atomic_incompatible_mem_order_clause) 9762 << getOpenMPClauseName(AtomicKind) 9763 << (AtomicKind == OMPC_unknown ? 1 : 0) 9764 << getOpenMPClauseName(MemOrderKind); 9765 Diag(MemOrderLoc, diag::note_omp_previous_mem_order_clause) 9766 << getOpenMPClauseName(MemOrderKind); 9767 } 9768 9769 Stmt *Body = CS->getCapturedStmt(); 9770 if (auto *EWC = dyn_cast<ExprWithCleanups>(Body)) 9771 Body = EWC->getSubExpr(); 9772 9773 Expr *X = nullptr; 9774 Expr *V = nullptr; 9775 Expr *E = nullptr; 9776 Expr *UE = nullptr; 9777 bool IsXLHSInRHSPart = false; 9778 bool IsPostfixUpdate = false; 9779 // OpenMP [2.12.6, atomic Construct] 9780 // In the next expressions: 9781 // * x and v (as applicable) are both l-value expressions with scalar type. 9782 // * During the execution of an atomic region, multiple syntactic 9783 // occurrences of x must designate the same storage location. 9784 // * Neither of v and expr (as applicable) may access the storage location 9785 // designated by x. 9786 // * Neither of x and expr (as applicable) may access the storage location 9787 // designated by v. 9788 // * expr is an expression with scalar type. 9789 // * binop is one of +, *, -, /, &, ^, |, <<, or >>. 9790 // * binop, binop=, ++, and -- are not overloaded operators. 9791 // * The expression x binop expr must be numerically equivalent to x binop 9792 // (expr). This requirement is satisfied if the operators in expr have 9793 // precedence greater than binop, or by using parentheses around expr or 9794 // subexpressions of expr. 9795 // * The expression expr binop x must be numerically equivalent to (expr) 9796 // binop x. This requirement is satisfied if the operators in expr have 9797 // precedence equal to or greater than binop, or by using parentheses around 9798 // expr or subexpressions of expr. 9799 // * For forms that allow multiple occurrences of x, the number of times 9800 // that x is evaluated is unspecified. 9801 if (AtomicKind == OMPC_read) { 9802 enum { 9803 NotAnExpression, 9804 NotAnAssignmentOp, 9805 NotAScalarType, 9806 NotAnLValue, 9807 NoError 9808 } ErrorFound = NoError; 9809 SourceLocation ErrorLoc, NoteLoc; 9810 SourceRange ErrorRange, NoteRange; 9811 // If clause is read: 9812 // v = x; 9813 if (const auto *AtomicBody = dyn_cast<Expr>(Body)) { 9814 const auto *AtomicBinOp = 9815 dyn_cast<BinaryOperator>(AtomicBody->IgnoreParenImpCasts()); 9816 if (AtomicBinOp && AtomicBinOp->getOpcode() == BO_Assign) { 9817 X = AtomicBinOp->getRHS()->IgnoreParenImpCasts(); 9818 V = AtomicBinOp->getLHS()->IgnoreParenImpCasts(); 9819 if ((X->isInstantiationDependent() || X->getType()->isScalarType()) && 9820 (V->isInstantiationDependent() || V->getType()->isScalarType())) { 9821 if (!X->isLValue() || !V->isLValue()) { 9822 const Expr *NotLValueExpr = X->isLValue() ? V : X; 9823 ErrorFound = NotAnLValue; 9824 ErrorLoc = AtomicBinOp->getExprLoc(); 9825 ErrorRange = AtomicBinOp->getSourceRange(); 9826 NoteLoc = NotLValueExpr->getExprLoc(); 9827 NoteRange = NotLValueExpr->getSourceRange(); 9828 } 9829 } else if (!X->isInstantiationDependent() || 9830 !V->isInstantiationDependent()) { 9831 const Expr *NotScalarExpr = 9832 (X->isInstantiationDependent() || X->getType()->isScalarType()) 9833 ? V 9834 : X; 9835 ErrorFound = NotAScalarType; 9836 ErrorLoc = AtomicBinOp->getExprLoc(); 9837 ErrorRange = AtomicBinOp->getSourceRange(); 9838 NoteLoc = NotScalarExpr->getExprLoc(); 9839 NoteRange = NotScalarExpr->getSourceRange(); 9840 } 9841 } else if (!AtomicBody->isInstantiationDependent()) { 9842 ErrorFound = NotAnAssignmentOp; 9843 ErrorLoc = AtomicBody->getExprLoc(); 9844 ErrorRange = AtomicBody->getSourceRange(); 9845 NoteLoc = AtomicBinOp ? AtomicBinOp->getOperatorLoc() 9846 : AtomicBody->getExprLoc(); 9847 NoteRange = AtomicBinOp ? AtomicBinOp->getSourceRange() 9848 : AtomicBody->getSourceRange(); 9849 } 9850 } else { 9851 ErrorFound = NotAnExpression; 9852 NoteLoc = ErrorLoc = Body->getBeginLoc(); 9853 NoteRange = ErrorRange = SourceRange(NoteLoc, NoteLoc); 9854 } 9855 if (ErrorFound != NoError) { 9856 Diag(ErrorLoc, diag::err_omp_atomic_read_not_expression_statement) 9857 << ErrorRange; 9858 Diag(NoteLoc, diag::note_omp_atomic_read_write) << ErrorFound 9859 << NoteRange; 9860 return StmtError(); 9861 } 9862 if (CurContext->isDependentContext()) 9863 V = X = nullptr; 9864 } else if (AtomicKind == OMPC_write) { 9865 enum { 9866 NotAnExpression, 9867 NotAnAssignmentOp, 9868 NotAScalarType, 9869 NotAnLValue, 9870 NoError 9871 } ErrorFound = NoError; 9872 SourceLocation ErrorLoc, NoteLoc; 9873 SourceRange ErrorRange, NoteRange; 9874 // If clause is write: 9875 // x = expr; 9876 if (const auto *AtomicBody = dyn_cast<Expr>(Body)) { 9877 const auto *AtomicBinOp = 9878 dyn_cast<BinaryOperator>(AtomicBody->IgnoreParenImpCasts()); 9879 if (AtomicBinOp && AtomicBinOp->getOpcode() == BO_Assign) { 9880 X = AtomicBinOp->getLHS(); 9881 E = AtomicBinOp->getRHS(); 9882 if ((X->isInstantiationDependent() || X->getType()->isScalarType()) && 9883 (E->isInstantiationDependent() || E->getType()->isScalarType())) { 9884 if (!X->isLValue()) { 9885 ErrorFound = NotAnLValue; 9886 ErrorLoc = AtomicBinOp->getExprLoc(); 9887 ErrorRange = AtomicBinOp->getSourceRange(); 9888 NoteLoc = X->getExprLoc(); 9889 NoteRange = X->getSourceRange(); 9890 } 9891 } else if (!X->isInstantiationDependent() || 9892 !E->isInstantiationDependent()) { 9893 const Expr *NotScalarExpr = 9894 (X->isInstantiationDependent() || X->getType()->isScalarType()) 9895 ? E 9896 : X; 9897 ErrorFound = NotAScalarType; 9898 ErrorLoc = AtomicBinOp->getExprLoc(); 9899 ErrorRange = AtomicBinOp->getSourceRange(); 9900 NoteLoc = NotScalarExpr->getExprLoc(); 9901 NoteRange = NotScalarExpr->getSourceRange(); 9902 } 9903 } else if (!AtomicBody->isInstantiationDependent()) { 9904 ErrorFound = NotAnAssignmentOp; 9905 ErrorLoc = AtomicBody->getExprLoc(); 9906 ErrorRange = AtomicBody->getSourceRange(); 9907 NoteLoc = AtomicBinOp ? AtomicBinOp->getOperatorLoc() 9908 : AtomicBody->getExprLoc(); 9909 NoteRange = AtomicBinOp ? AtomicBinOp->getSourceRange() 9910 : AtomicBody->getSourceRange(); 9911 } 9912 } else { 9913 ErrorFound = NotAnExpression; 9914 NoteLoc = ErrorLoc = Body->getBeginLoc(); 9915 NoteRange = ErrorRange = SourceRange(NoteLoc, NoteLoc); 9916 } 9917 if (ErrorFound != NoError) { 9918 Diag(ErrorLoc, diag::err_omp_atomic_write_not_expression_statement) 9919 << ErrorRange; 9920 Diag(NoteLoc, diag::note_omp_atomic_read_write) << ErrorFound 9921 << NoteRange; 9922 return StmtError(); 9923 } 9924 if (CurContext->isDependentContext()) 9925 E = X = nullptr; 9926 } else if (AtomicKind == OMPC_update || AtomicKind == OMPC_unknown) { 9927 // If clause is update: 9928 // x++; 9929 // x--; 9930 // ++x; 9931 // --x; 9932 // x binop= expr; 9933 // x = x binop expr; 9934 // x = expr binop x; 9935 OpenMPAtomicUpdateChecker Checker(*this); 9936 if (Checker.checkStatement( 9937 Body, (AtomicKind == OMPC_update) 9938 ? diag::err_omp_atomic_update_not_expression_statement 9939 : diag::err_omp_atomic_not_expression_statement, 9940 diag::note_omp_atomic_update)) 9941 return StmtError(); 9942 if (!CurContext->isDependentContext()) { 9943 E = Checker.getExpr(); 9944 X = Checker.getX(); 9945 UE = Checker.getUpdateExpr(); 9946 IsXLHSInRHSPart = Checker.isXLHSInRHSPart(); 9947 } 9948 } else if (AtomicKind == OMPC_capture) { 9949 enum { 9950 NotAnAssignmentOp, 9951 NotACompoundStatement, 9952 NotTwoSubstatements, 9953 NotASpecificExpression, 9954 NoError 9955 } ErrorFound = NoError; 9956 SourceLocation ErrorLoc, NoteLoc; 9957 SourceRange ErrorRange, NoteRange; 9958 if (const auto *AtomicBody = dyn_cast<Expr>(Body)) { 9959 // If clause is a capture: 9960 // v = x++; 9961 // v = x--; 9962 // v = ++x; 9963 // v = --x; 9964 // v = x binop= expr; 9965 // v = x = x binop expr; 9966 // v = x = expr binop x; 9967 const auto *AtomicBinOp = 9968 dyn_cast<BinaryOperator>(AtomicBody->IgnoreParenImpCasts()); 9969 if (AtomicBinOp && AtomicBinOp->getOpcode() == BO_Assign) { 9970 V = AtomicBinOp->getLHS(); 9971 Body = AtomicBinOp->getRHS()->IgnoreParenImpCasts(); 9972 OpenMPAtomicUpdateChecker Checker(*this); 9973 if (Checker.checkStatement( 9974 Body, diag::err_omp_atomic_capture_not_expression_statement, 9975 diag::note_omp_atomic_update)) 9976 return StmtError(); 9977 E = Checker.getExpr(); 9978 X = Checker.getX(); 9979 UE = Checker.getUpdateExpr(); 9980 IsXLHSInRHSPart = Checker.isXLHSInRHSPart(); 9981 IsPostfixUpdate = Checker.isPostfixUpdate(); 9982 } else if (!AtomicBody->isInstantiationDependent()) { 9983 ErrorLoc = AtomicBody->getExprLoc(); 9984 ErrorRange = AtomicBody->getSourceRange(); 9985 NoteLoc = AtomicBinOp ? AtomicBinOp->getOperatorLoc() 9986 : AtomicBody->getExprLoc(); 9987 NoteRange = AtomicBinOp ? AtomicBinOp->getSourceRange() 9988 : AtomicBody->getSourceRange(); 9989 ErrorFound = NotAnAssignmentOp; 9990 } 9991 if (ErrorFound != NoError) { 9992 Diag(ErrorLoc, diag::err_omp_atomic_capture_not_expression_statement) 9993 << ErrorRange; 9994 Diag(NoteLoc, diag::note_omp_atomic_capture) << ErrorFound << NoteRange; 9995 return StmtError(); 9996 } 9997 if (CurContext->isDependentContext()) 9998 UE = V = E = X = nullptr; 9999 } else { 10000 // If clause is a capture: 10001 // { v = x; x = expr; } 10002 // { v = x; x++; } 10003 // { v = x; x--; } 10004 // { v = x; ++x; } 10005 // { v = x; --x; } 10006 // { v = x; x binop= expr; } 10007 // { v = x; x = x binop expr; } 10008 // { v = x; x = expr binop x; } 10009 // { x++; v = x; } 10010 // { x--; v = x; } 10011 // { ++x; v = x; } 10012 // { --x; v = x; } 10013 // { x binop= expr; v = x; } 10014 // { x = x binop expr; v = x; } 10015 // { x = expr binop x; v = x; } 10016 if (auto *CS = dyn_cast<CompoundStmt>(Body)) { 10017 // Check that this is { expr1; expr2; } 10018 if (CS->size() == 2) { 10019 Stmt *First = CS->body_front(); 10020 Stmt *Second = CS->body_back(); 10021 if (auto *EWC = dyn_cast<ExprWithCleanups>(First)) 10022 First = EWC->getSubExpr()->IgnoreParenImpCasts(); 10023 if (auto *EWC = dyn_cast<ExprWithCleanups>(Second)) 10024 Second = EWC->getSubExpr()->IgnoreParenImpCasts(); 10025 // Need to find what subexpression is 'v' and what is 'x'. 10026 OpenMPAtomicUpdateChecker Checker(*this); 10027 bool IsUpdateExprFound = !Checker.checkStatement(Second); 10028 BinaryOperator *BinOp = nullptr; 10029 if (IsUpdateExprFound) { 10030 BinOp = dyn_cast<BinaryOperator>(First); 10031 IsUpdateExprFound = BinOp && BinOp->getOpcode() == BO_Assign; 10032 } 10033 if (IsUpdateExprFound && !CurContext->isDependentContext()) { 10034 // { v = x; x++; } 10035 // { v = x; x--; } 10036 // { v = x; ++x; } 10037 // { v = x; --x; } 10038 // { v = x; x binop= expr; } 10039 // { v = x; x = x binop expr; } 10040 // { v = x; x = expr binop x; } 10041 // Check that the first expression has form v = x. 10042 Expr *PossibleX = BinOp->getRHS()->IgnoreParenImpCasts(); 10043 llvm::FoldingSetNodeID XId, PossibleXId; 10044 Checker.getX()->Profile(XId, Context, /*Canonical=*/true); 10045 PossibleX->Profile(PossibleXId, Context, /*Canonical=*/true); 10046 IsUpdateExprFound = XId == PossibleXId; 10047 if (IsUpdateExprFound) { 10048 V = BinOp->getLHS(); 10049 X = Checker.getX(); 10050 E = Checker.getExpr(); 10051 UE = Checker.getUpdateExpr(); 10052 IsXLHSInRHSPart = Checker.isXLHSInRHSPart(); 10053 IsPostfixUpdate = true; 10054 } 10055 } 10056 if (!IsUpdateExprFound) { 10057 IsUpdateExprFound = !Checker.checkStatement(First); 10058 BinOp = nullptr; 10059 if (IsUpdateExprFound) { 10060 BinOp = dyn_cast<BinaryOperator>(Second); 10061 IsUpdateExprFound = BinOp && BinOp->getOpcode() == BO_Assign; 10062 } 10063 if (IsUpdateExprFound && !CurContext->isDependentContext()) { 10064 // { x++; v = x; } 10065 // { x--; v = x; } 10066 // { ++x; v = x; } 10067 // { --x; v = x; } 10068 // { x binop= expr; v = x; } 10069 // { x = x binop expr; v = x; } 10070 // { x = expr binop x; v = x; } 10071 // Check that the second expression has form v = x. 10072 Expr *PossibleX = BinOp->getRHS()->IgnoreParenImpCasts(); 10073 llvm::FoldingSetNodeID XId, PossibleXId; 10074 Checker.getX()->Profile(XId, Context, /*Canonical=*/true); 10075 PossibleX->Profile(PossibleXId, Context, /*Canonical=*/true); 10076 IsUpdateExprFound = XId == PossibleXId; 10077 if (IsUpdateExprFound) { 10078 V = BinOp->getLHS(); 10079 X = Checker.getX(); 10080 E = Checker.getExpr(); 10081 UE = Checker.getUpdateExpr(); 10082 IsXLHSInRHSPart = Checker.isXLHSInRHSPart(); 10083 IsPostfixUpdate = false; 10084 } 10085 } 10086 } 10087 if (!IsUpdateExprFound) { 10088 // { v = x; x = expr; } 10089 auto *FirstExpr = dyn_cast<Expr>(First); 10090 auto *SecondExpr = dyn_cast<Expr>(Second); 10091 if (!FirstExpr || !SecondExpr || 10092 !(FirstExpr->isInstantiationDependent() || 10093 SecondExpr->isInstantiationDependent())) { 10094 auto *FirstBinOp = dyn_cast<BinaryOperator>(First); 10095 if (!FirstBinOp || FirstBinOp->getOpcode() != BO_Assign) { 10096 ErrorFound = NotAnAssignmentOp; 10097 NoteLoc = ErrorLoc = FirstBinOp ? FirstBinOp->getOperatorLoc() 10098 : First->getBeginLoc(); 10099 NoteRange = ErrorRange = FirstBinOp 10100 ? FirstBinOp->getSourceRange() 10101 : SourceRange(ErrorLoc, ErrorLoc); 10102 } else { 10103 auto *SecondBinOp = dyn_cast<BinaryOperator>(Second); 10104 if (!SecondBinOp || SecondBinOp->getOpcode() != BO_Assign) { 10105 ErrorFound = NotAnAssignmentOp; 10106 NoteLoc = ErrorLoc = SecondBinOp 10107 ? SecondBinOp->getOperatorLoc() 10108 : Second->getBeginLoc(); 10109 NoteRange = ErrorRange = 10110 SecondBinOp ? SecondBinOp->getSourceRange() 10111 : SourceRange(ErrorLoc, ErrorLoc); 10112 } else { 10113 Expr *PossibleXRHSInFirst = 10114 FirstBinOp->getRHS()->IgnoreParenImpCasts(); 10115 Expr *PossibleXLHSInSecond = 10116 SecondBinOp->getLHS()->IgnoreParenImpCasts(); 10117 llvm::FoldingSetNodeID X1Id, X2Id; 10118 PossibleXRHSInFirst->Profile(X1Id, Context, 10119 /*Canonical=*/true); 10120 PossibleXLHSInSecond->Profile(X2Id, Context, 10121 /*Canonical=*/true); 10122 IsUpdateExprFound = X1Id == X2Id; 10123 if (IsUpdateExprFound) { 10124 V = FirstBinOp->getLHS(); 10125 X = SecondBinOp->getLHS(); 10126 E = SecondBinOp->getRHS(); 10127 UE = nullptr; 10128 IsXLHSInRHSPart = false; 10129 IsPostfixUpdate = true; 10130 } else { 10131 ErrorFound = NotASpecificExpression; 10132 ErrorLoc = FirstBinOp->getExprLoc(); 10133 ErrorRange = FirstBinOp->getSourceRange(); 10134 NoteLoc = SecondBinOp->getLHS()->getExprLoc(); 10135 NoteRange = SecondBinOp->getRHS()->getSourceRange(); 10136 } 10137 } 10138 } 10139 } 10140 } 10141 } else { 10142 NoteLoc = ErrorLoc = Body->getBeginLoc(); 10143 NoteRange = ErrorRange = 10144 SourceRange(Body->getBeginLoc(), Body->getBeginLoc()); 10145 ErrorFound = NotTwoSubstatements; 10146 } 10147 } else { 10148 NoteLoc = ErrorLoc = Body->getBeginLoc(); 10149 NoteRange = ErrorRange = 10150 SourceRange(Body->getBeginLoc(), Body->getBeginLoc()); 10151 ErrorFound = NotACompoundStatement; 10152 } 10153 if (ErrorFound != NoError) { 10154 Diag(ErrorLoc, diag::err_omp_atomic_capture_not_compound_statement) 10155 << ErrorRange; 10156 Diag(NoteLoc, diag::note_omp_atomic_capture) << ErrorFound << NoteRange; 10157 return StmtError(); 10158 } 10159 if (CurContext->isDependentContext()) 10160 UE = V = E = X = nullptr; 10161 } 10162 } 10163 10164 setFunctionHasBranchProtectedScope(); 10165 10166 return OMPAtomicDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt, 10167 X, V, E, UE, IsXLHSInRHSPart, 10168 IsPostfixUpdate); 10169 } 10170 10171 StmtResult Sema::ActOnOpenMPTargetDirective(ArrayRef<OMPClause *> Clauses, 10172 Stmt *AStmt, 10173 SourceLocation StartLoc, 10174 SourceLocation EndLoc) { 10175 if (!AStmt) 10176 return StmtError(); 10177 10178 auto *CS = cast<CapturedStmt>(AStmt); 10179 // 1.2.2 OpenMP Language Terminology 10180 // Structured block - An executable statement with a single entry at the 10181 // top and a single exit at the bottom. 10182 // The point of exit cannot be a branch out of the structured block. 10183 // longjmp() and throw() must not violate the entry/exit criteria. 10184 CS->getCapturedDecl()->setNothrow(); 10185 for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target); 10186 ThisCaptureLevel > 1; --ThisCaptureLevel) { 10187 CS = cast<CapturedStmt>(CS->getCapturedStmt()); 10188 // 1.2.2 OpenMP Language Terminology 10189 // Structured block - An executable statement with a single entry at the 10190 // top and a single exit at the bottom. 10191 // The point of exit cannot be a branch out of the structured block. 10192 // longjmp() and throw() must not violate the entry/exit criteria. 10193 CS->getCapturedDecl()->setNothrow(); 10194 } 10195 10196 // OpenMP [2.16, Nesting of Regions] 10197 // If specified, a teams construct must be contained within a target 10198 // construct. That target construct must contain no statements or directives 10199 // outside of the teams construct. 10200 if (DSAStack->hasInnerTeamsRegion()) { 10201 const Stmt *S = CS->IgnoreContainers(/*IgnoreCaptured=*/true); 10202 bool OMPTeamsFound = true; 10203 if (const auto *CS = dyn_cast<CompoundStmt>(S)) { 10204 auto I = CS->body_begin(); 10205 while (I != CS->body_end()) { 10206 const auto *OED = dyn_cast<OMPExecutableDirective>(*I); 10207 if (!OED || !isOpenMPTeamsDirective(OED->getDirectiveKind()) || 10208 OMPTeamsFound) { 10209 10210 OMPTeamsFound = false; 10211 break; 10212 } 10213 ++I; 10214 } 10215 assert(I != CS->body_end() && "Not found statement"); 10216 S = *I; 10217 } else { 10218 const auto *OED = dyn_cast<OMPExecutableDirective>(S); 10219 OMPTeamsFound = OED && isOpenMPTeamsDirective(OED->getDirectiveKind()); 10220 } 10221 if (!OMPTeamsFound) { 10222 Diag(StartLoc, diag::err_omp_target_contains_not_only_teams); 10223 Diag(DSAStack->getInnerTeamsRegionLoc(), 10224 diag::note_omp_nested_teams_construct_here); 10225 Diag(S->getBeginLoc(), diag::note_omp_nested_statement_here) 10226 << isa<OMPExecutableDirective>(S); 10227 return StmtError(); 10228 } 10229 } 10230 10231 setFunctionHasBranchProtectedScope(); 10232 10233 return OMPTargetDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt); 10234 } 10235 10236 StmtResult 10237 Sema::ActOnOpenMPTargetParallelDirective(ArrayRef<OMPClause *> Clauses, 10238 Stmt *AStmt, SourceLocation StartLoc, 10239 SourceLocation EndLoc) { 10240 if (!AStmt) 10241 return StmtError(); 10242 10243 auto *CS = cast<CapturedStmt>(AStmt); 10244 // 1.2.2 OpenMP Language Terminology 10245 // Structured block - An executable statement with a single entry at the 10246 // top and a single exit at the bottom. 10247 // The point of exit cannot be a branch out of the structured block. 10248 // longjmp() and throw() must not violate the entry/exit criteria. 10249 CS->getCapturedDecl()->setNothrow(); 10250 for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_parallel); 10251 ThisCaptureLevel > 1; --ThisCaptureLevel) { 10252 CS = cast<CapturedStmt>(CS->getCapturedStmt()); 10253 // 1.2.2 OpenMP Language Terminology 10254 // Structured block - An executable statement with a single entry at the 10255 // top and a single exit at the bottom. 10256 // The point of exit cannot be a branch out of the structured block. 10257 // longjmp() and throw() must not violate the entry/exit criteria. 10258 CS->getCapturedDecl()->setNothrow(); 10259 } 10260 10261 setFunctionHasBranchProtectedScope(); 10262 10263 return OMPTargetParallelDirective::Create( 10264 Context, StartLoc, EndLoc, Clauses, AStmt, 10265 DSAStack->getTaskgroupReductionRef(), DSAStack->isCancelRegion()); 10266 } 10267 10268 StmtResult Sema::ActOnOpenMPTargetParallelForDirective( 10269 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, 10270 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) { 10271 if (!AStmt) 10272 return StmtError(); 10273 10274 auto *CS = cast<CapturedStmt>(AStmt); 10275 // 1.2.2 OpenMP Language Terminology 10276 // Structured block - An executable statement with a single entry at the 10277 // top and a single exit at the bottom. 10278 // The point of exit cannot be a branch out of the structured block. 10279 // longjmp() and throw() must not violate the entry/exit criteria. 10280 CS->getCapturedDecl()->setNothrow(); 10281 for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_parallel_for); 10282 ThisCaptureLevel > 1; --ThisCaptureLevel) { 10283 CS = cast<CapturedStmt>(CS->getCapturedStmt()); 10284 // 1.2.2 OpenMP Language Terminology 10285 // Structured block - An executable statement with a single entry at the 10286 // top and a single exit at the bottom. 10287 // The point of exit cannot be a branch out of the structured block. 10288 // longjmp() and throw() must not violate the entry/exit criteria. 10289 CS->getCapturedDecl()->setNothrow(); 10290 } 10291 10292 OMPLoopDirective::HelperExprs B; 10293 // In presence of clause 'collapse' or 'ordered' with number of loops, it will 10294 // define the nested loops number. 10295 unsigned NestedLoopCount = 10296 checkOpenMPLoop(OMPD_target_parallel_for, getCollapseNumberExpr(Clauses), 10297 getOrderedNumberExpr(Clauses), CS, *this, *DSAStack, 10298 VarsWithImplicitDSA, B); 10299 if (NestedLoopCount == 0) 10300 return StmtError(); 10301 10302 assert((CurContext->isDependentContext() || B.builtAll()) && 10303 "omp target parallel for loop exprs were not built"); 10304 10305 if (!CurContext->isDependentContext()) { 10306 // Finalize the clauses that need pre-built expressions for CodeGen. 10307 for (OMPClause *C : Clauses) { 10308 if (auto *LC = dyn_cast<OMPLinearClause>(C)) 10309 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef), 10310 B.NumIterations, *this, CurScope, 10311 DSAStack)) 10312 return StmtError(); 10313 } 10314 } 10315 10316 setFunctionHasBranchProtectedScope(); 10317 return OMPTargetParallelForDirective::Create( 10318 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B, 10319 DSAStack->getTaskgroupReductionRef(), DSAStack->isCancelRegion()); 10320 } 10321 10322 /// Check for existence of a map clause in the list of clauses. 10323 static bool hasClauses(ArrayRef<OMPClause *> Clauses, 10324 const OpenMPClauseKind K) { 10325 return llvm::any_of( 10326 Clauses, [K](const OMPClause *C) { return C->getClauseKind() == K; }); 10327 } 10328 10329 template <typename... Params> 10330 static bool hasClauses(ArrayRef<OMPClause *> Clauses, const OpenMPClauseKind K, 10331 const Params... ClauseTypes) { 10332 return hasClauses(Clauses, K) || hasClauses(Clauses, ClauseTypes...); 10333 } 10334 10335 StmtResult Sema::ActOnOpenMPTargetDataDirective(ArrayRef<OMPClause *> Clauses, 10336 Stmt *AStmt, 10337 SourceLocation StartLoc, 10338 SourceLocation EndLoc) { 10339 if (!AStmt) 10340 return StmtError(); 10341 10342 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected"); 10343 10344 // OpenMP [2.12.2, target data Construct, Restrictions] 10345 // At least one map, use_device_addr or use_device_ptr clause must appear on 10346 // the directive. 10347 if (!hasClauses(Clauses, OMPC_map, OMPC_use_device_ptr) && 10348 (LangOpts.OpenMP < 50 || !hasClauses(Clauses, OMPC_use_device_addr))) { 10349 StringRef Expected; 10350 if (LangOpts.OpenMP < 50) 10351 Expected = "'map' or 'use_device_ptr'"; 10352 else 10353 Expected = "'map', 'use_device_ptr', or 'use_device_addr'"; 10354 Diag(StartLoc, diag::err_omp_no_clause_for_directive) 10355 << Expected << getOpenMPDirectiveName(OMPD_target_data); 10356 return StmtError(); 10357 } 10358 10359 setFunctionHasBranchProtectedScope(); 10360 10361 return OMPTargetDataDirective::Create(Context, StartLoc, EndLoc, Clauses, 10362 AStmt); 10363 } 10364 10365 StmtResult 10366 Sema::ActOnOpenMPTargetEnterDataDirective(ArrayRef<OMPClause *> Clauses, 10367 SourceLocation StartLoc, 10368 SourceLocation EndLoc, Stmt *AStmt) { 10369 if (!AStmt) 10370 return StmtError(); 10371 10372 auto *CS = cast<CapturedStmt>(AStmt); 10373 // 1.2.2 OpenMP Language Terminology 10374 // Structured block - An executable statement with a single entry at the 10375 // top and a single exit at the bottom. 10376 // The point of exit cannot be a branch out of the structured block. 10377 // longjmp() and throw() must not violate the entry/exit criteria. 10378 CS->getCapturedDecl()->setNothrow(); 10379 for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_enter_data); 10380 ThisCaptureLevel > 1; --ThisCaptureLevel) { 10381 CS = cast<CapturedStmt>(CS->getCapturedStmt()); 10382 // 1.2.2 OpenMP Language Terminology 10383 // Structured block - An executable statement with a single entry at the 10384 // top and a single exit at the bottom. 10385 // The point of exit cannot be a branch out of the structured block. 10386 // longjmp() and throw() must not violate the entry/exit criteria. 10387 CS->getCapturedDecl()->setNothrow(); 10388 } 10389 10390 // OpenMP [2.10.2, Restrictions, p. 99] 10391 // At least one map clause must appear on the directive. 10392 if (!hasClauses(Clauses, OMPC_map)) { 10393 Diag(StartLoc, diag::err_omp_no_clause_for_directive) 10394 << "'map'" << getOpenMPDirectiveName(OMPD_target_enter_data); 10395 return StmtError(); 10396 } 10397 10398 return OMPTargetEnterDataDirective::Create(Context, StartLoc, EndLoc, Clauses, 10399 AStmt); 10400 } 10401 10402 StmtResult 10403 Sema::ActOnOpenMPTargetExitDataDirective(ArrayRef<OMPClause *> Clauses, 10404 SourceLocation StartLoc, 10405 SourceLocation EndLoc, Stmt *AStmt) { 10406 if (!AStmt) 10407 return StmtError(); 10408 10409 auto *CS = cast<CapturedStmt>(AStmt); 10410 // 1.2.2 OpenMP Language Terminology 10411 // Structured block - An executable statement with a single entry at the 10412 // top and a single exit at the bottom. 10413 // The point of exit cannot be a branch out of the structured block. 10414 // longjmp() and throw() must not violate the entry/exit criteria. 10415 CS->getCapturedDecl()->setNothrow(); 10416 for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_exit_data); 10417 ThisCaptureLevel > 1; --ThisCaptureLevel) { 10418 CS = cast<CapturedStmt>(CS->getCapturedStmt()); 10419 // 1.2.2 OpenMP Language Terminology 10420 // Structured block - An executable statement with a single entry at the 10421 // top and a single exit at the bottom. 10422 // The point of exit cannot be a branch out of the structured block. 10423 // longjmp() and throw() must not violate the entry/exit criteria. 10424 CS->getCapturedDecl()->setNothrow(); 10425 } 10426 10427 // OpenMP [2.10.3, Restrictions, p. 102] 10428 // At least one map clause must appear on the directive. 10429 if (!hasClauses(Clauses, OMPC_map)) { 10430 Diag(StartLoc, diag::err_omp_no_clause_for_directive) 10431 << "'map'" << getOpenMPDirectiveName(OMPD_target_exit_data); 10432 return StmtError(); 10433 } 10434 10435 return OMPTargetExitDataDirective::Create(Context, StartLoc, EndLoc, Clauses, 10436 AStmt); 10437 } 10438 10439 StmtResult Sema::ActOnOpenMPTargetUpdateDirective(ArrayRef<OMPClause *> Clauses, 10440 SourceLocation StartLoc, 10441 SourceLocation EndLoc, 10442 Stmt *AStmt) { 10443 if (!AStmt) 10444 return StmtError(); 10445 10446 auto *CS = cast<CapturedStmt>(AStmt); 10447 // 1.2.2 OpenMP Language Terminology 10448 // Structured block - An executable statement with a single entry at the 10449 // top and a single exit at the bottom. 10450 // The point of exit cannot be a branch out of the structured block. 10451 // longjmp() and throw() must not violate the entry/exit criteria. 10452 CS->getCapturedDecl()->setNothrow(); 10453 for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_update); 10454 ThisCaptureLevel > 1; --ThisCaptureLevel) { 10455 CS = cast<CapturedStmt>(CS->getCapturedStmt()); 10456 // 1.2.2 OpenMP Language Terminology 10457 // Structured block - An executable statement with a single entry at the 10458 // top and a single exit at the bottom. 10459 // The point of exit cannot be a branch out of the structured block. 10460 // longjmp() and throw() must not violate the entry/exit criteria. 10461 CS->getCapturedDecl()->setNothrow(); 10462 } 10463 10464 if (!hasClauses(Clauses, OMPC_to, OMPC_from)) { 10465 Diag(StartLoc, diag::err_omp_at_least_one_motion_clause_required); 10466 return StmtError(); 10467 } 10468 return OMPTargetUpdateDirective::Create(Context, StartLoc, EndLoc, Clauses, 10469 AStmt); 10470 } 10471 10472 StmtResult Sema::ActOnOpenMPTeamsDirective(ArrayRef<OMPClause *> Clauses, 10473 Stmt *AStmt, SourceLocation StartLoc, 10474 SourceLocation EndLoc) { 10475 if (!AStmt) 10476 return StmtError(); 10477 10478 auto *CS = cast<CapturedStmt>(AStmt); 10479 // 1.2.2 OpenMP Language Terminology 10480 // Structured block - An executable statement with a single entry at the 10481 // top and a single exit at the bottom. 10482 // The point of exit cannot be a branch out of the structured block. 10483 // longjmp() and throw() must not violate the entry/exit criteria. 10484 CS->getCapturedDecl()->setNothrow(); 10485 10486 setFunctionHasBranchProtectedScope(); 10487 10488 DSAStack->setParentTeamsRegionLoc(StartLoc); 10489 10490 return OMPTeamsDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt); 10491 } 10492 10493 StmtResult 10494 Sema::ActOnOpenMPCancellationPointDirective(SourceLocation StartLoc, 10495 SourceLocation EndLoc, 10496 OpenMPDirectiveKind CancelRegion) { 10497 if (DSAStack->isParentNowaitRegion()) { 10498 Diag(StartLoc, diag::err_omp_parent_cancel_region_nowait) << 0; 10499 return StmtError(); 10500 } 10501 if (DSAStack->isParentOrderedRegion()) { 10502 Diag(StartLoc, diag::err_omp_parent_cancel_region_ordered) << 0; 10503 return StmtError(); 10504 } 10505 return OMPCancellationPointDirective::Create(Context, StartLoc, EndLoc, 10506 CancelRegion); 10507 } 10508 10509 StmtResult Sema::ActOnOpenMPCancelDirective(ArrayRef<OMPClause *> Clauses, 10510 SourceLocation StartLoc, 10511 SourceLocation EndLoc, 10512 OpenMPDirectiveKind CancelRegion) { 10513 if (DSAStack->isParentNowaitRegion()) { 10514 Diag(StartLoc, diag::err_omp_parent_cancel_region_nowait) << 1; 10515 return StmtError(); 10516 } 10517 if (DSAStack->isParentOrderedRegion()) { 10518 Diag(StartLoc, diag::err_omp_parent_cancel_region_ordered) << 1; 10519 return StmtError(); 10520 } 10521 DSAStack->setParentCancelRegion(/*Cancel=*/true); 10522 return OMPCancelDirective::Create(Context, StartLoc, EndLoc, Clauses, 10523 CancelRegion); 10524 } 10525 10526 static bool checkGrainsizeNumTasksClauses(Sema &S, 10527 ArrayRef<OMPClause *> Clauses) { 10528 const OMPClause *PrevClause = nullptr; 10529 bool ErrorFound = false; 10530 for (const OMPClause *C : Clauses) { 10531 if (C->getClauseKind() == OMPC_grainsize || 10532 C->getClauseKind() == OMPC_num_tasks) { 10533 if (!PrevClause) 10534 PrevClause = C; 10535 else if (PrevClause->getClauseKind() != C->getClauseKind()) { 10536 S.Diag(C->getBeginLoc(), diag::err_omp_clauses_mutually_exclusive) 10537 << getOpenMPClauseName(C->getClauseKind()) 10538 << getOpenMPClauseName(PrevClause->getClauseKind()); 10539 S.Diag(PrevClause->getBeginLoc(), diag::note_omp_previous_clause) 10540 << getOpenMPClauseName(PrevClause->getClauseKind()); 10541 ErrorFound = true; 10542 } 10543 } 10544 } 10545 return ErrorFound; 10546 } 10547 10548 static bool checkReductionClauseWithNogroup(Sema &S, 10549 ArrayRef<OMPClause *> Clauses) { 10550 const OMPClause *ReductionClause = nullptr; 10551 const OMPClause *NogroupClause = nullptr; 10552 for (const OMPClause *C : Clauses) { 10553 if (C->getClauseKind() == OMPC_reduction) { 10554 ReductionClause = C; 10555 if (NogroupClause) 10556 break; 10557 continue; 10558 } 10559 if (C->getClauseKind() == OMPC_nogroup) { 10560 NogroupClause = C; 10561 if (ReductionClause) 10562 break; 10563 continue; 10564 } 10565 } 10566 if (ReductionClause && NogroupClause) { 10567 S.Diag(ReductionClause->getBeginLoc(), diag::err_omp_reduction_with_nogroup) 10568 << SourceRange(NogroupClause->getBeginLoc(), 10569 NogroupClause->getEndLoc()); 10570 return true; 10571 } 10572 return false; 10573 } 10574 10575 StmtResult Sema::ActOnOpenMPTaskLoopDirective( 10576 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, 10577 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) { 10578 if (!AStmt) 10579 return StmtError(); 10580 10581 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected"); 10582 OMPLoopDirective::HelperExprs B; 10583 // In presence of clause 'collapse' or 'ordered' with number of loops, it will 10584 // define the nested loops number. 10585 unsigned NestedLoopCount = 10586 checkOpenMPLoop(OMPD_taskloop, getCollapseNumberExpr(Clauses), 10587 /*OrderedLoopCountExpr=*/nullptr, AStmt, *this, *DSAStack, 10588 VarsWithImplicitDSA, B); 10589 if (NestedLoopCount == 0) 10590 return StmtError(); 10591 10592 assert((CurContext->isDependentContext() || B.builtAll()) && 10593 "omp for loop exprs were not built"); 10594 10595 // OpenMP, [2.9.2 taskloop Construct, Restrictions] 10596 // The grainsize clause and num_tasks clause are mutually exclusive and may 10597 // not appear on the same taskloop directive. 10598 if (checkGrainsizeNumTasksClauses(*this, Clauses)) 10599 return StmtError(); 10600 // OpenMP, [2.9.2 taskloop Construct, Restrictions] 10601 // If a reduction clause is present on the taskloop directive, the nogroup 10602 // clause must not be specified. 10603 if (checkReductionClauseWithNogroup(*this, Clauses)) 10604 return StmtError(); 10605 10606 setFunctionHasBranchProtectedScope(); 10607 return OMPTaskLoopDirective::Create(Context, StartLoc, EndLoc, 10608 NestedLoopCount, Clauses, AStmt, B, 10609 DSAStack->isCancelRegion()); 10610 } 10611 10612 StmtResult Sema::ActOnOpenMPTaskLoopSimdDirective( 10613 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, 10614 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) { 10615 if (!AStmt) 10616 return StmtError(); 10617 10618 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected"); 10619 OMPLoopDirective::HelperExprs B; 10620 // In presence of clause 'collapse' or 'ordered' with number of loops, it will 10621 // define the nested loops number. 10622 unsigned NestedLoopCount = 10623 checkOpenMPLoop(OMPD_taskloop_simd, getCollapseNumberExpr(Clauses), 10624 /*OrderedLoopCountExpr=*/nullptr, AStmt, *this, *DSAStack, 10625 VarsWithImplicitDSA, B); 10626 if (NestedLoopCount == 0) 10627 return StmtError(); 10628 10629 assert((CurContext->isDependentContext() || B.builtAll()) && 10630 "omp for loop exprs were not built"); 10631 10632 if (!CurContext->isDependentContext()) { 10633 // Finalize the clauses that need pre-built expressions for CodeGen. 10634 for (OMPClause *C : Clauses) { 10635 if (auto *LC = dyn_cast<OMPLinearClause>(C)) 10636 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef), 10637 B.NumIterations, *this, CurScope, 10638 DSAStack)) 10639 return StmtError(); 10640 } 10641 } 10642 10643 // OpenMP, [2.9.2 taskloop Construct, Restrictions] 10644 // The grainsize clause and num_tasks clause are mutually exclusive and may 10645 // not appear on the same taskloop directive. 10646 if (checkGrainsizeNumTasksClauses(*this, Clauses)) 10647 return StmtError(); 10648 // OpenMP, [2.9.2 taskloop Construct, Restrictions] 10649 // If a reduction clause is present on the taskloop directive, the nogroup 10650 // clause must not be specified. 10651 if (checkReductionClauseWithNogroup(*this, Clauses)) 10652 return StmtError(); 10653 if (checkSimdlenSafelenSpecified(*this, Clauses)) 10654 return StmtError(); 10655 10656 setFunctionHasBranchProtectedScope(); 10657 return OMPTaskLoopSimdDirective::Create(Context, StartLoc, EndLoc, 10658 NestedLoopCount, Clauses, AStmt, B); 10659 } 10660 10661 StmtResult Sema::ActOnOpenMPMasterTaskLoopDirective( 10662 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, 10663 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) { 10664 if (!AStmt) 10665 return StmtError(); 10666 10667 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected"); 10668 OMPLoopDirective::HelperExprs B; 10669 // In presence of clause 'collapse' or 'ordered' with number of loops, it will 10670 // define the nested loops number. 10671 unsigned NestedLoopCount = 10672 checkOpenMPLoop(OMPD_master_taskloop, getCollapseNumberExpr(Clauses), 10673 /*OrderedLoopCountExpr=*/nullptr, AStmt, *this, *DSAStack, 10674 VarsWithImplicitDSA, B); 10675 if (NestedLoopCount == 0) 10676 return StmtError(); 10677 10678 assert((CurContext->isDependentContext() || B.builtAll()) && 10679 "omp for loop exprs were not built"); 10680 10681 // OpenMP, [2.9.2 taskloop Construct, Restrictions] 10682 // The grainsize clause and num_tasks clause are mutually exclusive and may 10683 // not appear on the same taskloop directive. 10684 if (checkGrainsizeNumTasksClauses(*this, Clauses)) 10685 return StmtError(); 10686 // OpenMP, [2.9.2 taskloop Construct, Restrictions] 10687 // If a reduction clause is present on the taskloop directive, the nogroup 10688 // clause must not be specified. 10689 if (checkReductionClauseWithNogroup(*this, Clauses)) 10690 return StmtError(); 10691 10692 setFunctionHasBranchProtectedScope(); 10693 return OMPMasterTaskLoopDirective::Create(Context, StartLoc, EndLoc, 10694 NestedLoopCount, Clauses, AStmt, B, 10695 DSAStack->isCancelRegion()); 10696 } 10697 10698 StmtResult Sema::ActOnOpenMPMasterTaskLoopSimdDirective( 10699 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, 10700 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) { 10701 if (!AStmt) 10702 return StmtError(); 10703 10704 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected"); 10705 OMPLoopDirective::HelperExprs B; 10706 // In presence of clause 'collapse' or 'ordered' with number of loops, it will 10707 // define the nested loops number. 10708 unsigned NestedLoopCount = 10709 checkOpenMPLoop(OMPD_master_taskloop_simd, getCollapseNumberExpr(Clauses), 10710 /*OrderedLoopCountExpr=*/nullptr, AStmt, *this, *DSAStack, 10711 VarsWithImplicitDSA, B); 10712 if (NestedLoopCount == 0) 10713 return StmtError(); 10714 10715 assert((CurContext->isDependentContext() || B.builtAll()) && 10716 "omp for loop exprs were not built"); 10717 10718 if (!CurContext->isDependentContext()) { 10719 // Finalize the clauses that need pre-built expressions for CodeGen. 10720 for (OMPClause *C : Clauses) { 10721 if (auto *LC = dyn_cast<OMPLinearClause>(C)) 10722 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef), 10723 B.NumIterations, *this, CurScope, 10724 DSAStack)) 10725 return StmtError(); 10726 } 10727 } 10728 10729 // OpenMP, [2.9.2 taskloop Construct, Restrictions] 10730 // The grainsize clause and num_tasks clause are mutually exclusive and may 10731 // not appear on the same taskloop directive. 10732 if (checkGrainsizeNumTasksClauses(*this, Clauses)) 10733 return StmtError(); 10734 // OpenMP, [2.9.2 taskloop Construct, Restrictions] 10735 // If a reduction clause is present on the taskloop directive, the nogroup 10736 // clause must not be specified. 10737 if (checkReductionClauseWithNogroup(*this, Clauses)) 10738 return StmtError(); 10739 if (checkSimdlenSafelenSpecified(*this, Clauses)) 10740 return StmtError(); 10741 10742 setFunctionHasBranchProtectedScope(); 10743 return OMPMasterTaskLoopSimdDirective::Create( 10744 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B); 10745 } 10746 10747 StmtResult Sema::ActOnOpenMPParallelMasterTaskLoopDirective( 10748 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, 10749 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) { 10750 if (!AStmt) 10751 return StmtError(); 10752 10753 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected"); 10754 auto *CS = cast<CapturedStmt>(AStmt); 10755 // 1.2.2 OpenMP Language Terminology 10756 // Structured block - An executable statement with a single entry at the 10757 // top and a single exit at the bottom. 10758 // The point of exit cannot be a branch out of the structured block. 10759 // longjmp() and throw() must not violate the entry/exit criteria. 10760 CS->getCapturedDecl()->setNothrow(); 10761 for (int ThisCaptureLevel = 10762 getOpenMPCaptureLevels(OMPD_parallel_master_taskloop); 10763 ThisCaptureLevel > 1; --ThisCaptureLevel) { 10764 CS = cast<CapturedStmt>(CS->getCapturedStmt()); 10765 // 1.2.2 OpenMP Language Terminology 10766 // Structured block - An executable statement with a single entry at the 10767 // top and a single exit at the bottom. 10768 // The point of exit cannot be a branch out of the structured block. 10769 // longjmp() and throw() must not violate the entry/exit criteria. 10770 CS->getCapturedDecl()->setNothrow(); 10771 } 10772 10773 OMPLoopDirective::HelperExprs B; 10774 // In presence of clause 'collapse' or 'ordered' with number of loops, it will 10775 // define the nested loops number. 10776 unsigned NestedLoopCount = checkOpenMPLoop( 10777 OMPD_parallel_master_taskloop, getCollapseNumberExpr(Clauses), 10778 /*OrderedLoopCountExpr=*/nullptr, CS, *this, *DSAStack, 10779 VarsWithImplicitDSA, B); 10780 if (NestedLoopCount == 0) 10781 return StmtError(); 10782 10783 assert((CurContext->isDependentContext() || B.builtAll()) && 10784 "omp for loop exprs were not built"); 10785 10786 // OpenMP, [2.9.2 taskloop Construct, Restrictions] 10787 // The grainsize clause and num_tasks clause are mutually exclusive and may 10788 // not appear on the same taskloop directive. 10789 if (checkGrainsizeNumTasksClauses(*this, Clauses)) 10790 return StmtError(); 10791 // OpenMP, [2.9.2 taskloop Construct, Restrictions] 10792 // If a reduction clause is present on the taskloop directive, the nogroup 10793 // clause must not be specified. 10794 if (checkReductionClauseWithNogroup(*this, Clauses)) 10795 return StmtError(); 10796 10797 setFunctionHasBranchProtectedScope(); 10798 return OMPParallelMasterTaskLoopDirective::Create( 10799 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B, 10800 DSAStack->isCancelRegion()); 10801 } 10802 10803 StmtResult Sema::ActOnOpenMPParallelMasterTaskLoopSimdDirective( 10804 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, 10805 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) { 10806 if (!AStmt) 10807 return StmtError(); 10808 10809 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected"); 10810 auto *CS = cast<CapturedStmt>(AStmt); 10811 // 1.2.2 OpenMP Language Terminology 10812 // Structured block - An executable statement with a single entry at the 10813 // top and a single exit at the bottom. 10814 // The point of exit cannot be a branch out of the structured block. 10815 // longjmp() and throw() must not violate the entry/exit criteria. 10816 CS->getCapturedDecl()->setNothrow(); 10817 for (int ThisCaptureLevel = 10818 getOpenMPCaptureLevels(OMPD_parallel_master_taskloop_simd); 10819 ThisCaptureLevel > 1; --ThisCaptureLevel) { 10820 CS = cast<CapturedStmt>(CS->getCapturedStmt()); 10821 // 1.2.2 OpenMP Language Terminology 10822 // Structured block - An executable statement with a single entry at the 10823 // top and a single exit at the bottom. 10824 // The point of exit cannot be a branch out of the structured block. 10825 // longjmp() and throw() must not violate the entry/exit criteria. 10826 CS->getCapturedDecl()->setNothrow(); 10827 } 10828 10829 OMPLoopDirective::HelperExprs B; 10830 // In presence of clause 'collapse' or 'ordered' with number of loops, it will 10831 // define the nested loops number. 10832 unsigned NestedLoopCount = checkOpenMPLoop( 10833 OMPD_parallel_master_taskloop_simd, getCollapseNumberExpr(Clauses), 10834 /*OrderedLoopCountExpr=*/nullptr, CS, *this, *DSAStack, 10835 VarsWithImplicitDSA, B); 10836 if (NestedLoopCount == 0) 10837 return StmtError(); 10838 10839 assert((CurContext->isDependentContext() || B.builtAll()) && 10840 "omp for loop exprs were not built"); 10841 10842 if (!CurContext->isDependentContext()) { 10843 // Finalize the clauses that need pre-built expressions for CodeGen. 10844 for (OMPClause *C : Clauses) { 10845 if (auto *LC = dyn_cast<OMPLinearClause>(C)) 10846 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef), 10847 B.NumIterations, *this, CurScope, 10848 DSAStack)) 10849 return StmtError(); 10850 } 10851 } 10852 10853 // OpenMP, [2.9.2 taskloop Construct, Restrictions] 10854 // The grainsize clause and num_tasks clause are mutually exclusive and may 10855 // not appear on the same taskloop directive. 10856 if (checkGrainsizeNumTasksClauses(*this, Clauses)) 10857 return StmtError(); 10858 // OpenMP, [2.9.2 taskloop Construct, Restrictions] 10859 // If a reduction clause is present on the taskloop directive, the nogroup 10860 // clause must not be specified. 10861 if (checkReductionClauseWithNogroup(*this, Clauses)) 10862 return StmtError(); 10863 if (checkSimdlenSafelenSpecified(*this, Clauses)) 10864 return StmtError(); 10865 10866 setFunctionHasBranchProtectedScope(); 10867 return OMPParallelMasterTaskLoopSimdDirective::Create( 10868 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B); 10869 } 10870 10871 StmtResult Sema::ActOnOpenMPDistributeDirective( 10872 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, 10873 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) { 10874 if (!AStmt) 10875 return StmtError(); 10876 10877 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected"); 10878 OMPLoopDirective::HelperExprs B; 10879 // In presence of clause 'collapse' with number of loops, it will 10880 // define the nested loops number. 10881 unsigned NestedLoopCount = 10882 checkOpenMPLoop(OMPD_distribute, getCollapseNumberExpr(Clauses), 10883 nullptr /*ordered not a clause on distribute*/, AStmt, 10884 *this, *DSAStack, VarsWithImplicitDSA, B); 10885 if (NestedLoopCount == 0) 10886 return StmtError(); 10887 10888 assert((CurContext->isDependentContext() || B.builtAll()) && 10889 "omp for loop exprs were not built"); 10890 10891 setFunctionHasBranchProtectedScope(); 10892 return OMPDistributeDirective::Create(Context, StartLoc, EndLoc, 10893 NestedLoopCount, Clauses, AStmt, B); 10894 } 10895 10896 StmtResult Sema::ActOnOpenMPDistributeParallelForDirective( 10897 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, 10898 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) { 10899 if (!AStmt) 10900 return StmtError(); 10901 10902 auto *CS = cast<CapturedStmt>(AStmt); 10903 // 1.2.2 OpenMP Language Terminology 10904 // Structured block - An executable statement with a single entry at the 10905 // top and a single exit at the bottom. 10906 // The point of exit cannot be a branch out of the structured block. 10907 // longjmp() and throw() must not violate the entry/exit criteria. 10908 CS->getCapturedDecl()->setNothrow(); 10909 for (int ThisCaptureLevel = 10910 getOpenMPCaptureLevels(OMPD_distribute_parallel_for); 10911 ThisCaptureLevel > 1; --ThisCaptureLevel) { 10912 CS = cast<CapturedStmt>(CS->getCapturedStmt()); 10913 // 1.2.2 OpenMP Language Terminology 10914 // Structured block - An executable statement with a single entry at the 10915 // top and a single exit at the bottom. 10916 // The point of exit cannot be a branch out of the structured block. 10917 // longjmp() and throw() must not violate the entry/exit criteria. 10918 CS->getCapturedDecl()->setNothrow(); 10919 } 10920 10921 OMPLoopDirective::HelperExprs B; 10922 // In presence of clause 'collapse' with number of loops, it will 10923 // define the nested loops number. 10924 unsigned NestedLoopCount = checkOpenMPLoop( 10925 OMPD_distribute_parallel_for, getCollapseNumberExpr(Clauses), 10926 nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStack, 10927 VarsWithImplicitDSA, B); 10928 if (NestedLoopCount == 0) 10929 return StmtError(); 10930 10931 assert((CurContext->isDependentContext() || B.builtAll()) && 10932 "omp for loop exprs were not built"); 10933 10934 setFunctionHasBranchProtectedScope(); 10935 return OMPDistributeParallelForDirective::Create( 10936 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B, 10937 DSAStack->getTaskgroupReductionRef(), DSAStack->isCancelRegion()); 10938 } 10939 10940 StmtResult Sema::ActOnOpenMPDistributeParallelForSimdDirective( 10941 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, 10942 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) { 10943 if (!AStmt) 10944 return StmtError(); 10945 10946 auto *CS = cast<CapturedStmt>(AStmt); 10947 // 1.2.2 OpenMP Language Terminology 10948 // Structured block - An executable statement with a single entry at the 10949 // top and a single exit at the bottom. 10950 // The point of exit cannot be a branch out of the structured block. 10951 // longjmp() and throw() must not violate the entry/exit criteria. 10952 CS->getCapturedDecl()->setNothrow(); 10953 for (int ThisCaptureLevel = 10954 getOpenMPCaptureLevels(OMPD_distribute_parallel_for_simd); 10955 ThisCaptureLevel > 1; --ThisCaptureLevel) { 10956 CS = cast<CapturedStmt>(CS->getCapturedStmt()); 10957 // 1.2.2 OpenMP Language Terminology 10958 // Structured block - An executable statement with a single entry at the 10959 // top and a single exit at the bottom. 10960 // The point of exit cannot be a branch out of the structured block. 10961 // longjmp() and throw() must not violate the entry/exit criteria. 10962 CS->getCapturedDecl()->setNothrow(); 10963 } 10964 10965 OMPLoopDirective::HelperExprs B; 10966 // In presence of clause 'collapse' with number of loops, it will 10967 // define the nested loops number. 10968 unsigned NestedLoopCount = checkOpenMPLoop( 10969 OMPD_distribute_parallel_for_simd, getCollapseNumberExpr(Clauses), 10970 nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStack, 10971 VarsWithImplicitDSA, B); 10972 if (NestedLoopCount == 0) 10973 return StmtError(); 10974 10975 assert((CurContext->isDependentContext() || B.builtAll()) && 10976 "omp for loop exprs were not built"); 10977 10978 if (!CurContext->isDependentContext()) { 10979 // Finalize the clauses that need pre-built expressions for CodeGen. 10980 for (OMPClause *C : Clauses) { 10981 if (auto *LC = dyn_cast<OMPLinearClause>(C)) 10982 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef), 10983 B.NumIterations, *this, CurScope, 10984 DSAStack)) 10985 return StmtError(); 10986 } 10987 } 10988 10989 if (checkSimdlenSafelenSpecified(*this, Clauses)) 10990 return StmtError(); 10991 10992 setFunctionHasBranchProtectedScope(); 10993 return OMPDistributeParallelForSimdDirective::Create( 10994 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B); 10995 } 10996 10997 StmtResult Sema::ActOnOpenMPDistributeSimdDirective( 10998 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, 10999 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) { 11000 if (!AStmt) 11001 return StmtError(); 11002 11003 auto *CS = cast<CapturedStmt>(AStmt); 11004 // 1.2.2 OpenMP Language Terminology 11005 // Structured block - An executable statement with a single entry at the 11006 // top and a single exit at the bottom. 11007 // The point of exit cannot be a branch out of the structured block. 11008 // longjmp() and throw() must not violate the entry/exit criteria. 11009 CS->getCapturedDecl()->setNothrow(); 11010 for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_distribute_simd); 11011 ThisCaptureLevel > 1; --ThisCaptureLevel) { 11012 CS = cast<CapturedStmt>(CS->getCapturedStmt()); 11013 // 1.2.2 OpenMP Language Terminology 11014 // Structured block - An executable statement with a single entry at the 11015 // top and a single exit at the bottom. 11016 // The point of exit cannot be a branch out of the structured block. 11017 // longjmp() and throw() must not violate the entry/exit criteria. 11018 CS->getCapturedDecl()->setNothrow(); 11019 } 11020 11021 OMPLoopDirective::HelperExprs B; 11022 // In presence of clause 'collapse' with number of loops, it will 11023 // define the nested loops number. 11024 unsigned NestedLoopCount = 11025 checkOpenMPLoop(OMPD_distribute_simd, getCollapseNumberExpr(Clauses), 11026 nullptr /*ordered not a clause on distribute*/, CS, *this, 11027 *DSAStack, VarsWithImplicitDSA, B); 11028 if (NestedLoopCount == 0) 11029 return StmtError(); 11030 11031 assert((CurContext->isDependentContext() || B.builtAll()) && 11032 "omp for loop exprs were not built"); 11033 11034 if (!CurContext->isDependentContext()) { 11035 // Finalize the clauses that need pre-built expressions for CodeGen. 11036 for (OMPClause *C : Clauses) { 11037 if (auto *LC = dyn_cast<OMPLinearClause>(C)) 11038 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef), 11039 B.NumIterations, *this, CurScope, 11040 DSAStack)) 11041 return StmtError(); 11042 } 11043 } 11044 11045 if (checkSimdlenSafelenSpecified(*this, Clauses)) 11046 return StmtError(); 11047 11048 setFunctionHasBranchProtectedScope(); 11049 return OMPDistributeSimdDirective::Create(Context, StartLoc, EndLoc, 11050 NestedLoopCount, Clauses, AStmt, B); 11051 } 11052 11053 StmtResult Sema::ActOnOpenMPTargetParallelForSimdDirective( 11054 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, 11055 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) { 11056 if (!AStmt) 11057 return StmtError(); 11058 11059 auto *CS = cast<CapturedStmt>(AStmt); 11060 // 1.2.2 OpenMP Language Terminology 11061 // Structured block - An executable statement with a single entry at the 11062 // top and a single exit at the bottom. 11063 // The point of exit cannot be a branch out of the structured block. 11064 // longjmp() and throw() must not violate the entry/exit criteria. 11065 CS->getCapturedDecl()->setNothrow(); 11066 for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_parallel_for); 11067 ThisCaptureLevel > 1; --ThisCaptureLevel) { 11068 CS = cast<CapturedStmt>(CS->getCapturedStmt()); 11069 // 1.2.2 OpenMP Language Terminology 11070 // Structured block - An executable statement with a single entry at the 11071 // top and a single exit at the bottom. 11072 // The point of exit cannot be a branch out of the structured block. 11073 // longjmp() and throw() must not violate the entry/exit criteria. 11074 CS->getCapturedDecl()->setNothrow(); 11075 } 11076 11077 OMPLoopDirective::HelperExprs B; 11078 // In presence of clause 'collapse' or 'ordered' with number of loops, it will 11079 // define the nested loops number. 11080 unsigned NestedLoopCount = checkOpenMPLoop( 11081 OMPD_target_parallel_for_simd, getCollapseNumberExpr(Clauses), 11082 getOrderedNumberExpr(Clauses), CS, *this, *DSAStack, 11083 VarsWithImplicitDSA, B); 11084 if (NestedLoopCount == 0) 11085 return StmtError(); 11086 11087 assert((CurContext->isDependentContext() || B.builtAll()) && 11088 "omp target parallel for simd loop exprs were not built"); 11089 11090 if (!CurContext->isDependentContext()) { 11091 // Finalize the clauses that need pre-built expressions for CodeGen. 11092 for (OMPClause *C : Clauses) { 11093 if (auto *LC = dyn_cast<OMPLinearClause>(C)) 11094 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef), 11095 B.NumIterations, *this, CurScope, 11096 DSAStack)) 11097 return StmtError(); 11098 } 11099 } 11100 if (checkSimdlenSafelenSpecified(*this, Clauses)) 11101 return StmtError(); 11102 11103 setFunctionHasBranchProtectedScope(); 11104 return OMPTargetParallelForSimdDirective::Create( 11105 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B); 11106 } 11107 11108 StmtResult Sema::ActOnOpenMPTargetSimdDirective( 11109 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, 11110 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) { 11111 if (!AStmt) 11112 return StmtError(); 11113 11114 auto *CS = cast<CapturedStmt>(AStmt); 11115 // 1.2.2 OpenMP Language Terminology 11116 // Structured block - An executable statement with a single entry at the 11117 // top and a single exit at the bottom. 11118 // The point of exit cannot be a branch out of the structured block. 11119 // longjmp() and throw() must not violate the entry/exit criteria. 11120 CS->getCapturedDecl()->setNothrow(); 11121 for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_simd); 11122 ThisCaptureLevel > 1; --ThisCaptureLevel) { 11123 CS = cast<CapturedStmt>(CS->getCapturedStmt()); 11124 // 1.2.2 OpenMP Language Terminology 11125 // Structured block - An executable statement with a single entry at the 11126 // top and a single exit at the bottom. 11127 // The point of exit cannot be a branch out of the structured block. 11128 // longjmp() and throw() must not violate the entry/exit criteria. 11129 CS->getCapturedDecl()->setNothrow(); 11130 } 11131 11132 OMPLoopDirective::HelperExprs B; 11133 // In presence of clause 'collapse' with number of loops, it will define the 11134 // nested loops number. 11135 unsigned NestedLoopCount = 11136 checkOpenMPLoop(OMPD_target_simd, getCollapseNumberExpr(Clauses), 11137 getOrderedNumberExpr(Clauses), CS, *this, *DSAStack, 11138 VarsWithImplicitDSA, B); 11139 if (NestedLoopCount == 0) 11140 return StmtError(); 11141 11142 assert((CurContext->isDependentContext() || B.builtAll()) && 11143 "omp target simd loop exprs were not built"); 11144 11145 if (!CurContext->isDependentContext()) { 11146 // Finalize the clauses that need pre-built expressions for CodeGen. 11147 for (OMPClause *C : Clauses) { 11148 if (auto *LC = dyn_cast<OMPLinearClause>(C)) 11149 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef), 11150 B.NumIterations, *this, CurScope, 11151 DSAStack)) 11152 return StmtError(); 11153 } 11154 } 11155 11156 if (checkSimdlenSafelenSpecified(*this, Clauses)) 11157 return StmtError(); 11158 11159 setFunctionHasBranchProtectedScope(); 11160 return OMPTargetSimdDirective::Create(Context, StartLoc, EndLoc, 11161 NestedLoopCount, Clauses, AStmt, B); 11162 } 11163 11164 StmtResult Sema::ActOnOpenMPTeamsDistributeDirective( 11165 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, 11166 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) { 11167 if (!AStmt) 11168 return StmtError(); 11169 11170 auto *CS = cast<CapturedStmt>(AStmt); 11171 // 1.2.2 OpenMP Language Terminology 11172 // Structured block - An executable statement with a single entry at the 11173 // top and a single exit at the bottom. 11174 // The point of exit cannot be a branch out of the structured block. 11175 // longjmp() and throw() must not violate the entry/exit criteria. 11176 CS->getCapturedDecl()->setNothrow(); 11177 for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_teams_distribute); 11178 ThisCaptureLevel > 1; --ThisCaptureLevel) { 11179 CS = cast<CapturedStmt>(CS->getCapturedStmt()); 11180 // 1.2.2 OpenMP Language Terminology 11181 // Structured block - An executable statement with a single entry at the 11182 // top and a single exit at the bottom. 11183 // The point of exit cannot be a branch out of the structured block. 11184 // longjmp() and throw() must not violate the entry/exit criteria. 11185 CS->getCapturedDecl()->setNothrow(); 11186 } 11187 11188 OMPLoopDirective::HelperExprs B; 11189 // In presence of clause 'collapse' with number of loops, it will 11190 // define the nested loops number. 11191 unsigned NestedLoopCount = 11192 checkOpenMPLoop(OMPD_teams_distribute, getCollapseNumberExpr(Clauses), 11193 nullptr /*ordered not a clause on distribute*/, CS, *this, 11194 *DSAStack, VarsWithImplicitDSA, B); 11195 if (NestedLoopCount == 0) 11196 return StmtError(); 11197 11198 assert((CurContext->isDependentContext() || B.builtAll()) && 11199 "omp teams distribute loop exprs were not built"); 11200 11201 setFunctionHasBranchProtectedScope(); 11202 11203 DSAStack->setParentTeamsRegionLoc(StartLoc); 11204 11205 return OMPTeamsDistributeDirective::Create( 11206 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B); 11207 } 11208 11209 StmtResult Sema::ActOnOpenMPTeamsDistributeSimdDirective( 11210 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, 11211 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) { 11212 if (!AStmt) 11213 return StmtError(); 11214 11215 auto *CS = cast<CapturedStmt>(AStmt); 11216 // 1.2.2 OpenMP Language Terminology 11217 // Structured block - An executable statement with a single entry at the 11218 // top and a single exit at the bottom. 11219 // The point of exit cannot be a branch out of the structured block. 11220 // longjmp() and throw() must not violate the entry/exit criteria. 11221 CS->getCapturedDecl()->setNothrow(); 11222 for (int ThisCaptureLevel = 11223 getOpenMPCaptureLevels(OMPD_teams_distribute_simd); 11224 ThisCaptureLevel > 1; --ThisCaptureLevel) { 11225 CS = cast<CapturedStmt>(CS->getCapturedStmt()); 11226 // 1.2.2 OpenMP Language Terminology 11227 // Structured block - An executable statement with a single entry at the 11228 // top and a single exit at the bottom. 11229 // The point of exit cannot be a branch out of the structured block. 11230 // longjmp() and throw() must not violate the entry/exit criteria. 11231 CS->getCapturedDecl()->setNothrow(); 11232 } 11233 11234 OMPLoopDirective::HelperExprs B; 11235 // In presence of clause 'collapse' with number of loops, it will 11236 // define the nested loops number. 11237 unsigned NestedLoopCount = checkOpenMPLoop( 11238 OMPD_teams_distribute_simd, getCollapseNumberExpr(Clauses), 11239 nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStack, 11240 VarsWithImplicitDSA, B); 11241 11242 if (NestedLoopCount == 0) 11243 return StmtError(); 11244 11245 assert((CurContext->isDependentContext() || B.builtAll()) && 11246 "omp teams distribute simd loop exprs were not built"); 11247 11248 if (!CurContext->isDependentContext()) { 11249 // Finalize the clauses that need pre-built expressions for CodeGen. 11250 for (OMPClause *C : Clauses) { 11251 if (auto *LC = dyn_cast<OMPLinearClause>(C)) 11252 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef), 11253 B.NumIterations, *this, CurScope, 11254 DSAStack)) 11255 return StmtError(); 11256 } 11257 } 11258 11259 if (checkSimdlenSafelenSpecified(*this, Clauses)) 11260 return StmtError(); 11261 11262 setFunctionHasBranchProtectedScope(); 11263 11264 DSAStack->setParentTeamsRegionLoc(StartLoc); 11265 11266 return OMPTeamsDistributeSimdDirective::Create( 11267 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B); 11268 } 11269 11270 StmtResult Sema::ActOnOpenMPTeamsDistributeParallelForSimdDirective( 11271 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, 11272 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) { 11273 if (!AStmt) 11274 return StmtError(); 11275 11276 auto *CS = cast<CapturedStmt>(AStmt); 11277 // 1.2.2 OpenMP Language Terminology 11278 // Structured block - An executable statement with a single entry at the 11279 // top and a single exit at the bottom. 11280 // The point of exit cannot be a branch out of the structured block. 11281 // longjmp() and throw() must not violate the entry/exit criteria. 11282 CS->getCapturedDecl()->setNothrow(); 11283 11284 for (int ThisCaptureLevel = 11285 getOpenMPCaptureLevels(OMPD_teams_distribute_parallel_for_simd); 11286 ThisCaptureLevel > 1; --ThisCaptureLevel) { 11287 CS = cast<CapturedStmt>(CS->getCapturedStmt()); 11288 // 1.2.2 OpenMP Language Terminology 11289 // Structured block - An executable statement with a single entry at the 11290 // top and a single exit at the bottom. 11291 // The point of exit cannot be a branch out of the structured block. 11292 // longjmp() and throw() must not violate the entry/exit criteria. 11293 CS->getCapturedDecl()->setNothrow(); 11294 } 11295 11296 OMPLoopDirective::HelperExprs B; 11297 // In presence of clause 'collapse' with number of loops, it will 11298 // define the nested loops number. 11299 unsigned NestedLoopCount = checkOpenMPLoop( 11300 OMPD_teams_distribute_parallel_for_simd, getCollapseNumberExpr(Clauses), 11301 nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStack, 11302 VarsWithImplicitDSA, B); 11303 11304 if (NestedLoopCount == 0) 11305 return StmtError(); 11306 11307 assert((CurContext->isDependentContext() || B.builtAll()) && 11308 "omp for loop exprs were not built"); 11309 11310 if (!CurContext->isDependentContext()) { 11311 // Finalize the clauses that need pre-built expressions for CodeGen. 11312 for (OMPClause *C : Clauses) { 11313 if (auto *LC = dyn_cast<OMPLinearClause>(C)) 11314 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef), 11315 B.NumIterations, *this, CurScope, 11316 DSAStack)) 11317 return StmtError(); 11318 } 11319 } 11320 11321 if (checkSimdlenSafelenSpecified(*this, Clauses)) 11322 return StmtError(); 11323 11324 setFunctionHasBranchProtectedScope(); 11325 11326 DSAStack->setParentTeamsRegionLoc(StartLoc); 11327 11328 return OMPTeamsDistributeParallelForSimdDirective::Create( 11329 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B); 11330 } 11331 11332 StmtResult Sema::ActOnOpenMPTeamsDistributeParallelForDirective( 11333 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, 11334 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) { 11335 if (!AStmt) 11336 return StmtError(); 11337 11338 auto *CS = cast<CapturedStmt>(AStmt); 11339 // 1.2.2 OpenMP Language Terminology 11340 // Structured block - An executable statement with a single entry at the 11341 // top and a single exit at the bottom. 11342 // The point of exit cannot be a branch out of the structured block. 11343 // longjmp() and throw() must not violate the entry/exit criteria. 11344 CS->getCapturedDecl()->setNothrow(); 11345 11346 for (int ThisCaptureLevel = 11347 getOpenMPCaptureLevels(OMPD_teams_distribute_parallel_for); 11348 ThisCaptureLevel > 1; --ThisCaptureLevel) { 11349 CS = cast<CapturedStmt>(CS->getCapturedStmt()); 11350 // 1.2.2 OpenMP Language Terminology 11351 // Structured block - An executable statement with a single entry at the 11352 // top and a single exit at the bottom. 11353 // The point of exit cannot be a branch out of the structured block. 11354 // longjmp() and throw() must not violate the entry/exit criteria. 11355 CS->getCapturedDecl()->setNothrow(); 11356 } 11357 11358 OMPLoopDirective::HelperExprs B; 11359 // In presence of clause 'collapse' with number of loops, it will 11360 // define the nested loops number. 11361 unsigned NestedLoopCount = checkOpenMPLoop( 11362 OMPD_teams_distribute_parallel_for, getCollapseNumberExpr(Clauses), 11363 nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStack, 11364 VarsWithImplicitDSA, B); 11365 11366 if (NestedLoopCount == 0) 11367 return StmtError(); 11368 11369 assert((CurContext->isDependentContext() || B.builtAll()) && 11370 "omp for loop exprs were not built"); 11371 11372 setFunctionHasBranchProtectedScope(); 11373 11374 DSAStack->setParentTeamsRegionLoc(StartLoc); 11375 11376 return OMPTeamsDistributeParallelForDirective::Create( 11377 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B, 11378 DSAStack->getTaskgroupReductionRef(), DSAStack->isCancelRegion()); 11379 } 11380 11381 StmtResult Sema::ActOnOpenMPTargetTeamsDirective(ArrayRef<OMPClause *> Clauses, 11382 Stmt *AStmt, 11383 SourceLocation StartLoc, 11384 SourceLocation EndLoc) { 11385 if (!AStmt) 11386 return StmtError(); 11387 11388 auto *CS = cast<CapturedStmt>(AStmt); 11389 // 1.2.2 OpenMP Language Terminology 11390 // Structured block - An executable statement with a single entry at the 11391 // top and a single exit at the bottom. 11392 // The point of exit cannot be a branch out of the structured block. 11393 // longjmp() and throw() must not violate the entry/exit criteria. 11394 CS->getCapturedDecl()->setNothrow(); 11395 11396 for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_teams); 11397 ThisCaptureLevel > 1; --ThisCaptureLevel) { 11398 CS = cast<CapturedStmt>(CS->getCapturedStmt()); 11399 // 1.2.2 OpenMP Language Terminology 11400 // Structured block - An executable statement with a single entry at the 11401 // top and a single exit at the bottom. 11402 // The point of exit cannot be a branch out of the structured block. 11403 // longjmp() and throw() must not violate the entry/exit criteria. 11404 CS->getCapturedDecl()->setNothrow(); 11405 } 11406 setFunctionHasBranchProtectedScope(); 11407 11408 return OMPTargetTeamsDirective::Create(Context, StartLoc, EndLoc, Clauses, 11409 AStmt); 11410 } 11411 11412 StmtResult Sema::ActOnOpenMPTargetTeamsDistributeDirective( 11413 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, 11414 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) { 11415 if (!AStmt) 11416 return StmtError(); 11417 11418 auto *CS = cast<CapturedStmt>(AStmt); 11419 // 1.2.2 OpenMP Language Terminology 11420 // Structured block - An executable statement with a single entry at the 11421 // top and a single exit at the bottom. 11422 // The point of exit cannot be a branch out of the structured block. 11423 // longjmp() and throw() must not violate the entry/exit criteria. 11424 CS->getCapturedDecl()->setNothrow(); 11425 for (int ThisCaptureLevel = 11426 getOpenMPCaptureLevels(OMPD_target_teams_distribute); 11427 ThisCaptureLevel > 1; --ThisCaptureLevel) { 11428 CS = cast<CapturedStmt>(CS->getCapturedStmt()); 11429 // 1.2.2 OpenMP Language Terminology 11430 // Structured block - An executable statement with a single entry at the 11431 // top and a single exit at the bottom. 11432 // The point of exit cannot be a branch out of the structured block. 11433 // longjmp() and throw() must not violate the entry/exit criteria. 11434 CS->getCapturedDecl()->setNothrow(); 11435 } 11436 11437 OMPLoopDirective::HelperExprs B; 11438 // In presence of clause 'collapse' with number of loops, it will 11439 // define the nested loops number. 11440 unsigned NestedLoopCount = checkOpenMPLoop( 11441 OMPD_target_teams_distribute, getCollapseNumberExpr(Clauses), 11442 nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStack, 11443 VarsWithImplicitDSA, B); 11444 if (NestedLoopCount == 0) 11445 return StmtError(); 11446 11447 assert((CurContext->isDependentContext() || B.builtAll()) && 11448 "omp target teams distribute loop exprs were not built"); 11449 11450 setFunctionHasBranchProtectedScope(); 11451 return OMPTargetTeamsDistributeDirective::Create( 11452 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B); 11453 } 11454 11455 StmtResult Sema::ActOnOpenMPTargetTeamsDistributeParallelForDirective( 11456 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, 11457 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) { 11458 if (!AStmt) 11459 return StmtError(); 11460 11461 auto *CS = cast<CapturedStmt>(AStmt); 11462 // 1.2.2 OpenMP Language Terminology 11463 // Structured block - An executable statement with a single entry at the 11464 // top and a single exit at the bottom. 11465 // The point of exit cannot be a branch out of the structured block. 11466 // longjmp() and throw() must not violate the entry/exit criteria. 11467 CS->getCapturedDecl()->setNothrow(); 11468 for (int ThisCaptureLevel = 11469 getOpenMPCaptureLevels(OMPD_target_teams_distribute_parallel_for); 11470 ThisCaptureLevel > 1; --ThisCaptureLevel) { 11471 CS = cast<CapturedStmt>(CS->getCapturedStmt()); 11472 // 1.2.2 OpenMP Language Terminology 11473 // Structured block - An executable statement with a single entry at the 11474 // top and a single exit at the bottom. 11475 // The point of exit cannot be a branch out of the structured block. 11476 // longjmp() and throw() must not violate the entry/exit criteria. 11477 CS->getCapturedDecl()->setNothrow(); 11478 } 11479 11480 OMPLoopDirective::HelperExprs B; 11481 // In presence of clause 'collapse' with number of loops, it will 11482 // define the nested loops number. 11483 unsigned NestedLoopCount = checkOpenMPLoop( 11484 OMPD_target_teams_distribute_parallel_for, getCollapseNumberExpr(Clauses), 11485 nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStack, 11486 VarsWithImplicitDSA, B); 11487 if (NestedLoopCount == 0) 11488 return StmtError(); 11489 11490 assert((CurContext->isDependentContext() || B.builtAll()) && 11491 "omp target teams distribute parallel for loop exprs were not built"); 11492 11493 if (!CurContext->isDependentContext()) { 11494 // Finalize the clauses that need pre-built expressions for CodeGen. 11495 for (OMPClause *C : Clauses) { 11496 if (auto *LC = dyn_cast<OMPLinearClause>(C)) 11497 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef), 11498 B.NumIterations, *this, CurScope, 11499 DSAStack)) 11500 return StmtError(); 11501 } 11502 } 11503 11504 setFunctionHasBranchProtectedScope(); 11505 return OMPTargetTeamsDistributeParallelForDirective::Create( 11506 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B, 11507 DSAStack->getTaskgroupReductionRef(), DSAStack->isCancelRegion()); 11508 } 11509 11510 StmtResult Sema::ActOnOpenMPTargetTeamsDistributeParallelForSimdDirective( 11511 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, 11512 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) { 11513 if (!AStmt) 11514 return StmtError(); 11515 11516 auto *CS = cast<CapturedStmt>(AStmt); 11517 // 1.2.2 OpenMP Language Terminology 11518 // Structured block - An executable statement with a single entry at the 11519 // top and a single exit at the bottom. 11520 // The point of exit cannot be a branch out of the structured block. 11521 // longjmp() and throw() must not violate the entry/exit criteria. 11522 CS->getCapturedDecl()->setNothrow(); 11523 for (int ThisCaptureLevel = getOpenMPCaptureLevels( 11524 OMPD_target_teams_distribute_parallel_for_simd); 11525 ThisCaptureLevel > 1; --ThisCaptureLevel) { 11526 CS = cast<CapturedStmt>(CS->getCapturedStmt()); 11527 // 1.2.2 OpenMP Language Terminology 11528 // Structured block - An executable statement with a single entry at the 11529 // top and a single exit at the bottom. 11530 // The point of exit cannot be a branch out of the structured block. 11531 // longjmp() and throw() must not violate the entry/exit criteria. 11532 CS->getCapturedDecl()->setNothrow(); 11533 } 11534 11535 OMPLoopDirective::HelperExprs B; 11536 // In presence of clause 'collapse' with number of loops, it will 11537 // define the nested loops number. 11538 unsigned NestedLoopCount = 11539 checkOpenMPLoop(OMPD_target_teams_distribute_parallel_for_simd, 11540 getCollapseNumberExpr(Clauses), 11541 nullptr /*ordered not a clause on distribute*/, CS, *this, 11542 *DSAStack, VarsWithImplicitDSA, B); 11543 if (NestedLoopCount == 0) 11544 return StmtError(); 11545 11546 assert((CurContext->isDependentContext() || B.builtAll()) && 11547 "omp target teams distribute parallel for simd loop exprs were not " 11548 "built"); 11549 11550 if (!CurContext->isDependentContext()) { 11551 // Finalize the clauses that need pre-built expressions for CodeGen. 11552 for (OMPClause *C : Clauses) { 11553 if (auto *LC = dyn_cast<OMPLinearClause>(C)) 11554 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef), 11555 B.NumIterations, *this, CurScope, 11556 DSAStack)) 11557 return StmtError(); 11558 } 11559 } 11560 11561 if (checkSimdlenSafelenSpecified(*this, Clauses)) 11562 return StmtError(); 11563 11564 setFunctionHasBranchProtectedScope(); 11565 return OMPTargetTeamsDistributeParallelForSimdDirective::Create( 11566 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B); 11567 } 11568 11569 StmtResult Sema::ActOnOpenMPTargetTeamsDistributeSimdDirective( 11570 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, 11571 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) { 11572 if (!AStmt) 11573 return StmtError(); 11574 11575 auto *CS = cast<CapturedStmt>(AStmt); 11576 // 1.2.2 OpenMP Language Terminology 11577 // Structured block - An executable statement with a single entry at the 11578 // top and a single exit at the bottom. 11579 // The point of exit cannot be a branch out of the structured block. 11580 // longjmp() and throw() must not violate the entry/exit criteria. 11581 CS->getCapturedDecl()->setNothrow(); 11582 for (int ThisCaptureLevel = 11583 getOpenMPCaptureLevels(OMPD_target_teams_distribute_simd); 11584 ThisCaptureLevel > 1; --ThisCaptureLevel) { 11585 CS = cast<CapturedStmt>(CS->getCapturedStmt()); 11586 // 1.2.2 OpenMP Language Terminology 11587 // Structured block - An executable statement with a single entry at the 11588 // top and a single exit at the bottom. 11589 // The point of exit cannot be a branch out of the structured block. 11590 // longjmp() and throw() must not violate the entry/exit criteria. 11591 CS->getCapturedDecl()->setNothrow(); 11592 } 11593 11594 OMPLoopDirective::HelperExprs B; 11595 // In presence of clause 'collapse' with number of loops, it will 11596 // define the nested loops number. 11597 unsigned NestedLoopCount = checkOpenMPLoop( 11598 OMPD_target_teams_distribute_simd, getCollapseNumberExpr(Clauses), 11599 nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStack, 11600 VarsWithImplicitDSA, B); 11601 if (NestedLoopCount == 0) 11602 return StmtError(); 11603 11604 assert((CurContext->isDependentContext() || B.builtAll()) && 11605 "omp target teams distribute simd loop exprs were not built"); 11606 11607 if (!CurContext->isDependentContext()) { 11608 // Finalize the clauses that need pre-built expressions for CodeGen. 11609 for (OMPClause *C : Clauses) { 11610 if (auto *LC = dyn_cast<OMPLinearClause>(C)) 11611 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef), 11612 B.NumIterations, *this, CurScope, 11613 DSAStack)) 11614 return StmtError(); 11615 } 11616 } 11617 11618 if (checkSimdlenSafelenSpecified(*this, Clauses)) 11619 return StmtError(); 11620 11621 setFunctionHasBranchProtectedScope(); 11622 return OMPTargetTeamsDistributeSimdDirective::Create( 11623 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B); 11624 } 11625 11626 OMPClause *Sema::ActOnOpenMPSingleExprClause(OpenMPClauseKind Kind, Expr *Expr, 11627 SourceLocation StartLoc, 11628 SourceLocation LParenLoc, 11629 SourceLocation EndLoc) { 11630 OMPClause *Res = nullptr; 11631 switch (Kind) { 11632 case OMPC_final: 11633 Res = ActOnOpenMPFinalClause(Expr, StartLoc, LParenLoc, EndLoc); 11634 break; 11635 case OMPC_num_threads: 11636 Res = ActOnOpenMPNumThreadsClause(Expr, StartLoc, LParenLoc, EndLoc); 11637 break; 11638 case OMPC_safelen: 11639 Res = ActOnOpenMPSafelenClause(Expr, StartLoc, LParenLoc, EndLoc); 11640 break; 11641 case OMPC_simdlen: 11642 Res = ActOnOpenMPSimdlenClause(Expr, StartLoc, LParenLoc, EndLoc); 11643 break; 11644 case OMPC_allocator: 11645 Res = ActOnOpenMPAllocatorClause(Expr, StartLoc, LParenLoc, EndLoc); 11646 break; 11647 case OMPC_collapse: 11648 Res = ActOnOpenMPCollapseClause(Expr, StartLoc, LParenLoc, EndLoc); 11649 break; 11650 case OMPC_ordered: 11651 Res = ActOnOpenMPOrderedClause(StartLoc, EndLoc, LParenLoc, Expr); 11652 break; 11653 case OMPC_num_teams: 11654 Res = ActOnOpenMPNumTeamsClause(Expr, StartLoc, LParenLoc, EndLoc); 11655 break; 11656 case OMPC_thread_limit: 11657 Res = ActOnOpenMPThreadLimitClause(Expr, StartLoc, LParenLoc, EndLoc); 11658 break; 11659 case OMPC_priority: 11660 Res = ActOnOpenMPPriorityClause(Expr, StartLoc, LParenLoc, EndLoc); 11661 break; 11662 case OMPC_grainsize: 11663 Res = ActOnOpenMPGrainsizeClause(Expr, StartLoc, LParenLoc, EndLoc); 11664 break; 11665 case OMPC_num_tasks: 11666 Res = ActOnOpenMPNumTasksClause(Expr, StartLoc, LParenLoc, EndLoc); 11667 break; 11668 case OMPC_hint: 11669 Res = ActOnOpenMPHintClause(Expr, StartLoc, LParenLoc, EndLoc); 11670 break; 11671 case OMPC_depobj: 11672 Res = ActOnOpenMPDepobjClause(Expr, StartLoc, LParenLoc, EndLoc); 11673 break; 11674 case OMPC_detach: 11675 Res = ActOnOpenMPDetachClause(Expr, StartLoc, LParenLoc, EndLoc); 11676 break; 11677 case OMPC_device: 11678 case OMPC_if: 11679 case OMPC_default: 11680 case OMPC_proc_bind: 11681 case OMPC_schedule: 11682 case OMPC_private: 11683 case OMPC_firstprivate: 11684 case OMPC_lastprivate: 11685 case OMPC_shared: 11686 case OMPC_reduction: 11687 case OMPC_task_reduction: 11688 case OMPC_in_reduction: 11689 case OMPC_linear: 11690 case OMPC_aligned: 11691 case OMPC_copyin: 11692 case OMPC_copyprivate: 11693 case OMPC_nowait: 11694 case OMPC_untied: 11695 case OMPC_mergeable: 11696 case OMPC_threadprivate: 11697 case OMPC_allocate: 11698 case OMPC_flush: 11699 case OMPC_read: 11700 case OMPC_write: 11701 case OMPC_update: 11702 case OMPC_capture: 11703 case OMPC_seq_cst: 11704 case OMPC_acq_rel: 11705 case OMPC_acquire: 11706 case OMPC_release: 11707 case OMPC_relaxed: 11708 case OMPC_depend: 11709 case OMPC_threads: 11710 case OMPC_simd: 11711 case OMPC_map: 11712 case OMPC_nogroup: 11713 case OMPC_dist_schedule: 11714 case OMPC_defaultmap: 11715 case OMPC_unknown: 11716 case OMPC_uniform: 11717 case OMPC_to: 11718 case OMPC_from: 11719 case OMPC_use_device_ptr: 11720 case OMPC_use_device_addr: 11721 case OMPC_is_device_ptr: 11722 case OMPC_unified_address: 11723 case OMPC_unified_shared_memory: 11724 case OMPC_reverse_offload: 11725 case OMPC_dynamic_allocators: 11726 case OMPC_atomic_default_mem_order: 11727 case OMPC_device_type: 11728 case OMPC_match: 11729 case OMPC_nontemporal: 11730 case OMPC_order: 11731 case OMPC_destroy: 11732 case OMPC_inclusive: 11733 case OMPC_exclusive: 11734 case OMPC_uses_allocators: 11735 case OMPC_affinity: 11736 default: 11737 llvm_unreachable("Clause is not allowed."); 11738 } 11739 return Res; 11740 } 11741 11742 // An OpenMP directive such as 'target parallel' has two captured regions: 11743 // for the 'target' and 'parallel' respectively. This function returns 11744 // the region in which to capture expressions associated with a clause. 11745 // A return value of OMPD_unknown signifies that the expression should not 11746 // be captured. 11747 static OpenMPDirectiveKind getOpenMPCaptureRegionForClause( 11748 OpenMPDirectiveKind DKind, OpenMPClauseKind CKind, unsigned OpenMPVersion, 11749 OpenMPDirectiveKind NameModifier = OMPD_unknown) { 11750 OpenMPDirectiveKind CaptureRegion = OMPD_unknown; 11751 switch (CKind) { 11752 case OMPC_if: 11753 switch (DKind) { 11754 case OMPD_target_parallel_for_simd: 11755 if (OpenMPVersion >= 50 && 11756 (NameModifier == OMPD_unknown || NameModifier == OMPD_simd)) { 11757 CaptureRegion = OMPD_parallel; 11758 break; 11759 } 11760 LLVM_FALLTHROUGH; 11761 case OMPD_target_parallel: 11762 case OMPD_target_parallel_for: 11763 // If this clause applies to the nested 'parallel' region, capture within 11764 // the 'target' region, otherwise do not capture. 11765 if (NameModifier == OMPD_unknown || NameModifier == OMPD_parallel) 11766 CaptureRegion = OMPD_target; 11767 break; 11768 case OMPD_target_teams_distribute_parallel_for_simd: 11769 if (OpenMPVersion >= 50 && 11770 (NameModifier == OMPD_unknown || NameModifier == OMPD_simd)) { 11771 CaptureRegion = OMPD_parallel; 11772 break; 11773 } 11774 LLVM_FALLTHROUGH; 11775 case OMPD_target_teams_distribute_parallel_for: 11776 // If this clause applies to the nested 'parallel' region, capture within 11777 // the 'teams' region, otherwise do not capture. 11778 if (NameModifier == OMPD_unknown || NameModifier == OMPD_parallel) 11779 CaptureRegion = OMPD_teams; 11780 break; 11781 case OMPD_teams_distribute_parallel_for_simd: 11782 if (OpenMPVersion >= 50 && 11783 (NameModifier == OMPD_unknown || NameModifier == OMPD_simd)) { 11784 CaptureRegion = OMPD_parallel; 11785 break; 11786 } 11787 LLVM_FALLTHROUGH; 11788 case OMPD_teams_distribute_parallel_for: 11789 CaptureRegion = OMPD_teams; 11790 break; 11791 case OMPD_target_update: 11792 case OMPD_target_enter_data: 11793 case OMPD_target_exit_data: 11794 CaptureRegion = OMPD_task; 11795 break; 11796 case OMPD_parallel_master_taskloop: 11797 if (NameModifier == OMPD_unknown || NameModifier == OMPD_taskloop) 11798 CaptureRegion = OMPD_parallel; 11799 break; 11800 case OMPD_parallel_master_taskloop_simd: 11801 if ((OpenMPVersion <= 45 && NameModifier == OMPD_unknown) || 11802 NameModifier == OMPD_taskloop) { 11803 CaptureRegion = OMPD_parallel; 11804 break; 11805 } 11806 if (OpenMPVersion <= 45) 11807 break; 11808 if (NameModifier == OMPD_unknown || NameModifier == OMPD_simd) 11809 CaptureRegion = OMPD_taskloop; 11810 break; 11811 case OMPD_parallel_for_simd: 11812 if (OpenMPVersion <= 45) 11813 break; 11814 if (NameModifier == OMPD_unknown || NameModifier == OMPD_simd) 11815 CaptureRegion = OMPD_parallel; 11816 break; 11817 case OMPD_taskloop_simd: 11818 case OMPD_master_taskloop_simd: 11819 if (OpenMPVersion <= 45) 11820 break; 11821 if (NameModifier == OMPD_unknown || NameModifier == OMPD_simd) 11822 CaptureRegion = OMPD_taskloop; 11823 break; 11824 case OMPD_distribute_parallel_for_simd: 11825 if (OpenMPVersion <= 45) 11826 break; 11827 if (NameModifier == OMPD_unknown || NameModifier == OMPD_simd) 11828 CaptureRegion = OMPD_parallel; 11829 break; 11830 case OMPD_target_simd: 11831 if (OpenMPVersion >= 50 && 11832 (NameModifier == OMPD_unknown || NameModifier == OMPD_simd)) 11833 CaptureRegion = OMPD_target; 11834 break; 11835 case OMPD_teams_distribute_simd: 11836 case OMPD_target_teams_distribute_simd: 11837 if (OpenMPVersion >= 50 && 11838 (NameModifier == OMPD_unknown || NameModifier == OMPD_simd)) 11839 CaptureRegion = OMPD_teams; 11840 break; 11841 case OMPD_cancel: 11842 case OMPD_parallel: 11843 case OMPD_parallel_master: 11844 case OMPD_parallel_sections: 11845 case OMPD_parallel_for: 11846 case OMPD_target: 11847 case OMPD_target_teams: 11848 case OMPD_target_teams_distribute: 11849 case OMPD_distribute_parallel_for: 11850 case OMPD_task: 11851 case OMPD_taskloop: 11852 case OMPD_master_taskloop: 11853 case OMPD_target_data: 11854 case OMPD_simd: 11855 case OMPD_for_simd: 11856 case OMPD_distribute_simd: 11857 // Do not capture if-clause expressions. 11858 break; 11859 case OMPD_threadprivate: 11860 case OMPD_allocate: 11861 case OMPD_taskyield: 11862 case OMPD_barrier: 11863 case OMPD_taskwait: 11864 case OMPD_cancellation_point: 11865 case OMPD_flush: 11866 case OMPD_depobj: 11867 case OMPD_scan: 11868 case OMPD_declare_reduction: 11869 case OMPD_declare_mapper: 11870 case OMPD_declare_simd: 11871 case OMPD_declare_variant: 11872 case OMPD_begin_declare_variant: 11873 case OMPD_end_declare_variant: 11874 case OMPD_declare_target: 11875 case OMPD_end_declare_target: 11876 case OMPD_teams: 11877 case OMPD_for: 11878 case OMPD_sections: 11879 case OMPD_section: 11880 case OMPD_single: 11881 case OMPD_master: 11882 case OMPD_critical: 11883 case OMPD_taskgroup: 11884 case OMPD_distribute: 11885 case OMPD_ordered: 11886 case OMPD_atomic: 11887 case OMPD_teams_distribute: 11888 case OMPD_requires: 11889 llvm_unreachable("Unexpected OpenMP directive with if-clause"); 11890 case OMPD_unknown: 11891 default: 11892 llvm_unreachable("Unknown OpenMP directive"); 11893 } 11894 break; 11895 case OMPC_num_threads: 11896 switch (DKind) { 11897 case OMPD_target_parallel: 11898 case OMPD_target_parallel_for: 11899 case OMPD_target_parallel_for_simd: 11900 CaptureRegion = OMPD_target; 11901 break; 11902 case OMPD_teams_distribute_parallel_for: 11903 case OMPD_teams_distribute_parallel_for_simd: 11904 case OMPD_target_teams_distribute_parallel_for: 11905 case OMPD_target_teams_distribute_parallel_for_simd: 11906 CaptureRegion = OMPD_teams; 11907 break; 11908 case OMPD_parallel: 11909 case OMPD_parallel_master: 11910 case OMPD_parallel_sections: 11911 case OMPD_parallel_for: 11912 case OMPD_parallel_for_simd: 11913 case OMPD_distribute_parallel_for: 11914 case OMPD_distribute_parallel_for_simd: 11915 case OMPD_parallel_master_taskloop: 11916 case OMPD_parallel_master_taskloop_simd: 11917 // Do not capture num_threads-clause expressions. 11918 break; 11919 case OMPD_target_data: 11920 case OMPD_target_enter_data: 11921 case OMPD_target_exit_data: 11922 case OMPD_target_update: 11923 case OMPD_target: 11924 case OMPD_target_simd: 11925 case OMPD_target_teams: 11926 case OMPD_target_teams_distribute: 11927 case OMPD_target_teams_distribute_simd: 11928 case OMPD_cancel: 11929 case OMPD_task: 11930 case OMPD_taskloop: 11931 case OMPD_taskloop_simd: 11932 case OMPD_master_taskloop: 11933 case OMPD_master_taskloop_simd: 11934 case OMPD_threadprivate: 11935 case OMPD_allocate: 11936 case OMPD_taskyield: 11937 case OMPD_barrier: 11938 case OMPD_taskwait: 11939 case OMPD_cancellation_point: 11940 case OMPD_flush: 11941 case OMPD_depobj: 11942 case OMPD_scan: 11943 case OMPD_declare_reduction: 11944 case OMPD_declare_mapper: 11945 case OMPD_declare_simd: 11946 case OMPD_declare_variant: 11947 case OMPD_begin_declare_variant: 11948 case OMPD_end_declare_variant: 11949 case OMPD_declare_target: 11950 case OMPD_end_declare_target: 11951 case OMPD_teams: 11952 case OMPD_simd: 11953 case OMPD_for: 11954 case OMPD_for_simd: 11955 case OMPD_sections: 11956 case OMPD_section: 11957 case OMPD_single: 11958 case OMPD_master: 11959 case OMPD_critical: 11960 case OMPD_taskgroup: 11961 case OMPD_distribute: 11962 case OMPD_ordered: 11963 case OMPD_atomic: 11964 case OMPD_distribute_simd: 11965 case OMPD_teams_distribute: 11966 case OMPD_teams_distribute_simd: 11967 case OMPD_requires: 11968 llvm_unreachable("Unexpected OpenMP directive with num_threads-clause"); 11969 case OMPD_unknown: 11970 default: 11971 llvm_unreachable("Unknown OpenMP directive"); 11972 } 11973 break; 11974 case OMPC_num_teams: 11975 switch (DKind) { 11976 case OMPD_target_teams: 11977 case OMPD_target_teams_distribute: 11978 case OMPD_target_teams_distribute_simd: 11979 case OMPD_target_teams_distribute_parallel_for: 11980 case OMPD_target_teams_distribute_parallel_for_simd: 11981 CaptureRegion = OMPD_target; 11982 break; 11983 case OMPD_teams_distribute_parallel_for: 11984 case OMPD_teams_distribute_parallel_for_simd: 11985 case OMPD_teams: 11986 case OMPD_teams_distribute: 11987 case OMPD_teams_distribute_simd: 11988 // Do not capture num_teams-clause expressions. 11989 break; 11990 case OMPD_distribute_parallel_for: 11991 case OMPD_distribute_parallel_for_simd: 11992 case OMPD_task: 11993 case OMPD_taskloop: 11994 case OMPD_taskloop_simd: 11995 case OMPD_master_taskloop: 11996 case OMPD_master_taskloop_simd: 11997 case OMPD_parallel_master_taskloop: 11998 case OMPD_parallel_master_taskloop_simd: 11999 case OMPD_target_data: 12000 case OMPD_target_enter_data: 12001 case OMPD_target_exit_data: 12002 case OMPD_target_update: 12003 case OMPD_cancel: 12004 case OMPD_parallel: 12005 case OMPD_parallel_master: 12006 case OMPD_parallel_sections: 12007 case OMPD_parallel_for: 12008 case OMPD_parallel_for_simd: 12009 case OMPD_target: 12010 case OMPD_target_simd: 12011 case OMPD_target_parallel: 12012 case OMPD_target_parallel_for: 12013 case OMPD_target_parallel_for_simd: 12014 case OMPD_threadprivate: 12015 case OMPD_allocate: 12016 case OMPD_taskyield: 12017 case OMPD_barrier: 12018 case OMPD_taskwait: 12019 case OMPD_cancellation_point: 12020 case OMPD_flush: 12021 case OMPD_depobj: 12022 case OMPD_scan: 12023 case OMPD_declare_reduction: 12024 case OMPD_declare_mapper: 12025 case OMPD_declare_simd: 12026 case OMPD_declare_variant: 12027 case OMPD_begin_declare_variant: 12028 case OMPD_end_declare_variant: 12029 case OMPD_declare_target: 12030 case OMPD_end_declare_target: 12031 case OMPD_simd: 12032 case OMPD_for: 12033 case OMPD_for_simd: 12034 case OMPD_sections: 12035 case OMPD_section: 12036 case OMPD_single: 12037 case OMPD_master: 12038 case OMPD_critical: 12039 case OMPD_taskgroup: 12040 case OMPD_distribute: 12041 case OMPD_ordered: 12042 case OMPD_atomic: 12043 case OMPD_distribute_simd: 12044 case OMPD_requires: 12045 llvm_unreachable("Unexpected OpenMP directive with num_teams-clause"); 12046 case OMPD_unknown: 12047 default: 12048 llvm_unreachable("Unknown OpenMP directive"); 12049 } 12050 break; 12051 case OMPC_thread_limit: 12052 switch (DKind) { 12053 case OMPD_target_teams: 12054 case OMPD_target_teams_distribute: 12055 case OMPD_target_teams_distribute_simd: 12056 case OMPD_target_teams_distribute_parallel_for: 12057 case OMPD_target_teams_distribute_parallel_for_simd: 12058 CaptureRegion = OMPD_target; 12059 break; 12060 case OMPD_teams_distribute_parallel_for: 12061 case OMPD_teams_distribute_parallel_for_simd: 12062 case OMPD_teams: 12063 case OMPD_teams_distribute: 12064 case OMPD_teams_distribute_simd: 12065 // Do not capture thread_limit-clause expressions. 12066 break; 12067 case OMPD_distribute_parallel_for: 12068 case OMPD_distribute_parallel_for_simd: 12069 case OMPD_task: 12070 case OMPD_taskloop: 12071 case OMPD_taskloop_simd: 12072 case OMPD_master_taskloop: 12073 case OMPD_master_taskloop_simd: 12074 case OMPD_parallel_master_taskloop: 12075 case OMPD_parallel_master_taskloop_simd: 12076 case OMPD_target_data: 12077 case OMPD_target_enter_data: 12078 case OMPD_target_exit_data: 12079 case OMPD_target_update: 12080 case OMPD_cancel: 12081 case OMPD_parallel: 12082 case OMPD_parallel_master: 12083 case OMPD_parallel_sections: 12084 case OMPD_parallel_for: 12085 case OMPD_parallel_for_simd: 12086 case OMPD_target: 12087 case OMPD_target_simd: 12088 case OMPD_target_parallel: 12089 case OMPD_target_parallel_for: 12090 case OMPD_target_parallel_for_simd: 12091 case OMPD_threadprivate: 12092 case OMPD_allocate: 12093 case OMPD_taskyield: 12094 case OMPD_barrier: 12095 case OMPD_taskwait: 12096 case OMPD_cancellation_point: 12097 case OMPD_flush: 12098 case OMPD_depobj: 12099 case OMPD_scan: 12100 case OMPD_declare_reduction: 12101 case OMPD_declare_mapper: 12102 case OMPD_declare_simd: 12103 case OMPD_declare_variant: 12104 case OMPD_begin_declare_variant: 12105 case OMPD_end_declare_variant: 12106 case OMPD_declare_target: 12107 case OMPD_end_declare_target: 12108 case OMPD_simd: 12109 case OMPD_for: 12110 case OMPD_for_simd: 12111 case OMPD_sections: 12112 case OMPD_section: 12113 case OMPD_single: 12114 case OMPD_master: 12115 case OMPD_critical: 12116 case OMPD_taskgroup: 12117 case OMPD_distribute: 12118 case OMPD_ordered: 12119 case OMPD_atomic: 12120 case OMPD_distribute_simd: 12121 case OMPD_requires: 12122 llvm_unreachable("Unexpected OpenMP directive with thread_limit-clause"); 12123 case OMPD_unknown: 12124 default: 12125 llvm_unreachable("Unknown OpenMP directive"); 12126 } 12127 break; 12128 case OMPC_schedule: 12129 switch (DKind) { 12130 case OMPD_parallel_for: 12131 case OMPD_parallel_for_simd: 12132 case OMPD_distribute_parallel_for: 12133 case OMPD_distribute_parallel_for_simd: 12134 case OMPD_teams_distribute_parallel_for: 12135 case OMPD_teams_distribute_parallel_for_simd: 12136 case OMPD_target_parallel_for: 12137 case OMPD_target_parallel_for_simd: 12138 case OMPD_target_teams_distribute_parallel_for: 12139 case OMPD_target_teams_distribute_parallel_for_simd: 12140 CaptureRegion = OMPD_parallel; 12141 break; 12142 case OMPD_for: 12143 case OMPD_for_simd: 12144 // Do not capture schedule-clause expressions. 12145 break; 12146 case OMPD_task: 12147 case OMPD_taskloop: 12148 case OMPD_taskloop_simd: 12149 case OMPD_master_taskloop: 12150 case OMPD_master_taskloop_simd: 12151 case OMPD_parallel_master_taskloop: 12152 case OMPD_parallel_master_taskloop_simd: 12153 case OMPD_target_data: 12154 case OMPD_target_enter_data: 12155 case OMPD_target_exit_data: 12156 case OMPD_target_update: 12157 case OMPD_teams: 12158 case OMPD_teams_distribute: 12159 case OMPD_teams_distribute_simd: 12160 case OMPD_target_teams_distribute: 12161 case OMPD_target_teams_distribute_simd: 12162 case OMPD_target: 12163 case OMPD_target_simd: 12164 case OMPD_target_parallel: 12165 case OMPD_cancel: 12166 case OMPD_parallel: 12167 case OMPD_parallel_master: 12168 case OMPD_parallel_sections: 12169 case OMPD_threadprivate: 12170 case OMPD_allocate: 12171 case OMPD_taskyield: 12172 case OMPD_barrier: 12173 case OMPD_taskwait: 12174 case OMPD_cancellation_point: 12175 case OMPD_flush: 12176 case OMPD_depobj: 12177 case OMPD_scan: 12178 case OMPD_declare_reduction: 12179 case OMPD_declare_mapper: 12180 case OMPD_declare_simd: 12181 case OMPD_declare_variant: 12182 case OMPD_begin_declare_variant: 12183 case OMPD_end_declare_variant: 12184 case OMPD_declare_target: 12185 case OMPD_end_declare_target: 12186 case OMPD_simd: 12187 case OMPD_sections: 12188 case OMPD_section: 12189 case OMPD_single: 12190 case OMPD_master: 12191 case OMPD_critical: 12192 case OMPD_taskgroup: 12193 case OMPD_distribute: 12194 case OMPD_ordered: 12195 case OMPD_atomic: 12196 case OMPD_distribute_simd: 12197 case OMPD_target_teams: 12198 case OMPD_requires: 12199 llvm_unreachable("Unexpected OpenMP directive with schedule clause"); 12200 case OMPD_unknown: 12201 default: 12202 llvm_unreachable("Unknown OpenMP directive"); 12203 } 12204 break; 12205 case OMPC_dist_schedule: 12206 switch (DKind) { 12207 case OMPD_teams_distribute_parallel_for: 12208 case OMPD_teams_distribute_parallel_for_simd: 12209 case OMPD_teams_distribute: 12210 case OMPD_teams_distribute_simd: 12211 case OMPD_target_teams_distribute_parallel_for: 12212 case OMPD_target_teams_distribute_parallel_for_simd: 12213 case OMPD_target_teams_distribute: 12214 case OMPD_target_teams_distribute_simd: 12215 CaptureRegion = OMPD_teams; 12216 break; 12217 case OMPD_distribute_parallel_for: 12218 case OMPD_distribute_parallel_for_simd: 12219 case OMPD_distribute: 12220 case OMPD_distribute_simd: 12221 // Do not capture thread_limit-clause expressions. 12222 break; 12223 case OMPD_parallel_for: 12224 case OMPD_parallel_for_simd: 12225 case OMPD_target_parallel_for_simd: 12226 case OMPD_target_parallel_for: 12227 case OMPD_task: 12228 case OMPD_taskloop: 12229 case OMPD_taskloop_simd: 12230 case OMPD_master_taskloop: 12231 case OMPD_master_taskloop_simd: 12232 case OMPD_parallel_master_taskloop: 12233 case OMPD_parallel_master_taskloop_simd: 12234 case OMPD_target_data: 12235 case OMPD_target_enter_data: 12236 case OMPD_target_exit_data: 12237 case OMPD_target_update: 12238 case OMPD_teams: 12239 case OMPD_target: 12240 case OMPD_target_simd: 12241 case OMPD_target_parallel: 12242 case OMPD_cancel: 12243 case OMPD_parallel: 12244 case OMPD_parallel_master: 12245 case OMPD_parallel_sections: 12246 case OMPD_threadprivate: 12247 case OMPD_allocate: 12248 case OMPD_taskyield: 12249 case OMPD_barrier: 12250 case OMPD_taskwait: 12251 case OMPD_cancellation_point: 12252 case OMPD_flush: 12253 case OMPD_depobj: 12254 case OMPD_scan: 12255 case OMPD_declare_reduction: 12256 case OMPD_declare_mapper: 12257 case OMPD_declare_simd: 12258 case OMPD_declare_variant: 12259 case OMPD_begin_declare_variant: 12260 case OMPD_end_declare_variant: 12261 case OMPD_declare_target: 12262 case OMPD_end_declare_target: 12263 case OMPD_simd: 12264 case OMPD_for: 12265 case OMPD_for_simd: 12266 case OMPD_sections: 12267 case OMPD_section: 12268 case OMPD_single: 12269 case OMPD_master: 12270 case OMPD_critical: 12271 case OMPD_taskgroup: 12272 case OMPD_ordered: 12273 case OMPD_atomic: 12274 case OMPD_target_teams: 12275 case OMPD_requires: 12276 llvm_unreachable("Unexpected OpenMP directive with schedule clause"); 12277 case OMPD_unknown: 12278 default: 12279 llvm_unreachable("Unknown OpenMP directive"); 12280 } 12281 break; 12282 case OMPC_device: 12283 switch (DKind) { 12284 case OMPD_target_update: 12285 case OMPD_target_enter_data: 12286 case OMPD_target_exit_data: 12287 case OMPD_target: 12288 case OMPD_target_simd: 12289 case OMPD_target_teams: 12290 case OMPD_target_parallel: 12291 case OMPD_target_teams_distribute: 12292 case OMPD_target_teams_distribute_simd: 12293 case OMPD_target_parallel_for: 12294 case OMPD_target_parallel_for_simd: 12295 case OMPD_target_teams_distribute_parallel_for: 12296 case OMPD_target_teams_distribute_parallel_for_simd: 12297 CaptureRegion = OMPD_task; 12298 break; 12299 case OMPD_target_data: 12300 // Do not capture device-clause expressions. 12301 break; 12302 case OMPD_teams_distribute_parallel_for: 12303 case OMPD_teams_distribute_parallel_for_simd: 12304 case OMPD_teams: 12305 case OMPD_teams_distribute: 12306 case OMPD_teams_distribute_simd: 12307 case OMPD_distribute_parallel_for: 12308 case OMPD_distribute_parallel_for_simd: 12309 case OMPD_task: 12310 case OMPD_taskloop: 12311 case OMPD_taskloop_simd: 12312 case OMPD_master_taskloop: 12313 case OMPD_master_taskloop_simd: 12314 case OMPD_parallel_master_taskloop: 12315 case OMPD_parallel_master_taskloop_simd: 12316 case OMPD_cancel: 12317 case OMPD_parallel: 12318 case OMPD_parallel_master: 12319 case OMPD_parallel_sections: 12320 case OMPD_parallel_for: 12321 case OMPD_parallel_for_simd: 12322 case OMPD_threadprivate: 12323 case OMPD_allocate: 12324 case OMPD_taskyield: 12325 case OMPD_barrier: 12326 case OMPD_taskwait: 12327 case OMPD_cancellation_point: 12328 case OMPD_flush: 12329 case OMPD_depobj: 12330 case OMPD_scan: 12331 case OMPD_declare_reduction: 12332 case OMPD_declare_mapper: 12333 case OMPD_declare_simd: 12334 case OMPD_declare_variant: 12335 case OMPD_begin_declare_variant: 12336 case OMPD_end_declare_variant: 12337 case OMPD_declare_target: 12338 case OMPD_end_declare_target: 12339 case OMPD_simd: 12340 case OMPD_for: 12341 case OMPD_for_simd: 12342 case OMPD_sections: 12343 case OMPD_section: 12344 case OMPD_single: 12345 case OMPD_master: 12346 case OMPD_critical: 12347 case OMPD_taskgroup: 12348 case OMPD_distribute: 12349 case OMPD_ordered: 12350 case OMPD_atomic: 12351 case OMPD_distribute_simd: 12352 case OMPD_requires: 12353 llvm_unreachable("Unexpected OpenMP directive with num_teams-clause"); 12354 case OMPD_unknown: 12355 default: 12356 llvm_unreachable("Unknown OpenMP directive"); 12357 } 12358 break; 12359 case OMPC_grainsize: 12360 case OMPC_num_tasks: 12361 case OMPC_final: 12362 case OMPC_priority: 12363 switch (DKind) { 12364 case OMPD_task: 12365 case OMPD_taskloop: 12366 case OMPD_taskloop_simd: 12367 case OMPD_master_taskloop: 12368 case OMPD_master_taskloop_simd: 12369 break; 12370 case OMPD_parallel_master_taskloop: 12371 case OMPD_parallel_master_taskloop_simd: 12372 CaptureRegion = OMPD_parallel; 12373 break; 12374 case OMPD_target_update: 12375 case OMPD_target_enter_data: 12376 case OMPD_target_exit_data: 12377 case OMPD_target: 12378 case OMPD_target_simd: 12379 case OMPD_target_teams: 12380 case OMPD_target_parallel: 12381 case OMPD_target_teams_distribute: 12382 case OMPD_target_teams_distribute_simd: 12383 case OMPD_target_parallel_for: 12384 case OMPD_target_parallel_for_simd: 12385 case OMPD_target_teams_distribute_parallel_for: 12386 case OMPD_target_teams_distribute_parallel_for_simd: 12387 case OMPD_target_data: 12388 case OMPD_teams_distribute_parallel_for: 12389 case OMPD_teams_distribute_parallel_for_simd: 12390 case OMPD_teams: 12391 case OMPD_teams_distribute: 12392 case OMPD_teams_distribute_simd: 12393 case OMPD_distribute_parallel_for: 12394 case OMPD_distribute_parallel_for_simd: 12395 case OMPD_cancel: 12396 case OMPD_parallel: 12397 case OMPD_parallel_master: 12398 case OMPD_parallel_sections: 12399 case OMPD_parallel_for: 12400 case OMPD_parallel_for_simd: 12401 case OMPD_threadprivate: 12402 case OMPD_allocate: 12403 case OMPD_taskyield: 12404 case OMPD_barrier: 12405 case OMPD_taskwait: 12406 case OMPD_cancellation_point: 12407 case OMPD_flush: 12408 case OMPD_depobj: 12409 case OMPD_scan: 12410 case OMPD_declare_reduction: 12411 case OMPD_declare_mapper: 12412 case OMPD_declare_simd: 12413 case OMPD_declare_variant: 12414 case OMPD_begin_declare_variant: 12415 case OMPD_end_declare_variant: 12416 case OMPD_declare_target: 12417 case OMPD_end_declare_target: 12418 case OMPD_simd: 12419 case OMPD_for: 12420 case OMPD_for_simd: 12421 case OMPD_sections: 12422 case OMPD_section: 12423 case OMPD_single: 12424 case OMPD_master: 12425 case OMPD_critical: 12426 case OMPD_taskgroup: 12427 case OMPD_distribute: 12428 case OMPD_ordered: 12429 case OMPD_atomic: 12430 case OMPD_distribute_simd: 12431 case OMPD_requires: 12432 llvm_unreachable("Unexpected OpenMP directive with grainsize-clause"); 12433 case OMPD_unknown: 12434 default: 12435 llvm_unreachable("Unknown OpenMP directive"); 12436 } 12437 break; 12438 case OMPC_firstprivate: 12439 case OMPC_lastprivate: 12440 case OMPC_reduction: 12441 case OMPC_task_reduction: 12442 case OMPC_in_reduction: 12443 case OMPC_linear: 12444 case OMPC_default: 12445 case OMPC_proc_bind: 12446 case OMPC_safelen: 12447 case OMPC_simdlen: 12448 case OMPC_allocator: 12449 case OMPC_collapse: 12450 case OMPC_private: 12451 case OMPC_shared: 12452 case OMPC_aligned: 12453 case OMPC_copyin: 12454 case OMPC_copyprivate: 12455 case OMPC_ordered: 12456 case OMPC_nowait: 12457 case OMPC_untied: 12458 case OMPC_mergeable: 12459 case OMPC_threadprivate: 12460 case OMPC_allocate: 12461 case OMPC_flush: 12462 case OMPC_depobj: 12463 case OMPC_read: 12464 case OMPC_write: 12465 case OMPC_update: 12466 case OMPC_capture: 12467 case OMPC_seq_cst: 12468 case OMPC_acq_rel: 12469 case OMPC_acquire: 12470 case OMPC_release: 12471 case OMPC_relaxed: 12472 case OMPC_depend: 12473 case OMPC_threads: 12474 case OMPC_simd: 12475 case OMPC_map: 12476 case OMPC_nogroup: 12477 case OMPC_hint: 12478 case OMPC_defaultmap: 12479 case OMPC_unknown: 12480 case OMPC_uniform: 12481 case OMPC_to: 12482 case OMPC_from: 12483 case OMPC_use_device_ptr: 12484 case OMPC_use_device_addr: 12485 case OMPC_is_device_ptr: 12486 case OMPC_unified_address: 12487 case OMPC_unified_shared_memory: 12488 case OMPC_reverse_offload: 12489 case OMPC_dynamic_allocators: 12490 case OMPC_atomic_default_mem_order: 12491 case OMPC_device_type: 12492 case OMPC_match: 12493 case OMPC_nontemporal: 12494 case OMPC_order: 12495 case OMPC_destroy: 12496 case OMPC_detach: 12497 case OMPC_inclusive: 12498 case OMPC_exclusive: 12499 case OMPC_uses_allocators: 12500 case OMPC_affinity: 12501 default: 12502 llvm_unreachable("Unexpected OpenMP clause."); 12503 } 12504 return CaptureRegion; 12505 } 12506 12507 OMPClause *Sema::ActOnOpenMPIfClause(OpenMPDirectiveKind NameModifier, 12508 Expr *Condition, SourceLocation StartLoc, 12509 SourceLocation LParenLoc, 12510 SourceLocation NameModifierLoc, 12511 SourceLocation ColonLoc, 12512 SourceLocation EndLoc) { 12513 Expr *ValExpr = Condition; 12514 Stmt *HelperValStmt = nullptr; 12515 OpenMPDirectiveKind CaptureRegion = OMPD_unknown; 12516 if (!Condition->isValueDependent() && !Condition->isTypeDependent() && 12517 !Condition->isInstantiationDependent() && 12518 !Condition->containsUnexpandedParameterPack()) { 12519 ExprResult Val = CheckBooleanCondition(StartLoc, Condition); 12520 if (Val.isInvalid()) 12521 return nullptr; 12522 12523 ValExpr = Val.get(); 12524 12525 OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective(); 12526 CaptureRegion = getOpenMPCaptureRegionForClause( 12527 DKind, OMPC_if, LangOpts.OpenMP, NameModifier); 12528 if (CaptureRegion != OMPD_unknown && !CurContext->isDependentContext()) { 12529 ValExpr = MakeFullExpr(ValExpr).get(); 12530 llvm::MapVector<const Expr *, DeclRefExpr *> Captures; 12531 ValExpr = tryBuildCapture(*this, ValExpr, Captures).get(); 12532 HelperValStmt = buildPreInits(Context, Captures); 12533 } 12534 } 12535 12536 return new (Context) 12537 OMPIfClause(NameModifier, ValExpr, HelperValStmt, CaptureRegion, StartLoc, 12538 LParenLoc, NameModifierLoc, ColonLoc, EndLoc); 12539 } 12540 12541 OMPClause *Sema::ActOnOpenMPFinalClause(Expr *Condition, 12542 SourceLocation StartLoc, 12543 SourceLocation LParenLoc, 12544 SourceLocation EndLoc) { 12545 Expr *ValExpr = Condition; 12546 Stmt *HelperValStmt = nullptr; 12547 OpenMPDirectiveKind CaptureRegion = OMPD_unknown; 12548 if (!Condition->isValueDependent() && !Condition->isTypeDependent() && 12549 !Condition->isInstantiationDependent() && 12550 !Condition->containsUnexpandedParameterPack()) { 12551 ExprResult Val = CheckBooleanCondition(StartLoc, Condition); 12552 if (Val.isInvalid()) 12553 return nullptr; 12554 12555 ValExpr = MakeFullExpr(Val.get()).get(); 12556 12557 OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective(); 12558 CaptureRegion = 12559 getOpenMPCaptureRegionForClause(DKind, OMPC_final, LangOpts.OpenMP); 12560 if (CaptureRegion != OMPD_unknown && !CurContext->isDependentContext()) { 12561 ValExpr = MakeFullExpr(ValExpr).get(); 12562 llvm::MapVector<const Expr *, DeclRefExpr *> Captures; 12563 ValExpr = tryBuildCapture(*this, ValExpr, Captures).get(); 12564 HelperValStmt = buildPreInits(Context, Captures); 12565 } 12566 } 12567 12568 return new (Context) OMPFinalClause(ValExpr, HelperValStmt, CaptureRegion, 12569 StartLoc, LParenLoc, EndLoc); 12570 } 12571 12572 ExprResult Sema::PerformOpenMPImplicitIntegerConversion(SourceLocation Loc, 12573 Expr *Op) { 12574 if (!Op) 12575 return ExprError(); 12576 12577 class IntConvertDiagnoser : public ICEConvertDiagnoser { 12578 public: 12579 IntConvertDiagnoser() 12580 : ICEConvertDiagnoser(/*AllowScopedEnumerations*/ false, false, true) {} 12581 SemaDiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc, 12582 QualType T) override { 12583 return S.Diag(Loc, diag::err_omp_not_integral) << T; 12584 } 12585 SemaDiagnosticBuilder diagnoseIncomplete(Sema &S, SourceLocation Loc, 12586 QualType T) override { 12587 return S.Diag(Loc, diag::err_omp_incomplete_type) << T; 12588 } 12589 SemaDiagnosticBuilder diagnoseExplicitConv(Sema &S, SourceLocation Loc, 12590 QualType T, 12591 QualType ConvTy) override { 12592 return S.Diag(Loc, diag::err_omp_explicit_conversion) << T << ConvTy; 12593 } 12594 SemaDiagnosticBuilder noteExplicitConv(Sema &S, CXXConversionDecl *Conv, 12595 QualType ConvTy) override { 12596 return S.Diag(Conv->getLocation(), diag::note_omp_conversion_here) 12597 << ConvTy->isEnumeralType() << ConvTy; 12598 } 12599 SemaDiagnosticBuilder diagnoseAmbiguous(Sema &S, SourceLocation Loc, 12600 QualType T) override { 12601 return S.Diag(Loc, diag::err_omp_ambiguous_conversion) << T; 12602 } 12603 SemaDiagnosticBuilder noteAmbiguous(Sema &S, CXXConversionDecl *Conv, 12604 QualType ConvTy) override { 12605 return S.Diag(Conv->getLocation(), diag::note_omp_conversion_here) 12606 << ConvTy->isEnumeralType() << ConvTy; 12607 } 12608 SemaDiagnosticBuilder diagnoseConversion(Sema &, SourceLocation, QualType, 12609 QualType) override { 12610 llvm_unreachable("conversion functions are permitted"); 12611 } 12612 } ConvertDiagnoser; 12613 return PerformContextualImplicitConversion(Loc, Op, ConvertDiagnoser); 12614 } 12615 12616 static bool 12617 isNonNegativeIntegerValue(Expr *&ValExpr, Sema &SemaRef, OpenMPClauseKind CKind, 12618 bool StrictlyPositive, bool BuildCapture = false, 12619 OpenMPDirectiveKind DKind = OMPD_unknown, 12620 OpenMPDirectiveKind *CaptureRegion = nullptr, 12621 Stmt **HelperValStmt = nullptr) { 12622 if (!ValExpr->isTypeDependent() && !ValExpr->isValueDependent() && 12623 !ValExpr->isInstantiationDependent()) { 12624 SourceLocation Loc = ValExpr->getExprLoc(); 12625 ExprResult Value = 12626 SemaRef.PerformOpenMPImplicitIntegerConversion(Loc, ValExpr); 12627 if (Value.isInvalid()) 12628 return false; 12629 12630 ValExpr = Value.get(); 12631 // The expression must evaluate to a non-negative integer value. 12632 if (Optional<llvm::APSInt> Result = 12633 ValExpr->getIntegerConstantExpr(SemaRef.Context)) { 12634 if (Result->isSigned() && 12635 !((!StrictlyPositive && Result->isNonNegative()) || 12636 (StrictlyPositive && Result->isStrictlyPositive()))) { 12637 SemaRef.Diag(Loc, diag::err_omp_negative_expression_in_clause) 12638 << getOpenMPClauseName(CKind) << (StrictlyPositive ? 1 : 0) 12639 << ValExpr->getSourceRange(); 12640 return false; 12641 } 12642 } 12643 if (!BuildCapture) 12644 return true; 12645 *CaptureRegion = 12646 getOpenMPCaptureRegionForClause(DKind, CKind, SemaRef.LangOpts.OpenMP); 12647 if (*CaptureRegion != OMPD_unknown && 12648 !SemaRef.CurContext->isDependentContext()) { 12649 ValExpr = SemaRef.MakeFullExpr(ValExpr).get(); 12650 llvm::MapVector<const Expr *, DeclRefExpr *> Captures; 12651 ValExpr = tryBuildCapture(SemaRef, ValExpr, Captures).get(); 12652 *HelperValStmt = buildPreInits(SemaRef.Context, Captures); 12653 } 12654 } 12655 return true; 12656 } 12657 12658 OMPClause *Sema::ActOnOpenMPNumThreadsClause(Expr *NumThreads, 12659 SourceLocation StartLoc, 12660 SourceLocation LParenLoc, 12661 SourceLocation EndLoc) { 12662 Expr *ValExpr = NumThreads; 12663 Stmt *HelperValStmt = nullptr; 12664 12665 // OpenMP [2.5, Restrictions] 12666 // The num_threads expression must evaluate to a positive integer value. 12667 if (!isNonNegativeIntegerValue(ValExpr, *this, OMPC_num_threads, 12668 /*StrictlyPositive=*/true)) 12669 return nullptr; 12670 12671 OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective(); 12672 OpenMPDirectiveKind CaptureRegion = 12673 getOpenMPCaptureRegionForClause(DKind, OMPC_num_threads, LangOpts.OpenMP); 12674 if (CaptureRegion != OMPD_unknown && !CurContext->isDependentContext()) { 12675 ValExpr = MakeFullExpr(ValExpr).get(); 12676 llvm::MapVector<const Expr *, DeclRefExpr *> Captures; 12677 ValExpr = tryBuildCapture(*this, ValExpr, Captures).get(); 12678 HelperValStmt = buildPreInits(Context, Captures); 12679 } 12680 12681 return new (Context) OMPNumThreadsClause( 12682 ValExpr, HelperValStmt, CaptureRegion, StartLoc, LParenLoc, EndLoc); 12683 } 12684 12685 ExprResult Sema::VerifyPositiveIntegerConstantInClause(Expr *E, 12686 OpenMPClauseKind CKind, 12687 bool StrictlyPositive) { 12688 if (!E) 12689 return ExprError(); 12690 if (E->isValueDependent() || E->isTypeDependent() || 12691 E->isInstantiationDependent() || E->containsUnexpandedParameterPack()) 12692 return E; 12693 llvm::APSInt Result; 12694 ExprResult ICE = VerifyIntegerConstantExpression(E, &Result); 12695 if (ICE.isInvalid()) 12696 return ExprError(); 12697 if ((StrictlyPositive && !Result.isStrictlyPositive()) || 12698 (!StrictlyPositive && !Result.isNonNegative())) { 12699 Diag(E->getExprLoc(), diag::err_omp_negative_expression_in_clause) 12700 << getOpenMPClauseName(CKind) << (StrictlyPositive ? 1 : 0) 12701 << E->getSourceRange(); 12702 return ExprError(); 12703 } 12704 if (CKind == OMPC_aligned && !Result.isPowerOf2()) { 12705 Diag(E->getExprLoc(), diag::warn_omp_alignment_not_power_of_two) 12706 << E->getSourceRange(); 12707 return ExprError(); 12708 } 12709 if (CKind == OMPC_collapse && DSAStack->getAssociatedLoops() == 1) 12710 DSAStack->setAssociatedLoops(Result.getExtValue()); 12711 else if (CKind == OMPC_ordered) 12712 DSAStack->setAssociatedLoops(Result.getExtValue()); 12713 return ICE; 12714 } 12715 12716 OMPClause *Sema::ActOnOpenMPSafelenClause(Expr *Len, SourceLocation StartLoc, 12717 SourceLocation LParenLoc, 12718 SourceLocation EndLoc) { 12719 // OpenMP [2.8.1, simd construct, Description] 12720 // The parameter of the safelen clause must be a constant 12721 // positive integer expression. 12722 ExprResult Safelen = VerifyPositiveIntegerConstantInClause(Len, OMPC_safelen); 12723 if (Safelen.isInvalid()) 12724 return nullptr; 12725 return new (Context) 12726 OMPSafelenClause(Safelen.get(), StartLoc, LParenLoc, EndLoc); 12727 } 12728 12729 OMPClause *Sema::ActOnOpenMPSimdlenClause(Expr *Len, SourceLocation StartLoc, 12730 SourceLocation LParenLoc, 12731 SourceLocation EndLoc) { 12732 // OpenMP [2.8.1, simd construct, Description] 12733 // The parameter of the simdlen clause must be a constant 12734 // positive integer expression. 12735 ExprResult Simdlen = VerifyPositiveIntegerConstantInClause(Len, OMPC_simdlen); 12736 if (Simdlen.isInvalid()) 12737 return nullptr; 12738 return new (Context) 12739 OMPSimdlenClause(Simdlen.get(), StartLoc, LParenLoc, EndLoc); 12740 } 12741 12742 /// Tries to find omp_allocator_handle_t type. 12743 static bool findOMPAllocatorHandleT(Sema &S, SourceLocation Loc, 12744 DSAStackTy *Stack) { 12745 QualType OMPAllocatorHandleT = Stack->getOMPAllocatorHandleT(); 12746 if (!OMPAllocatorHandleT.isNull()) 12747 return true; 12748 // Build the predefined allocator expressions. 12749 bool ErrorFound = false; 12750 for (int I = 0; I < OMPAllocateDeclAttr::OMPUserDefinedMemAlloc; ++I) { 12751 auto AllocatorKind = static_cast<OMPAllocateDeclAttr::AllocatorTypeTy>(I); 12752 StringRef Allocator = 12753 OMPAllocateDeclAttr::ConvertAllocatorTypeTyToStr(AllocatorKind); 12754 DeclarationName AllocatorName = &S.getASTContext().Idents.get(Allocator); 12755 auto *VD = dyn_cast_or_null<ValueDecl>( 12756 S.LookupSingleName(S.TUScope, AllocatorName, Loc, Sema::LookupAnyName)); 12757 if (!VD) { 12758 ErrorFound = true; 12759 break; 12760 } 12761 QualType AllocatorType = 12762 VD->getType().getNonLValueExprType(S.getASTContext()); 12763 ExprResult Res = S.BuildDeclRefExpr(VD, AllocatorType, VK_LValue, Loc); 12764 if (!Res.isUsable()) { 12765 ErrorFound = true; 12766 break; 12767 } 12768 if (OMPAllocatorHandleT.isNull()) 12769 OMPAllocatorHandleT = AllocatorType; 12770 if (!S.getASTContext().hasSameType(OMPAllocatorHandleT, AllocatorType)) { 12771 ErrorFound = true; 12772 break; 12773 } 12774 Stack->setAllocator(AllocatorKind, Res.get()); 12775 } 12776 if (ErrorFound) { 12777 S.Diag(Loc, diag::err_omp_implied_type_not_found) 12778 << "omp_allocator_handle_t"; 12779 return false; 12780 } 12781 OMPAllocatorHandleT.addConst(); 12782 Stack->setOMPAllocatorHandleT(OMPAllocatorHandleT); 12783 return true; 12784 } 12785 12786 OMPClause *Sema::ActOnOpenMPAllocatorClause(Expr *A, SourceLocation StartLoc, 12787 SourceLocation LParenLoc, 12788 SourceLocation EndLoc) { 12789 // OpenMP [2.11.3, allocate Directive, Description] 12790 // allocator is an expression of omp_allocator_handle_t type. 12791 if (!findOMPAllocatorHandleT(*this, A->getExprLoc(), DSAStack)) 12792 return nullptr; 12793 12794 ExprResult Allocator = DefaultLvalueConversion(A); 12795 if (Allocator.isInvalid()) 12796 return nullptr; 12797 Allocator = PerformImplicitConversion(Allocator.get(), 12798 DSAStack->getOMPAllocatorHandleT(), 12799 Sema::AA_Initializing, 12800 /*AllowExplicit=*/true); 12801 if (Allocator.isInvalid()) 12802 return nullptr; 12803 return new (Context) 12804 OMPAllocatorClause(Allocator.get(), StartLoc, LParenLoc, EndLoc); 12805 } 12806 12807 OMPClause *Sema::ActOnOpenMPCollapseClause(Expr *NumForLoops, 12808 SourceLocation StartLoc, 12809 SourceLocation LParenLoc, 12810 SourceLocation EndLoc) { 12811 // OpenMP [2.7.1, loop construct, Description] 12812 // OpenMP [2.8.1, simd construct, Description] 12813 // OpenMP [2.9.6, distribute construct, Description] 12814 // The parameter of the collapse clause must be a constant 12815 // positive integer expression. 12816 ExprResult NumForLoopsResult = 12817 VerifyPositiveIntegerConstantInClause(NumForLoops, OMPC_collapse); 12818 if (NumForLoopsResult.isInvalid()) 12819 return nullptr; 12820 return new (Context) 12821 OMPCollapseClause(NumForLoopsResult.get(), StartLoc, LParenLoc, EndLoc); 12822 } 12823 12824 OMPClause *Sema::ActOnOpenMPOrderedClause(SourceLocation StartLoc, 12825 SourceLocation EndLoc, 12826 SourceLocation LParenLoc, 12827 Expr *NumForLoops) { 12828 // OpenMP [2.7.1, loop construct, Description] 12829 // OpenMP [2.8.1, simd construct, Description] 12830 // OpenMP [2.9.6, distribute construct, Description] 12831 // The parameter of the ordered clause must be a constant 12832 // positive integer expression if any. 12833 if (NumForLoops && LParenLoc.isValid()) { 12834 ExprResult NumForLoopsResult = 12835 VerifyPositiveIntegerConstantInClause(NumForLoops, OMPC_ordered); 12836 if (NumForLoopsResult.isInvalid()) 12837 return nullptr; 12838 NumForLoops = NumForLoopsResult.get(); 12839 } else { 12840 NumForLoops = nullptr; 12841 } 12842 auto *Clause = OMPOrderedClause::Create( 12843 Context, NumForLoops, NumForLoops ? DSAStack->getAssociatedLoops() : 0, 12844 StartLoc, LParenLoc, EndLoc); 12845 DSAStack->setOrderedRegion(/*IsOrdered=*/true, NumForLoops, Clause); 12846 return Clause; 12847 } 12848 12849 OMPClause *Sema::ActOnOpenMPSimpleClause( 12850 OpenMPClauseKind Kind, unsigned Argument, SourceLocation ArgumentLoc, 12851 SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc) { 12852 OMPClause *Res = nullptr; 12853 switch (Kind) { 12854 case OMPC_default: 12855 Res = ActOnOpenMPDefaultClause(static_cast<DefaultKind>(Argument), 12856 ArgumentLoc, StartLoc, LParenLoc, EndLoc); 12857 break; 12858 case OMPC_proc_bind: 12859 Res = ActOnOpenMPProcBindClause(static_cast<ProcBindKind>(Argument), 12860 ArgumentLoc, StartLoc, LParenLoc, EndLoc); 12861 break; 12862 case OMPC_atomic_default_mem_order: 12863 Res = ActOnOpenMPAtomicDefaultMemOrderClause( 12864 static_cast<OpenMPAtomicDefaultMemOrderClauseKind>(Argument), 12865 ArgumentLoc, StartLoc, LParenLoc, EndLoc); 12866 break; 12867 case OMPC_order: 12868 Res = ActOnOpenMPOrderClause(static_cast<OpenMPOrderClauseKind>(Argument), 12869 ArgumentLoc, StartLoc, LParenLoc, EndLoc); 12870 break; 12871 case OMPC_update: 12872 Res = ActOnOpenMPUpdateClause(static_cast<OpenMPDependClauseKind>(Argument), 12873 ArgumentLoc, StartLoc, LParenLoc, EndLoc); 12874 break; 12875 case OMPC_if: 12876 case OMPC_final: 12877 case OMPC_num_threads: 12878 case OMPC_safelen: 12879 case OMPC_simdlen: 12880 case OMPC_allocator: 12881 case OMPC_collapse: 12882 case OMPC_schedule: 12883 case OMPC_private: 12884 case OMPC_firstprivate: 12885 case OMPC_lastprivate: 12886 case OMPC_shared: 12887 case OMPC_reduction: 12888 case OMPC_task_reduction: 12889 case OMPC_in_reduction: 12890 case OMPC_linear: 12891 case OMPC_aligned: 12892 case OMPC_copyin: 12893 case OMPC_copyprivate: 12894 case OMPC_ordered: 12895 case OMPC_nowait: 12896 case OMPC_untied: 12897 case OMPC_mergeable: 12898 case OMPC_threadprivate: 12899 case OMPC_allocate: 12900 case OMPC_flush: 12901 case OMPC_depobj: 12902 case OMPC_read: 12903 case OMPC_write: 12904 case OMPC_capture: 12905 case OMPC_seq_cst: 12906 case OMPC_acq_rel: 12907 case OMPC_acquire: 12908 case OMPC_release: 12909 case OMPC_relaxed: 12910 case OMPC_depend: 12911 case OMPC_device: 12912 case OMPC_threads: 12913 case OMPC_simd: 12914 case OMPC_map: 12915 case OMPC_num_teams: 12916 case OMPC_thread_limit: 12917 case OMPC_priority: 12918 case OMPC_grainsize: 12919 case OMPC_nogroup: 12920 case OMPC_num_tasks: 12921 case OMPC_hint: 12922 case OMPC_dist_schedule: 12923 case OMPC_defaultmap: 12924 case OMPC_unknown: 12925 case OMPC_uniform: 12926 case OMPC_to: 12927 case OMPC_from: 12928 case OMPC_use_device_ptr: 12929 case OMPC_use_device_addr: 12930 case OMPC_is_device_ptr: 12931 case OMPC_unified_address: 12932 case OMPC_unified_shared_memory: 12933 case OMPC_reverse_offload: 12934 case OMPC_dynamic_allocators: 12935 case OMPC_device_type: 12936 case OMPC_match: 12937 case OMPC_nontemporal: 12938 case OMPC_destroy: 12939 case OMPC_detach: 12940 case OMPC_inclusive: 12941 case OMPC_exclusive: 12942 case OMPC_uses_allocators: 12943 case OMPC_affinity: 12944 default: 12945 llvm_unreachable("Clause is not allowed."); 12946 } 12947 return Res; 12948 } 12949 12950 static std::string 12951 getListOfPossibleValues(OpenMPClauseKind K, unsigned First, unsigned Last, 12952 ArrayRef<unsigned> Exclude = llvm::None) { 12953 SmallString<256> Buffer; 12954 llvm::raw_svector_ostream Out(Buffer); 12955 unsigned Skipped = Exclude.size(); 12956 auto S = Exclude.begin(), E = Exclude.end(); 12957 for (unsigned I = First; I < Last; ++I) { 12958 if (std::find(S, E, I) != E) { 12959 --Skipped; 12960 continue; 12961 } 12962 Out << "'" << getOpenMPSimpleClauseTypeName(K, I) << "'"; 12963 if (I + Skipped + 2 == Last) 12964 Out << " or "; 12965 else if (I + Skipped + 1 != Last) 12966 Out << ", "; 12967 } 12968 return std::string(Out.str()); 12969 } 12970 12971 OMPClause *Sema::ActOnOpenMPDefaultClause(DefaultKind Kind, 12972 SourceLocation KindKwLoc, 12973 SourceLocation StartLoc, 12974 SourceLocation LParenLoc, 12975 SourceLocation EndLoc) { 12976 if (Kind == OMP_DEFAULT_unknown) { 12977 Diag(KindKwLoc, diag::err_omp_unexpected_clause_value) 12978 << getListOfPossibleValues(OMPC_default, /*First=*/0, 12979 /*Last=*/unsigned(OMP_DEFAULT_unknown)) 12980 << getOpenMPClauseName(OMPC_default); 12981 return nullptr; 12982 } 12983 12984 switch (Kind) { 12985 case OMP_DEFAULT_none: 12986 DSAStack->setDefaultDSANone(KindKwLoc); 12987 break; 12988 case OMP_DEFAULT_shared: 12989 DSAStack->setDefaultDSAShared(KindKwLoc); 12990 break; 12991 case OMP_DEFAULT_firstprivate: 12992 DSAStack->setDefaultDSAFirstPrivate(KindKwLoc); 12993 break; 12994 default: 12995 llvm_unreachable("DSA unexpected in OpenMP default clause"); 12996 } 12997 12998 return new (Context) 12999 OMPDefaultClause(Kind, KindKwLoc, StartLoc, LParenLoc, EndLoc); 13000 } 13001 13002 OMPClause *Sema::ActOnOpenMPProcBindClause(ProcBindKind Kind, 13003 SourceLocation KindKwLoc, 13004 SourceLocation StartLoc, 13005 SourceLocation LParenLoc, 13006 SourceLocation EndLoc) { 13007 if (Kind == OMP_PROC_BIND_unknown) { 13008 Diag(KindKwLoc, diag::err_omp_unexpected_clause_value) 13009 << getListOfPossibleValues(OMPC_proc_bind, 13010 /*First=*/unsigned(OMP_PROC_BIND_master), 13011 /*Last=*/5) 13012 << getOpenMPClauseName(OMPC_proc_bind); 13013 return nullptr; 13014 } 13015 return new (Context) 13016 OMPProcBindClause(Kind, KindKwLoc, StartLoc, LParenLoc, EndLoc); 13017 } 13018 13019 OMPClause *Sema::ActOnOpenMPAtomicDefaultMemOrderClause( 13020 OpenMPAtomicDefaultMemOrderClauseKind Kind, SourceLocation KindKwLoc, 13021 SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc) { 13022 if (Kind == OMPC_ATOMIC_DEFAULT_MEM_ORDER_unknown) { 13023 Diag(KindKwLoc, diag::err_omp_unexpected_clause_value) 13024 << getListOfPossibleValues( 13025 OMPC_atomic_default_mem_order, /*First=*/0, 13026 /*Last=*/OMPC_ATOMIC_DEFAULT_MEM_ORDER_unknown) 13027 << getOpenMPClauseName(OMPC_atomic_default_mem_order); 13028 return nullptr; 13029 } 13030 return new (Context) OMPAtomicDefaultMemOrderClause(Kind, KindKwLoc, StartLoc, 13031 LParenLoc, EndLoc); 13032 } 13033 13034 OMPClause *Sema::ActOnOpenMPOrderClause(OpenMPOrderClauseKind Kind, 13035 SourceLocation KindKwLoc, 13036 SourceLocation StartLoc, 13037 SourceLocation LParenLoc, 13038 SourceLocation EndLoc) { 13039 if (Kind == OMPC_ORDER_unknown) { 13040 static_assert(OMPC_ORDER_unknown > 0, 13041 "OMPC_ORDER_unknown not greater than 0"); 13042 Diag(KindKwLoc, diag::err_omp_unexpected_clause_value) 13043 << getListOfPossibleValues(OMPC_order, /*First=*/0, 13044 /*Last=*/OMPC_ORDER_unknown) 13045 << getOpenMPClauseName(OMPC_order); 13046 return nullptr; 13047 } 13048 return new (Context) 13049 OMPOrderClause(Kind, KindKwLoc, StartLoc, LParenLoc, EndLoc); 13050 } 13051 13052 OMPClause *Sema::ActOnOpenMPUpdateClause(OpenMPDependClauseKind Kind, 13053 SourceLocation KindKwLoc, 13054 SourceLocation StartLoc, 13055 SourceLocation LParenLoc, 13056 SourceLocation EndLoc) { 13057 if (Kind == OMPC_DEPEND_unknown || Kind == OMPC_DEPEND_source || 13058 Kind == OMPC_DEPEND_sink || Kind == OMPC_DEPEND_depobj) { 13059 unsigned Except[] = {OMPC_DEPEND_source, OMPC_DEPEND_sink, 13060 OMPC_DEPEND_depobj}; 13061 Diag(KindKwLoc, diag::err_omp_unexpected_clause_value) 13062 << getListOfPossibleValues(OMPC_depend, /*First=*/0, 13063 /*Last=*/OMPC_DEPEND_unknown, Except) 13064 << getOpenMPClauseName(OMPC_update); 13065 return nullptr; 13066 } 13067 return OMPUpdateClause::Create(Context, StartLoc, LParenLoc, KindKwLoc, Kind, 13068 EndLoc); 13069 } 13070 13071 OMPClause *Sema::ActOnOpenMPSingleExprWithArgClause( 13072 OpenMPClauseKind Kind, ArrayRef<unsigned> Argument, Expr *Expr, 13073 SourceLocation StartLoc, SourceLocation LParenLoc, 13074 ArrayRef<SourceLocation> ArgumentLoc, SourceLocation DelimLoc, 13075 SourceLocation EndLoc) { 13076 OMPClause *Res = nullptr; 13077 switch (Kind) { 13078 case OMPC_schedule: 13079 enum { Modifier1, Modifier2, ScheduleKind, NumberOfElements }; 13080 assert(Argument.size() == NumberOfElements && 13081 ArgumentLoc.size() == NumberOfElements); 13082 Res = ActOnOpenMPScheduleClause( 13083 static_cast<OpenMPScheduleClauseModifier>(Argument[Modifier1]), 13084 static_cast<OpenMPScheduleClauseModifier>(Argument[Modifier2]), 13085 static_cast<OpenMPScheduleClauseKind>(Argument[ScheduleKind]), Expr, 13086 StartLoc, LParenLoc, ArgumentLoc[Modifier1], ArgumentLoc[Modifier2], 13087 ArgumentLoc[ScheduleKind], DelimLoc, EndLoc); 13088 break; 13089 case OMPC_if: 13090 assert(Argument.size() == 1 && ArgumentLoc.size() == 1); 13091 Res = ActOnOpenMPIfClause(static_cast<OpenMPDirectiveKind>(Argument.back()), 13092 Expr, StartLoc, LParenLoc, ArgumentLoc.back(), 13093 DelimLoc, EndLoc); 13094 break; 13095 case OMPC_dist_schedule: 13096 Res = ActOnOpenMPDistScheduleClause( 13097 static_cast<OpenMPDistScheduleClauseKind>(Argument.back()), Expr, 13098 StartLoc, LParenLoc, ArgumentLoc.back(), DelimLoc, EndLoc); 13099 break; 13100 case OMPC_defaultmap: 13101 enum { Modifier, DefaultmapKind }; 13102 Res = ActOnOpenMPDefaultmapClause( 13103 static_cast<OpenMPDefaultmapClauseModifier>(Argument[Modifier]), 13104 static_cast<OpenMPDefaultmapClauseKind>(Argument[DefaultmapKind]), 13105 StartLoc, LParenLoc, ArgumentLoc[Modifier], ArgumentLoc[DefaultmapKind], 13106 EndLoc); 13107 break; 13108 case OMPC_device: 13109 assert(Argument.size() == 1 && ArgumentLoc.size() == 1); 13110 Res = ActOnOpenMPDeviceClause( 13111 static_cast<OpenMPDeviceClauseModifier>(Argument.back()), Expr, 13112 StartLoc, LParenLoc, ArgumentLoc.back(), EndLoc); 13113 break; 13114 case OMPC_final: 13115 case OMPC_num_threads: 13116 case OMPC_safelen: 13117 case OMPC_simdlen: 13118 case OMPC_allocator: 13119 case OMPC_collapse: 13120 case OMPC_default: 13121 case OMPC_proc_bind: 13122 case OMPC_private: 13123 case OMPC_firstprivate: 13124 case OMPC_lastprivate: 13125 case OMPC_shared: 13126 case OMPC_reduction: 13127 case OMPC_task_reduction: 13128 case OMPC_in_reduction: 13129 case OMPC_linear: 13130 case OMPC_aligned: 13131 case OMPC_copyin: 13132 case OMPC_copyprivate: 13133 case OMPC_ordered: 13134 case OMPC_nowait: 13135 case OMPC_untied: 13136 case OMPC_mergeable: 13137 case OMPC_threadprivate: 13138 case OMPC_allocate: 13139 case OMPC_flush: 13140 case OMPC_depobj: 13141 case OMPC_read: 13142 case OMPC_write: 13143 case OMPC_update: 13144 case OMPC_capture: 13145 case OMPC_seq_cst: 13146 case OMPC_acq_rel: 13147 case OMPC_acquire: 13148 case OMPC_release: 13149 case OMPC_relaxed: 13150 case OMPC_depend: 13151 case OMPC_threads: 13152 case OMPC_simd: 13153 case OMPC_map: 13154 case OMPC_num_teams: 13155 case OMPC_thread_limit: 13156 case OMPC_priority: 13157 case OMPC_grainsize: 13158 case OMPC_nogroup: 13159 case OMPC_num_tasks: 13160 case OMPC_hint: 13161 case OMPC_unknown: 13162 case OMPC_uniform: 13163 case OMPC_to: 13164 case OMPC_from: 13165 case OMPC_use_device_ptr: 13166 case OMPC_use_device_addr: 13167 case OMPC_is_device_ptr: 13168 case OMPC_unified_address: 13169 case OMPC_unified_shared_memory: 13170 case OMPC_reverse_offload: 13171 case OMPC_dynamic_allocators: 13172 case OMPC_atomic_default_mem_order: 13173 case OMPC_device_type: 13174 case OMPC_match: 13175 case OMPC_nontemporal: 13176 case OMPC_order: 13177 case OMPC_destroy: 13178 case OMPC_detach: 13179 case OMPC_inclusive: 13180 case OMPC_exclusive: 13181 case OMPC_uses_allocators: 13182 case OMPC_affinity: 13183 default: 13184 llvm_unreachable("Clause is not allowed."); 13185 } 13186 return Res; 13187 } 13188 13189 static bool checkScheduleModifiers(Sema &S, OpenMPScheduleClauseModifier M1, 13190 OpenMPScheduleClauseModifier M2, 13191 SourceLocation M1Loc, SourceLocation M2Loc) { 13192 if (M1 == OMPC_SCHEDULE_MODIFIER_unknown && M1Loc.isValid()) { 13193 SmallVector<unsigned, 2> Excluded; 13194 if (M2 != OMPC_SCHEDULE_MODIFIER_unknown) 13195 Excluded.push_back(M2); 13196 if (M2 == OMPC_SCHEDULE_MODIFIER_nonmonotonic) 13197 Excluded.push_back(OMPC_SCHEDULE_MODIFIER_monotonic); 13198 if (M2 == OMPC_SCHEDULE_MODIFIER_monotonic) 13199 Excluded.push_back(OMPC_SCHEDULE_MODIFIER_nonmonotonic); 13200 S.Diag(M1Loc, diag::err_omp_unexpected_clause_value) 13201 << getListOfPossibleValues(OMPC_schedule, 13202 /*First=*/OMPC_SCHEDULE_MODIFIER_unknown + 1, 13203 /*Last=*/OMPC_SCHEDULE_MODIFIER_last, 13204 Excluded) 13205 << getOpenMPClauseName(OMPC_schedule); 13206 return true; 13207 } 13208 return false; 13209 } 13210 13211 OMPClause *Sema::ActOnOpenMPScheduleClause( 13212 OpenMPScheduleClauseModifier M1, OpenMPScheduleClauseModifier M2, 13213 OpenMPScheduleClauseKind Kind, Expr *ChunkSize, SourceLocation StartLoc, 13214 SourceLocation LParenLoc, SourceLocation M1Loc, SourceLocation M2Loc, 13215 SourceLocation KindLoc, SourceLocation CommaLoc, SourceLocation EndLoc) { 13216 if (checkScheduleModifiers(*this, M1, M2, M1Loc, M2Loc) || 13217 checkScheduleModifiers(*this, M2, M1, M2Loc, M1Loc)) 13218 return nullptr; 13219 // OpenMP, 2.7.1, Loop Construct, Restrictions 13220 // Either the monotonic modifier or the nonmonotonic modifier can be specified 13221 // but not both. 13222 if ((M1 == M2 && M1 != OMPC_SCHEDULE_MODIFIER_unknown) || 13223 (M1 == OMPC_SCHEDULE_MODIFIER_monotonic && 13224 M2 == OMPC_SCHEDULE_MODIFIER_nonmonotonic) || 13225 (M1 == OMPC_SCHEDULE_MODIFIER_nonmonotonic && 13226 M2 == OMPC_SCHEDULE_MODIFIER_monotonic)) { 13227 Diag(M2Loc, diag::err_omp_unexpected_schedule_modifier) 13228 << getOpenMPSimpleClauseTypeName(OMPC_schedule, M2) 13229 << getOpenMPSimpleClauseTypeName(OMPC_schedule, M1); 13230 return nullptr; 13231 } 13232 if (Kind == OMPC_SCHEDULE_unknown) { 13233 std::string Values; 13234 if (M1Loc.isInvalid() && M2Loc.isInvalid()) { 13235 unsigned Exclude[] = {OMPC_SCHEDULE_unknown}; 13236 Values = getListOfPossibleValues(OMPC_schedule, /*First=*/0, 13237 /*Last=*/OMPC_SCHEDULE_MODIFIER_last, 13238 Exclude); 13239 } else { 13240 Values = getListOfPossibleValues(OMPC_schedule, /*First=*/0, 13241 /*Last=*/OMPC_SCHEDULE_unknown); 13242 } 13243 Diag(KindLoc, diag::err_omp_unexpected_clause_value) 13244 << Values << getOpenMPClauseName(OMPC_schedule); 13245 return nullptr; 13246 } 13247 // OpenMP, 2.7.1, Loop Construct, Restrictions 13248 // The nonmonotonic modifier can only be specified with schedule(dynamic) or 13249 // schedule(guided). 13250 // OpenMP 5.0 does not have this restriction. 13251 if (LangOpts.OpenMP < 50 && 13252 (M1 == OMPC_SCHEDULE_MODIFIER_nonmonotonic || 13253 M2 == OMPC_SCHEDULE_MODIFIER_nonmonotonic) && 13254 Kind != OMPC_SCHEDULE_dynamic && Kind != OMPC_SCHEDULE_guided) { 13255 Diag(M1 == OMPC_SCHEDULE_MODIFIER_nonmonotonic ? M1Loc : M2Loc, 13256 diag::err_omp_schedule_nonmonotonic_static); 13257 return nullptr; 13258 } 13259 Expr *ValExpr = ChunkSize; 13260 Stmt *HelperValStmt = nullptr; 13261 if (ChunkSize) { 13262 if (!ChunkSize->isValueDependent() && !ChunkSize->isTypeDependent() && 13263 !ChunkSize->isInstantiationDependent() && 13264 !ChunkSize->containsUnexpandedParameterPack()) { 13265 SourceLocation ChunkSizeLoc = ChunkSize->getBeginLoc(); 13266 ExprResult Val = 13267 PerformOpenMPImplicitIntegerConversion(ChunkSizeLoc, ChunkSize); 13268 if (Val.isInvalid()) 13269 return nullptr; 13270 13271 ValExpr = Val.get(); 13272 13273 // OpenMP [2.7.1, Restrictions] 13274 // chunk_size must be a loop invariant integer expression with a positive 13275 // value. 13276 if (Optional<llvm::APSInt> Result = 13277 ValExpr->getIntegerConstantExpr(Context)) { 13278 if (Result->isSigned() && !Result->isStrictlyPositive()) { 13279 Diag(ChunkSizeLoc, diag::err_omp_negative_expression_in_clause) 13280 << "schedule" << 1 << ChunkSize->getSourceRange(); 13281 return nullptr; 13282 } 13283 } else if (getOpenMPCaptureRegionForClause( 13284 DSAStack->getCurrentDirective(), OMPC_schedule, 13285 LangOpts.OpenMP) != OMPD_unknown && 13286 !CurContext->isDependentContext()) { 13287 ValExpr = MakeFullExpr(ValExpr).get(); 13288 llvm::MapVector<const Expr *, DeclRefExpr *> Captures; 13289 ValExpr = tryBuildCapture(*this, ValExpr, Captures).get(); 13290 HelperValStmt = buildPreInits(Context, Captures); 13291 } 13292 } 13293 } 13294 13295 return new (Context) 13296 OMPScheduleClause(StartLoc, LParenLoc, KindLoc, CommaLoc, EndLoc, Kind, 13297 ValExpr, HelperValStmt, M1, M1Loc, M2, M2Loc); 13298 } 13299 13300 OMPClause *Sema::ActOnOpenMPClause(OpenMPClauseKind Kind, 13301 SourceLocation StartLoc, 13302 SourceLocation EndLoc) { 13303 OMPClause *Res = nullptr; 13304 switch (Kind) { 13305 case OMPC_ordered: 13306 Res = ActOnOpenMPOrderedClause(StartLoc, EndLoc); 13307 break; 13308 case OMPC_nowait: 13309 Res = ActOnOpenMPNowaitClause(StartLoc, EndLoc); 13310 break; 13311 case OMPC_untied: 13312 Res = ActOnOpenMPUntiedClause(StartLoc, EndLoc); 13313 break; 13314 case OMPC_mergeable: 13315 Res = ActOnOpenMPMergeableClause(StartLoc, EndLoc); 13316 break; 13317 case OMPC_read: 13318 Res = ActOnOpenMPReadClause(StartLoc, EndLoc); 13319 break; 13320 case OMPC_write: 13321 Res = ActOnOpenMPWriteClause(StartLoc, EndLoc); 13322 break; 13323 case OMPC_update: 13324 Res = ActOnOpenMPUpdateClause(StartLoc, EndLoc); 13325 break; 13326 case OMPC_capture: 13327 Res = ActOnOpenMPCaptureClause(StartLoc, EndLoc); 13328 break; 13329 case OMPC_seq_cst: 13330 Res = ActOnOpenMPSeqCstClause(StartLoc, EndLoc); 13331 break; 13332 case OMPC_acq_rel: 13333 Res = ActOnOpenMPAcqRelClause(StartLoc, EndLoc); 13334 break; 13335 case OMPC_acquire: 13336 Res = ActOnOpenMPAcquireClause(StartLoc, EndLoc); 13337 break; 13338 case OMPC_release: 13339 Res = ActOnOpenMPReleaseClause(StartLoc, EndLoc); 13340 break; 13341 case OMPC_relaxed: 13342 Res = ActOnOpenMPRelaxedClause(StartLoc, EndLoc); 13343 break; 13344 case OMPC_threads: 13345 Res = ActOnOpenMPThreadsClause(StartLoc, EndLoc); 13346 break; 13347 case OMPC_simd: 13348 Res = ActOnOpenMPSIMDClause(StartLoc, EndLoc); 13349 break; 13350 case OMPC_nogroup: 13351 Res = ActOnOpenMPNogroupClause(StartLoc, EndLoc); 13352 break; 13353 case OMPC_unified_address: 13354 Res = ActOnOpenMPUnifiedAddressClause(StartLoc, EndLoc); 13355 break; 13356 case OMPC_unified_shared_memory: 13357 Res = ActOnOpenMPUnifiedSharedMemoryClause(StartLoc, EndLoc); 13358 break; 13359 case OMPC_reverse_offload: 13360 Res = ActOnOpenMPReverseOffloadClause(StartLoc, EndLoc); 13361 break; 13362 case OMPC_dynamic_allocators: 13363 Res = ActOnOpenMPDynamicAllocatorsClause(StartLoc, EndLoc); 13364 break; 13365 case OMPC_destroy: 13366 Res = ActOnOpenMPDestroyClause(StartLoc, EndLoc); 13367 break; 13368 case OMPC_if: 13369 case OMPC_final: 13370 case OMPC_num_threads: 13371 case OMPC_safelen: 13372 case OMPC_simdlen: 13373 case OMPC_allocator: 13374 case OMPC_collapse: 13375 case OMPC_schedule: 13376 case OMPC_private: 13377 case OMPC_firstprivate: 13378 case OMPC_lastprivate: 13379 case OMPC_shared: 13380 case OMPC_reduction: 13381 case OMPC_task_reduction: 13382 case OMPC_in_reduction: 13383 case OMPC_linear: 13384 case OMPC_aligned: 13385 case OMPC_copyin: 13386 case OMPC_copyprivate: 13387 case OMPC_default: 13388 case OMPC_proc_bind: 13389 case OMPC_threadprivate: 13390 case OMPC_allocate: 13391 case OMPC_flush: 13392 case OMPC_depobj: 13393 case OMPC_depend: 13394 case OMPC_device: 13395 case OMPC_map: 13396 case OMPC_num_teams: 13397 case OMPC_thread_limit: 13398 case OMPC_priority: 13399 case OMPC_grainsize: 13400 case OMPC_num_tasks: 13401 case OMPC_hint: 13402 case OMPC_dist_schedule: 13403 case OMPC_defaultmap: 13404 case OMPC_unknown: 13405 case OMPC_uniform: 13406 case OMPC_to: 13407 case OMPC_from: 13408 case OMPC_use_device_ptr: 13409 case OMPC_use_device_addr: 13410 case OMPC_is_device_ptr: 13411 case OMPC_atomic_default_mem_order: 13412 case OMPC_device_type: 13413 case OMPC_match: 13414 case OMPC_nontemporal: 13415 case OMPC_order: 13416 case OMPC_detach: 13417 case OMPC_inclusive: 13418 case OMPC_exclusive: 13419 case OMPC_uses_allocators: 13420 case OMPC_affinity: 13421 default: 13422 llvm_unreachable("Clause is not allowed."); 13423 } 13424 return Res; 13425 } 13426 13427 OMPClause *Sema::ActOnOpenMPNowaitClause(SourceLocation StartLoc, 13428 SourceLocation EndLoc) { 13429 DSAStack->setNowaitRegion(); 13430 return new (Context) OMPNowaitClause(StartLoc, EndLoc); 13431 } 13432 13433 OMPClause *Sema::ActOnOpenMPUntiedClause(SourceLocation StartLoc, 13434 SourceLocation EndLoc) { 13435 return new (Context) OMPUntiedClause(StartLoc, EndLoc); 13436 } 13437 13438 OMPClause *Sema::ActOnOpenMPMergeableClause(SourceLocation StartLoc, 13439 SourceLocation EndLoc) { 13440 return new (Context) OMPMergeableClause(StartLoc, EndLoc); 13441 } 13442 13443 OMPClause *Sema::ActOnOpenMPReadClause(SourceLocation StartLoc, 13444 SourceLocation EndLoc) { 13445 return new (Context) OMPReadClause(StartLoc, EndLoc); 13446 } 13447 13448 OMPClause *Sema::ActOnOpenMPWriteClause(SourceLocation StartLoc, 13449 SourceLocation EndLoc) { 13450 return new (Context) OMPWriteClause(StartLoc, EndLoc); 13451 } 13452 13453 OMPClause *Sema::ActOnOpenMPUpdateClause(SourceLocation StartLoc, 13454 SourceLocation EndLoc) { 13455 return OMPUpdateClause::Create(Context, StartLoc, EndLoc); 13456 } 13457 13458 OMPClause *Sema::ActOnOpenMPCaptureClause(SourceLocation StartLoc, 13459 SourceLocation EndLoc) { 13460 return new (Context) OMPCaptureClause(StartLoc, EndLoc); 13461 } 13462 13463 OMPClause *Sema::ActOnOpenMPSeqCstClause(SourceLocation StartLoc, 13464 SourceLocation EndLoc) { 13465 return new (Context) OMPSeqCstClause(StartLoc, EndLoc); 13466 } 13467 13468 OMPClause *Sema::ActOnOpenMPAcqRelClause(SourceLocation StartLoc, 13469 SourceLocation EndLoc) { 13470 return new (Context) OMPAcqRelClause(StartLoc, EndLoc); 13471 } 13472 13473 OMPClause *Sema::ActOnOpenMPAcquireClause(SourceLocation StartLoc, 13474 SourceLocation EndLoc) { 13475 return new (Context) OMPAcquireClause(StartLoc, EndLoc); 13476 } 13477 13478 OMPClause *Sema::ActOnOpenMPReleaseClause(SourceLocation StartLoc, 13479 SourceLocation EndLoc) { 13480 return new (Context) OMPReleaseClause(StartLoc, EndLoc); 13481 } 13482 13483 OMPClause *Sema::ActOnOpenMPRelaxedClause(SourceLocation StartLoc, 13484 SourceLocation EndLoc) { 13485 return new (Context) OMPRelaxedClause(StartLoc, EndLoc); 13486 } 13487 13488 OMPClause *Sema::ActOnOpenMPThreadsClause(SourceLocation StartLoc, 13489 SourceLocation EndLoc) { 13490 return new (Context) OMPThreadsClause(StartLoc, EndLoc); 13491 } 13492 13493 OMPClause *Sema::ActOnOpenMPSIMDClause(SourceLocation StartLoc, 13494 SourceLocation EndLoc) { 13495 return new (Context) OMPSIMDClause(StartLoc, EndLoc); 13496 } 13497 13498 OMPClause *Sema::ActOnOpenMPNogroupClause(SourceLocation StartLoc, 13499 SourceLocation EndLoc) { 13500 return new (Context) OMPNogroupClause(StartLoc, EndLoc); 13501 } 13502 13503 OMPClause *Sema::ActOnOpenMPUnifiedAddressClause(SourceLocation StartLoc, 13504 SourceLocation EndLoc) { 13505 return new (Context) OMPUnifiedAddressClause(StartLoc, EndLoc); 13506 } 13507 13508 OMPClause *Sema::ActOnOpenMPUnifiedSharedMemoryClause(SourceLocation StartLoc, 13509 SourceLocation EndLoc) { 13510 return new (Context) OMPUnifiedSharedMemoryClause(StartLoc, EndLoc); 13511 } 13512 13513 OMPClause *Sema::ActOnOpenMPReverseOffloadClause(SourceLocation StartLoc, 13514 SourceLocation EndLoc) { 13515 return new (Context) OMPReverseOffloadClause(StartLoc, EndLoc); 13516 } 13517 13518 OMPClause *Sema::ActOnOpenMPDynamicAllocatorsClause(SourceLocation StartLoc, 13519 SourceLocation EndLoc) { 13520 return new (Context) OMPDynamicAllocatorsClause(StartLoc, EndLoc); 13521 } 13522 13523 OMPClause *Sema::ActOnOpenMPDestroyClause(SourceLocation StartLoc, 13524 SourceLocation EndLoc) { 13525 return new (Context) OMPDestroyClause(StartLoc, EndLoc); 13526 } 13527 13528 OMPClause *Sema::ActOnOpenMPVarListClause( 13529 OpenMPClauseKind Kind, ArrayRef<Expr *> VarList, Expr *DepModOrTailExpr, 13530 const OMPVarListLocTy &Locs, SourceLocation ColonLoc, 13531 CXXScopeSpec &ReductionOrMapperIdScopeSpec, 13532 DeclarationNameInfo &ReductionOrMapperId, int ExtraModifier, 13533 ArrayRef<OpenMPMapModifierKind> MapTypeModifiers, 13534 ArrayRef<SourceLocation> MapTypeModifiersLoc, bool IsMapTypeImplicit, 13535 SourceLocation ExtraModifierLoc) { 13536 SourceLocation StartLoc = Locs.StartLoc; 13537 SourceLocation LParenLoc = Locs.LParenLoc; 13538 SourceLocation EndLoc = Locs.EndLoc; 13539 OMPClause *Res = nullptr; 13540 switch (Kind) { 13541 case OMPC_private: 13542 Res = ActOnOpenMPPrivateClause(VarList, StartLoc, LParenLoc, EndLoc); 13543 break; 13544 case OMPC_firstprivate: 13545 Res = ActOnOpenMPFirstprivateClause(VarList, StartLoc, LParenLoc, EndLoc); 13546 break; 13547 case OMPC_lastprivate: 13548 assert(0 <= ExtraModifier && ExtraModifier <= OMPC_LASTPRIVATE_unknown && 13549 "Unexpected lastprivate modifier."); 13550 Res = ActOnOpenMPLastprivateClause( 13551 VarList, static_cast<OpenMPLastprivateModifier>(ExtraModifier), 13552 ExtraModifierLoc, ColonLoc, StartLoc, LParenLoc, EndLoc); 13553 break; 13554 case OMPC_shared: 13555 Res = ActOnOpenMPSharedClause(VarList, StartLoc, LParenLoc, EndLoc); 13556 break; 13557 case OMPC_reduction: 13558 assert(0 <= ExtraModifier && ExtraModifier <= OMPC_REDUCTION_unknown && 13559 "Unexpected lastprivate modifier."); 13560 Res = ActOnOpenMPReductionClause( 13561 VarList, static_cast<OpenMPReductionClauseModifier>(ExtraModifier), 13562 StartLoc, LParenLoc, ExtraModifierLoc, ColonLoc, EndLoc, 13563 ReductionOrMapperIdScopeSpec, ReductionOrMapperId); 13564 break; 13565 case OMPC_task_reduction: 13566 Res = ActOnOpenMPTaskReductionClause(VarList, StartLoc, LParenLoc, ColonLoc, 13567 EndLoc, ReductionOrMapperIdScopeSpec, 13568 ReductionOrMapperId); 13569 break; 13570 case OMPC_in_reduction: 13571 Res = ActOnOpenMPInReductionClause(VarList, StartLoc, LParenLoc, ColonLoc, 13572 EndLoc, ReductionOrMapperIdScopeSpec, 13573 ReductionOrMapperId); 13574 break; 13575 case OMPC_linear: 13576 assert(0 <= ExtraModifier && ExtraModifier <= OMPC_LINEAR_unknown && 13577 "Unexpected linear modifier."); 13578 Res = ActOnOpenMPLinearClause( 13579 VarList, DepModOrTailExpr, StartLoc, LParenLoc, 13580 static_cast<OpenMPLinearClauseKind>(ExtraModifier), ExtraModifierLoc, 13581 ColonLoc, EndLoc); 13582 break; 13583 case OMPC_aligned: 13584 Res = ActOnOpenMPAlignedClause(VarList, DepModOrTailExpr, StartLoc, 13585 LParenLoc, ColonLoc, EndLoc); 13586 break; 13587 case OMPC_copyin: 13588 Res = ActOnOpenMPCopyinClause(VarList, StartLoc, LParenLoc, EndLoc); 13589 break; 13590 case OMPC_copyprivate: 13591 Res = ActOnOpenMPCopyprivateClause(VarList, StartLoc, LParenLoc, EndLoc); 13592 break; 13593 case OMPC_flush: 13594 Res = ActOnOpenMPFlushClause(VarList, StartLoc, LParenLoc, EndLoc); 13595 break; 13596 case OMPC_depend: 13597 assert(0 <= ExtraModifier && ExtraModifier <= OMPC_DEPEND_unknown && 13598 "Unexpected depend modifier."); 13599 Res = ActOnOpenMPDependClause( 13600 DepModOrTailExpr, static_cast<OpenMPDependClauseKind>(ExtraModifier), 13601 ExtraModifierLoc, ColonLoc, VarList, StartLoc, LParenLoc, EndLoc); 13602 break; 13603 case OMPC_map: 13604 assert(0 <= ExtraModifier && ExtraModifier <= OMPC_MAP_unknown && 13605 "Unexpected map modifier."); 13606 Res = ActOnOpenMPMapClause( 13607 MapTypeModifiers, MapTypeModifiersLoc, ReductionOrMapperIdScopeSpec, 13608 ReductionOrMapperId, static_cast<OpenMPMapClauseKind>(ExtraModifier), 13609 IsMapTypeImplicit, ExtraModifierLoc, ColonLoc, VarList, Locs); 13610 break; 13611 case OMPC_to: 13612 Res = ActOnOpenMPToClause(VarList, ReductionOrMapperIdScopeSpec, 13613 ReductionOrMapperId, Locs); 13614 break; 13615 case OMPC_from: 13616 Res = ActOnOpenMPFromClause(VarList, ReductionOrMapperIdScopeSpec, 13617 ReductionOrMapperId, Locs); 13618 break; 13619 case OMPC_use_device_ptr: 13620 Res = ActOnOpenMPUseDevicePtrClause(VarList, Locs); 13621 break; 13622 case OMPC_use_device_addr: 13623 Res = ActOnOpenMPUseDeviceAddrClause(VarList, Locs); 13624 break; 13625 case OMPC_is_device_ptr: 13626 Res = ActOnOpenMPIsDevicePtrClause(VarList, Locs); 13627 break; 13628 case OMPC_allocate: 13629 Res = ActOnOpenMPAllocateClause(DepModOrTailExpr, VarList, StartLoc, 13630 LParenLoc, ColonLoc, EndLoc); 13631 break; 13632 case OMPC_nontemporal: 13633 Res = ActOnOpenMPNontemporalClause(VarList, StartLoc, LParenLoc, EndLoc); 13634 break; 13635 case OMPC_inclusive: 13636 Res = ActOnOpenMPInclusiveClause(VarList, StartLoc, LParenLoc, EndLoc); 13637 break; 13638 case OMPC_exclusive: 13639 Res = ActOnOpenMPExclusiveClause(VarList, StartLoc, LParenLoc, EndLoc); 13640 break; 13641 case OMPC_affinity: 13642 Res = ActOnOpenMPAffinityClause(StartLoc, LParenLoc, ColonLoc, EndLoc, 13643 DepModOrTailExpr, VarList); 13644 break; 13645 case OMPC_if: 13646 case OMPC_depobj: 13647 case OMPC_final: 13648 case OMPC_num_threads: 13649 case OMPC_safelen: 13650 case OMPC_simdlen: 13651 case OMPC_allocator: 13652 case OMPC_collapse: 13653 case OMPC_default: 13654 case OMPC_proc_bind: 13655 case OMPC_schedule: 13656 case OMPC_ordered: 13657 case OMPC_nowait: 13658 case OMPC_untied: 13659 case OMPC_mergeable: 13660 case OMPC_threadprivate: 13661 case OMPC_read: 13662 case OMPC_write: 13663 case OMPC_update: 13664 case OMPC_capture: 13665 case OMPC_seq_cst: 13666 case OMPC_acq_rel: 13667 case OMPC_acquire: 13668 case OMPC_release: 13669 case OMPC_relaxed: 13670 case OMPC_device: 13671 case OMPC_threads: 13672 case OMPC_simd: 13673 case OMPC_num_teams: 13674 case OMPC_thread_limit: 13675 case OMPC_priority: 13676 case OMPC_grainsize: 13677 case OMPC_nogroup: 13678 case OMPC_num_tasks: 13679 case OMPC_hint: 13680 case OMPC_dist_schedule: 13681 case OMPC_defaultmap: 13682 case OMPC_unknown: 13683 case OMPC_uniform: 13684 case OMPC_unified_address: 13685 case OMPC_unified_shared_memory: 13686 case OMPC_reverse_offload: 13687 case OMPC_dynamic_allocators: 13688 case OMPC_atomic_default_mem_order: 13689 case OMPC_device_type: 13690 case OMPC_match: 13691 case OMPC_order: 13692 case OMPC_destroy: 13693 case OMPC_detach: 13694 case OMPC_uses_allocators: 13695 default: 13696 llvm_unreachable("Clause is not allowed."); 13697 } 13698 return Res; 13699 } 13700 13701 ExprResult Sema::getOpenMPCapturedExpr(VarDecl *Capture, ExprValueKind VK, 13702 ExprObjectKind OK, SourceLocation Loc) { 13703 ExprResult Res = BuildDeclRefExpr( 13704 Capture, Capture->getType().getNonReferenceType(), VK_LValue, Loc); 13705 if (!Res.isUsable()) 13706 return ExprError(); 13707 if (OK == OK_Ordinary && !getLangOpts().CPlusPlus) { 13708 Res = CreateBuiltinUnaryOp(Loc, UO_Deref, Res.get()); 13709 if (!Res.isUsable()) 13710 return ExprError(); 13711 } 13712 if (VK != VK_LValue && Res.get()->isGLValue()) { 13713 Res = DefaultLvalueConversion(Res.get()); 13714 if (!Res.isUsable()) 13715 return ExprError(); 13716 } 13717 return Res; 13718 } 13719 13720 OMPClause *Sema::ActOnOpenMPPrivateClause(ArrayRef<Expr *> VarList, 13721 SourceLocation StartLoc, 13722 SourceLocation LParenLoc, 13723 SourceLocation EndLoc) { 13724 SmallVector<Expr *, 8> Vars; 13725 SmallVector<Expr *, 8> PrivateCopies; 13726 for (Expr *RefExpr : VarList) { 13727 assert(RefExpr && "NULL expr in OpenMP private clause."); 13728 SourceLocation ELoc; 13729 SourceRange ERange; 13730 Expr *SimpleRefExpr = RefExpr; 13731 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange); 13732 if (Res.second) { 13733 // It will be analyzed later. 13734 Vars.push_back(RefExpr); 13735 PrivateCopies.push_back(nullptr); 13736 } 13737 ValueDecl *D = Res.first; 13738 if (!D) 13739 continue; 13740 13741 QualType Type = D->getType(); 13742 auto *VD = dyn_cast<VarDecl>(D); 13743 13744 // OpenMP [2.9.3.3, Restrictions, C/C++, p.3] 13745 // A variable that appears in a private clause must not have an incomplete 13746 // type or a reference type. 13747 if (RequireCompleteType(ELoc, Type, diag::err_omp_private_incomplete_type)) 13748 continue; 13749 Type = Type.getNonReferenceType(); 13750 13751 // OpenMP 5.0 [2.19.3, List Item Privatization, Restrictions] 13752 // A variable that is privatized must not have a const-qualified type 13753 // unless it is of class type with a mutable member. This restriction does 13754 // not apply to the firstprivate clause. 13755 // 13756 // OpenMP 3.1 [2.9.3.3, private clause, Restrictions] 13757 // A variable that appears in a private clause must not have a 13758 // const-qualified type unless it is of class type with a mutable member. 13759 if (rejectConstNotMutableType(*this, D, Type, OMPC_private, ELoc)) 13760 continue; 13761 13762 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced 13763 // in a Construct] 13764 // Variables with the predetermined data-sharing attributes may not be 13765 // listed in data-sharing attributes clauses, except for the cases 13766 // listed below. For these exceptions only, listing a predetermined 13767 // variable in a data-sharing attribute clause is allowed and overrides 13768 // the variable's predetermined data-sharing attributes. 13769 DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, /*FromParent=*/false); 13770 if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_private) { 13771 Diag(ELoc, diag::err_omp_wrong_dsa) << getOpenMPClauseName(DVar.CKind) 13772 << getOpenMPClauseName(OMPC_private); 13773 reportOriginalDsa(*this, DSAStack, D, DVar); 13774 continue; 13775 } 13776 13777 OpenMPDirectiveKind CurrDir = DSAStack->getCurrentDirective(); 13778 // Variably modified types are not supported for tasks. 13779 if (!Type->isAnyPointerType() && Type->isVariablyModifiedType() && 13780 isOpenMPTaskingDirective(CurrDir)) { 13781 Diag(ELoc, diag::err_omp_variably_modified_type_not_supported) 13782 << getOpenMPClauseName(OMPC_private) << Type 13783 << getOpenMPDirectiveName(CurrDir); 13784 bool IsDecl = 13785 !VD || 13786 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly; 13787 Diag(D->getLocation(), 13788 IsDecl ? diag::note_previous_decl : diag::note_defined_here) 13789 << D; 13790 continue; 13791 } 13792 13793 // OpenMP 4.5 [2.15.5.1, Restrictions, p.3] 13794 // A list item cannot appear in both a map clause and a data-sharing 13795 // attribute clause on the same construct 13796 // 13797 // OpenMP 5.0 [2.19.7.1, Restrictions, p.7] 13798 // A list item cannot appear in both a map clause and a data-sharing 13799 // attribute clause on the same construct unless the construct is a 13800 // combined construct. 13801 if ((LangOpts.OpenMP <= 45 && isOpenMPTargetExecutionDirective(CurrDir)) || 13802 CurrDir == OMPD_target) { 13803 OpenMPClauseKind ConflictKind; 13804 if (DSAStack->checkMappableExprComponentListsForDecl( 13805 VD, /*CurrentRegionOnly=*/true, 13806 [&](OMPClauseMappableExprCommon::MappableExprComponentListRef, 13807 OpenMPClauseKind WhereFoundClauseKind) -> bool { 13808 ConflictKind = WhereFoundClauseKind; 13809 return true; 13810 })) { 13811 Diag(ELoc, diag::err_omp_variable_in_given_clause_and_dsa) 13812 << getOpenMPClauseName(OMPC_private) 13813 << getOpenMPClauseName(ConflictKind) 13814 << getOpenMPDirectiveName(CurrDir); 13815 reportOriginalDsa(*this, DSAStack, D, DVar); 13816 continue; 13817 } 13818 } 13819 13820 // OpenMP [2.9.3.3, Restrictions, C/C++, p.1] 13821 // A variable of class type (or array thereof) that appears in a private 13822 // clause requires an accessible, unambiguous default constructor for the 13823 // class type. 13824 // Generate helper private variable and initialize it with the default 13825 // value. The address of the original variable is replaced by the address of 13826 // the new private variable in CodeGen. This new variable is not added to 13827 // IdResolver, so the code in the OpenMP region uses original variable for 13828 // proper diagnostics. 13829 Type = Type.getUnqualifiedType(); 13830 VarDecl *VDPrivate = 13831 buildVarDecl(*this, ELoc, Type, D->getName(), 13832 D->hasAttrs() ? &D->getAttrs() : nullptr, 13833 VD ? cast<DeclRefExpr>(SimpleRefExpr) : nullptr); 13834 ActOnUninitializedDecl(VDPrivate); 13835 if (VDPrivate->isInvalidDecl()) 13836 continue; 13837 DeclRefExpr *VDPrivateRefExpr = buildDeclRefExpr( 13838 *this, VDPrivate, RefExpr->getType().getUnqualifiedType(), ELoc); 13839 13840 DeclRefExpr *Ref = nullptr; 13841 if (!VD && !CurContext->isDependentContext()) 13842 Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/false); 13843 DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_private, Ref); 13844 Vars.push_back((VD || CurContext->isDependentContext()) 13845 ? RefExpr->IgnoreParens() 13846 : Ref); 13847 PrivateCopies.push_back(VDPrivateRefExpr); 13848 } 13849 13850 if (Vars.empty()) 13851 return nullptr; 13852 13853 return OMPPrivateClause::Create(Context, StartLoc, LParenLoc, EndLoc, Vars, 13854 PrivateCopies); 13855 } 13856 13857 namespace { 13858 class DiagsUninitializedSeveretyRAII { 13859 private: 13860 DiagnosticsEngine &Diags; 13861 SourceLocation SavedLoc; 13862 bool IsIgnored = false; 13863 13864 public: 13865 DiagsUninitializedSeveretyRAII(DiagnosticsEngine &Diags, SourceLocation Loc, 13866 bool IsIgnored) 13867 : Diags(Diags), SavedLoc(Loc), IsIgnored(IsIgnored) { 13868 if (!IsIgnored) { 13869 Diags.setSeverity(/*Diag*/ diag::warn_uninit_self_reference_in_init, 13870 /*Map*/ diag::Severity::Ignored, Loc); 13871 } 13872 } 13873 ~DiagsUninitializedSeveretyRAII() { 13874 if (!IsIgnored) 13875 Diags.popMappings(SavedLoc); 13876 } 13877 }; 13878 } 13879 13880 OMPClause *Sema::ActOnOpenMPFirstprivateClause(ArrayRef<Expr *> VarList, 13881 SourceLocation StartLoc, 13882 SourceLocation LParenLoc, 13883 SourceLocation EndLoc) { 13884 SmallVector<Expr *, 8> Vars; 13885 SmallVector<Expr *, 8> PrivateCopies; 13886 SmallVector<Expr *, 8> Inits; 13887 SmallVector<Decl *, 4> ExprCaptures; 13888 bool IsImplicitClause = 13889 StartLoc.isInvalid() && LParenLoc.isInvalid() && EndLoc.isInvalid(); 13890 SourceLocation ImplicitClauseLoc = DSAStack->getConstructLoc(); 13891 13892 for (Expr *RefExpr : VarList) { 13893 assert(RefExpr && "NULL expr in OpenMP firstprivate clause."); 13894 SourceLocation ELoc; 13895 SourceRange ERange; 13896 Expr *SimpleRefExpr = RefExpr; 13897 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange); 13898 if (Res.second) { 13899 // It will be analyzed later. 13900 Vars.push_back(RefExpr); 13901 PrivateCopies.push_back(nullptr); 13902 Inits.push_back(nullptr); 13903 } 13904 ValueDecl *D = Res.first; 13905 if (!D) 13906 continue; 13907 13908 ELoc = IsImplicitClause ? ImplicitClauseLoc : ELoc; 13909 QualType Type = D->getType(); 13910 auto *VD = dyn_cast<VarDecl>(D); 13911 13912 // OpenMP [2.9.3.3, Restrictions, C/C++, p.3] 13913 // A variable that appears in a private clause must not have an incomplete 13914 // type or a reference type. 13915 if (RequireCompleteType(ELoc, Type, 13916 diag::err_omp_firstprivate_incomplete_type)) 13917 continue; 13918 Type = Type.getNonReferenceType(); 13919 13920 // OpenMP [2.9.3.4, Restrictions, C/C++, p.1] 13921 // A variable of class type (or array thereof) that appears in a private 13922 // clause requires an accessible, unambiguous copy constructor for the 13923 // class type. 13924 QualType ElemType = Context.getBaseElementType(Type).getNonReferenceType(); 13925 13926 // If an implicit firstprivate variable found it was checked already. 13927 DSAStackTy::DSAVarData TopDVar; 13928 if (!IsImplicitClause) { 13929 DSAStackTy::DSAVarData DVar = 13930 DSAStack->getTopDSA(D, /*FromParent=*/false); 13931 TopDVar = DVar; 13932 OpenMPDirectiveKind CurrDir = DSAStack->getCurrentDirective(); 13933 bool IsConstant = ElemType.isConstant(Context); 13934 // OpenMP [2.4.13, Data-sharing Attribute Clauses] 13935 // A list item that specifies a given variable may not appear in more 13936 // than one clause on the same directive, except that a variable may be 13937 // specified in both firstprivate and lastprivate clauses. 13938 // OpenMP 4.5 [2.10.8, Distribute Construct, p.3] 13939 // A list item may appear in a firstprivate or lastprivate clause but not 13940 // both. 13941 if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_firstprivate && 13942 (isOpenMPDistributeDirective(CurrDir) || 13943 DVar.CKind != OMPC_lastprivate) && 13944 DVar.RefExpr) { 13945 Diag(ELoc, diag::err_omp_wrong_dsa) 13946 << getOpenMPClauseName(DVar.CKind) 13947 << getOpenMPClauseName(OMPC_firstprivate); 13948 reportOriginalDsa(*this, DSAStack, D, DVar); 13949 continue; 13950 } 13951 13952 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced 13953 // in a Construct] 13954 // Variables with the predetermined data-sharing attributes may not be 13955 // listed in data-sharing attributes clauses, except for the cases 13956 // listed below. For these exceptions only, listing a predetermined 13957 // variable in a data-sharing attribute clause is allowed and overrides 13958 // the variable's predetermined data-sharing attributes. 13959 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced 13960 // in a Construct, C/C++, p.2] 13961 // Variables with const-qualified type having no mutable member may be 13962 // listed in a firstprivate clause, even if they are static data members. 13963 if (!(IsConstant || (VD && VD->isStaticDataMember())) && !DVar.RefExpr && 13964 DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_shared) { 13965 Diag(ELoc, diag::err_omp_wrong_dsa) 13966 << getOpenMPClauseName(DVar.CKind) 13967 << getOpenMPClauseName(OMPC_firstprivate); 13968 reportOriginalDsa(*this, DSAStack, D, DVar); 13969 continue; 13970 } 13971 13972 // OpenMP [2.9.3.4, Restrictions, p.2] 13973 // A list item that is private within a parallel region must not appear 13974 // in a firstprivate clause on a worksharing construct if any of the 13975 // worksharing regions arising from the worksharing construct ever bind 13976 // to any of the parallel regions arising from the parallel construct. 13977 // OpenMP 4.5 [2.15.3.4, Restrictions, p.3] 13978 // A list item that is private within a teams region must not appear in a 13979 // firstprivate clause on a distribute construct if any of the distribute 13980 // regions arising from the distribute construct ever bind to any of the 13981 // teams regions arising from the teams construct. 13982 // OpenMP 4.5 [2.15.3.4, Restrictions, p.3] 13983 // A list item that appears in a reduction clause of a teams construct 13984 // must not appear in a firstprivate clause on a distribute construct if 13985 // any of the distribute regions arising from the distribute construct 13986 // ever bind to any of the teams regions arising from the teams construct. 13987 if ((isOpenMPWorksharingDirective(CurrDir) || 13988 isOpenMPDistributeDirective(CurrDir)) && 13989 !isOpenMPParallelDirective(CurrDir) && 13990 !isOpenMPTeamsDirective(CurrDir)) { 13991 DVar = DSAStack->getImplicitDSA(D, true); 13992 if (DVar.CKind != OMPC_shared && 13993 (isOpenMPParallelDirective(DVar.DKind) || 13994 isOpenMPTeamsDirective(DVar.DKind) || 13995 DVar.DKind == OMPD_unknown)) { 13996 Diag(ELoc, diag::err_omp_required_access) 13997 << getOpenMPClauseName(OMPC_firstprivate) 13998 << getOpenMPClauseName(OMPC_shared); 13999 reportOriginalDsa(*this, DSAStack, D, DVar); 14000 continue; 14001 } 14002 } 14003 // OpenMP [2.9.3.4, Restrictions, p.3] 14004 // A list item that appears in a reduction clause of a parallel construct 14005 // must not appear in a firstprivate clause on a worksharing or task 14006 // construct if any of the worksharing or task regions arising from the 14007 // worksharing or task construct ever bind to any of the parallel regions 14008 // arising from the parallel construct. 14009 // OpenMP [2.9.3.4, Restrictions, p.4] 14010 // A list item that appears in a reduction clause in worksharing 14011 // construct must not appear in a firstprivate clause in a task construct 14012 // encountered during execution of any of the worksharing regions arising 14013 // from the worksharing construct. 14014 if (isOpenMPTaskingDirective(CurrDir)) { 14015 DVar = DSAStack->hasInnermostDSA( 14016 D, [](OpenMPClauseKind C) { return C == OMPC_reduction; }, 14017 [](OpenMPDirectiveKind K) { 14018 return isOpenMPParallelDirective(K) || 14019 isOpenMPWorksharingDirective(K) || 14020 isOpenMPTeamsDirective(K); 14021 }, 14022 /*FromParent=*/true); 14023 if (DVar.CKind == OMPC_reduction && 14024 (isOpenMPParallelDirective(DVar.DKind) || 14025 isOpenMPWorksharingDirective(DVar.DKind) || 14026 isOpenMPTeamsDirective(DVar.DKind))) { 14027 Diag(ELoc, diag::err_omp_parallel_reduction_in_task_firstprivate) 14028 << getOpenMPDirectiveName(DVar.DKind); 14029 reportOriginalDsa(*this, DSAStack, D, DVar); 14030 continue; 14031 } 14032 } 14033 14034 // OpenMP 4.5 [2.15.5.1, Restrictions, p.3] 14035 // A list item cannot appear in both a map clause and a data-sharing 14036 // attribute clause on the same construct 14037 // 14038 // OpenMP 5.0 [2.19.7.1, Restrictions, p.7] 14039 // A list item cannot appear in both a map clause and a data-sharing 14040 // attribute clause on the same construct unless the construct is a 14041 // combined construct. 14042 if ((LangOpts.OpenMP <= 45 && 14043 isOpenMPTargetExecutionDirective(CurrDir)) || 14044 CurrDir == OMPD_target) { 14045 OpenMPClauseKind ConflictKind; 14046 if (DSAStack->checkMappableExprComponentListsForDecl( 14047 VD, /*CurrentRegionOnly=*/true, 14048 [&ConflictKind]( 14049 OMPClauseMappableExprCommon::MappableExprComponentListRef, 14050 OpenMPClauseKind WhereFoundClauseKind) { 14051 ConflictKind = WhereFoundClauseKind; 14052 return true; 14053 })) { 14054 Diag(ELoc, diag::err_omp_variable_in_given_clause_and_dsa) 14055 << getOpenMPClauseName(OMPC_firstprivate) 14056 << getOpenMPClauseName(ConflictKind) 14057 << getOpenMPDirectiveName(DSAStack->getCurrentDirective()); 14058 reportOriginalDsa(*this, DSAStack, D, DVar); 14059 continue; 14060 } 14061 } 14062 } 14063 14064 // Variably modified types are not supported for tasks. 14065 if (!Type->isAnyPointerType() && Type->isVariablyModifiedType() && 14066 isOpenMPTaskingDirective(DSAStack->getCurrentDirective())) { 14067 Diag(ELoc, diag::err_omp_variably_modified_type_not_supported) 14068 << getOpenMPClauseName(OMPC_firstprivate) << Type 14069 << getOpenMPDirectiveName(DSAStack->getCurrentDirective()); 14070 bool IsDecl = 14071 !VD || 14072 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly; 14073 Diag(D->getLocation(), 14074 IsDecl ? diag::note_previous_decl : diag::note_defined_here) 14075 << D; 14076 continue; 14077 } 14078 14079 Type = Type.getUnqualifiedType(); 14080 VarDecl *VDPrivate = 14081 buildVarDecl(*this, ELoc, Type, D->getName(), 14082 D->hasAttrs() ? &D->getAttrs() : nullptr, 14083 VD ? cast<DeclRefExpr>(SimpleRefExpr) : nullptr); 14084 // Generate helper private variable and initialize it with the value of the 14085 // original variable. The address of the original variable is replaced by 14086 // the address of the new private variable in the CodeGen. This new variable 14087 // is not added to IdResolver, so the code in the OpenMP region uses 14088 // original variable for proper diagnostics and variable capturing. 14089 Expr *VDInitRefExpr = nullptr; 14090 // For arrays generate initializer for single element and replace it by the 14091 // original array element in CodeGen. 14092 if (Type->isArrayType()) { 14093 VarDecl *VDInit = 14094 buildVarDecl(*this, RefExpr->getExprLoc(), ElemType, D->getName()); 14095 VDInitRefExpr = buildDeclRefExpr(*this, VDInit, ElemType, ELoc); 14096 Expr *Init = DefaultLvalueConversion(VDInitRefExpr).get(); 14097 ElemType = ElemType.getUnqualifiedType(); 14098 VarDecl *VDInitTemp = buildVarDecl(*this, RefExpr->getExprLoc(), ElemType, 14099 ".firstprivate.temp"); 14100 InitializedEntity Entity = 14101 InitializedEntity::InitializeVariable(VDInitTemp); 14102 InitializationKind Kind = InitializationKind::CreateCopy(ELoc, ELoc); 14103 14104 InitializationSequence InitSeq(*this, Entity, Kind, Init); 14105 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Init); 14106 if (Result.isInvalid()) 14107 VDPrivate->setInvalidDecl(); 14108 else 14109 VDPrivate->setInit(Result.getAs<Expr>()); 14110 // Remove temp variable declaration. 14111 Context.Deallocate(VDInitTemp); 14112 } else { 14113 VarDecl *VDInit = buildVarDecl(*this, RefExpr->getExprLoc(), Type, 14114 ".firstprivate.temp"); 14115 VDInitRefExpr = buildDeclRefExpr(*this, VDInit, RefExpr->getType(), 14116 RefExpr->getExprLoc()); 14117 AddInitializerToDecl(VDPrivate, 14118 DefaultLvalueConversion(VDInitRefExpr).get(), 14119 /*DirectInit=*/false); 14120 } 14121 if (VDPrivate->isInvalidDecl()) { 14122 if (IsImplicitClause) { 14123 Diag(RefExpr->getExprLoc(), 14124 diag::note_omp_task_predetermined_firstprivate_here); 14125 } 14126 continue; 14127 } 14128 CurContext->addDecl(VDPrivate); 14129 DeclRefExpr *VDPrivateRefExpr = buildDeclRefExpr( 14130 *this, VDPrivate, RefExpr->getType().getUnqualifiedType(), 14131 RefExpr->getExprLoc()); 14132 DeclRefExpr *Ref = nullptr; 14133 if (!VD && !CurContext->isDependentContext()) { 14134 if (TopDVar.CKind == OMPC_lastprivate) { 14135 Ref = TopDVar.PrivateCopy; 14136 } else { 14137 Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/true); 14138 if (!isOpenMPCapturedDecl(D)) 14139 ExprCaptures.push_back(Ref->getDecl()); 14140 } 14141 } 14142 if (!IsImplicitClause) 14143 DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_firstprivate, Ref); 14144 Vars.push_back((VD || CurContext->isDependentContext()) 14145 ? RefExpr->IgnoreParens() 14146 : Ref); 14147 PrivateCopies.push_back(VDPrivateRefExpr); 14148 Inits.push_back(VDInitRefExpr); 14149 } 14150 14151 if (Vars.empty()) 14152 return nullptr; 14153 14154 return OMPFirstprivateClause::Create(Context, StartLoc, LParenLoc, EndLoc, 14155 Vars, PrivateCopies, Inits, 14156 buildPreInits(Context, ExprCaptures)); 14157 } 14158 14159 OMPClause *Sema::ActOnOpenMPLastprivateClause( 14160 ArrayRef<Expr *> VarList, OpenMPLastprivateModifier LPKind, 14161 SourceLocation LPKindLoc, SourceLocation ColonLoc, SourceLocation StartLoc, 14162 SourceLocation LParenLoc, SourceLocation EndLoc) { 14163 if (LPKind == OMPC_LASTPRIVATE_unknown && LPKindLoc.isValid()) { 14164 assert(ColonLoc.isValid() && "Colon location must be valid."); 14165 Diag(LPKindLoc, diag::err_omp_unexpected_clause_value) 14166 << getListOfPossibleValues(OMPC_lastprivate, /*First=*/0, 14167 /*Last=*/OMPC_LASTPRIVATE_unknown) 14168 << getOpenMPClauseName(OMPC_lastprivate); 14169 return nullptr; 14170 } 14171 14172 SmallVector<Expr *, 8> Vars; 14173 SmallVector<Expr *, 8> SrcExprs; 14174 SmallVector<Expr *, 8> DstExprs; 14175 SmallVector<Expr *, 8> AssignmentOps; 14176 SmallVector<Decl *, 4> ExprCaptures; 14177 SmallVector<Expr *, 4> ExprPostUpdates; 14178 for (Expr *RefExpr : VarList) { 14179 assert(RefExpr && "NULL expr in OpenMP lastprivate clause."); 14180 SourceLocation ELoc; 14181 SourceRange ERange; 14182 Expr *SimpleRefExpr = RefExpr; 14183 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange); 14184 if (Res.second) { 14185 // It will be analyzed later. 14186 Vars.push_back(RefExpr); 14187 SrcExprs.push_back(nullptr); 14188 DstExprs.push_back(nullptr); 14189 AssignmentOps.push_back(nullptr); 14190 } 14191 ValueDecl *D = Res.first; 14192 if (!D) 14193 continue; 14194 14195 QualType Type = D->getType(); 14196 auto *VD = dyn_cast<VarDecl>(D); 14197 14198 // OpenMP [2.14.3.5, Restrictions, C/C++, p.2] 14199 // A variable that appears in a lastprivate clause must not have an 14200 // incomplete type or a reference type. 14201 if (RequireCompleteType(ELoc, Type, 14202 diag::err_omp_lastprivate_incomplete_type)) 14203 continue; 14204 Type = Type.getNonReferenceType(); 14205 14206 // OpenMP 5.0 [2.19.3, List Item Privatization, Restrictions] 14207 // A variable that is privatized must not have a const-qualified type 14208 // unless it is of class type with a mutable member. This restriction does 14209 // not apply to the firstprivate clause. 14210 // 14211 // OpenMP 3.1 [2.9.3.5, lastprivate clause, Restrictions] 14212 // A variable that appears in a lastprivate clause must not have a 14213 // const-qualified type unless it is of class type with a mutable member. 14214 if (rejectConstNotMutableType(*this, D, Type, OMPC_lastprivate, ELoc)) 14215 continue; 14216 14217 // OpenMP 5.0 [2.19.4.5 lastprivate Clause, Restrictions] 14218 // A list item that appears in a lastprivate clause with the conditional 14219 // modifier must be a scalar variable. 14220 if (LPKind == OMPC_LASTPRIVATE_conditional && !Type->isScalarType()) { 14221 Diag(ELoc, diag::err_omp_lastprivate_conditional_non_scalar); 14222 bool IsDecl = !VD || VD->isThisDeclarationADefinition(Context) == 14223 VarDecl::DeclarationOnly; 14224 Diag(D->getLocation(), 14225 IsDecl ? diag::note_previous_decl : diag::note_defined_here) 14226 << D; 14227 continue; 14228 } 14229 14230 OpenMPDirectiveKind CurrDir = DSAStack->getCurrentDirective(); 14231 // OpenMP [2.14.1.1, Data-sharing Attribute Rules for Variables Referenced 14232 // in a Construct] 14233 // Variables with the predetermined data-sharing attributes may not be 14234 // listed in data-sharing attributes clauses, except for the cases 14235 // listed below. 14236 // OpenMP 4.5 [2.10.8, Distribute Construct, p.3] 14237 // A list item may appear in a firstprivate or lastprivate clause but not 14238 // both. 14239 DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, /*FromParent=*/false); 14240 if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_lastprivate && 14241 (isOpenMPDistributeDirective(CurrDir) || 14242 DVar.CKind != OMPC_firstprivate) && 14243 (DVar.CKind != OMPC_private || DVar.RefExpr != nullptr)) { 14244 Diag(ELoc, diag::err_omp_wrong_dsa) 14245 << getOpenMPClauseName(DVar.CKind) 14246 << getOpenMPClauseName(OMPC_lastprivate); 14247 reportOriginalDsa(*this, DSAStack, D, DVar); 14248 continue; 14249 } 14250 14251 // OpenMP [2.14.3.5, Restrictions, p.2] 14252 // A list item that is private within a parallel region, or that appears in 14253 // the reduction clause of a parallel construct, must not appear in a 14254 // lastprivate clause on a worksharing construct if any of the corresponding 14255 // worksharing regions ever binds to any of the corresponding parallel 14256 // regions. 14257 DSAStackTy::DSAVarData TopDVar = DVar; 14258 if (isOpenMPWorksharingDirective(CurrDir) && 14259 !isOpenMPParallelDirective(CurrDir) && 14260 !isOpenMPTeamsDirective(CurrDir)) { 14261 DVar = DSAStack->getImplicitDSA(D, true); 14262 if (DVar.CKind != OMPC_shared) { 14263 Diag(ELoc, diag::err_omp_required_access) 14264 << getOpenMPClauseName(OMPC_lastprivate) 14265 << getOpenMPClauseName(OMPC_shared); 14266 reportOriginalDsa(*this, DSAStack, D, DVar); 14267 continue; 14268 } 14269 } 14270 14271 // OpenMP [2.14.3.5, Restrictions, C++, p.1,2] 14272 // A variable of class type (or array thereof) that appears in a 14273 // lastprivate clause requires an accessible, unambiguous default 14274 // constructor for the class type, unless the list item is also specified 14275 // in a firstprivate clause. 14276 // A variable of class type (or array thereof) that appears in a 14277 // lastprivate clause requires an accessible, unambiguous copy assignment 14278 // operator for the class type. 14279 Type = Context.getBaseElementType(Type).getNonReferenceType(); 14280 VarDecl *SrcVD = buildVarDecl(*this, ERange.getBegin(), 14281 Type.getUnqualifiedType(), ".lastprivate.src", 14282 D->hasAttrs() ? &D->getAttrs() : nullptr); 14283 DeclRefExpr *PseudoSrcExpr = 14284 buildDeclRefExpr(*this, SrcVD, Type.getUnqualifiedType(), ELoc); 14285 VarDecl *DstVD = 14286 buildVarDecl(*this, ERange.getBegin(), Type, ".lastprivate.dst", 14287 D->hasAttrs() ? &D->getAttrs() : nullptr); 14288 DeclRefExpr *PseudoDstExpr = buildDeclRefExpr(*this, DstVD, Type, ELoc); 14289 // For arrays generate assignment operation for single element and replace 14290 // it by the original array element in CodeGen. 14291 ExprResult AssignmentOp = BuildBinOp(/*S=*/nullptr, ELoc, BO_Assign, 14292 PseudoDstExpr, PseudoSrcExpr); 14293 if (AssignmentOp.isInvalid()) 14294 continue; 14295 AssignmentOp = 14296 ActOnFinishFullExpr(AssignmentOp.get(), ELoc, /*DiscardedValue*/ false); 14297 if (AssignmentOp.isInvalid()) 14298 continue; 14299 14300 DeclRefExpr *Ref = nullptr; 14301 if (!VD && !CurContext->isDependentContext()) { 14302 if (TopDVar.CKind == OMPC_firstprivate) { 14303 Ref = TopDVar.PrivateCopy; 14304 } else { 14305 Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/false); 14306 if (!isOpenMPCapturedDecl(D)) 14307 ExprCaptures.push_back(Ref->getDecl()); 14308 } 14309 if (TopDVar.CKind == OMPC_firstprivate || 14310 (!isOpenMPCapturedDecl(D) && 14311 Ref->getDecl()->hasAttr<OMPCaptureNoInitAttr>())) { 14312 ExprResult RefRes = DefaultLvalueConversion(Ref); 14313 if (!RefRes.isUsable()) 14314 continue; 14315 ExprResult PostUpdateRes = 14316 BuildBinOp(DSAStack->getCurScope(), ELoc, BO_Assign, SimpleRefExpr, 14317 RefRes.get()); 14318 if (!PostUpdateRes.isUsable()) 14319 continue; 14320 ExprPostUpdates.push_back( 14321 IgnoredValueConversions(PostUpdateRes.get()).get()); 14322 } 14323 } 14324 DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_lastprivate, Ref); 14325 Vars.push_back((VD || CurContext->isDependentContext()) 14326 ? RefExpr->IgnoreParens() 14327 : Ref); 14328 SrcExprs.push_back(PseudoSrcExpr); 14329 DstExprs.push_back(PseudoDstExpr); 14330 AssignmentOps.push_back(AssignmentOp.get()); 14331 } 14332 14333 if (Vars.empty()) 14334 return nullptr; 14335 14336 return OMPLastprivateClause::Create(Context, StartLoc, LParenLoc, EndLoc, 14337 Vars, SrcExprs, DstExprs, AssignmentOps, 14338 LPKind, LPKindLoc, ColonLoc, 14339 buildPreInits(Context, ExprCaptures), 14340 buildPostUpdate(*this, ExprPostUpdates)); 14341 } 14342 14343 OMPClause *Sema::ActOnOpenMPSharedClause(ArrayRef<Expr *> VarList, 14344 SourceLocation StartLoc, 14345 SourceLocation LParenLoc, 14346 SourceLocation EndLoc) { 14347 SmallVector<Expr *, 8> Vars; 14348 for (Expr *RefExpr : VarList) { 14349 assert(RefExpr && "NULL expr in OpenMP lastprivate clause."); 14350 SourceLocation ELoc; 14351 SourceRange ERange; 14352 Expr *SimpleRefExpr = RefExpr; 14353 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange); 14354 if (Res.second) { 14355 // It will be analyzed later. 14356 Vars.push_back(RefExpr); 14357 } 14358 ValueDecl *D = Res.first; 14359 if (!D) 14360 continue; 14361 14362 auto *VD = dyn_cast<VarDecl>(D); 14363 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced 14364 // in a Construct] 14365 // Variables with the predetermined data-sharing attributes may not be 14366 // listed in data-sharing attributes clauses, except for the cases 14367 // listed below. For these exceptions only, listing a predetermined 14368 // variable in a data-sharing attribute clause is allowed and overrides 14369 // the variable's predetermined data-sharing attributes. 14370 DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, /*FromParent=*/false); 14371 if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_shared && 14372 DVar.RefExpr) { 14373 Diag(ELoc, diag::err_omp_wrong_dsa) << getOpenMPClauseName(DVar.CKind) 14374 << getOpenMPClauseName(OMPC_shared); 14375 reportOriginalDsa(*this, DSAStack, D, DVar); 14376 continue; 14377 } 14378 14379 DeclRefExpr *Ref = nullptr; 14380 if (!VD && isOpenMPCapturedDecl(D) && !CurContext->isDependentContext()) 14381 Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/true); 14382 DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_shared, Ref); 14383 Vars.push_back((VD || !Ref || CurContext->isDependentContext()) 14384 ? RefExpr->IgnoreParens() 14385 : Ref); 14386 } 14387 14388 if (Vars.empty()) 14389 return nullptr; 14390 14391 return OMPSharedClause::Create(Context, StartLoc, LParenLoc, EndLoc, Vars); 14392 } 14393 14394 namespace { 14395 class DSARefChecker : public StmtVisitor<DSARefChecker, bool> { 14396 DSAStackTy *Stack; 14397 14398 public: 14399 bool VisitDeclRefExpr(DeclRefExpr *E) { 14400 if (auto *VD = dyn_cast<VarDecl>(E->getDecl())) { 14401 DSAStackTy::DSAVarData DVar = Stack->getTopDSA(VD, /*FromParent=*/false); 14402 if (DVar.CKind == OMPC_shared && !DVar.RefExpr) 14403 return false; 14404 if (DVar.CKind != OMPC_unknown) 14405 return true; 14406 DSAStackTy::DSAVarData DVarPrivate = Stack->hasDSA( 14407 VD, isOpenMPPrivate, [](OpenMPDirectiveKind) { return true; }, 14408 /*FromParent=*/true); 14409 return DVarPrivate.CKind != OMPC_unknown; 14410 } 14411 return false; 14412 } 14413 bool VisitStmt(Stmt *S) { 14414 for (Stmt *Child : S->children()) { 14415 if (Child && Visit(Child)) 14416 return true; 14417 } 14418 return false; 14419 } 14420 explicit DSARefChecker(DSAStackTy *S) : Stack(S) {} 14421 }; 14422 } // namespace 14423 14424 namespace { 14425 // Transform MemberExpression for specified FieldDecl of current class to 14426 // DeclRefExpr to specified OMPCapturedExprDecl. 14427 class TransformExprToCaptures : public TreeTransform<TransformExprToCaptures> { 14428 typedef TreeTransform<TransformExprToCaptures> BaseTransform; 14429 ValueDecl *Field = nullptr; 14430 DeclRefExpr *CapturedExpr = nullptr; 14431 14432 public: 14433 TransformExprToCaptures(Sema &SemaRef, ValueDecl *FieldDecl) 14434 : BaseTransform(SemaRef), Field(FieldDecl), CapturedExpr(nullptr) {} 14435 14436 ExprResult TransformMemberExpr(MemberExpr *E) { 14437 if (isa<CXXThisExpr>(E->getBase()->IgnoreParenImpCasts()) && 14438 E->getMemberDecl() == Field) { 14439 CapturedExpr = buildCapture(SemaRef, Field, E, /*WithInit=*/false); 14440 return CapturedExpr; 14441 } 14442 return BaseTransform::TransformMemberExpr(E); 14443 } 14444 DeclRefExpr *getCapturedExpr() { return CapturedExpr; } 14445 }; 14446 } // namespace 14447 14448 template <typename T, typename U> 14449 static T filterLookupForUDReductionAndMapper( 14450 SmallVectorImpl<U> &Lookups, const llvm::function_ref<T(ValueDecl *)> Gen) { 14451 for (U &Set : Lookups) { 14452 for (auto *D : Set) { 14453 if (T Res = Gen(cast<ValueDecl>(D))) 14454 return Res; 14455 } 14456 } 14457 return T(); 14458 } 14459 14460 static NamedDecl *findAcceptableDecl(Sema &SemaRef, NamedDecl *D) { 14461 assert(!LookupResult::isVisible(SemaRef, D) && "not in slow case"); 14462 14463 for (auto RD : D->redecls()) { 14464 // Don't bother with extra checks if we already know this one isn't visible. 14465 if (RD == D) 14466 continue; 14467 14468 auto ND = cast<NamedDecl>(RD); 14469 if (LookupResult::isVisible(SemaRef, ND)) 14470 return ND; 14471 } 14472 14473 return nullptr; 14474 } 14475 14476 static void 14477 argumentDependentLookup(Sema &SemaRef, const DeclarationNameInfo &Id, 14478 SourceLocation Loc, QualType Ty, 14479 SmallVectorImpl<UnresolvedSet<8>> &Lookups) { 14480 // Find all of the associated namespaces and classes based on the 14481 // arguments we have. 14482 Sema::AssociatedNamespaceSet AssociatedNamespaces; 14483 Sema::AssociatedClassSet AssociatedClasses; 14484 OpaqueValueExpr OVE(Loc, Ty, VK_LValue); 14485 SemaRef.FindAssociatedClassesAndNamespaces(Loc, &OVE, AssociatedNamespaces, 14486 AssociatedClasses); 14487 14488 // C++ [basic.lookup.argdep]p3: 14489 // Let X be the lookup set produced by unqualified lookup (3.4.1) 14490 // and let Y be the lookup set produced by argument dependent 14491 // lookup (defined as follows). If X contains [...] then Y is 14492 // empty. Otherwise Y is the set of declarations found in the 14493 // namespaces associated with the argument types as described 14494 // below. The set of declarations found by the lookup of the name 14495 // is the union of X and Y. 14496 // 14497 // Here, we compute Y and add its members to the overloaded 14498 // candidate set. 14499 for (auto *NS : AssociatedNamespaces) { 14500 // When considering an associated namespace, the lookup is the 14501 // same as the lookup performed when the associated namespace is 14502 // used as a qualifier (3.4.3.2) except that: 14503 // 14504 // -- Any using-directives in the associated namespace are 14505 // ignored. 14506 // 14507 // -- Any namespace-scope friend functions declared in 14508 // associated classes are visible within their respective 14509 // namespaces even if they are not visible during an ordinary 14510 // lookup (11.4). 14511 DeclContext::lookup_result R = NS->lookup(Id.getName()); 14512 for (auto *D : R) { 14513 auto *Underlying = D; 14514 if (auto *USD = dyn_cast<UsingShadowDecl>(D)) 14515 Underlying = USD->getTargetDecl(); 14516 14517 if (!isa<OMPDeclareReductionDecl>(Underlying) && 14518 !isa<OMPDeclareMapperDecl>(Underlying)) 14519 continue; 14520 14521 if (!SemaRef.isVisible(D)) { 14522 D = findAcceptableDecl(SemaRef, D); 14523 if (!D) 14524 continue; 14525 if (auto *USD = dyn_cast<UsingShadowDecl>(D)) 14526 Underlying = USD->getTargetDecl(); 14527 } 14528 Lookups.emplace_back(); 14529 Lookups.back().addDecl(Underlying); 14530 } 14531 } 14532 } 14533 14534 static ExprResult 14535 buildDeclareReductionRef(Sema &SemaRef, SourceLocation Loc, SourceRange Range, 14536 Scope *S, CXXScopeSpec &ReductionIdScopeSpec, 14537 const DeclarationNameInfo &ReductionId, QualType Ty, 14538 CXXCastPath &BasePath, Expr *UnresolvedReduction) { 14539 if (ReductionIdScopeSpec.isInvalid()) 14540 return ExprError(); 14541 SmallVector<UnresolvedSet<8>, 4> Lookups; 14542 if (S) { 14543 LookupResult Lookup(SemaRef, ReductionId, Sema::LookupOMPReductionName); 14544 Lookup.suppressDiagnostics(); 14545 while (S && SemaRef.LookupParsedName(Lookup, S, &ReductionIdScopeSpec)) { 14546 NamedDecl *D = Lookup.getRepresentativeDecl(); 14547 do { 14548 S = S->getParent(); 14549 } while (S && !S->isDeclScope(D)); 14550 if (S) 14551 S = S->getParent(); 14552 Lookups.emplace_back(); 14553 Lookups.back().append(Lookup.begin(), Lookup.end()); 14554 Lookup.clear(); 14555 } 14556 } else if (auto *ULE = 14557 cast_or_null<UnresolvedLookupExpr>(UnresolvedReduction)) { 14558 Lookups.push_back(UnresolvedSet<8>()); 14559 Decl *PrevD = nullptr; 14560 for (NamedDecl *D : ULE->decls()) { 14561 if (D == PrevD) 14562 Lookups.push_back(UnresolvedSet<8>()); 14563 else if (auto *DRD = dyn_cast<OMPDeclareReductionDecl>(D)) 14564 Lookups.back().addDecl(DRD); 14565 PrevD = D; 14566 } 14567 } 14568 if (SemaRef.CurContext->isDependentContext() || Ty->isDependentType() || 14569 Ty->isInstantiationDependentType() || 14570 Ty->containsUnexpandedParameterPack() || 14571 filterLookupForUDReductionAndMapper<bool>(Lookups, [](ValueDecl *D) { 14572 return !D->isInvalidDecl() && 14573 (D->getType()->isDependentType() || 14574 D->getType()->isInstantiationDependentType() || 14575 D->getType()->containsUnexpandedParameterPack()); 14576 })) { 14577 UnresolvedSet<8> ResSet; 14578 for (const UnresolvedSet<8> &Set : Lookups) { 14579 if (Set.empty()) 14580 continue; 14581 ResSet.append(Set.begin(), Set.end()); 14582 // The last item marks the end of all declarations at the specified scope. 14583 ResSet.addDecl(Set[Set.size() - 1]); 14584 } 14585 return UnresolvedLookupExpr::Create( 14586 SemaRef.Context, /*NamingClass=*/nullptr, 14587 ReductionIdScopeSpec.getWithLocInContext(SemaRef.Context), ReductionId, 14588 /*ADL=*/true, /*Overloaded=*/true, ResSet.begin(), ResSet.end()); 14589 } 14590 // Lookup inside the classes. 14591 // C++ [over.match.oper]p3: 14592 // For a unary operator @ with an operand of a type whose 14593 // cv-unqualified version is T1, and for a binary operator @ with 14594 // a left operand of a type whose cv-unqualified version is T1 and 14595 // a right operand of a type whose cv-unqualified version is T2, 14596 // three sets of candidate functions, designated member 14597 // candidates, non-member candidates and built-in candidates, are 14598 // constructed as follows: 14599 // -- If T1 is a complete class type or a class currently being 14600 // defined, the set of member candidates is the result of the 14601 // qualified lookup of T1::operator@ (13.3.1.1.1); otherwise, 14602 // the set of member candidates is empty. 14603 LookupResult Lookup(SemaRef, ReductionId, Sema::LookupOMPReductionName); 14604 Lookup.suppressDiagnostics(); 14605 if (const auto *TyRec = Ty->getAs<RecordType>()) { 14606 // Complete the type if it can be completed. 14607 // If the type is neither complete nor being defined, bail out now. 14608 if (SemaRef.isCompleteType(Loc, Ty) || TyRec->isBeingDefined() || 14609 TyRec->getDecl()->getDefinition()) { 14610 Lookup.clear(); 14611 SemaRef.LookupQualifiedName(Lookup, TyRec->getDecl()); 14612 if (Lookup.empty()) { 14613 Lookups.emplace_back(); 14614 Lookups.back().append(Lookup.begin(), Lookup.end()); 14615 } 14616 } 14617 } 14618 // Perform ADL. 14619 if (SemaRef.getLangOpts().CPlusPlus) 14620 argumentDependentLookup(SemaRef, ReductionId, Loc, Ty, Lookups); 14621 if (auto *VD = filterLookupForUDReductionAndMapper<ValueDecl *>( 14622 Lookups, [&SemaRef, Ty](ValueDecl *D) -> ValueDecl * { 14623 if (!D->isInvalidDecl() && 14624 SemaRef.Context.hasSameType(D->getType(), Ty)) 14625 return D; 14626 return nullptr; 14627 })) 14628 return SemaRef.BuildDeclRefExpr(VD, VD->getType().getNonReferenceType(), 14629 VK_LValue, Loc); 14630 if (SemaRef.getLangOpts().CPlusPlus) { 14631 if (auto *VD = filterLookupForUDReductionAndMapper<ValueDecl *>( 14632 Lookups, [&SemaRef, Ty, Loc](ValueDecl *D) -> ValueDecl * { 14633 if (!D->isInvalidDecl() && 14634 SemaRef.IsDerivedFrom(Loc, Ty, D->getType()) && 14635 !Ty.isMoreQualifiedThan(D->getType())) 14636 return D; 14637 return nullptr; 14638 })) { 14639 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true, 14640 /*DetectVirtual=*/false); 14641 if (SemaRef.IsDerivedFrom(Loc, Ty, VD->getType(), Paths)) { 14642 if (!Paths.isAmbiguous(SemaRef.Context.getCanonicalType( 14643 VD->getType().getUnqualifiedType()))) { 14644 if (SemaRef.CheckBaseClassAccess( 14645 Loc, VD->getType(), Ty, Paths.front(), 14646 /*DiagID=*/0) != Sema::AR_inaccessible) { 14647 SemaRef.BuildBasePathArray(Paths, BasePath); 14648 return SemaRef.BuildDeclRefExpr( 14649 VD, VD->getType().getNonReferenceType(), VK_LValue, Loc); 14650 } 14651 } 14652 } 14653 } 14654 } 14655 if (ReductionIdScopeSpec.isSet()) { 14656 SemaRef.Diag(Loc, diag::err_omp_not_resolved_reduction_identifier) 14657 << Ty << Range; 14658 return ExprError(); 14659 } 14660 return ExprEmpty(); 14661 } 14662 14663 namespace { 14664 /// Data for the reduction-based clauses. 14665 struct ReductionData { 14666 /// List of original reduction items. 14667 SmallVector<Expr *, 8> Vars; 14668 /// List of private copies of the reduction items. 14669 SmallVector<Expr *, 8> Privates; 14670 /// LHS expressions for the reduction_op expressions. 14671 SmallVector<Expr *, 8> LHSs; 14672 /// RHS expressions for the reduction_op expressions. 14673 SmallVector<Expr *, 8> RHSs; 14674 /// Reduction operation expression. 14675 SmallVector<Expr *, 8> ReductionOps; 14676 /// inscan copy operation expressions. 14677 SmallVector<Expr *, 8> InscanCopyOps; 14678 /// inscan copy temp array expressions for prefix sums. 14679 SmallVector<Expr *, 8> InscanCopyArrayTemps; 14680 /// inscan copy temp array element expressions for prefix sums. 14681 SmallVector<Expr *, 8> InscanCopyArrayElems; 14682 /// Taskgroup descriptors for the corresponding reduction items in 14683 /// in_reduction clauses. 14684 SmallVector<Expr *, 8> TaskgroupDescriptors; 14685 /// List of captures for clause. 14686 SmallVector<Decl *, 4> ExprCaptures; 14687 /// List of postupdate expressions. 14688 SmallVector<Expr *, 4> ExprPostUpdates; 14689 /// Reduction modifier. 14690 unsigned RedModifier = 0; 14691 ReductionData() = delete; 14692 /// Reserves required memory for the reduction data. 14693 ReductionData(unsigned Size, unsigned Modifier = 0) : RedModifier(Modifier) { 14694 Vars.reserve(Size); 14695 Privates.reserve(Size); 14696 LHSs.reserve(Size); 14697 RHSs.reserve(Size); 14698 ReductionOps.reserve(Size); 14699 if (RedModifier == OMPC_REDUCTION_inscan) { 14700 InscanCopyOps.reserve(Size); 14701 InscanCopyArrayTemps.reserve(Size); 14702 InscanCopyArrayElems.reserve(Size); 14703 } 14704 TaskgroupDescriptors.reserve(Size); 14705 ExprCaptures.reserve(Size); 14706 ExprPostUpdates.reserve(Size); 14707 } 14708 /// Stores reduction item and reduction operation only (required for dependent 14709 /// reduction item). 14710 void push(Expr *Item, Expr *ReductionOp) { 14711 Vars.emplace_back(Item); 14712 Privates.emplace_back(nullptr); 14713 LHSs.emplace_back(nullptr); 14714 RHSs.emplace_back(nullptr); 14715 ReductionOps.emplace_back(ReductionOp); 14716 TaskgroupDescriptors.emplace_back(nullptr); 14717 if (RedModifier == OMPC_REDUCTION_inscan) { 14718 InscanCopyOps.push_back(nullptr); 14719 InscanCopyArrayTemps.push_back(nullptr); 14720 InscanCopyArrayElems.push_back(nullptr); 14721 } 14722 } 14723 /// Stores reduction data. 14724 void push(Expr *Item, Expr *Private, Expr *LHS, Expr *RHS, Expr *ReductionOp, 14725 Expr *TaskgroupDescriptor, Expr *CopyOp, Expr *CopyArrayTemp, 14726 Expr *CopyArrayElem) { 14727 Vars.emplace_back(Item); 14728 Privates.emplace_back(Private); 14729 LHSs.emplace_back(LHS); 14730 RHSs.emplace_back(RHS); 14731 ReductionOps.emplace_back(ReductionOp); 14732 TaskgroupDescriptors.emplace_back(TaskgroupDescriptor); 14733 if (RedModifier == OMPC_REDUCTION_inscan) { 14734 InscanCopyOps.push_back(CopyOp); 14735 InscanCopyArrayTemps.push_back(CopyArrayTemp); 14736 InscanCopyArrayElems.push_back(CopyArrayElem); 14737 } else { 14738 assert(CopyOp == nullptr && CopyArrayTemp == nullptr && 14739 CopyArrayElem == nullptr && 14740 "Copy operation must be used for inscan reductions only."); 14741 } 14742 } 14743 }; 14744 } // namespace 14745 14746 static bool checkOMPArraySectionConstantForReduction( 14747 ASTContext &Context, const OMPArraySectionExpr *OASE, bool &SingleElement, 14748 SmallVectorImpl<llvm::APSInt> &ArraySizes) { 14749 const Expr *Length = OASE->getLength(); 14750 if (Length == nullptr) { 14751 // For array sections of the form [1:] or [:], we would need to analyze 14752 // the lower bound... 14753 if (OASE->getColonLocFirst().isValid()) 14754 return false; 14755 14756 // This is an array subscript which has implicit length 1! 14757 SingleElement = true; 14758 ArraySizes.push_back(llvm::APSInt::get(1)); 14759 } else { 14760 Expr::EvalResult Result; 14761 if (!Length->EvaluateAsInt(Result, Context)) 14762 return false; 14763 14764 llvm::APSInt ConstantLengthValue = Result.Val.getInt(); 14765 SingleElement = (ConstantLengthValue.getSExtValue() == 1); 14766 ArraySizes.push_back(ConstantLengthValue); 14767 } 14768 14769 // Get the base of this array section and walk up from there. 14770 const Expr *Base = OASE->getBase()->IgnoreParenImpCasts(); 14771 14772 // We require length = 1 for all array sections except the right-most to 14773 // guarantee that the memory region is contiguous and has no holes in it. 14774 while (const auto *TempOASE = dyn_cast<OMPArraySectionExpr>(Base)) { 14775 Length = TempOASE->getLength(); 14776 if (Length == nullptr) { 14777 // For array sections of the form [1:] or [:], we would need to analyze 14778 // the lower bound... 14779 if (OASE->getColonLocFirst().isValid()) 14780 return false; 14781 14782 // This is an array subscript which has implicit length 1! 14783 ArraySizes.push_back(llvm::APSInt::get(1)); 14784 } else { 14785 Expr::EvalResult Result; 14786 if (!Length->EvaluateAsInt(Result, Context)) 14787 return false; 14788 14789 llvm::APSInt ConstantLengthValue = Result.Val.getInt(); 14790 if (ConstantLengthValue.getSExtValue() != 1) 14791 return false; 14792 14793 ArraySizes.push_back(ConstantLengthValue); 14794 } 14795 Base = TempOASE->getBase()->IgnoreParenImpCasts(); 14796 } 14797 14798 // If we have a single element, we don't need to add the implicit lengths. 14799 if (!SingleElement) { 14800 while (const auto *TempASE = dyn_cast<ArraySubscriptExpr>(Base)) { 14801 // Has implicit length 1! 14802 ArraySizes.push_back(llvm::APSInt::get(1)); 14803 Base = TempASE->getBase()->IgnoreParenImpCasts(); 14804 } 14805 } 14806 14807 // This array section can be privatized as a single value or as a constant 14808 // sized array. 14809 return true; 14810 } 14811 14812 static bool actOnOMPReductionKindClause( 14813 Sema &S, DSAStackTy *Stack, OpenMPClauseKind ClauseKind, 14814 ArrayRef<Expr *> VarList, SourceLocation StartLoc, SourceLocation LParenLoc, 14815 SourceLocation ColonLoc, SourceLocation EndLoc, 14816 CXXScopeSpec &ReductionIdScopeSpec, const DeclarationNameInfo &ReductionId, 14817 ArrayRef<Expr *> UnresolvedReductions, ReductionData &RD) { 14818 DeclarationName DN = ReductionId.getName(); 14819 OverloadedOperatorKind OOK = DN.getCXXOverloadedOperator(); 14820 BinaryOperatorKind BOK = BO_Comma; 14821 14822 ASTContext &Context = S.Context; 14823 // OpenMP [2.14.3.6, reduction clause] 14824 // C 14825 // reduction-identifier is either an identifier or one of the following 14826 // operators: +, -, *, &, |, ^, && and || 14827 // C++ 14828 // reduction-identifier is either an id-expression or one of the following 14829 // operators: +, -, *, &, |, ^, && and || 14830 switch (OOK) { 14831 case OO_Plus: 14832 case OO_Minus: 14833 BOK = BO_Add; 14834 break; 14835 case OO_Star: 14836 BOK = BO_Mul; 14837 break; 14838 case OO_Amp: 14839 BOK = BO_And; 14840 break; 14841 case OO_Pipe: 14842 BOK = BO_Or; 14843 break; 14844 case OO_Caret: 14845 BOK = BO_Xor; 14846 break; 14847 case OO_AmpAmp: 14848 BOK = BO_LAnd; 14849 break; 14850 case OO_PipePipe: 14851 BOK = BO_LOr; 14852 break; 14853 case OO_New: 14854 case OO_Delete: 14855 case OO_Array_New: 14856 case OO_Array_Delete: 14857 case OO_Slash: 14858 case OO_Percent: 14859 case OO_Tilde: 14860 case OO_Exclaim: 14861 case OO_Equal: 14862 case OO_Less: 14863 case OO_Greater: 14864 case OO_LessEqual: 14865 case OO_GreaterEqual: 14866 case OO_PlusEqual: 14867 case OO_MinusEqual: 14868 case OO_StarEqual: 14869 case OO_SlashEqual: 14870 case OO_PercentEqual: 14871 case OO_CaretEqual: 14872 case OO_AmpEqual: 14873 case OO_PipeEqual: 14874 case OO_LessLess: 14875 case OO_GreaterGreater: 14876 case OO_LessLessEqual: 14877 case OO_GreaterGreaterEqual: 14878 case OO_EqualEqual: 14879 case OO_ExclaimEqual: 14880 case OO_Spaceship: 14881 case OO_PlusPlus: 14882 case OO_MinusMinus: 14883 case OO_Comma: 14884 case OO_ArrowStar: 14885 case OO_Arrow: 14886 case OO_Call: 14887 case OO_Subscript: 14888 case OO_Conditional: 14889 case OO_Coawait: 14890 case NUM_OVERLOADED_OPERATORS: 14891 llvm_unreachable("Unexpected reduction identifier"); 14892 case OO_None: 14893 if (IdentifierInfo *II = DN.getAsIdentifierInfo()) { 14894 if (II->isStr("max")) 14895 BOK = BO_GT; 14896 else if (II->isStr("min")) 14897 BOK = BO_LT; 14898 } 14899 break; 14900 } 14901 SourceRange ReductionIdRange; 14902 if (ReductionIdScopeSpec.isValid()) 14903 ReductionIdRange.setBegin(ReductionIdScopeSpec.getBeginLoc()); 14904 else 14905 ReductionIdRange.setBegin(ReductionId.getBeginLoc()); 14906 ReductionIdRange.setEnd(ReductionId.getEndLoc()); 14907 14908 auto IR = UnresolvedReductions.begin(), ER = UnresolvedReductions.end(); 14909 bool FirstIter = true; 14910 for (Expr *RefExpr : VarList) { 14911 assert(RefExpr && "nullptr expr in OpenMP reduction clause."); 14912 // OpenMP [2.1, C/C++] 14913 // A list item is a variable or array section, subject to the restrictions 14914 // specified in Section 2.4 on page 42 and in each of the sections 14915 // describing clauses and directives for which a list appears. 14916 // OpenMP [2.14.3.3, Restrictions, p.1] 14917 // A variable that is part of another variable (as an array or 14918 // structure element) cannot appear in a private clause. 14919 if (!FirstIter && IR != ER) 14920 ++IR; 14921 FirstIter = false; 14922 SourceLocation ELoc; 14923 SourceRange ERange; 14924 Expr *SimpleRefExpr = RefExpr; 14925 auto Res = getPrivateItem(S, SimpleRefExpr, ELoc, ERange, 14926 /*AllowArraySection=*/true); 14927 if (Res.second) { 14928 // Try to find 'declare reduction' corresponding construct before using 14929 // builtin/overloaded operators. 14930 QualType Type = Context.DependentTy; 14931 CXXCastPath BasePath; 14932 ExprResult DeclareReductionRef = buildDeclareReductionRef( 14933 S, ELoc, ERange, Stack->getCurScope(), ReductionIdScopeSpec, 14934 ReductionId, Type, BasePath, IR == ER ? nullptr : *IR); 14935 Expr *ReductionOp = nullptr; 14936 if (S.CurContext->isDependentContext() && 14937 (DeclareReductionRef.isUnset() || 14938 isa<UnresolvedLookupExpr>(DeclareReductionRef.get()))) 14939 ReductionOp = DeclareReductionRef.get(); 14940 // It will be analyzed later. 14941 RD.push(RefExpr, ReductionOp); 14942 } 14943 ValueDecl *D = Res.first; 14944 if (!D) 14945 continue; 14946 14947 Expr *TaskgroupDescriptor = nullptr; 14948 QualType Type; 14949 auto *ASE = dyn_cast<ArraySubscriptExpr>(RefExpr->IgnoreParens()); 14950 auto *OASE = dyn_cast<OMPArraySectionExpr>(RefExpr->IgnoreParens()); 14951 if (ASE) { 14952 Type = ASE->getType().getNonReferenceType(); 14953 } else if (OASE) { 14954 QualType BaseType = 14955 OMPArraySectionExpr::getBaseOriginalType(OASE->getBase()); 14956 if (const auto *ATy = BaseType->getAsArrayTypeUnsafe()) 14957 Type = ATy->getElementType(); 14958 else 14959 Type = BaseType->getPointeeType(); 14960 Type = Type.getNonReferenceType(); 14961 } else { 14962 Type = Context.getBaseElementType(D->getType().getNonReferenceType()); 14963 } 14964 auto *VD = dyn_cast<VarDecl>(D); 14965 14966 // OpenMP [2.9.3.3, Restrictions, C/C++, p.3] 14967 // A variable that appears in a private clause must not have an incomplete 14968 // type or a reference type. 14969 if (S.RequireCompleteType(ELoc, D->getType(), 14970 diag::err_omp_reduction_incomplete_type)) 14971 continue; 14972 // OpenMP [2.14.3.6, reduction clause, Restrictions] 14973 // A list item that appears in a reduction clause must not be 14974 // const-qualified. 14975 if (rejectConstNotMutableType(S, D, Type, ClauseKind, ELoc, 14976 /*AcceptIfMutable*/ false, ASE || OASE)) 14977 continue; 14978 14979 OpenMPDirectiveKind CurrDir = Stack->getCurrentDirective(); 14980 // OpenMP [2.9.3.6, Restrictions, C/C++, p.4] 14981 // If a list-item is a reference type then it must bind to the same object 14982 // for all threads of the team. 14983 if (!ASE && !OASE) { 14984 if (VD) { 14985 VarDecl *VDDef = VD->getDefinition(); 14986 if (VD->getType()->isReferenceType() && VDDef && VDDef->hasInit()) { 14987 DSARefChecker Check(Stack); 14988 if (Check.Visit(VDDef->getInit())) { 14989 S.Diag(ELoc, diag::err_omp_reduction_ref_type_arg) 14990 << getOpenMPClauseName(ClauseKind) << ERange; 14991 S.Diag(VDDef->getLocation(), diag::note_defined_here) << VDDef; 14992 continue; 14993 } 14994 } 14995 } 14996 14997 // OpenMP [2.14.1.1, Data-sharing Attribute Rules for Variables Referenced 14998 // in a Construct] 14999 // Variables with the predetermined data-sharing attributes may not be 15000 // listed in data-sharing attributes clauses, except for the cases 15001 // listed below. For these exceptions only, listing a predetermined 15002 // variable in a data-sharing attribute clause is allowed and overrides 15003 // the variable's predetermined data-sharing attributes. 15004 // OpenMP [2.14.3.6, Restrictions, p.3] 15005 // Any number of reduction clauses can be specified on the directive, 15006 // but a list item can appear only once in the reduction clauses for that 15007 // directive. 15008 DSAStackTy::DSAVarData DVar = Stack->getTopDSA(D, /*FromParent=*/false); 15009 if (DVar.CKind == OMPC_reduction) { 15010 S.Diag(ELoc, diag::err_omp_once_referenced) 15011 << getOpenMPClauseName(ClauseKind); 15012 if (DVar.RefExpr) 15013 S.Diag(DVar.RefExpr->getExprLoc(), diag::note_omp_referenced); 15014 continue; 15015 } 15016 if (DVar.CKind != OMPC_unknown) { 15017 S.Diag(ELoc, diag::err_omp_wrong_dsa) 15018 << getOpenMPClauseName(DVar.CKind) 15019 << getOpenMPClauseName(OMPC_reduction); 15020 reportOriginalDsa(S, Stack, D, DVar); 15021 continue; 15022 } 15023 15024 // OpenMP [2.14.3.6, Restrictions, p.1] 15025 // A list item that appears in a reduction clause of a worksharing 15026 // construct must be shared in the parallel regions to which any of the 15027 // worksharing regions arising from the worksharing construct bind. 15028 if (isOpenMPWorksharingDirective(CurrDir) && 15029 !isOpenMPParallelDirective(CurrDir) && 15030 !isOpenMPTeamsDirective(CurrDir)) { 15031 DVar = Stack->getImplicitDSA(D, true); 15032 if (DVar.CKind != OMPC_shared) { 15033 S.Diag(ELoc, diag::err_omp_required_access) 15034 << getOpenMPClauseName(OMPC_reduction) 15035 << getOpenMPClauseName(OMPC_shared); 15036 reportOriginalDsa(S, Stack, D, DVar); 15037 continue; 15038 } 15039 } 15040 } 15041 15042 // Try to find 'declare reduction' corresponding construct before using 15043 // builtin/overloaded operators. 15044 CXXCastPath BasePath; 15045 ExprResult DeclareReductionRef = buildDeclareReductionRef( 15046 S, ELoc, ERange, Stack->getCurScope(), ReductionIdScopeSpec, 15047 ReductionId, Type, BasePath, IR == ER ? nullptr : *IR); 15048 if (DeclareReductionRef.isInvalid()) 15049 continue; 15050 if (S.CurContext->isDependentContext() && 15051 (DeclareReductionRef.isUnset() || 15052 isa<UnresolvedLookupExpr>(DeclareReductionRef.get()))) { 15053 RD.push(RefExpr, DeclareReductionRef.get()); 15054 continue; 15055 } 15056 if (BOK == BO_Comma && DeclareReductionRef.isUnset()) { 15057 // Not allowed reduction identifier is found. 15058 S.Diag(ReductionId.getBeginLoc(), 15059 diag::err_omp_unknown_reduction_identifier) 15060 << Type << ReductionIdRange; 15061 continue; 15062 } 15063 15064 // OpenMP [2.14.3.6, reduction clause, Restrictions] 15065 // The type of a list item that appears in a reduction clause must be valid 15066 // for the reduction-identifier. For a max or min reduction in C, the type 15067 // of the list item must be an allowed arithmetic data type: char, int, 15068 // float, double, or _Bool, possibly modified with long, short, signed, or 15069 // unsigned. For a max or min reduction in C++, the type of the list item 15070 // must be an allowed arithmetic data type: char, wchar_t, int, float, 15071 // double, or bool, possibly modified with long, short, signed, or unsigned. 15072 if (DeclareReductionRef.isUnset()) { 15073 if ((BOK == BO_GT || BOK == BO_LT) && 15074 !(Type->isScalarType() || 15075 (S.getLangOpts().CPlusPlus && Type->isArithmeticType()))) { 15076 S.Diag(ELoc, diag::err_omp_clause_not_arithmetic_type_arg) 15077 << getOpenMPClauseName(ClauseKind) << S.getLangOpts().CPlusPlus; 15078 if (!ASE && !OASE) { 15079 bool IsDecl = !VD || VD->isThisDeclarationADefinition(Context) == 15080 VarDecl::DeclarationOnly; 15081 S.Diag(D->getLocation(), 15082 IsDecl ? diag::note_previous_decl : diag::note_defined_here) 15083 << D; 15084 } 15085 continue; 15086 } 15087 if ((BOK == BO_OrAssign || BOK == BO_AndAssign || BOK == BO_XorAssign) && 15088 !S.getLangOpts().CPlusPlus && Type->isFloatingType()) { 15089 S.Diag(ELoc, diag::err_omp_clause_floating_type_arg) 15090 << getOpenMPClauseName(ClauseKind); 15091 if (!ASE && !OASE) { 15092 bool IsDecl = !VD || VD->isThisDeclarationADefinition(Context) == 15093 VarDecl::DeclarationOnly; 15094 S.Diag(D->getLocation(), 15095 IsDecl ? diag::note_previous_decl : diag::note_defined_here) 15096 << D; 15097 } 15098 continue; 15099 } 15100 } 15101 15102 Type = Type.getNonLValueExprType(Context).getUnqualifiedType(); 15103 VarDecl *LHSVD = buildVarDecl(S, ELoc, Type, ".reduction.lhs", 15104 D->hasAttrs() ? &D->getAttrs() : nullptr); 15105 VarDecl *RHSVD = buildVarDecl(S, ELoc, Type, D->getName(), 15106 D->hasAttrs() ? &D->getAttrs() : nullptr); 15107 QualType PrivateTy = Type; 15108 15109 // Try if we can determine constant lengths for all array sections and avoid 15110 // the VLA. 15111 bool ConstantLengthOASE = false; 15112 if (OASE) { 15113 bool SingleElement; 15114 llvm::SmallVector<llvm::APSInt, 4> ArraySizes; 15115 ConstantLengthOASE = checkOMPArraySectionConstantForReduction( 15116 Context, OASE, SingleElement, ArraySizes); 15117 15118 // If we don't have a single element, we must emit a constant array type. 15119 if (ConstantLengthOASE && !SingleElement) { 15120 for (llvm::APSInt &Size : ArraySizes) 15121 PrivateTy = Context.getConstantArrayType(PrivateTy, Size, nullptr, 15122 ArrayType::Normal, 15123 /*IndexTypeQuals=*/0); 15124 } 15125 } 15126 15127 if ((OASE && !ConstantLengthOASE) || 15128 (!OASE && !ASE && 15129 D->getType().getNonReferenceType()->isVariablyModifiedType())) { 15130 if (!Context.getTargetInfo().isVLASupported()) { 15131 if (isOpenMPTargetExecutionDirective(Stack->getCurrentDirective())) { 15132 S.Diag(ELoc, diag::err_omp_reduction_vla_unsupported) << !!OASE; 15133 S.Diag(ELoc, diag::note_vla_unsupported); 15134 continue; 15135 } else { 15136 S.targetDiag(ELoc, diag::err_omp_reduction_vla_unsupported) << !!OASE; 15137 S.targetDiag(ELoc, diag::note_vla_unsupported); 15138 } 15139 } 15140 // For arrays/array sections only: 15141 // Create pseudo array type for private copy. The size for this array will 15142 // be generated during codegen. 15143 // For array subscripts or single variables Private Ty is the same as Type 15144 // (type of the variable or single array element). 15145 PrivateTy = Context.getVariableArrayType( 15146 Type, 15147 new (Context) OpaqueValueExpr(ELoc, Context.getSizeType(), VK_RValue), 15148 ArrayType::Normal, /*IndexTypeQuals=*/0, SourceRange()); 15149 } else if (!ASE && !OASE && 15150 Context.getAsArrayType(D->getType().getNonReferenceType())) { 15151 PrivateTy = D->getType().getNonReferenceType(); 15152 } 15153 // Private copy. 15154 VarDecl *PrivateVD = 15155 buildVarDecl(S, ELoc, PrivateTy, D->getName(), 15156 D->hasAttrs() ? &D->getAttrs() : nullptr, 15157 VD ? cast<DeclRefExpr>(SimpleRefExpr) : nullptr); 15158 // Add initializer for private variable. 15159 Expr *Init = nullptr; 15160 DeclRefExpr *LHSDRE = buildDeclRefExpr(S, LHSVD, Type, ELoc); 15161 DeclRefExpr *RHSDRE = buildDeclRefExpr(S, RHSVD, Type, ELoc); 15162 if (DeclareReductionRef.isUsable()) { 15163 auto *DRDRef = DeclareReductionRef.getAs<DeclRefExpr>(); 15164 auto *DRD = cast<OMPDeclareReductionDecl>(DRDRef->getDecl()); 15165 if (DRD->getInitializer()) { 15166 S.ActOnUninitializedDecl(PrivateVD); 15167 Init = DRDRef; 15168 RHSVD->setInit(DRDRef); 15169 RHSVD->setInitStyle(VarDecl::CallInit); 15170 } 15171 } else { 15172 switch (BOK) { 15173 case BO_Add: 15174 case BO_Xor: 15175 case BO_Or: 15176 case BO_LOr: 15177 // '+', '-', '^', '|', '||' reduction ops - initializer is '0'. 15178 if (Type->isScalarType() || Type->isAnyComplexType()) 15179 Init = S.ActOnIntegerConstant(ELoc, /*Val=*/0).get(); 15180 break; 15181 case BO_Mul: 15182 case BO_LAnd: 15183 if (Type->isScalarType() || Type->isAnyComplexType()) { 15184 // '*' and '&&' reduction ops - initializer is '1'. 15185 Init = S.ActOnIntegerConstant(ELoc, /*Val=*/1).get(); 15186 } 15187 break; 15188 case BO_And: { 15189 // '&' reduction op - initializer is '~0'. 15190 QualType OrigType = Type; 15191 if (auto *ComplexTy = OrigType->getAs<ComplexType>()) 15192 Type = ComplexTy->getElementType(); 15193 if (Type->isRealFloatingType()) { 15194 llvm::APFloat InitValue = llvm::APFloat::getAllOnesValue( 15195 Context.getFloatTypeSemantics(Type), 15196 Context.getTypeSize(Type)); 15197 Init = FloatingLiteral::Create(Context, InitValue, /*isexact=*/true, 15198 Type, ELoc); 15199 } else if (Type->isScalarType()) { 15200 uint64_t Size = Context.getTypeSize(Type); 15201 QualType IntTy = Context.getIntTypeForBitwidth(Size, /*Signed=*/0); 15202 llvm::APInt InitValue = llvm::APInt::getAllOnesValue(Size); 15203 Init = IntegerLiteral::Create(Context, InitValue, IntTy, ELoc); 15204 } 15205 if (Init && OrigType->isAnyComplexType()) { 15206 // Init = 0xFFFF + 0xFFFFi; 15207 auto *Im = new (Context) ImaginaryLiteral(Init, OrigType); 15208 Init = S.CreateBuiltinBinOp(ELoc, BO_Add, Init, Im).get(); 15209 } 15210 Type = OrigType; 15211 break; 15212 } 15213 case BO_LT: 15214 case BO_GT: { 15215 // 'min' reduction op - initializer is 'Largest representable number in 15216 // the reduction list item type'. 15217 // 'max' reduction op - initializer is 'Least representable number in 15218 // the reduction list item type'. 15219 if (Type->isIntegerType() || Type->isPointerType()) { 15220 bool IsSigned = Type->hasSignedIntegerRepresentation(); 15221 uint64_t Size = Context.getTypeSize(Type); 15222 QualType IntTy = 15223 Context.getIntTypeForBitwidth(Size, /*Signed=*/IsSigned); 15224 llvm::APInt InitValue = 15225 (BOK != BO_LT) ? IsSigned ? llvm::APInt::getSignedMinValue(Size) 15226 : llvm::APInt::getMinValue(Size) 15227 : IsSigned ? llvm::APInt::getSignedMaxValue(Size) 15228 : llvm::APInt::getMaxValue(Size); 15229 Init = IntegerLiteral::Create(Context, InitValue, IntTy, ELoc); 15230 if (Type->isPointerType()) { 15231 // Cast to pointer type. 15232 ExprResult CastExpr = S.BuildCStyleCastExpr( 15233 ELoc, Context.getTrivialTypeSourceInfo(Type, ELoc), ELoc, Init); 15234 if (CastExpr.isInvalid()) 15235 continue; 15236 Init = CastExpr.get(); 15237 } 15238 } else if (Type->isRealFloatingType()) { 15239 llvm::APFloat InitValue = llvm::APFloat::getLargest( 15240 Context.getFloatTypeSemantics(Type), BOK != BO_LT); 15241 Init = FloatingLiteral::Create(Context, InitValue, /*isexact=*/true, 15242 Type, ELoc); 15243 } 15244 break; 15245 } 15246 case BO_PtrMemD: 15247 case BO_PtrMemI: 15248 case BO_MulAssign: 15249 case BO_Div: 15250 case BO_Rem: 15251 case BO_Sub: 15252 case BO_Shl: 15253 case BO_Shr: 15254 case BO_LE: 15255 case BO_GE: 15256 case BO_EQ: 15257 case BO_NE: 15258 case BO_Cmp: 15259 case BO_AndAssign: 15260 case BO_XorAssign: 15261 case BO_OrAssign: 15262 case BO_Assign: 15263 case BO_AddAssign: 15264 case BO_SubAssign: 15265 case BO_DivAssign: 15266 case BO_RemAssign: 15267 case BO_ShlAssign: 15268 case BO_ShrAssign: 15269 case BO_Comma: 15270 llvm_unreachable("Unexpected reduction operation"); 15271 } 15272 } 15273 if (Init && DeclareReductionRef.isUnset()) { 15274 S.AddInitializerToDecl(RHSVD, Init, /*DirectInit=*/false); 15275 // Store initializer for single element in private copy. Will be used 15276 // during codegen. 15277 PrivateVD->setInit(RHSVD->getInit()); 15278 PrivateVD->setInitStyle(RHSVD->getInitStyle()); 15279 } else if (!Init) { 15280 S.ActOnUninitializedDecl(RHSVD); 15281 // Store initializer for single element in private copy. Will be used 15282 // during codegen. 15283 PrivateVD->setInit(RHSVD->getInit()); 15284 PrivateVD->setInitStyle(RHSVD->getInitStyle()); 15285 } 15286 if (RHSVD->isInvalidDecl()) 15287 continue; 15288 if (!RHSVD->hasInit() && 15289 (DeclareReductionRef.isUnset() || !S.LangOpts.CPlusPlus)) { 15290 S.Diag(ELoc, diag::err_omp_reduction_id_not_compatible) 15291 << Type << ReductionIdRange; 15292 bool IsDecl = !VD || VD->isThisDeclarationADefinition(Context) == 15293 VarDecl::DeclarationOnly; 15294 S.Diag(D->getLocation(), 15295 IsDecl ? diag::note_previous_decl : diag::note_defined_here) 15296 << D; 15297 continue; 15298 } 15299 DeclRefExpr *PrivateDRE = buildDeclRefExpr(S, PrivateVD, PrivateTy, ELoc); 15300 ExprResult ReductionOp; 15301 if (DeclareReductionRef.isUsable()) { 15302 QualType RedTy = DeclareReductionRef.get()->getType(); 15303 QualType PtrRedTy = Context.getPointerType(RedTy); 15304 ExprResult LHS = S.CreateBuiltinUnaryOp(ELoc, UO_AddrOf, LHSDRE); 15305 ExprResult RHS = S.CreateBuiltinUnaryOp(ELoc, UO_AddrOf, RHSDRE); 15306 if (!BasePath.empty()) { 15307 LHS = S.DefaultLvalueConversion(LHS.get()); 15308 RHS = S.DefaultLvalueConversion(RHS.get()); 15309 LHS = ImplicitCastExpr::Create(Context, PtrRedTy, 15310 CK_UncheckedDerivedToBase, LHS.get(), 15311 &BasePath, LHS.get()->getValueKind()); 15312 RHS = ImplicitCastExpr::Create(Context, PtrRedTy, 15313 CK_UncheckedDerivedToBase, RHS.get(), 15314 &BasePath, RHS.get()->getValueKind()); 15315 } 15316 FunctionProtoType::ExtProtoInfo EPI; 15317 QualType Params[] = {PtrRedTy, PtrRedTy}; 15318 QualType FnTy = Context.getFunctionType(Context.VoidTy, Params, EPI); 15319 auto *OVE = new (Context) OpaqueValueExpr( 15320 ELoc, Context.getPointerType(FnTy), VK_RValue, OK_Ordinary, 15321 S.DefaultLvalueConversion(DeclareReductionRef.get()).get()); 15322 Expr *Args[] = {LHS.get(), RHS.get()}; 15323 ReductionOp = 15324 CallExpr::Create(Context, OVE, Args, Context.VoidTy, VK_RValue, ELoc); 15325 } else { 15326 ReductionOp = S.BuildBinOp( 15327 Stack->getCurScope(), ReductionId.getBeginLoc(), BOK, LHSDRE, RHSDRE); 15328 if (ReductionOp.isUsable()) { 15329 if (BOK != BO_LT && BOK != BO_GT) { 15330 ReductionOp = 15331 S.BuildBinOp(Stack->getCurScope(), ReductionId.getBeginLoc(), 15332 BO_Assign, LHSDRE, ReductionOp.get()); 15333 } else { 15334 auto *ConditionalOp = new (Context) 15335 ConditionalOperator(ReductionOp.get(), ELoc, LHSDRE, ELoc, RHSDRE, 15336 Type, VK_LValue, OK_Ordinary); 15337 ReductionOp = 15338 S.BuildBinOp(Stack->getCurScope(), ReductionId.getBeginLoc(), 15339 BO_Assign, LHSDRE, ConditionalOp); 15340 } 15341 if (ReductionOp.isUsable()) 15342 ReductionOp = S.ActOnFinishFullExpr(ReductionOp.get(), 15343 /*DiscardedValue*/ false); 15344 } 15345 if (!ReductionOp.isUsable()) 15346 continue; 15347 } 15348 15349 // Add copy operations for inscan reductions. 15350 // LHS = RHS; 15351 ExprResult CopyOpRes, TempArrayRes, TempArrayElem; 15352 if (ClauseKind == OMPC_reduction && 15353 RD.RedModifier == OMPC_REDUCTION_inscan) { 15354 ExprResult RHS = S.DefaultLvalueConversion(RHSDRE); 15355 CopyOpRes = S.BuildBinOp(Stack->getCurScope(), ELoc, BO_Assign, LHSDRE, 15356 RHS.get()); 15357 if (!CopyOpRes.isUsable()) 15358 continue; 15359 CopyOpRes = 15360 S.ActOnFinishFullExpr(CopyOpRes.get(), /*DiscardedValue=*/true); 15361 if (!CopyOpRes.isUsable()) 15362 continue; 15363 // For simd directive and simd-based directives in simd mode no need to 15364 // construct temp array, need just a single temp element. 15365 if (Stack->getCurrentDirective() == OMPD_simd || 15366 (S.getLangOpts().OpenMPSimd && 15367 isOpenMPSimdDirective(Stack->getCurrentDirective()))) { 15368 VarDecl *TempArrayVD = 15369 buildVarDecl(S, ELoc, PrivateTy, D->getName(), 15370 D->hasAttrs() ? &D->getAttrs() : nullptr); 15371 // Add a constructor to the temp decl. 15372 S.ActOnUninitializedDecl(TempArrayVD); 15373 TempArrayRes = buildDeclRefExpr(S, TempArrayVD, PrivateTy, ELoc); 15374 } else { 15375 // Build temp array for prefix sum. 15376 auto *Dim = new (S.Context) 15377 OpaqueValueExpr(ELoc, S.Context.getSizeType(), VK_RValue); 15378 QualType ArrayTy = 15379 S.Context.getVariableArrayType(PrivateTy, Dim, ArrayType::Normal, 15380 /*IndexTypeQuals=*/0, {ELoc, ELoc}); 15381 VarDecl *TempArrayVD = 15382 buildVarDecl(S, ELoc, ArrayTy, D->getName(), 15383 D->hasAttrs() ? &D->getAttrs() : nullptr); 15384 // Add a constructor to the temp decl. 15385 S.ActOnUninitializedDecl(TempArrayVD); 15386 TempArrayRes = buildDeclRefExpr(S, TempArrayVD, ArrayTy, ELoc); 15387 TempArrayElem = 15388 S.DefaultFunctionArrayLvalueConversion(TempArrayRes.get()); 15389 auto *Idx = new (S.Context) 15390 OpaqueValueExpr(ELoc, S.Context.getSizeType(), VK_RValue); 15391 TempArrayElem = S.CreateBuiltinArraySubscriptExpr(TempArrayElem.get(), 15392 ELoc, Idx, ELoc); 15393 } 15394 } 15395 15396 // OpenMP [2.15.4.6, Restrictions, p.2] 15397 // A list item that appears in an in_reduction clause of a task construct 15398 // must appear in a task_reduction clause of a construct associated with a 15399 // taskgroup region that includes the participating task in its taskgroup 15400 // set. The construct associated with the innermost region that meets this 15401 // condition must specify the same reduction-identifier as the in_reduction 15402 // clause. 15403 if (ClauseKind == OMPC_in_reduction) { 15404 SourceRange ParentSR; 15405 BinaryOperatorKind ParentBOK; 15406 const Expr *ParentReductionOp = nullptr; 15407 Expr *ParentBOKTD = nullptr, *ParentReductionOpTD = nullptr; 15408 DSAStackTy::DSAVarData ParentBOKDSA = 15409 Stack->getTopMostTaskgroupReductionData(D, ParentSR, ParentBOK, 15410 ParentBOKTD); 15411 DSAStackTy::DSAVarData ParentReductionOpDSA = 15412 Stack->getTopMostTaskgroupReductionData( 15413 D, ParentSR, ParentReductionOp, ParentReductionOpTD); 15414 bool IsParentBOK = ParentBOKDSA.DKind != OMPD_unknown; 15415 bool IsParentReductionOp = ParentReductionOpDSA.DKind != OMPD_unknown; 15416 if ((DeclareReductionRef.isUnset() && IsParentReductionOp) || 15417 (DeclareReductionRef.isUsable() && IsParentBOK) || 15418 (IsParentBOK && BOK != ParentBOK) || IsParentReductionOp) { 15419 bool EmitError = true; 15420 if (IsParentReductionOp && DeclareReductionRef.isUsable()) { 15421 llvm::FoldingSetNodeID RedId, ParentRedId; 15422 ParentReductionOp->Profile(ParentRedId, Context, /*Canonical=*/true); 15423 DeclareReductionRef.get()->Profile(RedId, Context, 15424 /*Canonical=*/true); 15425 EmitError = RedId != ParentRedId; 15426 } 15427 if (EmitError) { 15428 S.Diag(ReductionId.getBeginLoc(), 15429 diag::err_omp_reduction_identifier_mismatch) 15430 << ReductionIdRange << RefExpr->getSourceRange(); 15431 S.Diag(ParentSR.getBegin(), 15432 diag::note_omp_previous_reduction_identifier) 15433 << ParentSR 15434 << (IsParentBOK ? ParentBOKDSA.RefExpr 15435 : ParentReductionOpDSA.RefExpr) 15436 ->getSourceRange(); 15437 continue; 15438 } 15439 } 15440 TaskgroupDescriptor = IsParentBOK ? ParentBOKTD : ParentReductionOpTD; 15441 } 15442 15443 DeclRefExpr *Ref = nullptr; 15444 Expr *VarsExpr = RefExpr->IgnoreParens(); 15445 if (!VD && !S.CurContext->isDependentContext()) { 15446 if (ASE || OASE) { 15447 TransformExprToCaptures RebuildToCapture(S, D); 15448 VarsExpr = 15449 RebuildToCapture.TransformExpr(RefExpr->IgnoreParens()).get(); 15450 Ref = RebuildToCapture.getCapturedExpr(); 15451 } else { 15452 VarsExpr = Ref = buildCapture(S, D, SimpleRefExpr, /*WithInit=*/false); 15453 } 15454 if (!S.isOpenMPCapturedDecl(D)) { 15455 RD.ExprCaptures.emplace_back(Ref->getDecl()); 15456 if (Ref->getDecl()->hasAttr<OMPCaptureNoInitAttr>()) { 15457 ExprResult RefRes = S.DefaultLvalueConversion(Ref); 15458 if (!RefRes.isUsable()) 15459 continue; 15460 ExprResult PostUpdateRes = 15461 S.BuildBinOp(Stack->getCurScope(), ELoc, BO_Assign, SimpleRefExpr, 15462 RefRes.get()); 15463 if (!PostUpdateRes.isUsable()) 15464 continue; 15465 if (isOpenMPTaskingDirective(Stack->getCurrentDirective()) || 15466 Stack->getCurrentDirective() == OMPD_taskgroup) { 15467 S.Diag(RefExpr->getExprLoc(), 15468 diag::err_omp_reduction_non_addressable_expression) 15469 << RefExpr->getSourceRange(); 15470 continue; 15471 } 15472 RD.ExprPostUpdates.emplace_back( 15473 S.IgnoredValueConversions(PostUpdateRes.get()).get()); 15474 } 15475 } 15476 } 15477 // All reduction items are still marked as reduction (to do not increase 15478 // code base size). 15479 unsigned Modifier = RD.RedModifier; 15480 // Consider task_reductions as reductions with task modifier. Required for 15481 // correct analysis of in_reduction clauses. 15482 if (CurrDir == OMPD_taskgroup && ClauseKind == OMPC_task_reduction) 15483 Modifier = OMPC_REDUCTION_task; 15484 Stack->addDSA(D, RefExpr->IgnoreParens(), OMPC_reduction, Ref, Modifier); 15485 if (Modifier == OMPC_REDUCTION_task && 15486 (CurrDir == OMPD_taskgroup || 15487 ((isOpenMPParallelDirective(CurrDir) || 15488 isOpenMPWorksharingDirective(CurrDir)) && 15489 !isOpenMPSimdDirective(CurrDir)))) { 15490 if (DeclareReductionRef.isUsable()) 15491 Stack->addTaskgroupReductionData(D, ReductionIdRange, 15492 DeclareReductionRef.get()); 15493 else 15494 Stack->addTaskgroupReductionData(D, ReductionIdRange, BOK); 15495 } 15496 RD.push(VarsExpr, PrivateDRE, LHSDRE, RHSDRE, ReductionOp.get(), 15497 TaskgroupDescriptor, CopyOpRes.get(), TempArrayRes.get(), 15498 TempArrayElem.get()); 15499 } 15500 return RD.Vars.empty(); 15501 } 15502 15503 OMPClause *Sema::ActOnOpenMPReductionClause( 15504 ArrayRef<Expr *> VarList, OpenMPReductionClauseModifier Modifier, 15505 SourceLocation StartLoc, SourceLocation LParenLoc, 15506 SourceLocation ModifierLoc, SourceLocation ColonLoc, SourceLocation EndLoc, 15507 CXXScopeSpec &ReductionIdScopeSpec, const DeclarationNameInfo &ReductionId, 15508 ArrayRef<Expr *> UnresolvedReductions) { 15509 if (ModifierLoc.isValid() && Modifier == OMPC_REDUCTION_unknown) { 15510 Diag(LParenLoc, diag::err_omp_unexpected_clause_value) 15511 << getListOfPossibleValues(OMPC_reduction, /*First=*/0, 15512 /*Last=*/OMPC_REDUCTION_unknown) 15513 << getOpenMPClauseName(OMPC_reduction); 15514 return nullptr; 15515 } 15516 // OpenMP 5.0, 2.19.5.4 reduction Clause, Restrictions 15517 // A reduction clause with the inscan reduction-modifier may only appear on a 15518 // worksharing-loop construct, a worksharing-loop SIMD construct, a simd 15519 // construct, a parallel worksharing-loop construct or a parallel 15520 // worksharing-loop SIMD construct. 15521 if (Modifier == OMPC_REDUCTION_inscan && 15522 (DSAStack->getCurrentDirective() != OMPD_for && 15523 DSAStack->getCurrentDirective() != OMPD_for_simd && 15524 DSAStack->getCurrentDirective() != OMPD_simd && 15525 DSAStack->getCurrentDirective() != OMPD_parallel_for && 15526 DSAStack->getCurrentDirective() != OMPD_parallel_for_simd)) { 15527 Diag(ModifierLoc, diag::err_omp_wrong_inscan_reduction); 15528 return nullptr; 15529 } 15530 15531 ReductionData RD(VarList.size(), Modifier); 15532 if (actOnOMPReductionKindClause(*this, DSAStack, OMPC_reduction, VarList, 15533 StartLoc, LParenLoc, ColonLoc, EndLoc, 15534 ReductionIdScopeSpec, ReductionId, 15535 UnresolvedReductions, RD)) 15536 return nullptr; 15537 15538 return OMPReductionClause::Create( 15539 Context, StartLoc, LParenLoc, ModifierLoc, ColonLoc, EndLoc, Modifier, 15540 RD.Vars, ReductionIdScopeSpec.getWithLocInContext(Context), ReductionId, 15541 RD.Privates, RD.LHSs, RD.RHSs, RD.ReductionOps, RD.InscanCopyOps, 15542 RD.InscanCopyArrayTemps, RD.InscanCopyArrayElems, 15543 buildPreInits(Context, RD.ExprCaptures), 15544 buildPostUpdate(*this, RD.ExprPostUpdates)); 15545 } 15546 15547 OMPClause *Sema::ActOnOpenMPTaskReductionClause( 15548 ArrayRef<Expr *> VarList, SourceLocation StartLoc, SourceLocation LParenLoc, 15549 SourceLocation ColonLoc, SourceLocation EndLoc, 15550 CXXScopeSpec &ReductionIdScopeSpec, const DeclarationNameInfo &ReductionId, 15551 ArrayRef<Expr *> UnresolvedReductions) { 15552 ReductionData RD(VarList.size()); 15553 if (actOnOMPReductionKindClause(*this, DSAStack, OMPC_task_reduction, VarList, 15554 StartLoc, LParenLoc, ColonLoc, EndLoc, 15555 ReductionIdScopeSpec, ReductionId, 15556 UnresolvedReductions, RD)) 15557 return nullptr; 15558 15559 return OMPTaskReductionClause::Create( 15560 Context, StartLoc, LParenLoc, ColonLoc, EndLoc, RD.Vars, 15561 ReductionIdScopeSpec.getWithLocInContext(Context), ReductionId, 15562 RD.Privates, RD.LHSs, RD.RHSs, RD.ReductionOps, 15563 buildPreInits(Context, RD.ExprCaptures), 15564 buildPostUpdate(*this, RD.ExprPostUpdates)); 15565 } 15566 15567 OMPClause *Sema::ActOnOpenMPInReductionClause( 15568 ArrayRef<Expr *> VarList, SourceLocation StartLoc, SourceLocation LParenLoc, 15569 SourceLocation ColonLoc, SourceLocation EndLoc, 15570 CXXScopeSpec &ReductionIdScopeSpec, const DeclarationNameInfo &ReductionId, 15571 ArrayRef<Expr *> UnresolvedReductions) { 15572 ReductionData RD(VarList.size()); 15573 if (actOnOMPReductionKindClause(*this, DSAStack, OMPC_in_reduction, VarList, 15574 StartLoc, LParenLoc, ColonLoc, EndLoc, 15575 ReductionIdScopeSpec, ReductionId, 15576 UnresolvedReductions, RD)) 15577 return nullptr; 15578 15579 return OMPInReductionClause::Create( 15580 Context, StartLoc, LParenLoc, ColonLoc, EndLoc, RD.Vars, 15581 ReductionIdScopeSpec.getWithLocInContext(Context), ReductionId, 15582 RD.Privates, RD.LHSs, RD.RHSs, RD.ReductionOps, RD.TaskgroupDescriptors, 15583 buildPreInits(Context, RD.ExprCaptures), 15584 buildPostUpdate(*this, RD.ExprPostUpdates)); 15585 } 15586 15587 bool Sema::CheckOpenMPLinearModifier(OpenMPLinearClauseKind LinKind, 15588 SourceLocation LinLoc) { 15589 if ((!LangOpts.CPlusPlus && LinKind != OMPC_LINEAR_val) || 15590 LinKind == OMPC_LINEAR_unknown) { 15591 Diag(LinLoc, diag::err_omp_wrong_linear_modifier) << LangOpts.CPlusPlus; 15592 return true; 15593 } 15594 return false; 15595 } 15596 15597 bool Sema::CheckOpenMPLinearDecl(const ValueDecl *D, SourceLocation ELoc, 15598 OpenMPLinearClauseKind LinKind, QualType Type, 15599 bool IsDeclareSimd) { 15600 const auto *VD = dyn_cast_or_null<VarDecl>(D); 15601 // A variable must not have an incomplete type or a reference type. 15602 if (RequireCompleteType(ELoc, Type, diag::err_omp_linear_incomplete_type)) 15603 return true; 15604 if ((LinKind == OMPC_LINEAR_uval || LinKind == OMPC_LINEAR_ref) && 15605 !Type->isReferenceType()) { 15606 Diag(ELoc, diag::err_omp_wrong_linear_modifier_non_reference) 15607 << Type << getOpenMPSimpleClauseTypeName(OMPC_linear, LinKind); 15608 return true; 15609 } 15610 Type = Type.getNonReferenceType(); 15611 15612 // OpenMP 5.0 [2.19.3, List Item Privatization, Restrictions] 15613 // A variable that is privatized must not have a const-qualified type 15614 // unless it is of class type with a mutable member. This restriction does 15615 // not apply to the firstprivate clause, nor to the linear clause on 15616 // declarative directives (like declare simd). 15617 if (!IsDeclareSimd && 15618 rejectConstNotMutableType(*this, D, Type, OMPC_linear, ELoc)) 15619 return true; 15620 15621 // A list item must be of integral or pointer type. 15622 Type = Type.getUnqualifiedType().getCanonicalType(); 15623 const auto *Ty = Type.getTypePtrOrNull(); 15624 if (!Ty || (LinKind != OMPC_LINEAR_ref && !Ty->isDependentType() && 15625 !Ty->isIntegralType(Context) && !Ty->isPointerType())) { 15626 Diag(ELoc, diag::err_omp_linear_expected_int_or_ptr) << Type; 15627 if (D) { 15628 bool IsDecl = 15629 !VD || 15630 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly; 15631 Diag(D->getLocation(), 15632 IsDecl ? diag::note_previous_decl : diag::note_defined_here) 15633 << D; 15634 } 15635 return true; 15636 } 15637 return false; 15638 } 15639 15640 OMPClause *Sema::ActOnOpenMPLinearClause( 15641 ArrayRef<Expr *> VarList, Expr *Step, SourceLocation StartLoc, 15642 SourceLocation LParenLoc, OpenMPLinearClauseKind LinKind, 15643 SourceLocation LinLoc, SourceLocation ColonLoc, SourceLocation EndLoc) { 15644 SmallVector<Expr *, 8> Vars; 15645 SmallVector<Expr *, 8> Privates; 15646 SmallVector<Expr *, 8> Inits; 15647 SmallVector<Decl *, 4> ExprCaptures; 15648 SmallVector<Expr *, 4> ExprPostUpdates; 15649 if (CheckOpenMPLinearModifier(LinKind, LinLoc)) 15650 LinKind = OMPC_LINEAR_val; 15651 for (Expr *RefExpr : VarList) { 15652 assert(RefExpr && "NULL expr in OpenMP linear clause."); 15653 SourceLocation ELoc; 15654 SourceRange ERange; 15655 Expr *SimpleRefExpr = RefExpr; 15656 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange); 15657 if (Res.second) { 15658 // It will be analyzed later. 15659 Vars.push_back(RefExpr); 15660 Privates.push_back(nullptr); 15661 Inits.push_back(nullptr); 15662 } 15663 ValueDecl *D = Res.first; 15664 if (!D) 15665 continue; 15666 15667 QualType Type = D->getType(); 15668 auto *VD = dyn_cast<VarDecl>(D); 15669 15670 // OpenMP [2.14.3.7, linear clause] 15671 // A list-item cannot appear in more than one linear clause. 15672 // A list-item that appears in a linear clause cannot appear in any 15673 // other data-sharing attribute clause. 15674 DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, /*FromParent=*/false); 15675 if (DVar.RefExpr) { 15676 Diag(ELoc, diag::err_omp_wrong_dsa) << getOpenMPClauseName(DVar.CKind) 15677 << getOpenMPClauseName(OMPC_linear); 15678 reportOriginalDsa(*this, DSAStack, D, DVar); 15679 continue; 15680 } 15681 15682 if (CheckOpenMPLinearDecl(D, ELoc, LinKind, Type)) 15683 continue; 15684 Type = Type.getNonReferenceType().getUnqualifiedType().getCanonicalType(); 15685 15686 // Build private copy of original var. 15687 VarDecl *Private = 15688 buildVarDecl(*this, ELoc, Type, D->getName(), 15689 D->hasAttrs() ? &D->getAttrs() : nullptr, 15690 VD ? cast<DeclRefExpr>(SimpleRefExpr) : nullptr); 15691 DeclRefExpr *PrivateRef = buildDeclRefExpr(*this, Private, Type, ELoc); 15692 // Build var to save initial value. 15693 VarDecl *Init = buildVarDecl(*this, ELoc, Type, ".linear.start"); 15694 Expr *InitExpr; 15695 DeclRefExpr *Ref = nullptr; 15696 if (!VD && !CurContext->isDependentContext()) { 15697 Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/false); 15698 if (!isOpenMPCapturedDecl(D)) { 15699 ExprCaptures.push_back(Ref->getDecl()); 15700 if (Ref->getDecl()->hasAttr<OMPCaptureNoInitAttr>()) { 15701 ExprResult RefRes = DefaultLvalueConversion(Ref); 15702 if (!RefRes.isUsable()) 15703 continue; 15704 ExprResult PostUpdateRes = 15705 BuildBinOp(DSAStack->getCurScope(), ELoc, BO_Assign, 15706 SimpleRefExpr, RefRes.get()); 15707 if (!PostUpdateRes.isUsable()) 15708 continue; 15709 ExprPostUpdates.push_back( 15710 IgnoredValueConversions(PostUpdateRes.get()).get()); 15711 } 15712 } 15713 } 15714 if (LinKind == OMPC_LINEAR_uval) 15715 InitExpr = VD ? VD->getInit() : SimpleRefExpr; 15716 else 15717 InitExpr = VD ? SimpleRefExpr : Ref; 15718 AddInitializerToDecl(Init, DefaultLvalueConversion(InitExpr).get(), 15719 /*DirectInit=*/false); 15720 DeclRefExpr *InitRef = buildDeclRefExpr(*this, Init, Type, ELoc); 15721 15722 DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_linear, Ref); 15723 Vars.push_back((VD || CurContext->isDependentContext()) 15724 ? RefExpr->IgnoreParens() 15725 : Ref); 15726 Privates.push_back(PrivateRef); 15727 Inits.push_back(InitRef); 15728 } 15729 15730 if (Vars.empty()) 15731 return nullptr; 15732 15733 Expr *StepExpr = Step; 15734 Expr *CalcStepExpr = nullptr; 15735 if (Step && !Step->isValueDependent() && !Step->isTypeDependent() && 15736 !Step->isInstantiationDependent() && 15737 !Step->containsUnexpandedParameterPack()) { 15738 SourceLocation StepLoc = Step->getBeginLoc(); 15739 ExprResult Val = PerformOpenMPImplicitIntegerConversion(StepLoc, Step); 15740 if (Val.isInvalid()) 15741 return nullptr; 15742 StepExpr = Val.get(); 15743 15744 // Build var to save the step value. 15745 VarDecl *SaveVar = 15746 buildVarDecl(*this, StepLoc, StepExpr->getType(), ".linear.step"); 15747 ExprResult SaveRef = 15748 buildDeclRefExpr(*this, SaveVar, StepExpr->getType(), StepLoc); 15749 ExprResult CalcStep = 15750 BuildBinOp(CurScope, StepLoc, BO_Assign, SaveRef.get(), StepExpr); 15751 CalcStep = ActOnFinishFullExpr(CalcStep.get(), /*DiscardedValue*/ false); 15752 15753 // Warn about zero linear step (it would be probably better specified as 15754 // making corresponding variables 'const'). 15755 if (Optional<llvm::APSInt> Result = 15756 StepExpr->getIntegerConstantExpr(Context)) { 15757 if (!Result->isNegative() && !Result->isStrictlyPositive()) 15758 Diag(StepLoc, diag::warn_omp_linear_step_zero) 15759 << Vars[0] << (Vars.size() > 1); 15760 } else if (CalcStep.isUsable()) { 15761 // Calculate the step beforehand instead of doing this on each iteration. 15762 // (This is not used if the number of iterations may be kfold-ed). 15763 CalcStepExpr = CalcStep.get(); 15764 } 15765 } 15766 15767 return OMPLinearClause::Create(Context, StartLoc, LParenLoc, LinKind, LinLoc, 15768 ColonLoc, EndLoc, Vars, Privates, Inits, 15769 StepExpr, CalcStepExpr, 15770 buildPreInits(Context, ExprCaptures), 15771 buildPostUpdate(*this, ExprPostUpdates)); 15772 } 15773 15774 static bool FinishOpenMPLinearClause(OMPLinearClause &Clause, DeclRefExpr *IV, 15775 Expr *NumIterations, Sema &SemaRef, 15776 Scope *S, DSAStackTy *Stack) { 15777 // Walk the vars and build update/final expressions for the CodeGen. 15778 SmallVector<Expr *, 8> Updates; 15779 SmallVector<Expr *, 8> Finals; 15780 SmallVector<Expr *, 8> UsedExprs; 15781 Expr *Step = Clause.getStep(); 15782 Expr *CalcStep = Clause.getCalcStep(); 15783 // OpenMP [2.14.3.7, linear clause] 15784 // If linear-step is not specified it is assumed to be 1. 15785 if (!Step) 15786 Step = SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get(); 15787 else if (CalcStep) 15788 Step = cast<BinaryOperator>(CalcStep)->getLHS(); 15789 bool HasErrors = false; 15790 auto CurInit = Clause.inits().begin(); 15791 auto CurPrivate = Clause.privates().begin(); 15792 OpenMPLinearClauseKind LinKind = Clause.getModifier(); 15793 for (Expr *RefExpr : Clause.varlists()) { 15794 SourceLocation ELoc; 15795 SourceRange ERange; 15796 Expr *SimpleRefExpr = RefExpr; 15797 auto Res = getPrivateItem(SemaRef, SimpleRefExpr, ELoc, ERange); 15798 ValueDecl *D = Res.first; 15799 if (Res.second || !D) { 15800 Updates.push_back(nullptr); 15801 Finals.push_back(nullptr); 15802 HasErrors = true; 15803 continue; 15804 } 15805 auto &&Info = Stack->isLoopControlVariable(D); 15806 // OpenMP [2.15.11, distribute simd Construct] 15807 // A list item may not appear in a linear clause, unless it is the loop 15808 // iteration variable. 15809 if (isOpenMPDistributeDirective(Stack->getCurrentDirective()) && 15810 isOpenMPSimdDirective(Stack->getCurrentDirective()) && !Info.first) { 15811 SemaRef.Diag(ELoc, 15812 diag::err_omp_linear_distribute_var_non_loop_iteration); 15813 Updates.push_back(nullptr); 15814 Finals.push_back(nullptr); 15815 HasErrors = true; 15816 continue; 15817 } 15818 Expr *InitExpr = *CurInit; 15819 15820 // Build privatized reference to the current linear var. 15821 auto *DE = cast<DeclRefExpr>(SimpleRefExpr); 15822 Expr *CapturedRef; 15823 if (LinKind == OMPC_LINEAR_uval) 15824 CapturedRef = cast<VarDecl>(DE->getDecl())->getInit(); 15825 else 15826 CapturedRef = 15827 buildDeclRefExpr(SemaRef, cast<VarDecl>(DE->getDecl()), 15828 DE->getType().getUnqualifiedType(), DE->getExprLoc(), 15829 /*RefersToCapture=*/true); 15830 15831 // Build update: Var = InitExpr + IV * Step 15832 ExprResult Update; 15833 if (!Info.first) 15834 Update = buildCounterUpdate( 15835 SemaRef, S, RefExpr->getExprLoc(), *CurPrivate, InitExpr, IV, Step, 15836 /*Subtract=*/false, /*IsNonRectangularLB=*/false); 15837 else 15838 Update = *CurPrivate; 15839 Update = SemaRef.ActOnFinishFullExpr(Update.get(), DE->getBeginLoc(), 15840 /*DiscardedValue*/ false); 15841 15842 // Build final: Var = InitExpr + NumIterations * Step 15843 ExprResult Final; 15844 if (!Info.first) 15845 Final = 15846 buildCounterUpdate(SemaRef, S, RefExpr->getExprLoc(), CapturedRef, 15847 InitExpr, NumIterations, Step, /*Subtract=*/false, 15848 /*IsNonRectangularLB=*/false); 15849 else 15850 Final = *CurPrivate; 15851 Final = SemaRef.ActOnFinishFullExpr(Final.get(), DE->getBeginLoc(), 15852 /*DiscardedValue*/ false); 15853 15854 if (!Update.isUsable() || !Final.isUsable()) { 15855 Updates.push_back(nullptr); 15856 Finals.push_back(nullptr); 15857 UsedExprs.push_back(nullptr); 15858 HasErrors = true; 15859 } else { 15860 Updates.push_back(Update.get()); 15861 Finals.push_back(Final.get()); 15862 if (!Info.first) 15863 UsedExprs.push_back(SimpleRefExpr); 15864 } 15865 ++CurInit; 15866 ++CurPrivate; 15867 } 15868 if (Expr *S = Clause.getStep()) 15869 UsedExprs.push_back(S); 15870 // Fill the remaining part with the nullptr. 15871 UsedExprs.append(Clause.varlist_size() + 1 - UsedExprs.size(), nullptr); 15872 Clause.setUpdates(Updates); 15873 Clause.setFinals(Finals); 15874 Clause.setUsedExprs(UsedExprs); 15875 return HasErrors; 15876 } 15877 15878 OMPClause *Sema::ActOnOpenMPAlignedClause( 15879 ArrayRef<Expr *> VarList, Expr *Alignment, SourceLocation StartLoc, 15880 SourceLocation LParenLoc, SourceLocation ColonLoc, SourceLocation EndLoc) { 15881 SmallVector<Expr *, 8> Vars; 15882 for (Expr *RefExpr : VarList) { 15883 assert(RefExpr && "NULL expr in OpenMP linear clause."); 15884 SourceLocation ELoc; 15885 SourceRange ERange; 15886 Expr *SimpleRefExpr = RefExpr; 15887 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange); 15888 if (Res.second) { 15889 // It will be analyzed later. 15890 Vars.push_back(RefExpr); 15891 } 15892 ValueDecl *D = Res.first; 15893 if (!D) 15894 continue; 15895 15896 QualType QType = D->getType(); 15897 auto *VD = dyn_cast<VarDecl>(D); 15898 15899 // OpenMP [2.8.1, simd construct, Restrictions] 15900 // The type of list items appearing in the aligned clause must be 15901 // array, pointer, reference to array, or reference to pointer. 15902 QType = QType.getNonReferenceType().getUnqualifiedType().getCanonicalType(); 15903 const Type *Ty = QType.getTypePtrOrNull(); 15904 if (!Ty || (!Ty->isArrayType() && !Ty->isPointerType())) { 15905 Diag(ELoc, diag::err_omp_aligned_expected_array_or_ptr) 15906 << QType << getLangOpts().CPlusPlus << ERange; 15907 bool IsDecl = 15908 !VD || 15909 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly; 15910 Diag(D->getLocation(), 15911 IsDecl ? diag::note_previous_decl : diag::note_defined_here) 15912 << D; 15913 continue; 15914 } 15915 15916 // OpenMP [2.8.1, simd construct, Restrictions] 15917 // A list-item cannot appear in more than one aligned clause. 15918 if (const Expr *PrevRef = DSAStack->addUniqueAligned(D, SimpleRefExpr)) { 15919 Diag(ELoc, diag::err_omp_used_in_clause_twice) 15920 << 0 << getOpenMPClauseName(OMPC_aligned) << ERange; 15921 Diag(PrevRef->getExprLoc(), diag::note_omp_explicit_dsa) 15922 << getOpenMPClauseName(OMPC_aligned); 15923 continue; 15924 } 15925 15926 DeclRefExpr *Ref = nullptr; 15927 if (!VD && isOpenMPCapturedDecl(D)) 15928 Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/true); 15929 Vars.push_back(DefaultFunctionArrayConversion( 15930 (VD || !Ref) ? RefExpr->IgnoreParens() : Ref) 15931 .get()); 15932 } 15933 15934 // OpenMP [2.8.1, simd construct, Description] 15935 // The parameter of the aligned clause, alignment, must be a constant 15936 // positive integer expression. 15937 // If no optional parameter is specified, implementation-defined default 15938 // alignments for SIMD instructions on the target platforms are assumed. 15939 if (Alignment != nullptr) { 15940 ExprResult AlignResult = 15941 VerifyPositiveIntegerConstantInClause(Alignment, OMPC_aligned); 15942 if (AlignResult.isInvalid()) 15943 return nullptr; 15944 Alignment = AlignResult.get(); 15945 } 15946 if (Vars.empty()) 15947 return nullptr; 15948 15949 return OMPAlignedClause::Create(Context, StartLoc, LParenLoc, ColonLoc, 15950 EndLoc, Vars, Alignment); 15951 } 15952 15953 OMPClause *Sema::ActOnOpenMPCopyinClause(ArrayRef<Expr *> VarList, 15954 SourceLocation StartLoc, 15955 SourceLocation LParenLoc, 15956 SourceLocation EndLoc) { 15957 SmallVector<Expr *, 8> Vars; 15958 SmallVector<Expr *, 8> SrcExprs; 15959 SmallVector<Expr *, 8> DstExprs; 15960 SmallVector<Expr *, 8> AssignmentOps; 15961 for (Expr *RefExpr : VarList) { 15962 assert(RefExpr && "NULL expr in OpenMP copyin clause."); 15963 if (isa<DependentScopeDeclRefExpr>(RefExpr)) { 15964 // It will be analyzed later. 15965 Vars.push_back(RefExpr); 15966 SrcExprs.push_back(nullptr); 15967 DstExprs.push_back(nullptr); 15968 AssignmentOps.push_back(nullptr); 15969 continue; 15970 } 15971 15972 SourceLocation ELoc = RefExpr->getExprLoc(); 15973 // OpenMP [2.1, C/C++] 15974 // A list item is a variable name. 15975 // OpenMP [2.14.4.1, Restrictions, p.1] 15976 // A list item that appears in a copyin clause must be threadprivate. 15977 auto *DE = dyn_cast<DeclRefExpr>(RefExpr); 15978 if (!DE || !isa<VarDecl>(DE->getDecl())) { 15979 Diag(ELoc, diag::err_omp_expected_var_name_member_expr) 15980 << 0 << RefExpr->getSourceRange(); 15981 continue; 15982 } 15983 15984 Decl *D = DE->getDecl(); 15985 auto *VD = cast<VarDecl>(D); 15986 15987 QualType Type = VD->getType(); 15988 if (Type->isDependentType() || Type->isInstantiationDependentType()) { 15989 // It will be analyzed later. 15990 Vars.push_back(DE); 15991 SrcExprs.push_back(nullptr); 15992 DstExprs.push_back(nullptr); 15993 AssignmentOps.push_back(nullptr); 15994 continue; 15995 } 15996 15997 // OpenMP [2.14.4.1, Restrictions, C/C++, p.1] 15998 // A list item that appears in a copyin clause must be threadprivate. 15999 if (!DSAStack->isThreadPrivate(VD)) { 16000 Diag(ELoc, diag::err_omp_required_access) 16001 << getOpenMPClauseName(OMPC_copyin) 16002 << getOpenMPDirectiveName(OMPD_threadprivate); 16003 continue; 16004 } 16005 16006 // OpenMP [2.14.4.1, Restrictions, C/C++, p.2] 16007 // A variable of class type (or array thereof) that appears in a 16008 // copyin clause requires an accessible, unambiguous copy assignment 16009 // operator for the class type. 16010 QualType ElemType = Context.getBaseElementType(Type).getNonReferenceType(); 16011 VarDecl *SrcVD = 16012 buildVarDecl(*this, DE->getBeginLoc(), ElemType.getUnqualifiedType(), 16013 ".copyin.src", VD->hasAttrs() ? &VD->getAttrs() : nullptr); 16014 DeclRefExpr *PseudoSrcExpr = buildDeclRefExpr( 16015 *this, SrcVD, ElemType.getUnqualifiedType(), DE->getExprLoc()); 16016 VarDecl *DstVD = 16017 buildVarDecl(*this, DE->getBeginLoc(), ElemType, ".copyin.dst", 16018 VD->hasAttrs() ? &VD->getAttrs() : nullptr); 16019 DeclRefExpr *PseudoDstExpr = 16020 buildDeclRefExpr(*this, DstVD, ElemType, DE->getExprLoc()); 16021 // For arrays generate assignment operation for single element and replace 16022 // it by the original array element in CodeGen. 16023 ExprResult AssignmentOp = 16024 BuildBinOp(/*S=*/nullptr, DE->getExprLoc(), BO_Assign, PseudoDstExpr, 16025 PseudoSrcExpr); 16026 if (AssignmentOp.isInvalid()) 16027 continue; 16028 AssignmentOp = ActOnFinishFullExpr(AssignmentOp.get(), DE->getExprLoc(), 16029 /*DiscardedValue*/ false); 16030 if (AssignmentOp.isInvalid()) 16031 continue; 16032 16033 DSAStack->addDSA(VD, DE, OMPC_copyin); 16034 Vars.push_back(DE); 16035 SrcExprs.push_back(PseudoSrcExpr); 16036 DstExprs.push_back(PseudoDstExpr); 16037 AssignmentOps.push_back(AssignmentOp.get()); 16038 } 16039 16040 if (Vars.empty()) 16041 return nullptr; 16042 16043 return OMPCopyinClause::Create(Context, StartLoc, LParenLoc, EndLoc, Vars, 16044 SrcExprs, DstExprs, AssignmentOps); 16045 } 16046 16047 OMPClause *Sema::ActOnOpenMPCopyprivateClause(ArrayRef<Expr *> VarList, 16048 SourceLocation StartLoc, 16049 SourceLocation LParenLoc, 16050 SourceLocation EndLoc) { 16051 SmallVector<Expr *, 8> Vars; 16052 SmallVector<Expr *, 8> SrcExprs; 16053 SmallVector<Expr *, 8> DstExprs; 16054 SmallVector<Expr *, 8> AssignmentOps; 16055 for (Expr *RefExpr : VarList) { 16056 assert(RefExpr && "NULL expr in OpenMP linear clause."); 16057 SourceLocation ELoc; 16058 SourceRange ERange; 16059 Expr *SimpleRefExpr = RefExpr; 16060 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange); 16061 if (Res.second) { 16062 // It will be analyzed later. 16063 Vars.push_back(RefExpr); 16064 SrcExprs.push_back(nullptr); 16065 DstExprs.push_back(nullptr); 16066 AssignmentOps.push_back(nullptr); 16067 } 16068 ValueDecl *D = Res.first; 16069 if (!D) 16070 continue; 16071 16072 QualType Type = D->getType(); 16073 auto *VD = dyn_cast<VarDecl>(D); 16074 16075 // OpenMP [2.14.4.2, Restrictions, p.2] 16076 // A list item that appears in a copyprivate clause may not appear in a 16077 // private or firstprivate clause on the single construct. 16078 if (!VD || !DSAStack->isThreadPrivate(VD)) { 16079 DSAStackTy::DSAVarData DVar = 16080 DSAStack->getTopDSA(D, /*FromParent=*/false); 16081 if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_copyprivate && 16082 DVar.RefExpr) { 16083 Diag(ELoc, diag::err_omp_wrong_dsa) 16084 << getOpenMPClauseName(DVar.CKind) 16085 << getOpenMPClauseName(OMPC_copyprivate); 16086 reportOriginalDsa(*this, DSAStack, D, DVar); 16087 continue; 16088 } 16089 16090 // OpenMP [2.11.4.2, Restrictions, p.1] 16091 // All list items that appear in a copyprivate clause must be either 16092 // threadprivate or private in the enclosing context. 16093 if (DVar.CKind == OMPC_unknown) { 16094 DVar = DSAStack->getImplicitDSA(D, false); 16095 if (DVar.CKind == OMPC_shared) { 16096 Diag(ELoc, diag::err_omp_required_access) 16097 << getOpenMPClauseName(OMPC_copyprivate) 16098 << "threadprivate or private in the enclosing context"; 16099 reportOriginalDsa(*this, DSAStack, D, DVar); 16100 continue; 16101 } 16102 } 16103 } 16104 16105 // Variably modified types are not supported. 16106 if (!Type->isAnyPointerType() && Type->isVariablyModifiedType()) { 16107 Diag(ELoc, diag::err_omp_variably_modified_type_not_supported) 16108 << getOpenMPClauseName(OMPC_copyprivate) << Type 16109 << getOpenMPDirectiveName(DSAStack->getCurrentDirective()); 16110 bool IsDecl = 16111 !VD || 16112 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly; 16113 Diag(D->getLocation(), 16114 IsDecl ? diag::note_previous_decl : diag::note_defined_here) 16115 << D; 16116 continue; 16117 } 16118 16119 // OpenMP [2.14.4.1, Restrictions, C/C++, p.2] 16120 // A variable of class type (or array thereof) that appears in a 16121 // copyin clause requires an accessible, unambiguous copy assignment 16122 // operator for the class type. 16123 Type = Context.getBaseElementType(Type.getNonReferenceType()) 16124 .getUnqualifiedType(); 16125 VarDecl *SrcVD = 16126 buildVarDecl(*this, RefExpr->getBeginLoc(), Type, ".copyprivate.src", 16127 D->hasAttrs() ? &D->getAttrs() : nullptr); 16128 DeclRefExpr *PseudoSrcExpr = buildDeclRefExpr(*this, SrcVD, Type, ELoc); 16129 VarDecl *DstVD = 16130 buildVarDecl(*this, RefExpr->getBeginLoc(), Type, ".copyprivate.dst", 16131 D->hasAttrs() ? &D->getAttrs() : nullptr); 16132 DeclRefExpr *PseudoDstExpr = buildDeclRefExpr(*this, DstVD, Type, ELoc); 16133 ExprResult AssignmentOp = BuildBinOp( 16134 DSAStack->getCurScope(), ELoc, BO_Assign, PseudoDstExpr, PseudoSrcExpr); 16135 if (AssignmentOp.isInvalid()) 16136 continue; 16137 AssignmentOp = 16138 ActOnFinishFullExpr(AssignmentOp.get(), ELoc, /*DiscardedValue*/ false); 16139 if (AssignmentOp.isInvalid()) 16140 continue; 16141 16142 // No need to mark vars as copyprivate, they are already threadprivate or 16143 // implicitly private. 16144 assert(VD || isOpenMPCapturedDecl(D)); 16145 Vars.push_back( 16146 VD ? RefExpr->IgnoreParens() 16147 : buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/false)); 16148 SrcExprs.push_back(PseudoSrcExpr); 16149 DstExprs.push_back(PseudoDstExpr); 16150 AssignmentOps.push_back(AssignmentOp.get()); 16151 } 16152 16153 if (Vars.empty()) 16154 return nullptr; 16155 16156 return OMPCopyprivateClause::Create(Context, StartLoc, LParenLoc, EndLoc, 16157 Vars, SrcExprs, DstExprs, AssignmentOps); 16158 } 16159 16160 OMPClause *Sema::ActOnOpenMPFlushClause(ArrayRef<Expr *> VarList, 16161 SourceLocation StartLoc, 16162 SourceLocation LParenLoc, 16163 SourceLocation EndLoc) { 16164 if (VarList.empty()) 16165 return nullptr; 16166 16167 return OMPFlushClause::Create(Context, StartLoc, LParenLoc, EndLoc, VarList); 16168 } 16169 16170 /// Tries to find omp_depend_t. type. 16171 static bool findOMPDependT(Sema &S, SourceLocation Loc, DSAStackTy *Stack, 16172 bool Diagnose = true) { 16173 QualType OMPDependT = Stack->getOMPDependT(); 16174 if (!OMPDependT.isNull()) 16175 return true; 16176 IdentifierInfo *II = &S.PP.getIdentifierTable().get("omp_depend_t"); 16177 ParsedType PT = S.getTypeName(*II, Loc, S.getCurScope()); 16178 if (!PT.getAsOpaquePtr() || PT.get().isNull()) { 16179 if (Diagnose) 16180 S.Diag(Loc, diag::err_omp_implied_type_not_found) << "omp_depend_t"; 16181 return false; 16182 } 16183 Stack->setOMPDependT(PT.get()); 16184 return true; 16185 } 16186 16187 OMPClause *Sema::ActOnOpenMPDepobjClause(Expr *Depobj, SourceLocation StartLoc, 16188 SourceLocation LParenLoc, 16189 SourceLocation EndLoc) { 16190 if (!Depobj) 16191 return nullptr; 16192 16193 bool OMPDependTFound = findOMPDependT(*this, StartLoc, DSAStack); 16194 16195 // OpenMP 5.0, 2.17.10.1 depobj Construct 16196 // depobj is an lvalue expression of type omp_depend_t. 16197 if (!Depobj->isTypeDependent() && !Depobj->isValueDependent() && 16198 !Depobj->isInstantiationDependent() && 16199 !Depobj->containsUnexpandedParameterPack() && 16200 (OMPDependTFound && 16201 !Context.typesAreCompatible(DSAStack->getOMPDependT(), Depobj->getType(), 16202 /*CompareUnqualified=*/true))) { 16203 Diag(Depobj->getExprLoc(), diag::err_omp_expected_omp_depend_t_lvalue) 16204 << 0 << Depobj->getType() << Depobj->getSourceRange(); 16205 } 16206 16207 if (!Depobj->isLValue()) { 16208 Diag(Depobj->getExprLoc(), diag::err_omp_expected_omp_depend_t_lvalue) 16209 << 1 << Depobj->getSourceRange(); 16210 } 16211 16212 return OMPDepobjClause::Create(Context, StartLoc, LParenLoc, EndLoc, Depobj); 16213 } 16214 16215 OMPClause * 16216 Sema::ActOnOpenMPDependClause(Expr *DepModifier, OpenMPDependClauseKind DepKind, 16217 SourceLocation DepLoc, SourceLocation ColonLoc, 16218 ArrayRef<Expr *> VarList, SourceLocation StartLoc, 16219 SourceLocation LParenLoc, SourceLocation EndLoc) { 16220 if (DSAStack->getCurrentDirective() == OMPD_ordered && 16221 DepKind != OMPC_DEPEND_source && DepKind != OMPC_DEPEND_sink) { 16222 Diag(DepLoc, diag::err_omp_unexpected_clause_value) 16223 << "'source' or 'sink'" << getOpenMPClauseName(OMPC_depend); 16224 return nullptr; 16225 } 16226 if ((DSAStack->getCurrentDirective() != OMPD_ordered || 16227 DSAStack->getCurrentDirective() == OMPD_depobj) && 16228 (DepKind == OMPC_DEPEND_unknown || DepKind == OMPC_DEPEND_source || 16229 DepKind == OMPC_DEPEND_sink || 16230 ((LangOpts.OpenMP < 50 || 16231 DSAStack->getCurrentDirective() == OMPD_depobj) && 16232 DepKind == OMPC_DEPEND_depobj))) { 16233 SmallVector<unsigned, 3> Except; 16234 Except.push_back(OMPC_DEPEND_source); 16235 Except.push_back(OMPC_DEPEND_sink); 16236 if (LangOpts.OpenMP < 50 || DSAStack->getCurrentDirective() == OMPD_depobj) 16237 Except.push_back(OMPC_DEPEND_depobj); 16238 std::string Expected = (LangOpts.OpenMP >= 50 && !DepModifier) 16239 ? "depend modifier(iterator) or " 16240 : ""; 16241 Diag(DepLoc, diag::err_omp_unexpected_clause_value) 16242 << Expected + getListOfPossibleValues(OMPC_depend, /*First=*/0, 16243 /*Last=*/OMPC_DEPEND_unknown, 16244 Except) 16245 << getOpenMPClauseName(OMPC_depend); 16246 return nullptr; 16247 } 16248 if (DepModifier && 16249 (DepKind == OMPC_DEPEND_source || DepKind == OMPC_DEPEND_sink)) { 16250 Diag(DepModifier->getExprLoc(), 16251 diag::err_omp_depend_sink_source_with_modifier); 16252 return nullptr; 16253 } 16254 if (DepModifier && 16255 !DepModifier->getType()->isSpecificBuiltinType(BuiltinType::OMPIterator)) 16256 Diag(DepModifier->getExprLoc(), diag::err_omp_depend_modifier_not_iterator); 16257 16258 SmallVector<Expr *, 8> Vars; 16259 DSAStackTy::OperatorOffsetTy OpsOffs; 16260 llvm::APSInt DepCounter(/*BitWidth=*/32); 16261 llvm::APSInt TotalDepCount(/*BitWidth=*/32); 16262 if (DepKind == OMPC_DEPEND_sink || DepKind == OMPC_DEPEND_source) { 16263 if (const Expr *OrderedCountExpr = 16264 DSAStack->getParentOrderedRegionParam().first) { 16265 TotalDepCount = OrderedCountExpr->EvaluateKnownConstInt(Context); 16266 TotalDepCount.setIsUnsigned(/*Val=*/true); 16267 } 16268 } 16269 for (Expr *RefExpr : VarList) { 16270 assert(RefExpr && "NULL expr in OpenMP shared clause."); 16271 if (isa<DependentScopeDeclRefExpr>(RefExpr)) { 16272 // It will be analyzed later. 16273 Vars.push_back(RefExpr); 16274 continue; 16275 } 16276 16277 SourceLocation ELoc = RefExpr->getExprLoc(); 16278 Expr *SimpleExpr = RefExpr->IgnoreParenCasts(); 16279 if (DepKind == OMPC_DEPEND_sink) { 16280 if (DSAStack->getParentOrderedRegionParam().first && 16281 DepCounter >= TotalDepCount) { 16282 Diag(ELoc, diag::err_omp_depend_sink_unexpected_expr); 16283 continue; 16284 } 16285 ++DepCounter; 16286 // OpenMP [2.13.9, Summary] 16287 // depend(dependence-type : vec), where dependence-type is: 16288 // 'sink' and where vec is the iteration vector, which has the form: 16289 // x1 [+- d1], x2 [+- d2 ], . . . , xn [+- dn] 16290 // where n is the value specified by the ordered clause in the loop 16291 // directive, xi denotes the loop iteration variable of the i-th nested 16292 // loop associated with the loop directive, and di is a constant 16293 // non-negative integer. 16294 if (CurContext->isDependentContext()) { 16295 // It will be analyzed later. 16296 Vars.push_back(RefExpr); 16297 continue; 16298 } 16299 SimpleExpr = SimpleExpr->IgnoreImplicit(); 16300 OverloadedOperatorKind OOK = OO_None; 16301 SourceLocation OOLoc; 16302 Expr *LHS = SimpleExpr; 16303 Expr *RHS = nullptr; 16304 if (auto *BO = dyn_cast<BinaryOperator>(SimpleExpr)) { 16305 OOK = BinaryOperator::getOverloadedOperator(BO->getOpcode()); 16306 OOLoc = BO->getOperatorLoc(); 16307 LHS = BO->getLHS()->IgnoreParenImpCasts(); 16308 RHS = BO->getRHS()->IgnoreParenImpCasts(); 16309 } else if (auto *OCE = dyn_cast<CXXOperatorCallExpr>(SimpleExpr)) { 16310 OOK = OCE->getOperator(); 16311 OOLoc = OCE->getOperatorLoc(); 16312 LHS = OCE->getArg(/*Arg=*/0)->IgnoreParenImpCasts(); 16313 RHS = OCE->getArg(/*Arg=*/1)->IgnoreParenImpCasts(); 16314 } else if (auto *MCE = dyn_cast<CXXMemberCallExpr>(SimpleExpr)) { 16315 OOK = MCE->getMethodDecl() 16316 ->getNameInfo() 16317 .getName() 16318 .getCXXOverloadedOperator(); 16319 OOLoc = MCE->getCallee()->getExprLoc(); 16320 LHS = MCE->getImplicitObjectArgument()->IgnoreParenImpCasts(); 16321 RHS = MCE->getArg(/*Arg=*/0)->IgnoreParenImpCasts(); 16322 } 16323 SourceLocation ELoc; 16324 SourceRange ERange; 16325 auto Res = getPrivateItem(*this, LHS, ELoc, ERange); 16326 if (Res.second) { 16327 // It will be analyzed later. 16328 Vars.push_back(RefExpr); 16329 } 16330 ValueDecl *D = Res.first; 16331 if (!D) 16332 continue; 16333 16334 if (OOK != OO_Plus && OOK != OO_Minus && (RHS || OOK != OO_None)) { 16335 Diag(OOLoc, diag::err_omp_depend_sink_expected_plus_minus); 16336 continue; 16337 } 16338 if (RHS) { 16339 ExprResult RHSRes = VerifyPositiveIntegerConstantInClause( 16340 RHS, OMPC_depend, /*StrictlyPositive=*/false); 16341 if (RHSRes.isInvalid()) 16342 continue; 16343 } 16344 if (!CurContext->isDependentContext() && 16345 DSAStack->getParentOrderedRegionParam().first && 16346 DepCounter != DSAStack->isParentLoopControlVariable(D).first) { 16347 const ValueDecl *VD = 16348 DSAStack->getParentLoopControlVariable(DepCounter.getZExtValue()); 16349 if (VD) 16350 Diag(ELoc, diag::err_omp_depend_sink_expected_loop_iteration) 16351 << 1 << VD; 16352 else 16353 Diag(ELoc, diag::err_omp_depend_sink_expected_loop_iteration) << 0; 16354 continue; 16355 } 16356 OpsOffs.emplace_back(RHS, OOK); 16357 } else { 16358 bool OMPDependTFound = LangOpts.OpenMP >= 50; 16359 if (OMPDependTFound) 16360 OMPDependTFound = findOMPDependT(*this, StartLoc, DSAStack, 16361 DepKind == OMPC_DEPEND_depobj); 16362 if (DepKind == OMPC_DEPEND_depobj) { 16363 // OpenMP 5.0, 2.17.11 depend Clause, Restrictions, C/C++ 16364 // List items used in depend clauses with the depobj dependence type 16365 // must be expressions of the omp_depend_t type. 16366 if (!RefExpr->isValueDependent() && !RefExpr->isTypeDependent() && 16367 !RefExpr->isInstantiationDependent() && 16368 !RefExpr->containsUnexpandedParameterPack() && 16369 (OMPDependTFound && 16370 !Context.hasSameUnqualifiedType(DSAStack->getOMPDependT(), 16371 RefExpr->getType()))) { 16372 Diag(ELoc, diag::err_omp_expected_omp_depend_t_lvalue) 16373 << 0 << RefExpr->getType() << RefExpr->getSourceRange(); 16374 continue; 16375 } 16376 if (!RefExpr->isLValue()) { 16377 Diag(ELoc, diag::err_omp_expected_omp_depend_t_lvalue) 16378 << 1 << RefExpr->getType() << RefExpr->getSourceRange(); 16379 continue; 16380 } 16381 } else { 16382 // OpenMP 5.0 [2.17.11, Restrictions] 16383 // List items used in depend clauses cannot be zero-length array 16384 // sections. 16385 QualType ExprTy = RefExpr->getType().getNonReferenceType(); 16386 const auto *OASE = dyn_cast<OMPArraySectionExpr>(SimpleExpr); 16387 if (OASE) { 16388 QualType BaseType = 16389 OMPArraySectionExpr::getBaseOriginalType(OASE->getBase()); 16390 if (const auto *ATy = BaseType->getAsArrayTypeUnsafe()) 16391 ExprTy = ATy->getElementType(); 16392 else 16393 ExprTy = BaseType->getPointeeType(); 16394 ExprTy = ExprTy.getNonReferenceType(); 16395 const Expr *Length = OASE->getLength(); 16396 Expr::EvalResult Result; 16397 if (Length && !Length->isValueDependent() && 16398 Length->EvaluateAsInt(Result, Context) && 16399 Result.Val.getInt().isNullValue()) { 16400 Diag(ELoc, 16401 diag::err_omp_depend_zero_length_array_section_not_allowed) 16402 << SimpleExpr->getSourceRange(); 16403 continue; 16404 } 16405 } 16406 16407 // OpenMP 5.0, 2.17.11 depend Clause, Restrictions, C/C++ 16408 // List items used in depend clauses with the in, out, inout or 16409 // mutexinoutset dependence types cannot be expressions of the 16410 // omp_depend_t type. 16411 if (!RefExpr->isValueDependent() && !RefExpr->isTypeDependent() && 16412 !RefExpr->isInstantiationDependent() && 16413 !RefExpr->containsUnexpandedParameterPack() && 16414 (OMPDependTFound && 16415 DSAStack->getOMPDependT().getTypePtr() == ExprTy.getTypePtr())) { 16416 Diag(ELoc, diag::err_omp_expected_addressable_lvalue_or_array_item) 16417 << (LangOpts.OpenMP >= 50 ? 1 : 0) << 1 16418 << RefExpr->getSourceRange(); 16419 continue; 16420 } 16421 16422 auto *ASE = dyn_cast<ArraySubscriptExpr>(SimpleExpr); 16423 if (!RefExpr->IgnoreParenImpCasts()->isLValue() || 16424 (ASE && !ASE->getBase()->isTypeDependent() && 16425 !ASE->getBase() 16426 ->getType() 16427 .getNonReferenceType() 16428 ->isPointerType() && 16429 !ASE->getBase()->getType().getNonReferenceType()->isArrayType())) { 16430 Diag(ELoc, diag::err_omp_expected_addressable_lvalue_or_array_item) 16431 << (LangOpts.OpenMP >= 50 ? 1 : 0) 16432 << (LangOpts.OpenMP >= 50 ? 1 : 0) << RefExpr->getSourceRange(); 16433 continue; 16434 } 16435 16436 ExprResult Res; 16437 { 16438 Sema::TentativeAnalysisScope Trap(*this); 16439 Res = CreateBuiltinUnaryOp(ELoc, UO_AddrOf, 16440 RefExpr->IgnoreParenImpCasts()); 16441 } 16442 if (!Res.isUsable() && !isa<OMPArraySectionExpr>(SimpleExpr) && 16443 !isa<OMPArrayShapingExpr>(SimpleExpr)) { 16444 Diag(ELoc, diag::err_omp_expected_addressable_lvalue_or_array_item) 16445 << (LangOpts.OpenMP >= 50 ? 1 : 0) 16446 << (LangOpts.OpenMP >= 50 ? 1 : 0) << RefExpr->getSourceRange(); 16447 continue; 16448 } 16449 } 16450 } 16451 Vars.push_back(RefExpr->IgnoreParenImpCasts()); 16452 } 16453 16454 if (!CurContext->isDependentContext() && DepKind == OMPC_DEPEND_sink && 16455 TotalDepCount > VarList.size() && 16456 DSAStack->getParentOrderedRegionParam().first && 16457 DSAStack->getParentLoopControlVariable(VarList.size() + 1)) { 16458 Diag(EndLoc, diag::err_omp_depend_sink_expected_loop_iteration) 16459 << 1 << DSAStack->getParentLoopControlVariable(VarList.size() + 1); 16460 } 16461 if (DepKind != OMPC_DEPEND_source && DepKind != OMPC_DEPEND_sink && 16462 Vars.empty()) 16463 return nullptr; 16464 16465 auto *C = OMPDependClause::Create(Context, StartLoc, LParenLoc, EndLoc, 16466 DepModifier, DepKind, DepLoc, ColonLoc, 16467 Vars, TotalDepCount.getZExtValue()); 16468 if ((DepKind == OMPC_DEPEND_sink || DepKind == OMPC_DEPEND_source) && 16469 DSAStack->isParentOrderedRegion()) 16470 DSAStack->addDoacrossDependClause(C, OpsOffs); 16471 return C; 16472 } 16473 16474 OMPClause *Sema::ActOnOpenMPDeviceClause(OpenMPDeviceClauseModifier Modifier, 16475 Expr *Device, SourceLocation StartLoc, 16476 SourceLocation LParenLoc, 16477 SourceLocation ModifierLoc, 16478 SourceLocation EndLoc) { 16479 assert((ModifierLoc.isInvalid() || LangOpts.OpenMP >= 50) && 16480 "Unexpected device modifier in OpenMP < 50."); 16481 16482 bool ErrorFound = false; 16483 if (ModifierLoc.isValid() && Modifier == OMPC_DEVICE_unknown) { 16484 std::string Values = 16485 getListOfPossibleValues(OMPC_device, /*First=*/0, OMPC_DEVICE_unknown); 16486 Diag(ModifierLoc, diag::err_omp_unexpected_clause_value) 16487 << Values << getOpenMPClauseName(OMPC_device); 16488 ErrorFound = true; 16489 } 16490 16491 Expr *ValExpr = Device; 16492 Stmt *HelperValStmt = nullptr; 16493 16494 // OpenMP [2.9.1, Restrictions] 16495 // The device expression must evaluate to a non-negative integer value. 16496 ErrorFound = !isNonNegativeIntegerValue(ValExpr, *this, OMPC_device, 16497 /*StrictlyPositive=*/false) || 16498 ErrorFound; 16499 if (ErrorFound) 16500 return nullptr; 16501 16502 OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective(); 16503 OpenMPDirectiveKind CaptureRegion = 16504 getOpenMPCaptureRegionForClause(DKind, OMPC_device, LangOpts.OpenMP); 16505 if (CaptureRegion != OMPD_unknown && !CurContext->isDependentContext()) { 16506 ValExpr = MakeFullExpr(ValExpr).get(); 16507 llvm::MapVector<const Expr *, DeclRefExpr *> Captures; 16508 ValExpr = tryBuildCapture(*this, ValExpr, Captures).get(); 16509 HelperValStmt = buildPreInits(Context, Captures); 16510 } 16511 16512 return new (Context) 16513 OMPDeviceClause(Modifier, ValExpr, HelperValStmt, CaptureRegion, StartLoc, 16514 LParenLoc, ModifierLoc, EndLoc); 16515 } 16516 16517 static bool checkTypeMappable(SourceLocation SL, SourceRange SR, Sema &SemaRef, 16518 DSAStackTy *Stack, QualType QTy, 16519 bool FullCheck = true) { 16520 NamedDecl *ND; 16521 if (QTy->isIncompleteType(&ND)) { 16522 SemaRef.Diag(SL, diag::err_incomplete_type) << QTy << SR; 16523 return false; 16524 } 16525 if (FullCheck && !SemaRef.CurContext->isDependentContext() && 16526 !QTy.isTriviallyCopyableType(SemaRef.Context)) 16527 SemaRef.Diag(SL, diag::warn_omp_non_trivial_type_mapped) << QTy << SR; 16528 return true; 16529 } 16530 16531 /// Return true if it can be proven that the provided array expression 16532 /// (array section or array subscript) does NOT specify the whole size of the 16533 /// array whose base type is \a BaseQTy. 16534 static bool checkArrayExpressionDoesNotReferToWholeSize(Sema &SemaRef, 16535 const Expr *E, 16536 QualType BaseQTy) { 16537 const auto *OASE = dyn_cast<OMPArraySectionExpr>(E); 16538 16539 // If this is an array subscript, it refers to the whole size if the size of 16540 // the dimension is constant and equals 1. Also, an array section assumes the 16541 // format of an array subscript if no colon is used. 16542 if (isa<ArraySubscriptExpr>(E) || 16543 (OASE && OASE->getColonLocFirst().isInvalid())) { 16544 if (const auto *ATy = dyn_cast<ConstantArrayType>(BaseQTy.getTypePtr())) 16545 return ATy->getSize().getSExtValue() != 1; 16546 // Size can't be evaluated statically. 16547 return false; 16548 } 16549 16550 assert(OASE && "Expecting array section if not an array subscript."); 16551 const Expr *LowerBound = OASE->getLowerBound(); 16552 const Expr *Length = OASE->getLength(); 16553 16554 // If there is a lower bound that does not evaluates to zero, we are not 16555 // covering the whole dimension. 16556 if (LowerBound) { 16557 Expr::EvalResult Result; 16558 if (!LowerBound->EvaluateAsInt(Result, SemaRef.getASTContext())) 16559 return false; // Can't get the integer value as a constant. 16560 16561 llvm::APSInt ConstLowerBound = Result.Val.getInt(); 16562 if (ConstLowerBound.getSExtValue()) 16563 return true; 16564 } 16565 16566 // If we don't have a length we covering the whole dimension. 16567 if (!Length) 16568 return false; 16569 16570 // If the base is a pointer, we don't have a way to get the size of the 16571 // pointee. 16572 if (BaseQTy->isPointerType()) 16573 return false; 16574 16575 // We can only check if the length is the same as the size of the dimension 16576 // if we have a constant array. 16577 const auto *CATy = dyn_cast<ConstantArrayType>(BaseQTy.getTypePtr()); 16578 if (!CATy) 16579 return false; 16580 16581 Expr::EvalResult Result; 16582 if (!Length->EvaluateAsInt(Result, SemaRef.getASTContext())) 16583 return false; // Can't get the integer value as a constant. 16584 16585 llvm::APSInt ConstLength = Result.Val.getInt(); 16586 return CATy->getSize().getSExtValue() != ConstLength.getSExtValue(); 16587 } 16588 16589 // Return true if it can be proven that the provided array expression (array 16590 // section or array subscript) does NOT specify a single element of the array 16591 // whose base type is \a BaseQTy. 16592 static bool checkArrayExpressionDoesNotReferToUnitySize(Sema &SemaRef, 16593 const Expr *E, 16594 QualType BaseQTy) { 16595 const auto *OASE = dyn_cast<OMPArraySectionExpr>(E); 16596 16597 // An array subscript always refer to a single element. Also, an array section 16598 // assumes the format of an array subscript if no colon is used. 16599 if (isa<ArraySubscriptExpr>(E) || 16600 (OASE && OASE->getColonLocFirst().isInvalid())) 16601 return false; 16602 16603 assert(OASE && "Expecting array section if not an array subscript."); 16604 const Expr *Length = OASE->getLength(); 16605 16606 // If we don't have a length we have to check if the array has unitary size 16607 // for this dimension. Also, we should always expect a length if the base type 16608 // is pointer. 16609 if (!Length) { 16610 if (const auto *ATy = dyn_cast<ConstantArrayType>(BaseQTy.getTypePtr())) 16611 return ATy->getSize().getSExtValue() != 1; 16612 // We cannot assume anything. 16613 return false; 16614 } 16615 16616 // Check if the length evaluates to 1. 16617 Expr::EvalResult Result; 16618 if (!Length->EvaluateAsInt(Result, SemaRef.getASTContext())) 16619 return false; // Can't get the integer value as a constant. 16620 16621 llvm::APSInt ConstLength = Result.Val.getInt(); 16622 return ConstLength.getSExtValue() != 1; 16623 } 16624 16625 // The base of elements of list in a map clause have to be either: 16626 // - a reference to variable or field. 16627 // - a member expression. 16628 // - an array expression. 16629 // 16630 // E.g. if we have the expression 'r.S.Arr[:12]', we want to retrieve the 16631 // reference to 'r'. 16632 // 16633 // If we have: 16634 // 16635 // struct SS { 16636 // Bla S; 16637 // foo() { 16638 // #pragma omp target map (S.Arr[:12]); 16639 // } 16640 // } 16641 // 16642 // We want to retrieve the member expression 'this->S'; 16643 16644 // OpenMP 5.0 [2.19.7.1, map Clause, Restrictions, p.2] 16645 // If a list item is an array section, it must specify contiguous storage. 16646 // 16647 // For this restriction it is sufficient that we make sure only references 16648 // to variables or fields and array expressions, and that no array sections 16649 // exist except in the rightmost expression (unless they cover the whole 16650 // dimension of the array). E.g. these would be invalid: 16651 // 16652 // r.ArrS[3:5].Arr[6:7] 16653 // 16654 // r.ArrS[3:5].x 16655 // 16656 // but these would be valid: 16657 // r.ArrS[3].Arr[6:7] 16658 // 16659 // r.ArrS[3].x 16660 namespace { 16661 class MapBaseChecker final : public StmtVisitor<MapBaseChecker, bool> { 16662 Sema &SemaRef; 16663 OpenMPClauseKind CKind = OMPC_unknown; 16664 OMPClauseMappableExprCommon::MappableExprComponentList &Components; 16665 bool NoDiagnose = false; 16666 const Expr *RelevantExpr = nullptr; 16667 bool AllowUnitySizeArraySection = true; 16668 bool AllowWholeSizeArraySection = true; 16669 SourceLocation ELoc; 16670 SourceRange ERange; 16671 16672 void emitErrorMsg() { 16673 // If nothing else worked, this is not a valid map clause expression. 16674 if (SemaRef.getLangOpts().OpenMP < 50) { 16675 SemaRef.Diag(ELoc, 16676 diag::err_omp_expected_named_var_member_or_array_expression) 16677 << ERange; 16678 } else { 16679 SemaRef.Diag(ELoc, diag::err_omp_non_lvalue_in_map_or_motion_clauses) 16680 << getOpenMPClauseName(CKind) << ERange; 16681 } 16682 } 16683 16684 public: 16685 bool VisitDeclRefExpr(DeclRefExpr *DRE) { 16686 if (!isa<VarDecl>(DRE->getDecl())) { 16687 emitErrorMsg(); 16688 return false; 16689 } 16690 assert(!RelevantExpr && "RelevantExpr is expected to be nullptr"); 16691 RelevantExpr = DRE; 16692 // Record the component. 16693 Components.emplace_back(DRE, DRE->getDecl()); 16694 return true; 16695 } 16696 16697 bool VisitMemberExpr(MemberExpr *ME) { 16698 Expr *E = ME; 16699 Expr *BaseE = ME->getBase()->IgnoreParenCasts(); 16700 16701 if (isa<CXXThisExpr>(BaseE)) { 16702 assert(!RelevantExpr && "RelevantExpr is expected to be nullptr"); 16703 // We found a base expression: this->Val. 16704 RelevantExpr = ME; 16705 } else { 16706 E = BaseE; 16707 } 16708 16709 if (!isa<FieldDecl>(ME->getMemberDecl())) { 16710 if (!NoDiagnose) { 16711 SemaRef.Diag(ELoc, diag::err_omp_expected_access_to_data_field) 16712 << ME->getSourceRange(); 16713 return false; 16714 } 16715 if (RelevantExpr) 16716 return false; 16717 return Visit(E); 16718 } 16719 16720 auto *FD = cast<FieldDecl>(ME->getMemberDecl()); 16721 16722 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C/C++, p.3] 16723 // A bit-field cannot appear in a map clause. 16724 // 16725 if (FD->isBitField()) { 16726 if (!NoDiagnose) { 16727 SemaRef.Diag(ELoc, diag::err_omp_bit_fields_forbidden_in_clause) 16728 << ME->getSourceRange() << getOpenMPClauseName(CKind); 16729 return false; 16730 } 16731 if (RelevantExpr) 16732 return false; 16733 return Visit(E); 16734 } 16735 16736 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C++, p.1] 16737 // If the type of a list item is a reference to a type T then the type 16738 // will be considered to be T for all purposes of this clause. 16739 QualType CurType = BaseE->getType().getNonReferenceType(); 16740 16741 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C/C++, p.2] 16742 // A list item cannot be a variable that is a member of a structure with 16743 // a union type. 16744 // 16745 if (CurType->isUnionType()) { 16746 if (!NoDiagnose) { 16747 SemaRef.Diag(ELoc, diag::err_omp_union_type_not_allowed) 16748 << ME->getSourceRange(); 16749 return false; 16750 } 16751 return RelevantExpr || Visit(E); 16752 } 16753 16754 // If we got a member expression, we should not expect any array section 16755 // before that: 16756 // 16757 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.7] 16758 // If a list item is an element of a structure, only the rightmost symbol 16759 // of the variable reference can be an array section. 16760 // 16761 AllowUnitySizeArraySection = false; 16762 AllowWholeSizeArraySection = false; 16763 16764 // Record the component. 16765 Components.emplace_back(ME, FD); 16766 return RelevantExpr || Visit(E); 16767 } 16768 16769 bool VisitArraySubscriptExpr(ArraySubscriptExpr *AE) { 16770 Expr *E = AE->getBase()->IgnoreParenImpCasts(); 16771 16772 if (!E->getType()->isAnyPointerType() && !E->getType()->isArrayType()) { 16773 if (!NoDiagnose) { 16774 SemaRef.Diag(ELoc, diag::err_omp_expected_base_var_name) 16775 << 0 << AE->getSourceRange(); 16776 return false; 16777 } 16778 return RelevantExpr || Visit(E); 16779 } 16780 16781 // If we got an array subscript that express the whole dimension we 16782 // can have any array expressions before. If it only expressing part of 16783 // the dimension, we can only have unitary-size array expressions. 16784 if (checkArrayExpressionDoesNotReferToWholeSize(SemaRef, AE, 16785 E->getType())) 16786 AllowWholeSizeArraySection = false; 16787 16788 if (const auto *TE = dyn_cast<CXXThisExpr>(E->IgnoreParenCasts())) { 16789 Expr::EvalResult Result; 16790 if (!AE->getIdx()->isValueDependent() && 16791 AE->getIdx()->EvaluateAsInt(Result, SemaRef.getASTContext()) && 16792 !Result.Val.getInt().isNullValue()) { 16793 SemaRef.Diag(AE->getIdx()->getExprLoc(), 16794 diag::err_omp_invalid_map_this_expr); 16795 SemaRef.Diag(AE->getIdx()->getExprLoc(), 16796 diag::note_omp_invalid_subscript_on_this_ptr_map); 16797 } 16798 assert(!RelevantExpr && "RelevantExpr is expected to be nullptr"); 16799 RelevantExpr = TE; 16800 } 16801 16802 // Record the component - we don't have any declaration associated. 16803 Components.emplace_back(AE, nullptr); 16804 16805 return RelevantExpr || Visit(E); 16806 } 16807 16808 bool VisitOMPArraySectionExpr(OMPArraySectionExpr *OASE) { 16809 assert(!NoDiagnose && "Array sections cannot be implicitly mapped."); 16810 Expr *E = OASE->getBase()->IgnoreParenImpCasts(); 16811 QualType CurType = 16812 OMPArraySectionExpr::getBaseOriginalType(E).getCanonicalType(); 16813 16814 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C++, p.1] 16815 // If the type of a list item is a reference to a type T then the type 16816 // will be considered to be T for all purposes of this clause. 16817 if (CurType->isReferenceType()) 16818 CurType = CurType->getPointeeType(); 16819 16820 bool IsPointer = CurType->isAnyPointerType(); 16821 16822 if (!IsPointer && !CurType->isArrayType()) { 16823 SemaRef.Diag(ELoc, diag::err_omp_expected_base_var_name) 16824 << 0 << OASE->getSourceRange(); 16825 return false; 16826 } 16827 16828 bool NotWhole = 16829 checkArrayExpressionDoesNotReferToWholeSize(SemaRef, OASE, CurType); 16830 bool NotUnity = 16831 checkArrayExpressionDoesNotReferToUnitySize(SemaRef, OASE, CurType); 16832 16833 if (AllowWholeSizeArraySection) { 16834 // Any array section is currently allowed. Allowing a whole size array 16835 // section implies allowing a unity array section as well. 16836 // 16837 // If this array section refers to the whole dimension we can still 16838 // accept other array sections before this one, except if the base is a 16839 // pointer. Otherwise, only unitary sections are accepted. 16840 if (NotWhole || IsPointer) 16841 AllowWholeSizeArraySection = false; 16842 } else if (AllowUnitySizeArraySection && NotUnity) { 16843 // A unity or whole array section is not allowed and that is not 16844 // compatible with the properties of the current array section. 16845 SemaRef.Diag( 16846 ELoc, diag::err_array_section_does_not_specify_contiguous_storage) 16847 << OASE->getSourceRange(); 16848 return false; 16849 } 16850 16851 if (const auto *TE = dyn_cast<CXXThisExpr>(E)) { 16852 Expr::EvalResult ResultR; 16853 Expr::EvalResult ResultL; 16854 if (!OASE->getLength()->isValueDependent() && 16855 OASE->getLength()->EvaluateAsInt(ResultR, SemaRef.getASTContext()) && 16856 !ResultR.Val.getInt().isOneValue()) { 16857 SemaRef.Diag(OASE->getLength()->getExprLoc(), 16858 diag::err_omp_invalid_map_this_expr); 16859 SemaRef.Diag(OASE->getLength()->getExprLoc(), 16860 diag::note_omp_invalid_length_on_this_ptr_mapping); 16861 } 16862 if (OASE->getLowerBound() && !OASE->getLowerBound()->isValueDependent() && 16863 OASE->getLowerBound()->EvaluateAsInt(ResultL, 16864 SemaRef.getASTContext()) && 16865 !ResultL.Val.getInt().isNullValue()) { 16866 SemaRef.Diag(OASE->getLowerBound()->getExprLoc(), 16867 diag::err_omp_invalid_map_this_expr); 16868 SemaRef.Diag(OASE->getLowerBound()->getExprLoc(), 16869 diag::note_omp_invalid_lower_bound_on_this_ptr_mapping); 16870 } 16871 assert(!RelevantExpr && "RelevantExpr is expected to be nullptr"); 16872 RelevantExpr = TE; 16873 } 16874 16875 // Record the component - we don't have any declaration associated. 16876 Components.emplace_back(OASE, nullptr); 16877 return RelevantExpr || Visit(E); 16878 } 16879 bool VisitOMPArrayShapingExpr(OMPArrayShapingExpr *E) { 16880 Expr *Base = E->getBase(); 16881 16882 // Record the component - we don't have any declaration associated. 16883 Components.emplace_back(E, nullptr); 16884 16885 return Visit(Base->IgnoreParenImpCasts()); 16886 } 16887 16888 bool VisitUnaryOperator(UnaryOperator *UO) { 16889 if (SemaRef.getLangOpts().OpenMP < 50 || !UO->isLValue() || 16890 UO->getOpcode() != UO_Deref) { 16891 emitErrorMsg(); 16892 return false; 16893 } 16894 if (!RelevantExpr) { 16895 // Record the component if haven't found base decl. 16896 Components.emplace_back(UO, nullptr); 16897 } 16898 return RelevantExpr || Visit(UO->getSubExpr()->IgnoreParenImpCasts()); 16899 } 16900 bool VisitBinaryOperator(BinaryOperator *BO) { 16901 if (SemaRef.getLangOpts().OpenMP < 50 || !BO->getType()->isPointerType()) { 16902 emitErrorMsg(); 16903 return false; 16904 } 16905 16906 // Pointer arithmetic is the only thing we expect to happen here so after we 16907 // make sure the binary operator is a pointer type, the we only thing need 16908 // to to is to visit the subtree that has the same type as root (so that we 16909 // know the other subtree is just an offset) 16910 Expr *LE = BO->getLHS()->IgnoreParenImpCasts(); 16911 Expr *RE = BO->getRHS()->IgnoreParenImpCasts(); 16912 Components.emplace_back(BO, nullptr); 16913 assert((LE->getType().getTypePtr() == BO->getType().getTypePtr() || 16914 RE->getType().getTypePtr() == BO->getType().getTypePtr()) && 16915 "Either LHS or RHS have base decl inside"); 16916 if (BO->getType().getTypePtr() == LE->getType().getTypePtr()) 16917 return RelevantExpr || Visit(LE); 16918 return RelevantExpr || Visit(RE); 16919 } 16920 bool VisitCXXThisExpr(CXXThisExpr *CTE) { 16921 assert(!RelevantExpr && "RelevantExpr is expected to be nullptr"); 16922 RelevantExpr = CTE; 16923 Components.emplace_back(CTE, nullptr); 16924 return true; 16925 } 16926 bool VisitStmt(Stmt *) { 16927 emitErrorMsg(); 16928 return false; 16929 } 16930 const Expr *getFoundBase() const { 16931 return RelevantExpr; 16932 } 16933 explicit MapBaseChecker( 16934 Sema &SemaRef, OpenMPClauseKind CKind, 16935 OMPClauseMappableExprCommon::MappableExprComponentList &Components, 16936 bool NoDiagnose, SourceLocation &ELoc, SourceRange &ERange) 16937 : SemaRef(SemaRef), CKind(CKind), Components(Components), 16938 NoDiagnose(NoDiagnose), ELoc(ELoc), ERange(ERange) {} 16939 }; 16940 } // namespace 16941 16942 /// Return the expression of the base of the mappable expression or null if it 16943 /// cannot be determined and do all the necessary checks to see if the expression 16944 /// is valid as a standalone mappable expression. In the process, record all the 16945 /// components of the expression. 16946 static const Expr *checkMapClauseExpressionBase( 16947 Sema &SemaRef, Expr *E, 16948 OMPClauseMappableExprCommon::MappableExprComponentList &CurComponents, 16949 OpenMPClauseKind CKind, bool NoDiagnose) { 16950 SourceLocation ELoc = E->getExprLoc(); 16951 SourceRange ERange = E->getSourceRange(); 16952 MapBaseChecker Checker(SemaRef, CKind, CurComponents, NoDiagnose, ELoc, 16953 ERange); 16954 if (Checker.Visit(E->IgnoreParens())) 16955 return Checker.getFoundBase(); 16956 return nullptr; 16957 } 16958 16959 // Return true if expression E associated with value VD has conflicts with other 16960 // map information. 16961 static bool checkMapConflicts( 16962 Sema &SemaRef, DSAStackTy *DSAS, const ValueDecl *VD, const Expr *E, 16963 bool CurrentRegionOnly, 16964 OMPClauseMappableExprCommon::MappableExprComponentListRef CurComponents, 16965 OpenMPClauseKind CKind) { 16966 assert(VD && E); 16967 SourceLocation ELoc = E->getExprLoc(); 16968 SourceRange ERange = E->getSourceRange(); 16969 16970 // In order to easily check the conflicts we need to match each component of 16971 // the expression under test with the components of the expressions that are 16972 // already in the stack. 16973 16974 assert(!CurComponents.empty() && "Map clause expression with no components!"); 16975 assert(CurComponents.back().getAssociatedDeclaration() == VD && 16976 "Map clause expression with unexpected base!"); 16977 16978 // Variables to help detecting enclosing problems in data environment nests. 16979 bool IsEnclosedByDataEnvironmentExpr = false; 16980 const Expr *EnclosingExpr = nullptr; 16981 16982 bool FoundError = DSAS->checkMappableExprComponentListsForDecl( 16983 VD, CurrentRegionOnly, 16984 [&IsEnclosedByDataEnvironmentExpr, &SemaRef, VD, CurrentRegionOnly, ELoc, 16985 ERange, CKind, &EnclosingExpr, 16986 CurComponents](OMPClauseMappableExprCommon::MappableExprComponentListRef 16987 StackComponents, 16988 OpenMPClauseKind) { 16989 assert(!StackComponents.empty() && 16990 "Map clause expression with no components!"); 16991 assert(StackComponents.back().getAssociatedDeclaration() == VD && 16992 "Map clause expression with unexpected base!"); 16993 (void)VD; 16994 16995 // The whole expression in the stack. 16996 const Expr *RE = StackComponents.front().getAssociatedExpression(); 16997 16998 // Expressions must start from the same base. Here we detect at which 16999 // point both expressions diverge from each other and see if we can 17000 // detect if the memory referred to both expressions is contiguous and 17001 // do not overlap. 17002 auto CI = CurComponents.rbegin(); 17003 auto CE = CurComponents.rend(); 17004 auto SI = StackComponents.rbegin(); 17005 auto SE = StackComponents.rend(); 17006 for (; CI != CE && SI != SE; ++CI, ++SI) { 17007 17008 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.3] 17009 // At most one list item can be an array item derived from a given 17010 // variable in map clauses of the same construct. 17011 if (CurrentRegionOnly && 17012 (isa<ArraySubscriptExpr>(CI->getAssociatedExpression()) || 17013 isa<OMPArraySectionExpr>(CI->getAssociatedExpression()) || 17014 isa<OMPArrayShapingExpr>(CI->getAssociatedExpression())) && 17015 (isa<ArraySubscriptExpr>(SI->getAssociatedExpression()) || 17016 isa<OMPArraySectionExpr>(SI->getAssociatedExpression()) || 17017 isa<OMPArrayShapingExpr>(SI->getAssociatedExpression()))) { 17018 SemaRef.Diag(CI->getAssociatedExpression()->getExprLoc(), 17019 diag::err_omp_multiple_array_items_in_map_clause) 17020 << CI->getAssociatedExpression()->getSourceRange(); 17021 SemaRef.Diag(SI->getAssociatedExpression()->getExprLoc(), 17022 diag::note_used_here) 17023 << SI->getAssociatedExpression()->getSourceRange(); 17024 return true; 17025 } 17026 17027 // Do both expressions have the same kind? 17028 if (CI->getAssociatedExpression()->getStmtClass() != 17029 SI->getAssociatedExpression()->getStmtClass()) 17030 break; 17031 17032 // Are we dealing with different variables/fields? 17033 if (CI->getAssociatedDeclaration() != SI->getAssociatedDeclaration()) 17034 break; 17035 } 17036 // Check if the extra components of the expressions in the enclosing 17037 // data environment are redundant for the current base declaration. 17038 // If they are, the maps completely overlap, which is legal. 17039 for (; SI != SE; ++SI) { 17040 QualType Type; 17041 if (const auto *ASE = 17042 dyn_cast<ArraySubscriptExpr>(SI->getAssociatedExpression())) { 17043 Type = ASE->getBase()->IgnoreParenImpCasts()->getType(); 17044 } else if (const auto *OASE = dyn_cast<OMPArraySectionExpr>( 17045 SI->getAssociatedExpression())) { 17046 const Expr *E = OASE->getBase()->IgnoreParenImpCasts(); 17047 Type = 17048 OMPArraySectionExpr::getBaseOriginalType(E).getCanonicalType(); 17049 } else if (const auto *OASE = dyn_cast<OMPArrayShapingExpr>( 17050 SI->getAssociatedExpression())) { 17051 Type = OASE->getBase()->getType()->getPointeeType(); 17052 } 17053 if (Type.isNull() || Type->isAnyPointerType() || 17054 checkArrayExpressionDoesNotReferToWholeSize( 17055 SemaRef, SI->getAssociatedExpression(), Type)) 17056 break; 17057 } 17058 17059 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.4] 17060 // List items of map clauses in the same construct must not share 17061 // original storage. 17062 // 17063 // If the expressions are exactly the same or one is a subset of the 17064 // other, it means they are sharing storage. 17065 if (CI == CE && SI == SE) { 17066 if (CurrentRegionOnly) { 17067 if (CKind == OMPC_map) { 17068 SemaRef.Diag(ELoc, diag::err_omp_map_shared_storage) << ERange; 17069 } else { 17070 assert(CKind == OMPC_to || CKind == OMPC_from); 17071 SemaRef.Diag(ELoc, diag::err_omp_once_referenced_in_target_update) 17072 << ERange; 17073 } 17074 SemaRef.Diag(RE->getExprLoc(), diag::note_used_here) 17075 << RE->getSourceRange(); 17076 return true; 17077 } 17078 // If we find the same expression in the enclosing data environment, 17079 // that is legal. 17080 IsEnclosedByDataEnvironmentExpr = true; 17081 return false; 17082 } 17083 17084 QualType DerivedType = 17085 std::prev(CI)->getAssociatedDeclaration()->getType(); 17086 SourceLocation DerivedLoc = 17087 std::prev(CI)->getAssociatedExpression()->getExprLoc(); 17088 17089 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C++, p.1] 17090 // If the type of a list item is a reference to a type T then the type 17091 // will be considered to be T for all purposes of this clause. 17092 DerivedType = DerivedType.getNonReferenceType(); 17093 17094 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C/C++, p.1] 17095 // A variable for which the type is pointer and an array section 17096 // derived from that variable must not appear as list items of map 17097 // clauses of the same construct. 17098 // 17099 // Also, cover one of the cases in: 17100 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.5] 17101 // If any part of the original storage of a list item has corresponding 17102 // storage in the device data environment, all of the original storage 17103 // must have corresponding storage in the device data environment. 17104 // 17105 if (DerivedType->isAnyPointerType()) { 17106 if (CI == CE || SI == SE) { 17107 SemaRef.Diag( 17108 DerivedLoc, 17109 diag::err_omp_pointer_mapped_along_with_derived_section) 17110 << DerivedLoc; 17111 SemaRef.Diag(RE->getExprLoc(), diag::note_used_here) 17112 << RE->getSourceRange(); 17113 return true; 17114 } 17115 if (CI->getAssociatedExpression()->getStmtClass() != 17116 SI->getAssociatedExpression()->getStmtClass() || 17117 CI->getAssociatedDeclaration()->getCanonicalDecl() == 17118 SI->getAssociatedDeclaration()->getCanonicalDecl()) { 17119 assert(CI != CE && SI != SE); 17120 SemaRef.Diag(DerivedLoc, diag::err_omp_same_pointer_dereferenced) 17121 << DerivedLoc; 17122 SemaRef.Diag(RE->getExprLoc(), diag::note_used_here) 17123 << RE->getSourceRange(); 17124 return true; 17125 } 17126 } 17127 17128 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.4] 17129 // List items of map clauses in the same construct must not share 17130 // original storage. 17131 // 17132 // An expression is a subset of the other. 17133 if (CurrentRegionOnly && (CI == CE || SI == SE)) { 17134 if (CKind == OMPC_map) { 17135 if (CI != CE || SI != SE) { 17136 // Allow constructs like this: map(s, s.ptr[0:1]), where s.ptr is 17137 // a pointer. 17138 auto Begin = 17139 CI != CE ? CurComponents.begin() : StackComponents.begin(); 17140 auto End = CI != CE ? CurComponents.end() : StackComponents.end(); 17141 auto It = Begin; 17142 while (It != End && !It->getAssociatedDeclaration()) 17143 std::advance(It, 1); 17144 assert(It != End && 17145 "Expected at least one component with the declaration."); 17146 if (It != Begin && It->getAssociatedDeclaration() 17147 ->getType() 17148 .getCanonicalType() 17149 ->isAnyPointerType()) { 17150 IsEnclosedByDataEnvironmentExpr = false; 17151 EnclosingExpr = nullptr; 17152 return false; 17153 } 17154 } 17155 SemaRef.Diag(ELoc, diag::err_omp_map_shared_storage) << ERange; 17156 } else { 17157 assert(CKind == OMPC_to || CKind == OMPC_from); 17158 SemaRef.Diag(ELoc, diag::err_omp_once_referenced_in_target_update) 17159 << ERange; 17160 } 17161 SemaRef.Diag(RE->getExprLoc(), diag::note_used_here) 17162 << RE->getSourceRange(); 17163 return true; 17164 } 17165 17166 // The current expression uses the same base as other expression in the 17167 // data environment but does not contain it completely. 17168 if (!CurrentRegionOnly && SI != SE) 17169 EnclosingExpr = RE; 17170 17171 // The current expression is a subset of the expression in the data 17172 // environment. 17173 IsEnclosedByDataEnvironmentExpr |= 17174 (!CurrentRegionOnly && CI != CE && SI == SE); 17175 17176 return false; 17177 }); 17178 17179 if (CurrentRegionOnly) 17180 return FoundError; 17181 17182 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.5] 17183 // If any part of the original storage of a list item has corresponding 17184 // storage in the device data environment, all of the original storage must 17185 // have corresponding storage in the device data environment. 17186 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.6] 17187 // If a list item is an element of a structure, and a different element of 17188 // the structure has a corresponding list item in the device data environment 17189 // prior to a task encountering the construct associated with the map clause, 17190 // then the list item must also have a corresponding list item in the device 17191 // data environment prior to the task encountering the construct. 17192 // 17193 if (EnclosingExpr && !IsEnclosedByDataEnvironmentExpr) { 17194 SemaRef.Diag(ELoc, 17195 diag::err_omp_original_storage_is_shared_and_does_not_contain) 17196 << ERange; 17197 SemaRef.Diag(EnclosingExpr->getExprLoc(), diag::note_used_here) 17198 << EnclosingExpr->getSourceRange(); 17199 return true; 17200 } 17201 17202 return FoundError; 17203 } 17204 17205 // Look up the user-defined mapper given the mapper name and mapped type, and 17206 // build a reference to it. 17207 static ExprResult buildUserDefinedMapperRef(Sema &SemaRef, Scope *S, 17208 CXXScopeSpec &MapperIdScopeSpec, 17209 const DeclarationNameInfo &MapperId, 17210 QualType Type, 17211 Expr *UnresolvedMapper) { 17212 if (MapperIdScopeSpec.isInvalid()) 17213 return ExprError(); 17214 // Get the actual type for the array type. 17215 if (Type->isArrayType()) { 17216 assert(Type->getAsArrayTypeUnsafe() && "Expect to get a valid array type"); 17217 Type = Type->getAsArrayTypeUnsafe()->getElementType().getCanonicalType(); 17218 } 17219 // Find all user-defined mappers with the given MapperId. 17220 SmallVector<UnresolvedSet<8>, 4> Lookups; 17221 LookupResult Lookup(SemaRef, MapperId, Sema::LookupOMPMapperName); 17222 Lookup.suppressDiagnostics(); 17223 if (S) { 17224 while (S && SemaRef.LookupParsedName(Lookup, S, &MapperIdScopeSpec)) { 17225 NamedDecl *D = Lookup.getRepresentativeDecl(); 17226 while (S && !S->isDeclScope(D)) 17227 S = S->getParent(); 17228 if (S) 17229 S = S->getParent(); 17230 Lookups.emplace_back(); 17231 Lookups.back().append(Lookup.begin(), Lookup.end()); 17232 Lookup.clear(); 17233 } 17234 } else if (auto *ULE = cast_or_null<UnresolvedLookupExpr>(UnresolvedMapper)) { 17235 // Extract the user-defined mappers with the given MapperId. 17236 Lookups.push_back(UnresolvedSet<8>()); 17237 for (NamedDecl *D : ULE->decls()) { 17238 auto *DMD = cast<OMPDeclareMapperDecl>(D); 17239 assert(DMD && "Expect valid OMPDeclareMapperDecl during instantiation."); 17240 Lookups.back().addDecl(DMD); 17241 } 17242 } 17243 // Defer the lookup for dependent types. The results will be passed through 17244 // UnresolvedMapper on instantiation. 17245 if (SemaRef.CurContext->isDependentContext() || Type->isDependentType() || 17246 Type->isInstantiationDependentType() || 17247 Type->containsUnexpandedParameterPack() || 17248 filterLookupForUDReductionAndMapper<bool>(Lookups, [](ValueDecl *D) { 17249 return !D->isInvalidDecl() && 17250 (D->getType()->isDependentType() || 17251 D->getType()->isInstantiationDependentType() || 17252 D->getType()->containsUnexpandedParameterPack()); 17253 })) { 17254 UnresolvedSet<8> URS; 17255 for (const UnresolvedSet<8> &Set : Lookups) { 17256 if (Set.empty()) 17257 continue; 17258 URS.append(Set.begin(), Set.end()); 17259 } 17260 return UnresolvedLookupExpr::Create( 17261 SemaRef.Context, /*NamingClass=*/nullptr, 17262 MapperIdScopeSpec.getWithLocInContext(SemaRef.Context), MapperId, 17263 /*ADL=*/false, /*Overloaded=*/true, URS.begin(), URS.end()); 17264 } 17265 SourceLocation Loc = MapperId.getLoc(); 17266 // [OpenMP 5.0], 2.19.7.3 declare mapper Directive, Restrictions 17267 // The type must be of struct, union or class type in C and C++ 17268 if (!Type->isStructureOrClassType() && !Type->isUnionType() && 17269 (MapperIdScopeSpec.isSet() || MapperId.getAsString() != "default")) { 17270 SemaRef.Diag(Loc, diag::err_omp_mapper_wrong_type); 17271 return ExprError(); 17272 } 17273 // Perform argument dependent lookup. 17274 if (SemaRef.getLangOpts().CPlusPlus && !MapperIdScopeSpec.isSet()) 17275 argumentDependentLookup(SemaRef, MapperId, Loc, Type, Lookups); 17276 // Return the first user-defined mapper with the desired type. 17277 if (auto *VD = filterLookupForUDReductionAndMapper<ValueDecl *>( 17278 Lookups, [&SemaRef, Type](ValueDecl *D) -> ValueDecl * { 17279 if (!D->isInvalidDecl() && 17280 SemaRef.Context.hasSameType(D->getType(), Type)) 17281 return D; 17282 return nullptr; 17283 })) 17284 return SemaRef.BuildDeclRefExpr(VD, Type, VK_LValue, Loc); 17285 // Find the first user-defined mapper with a type derived from the desired 17286 // type. 17287 if (auto *VD = filterLookupForUDReductionAndMapper<ValueDecl *>( 17288 Lookups, [&SemaRef, Type, Loc](ValueDecl *D) -> ValueDecl * { 17289 if (!D->isInvalidDecl() && 17290 SemaRef.IsDerivedFrom(Loc, Type, D->getType()) && 17291 !Type.isMoreQualifiedThan(D->getType())) 17292 return D; 17293 return nullptr; 17294 })) { 17295 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true, 17296 /*DetectVirtual=*/false); 17297 if (SemaRef.IsDerivedFrom(Loc, Type, VD->getType(), Paths)) { 17298 if (!Paths.isAmbiguous(SemaRef.Context.getCanonicalType( 17299 VD->getType().getUnqualifiedType()))) { 17300 if (SemaRef.CheckBaseClassAccess( 17301 Loc, VD->getType(), Type, Paths.front(), 17302 /*DiagID=*/0) != Sema::AR_inaccessible) { 17303 return SemaRef.BuildDeclRefExpr(VD, Type, VK_LValue, Loc); 17304 } 17305 } 17306 } 17307 } 17308 // Report error if a mapper is specified, but cannot be found. 17309 if (MapperIdScopeSpec.isSet() || MapperId.getAsString() != "default") { 17310 SemaRef.Diag(Loc, diag::err_omp_invalid_mapper) 17311 << Type << MapperId.getName(); 17312 return ExprError(); 17313 } 17314 return ExprEmpty(); 17315 } 17316 17317 namespace { 17318 // Utility struct that gathers all the related lists associated with a mappable 17319 // expression. 17320 struct MappableVarListInfo { 17321 // The list of expressions. 17322 ArrayRef<Expr *> VarList; 17323 // The list of processed expressions. 17324 SmallVector<Expr *, 16> ProcessedVarList; 17325 // The mappble components for each expression. 17326 OMPClauseMappableExprCommon::MappableExprComponentLists VarComponents; 17327 // The base declaration of the variable. 17328 SmallVector<ValueDecl *, 16> VarBaseDeclarations; 17329 // The reference to the user-defined mapper associated with every expression. 17330 SmallVector<Expr *, 16> UDMapperList; 17331 17332 MappableVarListInfo(ArrayRef<Expr *> VarList) : VarList(VarList) { 17333 // We have a list of components and base declarations for each entry in the 17334 // variable list. 17335 VarComponents.reserve(VarList.size()); 17336 VarBaseDeclarations.reserve(VarList.size()); 17337 } 17338 }; 17339 } 17340 17341 // Check the validity of the provided variable list for the provided clause kind 17342 // \a CKind. In the check process the valid expressions, mappable expression 17343 // components, variables, and user-defined mappers are extracted and used to 17344 // fill \a ProcessedVarList, \a VarComponents, \a VarBaseDeclarations, and \a 17345 // UDMapperList in MVLI. \a MapType, \a IsMapTypeImplicit, \a MapperIdScopeSpec, 17346 // and \a MapperId are expected to be valid if the clause kind is 'map'. 17347 static void checkMappableExpressionList( 17348 Sema &SemaRef, DSAStackTy *DSAS, OpenMPClauseKind CKind, 17349 MappableVarListInfo &MVLI, SourceLocation StartLoc, 17350 CXXScopeSpec &MapperIdScopeSpec, DeclarationNameInfo MapperId, 17351 ArrayRef<Expr *> UnresolvedMappers, 17352 OpenMPMapClauseKind MapType = OMPC_MAP_unknown, 17353 bool IsMapTypeImplicit = false) { 17354 // We only expect mappable expressions in 'to', 'from', and 'map' clauses. 17355 assert((CKind == OMPC_map || CKind == OMPC_to || CKind == OMPC_from) && 17356 "Unexpected clause kind with mappable expressions!"); 17357 17358 // If the identifier of user-defined mapper is not specified, it is "default". 17359 // We do not change the actual name in this clause to distinguish whether a 17360 // mapper is specified explicitly, i.e., it is not explicitly specified when 17361 // MapperId.getName() is empty. 17362 if (!MapperId.getName() || MapperId.getName().isEmpty()) { 17363 auto &DeclNames = SemaRef.getASTContext().DeclarationNames; 17364 MapperId.setName(DeclNames.getIdentifier( 17365 &SemaRef.getASTContext().Idents.get("default"))); 17366 } 17367 17368 // Iterators to find the current unresolved mapper expression. 17369 auto UMIt = UnresolvedMappers.begin(), UMEnd = UnresolvedMappers.end(); 17370 bool UpdateUMIt = false; 17371 Expr *UnresolvedMapper = nullptr; 17372 17373 // Keep track of the mappable components and base declarations in this clause. 17374 // Each entry in the list is going to have a list of components associated. We 17375 // record each set of the components so that we can build the clause later on. 17376 // In the end we should have the same amount of declarations and component 17377 // lists. 17378 17379 for (Expr *RE : MVLI.VarList) { 17380 assert(RE && "Null expr in omp to/from/map clause"); 17381 SourceLocation ELoc = RE->getExprLoc(); 17382 17383 // Find the current unresolved mapper expression. 17384 if (UpdateUMIt && UMIt != UMEnd) { 17385 UMIt++; 17386 assert( 17387 UMIt != UMEnd && 17388 "Expect the size of UnresolvedMappers to match with that of VarList"); 17389 } 17390 UpdateUMIt = true; 17391 if (UMIt != UMEnd) 17392 UnresolvedMapper = *UMIt; 17393 17394 const Expr *VE = RE->IgnoreParenLValueCasts(); 17395 17396 if (VE->isValueDependent() || VE->isTypeDependent() || 17397 VE->isInstantiationDependent() || 17398 VE->containsUnexpandedParameterPack()) { 17399 // Try to find the associated user-defined mapper. 17400 ExprResult ER = buildUserDefinedMapperRef( 17401 SemaRef, DSAS->getCurScope(), MapperIdScopeSpec, MapperId, 17402 VE->getType().getCanonicalType(), UnresolvedMapper); 17403 if (ER.isInvalid()) 17404 continue; 17405 MVLI.UDMapperList.push_back(ER.get()); 17406 // We can only analyze this information once the missing information is 17407 // resolved. 17408 MVLI.ProcessedVarList.push_back(RE); 17409 continue; 17410 } 17411 17412 Expr *SimpleExpr = RE->IgnoreParenCasts(); 17413 17414 if (!RE->isLValue()) { 17415 if (SemaRef.getLangOpts().OpenMP < 50) { 17416 SemaRef.Diag( 17417 ELoc, diag::err_omp_expected_named_var_member_or_array_expression) 17418 << RE->getSourceRange(); 17419 } else { 17420 SemaRef.Diag(ELoc, diag::err_omp_non_lvalue_in_map_or_motion_clauses) 17421 << getOpenMPClauseName(CKind) << RE->getSourceRange(); 17422 } 17423 continue; 17424 } 17425 17426 OMPClauseMappableExprCommon::MappableExprComponentList CurComponents; 17427 ValueDecl *CurDeclaration = nullptr; 17428 17429 // Obtain the array or member expression bases if required. Also, fill the 17430 // components array with all the components identified in the process. 17431 const Expr *BE = checkMapClauseExpressionBase( 17432 SemaRef, SimpleExpr, CurComponents, CKind, /*NoDiagnose=*/false); 17433 if (!BE) 17434 continue; 17435 17436 assert(!CurComponents.empty() && 17437 "Invalid mappable expression information."); 17438 17439 if (const auto *TE = dyn_cast<CXXThisExpr>(BE)) { 17440 // Add store "this" pointer to class in DSAStackTy for future checking 17441 DSAS->addMappedClassesQualTypes(TE->getType()); 17442 // Try to find the associated user-defined mapper. 17443 ExprResult ER = buildUserDefinedMapperRef( 17444 SemaRef, DSAS->getCurScope(), MapperIdScopeSpec, MapperId, 17445 VE->getType().getCanonicalType(), UnresolvedMapper); 17446 if (ER.isInvalid()) 17447 continue; 17448 MVLI.UDMapperList.push_back(ER.get()); 17449 // Skip restriction checking for variable or field declarations 17450 MVLI.ProcessedVarList.push_back(RE); 17451 MVLI.VarComponents.resize(MVLI.VarComponents.size() + 1); 17452 MVLI.VarComponents.back().append(CurComponents.begin(), 17453 CurComponents.end()); 17454 MVLI.VarBaseDeclarations.push_back(nullptr); 17455 continue; 17456 } 17457 17458 // For the following checks, we rely on the base declaration which is 17459 // expected to be associated with the last component. The declaration is 17460 // expected to be a variable or a field (if 'this' is being mapped). 17461 CurDeclaration = CurComponents.back().getAssociatedDeclaration(); 17462 assert(CurDeclaration && "Null decl on map clause."); 17463 assert( 17464 CurDeclaration->isCanonicalDecl() && 17465 "Expecting components to have associated only canonical declarations."); 17466 17467 auto *VD = dyn_cast<VarDecl>(CurDeclaration); 17468 const auto *FD = dyn_cast<FieldDecl>(CurDeclaration); 17469 17470 assert((VD || FD) && "Only variables or fields are expected here!"); 17471 (void)FD; 17472 17473 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.10] 17474 // threadprivate variables cannot appear in a map clause. 17475 // OpenMP 4.5 [2.10.5, target update Construct] 17476 // threadprivate variables cannot appear in a from clause. 17477 if (VD && DSAS->isThreadPrivate(VD)) { 17478 DSAStackTy::DSAVarData DVar = DSAS->getTopDSA(VD, /*FromParent=*/false); 17479 SemaRef.Diag(ELoc, diag::err_omp_threadprivate_in_clause) 17480 << getOpenMPClauseName(CKind); 17481 reportOriginalDsa(SemaRef, DSAS, VD, DVar); 17482 continue; 17483 } 17484 17485 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.9] 17486 // A list item cannot appear in both a map clause and a data-sharing 17487 // attribute clause on the same construct. 17488 17489 // Check conflicts with other map clause expressions. We check the conflicts 17490 // with the current construct separately from the enclosing data 17491 // environment, because the restrictions are different. We only have to 17492 // check conflicts across regions for the map clauses. 17493 if (checkMapConflicts(SemaRef, DSAS, CurDeclaration, SimpleExpr, 17494 /*CurrentRegionOnly=*/true, CurComponents, CKind)) 17495 break; 17496 if (CKind == OMPC_map && 17497 (SemaRef.getLangOpts().OpenMP <= 45 || StartLoc.isValid()) && 17498 checkMapConflicts(SemaRef, DSAS, CurDeclaration, SimpleExpr, 17499 /*CurrentRegionOnly=*/false, CurComponents, CKind)) 17500 break; 17501 17502 // OpenMP 4.5 [2.10.5, target update Construct] 17503 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C++, p.1] 17504 // If the type of a list item is a reference to a type T then the type will 17505 // be considered to be T for all purposes of this clause. 17506 auto I = llvm::find_if( 17507 CurComponents, 17508 [](const OMPClauseMappableExprCommon::MappableComponent &MC) { 17509 return MC.getAssociatedDeclaration(); 17510 }); 17511 assert(I != CurComponents.end() && "Null decl on map clause."); 17512 QualType Type; 17513 auto *ASE = dyn_cast<ArraySubscriptExpr>(VE->IgnoreParens()); 17514 auto *OASE = dyn_cast<OMPArraySectionExpr>(VE->IgnoreParens()); 17515 auto *OAShE = dyn_cast<OMPArrayShapingExpr>(VE->IgnoreParens()); 17516 if (ASE) { 17517 Type = ASE->getType().getNonReferenceType(); 17518 } else if (OASE) { 17519 QualType BaseType = 17520 OMPArraySectionExpr::getBaseOriginalType(OASE->getBase()); 17521 if (const auto *ATy = BaseType->getAsArrayTypeUnsafe()) 17522 Type = ATy->getElementType(); 17523 else 17524 Type = BaseType->getPointeeType(); 17525 Type = Type.getNonReferenceType(); 17526 } else if (OAShE) { 17527 Type = OAShE->getBase()->getType()->getPointeeType(); 17528 } else { 17529 Type = VE->getType(); 17530 } 17531 17532 // OpenMP 4.5 [2.10.5, target update Construct, Restrictions, p.4] 17533 // A list item in a to or from clause must have a mappable type. 17534 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.9] 17535 // A list item must have a mappable type. 17536 if (!checkTypeMappable(VE->getExprLoc(), VE->getSourceRange(), SemaRef, 17537 DSAS, Type)) 17538 continue; 17539 17540 Type = I->getAssociatedDeclaration()->getType().getNonReferenceType(); 17541 17542 if (CKind == OMPC_map) { 17543 // target enter data 17544 // OpenMP [2.10.2, Restrictions, p. 99] 17545 // A map-type must be specified in all map clauses and must be either 17546 // to or alloc. 17547 OpenMPDirectiveKind DKind = DSAS->getCurrentDirective(); 17548 if (DKind == OMPD_target_enter_data && 17549 !(MapType == OMPC_MAP_to || MapType == OMPC_MAP_alloc)) { 17550 SemaRef.Diag(StartLoc, diag::err_omp_invalid_map_type_for_directive) 17551 << (IsMapTypeImplicit ? 1 : 0) 17552 << getOpenMPSimpleClauseTypeName(OMPC_map, MapType) 17553 << getOpenMPDirectiveName(DKind); 17554 continue; 17555 } 17556 17557 // target exit_data 17558 // OpenMP [2.10.3, Restrictions, p. 102] 17559 // A map-type must be specified in all map clauses and must be either 17560 // from, release, or delete. 17561 if (DKind == OMPD_target_exit_data && 17562 !(MapType == OMPC_MAP_from || MapType == OMPC_MAP_release || 17563 MapType == OMPC_MAP_delete)) { 17564 SemaRef.Diag(StartLoc, diag::err_omp_invalid_map_type_for_directive) 17565 << (IsMapTypeImplicit ? 1 : 0) 17566 << getOpenMPSimpleClauseTypeName(OMPC_map, MapType) 17567 << getOpenMPDirectiveName(DKind); 17568 continue; 17569 } 17570 17571 // target, target data 17572 // OpenMP 5.0 [2.12.2, Restrictions, p. 163] 17573 // OpenMP 5.0 [2.12.5, Restrictions, p. 174] 17574 // A map-type in a map clause must be to, from, tofrom or alloc 17575 if ((DKind == OMPD_target_data || 17576 isOpenMPTargetExecutionDirective(DKind)) && 17577 !(MapType == OMPC_MAP_to || MapType == OMPC_MAP_from || 17578 MapType == OMPC_MAP_tofrom || MapType == OMPC_MAP_alloc)) { 17579 SemaRef.Diag(StartLoc, diag::err_omp_invalid_map_type_for_directive) 17580 << (IsMapTypeImplicit ? 1 : 0) 17581 << getOpenMPSimpleClauseTypeName(OMPC_map, MapType) 17582 << getOpenMPDirectiveName(DKind); 17583 continue; 17584 } 17585 17586 // OpenMP 4.5 [2.15.5.1, Restrictions, p.3] 17587 // A list item cannot appear in both a map clause and a data-sharing 17588 // attribute clause on the same construct 17589 // 17590 // OpenMP 5.0 [2.19.7.1, Restrictions, p.7] 17591 // A list item cannot appear in both a map clause and a data-sharing 17592 // attribute clause on the same construct unless the construct is a 17593 // combined construct. 17594 if (VD && ((SemaRef.LangOpts.OpenMP <= 45 && 17595 isOpenMPTargetExecutionDirective(DKind)) || 17596 DKind == OMPD_target)) { 17597 DSAStackTy::DSAVarData DVar = DSAS->getTopDSA(VD, /*FromParent=*/false); 17598 if (isOpenMPPrivate(DVar.CKind)) { 17599 SemaRef.Diag(ELoc, diag::err_omp_variable_in_given_clause_and_dsa) 17600 << getOpenMPClauseName(DVar.CKind) 17601 << getOpenMPClauseName(OMPC_map) 17602 << getOpenMPDirectiveName(DSAS->getCurrentDirective()); 17603 reportOriginalDsa(SemaRef, DSAS, CurDeclaration, DVar); 17604 continue; 17605 } 17606 } 17607 } 17608 17609 // Try to find the associated user-defined mapper. 17610 ExprResult ER = buildUserDefinedMapperRef( 17611 SemaRef, DSAS->getCurScope(), MapperIdScopeSpec, MapperId, 17612 Type.getCanonicalType(), UnresolvedMapper); 17613 if (ER.isInvalid()) 17614 continue; 17615 MVLI.UDMapperList.push_back(ER.get()); 17616 17617 // Save the current expression. 17618 MVLI.ProcessedVarList.push_back(RE); 17619 17620 // Store the components in the stack so that they can be used to check 17621 // against other clauses later on. 17622 DSAS->addMappableExpressionComponents(CurDeclaration, CurComponents, 17623 /*WhereFoundClauseKind=*/OMPC_map); 17624 17625 // Save the components and declaration to create the clause. For purposes of 17626 // the clause creation, any component list that has has base 'this' uses 17627 // null as base declaration. 17628 MVLI.VarComponents.resize(MVLI.VarComponents.size() + 1); 17629 MVLI.VarComponents.back().append(CurComponents.begin(), 17630 CurComponents.end()); 17631 MVLI.VarBaseDeclarations.push_back(isa<MemberExpr>(BE) ? nullptr 17632 : CurDeclaration); 17633 } 17634 } 17635 17636 OMPClause *Sema::ActOnOpenMPMapClause( 17637 ArrayRef<OpenMPMapModifierKind> MapTypeModifiers, 17638 ArrayRef<SourceLocation> MapTypeModifiersLoc, 17639 CXXScopeSpec &MapperIdScopeSpec, DeclarationNameInfo &MapperId, 17640 OpenMPMapClauseKind MapType, bool IsMapTypeImplicit, SourceLocation MapLoc, 17641 SourceLocation ColonLoc, ArrayRef<Expr *> VarList, 17642 const OMPVarListLocTy &Locs, ArrayRef<Expr *> UnresolvedMappers) { 17643 OpenMPMapModifierKind Modifiers[] = {OMPC_MAP_MODIFIER_unknown, 17644 OMPC_MAP_MODIFIER_unknown, 17645 OMPC_MAP_MODIFIER_unknown}; 17646 SourceLocation ModifiersLoc[NumberOfOMPMapClauseModifiers]; 17647 17648 // Process map-type-modifiers, flag errors for duplicate modifiers. 17649 unsigned Count = 0; 17650 for (unsigned I = 0, E = MapTypeModifiers.size(); I < E; ++I) { 17651 if (MapTypeModifiers[I] != OMPC_MAP_MODIFIER_unknown && 17652 llvm::find(Modifiers, MapTypeModifiers[I]) != std::end(Modifiers)) { 17653 Diag(MapTypeModifiersLoc[I], diag::err_omp_duplicate_map_type_modifier); 17654 continue; 17655 } 17656 assert(Count < NumberOfOMPMapClauseModifiers && 17657 "Modifiers exceed the allowed number of map type modifiers"); 17658 Modifiers[Count] = MapTypeModifiers[I]; 17659 ModifiersLoc[Count] = MapTypeModifiersLoc[I]; 17660 ++Count; 17661 } 17662 17663 MappableVarListInfo MVLI(VarList); 17664 checkMappableExpressionList(*this, DSAStack, OMPC_map, MVLI, Locs.StartLoc, 17665 MapperIdScopeSpec, MapperId, UnresolvedMappers, 17666 MapType, IsMapTypeImplicit); 17667 17668 // We need to produce a map clause even if we don't have variables so that 17669 // other diagnostics related with non-existing map clauses are accurate. 17670 return OMPMapClause::Create(Context, Locs, MVLI.ProcessedVarList, 17671 MVLI.VarBaseDeclarations, MVLI.VarComponents, 17672 MVLI.UDMapperList, Modifiers, ModifiersLoc, 17673 MapperIdScopeSpec.getWithLocInContext(Context), 17674 MapperId, MapType, IsMapTypeImplicit, MapLoc); 17675 } 17676 17677 QualType Sema::ActOnOpenMPDeclareReductionType(SourceLocation TyLoc, 17678 TypeResult ParsedType) { 17679 assert(ParsedType.isUsable()); 17680 17681 QualType ReductionType = GetTypeFromParser(ParsedType.get()); 17682 if (ReductionType.isNull()) 17683 return QualType(); 17684 17685 // [OpenMP 4.0], 2.15 declare reduction Directive, Restrictions, C\C++ 17686 // A type name in a declare reduction directive cannot be a function type, an 17687 // array type, a reference type, or a type qualified with const, volatile or 17688 // restrict. 17689 if (ReductionType.hasQualifiers()) { 17690 Diag(TyLoc, diag::err_omp_reduction_wrong_type) << 0; 17691 return QualType(); 17692 } 17693 17694 if (ReductionType->isFunctionType()) { 17695 Diag(TyLoc, diag::err_omp_reduction_wrong_type) << 1; 17696 return QualType(); 17697 } 17698 if (ReductionType->isReferenceType()) { 17699 Diag(TyLoc, diag::err_omp_reduction_wrong_type) << 2; 17700 return QualType(); 17701 } 17702 if (ReductionType->isArrayType()) { 17703 Diag(TyLoc, diag::err_omp_reduction_wrong_type) << 3; 17704 return QualType(); 17705 } 17706 return ReductionType; 17707 } 17708 17709 Sema::DeclGroupPtrTy Sema::ActOnOpenMPDeclareReductionDirectiveStart( 17710 Scope *S, DeclContext *DC, DeclarationName Name, 17711 ArrayRef<std::pair<QualType, SourceLocation>> ReductionTypes, 17712 AccessSpecifier AS, Decl *PrevDeclInScope) { 17713 SmallVector<Decl *, 8> Decls; 17714 Decls.reserve(ReductionTypes.size()); 17715 17716 LookupResult Lookup(*this, Name, SourceLocation(), LookupOMPReductionName, 17717 forRedeclarationInCurContext()); 17718 // [OpenMP 4.0], 2.15 declare reduction Directive, Restrictions 17719 // A reduction-identifier may not be re-declared in the current scope for the 17720 // same type or for a type that is compatible according to the base language 17721 // rules. 17722 llvm::DenseMap<QualType, SourceLocation> PreviousRedeclTypes; 17723 OMPDeclareReductionDecl *PrevDRD = nullptr; 17724 bool InCompoundScope = true; 17725 if (S != nullptr) { 17726 // Find previous declaration with the same name not referenced in other 17727 // declarations. 17728 FunctionScopeInfo *ParentFn = getEnclosingFunction(); 17729 InCompoundScope = 17730 (ParentFn != nullptr) && !ParentFn->CompoundScopes.empty(); 17731 LookupName(Lookup, S); 17732 FilterLookupForScope(Lookup, DC, S, /*ConsiderLinkage=*/false, 17733 /*AllowInlineNamespace=*/false); 17734 llvm::DenseMap<OMPDeclareReductionDecl *, bool> UsedAsPrevious; 17735 LookupResult::Filter Filter = Lookup.makeFilter(); 17736 while (Filter.hasNext()) { 17737 auto *PrevDecl = cast<OMPDeclareReductionDecl>(Filter.next()); 17738 if (InCompoundScope) { 17739 auto I = UsedAsPrevious.find(PrevDecl); 17740 if (I == UsedAsPrevious.end()) 17741 UsedAsPrevious[PrevDecl] = false; 17742 if (OMPDeclareReductionDecl *D = PrevDecl->getPrevDeclInScope()) 17743 UsedAsPrevious[D] = true; 17744 } 17745 PreviousRedeclTypes[PrevDecl->getType().getCanonicalType()] = 17746 PrevDecl->getLocation(); 17747 } 17748 Filter.done(); 17749 if (InCompoundScope) { 17750 for (const auto &PrevData : UsedAsPrevious) { 17751 if (!PrevData.second) { 17752 PrevDRD = PrevData.first; 17753 break; 17754 } 17755 } 17756 } 17757 } else if (PrevDeclInScope != nullptr) { 17758 auto *PrevDRDInScope = PrevDRD = 17759 cast<OMPDeclareReductionDecl>(PrevDeclInScope); 17760 do { 17761 PreviousRedeclTypes[PrevDRDInScope->getType().getCanonicalType()] = 17762 PrevDRDInScope->getLocation(); 17763 PrevDRDInScope = PrevDRDInScope->getPrevDeclInScope(); 17764 } while (PrevDRDInScope != nullptr); 17765 } 17766 for (const auto &TyData : ReductionTypes) { 17767 const auto I = PreviousRedeclTypes.find(TyData.first.getCanonicalType()); 17768 bool Invalid = false; 17769 if (I != PreviousRedeclTypes.end()) { 17770 Diag(TyData.second, diag::err_omp_declare_reduction_redefinition) 17771 << TyData.first; 17772 Diag(I->second, diag::note_previous_definition); 17773 Invalid = true; 17774 } 17775 PreviousRedeclTypes[TyData.first.getCanonicalType()] = TyData.second; 17776 auto *DRD = OMPDeclareReductionDecl::Create(Context, DC, TyData.second, 17777 Name, TyData.first, PrevDRD); 17778 DC->addDecl(DRD); 17779 DRD->setAccess(AS); 17780 Decls.push_back(DRD); 17781 if (Invalid) 17782 DRD->setInvalidDecl(); 17783 else 17784 PrevDRD = DRD; 17785 } 17786 17787 return DeclGroupPtrTy::make( 17788 DeclGroupRef::Create(Context, Decls.begin(), Decls.size())); 17789 } 17790 17791 void Sema::ActOnOpenMPDeclareReductionCombinerStart(Scope *S, Decl *D) { 17792 auto *DRD = cast<OMPDeclareReductionDecl>(D); 17793 17794 // Enter new function scope. 17795 PushFunctionScope(); 17796 setFunctionHasBranchProtectedScope(); 17797 getCurFunction()->setHasOMPDeclareReductionCombiner(); 17798 17799 if (S != nullptr) 17800 PushDeclContext(S, DRD); 17801 else 17802 CurContext = DRD; 17803 17804 PushExpressionEvaluationContext( 17805 ExpressionEvaluationContext::PotentiallyEvaluated); 17806 17807 QualType ReductionType = DRD->getType(); 17808 // Create 'T* omp_parm;T omp_in;'. All references to 'omp_in' will 17809 // be replaced by '*omp_parm' during codegen. This required because 'omp_in' 17810 // uses semantics of argument handles by value, but it should be passed by 17811 // reference. C lang does not support references, so pass all parameters as 17812 // pointers. 17813 // Create 'T omp_in;' variable. 17814 VarDecl *OmpInParm = 17815 buildVarDecl(*this, D->getLocation(), ReductionType, "omp_in"); 17816 // Create 'T* omp_parm;T omp_out;'. All references to 'omp_out' will 17817 // be replaced by '*omp_parm' during codegen. This required because 'omp_out' 17818 // uses semantics of argument handles by value, but it should be passed by 17819 // reference. C lang does not support references, so pass all parameters as 17820 // pointers. 17821 // Create 'T omp_out;' variable. 17822 VarDecl *OmpOutParm = 17823 buildVarDecl(*this, D->getLocation(), ReductionType, "omp_out"); 17824 if (S != nullptr) { 17825 PushOnScopeChains(OmpInParm, S); 17826 PushOnScopeChains(OmpOutParm, S); 17827 } else { 17828 DRD->addDecl(OmpInParm); 17829 DRD->addDecl(OmpOutParm); 17830 } 17831 Expr *InE = 17832 ::buildDeclRefExpr(*this, OmpInParm, ReductionType, D->getLocation()); 17833 Expr *OutE = 17834 ::buildDeclRefExpr(*this, OmpOutParm, ReductionType, D->getLocation()); 17835 DRD->setCombinerData(InE, OutE); 17836 } 17837 17838 void Sema::ActOnOpenMPDeclareReductionCombinerEnd(Decl *D, Expr *Combiner) { 17839 auto *DRD = cast<OMPDeclareReductionDecl>(D); 17840 DiscardCleanupsInEvaluationContext(); 17841 PopExpressionEvaluationContext(); 17842 17843 PopDeclContext(); 17844 PopFunctionScopeInfo(); 17845 17846 if (Combiner != nullptr) 17847 DRD->setCombiner(Combiner); 17848 else 17849 DRD->setInvalidDecl(); 17850 } 17851 17852 VarDecl *Sema::ActOnOpenMPDeclareReductionInitializerStart(Scope *S, Decl *D) { 17853 auto *DRD = cast<OMPDeclareReductionDecl>(D); 17854 17855 // Enter new function scope. 17856 PushFunctionScope(); 17857 setFunctionHasBranchProtectedScope(); 17858 17859 if (S != nullptr) 17860 PushDeclContext(S, DRD); 17861 else 17862 CurContext = DRD; 17863 17864 PushExpressionEvaluationContext( 17865 ExpressionEvaluationContext::PotentiallyEvaluated); 17866 17867 QualType ReductionType = DRD->getType(); 17868 // Create 'T* omp_parm;T omp_priv;'. All references to 'omp_priv' will 17869 // be replaced by '*omp_parm' during codegen. This required because 'omp_priv' 17870 // uses semantics of argument handles by value, but it should be passed by 17871 // reference. C lang does not support references, so pass all parameters as 17872 // pointers. 17873 // Create 'T omp_priv;' variable. 17874 VarDecl *OmpPrivParm = 17875 buildVarDecl(*this, D->getLocation(), ReductionType, "omp_priv"); 17876 // Create 'T* omp_parm;T omp_orig;'. All references to 'omp_orig' will 17877 // be replaced by '*omp_parm' during codegen. This required because 'omp_orig' 17878 // uses semantics of argument handles by value, but it should be passed by 17879 // reference. C lang does not support references, so pass all parameters as 17880 // pointers. 17881 // Create 'T omp_orig;' variable. 17882 VarDecl *OmpOrigParm = 17883 buildVarDecl(*this, D->getLocation(), ReductionType, "omp_orig"); 17884 if (S != nullptr) { 17885 PushOnScopeChains(OmpPrivParm, S); 17886 PushOnScopeChains(OmpOrigParm, S); 17887 } else { 17888 DRD->addDecl(OmpPrivParm); 17889 DRD->addDecl(OmpOrigParm); 17890 } 17891 Expr *OrigE = 17892 ::buildDeclRefExpr(*this, OmpOrigParm, ReductionType, D->getLocation()); 17893 Expr *PrivE = 17894 ::buildDeclRefExpr(*this, OmpPrivParm, ReductionType, D->getLocation()); 17895 DRD->setInitializerData(OrigE, PrivE); 17896 return OmpPrivParm; 17897 } 17898 17899 void Sema::ActOnOpenMPDeclareReductionInitializerEnd(Decl *D, Expr *Initializer, 17900 VarDecl *OmpPrivParm) { 17901 auto *DRD = cast<OMPDeclareReductionDecl>(D); 17902 DiscardCleanupsInEvaluationContext(); 17903 PopExpressionEvaluationContext(); 17904 17905 PopDeclContext(); 17906 PopFunctionScopeInfo(); 17907 17908 if (Initializer != nullptr) { 17909 DRD->setInitializer(Initializer, OMPDeclareReductionDecl::CallInit); 17910 } else if (OmpPrivParm->hasInit()) { 17911 DRD->setInitializer(OmpPrivParm->getInit(), 17912 OmpPrivParm->isDirectInit() 17913 ? OMPDeclareReductionDecl::DirectInit 17914 : OMPDeclareReductionDecl::CopyInit); 17915 } else { 17916 DRD->setInvalidDecl(); 17917 } 17918 } 17919 17920 Sema::DeclGroupPtrTy Sema::ActOnOpenMPDeclareReductionDirectiveEnd( 17921 Scope *S, DeclGroupPtrTy DeclReductions, bool IsValid) { 17922 for (Decl *D : DeclReductions.get()) { 17923 if (IsValid) { 17924 if (S) 17925 PushOnScopeChains(cast<OMPDeclareReductionDecl>(D), S, 17926 /*AddToContext=*/false); 17927 } else { 17928 D->setInvalidDecl(); 17929 } 17930 } 17931 return DeclReductions; 17932 } 17933 17934 TypeResult Sema::ActOnOpenMPDeclareMapperVarDecl(Scope *S, Declarator &D) { 17935 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); 17936 QualType T = TInfo->getType(); 17937 if (D.isInvalidType()) 17938 return true; 17939 17940 if (getLangOpts().CPlusPlus) { 17941 // Check that there are no default arguments (C++ only). 17942 CheckExtraCXXDefaultArguments(D); 17943 } 17944 17945 return CreateParsedType(T, TInfo); 17946 } 17947 17948 QualType Sema::ActOnOpenMPDeclareMapperType(SourceLocation TyLoc, 17949 TypeResult ParsedType) { 17950 assert(ParsedType.isUsable() && "Expect usable parsed mapper type"); 17951 17952 QualType MapperType = GetTypeFromParser(ParsedType.get()); 17953 assert(!MapperType.isNull() && "Expect valid mapper type"); 17954 17955 // [OpenMP 5.0], 2.19.7.3 declare mapper Directive, Restrictions 17956 // The type must be of struct, union or class type in C and C++ 17957 if (!MapperType->isStructureOrClassType() && !MapperType->isUnionType()) { 17958 Diag(TyLoc, diag::err_omp_mapper_wrong_type); 17959 return QualType(); 17960 } 17961 return MapperType; 17962 } 17963 17964 OMPDeclareMapperDecl *Sema::ActOnOpenMPDeclareMapperDirectiveStart( 17965 Scope *S, DeclContext *DC, DeclarationName Name, QualType MapperType, 17966 SourceLocation StartLoc, DeclarationName VN, AccessSpecifier AS, 17967 Decl *PrevDeclInScope) { 17968 LookupResult Lookup(*this, Name, SourceLocation(), LookupOMPMapperName, 17969 forRedeclarationInCurContext()); 17970 // [OpenMP 5.0], 2.19.7.3 declare mapper Directive, Restrictions 17971 // A mapper-identifier may not be redeclared in the current scope for the 17972 // same type or for a type that is compatible according to the base language 17973 // rules. 17974 llvm::DenseMap<QualType, SourceLocation> PreviousRedeclTypes; 17975 OMPDeclareMapperDecl *PrevDMD = nullptr; 17976 bool InCompoundScope = true; 17977 if (S != nullptr) { 17978 // Find previous declaration with the same name not referenced in other 17979 // declarations. 17980 FunctionScopeInfo *ParentFn = getEnclosingFunction(); 17981 InCompoundScope = 17982 (ParentFn != nullptr) && !ParentFn->CompoundScopes.empty(); 17983 LookupName(Lookup, S); 17984 FilterLookupForScope(Lookup, DC, S, /*ConsiderLinkage=*/false, 17985 /*AllowInlineNamespace=*/false); 17986 llvm::DenseMap<OMPDeclareMapperDecl *, bool> UsedAsPrevious; 17987 LookupResult::Filter Filter = Lookup.makeFilter(); 17988 while (Filter.hasNext()) { 17989 auto *PrevDecl = cast<OMPDeclareMapperDecl>(Filter.next()); 17990 if (InCompoundScope) { 17991 auto I = UsedAsPrevious.find(PrevDecl); 17992 if (I == UsedAsPrevious.end()) 17993 UsedAsPrevious[PrevDecl] = false; 17994 if (OMPDeclareMapperDecl *D = PrevDecl->getPrevDeclInScope()) 17995 UsedAsPrevious[D] = true; 17996 } 17997 PreviousRedeclTypes[PrevDecl->getType().getCanonicalType()] = 17998 PrevDecl->getLocation(); 17999 } 18000 Filter.done(); 18001 if (InCompoundScope) { 18002 for (const auto &PrevData : UsedAsPrevious) { 18003 if (!PrevData.second) { 18004 PrevDMD = PrevData.first; 18005 break; 18006 } 18007 } 18008 } 18009 } else if (PrevDeclInScope) { 18010 auto *PrevDMDInScope = PrevDMD = 18011 cast<OMPDeclareMapperDecl>(PrevDeclInScope); 18012 do { 18013 PreviousRedeclTypes[PrevDMDInScope->getType().getCanonicalType()] = 18014 PrevDMDInScope->getLocation(); 18015 PrevDMDInScope = PrevDMDInScope->getPrevDeclInScope(); 18016 } while (PrevDMDInScope != nullptr); 18017 } 18018 const auto I = PreviousRedeclTypes.find(MapperType.getCanonicalType()); 18019 bool Invalid = false; 18020 if (I != PreviousRedeclTypes.end()) { 18021 Diag(StartLoc, diag::err_omp_declare_mapper_redefinition) 18022 << MapperType << Name; 18023 Diag(I->second, diag::note_previous_definition); 18024 Invalid = true; 18025 } 18026 auto *DMD = OMPDeclareMapperDecl::Create(Context, DC, StartLoc, Name, 18027 MapperType, VN, PrevDMD); 18028 DC->addDecl(DMD); 18029 DMD->setAccess(AS); 18030 if (Invalid) 18031 DMD->setInvalidDecl(); 18032 18033 // Enter new function scope. 18034 PushFunctionScope(); 18035 setFunctionHasBranchProtectedScope(); 18036 18037 CurContext = DMD; 18038 18039 return DMD; 18040 } 18041 18042 void Sema::ActOnOpenMPDeclareMapperDirectiveVarDecl(OMPDeclareMapperDecl *DMD, 18043 Scope *S, 18044 QualType MapperType, 18045 SourceLocation StartLoc, 18046 DeclarationName VN) { 18047 VarDecl *VD = buildVarDecl(*this, StartLoc, MapperType, VN.getAsString()); 18048 if (S) 18049 PushOnScopeChains(VD, S); 18050 else 18051 DMD->addDecl(VD); 18052 Expr *MapperVarRefExpr = buildDeclRefExpr(*this, VD, MapperType, StartLoc); 18053 DMD->setMapperVarRef(MapperVarRefExpr); 18054 } 18055 18056 Sema::DeclGroupPtrTy 18057 Sema::ActOnOpenMPDeclareMapperDirectiveEnd(OMPDeclareMapperDecl *D, Scope *S, 18058 ArrayRef<OMPClause *> ClauseList) { 18059 PopDeclContext(); 18060 PopFunctionScopeInfo(); 18061 18062 if (D) { 18063 if (S) 18064 PushOnScopeChains(D, S, /*AddToContext=*/false); 18065 D->CreateClauses(Context, ClauseList); 18066 } 18067 18068 return DeclGroupPtrTy::make(DeclGroupRef(D)); 18069 } 18070 18071 OMPClause *Sema::ActOnOpenMPNumTeamsClause(Expr *NumTeams, 18072 SourceLocation StartLoc, 18073 SourceLocation LParenLoc, 18074 SourceLocation EndLoc) { 18075 Expr *ValExpr = NumTeams; 18076 Stmt *HelperValStmt = nullptr; 18077 18078 // OpenMP [teams Constrcut, Restrictions] 18079 // The num_teams expression must evaluate to a positive integer value. 18080 if (!isNonNegativeIntegerValue(ValExpr, *this, OMPC_num_teams, 18081 /*StrictlyPositive=*/true)) 18082 return nullptr; 18083 18084 OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective(); 18085 OpenMPDirectiveKind CaptureRegion = 18086 getOpenMPCaptureRegionForClause(DKind, OMPC_num_teams, LangOpts.OpenMP); 18087 if (CaptureRegion != OMPD_unknown && !CurContext->isDependentContext()) { 18088 ValExpr = MakeFullExpr(ValExpr).get(); 18089 llvm::MapVector<const Expr *, DeclRefExpr *> Captures; 18090 ValExpr = tryBuildCapture(*this, ValExpr, Captures).get(); 18091 HelperValStmt = buildPreInits(Context, Captures); 18092 } 18093 18094 return new (Context) OMPNumTeamsClause(ValExpr, HelperValStmt, CaptureRegion, 18095 StartLoc, LParenLoc, EndLoc); 18096 } 18097 18098 OMPClause *Sema::ActOnOpenMPThreadLimitClause(Expr *ThreadLimit, 18099 SourceLocation StartLoc, 18100 SourceLocation LParenLoc, 18101 SourceLocation EndLoc) { 18102 Expr *ValExpr = ThreadLimit; 18103 Stmt *HelperValStmt = nullptr; 18104 18105 // OpenMP [teams Constrcut, Restrictions] 18106 // The thread_limit expression must evaluate to a positive integer value. 18107 if (!isNonNegativeIntegerValue(ValExpr, *this, OMPC_thread_limit, 18108 /*StrictlyPositive=*/true)) 18109 return nullptr; 18110 18111 OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective(); 18112 OpenMPDirectiveKind CaptureRegion = getOpenMPCaptureRegionForClause( 18113 DKind, OMPC_thread_limit, LangOpts.OpenMP); 18114 if (CaptureRegion != OMPD_unknown && !CurContext->isDependentContext()) { 18115 ValExpr = MakeFullExpr(ValExpr).get(); 18116 llvm::MapVector<const Expr *, DeclRefExpr *> Captures; 18117 ValExpr = tryBuildCapture(*this, ValExpr, Captures).get(); 18118 HelperValStmt = buildPreInits(Context, Captures); 18119 } 18120 18121 return new (Context) OMPThreadLimitClause( 18122 ValExpr, HelperValStmt, CaptureRegion, StartLoc, LParenLoc, EndLoc); 18123 } 18124 18125 OMPClause *Sema::ActOnOpenMPPriorityClause(Expr *Priority, 18126 SourceLocation StartLoc, 18127 SourceLocation LParenLoc, 18128 SourceLocation EndLoc) { 18129 Expr *ValExpr = Priority; 18130 Stmt *HelperValStmt = nullptr; 18131 OpenMPDirectiveKind CaptureRegion = OMPD_unknown; 18132 18133 // OpenMP [2.9.1, task Constrcut] 18134 // The priority-value is a non-negative numerical scalar expression. 18135 if (!isNonNegativeIntegerValue( 18136 ValExpr, *this, OMPC_priority, 18137 /*StrictlyPositive=*/false, /*BuildCapture=*/true, 18138 DSAStack->getCurrentDirective(), &CaptureRegion, &HelperValStmt)) 18139 return nullptr; 18140 18141 return new (Context) OMPPriorityClause(ValExpr, HelperValStmt, CaptureRegion, 18142 StartLoc, LParenLoc, EndLoc); 18143 } 18144 18145 OMPClause *Sema::ActOnOpenMPGrainsizeClause(Expr *Grainsize, 18146 SourceLocation StartLoc, 18147 SourceLocation LParenLoc, 18148 SourceLocation EndLoc) { 18149 Expr *ValExpr = Grainsize; 18150 Stmt *HelperValStmt = nullptr; 18151 OpenMPDirectiveKind CaptureRegion = OMPD_unknown; 18152 18153 // OpenMP [2.9.2, taskloop Constrcut] 18154 // The parameter of the grainsize clause must be a positive integer 18155 // expression. 18156 if (!isNonNegativeIntegerValue( 18157 ValExpr, *this, OMPC_grainsize, 18158 /*StrictlyPositive=*/true, /*BuildCapture=*/true, 18159 DSAStack->getCurrentDirective(), &CaptureRegion, &HelperValStmt)) 18160 return nullptr; 18161 18162 return new (Context) OMPGrainsizeClause(ValExpr, HelperValStmt, CaptureRegion, 18163 StartLoc, LParenLoc, EndLoc); 18164 } 18165 18166 OMPClause *Sema::ActOnOpenMPNumTasksClause(Expr *NumTasks, 18167 SourceLocation StartLoc, 18168 SourceLocation LParenLoc, 18169 SourceLocation EndLoc) { 18170 Expr *ValExpr = NumTasks; 18171 Stmt *HelperValStmt = nullptr; 18172 OpenMPDirectiveKind CaptureRegion = OMPD_unknown; 18173 18174 // OpenMP [2.9.2, taskloop Constrcut] 18175 // The parameter of the num_tasks clause must be a positive integer 18176 // expression. 18177 if (!isNonNegativeIntegerValue( 18178 ValExpr, *this, OMPC_num_tasks, 18179 /*StrictlyPositive=*/true, /*BuildCapture=*/true, 18180 DSAStack->getCurrentDirective(), &CaptureRegion, &HelperValStmt)) 18181 return nullptr; 18182 18183 return new (Context) OMPNumTasksClause(ValExpr, HelperValStmt, CaptureRegion, 18184 StartLoc, LParenLoc, EndLoc); 18185 } 18186 18187 OMPClause *Sema::ActOnOpenMPHintClause(Expr *Hint, SourceLocation StartLoc, 18188 SourceLocation LParenLoc, 18189 SourceLocation EndLoc) { 18190 // OpenMP [2.13.2, critical construct, Description] 18191 // ... where hint-expression is an integer constant expression that evaluates 18192 // to a valid lock hint. 18193 ExprResult HintExpr = VerifyPositiveIntegerConstantInClause(Hint, OMPC_hint); 18194 if (HintExpr.isInvalid()) 18195 return nullptr; 18196 return new (Context) 18197 OMPHintClause(HintExpr.get(), StartLoc, LParenLoc, EndLoc); 18198 } 18199 18200 /// Tries to find omp_event_handle_t type. 18201 static bool findOMPEventHandleT(Sema &S, SourceLocation Loc, 18202 DSAStackTy *Stack) { 18203 QualType OMPEventHandleT = Stack->getOMPEventHandleT(); 18204 if (!OMPEventHandleT.isNull()) 18205 return true; 18206 IdentifierInfo *II = &S.PP.getIdentifierTable().get("omp_event_handle_t"); 18207 ParsedType PT = S.getTypeName(*II, Loc, S.getCurScope()); 18208 if (!PT.getAsOpaquePtr() || PT.get().isNull()) { 18209 S.Diag(Loc, diag::err_omp_implied_type_not_found) << "omp_event_handle_t"; 18210 return false; 18211 } 18212 Stack->setOMPEventHandleT(PT.get()); 18213 return true; 18214 } 18215 18216 OMPClause *Sema::ActOnOpenMPDetachClause(Expr *Evt, SourceLocation StartLoc, 18217 SourceLocation LParenLoc, 18218 SourceLocation EndLoc) { 18219 if (!Evt->isValueDependent() && !Evt->isTypeDependent() && 18220 !Evt->isInstantiationDependent() && 18221 !Evt->containsUnexpandedParameterPack()) { 18222 if (!findOMPEventHandleT(*this, Evt->getExprLoc(), DSAStack)) 18223 return nullptr; 18224 // OpenMP 5.0, 2.10.1 task Construct. 18225 // event-handle is a variable of the omp_event_handle_t type. 18226 auto *Ref = dyn_cast<DeclRefExpr>(Evt->IgnoreParenImpCasts()); 18227 if (!Ref) { 18228 Diag(Evt->getExprLoc(), diag::err_omp_var_expected) 18229 << "omp_event_handle_t" << 0 << Evt->getSourceRange(); 18230 return nullptr; 18231 } 18232 auto *VD = dyn_cast_or_null<VarDecl>(Ref->getDecl()); 18233 if (!VD) { 18234 Diag(Evt->getExprLoc(), diag::err_omp_var_expected) 18235 << "omp_event_handle_t" << 0 << Evt->getSourceRange(); 18236 return nullptr; 18237 } 18238 if (!Context.hasSameUnqualifiedType(DSAStack->getOMPEventHandleT(), 18239 VD->getType()) || 18240 VD->getType().isConstant(Context)) { 18241 Diag(Evt->getExprLoc(), diag::err_omp_var_expected) 18242 << "omp_event_handle_t" << 1 << VD->getType() 18243 << Evt->getSourceRange(); 18244 return nullptr; 18245 } 18246 // OpenMP 5.0, 2.10.1 task Construct 18247 // [detach clause]... The event-handle will be considered as if it was 18248 // specified on a firstprivate clause. 18249 DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(VD, /*FromParent=*/false); 18250 if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_firstprivate && 18251 DVar.RefExpr) { 18252 Diag(Evt->getExprLoc(), diag::err_omp_wrong_dsa) 18253 << getOpenMPClauseName(DVar.CKind) 18254 << getOpenMPClauseName(OMPC_firstprivate); 18255 reportOriginalDsa(*this, DSAStack, VD, DVar); 18256 return nullptr; 18257 } 18258 } 18259 18260 return new (Context) OMPDetachClause(Evt, StartLoc, LParenLoc, EndLoc); 18261 } 18262 18263 OMPClause *Sema::ActOnOpenMPDistScheduleClause( 18264 OpenMPDistScheduleClauseKind Kind, Expr *ChunkSize, SourceLocation StartLoc, 18265 SourceLocation LParenLoc, SourceLocation KindLoc, SourceLocation CommaLoc, 18266 SourceLocation EndLoc) { 18267 if (Kind == OMPC_DIST_SCHEDULE_unknown) { 18268 std::string Values; 18269 Values += "'"; 18270 Values += getOpenMPSimpleClauseTypeName(OMPC_dist_schedule, 0); 18271 Values += "'"; 18272 Diag(KindLoc, diag::err_omp_unexpected_clause_value) 18273 << Values << getOpenMPClauseName(OMPC_dist_schedule); 18274 return nullptr; 18275 } 18276 Expr *ValExpr = ChunkSize; 18277 Stmt *HelperValStmt = nullptr; 18278 if (ChunkSize) { 18279 if (!ChunkSize->isValueDependent() && !ChunkSize->isTypeDependent() && 18280 !ChunkSize->isInstantiationDependent() && 18281 !ChunkSize->containsUnexpandedParameterPack()) { 18282 SourceLocation ChunkSizeLoc = ChunkSize->getBeginLoc(); 18283 ExprResult Val = 18284 PerformOpenMPImplicitIntegerConversion(ChunkSizeLoc, ChunkSize); 18285 if (Val.isInvalid()) 18286 return nullptr; 18287 18288 ValExpr = Val.get(); 18289 18290 // OpenMP [2.7.1, Restrictions] 18291 // chunk_size must be a loop invariant integer expression with a positive 18292 // value. 18293 if (Optional<llvm::APSInt> Result = 18294 ValExpr->getIntegerConstantExpr(Context)) { 18295 if (Result->isSigned() && !Result->isStrictlyPositive()) { 18296 Diag(ChunkSizeLoc, diag::err_omp_negative_expression_in_clause) 18297 << "dist_schedule" << ChunkSize->getSourceRange(); 18298 return nullptr; 18299 } 18300 } else if (getOpenMPCaptureRegionForClause( 18301 DSAStack->getCurrentDirective(), OMPC_dist_schedule, 18302 LangOpts.OpenMP) != OMPD_unknown && 18303 !CurContext->isDependentContext()) { 18304 ValExpr = MakeFullExpr(ValExpr).get(); 18305 llvm::MapVector<const Expr *, DeclRefExpr *> Captures; 18306 ValExpr = tryBuildCapture(*this, ValExpr, Captures).get(); 18307 HelperValStmt = buildPreInits(Context, Captures); 18308 } 18309 } 18310 } 18311 18312 return new (Context) 18313 OMPDistScheduleClause(StartLoc, LParenLoc, KindLoc, CommaLoc, EndLoc, 18314 Kind, ValExpr, HelperValStmt); 18315 } 18316 18317 OMPClause *Sema::ActOnOpenMPDefaultmapClause( 18318 OpenMPDefaultmapClauseModifier M, OpenMPDefaultmapClauseKind Kind, 18319 SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation MLoc, 18320 SourceLocation KindLoc, SourceLocation EndLoc) { 18321 if (getLangOpts().OpenMP < 50) { 18322 if (M != OMPC_DEFAULTMAP_MODIFIER_tofrom || 18323 Kind != OMPC_DEFAULTMAP_scalar) { 18324 std::string Value; 18325 SourceLocation Loc; 18326 Value += "'"; 18327 if (M != OMPC_DEFAULTMAP_MODIFIER_tofrom) { 18328 Value += getOpenMPSimpleClauseTypeName(OMPC_defaultmap, 18329 OMPC_DEFAULTMAP_MODIFIER_tofrom); 18330 Loc = MLoc; 18331 } else { 18332 Value += getOpenMPSimpleClauseTypeName(OMPC_defaultmap, 18333 OMPC_DEFAULTMAP_scalar); 18334 Loc = KindLoc; 18335 } 18336 Value += "'"; 18337 Diag(Loc, diag::err_omp_unexpected_clause_value) 18338 << Value << getOpenMPClauseName(OMPC_defaultmap); 18339 return nullptr; 18340 } 18341 } else { 18342 bool isDefaultmapModifier = (M != OMPC_DEFAULTMAP_MODIFIER_unknown); 18343 bool isDefaultmapKind = (Kind != OMPC_DEFAULTMAP_unknown) || 18344 (LangOpts.OpenMP >= 50 && KindLoc.isInvalid()); 18345 if (!isDefaultmapKind || !isDefaultmapModifier) { 18346 std::string ModifierValue = "'alloc', 'from', 'to', 'tofrom', " 18347 "'firstprivate', 'none', 'default'"; 18348 std::string KindValue = "'scalar', 'aggregate', 'pointer'"; 18349 if (!isDefaultmapKind && isDefaultmapModifier) { 18350 Diag(KindLoc, diag::err_omp_unexpected_clause_value) 18351 << KindValue << getOpenMPClauseName(OMPC_defaultmap); 18352 } else if (isDefaultmapKind && !isDefaultmapModifier) { 18353 Diag(MLoc, diag::err_omp_unexpected_clause_value) 18354 << ModifierValue << getOpenMPClauseName(OMPC_defaultmap); 18355 } else { 18356 Diag(MLoc, diag::err_omp_unexpected_clause_value) 18357 << ModifierValue << getOpenMPClauseName(OMPC_defaultmap); 18358 Diag(KindLoc, diag::err_omp_unexpected_clause_value) 18359 << KindValue << getOpenMPClauseName(OMPC_defaultmap); 18360 } 18361 return nullptr; 18362 } 18363 18364 // OpenMP [5.0, 2.12.5, Restrictions, p. 174] 18365 // At most one defaultmap clause for each category can appear on the 18366 // directive. 18367 if (DSAStack->checkDefaultmapCategory(Kind)) { 18368 Diag(StartLoc, diag::err_omp_one_defaultmap_each_category); 18369 return nullptr; 18370 } 18371 } 18372 if (Kind == OMPC_DEFAULTMAP_unknown) { 18373 // Variable category is not specified - mark all categories. 18374 DSAStack->setDefaultDMAAttr(M, OMPC_DEFAULTMAP_aggregate, StartLoc); 18375 DSAStack->setDefaultDMAAttr(M, OMPC_DEFAULTMAP_scalar, StartLoc); 18376 DSAStack->setDefaultDMAAttr(M, OMPC_DEFAULTMAP_pointer, StartLoc); 18377 } else { 18378 DSAStack->setDefaultDMAAttr(M, Kind, StartLoc); 18379 } 18380 18381 return new (Context) 18382 OMPDefaultmapClause(StartLoc, LParenLoc, MLoc, KindLoc, EndLoc, Kind, M); 18383 } 18384 18385 bool Sema::ActOnStartOpenMPDeclareTargetDirective(SourceLocation Loc) { 18386 DeclContext *CurLexicalContext = getCurLexicalContext(); 18387 if (!CurLexicalContext->isFileContext() && 18388 !CurLexicalContext->isExternCContext() && 18389 !CurLexicalContext->isExternCXXContext() && 18390 !isa<CXXRecordDecl>(CurLexicalContext) && 18391 !isa<ClassTemplateDecl>(CurLexicalContext) && 18392 !isa<ClassTemplatePartialSpecializationDecl>(CurLexicalContext) && 18393 !isa<ClassTemplateSpecializationDecl>(CurLexicalContext)) { 18394 Diag(Loc, diag::err_omp_region_not_file_context); 18395 return false; 18396 } 18397 ++DeclareTargetNestingLevel; 18398 return true; 18399 } 18400 18401 void Sema::ActOnFinishOpenMPDeclareTargetDirective() { 18402 assert(DeclareTargetNestingLevel > 0 && 18403 "Unexpected ActOnFinishOpenMPDeclareTargetDirective"); 18404 --DeclareTargetNestingLevel; 18405 } 18406 18407 NamedDecl * 18408 Sema::lookupOpenMPDeclareTargetName(Scope *CurScope, CXXScopeSpec &ScopeSpec, 18409 const DeclarationNameInfo &Id, 18410 NamedDeclSetType &SameDirectiveDecls) { 18411 LookupResult Lookup(*this, Id, LookupOrdinaryName); 18412 LookupParsedName(Lookup, CurScope, &ScopeSpec, true); 18413 18414 if (Lookup.isAmbiguous()) 18415 return nullptr; 18416 Lookup.suppressDiagnostics(); 18417 18418 if (!Lookup.isSingleResult()) { 18419 VarOrFuncDeclFilterCCC CCC(*this); 18420 if (TypoCorrection Corrected = 18421 CorrectTypo(Id, LookupOrdinaryName, CurScope, nullptr, CCC, 18422 CTK_ErrorRecovery)) { 18423 diagnoseTypo(Corrected, PDiag(diag::err_undeclared_var_use_suggest) 18424 << Id.getName()); 18425 checkDeclIsAllowedInOpenMPTarget(nullptr, Corrected.getCorrectionDecl()); 18426 return nullptr; 18427 } 18428 18429 Diag(Id.getLoc(), diag::err_undeclared_var_use) << Id.getName(); 18430 return nullptr; 18431 } 18432 18433 NamedDecl *ND = Lookup.getAsSingle<NamedDecl>(); 18434 if (!isa<VarDecl>(ND) && !isa<FunctionDecl>(ND) && 18435 !isa<FunctionTemplateDecl>(ND)) { 18436 Diag(Id.getLoc(), diag::err_omp_invalid_target_decl) << Id.getName(); 18437 return nullptr; 18438 } 18439 if (!SameDirectiveDecls.insert(cast<NamedDecl>(ND->getCanonicalDecl()))) 18440 Diag(Id.getLoc(), diag::err_omp_declare_target_multiple) << Id.getName(); 18441 return ND; 18442 } 18443 18444 void Sema::ActOnOpenMPDeclareTargetName( 18445 NamedDecl *ND, SourceLocation Loc, OMPDeclareTargetDeclAttr::MapTypeTy MT, 18446 OMPDeclareTargetDeclAttr::DevTypeTy DT) { 18447 assert((isa<VarDecl>(ND) || isa<FunctionDecl>(ND) || 18448 isa<FunctionTemplateDecl>(ND)) && 18449 "Expected variable, function or function template."); 18450 18451 // Diagnose marking after use as it may lead to incorrect diagnosis and 18452 // codegen. 18453 if (LangOpts.OpenMP >= 50 && 18454 (ND->isUsed(/*CheckUsedAttr=*/false) || ND->isReferenced())) 18455 Diag(Loc, diag::warn_omp_declare_target_after_first_use); 18456 18457 Optional<OMPDeclareTargetDeclAttr::DevTypeTy> DevTy = 18458 OMPDeclareTargetDeclAttr::getDeviceType(cast<ValueDecl>(ND)); 18459 if (DevTy.hasValue() && *DevTy != DT) { 18460 Diag(Loc, diag::err_omp_device_type_mismatch) 18461 << OMPDeclareTargetDeclAttr::ConvertDevTypeTyToStr(DT) 18462 << OMPDeclareTargetDeclAttr::ConvertDevTypeTyToStr(*DevTy); 18463 return; 18464 } 18465 Optional<OMPDeclareTargetDeclAttr::MapTypeTy> Res = 18466 OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(cast<ValueDecl>(ND)); 18467 if (!Res) { 18468 auto *A = OMPDeclareTargetDeclAttr::CreateImplicit(Context, MT, DT, 18469 SourceRange(Loc, Loc)); 18470 ND->addAttr(A); 18471 if (ASTMutationListener *ML = Context.getASTMutationListener()) 18472 ML->DeclarationMarkedOpenMPDeclareTarget(ND, A); 18473 checkDeclIsAllowedInOpenMPTarget(nullptr, ND, Loc); 18474 } else if (*Res != MT) { 18475 Diag(Loc, diag::err_omp_declare_target_to_and_link) << ND; 18476 } 18477 } 18478 18479 static void checkDeclInTargetContext(SourceLocation SL, SourceRange SR, 18480 Sema &SemaRef, Decl *D) { 18481 if (!D || !isa<VarDecl>(D)) 18482 return; 18483 auto *VD = cast<VarDecl>(D); 18484 Optional<OMPDeclareTargetDeclAttr::MapTypeTy> MapTy = 18485 OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD); 18486 if (SemaRef.LangOpts.OpenMP >= 50 && 18487 (SemaRef.getCurLambda(/*IgnoreNonLambdaCapturingScope=*/true) || 18488 SemaRef.getCurBlock() || SemaRef.getCurCapturedRegion()) && 18489 VD->hasGlobalStorage()) { 18490 llvm::Optional<OMPDeclareTargetDeclAttr::MapTypeTy> MapTy = 18491 OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD); 18492 if (!MapTy || *MapTy != OMPDeclareTargetDeclAttr::MT_To) { 18493 // OpenMP 5.0, 2.12.7 declare target Directive, Restrictions 18494 // If a lambda declaration and definition appears between a 18495 // declare target directive and the matching end declare target 18496 // directive, all variables that are captured by the lambda 18497 // expression must also appear in a to clause. 18498 SemaRef.Diag(VD->getLocation(), 18499 diag::err_omp_lambda_capture_in_declare_target_not_to); 18500 SemaRef.Diag(SL, diag::note_var_explicitly_captured_here) 18501 << VD << 0 << SR; 18502 return; 18503 } 18504 } 18505 if (MapTy.hasValue()) 18506 return; 18507 SemaRef.Diag(VD->getLocation(), diag::warn_omp_not_in_target_context); 18508 SemaRef.Diag(SL, diag::note_used_here) << SR; 18509 } 18510 18511 static bool checkValueDeclInTarget(SourceLocation SL, SourceRange SR, 18512 Sema &SemaRef, DSAStackTy *Stack, 18513 ValueDecl *VD) { 18514 return OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD) || 18515 checkTypeMappable(SL, SR, SemaRef, Stack, VD->getType(), 18516 /*FullCheck=*/false); 18517 } 18518 18519 void Sema::checkDeclIsAllowedInOpenMPTarget(Expr *E, Decl *D, 18520 SourceLocation IdLoc) { 18521 if (!D || D->isInvalidDecl()) 18522 return; 18523 SourceRange SR = E ? E->getSourceRange() : D->getSourceRange(); 18524 SourceLocation SL = E ? E->getBeginLoc() : D->getLocation(); 18525 if (auto *VD = dyn_cast<VarDecl>(D)) { 18526 // Only global variables can be marked as declare target. 18527 if (!VD->isFileVarDecl() && !VD->isStaticLocal() && 18528 !VD->isStaticDataMember()) 18529 return; 18530 // 2.10.6: threadprivate variable cannot appear in a declare target 18531 // directive. 18532 if (DSAStack->isThreadPrivate(VD)) { 18533 Diag(SL, diag::err_omp_threadprivate_in_target); 18534 reportOriginalDsa(*this, DSAStack, VD, DSAStack->getTopDSA(VD, false)); 18535 return; 18536 } 18537 } 18538 if (const auto *FTD = dyn_cast<FunctionTemplateDecl>(D)) 18539 D = FTD->getTemplatedDecl(); 18540 if (auto *FD = dyn_cast<FunctionDecl>(D)) { 18541 llvm::Optional<OMPDeclareTargetDeclAttr::MapTypeTy> Res = 18542 OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(FD); 18543 if (IdLoc.isValid() && Res && *Res == OMPDeclareTargetDeclAttr::MT_Link) { 18544 Diag(IdLoc, diag::err_omp_function_in_link_clause); 18545 Diag(FD->getLocation(), diag::note_defined_here) << FD; 18546 return; 18547 } 18548 } 18549 if (auto *VD = dyn_cast<ValueDecl>(D)) { 18550 // Problem if any with var declared with incomplete type will be reported 18551 // as normal, so no need to check it here. 18552 if ((E || !VD->getType()->isIncompleteType()) && 18553 !checkValueDeclInTarget(SL, SR, *this, DSAStack, VD)) 18554 return; 18555 if (!E && !OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD)) { 18556 // Checking declaration inside declare target region. 18557 if (isa<VarDecl>(D) || isa<FunctionDecl>(D) || 18558 isa<FunctionTemplateDecl>(D)) { 18559 auto *A = OMPDeclareTargetDeclAttr::CreateImplicit( 18560 Context, OMPDeclareTargetDeclAttr::MT_To, 18561 OMPDeclareTargetDeclAttr::DT_Any, SourceRange(IdLoc, IdLoc)); 18562 D->addAttr(A); 18563 if (ASTMutationListener *ML = Context.getASTMutationListener()) 18564 ML->DeclarationMarkedOpenMPDeclareTarget(D, A); 18565 } 18566 return; 18567 } 18568 } 18569 if (!E) 18570 return; 18571 checkDeclInTargetContext(E->getExprLoc(), E->getSourceRange(), *this, D); 18572 } 18573 18574 OMPClause *Sema::ActOnOpenMPToClause(ArrayRef<Expr *> VarList, 18575 CXXScopeSpec &MapperIdScopeSpec, 18576 DeclarationNameInfo &MapperId, 18577 const OMPVarListLocTy &Locs, 18578 ArrayRef<Expr *> UnresolvedMappers) { 18579 MappableVarListInfo MVLI(VarList); 18580 checkMappableExpressionList(*this, DSAStack, OMPC_to, MVLI, Locs.StartLoc, 18581 MapperIdScopeSpec, MapperId, UnresolvedMappers); 18582 if (MVLI.ProcessedVarList.empty()) 18583 return nullptr; 18584 18585 return OMPToClause::Create( 18586 Context, Locs, MVLI.ProcessedVarList, MVLI.VarBaseDeclarations, 18587 MVLI.VarComponents, MVLI.UDMapperList, 18588 MapperIdScopeSpec.getWithLocInContext(Context), MapperId); 18589 } 18590 18591 OMPClause *Sema::ActOnOpenMPFromClause(ArrayRef<Expr *> VarList, 18592 CXXScopeSpec &MapperIdScopeSpec, 18593 DeclarationNameInfo &MapperId, 18594 const OMPVarListLocTy &Locs, 18595 ArrayRef<Expr *> UnresolvedMappers) { 18596 MappableVarListInfo MVLI(VarList); 18597 checkMappableExpressionList(*this, DSAStack, OMPC_from, MVLI, Locs.StartLoc, 18598 MapperIdScopeSpec, MapperId, UnresolvedMappers); 18599 if (MVLI.ProcessedVarList.empty()) 18600 return nullptr; 18601 18602 return OMPFromClause::Create( 18603 Context, Locs, MVLI.ProcessedVarList, MVLI.VarBaseDeclarations, 18604 MVLI.VarComponents, MVLI.UDMapperList, 18605 MapperIdScopeSpec.getWithLocInContext(Context), MapperId); 18606 } 18607 18608 OMPClause *Sema::ActOnOpenMPUseDevicePtrClause(ArrayRef<Expr *> VarList, 18609 const OMPVarListLocTy &Locs) { 18610 MappableVarListInfo MVLI(VarList); 18611 SmallVector<Expr *, 8> PrivateCopies; 18612 SmallVector<Expr *, 8> Inits; 18613 18614 for (Expr *RefExpr : VarList) { 18615 assert(RefExpr && "NULL expr in OpenMP use_device_ptr clause."); 18616 SourceLocation ELoc; 18617 SourceRange ERange; 18618 Expr *SimpleRefExpr = RefExpr; 18619 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange); 18620 if (Res.second) { 18621 // It will be analyzed later. 18622 MVLI.ProcessedVarList.push_back(RefExpr); 18623 PrivateCopies.push_back(nullptr); 18624 Inits.push_back(nullptr); 18625 } 18626 ValueDecl *D = Res.first; 18627 if (!D) 18628 continue; 18629 18630 QualType Type = D->getType(); 18631 Type = Type.getNonReferenceType().getUnqualifiedType(); 18632 18633 auto *VD = dyn_cast<VarDecl>(D); 18634 18635 // Item should be a pointer or reference to pointer. 18636 if (!Type->isPointerType()) { 18637 Diag(ELoc, diag::err_omp_usedeviceptr_not_a_pointer) 18638 << 0 << RefExpr->getSourceRange(); 18639 continue; 18640 } 18641 18642 // Build the private variable and the expression that refers to it. 18643 auto VDPrivate = 18644 buildVarDecl(*this, ELoc, Type, D->getName(), 18645 D->hasAttrs() ? &D->getAttrs() : nullptr, 18646 VD ? cast<DeclRefExpr>(SimpleRefExpr) : nullptr); 18647 if (VDPrivate->isInvalidDecl()) 18648 continue; 18649 18650 CurContext->addDecl(VDPrivate); 18651 DeclRefExpr *VDPrivateRefExpr = buildDeclRefExpr( 18652 *this, VDPrivate, RefExpr->getType().getUnqualifiedType(), ELoc); 18653 18654 // Add temporary variable to initialize the private copy of the pointer. 18655 VarDecl *VDInit = 18656 buildVarDecl(*this, RefExpr->getExprLoc(), Type, ".devptr.temp"); 18657 DeclRefExpr *VDInitRefExpr = buildDeclRefExpr( 18658 *this, VDInit, RefExpr->getType(), RefExpr->getExprLoc()); 18659 AddInitializerToDecl(VDPrivate, 18660 DefaultLvalueConversion(VDInitRefExpr).get(), 18661 /*DirectInit=*/false); 18662 18663 // If required, build a capture to implement the privatization initialized 18664 // with the current list item value. 18665 DeclRefExpr *Ref = nullptr; 18666 if (!VD) 18667 Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/true); 18668 MVLI.ProcessedVarList.push_back(VD ? RefExpr->IgnoreParens() : Ref); 18669 PrivateCopies.push_back(VDPrivateRefExpr); 18670 Inits.push_back(VDInitRefExpr); 18671 18672 // We need to add a data sharing attribute for this variable to make sure it 18673 // is correctly captured. A variable that shows up in a use_device_ptr has 18674 // similar properties of a first private variable. 18675 DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_firstprivate, Ref); 18676 18677 // Create a mappable component for the list item. List items in this clause 18678 // only need a component. 18679 MVLI.VarBaseDeclarations.push_back(D); 18680 MVLI.VarComponents.resize(MVLI.VarComponents.size() + 1); 18681 MVLI.VarComponents.back().push_back( 18682 OMPClauseMappableExprCommon::MappableComponent(SimpleRefExpr, D)); 18683 } 18684 18685 if (MVLI.ProcessedVarList.empty()) 18686 return nullptr; 18687 18688 return OMPUseDevicePtrClause::Create( 18689 Context, Locs, MVLI.ProcessedVarList, PrivateCopies, Inits, 18690 MVLI.VarBaseDeclarations, MVLI.VarComponents); 18691 } 18692 18693 OMPClause *Sema::ActOnOpenMPUseDeviceAddrClause(ArrayRef<Expr *> VarList, 18694 const OMPVarListLocTy &Locs) { 18695 MappableVarListInfo MVLI(VarList); 18696 18697 for (Expr *RefExpr : VarList) { 18698 assert(RefExpr && "NULL expr in OpenMP use_device_addr clause."); 18699 SourceLocation ELoc; 18700 SourceRange ERange; 18701 Expr *SimpleRefExpr = RefExpr; 18702 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange, 18703 /*AllowArraySection=*/true); 18704 if (Res.second) { 18705 // It will be analyzed later. 18706 MVLI.ProcessedVarList.push_back(RefExpr); 18707 } 18708 ValueDecl *D = Res.first; 18709 if (!D) 18710 continue; 18711 auto *VD = dyn_cast<VarDecl>(D); 18712 18713 // If required, build a capture to implement the privatization initialized 18714 // with the current list item value. 18715 DeclRefExpr *Ref = nullptr; 18716 if (!VD) 18717 Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/true); 18718 MVLI.ProcessedVarList.push_back(VD ? RefExpr->IgnoreParens() : Ref); 18719 18720 // We need to add a data sharing attribute for this variable to make sure it 18721 // is correctly captured. A variable that shows up in a use_device_addr has 18722 // similar properties of a first private variable. 18723 DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_firstprivate, Ref); 18724 18725 // Create a mappable component for the list item. List items in this clause 18726 // only need a component. 18727 MVLI.VarBaseDeclarations.push_back(D); 18728 MVLI.VarComponents.emplace_back(); 18729 Expr *Component = SimpleRefExpr; 18730 if (VD && (isa<OMPArraySectionExpr>(RefExpr->IgnoreParenImpCasts()) || 18731 isa<ArraySubscriptExpr>(RefExpr->IgnoreParenImpCasts()))) 18732 Component = DefaultFunctionArrayLvalueConversion(SimpleRefExpr).get(); 18733 MVLI.VarComponents.back().push_back( 18734 OMPClauseMappableExprCommon::MappableComponent(Component, D)); 18735 } 18736 18737 if (MVLI.ProcessedVarList.empty()) 18738 return nullptr; 18739 18740 return OMPUseDeviceAddrClause::Create(Context, Locs, MVLI.ProcessedVarList, 18741 MVLI.VarBaseDeclarations, 18742 MVLI.VarComponents); 18743 } 18744 18745 OMPClause *Sema::ActOnOpenMPIsDevicePtrClause(ArrayRef<Expr *> VarList, 18746 const OMPVarListLocTy &Locs) { 18747 MappableVarListInfo MVLI(VarList); 18748 for (Expr *RefExpr : VarList) { 18749 assert(RefExpr && "NULL expr in OpenMP is_device_ptr clause."); 18750 SourceLocation ELoc; 18751 SourceRange ERange; 18752 Expr *SimpleRefExpr = RefExpr; 18753 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange); 18754 if (Res.second) { 18755 // It will be analyzed later. 18756 MVLI.ProcessedVarList.push_back(RefExpr); 18757 } 18758 ValueDecl *D = Res.first; 18759 if (!D) 18760 continue; 18761 18762 QualType Type = D->getType(); 18763 // item should be a pointer or array or reference to pointer or array 18764 if (!Type.getNonReferenceType()->isPointerType() && 18765 !Type.getNonReferenceType()->isArrayType()) { 18766 Diag(ELoc, diag::err_omp_argument_type_isdeviceptr) 18767 << 0 << RefExpr->getSourceRange(); 18768 continue; 18769 } 18770 18771 // Check if the declaration in the clause does not show up in any data 18772 // sharing attribute. 18773 DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, /*FromParent=*/false); 18774 if (isOpenMPPrivate(DVar.CKind)) { 18775 Diag(ELoc, diag::err_omp_variable_in_given_clause_and_dsa) 18776 << getOpenMPClauseName(DVar.CKind) 18777 << getOpenMPClauseName(OMPC_is_device_ptr) 18778 << getOpenMPDirectiveName(DSAStack->getCurrentDirective()); 18779 reportOriginalDsa(*this, DSAStack, D, DVar); 18780 continue; 18781 } 18782 18783 const Expr *ConflictExpr; 18784 if (DSAStack->checkMappableExprComponentListsForDecl( 18785 D, /*CurrentRegionOnly=*/true, 18786 [&ConflictExpr]( 18787 OMPClauseMappableExprCommon::MappableExprComponentListRef R, 18788 OpenMPClauseKind) -> bool { 18789 ConflictExpr = R.front().getAssociatedExpression(); 18790 return true; 18791 })) { 18792 Diag(ELoc, diag::err_omp_map_shared_storage) << RefExpr->getSourceRange(); 18793 Diag(ConflictExpr->getExprLoc(), diag::note_used_here) 18794 << ConflictExpr->getSourceRange(); 18795 continue; 18796 } 18797 18798 // Store the components in the stack so that they can be used to check 18799 // against other clauses later on. 18800 OMPClauseMappableExprCommon::MappableComponent MC(SimpleRefExpr, D); 18801 DSAStack->addMappableExpressionComponents( 18802 D, MC, /*WhereFoundClauseKind=*/OMPC_is_device_ptr); 18803 18804 // Record the expression we've just processed. 18805 MVLI.ProcessedVarList.push_back(SimpleRefExpr); 18806 18807 // Create a mappable component for the list item. List items in this clause 18808 // only need a component. We use a null declaration to signal fields in 18809 // 'this'. 18810 assert((isa<DeclRefExpr>(SimpleRefExpr) || 18811 isa<CXXThisExpr>(cast<MemberExpr>(SimpleRefExpr)->getBase())) && 18812 "Unexpected device pointer expression!"); 18813 MVLI.VarBaseDeclarations.push_back( 18814 isa<DeclRefExpr>(SimpleRefExpr) ? D : nullptr); 18815 MVLI.VarComponents.resize(MVLI.VarComponents.size() + 1); 18816 MVLI.VarComponents.back().push_back(MC); 18817 } 18818 18819 if (MVLI.ProcessedVarList.empty()) 18820 return nullptr; 18821 18822 return OMPIsDevicePtrClause::Create(Context, Locs, MVLI.ProcessedVarList, 18823 MVLI.VarBaseDeclarations, 18824 MVLI.VarComponents); 18825 } 18826 18827 OMPClause *Sema::ActOnOpenMPAllocateClause( 18828 Expr *Allocator, ArrayRef<Expr *> VarList, SourceLocation StartLoc, 18829 SourceLocation ColonLoc, SourceLocation LParenLoc, SourceLocation EndLoc) { 18830 if (Allocator) { 18831 // OpenMP [2.11.4 allocate Clause, Description] 18832 // allocator is an expression of omp_allocator_handle_t type. 18833 if (!findOMPAllocatorHandleT(*this, Allocator->getExprLoc(), DSAStack)) 18834 return nullptr; 18835 18836 ExprResult AllocatorRes = DefaultLvalueConversion(Allocator); 18837 if (AllocatorRes.isInvalid()) 18838 return nullptr; 18839 AllocatorRes = PerformImplicitConversion(AllocatorRes.get(), 18840 DSAStack->getOMPAllocatorHandleT(), 18841 Sema::AA_Initializing, 18842 /*AllowExplicit=*/true); 18843 if (AllocatorRes.isInvalid()) 18844 return nullptr; 18845 Allocator = AllocatorRes.get(); 18846 } else { 18847 // OpenMP 5.0, 2.11.4 allocate Clause, Restrictions. 18848 // allocate clauses that appear on a target construct or on constructs in a 18849 // target region must specify an allocator expression unless a requires 18850 // directive with the dynamic_allocators clause is present in the same 18851 // compilation unit. 18852 if (LangOpts.OpenMPIsDevice && 18853 !DSAStack->hasRequiresDeclWithClause<OMPDynamicAllocatorsClause>()) 18854 targetDiag(StartLoc, diag::err_expected_allocator_expression); 18855 } 18856 // Analyze and build list of variables. 18857 SmallVector<Expr *, 8> Vars; 18858 for (Expr *RefExpr : VarList) { 18859 assert(RefExpr && "NULL expr in OpenMP private clause."); 18860 SourceLocation ELoc; 18861 SourceRange ERange; 18862 Expr *SimpleRefExpr = RefExpr; 18863 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange); 18864 if (Res.second) { 18865 // It will be analyzed later. 18866 Vars.push_back(RefExpr); 18867 } 18868 ValueDecl *D = Res.first; 18869 if (!D) 18870 continue; 18871 18872 auto *VD = dyn_cast<VarDecl>(D); 18873 DeclRefExpr *Ref = nullptr; 18874 if (!VD && !CurContext->isDependentContext()) 18875 Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/false); 18876 Vars.push_back((VD || CurContext->isDependentContext()) 18877 ? RefExpr->IgnoreParens() 18878 : Ref); 18879 } 18880 18881 if (Vars.empty()) 18882 return nullptr; 18883 18884 if (Allocator) 18885 DSAStack->addInnerAllocatorExpr(Allocator); 18886 return OMPAllocateClause::Create(Context, StartLoc, LParenLoc, Allocator, 18887 ColonLoc, EndLoc, Vars); 18888 } 18889 18890 OMPClause *Sema::ActOnOpenMPNontemporalClause(ArrayRef<Expr *> VarList, 18891 SourceLocation StartLoc, 18892 SourceLocation LParenLoc, 18893 SourceLocation EndLoc) { 18894 SmallVector<Expr *, 8> Vars; 18895 for (Expr *RefExpr : VarList) { 18896 assert(RefExpr && "NULL expr in OpenMP nontemporal clause."); 18897 SourceLocation ELoc; 18898 SourceRange ERange; 18899 Expr *SimpleRefExpr = RefExpr; 18900 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange); 18901 if (Res.second) 18902 // It will be analyzed later. 18903 Vars.push_back(RefExpr); 18904 ValueDecl *D = Res.first; 18905 if (!D) 18906 continue; 18907 18908 // OpenMP 5.0, 2.9.3.1 simd Construct, Restrictions. 18909 // A list-item cannot appear in more than one nontemporal clause. 18910 if (const Expr *PrevRef = 18911 DSAStack->addUniqueNontemporal(D, SimpleRefExpr)) { 18912 Diag(ELoc, diag::err_omp_used_in_clause_twice) 18913 << 0 << getOpenMPClauseName(OMPC_nontemporal) << ERange; 18914 Diag(PrevRef->getExprLoc(), diag::note_omp_explicit_dsa) 18915 << getOpenMPClauseName(OMPC_nontemporal); 18916 continue; 18917 } 18918 18919 Vars.push_back(RefExpr); 18920 } 18921 18922 if (Vars.empty()) 18923 return nullptr; 18924 18925 return OMPNontemporalClause::Create(Context, StartLoc, LParenLoc, EndLoc, 18926 Vars); 18927 } 18928 18929 OMPClause *Sema::ActOnOpenMPInclusiveClause(ArrayRef<Expr *> VarList, 18930 SourceLocation StartLoc, 18931 SourceLocation LParenLoc, 18932 SourceLocation EndLoc) { 18933 SmallVector<Expr *, 8> Vars; 18934 for (Expr *RefExpr : VarList) { 18935 assert(RefExpr && "NULL expr in OpenMP nontemporal clause."); 18936 SourceLocation ELoc; 18937 SourceRange ERange; 18938 Expr *SimpleRefExpr = RefExpr; 18939 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange, 18940 /*AllowArraySection=*/true); 18941 if (Res.second) 18942 // It will be analyzed later. 18943 Vars.push_back(RefExpr); 18944 ValueDecl *D = Res.first; 18945 if (!D) 18946 continue; 18947 18948 const DSAStackTy::DSAVarData DVar = 18949 DSAStack->getTopDSA(D, /*FromParent=*/true); 18950 // OpenMP 5.0, 2.9.6, scan Directive, Restrictions. 18951 // A list item that appears in the inclusive or exclusive clause must appear 18952 // in a reduction clause with the inscan modifier on the enclosing 18953 // worksharing-loop, worksharing-loop SIMD, or simd construct. 18954 if (DVar.CKind != OMPC_reduction || 18955 DVar.Modifier != OMPC_REDUCTION_inscan) 18956 Diag(ELoc, diag::err_omp_inclusive_exclusive_not_reduction) 18957 << RefExpr->getSourceRange(); 18958 18959 if (DSAStack->getParentDirective() != OMPD_unknown) 18960 DSAStack->markDeclAsUsedInScanDirective(D); 18961 Vars.push_back(RefExpr); 18962 } 18963 18964 if (Vars.empty()) 18965 return nullptr; 18966 18967 return OMPInclusiveClause::Create(Context, StartLoc, LParenLoc, EndLoc, Vars); 18968 } 18969 18970 OMPClause *Sema::ActOnOpenMPExclusiveClause(ArrayRef<Expr *> VarList, 18971 SourceLocation StartLoc, 18972 SourceLocation LParenLoc, 18973 SourceLocation EndLoc) { 18974 SmallVector<Expr *, 8> Vars; 18975 for (Expr *RefExpr : VarList) { 18976 assert(RefExpr && "NULL expr in OpenMP nontemporal clause."); 18977 SourceLocation ELoc; 18978 SourceRange ERange; 18979 Expr *SimpleRefExpr = RefExpr; 18980 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange, 18981 /*AllowArraySection=*/true); 18982 if (Res.second) 18983 // It will be analyzed later. 18984 Vars.push_back(RefExpr); 18985 ValueDecl *D = Res.first; 18986 if (!D) 18987 continue; 18988 18989 OpenMPDirectiveKind ParentDirective = DSAStack->getParentDirective(); 18990 DSAStackTy::DSAVarData DVar; 18991 if (ParentDirective != OMPD_unknown) 18992 DVar = DSAStack->getTopDSA(D, /*FromParent=*/true); 18993 // OpenMP 5.0, 2.9.6, scan Directive, Restrictions. 18994 // A list item that appears in the inclusive or exclusive clause must appear 18995 // in a reduction clause with the inscan modifier on the enclosing 18996 // worksharing-loop, worksharing-loop SIMD, or simd construct. 18997 if (ParentDirective == OMPD_unknown || DVar.CKind != OMPC_reduction || 18998 DVar.Modifier != OMPC_REDUCTION_inscan) { 18999 Diag(ELoc, diag::err_omp_inclusive_exclusive_not_reduction) 19000 << RefExpr->getSourceRange(); 19001 } else { 19002 DSAStack->markDeclAsUsedInScanDirective(D); 19003 } 19004 Vars.push_back(RefExpr); 19005 } 19006 19007 if (Vars.empty()) 19008 return nullptr; 19009 19010 return OMPExclusiveClause::Create(Context, StartLoc, LParenLoc, EndLoc, Vars); 19011 } 19012 19013 /// Tries to find omp_alloctrait_t type. 19014 static bool findOMPAlloctraitT(Sema &S, SourceLocation Loc, DSAStackTy *Stack) { 19015 QualType OMPAlloctraitT = Stack->getOMPAlloctraitT(); 19016 if (!OMPAlloctraitT.isNull()) 19017 return true; 19018 IdentifierInfo &II = S.PP.getIdentifierTable().get("omp_alloctrait_t"); 19019 ParsedType PT = S.getTypeName(II, Loc, S.getCurScope()); 19020 if (!PT.getAsOpaquePtr() || PT.get().isNull()) { 19021 S.Diag(Loc, diag::err_omp_implied_type_not_found) << "omp_alloctrait_t"; 19022 return false; 19023 } 19024 Stack->setOMPAlloctraitT(PT.get()); 19025 return true; 19026 } 19027 19028 OMPClause *Sema::ActOnOpenMPUsesAllocatorClause( 19029 SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc, 19030 ArrayRef<UsesAllocatorsData> Data) { 19031 // OpenMP [2.12.5, target Construct] 19032 // allocator is an identifier of omp_allocator_handle_t type. 19033 if (!findOMPAllocatorHandleT(*this, StartLoc, DSAStack)) 19034 return nullptr; 19035 // OpenMP [2.12.5, target Construct] 19036 // allocator-traits-array is an identifier of const omp_alloctrait_t * type. 19037 if (llvm::any_of( 19038 Data, 19039 [](const UsesAllocatorsData &D) { return D.AllocatorTraits; }) && 19040 !findOMPAlloctraitT(*this, StartLoc, DSAStack)) 19041 return nullptr; 19042 llvm::SmallPtrSet<CanonicalDeclPtr<Decl>, 4> PredefinedAllocators; 19043 for (int I = 0; I < OMPAllocateDeclAttr::OMPUserDefinedMemAlloc; ++I) { 19044 auto AllocatorKind = static_cast<OMPAllocateDeclAttr::AllocatorTypeTy>(I); 19045 StringRef Allocator = 19046 OMPAllocateDeclAttr::ConvertAllocatorTypeTyToStr(AllocatorKind); 19047 DeclarationName AllocatorName = &Context.Idents.get(Allocator); 19048 PredefinedAllocators.insert(LookupSingleName( 19049 TUScope, AllocatorName, StartLoc, Sema::LookupAnyName)); 19050 } 19051 19052 SmallVector<OMPUsesAllocatorsClause::Data, 4> NewData; 19053 for (const UsesAllocatorsData &D : Data) { 19054 Expr *AllocatorExpr = nullptr; 19055 // Check allocator expression. 19056 if (D.Allocator->isTypeDependent()) { 19057 AllocatorExpr = D.Allocator; 19058 } else { 19059 // Traits were specified - need to assign new allocator to the specified 19060 // allocator, so it must be an lvalue. 19061 AllocatorExpr = D.Allocator->IgnoreParenImpCasts(); 19062 auto *DRE = dyn_cast<DeclRefExpr>(AllocatorExpr); 19063 bool IsPredefinedAllocator = false; 19064 if (DRE) 19065 IsPredefinedAllocator = PredefinedAllocators.count(DRE->getDecl()); 19066 if (!DRE || 19067 !(Context.hasSameUnqualifiedType( 19068 AllocatorExpr->getType(), DSAStack->getOMPAllocatorHandleT()) || 19069 Context.typesAreCompatible(AllocatorExpr->getType(), 19070 DSAStack->getOMPAllocatorHandleT(), 19071 /*CompareUnqualified=*/true)) || 19072 (!IsPredefinedAllocator && 19073 (AllocatorExpr->getType().isConstant(Context) || 19074 !AllocatorExpr->isLValue()))) { 19075 Diag(D.Allocator->getExprLoc(), diag::err_omp_var_expected) 19076 << "omp_allocator_handle_t" << (DRE ? 1 : 0) 19077 << AllocatorExpr->getType() << D.Allocator->getSourceRange(); 19078 continue; 19079 } 19080 // OpenMP [2.12.5, target Construct] 19081 // Predefined allocators appearing in a uses_allocators clause cannot have 19082 // traits specified. 19083 if (IsPredefinedAllocator && D.AllocatorTraits) { 19084 Diag(D.AllocatorTraits->getExprLoc(), 19085 diag::err_omp_predefined_allocator_with_traits) 19086 << D.AllocatorTraits->getSourceRange(); 19087 Diag(D.Allocator->getExprLoc(), diag::note_omp_predefined_allocator) 19088 << cast<NamedDecl>(DRE->getDecl())->getName() 19089 << D.Allocator->getSourceRange(); 19090 continue; 19091 } 19092 // OpenMP [2.12.5, target Construct] 19093 // Non-predefined allocators appearing in a uses_allocators clause must 19094 // have traits specified. 19095 if (!IsPredefinedAllocator && !D.AllocatorTraits) { 19096 Diag(D.Allocator->getExprLoc(), 19097 diag::err_omp_nonpredefined_allocator_without_traits); 19098 continue; 19099 } 19100 // No allocator traits - just convert it to rvalue. 19101 if (!D.AllocatorTraits) 19102 AllocatorExpr = DefaultLvalueConversion(AllocatorExpr).get(); 19103 DSAStack->addUsesAllocatorsDecl( 19104 DRE->getDecl(), 19105 IsPredefinedAllocator 19106 ? DSAStackTy::UsesAllocatorsDeclKind::PredefinedAllocator 19107 : DSAStackTy::UsesAllocatorsDeclKind::UserDefinedAllocator); 19108 } 19109 Expr *AllocatorTraitsExpr = nullptr; 19110 if (D.AllocatorTraits) { 19111 if (D.AllocatorTraits->isTypeDependent()) { 19112 AllocatorTraitsExpr = D.AllocatorTraits; 19113 } else { 19114 // OpenMP [2.12.5, target Construct] 19115 // Arrays that contain allocator traits that appear in a uses_allocators 19116 // clause must be constant arrays, have constant values and be defined 19117 // in the same scope as the construct in which the clause appears. 19118 AllocatorTraitsExpr = D.AllocatorTraits->IgnoreParenImpCasts(); 19119 // Check that traits expr is a constant array. 19120 QualType TraitTy; 19121 if (const ArrayType *Ty = 19122 AllocatorTraitsExpr->getType()->getAsArrayTypeUnsafe()) 19123 if (const auto *ConstArrayTy = dyn_cast<ConstantArrayType>(Ty)) 19124 TraitTy = ConstArrayTy->getElementType(); 19125 if (TraitTy.isNull() || 19126 !(Context.hasSameUnqualifiedType(TraitTy, 19127 DSAStack->getOMPAlloctraitT()) || 19128 Context.typesAreCompatible(TraitTy, DSAStack->getOMPAlloctraitT(), 19129 /*CompareUnqualified=*/true))) { 19130 Diag(D.AllocatorTraits->getExprLoc(), 19131 diag::err_omp_expected_array_alloctraits) 19132 << AllocatorTraitsExpr->getType(); 19133 continue; 19134 } 19135 // Do not map by default allocator traits if it is a standalone 19136 // variable. 19137 if (auto *DRE = dyn_cast<DeclRefExpr>(AllocatorTraitsExpr)) 19138 DSAStack->addUsesAllocatorsDecl( 19139 DRE->getDecl(), 19140 DSAStackTy::UsesAllocatorsDeclKind::AllocatorTrait); 19141 } 19142 } 19143 OMPUsesAllocatorsClause::Data &NewD = NewData.emplace_back(); 19144 NewD.Allocator = AllocatorExpr; 19145 NewD.AllocatorTraits = AllocatorTraitsExpr; 19146 NewD.LParenLoc = D.LParenLoc; 19147 NewD.RParenLoc = D.RParenLoc; 19148 } 19149 return OMPUsesAllocatorsClause::Create(Context, StartLoc, LParenLoc, EndLoc, 19150 NewData); 19151 } 19152 19153 OMPClause *Sema::ActOnOpenMPAffinityClause( 19154 SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation ColonLoc, 19155 SourceLocation EndLoc, Expr *Modifier, ArrayRef<Expr *> Locators) { 19156 SmallVector<Expr *, 8> Vars; 19157 for (Expr *RefExpr : Locators) { 19158 assert(RefExpr && "NULL expr in OpenMP shared clause."); 19159 if (isa<DependentScopeDeclRefExpr>(RefExpr) || RefExpr->isTypeDependent()) { 19160 // It will be analyzed later. 19161 Vars.push_back(RefExpr); 19162 continue; 19163 } 19164 19165 SourceLocation ELoc = RefExpr->getExprLoc(); 19166 Expr *SimpleExpr = RefExpr->IgnoreParenImpCasts(); 19167 19168 if (!SimpleExpr->isLValue()) { 19169 Diag(ELoc, diag::err_omp_expected_addressable_lvalue_or_array_item) 19170 << 1 << 0 << RefExpr->getSourceRange(); 19171 continue; 19172 } 19173 19174 ExprResult Res; 19175 { 19176 Sema::TentativeAnalysisScope Trap(*this); 19177 Res = CreateBuiltinUnaryOp(ELoc, UO_AddrOf, SimpleExpr); 19178 } 19179 if (!Res.isUsable() && !isa<OMPArraySectionExpr>(SimpleExpr) && 19180 !isa<OMPArrayShapingExpr>(SimpleExpr)) { 19181 Diag(ELoc, diag::err_omp_expected_addressable_lvalue_or_array_item) 19182 << 1 << 0 << RefExpr->getSourceRange(); 19183 continue; 19184 } 19185 Vars.push_back(SimpleExpr); 19186 } 19187 19188 return OMPAffinityClause::Create(Context, StartLoc, LParenLoc, ColonLoc, 19189 EndLoc, Modifier, Vars); 19190 } 19191