1 //===--- SemaOpenMP.cpp - Semantic Analysis for OpenMP constructs ---------===// 2 // 3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 4 // See https://llvm.org/LICENSE.txt for license information. 5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 6 // 7 //===----------------------------------------------------------------------===// 8 /// \file 9 /// This file implements semantic analysis for OpenMP directives and 10 /// clauses. 11 /// 12 //===----------------------------------------------------------------------===// 13 14 #include "TreeTransform.h" 15 #include "clang/AST/ASTContext.h" 16 #include "clang/AST/ASTMutationListener.h" 17 #include "clang/AST/CXXInheritance.h" 18 #include "clang/AST/Decl.h" 19 #include "clang/AST/DeclCXX.h" 20 #include "clang/AST/DeclOpenMP.h" 21 #include "clang/AST/StmtCXX.h" 22 #include "clang/AST/StmtOpenMP.h" 23 #include "clang/AST/StmtVisitor.h" 24 #include "clang/AST/TypeOrdering.h" 25 #include "clang/Basic/DiagnosticSema.h" 26 #include "clang/Basic/OpenMPKinds.h" 27 #include "clang/Basic/PartialDiagnostic.h" 28 #include "clang/Basic/TargetInfo.h" 29 #include "clang/Sema/Initialization.h" 30 #include "clang/Sema/Lookup.h" 31 #include "clang/Sema/Scope.h" 32 #include "clang/Sema/ScopeInfo.h" 33 #include "clang/Sema/SemaInternal.h" 34 #include "llvm/ADT/IndexedMap.h" 35 #include "llvm/ADT/PointerEmbeddedInt.h" 36 #include "llvm/ADT/STLExtras.h" 37 #include "llvm/Frontend/OpenMP/OMPConstants.h" 38 using namespace clang; 39 using namespace llvm::omp; 40 41 //===----------------------------------------------------------------------===// 42 // Stack of data-sharing attributes for variables 43 //===----------------------------------------------------------------------===// 44 45 static const Expr *checkMapClauseExpressionBase( 46 Sema &SemaRef, Expr *E, 47 OMPClauseMappableExprCommon::MappableExprComponentList &CurComponents, 48 OpenMPClauseKind CKind, bool NoDiagnose); 49 50 namespace { 51 /// Default data sharing attributes, which can be applied to directive. 52 enum DefaultDataSharingAttributes { 53 DSA_unspecified = 0, /// Data sharing attribute not specified. 54 DSA_none = 1 << 0, /// Default data sharing attribute 'none'. 55 DSA_shared = 1 << 1, /// Default data sharing attribute 'shared'. 56 }; 57 58 /// Stack for tracking declarations used in OpenMP directives and 59 /// clauses and their data-sharing attributes. 60 class DSAStackTy { 61 public: 62 struct DSAVarData { 63 OpenMPDirectiveKind DKind = OMPD_unknown; 64 OpenMPClauseKind CKind = OMPC_unknown; 65 unsigned Modifier = 0; 66 const Expr *RefExpr = nullptr; 67 DeclRefExpr *PrivateCopy = nullptr; 68 SourceLocation ImplicitDSALoc; 69 DSAVarData() = default; 70 DSAVarData(OpenMPDirectiveKind DKind, OpenMPClauseKind CKind, 71 const Expr *RefExpr, DeclRefExpr *PrivateCopy, 72 SourceLocation ImplicitDSALoc, unsigned Modifier) 73 : DKind(DKind), CKind(CKind), Modifier(Modifier), RefExpr(RefExpr), 74 PrivateCopy(PrivateCopy), ImplicitDSALoc(ImplicitDSALoc) {} 75 }; 76 using OperatorOffsetTy = 77 llvm::SmallVector<std::pair<Expr *, OverloadedOperatorKind>, 4>; 78 using DoacrossDependMapTy = 79 llvm::DenseMap<OMPDependClause *, OperatorOffsetTy>; 80 81 private: 82 struct DSAInfo { 83 OpenMPClauseKind Attributes = OMPC_unknown; 84 unsigned Modifier = 0; 85 /// Pointer to a reference expression and a flag which shows that the 86 /// variable is marked as lastprivate(true) or not (false). 87 llvm::PointerIntPair<const Expr *, 1, bool> RefExpr; 88 DeclRefExpr *PrivateCopy = nullptr; 89 }; 90 using DeclSAMapTy = llvm::SmallDenseMap<const ValueDecl *, DSAInfo, 8>; 91 using UsedRefMapTy = llvm::SmallDenseMap<const ValueDecl *, const Expr *, 8>; 92 using LCDeclInfo = std::pair<unsigned, VarDecl *>; 93 using LoopControlVariablesMapTy = 94 llvm::SmallDenseMap<const ValueDecl *, LCDeclInfo, 8>; 95 /// Struct that associates a component with the clause kind where they are 96 /// found. 97 struct MappedExprComponentTy { 98 OMPClauseMappableExprCommon::MappableExprComponentLists Components; 99 OpenMPClauseKind Kind = OMPC_unknown; 100 }; 101 using MappedExprComponentsTy = 102 llvm::DenseMap<const ValueDecl *, MappedExprComponentTy>; 103 using CriticalsWithHintsTy = 104 llvm::StringMap<std::pair<const OMPCriticalDirective *, llvm::APSInt>>; 105 struct ReductionData { 106 using BOKPtrType = llvm::PointerEmbeddedInt<BinaryOperatorKind, 16>; 107 SourceRange ReductionRange; 108 llvm::PointerUnion<const Expr *, BOKPtrType> ReductionOp; 109 ReductionData() = default; 110 void set(BinaryOperatorKind BO, SourceRange RR) { 111 ReductionRange = RR; 112 ReductionOp = BO; 113 } 114 void set(const Expr *RefExpr, SourceRange RR) { 115 ReductionRange = RR; 116 ReductionOp = RefExpr; 117 } 118 }; 119 using DeclReductionMapTy = 120 llvm::SmallDenseMap<const ValueDecl *, ReductionData, 4>; 121 struct DefaultmapInfo { 122 OpenMPDefaultmapClauseModifier ImplicitBehavior = 123 OMPC_DEFAULTMAP_MODIFIER_unknown; 124 SourceLocation SLoc; 125 DefaultmapInfo() = default; 126 DefaultmapInfo(OpenMPDefaultmapClauseModifier M, SourceLocation Loc) 127 : ImplicitBehavior(M), SLoc(Loc) {} 128 }; 129 130 struct SharingMapTy { 131 DeclSAMapTy SharingMap; 132 DeclReductionMapTy ReductionMap; 133 UsedRefMapTy AlignedMap; 134 UsedRefMapTy NontemporalMap; 135 MappedExprComponentsTy MappedExprComponents; 136 LoopControlVariablesMapTy LCVMap; 137 DefaultDataSharingAttributes DefaultAttr = DSA_unspecified; 138 SourceLocation DefaultAttrLoc; 139 DefaultmapInfo DefaultmapMap[OMPC_DEFAULTMAP_unknown]; 140 OpenMPDirectiveKind Directive = OMPD_unknown; 141 DeclarationNameInfo DirectiveName; 142 Scope *CurScope = nullptr; 143 SourceLocation ConstructLoc; 144 /// Set of 'depend' clauses with 'sink|source' dependence kind. Required to 145 /// get the data (loop counters etc.) about enclosing loop-based construct. 146 /// This data is required during codegen. 147 DoacrossDependMapTy DoacrossDepends; 148 /// First argument (Expr *) contains optional argument of the 149 /// 'ordered' clause, the second one is true if the regions has 'ordered' 150 /// clause, false otherwise. 151 llvm::Optional<std::pair<const Expr *, OMPOrderedClause *>> OrderedRegion; 152 unsigned AssociatedLoops = 1; 153 bool HasMutipleLoops = false; 154 const Decl *PossiblyLoopCounter = nullptr; 155 bool NowaitRegion = false; 156 bool CancelRegion = false; 157 bool LoopStart = false; 158 bool BodyComplete = false; 159 SourceLocation PrevScanLocation; 160 SourceLocation InnerTeamsRegionLoc; 161 /// Reference to the taskgroup task_reduction reference expression. 162 Expr *TaskgroupReductionRef = nullptr; 163 llvm::DenseSet<QualType> MappedClassesQualTypes; 164 SmallVector<Expr *, 4> InnerUsedAllocators; 165 llvm::DenseSet<CanonicalDeclPtr<Decl>> ImplicitTaskFirstprivates; 166 /// List of globals marked as declare target link in this target region 167 /// (isOpenMPTargetExecutionDirective(Directive) == true). 168 llvm::SmallVector<DeclRefExpr *, 4> DeclareTargetLinkVarDecls; 169 /// List of decls used in inclusive/exclusive clauses of the scan directive. 170 llvm::DenseSet<CanonicalDeclPtr<Decl>> UsedInScanDirective; 171 SharingMapTy(OpenMPDirectiveKind DKind, DeclarationNameInfo Name, 172 Scope *CurScope, SourceLocation Loc) 173 : Directive(DKind), DirectiveName(Name), CurScope(CurScope), 174 ConstructLoc(Loc) {} 175 SharingMapTy() = default; 176 }; 177 178 using StackTy = SmallVector<SharingMapTy, 4>; 179 180 /// Stack of used declaration and their data-sharing attributes. 181 DeclSAMapTy Threadprivates; 182 const FunctionScopeInfo *CurrentNonCapturingFunctionScope = nullptr; 183 SmallVector<std::pair<StackTy, const FunctionScopeInfo *>, 4> Stack; 184 /// true, if check for DSA must be from parent directive, false, if 185 /// from current directive. 186 OpenMPClauseKind ClauseKindMode = OMPC_unknown; 187 Sema &SemaRef; 188 bool ForceCapturing = false; 189 /// true if all the variables in the target executable directives must be 190 /// captured by reference. 191 bool ForceCaptureByReferenceInTargetExecutable = false; 192 CriticalsWithHintsTy Criticals; 193 unsigned IgnoredStackElements = 0; 194 195 /// Iterators over the stack iterate in order from innermost to outermost 196 /// directive. 197 using const_iterator = StackTy::const_reverse_iterator; 198 const_iterator begin() const { 199 return Stack.empty() ? const_iterator() 200 : Stack.back().first.rbegin() + IgnoredStackElements; 201 } 202 const_iterator end() const { 203 return Stack.empty() ? const_iterator() : Stack.back().first.rend(); 204 } 205 using iterator = StackTy::reverse_iterator; 206 iterator begin() { 207 return Stack.empty() ? iterator() 208 : Stack.back().first.rbegin() + IgnoredStackElements; 209 } 210 iterator end() { 211 return Stack.empty() ? iterator() : Stack.back().first.rend(); 212 } 213 214 // Convenience operations to get at the elements of the stack. 215 216 bool isStackEmpty() const { 217 return Stack.empty() || 218 Stack.back().second != CurrentNonCapturingFunctionScope || 219 Stack.back().first.size() <= IgnoredStackElements; 220 } 221 size_t getStackSize() const { 222 return isStackEmpty() ? 0 223 : Stack.back().first.size() - IgnoredStackElements; 224 } 225 226 SharingMapTy *getTopOfStackOrNull() { 227 size_t Size = getStackSize(); 228 if (Size == 0) 229 return nullptr; 230 return &Stack.back().first[Size - 1]; 231 } 232 const SharingMapTy *getTopOfStackOrNull() const { 233 return const_cast<DSAStackTy&>(*this).getTopOfStackOrNull(); 234 } 235 SharingMapTy &getTopOfStack() { 236 assert(!isStackEmpty() && "no current directive"); 237 return *getTopOfStackOrNull(); 238 } 239 const SharingMapTy &getTopOfStack() const { 240 return const_cast<DSAStackTy&>(*this).getTopOfStack(); 241 } 242 243 SharingMapTy *getSecondOnStackOrNull() { 244 size_t Size = getStackSize(); 245 if (Size <= 1) 246 return nullptr; 247 return &Stack.back().first[Size - 2]; 248 } 249 const SharingMapTy *getSecondOnStackOrNull() const { 250 return const_cast<DSAStackTy&>(*this).getSecondOnStackOrNull(); 251 } 252 253 /// Get the stack element at a certain level (previously returned by 254 /// \c getNestingLevel). 255 /// 256 /// Note that nesting levels count from outermost to innermost, and this is 257 /// the reverse of our iteration order where new inner levels are pushed at 258 /// the front of the stack. 259 SharingMapTy &getStackElemAtLevel(unsigned Level) { 260 assert(Level < getStackSize() && "no such stack element"); 261 return Stack.back().first[Level]; 262 } 263 const SharingMapTy &getStackElemAtLevel(unsigned Level) const { 264 return const_cast<DSAStackTy&>(*this).getStackElemAtLevel(Level); 265 } 266 267 DSAVarData getDSA(const_iterator &Iter, ValueDecl *D) const; 268 269 /// Checks if the variable is a local for OpenMP region. 270 bool isOpenMPLocal(VarDecl *D, const_iterator Iter) const; 271 272 /// Vector of previously declared requires directives 273 SmallVector<const OMPRequiresDecl *, 2> RequiresDecls; 274 /// omp_allocator_handle_t type. 275 QualType OMPAllocatorHandleT; 276 /// omp_depend_t type. 277 QualType OMPDependT; 278 /// omp_event_handle_t type. 279 QualType OMPEventHandleT; 280 /// Expression for the predefined allocators. 281 Expr *OMPPredefinedAllocators[OMPAllocateDeclAttr::OMPUserDefinedMemAlloc] = { 282 nullptr}; 283 /// Vector of previously encountered target directives 284 SmallVector<SourceLocation, 2> TargetLocations; 285 SourceLocation AtomicLocation; 286 287 public: 288 explicit DSAStackTy(Sema &S) : SemaRef(S) {} 289 290 /// Sets omp_allocator_handle_t type. 291 void setOMPAllocatorHandleT(QualType Ty) { OMPAllocatorHandleT = Ty; } 292 /// Gets omp_allocator_handle_t type. 293 QualType getOMPAllocatorHandleT() const { return OMPAllocatorHandleT; } 294 /// Sets the given default allocator. 295 void setAllocator(OMPAllocateDeclAttr::AllocatorTypeTy AllocatorKind, 296 Expr *Allocator) { 297 OMPPredefinedAllocators[AllocatorKind] = Allocator; 298 } 299 /// Returns the specified default allocator. 300 Expr *getAllocator(OMPAllocateDeclAttr::AllocatorTypeTy AllocatorKind) const { 301 return OMPPredefinedAllocators[AllocatorKind]; 302 } 303 /// Sets omp_depend_t type. 304 void setOMPDependT(QualType Ty) { OMPDependT = Ty; } 305 /// Gets omp_depend_t type. 306 QualType getOMPDependT() const { return OMPDependT; } 307 308 /// Sets omp_event_handle_t type. 309 void setOMPEventHandleT(QualType Ty) { OMPEventHandleT = Ty; } 310 /// Gets omp_event_handle_t type. 311 QualType getOMPEventHandleT() const { return OMPEventHandleT; } 312 313 bool isClauseParsingMode() const { return ClauseKindMode != OMPC_unknown; } 314 OpenMPClauseKind getClauseParsingMode() const { 315 assert(isClauseParsingMode() && "Must be in clause parsing mode."); 316 return ClauseKindMode; 317 } 318 void setClauseParsingMode(OpenMPClauseKind K) { ClauseKindMode = K; } 319 320 bool isBodyComplete() const { 321 const SharingMapTy *Top = getTopOfStackOrNull(); 322 return Top && Top->BodyComplete; 323 } 324 void setBodyComplete() { 325 getTopOfStack().BodyComplete = true; 326 } 327 328 bool isForceVarCapturing() const { return ForceCapturing; } 329 void setForceVarCapturing(bool V) { ForceCapturing = V; } 330 331 void setForceCaptureByReferenceInTargetExecutable(bool V) { 332 ForceCaptureByReferenceInTargetExecutable = V; 333 } 334 bool isForceCaptureByReferenceInTargetExecutable() const { 335 return ForceCaptureByReferenceInTargetExecutable; 336 } 337 338 void push(OpenMPDirectiveKind DKind, const DeclarationNameInfo &DirName, 339 Scope *CurScope, SourceLocation Loc) { 340 assert(!IgnoredStackElements && 341 "cannot change stack while ignoring elements"); 342 if (Stack.empty() || 343 Stack.back().second != CurrentNonCapturingFunctionScope) 344 Stack.emplace_back(StackTy(), CurrentNonCapturingFunctionScope); 345 Stack.back().first.emplace_back(DKind, DirName, CurScope, Loc); 346 Stack.back().first.back().DefaultAttrLoc = Loc; 347 } 348 349 void pop() { 350 assert(!IgnoredStackElements && 351 "cannot change stack while ignoring elements"); 352 assert(!Stack.back().first.empty() && 353 "Data-sharing attributes stack is empty!"); 354 Stack.back().first.pop_back(); 355 } 356 357 /// RAII object to temporarily leave the scope of a directive when we want to 358 /// logically operate in its parent. 359 class ParentDirectiveScope { 360 DSAStackTy &Self; 361 bool Active; 362 public: 363 ParentDirectiveScope(DSAStackTy &Self, bool Activate) 364 : Self(Self), Active(false) { 365 if (Activate) 366 enable(); 367 } 368 ~ParentDirectiveScope() { disable(); } 369 void disable() { 370 if (Active) { 371 --Self.IgnoredStackElements; 372 Active = false; 373 } 374 } 375 void enable() { 376 if (!Active) { 377 ++Self.IgnoredStackElements; 378 Active = true; 379 } 380 } 381 }; 382 383 /// Marks that we're started loop parsing. 384 void loopInit() { 385 assert(isOpenMPLoopDirective(getCurrentDirective()) && 386 "Expected loop-based directive."); 387 getTopOfStack().LoopStart = true; 388 } 389 /// Start capturing of the variables in the loop context. 390 void loopStart() { 391 assert(isOpenMPLoopDirective(getCurrentDirective()) && 392 "Expected loop-based directive."); 393 getTopOfStack().LoopStart = false; 394 } 395 /// true, if variables are captured, false otherwise. 396 bool isLoopStarted() const { 397 assert(isOpenMPLoopDirective(getCurrentDirective()) && 398 "Expected loop-based directive."); 399 return !getTopOfStack().LoopStart; 400 } 401 /// Marks (or clears) declaration as possibly loop counter. 402 void resetPossibleLoopCounter(const Decl *D = nullptr) { 403 getTopOfStack().PossiblyLoopCounter = 404 D ? D->getCanonicalDecl() : D; 405 } 406 /// Gets the possible loop counter decl. 407 const Decl *getPossiblyLoopCunter() const { 408 return getTopOfStack().PossiblyLoopCounter; 409 } 410 /// Start new OpenMP region stack in new non-capturing function. 411 void pushFunction() { 412 assert(!IgnoredStackElements && 413 "cannot change stack while ignoring elements"); 414 const FunctionScopeInfo *CurFnScope = SemaRef.getCurFunction(); 415 assert(!isa<CapturingScopeInfo>(CurFnScope)); 416 CurrentNonCapturingFunctionScope = CurFnScope; 417 } 418 /// Pop region stack for non-capturing function. 419 void popFunction(const FunctionScopeInfo *OldFSI) { 420 assert(!IgnoredStackElements && 421 "cannot change stack while ignoring elements"); 422 if (!Stack.empty() && Stack.back().second == OldFSI) { 423 assert(Stack.back().first.empty()); 424 Stack.pop_back(); 425 } 426 CurrentNonCapturingFunctionScope = nullptr; 427 for (const FunctionScopeInfo *FSI : llvm::reverse(SemaRef.FunctionScopes)) { 428 if (!isa<CapturingScopeInfo>(FSI)) { 429 CurrentNonCapturingFunctionScope = FSI; 430 break; 431 } 432 } 433 } 434 435 void addCriticalWithHint(const OMPCriticalDirective *D, llvm::APSInt Hint) { 436 Criticals.try_emplace(D->getDirectiveName().getAsString(), D, Hint); 437 } 438 const std::pair<const OMPCriticalDirective *, llvm::APSInt> 439 getCriticalWithHint(const DeclarationNameInfo &Name) const { 440 auto I = Criticals.find(Name.getAsString()); 441 if (I != Criticals.end()) 442 return I->second; 443 return std::make_pair(nullptr, llvm::APSInt()); 444 } 445 /// If 'aligned' declaration for given variable \a D was not seen yet, 446 /// add it and return NULL; otherwise return previous occurrence's expression 447 /// for diagnostics. 448 const Expr *addUniqueAligned(const ValueDecl *D, const Expr *NewDE); 449 /// If 'nontemporal' declaration for given variable \a D was not seen yet, 450 /// add it and return NULL; otherwise return previous occurrence's expression 451 /// for diagnostics. 452 const Expr *addUniqueNontemporal(const ValueDecl *D, const Expr *NewDE); 453 454 /// Register specified variable as loop control variable. 455 void addLoopControlVariable(const ValueDecl *D, VarDecl *Capture); 456 /// Check if the specified variable is a loop control variable for 457 /// current region. 458 /// \return The index of the loop control variable in the list of associated 459 /// for-loops (from outer to inner). 460 const LCDeclInfo isLoopControlVariable(const ValueDecl *D) const; 461 /// Check if the specified variable is a loop control variable for 462 /// parent region. 463 /// \return The index of the loop control variable in the list of associated 464 /// for-loops (from outer to inner). 465 const LCDeclInfo isParentLoopControlVariable(const ValueDecl *D) const; 466 /// Check if the specified variable is a loop control variable for 467 /// current region. 468 /// \return The index of the loop control variable in the list of associated 469 /// for-loops (from outer to inner). 470 const LCDeclInfo isLoopControlVariable(const ValueDecl *D, 471 unsigned Level) const; 472 /// Get the loop control variable for the I-th loop (or nullptr) in 473 /// parent directive. 474 const ValueDecl *getParentLoopControlVariable(unsigned I) const; 475 476 /// Marks the specified decl \p D as used in scan directive. 477 void markDeclAsUsedInScanDirective(ValueDecl *D) { 478 if (SharingMapTy *Stack = getSecondOnStackOrNull()) 479 Stack->UsedInScanDirective.insert(D); 480 } 481 482 /// Checks if the specified declaration was used in the inner scan directive. 483 bool isUsedInScanDirective(ValueDecl *D) const { 484 if (const SharingMapTy *Stack = getTopOfStackOrNull()) 485 return Stack->UsedInScanDirective.count(D) > 0; 486 return false; 487 } 488 489 /// Adds explicit data sharing attribute to the specified declaration. 490 void addDSA(const ValueDecl *D, const Expr *E, OpenMPClauseKind A, 491 DeclRefExpr *PrivateCopy = nullptr, unsigned Modifier = 0); 492 493 /// Adds additional information for the reduction items with the reduction id 494 /// represented as an operator. 495 void addTaskgroupReductionData(const ValueDecl *D, SourceRange SR, 496 BinaryOperatorKind BOK); 497 /// Adds additional information for the reduction items with the reduction id 498 /// represented as reduction identifier. 499 void addTaskgroupReductionData(const ValueDecl *D, SourceRange SR, 500 const Expr *ReductionRef); 501 /// Returns the location and reduction operation from the innermost parent 502 /// region for the given \p D. 503 const DSAVarData 504 getTopMostTaskgroupReductionData(const ValueDecl *D, SourceRange &SR, 505 BinaryOperatorKind &BOK, 506 Expr *&TaskgroupDescriptor) const; 507 /// Returns the location and reduction operation from the innermost parent 508 /// region for the given \p D. 509 const DSAVarData 510 getTopMostTaskgroupReductionData(const ValueDecl *D, SourceRange &SR, 511 const Expr *&ReductionRef, 512 Expr *&TaskgroupDescriptor) const; 513 /// Return reduction reference expression for the current taskgroup. 514 Expr *getTaskgroupReductionRef() const { 515 assert(getTopOfStack().Directive == OMPD_taskgroup && 516 "taskgroup reference expression requested for non taskgroup " 517 "directive."); 518 return getTopOfStack().TaskgroupReductionRef; 519 } 520 /// Checks if the given \p VD declaration is actually a taskgroup reduction 521 /// descriptor variable at the \p Level of OpenMP regions. 522 bool isTaskgroupReductionRef(const ValueDecl *VD, unsigned Level) const { 523 return getStackElemAtLevel(Level).TaskgroupReductionRef && 524 cast<DeclRefExpr>(getStackElemAtLevel(Level).TaskgroupReductionRef) 525 ->getDecl() == VD; 526 } 527 528 /// Returns data sharing attributes from top of the stack for the 529 /// specified declaration. 530 const DSAVarData getTopDSA(ValueDecl *D, bool FromParent); 531 /// Returns data-sharing attributes for the specified declaration. 532 const DSAVarData getImplicitDSA(ValueDecl *D, bool FromParent) const; 533 /// Returns data-sharing attributes for the specified declaration. 534 const DSAVarData getImplicitDSA(ValueDecl *D, unsigned Level) const; 535 /// Checks if the specified variables has data-sharing attributes which 536 /// match specified \a CPred predicate in any directive which matches \a DPred 537 /// predicate. 538 const DSAVarData 539 hasDSA(ValueDecl *D, const llvm::function_ref<bool(OpenMPClauseKind)> CPred, 540 const llvm::function_ref<bool(OpenMPDirectiveKind)> DPred, 541 bool FromParent) const; 542 /// Checks if the specified variables has data-sharing attributes which 543 /// match specified \a CPred predicate in any innermost directive which 544 /// matches \a DPred predicate. 545 const DSAVarData 546 hasInnermostDSA(ValueDecl *D, 547 const llvm::function_ref<bool(OpenMPClauseKind)> CPred, 548 const llvm::function_ref<bool(OpenMPDirectiveKind)> DPred, 549 bool FromParent) const; 550 /// Checks if the specified variables has explicit data-sharing 551 /// attributes which match specified \a CPred predicate at the specified 552 /// OpenMP region. 553 bool hasExplicitDSA(const ValueDecl *D, 554 const llvm::function_ref<bool(OpenMPClauseKind)> CPred, 555 unsigned Level, bool NotLastprivate = false) const; 556 557 /// Returns true if the directive at level \Level matches in the 558 /// specified \a DPred predicate. 559 bool hasExplicitDirective( 560 const llvm::function_ref<bool(OpenMPDirectiveKind)> DPred, 561 unsigned Level) const; 562 563 /// Finds a directive which matches specified \a DPred predicate. 564 bool hasDirective( 565 const llvm::function_ref<bool( 566 OpenMPDirectiveKind, const DeclarationNameInfo &, SourceLocation)> 567 DPred, 568 bool FromParent) const; 569 570 /// Returns currently analyzed directive. 571 OpenMPDirectiveKind getCurrentDirective() const { 572 const SharingMapTy *Top = getTopOfStackOrNull(); 573 return Top ? Top->Directive : OMPD_unknown; 574 } 575 /// Returns directive kind at specified level. 576 OpenMPDirectiveKind getDirective(unsigned Level) const { 577 assert(!isStackEmpty() && "No directive at specified level."); 578 return getStackElemAtLevel(Level).Directive; 579 } 580 /// Returns the capture region at the specified level. 581 OpenMPDirectiveKind getCaptureRegion(unsigned Level, 582 unsigned OpenMPCaptureLevel) const { 583 SmallVector<OpenMPDirectiveKind, 4> CaptureRegions; 584 getOpenMPCaptureRegions(CaptureRegions, getDirective(Level)); 585 return CaptureRegions[OpenMPCaptureLevel]; 586 } 587 /// Returns parent directive. 588 OpenMPDirectiveKind getParentDirective() const { 589 const SharingMapTy *Parent = getSecondOnStackOrNull(); 590 return Parent ? Parent->Directive : OMPD_unknown; 591 } 592 593 /// Add requires decl to internal vector 594 void addRequiresDecl(OMPRequiresDecl *RD) { 595 RequiresDecls.push_back(RD); 596 } 597 598 /// Checks if the defined 'requires' directive has specified type of clause. 599 template <typename ClauseType> 600 bool hasRequiresDeclWithClause() const { 601 return llvm::any_of(RequiresDecls, [](const OMPRequiresDecl *D) { 602 return llvm::any_of(D->clauselists(), [](const OMPClause *C) { 603 return isa<ClauseType>(C); 604 }); 605 }); 606 } 607 608 /// Checks for a duplicate clause amongst previously declared requires 609 /// directives 610 bool hasDuplicateRequiresClause(ArrayRef<OMPClause *> ClauseList) const { 611 bool IsDuplicate = false; 612 for (OMPClause *CNew : ClauseList) { 613 for (const OMPRequiresDecl *D : RequiresDecls) { 614 for (const OMPClause *CPrev : D->clauselists()) { 615 if (CNew->getClauseKind() == CPrev->getClauseKind()) { 616 SemaRef.Diag(CNew->getBeginLoc(), 617 diag::err_omp_requires_clause_redeclaration) 618 << getOpenMPClauseName(CNew->getClauseKind()); 619 SemaRef.Diag(CPrev->getBeginLoc(), 620 diag::note_omp_requires_previous_clause) 621 << getOpenMPClauseName(CPrev->getClauseKind()); 622 IsDuplicate = true; 623 } 624 } 625 } 626 } 627 return IsDuplicate; 628 } 629 630 /// Add location of previously encountered target to internal vector 631 void addTargetDirLocation(SourceLocation LocStart) { 632 TargetLocations.push_back(LocStart); 633 } 634 635 /// Add location for the first encountered atomicc directive. 636 void addAtomicDirectiveLoc(SourceLocation Loc) { 637 if (AtomicLocation.isInvalid()) 638 AtomicLocation = Loc; 639 } 640 641 /// Returns the location of the first encountered atomic directive in the 642 /// module. 643 SourceLocation getAtomicDirectiveLoc() const { 644 return AtomicLocation; 645 } 646 647 // Return previously encountered target region locations. 648 ArrayRef<SourceLocation> getEncounteredTargetLocs() const { 649 return TargetLocations; 650 } 651 652 /// Set default data sharing attribute to none. 653 void setDefaultDSANone(SourceLocation Loc) { 654 getTopOfStack().DefaultAttr = DSA_none; 655 getTopOfStack().DefaultAttrLoc = Loc; 656 } 657 /// Set default data sharing attribute to shared. 658 void setDefaultDSAShared(SourceLocation Loc) { 659 getTopOfStack().DefaultAttr = DSA_shared; 660 getTopOfStack().DefaultAttrLoc = Loc; 661 } 662 /// Set default data mapping attribute to Modifier:Kind 663 void setDefaultDMAAttr(OpenMPDefaultmapClauseModifier M, 664 OpenMPDefaultmapClauseKind Kind, 665 SourceLocation Loc) { 666 DefaultmapInfo &DMI = getTopOfStack().DefaultmapMap[Kind]; 667 DMI.ImplicitBehavior = M; 668 DMI.SLoc = Loc; 669 } 670 /// Check whether the implicit-behavior has been set in defaultmap 671 bool checkDefaultmapCategory(OpenMPDefaultmapClauseKind VariableCategory) { 672 return getTopOfStack().DefaultmapMap[VariableCategory].ImplicitBehavior != 673 OMPC_DEFAULTMAP_MODIFIER_unknown; 674 } 675 676 DefaultDataSharingAttributes getDefaultDSA(unsigned Level) const { 677 return getStackSize() <= Level ? DSA_unspecified 678 : getStackElemAtLevel(Level).DefaultAttr; 679 } 680 DefaultDataSharingAttributes getDefaultDSA() const { 681 return isStackEmpty() ? DSA_unspecified 682 : getTopOfStack().DefaultAttr; 683 } 684 SourceLocation getDefaultDSALocation() const { 685 return isStackEmpty() ? SourceLocation() 686 : getTopOfStack().DefaultAttrLoc; 687 } 688 OpenMPDefaultmapClauseModifier 689 getDefaultmapModifier(OpenMPDefaultmapClauseKind Kind) const { 690 return isStackEmpty() 691 ? OMPC_DEFAULTMAP_MODIFIER_unknown 692 : getTopOfStack().DefaultmapMap[Kind].ImplicitBehavior; 693 } 694 OpenMPDefaultmapClauseModifier 695 getDefaultmapModifierAtLevel(unsigned Level, 696 OpenMPDefaultmapClauseKind Kind) const { 697 return getStackElemAtLevel(Level).DefaultmapMap[Kind].ImplicitBehavior; 698 } 699 bool isDefaultmapCapturedByRef(unsigned Level, 700 OpenMPDefaultmapClauseKind Kind) const { 701 OpenMPDefaultmapClauseModifier M = 702 getDefaultmapModifierAtLevel(Level, Kind); 703 if (Kind == OMPC_DEFAULTMAP_scalar || Kind == OMPC_DEFAULTMAP_pointer) { 704 return (M == OMPC_DEFAULTMAP_MODIFIER_alloc) || 705 (M == OMPC_DEFAULTMAP_MODIFIER_to) || 706 (M == OMPC_DEFAULTMAP_MODIFIER_from) || 707 (M == OMPC_DEFAULTMAP_MODIFIER_tofrom); 708 } 709 return true; 710 } 711 static bool mustBeFirstprivateBase(OpenMPDefaultmapClauseModifier M, 712 OpenMPDefaultmapClauseKind Kind) { 713 switch (Kind) { 714 case OMPC_DEFAULTMAP_scalar: 715 case OMPC_DEFAULTMAP_pointer: 716 return (M == OMPC_DEFAULTMAP_MODIFIER_unknown) || 717 (M == OMPC_DEFAULTMAP_MODIFIER_firstprivate) || 718 (M == OMPC_DEFAULTMAP_MODIFIER_default); 719 case OMPC_DEFAULTMAP_aggregate: 720 return M == OMPC_DEFAULTMAP_MODIFIER_firstprivate; 721 default: 722 break; 723 } 724 llvm_unreachable("Unexpected OpenMPDefaultmapClauseKind enum"); 725 } 726 bool mustBeFirstprivateAtLevel(unsigned Level, 727 OpenMPDefaultmapClauseKind Kind) const { 728 OpenMPDefaultmapClauseModifier M = 729 getDefaultmapModifierAtLevel(Level, Kind); 730 return mustBeFirstprivateBase(M, Kind); 731 } 732 bool mustBeFirstprivate(OpenMPDefaultmapClauseKind Kind) const { 733 OpenMPDefaultmapClauseModifier M = getDefaultmapModifier(Kind); 734 return mustBeFirstprivateBase(M, Kind); 735 } 736 737 /// Checks if the specified variable is a threadprivate. 738 bool isThreadPrivate(VarDecl *D) { 739 const DSAVarData DVar = getTopDSA(D, false); 740 return isOpenMPThreadPrivate(DVar.CKind); 741 } 742 743 /// Marks current region as ordered (it has an 'ordered' clause). 744 void setOrderedRegion(bool IsOrdered, const Expr *Param, 745 OMPOrderedClause *Clause) { 746 if (IsOrdered) 747 getTopOfStack().OrderedRegion.emplace(Param, Clause); 748 else 749 getTopOfStack().OrderedRegion.reset(); 750 } 751 /// Returns true, if region is ordered (has associated 'ordered' clause), 752 /// false - otherwise. 753 bool isOrderedRegion() const { 754 if (const SharingMapTy *Top = getTopOfStackOrNull()) 755 return Top->OrderedRegion.hasValue(); 756 return false; 757 } 758 /// Returns optional parameter for the ordered region. 759 std::pair<const Expr *, OMPOrderedClause *> getOrderedRegionParam() const { 760 if (const SharingMapTy *Top = getTopOfStackOrNull()) 761 if (Top->OrderedRegion.hasValue()) 762 return Top->OrderedRegion.getValue(); 763 return std::make_pair(nullptr, nullptr); 764 } 765 /// Returns true, if parent region is ordered (has associated 766 /// 'ordered' clause), false - otherwise. 767 bool isParentOrderedRegion() const { 768 if (const SharingMapTy *Parent = getSecondOnStackOrNull()) 769 return Parent->OrderedRegion.hasValue(); 770 return false; 771 } 772 /// Returns optional parameter for the ordered region. 773 std::pair<const Expr *, OMPOrderedClause *> 774 getParentOrderedRegionParam() const { 775 if (const SharingMapTy *Parent = getSecondOnStackOrNull()) 776 if (Parent->OrderedRegion.hasValue()) 777 return Parent->OrderedRegion.getValue(); 778 return std::make_pair(nullptr, nullptr); 779 } 780 /// Marks current region as nowait (it has a 'nowait' clause). 781 void setNowaitRegion(bool IsNowait = true) { 782 getTopOfStack().NowaitRegion = IsNowait; 783 } 784 /// Returns true, if parent region is nowait (has associated 785 /// 'nowait' clause), false - otherwise. 786 bool isParentNowaitRegion() const { 787 if (const SharingMapTy *Parent = getSecondOnStackOrNull()) 788 return Parent->NowaitRegion; 789 return false; 790 } 791 /// Marks parent region as cancel region. 792 void setParentCancelRegion(bool Cancel = true) { 793 if (SharingMapTy *Parent = getSecondOnStackOrNull()) 794 Parent->CancelRegion |= Cancel; 795 } 796 /// Return true if current region has inner cancel construct. 797 bool isCancelRegion() const { 798 const SharingMapTy *Top = getTopOfStackOrNull(); 799 return Top ? Top->CancelRegion : false; 800 } 801 802 /// Mark that parent region already has scan directive. 803 void setParentHasScanDirective(SourceLocation Loc) { 804 if (SharingMapTy *Parent = getSecondOnStackOrNull()) 805 Parent->PrevScanLocation = Loc; 806 } 807 /// Return true if current region has inner cancel construct. 808 bool doesParentHasScanDirective() const { 809 const SharingMapTy *Top = getSecondOnStackOrNull(); 810 return Top ? Top->PrevScanLocation.isValid() : false; 811 } 812 /// Return true if current region has inner cancel construct. 813 SourceLocation getParentScanDirectiveLoc() const { 814 const SharingMapTy *Top = getSecondOnStackOrNull(); 815 return Top ? Top->PrevScanLocation : SourceLocation(); 816 } 817 818 /// Set collapse value for the region. 819 void setAssociatedLoops(unsigned Val) { 820 getTopOfStack().AssociatedLoops = Val; 821 if (Val > 1) 822 getTopOfStack().HasMutipleLoops = true; 823 } 824 /// Return collapse value for region. 825 unsigned getAssociatedLoops() const { 826 const SharingMapTy *Top = getTopOfStackOrNull(); 827 return Top ? Top->AssociatedLoops : 0; 828 } 829 /// Returns true if the construct is associated with multiple loops. 830 bool hasMutipleLoops() const { 831 const SharingMapTy *Top = getTopOfStackOrNull(); 832 return Top ? Top->HasMutipleLoops : false; 833 } 834 835 /// Marks current target region as one with closely nested teams 836 /// region. 837 void setParentTeamsRegionLoc(SourceLocation TeamsRegionLoc) { 838 if (SharingMapTy *Parent = getSecondOnStackOrNull()) 839 Parent->InnerTeamsRegionLoc = TeamsRegionLoc; 840 } 841 /// Returns true, if current region has closely nested teams region. 842 bool hasInnerTeamsRegion() const { 843 return getInnerTeamsRegionLoc().isValid(); 844 } 845 /// Returns location of the nested teams region (if any). 846 SourceLocation getInnerTeamsRegionLoc() const { 847 const SharingMapTy *Top = getTopOfStackOrNull(); 848 return Top ? Top->InnerTeamsRegionLoc : SourceLocation(); 849 } 850 851 Scope *getCurScope() const { 852 const SharingMapTy *Top = getTopOfStackOrNull(); 853 return Top ? Top->CurScope : nullptr; 854 } 855 SourceLocation getConstructLoc() const { 856 const SharingMapTy *Top = getTopOfStackOrNull(); 857 return Top ? Top->ConstructLoc : SourceLocation(); 858 } 859 860 /// Do the check specified in \a Check to all component lists and return true 861 /// if any issue is found. 862 bool checkMappableExprComponentListsForDecl( 863 const ValueDecl *VD, bool CurrentRegionOnly, 864 const llvm::function_ref< 865 bool(OMPClauseMappableExprCommon::MappableExprComponentListRef, 866 OpenMPClauseKind)> 867 Check) const { 868 if (isStackEmpty()) 869 return false; 870 auto SI = begin(); 871 auto SE = end(); 872 873 if (SI == SE) 874 return false; 875 876 if (CurrentRegionOnly) 877 SE = std::next(SI); 878 else 879 std::advance(SI, 1); 880 881 for (; SI != SE; ++SI) { 882 auto MI = SI->MappedExprComponents.find(VD); 883 if (MI != SI->MappedExprComponents.end()) 884 for (OMPClauseMappableExprCommon::MappableExprComponentListRef L : 885 MI->second.Components) 886 if (Check(L, MI->second.Kind)) 887 return true; 888 } 889 return false; 890 } 891 892 /// Do the check specified in \a Check to all component lists at a given level 893 /// and return true if any issue is found. 894 bool checkMappableExprComponentListsForDeclAtLevel( 895 const ValueDecl *VD, unsigned Level, 896 const llvm::function_ref< 897 bool(OMPClauseMappableExprCommon::MappableExprComponentListRef, 898 OpenMPClauseKind)> 899 Check) const { 900 if (getStackSize() <= Level) 901 return false; 902 903 const SharingMapTy &StackElem = getStackElemAtLevel(Level); 904 auto MI = StackElem.MappedExprComponents.find(VD); 905 if (MI != StackElem.MappedExprComponents.end()) 906 for (OMPClauseMappableExprCommon::MappableExprComponentListRef L : 907 MI->second.Components) 908 if (Check(L, MI->second.Kind)) 909 return true; 910 return false; 911 } 912 913 /// Create a new mappable expression component list associated with a given 914 /// declaration and initialize it with the provided list of components. 915 void addMappableExpressionComponents( 916 const ValueDecl *VD, 917 OMPClauseMappableExprCommon::MappableExprComponentListRef Components, 918 OpenMPClauseKind WhereFoundClauseKind) { 919 MappedExprComponentTy &MEC = getTopOfStack().MappedExprComponents[VD]; 920 // Create new entry and append the new components there. 921 MEC.Components.resize(MEC.Components.size() + 1); 922 MEC.Components.back().append(Components.begin(), Components.end()); 923 MEC.Kind = WhereFoundClauseKind; 924 } 925 926 unsigned getNestingLevel() const { 927 assert(!isStackEmpty()); 928 return getStackSize() - 1; 929 } 930 void addDoacrossDependClause(OMPDependClause *C, 931 const OperatorOffsetTy &OpsOffs) { 932 SharingMapTy *Parent = getSecondOnStackOrNull(); 933 assert(Parent && isOpenMPWorksharingDirective(Parent->Directive)); 934 Parent->DoacrossDepends.try_emplace(C, OpsOffs); 935 } 936 llvm::iterator_range<DoacrossDependMapTy::const_iterator> 937 getDoacrossDependClauses() const { 938 const SharingMapTy &StackElem = getTopOfStack(); 939 if (isOpenMPWorksharingDirective(StackElem.Directive)) { 940 const DoacrossDependMapTy &Ref = StackElem.DoacrossDepends; 941 return llvm::make_range(Ref.begin(), Ref.end()); 942 } 943 return llvm::make_range(StackElem.DoacrossDepends.end(), 944 StackElem.DoacrossDepends.end()); 945 } 946 947 // Store types of classes which have been explicitly mapped 948 void addMappedClassesQualTypes(QualType QT) { 949 SharingMapTy &StackElem = getTopOfStack(); 950 StackElem.MappedClassesQualTypes.insert(QT); 951 } 952 953 // Return set of mapped classes types 954 bool isClassPreviouslyMapped(QualType QT) const { 955 const SharingMapTy &StackElem = getTopOfStack(); 956 return StackElem.MappedClassesQualTypes.count(QT) != 0; 957 } 958 959 /// Adds global declare target to the parent target region. 960 void addToParentTargetRegionLinkGlobals(DeclRefExpr *E) { 961 assert(*OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration( 962 E->getDecl()) == OMPDeclareTargetDeclAttr::MT_Link && 963 "Expected declare target link global."); 964 for (auto &Elem : *this) { 965 if (isOpenMPTargetExecutionDirective(Elem.Directive)) { 966 Elem.DeclareTargetLinkVarDecls.push_back(E); 967 return; 968 } 969 } 970 } 971 972 /// Returns the list of globals with declare target link if current directive 973 /// is target. 974 ArrayRef<DeclRefExpr *> getLinkGlobals() const { 975 assert(isOpenMPTargetExecutionDirective(getCurrentDirective()) && 976 "Expected target executable directive."); 977 return getTopOfStack().DeclareTargetLinkVarDecls; 978 } 979 980 /// Adds list of allocators expressions. 981 void addInnerAllocatorExpr(Expr *E) { 982 getTopOfStack().InnerUsedAllocators.push_back(E); 983 } 984 /// Return list of used allocators. 985 ArrayRef<Expr *> getInnerAllocators() const { 986 return getTopOfStack().InnerUsedAllocators; 987 } 988 /// Marks the declaration as implicitly firstprivate nin the task-based 989 /// regions. 990 void addImplicitTaskFirstprivate(unsigned Level, Decl *D) { 991 getStackElemAtLevel(Level).ImplicitTaskFirstprivates.insert(D); 992 } 993 /// Checks if the decl is implicitly firstprivate in the task-based region. 994 bool isImplicitTaskFirstprivate(Decl *D) const { 995 return getTopOfStack().ImplicitTaskFirstprivates.count(D) > 0; 996 } 997 }; 998 999 bool isImplicitTaskingRegion(OpenMPDirectiveKind DKind) { 1000 return isOpenMPParallelDirective(DKind) || isOpenMPTeamsDirective(DKind); 1001 } 1002 1003 bool isImplicitOrExplicitTaskingRegion(OpenMPDirectiveKind DKind) { 1004 return isImplicitTaskingRegion(DKind) || isOpenMPTaskingDirective(DKind) || 1005 DKind == OMPD_unknown; 1006 } 1007 1008 } // namespace 1009 1010 static const Expr *getExprAsWritten(const Expr *E) { 1011 if (const auto *FE = dyn_cast<FullExpr>(E)) 1012 E = FE->getSubExpr(); 1013 1014 if (const auto *MTE = dyn_cast<MaterializeTemporaryExpr>(E)) 1015 E = MTE->getSubExpr(); 1016 1017 while (const auto *Binder = dyn_cast<CXXBindTemporaryExpr>(E)) 1018 E = Binder->getSubExpr(); 1019 1020 if (const auto *ICE = dyn_cast<ImplicitCastExpr>(E)) 1021 E = ICE->getSubExprAsWritten(); 1022 return E->IgnoreParens(); 1023 } 1024 1025 static Expr *getExprAsWritten(Expr *E) { 1026 return const_cast<Expr *>(getExprAsWritten(const_cast<const Expr *>(E))); 1027 } 1028 1029 static const ValueDecl *getCanonicalDecl(const ValueDecl *D) { 1030 if (const auto *CED = dyn_cast<OMPCapturedExprDecl>(D)) 1031 if (const auto *ME = dyn_cast<MemberExpr>(getExprAsWritten(CED->getInit()))) 1032 D = ME->getMemberDecl(); 1033 const auto *VD = dyn_cast<VarDecl>(D); 1034 const auto *FD = dyn_cast<FieldDecl>(D); 1035 if (VD != nullptr) { 1036 VD = VD->getCanonicalDecl(); 1037 D = VD; 1038 } else { 1039 assert(FD); 1040 FD = FD->getCanonicalDecl(); 1041 D = FD; 1042 } 1043 return D; 1044 } 1045 1046 static ValueDecl *getCanonicalDecl(ValueDecl *D) { 1047 return const_cast<ValueDecl *>( 1048 getCanonicalDecl(const_cast<const ValueDecl *>(D))); 1049 } 1050 1051 DSAStackTy::DSAVarData DSAStackTy::getDSA(const_iterator &Iter, 1052 ValueDecl *D) const { 1053 D = getCanonicalDecl(D); 1054 auto *VD = dyn_cast<VarDecl>(D); 1055 const auto *FD = dyn_cast<FieldDecl>(D); 1056 DSAVarData DVar; 1057 if (Iter == end()) { 1058 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced 1059 // in a region but not in construct] 1060 // File-scope or namespace-scope variables referenced in called routines 1061 // in the region are shared unless they appear in a threadprivate 1062 // directive. 1063 if (VD && !VD->isFunctionOrMethodVarDecl() && !isa<ParmVarDecl>(VD)) 1064 DVar.CKind = OMPC_shared; 1065 1066 // OpenMP [2.9.1.2, Data-sharing Attribute Rules for Variables Referenced 1067 // in a region but not in construct] 1068 // Variables with static storage duration that are declared in called 1069 // routines in the region are shared. 1070 if (VD && VD->hasGlobalStorage()) 1071 DVar.CKind = OMPC_shared; 1072 1073 // Non-static data members are shared by default. 1074 if (FD) 1075 DVar.CKind = OMPC_shared; 1076 1077 return DVar; 1078 } 1079 1080 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced 1081 // in a Construct, C/C++, predetermined, p.1] 1082 // Variables with automatic storage duration that are declared in a scope 1083 // inside the construct are private. 1084 if (VD && isOpenMPLocal(VD, Iter) && VD->isLocalVarDecl() && 1085 (VD->getStorageClass() == SC_Auto || VD->getStorageClass() == SC_None)) { 1086 DVar.CKind = OMPC_private; 1087 return DVar; 1088 } 1089 1090 DVar.DKind = Iter->Directive; 1091 // Explicitly specified attributes and local variables with predetermined 1092 // attributes. 1093 if (Iter->SharingMap.count(D)) { 1094 const DSAInfo &Data = Iter->SharingMap.lookup(D); 1095 DVar.RefExpr = Data.RefExpr.getPointer(); 1096 DVar.PrivateCopy = Data.PrivateCopy; 1097 DVar.CKind = Data.Attributes; 1098 DVar.ImplicitDSALoc = Iter->DefaultAttrLoc; 1099 DVar.Modifier = Data.Modifier; 1100 return DVar; 1101 } 1102 1103 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced 1104 // in a Construct, C/C++, implicitly determined, p.1] 1105 // In a parallel or task construct, the data-sharing attributes of these 1106 // variables are determined by the default clause, if present. 1107 switch (Iter->DefaultAttr) { 1108 case DSA_shared: 1109 DVar.CKind = OMPC_shared; 1110 DVar.ImplicitDSALoc = Iter->DefaultAttrLoc; 1111 return DVar; 1112 case DSA_none: 1113 return DVar; 1114 case DSA_unspecified: 1115 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced 1116 // in a Construct, implicitly determined, p.2] 1117 // In a parallel construct, if no default clause is present, these 1118 // variables are shared. 1119 DVar.ImplicitDSALoc = Iter->DefaultAttrLoc; 1120 if ((isOpenMPParallelDirective(DVar.DKind) && 1121 !isOpenMPTaskLoopDirective(DVar.DKind)) || 1122 isOpenMPTeamsDirective(DVar.DKind)) { 1123 DVar.CKind = OMPC_shared; 1124 return DVar; 1125 } 1126 1127 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced 1128 // in a Construct, implicitly determined, p.4] 1129 // In a task construct, if no default clause is present, a variable that in 1130 // the enclosing context is determined to be shared by all implicit tasks 1131 // bound to the current team is shared. 1132 if (isOpenMPTaskingDirective(DVar.DKind)) { 1133 DSAVarData DVarTemp; 1134 const_iterator I = Iter, E = end(); 1135 do { 1136 ++I; 1137 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables 1138 // Referenced in a Construct, implicitly determined, p.6] 1139 // In a task construct, if no default clause is present, a variable 1140 // whose data-sharing attribute is not determined by the rules above is 1141 // firstprivate. 1142 DVarTemp = getDSA(I, D); 1143 if (DVarTemp.CKind != OMPC_shared) { 1144 DVar.RefExpr = nullptr; 1145 DVar.CKind = OMPC_firstprivate; 1146 return DVar; 1147 } 1148 } while (I != E && !isImplicitTaskingRegion(I->Directive)); 1149 DVar.CKind = 1150 (DVarTemp.CKind == OMPC_unknown) ? OMPC_firstprivate : OMPC_shared; 1151 return DVar; 1152 } 1153 } 1154 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced 1155 // in a Construct, implicitly determined, p.3] 1156 // For constructs other than task, if no default clause is present, these 1157 // variables inherit their data-sharing attributes from the enclosing 1158 // context. 1159 return getDSA(++Iter, D); 1160 } 1161 1162 const Expr *DSAStackTy::addUniqueAligned(const ValueDecl *D, 1163 const Expr *NewDE) { 1164 assert(!isStackEmpty() && "Data sharing attributes stack is empty"); 1165 D = getCanonicalDecl(D); 1166 SharingMapTy &StackElem = getTopOfStack(); 1167 auto It = StackElem.AlignedMap.find(D); 1168 if (It == StackElem.AlignedMap.end()) { 1169 assert(NewDE && "Unexpected nullptr expr to be added into aligned map"); 1170 StackElem.AlignedMap[D] = NewDE; 1171 return nullptr; 1172 } 1173 assert(It->second && "Unexpected nullptr expr in the aligned map"); 1174 return It->second; 1175 } 1176 1177 const Expr *DSAStackTy::addUniqueNontemporal(const ValueDecl *D, 1178 const Expr *NewDE) { 1179 assert(!isStackEmpty() && "Data sharing attributes stack is empty"); 1180 D = getCanonicalDecl(D); 1181 SharingMapTy &StackElem = getTopOfStack(); 1182 auto It = StackElem.NontemporalMap.find(D); 1183 if (It == StackElem.NontemporalMap.end()) { 1184 assert(NewDE && "Unexpected nullptr expr to be added into aligned map"); 1185 StackElem.NontemporalMap[D] = NewDE; 1186 return nullptr; 1187 } 1188 assert(It->second && "Unexpected nullptr expr in the aligned map"); 1189 return It->second; 1190 } 1191 1192 void DSAStackTy::addLoopControlVariable(const ValueDecl *D, VarDecl *Capture) { 1193 assert(!isStackEmpty() && "Data-sharing attributes stack is empty"); 1194 D = getCanonicalDecl(D); 1195 SharingMapTy &StackElem = getTopOfStack(); 1196 StackElem.LCVMap.try_emplace( 1197 D, LCDeclInfo(StackElem.LCVMap.size() + 1, Capture)); 1198 } 1199 1200 const DSAStackTy::LCDeclInfo 1201 DSAStackTy::isLoopControlVariable(const ValueDecl *D) const { 1202 assert(!isStackEmpty() && "Data-sharing attributes stack is empty"); 1203 D = getCanonicalDecl(D); 1204 const SharingMapTy &StackElem = getTopOfStack(); 1205 auto It = StackElem.LCVMap.find(D); 1206 if (It != StackElem.LCVMap.end()) 1207 return It->second; 1208 return {0, nullptr}; 1209 } 1210 1211 const DSAStackTy::LCDeclInfo 1212 DSAStackTy::isLoopControlVariable(const ValueDecl *D, unsigned Level) const { 1213 assert(!isStackEmpty() && "Data-sharing attributes stack is empty"); 1214 D = getCanonicalDecl(D); 1215 for (unsigned I = Level + 1; I > 0; --I) { 1216 const SharingMapTy &StackElem = getStackElemAtLevel(I - 1); 1217 auto It = StackElem.LCVMap.find(D); 1218 if (It != StackElem.LCVMap.end()) 1219 return It->second; 1220 } 1221 return {0, nullptr}; 1222 } 1223 1224 const DSAStackTy::LCDeclInfo 1225 DSAStackTy::isParentLoopControlVariable(const ValueDecl *D) const { 1226 const SharingMapTy *Parent = getSecondOnStackOrNull(); 1227 assert(Parent && "Data-sharing attributes stack is empty"); 1228 D = getCanonicalDecl(D); 1229 auto It = Parent->LCVMap.find(D); 1230 if (It != Parent->LCVMap.end()) 1231 return It->second; 1232 return {0, nullptr}; 1233 } 1234 1235 const ValueDecl *DSAStackTy::getParentLoopControlVariable(unsigned I) const { 1236 const SharingMapTy *Parent = getSecondOnStackOrNull(); 1237 assert(Parent && "Data-sharing attributes stack is empty"); 1238 if (Parent->LCVMap.size() < I) 1239 return nullptr; 1240 for (const auto &Pair : Parent->LCVMap) 1241 if (Pair.second.first == I) 1242 return Pair.first; 1243 return nullptr; 1244 } 1245 1246 void DSAStackTy::addDSA(const ValueDecl *D, const Expr *E, OpenMPClauseKind A, 1247 DeclRefExpr *PrivateCopy, unsigned Modifier) { 1248 D = getCanonicalDecl(D); 1249 if (A == OMPC_threadprivate) { 1250 DSAInfo &Data = Threadprivates[D]; 1251 Data.Attributes = A; 1252 Data.RefExpr.setPointer(E); 1253 Data.PrivateCopy = nullptr; 1254 Data.Modifier = Modifier; 1255 } else { 1256 DSAInfo &Data = getTopOfStack().SharingMap[D]; 1257 assert(Data.Attributes == OMPC_unknown || (A == Data.Attributes) || 1258 (A == OMPC_firstprivate && Data.Attributes == OMPC_lastprivate) || 1259 (A == OMPC_lastprivate && Data.Attributes == OMPC_firstprivate) || 1260 (isLoopControlVariable(D).first && A == OMPC_private)); 1261 Data.Modifier = Modifier; 1262 if (A == OMPC_lastprivate && Data.Attributes == OMPC_firstprivate) { 1263 Data.RefExpr.setInt(/*IntVal=*/true); 1264 return; 1265 } 1266 const bool IsLastprivate = 1267 A == OMPC_lastprivate || Data.Attributes == OMPC_lastprivate; 1268 Data.Attributes = A; 1269 Data.RefExpr.setPointerAndInt(E, IsLastprivate); 1270 Data.PrivateCopy = PrivateCopy; 1271 if (PrivateCopy) { 1272 DSAInfo &Data = getTopOfStack().SharingMap[PrivateCopy->getDecl()]; 1273 Data.Modifier = Modifier; 1274 Data.Attributes = A; 1275 Data.RefExpr.setPointerAndInt(PrivateCopy, IsLastprivate); 1276 Data.PrivateCopy = nullptr; 1277 } 1278 } 1279 } 1280 1281 /// Build a variable declaration for OpenMP loop iteration variable. 1282 static VarDecl *buildVarDecl(Sema &SemaRef, SourceLocation Loc, QualType Type, 1283 StringRef Name, const AttrVec *Attrs = nullptr, 1284 DeclRefExpr *OrigRef = nullptr) { 1285 DeclContext *DC = SemaRef.CurContext; 1286 IdentifierInfo *II = &SemaRef.PP.getIdentifierTable().get(Name); 1287 TypeSourceInfo *TInfo = SemaRef.Context.getTrivialTypeSourceInfo(Type, Loc); 1288 auto *Decl = 1289 VarDecl::Create(SemaRef.Context, DC, Loc, Loc, II, Type, TInfo, SC_None); 1290 if (Attrs) { 1291 for (specific_attr_iterator<AlignedAttr> I(Attrs->begin()), E(Attrs->end()); 1292 I != E; ++I) 1293 Decl->addAttr(*I); 1294 } 1295 Decl->setImplicit(); 1296 if (OrigRef) { 1297 Decl->addAttr( 1298 OMPReferencedVarAttr::CreateImplicit(SemaRef.Context, OrigRef)); 1299 } 1300 return Decl; 1301 } 1302 1303 static DeclRefExpr *buildDeclRefExpr(Sema &S, VarDecl *D, QualType Ty, 1304 SourceLocation Loc, 1305 bool RefersToCapture = false) { 1306 D->setReferenced(); 1307 D->markUsed(S.Context); 1308 return DeclRefExpr::Create(S.getASTContext(), NestedNameSpecifierLoc(), 1309 SourceLocation(), D, RefersToCapture, Loc, Ty, 1310 VK_LValue); 1311 } 1312 1313 void DSAStackTy::addTaskgroupReductionData(const ValueDecl *D, SourceRange SR, 1314 BinaryOperatorKind BOK) { 1315 D = getCanonicalDecl(D); 1316 assert(!isStackEmpty() && "Data-sharing attributes stack is empty"); 1317 assert( 1318 getTopOfStack().SharingMap[D].Attributes == OMPC_reduction && 1319 "Additional reduction info may be specified only for reduction items."); 1320 ReductionData &ReductionData = getTopOfStack().ReductionMap[D]; 1321 assert(ReductionData.ReductionRange.isInvalid() && 1322 getTopOfStack().Directive == OMPD_taskgroup && 1323 "Additional reduction info may be specified only once for reduction " 1324 "items."); 1325 ReductionData.set(BOK, SR); 1326 Expr *&TaskgroupReductionRef = 1327 getTopOfStack().TaskgroupReductionRef; 1328 if (!TaskgroupReductionRef) { 1329 VarDecl *VD = buildVarDecl(SemaRef, SR.getBegin(), 1330 SemaRef.Context.VoidPtrTy, ".task_red."); 1331 TaskgroupReductionRef = 1332 buildDeclRefExpr(SemaRef, VD, SemaRef.Context.VoidPtrTy, SR.getBegin()); 1333 } 1334 } 1335 1336 void DSAStackTy::addTaskgroupReductionData(const ValueDecl *D, SourceRange SR, 1337 const Expr *ReductionRef) { 1338 D = getCanonicalDecl(D); 1339 assert(!isStackEmpty() && "Data-sharing attributes stack is empty"); 1340 assert( 1341 getTopOfStack().SharingMap[D].Attributes == OMPC_reduction && 1342 "Additional reduction info may be specified only for reduction items."); 1343 ReductionData &ReductionData = getTopOfStack().ReductionMap[D]; 1344 assert(ReductionData.ReductionRange.isInvalid() && 1345 getTopOfStack().Directive == OMPD_taskgroup && 1346 "Additional reduction info may be specified only once for reduction " 1347 "items."); 1348 ReductionData.set(ReductionRef, SR); 1349 Expr *&TaskgroupReductionRef = 1350 getTopOfStack().TaskgroupReductionRef; 1351 if (!TaskgroupReductionRef) { 1352 VarDecl *VD = buildVarDecl(SemaRef, SR.getBegin(), 1353 SemaRef.Context.VoidPtrTy, ".task_red."); 1354 TaskgroupReductionRef = 1355 buildDeclRefExpr(SemaRef, VD, SemaRef.Context.VoidPtrTy, SR.getBegin()); 1356 } 1357 } 1358 1359 const DSAStackTy::DSAVarData DSAStackTy::getTopMostTaskgroupReductionData( 1360 const ValueDecl *D, SourceRange &SR, BinaryOperatorKind &BOK, 1361 Expr *&TaskgroupDescriptor) const { 1362 D = getCanonicalDecl(D); 1363 assert(!isStackEmpty() && "Data-sharing attributes stack is empty."); 1364 for (const_iterator I = begin() + 1, E = end(); I != E; ++I) { 1365 const DSAInfo &Data = I->SharingMap.lookup(D); 1366 if (Data.Attributes != OMPC_reduction || I->Directive != OMPD_taskgroup) 1367 continue; 1368 const ReductionData &ReductionData = I->ReductionMap.lookup(D); 1369 if (!ReductionData.ReductionOp || 1370 ReductionData.ReductionOp.is<const Expr *>()) 1371 return DSAVarData(); 1372 SR = ReductionData.ReductionRange; 1373 BOK = ReductionData.ReductionOp.get<ReductionData::BOKPtrType>(); 1374 assert(I->TaskgroupReductionRef && "taskgroup reduction reference " 1375 "expression for the descriptor is not " 1376 "set."); 1377 TaskgroupDescriptor = I->TaskgroupReductionRef; 1378 return DSAVarData(OMPD_taskgroup, OMPC_reduction, Data.RefExpr.getPointer(), 1379 Data.PrivateCopy, I->DefaultAttrLoc, /*Modifier=*/0); 1380 } 1381 return DSAVarData(); 1382 } 1383 1384 const DSAStackTy::DSAVarData DSAStackTy::getTopMostTaskgroupReductionData( 1385 const ValueDecl *D, SourceRange &SR, const Expr *&ReductionRef, 1386 Expr *&TaskgroupDescriptor) const { 1387 D = getCanonicalDecl(D); 1388 assert(!isStackEmpty() && "Data-sharing attributes stack is empty."); 1389 for (const_iterator I = begin() + 1, E = end(); I != E; ++I) { 1390 const DSAInfo &Data = I->SharingMap.lookup(D); 1391 if (Data.Attributes != OMPC_reduction || I->Directive != OMPD_taskgroup) 1392 continue; 1393 const ReductionData &ReductionData = I->ReductionMap.lookup(D); 1394 if (!ReductionData.ReductionOp || 1395 !ReductionData.ReductionOp.is<const Expr *>()) 1396 return DSAVarData(); 1397 SR = ReductionData.ReductionRange; 1398 ReductionRef = ReductionData.ReductionOp.get<const Expr *>(); 1399 assert(I->TaskgroupReductionRef && "taskgroup reduction reference " 1400 "expression for the descriptor is not " 1401 "set."); 1402 TaskgroupDescriptor = I->TaskgroupReductionRef; 1403 return DSAVarData(OMPD_taskgroup, OMPC_reduction, Data.RefExpr.getPointer(), 1404 Data.PrivateCopy, I->DefaultAttrLoc, /*Modifier=*/0); 1405 } 1406 return DSAVarData(); 1407 } 1408 1409 bool DSAStackTy::isOpenMPLocal(VarDecl *D, const_iterator I) const { 1410 D = D->getCanonicalDecl(); 1411 for (const_iterator E = end(); I != E; ++I) { 1412 if (isImplicitOrExplicitTaskingRegion(I->Directive) || 1413 isOpenMPTargetExecutionDirective(I->Directive)) { 1414 Scope *TopScope = I->CurScope ? I->CurScope->getParent() : nullptr; 1415 Scope *CurScope = getCurScope(); 1416 while (CurScope && CurScope != TopScope && !CurScope->isDeclScope(D)) 1417 CurScope = CurScope->getParent(); 1418 return CurScope != TopScope; 1419 } 1420 } 1421 return false; 1422 } 1423 1424 static bool isConstNotMutableType(Sema &SemaRef, QualType Type, 1425 bool AcceptIfMutable = true, 1426 bool *IsClassType = nullptr) { 1427 ASTContext &Context = SemaRef.getASTContext(); 1428 Type = Type.getNonReferenceType().getCanonicalType(); 1429 bool IsConstant = Type.isConstant(Context); 1430 Type = Context.getBaseElementType(Type); 1431 const CXXRecordDecl *RD = AcceptIfMutable && SemaRef.getLangOpts().CPlusPlus 1432 ? Type->getAsCXXRecordDecl() 1433 : nullptr; 1434 if (const auto *CTSD = dyn_cast_or_null<ClassTemplateSpecializationDecl>(RD)) 1435 if (const ClassTemplateDecl *CTD = CTSD->getSpecializedTemplate()) 1436 RD = CTD->getTemplatedDecl(); 1437 if (IsClassType) 1438 *IsClassType = RD; 1439 return IsConstant && !(SemaRef.getLangOpts().CPlusPlus && RD && 1440 RD->hasDefinition() && RD->hasMutableFields()); 1441 } 1442 1443 static bool rejectConstNotMutableType(Sema &SemaRef, const ValueDecl *D, 1444 QualType Type, OpenMPClauseKind CKind, 1445 SourceLocation ELoc, 1446 bool AcceptIfMutable = true, 1447 bool ListItemNotVar = false) { 1448 ASTContext &Context = SemaRef.getASTContext(); 1449 bool IsClassType; 1450 if (isConstNotMutableType(SemaRef, Type, AcceptIfMutable, &IsClassType)) { 1451 unsigned Diag = ListItemNotVar 1452 ? diag::err_omp_const_list_item 1453 : IsClassType ? diag::err_omp_const_not_mutable_variable 1454 : diag::err_omp_const_variable; 1455 SemaRef.Diag(ELoc, Diag) << getOpenMPClauseName(CKind); 1456 if (!ListItemNotVar && D) { 1457 const VarDecl *VD = dyn_cast<VarDecl>(D); 1458 bool IsDecl = !VD || VD->isThisDeclarationADefinition(Context) == 1459 VarDecl::DeclarationOnly; 1460 SemaRef.Diag(D->getLocation(), 1461 IsDecl ? diag::note_previous_decl : diag::note_defined_here) 1462 << D; 1463 } 1464 return true; 1465 } 1466 return false; 1467 } 1468 1469 const DSAStackTy::DSAVarData DSAStackTy::getTopDSA(ValueDecl *D, 1470 bool FromParent) { 1471 D = getCanonicalDecl(D); 1472 DSAVarData DVar; 1473 1474 auto *VD = dyn_cast<VarDecl>(D); 1475 auto TI = Threadprivates.find(D); 1476 if (TI != Threadprivates.end()) { 1477 DVar.RefExpr = TI->getSecond().RefExpr.getPointer(); 1478 DVar.CKind = OMPC_threadprivate; 1479 DVar.Modifier = TI->getSecond().Modifier; 1480 return DVar; 1481 } 1482 if (VD && VD->hasAttr<OMPThreadPrivateDeclAttr>()) { 1483 DVar.RefExpr = buildDeclRefExpr( 1484 SemaRef, VD, D->getType().getNonReferenceType(), 1485 VD->getAttr<OMPThreadPrivateDeclAttr>()->getLocation()); 1486 DVar.CKind = OMPC_threadprivate; 1487 addDSA(D, DVar.RefExpr, OMPC_threadprivate); 1488 return DVar; 1489 } 1490 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced 1491 // in a Construct, C/C++, predetermined, p.1] 1492 // Variables appearing in threadprivate directives are threadprivate. 1493 if ((VD && VD->getTLSKind() != VarDecl::TLS_None && 1494 !(VD->hasAttr<OMPThreadPrivateDeclAttr>() && 1495 SemaRef.getLangOpts().OpenMPUseTLS && 1496 SemaRef.getASTContext().getTargetInfo().isTLSSupported())) || 1497 (VD && VD->getStorageClass() == SC_Register && 1498 VD->hasAttr<AsmLabelAttr>() && !VD->isLocalVarDecl())) { 1499 DVar.RefExpr = buildDeclRefExpr( 1500 SemaRef, VD, D->getType().getNonReferenceType(), D->getLocation()); 1501 DVar.CKind = OMPC_threadprivate; 1502 addDSA(D, DVar.RefExpr, OMPC_threadprivate); 1503 return DVar; 1504 } 1505 if (SemaRef.getLangOpts().OpenMPCUDAMode && VD && 1506 VD->isLocalVarDeclOrParm() && !isStackEmpty() && 1507 !isLoopControlVariable(D).first) { 1508 const_iterator IterTarget = 1509 std::find_if(begin(), end(), [](const SharingMapTy &Data) { 1510 return isOpenMPTargetExecutionDirective(Data.Directive); 1511 }); 1512 if (IterTarget != end()) { 1513 const_iterator ParentIterTarget = IterTarget + 1; 1514 for (const_iterator Iter = begin(); 1515 Iter != ParentIterTarget; ++Iter) { 1516 if (isOpenMPLocal(VD, Iter)) { 1517 DVar.RefExpr = 1518 buildDeclRefExpr(SemaRef, VD, D->getType().getNonReferenceType(), 1519 D->getLocation()); 1520 DVar.CKind = OMPC_threadprivate; 1521 return DVar; 1522 } 1523 } 1524 if (!isClauseParsingMode() || IterTarget != begin()) { 1525 auto DSAIter = IterTarget->SharingMap.find(D); 1526 if (DSAIter != IterTarget->SharingMap.end() && 1527 isOpenMPPrivate(DSAIter->getSecond().Attributes)) { 1528 DVar.RefExpr = DSAIter->getSecond().RefExpr.getPointer(); 1529 DVar.CKind = OMPC_threadprivate; 1530 return DVar; 1531 } 1532 const_iterator End = end(); 1533 if (!SemaRef.isOpenMPCapturedByRef( 1534 D, std::distance(ParentIterTarget, End), 1535 /*OpenMPCaptureLevel=*/0)) { 1536 DVar.RefExpr = 1537 buildDeclRefExpr(SemaRef, VD, D->getType().getNonReferenceType(), 1538 IterTarget->ConstructLoc); 1539 DVar.CKind = OMPC_threadprivate; 1540 return DVar; 1541 } 1542 } 1543 } 1544 } 1545 1546 if (isStackEmpty()) 1547 // Not in OpenMP execution region and top scope was already checked. 1548 return DVar; 1549 1550 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced 1551 // in a Construct, C/C++, predetermined, p.4] 1552 // Static data members are shared. 1553 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced 1554 // in a Construct, C/C++, predetermined, p.7] 1555 // Variables with static storage duration that are declared in a scope 1556 // inside the construct are shared. 1557 if (VD && VD->isStaticDataMember()) { 1558 // Check for explicitly specified attributes. 1559 const_iterator I = begin(); 1560 const_iterator EndI = end(); 1561 if (FromParent && I != EndI) 1562 ++I; 1563 if (I != EndI) { 1564 auto It = I->SharingMap.find(D); 1565 if (It != I->SharingMap.end()) { 1566 const DSAInfo &Data = It->getSecond(); 1567 DVar.RefExpr = Data.RefExpr.getPointer(); 1568 DVar.PrivateCopy = Data.PrivateCopy; 1569 DVar.CKind = Data.Attributes; 1570 DVar.ImplicitDSALoc = I->DefaultAttrLoc; 1571 DVar.DKind = I->Directive; 1572 DVar.Modifier = Data.Modifier; 1573 return DVar; 1574 } 1575 } 1576 1577 DVar.CKind = OMPC_shared; 1578 return DVar; 1579 } 1580 1581 auto &&MatchesAlways = [](OpenMPDirectiveKind) { return true; }; 1582 // The predetermined shared attribute for const-qualified types having no 1583 // mutable members was removed after OpenMP 3.1. 1584 if (SemaRef.LangOpts.OpenMP <= 31) { 1585 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced 1586 // in a Construct, C/C++, predetermined, p.6] 1587 // Variables with const qualified type having no mutable member are 1588 // shared. 1589 if (isConstNotMutableType(SemaRef, D->getType())) { 1590 // Variables with const-qualified type having no mutable member may be 1591 // listed in a firstprivate clause, even if they are static data members. 1592 DSAVarData DVarTemp = hasInnermostDSA( 1593 D, 1594 [](OpenMPClauseKind C) { 1595 return C == OMPC_firstprivate || C == OMPC_shared; 1596 }, 1597 MatchesAlways, FromParent); 1598 if (DVarTemp.CKind != OMPC_unknown && DVarTemp.RefExpr) 1599 return DVarTemp; 1600 1601 DVar.CKind = OMPC_shared; 1602 return DVar; 1603 } 1604 } 1605 1606 // Explicitly specified attributes and local variables with predetermined 1607 // attributes. 1608 const_iterator I = begin(); 1609 const_iterator EndI = end(); 1610 if (FromParent && I != EndI) 1611 ++I; 1612 if (I == EndI) 1613 return DVar; 1614 auto It = I->SharingMap.find(D); 1615 if (It != I->SharingMap.end()) { 1616 const DSAInfo &Data = It->getSecond(); 1617 DVar.RefExpr = Data.RefExpr.getPointer(); 1618 DVar.PrivateCopy = Data.PrivateCopy; 1619 DVar.CKind = Data.Attributes; 1620 DVar.ImplicitDSALoc = I->DefaultAttrLoc; 1621 DVar.DKind = I->Directive; 1622 DVar.Modifier = Data.Modifier; 1623 } 1624 1625 return DVar; 1626 } 1627 1628 const DSAStackTy::DSAVarData DSAStackTy::getImplicitDSA(ValueDecl *D, 1629 bool FromParent) const { 1630 if (isStackEmpty()) { 1631 const_iterator I; 1632 return getDSA(I, D); 1633 } 1634 D = getCanonicalDecl(D); 1635 const_iterator StartI = begin(); 1636 const_iterator EndI = end(); 1637 if (FromParent && StartI != EndI) 1638 ++StartI; 1639 return getDSA(StartI, D); 1640 } 1641 1642 const DSAStackTy::DSAVarData DSAStackTy::getImplicitDSA(ValueDecl *D, 1643 unsigned Level) const { 1644 if (getStackSize() <= Level) 1645 return DSAVarData(); 1646 D = getCanonicalDecl(D); 1647 const_iterator StartI = std::next(begin(), getStackSize() - 1 - Level); 1648 return getDSA(StartI, D); 1649 } 1650 1651 const DSAStackTy::DSAVarData 1652 DSAStackTy::hasDSA(ValueDecl *D, 1653 const llvm::function_ref<bool(OpenMPClauseKind)> CPred, 1654 const llvm::function_ref<bool(OpenMPDirectiveKind)> DPred, 1655 bool FromParent) const { 1656 if (isStackEmpty()) 1657 return {}; 1658 D = getCanonicalDecl(D); 1659 const_iterator I = begin(); 1660 const_iterator EndI = end(); 1661 if (FromParent && I != EndI) 1662 ++I; 1663 for (; I != EndI; ++I) { 1664 if (!DPred(I->Directive) && 1665 !isImplicitOrExplicitTaskingRegion(I->Directive)) 1666 continue; 1667 const_iterator NewI = I; 1668 DSAVarData DVar = getDSA(NewI, D); 1669 if (I == NewI && CPred(DVar.CKind)) 1670 return DVar; 1671 } 1672 return {}; 1673 } 1674 1675 const DSAStackTy::DSAVarData DSAStackTy::hasInnermostDSA( 1676 ValueDecl *D, const llvm::function_ref<bool(OpenMPClauseKind)> CPred, 1677 const llvm::function_ref<bool(OpenMPDirectiveKind)> DPred, 1678 bool FromParent) const { 1679 if (isStackEmpty()) 1680 return {}; 1681 D = getCanonicalDecl(D); 1682 const_iterator StartI = begin(); 1683 const_iterator EndI = end(); 1684 if (FromParent && StartI != EndI) 1685 ++StartI; 1686 if (StartI == EndI || !DPred(StartI->Directive)) 1687 return {}; 1688 const_iterator NewI = StartI; 1689 DSAVarData DVar = getDSA(NewI, D); 1690 return (NewI == StartI && CPred(DVar.CKind)) ? DVar : DSAVarData(); 1691 } 1692 1693 bool DSAStackTy::hasExplicitDSA( 1694 const ValueDecl *D, const llvm::function_ref<bool(OpenMPClauseKind)> CPred, 1695 unsigned Level, bool NotLastprivate) const { 1696 if (getStackSize() <= Level) 1697 return false; 1698 D = getCanonicalDecl(D); 1699 const SharingMapTy &StackElem = getStackElemAtLevel(Level); 1700 auto I = StackElem.SharingMap.find(D); 1701 if (I != StackElem.SharingMap.end() && 1702 I->getSecond().RefExpr.getPointer() && 1703 CPred(I->getSecond().Attributes) && 1704 (!NotLastprivate || !I->getSecond().RefExpr.getInt())) 1705 return true; 1706 // Check predetermined rules for the loop control variables. 1707 auto LI = StackElem.LCVMap.find(D); 1708 if (LI != StackElem.LCVMap.end()) 1709 return CPred(OMPC_private); 1710 return false; 1711 } 1712 1713 bool DSAStackTy::hasExplicitDirective( 1714 const llvm::function_ref<bool(OpenMPDirectiveKind)> DPred, 1715 unsigned Level) const { 1716 if (getStackSize() <= Level) 1717 return false; 1718 const SharingMapTy &StackElem = getStackElemAtLevel(Level); 1719 return DPred(StackElem.Directive); 1720 } 1721 1722 bool DSAStackTy::hasDirective( 1723 const llvm::function_ref<bool(OpenMPDirectiveKind, 1724 const DeclarationNameInfo &, SourceLocation)> 1725 DPred, 1726 bool FromParent) const { 1727 // We look only in the enclosing region. 1728 size_t Skip = FromParent ? 2 : 1; 1729 for (const_iterator I = begin() + std::min(Skip, getStackSize()), E = end(); 1730 I != E; ++I) { 1731 if (DPred(I->Directive, I->DirectiveName, I->ConstructLoc)) 1732 return true; 1733 } 1734 return false; 1735 } 1736 1737 void Sema::InitDataSharingAttributesStack() { 1738 VarDataSharingAttributesStack = new DSAStackTy(*this); 1739 } 1740 1741 #define DSAStack static_cast<DSAStackTy *>(VarDataSharingAttributesStack) 1742 1743 void Sema::pushOpenMPFunctionRegion() { 1744 DSAStack->pushFunction(); 1745 } 1746 1747 void Sema::popOpenMPFunctionRegion(const FunctionScopeInfo *OldFSI) { 1748 DSAStack->popFunction(OldFSI); 1749 } 1750 1751 static bool isOpenMPDeviceDelayedContext(Sema &S) { 1752 assert(S.LangOpts.OpenMP && S.LangOpts.OpenMPIsDevice && 1753 "Expected OpenMP device compilation."); 1754 return !S.isInOpenMPTargetExecutionDirective() && 1755 !S.isInOpenMPDeclareTargetContext(); 1756 } 1757 1758 namespace { 1759 /// Status of the function emission on the host/device. 1760 enum class FunctionEmissionStatus { 1761 Emitted, 1762 Discarded, 1763 Unknown, 1764 }; 1765 } // anonymous namespace 1766 1767 Sema::DeviceDiagBuilder Sema::diagIfOpenMPDeviceCode(SourceLocation Loc, 1768 unsigned DiagID) { 1769 assert(LangOpts.OpenMP && LangOpts.OpenMPIsDevice && 1770 "Expected OpenMP device compilation."); 1771 FunctionEmissionStatus FES = getEmissionStatus(getCurFunctionDecl()); 1772 DeviceDiagBuilder::Kind Kind = DeviceDiagBuilder::K_Nop; 1773 switch (FES) { 1774 case FunctionEmissionStatus::Emitted: 1775 Kind = DeviceDiagBuilder::K_Immediate; 1776 break; 1777 case FunctionEmissionStatus::Unknown: 1778 Kind = isOpenMPDeviceDelayedContext(*this) ? DeviceDiagBuilder::K_Deferred 1779 : DeviceDiagBuilder::K_Immediate; 1780 break; 1781 case FunctionEmissionStatus::TemplateDiscarded: 1782 case FunctionEmissionStatus::OMPDiscarded: 1783 Kind = DeviceDiagBuilder::K_Nop; 1784 break; 1785 case FunctionEmissionStatus::CUDADiscarded: 1786 llvm_unreachable("CUDADiscarded unexpected in OpenMP device compilation"); 1787 break; 1788 } 1789 1790 return DeviceDiagBuilder(Kind, Loc, DiagID, getCurFunctionDecl(), *this); 1791 } 1792 1793 Sema::DeviceDiagBuilder Sema::diagIfOpenMPHostCode(SourceLocation Loc, 1794 unsigned DiagID) { 1795 assert(LangOpts.OpenMP && !LangOpts.OpenMPIsDevice && 1796 "Expected OpenMP host compilation."); 1797 FunctionEmissionStatus FES = getEmissionStatus(getCurFunctionDecl()); 1798 DeviceDiagBuilder::Kind Kind = DeviceDiagBuilder::K_Nop; 1799 switch (FES) { 1800 case FunctionEmissionStatus::Emitted: 1801 Kind = DeviceDiagBuilder::K_Immediate; 1802 break; 1803 case FunctionEmissionStatus::Unknown: 1804 Kind = DeviceDiagBuilder::K_Deferred; 1805 break; 1806 case FunctionEmissionStatus::TemplateDiscarded: 1807 case FunctionEmissionStatus::OMPDiscarded: 1808 case FunctionEmissionStatus::CUDADiscarded: 1809 Kind = DeviceDiagBuilder::K_Nop; 1810 break; 1811 } 1812 1813 return DeviceDiagBuilder(Kind, Loc, DiagID, getCurFunctionDecl(), *this); 1814 } 1815 1816 void Sema::checkOpenMPDeviceExpr(const Expr *E) { 1817 assert(getLangOpts().OpenMP && getLangOpts().OpenMPIsDevice && 1818 "OpenMP device compilation mode is expected."); 1819 QualType Ty = E->getType(); 1820 if ((Ty->isFloat16Type() && !Context.getTargetInfo().hasFloat16Type()) || 1821 ((Ty->isFloat128Type() || 1822 (Ty->isRealFloatingType() && Context.getTypeSize(Ty) == 128)) && 1823 !Context.getTargetInfo().hasFloat128Type()) || 1824 (Ty->isIntegerType() && Context.getTypeSize(Ty) == 128 && 1825 !Context.getTargetInfo().hasInt128Type())) 1826 targetDiag(E->getExprLoc(), diag::err_omp_unsupported_type) 1827 << static_cast<unsigned>(Context.getTypeSize(Ty)) << Ty 1828 << Context.getTargetInfo().getTriple().str() << E->getSourceRange(); 1829 } 1830 1831 static OpenMPDefaultmapClauseKind 1832 getVariableCategoryFromDecl(const LangOptions &LO, const ValueDecl *VD) { 1833 if (LO.OpenMP <= 45) { 1834 if (VD->getType().getNonReferenceType()->isScalarType()) 1835 return OMPC_DEFAULTMAP_scalar; 1836 return OMPC_DEFAULTMAP_aggregate; 1837 } 1838 if (VD->getType().getNonReferenceType()->isAnyPointerType()) 1839 return OMPC_DEFAULTMAP_pointer; 1840 if (VD->getType().getNonReferenceType()->isScalarType()) 1841 return OMPC_DEFAULTMAP_scalar; 1842 return OMPC_DEFAULTMAP_aggregate; 1843 } 1844 1845 bool Sema::isOpenMPCapturedByRef(const ValueDecl *D, unsigned Level, 1846 unsigned OpenMPCaptureLevel) const { 1847 assert(LangOpts.OpenMP && "OpenMP is not allowed"); 1848 1849 ASTContext &Ctx = getASTContext(); 1850 bool IsByRef = true; 1851 1852 // Find the directive that is associated with the provided scope. 1853 D = cast<ValueDecl>(D->getCanonicalDecl()); 1854 QualType Ty = D->getType(); 1855 1856 bool IsVariableUsedInMapClause = false; 1857 if (DSAStack->hasExplicitDirective(isOpenMPTargetExecutionDirective, Level)) { 1858 // This table summarizes how a given variable should be passed to the device 1859 // given its type and the clauses where it appears. This table is based on 1860 // the description in OpenMP 4.5 [2.10.4, target Construct] and 1861 // OpenMP 4.5 [2.15.5, Data-mapping Attribute Rules and Clauses]. 1862 // 1863 // ========================================================================= 1864 // | type | defaultmap | pvt | first | is_device_ptr | map | res. | 1865 // | |(tofrom:scalar)| | pvt | | | | 1866 // ========================================================================= 1867 // | scl | | | | - | | bycopy| 1868 // | scl | | - | x | - | - | bycopy| 1869 // | scl | | x | - | - | - | null | 1870 // | scl | x | | | - | | byref | 1871 // | scl | x | - | x | - | - | bycopy| 1872 // | scl | x | x | - | - | - | null | 1873 // | scl | | - | - | - | x | byref | 1874 // | scl | x | - | - | - | x | byref | 1875 // 1876 // | agg | n.a. | | | - | | byref | 1877 // | agg | n.a. | - | x | - | - | byref | 1878 // | agg | n.a. | x | - | - | - | null | 1879 // | agg | n.a. | - | - | - | x | byref | 1880 // | agg | n.a. | - | - | - | x[] | byref | 1881 // 1882 // | ptr | n.a. | | | - | | bycopy| 1883 // | ptr | n.a. | - | x | - | - | bycopy| 1884 // | ptr | n.a. | x | - | - | - | null | 1885 // | ptr | n.a. | - | - | - | x | byref | 1886 // | ptr | n.a. | - | - | - | x[] | bycopy| 1887 // | ptr | n.a. | - | - | x | | bycopy| 1888 // | ptr | n.a. | - | - | x | x | bycopy| 1889 // | ptr | n.a. | - | - | x | x[] | bycopy| 1890 // ========================================================================= 1891 // Legend: 1892 // scl - scalar 1893 // ptr - pointer 1894 // agg - aggregate 1895 // x - applies 1896 // - - invalid in this combination 1897 // [] - mapped with an array section 1898 // byref - should be mapped by reference 1899 // byval - should be mapped by value 1900 // null - initialize a local variable to null on the device 1901 // 1902 // Observations: 1903 // - All scalar declarations that show up in a map clause have to be passed 1904 // by reference, because they may have been mapped in the enclosing data 1905 // environment. 1906 // - If the scalar value does not fit the size of uintptr, it has to be 1907 // passed by reference, regardless the result in the table above. 1908 // - For pointers mapped by value that have either an implicit map or an 1909 // array section, the runtime library may pass the NULL value to the 1910 // device instead of the value passed to it by the compiler. 1911 1912 if (Ty->isReferenceType()) 1913 Ty = Ty->castAs<ReferenceType>()->getPointeeType(); 1914 1915 // Locate map clauses and see if the variable being captured is referred to 1916 // in any of those clauses. Here we only care about variables, not fields, 1917 // because fields are part of aggregates. 1918 bool IsVariableAssociatedWithSection = false; 1919 1920 DSAStack->checkMappableExprComponentListsForDeclAtLevel( 1921 D, Level, 1922 [&IsVariableUsedInMapClause, &IsVariableAssociatedWithSection, D]( 1923 OMPClauseMappableExprCommon::MappableExprComponentListRef 1924 MapExprComponents, 1925 OpenMPClauseKind WhereFoundClauseKind) { 1926 // Only the map clause information influences how a variable is 1927 // captured. E.g. is_device_ptr does not require changing the default 1928 // behavior. 1929 if (WhereFoundClauseKind != OMPC_map) 1930 return false; 1931 1932 auto EI = MapExprComponents.rbegin(); 1933 auto EE = MapExprComponents.rend(); 1934 1935 assert(EI != EE && "Invalid map expression!"); 1936 1937 if (isa<DeclRefExpr>(EI->getAssociatedExpression())) 1938 IsVariableUsedInMapClause |= EI->getAssociatedDeclaration() == D; 1939 1940 ++EI; 1941 if (EI == EE) 1942 return false; 1943 1944 if (isa<ArraySubscriptExpr>(EI->getAssociatedExpression()) || 1945 isa<OMPArraySectionExpr>(EI->getAssociatedExpression()) || 1946 isa<MemberExpr>(EI->getAssociatedExpression()) || 1947 isa<OMPArrayShapingExpr>(EI->getAssociatedExpression())) { 1948 IsVariableAssociatedWithSection = true; 1949 // There is nothing more we need to know about this variable. 1950 return true; 1951 } 1952 1953 // Keep looking for more map info. 1954 return false; 1955 }); 1956 1957 if (IsVariableUsedInMapClause) { 1958 // If variable is identified in a map clause it is always captured by 1959 // reference except if it is a pointer that is dereferenced somehow. 1960 IsByRef = !(Ty->isPointerType() && IsVariableAssociatedWithSection); 1961 } else { 1962 // By default, all the data that has a scalar type is mapped by copy 1963 // (except for reduction variables). 1964 // Defaultmap scalar is mutual exclusive to defaultmap pointer 1965 IsByRef = 1966 (DSAStack->isForceCaptureByReferenceInTargetExecutable() && 1967 !Ty->isAnyPointerType()) || 1968 !Ty->isScalarType() || 1969 DSAStack->isDefaultmapCapturedByRef( 1970 Level, getVariableCategoryFromDecl(LangOpts, D)) || 1971 DSAStack->hasExplicitDSA( 1972 D, [](OpenMPClauseKind K) { return K == OMPC_reduction; }, Level); 1973 } 1974 } 1975 1976 if (IsByRef && Ty.getNonReferenceType()->isScalarType()) { 1977 IsByRef = 1978 ((IsVariableUsedInMapClause && 1979 DSAStack->getCaptureRegion(Level, OpenMPCaptureLevel) == 1980 OMPD_target) || 1981 !DSAStack->hasExplicitDSA( 1982 D, 1983 [](OpenMPClauseKind K) -> bool { return K == OMPC_firstprivate; }, 1984 Level, /*NotLastprivate=*/true)) && 1985 // If the variable is artificial and must be captured by value - try to 1986 // capture by value. 1987 !(isa<OMPCapturedExprDecl>(D) && !D->hasAttr<OMPCaptureNoInitAttr>() && 1988 !cast<OMPCapturedExprDecl>(D)->getInit()->isGLValue()); 1989 } 1990 1991 // When passing data by copy, we need to make sure it fits the uintptr size 1992 // and alignment, because the runtime library only deals with uintptr types. 1993 // If it does not fit the uintptr size, we need to pass the data by reference 1994 // instead. 1995 if (!IsByRef && 1996 (Ctx.getTypeSizeInChars(Ty) > 1997 Ctx.getTypeSizeInChars(Ctx.getUIntPtrType()) || 1998 Ctx.getDeclAlign(D) > Ctx.getTypeAlignInChars(Ctx.getUIntPtrType()))) { 1999 IsByRef = true; 2000 } 2001 2002 return IsByRef; 2003 } 2004 2005 unsigned Sema::getOpenMPNestingLevel() const { 2006 assert(getLangOpts().OpenMP); 2007 return DSAStack->getNestingLevel(); 2008 } 2009 2010 bool Sema::isInOpenMPTargetExecutionDirective() const { 2011 return (isOpenMPTargetExecutionDirective(DSAStack->getCurrentDirective()) && 2012 !DSAStack->isClauseParsingMode()) || 2013 DSAStack->hasDirective( 2014 [](OpenMPDirectiveKind K, const DeclarationNameInfo &, 2015 SourceLocation) -> bool { 2016 return isOpenMPTargetExecutionDirective(K); 2017 }, 2018 false); 2019 } 2020 2021 VarDecl *Sema::isOpenMPCapturedDecl(ValueDecl *D, bool CheckScopeInfo, 2022 unsigned StopAt) { 2023 assert(LangOpts.OpenMP && "OpenMP is not allowed"); 2024 D = getCanonicalDecl(D); 2025 2026 auto *VD = dyn_cast<VarDecl>(D); 2027 // Do not capture constexpr variables. 2028 if (VD && VD->isConstexpr()) 2029 return nullptr; 2030 2031 // If we want to determine whether the variable should be captured from the 2032 // perspective of the current capturing scope, and we've already left all the 2033 // capturing scopes of the top directive on the stack, check from the 2034 // perspective of its parent directive (if any) instead. 2035 DSAStackTy::ParentDirectiveScope InParentDirectiveRAII( 2036 *DSAStack, CheckScopeInfo && DSAStack->isBodyComplete()); 2037 2038 // If we are attempting to capture a global variable in a directive with 2039 // 'target' we return true so that this global is also mapped to the device. 2040 // 2041 if (VD && !VD->hasLocalStorage() && 2042 (getCurCapturedRegion() || getCurBlock() || getCurLambda())) { 2043 if (isInOpenMPDeclareTargetContext()) { 2044 // Try to mark variable as declare target if it is used in capturing 2045 // regions. 2046 if (LangOpts.OpenMP <= 45 && 2047 !OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD)) 2048 checkDeclIsAllowedInOpenMPTarget(nullptr, VD); 2049 return nullptr; 2050 } else if (isInOpenMPTargetExecutionDirective()) { 2051 // If the declaration is enclosed in a 'declare target' directive, 2052 // then it should not be captured. 2053 // 2054 if (OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD)) 2055 return nullptr; 2056 CapturedRegionScopeInfo *CSI = nullptr; 2057 for (FunctionScopeInfo *FSI : llvm::drop_begin( 2058 llvm::reverse(FunctionScopes), 2059 CheckScopeInfo ? (FunctionScopes.size() - (StopAt + 1)) : 0)) { 2060 if (!isa<CapturingScopeInfo>(FSI)) 2061 return nullptr; 2062 if (auto *RSI = dyn_cast<CapturedRegionScopeInfo>(FSI)) 2063 if (RSI->CapRegionKind == CR_OpenMP) { 2064 CSI = RSI; 2065 break; 2066 } 2067 } 2068 SmallVector<OpenMPDirectiveKind, 4> Regions; 2069 getOpenMPCaptureRegions(Regions, 2070 DSAStack->getDirective(CSI->OpenMPLevel)); 2071 if (Regions[CSI->OpenMPCaptureLevel] != OMPD_task) 2072 return VD; 2073 } 2074 } 2075 2076 if (CheckScopeInfo) { 2077 bool OpenMPFound = false; 2078 for (unsigned I = StopAt + 1; I > 0; --I) { 2079 FunctionScopeInfo *FSI = FunctionScopes[I - 1]; 2080 if(!isa<CapturingScopeInfo>(FSI)) 2081 return nullptr; 2082 if (auto *RSI = dyn_cast<CapturedRegionScopeInfo>(FSI)) 2083 if (RSI->CapRegionKind == CR_OpenMP) { 2084 OpenMPFound = true; 2085 break; 2086 } 2087 } 2088 if (!OpenMPFound) 2089 return nullptr; 2090 } 2091 2092 if (DSAStack->getCurrentDirective() != OMPD_unknown && 2093 (!DSAStack->isClauseParsingMode() || 2094 DSAStack->getParentDirective() != OMPD_unknown)) { 2095 auto &&Info = DSAStack->isLoopControlVariable(D); 2096 if (Info.first || 2097 (VD && VD->hasLocalStorage() && 2098 isImplicitOrExplicitTaskingRegion(DSAStack->getCurrentDirective())) || 2099 (VD && DSAStack->isForceVarCapturing())) 2100 return VD ? VD : Info.second; 2101 DSAStackTy::DSAVarData DVarPrivate = 2102 DSAStack->getTopDSA(D, DSAStack->isClauseParsingMode()); 2103 if (DVarPrivate.CKind != OMPC_unknown && isOpenMPPrivate(DVarPrivate.CKind)) 2104 return VD ? VD : cast<VarDecl>(DVarPrivate.PrivateCopy->getDecl()); 2105 // Threadprivate variables must not be captured. 2106 if (isOpenMPThreadPrivate(DVarPrivate.CKind)) 2107 return nullptr; 2108 // The variable is not private or it is the variable in the directive with 2109 // default(none) clause and not used in any clause. 2110 DVarPrivate = DSAStack->hasDSA(D, isOpenMPPrivate, 2111 [](OpenMPDirectiveKind) { return true; }, 2112 DSAStack->isClauseParsingMode()); 2113 if (DVarPrivate.CKind != OMPC_unknown || 2114 (VD && DSAStack->getDefaultDSA() == DSA_none)) 2115 return VD ? VD : cast<VarDecl>(DVarPrivate.PrivateCopy->getDecl()); 2116 } 2117 return nullptr; 2118 } 2119 2120 void Sema::adjustOpenMPTargetScopeIndex(unsigned &FunctionScopesIndex, 2121 unsigned Level) const { 2122 FunctionScopesIndex -= getOpenMPCaptureLevels(DSAStack->getDirective(Level)); 2123 } 2124 2125 void Sema::startOpenMPLoop() { 2126 assert(LangOpts.OpenMP && "OpenMP must be enabled."); 2127 if (isOpenMPLoopDirective(DSAStack->getCurrentDirective())) 2128 DSAStack->loopInit(); 2129 } 2130 2131 void Sema::startOpenMPCXXRangeFor() { 2132 assert(LangOpts.OpenMP && "OpenMP must be enabled."); 2133 if (isOpenMPLoopDirective(DSAStack->getCurrentDirective())) { 2134 DSAStack->resetPossibleLoopCounter(); 2135 DSAStack->loopStart(); 2136 } 2137 } 2138 2139 OpenMPClauseKind Sema::isOpenMPPrivateDecl(ValueDecl *D, unsigned Level, 2140 unsigned CapLevel) const { 2141 assert(LangOpts.OpenMP && "OpenMP is not allowed"); 2142 if (DSAStack->hasExplicitDirective( 2143 [](OpenMPDirectiveKind K) { return isOpenMPTaskingDirective(K); }, 2144 Level)) { 2145 bool IsTriviallyCopyable = 2146 D->getType().getNonReferenceType().isTriviallyCopyableType(Context); 2147 OpenMPDirectiveKind DKind = DSAStack->getDirective(Level); 2148 SmallVector<OpenMPDirectiveKind, 4> CaptureRegions; 2149 getOpenMPCaptureRegions(CaptureRegions, DKind); 2150 if (isOpenMPTaskingDirective(CaptureRegions[CapLevel]) && 2151 (IsTriviallyCopyable || 2152 !isOpenMPTaskLoopDirective(CaptureRegions[CapLevel]))) { 2153 if (DSAStack->hasExplicitDSA( 2154 D, [](OpenMPClauseKind K) { return K == OMPC_firstprivate; }, 2155 Level, /*NotLastprivate=*/true)) 2156 return OMPC_firstprivate; 2157 DSAStackTy::DSAVarData DVar = DSAStack->getImplicitDSA(D, Level); 2158 if (DVar.CKind != OMPC_shared && 2159 !DSAStack->isLoopControlVariable(D, Level).first && !DVar.RefExpr) { 2160 DSAStack->addImplicitTaskFirstprivate(Level, D); 2161 return OMPC_firstprivate; 2162 } 2163 } 2164 } 2165 if (isOpenMPLoopDirective(DSAStack->getCurrentDirective())) { 2166 if (DSAStack->getAssociatedLoops() > 0 && 2167 !DSAStack->isLoopStarted()) { 2168 DSAStack->resetPossibleLoopCounter(D); 2169 DSAStack->loopStart(); 2170 return OMPC_private; 2171 } 2172 if ((DSAStack->getPossiblyLoopCunter() == D->getCanonicalDecl() || 2173 DSAStack->isLoopControlVariable(D).first) && 2174 !DSAStack->hasExplicitDSA( 2175 D, [](OpenMPClauseKind K) { return K != OMPC_private; }, Level) && 2176 !isOpenMPSimdDirective(DSAStack->getCurrentDirective())) 2177 return OMPC_private; 2178 } 2179 if (const auto *VD = dyn_cast<VarDecl>(D)) { 2180 if (DSAStack->isThreadPrivate(const_cast<VarDecl *>(VD)) && 2181 DSAStack->isForceVarCapturing() && 2182 !DSAStack->hasExplicitDSA( 2183 D, [](OpenMPClauseKind K) { return K == OMPC_copyin; }, Level)) 2184 return OMPC_private; 2185 } 2186 return (DSAStack->hasExplicitDSA( 2187 D, [](OpenMPClauseKind K) { return K == OMPC_private; }, Level) || 2188 (DSAStack->isClauseParsingMode() && 2189 DSAStack->getClauseParsingMode() == OMPC_private) || 2190 // Consider taskgroup reduction descriptor variable a private 2191 // to avoid possible capture in the region. 2192 (DSAStack->hasExplicitDirective( 2193 [](OpenMPDirectiveKind K) { return K == OMPD_taskgroup; }, 2194 Level) && 2195 DSAStack->isTaskgroupReductionRef(D, Level))) 2196 ? OMPC_private 2197 : OMPC_unknown; 2198 } 2199 2200 void Sema::setOpenMPCaptureKind(FieldDecl *FD, const ValueDecl *D, 2201 unsigned Level) { 2202 assert(LangOpts.OpenMP && "OpenMP is not allowed"); 2203 D = getCanonicalDecl(D); 2204 OpenMPClauseKind OMPC = OMPC_unknown; 2205 for (unsigned I = DSAStack->getNestingLevel() + 1; I > Level; --I) { 2206 const unsigned NewLevel = I - 1; 2207 if (DSAStack->hasExplicitDSA(D, 2208 [&OMPC](const OpenMPClauseKind K) { 2209 if (isOpenMPPrivate(K)) { 2210 OMPC = K; 2211 return true; 2212 } 2213 return false; 2214 }, 2215 NewLevel)) 2216 break; 2217 if (DSAStack->checkMappableExprComponentListsForDeclAtLevel( 2218 D, NewLevel, 2219 [](OMPClauseMappableExprCommon::MappableExprComponentListRef, 2220 OpenMPClauseKind) { return true; })) { 2221 OMPC = OMPC_map; 2222 break; 2223 } 2224 if (DSAStack->hasExplicitDirective(isOpenMPTargetExecutionDirective, 2225 NewLevel)) { 2226 OMPC = OMPC_map; 2227 if (DSAStack->mustBeFirstprivateAtLevel( 2228 NewLevel, getVariableCategoryFromDecl(LangOpts, D))) 2229 OMPC = OMPC_firstprivate; 2230 break; 2231 } 2232 } 2233 if (OMPC != OMPC_unknown) 2234 FD->addAttr(OMPCaptureKindAttr::CreateImplicit(Context, OMPC)); 2235 } 2236 2237 bool Sema::isOpenMPTargetCapturedDecl(const ValueDecl *D, unsigned Level, 2238 unsigned CaptureLevel) const { 2239 assert(LangOpts.OpenMP && "OpenMP is not allowed"); 2240 // Return true if the current level is no longer enclosed in a target region. 2241 2242 SmallVector<OpenMPDirectiveKind, 4> Regions; 2243 getOpenMPCaptureRegions(Regions, DSAStack->getDirective(Level)); 2244 const auto *VD = dyn_cast<VarDecl>(D); 2245 return VD && !VD->hasLocalStorage() && 2246 DSAStack->hasExplicitDirective(isOpenMPTargetExecutionDirective, 2247 Level) && 2248 Regions[CaptureLevel] != OMPD_task; 2249 } 2250 2251 bool Sema::isOpenMPGlobalCapturedDecl(ValueDecl *D, unsigned Level, 2252 unsigned CaptureLevel) const { 2253 assert(LangOpts.OpenMP && "OpenMP is not allowed"); 2254 // Return true if the current level is no longer enclosed in a target region. 2255 2256 if (const auto *VD = dyn_cast<VarDecl>(D)) { 2257 if (!VD->hasLocalStorage()) { 2258 DSAStackTy::DSAVarData TopDVar = 2259 DSAStack->getTopDSA(D, /*FromParent=*/false); 2260 unsigned NumLevels = 2261 getOpenMPCaptureLevels(DSAStack->getDirective(Level)); 2262 if (Level == 0) 2263 return (NumLevels == CaptureLevel + 1) && TopDVar.CKind != OMPC_shared; 2264 DSAStackTy::DSAVarData DVar = DSAStack->getImplicitDSA(D, Level - 1); 2265 return DVar.CKind != OMPC_shared || 2266 isOpenMPGlobalCapturedDecl( 2267 D, Level - 1, 2268 getOpenMPCaptureLevels(DSAStack->getDirective(Level - 1)) - 1); 2269 } 2270 } 2271 return true; 2272 } 2273 2274 void Sema::DestroyDataSharingAttributesStack() { delete DSAStack; } 2275 2276 void Sema::ActOnOpenMPBeginDeclareVariant(SourceLocation Loc, 2277 OMPTraitInfo &TI) { 2278 if (!OMPDeclareVariantScopes.empty()) { 2279 Diag(Loc, diag::warn_nested_declare_variant); 2280 return; 2281 } 2282 OMPDeclareVariantScopes.push_back(OMPDeclareVariantScope(TI)); 2283 } 2284 2285 void Sema::ActOnOpenMPEndDeclareVariant() { 2286 assert(isInOpenMPDeclareVariantScope() && 2287 "Not in OpenMP declare variant scope!"); 2288 2289 OMPDeclareVariantScopes.pop_back(); 2290 } 2291 2292 void Sema::finalizeOpenMPDelayedAnalysis(const FunctionDecl *Caller, 2293 const FunctionDecl *Callee, 2294 SourceLocation Loc) { 2295 assert(LangOpts.OpenMP && "Expected OpenMP compilation mode."); 2296 Optional<OMPDeclareTargetDeclAttr::DevTypeTy> DevTy = 2297 OMPDeclareTargetDeclAttr::getDeviceType(Caller->getMostRecentDecl()); 2298 // Ignore host functions during device analyzis. 2299 if (LangOpts.OpenMPIsDevice && DevTy && 2300 *DevTy == OMPDeclareTargetDeclAttr::DT_Host) 2301 return; 2302 // Ignore nohost functions during host analyzis. 2303 if (!LangOpts.OpenMPIsDevice && DevTy && 2304 *DevTy == OMPDeclareTargetDeclAttr::DT_NoHost) 2305 return; 2306 const FunctionDecl *FD = Callee->getMostRecentDecl(); 2307 DevTy = OMPDeclareTargetDeclAttr::getDeviceType(FD); 2308 if (LangOpts.OpenMPIsDevice && DevTy && 2309 *DevTy == OMPDeclareTargetDeclAttr::DT_Host) { 2310 // Diagnose host function called during device codegen. 2311 StringRef HostDevTy = 2312 getOpenMPSimpleClauseTypeName(OMPC_device_type, OMPC_DEVICE_TYPE_host); 2313 Diag(Loc, diag::err_omp_wrong_device_function_call) << HostDevTy << 0; 2314 Diag(FD->getAttr<OMPDeclareTargetDeclAttr>()->getLocation(), 2315 diag::note_omp_marked_device_type_here) 2316 << HostDevTy; 2317 return; 2318 } 2319 if (!LangOpts.OpenMPIsDevice && DevTy && 2320 *DevTy == OMPDeclareTargetDeclAttr::DT_NoHost) { 2321 // Diagnose nohost function called during host codegen. 2322 StringRef NoHostDevTy = getOpenMPSimpleClauseTypeName( 2323 OMPC_device_type, OMPC_DEVICE_TYPE_nohost); 2324 Diag(Loc, diag::err_omp_wrong_device_function_call) << NoHostDevTy << 1; 2325 Diag(FD->getAttr<OMPDeclareTargetDeclAttr>()->getLocation(), 2326 diag::note_omp_marked_device_type_here) 2327 << NoHostDevTy; 2328 } 2329 } 2330 2331 void Sema::StartOpenMPDSABlock(OpenMPDirectiveKind DKind, 2332 const DeclarationNameInfo &DirName, 2333 Scope *CurScope, SourceLocation Loc) { 2334 DSAStack->push(DKind, DirName, CurScope, Loc); 2335 PushExpressionEvaluationContext( 2336 ExpressionEvaluationContext::PotentiallyEvaluated); 2337 } 2338 2339 void Sema::StartOpenMPClause(OpenMPClauseKind K) { 2340 DSAStack->setClauseParsingMode(K); 2341 } 2342 2343 void Sema::EndOpenMPClause() { 2344 DSAStack->setClauseParsingMode(/*K=*/OMPC_unknown); 2345 } 2346 2347 static std::pair<ValueDecl *, bool> 2348 getPrivateItem(Sema &S, Expr *&RefExpr, SourceLocation &ELoc, 2349 SourceRange &ERange, bool AllowArraySection = false); 2350 2351 /// Check consistency of the reduction clauses. 2352 static void checkReductionClauses(Sema &S, DSAStackTy *Stack, 2353 ArrayRef<OMPClause *> Clauses) { 2354 bool InscanFound = false; 2355 SourceLocation InscanLoc; 2356 // OpenMP 5.0, 2.19.5.4 reduction Clause, Restrictions. 2357 // A reduction clause without the inscan reduction-modifier may not appear on 2358 // a construct on which a reduction clause with the inscan reduction-modifier 2359 // appears. 2360 for (OMPClause *C : Clauses) { 2361 if (C->getClauseKind() != OMPC_reduction) 2362 continue; 2363 auto *RC = cast<OMPReductionClause>(C); 2364 if (RC->getModifier() == OMPC_REDUCTION_inscan) { 2365 InscanFound = true; 2366 InscanLoc = RC->getModifierLoc(); 2367 break; 2368 } 2369 } 2370 if (InscanFound) { 2371 for (OMPClause *C : Clauses) { 2372 if (C->getClauseKind() != OMPC_reduction) 2373 continue; 2374 auto *RC = cast<OMPReductionClause>(C); 2375 if (RC->getModifier() != OMPC_REDUCTION_inscan) { 2376 S.Diag(RC->getModifier() == OMPC_REDUCTION_unknown 2377 ? RC->getBeginLoc() 2378 : RC->getModifierLoc(), 2379 diag::err_omp_inscan_reduction_expected); 2380 S.Diag(InscanLoc, diag::note_omp_previous_inscan_reduction); 2381 continue; 2382 } 2383 for (Expr *Ref : RC->varlists()) { 2384 assert(Ref && "NULL expr in OpenMP nontemporal clause."); 2385 SourceLocation ELoc; 2386 SourceRange ERange; 2387 Expr *SimpleRefExpr = Ref; 2388 auto Res = getPrivateItem(S, SimpleRefExpr, ELoc, ERange, 2389 /*AllowArraySection=*/true); 2390 ValueDecl *D = Res.first; 2391 if (!D) 2392 continue; 2393 if (!Stack->isUsedInScanDirective(getCanonicalDecl(D))) { 2394 S.Diag(Ref->getExprLoc(), 2395 diag::err_omp_reduction_not_inclusive_exclusive) 2396 << Ref->getSourceRange(); 2397 } 2398 } 2399 } 2400 } 2401 } 2402 2403 static void checkAllocateClauses(Sema &S, DSAStackTy *Stack, 2404 ArrayRef<OMPClause *> Clauses); 2405 static DeclRefExpr *buildCapture(Sema &S, ValueDecl *D, Expr *CaptureExpr, 2406 bool WithInit); 2407 2408 void Sema::EndOpenMPDSABlock(Stmt *CurDirective) { 2409 // OpenMP [2.14.3.5, Restrictions, C/C++, p.1] 2410 // A variable of class type (or array thereof) that appears in a lastprivate 2411 // clause requires an accessible, unambiguous default constructor for the 2412 // class type, unless the list item is also specified in a firstprivate 2413 // clause. 2414 if (const auto *D = dyn_cast_or_null<OMPExecutableDirective>(CurDirective)) { 2415 for (OMPClause *C : D->clauses()) { 2416 if (auto *Clause = dyn_cast<OMPLastprivateClause>(C)) { 2417 SmallVector<Expr *, 8> PrivateCopies; 2418 for (Expr *DE : Clause->varlists()) { 2419 if (DE->isValueDependent() || DE->isTypeDependent()) { 2420 PrivateCopies.push_back(nullptr); 2421 continue; 2422 } 2423 auto *DRE = cast<DeclRefExpr>(DE->IgnoreParens()); 2424 auto *VD = cast<VarDecl>(DRE->getDecl()); 2425 QualType Type = VD->getType().getNonReferenceType(); 2426 const DSAStackTy::DSAVarData DVar = 2427 DSAStack->getTopDSA(VD, /*FromParent=*/false); 2428 if (DVar.CKind == OMPC_lastprivate) { 2429 // Generate helper private variable and initialize it with the 2430 // default value. The address of the original variable is replaced 2431 // by the address of the new private variable in CodeGen. This new 2432 // variable is not added to IdResolver, so the code in the OpenMP 2433 // region uses original variable for proper diagnostics. 2434 VarDecl *VDPrivate = buildVarDecl( 2435 *this, DE->getExprLoc(), Type.getUnqualifiedType(), 2436 VD->getName(), VD->hasAttrs() ? &VD->getAttrs() : nullptr, DRE); 2437 ActOnUninitializedDecl(VDPrivate); 2438 if (VDPrivate->isInvalidDecl()) { 2439 PrivateCopies.push_back(nullptr); 2440 continue; 2441 } 2442 PrivateCopies.push_back(buildDeclRefExpr( 2443 *this, VDPrivate, DE->getType(), DE->getExprLoc())); 2444 } else { 2445 // The variable is also a firstprivate, so initialization sequence 2446 // for private copy is generated already. 2447 PrivateCopies.push_back(nullptr); 2448 } 2449 } 2450 Clause->setPrivateCopies(PrivateCopies); 2451 continue; 2452 } 2453 // Finalize nontemporal clause by handling private copies, if any. 2454 if (auto *Clause = dyn_cast<OMPNontemporalClause>(C)) { 2455 SmallVector<Expr *, 8> PrivateRefs; 2456 for (Expr *RefExpr : Clause->varlists()) { 2457 assert(RefExpr && "NULL expr in OpenMP nontemporal clause."); 2458 SourceLocation ELoc; 2459 SourceRange ERange; 2460 Expr *SimpleRefExpr = RefExpr; 2461 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange); 2462 if (Res.second) 2463 // It will be analyzed later. 2464 PrivateRefs.push_back(RefExpr); 2465 ValueDecl *D = Res.first; 2466 if (!D) 2467 continue; 2468 2469 const DSAStackTy::DSAVarData DVar = 2470 DSAStack->getTopDSA(D, /*FromParent=*/false); 2471 PrivateRefs.push_back(DVar.PrivateCopy ? DVar.PrivateCopy 2472 : SimpleRefExpr); 2473 } 2474 Clause->setPrivateRefs(PrivateRefs); 2475 continue; 2476 } 2477 } 2478 // Check allocate clauses. 2479 if (!CurContext->isDependentContext()) 2480 checkAllocateClauses(*this, DSAStack, D->clauses()); 2481 checkReductionClauses(*this, DSAStack, D->clauses()); 2482 } 2483 2484 DSAStack->pop(); 2485 DiscardCleanupsInEvaluationContext(); 2486 PopExpressionEvaluationContext(); 2487 } 2488 2489 static bool FinishOpenMPLinearClause(OMPLinearClause &Clause, DeclRefExpr *IV, 2490 Expr *NumIterations, Sema &SemaRef, 2491 Scope *S, DSAStackTy *Stack); 2492 2493 namespace { 2494 2495 class VarDeclFilterCCC final : public CorrectionCandidateCallback { 2496 private: 2497 Sema &SemaRef; 2498 2499 public: 2500 explicit VarDeclFilterCCC(Sema &S) : SemaRef(S) {} 2501 bool ValidateCandidate(const TypoCorrection &Candidate) override { 2502 NamedDecl *ND = Candidate.getCorrectionDecl(); 2503 if (const auto *VD = dyn_cast_or_null<VarDecl>(ND)) { 2504 return VD->hasGlobalStorage() && 2505 SemaRef.isDeclInScope(ND, SemaRef.getCurLexicalContext(), 2506 SemaRef.getCurScope()); 2507 } 2508 return false; 2509 } 2510 2511 std::unique_ptr<CorrectionCandidateCallback> clone() override { 2512 return std::make_unique<VarDeclFilterCCC>(*this); 2513 } 2514 2515 }; 2516 2517 class VarOrFuncDeclFilterCCC final : public CorrectionCandidateCallback { 2518 private: 2519 Sema &SemaRef; 2520 2521 public: 2522 explicit VarOrFuncDeclFilterCCC(Sema &S) : SemaRef(S) {} 2523 bool ValidateCandidate(const TypoCorrection &Candidate) override { 2524 NamedDecl *ND = Candidate.getCorrectionDecl(); 2525 if (ND && ((isa<VarDecl>(ND) && ND->getKind() == Decl::Var) || 2526 isa<FunctionDecl>(ND))) { 2527 return SemaRef.isDeclInScope(ND, SemaRef.getCurLexicalContext(), 2528 SemaRef.getCurScope()); 2529 } 2530 return false; 2531 } 2532 2533 std::unique_ptr<CorrectionCandidateCallback> clone() override { 2534 return std::make_unique<VarOrFuncDeclFilterCCC>(*this); 2535 } 2536 }; 2537 2538 } // namespace 2539 2540 ExprResult Sema::ActOnOpenMPIdExpression(Scope *CurScope, 2541 CXXScopeSpec &ScopeSpec, 2542 const DeclarationNameInfo &Id, 2543 OpenMPDirectiveKind Kind) { 2544 LookupResult Lookup(*this, Id, LookupOrdinaryName); 2545 LookupParsedName(Lookup, CurScope, &ScopeSpec, true); 2546 2547 if (Lookup.isAmbiguous()) 2548 return ExprError(); 2549 2550 VarDecl *VD; 2551 if (!Lookup.isSingleResult()) { 2552 VarDeclFilterCCC CCC(*this); 2553 if (TypoCorrection Corrected = 2554 CorrectTypo(Id, LookupOrdinaryName, CurScope, nullptr, CCC, 2555 CTK_ErrorRecovery)) { 2556 diagnoseTypo(Corrected, 2557 PDiag(Lookup.empty() 2558 ? diag::err_undeclared_var_use_suggest 2559 : diag::err_omp_expected_var_arg_suggest) 2560 << Id.getName()); 2561 VD = Corrected.getCorrectionDeclAs<VarDecl>(); 2562 } else { 2563 Diag(Id.getLoc(), Lookup.empty() ? diag::err_undeclared_var_use 2564 : diag::err_omp_expected_var_arg) 2565 << Id.getName(); 2566 return ExprError(); 2567 } 2568 } else if (!(VD = Lookup.getAsSingle<VarDecl>())) { 2569 Diag(Id.getLoc(), diag::err_omp_expected_var_arg) << Id.getName(); 2570 Diag(Lookup.getFoundDecl()->getLocation(), diag::note_declared_at); 2571 return ExprError(); 2572 } 2573 Lookup.suppressDiagnostics(); 2574 2575 // OpenMP [2.9.2, Syntax, C/C++] 2576 // Variables must be file-scope, namespace-scope, or static block-scope. 2577 if (Kind == OMPD_threadprivate && !VD->hasGlobalStorage()) { 2578 Diag(Id.getLoc(), diag::err_omp_global_var_arg) 2579 << getOpenMPDirectiveName(Kind) << !VD->isStaticLocal(); 2580 bool IsDecl = 2581 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly; 2582 Diag(VD->getLocation(), 2583 IsDecl ? diag::note_previous_decl : diag::note_defined_here) 2584 << VD; 2585 return ExprError(); 2586 } 2587 2588 VarDecl *CanonicalVD = VD->getCanonicalDecl(); 2589 NamedDecl *ND = CanonicalVD; 2590 // OpenMP [2.9.2, Restrictions, C/C++, p.2] 2591 // A threadprivate directive for file-scope variables must appear outside 2592 // any definition or declaration. 2593 if (CanonicalVD->getDeclContext()->isTranslationUnit() && 2594 !getCurLexicalContext()->isTranslationUnit()) { 2595 Diag(Id.getLoc(), diag::err_omp_var_scope) 2596 << getOpenMPDirectiveName(Kind) << VD; 2597 bool IsDecl = 2598 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly; 2599 Diag(VD->getLocation(), 2600 IsDecl ? diag::note_previous_decl : diag::note_defined_here) 2601 << VD; 2602 return ExprError(); 2603 } 2604 // OpenMP [2.9.2, Restrictions, C/C++, p.3] 2605 // A threadprivate directive for static class member variables must appear 2606 // in the class definition, in the same scope in which the member 2607 // variables are declared. 2608 if (CanonicalVD->isStaticDataMember() && 2609 !CanonicalVD->getDeclContext()->Equals(getCurLexicalContext())) { 2610 Diag(Id.getLoc(), diag::err_omp_var_scope) 2611 << getOpenMPDirectiveName(Kind) << VD; 2612 bool IsDecl = 2613 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly; 2614 Diag(VD->getLocation(), 2615 IsDecl ? diag::note_previous_decl : diag::note_defined_here) 2616 << VD; 2617 return ExprError(); 2618 } 2619 // OpenMP [2.9.2, Restrictions, C/C++, p.4] 2620 // A threadprivate directive for namespace-scope variables must appear 2621 // outside any definition or declaration other than the namespace 2622 // definition itself. 2623 if (CanonicalVD->getDeclContext()->isNamespace() && 2624 (!getCurLexicalContext()->isFileContext() || 2625 !getCurLexicalContext()->Encloses(CanonicalVD->getDeclContext()))) { 2626 Diag(Id.getLoc(), diag::err_omp_var_scope) 2627 << getOpenMPDirectiveName(Kind) << VD; 2628 bool IsDecl = 2629 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly; 2630 Diag(VD->getLocation(), 2631 IsDecl ? diag::note_previous_decl : diag::note_defined_here) 2632 << VD; 2633 return ExprError(); 2634 } 2635 // OpenMP [2.9.2, Restrictions, C/C++, p.6] 2636 // A threadprivate directive for static block-scope variables must appear 2637 // in the scope of the variable and not in a nested scope. 2638 if (CanonicalVD->isLocalVarDecl() && CurScope && 2639 !isDeclInScope(ND, getCurLexicalContext(), CurScope)) { 2640 Diag(Id.getLoc(), diag::err_omp_var_scope) 2641 << getOpenMPDirectiveName(Kind) << VD; 2642 bool IsDecl = 2643 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly; 2644 Diag(VD->getLocation(), 2645 IsDecl ? diag::note_previous_decl : diag::note_defined_here) 2646 << VD; 2647 return ExprError(); 2648 } 2649 2650 // OpenMP [2.9.2, Restrictions, C/C++, p.2-6] 2651 // A threadprivate directive must lexically precede all references to any 2652 // of the variables in its list. 2653 if (Kind == OMPD_threadprivate && VD->isUsed() && 2654 !DSAStack->isThreadPrivate(VD)) { 2655 Diag(Id.getLoc(), diag::err_omp_var_used) 2656 << getOpenMPDirectiveName(Kind) << VD; 2657 return ExprError(); 2658 } 2659 2660 QualType ExprType = VD->getType().getNonReferenceType(); 2661 return DeclRefExpr::Create(Context, NestedNameSpecifierLoc(), 2662 SourceLocation(), VD, 2663 /*RefersToEnclosingVariableOrCapture=*/false, 2664 Id.getLoc(), ExprType, VK_LValue); 2665 } 2666 2667 Sema::DeclGroupPtrTy 2668 Sema::ActOnOpenMPThreadprivateDirective(SourceLocation Loc, 2669 ArrayRef<Expr *> VarList) { 2670 if (OMPThreadPrivateDecl *D = CheckOMPThreadPrivateDecl(Loc, VarList)) { 2671 CurContext->addDecl(D); 2672 return DeclGroupPtrTy::make(DeclGroupRef(D)); 2673 } 2674 return nullptr; 2675 } 2676 2677 namespace { 2678 class LocalVarRefChecker final 2679 : public ConstStmtVisitor<LocalVarRefChecker, bool> { 2680 Sema &SemaRef; 2681 2682 public: 2683 bool VisitDeclRefExpr(const DeclRefExpr *E) { 2684 if (const auto *VD = dyn_cast<VarDecl>(E->getDecl())) { 2685 if (VD->hasLocalStorage()) { 2686 SemaRef.Diag(E->getBeginLoc(), 2687 diag::err_omp_local_var_in_threadprivate_init) 2688 << E->getSourceRange(); 2689 SemaRef.Diag(VD->getLocation(), diag::note_defined_here) 2690 << VD << VD->getSourceRange(); 2691 return true; 2692 } 2693 } 2694 return false; 2695 } 2696 bool VisitStmt(const Stmt *S) { 2697 for (const Stmt *Child : S->children()) { 2698 if (Child && Visit(Child)) 2699 return true; 2700 } 2701 return false; 2702 } 2703 explicit LocalVarRefChecker(Sema &SemaRef) : SemaRef(SemaRef) {} 2704 }; 2705 } // namespace 2706 2707 OMPThreadPrivateDecl * 2708 Sema::CheckOMPThreadPrivateDecl(SourceLocation Loc, ArrayRef<Expr *> VarList) { 2709 SmallVector<Expr *, 8> Vars; 2710 for (Expr *RefExpr : VarList) { 2711 auto *DE = cast<DeclRefExpr>(RefExpr); 2712 auto *VD = cast<VarDecl>(DE->getDecl()); 2713 SourceLocation ILoc = DE->getExprLoc(); 2714 2715 // Mark variable as used. 2716 VD->setReferenced(); 2717 VD->markUsed(Context); 2718 2719 QualType QType = VD->getType(); 2720 if (QType->isDependentType() || QType->isInstantiationDependentType()) { 2721 // It will be analyzed later. 2722 Vars.push_back(DE); 2723 continue; 2724 } 2725 2726 // OpenMP [2.9.2, Restrictions, C/C++, p.10] 2727 // A threadprivate variable must not have an incomplete type. 2728 if (RequireCompleteType(ILoc, VD->getType(), 2729 diag::err_omp_threadprivate_incomplete_type)) { 2730 continue; 2731 } 2732 2733 // OpenMP [2.9.2, Restrictions, C/C++, p.10] 2734 // A threadprivate variable must not have a reference type. 2735 if (VD->getType()->isReferenceType()) { 2736 Diag(ILoc, diag::err_omp_ref_type_arg) 2737 << getOpenMPDirectiveName(OMPD_threadprivate) << VD->getType(); 2738 bool IsDecl = 2739 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly; 2740 Diag(VD->getLocation(), 2741 IsDecl ? diag::note_previous_decl : diag::note_defined_here) 2742 << VD; 2743 continue; 2744 } 2745 2746 // Check if this is a TLS variable. If TLS is not being supported, produce 2747 // the corresponding diagnostic. 2748 if ((VD->getTLSKind() != VarDecl::TLS_None && 2749 !(VD->hasAttr<OMPThreadPrivateDeclAttr>() && 2750 getLangOpts().OpenMPUseTLS && 2751 getASTContext().getTargetInfo().isTLSSupported())) || 2752 (VD->getStorageClass() == SC_Register && VD->hasAttr<AsmLabelAttr>() && 2753 !VD->isLocalVarDecl())) { 2754 Diag(ILoc, diag::err_omp_var_thread_local) 2755 << VD << ((VD->getTLSKind() != VarDecl::TLS_None) ? 0 : 1); 2756 bool IsDecl = 2757 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly; 2758 Diag(VD->getLocation(), 2759 IsDecl ? diag::note_previous_decl : diag::note_defined_here) 2760 << VD; 2761 continue; 2762 } 2763 2764 // Check if initial value of threadprivate variable reference variable with 2765 // local storage (it is not supported by runtime). 2766 if (const Expr *Init = VD->getAnyInitializer()) { 2767 LocalVarRefChecker Checker(*this); 2768 if (Checker.Visit(Init)) 2769 continue; 2770 } 2771 2772 Vars.push_back(RefExpr); 2773 DSAStack->addDSA(VD, DE, OMPC_threadprivate); 2774 VD->addAttr(OMPThreadPrivateDeclAttr::CreateImplicit( 2775 Context, SourceRange(Loc, Loc))); 2776 if (ASTMutationListener *ML = Context.getASTMutationListener()) 2777 ML->DeclarationMarkedOpenMPThreadPrivate(VD); 2778 } 2779 OMPThreadPrivateDecl *D = nullptr; 2780 if (!Vars.empty()) { 2781 D = OMPThreadPrivateDecl::Create(Context, getCurLexicalContext(), Loc, 2782 Vars); 2783 D->setAccess(AS_public); 2784 } 2785 return D; 2786 } 2787 2788 static OMPAllocateDeclAttr::AllocatorTypeTy 2789 getAllocatorKind(Sema &S, DSAStackTy *Stack, Expr *Allocator) { 2790 if (!Allocator) 2791 return OMPAllocateDeclAttr::OMPDefaultMemAlloc; 2792 if (Allocator->isTypeDependent() || Allocator->isValueDependent() || 2793 Allocator->isInstantiationDependent() || 2794 Allocator->containsUnexpandedParameterPack()) 2795 return OMPAllocateDeclAttr::OMPUserDefinedMemAlloc; 2796 auto AllocatorKindRes = OMPAllocateDeclAttr::OMPUserDefinedMemAlloc; 2797 const Expr *AE = Allocator->IgnoreParenImpCasts(); 2798 for (int I = OMPAllocateDeclAttr::OMPDefaultMemAlloc; 2799 I < OMPAllocateDeclAttr::OMPUserDefinedMemAlloc; ++I) { 2800 auto AllocatorKind = static_cast<OMPAllocateDeclAttr::AllocatorTypeTy>(I); 2801 const Expr *DefAllocator = Stack->getAllocator(AllocatorKind); 2802 llvm::FoldingSetNodeID AEId, DAEId; 2803 AE->Profile(AEId, S.getASTContext(), /*Canonical=*/true); 2804 DefAllocator->Profile(DAEId, S.getASTContext(), /*Canonical=*/true); 2805 if (AEId == DAEId) { 2806 AllocatorKindRes = AllocatorKind; 2807 break; 2808 } 2809 } 2810 return AllocatorKindRes; 2811 } 2812 2813 static bool checkPreviousOMPAllocateAttribute( 2814 Sema &S, DSAStackTy *Stack, Expr *RefExpr, VarDecl *VD, 2815 OMPAllocateDeclAttr::AllocatorTypeTy AllocatorKind, Expr *Allocator) { 2816 if (!VD->hasAttr<OMPAllocateDeclAttr>()) 2817 return false; 2818 const auto *A = VD->getAttr<OMPAllocateDeclAttr>(); 2819 Expr *PrevAllocator = A->getAllocator(); 2820 OMPAllocateDeclAttr::AllocatorTypeTy PrevAllocatorKind = 2821 getAllocatorKind(S, Stack, PrevAllocator); 2822 bool AllocatorsMatch = AllocatorKind == PrevAllocatorKind; 2823 if (AllocatorsMatch && 2824 AllocatorKind == OMPAllocateDeclAttr::OMPUserDefinedMemAlloc && 2825 Allocator && PrevAllocator) { 2826 const Expr *AE = Allocator->IgnoreParenImpCasts(); 2827 const Expr *PAE = PrevAllocator->IgnoreParenImpCasts(); 2828 llvm::FoldingSetNodeID AEId, PAEId; 2829 AE->Profile(AEId, S.Context, /*Canonical=*/true); 2830 PAE->Profile(PAEId, S.Context, /*Canonical=*/true); 2831 AllocatorsMatch = AEId == PAEId; 2832 } 2833 if (!AllocatorsMatch) { 2834 SmallString<256> AllocatorBuffer; 2835 llvm::raw_svector_ostream AllocatorStream(AllocatorBuffer); 2836 if (Allocator) 2837 Allocator->printPretty(AllocatorStream, nullptr, S.getPrintingPolicy()); 2838 SmallString<256> PrevAllocatorBuffer; 2839 llvm::raw_svector_ostream PrevAllocatorStream(PrevAllocatorBuffer); 2840 if (PrevAllocator) 2841 PrevAllocator->printPretty(PrevAllocatorStream, nullptr, 2842 S.getPrintingPolicy()); 2843 2844 SourceLocation AllocatorLoc = 2845 Allocator ? Allocator->getExprLoc() : RefExpr->getExprLoc(); 2846 SourceRange AllocatorRange = 2847 Allocator ? Allocator->getSourceRange() : RefExpr->getSourceRange(); 2848 SourceLocation PrevAllocatorLoc = 2849 PrevAllocator ? PrevAllocator->getExprLoc() : A->getLocation(); 2850 SourceRange PrevAllocatorRange = 2851 PrevAllocator ? PrevAllocator->getSourceRange() : A->getRange(); 2852 S.Diag(AllocatorLoc, diag::warn_omp_used_different_allocator) 2853 << (Allocator ? 1 : 0) << AllocatorStream.str() 2854 << (PrevAllocator ? 1 : 0) << PrevAllocatorStream.str() 2855 << AllocatorRange; 2856 S.Diag(PrevAllocatorLoc, diag::note_omp_previous_allocator) 2857 << PrevAllocatorRange; 2858 return true; 2859 } 2860 return false; 2861 } 2862 2863 static void 2864 applyOMPAllocateAttribute(Sema &S, VarDecl *VD, 2865 OMPAllocateDeclAttr::AllocatorTypeTy AllocatorKind, 2866 Expr *Allocator, SourceRange SR) { 2867 if (VD->hasAttr<OMPAllocateDeclAttr>()) 2868 return; 2869 if (Allocator && 2870 (Allocator->isTypeDependent() || Allocator->isValueDependent() || 2871 Allocator->isInstantiationDependent() || 2872 Allocator->containsUnexpandedParameterPack())) 2873 return; 2874 auto *A = OMPAllocateDeclAttr::CreateImplicit(S.Context, AllocatorKind, 2875 Allocator, SR); 2876 VD->addAttr(A); 2877 if (ASTMutationListener *ML = S.Context.getASTMutationListener()) 2878 ML->DeclarationMarkedOpenMPAllocate(VD, A); 2879 } 2880 2881 Sema::DeclGroupPtrTy Sema::ActOnOpenMPAllocateDirective( 2882 SourceLocation Loc, ArrayRef<Expr *> VarList, 2883 ArrayRef<OMPClause *> Clauses, DeclContext *Owner) { 2884 assert(Clauses.size() <= 1 && "Expected at most one clause."); 2885 Expr *Allocator = nullptr; 2886 if (Clauses.empty()) { 2887 // OpenMP 5.0, 2.11.3 allocate Directive, Restrictions. 2888 // allocate directives that appear in a target region must specify an 2889 // allocator clause unless a requires directive with the dynamic_allocators 2890 // clause is present in the same compilation unit. 2891 if (LangOpts.OpenMPIsDevice && 2892 !DSAStack->hasRequiresDeclWithClause<OMPDynamicAllocatorsClause>()) 2893 targetDiag(Loc, diag::err_expected_allocator_clause); 2894 } else { 2895 Allocator = cast<OMPAllocatorClause>(Clauses.back())->getAllocator(); 2896 } 2897 OMPAllocateDeclAttr::AllocatorTypeTy AllocatorKind = 2898 getAllocatorKind(*this, DSAStack, Allocator); 2899 SmallVector<Expr *, 8> Vars; 2900 for (Expr *RefExpr : VarList) { 2901 auto *DE = cast<DeclRefExpr>(RefExpr); 2902 auto *VD = cast<VarDecl>(DE->getDecl()); 2903 2904 // Check if this is a TLS variable or global register. 2905 if (VD->getTLSKind() != VarDecl::TLS_None || 2906 VD->hasAttr<OMPThreadPrivateDeclAttr>() || 2907 (VD->getStorageClass() == SC_Register && VD->hasAttr<AsmLabelAttr>() && 2908 !VD->isLocalVarDecl())) 2909 continue; 2910 2911 // If the used several times in the allocate directive, the same allocator 2912 // must be used. 2913 if (checkPreviousOMPAllocateAttribute(*this, DSAStack, RefExpr, VD, 2914 AllocatorKind, Allocator)) 2915 continue; 2916 2917 // OpenMP, 2.11.3 allocate Directive, Restrictions, C / C++ 2918 // If a list item has a static storage type, the allocator expression in the 2919 // allocator clause must be a constant expression that evaluates to one of 2920 // the predefined memory allocator values. 2921 if (Allocator && VD->hasGlobalStorage()) { 2922 if (AllocatorKind == OMPAllocateDeclAttr::OMPUserDefinedMemAlloc) { 2923 Diag(Allocator->getExprLoc(), 2924 diag::err_omp_expected_predefined_allocator) 2925 << Allocator->getSourceRange(); 2926 bool IsDecl = VD->isThisDeclarationADefinition(Context) == 2927 VarDecl::DeclarationOnly; 2928 Diag(VD->getLocation(), 2929 IsDecl ? diag::note_previous_decl : diag::note_defined_here) 2930 << VD; 2931 continue; 2932 } 2933 } 2934 2935 Vars.push_back(RefExpr); 2936 applyOMPAllocateAttribute(*this, VD, AllocatorKind, Allocator, 2937 DE->getSourceRange()); 2938 } 2939 if (Vars.empty()) 2940 return nullptr; 2941 if (!Owner) 2942 Owner = getCurLexicalContext(); 2943 auto *D = OMPAllocateDecl::Create(Context, Owner, Loc, Vars, Clauses); 2944 D->setAccess(AS_public); 2945 Owner->addDecl(D); 2946 return DeclGroupPtrTy::make(DeclGroupRef(D)); 2947 } 2948 2949 Sema::DeclGroupPtrTy 2950 Sema::ActOnOpenMPRequiresDirective(SourceLocation Loc, 2951 ArrayRef<OMPClause *> ClauseList) { 2952 OMPRequiresDecl *D = nullptr; 2953 if (!CurContext->isFileContext()) { 2954 Diag(Loc, diag::err_omp_invalid_scope) << "requires"; 2955 } else { 2956 D = CheckOMPRequiresDecl(Loc, ClauseList); 2957 if (D) { 2958 CurContext->addDecl(D); 2959 DSAStack->addRequiresDecl(D); 2960 } 2961 } 2962 return DeclGroupPtrTy::make(DeclGroupRef(D)); 2963 } 2964 2965 OMPRequiresDecl *Sema::CheckOMPRequiresDecl(SourceLocation Loc, 2966 ArrayRef<OMPClause *> ClauseList) { 2967 /// For target specific clauses, the requires directive cannot be 2968 /// specified after the handling of any of the target regions in the 2969 /// current compilation unit. 2970 ArrayRef<SourceLocation> TargetLocations = 2971 DSAStack->getEncounteredTargetLocs(); 2972 SourceLocation AtomicLoc = DSAStack->getAtomicDirectiveLoc(); 2973 if (!TargetLocations.empty() || !AtomicLoc.isInvalid()) { 2974 for (const OMPClause *CNew : ClauseList) { 2975 // Check if any of the requires clauses affect target regions. 2976 if (isa<OMPUnifiedSharedMemoryClause>(CNew) || 2977 isa<OMPUnifiedAddressClause>(CNew) || 2978 isa<OMPReverseOffloadClause>(CNew) || 2979 isa<OMPDynamicAllocatorsClause>(CNew)) { 2980 Diag(Loc, diag::err_omp_directive_before_requires) 2981 << "target" << getOpenMPClauseName(CNew->getClauseKind()); 2982 for (SourceLocation TargetLoc : TargetLocations) { 2983 Diag(TargetLoc, diag::note_omp_requires_encountered_directive) 2984 << "target"; 2985 } 2986 } else if (!AtomicLoc.isInvalid() && 2987 isa<OMPAtomicDefaultMemOrderClause>(CNew)) { 2988 Diag(Loc, diag::err_omp_directive_before_requires) 2989 << "atomic" << getOpenMPClauseName(CNew->getClauseKind()); 2990 Diag(AtomicLoc, diag::note_omp_requires_encountered_directive) 2991 << "atomic"; 2992 } 2993 } 2994 } 2995 2996 if (!DSAStack->hasDuplicateRequiresClause(ClauseList)) 2997 return OMPRequiresDecl::Create(Context, getCurLexicalContext(), Loc, 2998 ClauseList); 2999 return nullptr; 3000 } 3001 3002 static void reportOriginalDsa(Sema &SemaRef, const DSAStackTy *Stack, 3003 const ValueDecl *D, 3004 const DSAStackTy::DSAVarData &DVar, 3005 bool IsLoopIterVar = false) { 3006 if (DVar.RefExpr) { 3007 SemaRef.Diag(DVar.RefExpr->getExprLoc(), diag::note_omp_explicit_dsa) 3008 << getOpenMPClauseName(DVar.CKind); 3009 return; 3010 } 3011 enum { 3012 PDSA_StaticMemberShared, 3013 PDSA_StaticLocalVarShared, 3014 PDSA_LoopIterVarPrivate, 3015 PDSA_LoopIterVarLinear, 3016 PDSA_LoopIterVarLastprivate, 3017 PDSA_ConstVarShared, 3018 PDSA_GlobalVarShared, 3019 PDSA_TaskVarFirstprivate, 3020 PDSA_LocalVarPrivate, 3021 PDSA_Implicit 3022 } Reason = PDSA_Implicit; 3023 bool ReportHint = false; 3024 auto ReportLoc = D->getLocation(); 3025 auto *VD = dyn_cast<VarDecl>(D); 3026 if (IsLoopIterVar) { 3027 if (DVar.CKind == OMPC_private) 3028 Reason = PDSA_LoopIterVarPrivate; 3029 else if (DVar.CKind == OMPC_lastprivate) 3030 Reason = PDSA_LoopIterVarLastprivate; 3031 else 3032 Reason = PDSA_LoopIterVarLinear; 3033 } else if (isOpenMPTaskingDirective(DVar.DKind) && 3034 DVar.CKind == OMPC_firstprivate) { 3035 Reason = PDSA_TaskVarFirstprivate; 3036 ReportLoc = DVar.ImplicitDSALoc; 3037 } else if (VD && VD->isStaticLocal()) 3038 Reason = PDSA_StaticLocalVarShared; 3039 else if (VD && VD->isStaticDataMember()) 3040 Reason = PDSA_StaticMemberShared; 3041 else if (VD && VD->isFileVarDecl()) 3042 Reason = PDSA_GlobalVarShared; 3043 else if (D->getType().isConstant(SemaRef.getASTContext())) 3044 Reason = PDSA_ConstVarShared; 3045 else if (VD && VD->isLocalVarDecl() && DVar.CKind == OMPC_private) { 3046 ReportHint = true; 3047 Reason = PDSA_LocalVarPrivate; 3048 } 3049 if (Reason != PDSA_Implicit) { 3050 SemaRef.Diag(ReportLoc, diag::note_omp_predetermined_dsa) 3051 << Reason << ReportHint 3052 << getOpenMPDirectiveName(Stack->getCurrentDirective()); 3053 } else if (DVar.ImplicitDSALoc.isValid()) { 3054 SemaRef.Diag(DVar.ImplicitDSALoc, diag::note_omp_implicit_dsa) 3055 << getOpenMPClauseName(DVar.CKind); 3056 } 3057 } 3058 3059 static OpenMPMapClauseKind 3060 getMapClauseKindFromModifier(OpenMPDefaultmapClauseModifier M, 3061 bool IsAggregateOrDeclareTarget) { 3062 OpenMPMapClauseKind Kind = OMPC_MAP_unknown; 3063 switch (M) { 3064 case OMPC_DEFAULTMAP_MODIFIER_alloc: 3065 Kind = OMPC_MAP_alloc; 3066 break; 3067 case OMPC_DEFAULTMAP_MODIFIER_to: 3068 Kind = OMPC_MAP_to; 3069 break; 3070 case OMPC_DEFAULTMAP_MODIFIER_from: 3071 Kind = OMPC_MAP_from; 3072 break; 3073 case OMPC_DEFAULTMAP_MODIFIER_tofrom: 3074 Kind = OMPC_MAP_tofrom; 3075 break; 3076 case OMPC_DEFAULTMAP_MODIFIER_firstprivate: 3077 case OMPC_DEFAULTMAP_MODIFIER_last: 3078 llvm_unreachable("Unexpected defaultmap implicit behavior"); 3079 case OMPC_DEFAULTMAP_MODIFIER_none: 3080 case OMPC_DEFAULTMAP_MODIFIER_default: 3081 case OMPC_DEFAULTMAP_MODIFIER_unknown: 3082 // IsAggregateOrDeclareTarget could be true if: 3083 // 1. the implicit behavior for aggregate is tofrom 3084 // 2. it's a declare target link 3085 if (IsAggregateOrDeclareTarget) { 3086 Kind = OMPC_MAP_tofrom; 3087 break; 3088 } 3089 llvm_unreachable("Unexpected defaultmap implicit behavior"); 3090 } 3091 assert(Kind != OMPC_MAP_unknown && "Expect map kind to be known"); 3092 return Kind; 3093 } 3094 3095 namespace { 3096 class DSAAttrChecker final : public StmtVisitor<DSAAttrChecker, void> { 3097 DSAStackTy *Stack; 3098 Sema &SemaRef; 3099 bool ErrorFound = false; 3100 bool TryCaptureCXXThisMembers = false; 3101 CapturedStmt *CS = nullptr; 3102 llvm::SmallVector<Expr *, 4> ImplicitFirstprivate; 3103 llvm::SmallVector<Expr *, 4> ImplicitMap[OMPC_MAP_delete]; 3104 Sema::VarsWithInheritedDSAType VarsWithInheritedDSA; 3105 llvm::SmallDenseSet<const ValueDecl *, 4> ImplicitDeclarations; 3106 3107 void VisitSubCaptures(OMPExecutableDirective *S) { 3108 // Check implicitly captured variables. 3109 if (!S->hasAssociatedStmt() || !S->getAssociatedStmt()) 3110 return; 3111 visitSubCaptures(S->getInnermostCapturedStmt()); 3112 // Try to capture inner this->member references to generate correct mappings 3113 // and diagnostics. 3114 if (TryCaptureCXXThisMembers || 3115 (isOpenMPTargetExecutionDirective(Stack->getCurrentDirective()) && 3116 llvm::any_of(S->getInnermostCapturedStmt()->captures(), 3117 [](const CapturedStmt::Capture &C) { 3118 return C.capturesThis(); 3119 }))) { 3120 bool SavedTryCaptureCXXThisMembers = TryCaptureCXXThisMembers; 3121 TryCaptureCXXThisMembers = true; 3122 Visit(S->getInnermostCapturedStmt()->getCapturedStmt()); 3123 TryCaptureCXXThisMembers = SavedTryCaptureCXXThisMembers; 3124 } 3125 // In tasks firstprivates are not captured anymore, need to analyze them 3126 // explicitly. 3127 if (isOpenMPTaskingDirective(S->getDirectiveKind()) && 3128 !isOpenMPTaskLoopDirective(S->getDirectiveKind())) { 3129 for (OMPClause *C : S->clauses()) 3130 if (auto *FC = dyn_cast<OMPFirstprivateClause>(C)) { 3131 for (Expr *Ref : FC->varlists()) 3132 Visit(Ref); 3133 } 3134 } 3135 } 3136 3137 public: 3138 void VisitDeclRefExpr(DeclRefExpr *E) { 3139 if (TryCaptureCXXThisMembers || E->isTypeDependent() || 3140 E->isValueDependent() || E->containsUnexpandedParameterPack() || 3141 E->isInstantiationDependent()) 3142 return; 3143 if (auto *VD = dyn_cast<VarDecl>(E->getDecl())) { 3144 // Check the datasharing rules for the expressions in the clauses. 3145 if (!CS) { 3146 if (auto *CED = dyn_cast<OMPCapturedExprDecl>(VD)) 3147 if (!CED->hasAttr<OMPCaptureNoInitAttr>()) { 3148 Visit(CED->getInit()); 3149 return; 3150 } 3151 } else if (VD->isImplicit() || isa<OMPCapturedExprDecl>(VD)) 3152 // Do not analyze internal variables and do not enclose them into 3153 // implicit clauses. 3154 return; 3155 VD = VD->getCanonicalDecl(); 3156 // Skip internally declared variables. 3157 if (VD->hasLocalStorage() && CS && !CS->capturesVariable(VD) && 3158 !Stack->isImplicitTaskFirstprivate(VD)) 3159 return; 3160 3161 DSAStackTy::DSAVarData DVar = Stack->getTopDSA(VD, /*FromParent=*/false); 3162 // Check if the variable has explicit DSA set and stop analysis if it so. 3163 if (DVar.RefExpr || !ImplicitDeclarations.insert(VD).second) 3164 return; 3165 3166 // Skip internally declared static variables. 3167 llvm::Optional<OMPDeclareTargetDeclAttr::MapTypeTy> Res = 3168 OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD); 3169 if (VD->hasGlobalStorage() && CS && !CS->capturesVariable(VD) && 3170 (Stack->hasRequiresDeclWithClause<OMPUnifiedSharedMemoryClause>() || 3171 !Res || *Res != OMPDeclareTargetDeclAttr::MT_Link) && 3172 !Stack->isImplicitTaskFirstprivate(VD)) 3173 return; 3174 3175 SourceLocation ELoc = E->getExprLoc(); 3176 OpenMPDirectiveKind DKind = Stack->getCurrentDirective(); 3177 // The default(none) clause requires that each variable that is referenced 3178 // in the construct, and does not have a predetermined data-sharing 3179 // attribute, must have its data-sharing attribute explicitly determined 3180 // by being listed in a data-sharing attribute clause. 3181 if (DVar.CKind == OMPC_unknown && Stack->getDefaultDSA() == DSA_none && 3182 isImplicitOrExplicitTaskingRegion(DKind) && 3183 VarsWithInheritedDSA.count(VD) == 0) { 3184 VarsWithInheritedDSA[VD] = E; 3185 return; 3186 } 3187 3188 // OpenMP 5.0 [2.19.7.2, defaultmap clause, Description] 3189 // If implicit-behavior is none, each variable referenced in the 3190 // construct that does not have a predetermined data-sharing attribute 3191 // and does not appear in a to or link clause on a declare target 3192 // directive must be listed in a data-mapping attribute clause, a 3193 // data-haring attribute clause (including a data-sharing attribute 3194 // clause on a combined construct where target. is one of the 3195 // constituent constructs), or an is_device_ptr clause. 3196 OpenMPDefaultmapClauseKind ClauseKind = 3197 getVariableCategoryFromDecl(SemaRef.getLangOpts(), VD); 3198 if (SemaRef.getLangOpts().OpenMP >= 50) { 3199 bool IsModifierNone = Stack->getDefaultmapModifier(ClauseKind) == 3200 OMPC_DEFAULTMAP_MODIFIER_none; 3201 if (DVar.CKind == OMPC_unknown && IsModifierNone && 3202 VarsWithInheritedDSA.count(VD) == 0 && !Res) { 3203 // Only check for data-mapping attribute and is_device_ptr here 3204 // since we have already make sure that the declaration does not 3205 // have a data-sharing attribute above 3206 if (!Stack->checkMappableExprComponentListsForDecl( 3207 VD, /*CurrentRegionOnly=*/true, 3208 [VD](OMPClauseMappableExprCommon::MappableExprComponentListRef 3209 MapExprComponents, 3210 OpenMPClauseKind) { 3211 auto MI = MapExprComponents.rbegin(); 3212 auto ME = MapExprComponents.rend(); 3213 return MI != ME && MI->getAssociatedDeclaration() == VD; 3214 })) { 3215 VarsWithInheritedDSA[VD] = E; 3216 return; 3217 } 3218 } 3219 } 3220 3221 if (isOpenMPTargetExecutionDirective(DKind) && 3222 !Stack->isLoopControlVariable(VD).first) { 3223 if (!Stack->checkMappableExprComponentListsForDecl( 3224 VD, /*CurrentRegionOnly=*/true, 3225 [](OMPClauseMappableExprCommon::MappableExprComponentListRef 3226 StackComponents, 3227 OpenMPClauseKind) { 3228 // Variable is used if it has been marked as an array, array 3229 // section, array shaping or the variable iself. 3230 return StackComponents.size() == 1 || 3231 std::all_of( 3232 std::next(StackComponents.rbegin()), 3233 StackComponents.rend(), 3234 [](const OMPClauseMappableExprCommon:: 3235 MappableComponent &MC) { 3236 return MC.getAssociatedDeclaration() == 3237 nullptr && 3238 (isa<OMPArraySectionExpr>( 3239 MC.getAssociatedExpression()) || 3240 isa<OMPArrayShapingExpr>( 3241 MC.getAssociatedExpression()) || 3242 isa<ArraySubscriptExpr>( 3243 MC.getAssociatedExpression())); 3244 }); 3245 })) { 3246 bool IsFirstprivate = false; 3247 // By default lambdas are captured as firstprivates. 3248 if (const auto *RD = 3249 VD->getType().getNonReferenceType()->getAsCXXRecordDecl()) 3250 IsFirstprivate = RD->isLambda(); 3251 IsFirstprivate = 3252 IsFirstprivate || (Stack->mustBeFirstprivate(ClauseKind) && !Res); 3253 if (IsFirstprivate) { 3254 ImplicitFirstprivate.emplace_back(E); 3255 } else { 3256 OpenMPDefaultmapClauseModifier M = 3257 Stack->getDefaultmapModifier(ClauseKind); 3258 OpenMPMapClauseKind Kind = getMapClauseKindFromModifier( 3259 M, ClauseKind == OMPC_DEFAULTMAP_aggregate || Res); 3260 ImplicitMap[Kind].emplace_back(E); 3261 } 3262 return; 3263 } 3264 } 3265 3266 // OpenMP [2.9.3.6, Restrictions, p.2] 3267 // A list item that appears in a reduction clause of the innermost 3268 // enclosing worksharing or parallel construct may not be accessed in an 3269 // explicit task. 3270 DVar = Stack->hasInnermostDSA( 3271 VD, [](OpenMPClauseKind C) { return C == OMPC_reduction; }, 3272 [](OpenMPDirectiveKind K) { 3273 return isOpenMPParallelDirective(K) || 3274 isOpenMPWorksharingDirective(K) || isOpenMPTeamsDirective(K); 3275 }, 3276 /*FromParent=*/true); 3277 if (isOpenMPTaskingDirective(DKind) && DVar.CKind == OMPC_reduction) { 3278 ErrorFound = true; 3279 SemaRef.Diag(ELoc, diag::err_omp_reduction_in_task); 3280 reportOriginalDsa(SemaRef, Stack, VD, DVar); 3281 return; 3282 } 3283 3284 // Define implicit data-sharing attributes for task. 3285 DVar = Stack->getImplicitDSA(VD, /*FromParent=*/false); 3286 if (isOpenMPTaskingDirective(DKind) && DVar.CKind != OMPC_shared && 3287 !Stack->isLoopControlVariable(VD).first) { 3288 ImplicitFirstprivate.push_back(E); 3289 return; 3290 } 3291 3292 // Store implicitly used globals with declare target link for parent 3293 // target. 3294 if (!isOpenMPTargetExecutionDirective(DKind) && Res && 3295 *Res == OMPDeclareTargetDeclAttr::MT_Link) { 3296 Stack->addToParentTargetRegionLinkGlobals(E); 3297 return; 3298 } 3299 } 3300 } 3301 void VisitMemberExpr(MemberExpr *E) { 3302 if (E->isTypeDependent() || E->isValueDependent() || 3303 E->containsUnexpandedParameterPack() || E->isInstantiationDependent()) 3304 return; 3305 auto *FD = dyn_cast<FieldDecl>(E->getMemberDecl()); 3306 OpenMPDirectiveKind DKind = Stack->getCurrentDirective(); 3307 if (auto *TE = dyn_cast<CXXThisExpr>(E->getBase()->IgnoreParenCasts())) { 3308 if (!FD) 3309 return; 3310 DSAStackTy::DSAVarData DVar = Stack->getTopDSA(FD, /*FromParent=*/false); 3311 // Check if the variable has explicit DSA set and stop analysis if it 3312 // so. 3313 if (DVar.RefExpr || !ImplicitDeclarations.insert(FD).second) 3314 return; 3315 3316 if (isOpenMPTargetExecutionDirective(DKind) && 3317 !Stack->isLoopControlVariable(FD).first && 3318 !Stack->checkMappableExprComponentListsForDecl( 3319 FD, /*CurrentRegionOnly=*/true, 3320 [](OMPClauseMappableExprCommon::MappableExprComponentListRef 3321 StackComponents, 3322 OpenMPClauseKind) { 3323 return isa<CXXThisExpr>( 3324 cast<MemberExpr>( 3325 StackComponents.back().getAssociatedExpression()) 3326 ->getBase() 3327 ->IgnoreParens()); 3328 })) { 3329 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C/C++, p.3] 3330 // A bit-field cannot appear in a map clause. 3331 // 3332 if (FD->isBitField()) 3333 return; 3334 3335 // Check to see if the member expression is referencing a class that 3336 // has already been explicitly mapped 3337 if (Stack->isClassPreviouslyMapped(TE->getType())) 3338 return; 3339 3340 OpenMPDefaultmapClauseModifier Modifier = 3341 Stack->getDefaultmapModifier(OMPC_DEFAULTMAP_aggregate); 3342 OpenMPMapClauseKind Kind = getMapClauseKindFromModifier( 3343 Modifier, /*IsAggregateOrDeclareTarget*/ true); 3344 ImplicitMap[Kind].emplace_back(E); 3345 return; 3346 } 3347 3348 SourceLocation ELoc = E->getExprLoc(); 3349 // OpenMP [2.9.3.6, Restrictions, p.2] 3350 // A list item that appears in a reduction clause of the innermost 3351 // enclosing worksharing or parallel construct may not be accessed in 3352 // an explicit task. 3353 DVar = Stack->hasInnermostDSA( 3354 FD, [](OpenMPClauseKind C) { return C == OMPC_reduction; }, 3355 [](OpenMPDirectiveKind K) { 3356 return isOpenMPParallelDirective(K) || 3357 isOpenMPWorksharingDirective(K) || isOpenMPTeamsDirective(K); 3358 }, 3359 /*FromParent=*/true); 3360 if (isOpenMPTaskingDirective(DKind) && DVar.CKind == OMPC_reduction) { 3361 ErrorFound = true; 3362 SemaRef.Diag(ELoc, diag::err_omp_reduction_in_task); 3363 reportOriginalDsa(SemaRef, Stack, FD, DVar); 3364 return; 3365 } 3366 3367 // Define implicit data-sharing attributes for task. 3368 DVar = Stack->getImplicitDSA(FD, /*FromParent=*/false); 3369 if (isOpenMPTaskingDirective(DKind) && DVar.CKind != OMPC_shared && 3370 !Stack->isLoopControlVariable(FD).first) { 3371 // Check if there is a captured expression for the current field in the 3372 // region. Do not mark it as firstprivate unless there is no captured 3373 // expression. 3374 // TODO: try to make it firstprivate. 3375 if (DVar.CKind != OMPC_unknown) 3376 ImplicitFirstprivate.push_back(E); 3377 } 3378 return; 3379 } 3380 if (isOpenMPTargetExecutionDirective(DKind)) { 3381 OMPClauseMappableExprCommon::MappableExprComponentList CurComponents; 3382 if (!checkMapClauseExpressionBase(SemaRef, E, CurComponents, OMPC_map, 3383 /*NoDiagnose=*/true)) 3384 return; 3385 const auto *VD = cast<ValueDecl>( 3386 CurComponents.back().getAssociatedDeclaration()->getCanonicalDecl()); 3387 if (!Stack->checkMappableExprComponentListsForDecl( 3388 VD, /*CurrentRegionOnly=*/true, 3389 [&CurComponents]( 3390 OMPClauseMappableExprCommon::MappableExprComponentListRef 3391 StackComponents, 3392 OpenMPClauseKind) { 3393 auto CCI = CurComponents.rbegin(); 3394 auto CCE = CurComponents.rend(); 3395 for (const auto &SC : llvm::reverse(StackComponents)) { 3396 // Do both expressions have the same kind? 3397 if (CCI->getAssociatedExpression()->getStmtClass() != 3398 SC.getAssociatedExpression()->getStmtClass()) 3399 if (!((isa<OMPArraySectionExpr>( 3400 SC.getAssociatedExpression()) || 3401 isa<OMPArrayShapingExpr>( 3402 SC.getAssociatedExpression())) && 3403 isa<ArraySubscriptExpr>( 3404 CCI->getAssociatedExpression()))) 3405 return false; 3406 3407 const Decl *CCD = CCI->getAssociatedDeclaration(); 3408 const Decl *SCD = SC.getAssociatedDeclaration(); 3409 CCD = CCD ? CCD->getCanonicalDecl() : nullptr; 3410 SCD = SCD ? SCD->getCanonicalDecl() : nullptr; 3411 if (SCD != CCD) 3412 return false; 3413 std::advance(CCI, 1); 3414 if (CCI == CCE) 3415 break; 3416 } 3417 return true; 3418 })) { 3419 Visit(E->getBase()); 3420 } 3421 } else if (!TryCaptureCXXThisMembers) { 3422 Visit(E->getBase()); 3423 } 3424 } 3425 void VisitOMPExecutableDirective(OMPExecutableDirective *S) { 3426 for (OMPClause *C : S->clauses()) { 3427 // Skip analysis of arguments of implicitly defined firstprivate clause 3428 // for task|target directives. 3429 // Skip analysis of arguments of implicitly defined map clause for target 3430 // directives. 3431 if (C && !((isa<OMPFirstprivateClause>(C) || isa<OMPMapClause>(C)) && 3432 C->isImplicit())) { 3433 for (Stmt *CC : C->children()) { 3434 if (CC) 3435 Visit(CC); 3436 } 3437 } 3438 } 3439 // Check implicitly captured variables. 3440 VisitSubCaptures(S); 3441 } 3442 void VisitStmt(Stmt *S) { 3443 for (Stmt *C : S->children()) { 3444 if (C) { 3445 // Check implicitly captured variables in the task-based directives to 3446 // check if they must be firstprivatized. 3447 Visit(C); 3448 } 3449 } 3450 } 3451 3452 void visitSubCaptures(CapturedStmt *S) { 3453 for (const CapturedStmt::Capture &Cap : S->captures()) { 3454 if (!Cap.capturesVariable() && !Cap.capturesVariableByCopy()) 3455 continue; 3456 VarDecl *VD = Cap.getCapturedVar(); 3457 // Do not try to map the variable if it or its sub-component was mapped 3458 // already. 3459 if (isOpenMPTargetExecutionDirective(Stack->getCurrentDirective()) && 3460 Stack->checkMappableExprComponentListsForDecl( 3461 VD, /*CurrentRegionOnly=*/true, 3462 [](OMPClauseMappableExprCommon::MappableExprComponentListRef, 3463 OpenMPClauseKind) { return true; })) 3464 continue; 3465 DeclRefExpr *DRE = buildDeclRefExpr( 3466 SemaRef, VD, VD->getType().getNonLValueExprType(SemaRef.Context), 3467 Cap.getLocation(), /*RefersToCapture=*/true); 3468 Visit(DRE); 3469 } 3470 } 3471 bool isErrorFound() const { return ErrorFound; } 3472 ArrayRef<Expr *> getImplicitFirstprivate() const { 3473 return ImplicitFirstprivate; 3474 } 3475 ArrayRef<Expr *> getImplicitMap(OpenMPDefaultmapClauseKind Kind) const { 3476 return ImplicitMap[Kind]; 3477 } 3478 const Sema::VarsWithInheritedDSAType &getVarsWithInheritedDSA() const { 3479 return VarsWithInheritedDSA; 3480 } 3481 3482 DSAAttrChecker(DSAStackTy *S, Sema &SemaRef, CapturedStmt *CS) 3483 : Stack(S), SemaRef(SemaRef), ErrorFound(false), CS(CS) { 3484 // Process declare target link variables for the target directives. 3485 if (isOpenMPTargetExecutionDirective(S->getCurrentDirective())) { 3486 for (DeclRefExpr *E : Stack->getLinkGlobals()) 3487 Visit(E); 3488 } 3489 } 3490 }; 3491 } // namespace 3492 3493 void Sema::ActOnOpenMPRegionStart(OpenMPDirectiveKind DKind, Scope *CurScope) { 3494 switch (DKind) { 3495 case OMPD_parallel: 3496 case OMPD_parallel_for: 3497 case OMPD_parallel_for_simd: 3498 case OMPD_parallel_sections: 3499 case OMPD_parallel_master: 3500 case OMPD_teams: 3501 case OMPD_teams_distribute: 3502 case OMPD_teams_distribute_simd: { 3503 QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1).withConst(); 3504 QualType KmpInt32PtrTy = 3505 Context.getPointerType(KmpInt32Ty).withConst().withRestrict(); 3506 Sema::CapturedParamNameType Params[] = { 3507 std::make_pair(".global_tid.", KmpInt32PtrTy), 3508 std::make_pair(".bound_tid.", KmpInt32PtrTy), 3509 std::make_pair(StringRef(), QualType()) // __context with shared vars 3510 }; 3511 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP, 3512 Params); 3513 break; 3514 } 3515 case OMPD_target_teams: 3516 case OMPD_target_parallel: 3517 case OMPD_target_parallel_for: 3518 case OMPD_target_parallel_for_simd: 3519 case OMPD_target_teams_distribute: 3520 case OMPD_target_teams_distribute_simd: { 3521 QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1).withConst(); 3522 QualType VoidPtrTy = Context.VoidPtrTy.withConst().withRestrict(); 3523 QualType KmpInt32PtrTy = 3524 Context.getPointerType(KmpInt32Ty).withConst().withRestrict(); 3525 QualType Args[] = {VoidPtrTy}; 3526 FunctionProtoType::ExtProtoInfo EPI; 3527 EPI.Variadic = true; 3528 QualType CopyFnType = Context.getFunctionType(Context.VoidTy, Args, EPI); 3529 Sema::CapturedParamNameType Params[] = { 3530 std::make_pair(".global_tid.", KmpInt32Ty), 3531 std::make_pair(".part_id.", KmpInt32PtrTy), 3532 std::make_pair(".privates.", VoidPtrTy), 3533 std::make_pair( 3534 ".copy_fn.", 3535 Context.getPointerType(CopyFnType).withConst().withRestrict()), 3536 std::make_pair(".task_t.", Context.VoidPtrTy.withConst()), 3537 std::make_pair(StringRef(), QualType()) // __context with shared vars 3538 }; 3539 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP, 3540 Params, /*OpenMPCaptureLevel=*/0); 3541 // Mark this captured region as inlined, because we don't use outlined 3542 // function directly. 3543 getCurCapturedRegion()->TheCapturedDecl->addAttr( 3544 AlwaysInlineAttr::CreateImplicit( 3545 Context, {}, AttributeCommonInfo::AS_Keyword, 3546 AlwaysInlineAttr::Keyword_forceinline)); 3547 Sema::CapturedParamNameType ParamsTarget[] = { 3548 std::make_pair(StringRef(), QualType()) // __context with shared vars 3549 }; 3550 // Start a captured region for 'target' with no implicit parameters. 3551 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP, 3552 ParamsTarget, /*OpenMPCaptureLevel=*/1); 3553 Sema::CapturedParamNameType ParamsTeamsOrParallel[] = { 3554 std::make_pair(".global_tid.", KmpInt32PtrTy), 3555 std::make_pair(".bound_tid.", KmpInt32PtrTy), 3556 std::make_pair(StringRef(), QualType()) // __context with shared vars 3557 }; 3558 // Start a captured region for 'teams' or 'parallel'. Both regions have 3559 // the same implicit parameters. 3560 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP, 3561 ParamsTeamsOrParallel, /*OpenMPCaptureLevel=*/2); 3562 break; 3563 } 3564 case OMPD_target: 3565 case OMPD_target_simd: { 3566 QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1).withConst(); 3567 QualType VoidPtrTy = Context.VoidPtrTy.withConst().withRestrict(); 3568 QualType KmpInt32PtrTy = 3569 Context.getPointerType(KmpInt32Ty).withConst().withRestrict(); 3570 QualType Args[] = {VoidPtrTy}; 3571 FunctionProtoType::ExtProtoInfo EPI; 3572 EPI.Variadic = true; 3573 QualType CopyFnType = Context.getFunctionType(Context.VoidTy, Args, EPI); 3574 Sema::CapturedParamNameType Params[] = { 3575 std::make_pair(".global_tid.", KmpInt32Ty), 3576 std::make_pair(".part_id.", KmpInt32PtrTy), 3577 std::make_pair(".privates.", VoidPtrTy), 3578 std::make_pair( 3579 ".copy_fn.", 3580 Context.getPointerType(CopyFnType).withConst().withRestrict()), 3581 std::make_pair(".task_t.", Context.VoidPtrTy.withConst()), 3582 std::make_pair(StringRef(), QualType()) // __context with shared vars 3583 }; 3584 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP, 3585 Params, /*OpenMPCaptureLevel=*/0); 3586 // Mark this captured region as inlined, because we don't use outlined 3587 // function directly. 3588 getCurCapturedRegion()->TheCapturedDecl->addAttr( 3589 AlwaysInlineAttr::CreateImplicit( 3590 Context, {}, AttributeCommonInfo::AS_Keyword, 3591 AlwaysInlineAttr::Keyword_forceinline)); 3592 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP, 3593 std::make_pair(StringRef(), QualType()), 3594 /*OpenMPCaptureLevel=*/1); 3595 break; 3596 } 3597 case OMPD_simd: 3598 case OMPD_for: 3599 case OMPD_for_simd: 3600 case OMPD_sections: 3601 case OMPD_section: 3602 case OMPD_single: 3603 case OMPD_master: 3604 case OMPD_critical: 3605 case OMPD_taskgroup: 3606 case OMPD_distribute: 3607 case OMPD_distribute_simd: 3608 case OMPD_ordered: 3609 case OMPD_atomic: 3610 case OMPD_target_data: { 3611 Sema::CapturedParamNameType Params[] = { 3612 std::make_pair(StringRef(), QualType()) // __context with shared vars 3613 }; 3614 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP, 3615 Params); 3616 break; 3617 } 3618 case OMPD_task: { 3619 QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1).withConst(); 3620 QualType VoidPtrTy = Context.VoidPtrTy.withConst().withRestrict(); 3621 QualType KmpInt32PtrTy = 3622 Context.getPointerType(KmpInt32Ty).withConst().withRestrict(); 3623 QualType Args[] = {VoidPtrTy}; 3624 FunctionProtoType::ExtProtoInfo EPI; 3625 EPI.Variadic = true; 3626 QualType CopyFnType = Context.getFunctionType(Context.VoidTy, Args, EPI); 3627 Sema::CapturedParamNameType Params[] = { 3628 std::make_pair(".global_tid.", KmpInt32Ty), 3629 std::make_pair(".part_id.", KmpInt32PtrTy), 3630 std::make_pair(".privates.", VoidPtrTy), 3631 std::make_pair( 3632 ".copy_fn.", 3633 Context.getPointerType(CopyFnType).withConst().withRestrict()), 3634 std::make_pair(".task_t.", Context.VoidPtrTy.withConst()), 3635 std::make_pair(StringRef(), QualType()) // __context with shared vars 3636 }; 3637 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP, 3638 Params); 3639 // Mark this captured region as inlined, because we don't use outlined 3640 // function directly. 3641 getCurCapturedRegion()->TheCapturedDecl->addAttr( 3642 AlwaysInlineAttr::CreateImplicit( 3643 Context, {}, AttributeCommonInfo::AS_Keyword, 3644 AlwaysInlineAttr::Keyword_forceinline)); 3645 break; 3646 } 3647 case OMPD_taskloop: 3648 case OMPD_taskloop_simd: 3649 case OMPD_master_taskloop: 3650 case OMPD_master_taskloop_simd: { 3651 QualType KmpInt32Ty = 3652 Context.getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/1) 3653 .withConst(); 3654 QualType KmpUInt64Ty = 3655 Context.getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/0) 3656 .withConst(); 3657 QualType KmpInt64Ty = 3658 Context.getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/1) 3659 .withConst(); 3660 QualType VoidPtrTy = Context.VoidPtrTy.withConst().withRestrict(); 3661 QualType KmpInt32PtrTy = 3662 Context.getPointerType(KmpInt32Ty).withConst().withRestrict(); 3663 QualType Args[] = {VoidPtrTy}; 3664 FunctionProtoType::ExtProtoInfo EPI; 3665 EPI.Variadic = true; 3666 QualType CopyFnType = Context.getFunctionType(Context.VoidTy, Args, EPI); 3667 Sema::CapturedParamNameType Params[] = { 3668 std::make_pair(".global_tid.", KmpInt32Ty), 3669 std::make_pair(".part_id.", KmpInt32PtrTy), 3670 std::make_pair(".privates.", VoidPtrTy), 3671 std::make_pair( 3672 ".copy_fn.", 3673 Context.getPointerType(CopyFnType).withConst().withRestrict()), 3674 std::make_pair(".task_t.", Context.VoidPtrTy.withConst()), 3675 std::make_pair(".lb.", KmpUInt64Ty), 3676 std::make_pair(".ub.", KmpUInt64Ty), 3677 std::make_pair(".st.", KmpInt64Ty), 3678 std::make_pair(".liter.", KmpInt32Ty), 3679 std::make_pair(".reductions.", VoidPtrTy), 3680 std::make_pair(StringRef(), QualType()) // __context with shared vars 3681 }; 3682 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP, 3683 Params); 3684 // Mark this captured region as inlined, because we don't use outlined 3685 // function directly. 3686 getCurCapturedRegion()->TheCapturedDecl->addAttr( 3687 AlwaysInlineAttr::CreateImplicit( 3688 Context, {}, AttributeCommonInfo::AS_Keyword, 3689 AlwaysInlineAttr::Keyword_forceinline)); 3690 break; 3691 } 3692 case OMPD_parallel_master_taskloop: 3693 case OMPD_parallel_master_taskloop_simd: { 3694 QualType KmpInt32Ty = 3695 Context.getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/1) 3696 .withConst(); 3697 QualType KmpUInt64Ty = 3698 Context.getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/0) 3699 .withConst(); 3700 QualType KmpInt64Ty = 3701 Context.getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/1) 3702 .withConst(); 3703 QualType VoidPtrTy = Context.VoidPtrTy.withConst().withRestrict(); 3704 QualType KmpInt32PtrTy = 3705 Context.getPointerType(KmpInt32Ty).withConst().withRestrict(); 3706 Sema::CapturedParamNameType ParamsParallel[] = { 3707 std::make_pair(".global_tid.", KmpInt32PtrTy), 3708 std::make_pair(".bound_tid.", KmpInt32PtrTy), 3709 std::make_pair(StringRef(), QualType()) // __context with shared vars 3710 }; 3711 // Start a captured region for 'parallel'. 3712 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP, 3713 ParamsParallel, /*OpenMPCaptureLevel=*/0); 3714 QualType Args[] = {VoidPtrTy}; 3715 FunctionProtoType::ExtProtoInfo EPI; 3716 EPI.Variadic = true; 3717 QualType CopyFnType = Context.getFunctionType(Context.VoidTy, Args, EPI); 3718 Sema::CapturedParamNameType Params[] = { 3719 std::make_pair(".global_tid.", KmpInt32Ty), 3720 std::make_pair(".part_id.", KmpInt32PtrTy), 3721 std::make_pair(".privates.", VoidPtrTy), 3722 std::make_pair( 3723 ".copy_fn.", 3724 Context.getPointerType(CopyFnType).withConst().withRestrict()), 3725 std::make_pair(".task_t.", Context.VoidPtrTy.withConst()), 3726 std::make_pair(".lb.", KmpUInt64Ty), 3727 std::make_pair(".ub.", KmpUInt64Ty), 3728 std::make_pair(".st.", KmpInt64Ty), 3729 std::make_pair(".liter.", KmpInt32Ty), 3730 std::make_pair(".reductions.", VoidPtrTy), 3731 std::make_pair(StringRef(), QualType()) // __context with shared vars 3732 }; 3733 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP, 3734 Params, /*OpenMPCaptureLevel=*/1); 3735 // Mark this captured region as inlined, because we don't use outlined 3736 // function directly. 3737 getCurCapturedRegion()->TheCapturedDecl->addAttr( 3738 AlwaysInlineAttr::CreateImplicit( 3739 Context, {}, AttributeCommonInfo::AS_Keyword, 3740 AlwaysInlineAttr::Keyword_forceinline)); 3741 break; 3742 } 3743 case OMPD_distribute_parallel_for_simd: 3744 case OMPD_distribute_parallel_for: { 3745 QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1).withConst(); 3746 QualType KmpInt32PtrTy = 3747 Context.getPointerType(KmpInt32Ty).withConst().withRestrict(); 3748 Sema::CapturedParamNameType Params[] = { 3749 std::make_pair(".global_tid.", KmpInt32PtrTy), 3750 std::make_pair(".bound_tid.", KmpInt32PtrTy), 3751 std::make_pair(".previous.lb.", Context.getSizeType().withConst()), 3752 std::make_pair(".previous.ub.", Context.getSizeType().withConst()), 3753 std::make_pair(StringRef(), QualType()) // __context with shared vars 3754 }; 3755 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP, 3756 Params); 3757 break; 3758 } 3759 case OMPD_target_teams_distribute_parallel_for: 3760 case OMPD_target_teams_distribute_parallel_for_simd: { 3761 QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1).withConst(); 3762 QualType KmpInt32PtrTy = 3763 Context.getPointerType(KmpInt32Ty).withConst().withRestrict(); 3764 QualType VoidPtrTy = Context.VoidPtrTy.withConst().withRestrict(); 3765 3766 QualType Args[] = {VoidPtrTy}; 3767 FunctionProtoType::ExtProtoInfo EPI; 3768 EPI.Variadic = true; 3769 QualType CopyFnType = Context.getFunctionType(Context.VoidTy, Args, EPI); 3770 Sema::CapturedParamNameType Params[] = { 3771 std::make_pair(".global_tid.", KmpInt32Ty), 3772 std::make_pair(".part_id.", KmpInt32PtrTy), 3773 std::make_pair(".privates.", VoidPtrTy), 3774 std::make_pair( 3775 ".copy_fn.", 3776 Context.getPointerType(CopyFnType).withConst().withRestrict()), 3777 std::make_pair(".task_t.", Context.VoidPtrTy.withConst()), 3778 std::make_pair(StringRef(), QualType()) // __context with shared vars 3779 }; 3780 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP, 3781 Params, /*OpenMPCaptureLevel=*/0); 3782 // Mark this captured region as inlined, because we don't use outlined 3783 // function directly. 3784 getCurCapturedRegion()->TheCapturedDecl->addAttr( 3785 AlwaysInlineAttr::CreateImplicit( 3786 Context, {}, AttributeCommonInfo::AS_Keyword, 3787 AlwaysInlineAttr::Keyword_forceinline)); 3788 Sema::CapturedParamNameType ParamsTarget[] = { 3789 std::make_pair(StringRef(), QualType()) // __context with shared vars 3790 }; 3791 // Start a captured region for 'target' with no implicit parameters. 3792 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP, 3793 ParamsTarget, /*OpenMPCaptureLevel=*/1); 3794 3795 Sema::CapturedParamNameType ParamsTeams[] = { 3796 std::make_pair(".global_tid.", KmpInt32PtrTy), 3797 std::make_pair(".bound_tid.", KmpInt32PtrTy), 3798 std::make_pair(StringRef(), QualType()) // __context with shared vars 3799 }; 3800 // Start a captured region for 'target' with no implicit parameters. 3801 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP, 3802 ParamsTeams, /*OpenMPCaptureLevel=*/2); 3803 3804 Sema::CapturedParamNameType ParamsParallel[] = { 3805 std::make_pair(".global_tid.", KmpInt32PtrTy), 3806 std::make_pair(".bound_tid.", KmpInt32PtrTy), 3807 std::make_pair(".previous.lb.", Context.getSizeType().withConst()), 3808 std::make_pair(".previous.ub.", Context.getSizeType().withConst()), 3809 std::make_pair(StringRef(), QualType()) // __context with shared vars 3810 }; 3811 // Start a captured region for 'teams' or 'parallel'. Both regions have 3812 // the same implicit parameters. 3813 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP, 3814 ParamsParallel, /*OpenMPCaptureLevel=*/3); 3815 break; 3816 } 3817 3818 case OMPD_teams_distribute_parallel_for: 3819 case OMPD_teams_distribute_parallel_for_simd: { 3820 QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1).withConst(); 3821 QualType KmpInt32PtrTy = 3822 Context.getPointerType(KmpInt32Ty).withConst().withRestrict(); 3823 3824 Sema::CapturedParamNameType ParamsTeams[] = { 3825 std::make_pair(".global_tid.", KmpInt32PtrTy), 3826 std::make_pair(".bound_tid.", KmpInt32PtrTy), 3827 std::make_pair(StringRef(), QualType()) // __context with shared vars 3828 }; 3829 // Start a captured region for 'target' with no implicit parameters. 3830 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP, 3831 ParamsTeams, /*OpenMPCaptureLevel=*/0); 3832 3833 Sema::CapturedParamNameType ParamsParallel[] = { 3834 std::make_pair(".global_tid.", KmpInt32PtrTy), 3835 std::make_pair(".bound_tid.", KmpInt32PtrTy), 3836 std::make_pair(".previous.lb.", Context.getSizeType().withConst()), 3837 std::make_pair(".previous.ub.", Context.getSizeType().withConst()), 3838 std::make_pair(StringRef(), QualType()) // __context with shared vars 3839 }; 3840 // Start a captured region for 'teams' or 'parallel'. Both regions have 3841 // the same implicit parameters. 3842 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP, 3843 ParamsParallel, /*OpenMPCaptureLevel=*/1); 3844 break; 3845 } 3846 case OMPD_target_update: 3847 case OMPD_target_enter_data: 3848 case OMPD_target_exit_data: { 3849 QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1).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(StringRef(), QualType()) // __context with shared vars 3866 }; 3867 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP, 3868 Params); 3869 // Mark this captured region as inlined, because we don't use outlined 3870 // function directly. 3871 getCurCapturedRegion()->TheCapturedDecl->addAttr( 3872 AlwaysInlineAttr::CreateImplicit( 3873 Context, {}, AttributeCommonInfo::AS_Keyword, 3874 AlwaysInlineAttr::Keyword_forceinline)); 3875 break; 3876 } 3877 case OMPD_threadprivate: 3878 case OMPD_allocate: 3879 case OMPD_taskyield: 3880 case OMPD_barrier: 3881 case OMPD_taskwait: 3882 case OMPD_cancellation_point: 3883 case OMPD_cancel: 3884 case OMPD_flush: 3885 case OMPD_depobj: 3886 case OMPD_scan: 3887 case OMPD_declare_reduction: 3888 case OMPD_declare_mapper: 3889 case OMPD_declare_simd: 3890 case OMPD_declare_target: 3891 case OMPD_end_declare_target: 3892 case OMPD_requires: 3893 case OMPD_declare_variant: 3894 case OMPD_begin_declare_variant: 3895 case OMPD_end_declare_variant: 3896 llvm_unreachable("OpenMP Directive is not allowed"); 3897 case OMPD_unknown: 3898 llvm_unreachable("Unknown OpenMP directive"); 3899 } 3900 } 3901 3902 int Sema::getNumberOfConstructScopes(unsigned Level) const { 3903 return getOpenMPCaptureLevels(DSAStack->getDirective(Level)); 3904 } 3905 3906 int Sema::getOpenMPCaptureLevels(OpenMPDirectiveKind DKind) { 3907 SmallVector<OpenMPDirectiveKind, 4> CaptureRegions; 3908 getOpenMPCaptureRegions(CaptureRegions, DKind); 3909 return CaptureRegions.size(); 3910 } 3911 3912 static OMPCapturedExprDecl *buildCaptureDecl(Sema &S, IdentifierInfo *Id, 3913 Expr *CaptureExpr, bool WithInit, 3914 bool AsExpression) { 3915 assert(CaptureExpr); 3916 ASTContext &C = S.getASTContext(); 3917 Expr *Init = AsExpression ? CaptureExpr : CaptureExpr->IgnoreImpCasts(); 3918 QualType Ty = Init->getType(); 3919 if (CaptureExpr->getObjectKind() == OK_Ordinary && CaptureExpr->isGLValue()) { 3920 if (S.getLangOpts().CPlusPlus) { 3921 Ty = C.getLValueReferenceType(Ty); 3922 } else { 3923 Ty = C.getPointerType(Ty); 3924 ExprResult Res = 3925 S.CreateBuiltinUnaryOp(CaptureExpr->getExprLoc(), UO_AddrOf, Init); 3926 if (!Res.isUsable()) 3927 return nullptr; 3928 Init = Res.get(); 3929 } 3930 WithInit = true; 3931 } 3932 auto *CED = OMPCapturedExprDecl::Create(C, S.CurContext, Id, Ty, 3933 CaptureExpr->getBeginLoc()); 3934 if (!WithInit) 3935 CED->addAttr(OMPCaptureNoInitAttr::CreateImplicit(C)); 3936 S.CurContext->addHiddenDecl(CED); 3937 S.AddInitializerToDecl(CED, Init, /*DirectInit=*/false); 3938 return CED; 3939 } 3940 3941 static DeclRefExpr *buildCapture(Sema &S, ValueDecl *D, Expr *CaptureExpr, 3942 bool WithInit) { 3943 OMPCapturedExprDecl *CD; 3944 if (VarDecl *VD = S.isOpenMPCapturedDecl(D)) 3945 CD = cast<OMPCapturedExprDecl>(VD); 3946 else 3947 CD = buildCaptureDecl(S, D->getIdentifier(), CaptureExpr, WithInit, 3948 /*AsExpression=*/false); 3949 return buildDeclRefExpr(S, CD, CD->getType().getNonReferenceType(), 3950 CaptureExpr->getExprLoc()); 3951 } 3952 3953 static ExprResult buildCapture(Sema &S, Expr *CaptureExpr, DeclRefExpr *&Ref) { 3954 CaptureExpr = S.DefaultLvalueConversion(CaptureExpr).get(); 3955 if (!Ref) { 3956 OMPCapturedExprDecl *CD = buildCaptureDecl( 3957 S, &S.getASTContext().Idents.get(".capture_expr."), CaptureExpr, 3958 /*WithInit=*/true, /*AsExpression=*/true); 3959 Ref = buildDeclRefExpr(S, CD, CD->getType().getNonReferenceType(), 3960 CaptureExpr->getExprLoc()); 3961 } 3962 ExprResult Res = Ref; 3963 if (!S.getLangOpts().CPlusPlus && 3964 CaptureExpr->getObjectKind() == OK_Ordinary && CaptureExpr->isGLValue() && 3965 Ref->getType()->isPointerType()) { 3966 Res = S.CreateBuiltinUnaryOp(CaptureExpr->getExprLoc(), UO_Deref, Ref); 3967 if (!Res.isUsable()) 3968 return ExprError(); 3969 } 3970 return S.DefaultLvalueConversion(Res.get()); 3971 } 3972 3973 namespace { 3974 // OpenMP directives parsed in this section are represented as a 3975 // CapturedStatement with an associated statement. If a syntax error 3976 // is detected during the parsing of the associated statement, the 3977 // compiler must abort processing and close the CapturedStatement. 3978 // 3979 // Combined directives such as 'target parallel' have more than one 3980 // nested CapturedStatements. This RAII ensures that we unwind out 3981 // of all the nested CapturedStatements when an error is found. 3982 class CaptureRegionUnwinderRAII { 3983 private: 3984 Sema &S; 3985 bool &ErrorFound; 3986 OpenMPDirectiveKind DKind = OMPD_unknown; 3987 3988 public: 3989 CaptureRegionUnwinderRAII(Sema &S, bool &ErrorFound, 3990 OpenMPDirectiveKind DKind) 3991 : S(S), ErrorFound(ErrorFound), DKind(DKind) {} 3992 ~CaptureRegionUnwinderRAII() { 3993 if (ErrorFound) { 3994 int ThisCaptureLevel = S.getOpenMPCaptureLevels(DKind); 3995 while (--ThisCaptureLevel >= 0) 3996 S.ActOnCapturedRegionError(); 3997 } 3998 } 3999 }; 4000 } // namespace 4001 4002 void Sema::tryCaptureOpenMPLambdas(ValueDecl *V) { 4003 // Capture variables captured by reference in lambdas for target-based 4004 // directives. 4005 if (!CurContext->isDependentContext() && 4006 (isOpenMPTargetExecutionDirective(DSAStack->getCurrentDirective()) || 4007 isOpenMPTargetDataManagementDirective( 4008 DSAStack->getCurrentDirective()))) { 4009 QualType Type = V->getType(); 4010 if (const auto *RD = Type.getCanonicalType() 4011 .getNonReferenceType() 4012 ->getAsCXXRecordDecl()) { 4013 bool SavedForceCaptureByReferenceInTargetExecutable = 4014 DSAStack->isForceCaptureByReferenceInTargetExecutable(); 4015 DSAStack->setForceCaptureByReferenceInTargetExecutable( 4016 /*V=*/true); 4017 if (RD->isLambda()) { 4018 llvm::DenseMap<const VarDecl *, FieldDecl *> Captures; 4019 FieldDecl *ThisCapture; 4020 RD->getCaptureFields(Captures, ThisCapture); 4021 for (const LambdaCapture &LC : RD->captures()) { 4022 if (LC.getCaptureKind() == LCK_ByRef) { 4023 VarDecl *VD = LC.getCapturedVar(); 4024 DeclContext *VDC = VD->getDeclContext(); 4025 if (!VDC->Encloses(CurContext)) 4026 continue; 4027 MarkVariableReferenced(LC.getLocation(), VD); 4028 } else if (LC.getCaptureKind() == LCK_This) { 4029 QualType ThisTy = getCurrentThisType(); 4030 if (!ThisTy.isNull() && 4031 Context.typesAreCompatible(ThisTy, ThisCapture->getType())) 4032 CheckCXXThisCapture(LC.getLocation()); 4033 } 4034 } 4035 } 4036 DSAStack->setForceCaptureByReferenceInTargetExecutable( 4037 SavedForceCaptureByReferenceInTargetExecutable); 4038 } 4039 } 4040 } 4041 4042 static bool checkOrderedOrderSpecified(Sema &S, 4043 const ArrayRef<OMPClause *> Clauses) { 4044 const OMPOrderedClause *Ordered = nullptr; 4045 const OMPOrderClause *Order = nullptr; 4046 4047 for (const OMPClause *Clause : Clauses) { 4048 if (Clause->getClauseKind() == OMPC_ordered) 4049 Ordered = cast<OMPOrderedClause>(Clause); 4050 else if (Clause->getClauseKind() == OMPC_order) { 4051 Order = cast<OMPOrderClause>(Clause); 4052 if (Order->getKind() != OMPC_ORDER_concurrent) 4053 Order = nullptr; 4054 } 4055 if (Ordered && Order) 4056 break; 4057 } 4058 4059 if (Ordered && Order) { 4060 S.Diag(Order->getKindKwLoc(), 4061 diag::err_omp_simple_clause_incompatible_with_ordered) 4062 << getOpenMPClauseName(OMPC_order) 4063 << getOpenMPSimpleClauseTypeName(OMPC_order, OMPC_ORDER_concurrent) 4064 << SourceRange(Order->getBeginLoc(), Order->getEndLoc()); 4065 S.Diag(Ordered->getBeginLoc(), diag::note_omp_ordered_param) 4066 << 0 << SourceRange(Ordered->getBeginLoc(), Ordered->getEndLoc()); 4067 return true; 4068 } 4069 return false; 4070 } 4071 4072 StmtResult Sema::ActOnOpenMPRegionEnd(StmtResult S, 4073 ArrayRef<OMPClause *> Clauses) { 4074 bool ErrorFound = false; 4075 CaptureRegionUnwinderRAII CaptureRegionUnwinder( 4076 *this, ErrorFound, DSAStack->getCurrentDirective()); 4077 if (!S.isUsable()) { 4078 ErrorFound = true; 4079 return StmtError(); 4080 } 4081 4082 SmallVector<OpenMPDirectiveKind, 4> CaptureRegions; 4083 getOpenMPCaptureRegions(CaptureRegions, DSAStack->getCurrentDirective()); 4084 OMPOrderedClause *OC = nullptr; 4085 OMPScheduleClause *SC = nullptr; 4086 SmallVector<const OMPLinearClause *, 4> LCs; 4087 SmallVector<const OMPClauseWithPreInit *, 4> PICs; 4088 // This is required for proper codegen. 4089 for (OMPClause *Clause : Clauses) { 4090 if (isOpenMPTaskingDirective(DSAStack->getCurrentDirective()) && 4091 Clause->getClauseKind() == OMPC_in_reduction) { 4092 // Capture taskgroup task_reduction descriptors inside the tasking regions 4093 // with the corresponding in_reduction items. 4094 auto *IRC = cast<OMPInReductionClause>(Clause); 4095 for (Expr *E : IRC->taskgroup_descriptors()) 4096 if (E) 4097 MarkDeclarationsReferencedInExpr(E); 4098 } 4099 if (isOpenMPPrivate(Clause->getClauseKind()) || 4100 Clause->getClauseKind() == OMPC_copyprivate || 4101 (getLangOpts().OpenMPUseTLS && 4102 getASTContext().getTargetInfo().isTLSSupported() && 4103 Clause->getClauseKind() == OMPC_copyin)) { 4104 DSAStack->setForceVarCapturing(Clause->getClauseKind() == OMPC_copyin); 4105 // Mark all variables in private list clauses as used in inner region. 4106 for (Stmt *VarRef : Clause->children()) { 4107 if (auto *E = cast_or_null<Expr>(VarRef)) { 4108 MarkDeclarationsReferencedInExpr(E); 4109 } 4110 } 4111 DSAStack->setForceVarCapturing(/*V=*/false); 4112 } else if (CaptureRegions.size() > 1 || 4113 CaptureRegions.back() != OMPD_unknown) { 4114 if (auto *C = OMPClauseWithPreInit::get(Clause)) 4115 PICs.push_back(C); 4116 if (auto *C = OMPClauseWithPostUpdate::get(Clause)) { 4117 if (Expr *E = C->getPostUpdateExpr()) 4118 MarkDeclarationsReferencedInExpr(E); 4119 } 4120 } 4121 if (Clause->getClauseKind() == OMPC_schedule) 4122 SC = cast<OMPScheduleClause>(Clause); 4123 else if (Clause->getClauseKind() == OMPC_ordered) 4124 OC = cast<OMPOrderedClause>(Clause); 4125 else if (Clause->getClauseKind() == OMPC_linear) 4126 LCs.push_back(cast<OMPLinearClause>(Clause)); 4127 } 4128 // Capture allocator expressions if used. 4129 for (Expr *E : DSAStack->getInnerAllocators()) 4130 MarkDeclarationsReferencedInExpr(E); 4131 // OpenMP, 2.7.1 Loop Construct, Restrictions 4132 // The nonmonotonic modifier cannot be specified if an ordered clause is 4133 // specified. 4134 if (SC && 4135 (SC->getFirstScheduleModifier() == OMPC_SCHEDULE_MODIFIER_nonmonotonic || 4136 SC->getSecondScheduleModifier() == 4137 OMPC_SCHEDULE_MODIFIER_nonmonotonic) && 4138 OC) { 4139 Diag(SC->getFirstScheduleModifier() == OMPC_SCHEDULE_MODIFIER_nonmonotonic 4140 ? SC->getFirstScheduleModifierLoc() 4141 : SC->getSecondScheduleModifierLoc(), 4142 diag::err_omp_simple_clause_incompatible_with_ordered) 4143 << getOpenMPClauseName(OMPC_schedule) 4144 << getOpenMPSimpleClauseTypeName(OMPC_schedule, 4145 OMPC_SCHEDULE_MODIFIER_nonmonotonic) 4146 << SourceRange(OC->getBeginLoc(), OC->getEndLoc()); 4147 ErrorFound = true; 4148 } 4149 // OpenMP 5.0, 2.9.2 Worksharing-Loop Construct, Restrictions. 4150 // If an order(concurrent) clause is present, an ordered clause may not appear 4151 // on the same directive. 4152 if (checkOrderedOrderSpecified(*this, Clauses)) 4153 ErrorFound = true; 4154 if (!LCs.empty() && OC && OC->getNumForLoops()) { 4155 for (const OMPLinearClause *C : LCs) { 4156 Diag(C->getBeginLoc(), diag::err_omp_linear_ordered) 4157 << SourceRange(OC->getBeginLoc(), OC->getEndLoc()); 4158 } 4159 ErrorFound = true; 4160 } 4161 if (isOpenMPWorksharingDirective(DSAStack->getCurrentDirective()) && 4162 isOpenMPSimdDirective(DSAStack->getCurrentDirective()) && OC && 4163 OC->getNumForLoops()) { 4164 Diag(OC->getBeginLoc(), diag::err_omp_ordered_simd) 4165 << getOpenMPDirectiveName(DSAStack->getCurrentDirective()); 4166 ErrorFound = true; 4167 } 4168 if (ErrorFound) { 4169 return StmtError(); 4170 } 4171 StmtResult SR = S; 4172 unsigned CompletedRegions = 0; 4173 for (OpenMPDirectiveKind ThisCaptureRegion : llvm::reverse(CaptureRegions)) { 4174 // Mark all variables in private list clauses as used in inner region. 4175 // Required for proper codegen of combined directives. 4176 // TODO: add processing for other clauses. 4177 if (ThisCaptureRegion != OMPD_unknown) { 4178 for (const clang::OMPClauseWithPreInit *C : PICs) { 4179 OpenMPDirectiveKind CaptureRegion = C->getCaptureRegion(); 4180 // Find the particular capture region for the clause if the 4181 // directive is a combined one with multiple capture regions. 4182 // If the directive is not a combined one, the capture region 4183 // associated with the clause is OMPD_unknown and is generated 4184 // only once. 4185 if (CaptureRegion == ThisCaptureRegion || 4186 CaptureRegion == OMPD_unknown) { 4187 if (auto *DS = cast_or_null<DeclStmt>(C->getPreInitStmt())) { 4188 for (Decl *D : DS->decls()) 4189 MarkVariableReferenced(D->getLocation(), cast<VarDecl>(D)); 4190 } 4191 } 4192 } 4193 } 4194 if (++CompletedRegions == CaptureRegions.size()) 4195 DSAStack->setBodyComplete(); 4196 SR = ActOnCapturedRegionEnd(SR.get()); 4197 } 4198 return SR; 4199 } 4200 4201 static bool checkCancelRegion(Sema &SemaRef, OpenMPDirectiveKind CurrentRegion, 4202 OpenMPDirectiveKind CancelRegion, 4203 SourceLocation StartLoc) { 4204 // CancelRegion is only needed for cancel and cancellation_point. 4205 if (CurrentRegion != OMPD_cancel && CurrentRegion != OMPD_cancellation_point) 4206 return false; 4207 4208 if (CancelRegion == OMPD_parallel || CancelRegion == OMPD_for || 4209 CancelRegion == OMPD_sections || CancelRegion == OMPD_taskgroup) 4210 return false; 4211 4212 SemaRef.Diag(StartLoc, diag::err_omp_wrong_cancel_region) 4213 << getOpenMPDirectiveName(CancelRegion); 4214 return true; 4215 } 4216 4217 static bool checkNestingOfRegions(Sema &SemaRef, const DSAStackTy *Stack, 4218 OpenMPDirectiveKind CurrentRegion, 4219 const DeclarationNameInfo &CurrentName, 4220 OpenMPDirectiveKind CancelRegion, 4221 SourceLocation StartLoc) { 4222 if (Stack->getCurScope()) { 4223 OpenMPDirectiveKind ParentRegion = Stack->getParentDirective(); 4224 OpenMPDirectiveKind OffendingRegion = ParentRegion; 4225 bool NestingProhibited = false; 4226 bool CloseNesting = true; 4227 bool OrphanSeen = false; 4228 enum { 4229 NoRecommend, 4230 ShouldBeInParallelRegion, 4231 ShouldBeInOrderedRegion, 4232 ShouldBeInTargetRegion, 4233 ShouldBeInTeamsRegion, 4234 ShouldBeInLoopSimdRegion, 4235 } Recommend = NoRecommend; 4236 if (isOpenMPSimdDirective(ParentRegion) && 4237 ((SemaRef.LangOpts.OpenMP <= 45 && CurrentRegion != OMPD_ordered) || 4238 (SemaRef.LangOpts.OpenMP >= 50 && CurrentRegion != OMPD_ordered && 4239 CurrentRegion != OMPD_simd && CurrentRegion != OMPD_atomic && 4240 CurrentRegion != OMPD_scan))) { 4241 // OpenMP [2.16, Nesting of Regions] 4242 // OpenMP constructs may not be nested inside a simd region. 4243 // OpenMP [2.8.1,simd Construct, Restrictions] 4244 // An ordered construct with the simd clause is the only OpenMP 4245 // construct that can appear in the simd region. 4246 // Allowing a SIMD construct nested in another SIMD construct is an 4247 // extension. The OpenMP 4.5 spec does not allow it. Issue a warning 4248 // message. 4249 // OpenMP 5.0 [2.9.3.1, simd Construct, Restrictions] 4250 // The only OpenMP constructs that can be encountered during execution of 4251 // a simd region are the atomic construct, the loop construct, the simd 4252 // construct and the ordered construct with the simd clause. 4253 SemaRef.Diag(StartLoc, (CurrentRegion != OMPD_simd) 4254 ? diag::err_omp_prohibited_region_simd 4255 : diag::warn_omp_nesting_simd) 4256 << (SemaRef.LangOpts.OpenMP >= 50 ? 1 : 0); 4257 return CurrentRegion != OMPD_simd; 4258 } 4259 if (ParentRegion == OMPD_atomic) { 4260 // OpenMP [2.16, Nesting of Regions] 4261 // OpenMP constructs may not be nested inside an atomic region. 4262 SemaRef.Diag(StartLoc, diag::err_omp_prohibited_region_atomic); 4263 return true; 4264 } 4265 if (CurrentRegion == OMPD_section) { 4266 // OpenMP [2.7.2, sections Construct, Restrictions] 4267 // Orphaned section directives are prohibited. That is, the section 4268 // directives must appear within the sections construct and must not be 4269 // encountered elsewhere in the sections region. 4270 if (ParentRegion != OMPD_sections && 4271 ParentRegion != OMPD_parallel_sections) { 4272 SemaRef.Diag(StartLoc, diag::err_omp_orphaned_section_directive) 4273 << (ParentRegion != OMPD_unknown) 4274 << getOpenMPDirectiveName(ParentRegion); 4275 return true; 4276 } 4277 return false; 4278 } 4279 // Allow some constructs (except teams and cancellation constructs) to be 4280 // orphaned (they could be used in functions, called from OpenMP regions 4281 // with the required preconditions). 4282 if (ParentRegion == OMPD_unknown && 4283 !isOpenMPNestingTeamsDirective(CurrentRegion) && 4284 CurrentRegion != OMPD_cancellation_point && 4285 CurrentRegion != OMPD_cancel && CurrentRegion != OMPD_scan) 4286 return false; 4287 if (CurrentRegion == OMPD_cancellation_point || 4288 CurrentRegion == OMPD_cancel) { 4289 // OpenMP [2.16, Nesting of Regions] 4290 // A cancellation point construct for which construct-type-clause is 4291 // taskgroup must be nested inside a task construct. A cancellation 4292 // point construct for which construct-type-clause is not taskgroup must 4293 // be closely nested inside an OpenMP construct that matches the type 4294 // specified in construct-type-clause. 4295 // A cancel construct for which construct-type-clause is taskgroup must be 4296 // nested inside a task construct. A cancel construct for which 4297 // construct-type-clause is not taskgroup must be closely nested inside an 4298 // OpenMP construct that matches the type specified in 4299 // construct-type-clause. 4300 NestingProhibited = 4301 !((CancelRegion == OMPD_parallel && 4302 (ParentRegion == OMPD_parallel || 4303 ParentRegion == OMPD_target_parallel)) || 4304 (CancelRegion == OMPD_for && 4305 (ParentRegion == OMPD_for || ParentRegion == OMPD_parallel_for || 4306 ParentRegion == OMPD_target_parallel_for || 4307 ParentRegion == OMPD_distribute_parallel_for || 4308 ParentRegion == OMPD_teams_distribute_parallel_for || 4309 ParentRegion == OMPD_target_teams_distribute_parallel_for)) || 4310 (CancelRegion == OMPD_taskgroup && 4311 (ParentRegion == OMPD_task || 4312 (SemaRef.getLangOpts().OpenMP >= 50 && 4313 (ParentRegion == OMPD_taskloop || 4314 ParentRegion == OMPD_master_taskloop || 4315 ParentRegion == OMPD_parallel_master_taskloop)))) || 4316 (CancelRegion == OMPD_sections && 4317 (ParentRegion == OMPD_section || ParentRegion == OMPD_sections || 4318 ParentRegion == OMPD_parallel_sections))); 4319 OrphanSeen = ParentRegion == OMPD_unknown; 4320 } else if (CurrentRegion == OMPD_master) { 4321 // OpenMP [2.16, Nesting of Regions] 4322 // A master region may not be closely nested inside a worksharing, 4323 // atomic, or explicit task region. 4324 NestingProhibited = isOpenMPWorksharingDirective(ParentRegion) || 4325 isOpenMPTaskingDirective(ParentRegion); 4326 } else if (CurrentRegion == OMPD_critical && CurrentName.getName()) { 4327 // OpenMP [2.16, Nesting of Regions] 4328 // A critical region may not be nested (closely or otherwise) inside a 4329 // critical region with the same name. Note that this restriction is not 4330 // sufficient to prevent deadlock. 4331 SourceLocation PreviousCriticalLoc; 4332 bool DeadLock = Stack->hasDirective( 4333 [CurrentName, &PreviousCriticalLoc](OpenMPDirectiveKind K, 4334 const DeclarationNameInfo &DNI, 4335 SourceLocation Loc) { 4336 if (K == OMPD_critical && DNI.getName() == CurrentName.getName()) { 4337 PreviousCriticalLoc = Loc; 4338 return true; 4339 } 4340 return false; 4341 }, 4342 false /* skip top directive */); 4343 if (DeadLock) { 4344 SemaRef.Diag(StartLoc, 4345 diag::err_omp_prohibited_region_critical_same_name) 4346 << CurrentName.getName(); 4347 if (PreviousCriticalLoc.isValid()) 4348 SemaRef.Diag(PreviousCriticalLoc, 4349 diag::note_omp_previous_critical_region); 4350 return true; 4351 } 4352 } else if (CurrentRegion == OMPD_barrier) { 4353 // OpenMP [2.16, Nesting of Regions] 4354 // A barrier region may not be closely nested inside a worksharing, 4355 // explicit task, critical, ordered, atomic, or master region. 4356 NestingProhibited = isOpenMPWorksharingDirective(ParentRegion) || 4357 isOpenMPTaskingDirective(ParentRegion) || 4358 ParentRegion == OMPD_master || 4359 ParentRegion == OMPD_parallel_master || 4360 ParentRegion == OMPD_critical || 4361 ParentRegion == OMPD_ordered; 4362 } else if (isOpenMPWorksharingDirective(CurrentRegion) && 4363 !isOpenMPParallelDirective(CurrentRegion) && 4364 !isOpenMPTeamsDirective(CurrentRegion)) { 4365 // OpenMP [2.16, Nesting of Regions] 4366 // A worksharing region may not be closely nested inside a worksharing, 4367 // explicit task, critical, ordered, atomic, or master region. 4368 NestingProhibited = isOpenMPWorksharingDirective(ParentRegion) || 4369 isOpenMPTaskingDirective(ParentRegion) || 4370 ParentRegion == OMPD_master || 4371 ParentRegion == OMPD_parallel_master || 4372 ParentRegion == OMPD_critical || 4373 ParentRegion == OMPD_ordered; 4374 Recommend = ShouldBeInParallelRegion; 4375 } else if (CurrentRegion == OMPD_ordered) { 4376 // OpenMP [2.16, Nesting of Regions] 4377 // An ordered region may not be closely nested inside a critical, 4378 // atomic, or explicit task region. 4379 // An ordered region must be closely nested inside a loop region (or 4380 // parallel loop region) with an ordered clause. 4381 // OpenMP [2.8.1,simd Construct, Restrictions] 4382 // An ordered construct with the simd clause is the only OpenMP construct 4383 // that can appear in the simd region. 4384 NestingProhibited = ParentRegion == OMPD_critical || 4385 isOpenMPTaskingDirective(ParentRegion) || 4386 !(isOpenMPSimdDirective(ParentRegion) || 4387 Stack->isParentOrderedRegion()); 4388 Recommend = ShouldBeInOrderedRegion; 4389 } else if (isOpenMPNestingTeamsDirective(CurrentRegion)) { 4390 // OpenMP [2.16, Nesting of Regions] 4391 // If specified, a teams construct must be contained within a target 4392 // construct. 4393 NestingProhibited = 4394 (SemaRef.LangOpts.OpenMP <= 45 && ParentRegion != OMPD_target) || 4395 (SemaRef.LangOpts.OpenMP >= 50 && ParentRegion != OMPD_unknown && 4396 ParentRegion != OMPD_target); 4397 OrphanSeen = ParentRegion == OMPD_unknown; 4398 Recommend = ShouldBeInTargetRegion; 4399 } else if (CurrentRegion == OMPD_scan) { 4400 // OpenMP [2.16, Nesting of Regions] 4401 // If specified, a teams construct must be contained within a target 4402 // construct. 4403 NestingProhibited = 4404 SemaRef.LangOpts.OpenMP < 50 || 4405 (ParentRegion != OMPD_simd && ParentRegion != OMPD_for && 4406 ParentRegion != OMPD_for_simd && ParentRegion != OMPD_parallel_for && 4407 ParentRegion != OMPD_parallel_for_simd); 4408 OrphanSeen = ParentRegion == OMPD_unknown; 4409 Recommend = ShouldBeInLoopSimdRegion; 4410 } 4411 if (!NestingProhibited && 4412 !isOpenMPTargetExecutionDirective(CurrentRegion) && 4413 !isOpenMPTargetDataManagementDirective(CurrentRegion) && 4414 (ParentRegion == OMPD_teams || ParentRegion == OMPD_target_teams)) { 4415 // OpenMP [2.16, Nesting of Regions] 4416 // distribute, parallel, parallel sections, parallel workshare, and the 4417 // parallel loop and parallel loop SIMD constructs are the only OpenMP 4418 // constructs that can be closely nested in the teams region. 4419 NestingProhibited = !isOpenMPParallelDirective(CurrentRegion) && 4420 !isOpenMPDistributeDirective(CurrentRegion); 4421 Recommend = ShouldBeInParallelRegion; 4422 } 4423 if (!NestingProhibited && 4424 isOpenMPNestingDistributeDirective(CurrentRegion)) { 4425 // OpenMP 4.5 [2.17 Nesting of Regions] 4426 // The region associated with the distribute construct must be strictly 4427 // nested inside a teams region 4428 NestingProhibited = 4429 (ParentRegion != OMPD_teams && ParentRegion != OMPD_target_teams); 4430 Recommend = ShouldBeInTeamsRegion; 4431 } 4432 if (!NestingProhibited && 4433 (isOpenMPTargetExecutionDirective(CurrentRegion) || 4434 isOpenMPTargetDataManagementDirective(CurrentRegion))) { 4435 // OpenMP 4.5 [2.17 Nesting of Regions] 4436 // If a target, target update, target data, target enter data, or 4437 // target exit data construct is encountered during execution of a 4438 // target region, the behavior is unspecified. 4439 NestingProhibited = Stack->hasDirective( 4440 [&OffendingRegion](OpenMPDirectiveKind K, const DeclarationNameInfo &, 4441 SourceLocation) { 4442 if (isOpenMPTargetExecutionDirective(K)) { 4443 OffendingRegion = K; 4444 return true; 4445 } 4446 return false; 4447 }, 4448 false /* don't skip top directive */); 4449 CloseNesting = false; 4450 } 4451 if (NestingProhibited) { 4452 if (OrphanSeen) { 4453 SemaRef.Diag(StartLoc, diag::err_omp_orphaned_device_directive) 4454 << getOpenMPDirectiveName(CurrentRegion) << Recommend; 4455 } else { 4456 SemaRef.Diag(StartLoc, diag::err_omp_prohibited_region) 4457 << CloseNesting << getOpenMPDirectiveName(OffendingRegion) 4458 << Recommend << getOpenMPDirectiveName(CurrentRegion); 4459 } 4460 return true; 4461 } 4462 } 4463 return false; 4464 } 4465 4466 struct Kind2Unsigned { 4467 using argument_type = OpenMPDirectiveKind; 4468 unsigned operator()(argument_type DK) { return unsigned(DK); } 4469 }; 4470 static bool checkIfClauses(Sema &S, OpenMPDirectiveKind Kind, 4471 ArrayRef<OMPClause *> Clauses, 4472 ArrayRef<OpenMPDirectiveKind> AllowedNameModifiers) { 4473 bool ErrorFound = false; 4474 unsigned NamedModifiersNumber = 0; 4475 llvm::IndexedMap<const OMPIfClause *, Kind2Unsigned> FoundNameModifiers; 4476 FoundNameModifiers.resize(unsigned(OMPD_unknown) + 1); 4477 SmallVector<SourceLocation, 4> NameModifierLoc; 4478 for (const OMPClause *C : Clauses) { 4479 if (const auto *IC = dyn_cast_or_null<OMPIfClause>(C)) { 4480 // At most one if clause without a directive-name-modifier can appear on 4481 // the directive. 4482 OpenMPDirectiveKind CurNM = IC->getNameModifier(); 4483 if (FoundNameModifiers[CurNM]) { 4484 S.Diag(C->getBeginLoc(), diag::err_omp_more_one_clause) 4485 << getOpenMPDirectiveName(Kind) << getOpenMPClauseName(OMPC_if) 4486 << (CurNM != OMPD_unknown) << getOpenMPDirectiveName(CurNM); 4487 ErrorFound = true; 4488 } else if (CurNM != OMPD_unknown) { 4489 NameModifierLoc.push_back(IC->getNameModifierLoc()); 4490 ++NamedModifiersNumber; 4491 } 4492 FoundNameModifiers[CurNM] = IC; 4493 if (CurNM == OMPD_unknown) 4494 continue; 4495 // Check if the specified name modifier is allowed for the current 4496 // directive. 4497 // At most one if clause with the particular directive-name-modifier can 4498 // appear on the directive. 4499 bool MatchFound = false; 4500 for (auto NM : AllowedNameModifiers) { 4501 if (CurNM == NM) { 4502 MatchFound = true; 4503 break; 4504 } 4505 } 4506 if (!MatchFound) { 4507 S.Diag(IC->getNameModifierLoc(), 4508 diag::err_omp_wrong_if_directive_name_modifier) 4509 << getOpenMPDirectiveName(CurNM) << getOpenMPDirectiveName(Kind); 4510 ErrorFound = true; 4511 } 4512 } 4513 } 4514 // If any if clause on the directive includes a directive-name-modifier then 4515 // all if clauses on the directive must include a directive-name-modifier. 4516 if (FoundNameModifiers[OMPD_unknown] && NamedModifiersNumber > 0) { 4517 if (NamedModifiersNumber == AllowedNameModifiers.size()) { 4518 S.Diag(FoundNameModifiers[OMPD_unknown]->getBeginLoc(), 4519 diag::err_omp_no_more_if_clause); 4520 } else { 4521 std::string Values; 4522 std::string Sep(", "); 4523 unsigned AllowedCnt = 0; 4524 unsigned TotalAllowedNum = 4525 AllowedNameModifiers.size() - NamedModifiersNumber; 4526 for (unsigned Cnt = 0, End = AllowedNameModifiers.size(); Cnt < End; 4527 ++Cnt) { 4528 OpenMPDirectiveKind NM = AllowedNameModifiers[Cnt]; 4529 if (!FoundNameModifiers[NM]) { 4530 Values += "'"; 4531 Values += getOpenMPDirectiveName(NM); 4532 Values += "'"; 4533 if (AllowedCnt + 2 == TotalAllowedNum) 4534 Values += " or "; 4535 else if (AllowedCnt + 1 != TotalAllowedNum) 4536 Values += Sep; 4537 ++AllowedCnt; 4538 } 4539 } 4540 S.Diag(FoundNameModifiers[OMPD_unknown]->getCondition()->getBeginLoc(), 4541 diag::err_omp_unnamed_if_clause) 4542 << (TotalAllowedNum > 1) << Values; 4543 } 4544 for (SourceLocation Loc : NameModifierLoc) { 4545 S.Diag(Loc, diag::note_omp_previous_named_if_clause); 4546 } 4547 ErrorFound = true; 4548 } 4549 return ErrorFound; 4550 } 4551 4552 static std::pair<ValueDecl *, bool> getPrivateItem(Sema &S, Expr *&RefExpr, 4553 SourceLocation &ELoc, 4554 SourceRange &ERange, 4555 bool AllowArraySection) { 4556 if (RefExpr->isTypeDependent() || RefExpr->isValueDependent() || 4557 RefExpr->containsUnexpandedParameterPack()) 4558 return std::make_pair(nullptr, true); 4559 4560 // OpenMP [3.1, C/C++] 4561 // A list item is a variable name. 4562 // OpenMP [2.9.3.3, Restrictions, p.1] 4563 // A variable that is part of another variable (as an array or 4564 // structure element) cannot appear in a private clause. 4565 RefExpr = RefExpr->IgnoreParens(); 4566 enum { 4567 NoArrayExpr = -1, 4568 ArraySubscript = 0, 4569 OMPArraySection = 1 4570 } IsArrayExpr = NoArrayExpr; 4571 if (AllowArraySection) { 4572 if (auto *ASE = dyn_cast_or_null<ArraySubscriptExpr>(RefExpr)) { 4573 Expr *Base = ASE->getBase()->IgnoreParenImpCasts(); 4574 while (auto *TempASE = dyn_cast<ArraySubscriptExpr>(Base)) 4575 Base = TempASE->getBase()->IgnoreParenImpCasts(); 4576 RefExpr = Base; 4577 IsArrayExpr = ArraySubscript; 4578 } else if (auto *OASE = dyn_cast_or_null<OMPArraySectionExpr>(RefExpr)) { 4579 Expr *Base = OASE->getBase()->IgnoreParenImpCasts(); 4580 while (auto *TempOASE = dyn_cast<OMPArraySectionExpr>(Base)) 4581 Base = TempOASE->getBase()->IgnoreParenImpCasts(); 4582 while (auto *TempASE = dyn_cast<ArraySubscriptExpr>(Base)) 4583 Base = TempASE->getBase()->IgnoreParenImpCasts(); 4584 RefExpr = Base; 4585 IsArrayExpr = OMPArraySection; 4586 } 4587 } 4588 ELoc = RefExpr->getExprLoc(); 4589 ERange = RefExpr->getSourceRange(); 4590 RefExpr = RefExpr->IgnoreParenImpCasts(); 4591 auto *DE = dyn_cast_or_null<DeclRefExpr>(RefExpr); 4592 auto *ME = dyn_cast_or_null<MemberExpr>(RefExpr); 4593 if ((!DE || !isa<VarDecl>(DE->getDecl())) && 4594 (S.getCurrentThisType().isNull() || !ME || 4595 !isa<CXXThisExpr>(ME->getBase()->IgnoreParenImpCasts()) || 4596 !isa<FieldDecl>(ME->getMemberDecl()))) { 4597 if (IsArrayExpr != NoArrayExpr) { 4598 S.Diag(ELoc, diag::err_omp_expected_base_var_name) << IsArrayExpr 4599 << ERange; 4600 } else { 4601 S.Diag(ELoc, 4602 AllowArraySection 4603 ? diag::err_omp_expected_var_name_member_expr_or_array_item 4604 : diag::err_omp_expected_var_name_member_expr) 4605 << (S.getCurrentThisType().isNull() ? 0 : 1) << ERange; 4606 } 4607 return std::make_pair(nullptr, false); 4608 } 4609 return std::make_pair( 4610 getCanonicalDecl(DE ? DE->getDecl() : ME->getMemberDecl()), false); 4611 } 4612 4613 static void checkAllocateClauses(Sema &S, DSAStackTy *Stack, 4614 ArrayRef<OMPClause *> Clauses) { 4615 assert(!S.CurContext->isDependentContext() && 4616 "Expected non-dependent context."); 4617 auto AllocateRange = 4618 llvm::make_filter_range(Clauses, OMPAllocateClause::classof); 4619 llvm::DenseMap<CanonicalDeclPtr<Decl>, CanonicalDeclPtr<VarDecl>> 4620 DeclToCopy; 4621 auto PrivateRange = llvm::make_filter_range(Clauses, [](const OMPClause *C) { 4622 return isOpenMPPrivate(C->getClauseKind()); 4623 }); 4624 for (OMPClause *Cl : PrivateRange) { 4625 MutableArrayRef<Expr *>::iterator I, It, Et; 4626 if (Cl->getClauseKind() == OMPC_private) { 4627 auto *PC = cast<OMPPrivateClause>(Cl); 4628 I = PC->private_copies().begin(); 4629 It = PC->varlist_begin(); 4630 Et = PC->varlist_end(); 4631 } else if (Cl->getClauseKind() == OMPC_firstprivate) { 4632 auto *PC = cast<OMPFirstprivateClause>(Cl); 4633 I = PC->private_copies().begin(); 4634 It = PC->varlist_begin(); 4635 Et = PC->varlist_end(); 4636 } else if (Cl->getClauseKind() == OMPC_lastprivate) { 4637 auto *PC = cast<OMPLastprivateClause>(Cl); 4638 I = PC->private_copies().begin(); 4639 It = PC->varlist_begin(); 4640 Et = PC->varlist_end(); 4641 } else if (Cl->getClauseKind() == OMPC_linear) { 4642 auto *PC = cast<OMPLinearClause>(Cl); 4643 I = PC->privates().begin(); 4644 It = PC->varlist_begin(); 4645 Et = PC->varlist_end(); 4646 } else if (Cl->getClauseKind() == OMPC_reduction) { 4647 auto *PC = cast<OMPReductionClause>(Cl); 4648 I = PC->privates().begin(); 4649 It = PC->varlist_begin(); 4650 Et = PC->varlist_end(); 4651 } else if (Cl->getClauseKind() == OMPC_task_reduction) { 4652 auto *PC = cast<OMPTaskReductionClause>(Cl); 4653 I = PC->privates().begin(); 4654 It = PC->varlist_begin(); 4655 Et = PC->varlist_end(); 4656 } else if (Cl->getClauseKind() == OMPC_in_reduction) { 4657 auto *PC = cast<OMPInReductionClause>(Cl); 4658 I = PC->privates().begin(); 4659 It = PC->varlist_begin(); 4660 Et = PC->varlist_end(); 4661 } else { 4662 llvm_unreachable("Expected private clause."); 4663 } 4664 for (Expr *E : llvm::make_range(It, Et)) { 4665 if (!*I) { 4666 ++I; 4667 continue; 4668 } 4669 SourceLocation ELoc; 4670 SourceRange ERange; 4671 Expr *SimpleRefExpr = E; 4672 auto Res = getPrivateItem(S, SimpleRefExpr, ELoc, ERange, 4673 /*AllowArraySection=*/true); 4674 DeclToCopy.try_emplace(Res.first, 4675 cast<VarDecl>(cast<DeclRefExpr>(*I)->getDecl())); 4676 ++I; 4677 } 4678 } 4679 for (OMPClause *C : AllocateRange) { 4680 auto *AC = cast<OMPAllocateClause>(C); 4681 OMPAllocateDeclAttr::AllocatorTypeTy AllocatorKind = 4682 getAllocatorKind(S, Stack, AC->getAllocator()); 4683 // OpenMP, 2.11.4 allocate Clause, Restrictions. 4684 // For task, taskloop or target directives, allocation requests to memory 4685 // allocators with the trait access set to thread result in unspecified 4686 // behavior. 4687 if (AllocatorKind == OMPAllocateDeclAttr::OMPThreadMemAlloc && 4688 (isOpenMPTaskingDirective(Stack->getCurrentDirective()) || 4689 isOpenMPTargetExecutionDirective(Stack->getCurrentDirective()))) { 4690 S.Diag(AC->getAllocator()->getExprLoc(), 4691 diag::warn_omp_allocate_thread_on_task_target_directive) 4692 << getOpenMPDirectiveName(Stack->getCurrentDirective()); 4693 } 4694 for (Expr *E : AC->varlists()) { 4695 SourceLocation ELoc; 4696 SourceRange ERange; 4697 Expr *SimpleRefExpr = E; 4698 auto Res = getPrivateItem(S, SimpleRefExpr, ELoc, ERange); 4699 ValueDecl *VD = Res.first; 4700 DSAStackTy::DSAVarData Data = Stack->getTopDSA(VD, /*FromParent=*/false); 4701 if (!isOpenMPPrivate(Data.CKind)) { 4702 S.Diag(E->getExprLoc(), 4703 diag::err_omp_expected_private_copy_for_allocate); 4704 continue; 4705 } 4706 VarDecl *PrivateVD = DeclToCopy[VD]; 4707 if (checkPreviousOMPAllocateAttribute(S, Stack, E, PrivateVD, 4708 AllocatorKind, AC->getAllocator())) 4709 continue; 4710 applyOMPAllocateAttribute(S, PrivateVD, AllocatorKind, AC->getAllocator(), 4711 E->getSourceRange()); 4712 } 4713 } 4714 } 4715 4716 StmtResult Sema::ActOnOpenMPExecutableDirective( 4717 OpenMPDirectiveKind Kind, const DeclarationNameInfo &DirName, 4718 OpenMPDirectiveKind CancelRegion, ArrayRef<OMPClause *> Clauses, 4719 Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc) { 4720 StmtResult Res = StmtError(); 4721 // First check CancelRegion which is then used in checkNestingOfRegions. 4722 if (checkCancelRegion(*this, Kind, CancelRegion, StartLoc) || 4723 checkNestingOfRegions(*this, DSAStack, Kind, DirName, CancelRegion, 4724 StartLoc)) 4725 return StmtError(); 4726 4727 llvm::SmallVector<OMPClause *, 8> ClausesWithImplicit; 4728 VarsWithInheritedDSAType VarsWithInheritedDSA; 4729 bool ErrorFound = false; 4730 ClausesWithImplicit.append(Clauses.begin(), Clauses.end()); 4731 if (AStmt && !CurContext->isDependentContext()) { 4732 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected"); 4733 4734 // Check default data sharing attributes for referenced variables. 4735 DSAAttrChecker DSAChecker(DSAStack, *this, cast<CapturedStmt>(AStmt)); 4736 int ThisCaptureLevel = getOpenMPCaptureLevels(Kind); 4737 Stmt *S = AStmt; 4738 while (--ThisCaptureLevel >= 0) 4739 S = cast<CapturedStmt>(S)->getCapturedStmt(); 4740 DSAChecker.Visit(S); 4741 if (!isOpenMPTargetDataManagementDirective(Kind) && 4742 !isOpenMPTaskingDirective(Kind)) { 4743 // Visit subcaptures to generate implicit clauses for captured vars. 4744 auto *CS = cast<CapturedStmt>(AStmt); 4745 SmallVector<OpenMPDirectiveKind, 4> CaptureRegions; 4746 getOpenMPCaptureRegions(CaptureRegions, Kind); 4747 // Ignore outer tasking regions for target directives. 4748 if (CaptureRegions.size() > 1 && CaptureRegions.front() == OMPD_task) 4749 CS = cast<CapturedStmt>(CS->getCapturedStmt()); 4750 DSAChecker.visitSubCaptures(CS); 4751 } 4752 if (DSAChecker.isErrorFound()) 4753 return StmtError(); 4754 // Generate list of implicitly defined firstprivate variables. 4755 VarsWithInheritedDSA = DSAChecker.getVarsWithInheritedDSA(); 4756 4757 SmallVector<Expr *, 4> ImplicitFirstprivates( 4758 DSAChecker.getImplicitFirstprivate().begin(), 4759 DSAChecker.getImplicitFirstprivate().end()); 4760 SmallVector<Expr *, 4> ImplicitMaps[OMPC_MAP_delete]; 4761 for (unsigned I = 0; I < OMPC_MAP_delete; ++I) { 4762 ArrayRef<Expr *> ImplicitMap = 4763 DSAChecker.getImplicitMap(static_cast<OpenMPDefaultmapClauseKind>(I)); 4764 ImplicitMaps[I].append(ImplicitMap.begin(), ImplicitMap.end()); 4765 } 4766 // Mark taskgroup task_reduction descriptors as implicitly firstprivate. 4767 for (OMPClause *C : Clauses) { 4768 if (auto *IRC = dyn_cast<OMPInReductionClause>(C)) { 4769 for (Expr *E : IRC->taskgroup_descriptors()) 4770 if (E) 4771 ImplicitFirstprivates.emplace_back(E); 4772 } 4773 // OpenMP 5.0, 2.10.1 task Construct 4774 // [detach clause]... The event-handle will be considered as if it was 4775 // specified on a firstprivate clause. 4776 if (auto *DC = dyn_cast<OMPDetachClause>(C)) 4777 ImplicitFirstprivates.push_back(DC->getEventHandler()); 4778 } 4779 if (!ImplicitFirstprivates.empty()) { 4780 if (OMPClause *Implicit = ActOnOpenMPFirstprivateClause( 4781 ImplicitFirstprivates, SourceLocation(), SourceLocation(), 4782 SourceLocation())) { 4783 ClausesWithImplicit.push_back(Implicit); 4784 ErrorFound = cast<OMPFirstprivateClause>(Implicit)->varlist_size() != 4785 ImplicitFirstprivates.size(); 4786 } else { 4787 ErrorFound = true; 4788 } 4789 } 4790 int ClauseKindCnt = -1; 4791 for (ArrayRef<Expr *> ImplicitMap : ImplicitMaps) { 4792 ++ClauseKindCnt; 4793 if (ImplicitMap.empty()) 4794 continue; 4795 CXXScopeSpec MapperIdScopeSpec; 4796 DeclarationNameInfo MapperId; 4797 auto Kind = static_cast<OpenMPMapClauseKind>(ClauseKindCnt); 4798 if (OMPClause *Implicit = ActOnOpenMPMapClause( 4799 llvm::None, llvm::None, MapperIdScopeSpec, MapperId, Kind, 4800 /*IsMapTypeImplicit=*/true, SourceLocation(), SourceLocation(), 4801 ImplicitMap, OMPVarListLocTy())) { 4802 ClausesWithImplicit.emplace_back(Implicit); 4803 ErrorFound |= 4804 cast<OMPMapClause>(Implicit)->varlist_size() != ImplicitMap.size(); 4805 } else { 4806 ErrorFound = true; 4807 } 4808 } 4809 } 4810 4811 llvm::SmallVector<OpenMPDirectiveKind, 4> AllowedNameModifiers; 4812 switch (Kind) { 4813 case OMPD_parallel: 4814 Res = ActOnOpenMPParallelDirective(ClausesWithImplicit, AStmt, StartLoc, 4815 EndLoc); 4816 AllowedNameModifiers.push_back(OMPD_parallel); 4817 break; 4818 case OMPD_simd: 4819 Res = ActOnOpenMPSimdDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc, 4820 VarsWithInheritedDSA); 4821 if (LangOpts.OpenMP >= 50) 4822 AllowedNameModifiers.push_back(OMPD_simd); 4823 break; 4824 case OMPD_for: 4825 Res = ActOnOpenMPForDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc, 4826 VarsWithInheritedDSA); 4827 break; 4828 case OMPD_for_simd: 4829 Res = ActOnOpenMPForSimdDirective(ClausesWithImplicit, AStmt, StartLoc, 4830 EndLoc, VarsWithInheritedDSA); 4831 if (LangOpts.OpenMP >= 50) 4832 AllowedNameModifiers.push_back(OMPD_simd); 4833 break; 4834 case OMPD_sections: 4835 Res = ActOnOpenMPSectionsDirective(ClausesWithImplicit, AStmt, StartLoc, 4836 EndLoc); 4837 break; 4838 case OMPD_section: 4839 assert(ClausesWithImplicit.empty() && 4840 "No clauses are allowed for 'omp section' directive"); 4841 Res = ActOnOpenMPSectionDirective(AStmt, StartLoc, EndLoc); 4842 break; 4843 case OMPD_single: 4844 Res = ActOnOpenMPSingleDirective(ClausesWithImplicit, AStmt, StartLoc, 4845 EndLoc); 4846 break; 4847 case OMPD_master: 4848 assert(ClausesWithImplicit.empty() && 4849 "No clauses are allowed for 'omp master' directive"); 4850 Res = ActOnOpenMPMasterDirective(AStmt, StartLoc, EndLoc); 4851 break; 4852 case OMPD_critical: 4853 Res = ActOnOpenMPCriticalDirective(DirName, ClausesWithImplicit, AStmt, 4854 StartLoc, EndLoc); 4855 break; 4856 case OMPD_parallel_for: 4857 Res = ActOnOpenMPParallelForDirective(ClausesWithImplicit, AStmt, StartLoc, 4858 EndLoc, VarsWithInheritedDSA); 4859 AllowedNameModifiers.push_back(OMPD_parallel); 4860 break; 4861 case OMPD_parallel_for_simd: 4862 Res = ActOnOpenMPParallelForSimdDirective( 4863 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA); 4864 AllowedNameModifiers.push_back(OMPD_parallel); 4865 if (LangOpts.OpenMP >= 50) 4866 AllowedNameModifiers.push_back(OMPD_simd); 4867 break; 4868 case OMPD_parallel_master: 4869 Res = ActOnOpenMPParallelMasterDirective(ClausesWithImplicit, AStmt, 4870 StartLoc, EndLoc); 4871 AllowedNameModifiers.push_back(OMPD_parallel); 4872 break; 4873 case OMPD_parallel_sections: 4874 Res = ActOnOpenMPParallelSectionsDirective(ClausesWithImplicit, AStmt, 4875 StartLoc, EndLoc); 4876 AllowedNameModifiers.push_back(OMPD_parallel); 4877 break; 4878 case OMPD_task: 4879 Res = 4880 ActOnOpenMPTaskDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc); 4881 AllowedNameModifiers.push_back(OMPD_task); 4882 break; 4883 case OMPD_taskyield: 4884 assert(ClausesWithImplicit.empty() && 4885 "No clauses are allowed for 'omp taskyield' directive"); 4886 assert(AStmt == nullptr && 4887 "No associated statement allowed for 'omp taskyield' directive"); 4888 Res = ActOnOpenMPTaskyieldDirective(StartLoc, EndLoc); 4889 break; 4890 case OMPD_barrier: 4891 assert(ClausesWithImplicit.empty() && 4892 "No clauses are allowed for 'omp barrier' directive"); 4893 assert(AStmt == nullptr && 4894 "No associated statement allowed for 'omp barrier' directive"); 4895 Res = ActOnOpenMPBarrierDirective(StartLoc, EndLoc); 4896 break; 4897 case OMPD_taskwait: 4898 assert(ClausesWithImplicit.empty() && 4899 "No clauses are allowed for 'omp taskwait' directive"); 4900 assert(AStmt == nullptr && 4901 "No associated statement allowed for 'omp taskwait' directive"); 4902 Res = ActOnOpenMPTaskwaitDirective(StartLoc, EndLoc); 4903 break; 4904 case OMPD_taskgroup: 4905 Res = ActOnOpenMPTaskgroupDirective(ClausesWithImplicit, AStmt, StartLoc, 4906 EndLoc); 4907 break; 4908 case OMPD_flush: 4909 assert(AStmt == nullptr && 4910 "No associated statement allowed for 'omp flush' directive"); 4911 Res = ActOnOpenMPFlushDirective(ClausesWithImplicit, StartLoc, EndLoc); 4912 break; 4913 case OMPD_depobj: 4914 assert(AStmt == nullptr && 4915 "No associated statement allowed for 'omp depobj' directive"); 4916 Res = ActOnOpenMPDepobjDirective(ClausesWithImplicit, StartLoc, EndLoc); 4917 break; 4918 case OMPD_scan: 4919 assert(AStmt == nullptr && 4920 "No associated statement allowed for 'omp scan' directive"); 4921 Res = ActOnOpenMPScanDirective(ClausesWithImplicit, StartLoc, EndLoc); 4922 break; 4923 case OMPD_ordered: 4924 Res = ActOnOpenMPOrderedDirective(ClausesWithImplicit, AStmt, StartLoc, 4925 EndLoc); 4926 break; 4927 case OMPD_atomic: 4928 Res = ActOnOpenMPAtomicDirective(ClausesWithImplicit, AStmt, StartLoc, 4929 EndLoc); 4930 break; 4931 case OMPD_teams: 4932 Res = 4933 ActOnOpenMPTeamsDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc); 4934 break; 4935 case OMPD_target: 4936 Res = ActOnOpenMPTargetDirective(ClausesWithImplicit, AStmt, StartLoc, 4937 EndLoc); 4938 AllowedNameModifiers.push_back(OMPD_target); 4939 break; 4940 case OMPD_target_parallel: 4941 Res = ActOnOpenMPTargetParallelDirective(ClausesWithImplicit, AStmt, 4942 StartLoc, EndLoc); 4943 AllowedNameModifiers.push_back(OMPD_target); 4944 AllowedNameModifiers.push_back(OMPD_parallel); 4945 break; 4946 case OMPD_target_parallel_for: 4947 Res = ActOnOpenMPTargetParallelForDirective( 4948 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA); 4949 AllowedNameModifiers.push_back(OMPD_target); 4950 AllowedNameModifiers.push_back(OMPD_parallel); 4951 break; 4952 case OMPD_cancellation_point: 4953 assert(ClausesWithImplicit.empty() && 4954 "No clauses are allowed for 'omp cancellation point' directive"); 4955 assert(AStmt == nullptr && "No associated statement allowed for 'omp " 4956 "cancellation point' directive"); 4957 Res = ActOnOpenMPCancellationPointDirective(StartLoc, EndLoc, CancelRegion); 4958 break; 4959 case OMPD_cancel: 4960 assert(AStmt == nullptr && 4961 "No associated statement allowed for 'omp cancel' directive"); 4962 Res = ActOnOpenMPCancelDirective(ClausesWithImplicit, StartLoc, EndLoc, 4963 CancelRegion); 4964 AllowedNameModifiers.push_back(OMPD_cancel); 4965 break; 4966 case OMPD_target_data: 4967 Res = ActOnOpenMPTargetDataDirective(ClausesWithImplicit, AStmt, StartLoc, 4968 EndLoc); 4969 AllowedNameModifiers.push_back(OMPD_target_data); 4970 break; 4971 case OMPD_target_enter_data: 4972 Res = ActOnOpenMPTargetEnterDataDirective(ClausesWithImplicit, StartLoc, 4973 EndLoc, AStmt); 4974 AllowedNameModifiers.push_back(OMPD_target_enter_data); 4975 break; 4976 case OMPD_target_exit_data: 4977 Res = ActOnOpenMPTargetExitDataDirective(ClausesWithImplicit, StartLoc, 4978 EndLoc, AStmt); 4979 AllowedNameModifiers.push_back(OMPD_target_exit_data); 4980 break; 4981 case OMPD_taskloop: 4982 Res = ActOnOpenMPTaskLoopDirective(ClausesWithImplicit, AStmt, StartLoc, 4983 EndLoc, VarsWithInheritedDSA); 4984 AllowedNameModifiers.push_back(OMPD_taskloop); 4985 break; 4986 case OMPD_taskloop_simd: 4987 Res = ActOnOpenMPTaskLoopSimdDirective(ClausesWithImplicit, AStmt, StartLoc, 4988 EndLoc, VarsWithInheritedDSA); 4989 AllowedNameModifiers.push_back(OMPD_taskloop); 4990 if (LangOpts.OpenMP >= 50) 4991 AllowedNameModifiers.push_back(OMPD_simd); 4992 break; 4993 case OMPD_master_taskloop: 4994 Res = ActOnOpenMPMasterTaskLoopDirective( 4995 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA); 4996 AllowedNameModifiers.push_back(OMPD_taskloop); 4997 break; 4998 case OMPD_master_taskloop_simd: 4999 Res = ActOnOpenMPMasterTaskLoopSimdDirective( 5000 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA); 5001 AllowedNameModifiers.push_back(OMPD_taskloop); 5002 if (LangOpts.OpenMP >= 50) 5003 AllowedNameModifiers.push_back(OMPD_simd); 5004 break; 5005 case OMPD_parallel_master_taskloop: 5006 Res = ActOnOpenMPParallelMasterTaskLoopDirective( 5007 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA); 5008 AllowedNameModifiers.push_back(OMPD_taskloop); 5009 AllowedNameModifiers.push_back(OMPD_parallel); 5010 break; 5011 case OMPD_parallel_master_taskloop_simd: 5012 Res = ActOnOpenMPParallelMasterTaskLoopSimdDirective( 5013 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA); 5014 AllowedNameModifiers.push_back(OMPD_taskloop); 5015 AllowedNameModifiers.push_back(OMPD_parallel); 5016 if (LangOpts.OpenMP >= 50) 5017 AllowedNameModifiers.push_back(OMPD_simd); 5018 break; 5019 case OMPD_distribute: 5020 Res = ActOnOpenMPDistributeDirective(ClausesWithImplicit, AStmt, StartLoc, 5021 EndLoc, VarsWithInheritedDSA); 5022 break; 5023 case OMPD_target_update: 5024 Res = ActOnOpenMPTargetUpdateDirective(ClausesWithImplicit, StartLoc, 5025 EndLoc, AStmt); 5026 AllowedNameModifiers.push_back(OMPD_target_update); 5027 break; 5028 case OMPD_distribute_parallel_for: 5029 Res = ActOnOpenMPDistributeParallelForDirective( 5030 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA); 5031 AllowedNameModifiers.push_back(OMPD_parallel); 5032 break; 5033 case OMPD_distribute_parallel_for_simd: 5034 Res = ActOnOpenMPDistributeParallelForSimdDirective( 5035 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA); 5036 AllowedNameModifiers.push_back(OMPD_parallel); 5037 if (LangOpts.OpenMP >= 50) 5038 AllowedNameModifiers.push_back(OMPD_simd); 5039 break; 5040 case OMPD_distribute_simd: 5041 Res = ActOnOpenMPDistributeSimdDirective( 5042 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA); 5043 if (LangOpts.OpenMP >= 50) 5044 AllowedNameModifiers.push_back(OMPD_simd); 5045 break; 5046 case OMPD_target_parallel_for_simd: 5047 Res = ActOnOpenMPTargetParallelForSimdDirective( 5048 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA); 5049 AllowedNameModifiers.push_back(OMPD_target); 5050 AllowedNameModifiers.push_back(OMPD_parallel); 5051 if (LangOpts.OpenMP >= 50) 5052 AllowedNameModifiers.push_back(OMPD_simd); 5053 break; 5054 case OMPD_target_simd: 5055 Res = ActOnOpenMPTargetSimdDirective(ClausesWithImplicit, AStmt, StartLoc, 5056 EndLoc, VarsWithInheritedDSA); 5057 AllowedNameModifiers.push_back(OMPD_target); 5058 if (LangOpts.OpenMP >= 50) 5059 AllowedNameModifiers.push_back(OMPD_simd); 5060 break; 5061 case OMPD_teams_distribute: 5062 Res = ActOnOpenMPTeamsDistributeDirective( 5063 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA); 5064 break; 5065 case OMPD_teams_distribute_simd: 5066 Res = ActOnOpenMPTeamsDistributeSimdDirective( 5067 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA); 5068 if (LangOpts.OpenMP >= 50) 5069 AllowedNameModifiers.push_back(OMPD_simd); 5070 break; 5071 case OMPD_teams_distribute_parallel_for_simd: 5072 Res = ActOnOpenMPTeamsDistributeParallelForSimdDirective( 5073 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA); 5074 AllowedNameModifiers.push_back(OMPD_parallel); 5075 if (LangOpts.OpenMP >= 50) 5076 AllowedNameModifiers.push_back(OMPD_simd); 5077 break; 5078 case OMPD_teams_distribute_parallel_for: 5079 Res = ActOnOpenMPTeamsDistributeParallelForDirective( 5080 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA); 5081 AllowedNameModifiers.push_back(OMPD_parallel); 5082 break; 5083 case OMPD_target_teams: 5084 Res = ActOnOpenMPTargetTeamsDirective(ClausesWithImplicit, AStmt, StartLoc, 5085 EndLoc); 5086 AllowedNameModifiers.push_back(OMPD_target); 5087 break; 5088 case OMPD_target_teams_distribute: 5089 Res = ActOnOpenMPTargetTeamsDistributeDirective( 5090 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA); 5091 AllowedNameModifiers.push_back(OMPD_target); 5092 break; 5093 case OMPD_target_teams_distribute_parallel_for: 5094 Res = ActOnOpenMPTargetTeamsDistributeParallelForDirective( 5095 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA); 5096 AllowedNameModifiers.push_back(OMPD_target); 5097 AllowedNameModifiers.push_back(OMPD_parallel); 5098 break; 5099 case OMPD_target_teams_distribute_parallel_for_simd: 5100 Res = ActOnOpenMPTargetTeamsDistributeParallelForSimdDirective( 5101 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA); 5102 AllowedNameModifiers.push_back(OMPD_target); 5103 AllowedNameModifiers.push_back(OMPD_parallel); 5104 if (LangOpts.OpenMP >= 50) 5105 AllowedNameModifiers.push_back(OMPD_simd); 5106 break; 5107 case OMPD_target_teams_distribute_simd: 5108 Res = ActOnOpenMPTargetTeamsDistributeSimdDirective( 5109 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA); 5110 AllowedNameModifiers.push_back(OMPD_target); 5111 if (LangOpts.OpenMP >= 50) 5112 AllowedNameModifiers.push_back(OMPD_simd); 5113 break; 5114 case OMPD_declare_target: 5115 case OMPD_end_declare_target: 5116 case OMPD_threadprivate: 5117 case OMPD_allocate: 5118 case OMPD_declare_reduction: 5119 case OMPD_declare_mapper: 5120 case OMPD_declare_simd: 5121 case OMPD_requires: 5122 case OMPD_declare_variant: 5123 case OMPD_begin_declare_variant: 5124 case OMPD_end_declare_variant: 5125 llvm_unreachable("OpenMP Directive is not allowed"); 5126 case OMPD_unknown: 5127 llvm_unreachable("Unknown OpenMP directive"); 5128 } 5129 5130 ErrorFound = Res.isInvalid() || ErrorFound; 5131 5132 // Check variables in the clauses if default(none) was specified. 5133 if (DSAStack->getDefaultDSA() == DSA_none) { 5134 DSAAttrChecker DSAChecker(DSAStack, *this, nullptr); 5135 for (OMPClause *C : Clauses) { 5136 switch (C->getClauseKind()) { 5137 case OMPC_num_threads: 5138 case OMPC_dist_schedule: 5139 // Do not analyse if no parent teams directive. 5140 if (isOpenMPTeamsDirective(Kind)) 5141 break; 5142 continue; 5143 case OMPC_if: 5144 if (isOpenMPTeamsDirective(Kind) && 5145 cast<OMPIfClause>(C)->getNameModifier() != OMPD_target) 5146 break; 5147 if (isOpenMPParallelDirective(Kind) && 5148 isOpenMPTaskLoopDirective(Kind) && 5149 cast<OMPIfClause>(C)->getNameModifier() != OMPD_parallel) 5150 break; 5151 continue; 5152 case OMPC_schedule: 5153 case OMPC_detach: 5154 break; 5155 case OMPC_grainsize: 5156 case OMPC_num_tasks: 5157 case OMPC_final: 5158 case OMPC_priority: 5159 // Do not analyze if no parent parallel directive. 5160 if (isOpenMPParallelDirective(Kind)) 5161 break; 5162 continue; 5163 case OMPC_ordered: 5164 case OMPC_device: 5165 case OMPC_num_teams: 5166 case OMPC_thread_limit: 5167 case OMPC_hint: 5168 case OMPC_collapse: 5169 case OMPC_safelen: 5170 case OMPC_simdlen: 5171 case OMPC_default: 5172 case OMPC_proc_bind: 5173 case OMPC_private: 5174 case OMPC_firstprivate: 5175 case OMPC_lastprivate: 5176 case OMPC_shared: 5177 case OMPC_reduction: 5178 case OMPC_task_reduction: 5179 case OMPC_in_reduction: 5180 case OMPC_linear: 5181 case OMPC_aligned: 5182 case OMPC_copyin: 5183 case OMPC_copyprivate: 5184 case OMPC_nowait: 5185 case OMPC_untied: 5186 case OMPC_mergeable: 5187 case OMPC_allocate: 5188 case OMPC_read: 5189 case OMPC_write: 5190 case OMPC_update: 5191 case OMPC_capture: 5192 case OMPC_seq_cst: 5193 case OMPC_acq_rel: 5194 case OMPC_acquire: 5195 case OMPC_release: 5196 case OMPC_relaxed: 5197 case OMPC_depend: 5198 case OMPC_threads: 5199 case OMPC_simd: 5200 case OMPC_map: 5201 case OMPC_nogroup: 5202 case OMPC_defaultmap: 5203 case OMPC_to: 5204 case OMPC_from: 5205 case OMPC_use_device_ptr: 5206 case OMPC_is_device_ptr: 5207 case OMPC_nontemporal: 5208 case OMPC_order: 5209 case OMPC_destroy: 5210 case OMPC_inclusive: 5211 case OMPC_exclusive: 5212 continue; 5213 case OMPC_allocator: 5214 case OMPC_flush: 5215 case OMPC_depobj: 5216 case OMPC_threadprivate: 5217 case OMPC_uniform: 5218 case OMPC_unknown: 5219 case OMPC_unified_address: 5220 case OMPC_unified_shared_memory: 5221 case OMPC_reverse_offload: 5222 case OMPC_dynamic_allocators: 5223 case OMPC_atomic_default_mem_order: 5224 case OMPC_device_type: 5225 case OMPC_match: 5226 llvm_unreachable("Unexpected clause"); 5227 } 5228 for (Stmt *CC : C->children()) { 5229 if (CC) 5230 DSAChecker.Visit(CC); 5231 } 5232 } 5233 for (const auto &P : DSAChecker.getVarsWithInheritedDSA()) 5234 VarsWithInheritedDSA[P.getFirst()] = P.getSecond(); 5235 } 5236 for (const auto &P : VarsWithInheritedDSA) { 5237 if (P.getFirst()->isImplicit() || isa<OMPCapturedExprDecl>(P.getFirst())) 5238 continue; 5239 ErrorFound = true; 5240 if (DSAStack->getDefaultDSA() == DSA_none) { 5241 Diag(P.second->getExprLoc(), diag::err_omp_no_dsa_for_variable) 5242 << P.first << P.second->getSourceRange(); 5243 Diag(DSAStack->getDefaultDSALocation(), diag::note_omp_default_dsa_none); 5244 } else if (getLangOpts().OpenMP >= 50) { 5245 Diag(P.second->getExprLoc(), 5246 diag::err_omp_defaultmap_no_attr_for_variable) 5247 << P.first << P.second->getSourceRange(); 5248 Diag(DSAStack->getDefaultDSALocation(), 5249 diag::note_omp_defaultmap_attr_none); 5250 } 5251 } 5252 5253 if (!AllowedNameModifiers.empty()) 5254 ErrorFound = checkIfClauses(*this, Kind, Clauses, AllowedNameModifiers) || 5255 ErrorFound; 5256 5257 if (ErrorFound) 5258 return StmtError(); 5259 5260 if (!CurContext->isDependentContext() && 5261 isOpenMPTargetExecutionDirective(Kind) && 5262 !(DSAStack->hasRequiresDeclWithClause<OMPUnifiedSharedMemoryClause>() || 5263 DSAStack->hasRequiresDeclWithClause<OMPUnifiedAddressClause>() || 5264 DSAStack->hasRequiresDeclWithClause<OMPReverseOffloadClause>() || 5265 DSAStack->hasRequiresDeclWithClause<OMPDynamicAllocatorsClause>())) { 5266 // Register target to DSA Stack. 5267 DSAStack->addTargetDirLocation(StartLoc); 5268 } 5269 5270 return Res; 5271 } 5272 5273 Sema::DeclGroupPtrTy Sema::ActOnOpenMPDeclareSimdDirective( 5274 DeclGroupPtrTy DG, OMPDeclareSimdDeclAttr::BranchStateTy BS, Expr *Simdlen, 5275 ArrayRef<Expr *> Uniforms, ArrayRef<Expr *> Aligneds, 5276 ArrayRef<Expr *> Alignments, ArrayRef<Expr *> Linears, 5277 ArrayRef<unsigned> LinModifiers, ArrayRef<Expr *> Steps, SourceRange SR) { 5278 assert(Aligneds.size() == Alignments.size()); 5279 assert(Linears.size() == LinModifiers.size()); 5280 assert(Linears.size() == Steps.size()); 5281 if (!DG || DG.get().isNull()) 5282 return DeclGroupPtrTy(); 5283 5284 const int SimdId = 0; 5285 if (!DG.get().isSingleDecl()) { 5286 Diag(SR.getBegin(), diag::err_omp_single_decl_in_declare_simd_variant) 5287 << SimdId; 5288 return DG; 5289 } 5290 Decl *ADecl = DG.get().getSingleDecl(); 5291 if (auto *FTD = dyn_cast<FunctionTemplateDecl>(ADecl)) 5292 ADecl = FTD->getTemplatedDecl(); 5293 5294 auto *FD = dyn_cast<FunctionDecl>(ADecl); 5295 if (!FD) { 5296 Diag(ADecl->getLocation(), diag::err_omp_function_expected) << SimdId; 5297 return DeclGroupPtrTy(); 5298 } 5299 5300 // OpenMP [2.8.2, declare simd construct, Description] 5301 // The parameter of the simdlen clause must be a constant positive integer 5302 // expression. 5303 ExprResult SL; 5304 if (Simdlen) 5305 SL = VerifyPositiveIntegerConstantInClause(Simdlen, OMPC_simdlen); 5306 // OpenMP [2.8.2, declare simd construct, Description] 5307 // The special this pointer can be used as if was one of the arguments to the 5308 // function in any of the linear, aligned, or uniform clauses. 5309 // The uniform clause declares one or more arguments to have an invariant 5310 // value for all concurrent invocations of the function in the execution of a 5311 // single SIMD loop. 5312 llvm::DenseMap<const Decl *, const Expr *> UniformedArgs; 5313 const Expr *UniformedLinearThis = nullptr; 5314 for (const Expr *E : Uniforms) { 5315 E = E->IgnoreParenImpCasts(); 5316 if (const auto *DRE = dyn_cast<DeclRefExpr>(E)) 5317 if (const auto *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl())) 5318 if (FD->getNumParams() > PVD->getFunctionScopeIndex() && 5319 FD->getParamDecl(PVD->getFunctionScopeIndex()) 5320 ->getCanonicalDecl() == PVD->getCanonicalDecl()) { 5321 UniformedArgs.try_emplace(PVD->getCanonicalDecl(), E); 5322 continue; 5323 } 5324 if (isa<CXXThisExpr>(E)) { 5325 UniformedLinearThis = E; 5326 continue; 5327 } 5328 Diag(E->getExprLoc(), diag::err_omp_param_or_this_in_clause) 5329 << FD->getDeclName() << (isa<CXXMethodDecl>(ADecl) ? 1 : 0); 5330 } 5331 // OpenMP [2.8.2, declare simd construct, Description] 5332 // The aligned clause declares that the object to which each list item points 5333 // is aligned to the number of bytes expressed in the optional parameter of 5334 // the aligned clause. 5335 // The special this pointer can be used as if was one of the arguments to the 5336 // function in any of the linear, aligned, or uniform clauses. 5337 // The type of list items appearing in the aligned clause must be array, 5338 // pointer, reference to array, or reference to pointer. 5339 llvm::DenseMap<const Decl *, const Expr *> AlignedArgs; 5340 const Expr *AlignedThis = nullptr; 5341 for (const Expr *E : Aligneds) { 5342 E = E->IgnoreParenImpCasts(); 5343 if (const auto *DRE = dyn_cast<DeclRefExpr>(E)) 5344 if (const auto *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl())) { 5345 const VarDecl *CanonPVD = PVD->getCanonicalDecl(); 5346 if (FD->getNumParams() > PVD->getFunctionScopeIndex() && 5347 FD->getParamDecl(PVD->getFunctionScopeIndex()) 5348 ->getCanonicalDecl() == CanonPVD) { 5349 // OpenMP [2.8.1, simd construct, Restrictions] 5350 // A list-item cannot appear in more than one aligned clause. 5351 if (AlignedArgs.count(CanonPVD) > 0) { 5352 Diag(E->getExprLoc(), diag::err_omp_used_in_clause_twice) 5353 << 1 << getOpenMPClauseName(OMPC_aligned) 5354 << E->getSourceRange(); 5355 Diag(AlignedArgs[CanonPVD]->getExprLoc(), 5356 diag::note_omp_explicit_dsa) 5357 << getOpenMPClauseName(OMPC_aligned); 5358 continue; 5359 } 5360 AlignedArgs[CanonPVD] = E; 5361 QualType QTy = PVD->getType() 5362 .getNonReferenceType() 5363 .getUnqualifiedType() 5364 .getCanonicalType(); 5365 const Type *Ty = QTy.getTypePtrOrNull(); 5366 if (!Ty || (!Ty->isArrayType() && !Ty->isPointerType())) { 5367 Diag(E->getExprLoc(), diag::err_omp_aligned_expected_array_or_ptr) 5368 << QTy << getLangOpts().CPlusPlus << E->getSourceRange(); 5369 Diag(PVD->getLocation(), diag::note_previous_decl) << PVD; 5370 } 5371 continue; 5372 } 5373 } 5374 if (isa<CXXThisExpr>(E)) { 5375 if (AlignedThis) { 5376 Diag(E->getExprLoc(), diag::err_omp_used_in_clause_twice) 5377 << 2 << getOpenMPClauseName(OMPC_aligned) << E->getSourceRange(); 5378 Diag(AlignedThis->getExprLoc(), diag::note_omp_explicit_dsa) 5379 << getOpenMPClauseName(OMPC_aligned); 5380 } 5381 AlignedThis = E; 5382 continue; 5383 } 5384 Diag(E->getExprLoc(), diag::err_omp_param_or_this_in_clause) 5385 << FD->getDeclName() << (isa<CXXMethodDecl>(ADecl) ? 1 : 0); 5386 } 5387 // The optional parameter of the aligned clause, alignment, must be a constant 5388 // positive integer expression. If no optional parameter is specified, 5389 // implementation-defined default alignments for SIMD instructions on the 5390 // target platforms are assumed. 5391 SmallVector<const Expr *, 4> NewAligns; 5392 for (Expr *E : Alignments) { 5393 ExprResult Align; 5394 if (E) 5395 Align = VerifyPositiveIntegerConstantInClause(E, OMPC_aligned); 5396 NewAligns.push_back(Align.get()); 5397 } 5398 // OpenMP [2.8.2, declare simd construct, Description] 5399 // The linear clause declares one or more list items to be private to a SIMD 5400 // lane and to have a linear relationship with respect to the iteration space 5401 // of a loop. 5402 // The special this pointer can be used as if was one of the arguments to the 5403 // function in any of the linear, aligned, or uniform clauses. 5404 // When a linear-step expression is specified in a linear clause it must be 5405 // either a constant integer expression or an integer-typed parameter that is 5406 // specified in a uniform clause on the directive. 5407 llvm::DenseMap<const Decl *, const Expr *> LinearArgs; 5408 const bool IsUniformedThis = UniformedLinearThis != nullptr; 5409 auto MI = LinModifiers.begin(); 5410 for (const Expr *E : Linears) { 5411 auto LinKind = static_cast<OpenMPLinearClauseKind>(*MI); 5412 ++MI; 5413 E = E->IgnoreParenImpCasts(); 5414 if (const auto *DRE = dyn_cast<DeclRefExpr>(E)) 5415 if (const auto *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl())) { 5416 const VarDecl *CanonPVD = PVD->getCanonicalDecl(); 5417 if (FD->getNumParams() > PVD->getFunctionScopeIndex() && 5418 FD->getParamDecl(PVD->getFunctionScopeIndex()) 5419 ->getCanonicalDecl() == CanonPVD) { 5420 // OpenMP [2.15.3.7, linear Clause, Restrictions] 5421 // A list-item cannot appear in more than one linear clause. 5422 if (LinearArgs.count(CanonPVD) > 0) { 5423 Diag(E->getExprLoc(), diag::err_omp_wrong_dsa) 5424 << getOpenMPClauseName(OMPC_linear) 5425 << getOpenMPClauseName(OMPC_linear) << E->getSourceRange(); 5426 Diag(LinearArgs[CanonPVD]->getExprLoc(), 5427 diag::note_omp_explicit_dsa) 5428 << getOpenMPClauseName(OMPC_linear); 5429 continue; 5430 } 5431 // Each argument can appear in at most one uniform or linear clause. 5432 if (UniformedArgs.count(CanonPVD) > 0) { 5433 Diag(E->getExprLoc(), diag::err_omp_wrong_dsa) 5434 << getOpenMPClauseName(OMPC_linear) 5435 << getOpenMPClauseName(OMPC_uniform) << E->getSourceRange(); 5436 Diag(UniformedArgs[CanonPVD]->getExprLoc(), 5437 diag::note_omp_explicit_dsa) 5438 << getOpenMPClauseName(OMPC_uniform); 5439 continue; 5440 } 5441 LinearArgs[CanonPVD] = E; 5442 if (E->isValueDependent() || E->isTypeDependent() || 5443 E->isInstantiationDependent() || 5444 E->containsUnexpandedParameterPack()) 5445 continue; 5446 (void)CheckOpenMPLinearDecl(CanonPVD, E->getExprLoc(), LinKind, 5447 PVD->getOriginalType(), 5448 /*IsDeclareSimd=*/true); 5449 continue; 5450 } 5451 } 5452 if (isa<CXXThisExpr>(E)) { 5453 if (UniformedLinearThis) { 5454 Diag(E->getExprLoc(), diag::err_omp_wrong_dsa) 5455 << getOpenMPClauseName(OMPC_linear) 5456 << getOpenMPClauseName(IsUniformedThis ? OMPC_uniform : OMPC_linear) 5457 << E->getSourceRange(); 5458 Diag(UniformedLinearThis->getExprLoc(), diag::note_omp_explicit_dsa) 5459 << getOpenMPClauseName(IsUniformedThis ? OMPC_uniform 5460 : OMPC_linear); 5461 continue; 5462 } 5463 UniformedLinearThis = E; 5464 if (E->isValueDependent() || E->isTypeDependent() || 5465 E->isInstantiationDependent() || E->containsUnexpandedParameterPack()) 5466 continue; 5467 (void)CheckOpenMPLinearDecl(/*D=*/nullptr, E->getExprLoc(), LinKind, 5468 E->getType(), /*IsDeclareSimd=*/true); 5469 continue; 5470 } 5471 Diag(E->getExprLoc(), diag::err_omp_param_or_this_in_clause) 5472 << FD->getDeclName() << (isa<CXXMethodDecl>(ADecl) ? 1 : 0); 5473 } 5474 Expr *Step = nullptr; 5475 Expr *NewStep = nullptr; 5476 SmallVector<Expr *, 4> NewSteps; 5477 for (Expr *E : Steps) { 5478 // Skip the same step expression, it was checked already. 5479 if (Step == E || !E) { 5480 NewSteps.push_back(E ? NewStep : nullptr); 5481 continue; 5482 } 5483 Step = E; 5484 if (const auto *DRE = dyn_cast<DeclRefExpr>(Step)) 5485 if (const auto *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl())) { 5486 const VarDecl *CanonPVD = PVD->getCanonicalDecl(); 5487 if (UniformedArgs.count(CanonPVD) == 0) { 5488 Diag(Step->getExprLoc(), diag::err_omp_expected_uniform_param) 5489 << Step->getSourceRange(); 5490 } else if (E->isValueDependent() || E->isTypeDependent() || 5491 E->isInstantiationDependent() || 5492 E->containsUnexpandedParameterPack() || 5493 CanonPVD->getType()->hasIntegerRepresentation()) { 5494 NewSteps.push_back(Step); 5495 } else { 5496 Diag(Step->getExprLoc(), diag::err_omp_expected_int_param) 5497 << Step->getSourceRange(); 5498 } 5499 continue; 5500 } 5501 NewStep = Step; 5502 if (Step && !Step->isValueDependent() && !Step->isTypeDependent() && 5503 !Step->isInstantiationDependent() && 5504 !Step->containsUnexpandedParameterPack()) { 5505 NewStep = PerformOpenMPImplicitIntegerConversion(Step->getExprLoc(), Step) 5506 .get(); 5507 if (NewStep) 5508 NewStep = VerifyIntegerConstantExpression(NewStep).get(); 5509 } 5510 NewSteps.push_back(NewStep); 5511 } 5512 auto *NewAttr = OMPDeclareSimdDeclAttr::CreateImplicit( 5513 Context, BS, SL.get(), const_cast<Expr **>(Uniforms.data()), 5514 Uniforms.size(), const_cast<Expr **>(Aligneds.data()), Aligneds.size(), 5515 const_cast<Expr **>(NewAligns.data()), NewAligns.size(), 5516 const_cast<Expr **>(Linears.data()), Linears.size(), 5517 const_cast<unsigned *>(LinModifiers.data()), LinModifiers.size(), 5518 NewSteps.data(), NewSteps.size(), SR); 5519 ADecl->addAttr(NewAttr); 5520 return DG; 5521 } 5522 5523 static void setPrototype(Sema &S, FunctionDecl *FD, FunctionDecl *FDWithProto, 5524 QualType NewType) { 5525 assert(NewType->isFunctionProtoType() && 5526 "Expected function type with prototype."); 5527 assert(FD->getType()->isFunctionNoProtoType() && 5528 "Expected function with type with no prototype."); 5529 assert(FDWithProto->getType()->isFunctionProtoType() && 5530 "Expected function with prototype."); 5531 // Synthesize parameters with the same types. 5532 FD->setType(NewType); 5533 SmallVector<ParmVarDecl *, 16> Params; 5534 for (const ParmVarDecl *P : FDWithProto->parameters()) { 5535 auto *Param = ParmVarDecl::Create(S.getASTContext(), FD, SourceLocation(), 5536 SourceLocation(), nullptr, P->getType(), 5537 /*TInfo=*/nullptr, SC_None, nullptr); 5538 Param->setScopeInfo(0, Params.size()); 5539 Param->setImplicit(); 5540 Params.push_back(Param); 5541 } 5542 5543 FD->setParams(Params); 5544 } 5545 5546 FunctionDecl * 5547 Sema::ActOnStartOfFunctionDefinitionInOpenMPDeclareVariantScope(Scope *S, 5548 Declarator &D) { 5549 auto *BaseFD = cast<FunctionDecl>(ActOnDeclarator(S, D)); 5550 OMPDeclareVariantScope &DVScope = OMPDeclareVariantScopes.back(); 5551 std::string MangledName; 5552 MangledName += D.getIdentifier()->getName(); 5553 MangledName += getOpenMPVariantManglingSeparatorStr(); 5554 MangledName += DVScope.NameSuffix; 5555 IdentifierInfo &VariantII = Context.Idents.get(MangledName); 5556 5557 VariantII.setMangledOpenMPVariantName(true); 5558 D.SetIdentifier(&VariantII, D.getBeginLoc()); 5559 return BaseFD; 5560 } 5561 5562 void Sema::ActOnFinishedFunctionDefinitionInOpenMPDeclareVariantScope( 5563 FunctionDecl *FD, FunctionDecl *BaseFD) { 5564 // Do not mark function as is used to prevent its emission if this is the 5565 // only place where it is used. 5566 EnterExpressionEvaluationContext Unevaluated( 5567 *this, Sema::ExpressionEvaluationContext::Unevaluated); 5568 5569 Expr *VariantFuncRef = DeclRefExpr::Create( 5570 Context, NestedNameSpecifierLoc(), SourceLocation(), FD, 5571 /* RefersToEnclosingVariableOrCapture */ false, 5572 /* NameLoc */ FD->getLocation(), FD->getType(), ExprValueKind::VK_RValue); 5573 5574 OMPDeclareVariantScope &DVScope = OMPDeclareVariantScopes.back(); 5575 auto *OMPDeclareVariantA = OMPDeclareVariantAttr::CreateImplicit( 5576 Context, VariantFuncRef, DVScope.TI); 5577 BaseFD->addAttr(OMPDeclareVariantA); 5578 5579 BaseFD->setImplicit(true); 5580 } 5581 5582 ExprResult Sema::ActOnOpenMPCall(Sema &S, ExprResult Call, Scope *Scope, 5583 SourceLocation LParenLoc, 5584 MultiExprArg ArgExprs, 5585 SourceLocation RParenLoc, Expr *ExecConfig) { 5586 // The common case is a regular call we do not want to specialize at all. Try 5587 // to make that case fast by bailing early. 5588 CallExpr *CE = dyn_cast<CallExpr>(Call.get()); 5589 if (!CE) 5590 return Call; 5591 5592 FunctionDecl *CalleeFnDecl = CE->getDirectCallee(); 5593 if (!CalleeFnDecl) 5594 return Call; 5595 5596 if (!CalleeFnDecl->hasAttr<OMPDeclareVariantAttr>()) 5597 return Call; 5598 5599 ASTContext &Context = S.getASTContext(); 5600 OMPContext OMPCtx(S.getLangOpts().OpenMPIsDevice, 5601 Context.getTargetInfo().getTriple()); 5602 5603 SmallVector<Expr *, 4> Exprs; 5604 SmallVector<VariantMatchInfo, 4> VMIs; 5605 while (CalleeFnDecl) { 5606 for (OMPDeclareVariantAttr *A : 5607 CalleeFnDecl->specific_attrs<OMPDeclareVariantAttr>()) { 5608 Expr *VariantRef = A->getVariantFuncRef(); 5609 5610 VariantMatchInfo VMI; 5611 OMPTraitInfo &TI = A->getTraitInfo(); 5612 TI.getAsVariantMatchInfo(Context, VMI, /* DeviceSetOnly */ false); 5613 if (!isVariantApplicableInContext(VMI, OMPCtx)) 5614 continue; 5615 5616 VMIs.push_back(VMI); 5617 Exprs.push_back(VariantRef); 5618 } 5619 5620 CalleeFnDecl = CalleeFnDecl->getPreviousDecl(); 5621 } 5622 5623 ExprResult NewCall; 5624 do { 5625 int BestIdx = getBestVariantMatchForContext(VMIs, OMPCtx); 5626 if (BestIdx < 0) 5627 return Call; 5628 Expr *BestExpr = cast<DeclRefExpr>(Exprs[BestIdx]); 5629 Decl *BestDecl = cast<DeclRefExpr>(BestExpr)->getDecl(); 5630 5631 { 5632 // Try to build a (member) call expression for the current best applicable 5633 // variant expression. We allow this to fail in which case we continue 5634 // with the next best variant expression. The fail case is part of the 5635 // implementation defined behavior in the OpenMP standard when it talks 5636 // about what differences in the function prototypes: "Any differences 5637 // that the specific OpenMP context requires in the prototype of the 5638 // variant from the base function prototype are implementation defined." 5639 // This wording is there to allow the specialized variant to have a 5640 // different type than the base function. This is intended and OK but if 5641 // we cannot create a call the difference is not in the "implementation 5642 // defined range" we allow. 5643 Sema::TentativeAnalysisScope Trap(*this); 5644 5645 if (auto *SpecializedMethod = dyn_cast<CXXMethodDecl>(BestDecl)) { 5646 auto *MemberCall = dyn_cast<CXXMemberCallExpr>(CE); 5647 BestExpr = MemberExpr::CreateImplicit( 5648 S.Context, MemberCall->getImplicitObjectArgument(), 5649 /* IsArrow */ false, SpecializedMethod, S.Context.BoundMemberTy, 5650 MemberCall->getValueKind(), MemberCall->getObjectKind()); 5651 } 5652 NewCall = S.BuildCallExpr(Scope, BestExpr, LParenLoc, ArgExprs, RParenLoc, 5653 ExecConfig); 5654 if (NewCall.isUsable()) 5655 break; 5656 } 5657 5658 VMIs.erase(VMIs.begin() + BestIdx); 5659 Exprs.erase(Exprs.begin() + BestIdx); 5660 } while (!VMIs.empty()); 5661 5662 if (!NewCall.isUsable()) 5663 return Call; 5664 5665 return PseudoObjectExpr::Create(Context, CE, {NewCall.get()}, 0); 5666 } 5667 5668 Optional<std::pair<FunctionDecl *, Expr *>> 5669 Sema::checkOpenMPDeclareVariantFunction(Sema::DeclGroupPtrTy DG, 5670 Expr *VariantRef, OMPTraitInfo &TI, 5671 SourceRange SR) { 5672 if (!DG || DG.get().isNull()) 5673 return None; 5674 5675 const int VariantId = 1; 5676 // Must be applied only to single decl. 5677 if (!DG.get().isSingleDecl()) { 5678 Diag(SR.getBegin(), diag::err_omp_single_decl_in_declare_simd_variant) 5679 << VariantId << SR; 5680 return None; 5681 } 5682 Decl *ADecl = DG.get().getSingleDecl(); 5683 if (auto *FTD = dyn_cast<FunctionTemplateDecl>(ADecl)) 5684 ADecl = FTD->getTemplatedDecl(); 5685 5686 // Decl must be a function. 5687 auto *FD = dyn_cast<FunctionDecl>(ADecl); 5688 if (!FD) { 5689 Diag(ADecl->getLocation(), diag::err_omp_function_expected) 5690 << VariantId << SR; 5691 return None; 5692 } 5693 5694 auto &&HasMultiVersionAttributes = [](const FunctionDecl *FD) { 5695 return FD->hasAttrs() && 5696 (FD->hasAttr<CPUDispatchAttr>() || FD->hasAttr<CPUSpecificAttr>() || 5697 FD->hasAttr<TargetAttr>()); 5698 }; 5699 // OpenMP is not compatible with CPU-specific attributes. 5700 if (HasMultiVersionAttributes(FD)) { 5701 Diag(FD->getLocation(), diag::err_omp_declare_variant_incompat_attributes) 5702 << SR; 5703 return None; 5704 } 5705 5706 // Allow #pragma omp declare variant only if the function is not used. 5707 if (FD->isUsed(false)) 5708 Diag(SR.getBegin(), diag::warn_omp_declare_variant_after_used) 5709 << FD->getLocation(); 5710 5711 // Check if the function was emitted already. 5712 const FunctionDecl *Definition; 5713 if (!FD->isThisDeclarationADefinition() && FD->isDefined(Definition) && 5714 (LangOpts.EmitAllDecls || Context.DeclMustBeEmitted(Definition))) 5715 Diag(SR.getBegin(), diag::warn_omp_declare_variant_after_emitted) 5716 << FD->getLocation(); 5717 5718 // The VariantRef must point to function. 5719 if (!VariantRef) { 5720 Diag(SR.getBegin(), diag::err_omp_function_expected) << VariantId; 5721 return None; 5722 } 5723 5724 auto ShouldDelayChecks = [](Expr *&E, bool) { 5725 return E && (E->isTypeDependent() || E->isValueDependent() || 5726 E->containsUnexpandedParameterPack() || 5727 E->isInstantiationDependent()); 5728 }; 5729 // Do not check templates, wait until instantiation. 5730 if (FD->isDependentContext() || ShouldDelayChecks(VariantRef, false) || 5731 TI.anyScoreOrCondition(ShouldDelayChecks)) 5732 return std::make_pair(FD, VariantRef); 5733 5734 // Deal with non-constant score and user condition expressions. 5735 auto HandleNonConstantScoresAndConditions = [this](Expr *&E, 5736 bool IsScore) -> bool { 5737 llvm::APSInt Result; 5738 if (!E || E->isIntegerConstantExpr(Result, Context)) 5739 return false; 5740 5741 if (IsScore) { 5742 // We warn on non-constant scores and pretend they were not present. 5743 Diag(E->getExprLoc(), diag::warn_omp_declare_variant_score_not_constant) 5744 << E; 5745 E = nullptr; 5746 } else { 5747 // We could replace a non-constant user condition with "false" but we 5748 // will soon need to handle these anyway for the dynamic version of 5749 // OpenMP context selectors. 5750 Diag(E->getExprLoc(), 5751 diag::err_omp_declare_variant_user_condition_not_constant) 5752 << E; 5753 } 5754 return true; 5755 }; 5756 if (TI.anyScoreOrCondition(HandleNonConstantScoresAndConditions)) 5757 return None; 5758 5759 // Convert VariantRef expression to the type of the original function to 5760 // resolve possible conflicts. 5761 ExprResult VariantRefCast; 5762 if (LangOpts.CPlusPlus) { 5763 QualType FnPtrType; 5764 auto *Method = dyn_cast<CXXMethodDecl>(FD); 5765 if (Method && !Method->isStatic()) { 5766 const Type *ClassType = 5767 Context.getTypeDeclType(Method->getParent()).getTypePtr(); 5768 FnPtrType = Context.getMemberPointerType(FD->getType(), ClassType); 5769 ExprResult ER; 5770 { 5771 // Build adrr_of unary op to correctly handle type checks for member 5772 // functions. 5773 Sema::TentativeAnalysisScope Trap(*this); 5774 ER = CreateBuiltinUnaryOp(VariantRef->getBeginLoc(), UO_AddrOf, 5775 VariantRef); 5776 } 5777 if (!ER.isUsable()) { 5778 Diag(VariantRef->getExprLoc(), diag::err_omp_function_expected) 5779 << VariantId << VariantRef->getSourceRange(); 5780 return None; 5781 } 5782 VariantRef = ER.get(); 5783 } else { 5784 FnPtrType = Context.getPointerType(FD->getType()); 5785 } 5786 ImplicitConversionSequence ICS = 5787 TryImplicitConversion(VariantRef, FnPtrType.getUnqualifiedType(), 5788 /*SuppressUserConversions=*/false, 5789 AllowedExplicit::None, 5790 /*InOverloadResolution=*/false, 5791 /*CStyle=*/false, 5792 /*AllowObjCWritebackConversion=*/false); 5793 if (ICS.isFailure()) { 5794 Diag(VariantRef->getExprLoc(), 5795 diag::err_omp_declare_variant_incompat_types) 5796 << VariantRef->getType() 5797 << ((Method && !Method->isStatic()) ? FnPtrType : FD->getType()) 5798 << VariantRef->getSourceRange(); 5799 return None; 5800 } 5801 VariantRefCast = PerformImplicitConversion( 5802 VariantRef, FnPtrType.getUnqualifiedType(), AA_Converting); 5803 if (!VariantRefCast.isUsable()) 5804 return None; 5805 // Drop previously built artificial addr_of unary op for member functions. 5806 if (Method && !Method->isStatic()) { 5807 Expr *PossibleAddrOfVariantRef = VariantRefCast.get(); 5808 if (auto *UO = dyn_cast<UnaryOperator>( 5809 PossibleAddrOfVariantRef->IgnoreImplicit())) 5810 VariantRefCast = UO->getSubExpr(); 5811 } 5812 } else { 5813 VariantRefCast = VariantRef; 5814 } 5815 5816 ExprResult ER = CheckPlaceholderExpr(VariantRefCast.get()); 5817 if (!ER.isUsable() || 5818 !ER.get()->IgnoreParenImpCasts()->getType()->isFunctionType()) { 5819 Diag(VariantRef->getExprLoc(), diag::err_omp_function_expected) 5820 << VariantId << VariantRef->getSourceRange(); 5821 return None; 5822 } 5823 5824 // The VariantRef must point to function. 5825 auto *DRE = dyn_cast<DeclRefExpr>(ER.get()->IgnoreParenImpCasts()); 5826 if (!DRE) { 5827 Diag(VariantRef->getExprLoc(), diag::err_omp_function_expected) 5828 << VariantId << VariantRef->getSourceRange(); 5829 return None; 5830 } 5831 auto *NewFD = dyn_cast_or_null<FunctionDecl>(DRE->getDecl()); 5832 if (!NewFD) { 5833 Diag(VariantRef->getExprLoc(), diag::err_omp_function_expected) 5834 << VariantId << VariantRef->getSourceRange(); 5835 return None; 5836 } 5837 5838 // Check if function types are compatible in C. 5839 if (!LangOpts.CPlusPlus) { 5840 QualType NewType = 5841 Context.mergeFunctionTypes(FD->getType(), NewFD->getType()); 5842 if (NewType.isNull()) { 5843 Diag(VariantRef->getExprLoc(), 5844 diag::err_omp_declare_variant_incompat_types) 5845 << NewFD->getType() << FD->getType() << VariantRef->getSourceRange(); 5846 return None; 5847 } 5848 if (NewType->isFunctionProtoType()) { 5849 if (FD->getType()->isFunctionNoProtoType()) 5850 setPrototype(*this, FD, NewFD, NewType); 5851 else if (NewFD->getType()->isFunctionNoProtoType()) 5852 setPrototype(*this, NewFD, FD, NewType); 5853 } 5854 } 5855 5856 // Check if variant function is not marked with declare variant directive. 5857 if (NewFD->hasAttrs() && NewFD->hasAttr<OMPDeclareVariantAttr>()) { 5858 Diag(VariantRef->getExprLoc(), 5859 diag::warn_omp_declare_variant_marked_as_declare_variant) 5860 << VariantRef->getSourceRange(); 5861 SourceRange SR = 5862 NewFD->specific_attr_begin<OMPDeclareVariantAttr>()->getRange(); 5863 Diag(SR.getBegin(), diag::note_omp_marked_declare_variant_here) << SR; 5864 return None; 5865 } 5866 5867 enum DoesntSupport { 5868 VirtFuncs = 1, 5869 Constructors = 3, 5870 Destructors = 4, 5871 DeletedFuncs = 5, 5872 DefaultedFuncs = 6, 5873 ConstexprFuncs = 7, 5874 ConstevalFuncs = 8, 5875 }; 5876 if (const auto *CXXFD = dyn_cast<CXXMethodDecl>(FD)) { 5877 if (CXXFD->isVirtual()) { 5878 Diag(FD->getLocation(), diag::err_omp_declare_variant_doesnt_support) 5879 << VirtFuncs; 5880 return None; 5881 } 5882 5883 if (isa<CXXConstructorDecl>(FD)) { 5884 Diag(FD->getLocation(), diag::err_omp_declare_variant_doesnt_support) 5885 << Constructors; 5886 return None; 5887 } 5888 5889 if (isa<CXXDestructorDecl>(FD)) { 5890 Diag(FD->getLocation(), diag::err_omp_declare_variant_doesnt_support) 5891 << Destructors; 5892 return None; 5893 } 5894 } 5895 5896 if (FD->isDeleted()) { 5897 Diag(FD->getLocation(), diag::err_omp_declare_variant_doesnt_support) 5898 << DeletedFuncs; 5899 return None; 5900 } 5901 5902 if (FD->isDefaulted()) { 5903 Diag(FD->getLocation(), diag::err_omp_declare_variant_doesnt_support) 5904 << DefaultedFuncs; 5905 return None; 5906 } 5907 5908 if (FD->isConstexpr()) { 5909 Diag(FD->getLocation(), diag::err_omp_declare_variant_doesnt_support) 5910 << (NewFD->isConsteval() ? ConstevalFuncs : ConstexprFuncs); 5911 return None; 5912 } 5913 5914 // Check general compatibility. 5915 if (areMultiversionVariantFunctionsCompatible( 5916 FD, NewFD, PartialDiagnostic::NullDiagnostic(), 5917 PartialDiagnosticAt(SourceLocation(), 5918 PartialDiagnostic::NullDiagnostic()), 5919 PartialDiagnosticAt( 5920 VariantRef->getExprLoc(), 5921 PDiag(diag::err_omp_declare_variant_doesnt_support)), 5922 PartialDiagnosticAt(VariantRef->getExprLoc(), 5923 PDiag(diag::err_omp_declare_variant_diff) 5924 << FD->getLocation()), 5925 /*TemplatesSupported=*/true, /*ConstexprSupported=*/false, 5926 /*CLinkageMayDiffer=*/true)) 5927 return None; 5928 return std::make_pair(FD, cast<Expr>(DRE)); 5929 } 5930 5931 void Sema::ActOnOpenMPDeclareVariantDirective(FunctionDecl *FD, 5932 Expr *VariantRef, 5933 OMPTraitInfo &TI, 5934 SourceRange SR) { 5935 auto *NewAttr = 5936 OMPDeclareVariantAttr::CreateImplicit(Context, VariantRef, &TI, SR); 5937 FD->addAttr(NewAttr); 5938 } 5939 5940 StmtResult Sema::ActOnOpenMPParallelDirective(ArrayRef<OMPClause *> Clauses, 5941 Stmt *AStmt, 5942 SourceLocation StartLoc, 5943 SourceLocation EndLoc) { 5944 if (!AStmt) 5945 return StmtError(); 5946 5947 auto *CS = cast<CapturedStmt>(AStmt); 5948 // 1.2.2 OpenMP Language Terminology 5949 // Structured block - An executable statement with a single entry at the 5950 // top and a single exit at the bottom. 5951 // The point of exit cannot be a branch out of the structured block. 5952 // longjmp() and throw() must not violate the entry/exit criteria. 5953 CS->getCapturedDecl()->setNothrow(); 5954 5955 setFunctionHasBranchProtectedScope(); 5956 5957 return OMPParallelDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt, 5958 DSAStack->isCancelRegion()); 5959 } 5960 5961 namespace { 5962 /// Iteration space of a single for loop. 5963 struct LoopIterationSpace final { 5964 /// True if the condition operator is the strict compare operator (<, > or 5965 /// !=). 5966 bool IsStrictCompare = false; 5967 /// Condition of the loop. 5968 Expr *PreCond = nullptr; 5969 /// This expression calculates the number of iterations in the loop. 5970 /// It is always possible to calculate it before starting the loop. 5971 Expr *NumIterations = nullptr; 5972 /// The loop counter variable. 5973 Expr *CounterVar = nullptr; 5974 /// Private loop counter variable. 5975 Expr *PrivateCounterVar = nullptr; 5976 /// This is initializer for the initial value of #CounterVar. 5977 Expr *CounterInit = nullptr; 5978 /// This is step for the #CounterVar used to generate its update: 5979 /// #CounterVar = #CounterInit + #CounterStep * CurrentIteration. 5980 Expr *CounterStep = nullptr; 5981 /// Should step be subtracted? 5982 bool Subtract = false; 5983 /// Source range of the loop init. 5984 SourceRange InitSrcRange; 5985 /// Source range of the loop condition. 5986 SourceRange CondSrcRange; 5987 /// Source range of the loop increment. 5988 SourceRange IncSrcRange; 5989 /// Minimum value that can have the loop control variable. Used to support 5990 /// non-rectangular loops. Applied only for LCV with the non-iterator types, 5991 /// since only such variables can be used in non-loop invariant expressions. 5992 Expr *MinValue = nullptr; 5993 /// Maximum value that can have the loop control variable. Used to support 5994 /// non-rectangular loops. Applied only for LCV with the non-iterator type, 5995 /// since only such variables can be used in non-loop invariant expressions. 5996 Expr *MaxValue = nullptr; 5997 /// true, if the lower bound depends on the outer loop control var. 5998 bool IsNonRectangularLB = false; 5999 /// true, if the upper bound depends on the outer loop control var. 6000 bool IsNonRectangularUB = false; 6001 /// Index of the loop this loop depends on and forms non-rectangular loop 6002 /// nest. 6003 unsigned LoopDependentIdx = 0; 6004 /// Final condition for the non-rectangular loop nest support. It is used to 6005 /// check that the number of iterations for this particular counter must be 6006 /// finished. 6007 Expr *FinalCondition = nullptr; 6008 }; 6009 6010 /// Helper class for checking canonical form of the OpenMP loops and 6011 /// extracting iteration space of each loop in the loop nest, that will be used 6012 /// for IR generation. 6013 class OpenMPIterationSpaceChecker { 6014 /// Reference to Sema. 6015 Sema &SemaRef; 6016 /// Data-sharing stack. 6017 DSAStackTy &Stack; 6018 /// A location for diagnostics (when there is no some better location). 6019 SourceLocation DefaultLoc; 6020 /// A location for diagnostics (when increment is not compatible). 6021 SourceLocation ConditionLoc; 6022 /// A source location for referring to loop init later. 6023 SourceRange InitSrcRange; 6024 /// A source location for referring to condition later. 6025 SourceRange ConditionSrcRange; 6026 /// A source location for referring to increment later. 6027 SourceRange IncrementSrcRange; 6028 /// Loop variable. 6029 ValueDecl *LCDecl = nullptr; 6030 /// Reference to loop variable. 6031 Expr *LCRef = nullptr; 6032 /// Lower bound (initializer for the var). 6033 Expr *LB = nullptr; 6034 /// Upper bound. 6035 Expr *UB = nullptr; 6036 /// Loop step (increment). 6037 Expr *Step = nullptr; 6038 /// This flag is true when condition is one of: 6039 /// Var < UB 6040 /// Var <= UB 6041 /// UB > Var 6042 /// UB >= Var 6043 /// This will have no value when the condition is != 6044 llvm::Optional<bool> TestIsLessOp; 6045 /// This flag is true when condition is strict ( < or > ). 6046 bool TestIsStrictOp = false; 6047 /// This flag is true when step is subtracted on each iteration. 6048 bool SubtractStep = false; 6049 /// The outer loop counter this loop depends on (if any). 6050 const ValueDecl *DepDecl = nullptr; 6051 /// Contains number of loop (starts from 1) on which loop counter init 6052 /// expression of this loop depends on. 6053 Optional<unsigned> InitDependOnLC; 6054 /// Contains number of loop (starts from 1) on which loop counter condition 6055 /// expression of this loop depends on. 6056 Optional<unsigned> CondDependOnLC; 6057 /// Checks if the provide statement depends on the loop counter. 6058 Optional<unsigned> doesDependOnLoopCounter(const Stmt *S, bool IsInitializer); 6059 /// Original condition required for checking of the exit condition for 6060 /// non-rectangular loop. 6061 Expr *Condition = nullptr; 6062 6063 public: 6064 OpenMPIterationSpaceChecker(Sema &SemaRef, DSAStackTy &Stack, 6065 SourceLocation DefaultLoc) 6066 : SemaRef(SemaRef), Stack(Stack), DefaultLoc(DefaultLoc), 6067 ConditionLoc(DefaultLoc) {} 6068 /// Check init-expr for canonical loop form and save loop counter 6069 /// variable - #Var and its initialization value - #LB. 6070 bool checkAndSetInit(Stmt *S, bool EmitDiags = true); 6071 /// Check test-expr for canonical form, save upper-bound (#UB), flags 6072 /// for less/greater and for strict/non-strict comparison. 6073 bool checkAndSetCond(Expr *S); 6074 /// Check incr-expr for canonical loop form and return true if it 6075 /// does not conform, otherwise save loop step (#Step). 6076 bool checkAndSetInc(Expr *S); 6077 /// Return the loop counter variable. 6078 ValueDecl *getLoopDecl() const { return LCDecl; } 6079 /// Return the reference expression to loop counter variable. 6080 Expr *getLoopDeclRefExpr() const { return LCRef; } 6081 /// Source range of the loop init. 6082 SourceRange getInitSrcRange() const { return InitSrcRange; } 6083 /// Source range of the loop condition. 6084 SourceRange getConditionSrcRange() const { return ConditionSrcRange; } 6085 /// Source range of the loop increment. 6086 SourceRange getIncrementSrcRange() const { return IncrementSrcRange; } 6087 /// True if the step should be subtracted. 6088 bool shouldSubtractStep() const { return SubtractStep; } 6089 /// True, if the compare operator is strict (<, > or !=). 6090 bool isStrictTestOp() const { return TestIsStrictOp; } 6091 /// Build the expression to calculate the number of iterations. 6092 Expr *buildNumIterations( 6093 Scope *S, ArrayRef<LoopIterationSpace> ResultIterSpaces, bool LimitedType, 6094 llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) const; 6095 /// Build the precondition expression for the loops. 6096 Expr * 6097 buildPreCond(Scope *S, Expr *Cond, 6098 llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) const; 6099 /// Build reference expression to the counter be used for codegen. 6100 DeclRefExpr * 6101 buildCounterVar(llvm::MapVector<const Expr *, DeclRefExpr *> &Captures, 6102 DSAStackTy &DSA) const; 6103 /// Build reference expression to the private counter be used for 6104 /// codegen. 6105 Expr *buildPrivateCounterVar() const; 6106 /// Build initialization of the counter be used for codegen. 6107 Expr *buildCounterInit() const; 6108 /// Build step of the counter be used for codegen. 6109 Expr *buildCounterStep() const; 6110 /// Build loop data with counter value for depend clauses in ordered 6111 /// directives. 6112 Expr * 6113 buildOrderedLoopData(Scope *S, Expr *Counter, 6114 llvm::MapVector<const Expr *, DeclRefExpr *> &Captures, 6115 SourceLocation Loc, Expr *Inc = nullptr, 6116 OverloadedOperatorKind OOK = OO_Amp); 6117 /// Builds the minimum value for the loop counter. 6118 std::pair<Expr *, Expr *> buildMinMaxValues( 6119 Scope *S, llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) const; 6120 /// Builds final condition for the non-rectangular loops. 6121 Expr *buildFinalCondition(Scope *S) const; 6122 /// Return true if any expression is dependent. 6123 bool dependent() const; 6124 /// Returns true if the initializer forms non-rectangular loop. 6125 bool doesInitDependOnLC() const { return InitDependOnLC.hasValue(); } 6126 /// Returns true if the condition forms non-rectangular loop. 6127 bool doesCondDependOnLC() const { return CondDependOnLC.hasValue(); } 6128 /// Returns index of the loop we depend on (starting from 1), or 0 otherwise. 6129 unsigned getLoopDependentIdx() const { 6130 return InitDependOnLC.getValueOr(CondDependOnLC.getValueOr(0)); 6131 } 6132 6133 private: 6134 /// Check the right-hand side of an assignment in the increment 6135 /// expression. 6136 bool checkAndSetIncRHS(Expr *RHS); 6137 /// Helper to set loop counter variable and its initializer. 6138 bool setLCDeclAndLB(ValueDecl *NewLCDecl, Expr *NewDeclRefExpr, Expr *NewLB, 6139 bool EmitDiags); 6140 /// Helper to set upper bound. 6141 bool setUB(Expr *NewUB, llvm::Optional<bool> LessOp, bool StrictOp, 6142 SourceRange SR, SourceLocation SL); 6143 /// Helper to set loop increment. 6144 bool setStep(Expr *NewStep, bool Subtract); 6145 }; 6146 6147 bool OpenMPIterationSpaceChecker::dependent() const { 6148 if (!LCDecl) { 6149 assert(!LB && !UB && !Step); 6150 return false; 6151 } 6152 return LCDecl->getType()->isDependentType() || 6153 (LB && LB->isValueDependent()) || (UB && UB->isValueDependent()) || 6154 (Step && Step->isValueDependent()); 6155 } 6156 6157 bool OpenMPIterationSpaceChecker::setLCDeclAndLB(ValueDecl *NewLCDecl, 6158 Expr *NewLCRefExpr, 6159 Expr *NewLB, bool EmitDiags) { 6160 // State consistency checking to ensure correct usage. 6161 assert(LCDecl == nullptr && LB == nullptr && LCRef == nullptr && 6162 UB == nullptr && Step == nullptr && !TestIsLessOp && !TestIsStrictOp); 6163 if (!NewLCDecl || !NewLB) 6164 return true; 6165 LCDecl = getCanonicalDecl(NewLCDecl); 6166 LCRef = NewLCRefExpr; 6167 if (auto *CE = dyn_cast_or_null<CXXConstructExpr>(NewLB)) 6168 if (const CXXConstructorDecl *Ctor = CE->getConstructor()) 6169 if ((Ctor->isCopyOrMoveConstructor() || 6170 Ctor->isConvertingConstructor(/*AllowExplicit=*/false)) && 6171 CE->getNumArgs() > 0 && CE->getArg(0) != nullptr) 6172 NewLB = CE->getArg(0)->IgnoreParenImpCasts(); 6173 LB = NewLB; 6174 if (EmitDiags) 6175 InitDependOnLC = doesDependOnLoopCounter(LB, /*IsInitializer=*/true); 6176 return false; 6177 } 6178 6179 bool OpenMPIterationSpaceChecker::setUB(Expr *NewUB, 6180 llvm::Optional<bool> LessOp, 6181 bool StrictOp, SourceRange SR, 6182 SourceLocation SL) { 6183 // State consistency checking to ensure correct usage. 6184 assert(LCDecl != nullptr && LB != nullptr && UB == nullptr && 6185 Step == nullptr && !TestIsLessOp && !TestIsStrictOp); 6186 if (!NewUB) 6187 return true; 6188 UB = NewUB; 6189 if (LessOp) 6190 TestIsLessOp = LessOp; 6191 TestIsStrictOp = StrictOp; 6192 ConditionSrcRange = SR; 6193 ConditionLoc = SL; 6194 CondDependOnLC = doesDependOnLoopCounter(UB, /*IsInitializer=*/false); 6195 return false; 6196 } 6197 6198 bool OpenMPIterationSpaceChecker::setStep(Expr *NewStep, bool Subtract) { 6199 // State consistency checking to ensure correct usage. 6200 assert(LCDecl != nullptr && LB != nullptr && Step == nullptr); 6201 if (!NewStep) 6202 return true; 6203 if (!NewStep->isValueDependent()) { 6204 // Check that the step is integer expression. 6205 SourceLocation StepLoc = NewStep->getBeginLoc(); 6206 ExprResult Val = SemaRef.PerformOpenMPImplicitIntegerConversion( 6207 StepLoc, getExprAsWritten(NewStep)); 6208 if (Val.isInvalid()) 6209 return true; 6210 NewStep = Val.get(); 6211 6212 // OpenMP [2.6, Canonical Loop Form, Restrictions] 6213 // If test-expr is of form var relational-op b and relational-op is < or 6214 // <= then incr-expr must cause var to increase on each iteration of the 6215 // loop. If test-expr is of form var relational-op b and relational-op is 6216 // > or >= then incr-expr must cause var to decrease on each iteration of 6217 // the loop. 6218 // If test-expr is of form b relational-op var and relational-op is < or 6219 // <= then incr-expr must cause var to decrease on each iteration of the 6220 // loop. If test-expr is of form b relational-op var and relational-op is 6221 // > or >= then incr-expr must cause var to increase on each iteration of 6222 // the loop. 6223 llvm::APSInt Result; 6224 bool IsConstant = NewStep->isIntegerConstantExpr(Result, SemaRef.Context); 6225 bool IsUnsigned = !NewStep->getType()->hasSignedIntegerRepresentation(); 6226 bool IsConstNeg = 6227 IsConstant && Result.isSigned() && (Subtract != Result.isNegative()); 6228 bool IsConstPos = 6229 IsConstant && Result.isSigned() && (Subtract == Result.isNegative()); 6230 bool IsConstZero = IsConstant && !Result.getBoolValue(); 6231 6232 // != with increment is treated as <; != with decrement is treated as > 6233 if (!TestIsLessOp.hasValue()) 6234 TestIsLessOp = IsConstPos || (IsUnsigned && !Subtract); 6235 if (UB && (IsConstZero || 6236 (TestIsLessOp.getValue() ? 6237 (IsConstNeg || (IsUnsigned && Subtract)) : 6238 (IsConstPos || (IsUnsigned && !Subtract))))) { 6239 SemaRef.Diag(NewStep->getExprLoc(), 6240 diag::err_omp_loop_incr_not_compatible) 6241 << LCDecl << TestIsLessOp.getValue() << NewStep->getSourceRange(); 6242 SemaRef.Diag(ConditionLoc, 6243 diag::note_omp_loop_cond_requres_compatible_incr) 6244 << TestIsLessOp.getValue() << ConditionSrcRange; 6245 return true; 6246 } 6247 if (TestIsLessOp.getValue() == Subtract) { 6248 NewStep = 6249 SemaRef.CreateBuiltinUnaryOp(NewStep->getExprLoc(), UO_Minus, NewStep) 6250 .get(); 6251 Subtract = !Subtract; 6252 } 6253 } 6254 6255 Step = NewStep; 6256 SubtractStep = Subtract; 6257 return false; 6258 } 6259 6260 namespace { 6261 /// Checker for the non-rectangular loops. Checks if the initializer or 6262 /// condition expression references loop counter variable. 6263 class LoopCounterRefChecker final 6264 : public ConstStmtVisitor<LoopCounterRefChecker, bool> { 6265 Sema &SemaRef; 6266 DSAStackTy &Stack; 6267 const ValueDecl *CurLCDecl = nullptr; 6268 const ValueDecl *DepDecl = nullptr; 6269 const ValueDecl *PrevDepDecl = nullptr; 6270 bool IsInitializer = true; 6271 unsigned BaseLoopId = 0; 6272 bool checkDecl(const Expr *E, const ValueDecl *VD) { 6273 if (getCanonicalDecl(VD) == getCanonicalDecl(CurLCDecl)) { 6274 SemaRef.Diag(E->getExprLoc(), diag::err_omp_stmt_depends_on_loop_counter) 6275 << (IsInitializer ? 0 : 1); 6276 return false; 6277 } 6278 const auto &&Data = Stack.isLoopControlVariable(VD); 6279 // OpenMP, 2.9.1 Canonical Loop Form, Restrictions. 6280 // The type of the loop iterator on which we depend may not have a random 6281 // access iterator type. 6282 if (Data.first && VD->getType()->isRecordType()) { 6283 SmallString<128> Name; 6284 llvm::raw_svector_ostream OS(Name); 6285 VD->getNameForDiagnostic(OS, SemaRef.getPrintingPolicy(), 6286 /*Qualified=*/true); 6287 SemaRef.Diag(E->getExprLoc(), 6288 diag::err_omp_wrong_dependency_iterator_type) 6289 << OS.str(); 6290 SemaRef.Diag(VD->getLocation(), diag::note_previous_decl) << VD; 6291 return false; 6292 } 6293 if (Data.first && 6294 (DepDecl || (PrevDepDecl && 6295 getCanonicalDecl(VD) != getCanonicalDecl(PrevDepDecl)))) { 6296 if (!DepDecl && PrevDepDecl) 6297 DepDecl = PrevDepDecl; 6298 SmallString<128> Name; 6299 llvm::raw_svector_ostream OS(Name); 6300 DepDecl->getNameForDiagnostic(OS, SemaRef.getPrintingPolicy(), 6301 /*Qualified=*/true); 6302 SemaRef.Diag(E->getExprLoc(), 6303 diag::err_omp_invariant_or_linear_dependency) 6304 << OS.str(); 6305 return false; 6306 } 6307 if (Data.first) { 6308 DepDecl = VD; 6309 BaseLoopId = Data.first; 6310 } 6311 return Data.first; 6312 } 6313 6314 public: 6315 bool VisitDeclRefExpr(const DeclRefExpr *E) { 6316 const ValueDecl *VD = E->getDecl(); 6317 if (isa<VarDecl>(VD)) 6318 return checkDecl(E, VD); 6319 return false; 6320 } 6321 bool VisitMemberExpr(const MemberExpr *E) { 6322 if (isa<CXXThisExpr>(E->getBase()->IgnoreParens())) { 6323 const ValueDecl *VD = E->getMemberDecl(); 6324 if (isa<VarDecl>(VD) || isa<FieldDecl>(VD)) 6325 return checkDecl(E, VD); 6326 } 6327 return false; 6328 } 6329 bool VisitStmt(const Stmt *S) { 6330 bool Res = false; 6331 for (const Stmt *Child : S->children()) 6332 Res = (Child && Visit(Child)) || Res; 6333 return Res; 6334 } 6335 explicit LoopCounterRefChecker(Sema &SemaRef, DSAStackTy &Stack, 6336 const ValueDecl *CurLCDecl, bool IsInitializer, 6337 const ValueDecl *PrevDepDecl = nullptr) 6338 : SemaRef(SemaRef), Stack(Stack), CurLCDecl(CurLCDecl), 6339 PrevDepDecl(PrevDepDecl), IsInitializer(IsInitializer) {} 6340 unsigned getBaseLoopId() const { 6341 assert(CurLCDecl && "Expected loop dependency."); 6342 return BaseLoopId; 6343 } 6344 const ValueDecl *getDepDecl() const { 6345 assert(CurLCDecl && "Expected loop dependency."); 6346 return DepDecl; 6347 } 6348 }; 6349 } // namespace 6350 6351 Optional<unsigned> 6352 OpenMPIterationSpaceChecker::doesDependOnLoopCounter(const Stmt *S, 6353 bool IsInitializer) { 6354 // Check for the non-rectangular loops. 6355 LoopCounterRefChecker LoopStmtChecker(SemaRef, Stack, LCDecl, IsInitializer, 6356 DepDecl); 6357 if (LoopStmtChecker.Visit(S)) { 6358 DepDecl = LoopStmtChecker.getDepDecl(); 6359 return LoopStmtChecker.getBaseLoopId(); 6360 } 6361 return llvm::None; 6362 } 6363 6364 bool OpenMPIterationSpaceChecker::checkAndSetInit(Stmt *S, bool EmitDiags) { 6365 // Check init-expr for canonical loop form and save loop counter 6366 // variable - #Var and its initialization value - #LB. 6367 // OpenMP [2.6] Canonical loop form. init-expr may be one of the following: 6368 // var = lb 6369 // integer-type var = lb 6370 // random-access-iterator-type var = lb 6371 // pointer-type var = lb 6372 // 6373 if (!S) { 6374 if (EmitDiags) { 6375 SemaRef.Diag(DefaultLoc, diag::err_omp_loop_not_canonical_init); 6376 } 6377 return true; 6378 } 6379 if (auto *ExprTemp = dyn_cast<ExprWithCleanups>(S)) 6380 if (!ExprTemp->cleanupsHaveSideEffects()) 6381 S = ExprTemp->getSubExpr(); 6382 6383 InitSrcRange = S->getSourceRange(); 6384 if (Expr *E = dyn_cast<Expr>(S)) 6385 S = E->IgnoreParens(); 6386 if (auto *BO = dyn_cast<BinaryOperator>(S)) { 6387 if (BO->getOpcode() == BO_Assign) { 6388 Expr *LHS = BO->getLHS()->IgnoreParens(); 6389 if (auto *DRE = dyn_cast<DeclRefExpr>(LHS)) { 6390 if (auto *CED = dyn_cast<OMPCapturedExprDecl>(DRE->getDecl())) 6391 if (auto *ME = dyn_cast<MemberExpr>(getExprAsWritten(CED->getInit()))) 6392 return setLCDeclAndLB(ME->getMemberDecl(), ME, BO->getRHS(), 6393 EmitDiags); 6394 return setLCDeclAndLB(DRE->getDecl(), DRE, BO->getRHS(), EmitDiags); 6395 } 6396 if (auto *ME = dyn_cast<MemberExpr>(LHS)) { 6397 if (ME->isArrow() && 6398 isa<CXXThisExpr>(ME->getBase()->IgnoreParenImpCasts())) 6399 return setLCDeclAndLB(ME->getMemberDecl(), ME, BO->getRHS(), 6400 EmitDiags); 6401 } 6402 } 6403 } else if (auto *DS = dyn_cast<DeclStmt>(S)) { 6404 if (DS->isSingleDecl()) { 6405 if (auto *Var = dyn_cast_or_null<VarDecl>(DS->getSingleDecl())) { 6406 if (Var->hasInit() && !Var->getType()->isReferenceType()) { 6407 // Accept non-canonical init form here but emit ext. warning. 6408 if (Var->getInitStyle() != VarDecl::CInit && EmitDiags) 6409 SemaRef.Diag(S->getBeginLoc(), 6410 diag::ext_omp_loop_not_canonical_init) 6411 << S->getSourceRange(); 6412 return setLCDeclAndLB( 6413 Var, 6414 buildDeclRefExpr(SemaRef, Var, 6415 Var->getType().getNonReferenceType(), 6416 DS->getBeginLoc()), 6417 Var->getInit(), EmitDiags); 6418 } 6419 } 6420 } 6421 } else if (auto *CE = dyn_cast<CXXOperatorCallExpr>(S)) { 6422 if (CE->getOperator() == OO_Equal) { 6423 Expr *LHS = CE->getArg(0); 6424 if (auto *DRE = dyn_cast<DeclRefExpr>(LHS)) { 6425 if (auto *CED = dyn_cast<OMPCapturedExprDecl>(DRE->getDecl())) 6426 if (auto *ME = dyn_cast<MemberExpr>(getExprAsWritten(CED->getInit()))) 6427 return setLCDeclAndLB(ME->getMemberDecl(), ME, BO->getRHS(), 6428 EmitDiags); 6429 return setLCDeclAndLB(DRE->getDecl(), DRE, CE->getArg(1), EmitDiags); 6430 } 6431 if (auto *ME = dyn_cast<MemberExpr>(LHS)) { 6432 if (ME->isArrow() && 6433 isa<CXXThisExpr>(ME->getBase()->IgnoreParenImpCasts())) 6434 return setLCDeclAndLB(ME->getMemberDecl(), ME, BO->getRHS(), 6435 EmitDiags); 6436 } 6437 } 6438 } 6439 6440 if (dependent() || SemaRef.CurContext->isDependentContext()) 6441 return false; 6442 if (EmitDiags) { 6443 SemaRef.Diag(S->getBeginLoc(), diag::err_omp_loop_not_canonical_init) 6444 << S->getSourceRange(); 6445 } 6446 return true; 6447 } 6448 6449 /// Ignore parenthesizes, implicit casts, copy constructor and return the 6450 /// variable (which may be the loop variable) if possible. 6451 static const ValueDecl *getInitLCDecl(const Expr *E) { 6452 if (!E) 6453 return nullptr; 6454 E = getExprAsWritten(E); 6455 if (const auto *CE = dyn_cast_or_null<CXXConstructExpr>(E)) 6456 if (const CXXConstructorDecl *Ctor = CE->getConstructor()) 6457 if ((Ctor->isCopyOrMoveConstructor() || 6458 Ctor->isConvertingConstructor(/*AllowExplicit=*/false)) && 6459 CE->getNumArgs() > 0 && CE->getArg(0) != nullptr) 6460 E = CE->getArg(0)->IgnoreParenImpCasts(); 6461 if (const auto *DRE = dyn_cast_or_null<DeclRefExpr>(E)) { 6462 if (const auto *VD = dyn_cast<VarDecl>(DRE->getDecl())) 6463 return getCanonicalDecl(VD); 6464 } 6465 if (const auto *ME = dyn_cast_or_null<MemberExpr>(E)) 6466 if (ME->isArrow() && isa<CXXThisExpr>(ME->getBase()->IgnoreParenImpCasts())) 6467 return getCanonicalDecl(ME->getMemberDecl()); 6468 return nullptr; 6469 } 6470 6471 bool OpenMPIterationSpaceChecker::checkAndSetCond(Expr *S) { 6472 // Check test-expr for canonical form, save upper-bound UB, flags for 6473 // less/greater and for strict/non-strict comparison. 6474 // OpenMP [2.9] Canonical loop form. Test-expr may be one of the following: 6475 // var relational-op b 6476 // b relational-op var 6477 // 6478 bool IneqCondIsCanonical = SemaRef.getLangOpts().OpenMP >= 50; 6479 if (!S) { 6480 SemaRef.Diag(DefaultLoc, diag::err_omp_loop_not_canonical_cond) 6481 << (IneqCondIsCanonical ? 1 : 0) << LCDecl; 6482 return true; 6483 } 6484 Condition = S; 6485 S = getExprAsWritten(S); 6486 SourceLocation CondLoc = S->getBeginLoc(); 6487 if (auto *BO = dyn_cast<BinaryOperator>(S)) { 6488 if (BO->isRelationalOp()) { 6489 if (getInitLCDecl(BO->getLHS()) == LCDecl) 6490 return setUB(BO->getRHS(), 6491 (BO->getOpcode() == BO_LT || BO->getOpcode() == BO_LE), 6492 (BO->getOpcode() == BO_LT || BO->getOpcode() == BO_GT), 6493 BO->getSourceRange(), BO->getOperatorLoc()); 6494 if (getInitLCDecl(BO->getRHS()) == LCDecl) 6495 return setUB(BO->getLHS(), 6496 (BO->getOpcode() == BO_GT || BO->getOpcode() == BO_GE), 6497 (BO->getOpcode() == BO_LT || BO->getOpcode() == BO_GT), 6498 BO->getSourceRange(), BO->getOperatorLoc()); 6499 } else if (IneqCondIsCanonical && BO->getOpcode() == BO_NE) 6500 return setUB( 6501 getInitLCDecl(BO->getLHS()) == LCDecl ? BO->getRHS() : BO->getLHS(), 6502 /*LessOp=*/llvm::None, 6503 /*StrictOp=*/true, BO->getSourceRange(), BO->getOperatorLoc()); 6504 } else if (auto *CE = dyn_cast<CXXOperatorCallExpr>(S)) { 6505 if (CE->getNumArgs() == 2) { 6506 auto Op = CE->getOperator(); 6507 switch (Op) { 6508 case OO_Greater: 6509 case OO_GreaterEqual: 6510 case OO_Less: 6511 case OO_LessEqual: 6512 if (getInitLCDecl(CE->getArg(0)) == LCDecl) 6513 return setUB(CE->getArg(1), Op == OO_Less || Op == OO_LessEqual, 6514 Op == OO_Less || Op == OO_Greater, CE->getSourceRange(), 6515 CE->getOperatorLoc()); 6516 if (getInitLCDecl(CE->getArg(1)) == LCDecl) 6517 return setUB(CE->getArg(0), Op == OO_Greater || Op == OO_GreaterEqual, 6518 Op == OO_Less || Op == OO_Greater, CE->getSourceRange(), 6519 CE->getOperatorLoc()); 6520 break; 6521 case OO_ExclaimEqual: 6522 if (IneqCondIsCanonical) 6523 return setUB(getInitLCDecl(CE->getArg(0)) == LCDecl ? CE->getArg(1) 6524 : CE->getArg(0), 6525 /*LessOp=*/llvm::None, 6526 /*StrictOp=*/true, CE->getSourceRange(), 6527 CE->getOperatorLoc()); 6528 break; 6529 default: 6530 break; 6531 } 6532 } 6533 } 6534 if (dependent() || SemaRef.CurContext->isDependentContext()) 6535 return false; 6536 SemaRef.Diag(CondLoc, diag::err_omp_loop_not_canonical_cond) 6537 << (IneqCondIsCanonical ? 1 : 0) << S->getSourceRange() << LCDecl; 6538 return true; 6539 } 6540 6541 bool OpenMPIterationSpaceChecker::checkAndSetIncRHS(Expr *RHS) { 6542 // RHS of canonical loop form increment can be: 6543 // var + incr 6544 // incr + var 6545 // var - incr 6546 // 6547 RHS = RHS->IgnoreParenImpCasts(); 6548 if (auto *BO = dyn_cast<BinaryOperator>(RHS)) { 6549 if (BO->isAdditiveOp()) { 6550 bool IsAdd = BO->getOpcode() == BO_Add; 6551 if (getInitLCDecl(BO->getLHS()) == LCDecl) 6552 return setStep(BO->getRHS(), !IsAdd); 6553 if (IsAdd && getInitLCDecl(BO->getRHS()) == LCDecl) 6554 return setStep(BO->getLHS(), /*Subtract=*/false); 6555 } 6556 } else if (auto *CE = dyn_cast<CXXOperatorCallExpr>(RHS)) { 6557 bool IsAdd = CE->getOperator() == OO_Plus; 6558 if ((IsAdd || CE->getOperator() == OO_Minus) && CE->getNumArgs() == 2) { 6559 if (getInitLCDecl(CE->getArg(0)) == LCDecl) 6560 return setStep(CE->getArg(1), !IsAdd); 6561 if (IsAdd && getInitLCDecl(CE->getArg(1)) == LCDecl) 6562 return setStep(CE->getArg(0), /*Subtract=*/false); 6563 } 6564 } 6565 if (dependent() || SemaRef.CurContext->isDependentContext()) 6566 return false; 6567 SemaRef.Diag(RHS->getBeginLoc(), diag::err_omp_loop_not_canonical_incr) 6568 << RHS->getSourceRange() << LCDecl; 6569 return true; 6570 } 6571 6572 bool OpenMPIterationSpaceChecker::checkAndSetInc(Expr *S) { 6573 // Check incr-expr for canonical loop form and return true if it 6574 // does not conform. 6575 // OpenMP [2.6] Canonical loop form. Test-expr may be one of the following: 6576 // ++var 6577 // var++ 6578 // --var 6579 // var-- 6580 // var += incr 6581 // var -= incr 6582 // var = var + incr 6583 // var = incr + var 6584 // var = var - incr 6585 // 6586 if (!S) { 6587 SemaRef.Diag(DefaultLoc, diag::err_omp_loop_not_canonical_incr) << LCDecl; 6588 return true; 6589 } 6590 if (auto *ExprTemp = dyn_cast<ExprWithCleanups>(S)) 6591 if (!ExprTemp->cleanupsHaveSideEffects()) 6592 S = ExprTemp->getSubExpr(); 6593 6594 IncrementSrcRange = S->getSourceRange(); 6595 S = S->IgnoreParens(); 6596 if (auto *UO = dyn_cast<UnaryOperator>(S)) { 6597 if (UO->isIncrementDecrementOp() && 6598 getInitLCDecl(UO->getSubExpr()) == LCDecl) 6599 return setStep(SemaRef 6600 .ActOnIntegerConstant(UO->getBeginLoc(), 6601 (UO->isDecrementOp() ? -1 : 1)) 6602 .get(), 6603 /*Subtract=*/false); 6604 } else if (auto *BO = dyn_cast<BinaryOperator>(S)) { 6605 switch (BO->getOpcode()) { 6606 case BO_AddAssign: 6607 case BO_SubAssign: 6608 if (getInitLCDecl(BO->getLHS()) == LCDecl) 6609 return setStep(BO->getRHS(), BO->getOpcode() == BO_SubAssign); 6610 break; 6611 case BO_Assign: 6612 if (getInitLCDecl(BO->getLHS()) == LCDecl) 6613 return checkAndSetIncRHS(BO->getRHS()); 6614 break; 6615 default: 6616 break; 6617 } 6618 } else if (auto *CE = dyn_cast<CXXOperatorCallExpr>(S)) { 6619 switch (CE->getOperator()) { 6620 case OO_PlusPlus: 6621 case OO_MinusMinus: 6622 if (getInitLCDecl(CE->getArg(0)) == LCDecl) 6623 return setStep(SemaRef 6624 .ActOnIntegerConstant( 6625 CE->getBeginLoc(), 6626 ((CE->getOperator() == OO_MinusMinus) ? -1 : 1)) 6627 .get(), 6628 /*Subtract=*/false); 6629 break; 6630 case OO_PlusEqual: 6631 case OO_MinusEqual: 6632 if (getInitLCDecl(CE->getArg(0)) == LCDecl) 6633 return setStep(CE->getArg(1), CE->getOperator() == OO_MinusEqual); 6634 break; 6635 case OO_Equal: 6636 if (getInitLCDecl(CE->getArg(0)) == LCDecl) 6637 return checkAndSetIncRHS(CE->getArg(1)); 6638 break; 6639 default: 6640 break; 6641 } 6642 } 6643 if (dependent() || SemaRef.CurContext->isDependentContext()) 6644 return false; 6645 SemaRef.Diag(S->getBeginLoc(), diag::err_omp_loop_not_canonical_incr) 6646 << S->getSourceRange() << LCDecl; 6647 return true; 6648 } 6649 6650 static ExprResult 6651 tryBuildCapture(Sema &SemaRef, Expr *Capture, 6652 llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) { 6653 if (SemaRef.CurContext->isDependentContext()) 6654 return ExprResult(Capture); 6655 if (Capture->isEvaluatable(SemaRef.Context, Expr::SE_AllowSideEffects)) 6656 return SemaRef.PerformImplicitConversion( 6657 Capture->IgnoreImpCasts(), Capture->getType(), Sema::AA_Converting, 6658 /*AllowExplicit=*/true); 6659 auto I = Captures.find(Capture); 6660 if (I != Captures.end()) 6661 return buildCapture(SemaRef, Capture, I->second); 6662 DeclRefExpr *Ref = nullptr; 6663 ExprResult Res = buildCapture(SemaRef, Capture, Ref); 6664 Captures[Capture] = Ref; 6665 return Res; 6666 } 6667 6668 /// Build the expression to calculate the number of iterations. 6669 Expr *OpenMPIterationSpaceChecker::buildNumIterations( 6670 Scope *S, ArrayRef<LoopIterationSpace> ResultIterSpaces, bool LimitedType, 6671 llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) const { 6672 ExprResult Diff; 6673 QualType VarType = LCDecl->getType().getNonReferenceType(); 6674 if (VarType->isIntegerType() || VarType->isPointerType() || 6675 SemaRef.getLangOpts().CPlusPlus) { 6676 Expr *LBVal = LB; 6677 Expr *UBVal = UB; 6678 // LB = TestIsLessOp.getValue() ? min(LB(MinVal), LB(MaxVal)) : 6679 // max(LB(MinVal), LB(MaxVal)) 6680 if (InitDependOnLC) { 6681 const LoopIterationSpace &IS = 6682 ResultIterSpaces[ResultIterSpaces.size() - 1 - 6683 InitDependOnLC.getValueOr( 6684 CondDependOnLC.getValueOr(0))]; 6685 if (!IS.MinValue || !IS.MaxValue) 6686 return nullptr; 6687 // OuterVar = Min 6688 ExprResult MinValue = 6689 SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, IS.MinValue); 6690 if (!MinValue.isUsable()) 6691 return nullptr; 6692 6693 ExprResult LBMinVal = SemaRef.BuildBinOp(S, DefaultLoc, BO_Assign, 6694 IS.CounterVar, MinValue.get()); 6695 if (!LBMinVal.isUsable()) 6696 return nullptr; 6697 // OuterVar = Min, LBVal 6698 LBMinVal = 6699 SemaRef.BuildBinOp(S, DefaultLoc, BO_Comma, LBMinVal.get(), LBVal); 6700 if (!LBMinVal.isUsable()) 6701 return nullptr; 6702 // (OuterVar = Min, LBVal) 6703 LBMinVal = SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, LBMinVal.get()); 6704 if (!LBMinVal.isUsable()) 6705 return nullptr; 6706 6707 // OuterVar = Max 6708 ExprResult MaxValue = 6709 SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, IS.MaxValue); 6710 if (!MaxValue.isUsable()) 6711 return nullptr; 6712 6713 ExprResult LBMaxVal = SemaRef.BuildBinOp(S, DefaultLoc, BO_Assign, 6714 IS.CounterVar, MaxValue.get()); 6715 if (!LBMaxVal.isUsable()) 6716 return nullptr; 6717 // OuterVar = Max, LBVal 6718 LBMaxVal = 6719 SemaRef.BuildBinOp(S, DefaultLoc, BO_Comma, LBMaxVal.get(), LBVal); 6720 if (!LBMaxVal.isUsable()) 6721 return nullptr; 6722 // (OuterVar = Max, LBVal) 6723 LBMaxVal = SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, LBMaxVal.get()); 6724 if (!LBMaxVal.isUsable()) 6725 return nullptr; 6726 6727 Expr *LBMin = tryBuildCapture(SemaRef, LBMinVal.get(), Captures).get(); 6728 Expr *LBMax = tryBuildCapture(SemaRef, LBMaxVal.get(), Captures).get(); 6729 if (!LBMin || !LBMax) 6730 return nullptr; 6731 // LB(MinVal) < LB(MaxVal) 6732 ExprResult MinLessMaxRes = 6733 SemaRef.BuildBinOp(S, DefaultLoc, BO_LT, LBMin, LBMax); 6734 if (!MinLessMaxRes.isUsable()) 6735 return nullptr; 6736 Expr *MinLessMax = 6737 tryBuildCapture(SemaRef, MinLessMaxRes.get(), Captures).get(); 6738 if (!MinLessMax) 6739 return nullptr; 6740 if (TestIsLessOp.getValue()) { 6741 // LB(MinVal) < LB(MaxVal) ? LB(MinVal) : LB(MaxVal) - min(LB(MinVal), 6742 // LB(MaxVal)) 6743 ExprResult MinLB = SemaRef.ActOnConditionalOp(DefaultLoc, DefaultLoc, 6744 MinLessMax, LBMin, LBMax); 6745 if (!MinLB.isUsable()) 6746 return nullptr; 6747 LBVal = MinLB.get(); 6748 } else { 6749 // LB(MinVal) < LB(MaxVal) ? LB(MaxVal) : LB(MinVal) - max(LB(MinVal), 6750 // LB(MaxVal)) 6751 ExprResult MaxLB = SemaRef.ActOnConditionalOp(DefaultLoc, DefaultLoc, 6752 MinLessMax, LBMax, LBMin); 6753 if (!MaxLB.isUsable()) 6754 return nullptr; 6755 LBVal = MaxLB.get(); 6756 } 6757 } 6758 // UB = TestIsLessOp.getValue() ? max(UB(MinVal), UB(MaxVal)) : 6759 // min(UB(MinVal), UB(MaxVal)) 6760 if (CondDependOnLC) { 6761 const LoopIterationSpace &IS = 6762 ResultIterSpaces[ResultIterSpaces.size() - 1 - 6763 InitDependOnLC.getValueOr( 6764 CondDependOnLC.getValueOr(0))]; 6765 if (!IS.MinValue || !IS.MaxValue) 6766 return nullptr; 6767 // OuterVar = Min 6768 ExprResult MinValue = 6769 SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, IS.MinValue); 6770 if (!MinValue.isUsable()) 6771 return nullptr; 6772 6773 ExprResult UBMinVal = SemaRef.BuildBinOp(S, DefaultLoc, BO_Assign, 6774 IS.CounterVar, MinValue.get()); 6775 if (!UBMinVal.isUsable()) 6776 return nullptr; 6777 // OuterVar = Min, UBVal 6778 UBMinVal = 6779 SemaRef.BuildBinOp(S, DefaultLoc, BO_Comma, UBMinVal.get(), UBVal); 6780 if (!UBMinVal.isUsable()) 6781 return nullptr; 6782 // (OuterVar = Min, UBVal) 6783 UBMinVal = SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, UBMinVal.get()); 6784 if (!UBMinVal.isUsable()) 6785 return nullptr; 6786 6787 // OuterVar = Max 6788 ExprResult MaxValue = 6789 SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, IS.MaxValue); 6790 if (!MaxValue.isUsable()) 6791 return nullptr; 6792 6793 ExprResult UBMaxVal = SemaRef.BuildBinOp(S, DefaultLoc, BO_Assign, 6794 IS.CounterVar, MaxValue.get()); 6795 if (!UBMaxVal.isUsable()) 6796 return nullptr; 6797 // OuterVar = Max, UBVal 6798 UBMaxVal = 6799 SemaRef.BuildBinOp(S, DefaultLoc, BO_Comma, UBMaxVal.get(), UBVal); 6800 if (!UBMaxVal.isUsable()) 6801 return nullptr; 6802 // (OuterVar = Max, UBVal) 6803 UBMaxVal = SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, UBMaxVal.get()); 6804 if (!UBMaxVal.isUsable()) 6805 return nullptr; 6806 6807 Expr *UBMin = tryBuildCapture(SemaRef, UBMinVal.get(), Captures).get(); 6808 Expr *UBMax = tryBuildCapture(SemaRef, UBMaxVal.get(), Captures).get(); 6809 if (!UBMin || !UBMax) 6810 return nullptr; 6811 // UB(MinVal) > UB(MaxVal) 6812 ExprResult MinGreaterMaxRes = 6813 SemaRef.BuildBinOp(S, DefaultLoc, BO_GT, UBMin, UBMax); 6814 if (!MinGreaterMaxRes.isUsable()) 6815 return nullptr; 6816 Expr *MinGreaterMax = 6817 tryBuildCapture(SemaRef, MinGreaterMaxRes.get(), Captures).get(); 6818 if (!MinGreaterMax) 6819 return nullptr; 6820 if (TestIsLessOp.getValue()) { 6821 // UB(MinVal) > UB(MaxVal) ? UB(MinVal) : UB(MaxVal) - max(UB(MinVal), 6822 // UB(MaxVal)) 6823 ExprResult MaxUB = SemaRef.ActOnConditionalOp( 6824 DefaultLoc, DefaultLoc, MinGreaterMax, UBMin, UBMax); 6825 if (!MaxUB.isUsable()) 6826 return nullptr; 6827 UBVal = MaxUB.get(); 6828 } else { 6829 // UB(MinVal) > UB(MaxVal) ? UB(MaxVal) : UB(MinVal) - min(UB(MinVal), 6830 // UB(MaxVal)) 6831 ExprResult MinUB = SemaRef.ActOnConditionalOp( 6832 DefaultLoc, DefaultLoc, MinGreaterMax, UBMax, UBMin); 6833 if (!MinUB.isUsable()) 6834 return nullptr; 6835 UBVal = MinUB.get(); 6836 } 6837 } 6838 // Upper - Lower 6839 Expr *UBExpr = TestIsLessOp.getValue() ? UBVal : LBVal; 6840 Expr *LBExpr = TestIsLessOp.getValue() ? LBVal : UBVal; 6841 Expr *Upper = tryBuildCapture(SemaRef, UBExpr, Captures).get(); 6842 Expr *Lower = tryBuildCapture(SemaRef, LBExpr, Captures).get(); 6843 if (!Upper || !Lower) 6844 return nullptr; 6845 6846 Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Sub, Upper, Lower); 6847 6848 if (!Diff.isUsable() && VarType->getAsCXXRecordDecl()) { 6849 // BuildBinOp already emitted error, this one is to point user to upper 6850 // and lower bound, and to tell what is passed to 'operator-'. 6851 SemaRef.Diag(Upper->getBeginLoc(), diag::err_omp_loop_diff_cxx) 6852 << Upper->getSourceRange() << Lower->getSourceRange(); 6853 return nullptr; 6854 } 6855 } 6856 6857 if (!Diff.isUsable()) 6858 return nullptr; 6859 6860 // Upper - Lower [- 1] 6861 if (TestIsStrictOp) 6862 Diff = SemaRef.BuildBinOp( 6863 S, DefaultLoc, BO_Sub, Diff.get(), 6864 SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get()); 6865 if (!Diff.isUsable()) 6866 return nullptr; 6867 6868 // Upper - Lower [- 1] + Step 6869 ExprResult NewStep = tryBuildCapture(SemaRef, Step, Captures); 6870 if (!NewStep.isUsable()) 6871 return nullptr; 6872 Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Add, Diff.get(), NewStep.get()); 6873 if (!Diff.isUsable()) 6874 return nullptr; 6875 6876 // Parentheses (for dumping/debugging purposes only). 6877 Diff = SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, Diff.get()); 6878 if (!Diff.isUsable()) 6879 return nullptr; 6880 6881 // (Upper - Lower [- 1] + Step) / Step 6882 Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Div, Diff.get(), NewStep.get()); 6883 if (!Diff.isUsable()) 6884 return nullptr; 6885 6886 // OpenMP runtime requires 32-bit or 64-bit loop variables. 6887 QualType Type = Diff.get()->getType(); 6888 ASTContext &C = SemaRef.Context; 6889 bool UseVarType = VarType->hasIntegerRepresentation() && 6890 C.getTypeSize(Type) > C.getTypeSize(VarType); 6891 if (!Type->isIntegerType() || UseVarType) { 6892 unsigned NewSize = 6893 UseVarType ? C.getTypeSize(VarType) : C.getTypeSize(Type); 6894 bool IsSigned = UseVarType ? VarType->hasSignedIntegerRepresentation() 6895 : Type->hasSignedIntegerRepresentation(); 6896 Type = C.getIntTypeForBitwidth(NewSize, IsSigned); 6897 if (!SemaRef.Context.hasSameType(Diff.get()->getType(), Type)) { 6898 Diff = SemaRef.PerformImplicitConversion( 6899 Diff.get(), Type, Sema::AA_Converting, /*AllowExplicit=*/true); 6900 if (!Diff.isUsable()) 6901 return nullptr; 6902 } 6903 } 6904 if (LimitedType) { 6905 unsigned NewSize = (C.getTypeSize(Type) > 32) ? 64 : 32; 6906 if (NewSize != C.getTypeSize(Type)) { 6907 if (NewSize < C.getTypeSize(Type)) { 6908 assert(NewSize == 64 && "incorrect loop var size"); 6909 SemaRef.Diag(DefaultLoc, diag::warn_omp_loop_64_bit_var) 6910 << InitSrcRange << ConditionSrcRange; 6911 } 6912 QualType NewType = C.getIntTypeForBitwidth( 6913 NewSize, Type->hasSignedIntegerRepresentation() || 6914 C.getTypeSize(Type) < NewSize); 6915 if (!SemaRef.Context.hasSameType(Diff.get()->getType(), NewType)) { 6916 Diff = SemaRef.PerformImplicitConversion(Diff.get(), NewType, 6917 Sema::AA_Converting, true); 6918 if (!Diff.isUsable()) 6919 return nullptr; 6920 } 6921 } 6922 } 6923 6924 return Diff.get(); 6925 } 6926 6927 std::pair<Expr *, Expr *> OpenMPIterationSpaceChecker::buildMinMaxValues( 6928 Scope *S, llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) const { 6929 // Do not build for iterators, they cannot be used in non-rectangular loop 6930 // nests. 6931 if (LCDecl->getType()->isRecordType()) 6932 return std::make_pair(nullptr, nullptr); 6933 // If we subtract, the min is in the condition, otherwise the min is in the 6934 // init value. 6935 Expr *MinExpr = nullptr; 6936 Expr *MaxExpr = nullptr; 6937 Expr *LBExpr = TestIsLessOp.getValue() ? LB : UB; 6938 Expr *UBExpr = TestIsLessOp.getValue() ? UB : LB; 6939 bool LBNonRect = TestIsLessOp.getValue() ? InitDependOnLC.hasValue() 6940 : CondDependOnLC.hasValue(); 6941 bool UBNonRect = TestIsLessOp.getValue() ? CondDependOnLC.hasValue() 6942 : InitDependOnLC.hasValue(); 6943 Expr *Lower = 6944 LBNonRect ? LBExpr : tryBuildCapture(SemaRef, LBExpr, Captures).get(); 6945 Expr *Upper = 6946 UBNonRect ? UBExpr : tryBuildCapture(SemaRef, UBExpr, Captures).get(); 6947 if (!Upper || !Lower) 6948 return std::make_pair(nullptr, nullptr); 6949 6950 if (TestIsLessOp.getValue()) 6951 MinExpr = Lower; 6952 else 6953 MaxExpr = Upper; 6954 6955 // Build minimum/maximum value based on number of iterations. 6956 ExprResult Diff; 6957 QualType VarType = LCDecl->getType().getNonReferenceType(); 6958 6959 Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Sub, Upper, Lower); 6960 if (!Diff.isUsable()) 6961 return std::make_pair(nullptr, nullptr); 6962 6963 // Upper - Lower [- 1] 6964 if (TestIsStrictOp) 6965 Diff = SemaRef.BuildBinOp( 6966 S, DefaultLoc, BO_Sub, Diff.get(), 6967 SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get()); 6968 if (!Diff.isUsable()) 6969 return std::make_pair(nullptr, nullptr); 6970 6971 // Upper - Lower [- 1] + Step 6972 ExprResult NewStep = tryBuildCapture(SemaRef, Step, Captures); 6973 if (!NewStep.isUsable()) 6974 return std::make_pair(nullptr, nullptr); 6975 6976 // Parentheses (for dumping/debugging purposes only). 6977 Diff = SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, Diff.get()); 6978 if (!Diff.isUsable()) 6979 return std::make_pair(nullptr, nullptr); 6980 6981 // (Upper - Lower [- 1]) / Step 6982 Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Div, Diff.get(), NewStep.get()); 6983 if (!Diff.isUsable()) 6984 return std::make_pair(nullptr, nullptr); 6985 6986 // ((Upper - Lower [- 1]) / Step) * Step 6987 // Parentheses (for dumping/debugging purposes only). 6988 Diff = SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, Diff.get()); 6989 if (!Diff.isUsable()) 6990 return std::make_pair(nullptr, nullptr); 6991 6992 Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Mul, Diff.get(), NewStep.get()); 6993 if (!Diff.isUsable()) 6994 return std::make_pair(nullptr, nullptr); 6995 6996 // Convert to the original type or ptrdiff_t, if original type is pointer. 6997 if (!VarType->isAnyPointerType() && 6998 !SemaRef.Context.hasSameType(Diff.get()->getType(), VarType)) { 6999 Diff = SemaRef.PerformImplicitConversion( 7000 Diff.get(), VarType, Sema::AA_Converting, /*AllowExplicit=*/true); 7001 } else if (VarType->isAnyPointerType() && 7002 !SemaRef.Context.hasSameType( 7003 Diff.get()->getType(), 7004 SemaRef.Context.getUnsignedPointerDiffType())) { 7005 Diff = SemaRef.PerformImplicitConversion( 7006 Diff.get(), SemaRef.Context.getUnsignedPointerDiffType(), 7007 Sema::AA_Converting, /*AllowExplicit=*/true); 7008 } 7009 if (!Diff.isUsable()) 7010 return std::make_pair(nullptr, nullptr); 7011 7012 // Parentheses (for dumping/debugging purposes only). 7013 Diff = SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, Diff.get()); 7014 if (!Diff.isUsable()) 7015 return std::make_pair(nullptr, nullptr); 7016 7017 if (TestIsLessOp.getValue()) { 7018 // MinExpr = Lower; 7019 // MaxExpr = Lower + (((Upper - Lower [- 1]) / Step) * Step) 7020 Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Add, Lower, Diff.get()); 7021 if (!Diff.isUsable()) 7022 return std::make_pair(nullptr, nullptr); 7023 Diff = SemaRef.ActOnFinishFullExpr(Diff.get(), /*DiscardedValue*/ false); 7024 if (!Diff.isUsable()) 7025 return std::make_pair(nullptr, nullptr); 7026 MaxExpr = Diff.get(); 7027 } else { 7028 // MaxExpr = Upper; 7029 // MinExpr = Upper - (((Upper - Lower [- 1]) / Step) * Step) 7030 Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Sub, Upper, Diff.get()); 7031 if (!Diff.isUsable()) 7032 return std::make_pair(nullptr, nullptr); 7033 Diff = SemaRef.ActOnFinishFullExpr(Diff.get(), /*DiscardedValue*/ false); 7034 if (!Diff.isUsable()) 7035 return std::make_pair(nullptr, nullptr); 7036 MinExpr = Diff.get(); 7037 } 7038 7039 return std::make_pair(MinExpr, MaxExpr); 7040 } 7041 7042 Expr *OpenMPIterationSpaceChecker::buildFinalCondition(Scope *S) const { 7043 if (InitDependOnLC || CondDependOnLC) 7044 return Condition; 7045 return nullptr; 7046 } 7047 7048 Expr *OpenMPIterationSpaceChecker::buildPreCond( 7049 Scope *S, Expr *Cond, 7050 llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) const { 7051 // Do not build a precondition when the condition/initialization is dependent 7052 // to prevent pessimistic early loop exit. 7053 // TODO: this can be improved by calculating min/max values but not sure that 7054 // it will be very effective. 7055 if (CondDependOnLC || InitDependOnLC) 7056 return SemaRef.PerformImplicitConversion( 7057 SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get(), 7058 SemaRef.Context.BoolTy, /*Action=*/Sema::AA_Casting, 7059 /*AllowExplicit=*/true).get(); 7060 7061 // Try to build LB <op> UB, where <op> is <, >, <=, or >=. 7062 Sema::TentativeAnalysisScope Trap(SemaRef); 7063 7064 ExprResult NewLB = tryBuildCapture(SemaRef, LB, Captures); 7065 ExprResult NewUB = tryBuildCapture(SemaRef, UB, Captures); 7066 if (!NewLB.isUsable() || !NewUB.isUsable()) 7067 return nullptr; 7068 7069 ExprResult CondExpr = 7070 SemaRef.BuildBinOp(S, DefaultLoc, 7071 TestIsLessOp.getValue() ? 7072 (TestIsStrictOp ? BO_LT : BO_LE) : 7073 (TestIsStrictOp ? BO_GT : BO_GE), 7074 NewLB.get(), NewUB.get()); 7075 if (CondExpr.isUsable()) { 7076 if (!SemaRef.Context.hasSameUnqualifiedType(CondExpr.get()->getType(), 7077 SemaRef.Context.BoolTy)) 7078 CondExpr = SemaRef.PerformImplicitConversion( 7079 CondExpr.get(), SemaRef.Context.BoolTy, /*Action=*/Sema::AA_Casting, 7080 /*AllowExplicit=*/true); 7081 } 7082 7083 // Otherwise use original loop condition and evaluate it in runtime. 7084 return CondExpr.isUsable() ? CondExpr.get() : Cond; 7085 } 7086 7087 /// Build reference expression to the counter be used for codegen. 7088 DeclRefExpr *OpenMPIterationSpaceChecker::buildCounterVar( 7089 llvm::MapVector<const Expr *, DeclRefExpr *> &Captures, 7090 DSAStackTy &DSA) const { 7091 auto *VD = dyn_cast<VarDecl>(LCDecl); 7092 if (!VD) { 7093 VD = SemaRef.isOpenMPCapturedDecl(LCDecl); 7094 DeclRefExpr *Ref = buildDeclRefExpr( 7095 SemaRef, VD, VD->getType().getNonReferenceType(), DefaultLoc); 7096 const DSAStackTy::DSAVarData Data = 7097 DSA.getTopDSA(LCDecl, /*FromParent=*/false); 7098 // If the loop control decl is explicitly marked as private, do not mark it 7099 // as captured again. 7100 if (!isOpenMPPrivate(Data.CKind) || !Data.RefExpr) 7101 Captures.insert(std::make_pair(LCRef, Ref)); 7102 return Ref; 7103 } 7104 return cast<DeclRefExpr>(LCRef); 7105 } 7106 7107 Expr *OpenMPIterationSpaceChecker::buildPrivateCounterVar() const { 7108 if (LCDecl && !LCDecl->isInvalidDecl()) { 7109 QualType Type = LCDecl->getType().getNonReferenceType(); 7110 VarDecl *PrivateVar = buildVarDecl( 7111 SemaRef, DefaultLoc, Type, LCDecl->getName(), 7112 LCDecl->hasAttrs() ? &LCDecl->getAttrs() : nullptr, 7113 isa<VarDecl>(LCDecl) 7114 ? buildDeclRefExpr(SemaRef, cast<VarDecl>(LCDecl), Type, DefaultLoc) 7115 : nullptr); 7116 if (PrivateVar->isInvalidDecl()) 7117 return nullptr; 7118 return buildDeclRefExpr(SemaRef, PrivateVar, Type, DefaultLoc); 7119 } 7120 return nullptr; 7121 } 7122 7123 /// Build initialization of the counter to be used for codegen. 7124 Expr *OpenMPIterationSpaceChecker::buildCounterInit() const { return LB; } 7125 7126 /// Build step of the counter be used for codegen. 7127 Expr *OpenMPIterationSpaceChecker::buildCounterStep() const { return Step; } 7128 7129 Expr *OpenMPIterationSpaceChecker::buildOrderedLoopData( 7130 Scope *S, Expr *Counter, 7131 llvm::MapVector<const Expr *, DeclRefExpr *> &Captures, SourceLocation Loc, 7132 Expr *Inc, OverloadedOperatorKind OOK) { 7133 Expr *Cnt = SemaRef.DefaultLvalueConversion(Counter).get(); 7134 if (!Cnt) 7135 return nullptr; 7136 if (Inc) { 7137 assert((OOK == OO_Plus || OOK == OO_Minus) && 7138 "Expected only + or - operations for depend clauses."); 7139 BinaryOperatorKind BOK = (OOK == OO_Plus) ? BO_Add : BO_Sub; 7140 Cnt = SemaRef.BuildBinOp(S, Loc, BOK, Cnt, Inc).get(); 7141 if (!Cnt) 7142 return nullptr; 7143 } 7144 ExprResult Diff; 7145 QualType VarType = LCDecl->getType().getNonReferenceType(); 7146 if (VarType->isIntegerType() || VarType->isPointerType() || 7147 SemaRef.getLangOpts().CPlusPlus) { 7148 // Upper - Lower 7149 Expr *Upper = TestIsLessOp.getValue() 7150 ? Cnt 7151 : tryBuildCapture(SemaRef, LB, Captures).get(); 7152 Expr *Lower = TestIsLessOp.getValue() 7153 ? tryBuildCapture(SemaRef, LB, Captures).get() 7154 : Cnt; 7155 if (!Upper || !Lower) 7156 return nullptr; 7157 7158 Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Sub, Upper, Lower); 7159 7160 if (!Diff.isUsable() && VarType->getAsCXXRecordDecl()) { 7161 // BuildBinOp already emitted error, this one is to point user to upper 7162 // and lower bound, and to tell what is passed to 'operator-'. 7163 SemaRef.Diag(Upper->getBeginLoc(), diag::err_omp_loop_diff_cxx) 7164 << Upper->getSourceRange() << Lower->getSourceRange(); 7165 return nullptr; 7166 } 7167 } 7168 7169 if (!Diff.isUsable()) 7170 return nullptr; 7171 7172 // Parentheses (for dumping/debugging purposes only). 7173 Diff = SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, Diff.get()); 7174 if (!Diff.isUsable()) 7175 return nullptr; 7176 7177 ExprResult NewStep = tryBuildCapture(SemaRef, Step, Captures); 7178 if (!NewStep.isUsable()) 7179 return nullptr; 7180 // (Upper - Lower) / Step 7181 Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Div, Diff.get(), NewStep.get()); 7182 if (!Diff.isUsable()) 7183 return nullptr; 7184 7185 return Diff.get(); 7186 } 7187 } // namespace 7188 7189 void Sema::ActOnOpenMPLoopInitialization(SourceLocation ForLoc, Stmt *Init) { 7190 assert(getLangOpts().OpenMP && "OpenMP is not active."); 7191 assert(Init && "Expected loop in canonical form."); 7192 unsigned AssociatedLoops = DSAStack->getAssociatedLoops(); 7193 if (AssociatedLoops > 0 && 7194 isOpenMPLoopDirective(DSAStack->getCurrentDirective())) { 7195 DSAStack->loopStart(); 7196 OpenMPIterationSpaceChecker ISC(*this, *DSAStack, ForLoc); 7197 if (!ISC.checkAndSetInit(Init, /*EmitDiags=*/false)) { 7198 if (ValueDecl *D = ISC.getLoopDecl()) { 7199 auto *VD = dyn_cast<VarDecl>(D); 7200 DeclRefExpr *PrivateRef = nullptr; 7201 if (!VD) { 7202 if (VarDecl *Private = isOpenMPCapturedDecl(D)) { 7203 VD = Private; 7204 } else { 7205 PrivateRef = buildCapture(*this, D, ISC.getLoopDeclRefExpr(), 7206 /*WithInit=*/false); 7207 VD = cast<VarDecl>(PrivateRef->getDecl()); 7208 } 7209 } 7210 DSAStack->addLoopControlVariable(D, VD); 7211 const Decl *LD = DSAStack->getPossiblyLoopCunter(); 7212 if (LD != D->getCanonicalDecl()) { 7213 DSAStack->resetPossibleLoopCounter(); 7214 if (auto *Var = dyn_cast_or_null<VarDecl>(LD)) 7215 MarkDeclarationsReferencedInExpr( 7216 buildDeclRefExpr(*this, const_cast<VarDecl *>(Var), 7217 Var->getType().getNonLValueExprType(Context), 7218 ForLoc, /*RefersToCapture=*/true)); 7219 } 7220 OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective(); 7221 // OpenMP [2.14.1.1, Data-sharing Attribute Rules for Variables 7222 // Referenced in a Construct, C/C++]. The loop iteration variable in the 7223 // associated for-loop of a simd construct with just one associated 7224 // for-loop may be listed in a linear clause with a constant-linear-step 7225 // that is the increment of the associated for-loop. The loop iteration 7226 // variable(s) in the associated for-loop(s) of a for or parallel for 7227 // construct may be listed in a private or lastprivate clause. 7228 DSAStackTy::DSAVarData DVar = 7229 DSAStack->getTopDSA(D, /*FromParent=*/false); 7230 // If LoopVarRefExpr is nullptr it means the corresponding loop variable 7231 // is declared in the loop and it is predetermined as a private. 7232 Expr *LoopDeclRefExpr = ISC.getLoopDeclRefExpr(); 7233 OpenMPClauseKind PredeterminedCKind = 7234 isOpenMPSimdDirective(DKind) 7235 ? (DSAStack->hasMutipleLoops() ? OMPC_lastprivate : OMPC_linear) 7236 : OMPC_private; 7237 if (((isOpenMPSimdDirective(DKind) && DVar.CKind != OMPC_unknown && 7238 DVar.CKind != PredeterminedCKind && DVar.RefExpr && 7239 (LangOpts.OpenMP <= 45 || (DVar.CKind != OMPC_lastprivate && 7240 DVar.CKind != OMPC_private))) || 7241 ((isOpenMPWorksharingDirective(DKind) || DKind == OMPD_taskloop || 7242 DKind == OMPD_master_taskloop || 7243 DKind == OMPD_parallel_master_taskloop || 7244 isOpenMPDistributeDirective(DKind)) && 7245 !isOpenMPSimdDirective(DKind) && DVar.CKind != OMPC_unknown && 7246 DVar.CKind != OMPC_private && DVar.CKind != OMPC_lastprivate)) && 7247 (DVar.CKind != OMPC_private || DVar.RefExpr)) { 7248 Diag(Init->getBeginLoc(), diag::err_omp_loop_var_dsa) 7249 << getOpenMPClauseName(DVar.CKind) 7250 << getOpenMPDirectiveName(DKind) 7251 << getOpenMPClauseName(PredeterminedCKind); 7252 if (DVar.RefExpr == nullptr) 7253 DVar.CKind = PredeterminedCKind; 7254 reportOriginalDsa(*this, DSAStack, D, DVar, 7255 /*IsLoopIterVar=*/true); 7256 } else if (LoopDeclRefExpr) { 7257 // Make the loop iteration variable private (for worksharing 7258 // constructs), linear (for simd directives with the only one 7259 // associated loop) or lastprivate (for simd directives with several 7260 // collapsed or ordered loops). 7261 if (DVar.CKind == OMPC_unknown) 7262 DSAStack->addDSA(D, LoopDeclRefExpr, PredeterminedCKind, 7263 PrivateRef); 7264 } 7265 } 7266 } 7267 DSAStack->setAssociatedLoops(AssociatedLoops - 1); 7268 } 7269 } 7270 7271 /// Called on a for stmt to check and extract its iteration space 7272 /// for further processing (such as collapsing). 7273 static bool checkOpenMPIterationSpace( 7274 OpenMPDirectiveKind DKind, Stmt *S, Sema &SemaRef, DSAStackTy &DSA, 7275 unsigned CurrentNestedLoopCount, unsigned NestedLoopCount, 7276 unsigned TotalNestedLoopCount, Expr *CollapseLoopCountExpr, 7277 Expr *OrderedLoopCountExpr, 7278 Sema::VarsWithInheritedDSAType &VarsWithImplicitDSA, 7279 llvm::MutableArrayRef<LoopIterationSpace> ResultIterSpaces, 7280 llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) { 7281 // OpenMP [2.9.1, Canonical Loop Form] 7282 // for (init-expr; test-expr; incr-expr) structured-block 7283 // for (range-decl: range-expr) structured-block 7284 auto *For = dyn_cast_or_null<ForStmt>(S); 7285 auto *CXXFor = dyn_cast_or_null<CXXForRangeStmt>(S); 7286 // Ranged for is supported only in OpenMP 5.0. 7287 if (!For && (SemaRef.LangOpts.OpenMP <= 45 || !CXXFor)) { 7288 SemaRef.Diag(S->getBeginLoc(), diag::err_omp_not_for) 7289 << (CollapseLoopCountExpr != nullptr || OrderedLoopCountExpr != nullptr) 7290 << getOpenMPDirectiveName(DKind) << TotalNestedLoopCount 7291 << (CurrentNestedLoopCount > 0) << CurrentNestedLoopCount; 7292 if (TotalNestedLoopCount > 1) { 7293 if (CollapseLoopCountExpr && OrderedLoopCountExpr) 7294 SemaRef.Diag(DSA.getConstructLoc(), 7295 diag::note_omp_collapse_ordered_expr) 7296 << 2 << CollapseLoopCountExpr->getSourceRange() 7297 << OrderedLoopCountExpr->getSourceRange(); 7298 else if (CollapseLoopCountExpr) 7299 SemaRef.Diag(CollapseLoopCountExpr->getExprLoc(), 7300 diag::note_omp_collapse_ordered_expr) 7301 << 0 << CollapseLoopCountExpr->getSourceRange(); 7302 else 7303 SemaRef.Diag(OrderedLoopCountExpr->getExprLoc(), 7304 diag::note_omp_collapse_ordered_expr) 7305 << 1 << OrderedLoopCountExpr->getSourceRange(); 7306 } 7307 return true; 7308 } 7309 assert(((For && For->getBody()) || (CXXFor && CXXFor->getBody())) && 7310 "No loop body."); 7311 7312 OpenMPIterationSpaceChecker ISC(SemaRef, DSA, 7313 For ? For->getForLoc() : CXXFor->getForLoc()); 7314 7315 // Check init. 7316 Stmt *Init = For ? For->getInit() : CXXFor->getBeginStmt(); 7317 if (ISC.checkAndSetInit(Init)) 7318 return true; 7319 7320 bool HasErrors = false; 7321 7322 // Check loop variable's type. 7323 if (ValueDecl *LCDecl = ISC.getLoopDecl()) { 7324 // OpenMP [2.6, Canonical Loop Form] 7325 // Var is one of the following: 7326 // A variable of signed or unsigned integer type. 7327 // For C++, a variable of a random access iterator type. 7328 // For C, a variable of a pointer type. 7329 QualType VarType = LCDecl->getType().getNonReferenceType(); 7330 if (!VarType->isDependentType() && !VarType->isIntegerType() && 7331 !VarType->isPointerType() && 7332 !(SemaRef.getLangOpts().CPlusPlus && VarType->isOverloadableType())) { 7333 SemaRef.Diag(Init->getBeginLoc(), diag::err_omp_loop_variable_type) 7334 << SemaRef.getLangOpts().CPlusPlus; 7335 HasErrors = true; 7336 } 7337 7338 // OpenMP, 2.14.1.1 Data-sharing Attribute Rules for Variables Referenced in 7339 // a Construct 7340 // The loop iteration variable(s) in the associated for-loop(s) of a for or 7341 // parallel for construct is (are) private. 7342 // The loop iteration variable in the associated for-loop of a simd 7343 // construct with just one associated for-loop is linear with a 7344 // constant-linear-step that is the increment of the associated for-loop. 7345 // Exclude loop var from the list of variables with implicitly defined data 7346 // sharing attributes. 7347 VarsWithImplicitDSA.erase(LCDecl); 7348 7349 assert(isOpenMPLoopDirective(DKind) && "DSA for non-loop vars"); 7350 7351 // Check test-expr. 7352 HasErrors |= ISC.checkAndSetCond(For ? For->getCond() : CXXFor->getCond()); 7353 7354 // Check incr-expr. 7355 HasErrors |= ISC.checkAndSetInc(For ? For->getInc() : CXXFor->getInc()); 7356 } 7357 7358 if (ISC.dependent() || SemaRef.CurContext->isDependentContext() || HasErrors) 7359 return HasErrors; 7360 7361 // Build the loop's iteration space representation. 7362 ResultIterSpaces[CurrentNestedLoopCount].PreCond = ISC.buildPreCond( 7363 DSA.getCurScope(), For ? For->getCond() : CXXFor->getCond(), Captures); 7364 ResultIterSpaces[CurrentNestedLoopCount].NumIterations = 7365 ISC.buildNumIterations(DSA.getCurScope(), ResultIterSpaces, 7366 (isOpenMPWorksharingDirective(DKind) || 7367 isOpenMPTaskLoopDirective(DKind) || 7368 isOpenMPDistributeDirective(DKind)), 7369 Captures); 7370 ResultIterSpaces[CurrentNestedLoopCount].CounterVar = 7371 ISC.buildCounterVar(Captures, DSA); 7372 ResultIterSpaces[CurrentNestedLoopCount].PrivateCounterVar = 7373 ISC.buildPrivateCounterVar(); 7374 ResultIterSpaces[CurrentNestedLoopCount].CounterInit = ISC.buildCounterInit(); 7375 ResultIterSpaces[CurrentNestedLoopCount].CounterStep = ISC.buildCounterStep(); 7376 ResultIterSpaces[CurrentNestedLoopCount].InitSrcRange = ISC.getInitSrcRange(); 7377 ResultIterSpaces[CurrentNestedLoopCount].CondSrcRange = 7378 ISC.getConditionSrcRange(); 7379 ResultIterSpaces[CurrentNestedLoopCount].IncSrcRange = 7380 ISC.getIncrementSrcRange(); 7381 ResultIterSpaces[CurrentNestedLoopCount].Subtract = ISC.shouldSubtractStep(); 7382 ResultIterSpaces[CurrentNestedLoopCount].IsStrictCompare = 7383 ISC.isStrictTestOp(); 7384 std::tie(ResultIterSpaces[CurrentNestedLoopCount].MinValue, 7385 ResultIterSpaces[CurrentNestedLoopCount].MaxValue) = 7386 ISC.buildMinMaxValues(DSA.getCurScope(), Captures); 7387 ResultIterSpaces[CurrentNestedLoopCount].FinalCondition = 7388 ISC.buildFinalCondition(DSA.getCurScope()); 7389 ResultIterSpaces[CurrentNestedLoopCount].IsNonRectangularLB = 7390 ISC.doesInitDependOnLC(); 7391 ResultIterSpaces[CurrentNestedLoopCount].IsNonRectangularUB = 7392 ISC.doesCondDependOnLC(); 7393 ResultIterSpaces[CurrentNestedLoopCount].LoopDependentIdx = 7394 ISC.getLoopDependentIdx(); 7395 7396 HasErrors |= 7397 (ResultIterSpaces[CurrentNestedLoopCount].PreCond == nullptr || 7398 ResultIterSpaces[CurrentNestedLoopCount].NumIterations == nullptr || 7399 ResultIterSpaces[CurrentNestedLoopCount].CounterVar == nullptr || 7400 ResultIterSpaces[CurrentNestedLoopCount].PrivateCounterVar == nullptr || 7401 ResultIterSpaces[CurrentNestedLoopCount].CounterInit == nullptr || 7402 ResultIterSpaces[CurrentNestedLoopCount].CounterStep == nullptr); 7403 if (!HasErrors && DSA.isOrderedRegion()) { 7404 if (DSA.getOrderedRegionParam().second->getNumForLoops()) { 7405 if (CurrentNestedLoopCount < 7406 DSA.getOrderedRegionParam().second->getLoopNumIterations().size()) { 7407 DSA.getOrderedRegionParam().second->setLoopNumIterations( 7408 CurrentNestedLoopCount, 7409 ResultIterSpaces[CurrentNestedLoopCount].NumIterations); 7410 DSA.getOrderedRegionParam().second->setLoopCounter( 7411 CurrentNestedLoopCount, 7412 ResultIterSpaces[CurrentNestedLoopCount].CounterVar); 7413 } 7414 } 7415 for (auto &Pair : DSA.getDoacrossDependClauses()) { 7416 if (CurrentNestedLoopCount >= Pair.first->getNumLoops()) { 7417 // Erroneous case - clause has some problems. 7418 continue; 7419 } 7420 if (Pair.first->getDependencyKind() == OMPC_DEPEND_sink && 7421 Pair.second.size() <= CurrentNestedLoopCount) { 7422 // Erroneous case - clause has some problems. 7423 Pair.first->setLoopData(CurrentNestedLoopCount, nullptr); 7424 continue; 7425 } 7426 Expr *CntValue; 7427 if (Pair.first->getDependencyKind() == OMPC_DEPEND_source) 7428 CntValue = ISC.buildOrderedLoopData( 7429 DSA.getCurScope(), 7430 ResultIterSpaces[CurrentNestedLoopCount].CounterVar, Captures, 7431 Pair.first->getDependencyLoc()); 7432 else 7433 CntValue = ISC.buildOrderedLoopData( 7434 DSA.getCurScope(), 7435 ResultIterSpaces[CurrentNestedLoopCount].CounterVar, Captures, 7436 Pair.first->getDependencyLoc(), 7437 Pair.second[CurrentNestedLoopCount].first, 7438 Pair.second[CurrentNestedLoopCount].second); 7439 Pair.first->setLoopData(CurrentNestedLoopCount, CntValue); 7440 } 7441 } 7442 7443 return HasErrors; 7444 } 7445 7446 /// Build 'VarRef = Start. 7447 static ExprResult 7448 buildCounterInit(Sema &SemaRef, Scope *S, SourceLocation Loc, ExprResult VarRef, 7449 ExprResult Start, bool IsNonRectangularLB, 7450 llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) { 7451 // Build 'VarRef = Start. 7452 ExprResult NewStart = IsNonRectangularLB 7453 ? Start.get() 7454 : tryBuildCapture(SemaRef, Start.get(), Captures); 7455 if (!NewStart.isUsable()) 7456 return ExprError(); 7457 if (!SemaRef.Context.hasSameType(NewStart.get()->getType(), 7458 VarRef.get()->getType())) { 7459 NewStart = SemaRef.PerformImplicitConversion( 7460 NewStart.get(), VarRef.get()->getType(), Sema::AA_Converting, 7461 /*AllowExplicit=*/true); 7462 if (!NewStart.isUsable()) 7463 return ExprError(); 7464 } 7465 7466 ExprResult Init = 7467 SemaRef.BuildBinOp(S, Loc, BO_Assign, VarRef.get(), NewStart.get()); 7468 return Init; 7469 } 7470 7471 /// Build 'VarRef = Start + Iter * Step'. 7472 static ExprResult buildCounterUpdate( 7473 Sema &SemaRef, Scope *S, SourceLocation Loc, ExprResult VarRef, 7474 ExprResult Start, ExprResult Iter, ExprResult Step, bool Subtract, 7475 bool IsNonRectangularLB, 7476 llvm::MapVector<const Expr *, DeclRefExpr *> *Captures = nullptr) { 7477 // Add parentheses (for debugging purposes only). 7478 Iter = SemaRef.ActOnParenExpr(Loc, Loc, Iter.get()); 7479 if (!VarRef.isUsable() || !Start.isUsable() || !Iter.isUsable() || 7480 !Step.isUsable()) 7481 return ExprError(); 7482 7483 ExprResult NewStep = Step; 7484 if (Captures) 7485 NewStep = tryBuildCapture(SemaRef, Step.get(), *Captures); 7486 if (NewStep.isInvalid()) 7487 return ExprError(); 7488 ExprResult Update = 7489 SemaRef.BuildBinOp(S, Loc, BO_Mul, Iter.get(), NewStep.get()); 7490 if (!Update.isUsable()) 7491 return ExprError(); 7492 7493 // Try to build 'VarRef = Start, VarRef (+|-)= Iter * Step' or 7494 // 'VarRef = Start (+|-) Iter * Step'. 7495 if (!Start.isUsable()) 7496 return ExprError(); 7497 ExprResult NewStart = SemaRef.ActOnParenExpr(Loc, Loc, Start.get()); 7498 if (!NewStart.isUsable()) 7499 return ExprError(); 7500 if (Captures && !IsNonRectangularLB) 7501 NewStart = tryBuildCapture(SemaRef, Start.get(), *Captures); 7502 if (NewStart.isInvalid()) 7503 return ExprError(); 7504 7505 // First attempt: try to build 'VarRef = Start, VarRef += Iter * Step'. 7506 ExprResult SavedUpdate = Update; 7507 ExprResult UpdateVal; 7508 if (VarRef.get()->getType()->isOverloadableType() || 7509 NewStart.get()->getType()->isOverloadableType() || 7510 Update.get()->getType()->isOverloadableType()) { 7511 Sema::TentativeAnalysisScope Trap(SemaRef); 7512 7513 Update = 7514 SemaRef.BuildBinOp(S, Loc, BO_Assign, VarRef.get(), NewStart.get()); 7515 if (Update.isUsable()) { 7516 UpdateVal = 7517 SemaRef.BuildBinOp(S, Loc, Subtract ? BO_SubAssign : BO_AddAssign, 7518 VarRef.get(), SavedUpdate.get()); 7519 if (UpdateVal.isUsable()) { 7520 Update = SemaRef.CreateBuiltinBinOp(Loc, BO_Comma, Update.get(), 7521 UpdateVal.get()); 7522 } 7523 } 7524 } 7525 7526 // Second attempt: try to build 'VarRef = Start (+|-) Iter * Step'. 7527 if (!Update.isUsable() || !UpdateVal.isUsable()) { 7528 Update = SemaRef.BuildBinOp(S, Loc, Subtract ? BO_Sub : BO_Add, 7529 NewStart.get(), SavedUpdate.get()); 7530 if (!Update.isUsable()) 7531 return ExprError(); 7532 7533 if (!SemaRef.Context.hasSameType(Update.get()->getType(), 7534 VarRef.get()->getType())) { 7535 Update = SemaRef.PerformImplicitConversion( 7536 Update.get(), VarRef.get()->getType(), Sema::AA_Converting, true); 7537 if (!Update.isUsable()) 7538 return ExprError(); 7539 } 7540 7541 Update = SemaRef.BuildBinOp(S, Loc, BO_Assign, VarRef.get(), Update.get()); 7542 } 7543 return Update; 7544 } 7545 7546 /// Convert integer expression \a E to make it have at least \a Bits 7547 /// bits. 7548 static ExprResult widenIterationCount(unsigned Bits, Expr *E, Sema &SemaRef) { 7549 if (E == nullptr) 7550 return ExprError(); 7551 ASTContext &C = SemaRef.Context; 7552 QualType OldType = E->getType(); 7553 unsigned HasBits = C.getTypeSize(OldType); 7554 if (HasBits >= Bits) 7555 return ExprResult(E); 7556 // OK to convert to signed, because new type has more bits than old. 7557 QualType NewType = C.getIntTypeForBitwidth(Bits, /* Signed */ true); 7558 return SemaRef.PerformImplicitConversion(E, NewType, Sema::AA_Converting, 7559 true); 7560 } 7561 7562 /// Check if the given expression \a E is a constant integer that fits 7563 /// into \a Bits bits. 7564 static bool fitsInto(unsigned Bits, bool Signed, const Expr *E, Sema &SemaRef) { 7565 if (E == nullptr) 7566 return false; 7567 llvm::APSInt Result; 7568 if (E->isIntegerConstantExpr(Result, SemaRef.Context)) 7569 return Signed ? Result.isSignedIntN(Bits) : Result.isIntN(Bits); 7570 return false; 7571 } 7572 7573 /// Build preinits statement for the given declarations. 7574 static Stmt *buildPreInits(ASTContext &Context, 7575 MutableArrayRef<Decl *> PreInits) { 7576 if (!PreInits.empty()) { 7577 return new (Context) DeclStmt( 7578 DeclGroupRef::Create(Context, PreInits.begin(), PreInits.size()), 7579 SourceLocation(), SourceLocation()); 7580 } 7581 return nullptr; 7582 } 7583 7584 /// Build preinits statement for the given declarations. 7585 static Stmt * 7586 buildPreInits(ASTContext &Context, 7587 const llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) { 7588 if (!Captures.empty()) { 7589 SmallVector<Decl *, 16> PreInits; 7590 for (const auto &Pair : Captures) 7591 PreInits.push_back(Pair.second->getDecl()); 7592 return buildPreInits(Context, PreInits); 7593 } 7594 return nullptr; 7595 } 7596 7597 /// Build postupdate expression for the given list of postupdates expressions. 7598 static Expr *buildPostUpdate(Sema &S, ArrayRef<Expr *> PostUpdates) { 7599 Expr *PostUpdate = nullptr; 7600 if (!PostUpdates.empty()) { 7601 for (Expr *E : PostUpdates) { 7602 Expr *ConvE = S.BuildCStyleCastExpr( 7603 E->getExprLoc(), 7604 S.Context.getTrivialTypeSourceInfo(S.Context.VoidTy), 7605 E->getExprLoc(), E) 7606 .get(); 7607 PostUpdate = PostUpdate 7608 ? S.CreateBuiltinBinOp(ConvE->getExprLoc(), BO_Comma, 7609 PostUpdate, ConvE) 7610 .get() 7611 : ConvE; 7612 } 7613 } 7614 return PostUpdate; 7615 } 7616 7617 /// Called on a for stmt to check itself and nested loops (if any). 7618 /// \return Returns 0 if one of the collapsed stmts is not canonical for loop, 7619 /// number of collapsed loops otherwise. 7620 static unsigned 7621 checkOpenMPLoop(OpenMPDirectiveKind DKind, Expr *CollapseLoopCountExpr, 7622 Expr *OrderedLoopCountExpr, Stmt *AStmt, Sema &SemaRef, 7623 DSAStackTy &DSA, 7624 Sema::VarsWithInheritedDSAType &VarsWithImplicitDSA, 7625 OMPLoopDirective::HelperExprs &Built) { 7626 unsigned NestedLoopCount = 1; 7627 if (CollapseLoopCountExpr) { 7628 // Found 'collapse' clause - calculate collapse number. 7629 Expr::EvalResult Result; 7630 if (!CollapseLoopCountExpr->isValueDependent() && 7631 CollapseLoopCountExpr->EvaluateAsInt(Result, SemaRef.getASTContext())) { 7632 NestedLoopCount = Result.Val.getInt().getLimitedValue(); 7633 } else { 7634 Built.clear(/*Size=*/1); 7635 return 1; 7636 } 7637 } 7638 unsigned OrderedLoopCount = 1; 7639 if (OrderedLoopCountExpr) { 7640 // Found 'ordered' clause - calculate collapse number. 7641 Expr::EvalResult EVResult; 7642 if (!OrderedLoopCountExpr->isValueDependent() && 7643 OrderedLoopCountExpr->EvaluateAsInt(EVResult, 7644 SemaRef.getASTContext())) { 7645 llvm::APSInt Result = EVResult.Val.getInt(); 7646 if (Result.getLimitedValue() < NestedLoopCount) { 7647 SemaRef.Diag(OrderedLoopCountExpr->getExprLoc(), 7648 diag::err_omp_wrong_ordered_loop_count) 7649 << OrderedLoopCountExpr->getSourceRange(); 7650 SemaRef.Diag(CollapseLoopCountExpr->getExprLoc(), 7651 diag::note_collapse_loop_count) 7652 << CollapseLoopCountExpr->getSourceRange(); 7653 } 7654 OrderedLoopCount = Result.getLimitedValue(); 7655 } else { 7656 Built.clear(/*Size=*/1); 7657 return 1; 7658 } 7659 } 7660 // This is helper routine for loop directives (e.g., 'for', 'simd', 7661 // 'for simd', etc.). 7662 llvm::MapVector<const Expr *, DeclRefExpr *> Captures; 7663 SmallVector<LoopIterationSpace, 4> IterSpaces( 7664 std::max(OrderedLoopCount, NestedLoopCount)); 7665 Stmt *CurStmt = AStmt->IgnoreContainers(/* IgnoreCaptured */ true); 7666 for (unsigned Cnt = 0; Cnt < NestedLoopCount; ++Cnt) { 7667 if (checkOpenMPIterationSpace( 7668 DKind, CurStmt, SemaRef, DSA, Cnt, NestedLoopCount, 7669 std::max(OrderedLoopCount, NestedLoopCount), CollapseLoopCountExpr, 7670 OrderedLoopCountExpr, VarsWithImplicitDSA, IterSpaces, Captures)) 7671 return 0; 7672 // Move on to the next nested for loop, or to the loop body. 7673 // OpenMP [2.8.1, simd construct, Restrictions] 7674 // All loops associated with the construct must be perfectly nested; that 7675 // is, there must be no intervening code nor any OpenMP directive between 7676 // any two loops. 7677 if (auto *For = dyn_cast<ForStmt>(CurStmt)) { 7678 CurStmt = For->getBody(); 7679 } else { 7680 assert(isa<CXXForRangeStmt>(CurStmt) && 7681 "Expected canonical for or range-based for loops."); 7682 CurStmt = cast<CXXForRangeStmt>(CurStmt)->getBody(); 7683 } 7684 CurStmt = OMPLoopDirective::tryToFindNextInnerLoop( 7685 CurStmt, SemaRef.LangOpts.OpenMP >= 50); 7686 } 7687 for (unsigned Cnt = NestedLoopCount; Cnt < OrderedLoopCount; ++Cnt) { 7688 if (checkOpenMPIterationSpace( 7689 DKind, CurStmt, SemaRef, DSA, Cnt, NestedLoopCount, 7690 std::max(OrderedLoopCount, NestedLoopCount), CollapseLoopCountExpr, 7691 OrderedLoopCountExpr, VarsWithImplicitDSA, IterSpaces, Captures)) 7692 return 0; 7693 if (Cnt > 0 && IterSpaces[Cnt].CounterVar) { 7694 // Handle initialization of captured loop iterator variables. 7695 auto *DRE = cast<DeclRefExpr>(IterSpaces[Cnt].CounterVar); 7696 if (isa<OMPCapturedExprDecl>(DRE->getDecl())) { 7697 Captures[DRE] = DRE; 7698 } 7699 } 7700 // Move on to the next nested for loop, or to the loop body. 7701 // OpenMP [2.8.1, simd construct, Restrictions] 7702 // All loops associated with the construct must be perfectly nested; that 7703 // is, there must be no intervening code nor any OpenMP directive between 7704 // any two loops. 7705 if (auto *For = dyn_cast<ForStmt>(CurStmt)) { 7706 CurStmt = For->getBody(); 7707 } else { 7708 assert(isa<CXXForRangeStmt>(CurStmt) && 7709 "Expected canonical for or range-based for loops."); 7710 CurStmt = cast<CXXForRangeStmt>(CurStmt)->getBody(); 7711 } 7712 CurStmt = OMPLoopDirective::tryToFindNextInnerLoop( 7713 CurStmt, SemaRef.LangOpts.OpenMP >= 50); 7714 } 7715 7716 Built.clear(/* size */ NestedLoopCount); 7717 7718 if (SemaRef.CurContext->isDependentContext()) 7719 return NestedLoopCount; 7720 7721 // An example of what is generated for the following code: 7722 // 7723 // #pragma omp simd collapse(2) ordered(2) 7724 // for (i = 0; i < NI; ++i) 7725 // for (k = 0; k < NK; ++k) 7726 // for (j = J0; j < NJ; j+=2) { 7727 // <loop body> 7728 // } 7729 // 7730 // We generate the code below. 7731 // Note: the loop body may be outlined in CodeGen. 7732 // Note: some counters may be C++ classes, operator- is used to find number of 7733 // iterations and operator+= to calculate counter value. 7734 // Note: decltype(NumIterations) must be integer type (in 'omp for', only i32 7735 // or i64 is currently supported). 7736 // 7737 // #define NumIterations (NI * ((NJ - J0 - 1 + 2) / 2)) 7738 // for (int[32|64]_t IV = 0; IV < NumIterations; ++IV ) { 7739 // .local.i = IV / ((NJ - J0 - 1 + 2) / 2); 7740 // .local.j = J0 + (IV % ((NJ - J0 - 1 + 2) / 2)) * 2; 7741 // // similar updates for vars in clauses (e.g. 'linear') 7742 // <loop body (using local i and j)> 7743 // } 7744 // i = NI; // assign final values of counters 7745 // j = NJ; 7746 // 7747 7748 // Last iteration number is (I1 * I2 * ... In) - 1, where I1, I2 ... In are 7749 // the iteration counts of the collapsed for loops. 7750 // Precondition tests if there is at least one iteration (all conditions are 7751 // true). 7752 auto PreCond = ExprResult(IterSpaces[0].PreCond); 7753 Expr *N0 = IterSpaces[0].NumIterations; 7754 ExprResult LastIteration32 = 7755 widenIterationCount(/*Bits=*/32, 7756 SemaRef 7757 .PerformImplicitConversion( 7758 N0->IgnoreImpCasts(), N0->getType(), 7759 Sema::AA_Converting, /*AllowExplicit=*/true) 7760 .get(), 7761 SemaRef); 7762 ExprResult LastIteration64 = widenIterationCount( 7763 /*Bits=*/64, 7764 SemaRef 7765 .PerformImplicitConversion(N0->IgnoreImpCasts(), N0->getType(), 7766 Sema::AA_Converting, 7767 /*AllowExplicit=*/true) 7768 .get(), 7769 SemaRef); 7770 7771 if (!LastIteration32.isUsable() || !LastIteration64.isUsable()) 7772 return NestedLoopCount; 7773 7774 ASTContext &C = SemaRef.Context; 7775 bool AllCountsNeedLessThan32Bits = C.getTypeSize(N0->getType()) < 32; 7776 7777 Scope *CurScope = DSA.getCurScope(); 7778 for (unsigned Cnt = 1; Cnt < NestedLoopCount; ++Cnt) { 7779 if (PreCond.isUsable()) { 7780 PreCond = 7781 SemaRef.BuildBinOp(CurScope, PreCond.get()->getExprLoc(), BO_LAnd, 7782 PreCond.get(), IterSpaces[Cnt].PreCond); 7783 } 7784 Expr *N = IterSpaces[Cnt].NumIterations; 7785 SourceLocation Loc = N->getExprLoc(); 7786 AllCountsNeedLessThan32Bits &= C.getTypeSize(N->getType()) < 32; 7787 if (LastIteration32.isUsable()) 7788 LastIteration32 = SemaRef.BuildBinOp( 7789 CurScope, Loc, BO_Mul, LastIteration32.get(), 7790 SemaRef 7791 .PerformImplicitConversion(N->IgnoreImpCasts(), N->getType(), 7792 Sema::AA_Converting, 7793 /*AllowExplicit=*/true) 7794 .get()); 7795 if (LastIteration64.isUsable()) 7796 LastIteration64 = SemaRef.BuildBinOp( 7797 CurScope, Loc, BO_Mul, LastIteration64.get(), 7798 SemaRef 7799 .PerformImplicitConversion(N->IgnoreImpCasts(), N->getType(), 7800 Sema::AA_Converting, 7801 /*AllowExplicit=*/true) 7802 .get()); 7803 } 7804 7805 // Choose either the 32-bit or 64-bit version. 7806 ExprResult LastIteration = LastIteration64; 7807 if (SemaRef.getLangOpts().OpenMPOptimisticCollapse || 7808 (LastIteration32.isUsable() && 7809 C.getTypeSize(LastIteration32.get()->getType()) == 32 && 7810 (AllCountsNeedLessThan32Bits || NestedLoopCount == 1 || 7811 fitsInto( 7812 /*Bits=*/32, 7813 LastIteration32.get()->getType()->hasSignedIntegerRepresentation(), 7814 LastIteration64.get(), SemaRef)))) 7815 LastIteration = LastIteration32; 7816 QualType VType = LastIteration.get()->getType(); 7817 QualType RealVType = VType; 7818 QualType StrideVType = VType; 7819 if (isOpenMPTaskLoopDirective(DKind)) { 7820 VType = 7821 SemaRef.Context.getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/0); 7822 StrideVType = 7823 SemaRef.Context.getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/1); 7824 } 7825 7826 if (!LastIteration.isUsable()) 7827 return 0; 7828 7829 // Save the number of iterations. 7830 ExprResult NumIterations = LastIteration; 7831 { 7832 LastIteration = SemaRef.BuildBinOp( 7833 CurScope, LastIteration.get()->getExprLoc(), BO_Sub, 7834 LastIteration.get(), 7835 SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get()); 7836 if (!LastIteration.isUsable()) 7837 return 0; 7838 } 7839 7840 // Calculate the last iteration number beforehand instead of doing this on 7841 // each iteration. Do not do this if the number of iterations may be kfold-ed. 7842 llvm::APSInt Result; 7843 bool IsConstant = 7844 LastIteration.get()->isIntegerConstantExpr(Result, SemaRef.Context); 7845 ExprResult CalcLastIteration; 7846 if (!IsConstant) { 7847 ExprResult SaveRef = 7848 tryBuildCapture(SemaRef, LastIteration.get(), Captures); 7849 LastIteration = SaveRef; 7850 7851 // Prepare SaveRef + 1. 7852 NumIterations = SemaRef.BuildBinOp( 7853 CurScope, SaveRef.get()->getExprLoc(), BO_Add, SaveRef.get(), 7854 SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get()); 7855 if (!NumIterations.isUsable()) 7856 return 0; 7857 } 7858 7859 SourceLocation InitLoc = IterSpaces[0].InitSrcRange.getBegin(); 7860 7861 // Build variables passed into runtime, necessary for worksharing directives. 7862 ExprResult LB, UB, IL, ST, EUB, CombLB, CombUB, PrevLB, PrevUB, CombEUB; 7863 if (isOpenMPWorksharingDirective(DKind) || isOpenMPTaskLoopDirective(DKind) || 7864 isOpenMPDistributeDirective(DKind)) { 7865 // Lower bound variable, initialized with zero. 7866 VarDecl *LBDecl = buildVarDecl(SemaRef, InitLoc, VType, ".omp.lb"); 7867 LB = buildDeclRefExpr(SemaRef, LBDecl, VType, InitLoc); 7868 SemaRef.AddInitializerToDecl(LBDecl, 7869 SemaRef.ActOnIntegerConstant(InitLoc, 0).get(), 7870 /*DirectInit*/ false); 7871 7872 // Upper bound variable, initialized with last iteration number. 7873 VarDecl *UBDecl = buildVarDecl(SemaRef, InitLoc, VType, ".omp.ub"); 7874 UB = buildDeclRefExpr(SemaRef, UBDecl, VType, InitLoc); 7875 SemaRef.AddInitializerToDecl(UBDecl, LastIteration.get(), 7876 /*DirectInit*/ false); 7877 7878 // A 32-bit variable-flag where runtime returns 1 for the last iteration. 7879 // This will be used to implement clause 'lastprivate'. 7880 QualType Int32Ty = SemaRef.Context.getIntTypeForBitwidth(32, true); 7881 VarDecl *ILDecl = buildVarDecl(SemaRef, InitLoc, Int32Ty, ".omp.is_last"); 7882 IL = buildDeclRefExpr(SemaRef, ILDecl, Int32Ty, InitLoc); 7883 SemaRef.AddInitializerToDecl(ILDecl, 7884 SemaRef.ActOnIntegerConstant(InitLoc, 0).get(), 7885 /*DirectInit*/ false); 7886 7887 // Stride variable returned by runtime (we initialize it to 1 by default). 7888 VarDecl *STDecl = 7889 buildVarDecl(SemaRef, InitLoc, StrideVType, ".omp.stride"); 7890 ST = buildDeclRefExpr(SemaRef, STDecl, StrideVType, InitLoc); 7891 SemaRef.AddInitializerToDecl(STDecl, 7892 SemaRef.ActOnIntegerConstant(InitLoc, 1).get(), 7893 /*DirectInit*/ false); 7894 7895 // Build expression: UB = min(UB, LastIteration) 7896 // It is necessary for CodeGen of directives with static scheduling. 7897 ExprResult IsUBGreater = SemaRef.BuildBinOp(CurScope, InitLoc, BO_GT, 7898 UB.get(), LastIteration.get()); 7899 ExprResult CondOp = SemaRef.ActOnConditionalOp( 7900 LastIteration.get()->getExprLoc(), InitLoc, IsUBGreater.get(), 7901 LastIteration.get(), UB.get()); 7902 EUB = SemaRef.BuildBinOp(CurScope, InitLoc, BO_Assign, UB.get(), 7903 CondOp.get()); 7904 EUB = SemaRef.ActOnFinishFullExpr(EUB.get(), /*DiscardedValue*/ false); 7905 7906 // If we have a combined directive that combines 'distribute', 'for' or 7907 // 'simd' we need to be able to access the bounds of the schedule of the 7908 // enclosing region. E.g. in 'distribute parallel for' the bounds obtained 7909 // by scheduling 'distribute' have to be passed to the schedule of 'for'. 7910 if (isOpenMPLoopBoundSharingDirective(DKind)) { 7911 // Lower bound variable, initialized with zero. 7912 VarDecl *CombLBDecl = 7913 buildVarDecl(SemaRef, InitLoc, VType, ".omp.comb.lb"); 7914 CombLB = buildDeclRefExpr(SemaRef, CombLBDecl, VType, InitLoc); 7915 SemaRef.AddInitializerToDecl( 7916 CombLBDecl, SemaRef.ActOnIntegerConstant(InitLoc, 0).get(), 7917 /*DirectInit*/ false); 7918 7919 // Upper bound variable, initialized with last iteration number. 7920 VarDecl *CombUBDecl = 7921 buildVarDecl(SemaRef, InitLoc, VType, ".omp.comb.ub"); 7922 CombUB = buildDeclRefExpr(SemaRef, CombUBDecl, VType, InitLoc); 7923 SemaRef.AddInitializerToDecl(CombUBDecl, LastIteration.get(), 7924 /*DirectInit*/ false); 7925 7926 ExprResult CombIsUBGreater = SemaRef.BuildBinOp( 7927 CurScope, InitLoc, BO_GT, CombUB.get(), LastIteration.get()); 7928 ExprResult CombCondOp = 7929 SemaRef.ActOnConditionalOp(InitLoc, InitLoc, CombIsUBGreater.get(), 7930 LastIteration.get(), CombUB.get()); 7931 CombEUB = SemaRef.BuildBinOp(CurScope, InitLoc, BO_Assign, CombUB.get(), 7932 CombCondOp.get()); 7933 CombEUB = 7934 SemaRef.ActOnFinishFullExpr(CombEUB.get(), /*DiscardedValue*/ false); 7935 7936 const CapturedDecl *CD = cast<CapturedStmt>(AStmt)->getCapturedDecl(); 7937 // We expect to have at least 2 more parameters than the 'parallel' 7938 // directive does - the lower and upper bounds of the previous schedule. 7939 assert(CD->getNumParams() >= 4 && 7940 "Unexpected number of parameters in loop combined directive"); 7941 7942 // Set the proper type for the bounds given what we learned from the 7943 // enclosed loops. 7944 ImplicitParamDecl *PrevLBDecl = CD->getParam(/*PrevLB=*/2); 7945 ImplicitParamDecl *PrevUBDecl = CD->getParam(/*PrevUB=*/3); 7946 7947 // Previous lower and upper bounds are obtained from the region 7948 // parameters. 7949 PrevLB = 7950 buildDeclRefExpr(SemaRef, PrevLBDecl, PrevLBDecl->getType(), InitLoc); 7951 PrevUB = 7952 buildDeclRefExpr(SemaRef, PrevUBDecl, PrevUBDecl->getType(), InitLoc); 7953 } 7954 } 7955 7956 // Build the iteration variable and its initialization before loop. 7957 ExprResult IV; 7958 ExprResult Init, CombInit; 7959 { 7960 VarDecl *IVDecl = buildVarDecl(SemaRef, InitLoc, RealVType, ".omp.iv"); 7961 IV = buildDeclRefExpr(SemaRef, IVDecl, RealVType, InitLoc); 7962 Expr *RHS = 7963 (isOpenMPWorksharingDirective(DKind) || 7964 isOpenMPTaskLoopDirective(DKind) || isOpenMPDistributeDirective(DKind)) 7965 ? LB.get() 7966 : SemaRef.ActOnIntegerConstant(SourceLocation(), 0).get(); 7967 Init = SemaRef.BuildBinOp(CurScope, InitLoc, BO_Assign, IV.get(), RHS); 7968 Init = SemaRef.ActOnFinishFullExpr(Init.get(), /*DiscardedValue*/ false); 7969 7970 if (isOpenMPLoopBoundSharingDirective(DKind)) { 7971 Expr *CombRHS = 7972 (isOpenMPWorksharingDirective(DKind) || 7973 isOpenMPTaskLoopDirective(DKind) || 7974 isOpenMPDistributeDirective(DKind)) 7975 ? CombLB.get() 7976 : SemaRef.ActOnIntegerConstant(SourceLocation(), 0).get(); 7977 CombInit = 7978 SemaRef.BuildBinOp(CurScope, InitLoc, BO_Assign, IV.get(), CombRHS); 7979 CombInit = 7980 SemaRef.ActOnFinishFullExpr(CombInit.get(), /*DiscardedValue*/ false); 7981 } 7982 } 7983 7984 bool UseStrictCompare = 7985 RealVType->hasUnsignedIntegerRepresentation() && 7986 llvm::all_of(IterSpaces, [](const LoopIterationSpace &LIS) { 7987 return LIS.IsStrictCompare; 7988 }); 7989 // Loop condition (IV < NumIterations) or (IV <= UB or IV < UB + 1 (for 7990 // unsigned IV)) for worksharing loops. 7991 SourceLocation CondLoc = AStmt->getBeginLoc(); 7992 Expr *BoundUB = UB.get(); 7993 if (UseStrictCompare) { 7994 BoundUB = 7995 SemaRef 7996 .BuildBinOp(CurScope, CondLoc, BO_Add, BoundUB, 7997 SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get()) 7998 .get(); 7999 BoundUB = 8000 SemaRef.ActOnFinishFullExpr(BoundUB, /*DiscardedValue*/ false).get(); 8001 } 8002 ExprResult Cond = 8003 (isOpenMPWorksharingDirective(DKind) || 8004 isOpenMPTaskLoopDirective(DKind) || isOpenMPDistributeDirective(DKind)) 8005 ? SemaRef.BuildBinOp(CurScope, CondLoc, 8006 UseStrictCompare ? BO_LT : BO_LE, IV.get(), 8007 BoundUB) 8008 : SemaRef.BuildBinOp(CurScope, CondLoc, BO_LT, IV.get(), 8009 NumIterations.get()); 8010 ExprResult CombDistCond; 8011 if (isOpenMPLoopBoundSharingDirective(DKind)) { 8012 CombDistCond = SemaRef.BuildBinOp(CurScope, CondLoc, BO_LT, IV.get(), 8013 NumIterations.get()); 8014 } 8015 8016 ExprResult CombCond; 8017 if (isOpenMPLoopBoundSharingDirective(DKind)) { 8018 Expr *BoundCombUB = CombUB.get(); 8019 if (UseStrictCompare) { 8020 BoundCombUB = 8021 SemaRef 8022 .BuildBinOp( 8023 CurScope, CondLoc, BO_Add, BoundCombUB, 8024 SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get()) 8025 .get(); 8026 BoundCombUB = 8027 SemaRef.ActOnFinishFullExpr(BoundCombUB, /*DiscardedValue*/ false) 8028 .get(); 8029 } 8030 CombCond = 8031 SemaRef.BuildBinOp(CurScope, CondLoc, UseStrictCompare ? BO_LT : BO_LE, 8032 IV.get(), BoundCombUB); 8033 } 8034 // Loop increment (IV = IV + 1) 8035 SourceLocation IncLoc = AStmt->getBeginLoc(); 8036 ExprResult Inc = 8037 SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, IV.get(), 8038 SemaRef.ActOnIntegerConstant(IncLoc, 1).get()); 8039 if (!Inc.isUsable()) 8040 return 0; 8041 Inc = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, IV.get(), Inc.get()); 8042 Inc = SemaRef.ActOnFinishFullExpr(Inc.get(), /*DiscardedValue*/ false); 8043 if (!Inc.isUsable()) 8044 return 0; 8045 8046 // Increments for worksharing loops (LB = LB + ST; UB = UB + ST). 8047 // Used for directives with static scheduling. 8048 // In combined construct, add combined version that use CombLB and CombUB 8049 // base variables for the update 8050 ExprResult NextLB, NextUB, CombNextLB, CombNextUB; 8051 if (isOpenMPWorksharingDirective(DKind) || isOpenMPTaskLoopDirective(DKind) || 8052 isOpenMPDistributeDirective(DKind)) { 8053 // LB + ST 8054 NextLB = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, LB.get(), ST.get()); 8055 if (!NextLB.isUsable()) 8056 return 0; 8057 // LB = LB + ST 8058 NextLB = 8059 SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, LB.get(), NextLB.get()); 8060 NextLB = 8061 SemaRef.ActOnFinishFullExpr(NextLB.get(), /*DiscardedValue*/ false); 8062 if (!NextLB.isUsable()) 8063 return 0; 8064 // UB + ST 8065 NextUB = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, UB.get(), ST.get()); 8066 if (!NextUB.isUsable()) 8067 return 0; 8068 // UB = UB + ST 8069 NextUB = 8070 SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, UB.get(), NextUB.get()); 8071 NextUB = 8072 SemaRef.ActOnFinishFullExpr(NextUB.get(), /*DiscardedValue*/ false); 8073 if (!NextUB.isUsable()) 8074 return 0; 8075 if (isOpenMPLoopBoundSharingDirective(DKind)) { 8076 CombNextLB = 8077 SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, CombLB.get(), ST.get()); 8078 if (!NextLB.isUsable()) 8079 return 0; 8080 // LB = LB + ST 8081 CombNextLB = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, CombLB.get(), 8082 CombNextLB.get()); 8083 CombNextLB = SemaRef.ActOnFinishFullExpr(CombNextLB.get(), 8084 /*DiscardedValue*/ false); 8085 if (!CombNextLB.isUsable()) 8086 return 0; 8087 // UB + ST 8088 CombNextUB = 8089 SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, CombUB.get(), ST.get()); 8090 if (!CombNextUB.isUsable()) 8091 return 0; 8092 // UB = UB + ST 8093 CombNextUB = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, CombUB.get(), 8094 CombNextUB.get()); 8095 CombNextUB = SemaRef.ActOnFinishFullExpr(CombNextUB.get(), 8096 /*DiscardedValue*/ false); 8097 if (!CombNextUB.isUsable()) 8098 return 0; 8099 } 8100 } 8101 8102 // Create increment expression for distribute loop when combined in a same 8103 // directive with for as IV = IV + ST; ensure upper bound expression based 8104 // on PrevUB instead of NumIterations - used to implement 'for' when found 8105 // in combination with 'distribute', like in 'distribute parallel for' 8106 SourceLocation DistIncLoc = AStmt->getBeginLoc(); 8107 ExprResult DistCond, DistInc, PrevEUB, ParForInDistCond; 8108 if (isOpenMPLoopBoundSharingDirective(DKind)) { 8109 DistCond = SemaRef.BuildBinOp( 8110 CurScope, CondLoc, UseStrictCompare ? BO_LT : BO_LE, IV.get(), BoundUB); 8111 assert(DistCond.isUsable() && "distribute cond expr was not built"); 8112 8113 DistInc = 8114 SemaRef.BuildBinOp(CurScope, DistIncLoc, BO_Add, IV.get(), ST.get()); 8115 assert(DistInc.isUsable() && "distribute inc expr was not built"); 8116 DistInc = SemaRef.BuildBinOp(CurScope, DistIncLoc, BO_Assign, IV.get(), 8117 DistInc.get()); 8118 DistInc = 8119 SemaRef.ActOnFinishFullExpr(DistInc.get(), /*DiscardedValue*/ false); 8120 assert(DistInc.isUsable() && "distribute inc expr was not built"); 8121 8122 // Build expression: UB = min(UB, prevUB) for #for in composite or combined 8123 // construct 8124 SourceLocation DistEUBLoc = AStmt->getBeginLoc(); 8125 ExprResult IsUBGreater = 8126 SemaRef.BuildBinOp(CurScope, DistEUBLoc, BO_GT, UB.get(), PrevUB.get()); 8127 ExprResult CondOp = SemaRef.ActOnConditionalOp( 8128 DistEUBLoc, DistEUBLoc, IsUBGreater.get(), PrevUB.get(), UB.get()); 8129 PrevEUB = SemaRef.BuildBinOp(CurScope, DistIncLoc, BO_Assign, UB.get(), 8130 CondOp.get()); 8131 PrevEUB = 8132 SemaRef.ActOnFinishFullExpr(PrevEUB.get(), /*DiscardedValue*/ false); 8133 8134 // Build IV <= PrevUB or IV < PrevUB + 1 for unsigned IV to be used in 8135 // parallel for is in combination with a distribute directive with 8136 // schedule(static, 1) 8137 Expr *BoundPrevUB = PrevUB.get(); 8138 if (UseStrictCompare) { 8139 BoundPrevUB = 8140 SemaRef 8141 .BuildBinOp( 8142 CurScope, CondLoc, BO_Add, BoundPrevUB, 8143 SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get()) 8144 .get(); 8145 BoundPrevUB = 8146 SemaRef.ActOnFinishFullExpr(BoundPrevUB, /*DiscardedValue*/ false) 8147 .get(); 8148 } 8149 ParForInDistCond = 8150 SemaRef.BuildBinOp(CurScope, CondLoc, UseStrictCompare ? BO_LT : BO_LE, 8151 IV.get(), BoundPrevUB); 8152 } 8153 8154 // Build updates and final values of the loop counters. 8155 bool HasErrors = false; 8156 Built.Counters.resize(NestedLoopCount); 8157 Built.Inits.resize(NestedLoopCount); 8158 Built.Updates.resize(NestedLoopCount); 8159 Built.Finals.resize(NestedLoopCount); 8160 Built.DependentCounters.resize(NestedLoopCount); 8161 Built.DependentInits.resize(NestedLoopCount); 8162 Built.FinalsConditions.resize(NestedLoopCount); 8163 { 8164 // We implement the following algorithm for obtaining the 8165 // original loop iteration variable values based on the 8166 // value of the collapsed loop iteration variable IV. 8167 // 8168 // Let n+1 be the number of collapsed loops in the nest. 8169 // Iteration variables (I0, I1, .... In) 8170 // Iteration counts (N0, N1, ... Nn) 8171 // 8172 // Acc = IV; 8173 // 8174 // To compute Ik for loop k, 0 <= k <= n, generate: 8175 // Prod = N(k+1) * N(k+2) * ... * Nn; 8176 // Ik = Acc / Prod; 8177 // Acc -= Ik * Prod; 8178 // 8179 ExprResult Acc = IV; 8180 for (unsigned int Cnt = 0; Cnt < NestedLoopCount; ++Cnt) { 8181 LoopIterationSpace &IS = IterSpaces[Cnt]; 8182 SourceLocation UpdLoc = IS.IncSrcRange.getBegin(); 8183 ExprResult Iter; 8184 8185 // Compute prod 8186 ExprResult Prod = 8187 SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get(); 8188 for (unsigned int K = Cnt+1; K < NestedLoopCount; ++K) 8189 Prod = SemaRef.BuildBinOp(CurScope, UpdLoc, BO_Mul, Prod.get(), 8190 IterSpaces[K].NumIterations); 8191 8192 // Iter = Acc / Prod 8193 // If there is at least one more inner loop to avoid 8194 // multiplication by 1. 8195 if (Cnt + 1 < NestedLoopCount) 8196 Iter = SemaRef.BuildBinOp(CurScope, UpdLoc, BO_Div, 8197 Acc.get(), Prod.get()); 8198 else 8199 Iter = Acc; 8200 if (!Iter.isUsable()) { 8201 HasErrors = true; 8202 break; 8203 } 8204 8205 // Update Acc: 8206 // Acc -= Iter * Prod 8207 // Check if there is at least one more inner loop to avoid 8208 // multiplication by 1. 8209 if (Cnt + 1 < NestedLoopCount) 8210 Prod = SemaRef.BuildBinOp(CurScope, UpdLoc, BO_Mul, 8211 Iter.get(), Prod.get()); 8212 else 8213 Prod = Iter; 8214 Acc = SemaRef.BuildBinOp(CurScope, UpdLoc, BO_Sub, 8215 Acc.get(), Prod.get()); 8216 8217 // Build update: IS.CounterVar(Private) = IS.Start + Iter * IS.Step 8218 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(IS.CounterVar)->getDecl()); 8219 DeclRefExpr *CounterVar = buildDeclRefExpr( 8220 SemaRef, VD, IS.CounterVar->getType(), IS.CounterVar->getExprLoc(), 8221 /*RefersToCapture=*/true); 8222 ExprResult Init = 8223 buildCounterInit(SemaRef, CurScope, UpdLoc, CounterVar, 8224 IS.CounterInit, IS.IsNonRectangularLB, Captures); 8225 if (!Init.isUsable()) { 8226 HasErrors = true; 8227 break; 8228 } 8229 ExprResult Update = buildCounterUpdate( 8230 SemaRef, CurScope, UpdLoc, CounterVar, IS.CounterInit, Iter, 8231 IS.CounterStep, IS.Subtract, IS.IsNonRectangularLB, &Captures); 8232 if (!Update.isUsable()) { 8233 HasErrors = true; 8234 break; 8235 } 8236 8237 // Build final: IS.CounterVar = IS.Start + IS.NumIters * IS.Step 8238 ExprResult Final = 8239 buildCounterUpdate(SemaRef, CurScope, UpdLoc, CounterVar, 8240 IS.CounterInit, IS.NumIterations, IS.CounterStep, 8241 IS.Subtract, IS.IsNonRectangularLB, &Captures); 8242 if (!Final.isUsable()) { 8243 HasErrors = true; 8244 break; 8245 } 8246 8247 if (!Update.isUsable() || !Final.isUsable()) { 8248 HasErrors = true; 8249 break; 8250 } 8251 // Save results 8252 Built.Counters[Cnt] = IS.CounterVar; 8253 Built.PrivateCounters[Cnt] = IS.PrivateCounterVar; 8254 Built.Inits[Cnt] = Init.get(); 8255 Built.Updates[Cnt] = Update.get(); 8256 Built.Finals[Cnt] = Final.get(); 8257 Built.DependentCounters[Cnt] = nullptr; 8258 Built.DependentInits[Cnt] = nullptr; 8259 Built.FinalsConditions[Cnt] = nullptr; 8260 if (IS.IsNonRectangularLB || IS.IsNonRectangularUB) { 8261 Built.DependentCounters[Cnt] = 8262 Built.Counters[NestedLoopCount - 1 - IS.LoopDependentIdx]; 8263 Built.DependentInits[Cnt] = 8264 Built.Inits[NestedLoopCount - 1 - IS.LoopDependentIdx]; 8265 Built.FinalsConditions[Cnt] = IS.FinalCondition; 8266 } 8267 } 8268 } 8269 8270 if (HasErrors) 8271 return 0; 8272 8273 // Save results 8274 Built.IterationVarRef = IV.get(); 8275 Built.LastIteration = LastIteration.get(); 8276 Built.NumIterations = NumIterations.get(); 8277 Built.CalcLastIteration = SemaRef 8278 .ActOnFinishFullExpr(CalcLastIteration.get(), 8279 /*DiscardedValue=*/false) 8280 .get(); 8281 Built.PreCond = PreCond.get(); 8282 Built.PreInits = buildPreInits(C, Captures); 8283 Built.Cond = Cond.get(); 8284 Built.Init = Init.get(); 8285 Built.Inc = Inc.get(); 8286 Built.LB = LB.get(); 8287 Built.UB = UB.get(); 8288 Built.IL = IL.get(); 8289 Built.ST = ST.get(); 8290 Built.EUB = EUB.get(); 8291 Built.NLB = NextLB.get(); 8292 Built.NUB = NextUB.get(); 8293 Built.PrevLB = PrevLB.get(); 8294 Built.PrevUB = PrevUB.get(); 8295 Built.DistInc = DistInc.get(); 8296 Built.PrevEUB = PrevEUB.get(); 8297 Built.DistCombinedFields.LB = CombLB.get(); 8298 Built.DistCombinedFields.UB = CombUB.get(); 8299 Built.DistCombinedFields.EUB = CombEUB.get(); 8300 Built.DistCombinedFields.Init = CombInit.get(); 8301 Built.DistCombinedFields.Cond = CombCond.get(); 8302 Built.DistCombinedFields.NLB = CombNextLB.get(); 8303 Built.DistCombinedFields.NUB = CombNextUB.get(); 8304 Built.DistCombinedFields.DistCond = CombDistCond.get(); 8305 Built.DistCombinedFields.ParForInDistCond = ParForInDistCond.get(); 8306 8307 return NestedLoopCount; 8308 } 8309 8310 static Expr *getCollapseNumberExpr(ArrayRef<OMPClause *> Clauses) { 8311 auto CollapseClauses = 8312 OMPExecutableDirective::getClausesOfKind<OMPCollapseClause>(Clauses); 8313 if (CollapseClauses.begin() != CollapseClauses.end()) 8314 return (*CollapseClauses.begin())->getNumForLoops(); 8315 return nullptr; 8316 } 8317 8318 static Expr *getOrderedNumberExpr(ArrayRef<OMPClause *> Clauses) { 8319 auto OrderedClauses = 8320 OMPExecutableDirective::getClausesOfKind<OMPOrderedClause>(Clauses); 8321 if (OrderedClauses.begin() != OrderedClauses.end()) 8322 return (*OrderedClauses.begin())->getNumForLoops(); 8323 return nullptr; 8324 } 8325 8326 static bool checkSimdlenSafelenSpecified(Sema &S, 8327 const ArrayRef<OMPClause *> Clauses) { 8328 const OMPSafelenClause *Safelen = nullptr; 8329 const OMPSimdlenClause *Simdlen = nullptr; 8330 8331 for (const OMPClause *Clause : Clauses) { 8332 if (Clause->getClauseKind() == OMPC_safelen) 8333 Safelen = cast<OMPSafelenClause>(Clause); 8334 else if (Clause->getClauseKind() == OMPC_simdlen) 8335 Simdlen = cast<OMPSimdlenClause>(Clause); 8336 if (Safelen && Simdlen) 8337 break; 8338 } 8339 8340 if (Simdlen && Safelen) { 8341 const Expr *SimdlenLength = Simdlen->getSimdlen(); 8342 const Expr *SafelenLength = Safelen->getSafelen(); 8343 if (SimdlenLength->isValueDependent() || SimdlenLength->isTypeDependent() || 8344 SimdlenLength->isInstantiationDependent() || 8345 SimdlenLength->containsUnexpandedParameterPack()) 8346 return false; 8347 if (SafelenLength->isValueDependent() || SafelenLength->isTypeDependent() || 8348 SafelenLength->isInstantiationDependent() || 8349 SafelenLength->containsUnexpandedParameterPack()) 8350 return false; 8351 Expr::EvalResult SimdlenResult, SafelenResult; 8352 SimdlenLength->EvaluateAsInt(SimdlenResult, S.Context); 8353 SafelenLength->EvaluateAsInt(SafelenResult, S.Context); 8354 llvm::APSInt SimdlenRes = SimdlenResult.Val.getInt(); 8355 llvm::APSInt SafelenRes = SafelenResult.Val.getInt(); 8356 // OpenMP 4.5 [2.8.1, simd Construct, Restrictions] 8357 // If both simdlen and safelen clauses are specified, the value of the 8358 // simdlen parameter must be less than or equal to the value of the safelen 8359 // parameter. 8360 if (SimdlenRes > SafelenRes) { 8361 S.Diag(SimdlenLength->getExprLoc(), 8362 diag::err_omp_wrong_simdlen_safelen_values) 8363 << SimdlenLength->getSourceRange() << SafelenLength->getSourceRange(); 8364 return true; 8365 } 8366 } 8367 return false; 8368 } 8369 8370 StmtResult 8371 Sema::ActOnOpenMPSimdDirective(ArrayRef<OMPClause *> Clauses, Stmt *AStmt, 8372 SourceLocation StartLoc, SourceLocation EndLoc, 8373 VarsWithInheritedDSAType &VarsWithImplicitDSA) { 8374 if (!AStmt) 8375 return StmtError(); 8376 8377 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected"); 8378 OMPLoopDirective::HelperExprs B; 8379 // In presence of clause 'collapse' or 'ordered' with number of loops, it will 8380 // define the nested loops number. 8381 unsigned NestedLoopCount = checkOpenMPLoop( 8382 OMPD_simd, getCollapseNumberExpr(Clauses), getOrderedNumberExpr(Clauses), 8383 AStmt, *this, *DSAStack, VarsWithImplicitDSA, B); 8384 if (NestedLoopCount == 0) 8385 return StmtError(); 8386 8387 assert((CurContext->isDependentContext() || B.builtAll()) && 8388 "omp simd loop exprs were not built"); 8389 8390 if (!CurContext->isDependentContext()) { 8391 // Finalize the clauses that need pre-built expressions for CodeGen. 8392 for (OMPClause *C : Clauses) { 8393 if (auto *LC = dyn_cast<OMPLinearClause>(C)) 8394 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef), 8395 B.NumIterations, *this, CurScope, 8396 DSAStack)) 8397 return StmtError(); 8398 } 8399 } 8400 8401 if (checkSimdlenSafelenSpecified(*this, Clauses)) 8402 return StmtError(); 8403 8404 setFunctionHasBranchProtectedScope(); 8405 return OMPSimdDirective::Create(Context, StartLoc, EndLoc, NestedLoopCount, 8406 Clauses, AStmt, B); 8407 } 8408 8409 StmtResult 8410 Sema::ActOnOpenMPForDirective(ArrayRef<OMPClause *> Clauses, Stmt *AStmt, 8411 SourceLocation StartLoc, SourceLocation EndLoc, 8412 VarsWithInheritedDSAType &VarsWithImplicitDSA) { 8413 if (!AStmt) 8414 return StmtError(); 8415 8416 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected"); 8417 OMPLoopDirective::HelperExprs B; 8418 // In presence of clause 'collapse' or 'ordered' with number of loops, it will 8419 // define the nested loops number. 8420 unsigned NestedLoopCount = checkOpenMPLoop( 8421 OMPD_for, getCollapseNumberExpr(Clauses), getOrderedNumberExpr(Clauses), 8422 AStmt, *this, *DSAStack, VarsWithImplicitDSA, B); 8423 if (NestedLoopCount == 0) 8424 return StmtError(); 8425 8426 assert((CurContext->isDependentContext() || B.builtAll()) && 8427 "omp for loop exprs were not built"); 8428 8429 if (!CurContext->isDependentContext()) { 8430 // Finalize the clauses that need pre-built expressions for CodeGen. 8431 for (OMPClause *C : Clauses) { 8432 if (auto *LC = dyn_cast<OMPLinearClause>(C)) 8433 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef), 8434 B.NumIterations, *this, CurScope, 8435 DSAStack)) 8436 return StmtError(); 8437 } 8438 } 8439 8440 setFunctionHasBranchProtectedScope(); 8441 return OMPForDirective::Create(Context, StartLoc, EndLoc, NestedLoopCount, 8442 Clauses, AStmt, B, DSAStack->isCancelRegion()); 8443 } 8444 8445 StmtResult Sema::ActOnOpenMPForSimdDirective( 8446 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, 8447 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) { 8448 if (!AStmt) 8449 return StmtError(); 8450 8451 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected"); 8452 OMPLoopDirective::HelperExprs B; 8453 // In presence of clause 'collapse' or 'ordered' with number of loops, it will 8454 // define the nested loops number. 8455 unsigned NestedLoopCount = 8456 checkOpenMPLoop(OMPD_for_simd, getCollapseNumberExpr(Clauses), 8457 getOrderedNumberExpr(Clauses), AStmt, *this, *DSAStack, 8458 VarsWithImplicitDSA, B); 8459 if (NestedLoopCount == 0) 8460 return StmtError(); 8461 8462 assert((CurContext->isDependentContext() || B.builtAll()) && 8463 "omp for simd loop exprs were not built"); 8464 8465 if (!CurContext->isDependentContext()) { 8466 // Finalize the clauses that need pre-built expressions for CodeGen. 8467 for (OMPClause *C : Clauses) { 8468 if (auto *LC = dyn_cast<OMPLinearClause>(C)) 8469 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef), 8470 B.NumIterations, *this, CurScope, 8471 DSAStack)) 8472 return StmtError(); 8473 } 8474 } 8475 8476 if (checkSimdlenSafelenSpecified(*this, Clauses)) 8477 return StmtError(); 8478 8479 setFunctionHasBranchProtectedScope(); 8480 return OMPForSimdDirective::Create(Context, StartLoc, EndLoc, NestedLoopCount, 8481 Clauses, AStmt, B); 8482 } 8483 8484 StmtResult Sema::ActOnOpenMPSectionsDirective(ArrayRef<OMPClause *> Clauses, 8485 Stmt *AStmt, 8486 SourceLocation StartLoc, 8487 SourceLocation EndLoc) { 8488 if (!AStmt) 8489 return StmtError(); 8490 8491 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected"); 8492 auto BaseStmt = AStmt; 8493 while (auto *CS = dyn_cast_or_null<CapturedStmt>(BaseStmt)) 8494 BaseStmt = CS->getCapturedStmt(); 8495 if (auto *C = dyn_cast_or_null<CompoundStmt>(BaseStmt)) { 8496 auto S = C->children(); 8497 if (S.begin() == S.end()) 8498 return StmtError(); 8499 // All associated statements must be '#pragma omp section' except for 8500 // the first one. 8501 for (Stmt *SectionStmt : llvm::make_range(std::next(S.begin()), S.end())) { 8502 if (!SectionStmt || !isa<OMPSectionDirective>(SectionStmt)) { 8503 if (SectionStmt) 8504 Diag(SectionStmt->getBeginLoc(), 8505 diag::err_omp_sections_substmt_not_section); 8506 return StmtError(); 8507 } 8508 cast<OMPSectionDirective>(SectionStmt) 8509 ->setHasCancel(DSAStack->isCancelRegion()); 8510 } 8511 } else { 8512 Diag(AStmt->getBeginLoc(), diag::err_omp_sections_not_compound_stmt); 8513 return StmtError(); 8514 } 8515 8516 setFunctionHasBranchProtectedScope(); 8517 8518 return OMPSectionsDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt, 8519 DSAStack->isCancelRegion()); 8520 } 8521 8522 StmtResult Sema::ActOnOpenMPSectionDirective(Stmt *AStmt, 8523 SourceLocation StartLoc, 8524 SourceLocation EndLoc) { 8525 if (!AStmt) 8526 return StmtError(); 8527 8528 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected"); 8529 8530 setFunctionHasBranchProtectedScope(); 8531 DSAStack->setParentCancelRegion(DSAStack->isCancelRegion()); 8532 8533 return OMPSectionDirective::Create(Context, StartLoc, EndLoc, AStmt, 8534 DSAStack->isCancelRegion()); 8535 } 8536 8537 StmtResult Sema::ActOnOpenMPSingleDirective(ArrayRef<OMPClause *> Clauses, 8538 Stmt *AStmt, 8539 SourceLocation StartLoc, 8540 SourceLocation EndLoc) { 8541 if (!AStmt) 8542 return StmtError(); 8543 8544 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected"); 8545 8546 setFunctionHasBranchProtectedScope(); 8547 8548 // OpenMP [2.7.3, single Construct, Restrictions] 8549 // The copyprivate clause must not be used with the nowait clause. 8550 const OMPClause *Nowait = nullptr; 8551 const OMPClause *Copyprivate = nullptr; 8552 for (const OMPClause *Clause : Clauses) { 8553 if (Clause->getClauseKind() == OMPC_nowait) 8554 Nowait = Clause; 8555 else if (Clause->getClauseKind() == OMPC_copyprivate) 8556 Copyprivate = Clause; 8557 if (Copyprivate && Nowait) { 8558 Diag(Copyprivate->getBeginLoc(), 8559 diag::err_omp_single_copyprivate_with_nowait); 8560 Diag(Nowait->getBeginLoc(), diag::note_omp_nowait_clause_here); 8561 return StmtError(); 8562 } 8563 } 8564 8565 return OMPSingleDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt); 8566 } 8567 8568 StmtResult Sema::ActOnOpenMPMasterDirective(Stmt *AStmt, 8569 SourceLocation StartLoc, 8570 SourceLocation EndLoc) { 8571 if (!AStmt) 8572 return StmtError(); 8573 8574 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected"); 8575 8576 setFunctionHasBranchProtectedScope(); 8577 8578 return OMPMasterDirective::Create(Context, StartLoc, EndLoc, AStmt); 8579 } 8580 8581 StmtResult Sema::ActOnOpenMPCriticalDirective( 8582 const DeclarationNameInfo &DirName, ArrayRef<OMPClause *> Clauses, 8583 Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc) { 8584 if (!AStmt) 8585 return StmtError(); 8586 8587 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected"); 8588 8589 bool ErrorFound = false; 8590 llvm::APSInt Hint; 8591 SourceLocation HintLoc; 8592 bool DependentHint = false; 8593 for (const OMPClause *C : Clauses) { 8594 if (C->getClauseKind() == OMPC_hint) { 8595 if (!DirName.getName()) { 8596 Diag(C->getBeginLoc(), diag::err_omp_hint_clause_no_name); 8597 ErrorFound = true; 8598 } 8599 Expr *E = cast<OMPHintClause>(C)->getHint(); 8600 if (E->isTypeDependent() || E->isValueDependent() || 8601 E->isInstantiationDependent()) { 8602 DependentHint = true; 8603 } else { 8604 Hint = E->EvaluateKnownConstInt(Context); 8605 HintLoc = C->getBeginLoc(); 8606 } 8607 } 8608 } 8609 if (ErrorFound) 8610 return StmtError(); 8611 const auto Pair = DSAStack->getCriticalWithHint(DirName); 8612 if (Pair.first && DirName.getName() && !DependentHint) { 8613 if (llvm::APSInt::compareValues(Hint, Pair.second) != 0) { 8614 Diag(StartLoc, diag::err_omp_critical_with_hint); 8615 if (HintLoc.isValid()) 8616 Diag(HintLoc, diag::note_omp_critical_hint_here) 8617 << 0 << Hint.toString(/*Radix=*/10, /*Signed=*/false); 8618 else 8619 Diag(StartLoc, diag::note_omp_critical_no_hint) << 0; 8620 if (const auto *C = Pair.first->getSingleClause<OMPHintClause>()) { 8621 Diag(C->getBeginLoc(), diag::note_omp_critical_hint_here) 8622 << 1 8623 << C->getHint()->EvaluateKnownConstInt(Context).toString( 8624 /*Radix=*/10, /*Signed=*/false); 8625 } else { 8626 Diag(Pair.first->getBeginLoc(), diag::note_omp_critical_no_hint) << 1; 8627 } 8628 } 8629 } 8630 8631 setFunctionHasBranchProtectedScope(); 8632 8633 auto *Dir = OMPCriticalDirective::Create(Context, DirName, StartLoc, EndLoc, 8634 Clauses, AStmt); 8635 if (!Pair.first && DirName.getName() && !DependentHint) 8636 DSAStack->addCriticalWithHint(Dir, Hint); 8637 return Dir; 8638 } 8639 8640 StmtResult Sema::ActOnOpenMPParallelForDirective( 8641 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, 8642 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) { 8643 if (!AStmt) 8644 return StmtError(); 8645 8646 auto *CS = cast<CapturedStmt>(AStmt); 8647 // 1.2.2 OpenMP Language Terminology 8648 // Structured block - An executable statement with a single entry at the 8649 // top and a single exit at the bottom. 8650 // The point of exit cannot be a branch out of the structured block. 8651 // longjmp() and throw() must not violate the entry/exit criteria. 8652 CS->getCapturedDecl()->setNothrow(); 8653 8654 OMPLoopDirective::HelperExprs B; 8655 // In presence of clause 'collapse' or 'ordered' with number of loops, it will 8656 // define the nested loops number. 8657 unsigned NestedLoopCount = 8658 checkOpenMPLoop(OMPD_parallel_for, getCollapseNumberExpr(Clauses), 8659 getOrderedNumberExpr(Clauses), AStmt, *this, *DSAStack, 8660 VarsWithImplicitDSA, B); 8661 if (NestedLoopCount == 0) 8662 return StmtError(); 8663 8664 assert((CurContext->isDependentContext() || B.builtAll()) && 8665 "omp parallel for loop exprs were not built"); 8666 8667 if (!CurContext->isDependentContext()) { 8668 // Finalize the clauses that need pre-built expressions for CodeGen. 8669 for (OMPClause *C : Clauses) { 8670 if (auto *LC = dyn_cast<OMPLinearClause>(C)) 8671 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef), 8672 B.NumIterations, *this, CurScope, 8673 DSAStack)) 8674 return StmtError(); 8675 } 8676 } 8677 8678 setFunctionHasBranchProtectedScope(); 8679 return OMPParallelForDirective::Create(Context, StartLoc, EndLoc, 8680 NestedLoopCount, Clauses, AStmt, B, 8681 DSAStack->isCancelRegion()); 8682 } 8683 8684 StmtResult Sema::ActOnOpenMPParallelForSimdDirective( 8685 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, 8686 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) { 8687 if (!AStmt) 8688 return StmtError(); 8689 8690 auto *CS = cast<CapturedStmt>(AStmt); 8691 // 1.2.2 OpenMP Language Terminology 8692 // Structured block - An executable statement with a single entry at the 8693 // top and a single exit at the bottom. 8694 // The point of exit cannot be a branch out of the structured block. 8695 // longjmp() and throw() must not violate the entry/exit criteria. 8696 CS->getCapturedDecl()->setNothrow(); 8697 8698 OMPLoopDirective::HelperExprs B; 8699 // In presence of clause 'collapse' or 'ordered' with number of loops, it will 8700 // define the nested loops number. 8701 unsigned NestedLoopCount = 8702 checkOpenMPLoop(OMPD_parallel_for_simd, getCollapseNumberExpr(Clauses), 8703 getOrderedNumberExpr(Clauses), AStmt, *this, *DSAStack, 8704 VarsWithImplicitDSA, B); 8705 if (NestedLoopCount == 0) 8706 return StmtError(); 8707 8708 if (!CurContext->isDependentContext()) { 8709 // Finalize the clauses that need pre-built expressions for CodeGen. 8710 for (OMPClause *C : Clauses) { 8711 if (auto *LC = dyn_cast<OMPLinearClause>(C)) 8712 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef), 8713 B.NumIterations, *this, CurScope, 8714 DSAStack)) 8715 return StmtError(); 8716 } 8717 } 8718 8719 if (checkSimdlenSafelenSpecified(*this, Clauses)) 8720 return StmtError(); 8721 8722 setFunctionHasBranchProtectedScope(); 8723 return OMPParallelForSimdDirective::Create( 8724 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B); 8725 } 8726 8727 StmtResult 8728 Sema::ActOnOpenMPParallelMasterDirective(ArrayRef<OMPClause *> Clauses, 8729 Stmt *AStmt, SourceLocation StartLoc, 8730 SourceLocation EndLoc) { 8731 if (!AStmt) 8732 return StmtError(); 8733 8734 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected"); 8735 auto *CS = cast<CapturedStmt>(AStmt); 8736 // 1.2.2 OpenMP Language Terminology 8737 // Structured block - An executable statement with a single entry at the 8738 // top and a single exit at the bottom. 8739 // The point of exit cannot be a branch out of the structured block. 8740 // longjmp() and throw() must not violate the entry/exit criteria. 8741 CS->getCapturedDecl()->setNothrow(); 8742 8743 setFunctionHasBranchProtectedScope(); 8744 8745 return OMPParallelMasterDirective::Create(Context, StartLoc, EndLoc, Clauses, 8746 AStmt); 8747 } 8748 8749 StmtResult 8750 Sema::ActOnOpenMPParallelSectionsDirective(ArrayRef<OMPClause *> Clauses, 8751 Stmt *AStmt, SourceLocation StartLoc, 8752 SourceLocation EndLoc) { 8753 if (!AStmt) 8754 return StmtError(); 8755 8756 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected"); 8757 auto BaseStmt = AStmt; 8758 while (auto *CS = dyn_cast_or_null<CapturedStmt>(BaseStmt)) 8759 BaseStmt = CS->getCapturedStmt(); 8760 if (auto *C = dyn_cast_or_null<CompoundStmt>(BaseStmt)) { 8761 auto S = C->children(); 8762 if (S.begin() == S.end()) 8763 return StmtError(); 8764 // All associated statements must be '#pragma omp section' except for 8765 // the first one. 8766 for (Stmt *SectionStmt : llvm::make_range(std::next(S.begin()), S.end())) { 8767 if (!SectionStmt || !isa<OMPSectionDirective>(SectionStmt)) { 8768 if (SectionStmt) 8769 Diag(SectionStmt->getBeginLoc(), 8770 diag::err_omp_parallel_sections_substmt_not_section); 8771 return StmtError(); 8772 } 8773 cast<OMPSectionDirective>(SectionStmt) 8774 ->setHasCancel(DSAStack->isCancelRegion()); 8775 } 8776 } else { 8777 Diag(AStmt->getBeginLoc(), 8778 diag::err_omp_parallel_sections_not_compound_stmt); 8779 return StmtError(); 8780 } 8781 8782 setFunctionHasBranchProtectedScope(); 8783 8784 return OMPParallelSectionsDirective::Create( 8785 Context, StartLoc, EndLoc, Clauses, AStmt, DSAStack->isCancelRegion()); 8786 } 8787 8788 /// detach and mergeable clauses are mutially exclusive, check for it. 8789 static bool checkDetachMergeableClauses(Sema &S, 8790 ArrayRef<OMPClause *> Clauses) { 8791 const OMPClause *PrevClause = nullptr; 8792 bool ErrorFound = false; 8793 for (const OMPClause *C : Clauses) { 8794 if (C->getClauseKind() == OMPC_detach || 8795 C->getClauseKind() == OMPC_mergeable) { 8796 if (!PrevClause) { 8797 PrevClause = C; 8798 } else if (PrevClause->getClauseKind() != C->getClauseKind()) { 8799 S.Diag(C->getBeginLoc(), diag::err_omp_clauses_mutually_exclusive) 8800 << getOpenMPClauseName(C->getClauseKind()) 8801 << getOpenMPClauseName(PrevClause->getClauseKind()); 8802 S.Diag(PrevClause->getBeginLoc(), diag::note_omp_previous_clause) 8803 << getOpenMPClauseName(PrevClause->getClauseKind()); 8804 ErrorFound = true; 8805 } 8806 } 8807 } 8808 return ErrorFound; 8809 } 8810 8811 StmtResult Sema::ActOnOpenMPTaskDirective(ArrayRef<OMPClause *> Clauses, 8812 Stmt *AStmt, SourceLocation StartLoc, 8813 SourceLocation EndLoc) { 8814 if (!AStmt) 8815 return StmtError(); 8816 8817 // OpenMP 5.0, 2.10.1 task Construct 8818 // If a detach clause appears on the directive, then a mergeable clause cannot 8819 // appear on the same directive. 8820 if (checkDetachMergeableClauses(*this, Clauses)) 8821 return StmtError(); 8822 8823 auto *CS = cast<CapturedStmt>(AStmt); 8824 // 1.2.2 OpenMP Language Terminology 8825 // Structured block - An executable statement with a single entry at the 8826 // top and a single exit at the bottom. 8827 // The point of exit cannot be a branch out of the structured block. 8828 // longjmp() and throw() must not violate the entry/exit criteria. 8829 CS->getCapturedDecl()->setNothrow(); 8830 8831 setFunctionHasBranchProtectedScope(); 8832 8833 return OMPTaskDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt, 8834 DSAStack->isCancelRegion()); 8835 } 8836 8837 StmtResult Sema::ActOnOpenMPTaskyieldDirective(SourceLocation StartLoc, 8838 SourceLocation EndLoc) { 8839 return OMPTaskyieldDirective::Create(Context, StartLoc, EndLoc); 8840 } 8841 8842 StmtResult Sema::ActOnOpenMPBarrierDirective(SourceLocation StartLoc, 8843 SourceLocation EndLoc) { 8844 return OMPBarrierDirective::Create(Context, StartLoc, EndLoc); 8845 } 8846 8847 StmtResult Sema::ActOnOpenMPTaskwaitDirective(SourceLocation StartLoc, 8848 SourceLocation EndLoc) { 8849 return OMPTaskwaitDirective::Create(Context, StartLoc, EndLoc); 8850 } 8851 8852 StmtResult Sema::ActOnOpenMPTaskgroupDirective(ArrayRef<OMPClause *> Clauses, 8853 Stmt *AStmt, 8854 SourceLocation StartLoc, 8855 SourceLocation EndLoc) { 8856 if (!AStmt) 8857 return StmtError(); 8858 8859 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected"); 8860 8861 setFunctionHasBranchProtectedScope(); 8862 8863 return OMPTaskgroupDirective::Create(Context, StartLoc, EndLoc, Clauses, 8864 AStmt, 8865 DSAStack->getTaskgroupReductionRef()); 8866 } 8867 8868 StmtResult Sema::ActOnOpenMPFlushDirective(ArrayRef<OMPClause *> Clauses, 8869 SourceLocation StartLoc, 8870 SourceLocation EndLoc) { 8871 OMPFlushClause *FC = nullptr; 8872 OMPClause *OrderClause = nullptr; 8873 for (OMPClause *C : Clauses) { 8874 if (C->getClauseKind() == OMPC_flush) 8875 FC = cast<OMPFlushClause>(C); 8876 else 8877 OrderClause = C; 8878 } 8879 OpenMPClauseKind MemOrderKind = OMPC_unknown; 8880 SourceLocation MemOrderLoc; 8881 for (const OMPClause *C : Clauses) { 8882 if (C->getClauseKind() == OMPC_acq_rel || 8883 C->getClauseKind() == OMPC_acquire || 8884 C->getClauseKind() == OMPC_release) { 8885 if (MemOrderKind != OMPC_unknown) { 8886 Diag(C->getBeginLoc(), diag::err_omp_several_mem_order_clauses) 8887 << getOpenMPDirectiveName(OMPD_flush) << 1 8888 << SourceRange(C->getBeginLoc(), C->getEndLoc()); 8889 Diag(MemOrderLoc, diag::note_omp_previous_mem_order_clause) 8890 << getOpenMPClauseName(MemOrderKind); 8891 } else { 8892 MemOrderKind = C->getClauseKind(); 8893 MemOrderLoc = C->getBeginLoc(); 8894 } 8895 } 8896 } 8897 if (FC && OrderClause) { 8898 Diag(FC->getLParenLoc(), diag::err_omp_flush_order_clause_and_list) 8899 << getOpenMPClauseName(OrderClause->getClauseKind()); 8900 Diag(OrderClause->getBeginLoc(), diag::note_omp_flush_order_clause_here) 8901 << getOpenMPClauseName(OrderClause->getClauseKind()); 8902 return StmtError(); 8903 } 8904 return OMPFlushDirective::Create(Context, StartLoc, EndLoc, Clauses); 8905 } 8906 8907 StmtResult Sema::ActOnOpenMPDepobjDirective(ArrayRef<OMPClause *> Clauses, 8908 SourceLocation StartLoc, 8909 SourceLocation EndLoc) { 8910 if (Clauses.empty()) { 8911 Diag(StartLoc, diag::err_omp_depobj_expected); 8912 return StmtError(); 8913 } else if (Clauses[0]->getClauseKind() != OMPC_depobj) { 8914 Diag(Clauses[0]->getBeginLoc(), diag::err_omp_depobj_expected); 8915 return StmtError(); 8916 } 8917 // Only depobj expression and another single clause is allowed. 8918 if (Clauses.size() > 2) { 8919 Diag(Clauses[2]->getBeginLoc(), 8920 diag::err_omp_depobj_single_clause_expected); 8921 return StmtError(); 8922 } else if (Clauses.size() < 1) { 8923 Diag(Clauses[0]->getEndLoc(), diag::err_omp_depobj_single_clause_expected); 8924 return StmtError(); 8925 } 8926 return OMPDepobjDirective::Create(Context, StartLoc, EndLoc, Clauses); 8927 } 8928 8929 StmtResult Sema::ActOnOpenMPScanDirective(ArrayRef<OMPClause *> Clauses, 8930 SourceLocation StartLoc, 8931 SourceLocation EndLoc) { 8932 // Check that exactly one clause is specified. 8933 if (Clauses.size() != 1) { 8934 Diag(Clauses.empty() ? EndLoc : Clauses[1]->getBeginLoc(), 8935 diag::err_omp_scan_single_clause_expected); 8936 return StmtError(); 8937 } 8938 // Check that only one instance of scan directives is used in the same outer 8939 // region. 8940 if (DSAStack->doesParentHasScanDirective()) { 8941 Diag(StartLoc, diag::err_omp_several_scan_directives_in_region); 8942 Diag(DSAStack->getParentScanDirectiveLoc(), 8943 diag::note_omp_previous_scan_directive); 8944 return StmtError(); 8945 } 8946 DSAStack->setParentHasScanDirective(StartLoc); 8947 return OMPScanDirective::Create(Context, StartLoc, EndLoc, Clauses); 8948 } 8949 8950 StmtResult Sema::ActOnOpenMPOrderedDirective(ArrayRef<OMPClause *> Clauses, 8951 Stmt *AStmt, 8952 SourceLocation StartLoc, 8953 SourceLocation EndLoc) { 8954 const OMPClause *DependFound = nullptr; 8955 const OMPClause *DependSourceClause = nullptr; 8956 const OMPClause *DependSinkClause = nullptr; 8957 bool ErrorFound = false; 8958 const OMPThreadsClause *TC = nullptr; 8959 const OMPSIMDClause *SC = nullptr; 8960 for (const OMPClause *C : Clauses) { 8961 if (auto *DC = dyn_cast<OMPDependClause>(C)) { 8962 DependFound = C; 8963 if (DC->getDependencyKind() == OMPC_DEPEND_source) { 8964 if (DependSourceClause) { 8965 Diag(C->getBeginLoc(), diag::err_omp_more_one_clause) 8966 << getOpenMPDirectiveName(OMPD_ordered) 8967 << getOpenMPClauseName(OMPC_depend) << 2; 8968 ErrorFound = true; 8969 } else { 8970 DependSourceClause = C; 8971 } 8972 if (DependSinkClause) { 8973 Diag(C->getBeginLoc(), diag::err_omp_depend_sink_source_not_allowed) 8974 << 0; 8975 ErrorFound = true; 8976 } 8977 } else if (DC->getDependencyKind() == OMPC_DEPEND_sink) { 8978 if (DependSourceClause) { 8979 Diag(C->getBeginLoc(), diag::err_omp_depend_sink_source_not_allowed) 8980 << 1; 8981 ErrorFound = true; 8982 } 8983 DependSinkClause = C; 8984 } 8985 } else if (C->getClauseKind() == OMPC_threads) { 8986 TC = cast<OMPThreadsClause>(C); 8987 } else if (C->getClauseKind() == OMPC_simd) { 8988 SC = cast<OMPSIMDClause>(C); 8989 } 8990 } 8991 if (!ErrorFound && !SC && 8992 isOpenMPSimdDirective(DSAStack->getParentDirective())) { 8993 // OpenMP [2.8.1,simd Construct, Restrictions] 8994 // An ordered construct with the simd clause is the only OpenMP construct 8995 // that can appear in the simd region. 8996 Diag(StartLoc, diag::err_omp_prohibited_region_simd) 8997 << (LangOpts.OpenMP >= 50 ? 1 : 0); 8998 ErrorFound = true; 8999 } else if (DependFound && (TC || SC)) { 9000 Diag(DependFound->getBeginLoc(), diag::err_omp_depend_clause_thread_simd) 9001 << getOpenMPClauseName(TC ? TC->getClauseKind() : SC->getClauseKind()); 9002 ErrorFound = true; 9003 } else if (DependFound && !DSAStack->getParentOrderedRegionParam().first) { 9004 Diag(DependFound->getBeginLoc(), 9005 diag::err_omp_ordered_directive_without_param); 9006 ErrorFound = true; 9007 } else if (TC || Clauses.empty()) { 9008 if (const Expr *Param = DSAStack->getParentOrderedRegionParam().first) { 9009 SourceLocation ErrLoc = TC ? TC->getBeginLoc() : StartLoc; 9010 Diag(ErrLoc, diag::err_omp_ordered_directive_with_param) 9011 << (TC != nullptr); 9012 Diag(Param->getBeginLoc(), diag::note_omp_ordered_param) << 1; 9013 ErrorFound = true; 9014 } 9015 } 9016 if ((!AStmt && !DependFound) || ErrorFound) 9017 return StmtError(); 9018 9019 if (AStmt) { 9020 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected"); 9021 9022 setFunctionHasBranchProtectedScope(); 9023 } 9024 9025 return OMPOrderedDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt); 9026 } 9027 9028 namespace { 9029 /// Helper class for checking expression in 'omp atomic [update]' 9030 /// construct. 9031 class OpenMPAtomicUpdateChecker { 9032 /// Error results for atomic update expressions. 9033 enum ExprAnalysisErrorCode { 9034 /// A statement is not an expression statement. 9035 NotAnExpression, 9036 /// Expression is not builtin binary or unary operation. 9037 NotABinaryOrUnaryExpression, 9038 /// Unary operation is not post-/pre- increment/decrement operation. 9039 NotAnUnaryIncDecExpression, 9040 /// An expression is not of scalar type. 9041 NotAScalarType, 9042 /// A binary operation is not an assignment operation. 9043 NotAnAssignmentOp, 9044 /// RHS part of the binary operation is not a binary expression. 9045 NotABinaryExpression, 9046 /// RHS part is not additive/multiplicative/shift/biwise binary 9047 /// expression. 9048 NotABinaryOperator, 9049 /// RHS binary operation does not have reference to the updated LHS 9050 /// part. 9051 NotAnUpdateExpression, 9052 /// No errors is found. 9053 NoError 9054 }; 9055 /// Reference to Sema. 9056 Sema &SemaRef; 9057 /// A location for note diagnostics (when error is found). 9058 SourceLocation NoteLoc; 9059 /// 'x' lvalue part of the source atomic expression. 9060 Expr *X; 9061 /// 'expr' rvalue part of the source atomic expression. 9062 Expr *E; 9063 /// Helper expression of the form 9064 /// 'OpaqueValueExpr(x) binop OpaqueValueExpr(expr)' or 9065 /// 'OpaqueValueExpr(expr) binop OpaqueValueExpr(x)'. 9066 Expr *UpdateExpr; 9067 /// Is 'x' a LHS in a RHS part of full update expression. It is 9068 /// important for non-associative operations. 9069 bool IsXLHSInRHSPart; 9070 BinaryOperatorKind Op; 9071 SourceLocation OpLoc; 9072 /// true if the source expression is a postfix unary operation, false 9073 /// if it is a prefix unary operation. 9074 bool IsPostfixUpdate; 9075 9076 public: 9077 OpenMPAtomicUpdateChecker(Sema &SemaRef) 9078 : SemaRef(SemaRef), X(nullptr), E(nullptr), UpdateExpr(nullptr), 9079 IsXLHSInRHSPart(false), Op(BO_PtrMemD), IsPostfixUpdate(false) {} 9080 /// Check specified statement that it is suitable for 'atomic update' 9081 /// constructs and extract 'x', 'expr' and Operation from the original 9082 /// expression. If DiagId and NoteId == 0, then only check is performed 9083 /// without error notification. 9084 /// \param DiagId Diagnostic which should be emitted if error is found. 9085 /// \param NoteId Diagnostic note for the main error message. 9086 /// \return true if statement is not an update expression, false otherwise. 9087 bool checkStatement(Stmt *S, unsigned DiagId = 0, unsigned NoteId = 0); 9088 /// Return the 'x' lvalue part of the source atomic expression. 9089 Expr *getX() const { return X; } 9090 /// Return the 'expr' rvalue part of the source atomic expression. 9091 Expr *getExpr() const { return E; } 9092 /// Return the update expression used in calculation of the updated 9093 /// value. Always has form 'OpaqueValueExpr(x) binop OpaqueValueExpr(expr)' or 9094 /// 'OpaqueValueExpr(expr) binop OpaqueValueExpr(x)'. 9095 Expr *getUpdateExpr() const { return UpdateExpr; } 9096 /// Return true if 'x' is LHS in RHS part of full update expression, 9097 /// false otherwise. 9098 bool isXLHSInRHSPart() const { return IsXLHSInRHSPart; } 9099 9100 /// true if the source expression is a postfix unary operation, false 9101 /// if it is a prefix unary operation. 9102 bool isPostfixUpdate() const { return IsPostfixUpdate; } 9103 9104 private: 9105 bool checkBinaryOperation(BinaryOperator *AtomicBinOp, unsigned DiagId = 0, 9106 unsigned NoteId = 0); 9107 }; 9108 } // namespace 9109 9110 bool OpenMPAtomicUpdateChecker::checkBinaryOperation( 9111 BinaryOperator *AtomicBinOp, unsigned DiagId, unsigned NoteId) { 9112 ExprAnalysisErrorCode ErrorFound = NoError; 9113 SourceLocation ErrorLoc, NoteLoc; 9114 SourceRange ErrorRange, NoteRange; 9115 // Allowed constructs are: 9116 // x = x binop expr; 9117 // x = expr binop x; 9118 if (AtomicBinOp->getOpcode() == BO_Assign) { 9119 X = AtomicBinOp->getLHS(); 9120 if (const auto *AtomicInnerBinOp = dyn_cast<BinaryOperator>( 9121 AtomicBinOp->getRHS()->IgnoreParenImpCasts())) { 9122 if (AtomicInnerBinOp->isMultiplicativeOp() || 9123 AtomicInnerBinOp->isAdditiveOp() || AtomicInnerBinOp->isShiftOp() || 9124 AtomicInnerBinOp->isBitwiseOp()) { 9125 Op = AtomicInnerBinOp->getOpcode(); 9126 OpLoc = AtomicInnerBinOp->getOperatorLoc(); 9127 Expr *LHS = AtomicInnerBinOp->getLHS(); 9128 Expr *RHS = AtomicInnerBinOp->getRHS(); 9129 llvm::FoldingSetNodeID XId, LHSId, RHSId; 9130 X->IgnoreParenImpCasts()->Profile(XId, SemaRef.getASTContext(), 9131 /*Canonical=*/true); 9132 LHS->IgnoreParenImpCasts()->Profile(LHSId, SemaRef.getASTContext(), 9133 /*Canonical=*/true); 9134 RHS->IgnoreParenImpCasts()->Profile(RHSId, SemaRef.getASTContext(), 9135 /*Canonical=*/true); 9136 if (XId == LHSId) { 9137 E = RHS; 9138 IsXLHSInRHSPart = true; 9139 } else if (XId == RHSId) { 9140 E = LHS; 9141 IsXLHSInRHSPart = false; 9142 } else { 9143 ErrorLoc = AtomicInnerBinOp->getExprLoc(); 9144 ErrorRange = AtomicInnerBinOp->getSourceRange(); 9145 NoteLoc = X->getExprLoc(); 9146 NoteRange = X->getSourceRange(); 9147 ErrorFound = NotAnUpdateExpression; 9148 } 9149 } else { 9150 ErrorLoc = AtomicInnerBinOp->getExprLoc(); 9151 ErrorRange = AtomicInnerBinOp->getSourceRange(); 9152 NoteLoc = AtomicInnerBinOp->getOperatorLoc(); 9153 NoteRange = SourceRange(NoteLoc, NoteLoc); 9154 ErrorFound = NotABinaryOperator; 9155 } 9156 } else { 9157 NoteLoc = ErrorLoc = AtomicBinOp->getRHS()->getExprLoc(); 9158 NoteRange = ErrorRange = AtomicBinOp->getRHS()->getSourceRange(); 9159 ErrorFound = NotABinaryExpression; 9160 } 9161 } else { 9162 ErrorLoc = AtomicBinOp->getExprLoc(); 9163 ErrorRange = AtomicBinOp->getSourceRange(); 9164 NoteLoc = AtomicBinOp->getOperatorLoc(); 9165 NoteRange = SourceRange(NoteLoc, NoteLoc); 9166 ErrorFound = NotAnAssignmentOp; 9167 } 9168 if (ErrorFound != NoError && DiagId != 0 && NoteId != 0) { 9169 SemaRef.Diag(ErrorLoc, DiagId) << ErrorRange; 9170 SemaRef.Diag(NoteLoc, NoteId) << ErrorFound << NoteRange; 9171 return true; 9172 } 9173 if (SemaRef.CurContext->isDependentContext()) 9174 E = X = UpdateExpr = nullptr; 9175 return ErrorFound != NoError; 9176 } 9177 9178 bool OpenMPAtomicUpdateChecker::checkStatement(Stmt *S, unsigned DiagId, 9179 unsigned NoteId) { 9180 ExprAnalysisErrorCode ErrorFound = NoError; 9181 SourceLocation ErrorLoc, NoteLoc; 9182 SourceRange ErrorRange, NoteRange; 9183 // Allowed constructs are: 9184 // x++; 9185 // x--; 9186 // ++x; 9187 // --x; 9188 // x binop= expr; 9189 // x = x binop expr; 9190 // x = expr binop x; 9191 if (auto *AtomicBody = dyn_cast<Expr>(S)) { 9192 AtomicBody = AtomicBody->IgnoreParenImpCasts(); 9193 if (AtomicBody->getType()->isScalarType() || 9194 AtomicBody->isInstantiationDependent()) { 9195 if (const auto *AtomicCompAssignOp = dyn_cast<CompoundAssignOperator>( 9196 AtomicBody->IgnoreParenImpCasts())) { 9197 // Check for Compound Assignment Operation 9198 Op = BinaryOperator::getOpForCompoundAssignment( 9199 AtomicCompAssignOp->getOpcode()); 9200 OpLoc = AtomicCompAssignOp->getOperatorLoc(); 9201 E = AtomicCompAssignOp->getRHS(); 9202 X = AtomicCompAssignOp->getLHS()->IgnoreParens(); 9203 IsXLHSInRHSPart = true; 9204 } else if (auto *AtomicBinOp = dyn_cast<BinaryOperator>( 9205 AtomicBody->IgnoreParenImpCasts())) { 9206 // Check for Binary Operation 9207 if (checkBinaryOperation(AtomicBinOp, DiagId, NoteId)) 9208 return true; 9209 } else if (const auto *AtomicUnaryOp = dyn_cast<UnaryOperator>( 9210 AtomicBody->IgnoreParenImpCasts())) { 9211 // Check for Unary Operation 9212 if (AtomicUnaryOp->isIncrementDecrementOp()) { 9213 IsPostfixUpdate = AtomicUnaryOp->isPostfix(); 9214 Op = AtomicUnaryOp->isIncrementOp() ? BO_Add : BO_Sub; 9215 OpLoc = AtomicUnaryOp->getOperatorLoc(); 9216 X = AtomicUnaryOp->getSubExpr()->IgnoreParens(); 9217 E = SemaRef.ActOnIntegerConstant(OpLoc, /*uint64_t Val=*/1).get(); 9218 IsXLHSInRHSPart = true; 9219 } else { 9220 ErrorFound = NotAnUnaryIncDecExpression; 9221 ErrorLoc = AtomicUnaryOp->getExprLoc(); 9222 ErrorRange = AtomicUnaryOp->getSourceRange(); 9223 NoteLoc = AtomicUnaryOp->getOperatorLoc(); 9224 NoteRange = SourceRange(NoteLoc, NoteLoc); 9225 } 9226 } else if (!AtomicBody->isInstantiationDependent()) { 9227 ErrorFound = NotABinaryOrUnaryExpression; 9228 NoteLoc = ErrorLoc = AtomicBody->getExprLoc(); 9229 NoteRange = ErrorRange = AtomicBody->getSourceRange(); 9230 } 9231 } else { 9232 ErrorFound = NotAScalarType; 9233 NoteLoc = ErrorLoc = AtomicBody->getBeginLoc(); 9234 NoteRange = ErrorRange = SourceRange(NoteLoc, NoteLoc); 9235 } 9236 } else { 9237 ErrorFound = NotAnExpression; 9238 NoteLoc = ErrorLoc = S->getBeginLoc(); 9239 NoteRange = ErrorRange = SourceRange(NoteLoc, NoteLoc); 9240 } 9241 if (ErrorFound != NoError && DiagId != 0 && NoteId != 0) { 9242 SemaRef.Diag(ErrorLoc, DiagId) << ErrorRange; 9243 SemaRef.Diag(NoteLoc, NoteId) << ErrorFound << NoteRange; 9244 return true; 9245 } 9246 if (SemaRef.CurContext->isDependentContext()) 9247 E = X = UpdateExpr = nullptr; 9248 if (ErrorFound == NoError && E && X) { 9249 // Build an update expression of form 'OpaqueValueExpr(x) binop 9250 // OpaqueValueExpr(expr)' or 'OpaqueValueExpr(expr) binop 9251 // OpaqueValueExpr(x)' and then cast it to the type of the 'x' expression. 9252 auto *OVEX = new (SemaRef.getASTContext()) 9253 OpaqueValueExpr(X->getExprLoc(), X->getType(), VK_RValue); 9254 auto *OVEExpr = new (SemaRef.getASTContext()) 9255 OpaqueValueExpr(E->getExprLoc(), E->getType(), VK_RValue); 9256 ExprResult Update = 9257 SemaRef.CreateBuiltinBinOp(OpLoc, Op, IsXLHSInRHSPart ? OVEX : OVEExpr, 9258 IsXLHSInRHSPart ? OVEExpr : OVEX); 9259 if (Update.isInvalid()) 9260 return true; 9261 Update = SemaRef.PerformImplicitConversion(Update.get(), X->getType(), 9262 Sema::AA_Casting); 9263 if (Update.isInvalid()) 9264 return true; 9265 UpdateExpr = Update.get(); 9266 } 9267 return ErrorFound != NoError; 9268 } 9269 9270 StmtResult Sema::ActOnOpenMPAtomicDirective(ArrayRef<OMPClause *> Clauses, 9271 Stmt *AStmt, 9272 SourceLocation StartLoc, 9273 SourceLocation EndLoc) { 9274 // Register location of the first atomic directive. 9275 DSAStack->addAtomicDirectiveLoc(StartLoc); 9276 if (!AStmt) 9277 return StmtError(); 9278 9279 auto *CS = cast<CapturedStmt>(AStmt); 9280 // 1.2.2 OpenMP Language Terminology 9281 // Structured block - An executable statement with a single entry at the 9282 // top and a single exit at the bottom. 9283 // The point of exit cannot be a branch out of the structured block. 9284 // longjmp() and throw() must not violate the entry/exit criteria. 9285 OpenMPClauseKind AtomicKind = OMPC_unknown; 9286 SourceLocation AtomicKindLoc; 9287 OpenMPClauseKind MemOrderKind = OMPC_unknown; 9288 SourceLocation MemOrderLoc; 9289 for (const OMPClause *C : Clauses) { 9290 if (C->getClauseKind() == OMPC_read || C->getClauseKind() == OMPC_write || 9291 C->getClauseKind() == OMPC_update || 9292 C->getClauseKind() == OMPC_capture) { 9293 if (AtomicKind != OMPC_unknown) { 9294 Diag(C->getBeginLoc(), diag::err_omp_atomic_several_clauses) 9295 << SourceRange(C->getBeginLoc(), C->getEndLoc()); 9296 Diag(AtomicKindLoc, diag::note_omp_previous_mem_order_clause) 9297 << getOpenMPClauseName(AtomicKind); 9298 } else { 9299 AtomicKind = C->getClauseKind(); 9300 AtomicKindLoc = C->getBeginLoc(); 9301 } 9302 } 9303 if (C->getClauseKind() == OMPC_seq_cst || 9304 C->getClauseKind() == OMPC_acq_rel || 9305 C->getClauseKind() == OMPC_acquire || 9306 C->getClauseKind() == OMPC_release || 9307 C->getClauseKind() == OMPC_relaxed) { 9308 if (MemOrderKind != OMPC_unknown) { 9309 Diag(C->getBeginLoc(), diag::err_omp_several_mem_order_clauses) 9310 << getOpenMPDirectiveName(OMPD_atomic) << 0 9311 << SourceRange(C->getBeginLoc(), C->getEndLoc()); 9312 Diag(MemOrderLoc, diag::note_omp_previous_mem_order_clause) 9313 << getOpenMPClauseName(MemOrderKind); 9314 } else { 9315 MemOrderKind = C->getClauseKind(); 9316 MemOrderLoc = C->getBeginLoc(); 9317 } 9318 } 9319 } 9320 // OpenMP 5.0, 2.17.7 atomic Construct, Restrictions 9321 // If atomic-clause is read then memory-order-clause must not be acq_rel or 9322 // release. 9323 // If atomic-clause is write then memory-order-clause must not be acq_rel or 9324 // acquire. 9325 // If atomic-clause is update or not present then memory-order-clause must not 9326 // be acq_rel or acquire. 9327 if ((AtomicKind == OMPC_read && 9328 (MemOrderKind == OMPC_acq_rel || MemOrderKind == OMPC_release)) || 9329 ((AtomicKind == OMPC_write || AtomicKind == OMPC_update || 9330 AtomicKind == OMPC_unknown) && 9331 (MemOrderKind == OMPC_acq_rel || MemOrderKind == OMPC_acquire))) { 9332 SourceLocation Loc = AtomicKindLoc; 9333 if (AtomicKind == OMPC_unknown) 9334 Loc = StartLoc; 9335 Diag(Loc, diag::err_omp_atomic_incompatible_mem_order_clause) 9336 << getOpenMPClauseName(AtomicKind) 9337 << (AtomicKind == OMPC_unknown ? 1 : 0) 9338 << getOpenMPClauseName(MemOrderKind); 9339 Diag(MemOrderLoc, diag::note_omp_previous_mem_order_clause) 9340 << getOpenMPClauseName(MemOrderKind); 9341 } 9342 9343 Stmt *Body = CS->getCapturedStmt(); 9344 if (auto *EWC = dyn_cast<ExprWithCleanups>(Body)) 9345 Body = EWC->getSubExpr(); 9346 9347 Expr *X = nullptr; 9348 Expr *V = nullptr; 9349 Expr *E = nullptr; 9350 Expr *UE = nullptr; 9351 bool IsXLHSInRHSPart = false; 9352 bool IsPostfixUpdate = false; 9353 // OpenMP [2.12.6, atomic Construct] 9354 // In the next expressions: 9355 // * x and v (as applicable) are both l-value expressions with scalar type. 9356 // * During the execution of an atomic region, multiple syntactic 9357 // occurrences of x must designate the same storage location. 9358 // * Neither of v and expr (as applicable) may access the storage location 9359 // designated by x. 9360 // * Neither of x and expr (as applicable) may access the storage location 9361 // designated by v. 9362 // * expr is an expression with scalar type. 9363 // * binop is one of +, *, -, /, &, ^, |, <<, or >>. 9364 // * binop, binop=, ++, and -- are not overloaded operators. 9365 // * The expression x binop expr must be numerically equivalent to x binop 9366 // (expr). This requirement is satisfied if the operators in expr have 9367 // precedence greater than binop, or by using parentheses around expr or 9368 // subexpressions of expr. 9369 // * The expression expr binop x must be numerically equivalent to (expr) 9370 // binop x. This requirement is satisfied if the operators in expr have 9371 // precedence equal to or greater than binop, or by using parentheses around 9372 // expr or subexpressions of expr. 9373 // * For forms that allow multiple occurrences of x, the number of times 9374 // that x is evaluated is unspecified. 9375 if (AtomicKind == OMPC_read) { 9376 enum { 9377 NotAnExpression, 9378 NotAnAssignmentOp, 9379 NotAScalarType, 9380 NotAnLValue, 9381 NoError 9382 } ErrorFound = NoError; 9383 SourceLocation ErrorLoc, NoteLoc; 9384 SourceRange ErrorRange, NoteRange; 9385 // If clause is read: 9386 // v = x; 9387 if (const auto *AtomicBody = dyn_cast<Expr>(Body)) { 9388 const auto *AtomicBinOp = 9389 dyn_cast<BinaryOperator>(AtomicBody->IgnoreParenImpCasts()); 9390 if (AtomicBinOp && AtomicBinOp->getOpcode() == BO_Assign) { 9391 X = AtomicBinOp->getRHS()->IgnoreParenImpCasts(); 9392 V = AtomicBinOp->getLHS()->IgnoreParenImpCasts(); 9393 if ((X->isInstantiationDependent() || X->getType()->isScalarType()) && 9394 (V->isInstantiationDependent() || V->getType()->isScalarType())) { 9395 if (!X->isLValue() || !V->isLValue()) { 9396 const Expr *NotLValueExpr = X->isLValue() ? V : X; 9397 ErrorFound = NotAnLValue; 9398 ErrorLoc = AtomicBinOp->getExprLoc(); 9399 ErrorRange = AtomicBinOp->getSourceRange(); 9400 NoteLoc = NotLValueExpr->getExprLoc(); 9401 NoteRange = NotLValueExpr->getSourceRange(); 9402 } 9403 } else if (!X->isInstantiationDependent() || 9404 !V->isInstantiationDependent()) { 9405 const Expr *NotScalarExpr = 9406 (X->isInstantiationDependent() || X->getType()->isScalarType()) 9407 ? V 9408 : X; 9409 ErrorFound = NotAScalarType; 9410 ErrorLoc = AtomicBinOp->getExprLoc(); 9411 ErrorRange = AtomicBinOp->getSourceRange(); 9412 NoteLoc = NotScalarExpr->getExprLoc(); 9413 NoteRange = NotScalarExpr->getSourceRange(); 9414 } 9415 } else if (!AtomicBody->isInstantiationDependent()) { 9416 ErrorFound = NotAnAssignmentOp; 9417 ErrorLoc = AtomicBody->getExprLoc(); 9418 ErrorRange = AtomicBody->getSourceRange(); 9419 NoteLoc = AtomicBinOp ? AtomicBinOp->getOperatorLoc() 9420 : AtomicBody->getExprLoc(); 9421 NoteRange = AtomicBinOp ? AtomicBinOp->getSourceRange() 9422 : AtomicBody->getSourceRange(); 9423 } 9424 } else { 9425 ErrorFound = NotAnExpression; 9426 NoteLoc = ErrorLoc = Body->getBeginLoc(); 9427 NoteRange = ErrorRange = SourceRange(NoteLoc, NoteLoc); 9428 } 9429 if (ErrorFound != NoError) { 9430 Diag(ErrorLoc, diag::err_omp_atomic_read_not_expression_statement) 9431 << ErrorRange; 9432 Diag(NoteLoc, diag::note_omp_atomic_read_write) << ErrorFound 9433 << NoteRange; 9434 return StmtError(); 9435 } 9436 if (CurContext->isDependentContext()) 9437 V = X = nullptr; 9438 } else if (AtomicKind == OMPC_write) { 9439 enum { 9440 NotAnExpression, 9441 NotAnAssignmentOp, 9442 NotAScalarType, 9443 NotAnLValue, 9444 NoError 9445 } ErrorFound = NoError; 9446 SourceLocation ErrorLoc, NoteLoc; 9447 SourceRange ErrorRange, NoteRange; 9448 // If clause is write: 9449 // x = expr; 9450 if (const auto *AtomicBody = dyn_cast<Expr>(Body)) { 9451 const auto *AtomicBinOp = 9452 dyn_cast<BinaryOperator>(AtomicBody->IgnoreParenImpCasts()); 9453 if (AtomicBinOp && AtomicBinOp->getOpcode() == BO_Assign) { 9454 X = AtomicBinOp->getLHS(); 9455 E = AtomicBinOp->getRHS(); 9456 if ((X->isInstantiationDependent() || X->getType()->isScalarType()) && 9457 (E->isInstantiationDependent() || E->getType()->isScalarType())) { 9458 if (!X->isLValue()) { 9459 ErrorFound = NotAnLValue; 9460 ErrorLoc = AtomicBinOp->getExprLoc(); 9461 ErrorRange = AtomicBinOp->getSourceRange(); 9462 NoteLoc = X->getExprLoc(); 9463 NoteRange = X->getSourceRange(); 9464 } 9465 } else if (!X->isInstantiationDependent() || 9466 !E->isInstantiationDependent()) { 9467 const Expr *NotScalarExpr = 9468 (X->isInstantiationDependent() || X->getType()->isScalarType()) 9469 ? E 9470 : X; 9471 ErrorFound = NotAScalarType; 9472 ErrorLoc = AtomicBinOp->getExprLoc(); 9473 ErrorRange = AtomicBinOp->getSourceRange(); 9474 NoteLoc = NotScalarExpr->getExprLoc(); 9475 NoteRange = NotScalarExpr->getSourceRange(); 9476 } 9477 } else if (!AtomicBody->isInstantiationDependent()) { 9478 ErrorFound = NotAnAssignmentOp; 9479 ErrorLoc = AtomicBody->getExprLoc(); 9480 ErrorRange = AtomicBody->getSourceRange(); 9481 NoteLoc = AtomicBinOp ? AtomicBinOp->getOperatorLoc() 9482 : AtomicBody->getExprLoc(); 9483 NoteRange = AtomicBinOp ? AtomicBinOp->getSourceRange() 9484 : AtomicBody->getSourceRange(); 9485 } 9486 } else { 9487 ErrorFound = NotAnExpression; 9488 NoteLoc = ErrorLoc = Body->getBeginLoc(); 9489 NoteRange = ErrorRange = SourceRange(NoteLoc, NoteLoc); 9490 } 9491 if (ErrorFound != NoError) { 9492 Diag(ErrorLoc, diag::err_omp_atomic_write_not_expression_statement) 9493 << ErrorRange; 9494 Diag(NoteLoc, diag::note_omp_atomic_read_write) << ErrorFound 9495 << NoteRange; 9496 return StmtError(); 9497 } 9498 if (CurContext->isDependentContext()) 9499 E = X = nullptr; 9500 } else if (AtomicKind == OMPC_update || AtomicKind == OMPC_unknown) { 9501 // If clause is update: 9502 // x++; 9503 // x--; 9504 // ++x; 9505 // --x; 9506 // x binop= expr; 9507 // x = x binop expr; 9508 // x = expr binop x; 9509 OpenMPAtomicUpdateChecker Checker(*this); 9510 if (Checker.checkStatement( 9511 Body, (AtomicKind == OMPC_update) 9512 ? diag::err_omp_atomic_update_not_expression_statement 9513 : diag::err_omp_atomic_not_expression_statement, 9514 diag::note_omp_atomic_update)) 9515 return StmtError(); 9516 if (!CurContext->isDependentContext()) { 9517 E = Checker.getExpr(); 9518 X = Checker.getX(); 9519 UE = Checker.getUpdateExpr(); 9520 IsXLHSInRHSPart = Checker.isXLHSInRHSPart(); 9521 } 9522 } else if (AtomicKind == OMPC_capture) { 9523 enum { 9524 NotAnAssignmentOp, 9525 NotACompoundStatement, 9526 NotTwoSubstatements, 9527 NotASpecificExpression, 9528 NoError 9529 } ErrorFound = NoError; 9530 SourceLocation ErrorLoc, NoteLoc; 9531 SourceRange ErrorRange, NoteRange; 9532 if (const auto *AtomicBody = dyn_cast<Expr>(Body)) { 9533 // If clause is a capture: 9534 // v = x++; 9535 // v = x--; 9536 // v = ++x; 9537 // v = --x; 9538 // v = x binop= expr; 9539 // v = x = x binop expr; 9540 // v = x = expr binop x; 9541 const auto *AtomicBinOp = 9542 dyn_cast<BinaryOperator>(AtomicBody->IgnoreParenImpCasts()); 9543 if (AtomicBinOp && AtomicBinOp->getOpcode() == BO_Assign) { 9544 V = AtomicBinOp->getLHS(); 9545 Body = AtomicBinOp->getRHS()->IgnoreParenImpCasts(); 9546 OpenMPAtomicUpdateChecker Checker(*this); 9547 if (Checker.checkStatement( 9548 Body, diag::err_omp_atomic_capture_not_expression_statement, 9549 diag::note_omp_atomic_update)) 9550 return StmtError(); 9551 E = Checker.getExpr(); 9552 X = Checker.getX(); 9553 UE = Checker.getUpdateExpr(); 9554 IsXLHSInRHSPart = Checker.isXLHSInRHSPart(); 9555 IsPostfixUpdate = Checker.isPostfixUpdate(); 9556 } else if (!AtomicBody->isInstantiationDependent()) { 9557 ErrorLoc = AtomicBody->getExprLoc(); 9558 ErrorRange = AtomicBody->getSourceRange(); 9559 NoteLoc = AtomicBinOp ? AtomicBinOp->getOperatorLoc() 9560 : AtomicBody->getExprLoc(); 9561 NoteRange = AtomicBinOp ? AtomicBinOp->getSourceRange() 9562 : AtomicBody->getSourceRange(); 9563 ErrorFound = NotAnAssignmentOp; 9564 } 9565 if (ErrorFound != NoError) { 9566 Diag(ErrorLoc, diag::err_omp_atomic_capture_not_expression_statement) 9567 << ErrorRange; 9568 Diag(NoteLoc, diag::note_omp_atomic_capture) << ErrorFound << NoteRange; 9569 return StmtError(); 9570 } 9571 if (CurContext->isDependentContext()) 9572 UE = V = E = X = nullptr; 9573 } else { 9574 // If clause is a capture: 9575 // { v = x; x = expr; } 9576 // { v = x; x++; } 9577 // { v = x; x--; } 9578 // { v = x; ++x; } 9579 // { v = x; --x; } 9580 // { v = x; x binop= expr; } 9581 // { v = x; x = x binop expr; } 9582 // { v = x; x = expr binop x; } 9583 // { x++; v = x; } 9584 // { x--; v = x; } 9585 // { ++x; v = x; } 9586 // { --x; v = x; } 9587 // { x binop= expr; v = x; } 9588 // { x = x binop expr; v = x; } 9589 // { x = expr binop x; v = x; } 9590 if (auto *CS = dyn_cast<CompoundStmt>(Body)) { 9591 // Check that this is { expr1; expr2; } 9592 if (CS->size() == 2) { 9593 Stmt *First = CS->body_front(); 9594 Stmt *Second = CS->body_back(); 9595 if (auto *EWC = dyn_cast<ExprWithCleanups>(First)) 9596 First = EWC->getSubExpr()->IgnoreParenImpCasts(); 9597 if (auto *EWC = dyn_cast<ExprWithCleanups>(Second)) 9598 Second = EWC->getSubExpr()->IgnoreParenImpCasts(); 9599 // Need to find what subexpression is 'v' and what is 'x'. 9600 OpenMPAtomicUpdateChecker Checker(*this); 9601 bool IsUpdateExprFound = !Checker.checkStatement(Second); 9602 BinaryOperator *BinOp = nullptr; 9603 if (IsUpdateExprFound) { 9604 BinOp = dyn_cast<BinaryOperator>(First); 9605 IsUpdateExprFound = BinOp && BinOp->getOpcode() == BO_Assign; 9606 } 9607 if (IsUpdateExprFound && !CurContext->isDependentContext()) { 9608 // { v = x; x++; } 9609 // { v = x; x--; } 9610 // { v = x; ++x; } 9611 // { v = x; --x; } 9612 // { v = x; x binop= expr; } 9613 // { v = x; x = x binop expr; } 9614 // { v = x; x = expr binop x; } 9615 // Check that the first expression has form v = x. 9616 Expr *PossibleX = BinOp->getRHS()->IgnoreParenImpCasts(); 9617 llvm::FoldingSetNodeID XId, PossibleXId; 9618 Checker.getX()->Profile(XId, Context, /*Canonical=*/true); 9619 PossibleX->Profile(PossibleXId, Context, /*Canonical=*/true); 9620 IsUpdateExprFound = XId == PossibleXId; 9621 if (IsUpdateExprFound) { 9622 V = BinOp->getLHS(); 9623 X = Checker.getX(); 9624 E = Checker.getExpr(); 9625 UE = Checker.getUpdateExpr(); 9626 IsXLHSInRHSPart = Checker.isXLHSInRHSPart(); 9627 IsPostfixUpdate = true; 9628 } 9629 } 9630 if (!IsUpdateExprFound) { 9631 IsUpdateExprFound = !Checker.checkStatement(First); 9632 BinOp = nullptr; 9633 if (IsUpdateExprFound) { 9634 BinOp = dyn_cast<BinaryOperator>(Second); 9635 IsUpdateExprFound = BinOp && BinOp->getOpcode() == BO_Assign; 9636 } 9637 if (IsUpdateExprFound && !CurContext->isDependentContext()) { 9638 // { x++; v = x; } 9639 // { x--; v = x; } 9640 // { ++x; v = x; } 9641 // { --x; v = x; } 9642 // { x binop= expr; v = x; } 9643 // { x = x binop expr; v = x; } 9644 // { x = expr binop x; v = x; } 9645 // Check that the second expression has form v = x. 9646 Expr *PossibleX = BinOp->getRHS()->IgnoreParenImpCasts(); 9647 llvm::FoldingSetNodeID XId, PossibleXId; 9648 Checker.getX()->Profile(XId, Context, /*Canonical=*/true); 9649 PossibleX->Profile(PossibleXId, Context, /*Canonical=*/true); 9650 IsUpdateExprFound = XId == PossibleXId; 9651 if (IsUpdateExprFound) { 9652 V = BinOp->getLHS(); 9653 X = Checker.getX(); 9654 E = Checker.getExpr(); 9655 UE = Checker.getUpdateExpr(); 9656 IsXLHSInRHSPart = Checker.isXLHSInRHSPart(); 9657 IsPostfixUpdate = false; 9658 } 9659 } 9660 } 9661 if (!IsUpdateExprFound) { 9662 // { v = x; x = expr; } 9663 auto *FirstExpr = dyn_cast<Expr>(First); 9664 auto *SecondExpr = dyn_cast<Expr>(Second); 9665 if (!FirstExpr || !SecondExpr || 9666 !(FirstExpr->isInstantiationDependent() || 9667 SecondExpr->isInstantiationDependent())) { 9668 auto *FirstBinOp = dyn_cast<BinaryOperator>(First); 9669 if (!FirstBinOp || FirstBinOp->getOpcode() != BO_Assign) { 9670 ErrorFound = NotAnAssignmentOp; 9671 NoteLoc = ErrorLoc = FirstBinOp ? FirstBinOp->getOperatorLoc() 9672 : First->getBeginLoc(); 9673 NoteRange = ErrorRange = FirstBinOp 9674 ? FirstBinOp->getSourceRange() 9675 : SourceRange(ErrorLoc, ErrorLoc); 9676 } else { 9677 auto *SecondBinOp = dyn_cast<BinaryOperator>(Second); 9678 if (!SecondBinOp || SecondBinOp->getOpcode() != BO_Assign) { 9679 ErrorFound = NotAnAssignmentOp; 9680 NoteLoc = ErrorLoc = SecondBinOp 9681 ? SecondBinOp->getOperatorLoc() 9682 : Second->getBeginLoc(); 9683 NoteRange = ErrorRange = 9684 SecondBinOp ? SecondBinOp->getSourceRange() 9685 : SourceRange(ErrorLoc, ErrorLoc); 9686 } else { 9687 Expr *PossibleXRHSInFirst = 9688 FirstBinOp->getRHS()->IgnoreParenImpCasts(); 9689 Expr *PossibleXLHSInSecond = 9690 SecondBinOp->getLHS()->IgnoreParenImpCasts(); 9691 llvm::FoldingSetNodeID X1Id, X2Id; 9692 PossibleXRHSInFirst->Profile(X1Id, Context, 9693 /*Canonical=*/true); 9694 PossibleXLHSInSecond->Profile(X2Id, Context, 9695 /*Canonical=*/true); 9696 IsUpdateExprFound = X1Id == X2Id; 9697 if (IsUpdateExprFound) { 9698 V = FirstBinOp->getLHS(); 9699 X = SecondBinOp->getLHS(); 9700 E = SecondBinOp->getRHS(); 9701 UE = nullptr; 9702 IsXLHSInRHSPart = false; 9703 IsPostfixUpdate = true; 9704 } else { 9705 ErrorFound = NotASpecificExpression; 9706 ErrorLoc = FirstBinOp->getExprLoc(); 9707 ErrorRange = FirstBinOp->getSourceRange(); 9708 NoteLoc = SecondBinOp->getLHS()->getExprLoc(); 9709 NoteRange = SecondBinOp->getRHS()->getSourceRange(); 9710 } 9711 } 9712 } 9713 } 9714 } 9715 } else { 9716 NoteLoc = ErrorLoc = Body->getBeginLoc(); 9717 NoteRange = ErrorRange = 9718 SourceRange(Body->getBeginLoc(), Body->getBeginLoc()); 9719 ErrorFound = NotTwoSubstatements; 9720 } 9721 } else { 9722 NoteLoc = ErrorLoc = Body->getBeginLoc(); 9723 NoteRange = ErrorRange = 9724 SourceRange(Body->getBeginLoc(), Body->getBeginLoc()); 9725 ErrorFound = NotACompoundStatement; 9726 } 9727 if (ErrorFound != NoError) { 9728 Diag(ErrorLoc, diag::err_omp_atomic_capture_not_compound_statement) 9729 << ErrorRange; 9730 Diag(NoteLoc, diag::note_omp_atomic_capture) << ErrorFound << NoteRange; 9731 return StmtError(); 9732 } 9733 if (CurContext->isDependentContext()) 9734 UE = V = E = X = nullptr; 9735 } 9736 } 9737 9738 setFunctionHasBranchProtectedScope(); 9739 9740 return OMPAtomicDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt, 9741 X, V, E, UE, IsXLHSInRHSPart, 9742 IsPostfixUpdate); 9743 } 9744 9745 StmtResult Sema::ActOnOpenMPTargetDirective(ArrayRef<OMPClause *> Clauses, 9746 Stmt *AStmt, 9747 SourceLocation StartLoc, 9748 SourceLocation EndLoc) { 9749 if (!AStmt) 9750 return StmtError(); 9751 9752 auto *CS = cast<CapturedStmt>(AStmt); 9753 // 1.2.2 OpenMP Language Terminology 9754 // Structured block - An executable statement with a single entry at the 9755 // top and a single exit at the bottom. 9756 // The point of exit cannot be a branch out of the structured block. 9757 // longjmp() and throw() must not violate the entry/exit criteria. 9758 CS->getCapturedDecl()->setNothrow(); 9759 for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target); 9760 ThisCaptureLevel > 1; --ThisCaptureLevel) { 9761 CS = cast<CapturedStmt>(CS->getCapturedStmt()); 9762 // 1.2.2 OpenMP Language Terminology 9763 // Structured block - An executable statement with a single entry at the 9764 // top and a single exit at the bottom. 9765 // The point of exit cannot be a branch out of the structured block. 9766 // longjmp() and throw() must not violate the entry/exit criteria. 9767 CS->getCapturedDecl()->setNothrow(); 9768 } 9769 9770 // OpenMP [2.16, Nesting of Regions] 9771 // If specified, a teams construct must be contained within a target 9772 // construct. That target construct must contain no statements or directives 9773 // outside of the teams construct. 9774 if (DSAStack->hasInnerTeamsRegion()) { 9775 const Stmt *S = CS->IgnoreContainers(/*IgnoreCaptured=*/true); 9776 bool OMPTeamsFound = true; 9777 if (const auto *CS = dyn_cast<CompoundStmt>(S)) { 9778 auto I = CS->body_begin(); 9779 while (I != CS->body_end()) { 9780 const auto *OED = dyn_cast<OMPExecutableDirective>(*I); 9781 if (!OED || !isOpenMPTeamsDirective(OED->getDirectiveKind()) || 9782 OMPTeamsFound) { 9783 9784 OMPTeamsFound = false; 9785 break; 9786 } 9787 ++I; 9788 } 9789 assert(I != CS->body_end() && "Not found statement"); 9790 S = *I; 9791 } else { 9792 const auto *OED = dyn_cast<OMPExecutableDirective>(S); 9793 OMPTeamsFound = OED && isOpenMPTeamsDirective(OED->getDirectiveKind()); 9794 } 9795 if (!OMPTeamsFound) { 9796 Diag(StartLoc, diag::err_omp_target_contains_not_only_teams); 9797 Diag(DSAStack->getInnerTeamsRegionLoc(), 9798 diag::note_omp_nested_teams_construct_here); 9799 Diag(S->getBeginLoc(), diag::note_omp_nested_statement_here) 9800 << isa<OMPExecutableDirective>(S); 9801 return StmtError(); 9802 } 9803 } 9804 9805 setFunctionHasBranchProtectedScope(); 9806 9807 return OMPTargetDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt); 9808 } 9809 9810 StmtResult 9811 Sema::ActOnOpenMPTargetParallelDirective(ArrayRef<OMPClause *> Clauses, 9812 Stmt *AStmt, SourceLocation StartLoc, 9813 SourceLocation EndLoc) { 9814 if (!AStmt) 9815 return StmtError(); 9816 9817 auto *CS = cast<CapturedStmt>(AStmt); 9818 // 1.2.2 OpenMP Language Terminology 9819 // Structured block - An executable statement with a single entry at the 9820 // top and a single exit at the bottom. 9821 // The point of exit cannot be a branch out of the structured block. 9822 // longjmp() and throw() must not violate the entry/exit criteria. 9823 CS->getCapturedDecl()->setNothrow(); 9824 for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_parallel); 9825 ThisCaptureLevel > 1; --ThisCaptureLevel) { 9826 CS = cast<CapturedStmt>(CS->getCapturedStmt()); 9827 // 1.2.2 OpenMP Language Terminology 9828 // Structured block - An executable statement with a single entry at the 9829 // top and a single exit at the bottom. 9830 // The point of exit cannot be a branch out of the structured block. 9831 // longjmp() and throw() must not violate the entry/exit criteria. 9832 CS->getCapturedDecl()->setNothrow(); 9833 } 9834 9835 setFunctionHasBranchProtectedScope(); 9836 9837 return OMPTargetParallelDirective::Create(Context, StartLoc, EndLoc, Clauses, 9838 AStmt); 9839 } 9840 9841 StmtResult Sema::ActOnOpenMPTargetParallelForDirective( 9842 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, 9843 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) { 9844 if (!AStmt) 9845 return StmtError(); 9846 9847 auto *CS = cast<CapturedStmt>(AStmt); 9848 // 1.2.2 OpenMP Language Terminology 9849 // Structured block - An executable statement with a single entry at the 9850 // top and a single exit at the bottom. 9851 // The point of exit cannot be a branch out of the structured block. 9852 // longjmp() and throw() must not violate the entry/exit criteria. 9853 CS->getCapturedDecl()->setNothrow(); 9854 for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_parallel_for); 9855 ThisCaptureLevel > 1; --ThisCaptureLevel) { 9856 CS = cast<CapturedStmt>(CS->getCapturedStmt()); 9857 // 1.2.2 OpenMP Language Terminology 9858 // Structured block - An executable statement with a single entry at the 9859 // top and a single exit at the bottom. 9860 // The point of exit cannot be a branch out of the structured block. 9861 // longjmp() and throw() must not violate the entry/exit criteria. 9862 CS->getCapturedDecl()->setNothrow(); 9863 } 9864 9865 OMPLoopDirective::HelperExprs B; 9866 // In presence of clause 'collapse' or 'ordered' with number of loops, it will 9867 // define the nested loops number. 9868 unsigned NestedLoopCount = 9869 checkOpenMPLoop(OMPD_target_parallel_for, getCollapseNumberExpr(Clauses), 9870 getOrderedNumberExpr(Clauses), CS, *this, *DSAStack, 9871 VarsWithImplicitDSA, B); 9872 if (NestedLoopCount == 0) 9873 return StmtError(); 9874 9875 assert((CurContext->isDependentContext() || B.builtAll()) && 9876 "omp target parallel for loop exprs were not built"); 9877 9878 if (!CurContext->isDependentContext()) { 9879 // Finalize the clauses that need pre-built expressions for CodeGen. 9880 for (OMPClause *C : Clauses) { 9881 if (auto *LC = dyn_cast<OMPLinearClause>(C)) 9882 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef), 9883 B.NumIterations, *this, CurScope, 9884 DSAStack)) 9885 return StmtError(); 9886 } 9887 } 9888 9889 setFunctionHasBranchProtectedScope(); 9890 return OMPTargetParallelForDirective::Create(Context, StartLoc, EndLoc, 9891 NestedLoopCount, Clauses, AStmt, 9892 B, DSAStack->isCancelRegion()); 9893 } 9894 9895 /// Check for existence of a map clause in the list of clauses. 9896 static bool hasClauses(ArrayRef<OMPClause *> Clauses, 9897 const OpenMPClauseKind K) { 9898 return llvm::any_of( 9899 Clauses, [K](const OMPClause *C) { return C->getClauseKind() == K; }); 9900 } 9901 9902 template <typename... Params> 9903 static bool hasClauses(ArrayRef<OMPClause *> Clauses, const OpenMPClauseKind K, 9904 const Params... ClauseTypes) { 9905 return hasClauses(Clauses, K) || hasClauses(Clauses, ClauseTypes...); 9906 } 9907 9908 StmtResult Sema::ActOnOpenMPTargetDataDirective(ArrayRef<OMPClause *> Clauses, 9909 Stmt *AStmt, 9910 SourceLocation StartLoc, 9911 SourceLocation EndLoc) { 9912 if (!AStmt) 9913 return StmtError(); 9914 9915 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected"); 9916 9917 // OpenMP [2.10.1, Restrictions, p. 97] 9918 // At least one map clause must appear on the directive. 9919 if (!hasClauses(Clauses, OMPC_map, OMPC_use_device_ptr)) { 9920 Diag(StartLoc, diag::err_omp_no_clause_for_directive) 9921 << "'map' or 'use_device_ptr'" 9922 << getOpenMPDirectiveName(OMPD_target_data); 9923 return StmtError(); 9924 } 9925 9926 setFunctionHasBranchProtectedScope(); 9927 9928 return OMPTargetDataDirective::Create(Context, StartLoc, EndLoc, Clauses, 9929 AStmt); 9930 } 9931 9932 StmtResult 9933 Sema::ActOnOpenMPTargetEnterDataDirective(ArrayRef<OMPClause *> Clauses, 9934 SourceLocation StartLoc, 9935 SourceLocation EndLoc, Stmt *AStmt) { 9936 if (!AStmt) 9937 return StmtError(); 9938 9939 auto *CS = cast<CapturedStmt>(AStmt); 9940 // 1.2.2 OpenMP Language Terminology 9941 // Structured block - An executable statement with a single entry at the 9942 // top and a single exit at the bottom. 9943 // The point of exit cannot be a branch out of the structured block. 9944 // longjmp() and throw() must not violate the entry/exit criteria. 9945 CS->getCapturedDecl()->setNothrow(); 9946 for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_enter_data); 9947 ThisCaptureLevel > 1; --ThisCaptureLevel) { 9948 CS = cast<CapturedStmt>(CS->getCapturedStmt()); 9949 // 1.2.2 OpenMP Language Terminology 9950 // Structured block - An executable statement with a single entry at the 9951 // top and a single exit at the bottom. 9952 // The point of exit cannot be a branch out of the structured block. 9953 // longjmp() and throw() must not violate the entry/exit criteria. 9954 CS->getCapturedDecl()->setNothrow(); 9955 } 9956 9957 // OpenMP [2.10.2, Restrictions, p. 99] 9958 // At least one map clause must appear on the directive. 9959 if (!hasClauses(Clauses, OMPC_map)) { 9960 Diag(StartLoc, diag::err_omp_no_clause_for_directive) 9961 << "'map'" << getOpenMPDirectiveName(OMPD_target_enter_data); 9962 return StmtError(); 9963 } 9964 9965 return OMPTargetEnterDataDirective::Create(Context, StartLoc, EndLoc, Clauses, 9966 AStmt); 9967 } 9968 9969 StmtResult 9970 Sema::ActOnOpenMPTargetExitDataDirective(ArrayRef<OMPClause *> Clauses, 9971 SourceLocation StartLoc, 9972 SourceLocation EndLoc, Stmt *AStmt) { 9973 if (!AStmt) 9974 return StmtError(); 9975 9976 auto *CS = cast<CapturedStmt>(AStmt); 9977 // 1.2.2 OpenMP Language Terminology 9978 // Structured block - An executable statement with a single entry at the 9979 // top and a single exit at the bottom. 9980 // The point of exit cannot be a branch out of the structured block. 9981 // longjmp() and throw() must not violate the entry/exit criteria. 9982 CS->getCapturedDecl()->setNothrow(); 9983 for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_exit_data); 9984 ThisCaptureLevel > 1; --ThisCaptureLevel) { 9985 CS = cast<CapturedStmt>(CS->getCapturedStmt()); 9986 // 1.2.2 OpenMP Language Terminology 9987 // Structured block - An executable statement with a single entry at the 9988 // top and a single exit at the bottom. 9989 // The point of exit cannot be a branch out of the structured block. 9990 // longjmp() and throw() must not violate the entry/exit criteria. 9991 CS->getCapturedDecl()->setNothrow(); 9992 } 9993 9994 // OpenMP [2.10.3, Restrictions, p. 102] 9995 // At least one map clause must appear on the directive. 9996 if (!hasClauses(Clauses, OMPC_map)) { 9997 Diag(StartLoc, diag::err_omp_no_clause_for_directive) 9998 << "'map'" << getOpenMPDirectiveName(OMPD_target_exit_data); 9999 return StmtError(); 10000 } 10001 10002 return OMPTargetExitDataDirective::Create(Context, StartLoc, EndLoc, Clauses, 10003 AStmt); 10004 } 10005 10006 StmtResult Sema::ActOnOpenMPTargetUpdateDirective(ArrayRef<OMPClause *> Clauses, 10007 SourceLocation StartLoc, 10008 SourceLocation EndLoc, 10009 Stmt *AStmt) { 10010 if (!AStmt) 10011 return StmtError(); 10012 10013 auto *CS = cast<CapturedStmt>(AStmt); 10014 // 1.2.2 OpenMP Language Terminology 10015 // Structured block - An executable statement with a single entry at the 10016 // top and a single exit at the bottom. 10017 // The point of exit cannot be a branch out of the structured block. 10018 // longjmp() and throw() must not violate the entry/exit criteria. 10019 CS->getCapturedDecl()->setNothrow(); 10020 for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_update); 10021 ThisCaptureLevel > 1; --ThisCaptureLevel) { 10022 CS = cast<CapturedStmt>(CS->getCapturedStmt()); 10023 // 1.2.2 OpenMP Language Terminology 10024 // Structured block - An executable statement with a single entry at the 10025 // top and a single exit at the bottom. 10026 // The point of exit cannot be a branch out of the structured block. 10027 // longjmp() and throw() must not violate the entry/exit criteria. 10028 CS->getCapturedDecl()->setNothrow(); 10029 } 10030 10031 if (!hasClauses(Clauses, OMPC_to, OMPC_from)) { 10032 Diag(StartLoc, diag::err_omp_at_least_one_motion_clause_required); 10033 return StmtError(); 10034 } 10035 return OMPTargetUpdateDirective::Create(Context, StartLoc, EndLoc, Clauses, 10036 AStmt); 10037 } 10038 10039 StmtResult Sema::ActOnOpenMPTeamsDirective(ArrayRef<OMPClause *> Clauses, 10040 Stmt *AStmt, SourceLocation StartLoc, 10041 SourceLocation EndLoc) { 10042 if (!AStmt) 10043 return StmtError(); 10044 10045 auto *CS = cast<CapturedStmt>(AStmt); 10046 // 1.2.2 OpenMP Language Terminology 10047 // Structured block - An executable statement with a single entry at the 10048 // top and a single exit at the bottom. 10049 // The point of exit cannot be a branch out of the structured block. 10050 // longjmp() and throw() must not violate the entry/exit criteria. 10051 CS->getCapturedDecl()->setNothrow(); 10052 10053 setFunctionHasBranchProtectedScope(); 10054 10055 DSAStack->setParentTeamsRegionLoc(StartLoc); 10056 10057 return OMPTeamsDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt); 10058 } 10059 10060 StmtResult 10061 Sema::ActOnOpenMPCancellationPointDirective(SourceLocation StartLoc, 10062 SourceLocation EndLoc, 10063 OpenMPDirectiveKind CancelRegion) { 10064 if (DSAStack->isParentNowaitRegion()) { 10065 Diag(StartLoc, diag::err_omp_parent_cancel_region_nowait) << 0; 10066 return StmtError(); 10067 } 10068 if (DSAStack->isParentOrderedRegion()) { 10069 Diag(StartLoc, diag::err_omp_parent_cancel_region_ordered) << 0; 10070 return StmtError(); 10071 } 10072 return OMPCancellationPointDirective::Create(Context, StartLoc, EndLoc, 10073 CancelRegion); 10074 } 10075 10076 StmtResult Sema::ActOnOpenMPCancelDirective(ArrayRef<OMPClause *> Clauses, 10077 SourceLocation StartLoc, 10078 SourceLocation EndLoc, 10079 OpenMPDirectiveKind CancelRegion) { 10080 if (DSAStack->isParentNowaitRegion()) { 10081 Diag(StartLoc, diag::err_omp_parent_cancel_region_nowait) << 1; 10082 return StmtError(); 10083 } 10084 if (DSAStack->isParentOrderedRegion()) { 10085 Diag(StartLoc, diag::err_omp_parent_cancel_region_ordered) << 1; 10086 return StmtError(); 10087 } 10088 DSAStack->setParentCancelRegion(/*Cancel=*/true); 10089 return OMPCancelDirective::Create(Context, StartLoc, EndLoc, Clauses, 10090 CancelRegion); 10091 } 10092 10093 static bool checkGrainsizeNumTasksClauses(Sema &S, 10094 ArrayRef<OMPClause *> Clauses) { 10095 const OMPClause *PrevClause = nullptr; 10096 bool ErrorFound = false; 10097 for (const OMPClause *C : Clauses) { 10098 if (C->getClauseKind() == OMPC_grainsize || 10099 C->getClauseKind() == OMPC_num_tasks) { 10100 if (!PrevClause) 10101 PrevClause = C; 10102 else if (PrevClause->getClauseKind() != C->getClauseKind()) { 10103 S.Diag(C->getBeginLoc(), diag::err_omp_clauses_mutually_exclusive) 10104 << getOpenMPClauseName(C->getClauseKind()) 10105 << getOpenMPClauseName(PrevClause->getClauseKind()); 10106 S.Diag(PrevClause->getBeginLoc(), diag::note_omp_previous_clause) 10107 << getOpenMPClauseName(PrevClause->getClauseKind()); 10108 ErrorFound = true; 10109 } 10110 } 10111 } 10112 return ErrorFound; 10113 } 10114 10115 static bool checkReductionClauseWithNogroup(Sema &S, 10116 ArrayRef<OMPClause *> Clauses) { 10117 const OMPClause *ReductionClause = nullptr; 10118 const OMPClause *NogroupClause = nullptr; 10119 for (const OMPClause *C : Clauses) { 10120 if (C->getClauseKind() == OMPC_reduction) { 10121 ReductionClause = C; 10122 if (NogroupClause) 10123 break; 10124 continue; 10125 } 10126 if (C->getClauseKind() == OMPC_nogroup) { 10127 NogroupClause = C; 10128 if (ReductionClause) 10129 break; 10130 continue; 10131 } 10132 } 10133 if (ReductionClause && NogroupClause) { 10134 S.Diag(ReductionClause->getBeginLoc(), diag::err_omp_reduction_with_nogroup) 10135 << SourceRange(NogroupClause->getBeginLoc(), 10136 NogroupClause->getEndLoc()); 10137 return true; 10138 } 10139 return false; 10140 } 10141 10142 StmtResult Sema::ActOnOpenMPTaskLoopDirective( 10143 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, 10144 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) { 10145 if (!AStmt) 10146 return StmtError(); 10147 10148 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected"); 10149 OMPLoopDirective::HelperExprs B; 10150 // In presence of clause 'collapse' or 'ordered' with number of loops, it will 10151 // define the nested loops number. 10152 unsigned NestedLoopCount = 10153 checkOpenMPLoop(OMPD_taskloop, getCollapseNumberExpr(Clauses), 10154 /*OrderedLoopCountExpr=*/nullptr, AStmt, *this, *DSAStack, 10155 VarsWithImplicitDSA, B); 10156 if (NestedLoopCount == 0) 10157 return StmtError(); 10158 10159 assert((CurContext->isDependentContext() || B.builtAll()) && 10160 "omp for loop exprs were not built"); 10161 10162 // OpenMP, [2.9.2 taskloop Construct, Restrictions] 10163 // The grainsize clause and num_tasks clause are mutually exclusive and may 10164 // not appear on the same taskloop directive. 10165 if (checkGrainsizeNumTasksClauses(*this, Clauses)) 10166 return StmtError(); 10167 // OpenMP, [2.9.2 taskloop Construct, Restrictions] 10168 // If a reduction clause is present on the taskloop directive, the nogroup 10169 // clause must not be specified. 10170 if (checkReductionClauseWithNogroup(*this, Clauses)) 10171 return StmtError(); 10172 10173 setFunctionHasBranchProtectedScope(); 10174 return OMPTaskLoopDirective::Create(Context, StartLoc, EndLoc, 10175 NestedLoopCount, Clauses, AStmt, B, 10176 DSAStack->isCancelRegion()); 10177 } 10178 10179 StmtResult Sema::ActOnOpenMPTaskLoopSimdDirective( 10180 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, 10181 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) { 10182 if (!AStmt) 10183 return StmtError(); 10184 10185 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected"); 10186 OMPLoopDirective::HelperExprs B; 10187 // In presence of clause 'collapse' or 'ordered' with number of loops, it will 10188 // define the nested loops number. 10189 unsigned NestedLoopCount = 10190 checkOpenMPLoop(OMPD_taskloop_simd, getCollapseNumberExpr(Clauses), 10191 /*OrderedLoopCountExpr=*/nullptr, AStmt, *this, *DSAStack, 10192 VarsWithImplicitDSA, B); 10193 if (NestedLoopCount == 0) 10194 return StmtError(); 10195 10196 assert((CurContext->isDependentContext() || B.builtAll()) && 10197 "omp for loop exprs were not built"); 10198 10199 if (!CurContext->isDependentContext()) { 10200 // Finalize the clauses that need pre-built expressions for CodeGen. 10201 for (OMPClause *C : Clauses) { 10202 if (auto *LC = dyn_cast<OMPLinearClause>(C)) 10203 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef), 10204 B.NumIterations, *this, CurScope, 10205 DSAStack)) 10206 return StmtError(); 10207 } 10208 } 10209 10210 // OpenMP, [2.9.2 taskloop Construct, Restrictions] 10211 // The grainsize clause and num_tasks clause are mutually exclusive and may 10212 // not appear on the same taskloop directive. 10213 if (checkGrainsizeNumTasksClauses(*this, Clauses)) 10214 return StmtError(); 10215 // OpenMP, [2.9.2 taskloop Construct, Restrictions] 10216 // If a reduction clause is present on the taskloop directive, the nogroup 10217 // clause must not be specified. 10218 if (checkReductionClauseWithNogroup(*this, Clauses)) 10219 return StmtError(); 10220 if (checkSimdlenSafelenSpecified(*this, Clauses)) 10221 return StmtError(); 10222 10223 setFunctionHasBranchProtectedScope(); 10224 return OMPTaskLoopSimdDirective::Create(Context, StartLoc, EndLoc, 10225 NestedLoopCount, Clauses, AStmt, B); 10226 } 10227 10228 StmtResult Sema::ActOnOpenMPMasterTaskLoopDirective( 10229 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, 10230 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) { 10231 if (!AStmt) 10232 return StmtError(); 10233 10234 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected"); 10235 OMPLoopDirective::HelperExprs B; 10236 // In presence of clause 'collapse' or 'ordered' with number of loops, it will 10237 // define the nested loops number. 10238 unsigned NestedLoopCount = 10239 checkOpenMPLoop(OMPD_master_taskloop, getCollapseNumberExpr(Clauses), 10240 /*OrderedLoopCountExpr=*/nullptr, AStmt, *this, *DSAStack, 10241 VarsWithImplicitDSA, B); 10242 if (NestedLoopCount == 0) 10243 return StmtError(); 10244 10245 assert((CurContext->isDependentContext() || B.builtAll()) && 10246 "omp for loop exprs were not built"); 10247 10248 // OpenMP, [2.9.2 taskloop Construct, Restrictions] 10249 // The grainsize clause and num_tasks clause are mutually exclusive and may 10250 // not appear on the same taskloop directive. 10251 if (checkGrainsizeNumTasksClauses(*this, Clauses)) 10252 return StmtError(); 10253 // OpenMP, [2.9.2 taskloop Construct, Restrictions] 10254 // If a reduction clause is present on the taskloop directive, the nogroup 10255 // clause must not be specified. 10256 if (checkReductionClauseWithNogroup(*this, Clauses)) 10257 return StmtError(); 10258 10259 setFunctionHasBranchProtectedScope(); 10260 return OMPMasterTaskLoopDirective::Create(Context, StartLoc, EndLoc, 10261 NestedLoopCount, Clauses, AStmt, B, 10262 DSAStack->isCancelRegion()); 10263 } 10264 10265 StmtResult Sema::ActOnOpenMPMasterTaskLoopSimdDirective( 10266 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, 10267 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) { 10268 if (!AStmt) 10269 return StmtError(); 10270 10271 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected"); 10272 OMPLoopDirective::HelperExprs B; 10273 // In presence of clause 'collapse' or 'ordered' with number of loops, it will 10274 // define the nested loops number. 10275 unsigned NestedLoopCount = 10276 checkOpenMPLoop(OMPD_master_taskloop_simd, getCollapseNumberExpr(Clauses), 10277 /*OrderedLoopCountExpr=*/nullptr, AStmt, *this, *DSAStack, 10278 VarsWithImplicitDSA, B); 10279 if (NestedLoopCount == 0) 10280 return StmtError(); 10281 10282 assert((CurContext->isDependentContext() || B.builtAll()) && 10283 "omp for loop exprs were not built"); 10284 10285 if (!CurContext->isDependentContext()) { 10286 // Finalize the clauses that need pre-built expressions for CodeGen. 10287 for (OMPClause *C : Clauses) { 10288 if (auto *LC = dyn_cast<OMPLinearClause>(C)) 10289 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef), 10290 B.NumIterations, *this, CurScope, 10291 DSAStack)) 10292 return StmtError(); 10293 } 10294 } 10295 10296 // OpenMP, [2.9.2 taskloop Construct, Restrictions] 10297 // The grainsize clause and num_tasks clause are mutually exclusive and may 10298 // not appear on the same taskloop directive. 10299 if (checkGrainsizeNumTasksClauses(*this, Clauses)) 10300 return StmtError(); 10301 // OpenMP, [2.9.2 taskloop Construct, Restrictions] 10302 // If a reduction clause is present on the taskloop directive, the nogroup 10303 // clause must not be specified. 10304 if (checkReductionClauseWithNogroup(*this, Clauses)) 10305 return StmtError(); 10306 if (checkSimdlenSafelenSpecified(*this, Clauses)) 10307 return StmtError(); 10308 10309 setFunctionHasBranchProtectedScope(); 10310 return OMPMasterTaskLoopSimdDirective::Create( 10311 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B); 10312 } 10313 10314 StmtResult Sema::ActOnOpenMPParallelMasterTaskLoopDirective( 10315 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, 10316 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) { 10317 if (!AStmt) 10318 return StmtError(); 10319 10320 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected"); 10321 auto *CS = cast<CapturedStmt>(AStmt); 10322 // 1.2.2 OpenMP Language Terminology 10323 // Structured block - An executable statement with a single entry at the 10324 // top and a single exit at the bottom. 10325 // The point of exit cannot be a branch out of the structured block. 10326 // longjmp() and throw() must not violate the entry/exit criteria. 10327 CS->getCapturedDecl()->setNothrow(); 10328 for (int ThisCaptureLevel = 10329 getOpenMPCaptureLevels(OMPD_parallel_master_taskloop); 10330 ThisCaptureLevel > 1; --ThisCaptureLevel) { 10331 CS = cast<CapturedStmt>(CS->getCapturedStmt()); 10332 // 1.2.2 OpenMP Language Terminology 10333 // Structured block - An executable statement with a single entry at the 10334 // top and a single exit at the bottom. 10335 // The point of exit cannot be a branch out of the structured block. 10336 // longjmp() and throw() must not violate the entry/exit criteria. 10337 CS->getCapturedDecl()->setNothrow(); 10338 } 10339 10340 OMPLoopDirective::HelperExprs B; 10341 // In presence of clause 'collapse' or 'ordered' with number of loops, it will 10342 // define the nested loops number. 10343 unsigned NestedLoopCount = checkOpenMPLoop( 10344 OMPD_parallel_master_taskloop, getCollapseNumberExpr(Clauses), 10345 /*OrderedLoopCountExpr=*/nullptr, CS, *this, *DSAStack, 10346 VarsWithImplicitDSA, B); 10347 if (NestedLoopCount == 0) 10348 return StmtError(); 10349 10350 assert((CurContext->isDependentContext() || B.builtAll()) && 10351 "omp for loop exprs were not built"); 10352 10353 // OpenMP, [2.9.2 taskloop Construct, Restrictions] 10354 // The grainsize clause and num_tasks clause are mutually exclusive and may 10355 // not appear on the same taskloop directive. 10356 if (checkGrainsizeNumTasksClauses(*this, Clauses)) 10357 return StmtError(); 10358 // OpenMP, [2.9.2 taskloop Construct, Restrictions] 10359 // If a reduction clause is present on the taskloop directive, the nogroup 10360 // clause must not be specified. 10361 if (checkReductionClauseWithNogroup(*this, Clauses)) 10362 return StmtError(); 10363 10364 setFunctionHasBranchProtectedScope(); 10365 return OMPParallelMasterTaskLoopDirective::Create( 10366 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B, 10367 DSAStack->isCancelRegion()); 10368 } 10369 10370 StmtResult Sema::ActOnOpenMPParallelMasterTaskLoopSimdDirective( 10371 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, 10372 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) { 10373 if (!AStmt) 10374 return StmtError(); 10375 10376 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected"); 10377 auto *CS = cast<CapturedStmt>(AStmt); 10378 // 1.2.2 OpenMP Language Terminology 10379 // Structured block - An executable statement with a single entry at the 10380 // top and a single exit at the bottom. 10381 // The point of exit cannot be a branch out of the structured block. 10382 // longjmp() and throw() must not violate the entry/exit criteria. 10383 CS->getCapturedDecl()->setNothrow(); 10384 for (int ThisCaptureLevel = 10385 getOpenMPCaptureLevels(OMPD_parallel_master_taskloop_simd); 10386 ThisCaptureLevel > 1; --ThisCaptureLevel) { 10387 CS = cast<CapturedStmt>(CS->getCapturedStmt()); 10388 // 1.2.2 OpenMP Language Terminology 10389 // Structured block - An executable statement with a single entry at the 10390 // top and a single exit at the bottom. 10391 // The point of exit cannot be a branch out of the structured block. 10392 // longjmp() and throw() must not violate the entry/exit criteria. 10393 CS->getCapturedDecl()->setNothrow(); 10394 } 10395 10396 OMPLoopDirective::HelperExprs B; 10397 // In presence of clause 'collapse' or 'ordered' with number of loops, it will 10398 // define the nested loops number. 10399 unsigned NestedLoopCount = checkOpenMPLoop( 10400 OMPD_parallel_master_taskloop_simd, getCollapseNumberExpr(Clauses), 10401 /*OrderedLoopCountExpr=*/nullptr, CS, *this, *DSAStack, 10402 VarsWithImplicitDSA, B); 10403 if (NestedLoopCount == 0) 10404 return StmtError(); 10405 10406 assert((CurContext->isDependentContext() || B.builtAll()) && 10407 "omp for loop exprs were not built"); 10408 10409 if (!CurContext->isDependentContext()) { 10410 // Finalize the clauses that need pre-built expressions for CodeGen. 10411 for (OMPClause *C : Clauses) { 10412 if (auto *LC = dyn_cast<OMPLinearClause>(C)) 10413 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef), 10414 B.NumIterations, *this, CurScope, 10415 DSAStack)) 10416 return StmtError(); 10417 } 10418 } 10419 10420 // OpenMP, [2.9.2 taskloop Construct, Restrictions] 10421 // The grainsize clause and num_tasks clause are mutually exclusive and may 10422 // not appear on the same taskloop directive. 10423 if (checkGrainsizeNumTasksClauses(*this, Clauses)) 10424 return StmtError(); 10425 // OpenMP, [2.9.2 taskloop Construct, Restrictions] 10426 // If a reduction clause is present on the taskloop directive, the nogroup 10427 // clause must not be specified. 10428 if (checkReductionClauseWithNogroup(*this, Clauses)) 10429 return StmtError(); 10430 if (checkSimdlenSafelenSpecified(*this, Clauses)) 10431 return StmtError(); 10432 10433 setFunctionHasBranchProtectedScope(); 10434 return OMPParallelMasterTaskLoopSimdDirective::Create( 10435 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B); 10436 } 10437 10438 StmtResult Sema::ActOnOpenMPDistributeDirective( 10439 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, 10440 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) { 10441 if (!AStmt) 10442 return StmtError(); 10443 10444 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected"); 10445 OMPLoopDirective::HelperExprs B; 10446 // In presence of clause 'collapse' with number of loops, it will 10447 // define the nested loops number. 10448 unsigned NestedLoopCount = 10449 checkOpenMPLoop(OMPD_distribute, getCollapseNumberExpr(Clauses), 10450 nullptr /*ordered not a clause on distribute*/, AStmt, 10451 *this, *DSAStack, VarsWithImplicitDSA, B); 10452 if (NestedLoopCount == 0) 10453 return StmtError(); 10454 10455 assert((CurContext->isDependentContext() || B.builtAll()) && 10456 "omp for loop exprs were not built"); 10457 10458 setFunctionHasBranchProtectedScope(); 10459 return OMPDistributeDirective::Create(Context, StartLoc, EndLoc, 10460 NestedLoopCount, Clauses, AStmt, B); 10461 } 10462 10463 StmtResult Sema::ActOnOpenMPDistributeParallelForDirective( 10464 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, 10465 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) { 10466 if (!AStmt) 10467 return StmtError(); 10468 10469 auto *CS = cast<CapturedStmt>(AStmt); 10470 // 1.2.2 OpenMP Language Terminology 10471 // Structured block - An executable statement with a single entry at the 10472 // top and a single exit at the bottom. 10473 // The point of exit cannot be a branch out of the structured block. 10474 // longjmp() and throw() must not violate the entry/exit criteria. 10475 CS->getCapturedDecl()->setNothrow(); 10476 for (int ThisCaptureLevel = 10477 getOpenMPCaptureLevels(OMPD_distribute_parallel_for); 10478 ThisCaptureLevel > 1; --ThisCaptureLevel) { 10479 CS = cast<CapturedStmt>(CS->getCapturedStmt()); 10480 // 1.2.2 OpenMP Language Terminology 10481 // Structured block - An executable statement with a single entry at the 10482 // top and a single exit at the bottom. 10483 // The point of exit cannot be a branch out of the structured block. 10484 // longjmp() and throw() must not violate the entry/exit criteria. 10485 CS->getCapturedDecl()->setNothrow(); 10486 } 10487 10488 OMPLoopDirective::HelperExprs B; 10489 // In presence of clause 'collapse' with number of loops, it will 10490 // define the nested loops number. 10491 unsigned NestedLoopCount = checkOpenMPLoop( 10492 OMPD_distribute_parallel_for, getCollapseNumberExpr(Clauses), 10493 nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStack, 10494 VarsWithImplicitDSA, B); 10495 if (NestedLoopCount == 0) 10496 return StmtError(); 10497 10498 assert((CurContext->isDependentContext() || B.builtAll()) && 10499 "omp for loop exprs were not built"); 10500 10501 setFunctionHasBranchProtectedScope(); 10502 return OMPDistributeParallelForDirective::Create( 10503 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B, 10504 DSAStack->isCancelRegion()); 10505 } 10506 10507 StmtResult Sema::ActOnOpenMPDistributeParallelForSimdDirective( 10508 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, 10509 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) { 10510 if (!AStmt) 10511 return StmtError(); 10512 10513 auto *CS = cast<CapturedStmt>(AStmt); 10514 // 1.2.2 OpenMP Language Terminology 10515 // Structured block - An executable statement with a single entry at the 10516 // top and a single exit at the bottom. 10517 // The point of exit cannot be a branch out of the structured block. 10518 // longjmp() and throw() must not violate the entry/exit criteria. 10519 CS->getCapturedDecl()->setNothrow(); 10520 for (int ThisCaptureLevel = 10521 getOpenMPCaptureLevels(OMPD_distribute_parallel_for_simd); 10522 ThisCaptureLevel > 1; --ThisCaptureLevel) { 10523 CS = cast<CapturedStmt>(CS->getCapturedStmt()); 10524 // 1.2.2 OpenMP Language Terminology 10525 // Structured block - An executable statement with a single entry at the 10526 // top and a single exit at the bottom. 10527 // The point of exit cannot be a branch out of the structured block. 10528 // longjmp() and throw() must not violate the entry/exit criteria. 10529 CS->getCapturedDecl()->setNothrow(); 10530 } 10531 10532 OMPLoopDirective::HelperExprs B; 10533 // In presence of clause 'collapse' with number of loops, it will 10534 // define the nested loops number. 10535 unsigned NestedLoopCount = checkOpenMPLoop( 10536 OMPD_distribute_parallel_for_simd, getCollapseNumberExpr(Clauses), 10537 nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStack, 10538 VarsWithImplicitDSA, B); 10539 if (NestedLoopCount == 0) 10540 return StmtError(); 10541 10542 assert((CurContext->isDependentContext() || B.builtAll()) && 10543 "omp for loop exprs were not built"); 10544 10545 if (!CurContext->isDependentContext()) { 10546 // Finalize the clauses that need pre-built expressions for CodeGen. 10547 for (OMPClause *C : Clauses) { 10548 if (auto *LC = dyn_cast<OMPLinearClause>(C)) 10549 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef), 10550 B.NumIterations, *this, CurScope, 10551 DSAStack)) 10552 return StmtError(); 10553 } 10554 } 10555 10556 if (checkSimdlenSafelenSpecified(*this, Clauses)) 10557 return StmtError(); 10558 10559 setFunctionHasBranchProtectedScope(); 10560 return OMPDistributeParallelForSimdDirective::Create( 10561 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B); 10562 } 10563 10564 StmtResult Sema::ActOnOpenMPDistributeSimdDirective( 10565 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, 10566 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) { 10567 if (!AStmt) 10568 return StmtError(); 10569 10570 auto *CS = cast<CapturedStmt>(AStmt); 10571 // 1.2.2 OpenMP Language Terminology 10572 // Structured block - An executable statement with a single entry at the 10573 // top and a single exit at the bottom. 10574 // The point of exit cannot be a branch out of the structured block. 10575 // longjmp() and throw() must not violate the entry/exit criteria. 10576 CS->getCapturedDecl()->setNothrow(); 10577 for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_distribute_simd); 10578 ThisCaptureLevel > 1; --ThisCaptureLevel) { 10579 CS = cast<CapturedStmt>(CS->getCapturedStmt()); 10580 // 1.2.2 OpenMP Language Terminology 10581 // Structured block - An executable statement with a single entry at the 10582 // top and a single exit at the bottom. 10583 // The point of exit cannot be a branch out of the structured block. 10584 // longjmp() and throw() must not violate the entry/exit criteria. 10585 CS->getCapturedDecl()->setNothrow(); 10586 } 10587 10588 OMPLoopDirective::HelperExprs B; 10589 // In presence of clause 'collapse' with number of loops, it will 10590 // define the nested loops number. 10591 unsigned NestedLoopCount = 10592 checkOpenMPLoop(OMPD_distribute_simd, getCollapseNumberExpr(Clauses), 10593 nullptr /*ordered not a clause on distribute*/, CS, *this, 10594 *DSAStack, VarsWithImplicitDSA, B); 10595 if (NestedLoopCount == 0) 10596 return StmtError(); 10597 10598 assert((CurContext->isDependentContext() || B.builtAll()) && 10599 "omp for loop exprs were not built"); 10600 10601 if (!CurContext->isDependentContext()) { 10602 // Finalize the clauses that need pre-built expressions for CodeGen. 10603 for (OMPClause *C : Clauses) { 10604 if (auto *LC = dyn_cast<OMPLinearClause>(C)) 10605 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef), 10606 B.NumIterations, *this, CurScope, 10607 DSAStack)) 10608 return StmtError(); 10609 } 10610 } 10611 10612 if (checkSimdlenSafelenSpecified(*this, Clauses)) 10613 return StmtError(); 10614 10615 setFunctionHasBranchProtectedScope(); 10616 return OMPDistributeSimdDirective::Create(Context, StartLoc, EndLoc, 10617 NestedLoopCount, Clauses, AStmt, B); 10618 } 10619 10620 StmtResult Sema::ActOnOpenMPTargetParallelForSimdDirective( 10621 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, 10622 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) { 10623 if (!AStmt) 10624 return StmtError(); 10625 10626 auto *CS = cast<CapturedStmt>(AStmt); 10627 // 1.2.2 OpenMP Language Terminology 10628 // Structured block - An executable statement with a single entry at the 10629 // top and a single exit at the bottom. 10630 // The point of exit cannot be a branch out of the structured block. 10631 // longjmp() and throw() must not violate the entry/exit criteria. 10632 CS->getCapturedDecl()->setNothrow(); 10633 for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_parallel_for); 10634 ThisCaptureLevel > 1; --ThisCaptureLevel) { 10635 CS = cast<CapturedStmt>(CS->getCapturedStmt()); 10636 // 1.2.2 OpenMP Language Terminology 10637 // Structured block - An executable statement with a single entry at the 10638 // top and a single exit at the bottom. 10639 // The point of exit cannot be a branch out of the structured block. 10640 // longjmp() and throw() must not violate the entry/exit criteria. 10641 CS->getCapturedDecl()->setNothrow(); 10642 } 10643 10644 OMPLoopDirective::HelperExprs B; 10645 // In presence of clause 'collapse' or 'ordered' with number of loops, it will 10646 // define the nested loops number. 10647 unsigned NestedLoopCount = checkOpenMPLoop( 10648 OMPD_target_parallel_for_simd, getCollapseNumberExpr(Clauses), 10649 getOrderedNumberExpr(Clauses), CS, *this, *DSAStack, 10650 VarsWithImplicitDSA, B); 10651 if (NestedLoopCount == 0) 10652 return StmtError(); 10653 10654 assert((CurContext->isDependentContext() || B.builtAll()) && 10655 "omp target parallel for simd loop exprs were not built"); 10656 10657 if (!CurContext->isDependentContext()) { 10658 // Finalize the clauses that need pre-built expressions for CodeGen. 10659 for (OMPClause *C : Clauses) { 10660 if (auto *LC = dyn_cast<OMPLinearClause>(C)) 10661 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef), 10662 B.NumIterations, *this, CurScope, 10663 DSAStack)) 10664 return StmtError(); 10665 } 10666 } 10667 if (checkSimdlenSafelenSpecified(*this, Clauses)) 10668 return StmtError(); 10669 10670 setFunctionHasBranchProtectedScope(); 10671 return OMPTargetParallelForSimdDirective::Create( 10672 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B); 10673 } 10674 10675 StmtResult Sema::ActOnOpenMPTargetSimdDirective( 10676 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, 10677 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) { 10678 if (!AStmt) 10679 return StmtError(); 10680 10681 auto *CS = cast<CapturedStmt>(AStmt); 10682 // 1.2.2 OpenMP Language Terminology 10683 // Structured block - An executable statement with a single entry at the 10684 // top and a single exit at the bottom. 10685 // The point of exit cannot be a branch out of the structured block. 10686 // longjmp() and throw() must not violate the entry/exit criteria. 10687 CS->getCapturedDecl()->setNothrow(); 10688 for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_simd); 10689 ThisCaptureLevel > 1; --ThisCaptureLevel) { 10690 CS = cast<CapturedStmt>(CS->getCapturedStmt()); 10691 // 1.2.2 OpenMP Language Terminology 10692 // Structured block - An executable statement with a single entry at the 10693 // top and a single exit at the bottom. 10694 // The point of exit cannot be a branch out of the structured block. 10695 // longjmp() and throw() must not violate the entry/exit criteria. 10696 CS->getCapturedDecl()->setNothrow(); 10697 } 10698 10699 OMPLoopDirective::HelperExprs B; 10700 // In presence of clause 'collapse' with number of loops, it will define the 10701 // nested loops number. 10702 unsigned NestedLoopCount = 10703 checkOpenMPLoop(OMPD_target_simd, getCollapseNumberExpr(Clauses), 10704 getOrderedNumberExpr(Clauses), CS, *this, *DSAStack, 10705 VarsWithImplicitDSA, B); 10706 if (NestedLoopCount == 0) 10707 return StmtError(); 10708 10709 assert((CurContext->isDependentContext() || B.builtAll()) && 10710 "omp target simd loop exprs were not built"); 10711 10712 if (!CurContext->isDependentContext()) { 10713 // Finalize the clauses that need pre-built expressions for CodeGen. 10714 for (OMPClause *C : Clauses) { 10715 if (auto *LC = dyn_cast<OMPLinearClause>(C)) 10716 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef), 10717 B.NumIterations, *this, CurScope, 10718 DSAStack)) 10719 return StmtError(); 10720 } 10721 } 10722 10723 if (checkSimdlenSafelenSpecified(*this, Clauses)) 10724 return StmtError(); 10725 10726 setFunctionHasBranchProtectedScope(); 10727 return OMPTargetSimdDirective::Create(Context, StartLoc, EndLoc, 10728 NestedLoopCount, Clauses, AStmt, B); 10729 } 10730 10731 StmtResult Sema::ActOnOpenMPTeamsDistributeDirective( 10732 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, 10733 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) { 10734 if (!AStmt) 10735 return StmtError(); 10736 10737 auto *CS = cast<CapturedStmt>(AStmt); 10738 // 1.2.2 OpenMP Language Terminology 10739 // Structured block - An executable statement with a single entry at the 10740 // top and a single exit at the bottom. 10741 // The point of exit cannot be a branch out of the structured block. 10742 // longjmp() and throw() must not violate the entry/exit criteria. 10743 CS->getCapturedDecl()->setNothrow(); 10744 for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_teams_distribute); 10745 ThisCaptureLevel > 1; --ThisCaptureLevel) { 10746 CS = cast<CapturedStmt>(CS->getCapturedStmt()); 10747 // 1.2.2 OpenMP Language Terminology 10748 // Structured block - An executable statement with a single entry at the 10749 // top and a single exit at the bottom. 10750 // The point of exit cannot be a branch out of the structured block. 10751 // longjmp() and throw() must not violate the entry/exit criteria. 10752 CS->getCapturedDecl()->setNothrow(); 10753 } 10754 10755 OMPLoopDirective::HelperExprs B; 10756 // In presence of clause 'collapse' with number of loops, it will 10757 // define the nested loops number. 10758 unsigned NestedLoopCount = 10759 checkOpenMPLoop(OMPD_teams_distribute, getCollapseNumberExpr(Clauses), 10760 nullptr /*ordered not a clause on distribute*/, CS, *this, 10761 *DSAStack, VarsWithImplicitDSA, B); 10762 if (NestedLoopCount == 0) 10763 return StmtError(); 10764 10765 assert((CurContext->isDependentContext() || B.builtAll()) && 10766 "omp teams distribute loop exprs were not built"); 10767 10768 setFunctionHasBranchProtectedScope(); 10769 10770 DSAStack->setParentTeamsRegionLoc(StartLoc); 10771 10772 return OMPTeamsDistributeDirective::Create( 10773 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B); 10774 } 10775 10776 StmtResult Sema::ActOnOpenMPTeamsDistributeSimdDirective( 10777 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, 10778 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) { 10779 if (!AStmt) 10780 return StmtError(); 10781 10782 auto *CS = cast<CapturedStmt>(AStmt); 10783 // 1.2.2 OpenMP Language Terminology 10784 // Structured block - An executable statement with a single entry at the 10785 // top and a single exit at the bottom. 10786 // The point of exit cannot be a branch out of the structured block. 10787 // longjmp() and throw() must not violate the entry/exit criteria. 10788 CS->getCapturedDecl()->setNothrow(); 10789 for (int ThisCaptureLevel = 10790 getOpenMPCaptureLevels(OMPD_teams_distribute_simd); 10791 ThisCaptureLevel > 1; --ThisCaptureLevel) { 10792 CS = cast<CapturedStmt>(CS->getCapturedStmt()); 10793 // 1.2.2 OpenMP Language Terminology 10794 // Structured block - An executable statement with a single entry at the 10795 // top and a single exit at the bottom. 10796 // The point of exit cannot be a branch out of the structured block. 10797 // longjmp() and throw() must not violate the entry/exit criteria. 10798 CS->getCapturedDecl()->setNothrow(); 10799 } 10800 10801 OMPLoopDirective::HelperExprs B; 10802 // In presence of clause 'collapse' with number of loops, it will 10803 // define the nested loops number. 10804 unsigned NestedLoopCount = checkOpenMPLoop( 10805 OMPD_teams_distribute_simd, getCollapseNumberExpr(Clauses), 10806 nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStack, 10807 VarsWithImplicitDSA, B); 10808 10809 if (NestedLoopCount == 0) 10810 return StmtError(); 10811 10812 assert((CurContext->isDependentContext() || B.builtAll()) && 10813 "omp teams distribute simd loop exprs were not built"); 10814 10815 if (!CurContext->isDependentContext()) { 10816 // Finalize the clauses that need pre-built expressions for CodeGen. 10817 for (OMPClause *C : Clauses) { 10818 if (auto *LC = dyn_cast<OMPLinearClause>(C)) 10819 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef), 10820 B.NumIterations, *this, CurScope, 10821 DSAStack)) 10822 return StmtError(); 10823 } 10824 } 10825 10826 if (checkSimdlenSafelenSpecified(*this, Clauses)) 10827 return StmtError(); 10828 10829 setFunctionHasBranchProtectedScope(); 10830 10831 DSAStack->setParentTeamsRegionLoc(StartLoc); 10832 10833 return OMPTeamsDistributeSimdDirective::Create( 10834 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B); 10835 } 10836 10837 StmtResult Sema::ActOnOpenMPTeamsDistributeParallelForSimdDirective( 10838 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, 10839 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) { 10840 if (!AStmt) 10841 return StmtError(); 10842 10843 auto *CS = cast<CapturedStmt>(AStmt); 10844 // 1.2.2 OpenMP Language Terminology 10845 // Structured block - An executable statement with a single entry at the 10846 // top and a single exit at the bottom. 10847 // The point of exit cannot be a branch out of the structured block. 10848 // longjmp() and throw() must not violate the entry/exit criteria. 10849 CS->getCapturedDecl()->setNothrow(); 10850 10851 for (int ThisCaptureLevel = 10852 getOpenMPCaptureLevels(OMPD_teams_distribute_parallel_for_simd); 10853 ThisCaptureLevel > 1; --ThisCaptureLevel) { 10854 CS = cast<CapturedStmt>(CS->getCapturedStmt()); 10855 // 1.2.2 OpenMP Language Terminology 10856 // Structured block - An executable statement with a single entry at the 10857 // top and a single exit at the bottom. 10858 // The point of exit cannot be a branch out of the structured block. 10859 // longjmp() and throw() must not violate the entry/exit criteria. 10860 CS->getCapturedDecl()->setNothrow(); 10861 } 10862 10863 OMPLoopDirective::HelperExprs B; 10864 // In presence of clause 'collapse' with number of loops, it will 10865 // define the nested loops number. 10866 unsigned NestedLoopCount = checkOpenMPLoop( 10867 OMPD_teams_distribute_parallel_for_simd, getCollapseNumberExpr(Clauses), 10868 nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStack, 10869 VarsWithImplicitDSA, B); 10870 10871 if (NestedLoopCount == 0) 10872 return StmtError(); 10873 10874 assert((CurContext->isDependentContext() || B.builtAll()) && 10875 "omp for loop exprs were not built"); 10876 10877 if (!CurContext->isDependentContext()) { 10878 // Finalize the clauses that need pre-built expressions for CodeGen. 10879 for (OMPClause *C : Clauses) { 10880 if (auto *LC = dyn_cast<OMPLinearClause>(C)) 10881 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef), 10882 B.NumIterations, *this, CurScope, 10883 DSAStack)) 10884 return StmtError(); 10885 } 10886 } 10887 10888 if (checkSimdlenSafelenSpecified(*this, Clauses)) 10889 return StmtError(); 10890 10891 setFunctionHasBranchProtectedScope(); 10892 10893 DSAStack->setParentTeamsRegionLoc(StartLoc); 10894 10895 return OMPTeamsDistributeParallelForSimdDirective::Create( 10896 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B); 10897 } 10898 10899 StmtResult Sema::ActOnOpenMPTeamsDistributeParallelForDirective( 10900 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, 10901 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) { 10902 if (!AStmt) 10903 return StmtError(); 10904 10905 auto *CS = cast<CapturedStmt>(AStmt); 10906 // 1.2.2 OpenMP Language Terminology 10907 // Structured block - An executable statement with a single entry at the 10908 // top and a single exit at the bottom. 10909 // The point of exit cannot be a branch out of the structured block. 10910 // longjmp() and throw() must not violate the entry/exit criteria. 10911 CS->getCapturedDecl()->setNothrow(); 10912 10913 for (int ThisCaptureLevel = 10914 getOpenMPCaptureLevels(OMPD_teams_distribute_parallel_for); 10915 ThisCaptureLevel > 1; --ThisCaptureLevel) { 10916 CS = cast<CapturedStmt>(CS->getCapturedStmt()); 10917 // 1.2.2 OpenMP Language Terminology 10918 // Structured block - An executable statement with a single entry at the 10919 // top and a single exit at the bottom. 10920 // The point of exit cannot be a branch out of the structured block. 10921 // longjmp() and throw() must not violate the entry/exit criteria. 10922 CS->getCapturedDecl()->setNothrow(); 10923 } 10924 10925 OMPLoopDirective::HelperExprs B; 10926 // In presence of clause 'collapse' with number of loops, it will 10927 // define the nested loops number. 10928 unsigned NestedLoopCount = checkOpenMPLoop( 10929 OMPD_teams_distribute_parallel_for, getCollapseNumberExpr(Clauses), 10930 nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStack, 10931 VarsWithImplicitDSA, B); 10932 10933 if (NestedLoopCount == 0) 10934 return StmtError(); 10935 10936 assert((CurContext->isDependentContext() || B.builtAll()) && 10937 "omp for loop exprs were not built"); 10938 10939 setFunctionHasBranchProtectedScope(); 10940 10941 DSAStack->setParentTeamsRegionLoc(StartLoc); 10942 10943 return OMPTeamsDistributeParallelForDirective::Create( 10944 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B, 10945 DSAStack->isCancelRegion()); 10946 } 10947 10948 StmtResult Sema::ActOnOpenMPTargetTeamsDirective(ArrayRef<OMPClause *> Clauses, 10949 Stmt *AStmt, 10950 SourceLocation StartLoc, 10951 SourceLocation EndLoc) { 10952 if (!AStmt) 10953 return StmtError(); 10954 10955 auto *CS = cast<CapturedStmt>(AStmt); 10956 // 1.2.2 OpenMP Language Terminology 10957 // Structured block - An executable statement with a single entry at the 10958 // top and a single exit at the bottom. 10959 // The point of exit cannot be a branch out of the structured block. 10960 // longjmp() and throw() must not violate the entry/exit criteria. 10961 CS->getCapturedDecl()->setNothrow(); 10962 10963 for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_teams); 10964 ThisCaptureLevel > 1; --ThisCaptureLevel) { 10965 CS = cast<CapturedStmt>(CS->getCapturedStmt()); 10966 // 1.2.2 OpenMP Language Terminology 10967 // Structured block - An executable statement with a single entry at the 10968 // top and a single exit at the bottom. 10969 // The point of exit cannot be a branch out of the structured block. 10970 // longjmp() and throw() must not violate the entry/exit criteria. 10971 CS->getCapturedDecl()->setNothrow(); 10972 } 10973 setFunctionHasBranchProtectedScope(); 10974 10975 return OMPTargetTeamsDirective::Create(Context, StartLoc, EndLoc, Clauses, 10976 AStmt); 10977 } 10978 10979 StmtResult Sema::ActOnOpenMPTargetTeamsDistributeDirective( 10980 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, 10981 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) { 10982 if (!AStmt) 10983 return StmtError(); 10984 10985 auto *CS = cast<CapturedStmt>(AStmt); 10986 // 1.2.2 OpenMP Language Terminology 10987 // Structured block - An executable statement with a single entry at the 10988 // top and a single exit at the bottom. 10989 // The point of exit cannot be a branch out of the structured block. 10990 // longjmp() and throw() must not violate the entry/exit criteria. 10991 CS->getCapturedDecl()->setNothrow(); 10992 for (int ThisCaptureLevel = 10993 getOpenMPCaptureLevels(OMPD_target_teams_distribute); 10994 ThisCaptureLevel > 1; --ThisCaptureLevel) { 10995 CS = cast<CapturedStmt>(CS->getCapturedStmt()); 10996 // 1.2.2 OpenMP Language Terminology 10997 // Structured block - An executable statement with a single entry at the 10998 // top and a single exit at the bottom. 10999 // The point of exit cannot be a branch out of the structured block. 11000 // longjmp() and throw() must not violate the entry/exit criteria. 11001 CS->getCapturedDecl()->setNothrow(); 11002 } 11003 11004 OMPLoopDirective::HelperExprs B; 11005 // In presence of clause 'collapse' with number of loops, it will 11006 // define the nested loops number. 11007 unsigned NestedLoopCount = checkOpenMPLoop( 11008 OMPD_target_teams_distribute, getCollapseNumberExpr(Clauses), 11009 nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStack, 11010 VarsWithImplicitDSA, B); 11011 if (NestedLoopCount == 0) 11012 return StmtError(); 11013 11014 assert((CurContext->isDependentContext() || B.builtAll()) && 11015 "omp target teams distribute loop exprs were not built"); 11016 11017 setFunctionHasBranchProtectedScope(); 11018 return OMPTargetTeamsDistributeDirective::Create( 11019 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B); 11020 } 11021 11022 StmtResult Sema::ActOnOpenMPTargetTeamsDistributeParallelForDirective( 11023 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, 11024 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) { 11025 if (!AStmt) 11026 return StmtError(); 11027 11028 auto *CS = cast<CapturedStmt>(AStmt); 11029 // 1.2.2 OpenMP Language Terminology 11030 // Structured block - An executable statement with a single entry at the 11031 // top and a single exit at the bottom. 11032 // The point of exit cannot be a branch out of the structured block. 11033 // longjmp() and throw() must not violate the entry/exit criteria. 11034 CS->getCapturedDecl()->setNothrow(); 11035 for (int ThisCaptureLevel = 11036 getOpenMPCaptureLevels(OMPD_target_teams_distribute_parallel_for); 11037 ThisCaptureLevel > 1; --ThisCaptureLevel) { 11038 CS = cast<CapturedStmt>(CS->getCapturedStmt()); 11039 // 1.2.2 OpenMP Language Terminology 11040 // Structured block - An executable statement with a single entry at the 11041 // top and a single exit at the bottom. 11042 // The point of exit cannot be a branch out of the structured block. 11043 // longjmp() and throw() must not violate the entry/exit criteria. 11044 CS->getCapturedDecl()->setNothrow(); 11045 } 11046 11047 OMPLoopDirective::HelperExprs B; 11048 // In presence of clause 'collapse' with number of loops, it will 11049 // define the nested loops number. 11050 unsigned NestedLoopCount = checkOpenMPLoop( 11051 OMPD_target_teams_distribute_parallel_for, getCollapseNumberExpr(Clauses), 11052 nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStack, 11053 VarsWithImplicitDSA, B); 11054 if (NestedLoopCount == 0) 11055 return StmtError(); 11056 11057 assert((CurContext->isDependentContext() || B.builtAll()) && 11058 "omp target teams distribute parallel for loop exprs were not built"); 11059 11060 if (!CurContext->isDependentContext()) { 11061 // Finalize the clauses that need pre-built expressions for CodeGen. 11062 for (OMPClause *C : Clauses) { 11063 if (auto *LC = dyn_cast<OMPLinearClause>(C)) 11064 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef), 11065 B.NumIterations, *this, CurScope, 11066 DSAStack)) 11067 return StmtError(); 11068 } 11069 } 11070 11071 setFunctionHasBranchProtectedScope(); 11072 return OMPTargetTeamsDistributeParallelForDirective::Create( 11073 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B, 11074 DSAStack->isCancelRegion()); 11075 } 11076 11077 StmtResult Sema::ActOnOpenMPTargetTeamsDistributeParallelForSimdDirective( 11078 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, 11079 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) { 11080 if (!AStmt) 11081 return StmtError(); 11082 11083 auto *CS = cast<CapturedStmt>(AStmt); 11084 // 1.2.2 OpenMP Language Terminology 11085 // Structured block - An executable statement with a single entry at the 11086 // top and a single exit at the bottom. 11087 // The point of exit cannot be a branch out of the structured block. 11088 // longjmp() and throw() must not violate the entry/exit criteria. 11089 CS->getCapturedDecl()->setNothrow(); 11090 for (int ThisCaptureLevel = getOpenMPCaptureLevels( 11091 OMPD_target_teams_distribute_parallel_for_simd); 11092 ThisCaptureLevel > 1; --ThisCaptureLevel) { 11093 CS = cast<CapturedStmt>(CS->getCapturedStmt()); 11094 // 1.2.2 OpenMP Language Terminology 11095 // Structured block - An executable statement with a single entry at the 11096 // top and a single exit at the bottom. 11097 // The point of exit cannot be a branch out of the structured block. 11098 // longjmp() and throw() must not violate the entry/exit criteria. 11099 CS->getCapturedDecl()->setNothrow(); 11100 } 11101 11102 OMPLoopDirective::HelperExprs B; 11103 // In presence of clause 'collapse' with number of loops, it will 11104 // define the nested loops number. 11105 unsigned NestedLoopCount = 11106 checkOpenMPLoop(OMPD_target_teams_distribute_parallel_for_simd, 11107 getCollapseNumberExpr(Clauses), 11108 nullptr /*ordered not a clause on distribute*/, CS, *this, 11109 *DSAStack, VarsWithImplicitDSA, B); 11110 if (NestedLoopCount == 0) 11111 return StmtError(); 11112 11113 assert((CurContext->isDependentContext() || B.builtAll()) && 11114 "omp target teams distribute parallel for simd loop exprs were not " 11115 "built"); 11116 11117 if (!CurContext->isDependentContext()) { 11118 // Finalize the clauses that need pre-built expressions for CodeGen. 11119 for (OMPClause *C : Clauses) { 11120 if (auto *LC = dyn_cast<OMPLinearClause>(C)) 11121 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef), 11122 B.NumIterations, *this, CurScope, 11123 DSAStack)) 11124 return StmtError(); 11125 } 11126 } 11127 11128 if (checkSimdlenSafelenSpecified(*this, Clauses)) 11129 return StmtError(); 11130 11131 setFunctionHasBranchProtectedScope(); 11132 return OMPTargetTeamsDistributeParallelForSimdDirective::Create( 11133 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B); 11134 } 11135 11136 StmtResult Sema::ActOnOpenMPTargetTeamsDistributeSimdDirective( 11137 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, 11138 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) { 11139 if (!AStmt) 11140 return StmtError(); 11141 11142 auto *CS = cast<CapturedStmt>(AStmt); 11143 // 1.2.2 OpenMP Language Terminology 11144 // Structured block - An executable statement with a single entry at the 11145 // top and a single exit at the bottom. 11146 // The point of exit cannot be a branch out of the structured block. 11147 // longjmp() and throw() must not violate the entry/exit criteria. 11148 CS->getCapturedDecl()->setNothrow(); 11149 for (int ThisCaptureLevel = 11150 getOpenMPCaptureLevels(OMPD_target_teams_distribute_simd); 11151 ThisCaptureLevel > 1; --ThisCaptureLevel) { 11152 CS = cast<CapturedStmt>(CS->getCapturedStmt()); 11153 // 1.2.2 OpenMP Language Terminology 11154 // Structured block - An executable statement with a single entry at the 11155 // top and a single exit at the bottom. 11156 // The point of exit cannot be a branch out of the structured block. 11157 // longjmp() and throw() must not violate the entry/exit criteria. 11158 CS->getCapturedDecl()->setNothrow(); 11159 } 11160 11161 OMPLoopDirective::HelperExprs B; 11162 // In presence of clause 'collapse' with number of loops, it will 11163 // define the nested loops number. 11164 unsigned NestedLoopCount = checkOpenMPLoop( 11165 OMPD_target_teams_distribute_simd, getCollapseNumberExpr(Clauses), 11166 nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStack, 11167 VarsWithImplicitDSA, B); 11168 if (NestedLoopCount == 0) 11169 return StmtError(); 11170 11171 assert((CurContext->isDependentContext() || B.builtAll()) && 11172 "omp target teams distribute simd loop exprs were not built"); 11173 11174 if (!CurContext->isDependentContext()) { 11175 // Finalize the clauses that need pre-built expressions for CodeGen. 11176 for (OMPClause *C : Clauses) { 11177 if (auto *LC = dyn_cast<OMPLinearClause>(C)) 11178 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef), 11179 B.NumIterations, *this, CurScope, 11180 DSAStack)) 11181 return StmtError(); 11182 } 11183 } 11184 11185 if (checkSimdlenSafelenSpecified(*this, Clauses)) 11186 return StmtError(); 11187 11188 setFunctionHasBranchProtectedScope(); 11189 return OMPTargetTeamsDistributeSimdDirective::Create( 11190 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B); 11191 } 11192 11193 OMPClause *Sema::ActOnOpenMPSingleExprClause(OpenMPClauseKind Kind, Expr *Expr, 11194 SourceLocation StartLoc, 11195 SourceLocation LParenLoc, 11196 SourceLocation EndLoc) { 11197 OMPClause *Res = nullptr; 11198 switch (Kind) { 11199 case OMPC_final: 11200 Res = ActOnOpenMPFinalClause(Expr, StartLoc, LParenLoc, EndLoc); 11201 break; 11202 case OMPC_num_threads: 11203 Res = ActOnOpenMPNumThreadsClause(Expr, StartLoc, LParenLoc, EndLoc); 11204 break; 11205 case OMPC_safelen: 11206 Res = ActOnOpenMPSafelenClause(Expr, StartLoc, LParenLoc, EndLoc); 11207 break; 11208 case OMPC_simdlen: 11209 Res = ActOnOpenMPSimdlenClause(Expr, StartLoc, LParenLoc, EndLoc); 11210 break; 11211 case OMPC_allocator: 11212 Res = ActOnOpenMPAllocatorClause(Expr, StartLoc, LParenLoc, EndLoc); 11213 break; 11214 case OMPC_collapse: 11215 Res = ActOnOpenMPCollapseClause(Expr, StartLoc, LParenLoc, EndLoc); 11216 break; 11217 case OMPC_ordered: 11218 Res = ActOnOpenMPOrderedClause(StartLoc, EndLoc, LParenLoc, Expr); 11219 break; 11220 case OMPC_num_teams: 11221 Res = ActOnOpenMPNumTeamsClause(Expr, StartLoc, LParenLoc, EndLoc); 11222 break; 11223 case OMPC_thread_limit: 11224 Res = ActOnOpenMPThreadLimitClause(Expr, StartLoc, LParenLoc, EndLoc); 11225 break; 11226 case OMPC_priority: 11227 Res = ActOnOpenMPPriorityClause(Expr, StartLoc, LParenLoc, EndLoc); 11228 break; 11229 case OMPC_grainsize: 11230 Res = ActOnOpenMPGrainsizeClause(Expr, StartLoc, LParenLoc, EndLoc); 11231 break; 11232 case OMPC_num_tasks: 11233 Res = ActOnOpenMPNumTasksClause(Expr, StartLoc, LParenLoc, EndLoc); 11234 break; 11235 case OMPC_hint: 11236 Res = ActOnOpenMPHintClause(Expr, StartLoc, LParenLoc, EndLoc); 11237 break; 11238 case OMPC_depobj: 11239 Res = ActOnOpenMPDepobjClause(Expr, StartLoc, LParenLoc, EndLoc); 11240 break; 11241 case OMPC_detach: 11242 Res = ActOnOpenMPDetachClause(Expr, StartLoc, LParenLoc, EndLoc); 11243 break; 11244 case OMPC_device: 11245 case OMPC_if: 11246 case OMPC_default: 11247 case OMPC_proc_bind: 11248 case OMPC_schedule: 11249 case OMPC_private: 11250 case OMPC_firstprivate: 11251 case OMPC_lastprivate: 11252 case OMPC_shared: 11253 case OMPC_reduction: 11254 case OMPC_task_reduction: 11255 case OMPC_in_reduction: 11256 case OMPC_linear: 11257 case OMPC_aligned: 11258 case OMPC_copyin: 11259 case OMPC_copyprivate: 11260 case OMPC_nowait: 11261 case OMPC_untied: 11262 case OMPC_mergeable: 11263 case OMPC_threadprivate: 11264 case OMPC_allocate: 11265 case OMPC_flush: 11266 case OMPC_read: 11267 case OMPC_write: 11268 case OMPC_update: 11269 case OMPC_capture: 11270 case OMPC_seq_cst: 11271 case OMPC_acq_rel: 11272 case OMPC_acquire: 11273 case OMPC_release: 11274 case OMPC_relaxed: 11275 case OMPC_depend: 11276 case OMPC_threads: 11277 case OMPC_simd: 11278 case OMPC_map: 11279 case OMPC_nogroup: 11280 case OMPC_dist_schedule: 11281 case OMPC_defaultmap: 11282 case OMPC_unknown: 11283 case OMPC_uniform: 11284 case OMPC_to: 11285 case OMPC_from: 11286 case OMPC_use_device_ptr: 11287 case OMPC_is_device_ptr: 11288 case OMPC_unified_address: 11289 case OMPC_unified_shared_memory: 11290 case OMPC_reverse_offload: 11291 case OMPC_dynamic_allocators: 11292 case OMPC_atomic_default_mem_order: 11293 case OMPC_device_type: 11294 case OMPC_match: 11295 case OMPC_nontemporal: 11296 case OMPC_order: 11297 case OMPC_destroy: 11298 case OMPC_inclusive: 11299 case OMPC_exclusive: 11300 llvm_unreachable("Clause is not allowed."); 11301 } 11302 return Res; 11303 } 11304 11305 // An OpenMP directive such as 'target parallel' has two captured regions: 11306 // for the 'target' and 'parallel' respectively. This function returns 11307 // the region in which to capture expressions associated with a clause. 11308 // A return value of OMPD_unknown signifies that the expression should not 11309 // be captured. 11310 static OpenMPDirectiveKind getOpenMPCaptureRegionForClause( 11311 OpenMPDirectiveKind DKind, OpenMPClauseKind CKind, unsigned OpenMPVersion, 11312 OpenMPDirectiveKind NameModifier = OMPD_unknown) { 11313 OpenMPDirectiveKind CaptureRegion = OMPD_unknown; 11314 switch (CKind) { 11315 case OMPC_if: 11316 switch (DKind) { 11317 case OMPD_target_parallel_for_simd: 11318 if (OpenMPVersion >= 50 && 11319 (NameModifier == OMPD_unknown || NameModifier == OMPD_simd)) { 11320 CaptureRegion = OMPD_parallel; 11321 break; 11322 } 11323 LLVM_FALLTHROUGH; 11324 case OMPD_target_parallel: 11325 case OMPD_target_parallel_for: 11326 // If this clause applies to the nested 'parallel' region, capture within 11327 // the 'target' region, otherwise do not capture. 11328 if (NameModifier == OMPD_unknown || NameModifier == OMPD_parallel) 11329 CaptureRegion = OMPD_target; 11330 break; 11331 case OMPD_target_teams_distribute_parallel_for_simd: 11332 if (OpenMPVersion >= 50 && 11333 (NameModifier == OMPD_unknown || NameModifier == OMPD_simd)) { 11334 CaptureRegion = OMPD_parallel; 11335 break; 11336 } 11337 LLVM_FALLTHROUGH; 11338 case OMPD_target_teams_distribute_parallel_for: 11339 // If this clause applies to the nested 'parallel' region, capture within 11340 // the 'teams' region, otherwise do not capture. 11341 if (NameModifier == OMPD_unknown || NameModifier == OMPD_parallel) 11342 CaptureRegion = OMPD_teams; 11343 break; 11344 case OMPD_teams_distribute_parallel_for_simd: 11345 if (OpenMPVersion >= 50 && 11346 (NameModifier == OMPD_unknown || NameModifier == OMPD_simd)) { 11347 CaptureRegion = OMPD_parallel; 11348 break; 11349 } 11350 LLVM_FALLTHROUGH; 11351 case OMPD_teams_distribute_parallel_for: 11352 CaptureRegion = OMPD_teams; 11353 break; 11354 case OMPD_target_update: 11355 case OMPD_target_enter_data: 11356 case OMPD_target_exit_data: 11357 CaptureRegion = OMPD_task; 11358 break; 11359 case OMPD_parallel_master_taskloop: 11360 if (NameModifier == OMPD_unknown || NameModifier == OMPD_taskloop) 11361 CaptureRegion = OMPD_parallel; 11362 break; 11363 case OMPD_parallel_master_taskloop_simd: 11364 if ((OpenMPVersion <= 45 && NameModifier == OMPD_unknown) || 11365 NameModifier == OMPD_taskloop) { 11366 CaptureRegion = OMPD_parallel; 11367 break; 11368 } 11369 if (OpenMPVersion <= 45) 11370 break; 11371 if (NameModifier == OMPD_unknown || NameModifier == OMPD_simd) 11372 CaptureRegion = OMPD_taskloop; 11373 break; 11374 case OMPD_parallel_for_simd: 11375 if (OpenMPVersion <= 45) 11376 break; 11377 if (NameModifier == OMPD_unknown || NameModifier == OMPD_simd) 11378 CaptureRegion = OMPD_parallel; 11379 break; 11380 case OMPD_taskloop_simd: 11381 case OMPD_master_taskloop_simd: 11382 if (OpenMPVersion <= 45) 11383 break; 11384 if (NameModifier == OMPD_unknown || NameModifier == OMPD_simd) 11385 CaptureRegion = OMPD_taskloop; 11386 break; 11387 case OMPD_distribute_parallel_for_simd: 11388 if (OpenMPVersion <= 45) 11389 break; 11390 if (NameModifier == OMPD_unknown || NameModifier == OMPD_simd) 11391 CaptureRegion = OMPD_parallel; 11392 break; 11393 case OMPD_target_simd: 11394 if (OpenMPVersion >= 50 && 11395 (NameModifier == OMPD_unknown || NameModifier == OMPD_simd)) 11396 CaptureRegion = OMPD_target; 11397 break; 11398 case OMPD_teams_distribute_simd: 11399 case OMPD_target_teams_distribute_simd: 11400 if (OpenMPVersion >= 50 && 11401 (NameModifier == OMPD_unknown || NameModifier == OMPD_simd)) 11402 CaptureRegion = OMPD_teams; 11403 break; 11404 case OMPD_cancel: 11405 case OMPD_parallel: 11406 case OMPD_parallel_master: 11407 case OMPD_parallel_sections: 11408 case OMPD_parallel_for: 11409 case OMPD_target: 11410 case OMPD_target_teams: 11411 case OMPD_target_teams_distribute: 11412 case OMPD_distribute_parallel_for: 11413 case OMPD_task: 11414 case OMPD_taskloop: 11415 case OMPD_master_taskloop: 11416 case OMPD_target_data: 11417 case OMPD_simd: 11418 case OMPD_for_simd: 11419 case OMPD_distribute_simd: 11420 // Do not capture if-clause expressions. 11421 break; 11422 case OMPD_threadprivate: 11423 case OMPD_allocate: 11424 case OMPD_taskyield: 11425 case OMPD_barrier: 11426 case OMPD_taskwait: 11427 case OMPD_cancellation_point: 11428 case OMPD_flush: 11429 case OMPD_depobj: 11430 case OMPD_scan: 11431 case OMPD_declare_reduction: 11432 case OMPD_declare_mapper: 11433 case OMPD_declare_simd: 11434 case OMPD_declare_variant: 11435 case OMPD_begin_declare_variant: 11436 case OMPD_end_declare_variant: 11437 case OMPD_declare_target: 11438 case OMPD_end_declare_target: 11439 case OMPD_teams: 11440 case OMPD_for: 11441 case OMPD_sections: 11442 case OMPD_section: 11443 case OMPD_single: 11444 case OMPD_master: 11445 case OMPD_critical: 11446 case OMPD_taskgroup: 11447 case OMPD_distribute: 11448 case OMPD_ordered: 11449 case OMPD_atomic: 11450 case OMPD_teams_distribute: 11451 case OMPD_requires: 11452 llvm_unreachable("Unexpected OpenMP directive with if-clause"); 11453 case OMPD_unknown: 11454 llvm_unreachable("Unknown OpenMP directive"); 11455 } 11456 break; 11457 case OMPC_num_threads: 11458 switch (DKind) { 11459 case OMPD_target_parallel: 11460 case OMPD_target_parallel_for: 11461 case OMPD_target_parallel_for_simd: 11462 CaptureRegion = OMPD_target; 11463 break; 11464 case OMPD_teams_distribute_parallel_for: 11465 case OMPD_teams_distribute_parallel_for_simd: 11466 case OMPD_target_teams_distribute_parallel_for: 11467 case OMPD_target_teams_distribute_parallel_for_simd: 11468 CaptureRegion = OMPD_teams; 11469 break; 11470 case OMPD_parallel: 11471 case OMPD_parallel_master: 11472 case OMPD_parallel_sections: 11473 case OMPD_parallel_for: 11474 case OMPD_parallel_for_simd: 11475 case OMPD_distribute_parallel_for: 11476 case OMPD_distribute_parallel_for_simd: 11477 case OMPD_parallel_master_taskloop: 11478 case OMPD_parallel_master_taskloop_simd: 11479 // Do not capture num_threads-clause expressions. 11480 break; 11481 case OMPD_target_data: 11482 case OMPD_target_enter_data: 11483 case OMPD_target_exit_data: 11484 case OMPD_target_update: 11485 case OMPD_target: 11486 case OMPD_target_simd: 11487 case OMPD_target_teams: 11488 case OMPD_target_teams_distribute: 11489 case OMPD_target_teams_distribute_simd: 11490 case OMPD_cancel: 11491 case OMPD_task: 11492 case OMPD_taskloop: 11493 case OMPD_taskloop_simd: 11494 case OMPD_master_taskloop: 11495 case OMPD_master_taskloop_simd: 11496 case OMPD_threadprivate: 11497 case OMPD_allocate: 11498 case OMPD_taskyield: 11499 case OMPD_barrier: 11500 case OMPD_taskwait: 11501 case OMPD_cancellation_point: 11502 case OMPD_flush: 11503 case OMPD_depobj: 11504 case OMPD_scan: 11505 case OMPD_declare_reduction: 11506 case OMPD_declare_mapper: 11507 case OMPD_declare_simd: 11508 case OMPD_declare_variant: 11509 case OMPD_begin_declare_variant: 11510 case OMPD_end_declare_variant: 11511 case OMPD_declare_target: 11512 case OMPD_end_declare_target: 11513 case OMPD_teams: 11514 case OMPD_simd: 11515 case OMPD_for: 11516 case OMPD_for_simd: 11517 case OMPD_sections: 11518 case OMPD_section: 11519 case OMPD_single: 11520 case OMPD_master: 11521 case OMPD_critical: 11522 case OMPD_taskgroup: 11523 case OMPD_distribute: 11524 case OMPD_ordered: 11525 case OMPD_atomic: 11526 case OMPD_distribute_simd: 11527 case OMPD_teams_distribute: 11528 case OMPD_teams_distribute_simd: 11529 case OMPD_requires: 11530 llvm_unreachable("Unexpected OpenMP directive with num_threads-clause"); 11531 case OMPD_unknown: 11532 llvm_unreachable("Unknown OpenMP directive"); 11533 } 11534 break; 11535 case OMPC_num_teams: 11536 switch (DKind) { 11537 case OMPD_target_teams: 11538 case OMPD_target_teams_distribute: 11539 case OMPD_target_teams_distribute_simd: 11540 case OMPD_target_teams_distribute_parallel_for: 11541 case OMPD_target_teams_distribute_parallel_for_simd: 11542 CaptureRegion = OMPD_target; 11543 break; 11544 case OMPD_teams_distribute_parallel_for: 11545 case OMPD_teams_distribute_parallel_for_simd: 11546 case OMPD_teams: 11547 case OMPD_teams_distribute: 11548 case OMPD_teams_distribute_simd: 11549 // Do not capture num_teams-clause expressions. 11550 break; 11551 case OMPD_distribute_parallel_for: 11552 case OMPD_distribute_parallel_for_simd: 11553 case OMPD_task: 11554 case OMPD_taskloop: 11555 case OMPD_taskloop_simd: 11556 case OMPD_master_taskloop: 11557 case OMPD_master_taskloop_simd: 11558 case OMPD_parallel_master_taskloop: 11559 case OMPD_parallel_master_taskloop_simd: 11560 case OMPD_target_data: 11561 case OMPD_target_enter_data: 11562 case OMPD_target_exit_data: 11563 case OMPD_target_update: 11564 case OMPD_cancel: 11565 case OMPD_parallel: 11566 case OMPD_parallel_master: 11567 case OMPD_parallel_sections: 11568 case OMPD_parallel_for: 11569 case OMPD_parallel_for_simd: 11570 case OMPD_target: 11571 case OMPD_target_simd: 11572 case OMPD_target_parallel: 11573 case OMPD_target_parallel_for: 11574 case OMPD_target_parallel_for_simd: 11575 case OMPD_threadprivate: 11576 case OMPD_allocate: 11577 case OMPD_taskyield: 11578 case OMPD_barrier: 11579 case OMPD_taskwait: 11580 case OMPD_cancellation_point: 11581 case OMPD_flush: 11582 case OMPD_depobj: 11583 case OMPD_scan: 11584 case OMPD_declare_reduction: 11585 case OMPD_declare_mapper: 11586 case OMPD_declare_simd: 11587 case OMPD_declare_variant: 11588 case OMPD_begin_declare_variant: 11589 case OMPD_end_declare_variant: 11590 case OMPD_declare_target: 11591 case OMPD_end_declare_target: 11592 case OMPD_simd: 11593 case OMPD_for: 11594 case OMPD_for_simd: 11595 case OMPD_sections: 11596 case OMPD_section: 11597 case OMPD_single: 11598 case OMPD_master: 11599 case OMPD_critical: 11600 case OMPD_taskgroup: 11601 case OMPD_distribute: 11602 case OMPD_ordered: 11603 case OMPD_atomic: 11604 case OMPD_distribute_simd: 11605 case OMPD_requires: 11606 llvm_unreachable("Unexpected OpenMP directive with num_teams-clause"); 11607 case OMPD_unknown: 11608 llvm_unreachable("Unknown OpenMP directive"); 11609 } 11610 break; 11611 case OMPC_thread_limit: 11612 switch (DKind) { 11613 case OMPD_target_teams: 11614 case OMPD_target_teams_distribute: 11615 case OMPD_target_teams_distribute_simd: 11616 case OMPD_target_teams_distribute_parallel_for: 11617 case OMPD_target_teams_distribute_parallel_for_simd: 11618 CaptureRegion = OMPD_target; 11619 break; 11620 case OMPD_teams_distribute_parallel_for: 11621 case OMPD_teams_distribute_parallel_for_simd: 11622 case OMPD_teams: 11623 case OMPD_teams_distribute: 11624 case OMPD_teams_distribute_simd: 11625 // Do not capture thread_limit-clause expressions. 11626 break; 11627 case OMPD_distribute_parallel_for: 11628 case OMPD_distribute_parallel_for_simd: 11629 case OMPD_task: 11630 case OMPD_taskloop: 11631 case OMPD_taskloop_simd: 11632 case OMPD_master_taskloop: 11633 case OMPD_master_taskloop_simd: 11634 case OMPD_parallel_master_taskloop: 11635 case OMPD_parallel_master_taskloop_simd: 11636 case OMPD_target_data: 11637 case OMPD_target_enter_data: 11638 case OMPD_target_exit_data: 11639 case OMPD_target_update: 11640 case OMPD_cancel: 11641 case OMPD_parallel: 11642 case OMPD_parallel_master: 11643 case OMPD_parallel_sections: 11644 case OMPD_parallel_for: 11645 case OMPD_parallel_for_simd: 11646 case OMPD_target: 11647 case OMPD_target_simd: 11648 case OMPD_target_parallel: 11649 case OMPD_target_parallel_for: 11650 case OMPD_target_parallel_for_simd: 11651 case OMPD_threadprivate: 11652 case OMPD_allocate: 11653 case OMPD_taskyield: 11654 case OMPD_barrier: 11655 case OMPD_taskwait: 11656 case OMPD_cancellation_point: 11657 case OMPD_flush: 11658 case OMPD_depobj: 11659 case OMPD_scan: 11660 case OMPD_declare_reduction: 11661 case OMPD_declare_mapper: 11662 case OMPD_declare_simd: 11663 case OMPD_declare_variant: 11664 case OMPD_begin_declare_variant: 11665 case OMPD_end_declare_variant: 11666 case OMPD_declare_target: 11667 case OMPD_end_declare_target: 11668 case OMPD_simd: 11669 case OMPD_for: 11670 case OMPD_for_simd: 11671 case OMPD_sections: 11672 case OMPD_section: 11673 case OMPD_single: 11674 case OMPD_master: 11675 case OMPD_critical: 11676 case OMPD_taskgroup: 11677 case OMPD_distribute: 11678 case OMPD_ordered: 11679 case OMPD_atomic: 11680 case OMPD_distribute_simd: 11681 case OMPD_requires: 11682 llvm_unreachable("Unexpected OpenMP directive with thread_limit-clause"); 11683 case OMPD_unknown: 11684 llvm_unreachable("Unknown OpenMP directive"); 11685 } 11686 break; 11687 case OMPC_schedule: 11688 switch (DKind) { 11689 case OMPD_parallel_for: 11690 case OMPD_parallel_for_simd: 11691 case OMPD_distribute_parallel_for: 11692 case OMPD_distribute_parallel_for_simd: 11693 case OMPD_teams_distribute_parallel_for: 11694 case OMPD_teams_distribute_parallel_for_simd: 11695 case OMPD_target_parallel_for: 11696 case OMPD_target_parallel_for_simd: 11697 case OMPD_target_teams_distribute_parallel_for: 11698 case OMPD_target_teams_distribute_parallel_for_simd: 11699 CaptureRegion = OMPD_parallel; 11700 break; 11701 case OMPD_for: 11702 case OMPD_for_simd: 11703 // Do not capture schedule-clause expressions. 11704 break; 11705 case OMPD_task: 11706 case OMPD_taskloop: 11707 case OMPD_taskloop_simd: 11708 case OMPD_master_taskloop: 11709 case OMPD_master_taskloop_simd: 11710 case OMPD_parallel_master_taskloop: 11711 case OMPD_parallel_master_taskloop_simd: 11712 case OMPD_target_data: 11713 case OMPD_target_enter_data: 11714 case OMPD_target_exit_data: 11715 case OMPD_target_update: 11716 case OMPD_teams: 11717 case OMPD_teams_distribute: 11718 case OMPD_teams_distribute_simd: 11719 case OMPD_target_teams_distribute: 11720 case OMPD_target_teams_distribute_simd: 11721 case OMPD_target: 11722 case OMPD_target_simd: 11723 case OMPD_target_parallel: 11724 case OMPD_cancel: 11725 case OMPD_parallel: 11726 case OMPD_parallel_master: 11727 case OMPD_parallel_sections: 11728 case OMPD_threadprivate: 11729 case OMPD_allocate: 11730 case OMPD_taskyield: 11731 case OMPD_barrier: 11732 case OMPD_taskwait: 11733 case OMPD_cancellation_point: 11734 case OMPD_flush: 11735 case OMPD_depobj: 11736 case OMPD_scan: 11737 case OMPD_declare_reduction: 11738 case OMPD_declare_mapper: 11739 case OMPD_declare_simd: 11740 case OMPD_declare_variant: 11741 case OMPD_begin_declare_variant: 11742 case OMPD_end_declare_variant: 11743 case OMPD_declare_target: 11744 case OMPD_end_declare_target: 11745 case OMPD_simd: 11746 case OMPD_sections: 11747 case OMPD_section: 11748 case OMPD_single: 11749 case OMPD_master: 11750 case OMPD_critical: 11751 case OMPD_taskgroup: 11752 case OMPD_distribute: 11753 case OMPD_ordered: 11754 case OMPD_atomic: 11755 case OMPD_distribute_simd: 11756 case OMPD_target_teams: 11757 case OMPD_requires: 11758 llvm_unreachable("Unexpected OpenMP directive with schedule clause"); 11759 case OMPD_unknown: 11760 llvm_unreachable("Unknown OpenMP directive"); 11761 } 11762 break; 11763 case OMPC_dist_schedule: 11764 switch (DKind) { 11765 case OMPD_teams_distribute_parallel_for: 11766 case OMPD_teams_distribute_parallel_for_simd: 11767 case OMPD_teams_distribute: 11768 case OMPD_teams_distribute_simd: 11769 case OMPD_target_teams_distribute_parallel_for: 11770 case OMPD_target_teams_distribute_parallel_for_simd: 11771 case OMPD_target_teams_distribute: 11772 case OMPD_target_teams_distribute_simd: 11773 CaptureRegion = OMPD_teams; 11774 break; 11775 case OMPD_distribute_parallel_for: 11776 case OMPD_distribute_parallel_for_simd: 11777 case OMPD_distribute: 11778 case OMPD_distribute_simd: 11779 // Do not capture thread_limit-clause expressions. 11780 break; 11781 case OMPD_parallel_for: 11782 case OMPD_parallel_for_simd: 11783 case OMPD_target_parallel_for_simd: 11784 case OMPD_target_parallel_for: 11785 case OMPD_task: 11786 case OMPD_taskloop: 11787 case OMPD_taskloop_simd: 11788 case OMPD_master_taskloop: 11789 case OMPD_master_taskloop_simd: 11790 case OMPD_parallel_master_taskloop: 11791 case OMPD_parallel_master_taskloop_simd: 11792 case OMPD_target_data: 11793 case OMPD_target_enter_data: 11794 case OMPD_target_exit_data: 11795 case OMPD_target_update: 11796 case OMPD_teams: 11797 case OMPD_target: 11798 case OMPD_target_simd: 11799 case OMPD_target_parallel: 11800 case OMPD_cancel: 11801 case OMPD_parallel: 11802 case OMPD_parallel_master: 11803 case OMPD_parallel_sections: 11804 case OMPD_threadprivate: 11805 case OMPD_allocate: 11806 case OMPD_taskyield: 11807 case OMPD_barrier: 11808 case OMPD_taskwait: 11809 case OMPD_cancellation_point: 11810 case OMPD_flush: 11811 case OMPD_depobj: 11812 case OMPD_scan: 11813 case OMPD_declare_reduction: 11814 case OMPD_declare_mapper: 11815 case OMPD_declare_simd: 11816 case OMPD_declare_variant: 11817 case OMPD_begin_declare_variant: 11818 case OMPD_end_declare_variant: 11819 case OMPD_declare_target: 11820 case OMPD_end_declare_target: 11821 case OMPD_simd: 11822 case OMPD_for: 11823 case OMPD_for_simd: 11824 case OMPD_sections: 11825 case OMPD_section: 11826 case OMPD_single: 11827 case OMPD_master: 11828 case OMPD_critical: 11829 case OMPD_taskgroup: 11830 case OMPD_ordered: 11831 case OMPD_atomic: 11832 case OMPD_target_teams: 11833 case OMPD_requires: 11834 llvm_unreachable("Unexpected OpenMP directive with schedule clause"); 11835 case OMPD_unknown: 11836 llvm_unreachable("Unknown OpenMP directive"); 11837 } 11838 break; 11839 case OMPC_device: 11840 switch (DKind) { 11841 case OMPD_target_update: 11842 case OMPD_target_enter_data: 11843 case OMPD_target_exit_data: 11844 case OMPD_target: 11845 case OMPD_target_simd: 11846 case OMPD_target_teams: 11847 case OMPD_target_parallel: 11848 case OMPD_target_teams_distribute: 11849 case OMPD_target_teams_distribute_simd: 11850 case OMPD_target_parallel_for: 11851 case OMPD_target_parallel_for_simd: 11852 case OMPD_target_teams_distribute_parallel_for: 11853 case OMPD_target_teams_distribute_parallel_for_simd: 11854 CaptureRegion = OMPD_task; 11855 break; 11856 case OMPD_target_data: 11857 // Do not capture device-clause expressions. 11858 break; 11859 case OMPD_teams_distribute_parallel_for: 11860 case OMPD_teams_distribute_parallel_for_simd: 11861 case OMPD_teams: 11862 case OMPD_teams_distribute: 11863 case OMPD_teams_distribute_simd: 11864 case OMPD_distribute_parallel_for: 11865 case OMPD_distribute_parallel_for_simd: 11866 case OMPD_task: 11867 case OMPD_taskloop: 11868 case OMPD_taskloop_simd: 11869 case OMPD_master_taskloop: 11870 case OMPD_master_taskloop_simd: 11871 case OMPD_parallel_master_taskloop: 11872 case OMPD_parallel_master_taskloop_simd: 11873 case OMPD_cancel: 11874 case OMPD_parallel: 11875 case OMPD_parallel_master: 11876 case OMPD_parallel_sections: 11877 case OMPD_parallel_for: 11878 case OMPD_parallel_for_simd: 11879 case OMPD_threadprivate: 11880 case OMPD_allocate: 11881 case OMPD_taskyield: 11882 case OMPD_barrier: 11883 case OMPD_taskwait: 11884 case OMPD_cancellation_point: 11885 case OMPD_flush: 11886 case OMPD_depobj: 11887 case OMPD_scan: 11888 case OMPD_declare_reduction: 11889 case OMPD_declare_mapper: 11890 case OMPD_declare_simd: 11891 case OMPD_declare_variant: 11892 case OMPD_begin_declare_variant: 11893 case OMPD_end_declare_variant: 11894 case OMPD_declare_target: 11895 case OMPD_end_declare_target: 11896 case OMPD_simd: 11897 case OMPD_for: 11898 case OMPD_for_simd: 11899 case OMPD_sections: 11900 case OMPD_section: 11901 case OMPD_single: 11902 case OMPD_master: 11903 case OMPD_critical: 11904 case OMPD_taskgroup: 11905 case OMPD_distribute: 11906 case OMPD_ordered: 11907 case OMPD_atomic: 11908 case OMPD_distribute_simd: 11909 case OMPD_requires: 11910 llvm_unreachable("Unexpected OpenMP directive with num_teams-clause"); 11911 case OMPD_unknown: 11912 llvm_unreachable("Unknown OpenMP directive"); 11913 } 11914 break; 11915 case OMPC_grainsize: 11916 case OMPC_num_tasks: 11917 case OMPC_final: 11918 case OMPC_priority: 11919 switch (DKind) { 11920 case OMPD_task: 11921 case OMPD_taskloop: 11922 case OMPD_taskloop_simd: 11923 case OMPD_master_taskloop: 11924 case OMPD_master_taskloop_simd: 11925 break; 11926 case OMPD_parallel_master_taskloop: 11927 case OMPD_parallel_master_taskloop_simd: 11928 CaptureRegion = OMPD_parallel; 11929 break; 11930 case OMPD_target_update: 11931 case OMPD_target_enter_data: 11932 case OMPD_target_exit_data: 11933 case OMPD_target: 11934 case OMPD_target_simd: 11935 case OMPD_target_teams: 11936 case OMPD_target_parallel: 11937 case OMPD_target_teams_distribute: 11938 case OMPD_target_teams_distribute_simd: 11939 case OMPD_target_parallel_for: 11940 case OMPD_target_parallel_for_simd: 11941 case OMPD_target_teams_distribute_parallel_for: 11942 case OMPD_target_teams_distribute_parallel_for_simd: 11943 case OMPD_target_data: 11944 case OMPD_teams_distribute_parallel_for: 11945 case OMPD_teams_distribute_parallel_for_simd: 11946 case OMPD_teams: 11947 case OMPD_teams_distribute: 11948 case OMPD_teams_distribute_simd: 11949 case OMPD_distribute_parallel_for: 11950 case OMPD_distribute_parallel_for_simd: 11951 case OMPD_cancel: 11952 case OMPD_parallel: 11953 case OMPD_parallel_master: 11954 case OMPD_parallel_sections: 11955 case OMPD_parallel_for: 11956 case OMPD_parallel_for_simd: 11957 case OMPD_threadprivate: 11958 case OMPD_allocate: 11959 case OMPD_taskyield: 11960 case OMPD_barrier: 11961 case OMPD_taskwait: 11962 case OMPD_cancellation_point: 11963 case OMPD_flush: 11964 case OMPD_depobj: 11965 case OMPD_scan: 11966 case OMPD_declare_reduction: 11967 case OMPD_declare_mapper: 11968 case OMPD_declare_simd: 11969 case OMPD_declare_variant: 11970 case OMPD_begin_declare_variant: 11971 case OMPD_end_declare_variant: 11972 case OMPD_declare_target: 11973 case OMPD_end_declare_target: 11974 case OMPD_simd: 11975 case OMPD_for: 11976 case OMPD_for_simd: 11977 case OMPD_sections: 11978 case OMPD_section: 11979 case OMPD_single: 11980 case OMPD_master: 11981 case OMPD_critical: 11982 case OMPD_taskgroup: 11983 case OMPD_distribute: 11984 case OMPD_ordered: 11985 case OMPD_atomic: 11986 case OMPD_distribute_simd: 11987 case OMPD_requires: 11988 llvm_unreachable("Unexpected OpenMP directive with grainsize-clause"); 11989 case OMPD_unknown: 11990 llvm_unreachable("Unknown OpenMP directive"); 11991 } 11992 break; 11993 case OMPC_firstprivate: 11994 case OMPC_lastprivate: 11995 case OMPC_reduction: 11996 case OMPC_task_reduction: 11997 case OMPC_in_reduction: 11998 case OMPC_linear: 11999 case OMPC_default: 12000 case OMPC_proc_bind: 12001 case OMPC_safelen: 12002 case OMPC_simdlen: 12003 case OMPC_allocator: 12004 case OMPC_collapse: 12005 case OMPC_private: 12006 case OMPC_shared: 12007 case OMPC_aligned: 12008 case OMPC_copyin: 12009 case OMPC_copyprivate: 12010 case OMPC_ordered: 12011 case OMPC_nowait: 12012 case OMPC_untied: 12013 case OMPC_mergeable: 12014 case OMPC_threadprivate: 12015 case OMPC_allocate: 12016 case OMPC_flush: 12017 case OMPC_depobj: 12018 case OMPC_read: 12019 case OMPC_write: 12020 case OMPC_update: 12021 case OMPC_capture: 12022 case OMPC_seq_cst: 12023 case OMPC_acq_rel: 12024 case OMPC_acquire: 12025 case OMPC_release: 12026 case OMPC_relaxed: 12027 case OMPC_depend: 12028 case OMPC_threads: 12029 case OMPC_simd: 12030 case OMPC_map: 12031 case OMPC_nogroup: 12032 case OMPC_hint: 12033 case OMPC_defaultmap: 12034 case OMPC_unknown: 12035 case OMPC_uniform: 12036 case OMPC_to: 12037 case OMPC_from: 12038 case OMPC_use_device_ptr: 12039 case OMPC_is_device_ptr: 12040 case OMPC_unified_address: 12041 case OMPC_unified_shared_memory: 12042 case OMPC_reverse_offload: 12043 case OMPC_dynamic_allocators: 12044 case OMPC_atomic_default_mem_order: 12045 case OMPC_device_type: 12046 case OMPC_match: 12047 case OMPC_nontemporal: 12048 case OMPC_order: 12049 case OMPC_destroy: 12050 case OMPC_detach: 12051 case OMPC_inclusive: 12052 case OMPC_exclusive: 12053 llvm_unreachable("Unexpected OpenMP clause."); 12054 } 12055 return CaptureRegion; 12056 } 12057 12058 OMPClause *Sema::ActOnOpenMPIfClause(OpenMPDirectiveKind NameModifier, 12059 Expr *Condition, SourceLocation StartLoc, 12060 SourceLocation LParenLoc, 12061 SourceLocation NameModifierLoc, 12062 SourceLocation ColonLoc, 12063 SourceLocation EndLoc) { 12064 Expr *ValExpr = Condition; 12065 Stmt *HelperValStmt = nullptr; 12066 OpenMPDirectiveKind CaptureRegion = OMPD_unknown; 12067 if (!Condition->isValueDependent() && !Condition->isTypeDependent() && 12068 !Condition->isInstantiationDependent() && 12069 !Condition->containsUnexpandedParameterPack()) { 12070 ExprResult Val = CheckBooleanCondition(StartLoc, Condition); 12071 if (Val.isInvalid()) 12072 return nullptr; 12073 12074 ValExpr = Val.get(); 12075 12076 OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective(); 12077 CaptureRegion = getOpenMPCaptureRegionForClause( 12078 DKind, OMPC_if, LangOpts.OpenMP, NameModifier); 12079 if (CaptureRegion != OMPD_unknown && !CurContext->isDependentContext()) { 12080 ValExpr = MakeFullExpr(ValExpr).get(); 12081 llvm::MapVector<const Expr *, DeclRefExpr *> Captures; 12082 ValExpr = tryBuildCapture(*this, ValExpr, Captures).get(); 12083 HelperValStmt = buildPreInits(Context, Captures); 12084 } 12085 } 12086 12087 return new (Context) 12088 OMPIfClause(NameModifier, ValExpr, HelperValStmt, CaptureRegion, StartLoc, 12089 LParenLoc, NameModifierLoc, ColonLoc, EndLoc); 12090 } 12091 12092 OMPClause *Sema::ActOnOpenMPFinalClause(Expr *Condition, 12093 SourceLocation StartLoc, 12094 SourceLocation LParenLoc, 12095 SourceLocation EndLoc) { 12096 Expr *ValExpr = Condition; 12097 Stmt *HelperValStmt = nullptr; 12098 OpenMPDirectiveKind CaptureRegion = OMPD_unknown; 12099 if (!Condition->isValueDependent() && !Condition->isTypeDependent() && 12100 !Condition->isInstantiationDependent() && 12101 !Condition->containsUnexpandedParameterPack()) { 12102 ExprResult Val = CheckBooleanCondition(StartLoc, Condition); 12103 if (Val.isInvalid()) 12104 return nullptr; 12105 12106 ValExpr = MakeFullExpr(Val.get()).get(); 12107 12108 OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective(); 12109 CaptureRegion = 12110 getOpenMPCaptureRegionForClause(DKind, OMPC_final, LangOpts.OpenMP); 12111 if (CaptureRegion != OMPD_unknown && !CurContext->isDependentContext()) { 12112 ValExpr = MakeFullExpr(ValExpr).get(); 12113 llvm::MapVector<const Expr *, DeclRefExpr *> Captures; 12114 ValExpr = tryBuildCapture(*this, ValExpr, Captures).get(); 12115 HelperValStmt = buildPreInits(Context, Captures); 12116 } 12117 } 12118 12119 return new (Context) OMPFinalClause(ValExpr, HelperValStmt, CaptureRegion, 12120 StartLoc, LParenLoc, EndLoc); 12121 } 12122 12123 ExprResult Sema::PerformOpenMPImplicitIntegerConversion(SourceLocation Loc, 12124 Expr *Op) { 12125 if (!Op) 12126 return ExprError(); 12127 12128 class IntConvertDiagnoser : public ICEConvertDiagnoser { 12129 public: 12130 IntConvertDiagnoser() 12131 : ICEConvertDiagnoser(/*AllowScopedEnumerations*/ false, false, true) {} 12132 SemaDiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc, 12133 QualType T) override { 12134 return S.Diag(Loc, diag::err_omp_not_integral) << T; 12135 } 12136 SemaDiagnosticBuilder diagnoseIncomplete(Sema &S, SourceLocation Loc, 12137 QualType T) override { 12138 return S.Diag(Loc, diag::err_omp_incomplete_type) << T; 12139 } 12140 SemaDiagnosticBuilder diagnoseExplicitConv(Sema &S, SourceLocation Loc, 12141 QualType T, 12142 QualType ConvTy) override { 12143 return S.Diag(Loc, diag::err_omp_explicit_conversion) << T << ConvTy; 12144 } 12145 SemaDiagnosticBuilder noteExplicitConv(Sema &S, CXXConversionDecl *Conv, 12146 QualType ConvTy) override { 12147 return S.Diag(Conv->getLocation(), diag::note_omp_conversion_here) 12148 << ConvTy->isEnumeralType() << ConvTy; 12149 } 12150 SemaDiagnosticBuilder diagnoseAmbiguous(Sema &S, SourceLocation Loc, 12151 QualType T) override { 12152 return S.Diag(Loc, diag::err_omp_ambiguous_conversion) << T; 12153 } 12154 SemaDiagnosticBuilder noteAmbiguous(Sema &S, CXXConversionDecl *Conv, 12155 QualType ConvTy) override { 12156 return S.Diag(Conv->getLocation(), diag::note_omp_conversion_here) 12157 << ConvTy->isEnumeralType() << ConvTy; 12158 } 12159 SemaDiagnosticBuilder diagnoseConversion(Sema &, SourceLocation, QualType, 12160 QualType) override { 12161 llvm_unreachable("conversion functions are permitted"); 12162 } 12163 } ConvertDiagnoser; 12164 return PerformContextualImplicitConversion(Loc, Op, ConvertDiagnoser); 12165 } 12166 12167 static bool 12168 isNonNegativeIntegerValue(Expr *&ValExpr, Sema &SemaRef, OpenMPClauseKind CKind, 12169 bool StrictlyPositive, bool BuildCapture = false, 12170 OpenMPDirectiveKind DKind = OMPD_unknown, 12171 OpenMPDirectiveKind *CaptureRegion = nullptr, 12172 Stmt **HelperValStmt = nullptr) { 12173 if (!ValExpr->isTypeDependent() && !ValExpr->isValueDependent() && 12174 !ValExpr->isInstantiationDependent()) { 12175 SourceLocation Loc = ValExpr->getExprLoc(); 12176 ExprResult Value = 12177 SemaRef.PerformOpenMPImplicitIntegerConversion(Loc, ValExpr); 12178 if (Value.isInvalid()) 12179 return false; 12180 12181 ValExpr = Value.get(); 12182 // The expression must evaluate to a non-negative integer value. 12183 llvm::APSInt Result; 12184 if (ValExpr->isIntegerConstantExpr(Result, SemaRef.Context) && 12185 Result.isSigned() && 12186 !((!StrictlyPositive && Result.isNonNegative()) || 12187 (StrictlyPositive && Result.isStrictlyPositive()))) { 12188 SemaRef.Diag(Loc, diag::err_omp_negative_expression_in_clause) 12189 << getOpenMPClauseName(CKind) << (StrictlyPositive ? 1 : 0) 12190 << ValExpr->getSourceRange(); 12191 return false; 12192 } 12193 if (!BuildCapture) 12194 return true; 12195 *CaptureRegion = 12196 getOpenMPCaptureRegionForClause(DKind, CKind, SemaRef.LangOpts.OpenMP); 12197 if (*CaptureRegion != OMPD_unknown && 12198 !SemaRef.CurContext->isDependentContext()) { 12199 ValExpr = SemaRef.MakeFullExpr(ValExpr).get(); 12200 llvm::MapVector<const Expr *, DeclRefExpr *> Captures; 12201 ValExpr = tryBuildCapture(SemaRef, ValExpr, Captures).get(); 12202 *HelperValStmt = buildPreInits(SemaRef.Context, Captures); 12203 } 12204 } 12205 return true; 12206 } 12207 12208 OMPClause *Sema::ActOnOpenMPNumThreadsClause(Expr *NumThreads, 12209 SourceLocation StartLoc, 12210 SourceLocation LParenLoc, 12211 SourceLocation EndLoc) { 12212 Expr *ValExpr = NumThreads; 12213 Stmt *HelperValStmt = nullptr; 12214 12215 // OpenMP [2.5, Restrictions] 12216 // The num_threads expression must evaluate to a positive integer value. 12217 if (!isNonNegativeIntegerValue(ValExpr, *this, OMPC_num_threads, 12218 /*StrictlyPositive=*/true)) 12219 return nullptr; 12220 12221 OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective(); 12222 OpenMPDirectiveKind CaptureRegion = 12223 getOpenMPCaptureRegionForClause(DKind, OMPC_num_threads, LangOpts.OpenMP); 12224 if (CaptureRegion != OMPD_unknown && !CurContext->isDependentContext()) { 12225 ValExpr = MakeFullExpr(ValExpr).get(); 12226 llvm::MapVector<const Expr *, DeclRefExpr *> Captures; 12227 ValExpr = tryBuildCapture(*this, ValExpr, Captures).get(); 12228 HelperValStmt = buildPreInits(Context, Captures); 12229 } 12230 12231 return new (Context) OMPNumThreadsClause( 12232 ValExpr, HelperValStmt, CaptureRegion, StartLoc, LParenLoc, EndLoc); 12233 } 12234 12235 ExprResult Sema::VerifyPositiveIntegerConstantInClause(Expr *E, 12236 OpenMPClauseKind CKind, 12237 bool StrictlyPositive) { 12238 if (!E) 12239 return ExprError(); 12240 if (E->isValueDependent() || E->isTypeDependent() || 12241 E->isInstantiationDependent() || E->containsUnexpandedParameterPack()) 12242 return E; 12243 llvm::APSInt Result; 12244 ExprResult ICE = VerifyIntegerConstantExpression(E, &Result); 12245 if (ICE.isInvalid()) 12246 return ExprError(); 12247 if ((StrictlyPositive && !Result.isStrictlyPositive()) || 12248 (!StrictlyPositive && !Result.isNonNegative())) { 12249 Diag(E->getExprLoc(), diag::err_omp_negative_expression_in_clause) 12250 << getOpenMPClauseName(CKind) << (StrictlyPositive ? 1 : 0) 12251 << E->getSourceRange(); 12252 return ExprError(); 12253 } 12254 if (CKind == OMPC_aligned && !Result.isPowerOf2()) { 12255 Diag(E->getExprLoc(), diag::warn_omp_alignment_not_power_of_two) 12256 << E->getSourceRange(); 12257 return ExprError(); 12258 } 12259 if (CKind == OMPC_collapse && DSAStack->getAssociatedLoops() == 1) 12260 DSAStack->setAssociatedLoops(Result.getExtValue()); 12261 else if (CKind == OMPC_ordered) 12262 DSAStack->setAssociatedLoops(Result.getExtValue()); 12263 return ICE; 12264 } 12265 12266 OMPClause *Sema::ActOnOpenMPSafelenClause(Expr *Len, SourceLocation StartLoc, 12267 SourceLocation LParenLoc, 12268 SourceLocation EndLoc) { 12269 // OpenMP [2.8.1, simd construct, Description] 12270 // The parameter of the safelen clause must be a constant 12271 // positive integer expression. 12272 ExprResult Safelen = VerifyPositiveIntegerConstantInClause(Len, OMPC_safelen); 12273 if (Safelen.isInvalid()) 12274 return nullptr; 12275 return new (Context) 12276 OMPSafelenClause(Safelen.get(), StartLoc, LParenLoc, EndLoc); 12277 } 12278 12279 OMPClause *Sema::ActOnOpenMPSimdlenClause(Expr *Len, SourceLocation StartLoc, 12280 SourceLocation LParenLoc, 12281 SourceLocation EndLoc) { 12282 // OpenMP [2.8.1, simd construct, Description] 12283 // The parameter of the simdlen clause must be a constant 12284 // positive integer expression. 12285 ExprResult Simdlen = VerifyPositiveIntegerConstantInClause(Len, OMPC_simdlen); 12286 if (Simdlen.isInvalid()) 12287 return nullptr; 12288 return new (Context) 12289 OMPSimdlenClause(Simdlen.get(), StartLoc, LParenLoc, EndLoc); 12290 } 12291 12292 /// Tries to find omp_allocator_handle_t type. 12293 static bool findOMPAllocatorHandleT(Sema &S, SourceLocation Loc, 12294 DSAStackTy *Stack) { 12295 QualType OMPAllocatorHandleT = Stack->getOMPAllocatorHandleT(); 12296 if (!OMPAllocatorHandleT.isNull()) 12297 return true; 12298 // Build the predefined allocator expressions. 12299 bool ErrorFound = false; 12300 for (int I = OMPAllocateDeclAttr::OMPDefaultMemAlloc; 12301 I < OMPAllocateDeclAttr::OMPUserDefinedMemAlloc; ++I) { 12302 auto AllocatorKind = static_cast<OMPAllocateDeclAttr::AllocatorTypeTy>(I); 12303 StringRef Allocator = 12304 OMPAllocateDeclAttr::ConvertAllocatorTypeTyToStr(AllocatorKind); 12305 DeclarationName AllocatorName = &S.getASTContext().Idents.get(Allocator); 12306 auto *VD = dyn_cast_or_null<ValueDecl>( 12307 S.LookupSingleName(S.TUScope, AllocatorName, Loc, Sema::LookupAnyName)); 12308 if (!VD) { 12309 ErrorFound = true; 12310 break; 12311 } 12312 QualType AllocatorType = 12313 VD->getType().getNonLValueExprType(S.getASTContext()); 12314 ExprResult Res = S.BuildDeclRefExpr(VD, AllocatorType, VK_LValue, Loc); 12315 if (!Res.isUsable()) { 12316 ErrorFound = true; 12317 break; 12318 } 12319 if (OMPAllocatorHandleT.isNull()) 12320 OMPAllocatorHandleT = AllocatorType; 12321 if (!S.getASTContext().hasSameType(OMPAllocatorHandleT, AllocatorType)) { 12322 ErrorFound = true; 12323 break; 12324 } 12325 Stack->setAllocator(AllocatorKind, Res.get()); 12326 } 12327 if (ErrorFound) { 12328 S.Diag(Loc, diag::err_omp_implied_type_not_found) 12329 << "omp_allocator_handle_t"; 12330 return false; 12331 } 12332 OMPAllocatorHandleT.addConst(); 12333 Stack->setOMPAllocatorHandleT(OMPAllocatorHandleT); 12334 return true; 12335 } 12336 12337 OMPClause *Sema::ActOnOpenMPAllocatorClause(Expr *A, SourceLocation StartLoc, 12338 SourceLocation LParenLoc, 12339 SourceLocation EndLoc) { 12340 // OpenMP [2.11.3, allocate Directive, Description] 12341 // allocator is an expression of omp_allocator_handle_t type. 12342 if (!findOMPAllocatorHandleT(*this, A->getExprLoc(), DSAStack)) 12343 return nullptr; 12344 12345 ExprResult Allocator = DefaultLvalueConversion(A); 12346 if (Allocator.isInvalid()) 12347 return nullptr; 12348 Allocator = PerformImplicitConversion(Allocator.get(), 12349 DSAStack->getOMPAllocatorHandleT(), 12350 Sema::AA_Initializing, 12351 /*AllowExplicit=*/true); 12352 if (Allocator.isInvalid()) 12353 return nullptr; 12354 return new (Context) 12355 OMPAllocatorClause(Allocator.get(), StartLoc, LParenLoc, EndLoc); 12356 } 12357 12358 OMPClause *Sema::ActOnOpenMPCollapseClause(Expr *NumForLoops, 12359 SourceLocation StartLoc, 12360 SourceLocation LParenLoc, 12361 SourceLocation EndLoc) { 12362 // OpenMP [2.7.1, loop construct, Description] 12363 // OpenMP [2.8.1, simd construct, Description] 12364 // OpenMP [2.9.6, distribute construct, Description] 12365 // The parameter of the collapse clause must be a constant 12366 // positive integer expression. 12367 ExprResult NumForLoopsResult = 12368 VerifyPositiveIntegerConstantInClause(NumForLoops, OMPC_collapse); 12369 if (NumForLoopsResult.isInvalid()) 12370 return nullptr; 12371 return new (Context) 12372 OMPCollapseClause(NumForLoopsResult.get(), StartLoc, LParenLoc, EndLoc); 12373 } 12374 12375 OMPClause *Sema::ActOnOpenMPOrderedClause(SourceLocation StartLoc, 12376 SourceLocation EndLoc, 12377 SourceLocation LParenLoc, 12378 Expr *NumForLoops) { 12379 // OpenMP [2.7.1, loop construct, Description] 12380 // OpenMP [2.8.1, simd construct, Description] 12381 // OpenMP [2.9.6, distribute construct, Description] 12382 // The parameter of the ordered clause must be a constant 12383 // positive integer expression if any. 12384 if (NumForLoops && LParenLoc.isValid()) { 12385 ExprResult NumForLoopsResult = 12386 VerifyPositiveIntegerConstantInClause(NumForLoops, OMPC_ordered); 12387 if (NumForLoopsResult.isInvalid()) 12388 return nullptr; 12389 NumForLoops = NumForLoopsResult.get(); 12390 } else { 12391 NumForLoops = nullptr; 12392 } 12393 auto *Clause = OMPOrderedClause::Create( 12394 Context, NumForLoops, NumForLoops ? DSAStack->getAssociatedLoops() : 0, 12395 StartLoc, LParenLoc, EndLoc); 12396 DSAStack->setOrderedRegion(/*IsOrdered=*/true, NumForLoops, Clause); 12397 return Clause; 12398 } 12399 12400 OMPClause *Sema::ActOnOpenMPSimpleClause( 12401 OpenMPClauseKind Kind, unsigned Argument, SourceLocation ArgumentLoc, 12402 SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc) { 12403 OMPClause *Res = nullptr; 12404 switch (Kind) { 12405 case OMPC_default: 12406 Res = ActOnOpenMPDefaultClause(static_cast<DefaultKind>(Argument), 12407 ArgumentLoc, StartLoc, LParenLoc, EndLoc); 12408 break; 12409 case OMPC_proc_bind: 12410 Res = ActOnOpenMPProcBindClause(static_cast<ProcBindKind>(Argument), 12411 ArgumentLoc, StartLoc, LParenLoc, EndLoc); 12412 break; 12413 case OMPC_atomic_default_mem_order: 12414 Res = ActOnOpenMPAtomicDefaultMemOrderClause( 12415 static_cast<OpenMPAtomicDefaultMemOrderClauseKind>(Argument), 12416 ArgumentLoc, StartLoc, LParenLoc, EndLoc); 12417 break; 12418 case OMPC_order: 12419 Res = ActOnOpenMPOrderClause(static_cast<OpenMPOrderClauseKind>(Argument), 12420 ArgumentLoc, StartLoc, LParenLoc, EndLoc); 12421 break; 12422 case OMPC_update: 12423 Res = ActOnOpenMPUpdateClause(static_cast<OpenMPDependClauseKind>(Argument), 12424 ArgumentLoc, StartLoc, LParenLoc, EndLoc); 12425 break; 12426 case OMPC_if: 12427 case OMPC_final: 12428 case OMPC_num_threads: 12429 case OMPC_safelen: 12430 case OMPC_simdlen: 12431 case OMPC_allocator: 12432 case OMPC_collapse: 12433 case OMPC_schedule: 12434 case OMPC_private: 12435 case OMPC_firstprivate: 12436 case OMPC_lastprivate: 12437 case OMPC_shared: 12438 case OMPC_reduction: 12439 case OMPC_task_reduction: 12440 case OMPC_in_reduction: 12441 case OMPC_linear: 12442 case OMPC_aligned: 12443 case OMPC_copyin: 12444 case OMPC_copyprivate: 12445 case OMPC_ordered: 12446 case OMPC_nowait: 12447 case OMPC_untied: 12448 case OMPC_mergeable: 12449 case OMPC_threadprivate: 12450 case OMPC_allocate: 12451 case OMPC_flush: 12452 case OMPC_depobj: 12453 case OMPC_read: 12454 case OMPC_write: 12455 case OMPC_capture: 12456 case OMPC_seq_cst: 12457 case OMPC_acq_rel: 12458 case OMPC_acquire: 12459 case OMPC_release: 12460 case OMPC_relaxed: 12461 case OMPC_depend: 12462 case OMPC_device: 12463 case OMPC_threads: 12464 case OMPC_simd: 12465 case OMPC_map: 12466 case OMPC_num_teams: 12467 case OMPC_thread_limit: 12468 case OMPC_priority: 12469 case OMPC_grainsize: 12470 case OMPC_nogroup: 12471 case OMPC_num_tasks: 12472 case OMPC_hint: 12473 case OMPC_dist_schedule: 12474 case OMPC_defaultmap: 12475 case OMPC_unknown: 12476 case OMPC_uniform: 12477 case OMPC_to: 12478 case OMPC_from: 12479 case OMPC_use_device_ptr: 12480 case OMPC_is_device_ptr: 12481 case OMPC_unified_address: 12482 case OMPC_unified_shared_memory: 12483 case OMPC_reverse_offload: 12484 case OMPC_dynamic_allocators: 12485 case OMPC_device_type: 12486 case OMPC_match: 12487 case OMPC_nontemporal: 12488 case OMPC_destroy: 12489 case OMPC_detach: 12490 case OMPC_inclusive: 12491 case OMPC_exclusive: 12492 llvm_unreachable("Clause is not allowed."); 12493 } 12494 return Res; 12495 } 12496 12497 static std::string 12498 getListOfPossibleValues(OpenMPClauseKind K, unsigned First, unsigned Last, 12499 ArrayRef<unsigned> Exclude = llvm::None) { 12500 SmallString<256> Buffer; 12501 llvm::raw_svector_ostream Out(Buffer); 12502 unsigned Skipped = Exclude.size(); 12503 auto S = Exclude.begin(), E = Exclude.end(); 12504 for (unsigned I = First; I < Last; ++I) { 12505 if (std::find(S, E, I) != E) { 12506 --Skipped; 12507 continue; 12508 } 12509 Out << "'" << getOpenMPSimpleClauseTypeName(K, I) << "'"; 12510 if (I + Skipped + 2 == Last) 12511 Out << " or "; 12512 else if (I + Skipped + 1 != Last) 12513 Out << ", "; 12514 } 12515 return std::string(Out.str()); 12516 } 12517 12518 OMPClause *Sema::ActOnOpenMPDefaultClause(DefaultKind Kind, 12519 SourceLocation KindKwLoc, 12520 SourceLocation StartLoc, 12521 SourceLocation LParenLoc, 12522 SourceLocation EndLoc) { 12523 if (Kind == OMP_DEFAULT_unknown) { 12524 Diag(KindKwLoc, diag::err_omp_unexpected_clause_value) 12525 << getListOfPossibleValues(OMPC_default, /*First=*/0, 12526 /*Last=*/unsigned(OMP_DEFAULT_unknown)) 12527 << getOpenMPClauseName(OMPC_default); 12528 return nullptr; 12529 } 12530 if (Kind == OMP_DEFAULT_none) 12531 DSAStack->setDefaultDSANone(KindKwLoc); 12532 else if (Kind == OMP_DEFAULT_shared) 12533 DSAStack->setDefaultDSAShared(KindKwLoc); 12534 12535 return new (Context) 12536 OMPDefaultClause(Kind, KindKwLoc, StartLoc, LParenLoc, EndLoc); 12537 } 12538 12539 OMPClause *Sema::ActOnOpenMPProcBindClause(ProcBindKind Kind, 12540 SourceLocation KindKwLoc, 12541 SourceLocation StartLoc, 12542 SourceLocation LParenLoc, 12543 SourceLocation EndLoc) { 12544 if (Kind == OMP_PROC_BIND_unknown) { 12545 Diag(KindKwLoc, diag::err_omp_unexpected_clause_value) 12546 << getListOfPossibleValues(OMPC_proc_bind, 12547 /*First=*/unsigned(OMP_PROC_BIND_master), 12548 /*Last=*/5) 12549 << getOpenMPClauseName(OMPC_proc_bind); 12550 return nullptr; 12551 } 12552 return new (Context) 12553 OMPProcBindClause(Kind, KindKwLoc, StartLoc, LParenLoc, EndLoc); 12554 } 12555 12556 OMPClause *Sema::ActOnOpenMPAtomicDefaultMemOrderClause( 12557 OpenMPAtomicDefaultMemOrderClauseKind Kind, SourceLocation KindKwLoc, 12558 SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc) { 12559 if (Kind == OMPC_ATOMIC_DEFAULT_MEM_ORDER_unknown) { 12560 Diag(KindKwLoc, diag::err_omp_unexpected_clause_value) 12561 << getListOfPossibleValues( 12562 OMPC_atomic_default_mem_order, /*First=*/0, 12563 /*Last=*/OMPC_ATOMIC_DEFAULT_MEM_ORDER_unknown) 12564 << getOpenMPClauseName(OMPC_atomic_default_mem_order); 12565 return nullptr; 12566 } 12567 return new (Context) OMPAtomicDefaultMemOrderClause(Kind, KindKwLoc, StartLoc, 12568 LParenLoc, EndLoc); 12569 } 12570 12571 OMPClause *Sema::ActOnOpenMPOrderClause(OpenMPOrderClauseKind Kind, 12572 SourceLocation KindKwLoc, 12573 SourceLocation StartLoc, 12574 SourceLocation LParenLoc, 12575 SourceLocation EndLoc) { 12576 if (Kind == OMPC_ORDER_unknown) { 12577 static_assert(OMPC_ORDER_unknown > 0, 12578 "OMPC_ORDER_unknown not greater than 0"); 12579 Diag(KindKwLoc, diag::err_omp_unexpected_clause_value) 12580 << getListOfPossibleValues(OMPC_order, /*First=*/0, 12581 /*Last=*/OMPC_ORDER_unknown) 12582 << getOpenMPClauseName(OMPC_order); 12583 return nullptr; 12584 } 12585 return new (Context) 12586 OMPOrderClause(Kind, KindKwLoc, StartLoc, LParenLoc, EndLoc); 12587 } 12588 12589 OMPClause *Sema::ActOnOpenMPUpdateClause(OpenMPDependClauseKind Kind, 12590 SourceLocation KindKwLoc, 12591 SourceLocation StartLoc, 12592 SourceLocation LParenLoc, 12593 SourceLocation EndLoc) { 12594 if (Kind == OMPC_DEPEND_unknown || Kind == OMPC_DEPEND_source || 12595 Kind == OMPC_DEPEND_sink || Kind == OMPC_DEPEND_depobj) { 12596 unsigned Except[] = {OMPC_DEPEND_source, OMPC_DEPEND_sink, 12597 OMPC_DEPEND_depobj}; 12598 Diag(KindKwLoc, diag::err_omp_unexpected_clause_value) 12599 << getListOfPossibleValues(OMPC_depend, /*First=*/0, 12600 /*Last=*/OMPC_DEPEND_unknown, Except) 12601 << getOpenMPClauseName(OMPC_update); 12602 return nullptr; 12603 } 12604 return OMPUpdateClause::Create(Context, StartLoc, LParenLoc, KindKwLoc, Kind, 12605 EndLoc); 12606 } 12607 12608 OMPClause *Sema::ActOnOpenMPSingleExprWithArgClause( 12609 OpenMPClauseKind Kind, ArrayRef<unsigned> Argument, Expr *Expr, 12610 SourceLocation StartLoc, SourceLocation LParenLoc, 12611 ArrayRef<SourceLocation> ArgumentLoc, SourceLocation DelimLoc, 12612 SourceLocation EndLoc) { 12613 OMPClause *Res = nullptr; 12614 switch (Kind) { 12615 case OMPC_schedule: 12616 enum { Modifier1, Modifier2, ScheduleKind, NumberOfElements }; 12617 assert(Argument.size() == NumberOfElements && 12618 ArgumentLoc.size() == NumberOfElements); 12619 Res = ActOnOpenMPScheduleClause( 12620 static_cast<OpenMPScheduleClauseModifier>(Argument[Modifier1]), 12621 static_cast<OpenMPScheduleClauseModifier>(Argument[Modifier2]), 12622 static_cast<OpenMPScheduleClauseKind>(Argument[ScheduleKind]), Expr, 12623 StartLoc, LParenLoc, ArgumentLoc[Modifier1], ArgumentLoc[Modifier2], 12624 ArgumentLoc[ScheduleKind], DelimLoc, EndLoc); 12625 break; 12626 case OMPC_if: 12627 assert(Argument.size() == 1 && ArgumentLoc.size() == 1); 12628 Res = ActOnOpenMPIfClause(static_cast<OpenMPDirectiveKind>(Argument.back()), 12629 Expr, StartLoc, LParenLoc, ArgumentLoc.back(), 12630 DelimLoc, EndLoc); 12631 break; 12632 case OMPC_dist_schedule: 12633 Res = ActOnOpenMPDistScheduleClause( 12634 static_cast<OpenMPDistScheduleClauseKind>(Argument.back()), Expr, 12635 StartLoc, LParenLoc, ArgumentLoc.back(), DelimLoc, EndLoc); 12636 break; 12637 case OMPC_defaultmap: 12638 enum { Modifier, DefaultmapKind }; 12639 Res = ActOnOpenMPDefaultmapClause( 12640 static_cast<OpenMPDefaultmapClauseModifier>(Argument[Modifier]), 12641 static_cast<OpenMPDefaultmapClauseKind>(Argument[DefaultmapKind]), 12642 StartLoc, LParenLoc, ArgumentLoc[Modifier], ArgumentLoc[DefaultmapKind], 12643 EndLoc); 12644 break; 12645 case OMPC_device: 12646 assert(Argument.size() == 1 && ArgumentLoc.size() == 1); 12647 Res = ActOnOpenMPDeviceClause( 12648 static_cast<OpenMPDeviceClauseModifier>(Argument.back()), Expr, 12649 StartLoc, LParenLoc, ArgumentLoc.back(), EndLoc); 12650 break; 12651 case OMPC_final: 12652 case OMPC_num_threads: 12653 case OMPC_safelen: 12654 case OMPC_simdlen: 12655 case OMPC_allocator: 12656 case OMPC_collapse: 12657 case OMPC_default: 12658 case OMPC_proc_bind: 12659 case OMPC_private: 12660 case OMPC_firstprivate: 12661 case OMPC_lastprivate: 12662 case OMPC_shared: 12663 case OMPC_reduction: 12664 case OMPC_task_reduction: 12665 case OMPC_in_reduction: 12666 case OMPC_linear: 12667 case OMPC_aligned: 12668 case OMPC_copyin: 12669 case OMPC_copyprivate: 12670 case OMPC_ordered: 12671 case OMPC_nowait: 12672 case OMPC_untied: 12673 case OMPC_mergeable: 12674 case OMPC_threadprivate: 12675 case OMPC_allocate: 12676 case OMPC_flush: 12677 case OMPC_depobj: 12678 case OMPC_read: 12679 case OMPC_write: 12680 case OMPC_update: 12681 case OMPC_capture: 12682 case OMPC_seq_cst: 12683 case OMPC_acq_rel: 12684 case OMPC_acquire: 12685 case OMPC_release: 12686 case OMPC_relaxed: 12687 case OMPC_depend: 12688 case OMPC_threads: 12689 case OMPC_simd: 12690 case OMPC_map: 12691 case OMPC_num_teams: 12692 case OMPC_thread_limit: 12693 case OMPC_priority: 12694 case OMPC_grainsize: 12695 case OMPC_nogroup: 12696 case OMPC_num_tasks: 12697 case OMPC_hint: 12698 case OMPC_unknown: 12699 case OMPC_uniform: 12700 case OMPC_to: 12701 case OMPC_from: 12702 case OMPC_use_device_ptr: 12703 case OMPC_is_device_ptr: 12704 case OMPC_unified_address: 12705 case OMPC_unified_shared_memory: 12706 case OMPC_reverse_offload: 12707 case OMPC_dynamic_allocators: 12708 case OMPC_atomic_default_mem_order: 12709 case OMPC_device_type: 12710 case OMPC_match: 12711 case OMPC_nontemporal: 12712 case OMPC_order: 12713 case OMPC_destroy: 12714 case OMPC_detach: 12715 case OMPC_inclusive: 12716 case OMPC_exclusive: 12717 llvm_unreachable("Clause is not allowed."); 12718 } 12719 return Res; 12720 } 12721 12722 static bool checkScheduleModifiers(Sema &S, OpenMPScheduleClauseModifier M1, 12723 OpenMPScheduleClauseModifier M2, 12724 SourceLocation M1Loc, SourceLocation M2Loc) { 12725 if (M1 == OMPC_SCHEDULE_MODIFIER_unknown && M1Loc.isValid()) { 12726 SmallVector<unsigned, 2> Excluded; 12727 if (M2 != OMPC_SCHEDULE_MODIFIER_unknown) 12728 Excluded.push_back(M2); 12729 if (M2 == OMPC_SCHEDULE_MODIFIER_nonmonotonic) 12730 Excluded.push_back(OMPC_SCHEDULE_MODIFIER_monotonic); 12731 if (M2 == OMPC_SCHEDULE_MODIFIER_monotonic) 12732 Excluded.push_back(OMPC_SCHEDULE_MODIFIER_nonmonotonic); 12733 S.Diag(M1Loc, diag::err_omp_unexpected_clause_value) 12734 << getListOfPossibleValues(OMPC_schedule, 12735 /*First=*/OMPC_SCHEDULE_MODIFIER_unknown + 1, 12736 /*Last=*/OMPC_SCHEDULE_MODIFIER_last, 12737 Excluded) 12738 << getOpenMPClauseName(OMPC_schedule); 12739 return true; 12740 } 12741 return false; 12742 } 12743 12744 OMPClause *Sema::ActOnOpenMPScheduleClause( 12745 OpenMPScheduleClauseModifier M1, OpenMPScheduleClauseModifier M2, 12746 OpenMPScheduleClauseKind Kind, Expr *ChunkSize, SourceLocation StartLoc, 12747 SourceLocation LParenLoc, SourceLocation M1Loc, SourceLocation M2Loc, 12748 SourceLocation KindLoc, SourceLocation CommaLoc, SourceLocation EndLoc) { 12749 if (checkScheduleModifiers(*this, M1, M2, M1Loc, M2Loc) || 12750 checkScheduleModifiers(*this, M2, M1, M2Loc, M1Loc)) 12751 return nullptr; 12752 // OpenMP, 2.7.1, Loop Construct, Restrictions 12753 // Either the monotonic modifier or the nonmonotonic modifier can be specified 12754 // but not both. 12755 if ((M1 == M2 && M1 != OMPC_SCHEDULE_MODIFIER_unknown) || 12756 (M1 == OMPC_SCHEDULE_MODIFIER_monotonic && 12757 M2 == OMPC_SCHEDULE_MODIFIER_nonmonotonic) || 12758 (M1 == OMPC_SCHEDULE_MODIFIER_nonmonotonic && 12759 M2 == OMPC_SCHEDULE_MODIFIER_monotonic)) { 12760 Diag(M2Loc, diag::err_omp_unexpected_schedule_modifier) 12761 << getOpenMPSimpleClauseTypeName(OMPC_schedule, M2) 12762 << getOpenMPSimpleClauseTypeName(OMPC_schedule, M1); 12763 return nullptr; 12764 } 12765 if (Kind == OMPC_SCHEDULE_unknown) { 12766 std::string Values; 12767 if (M1Loc.isInvalid() && M2Loc.isInvalid()) { 12768 unsigned Exclude[] = {OMPC_SCHEDULE_unknown}; 12769 Values = getListOfPossibleValues(OMPC_schedule, /*First=*/0, 12770 /*Last=*/OMPC_SCHEDULE_MODIFIER_last, 12771 Exclude); 12772 } else { 12773 Values = getListOfPossibleValues(OMPC_schedule, /*First=*/0, 12774 /*Last=*/OMPC_SCHEDULE_unknown); 12775 } 12776 Diag(KindLoc, diag::err_omp_unexpected_clause_value) 12777 << Values << getOpenMPClauseName(OMPC_schedule); 12778 return nullptr; 12779 } 12780 // OpenMP, 2.7.1, Loop Construct, Restrictions 12781 // The nonmonotonic modifier can only be specified with schedule(dynamic) or 12782 // schedule(guided). 12783 if ((M1 == OMPC_SCHEDULE_MODIFIER_nonmonotonic || 12784 M2 == OMPC_SCHEDULE_MODIFIER_nonmonotonic) && 12785 Kind != OMPC_SCHEDULE_dynamic && Kind != OMPC_SCHEDULE_guided) { 12786 Diag(M1 == OMPC_SCHEDULE_MODIFIER_nonmonotonic ? M1Loc : M2Loc, 12787 diag::err_omp_schedule_nonmonotonic_static); 12788 return nullptr; 12789 } 12790 Expr *ValExpr = ChunkSize; 12791 Stmt *HelperValStmt = nullptr; 12792 if (ChunkSize) { 12793 if (!ChunkSize->isValueDependent() && !ChunkSize->isTypeDependent() && 12794 !ChunkSize->isInstantiationDependent() && 12795 !ChunkSize->containsUnexpandedParameterPack()) { 12796 SourceLocation ChunkSizeLoc = ChunkSize->getBeginLoc(); 12797 ExprResult Val = 12798 PerformOpenMPImplicitIntegerConversion(ChunkSizeLoc, ChunkSize); 12799 if (Val.isInvalid()) 12800 return nullptr; 12801 12802 ValExpr = Val.get(); 12803 12804 // OpenMP [2.7.1, Restrictions] 12805 // chunk_size must be a loop invariant integer expression with a positive 12806 // value. 12807 llvm::APSInt Result; 12808 if (ValExpr->isIntegerConstantExpr(Result, Context)) { 12809 if (Result.isSigned() && !Result.isStrictlyPositive()) { 12810 Diag(ChunkSizeLoc, diag::err_omp_negative_expression_in_clause) 12811 << "schedule" << 1 << ChunkSize->getSourceRange(); 12812 return nullptr; 12813 } 12814 } else if (getOpenMPCaptureRegionForClause( 12815 DSAStack->getCurrentDirective(), OMPC_schedule, 12816 LangOpts.OpenMP) != OMPD_unknown && 12817 !CurContext->isDependentContext()) { 12818 ValExpr = MakeFullExpr(ValExpr).get(); 12819 llvm::MapVector<const Expr *, DeclRefExpr *> Captures; 12820 ValExpr = tryBuildCapture(*this, ValExpr, Captures).get(); 12821 HelperValStmt = buildPreInits(Context, Captures); 12822 } 12823 } 12824 } 12825 12826 return new (Context) 12827 OMPScheduleClause(StartLoc, LParenLoc, KindLoc, CommaLoc, EndLoc, Kind, 12828 ValExpr, HelperValStmt, M1, M1Loc, M2, M2Loc); 12829 } 12830 12831 OMPClause *Sema::ActOnOpenMPClause(OpenMPClauseKind Kind, 12832 SourceLocation StartLoc, 12833 SourceLocation EndLoc) { 12834 OMPClause *Res = nullptr; 12835 switch (Kind) { 12836 case OMPC_ordered: 12837 Res = ActOnOpenMPOrderedClause(StartLoc, EndLoc); 12838 break; 12839 case OMPC_nowait: 12840 Res = ActOnOpenMPNowaitClause(StartLoc, EndLoc); 12841 break; 12842 case OMPC_untied: 12843 Res = ActOnOpenMPUntiedClause(StartLoc, EndLoc); 12844 break; 12845 case OMPC_mergeable: 12846 Res = ActOnOpenMPMergeableClause(StartLoc, EndLoc); 12847 break; 12848 case OMPC_read: 12849 Res = ActOnOpenMPReadClause(StartLoc, EndLoc); 12850 break; 12851 case OMPC_write: 12852 Res = ActOnOpenMPWriteClause(StartLoc, EndLoc); 12853 break; 12854 case OMPC_update: 12855 Res = ActOnOpenMPUpdateClause(StartLoc, EndLoc); 12856 break; 12857 case OMPC_capture: 12858 Res = ActOnOpenMPCaptureClause(StartLoc, EndLoc); 12859 break; 12860 case OMPC_seq_cst: 12861 Res = ActOnOpenMPSeqCstClause(StartLoc, EndLoc); 12862 break; 12863 case OMPC_acq_rel: 12864 Res = ActOnOpenMPAcqRelClause(StartLoc, EndLoc); 12865 break; 12866 case OMPC_acquire: 12867 Res = ActOnOpenMPAcquireClause(StartLoc, EndLoc); 12868 break; 12869 case OMPC_release: 12870 Res = ActOnOpenMPReleaseClause(StartLoc, EndLoc); 12871 break; 12872 case OMPC_relaxed: 12873 Res = ActOnOpenMPRelaxedClause(StartLoc, EndLoc); 12874 break; 12875 case OMPC_threads: 12876 Res = ActOnOpenMPThreadsClause(StartLoc, EndLoc); 12877 break; 12878 case OMPC_simd: 12879 Res = ActOnOpenMPSIMDClause(StartLoc, EndLoc); 12880 break; 12881 case OMPC_nogroup: 12882 Res = ActOnOpenMPNogroupClause(StartLoc, EndLoc); 12883 break; 12884 case OMPC_unified_address: 12885 Res = ActOnOpenMPUnifiedAddressClause(StartLoc, EndLoc); 12886 break; 12887 case OMPC_unified_shared_memory: 12888 Res = ActOnOpenMPUnifiedSharedMemoryClause(StartLoc, EndLoc); 12889 break; 12890 case OMPC_reverse_offload: 12891 Res = ActOnOpenMPReverseOffloadClause(StartLoc, EndLoc); 12892 break; 12893 case OMPC_dynamic_allocators: 12894 Res = ActOnOpenMPDynamicAllocatorsClause(StartLoc, EndLoc); 12895 break; 12896 case OMPC_destroy: 12897 Res = ActOnOpenMPDestroyClause(StartLoc, EndLoc); 12898 break; 12899 case OMPC_if: 12900 case OMPC_final: 12901 case OMPC_num_threads: 12902 case OMPC_safelen: 12903 case OMPC_simdlen: 12904 case OMPC_allocator: 12905 case OMPC_collapse: 12906 case OMPC_schedule: 12907 case OMPC_private: 12908 case OMPC_firstprivate: 12909 case OMPC_lastprivate: 12910 case OMPC_shared: 12911 case OMPC_reduction: 12912 case OMPC_task_reduction: 12913 case OMPC_in_reduction: 12914 case OMPC_linear: 12915 case OMPC_aligned: 12916 case OMPC_copyin: 12917 case OMPC_copyprivate: 12918 case OMPC_default: 12919 case OMPC_proc_bind: 12920 case OMPC_threadprivate: 12921 case OMPC_allocate: 12922 case OMPC_flush: 12923 case OMPC_depobj: 12924 case OMPC_depend: 12925 case OMPC_device: 12926 case OMPC_map: 12927 case OMPC_num_teams: 12928 case OMPC_thread_limit: 12929 case OMPC_priority: 12930 case OMPC_grainsize: 12931 case OMPC_num_tasks: 12932 case OMPC_hint: 12933 case OMPC_dist_schedule: 12934 case OMPC_defaultmap: 12935 case OMPC_unknown: 12936 case OMPC_uniform: 12937 case OMPC_to: 12938 case OMPC_from: 12939 case OMPC_use_device_ptr: 12940 case OMPC_is_device_ptr: 12941 case OMPC_atomic_default_mem_order: 12942 case OMPC_device_type: 12943 case OMPC_match: 12944 case OMPC_nontemporal: 12945 case OMPC_order: 12946 case OMPC_detach: 12947 case OMPC_inclusive: 12948 case OMPC_exclusive: 12949 llvm_unreachable("Clause is not allowed."); 12950 } 12951 return Res; 12952 } 12953 12954 OMPClause *Sema::ActOnOpenMPNowaitClause(SourceLocation StartLoc, 12955 SourceLocation EndLoc) { 12956 DSAStack->setNowaitRegion(); 12957 return new (Context) OMPNowaitClause(StartLoc, EndLoc); 12958 } 12959 12960 OMPClause *Sema::ActOnOpenMPUntiedClause(SourceLocation StartLoc, 12961 SourceLocation EndLoc) { 12962 return new (Context) OMPUntiedClause(StartLoc, EndLoc); 12963 } 12964 12965 OMPClause *Sema::ActOnOpenMPMergeableClause(SourceLocation StartLoc, 12966 SourceLocation EndLoc) { 12967 return new (Context) OMPMergeableClause(StartLoc, EndLoc); 12968 } 12969 12970 OMPClause *Sema::ActOnOpenMPReadClause(SourceLocation StartLoc, 12971 SourceLocation EndLoc) { 12972 return new (Context) OMPReadClause(StartLoc, EndLoc); 12973 } 12974 12975 OMPClause *Sema::ActOnOpenMPWriteClause(SourceLocation StartLoc, 12976 SourceLocation EndLoc) { 12977 return new (Context) OMPWriteClause(StartLoc, EndLoc); 12978 } 12979 12980 OMPClause *Sema::ActOnOpenMPUpdateClause(SourceLocation StartLoc, 12981 SourceLocation EndLoc) { 12982 return OMPUpdateClause::Create(Context, StartLoc, EndLoc); 12983 } 12984 12985 OMPClause *Sema::ActOnOpenMPCaptureClause(SourceLocation StartLoc, 12986 SourceLocation EndLoc) { 12987 return new (Context) OMPCaptureClause(StartLoc, EndLoc); 12988 } 12989 12990 OMPClause *Sema::ActOnOpenMPSeqCstClause(SourceLocation StartLoc, 12991 SourceLocation EndLoc) { 12992 return new (Context) OMPSeqCstClause(StartLoc, EndLoc); 12993 } 12994 12995 OMPClause *Sema::ActOnOpenMPAcqRelClause(SourceLocation StartLoc, 12996 SourceLocation EndLoc) { 12997 return new (Context) OMPAcqRelClause(StartLoc, EndLoc); 12998 } 12999 13000 OMPClause *Sema::ActOnOpenMPAcquireClause(SourceLocation StartLoc, 13001 SourceLocation EndLoc) { 13002 return new (Context) OMPAcquireClause(StartLoc, EndLoc); 13003 } 13004 13005 OMPClause *Sema::ActOnOpenMPReleaseClause(SourceLocation StartLoc, 13006 SourceLocation EndLoc) { 13007 return new (Context) OMPReleaseClause(StartLoc, EndLoc); 13008 } 13009 13010 OMPClause *Sema::ActOnOpenMPRelaxedClause(SourceLocation StartLoc, 13011 SourceLocation EndLoc) { 13012 return new (Context) OMPRelaxedClause(StartLoc, EndLoc); 13013 } 13014 13015 OMPClause *Sema::ActOnOpenMPThreadsClause(SourceLocation StartLoc, 13016 SourceLocation EndLoc) { 13017 return new (Context) OMPThreadsClause(StartLoc, EndLoc); 13018 } 13019 13020 OMPClause *Sema::ActOnOpenMPSIMDClause(SourceLocation StartLoc, 13021 SourceLocation EndLoc) { 13022 return new (Context) OMPSIMDClause(StartLoc, EndLoc); 13023 } 13024 13025 OMPClause *Sema::ActOnOpenMPNogroupClause(SourceLocation StartLoc, 13026 SourceLocation EndLoc) { 13027 return new (Context) OMPNogroupClause(StartLoc, EndLoc); 13028 } 13029 13030 OMPClause *Sema::ActOnOpenMPUnifiedAddressClause(SourceLocation StartLoc, 13031 SourceLocation EndLoc) { 13032 return new (Context) OMPUnifiedAddressClause(StartLoc, EndLoc); 13033 } 13034 13035 OMPClause *Sema::ActOnOpenMPUnifiedSharedMemoryClause(SourceLocation StartLoc, 13036 SourceLocation EndLoc) { 13037 return new (Context) OMPUnifiedSharedMemoryClause(StartLoc, EndLoc); 13038 } 13039 13040 OMPClause *Sema::ActOnOpenMPReverseOffloadClause(SourceLocation StartLoc, 13041 SourceLocation EndLoc) { 13042 return new (Context) OMPReverseOffloadClause(StartLoc, EndLoc); 13043 } 13044 13045 OMPClause *Sema::ActOnOpenMPDynamicAllocatorsClause(SourceLocation StartLoc, 13046 SourceLocation EndLoc) { 13047 return new (Context) OMPDynamicAllocatorsClause(StartLoc, EndLoc); 13048 } 13049 13050 OMPClause *Sema::ActOnOpenMPDestroyClause(SourceLocation StartLoc, 13051 SourceLocation EndLoc) { 13052 return new (Context) OMPDestroyClause(StartLoc, EndLoc); 13053 } 13054 13055 OMPClause *Sema::ActOnOpenMPVarListClause( 13056 OpenMPClauseKind Kind, ArrayRef<Expr *> VarList, Expr *TailExpr, 13057 const OMPVarListLocTy &Locs, SourceLocation ColonLoc, 13058 CXXScopeSpec &ReductionOrMapperIdScopeSpec, 13059 DeclarationNameInfo &ReductionOrMapperId, int ExtraModifier, 13060 ArrayRef<OpenMPMapModifierKind> MapTypeModifiers, 13061 ArrayRef<SourceLocation> MapTypeModifiersLoc, bool IsMapTypeImplicit, 13062 SourceLocation ExtraModifierLoc) { 13063 SourceLocation StartLoc = Locs.StartLoc; 13064 SourceLocation LParenLoc = Locs.LParenLoc; 13065 SourceLocation EndLoc = Locs.EndLoc; 13066 OMPClause *Res = nullptr; 13067 switch (Kind) { 13068 case OMPC_private: 13069 Res = ActOnOpenMPPrivateClause(VarList, StartLoc, LParenLoc, EndLoc); 13070 break; 13071 case OMPC_firstprivate: 13072 Res = ActOnOpenMPFirstprivateClause(VarList, StartLoc, LParenLoc, EndLoc); 13073 break; 13074 case OMPC_lastprivate: 13075 assert(0 <= ExtraModifier && ExtraModifier <= OMPC_LASTPRIVATE_unknown && 13076 "Unexpected lastprivate modifier."); 13077 Res = ActOnOpenMPLastprivateClause( 13078 VarList, static_cast<OpenMPLastprivateModifier>(ExtraModifier), 13079 ExtraModifierLoc, ColonLoc, StartLoc, LParenLoc, EndLoc); 13080 break; 13081 case OMPC_shared: 13082 Res = ActOnOpenMPSharedClause(VarList, StartLoc, LParenLoc, EndLoc); 13083 break; 13084 case OMPC_reduction: 13085 assert(0 <= ExtraModifier && ExtraModifier <= OMPC_REDUCTION_unknown && 13086 "Unexpected lastprivate modifier."); 13087 Res = ActOnOpenMPReductionClause( 13088 VarList, static_cast<OpenMPReductionClauseModifier>(ExtraModifier), 13089 StartLoc, LParenLoc, ExtraModifierLoc, ColonLoc, EndLoc, 13090 ReductionOrMapperIdScopeSpec, ReductionOrMapperId); 13091 break; 13092 case OMPC_task_reduction: 13093 Res = ActOnOpenMPTaskReductionClause(VarList, StartLoc, LParenLoc, ColonLoc, 13094 EndLoc, ReductionOrMapperIdScopeSpec, 13095 ReductionOrMapperId); 13096 break; 13097 case OMPC_in_reduction: 13098 Res = ActOnOpenMPInReductionClause(VarList, StartLoc, LParenLoc, ColonLoc, 13099 EndLoc, ReductionOrMapperIdScopeSpec, 13100 ReductionOrMapperId); 13101 break; 13102 case OMPC_linear: 13103 assert(0 <= ExtraModifier && ExtraModifier <= OMPC_LINEAR_unknown && 13104 "Unexpected linear modifier."); 13105 Res = ActOnOpenMPLinearClause( 13106 VarList, TailExpr, StartLoc, LParenLoc, 13107 static_cast<OpenMPLinearClauseKind>(ExtraModifier), ExtraModifierLoc, 13108 ColonLoc, EndLoc); 13109 break; 13110 case OMPC_aligned: 13111 Res = ActOnOpenMPAlignedClause(VarList, TailExpr, StartLoc, LParenLoc, 13112 ColonLoc, EndLoc); 13113 break; 13114 case OMPC_copyin: 13115 Res = ActOnOpenMPCopyinClause(VarList, StartLoc, LParenLoc, EndLoc); 13116 break; 13117 case OMPC_copyprivate: 13118 Res = ActOnOpenMPCopyprivateClause(VarList, StartLoc, LParenLoc, EndLoc); 13119 break; 13120 case OMPC_flush: 13121 Res = ActOnOpenMPFlushClause(VarList, StartLoc, LParenLoc, EndLoc); 13122 break; 13123 case OMPC_depend: 13124 assert(0 <= ExtraModifier && ExtraModifier <= OMPC_DEPEND_unknown && 13125 "Unexpected depend modifier."); 13126 Res = ActOnOpenMPDependClause( 13127 static_cast<OpenMPDependClauseKind>(ExtraModifier), ExtraModifierLoc, 13128 ColonLoc, VarList, StartLoc, LParenLoc, EndLoc); 13129 break; 13130 case OMPC_map: 13131 assert(0 <= ExtraModifier && ExtraModifier <= OMPC_MAP_unknown && 13132 "Unexpected map modifier."); 13133 Res = ActOnOpenMPMapClause( 13134 MapTypeModifiers, MapTypeModifiersLoc, ReductionOrMapperIdScopeSpec, 13135 ReductionOrMapperId, static_cast<OpenMPMapClauseKind>(ExtraModifier), 13136 IsMapTypeImplicit, ExtraModifierLoc, ColonLoc, VarList, Locs); 13137 break; 13138 case OMPC_to: 13139 Res = ActOnOpenMPToClause(VarList, ReductionOrMapperIdScopeSpec, 13140 ReductionOrMapperId, Locs); 13141 break; 13142 case OMPC_from: 13143 Res = ActOnOpenMPFromClause(VarList, ReductionOrMapperIdScopeSpec, 13144 ReductionOrMapperId, Locs); 13145 break; 13146 case OMPC_use_device_ptr: 13147 Res = ActOnOpenMPUseDevicePtrClause(VarList, Locs); 13148 break; 13149 case OMPC_is_device_ptr: 13150 Res = ActOnOpenMPIsDevicePtrClause(VarList, Locs); 13151 break; 13152 case OMPC_allocate: 13153 Res = ActOnOpenMPAllocateClause(TailExpr, VarList, StartLoc, LParenLoc, 13154 ColonLoc, EndLoc); 13155 break; 13156 case OMPC_nontemporal: 13157 Res = ActOnOpenMPNontemporalClause(VarList, StartLoc, LParenLoc, EndLoc); 13158 break; 13159 case OMPC_inclusive: 13160 Res = ActOnOpenMPInclusiveClause(VarList, StartLoc, LParenLoc, EndLoc); 13161 break; 13162 case OMPC_exclusive: 13163 Res = ActOnOpenMPExclusiveClause(VarList, StartLoc, LParenLoc, EndLoc); 13164 break; 13165 case OMPC_if: 13166 case OMPC_depobj: 13167 case OMPC_final: 13168 case OMPC_num_threads: 13169 case OMPC_safelen: 13170 case OMPC_simdlen: 13171 case OMPC_allocator: 13172 case OMPC_collapse: 13173 case OMPC_default: 13174 case OMPC_proc_bind: 13175 case OMPC_schedule: 13176 case OMPC_ordered: 13177 case OMPC_nowait: 13178 case OMPC_untied: 13179 case OMPC_mergeable: 13180 case OMPC_threadprivate: 13181 case OMPC_read: 13182 case OMPC_write: 13183 case OMPC_update: 13184 case OMPC_capture: 13185 case OMPC_seq_cst: 13186 case OMPC_acq_rel: 13187 case OMPC_acquire: 13188 case OMPC_release: 13189 case OMPC_relaxed: 13190 case OMPC_device: 13191 case OMPC_threads: 13192 case OMPC_simd: 13193 case OMPC_num_teams: 13194 case OMPC_thread_limit: 13195 case OMPC_priority: 13196 case OMPC_grainsize: 13197 case OMPC_nogroup: 13198 case OMPC_num_tasks: 13199 case OMPC_hint: 13200 case OMPC_dist_schedule: 13201 case OMPC_defaultmap: 13202 case OMPC_unknown: 13203 case OMPC_uniform: 13204 case OMPC_unified_address: 13205 case OMPC_unified_shared_memory: 13206 case OMPC_reverse_offload: 13207 case OMPC_dynamic_allocators: 13208 case OMPC_atomic_default_mem_order: 13209 case OMPC_device_type: 13210 case OMPC_match: 13211 case OMPC_order: 13212 case OMPC_destroy: 13213 case OMPC_detach: 13214 llvm_unreachable("Clause is not allowed."); 13215 } 13216 return Res; 13217 } 13218 13219 ExprResult Sema::getOpenMPCapturedExpr(VarDecl *Capture, ExprValueKind VK, 13220 ExprObjectKind OK, SourceLocation Loc) { 13221 ExprResult Res = BuildDeclRefExpr( 13222 Capture, Capture->getType().getNonReferenceType(), VK_LValue, Loc); 13223 if (!Res.isUsable()) 13224 return ExprError(); 13225 if (OK == OK_Ordinary && !getLangOpts().CPlusPlus) { 13226 Res = CreateBuiltinUnaryOp(Loc, UO_Deref, Res.get()); 13227 if (!Res.isUsable()) 13228 return ExprError(); 13229 } 13230 if (VK != VK_LValue && Res.get()->isGLValue()) { 13231 Res = DefaultLvalueConversion(Res.get()); 13232 if (!Res.isUsable()) 13233 return ExprError(); 13234 } 13235 return Res; 13236 } 13237 13238 OMPClause *Sema::ActOnOpenMPPrivateClause(ArrayRef<Expr *> VarList, 13239 SourceLocation StartLoc, 13240 SourceLocation LParenLoc, 13241 SourceLocation EndLoc) { 13242 SmallVector<Expr *, 8> Vars; 13243 SmallVector<Expr *, 8> PrivateCopies; 13244 for (Expr *RefExpr : VarList) { 13245 assert(RefExpr && "NULL expr in OpenMP private clause."); 13246 SourceLocation ELoc; 13247 SourceRange ERange; 13248 Expr *SimpleRefExpr = RefExpr; 13249 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange); 13250 if (Res.second) { 13251 // It will be analyzed later. 13252 Vars.push_back(RefExpr); 13253 PrivateCopies.push_back(nullptr); 13254 } 13255 ValueDecl *D = Res.first; 13256 if (!D) 13257 continue; 13258 13259 QualType Type = D->getType(); 13260 auto *VD = dyn_cast<VarDecl>(D); 13261 13262 // OpenMP [2.9.3.3, Restrictions, C/C++, p.3] 13263 // A variable that appears in a private clause must not have an incomplete 13264 // type or a reference type. 13265 if (RequireCompleteType(ELoc, Type, diag::err_omp_private_incomplete_type)) 13266 continue; 13267 Type = Type.getNonReferenceType(); 13268 13269 // OpenMP 5.0 [2.19.3, List Item Privatization, Restrictions] 13270 // A variable that is privatized must not have a const-qualified type 13271 // unless it is of class type with a mutable member. This restriction does 13272 // not apply to the firstprivate clause. 13273 // 13274 // OpenMP 3.1 [2.9.3.3, private clause, Restrictions] 13275 // A variable that appears in a private clause must not have a 13276 // const-qualified type unless it is of class type with a mutable member. 13277 if (rejectConstNotMutableType(*this, D, Type, OMPC_private, ELoc)) 13278 continue; 13279 13280 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced 13281 // in a Construct] 13282 // Variables with the predetermined data-sharing attributes may not be 13283 // listed in data-sharing attributes clauses, except for the cases 13284 // listed below. For these exceptions only, listing a predetermined 13285 // variable in a data-sharing attribute clause is allowed and overrides 13286 // the variable's predetermined data-sharing attributes. 13287 DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, /*FromParent=*/false); 13288 if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_private) { 13289 Diag(ELoc, diag::err_omp_wrong_dsa) << getOpenMPClauseName(DVar.CKind) 13290 << getOpenMPClauseName(OMPC_private); 13291 reportOriginalDsa(*this, DSAStack, D, DVar); 13292 continue; 13293 } 13294 13295 OpenMPDirectiveKind CurrDir = DSAStack->getCurrentDirective(); 13296 // Variably modified types are not supported for tasks. 13297 if (!Type->isAnyPointerType() && Type->isVariablyModifiedType() && 13298 isOpenMPTaskingDirective(CurrDir)) { 13299 Diag(ELoc, diag::err_omp_variably_modified_type_not_supported) 13300 << getOpenMPClauseName(OMPC_private) << Type 13301 << getOpenMPDirectiveName(CurrDir); 13302 bool IsDecl = 13303 !VD || 13304 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly; 13305 Diag(D->getLocation(), 13306 IsDecl ? diag::note_previous_decl : diag::note_defined_here) 13307 << D; 13308 continue; 13309 } 13310 13311 // OpenMP 4.5 [2.15.5.1, Restrictions, p.3] 13312 // A list item cannot appear in both a map clause and a data-sharing 13313 // attribute clause on the same construct 13314 // 13315 // OpenMP 5.0 [2.19.7.1, Restrictions, p.7] 13316 // A list item cannot appear in both a map clause and a data-sharing 13317 // attribute clause on the same construct unless the construct is a 13318 // combined construct. 13319 if ((LangOpts.OpenMP <= 45 && isOpenMPTargetExecutionDirective(CurrDir)) || 13320 CurrDir == OMPD_target) { 13321 OpenMPClauseKind ConflictKind; 13322 if (DSAStack->checkMappableExprComponentListsForDecl( 13323 VD, /*CurrentRegionOnly=*/true, 13324 [&](OMPClauseMappableExprCommon::MappableExprComponentListRef, 13325 OpenMPClauseKind WhereFoundClauseKind) -> bool { 13326 ConflictKind = WhereFoundClauseKind; 13327 return true; 13328 })) { 13329 Diag(ELoc, diag::err_omp_variable_in_given_clause_and_dsa) 13330 << getOpenMPClauseName(OMPC_private) 13331 << getOpenMPClauseName(ConflictKind) 13332 << getOpenMPDirectiveName(CurrDir); 13333 reportOriginalDsa(*this, DSAStack, D, DVar); 13334 continue; 13335 } 13336 } 13337 13338 // OpenMP [2.9.3.3, Restrictions, C/C++, p.1] 13339 // A variable of class type (or array thereof) that appears in a private 13340 // clause requires an accessible, unambiguous default constructor for the 13341 // class type. 13342 // Generate helper private variable and initialize it with the default 13343 // value. The address of the original variable is replaced by the address of 13344 // the new private variable in CodeGen. This new variable is not added to 13345 // IdResolver, so the code in the OpenMP region uses original variable for 13346 // proper diagnostics. 13347 Type = Type.getUnqualifiedType(); 13348 VarDecl *VDPrivate = 13349 buildVarDecl(*this, ELoc, Type, D->getName(), 13350 D->hasAttrs() ? &D->getAttrs() : nullptr, 13351 VD ? cast<DeclRefExpr>(SimpleRefExpr) : nullptr); 13352 ActOnUninitializedDecl(VDPrivate); 13353 if (VDPrivate->isInvalidDecl()) 13354 continue; 13355 DeclRefExpr *VDPrivateRefExpr = buildDeclRefExpr( 13356 *this, VDPrivate, RefExpr->getType().getUnqualifiedType(), ELoc); 13357 13358 DeclRefExpr *Ref = nullptr; 13359 if (!VD && !CurContext->isDependentContext()) 13360 Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/false); 13361 DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_private, Ref); 13362 Vars.push_back((VD || CurContext->isDependentContext()) 13363 ? RefExpr->IgnoreParens() 13364 : Ref); 13365 PrivateCopies.push_back(VDPrivateRefExpr); 13366 } 13367 13368 if (Vars.empty()) 13369 return nullptr; 13370 13371 return OMPPrivateClause::Create(Context, StartLoc, LParenLoc, EndLoc, Vars, 13372 PrivateCopies); 13373 } 13374 13375 namespace { 13376 class DiagsUninitializedSeveretyRAII { 13377 private: 13378 DiagnosticsEngine &Diags; 13379 SourceLocation SavedLoc; 13380 bool IsIgnored = false; 13381 13382 public: 13383 DiagsUninitializedSeveretyRAII(DiagnosticsEngine &Diags, SourceLocation Loc, 13384 bool IsIgnored) 13385 : Diags(Diags), SavedLoc(Loc), IsIgnored(IsIgnored) { 13386 if (!IsIgnored) { 13387 Diags.setSeverity(/*Diag*/ diag::warn_uninit_self_reference_in_init, 13388 /*Map*/ diag::Severity::Ignored, Loc); 13389 } 13390 } 13391 ~DiagsUninitializedSeveretyRAII() { 13392 if (!IsIgnored) 13393 Diags.popMappings(SavedLoc); 13394 } 13395 }; 13396 } 13397 13398 OMPClause *Sema::ActOnOpenMPFirstprivateClause(ArrayRef<Expr *> VarList, 13399 SourceLocation StartLoc, 13400 SourceLocation LParenLoc, 13401 SourceLocation EndLoc) { 13402 SmallVector<Expr *, 8> Vars; 13403 SmallVector<Expr *, 8> PrivateCopies; 13404 SmallVector<Expr *, 8> Inits; 13405 SmallVector<Decl *, 4> ExprCaptures; 13406 bool IsImplicitClause = 13407 StartLoc.isInvalid() && LParenLoc.isInvalid() && EndLoc.isInvalid(); 13408 SourceLocation ImplicitClauseLoc = DSAStack->getConstructLoc(); 13409 13410 for (Expr *RefExpr : VarList) { 13411 assert(RefExpr && "NULL expr in OpenMP firstprivate clause."); 13412 SourceLocation ELoc; 13413 SourceRange ERange; 13414 Expr *SimpleRefExpr = RefExpr; 13415 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange); 13416 if (Res.second) { 13417 // It will be analyzed later. 13418 Vars.push_back(RefExpr); 13419 PrivateCopies.push_back(nullptr); 13420 Inits.push_back(nullptr); 13421 } 13422 ValueDecl *D = Res.first; 13423 if (!D) 13424 continue; 13425 13426 ELoc = IsImplicitClause ? ImplicitClauseLoc : ELoc; 13427 QualType Type = D->getType(); 13428 auto *VD = dyn_cast<VarDecl>(D); 13429 13430 // OpenMP [2.9.3.3, Restrictions, C/C++, p.3] 13431 // A variable that appears in a private clause must not have an incomplete 13432 // type or a reference type. 13433 if (RequireCompleteType(ELoc, Type, 13434 diag::err_omp_firstprivate_incomplete_type)) 13435 continue; 13436 Type = Type.getNonReferenceType(); 13437 13438 // OpenMP [2.9.3.4, Restrictions, C/C++, p.1] 13439 // A variable of class type (or array thereof) that appears in a private 13440 // clause requires an accessible, unambiguous copy constructor for the 13441 // class type. 13442 QualType ElemType = Context.getBaseElementType(Type).getNonReferenceType(); 13443 13444 // If an implicit firstprivate variable found it was checked already. 13445 DSAStackTy::DSAVarData TopDVar; 13446 if (!IsImplicitClause) { 13447 DSAStackTy::DSAVarData DVar = 13448 DSAStack->getTopDSA(D, /*FromParent=*/false); 13449 TopDVar = DVar; 13450 OpenMPDirectiveKind CurrDir = DSAStack->getCurrentDirective(); 13451 bool IsConstant = ElemType.isConstant(Context); 13452 // OpenMP [2.4.13, Data-sharing Attribute Clauses] 13453 // A list item that specifies a given variable may not appear in more 13454 // than one clause on the same directive, except that a variable may be 13455 // specified in both firstprivate and lastprivate clauses. 13456 // OpenMP 4.5 [2.10.8, Distribute Construct, p.3] 13457 // A list item may appear in a firstprivate or lastprivate clause but not 13458 // both. 13459 if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_firstprivate && 13460 (isOpenMPDistributeDirective(CurrDir) || 13461 DVar.CKind != OMPC_lastprivate) && 13462 DVar.RefExpr) { 13463 Diag(ELoc, diag::err_omp_wrong_dsa) 13464 << getOpenMPClauseName(DVar.CKind) 13465 << getOpenMPClauseName(OMPC_firstprivate); 13466 reportOriginalDsa(*this, DSAStack, D, DVar); 13467 continue; 13468 } 13469 13470 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced 13471 // in a Construct] 13472 // Variables with the predetermined data-sharing attributes may not be 13473 // listed in data-sharing attributes clauses, except for the cases 13474 // listed below. For these exceptions only, listing a predetermined 13475 // variable in a data-sharing attribute clause is allowed and overrides 13476 // the variable's predetermined data-sharing attributes. 13477 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced 13478 // in a Construct, C/C++, p.2] 13479 // Variables with const-qualified type having no mutable member may be 13480 // listed in a firstprivate clause, even if they are static data members. 13481 if (!(IsConstant || (VD && VD->isStaticDataMember())) && !DVar.RefExpr && 13482 DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_shared) { 13483 Diag(ELoc, diag::err_omp_wrong_dsa) 13484 << getOpenMPClauseName(DVar.CKind) 13485 << getOpenMPClauseName(OMPC_firstprivate); 13486 reportOriginalDsa(*this, DSAStack, D, DVar); 13487 continue; 13488 } 13489 13490 // OpenMP [2.9.3.4, Restrictions, p.2] 13491 // A list item that is private within a parallel region must not appear 13492 // in a firstprivate clause on a worksharing construct if any of the 13493 // worksharing regions arising from the worksharing construct ever bind 13494 // to any of the parallel regions arising from the parallel construct. 13495 // OpenMP 4.5 [2.15.3.4, Restrictions, p.3] 13496 // A list item that is private within a teams region must not appear in a 13497 // firstprivate clause on a distribute construct if any of the distribute 13498 // regions arising from the distribute construct ever bind to any of the 13499 // teams regions arising from the teams construct. 13500 // OpenMP 4.5 [2.15.3.4, Restrictions, p.3] 13501 // A list item that appears in a reduction clause of a teams construct 13502 // must not appear in a firstprivate clause on a distribute construct if 13503 // any of the distribute regions arising from the distribute construct 13504 // ever bind to any of the teams regions arising from the teams construct. 13505 if ((isOpenMPWorksharingDirective(CurrDir) || 13506 isOpenMPDistributeDirective(CurrDir)) && 13507 !isOpenMPParallelDirective(CurrDir) && 13508 !isOpenMPTeamsDirective(CurrDir)) { 13509 DVar = DSAStack->getImplicitDSA(D, true); 13510 if (DVar.CKind != OMPC_shared && 13511 (isOpenMPParallelDirective(DVar.DKind) || 13512 isOpenMPTeamsDirective(DVar.DKind) || 13513 DVar.DKind == OMPD_unknown)) { 13514 Diag(ELoc, diag::err_omp_required_access) 13515 << getOpenMPClauseName(OMPC_firstprivate) 13516 << getOpenMPClauseName(OMPC_shared); 13517 reportOriginalDsa(*this, DSAStack, D, DVar); 13518 continue; 13519 } 13520 } 13521 // OpenMP [2.9.3.4, Restrictions, p.3] 13522 // A list item that appears in a reduction clause of a parallel construct 13523 // must not appear in a firstprivate clause on a worksharing or task 13524 // construct if any of the worksharing or task regions arising from the 13525 // worksharing or task construct ever bind to any of the parallel regions 13526 // arising from the parallel construct. 13527 // OpenMP [2.9.3.4, Restrictions, p.4] 13528 // A list item that appears in a reduction clause in worksharing 13529 // construct must not appear in a firstprivate clause in a task construct 13530 // encountered during execution of any of the worksharing regions arising 13531 // from the worksharing construct. 13532 if (isOpenMPTaskingDirective(CurrDir)) { 13533 DVar = DSAStack->hasInnermostDSA( 13534 D, [](OpenMPClauseKind C) { return C == OMPC_reduction; }, 13535 [](OpenMPDirectiveKind K) { 13536 return isOpenMPParallelDirective(K) || 13537 isOpenMPWorksharingDirective(K) || 13538 isOpenMPTeamsDirective(K); 13539 }, 13540 /*FromParent=*/true); 13541 if (DVar.CKind == OMPC_reduction && 13542 (isOpenMPParallelDirective(DVar.DKind) || 13543 isOpenMPWorksharingDirective(DVar.DKind) || 13544 isOpenMPTeamsDirective(DVar.DKind))) { 13545 Diag(ELoc, diag::err_omp_parallel_reduction_in_task_firstprivate) 13546 << getOpenMPDirectiveName(DVar.DKind); 13547 reportOriginalDsa(*this, DSAStack, D, DVar); 13548 continue; 13549 } 13550 } 13551 13552 // OpenMP 4.5 [2.15.5.1, Restrictions, p.3] 13553 // A list item cannot appear in both a map clause and a data-sharing 13554 // attribute clause on the same construct 13555 // 13556 // OpenMP 5.0 [2.19.7.1, Restrictions, p.7] 13557 // A list item cannot appear in both a map clause and a data-sharing 13558 // attribute clause on the same construct unless the construct is a 13559 // combined construct. 13560 if ((LangOpts.OpenMP <= 45 && 13561 isOpenMPTargetExecutionDirective(CurrDir)) || 13562 CurrDir == OMPD_target) { 13563 OpenMPClauseKind ConflictKind; 13564 if (DSAStack->checkMappableExprComponentListsForDecl( 13565 VD, /*CurrentRegionOnly=*/true, 13566 [&ConflictKind]( 13567 OMPClauseMappableExprCommon::MappableExprComponentListRef, 13568 OpenMPClauseKind WhereFoundClauseKind) { 13569 ConflictKind = WhereFoundClauseKind; 13570 return true; 13571 })) { 13572 Diag(ELoc, diag::err_omp_variable_in_given_clause_and_dsa) 13573 << getOpenMPClauseName(OMPC_firstprivate) 13574 << getOpenMPClauseName(ConflictKind) 13575 << getOpenMPDirectiveName(DSAStack->getCurrentDirective()); 13576 reportOriginalDsa(*this, DSAStack, D, DVar); 13577 continue; 13578 } 13579 } 13580 } 13581 13582 // Variably modified types are not supported for tasks. 13583 if (!Type->isAnyPointerType() && Type->isVariablyModifiedType() && 13584 isOpenMPTaskingDirective(DSAStack->getCurrentDirective())) { 13585 Diag(ELoc, diag::err_omp_variably_modified_type_not_supported) 13586 << getOpenMPClauseName(OMPC_firstprivate) << Type 13587 << getOpenMPDirectiveName(DSAStack->getCurrentDirective()); 13588 bool IsDecl = 13589 !VD || 13590 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly; 13591 Diag(D->getLocation(), 13592 IsDecl ? diag::note_previous_decl : diag::note_defined_here) 13593 << D; 13594 continue; 13595 } 13596 13597 Type = Type.getUnqualifiedType(); 13598 VarDecl *VDPrivate = 13599 buildVarDecl(*this, ELoc, Type, D->getName(), 13600 D->hasAttrs() ? &D->getAttrs() : nullptr, 13601 VD ? cast<DeclRefExpr>(SimpleRefExpr) : nullptr); 13602 // Generate helper private variable and initialize it with the value of the 13603 // original variable. The address of the original variable is replaced by 13604 // the address of the new private variable in the CodeGen. This new variable 13605 // is not added to IdResolver, so the code in the OpenMP region uses 13606 // original variable for proper diagnostics and variable capturing. 13607 Expr *VDInitRefExpr = nullptr; 13608 // For arrays generate initializer for single element and replace it by the 13609 // original array element in CodeGen. 13610 if (Type->isArrayType()) { 13611 VarDecl *VDInit = 13612 buildVarDecl(*this, RefExpr->getExprLoc(), ElemType, D->getName()); 13613 VDInitRefExpr = buildDeclRefExpr(*this, VDInit, ElemType, ELoc); 13614 Expr *Init = DefaultLvalueConversion(VDInitRefExpr).get(); 13615 ElemType = ElemType.getUnqualifiedType(); 13616 VarDecl *VDInitTemp = buildVarDecl(*this, RefExpr->getExprLoc(), ElemType, 13617 ".firstprivate.temp"); 13618 InitializedEntity Entity = 13619 InitializedEntity::InitializeVariable(VDInitTemp); 13620 InitializationKind Kind = InitializationKind::CreateCopy(ELoc, ELoc); 13621 13622 InitializationSequence InitSeq(*this, Entity, Kind, Init); 13623 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Init); 13624 if (Result.isInvalid()) 13625 VDPrivate->setInvalidDecl(); 13626 else 13627 VDPrivate->setInit(Result.getAs<Expr>()); 13628 // Remove temp variable declaration. 13629 Context.Deallocate(VDInitTemp); 13630 } else { 13631 VarDecl *VDInit = buildVarDecl(*this, RefExpr->getExprLoc(), Type, 13632 ".firstprivate.temp"); 13633 VDInitRefExpr = buildDeclRefExpr(*this, VDInit, RefExpr->getType(), 13634 RefExpr->getExprLoc()); 13635 AddInitializerToDecl(VDPrivate, 13636 DefaultLvalueConversion(VDInitRefExpr).get(), 13637 /*DirectInit=*/false); 13638 } 13639 if (VDPrivate->isInvalidDecl()) { 13640 if (IsImplicitClause) { 13641 Diag(RefExpr->getExprLoc(), 13642 diag::note_omp_task_predetermined_firstprivate_here); 13643 } 13644 continue; 13645 } 13646 CurContext->addDecl(VDPrivate); 13647 DeclRefExpr *VDPrivateRefExpr = buildDeclRefExpr( 13648 *this, VDPrivate, RefExpr->getType().getUnqualifiedType(), 13649 RefExpr->getExprLoc()); 13650 DeclRefExpr *Ref = nullptr; 13651 if (!VD && !CurContext->isDependentContext()) { 13652 if (TopDVar.CKind == OMPC_lastprivate) { 13653 Ref = TopDVar.PrivateCopy; 13654 } else { 13655 Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/true); 13656 if (!isOpenMPCapturedDecl(D)) 13657 ExprCaptures.push_back(Ref->getDecl()); 13658 } 13659 } 13660 if (!IsImplicitClause) 13661 DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_firstprivate, Ref); 13662 Vars.push_back((VD || CurContext->isDependentContext()) 13663 ? RefExpr->IgnoreParens() 13664 : Ref); 13665 PrivateCopies.push_back(VDPrivateRefExpr); 13666 Inits.push_back(VDInitRefExpr); 13667 } 13668 13669 if (Vars.empty()) 13670 return nullptr; 13671 13672 return OMPFirstprivateClause::Create(Context, StartLoc, LParenLoc, EndLoc, 13673 Vars, PrivateCopies, Inits, 13674 buildPreInits(Context, ExprCaptures)); 13675 } 13676 13677 OMPClause *Sema::ActOnOpenMPLastprivateClause( 13678 ArrayRef<Expr *> VarList, OpenMPLastprivateModifier LPKind, 13679 SourceLocation LPKindLoc, SourceLocation ColonLoc, SourceLocation StartLoc, 13680 SourceLocation LParenLoc, SourceLocation EndLoc) { 13681 if (LPKind == OMPC_LASTPRIVATE_unknown && LPKindLoc.isValid()) { 13682 assert(ColonLoc.isValid() && "Colon location must be valid."); 13683 Diag(LPKindLoc, diag::err_omp_unexpected_clause_value) 13684 << getListOfPossibleValues(OMPC_lastprivate, /*First=*/0, 13685 /*Last=*/OMPC_LASTPRIVATE_unknown) 13686 << getOpenMPClauseName(OMPC_lastprivate); 13687 return nullptr; 13688 } 13689 13690 SmallVector<Expr *, 8> Vars; 13691 SmallVector<Expr *, 8> SrcExprs; 13692 SmallVector<Expr *, 8> DstExprs; 13693 SmallVector<Expr *, 8> AssignmentOps; 13694 SmallVector<Decl *, 4> ExprCaptures; 13695 SmallVector<Expr *, 4> ExprPostUpdates; 13696 for (Expr *RefExpr : VarList) { 13697 assert(RefExpr && "NULL expr in OpenMP lastprivate clause."); 13698 SourceLocation ELoc; 13699 SourceRange ERange; 13700 Expr *SimpleRefExpr = RefExpr; 13701 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange); 13702 if (Res.second) { 13703 // It will be analyzed later. 13704 Vars.push_back(RefExpr); 13705 SrcExprs.push_back(nullptr); 13706 DstExprs.push_back(nullptr); 13707 AssignmentOps.push_back(nullptr); 13708 } 13709 ValueDecl *D = Res.first; 13710 if (!D) 13711 continue; 13712 13713 QualType Type = D->getType(); 13714 auto *VD = dyn_cast<VarDecl>(D); 13715 13716 // OpenMP [2.14.3.5, Restrictions, C/C++, p.2] 13717 // A variable that appears in a lastprivate clause must not have an 13718 // incomplete type or a reference type. 13719 if (RequireCompleteType(ELoc, Type, 13720 diag::err_omp_lastprivate_incomplete_type)) 13721 continue; 13722 Type = Type.getNonReferenceType(); 13723 13724 // OpenMP 5.0 [2.19.3, List Item Privatization, Restrictions] 13725 // A variable that is privatized must not have a const-qualified type 13726 // unless it is of class type with a mutable member. This restriction does 13727 // not apply to the firstprivate clause. 13728 // 13729 // OpenMP 3.1 [2.9.3.5, lastprivate clause, Restrictions] 13730 // A variable that appears in a lastprivate clause must not have a 13731 // const-qualified type unless it is of class type with a mutable member. 13732 if (rejectConstNotMutableType(*this, D, Type, OMPC_lastprivate, ELoc)) 13733 continue; 13734 13735 // OpenMP 5.0 [2.19.4.5 lastprivate Clause, Restrictions] 13736 // A list item that appears in a lastprivate clause with the conditional 13737 // modifier must be a scalar variable. 13738 if (LPKind == OMPC_LASTPRIVATE_conditional && !Type->isScalarType()) { 13739 Diag(ELoc, diag::err_omp_lastprivate_conditional_non_scalar); 13740 bool IsDecl = !VD || VD->isThisDeclarationADefinition(Context) == 13741 VarDecl::DeclarationOnly; 13742 Diag(D->getLocation(), 13743 IsDecl ? diag::note_previous_decl : diag::note_defined_here) 13744 << D; 13745 continue; 13746 } 13747 13748 OpenMPDirectiveKind CurrDir = DSAStack->getCurrentDirective(); 13749 // OpenMP [2.14.1.1, Data-sharing Attribute Rules for Variables Referenced 13750 // in a Construct] 13751 // Variables with the predetermined data-sharing attributes may not be 13752 // listed in data-sharing attributes clauses, except for the cases 13753 // listed below. 13754 // OpenMP 4.5 [2.10.8, Distribute Construct, p.3] 13755 // A list item may appear in a firstprivate or lastprivate clause but not 13756 // both. 13757 DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, /*FromParent=*/false); 13758 if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_lastprivate && 13759 (isOpenMPDistributeDirective(CurrDir) || 13760 DVar.CKind != OMPC_firstprivate) && 13761 (DVar.CKind != OMPC_private || DVar.RefExpr != nullptr)) { 13762 Diag(ELoc, diag::err_omp_wrong_dsa) 13763 << getOpenMPClauseName(DVar.CKind) 13764 << getOpenMPClauseName(OMPC_lastprivate); 13765 reportOriginalDsa(*this, DSAStack, D, DVar); 13766 continue; 13767 } 13768 13769 // OpenMP [2.14.3.5, Restrictions, p.2] 13770 // A list item that is private within a parallel region, or that appears in 13771 // the reduction clause of a parallel construct, must not appear in a 13772 // lastprivate clause on a worksharing construct if any of the corresponding 13773 // worksharing regions ever binds to any of the corresponding parallel 13774 // regions. 13775 DSAStackTy::DSAVarData TopDVar = DVar; 13776 if (isOpenMPWorksharingDirective(CurrDir) && 13777 !isOpenMPParallelDirective(CurrDir) && 13778 !isOpenMPTeamsDirective(CurrDir)) { 13779 DVar = DSAStack->getImplicitDSA(D, true); 13780 if (DVar.CKind != OMPC_shared) { 13781 Diag(ELoc, diag::err_omp_required_access) 13782 << getOpenMPClauseName(OMPC_lastprivate) 13783 << getOpenMPClauseName(OMPC_shared); 13784 reportOriginalDsa(*this, DSAStack, D, DVar); 13785 continue; 13786 } 13787 } 13788 13789 // OpenMP [2.14.3.5, Restrictions, C++, p.1,2] 13790 // A variable of class type (or array thereof) that appears in a 13791 // lastprivate clause requires an accessible, unambiguous default 13792 // constructor for the class type, unless the list item is also specified 13793 // in a firstprivate clause. 13794 // A variable of class type (or array thereof) that appears in a 13795 // lastprivate clause requires an accessible, unambiguous copy assignment 13796 // operator for the class type. 13797 Type = Context.getBaseElementType(Type).getNonReferenceType(); 13798 VarDecl *SrcVD = buildVarDecl(*this, ERange.getBegin(), 13799 Type.getUnqualifiedType(), ".lastprivate.src", 13800 D->hasAttrs() ? &D->getAttrs() : nullptr); 13801 DeclRefExpr *PseudoSrcExpr = 13802 buildDeclRefExpr(*this, SrcVD, Type.getUnqualifiedType(), ELoc); 13803 VarDecl *DstVD = 13804 buildVarDecl(*this, ERange.getBegin(), Type, ".lastprivate.dst", 13805 D->hasAttrs() ? &D->getAttrs() : nullptr); 13806 DeclRefExpr *PseudoDstExpr = buildDeclRefExpr(*this, DstVD, Type, ELoc); 13807 // For arrays generate assignment operation for single element and replace 13808 // it by the original array element in CodeGen. 13809 ExprResult AssignmentOp = BuildBinOp(/*S=*/nullptr, ELoc, BO_Assign, 13810 PseudoDstExpr, PseudoSrcExpr); 13811 if (AssignmentOp.isInvalid()) 13812 continue; 13813 AssignmentOp = 13814 ActOnFinishFullExpr(AssignmentOp.get(), ELoc, /*DiscardedValue*/ false); 13815 if (AssignmentOp.isInvalid()) 13816 continue; 13817 13818 DeclRefExpr *Ref = nullptr; 13819 if (!VD && !CurContext->isDependentContext()) { 13820 if (TopDVar.CKind == OMPC_firstprivate) { 13821 Ref = TopDVar.PrivateCopy; 13822 } else { 13823 Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/false); 13824 if (!isOpenMPCapturedDecl(D)) 13825 ExprCaptures.push_back(Ref->getDecl()); 13826 } 13827 if (TopDVar.CKind == OMPC_firstprivate || 13828 (!isOpenMPCapturedDecl(D) && 13829 Ref->getDecl()->hasAttr<OMPCaptureNoInitAttr>())) { 13830 ExprResult RefRes = DefaultLvalueConversion(Ref); 13831 if (!RefRes.isUsable()) 13832 continue; 13833 ExprResult PostUpdateRes = 13834 BuildBinOp(DSAStack->getCurScope(), ELoc, BO_Assign, SimpleRefExpr, 13835 RefRes.get()); 13836 if (!PostUpdateRes.isUsable()) 13837 continue; 13838 ExprPostUpdates.push_back( 13839 IgnoredValueConversions(PostUpdateRes.get()).get()); 13840 } 13841 } 13842 DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_lastprivate, Ref); 13843 Vars.push_back((VD || CurContext->isDependentContext()) 13844 ? RefExpr->IgnoreParens() 13845 : Ref); 13846 SrcExprs.push_back(PseudoSrcExpr); 13847 DstExprs.push_back(PseudoDstExpr); 13848 AssignmentOps.push_back(AssignmentOp.get()); 13849 } 13850 13851 if (Vars.empty()) 13852 return nullptr; 13853 13854 return OMPLastprivateClause::Create(Context, StartLoc, LParenLoc, EndLoc, 13855 Vars, SrcExprs, DstExprs, AssignmentOps, 13856 LPKind, LPKindLoc, ColonLoc, 13857 buildPreInits(Context, ExprCaptures), 13858 buildPostUpdate(*this, ExprPostUpdates)); 13859 } 13860 13861 OMPClause *Sema::ActOnOpenMPSharedClause(ArrayRef<Expr *> VarList, 13862 SourceLocation StartLoc, 13863 SourceLocation LParenLoc, 13864 SourceLocation EndLoc) { 13865 SmallVector<Expr *, 8> Vars; 13866 for (Expr *RefExpr : VarList) { 13867 assert(RefExpr && "NULL expr in OpenMP lastprivate clause."); 13868 SourceLocation ELoc; 13869 SourceRange ERange; 13870 Expr *SimpleRefExpr = RefExpr; 13871 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange); 13872 if (Res.second) { 13873 // It will be analyzed later. 13874 Vars.push_back(RefExpr); 13875 } 13876 ValueDecl *D = Res.first; 13877 if (!D) 13878 continue; 13879 13880 auto *VD = dyn_cast<VarDecl>(D); 13881 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced 13882 // in a Construct] 13883 // Variables with the predetermined data-sharing attributes may not be 13884 // listed in data-sharing attributes clauses, except for the cases 13885 // listed below. For these exceptions only, listing a predetermined 13886 // variable in a data-sharing attribute clause is allowed and overrides 13887 // the variable's predetermined data-sharing attributes. 13888 DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, /*FromParent=*/false); 13889 if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_shared && 13890 DVar.RefExpr) { 13891 Diag(ELoc, diag::err_omp_wrong_dsa) << getOpenMPClauseName(DVar.CKind) 13892 << getOpenMPClauseName(OMPC_shared); 13893 reportOriginalDsa(*this, DSAStack, D, DVar); 13894 continue; 13895 } 13896 13897 DeclRefExpr *Ref = nullptr; 13898 if (!VD && isOpenMPCapturedDecl(D) && !CurContext->isDependentContext()) 13899 Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/true); 13900 DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_shared, Ref); 13901 Vars.push_back((VD || !Ref || CurContext->isDependentContext()) 13902 ? RefExpr->IgnoreParens() 13903 : Ref); 13904 } 13905 13906 if (Vars.empty()) 13907 return nullptr; 13908 13909 return OMPSharedClause::Create(Context, StartLoc, LParenLoc, EndLoc, Vars); 13910 } 13911 13912 namespace { 13913 class DSARefChecker : public StmtVisitor<DSARefChecker, bool> { 13914 DSAStackTy *Stack; 13915 13916 public: 13917 bool VisitDeclRefExpr(DeclRefExpr *E) { 13918 if (auto *VD = dyn_cast<VarDecl>(E->getDecl())) { 13919 DSAStackTy::DSAVarData DVar = Stack->getTopDSA(VD, /*FromParent=*/false); 13920 if (DVar.CKind == OMPC_shared && !DVar.RefExpr) 13921 return false; 13922 if (DVar.CKind != OMPC_unknown) 13923 return true; 13924 DSAStackTy::DSAVarData DVarPrivate = Stack->hasDSA( 13925 VD, isOpenMPPrivate, [](OpenMPDirectiveKind) { return true; }, 13926 /*FromParent=*/true); 13927 return DVarPrivate.CKind != OMPC_unknown; 13928 } 13929 return false; 13930 } 13931 bool VisitStmt(Stmt *S) { 13932 for (Stmt *Child : S->children()) { 13933 if (Child && Visit(Child)) 13934 return true; 13935 } 13936 return false; 13937 } 13938 explicit DSARefChecker(DSAStackTy *S) : Stack(S) {} 13939 }; 13940 } // namespace 13941 13942 namespace { 13943 // Transform MemberExpression for specified FieldDecl of current class to 13944 // DeclRefExpr to specified OMPCapturedExprDecl. 13945 class TransformExprToCaptures : public TreeTransform<TransformExprToCaptures> { 13946 typedef TreeTransform<TransformExprToCaptures> BaseTransform; 13947 ValueDecl *Field = nullptr; 13948 DeclRefExpr *CapturedExpr = nullptr; 13949 13950 public: 13951 TransformExprToCaptures(Sema &SemaRef, ValueDecl *FieldDecl) 13952 : BaseTransform(SemaRef), Field(FieldDecl), CapturedExpr(nullptr) {} 13953 13954 ExprResult TransformMemberExpr(MemberExpr *E) { 13955 if (isa<CXXThisExpr>(E->getBase()->IgnoreParenImpCasts()) && 13956 E->getMemberDecl() == Field) { 13957 CapturedExpr = buildCapture(SemaRef, Field, E, /*WithInit=*/false); 13958 return CapturedExpr; 13959 } 13960 return BaseTransform::TransformMemberExpr(E); 13961 } 13962 DeclRefExpr *getCapturedExpr() { return CapturedExpr; } 13963 }; 13964 } // namespace 13965 13966 template <typename T, typename U> 13967 static T filterLookupForUDReductionAndMapper( 13968 SmallVectorImpl<U> &Lookups, const llvm::function_ref<T(ValueDecl *)> Gen) { 13969 for (U &Set : Lookups) { 13970 for (auto *D : Set) { 13971 if (T Res = Gen(cast<ValueDecl>(D))) 13972 return Res; 13973 } 13974 } 13975 return T(); 13976 } 13977 13978 static NamedDecl *findAcceptableDecl(Sema &SemaRef, NamedDecl *D) { 13979 assert(!LookupResult::isVisible(SemaRef, D) && "not in slow case"); 13980 13981 for (auto RD : D->redecls()) { 13982 // Don't bother with extra checks if we already know this one isn't visible. 13983 if (RD == D) 13984 continue; 13985 13986 auto ND = cast<NamedDecl>(RD); 13987 if (LookupResult::isVisible(SemaRef, ND)) 13988 return ND; 13989 } 13990 13991 return nullptr; 13992 } 13993 13994 static void 13995 argumentDependentLookup(Sema &SemaRef, const DeclarationNameInfo &Id, 13996 SourceLocation Loc, QualType Ty, 13997 SmallVectorImpl<UnresolvedSet<8>> &Lookups) { 13998 // Find all of the associated namespaces and classes based on the 13999 // arguments we have. 14000 Sema::AssociatedNamespaceSet AssociatedNamespaces; 14001 Sema::AssociatedClassSet AssociatedClasses; 14002 OpaqueValueExpr OVE(Loc, Ty, VK_LValue); 14003 SemaRef.FindAssociatedClassesAndNamespaces(Loc, &OVE, AssociatedNamespaces, 14004 AssociatedClasses); 14005 14006 // C++ [basic.lookup.argdep]p3: 14007 // Let X be the lookup set produced by unqualified lookup (3.4.1) 14008 // and let Y be the lookup set produced by argument dependent 14009 // lookup (defined as follows). If X contains [...] then Y is 14010 // empty. Otherwise Y is the set of declarations found in the 14011 // namespaces associated with the argument types as described 14012 // below. The set of declarations found by the lookup of the name 14013 // is the union of X and Y. 14014 // 14015 // Here, we compute Y and add its members to the overloaded 14016 // candidate set. 14017 for (auto *NS : AssociatedNamespaces) { 14018 // When considering an associated namespace, the lookup is the 14019 // same as the lookup performed when the associated namespace is 14020 // used as a qualifier (3.4.3.2) except that: 14021 // 14022 // -- Any using-directives in the associated namespace are 14023 // ignored. 14024 // 14025 // -- Any namespace-scope friend functions declared in 14026 // associated classes are visible within their respective 14027 // namespaces even if they are not visible during an ordinary 14028 // lookup (11.4). 14029 DeclContext::lookup_result R = NS->lookup(Id.getName()); 14030 for (auto *D : R) { 14031 auto *Underlying = D; 14032 if (auto *USD = dyn_cast<UsingShadowDecl>(D)) 14033 Underlying = USD->getTargetDecl(); 14034 14035 if (!isa<OMPDeclareReductionDecl>(Underlying) && 14036 !isa<OMPDeclareMapperDecl>(Underlying)) 14037 continue; 14038 14039 if (!SemaRef.isVisible(D)) { 14040 D = findAcceptableDecl(SemaRef, D); 14041 if (!D) 14042 continue; 14043 if (auto *USD = dyn_cast<UsingShadowDecl>(D)) 14044 Underlying = USD->getTargetDecl(); 14045 } 14046 Lookups.emplace_back(); 14047 Lookups.back().addDecl(Underlying); 14048 } 14049 } 14050 } 14051 14052 static ExprResult 14053 buildDeclareReductionRef(Sema &SemaRef, SourceLocation Loc, SourceRange Range, 14054 Scope *S, CXXScopeSpec &ReductionIdScopeSpec, 14055 const DeclarationNameInfo &ReductionId, QualType Ty, 14056 CXXCastPath &BasePath, Expr *UnresolvedReduction) { 14057 if (ReductionIdScopeSpec.isInvalid()) 14058 return ExprError(); 14059 SmallVector<UnresolvedSet<8>, 4> Lookups; 14060 if (S) { 14061 LookupResult Lookup(SemaRef, ReductionId, Sema::LookupOMPReductionName); 14062 Lookup.suppressDiagnostics(); 14063 while (S && SemaRef.LookupParsedName(Lookup, S, &ReductionIdScopeSpec)) { 14064 NamedDecl *D = Lookup.getRepresentativeDecl(); 14065 do { 14066 S = S->getParent(); 14067 } while (S && !S->isDeclScope(D)); 14068 if (S) 14069 S = S->getParent(); 14070 Lookups.emplace_back(); 14071 Lookups.back().append(Lookup.begin(), Lookup.end()); 14072 Lookup.clear(); 14073 } 14074 } else if (auto *ULE = 14075 cast_or_null<UnresolvedLookupExpr>(UnresolvedReduction)) { 14076 Lookups.push_back(UnresolvedSet<8>()); 14077 Decl *PrevD = nullptr; 14078 for (NamedDecl *D : ULE->decls()) { 14079 if (D == PrevD) 14080 Lookups.push_back(UnresolvedSet<8>()); 14081 else if (auto *DRD = dyn_cast<OMPDeclareReductionDecl>(D)) 14082 Lookups.back().addDecl(DRD); 14083 PrevD = D; 14084 } 14085 } 14086 if (SemaRef.CurContext->isDependentContext() || Ty->isDependentType() || 14087 Ty->isInstantiationDependentType() || 14088 Ty->containsUnexpandedParameterPack() || 14089 filterLookupForUDReductionAndMapper<bool>(Lookups, [](ValueDecl *D) { 14090 return !D->isInvalidDecl() && 14091 (D->getType()->isDependentType() || 14092 D->getType()->isInstantiationDependentType() || 14093 D->getType()->containsUnexpandedParameterPack()); 14094 })) { 14095 UnresolvedSet<8> ResSet; 14096 for (const UnresolvedSet<8> &Set : Lookups) { 14097 if (Set.empty()) 14098 continue; 14099 ResSet.append(Set.begin(), Set.end()); 14100 // The last item marks the end of all declarations at the specified scope. 14101 ResSet.addDecl(Set[Set.size() - 1]); 14102 } 14103 return UnresolvedLookupExpr::Create( 14104 SemaRef.Context, /*NamingClass=*/nullptr, 14105 ReductionIdScopeSpec.getWithLocInContext(SemaRef.Context), ReductionId, 14106 /*ADL=*/true, /*Overloaded=*/true, ResSet.begin(), ResSet.end()); 14107 } 14108 // Lookup inside the classes. 14109 // C++ [over.match.oper]p3: 14110 // For a unary operator @ with an operand of a type whose 14111 // cv-unqualified version is T1, and for a binary operator @ with 14112 // a left operand of a type whose cv-unqualified version is T1 and 14113 // a right operand of a type whose cv-unqualified version is T2, 14114 // three sets of candidate functions, designated member 14115 // candidates, non-member candidates and built-in candidates, are 14116 // constructed as follows: 14117 // -- If T1 is a complete class type or a class currently being 14118 // defined, the set of member candidates is the result of the 14119 // qualified lookup of T1::operator@ (13.3.1.1.1); otherwise, 14120 // the set of member candidates is empty. 14121 LookupResult Lookup(SemaRef, ReductionId, Sema::LookupOMPReductionName); 14122 Lookup.suppressDiagnostics(); 14123 if (const auto *TyRec = Ty->getAs<RecordType>()) { 14124 // Complete the type if it can be completed. 14125 // If the type is neither complete nor being defined, bail out now. 14126 if (SemaRef.isCompleteType(Loc, Ty) || TyRec->isBeingDefined() || 14127 TyRec->getDecl()->getDefinition()) { 14128 Lookup.clear(); 14129 SemaRef.LookupQualifiedName(Lookup, TyRec->getDecl()); 14130 if (Lookup.empty()) { 14131 Lookups.emplace_back(); 14132 Lookups.back().append(Lookup.begin(), Lookup.end()); 14133 } 14134 } 14135 } 14136 // Perform ADL. 14137 if (SemaRef.getLangOpts().CPlusPlus) 14138 argumentDependentLookup(SemaRef, ReductionId, Loc, Ty, Lookups); 14139 if (auto *VD = filterLookupForUDReductionAndMapper<ValueDecl *>( 14140 Lookups, [&SemaRef, Ty](ValueDecl *D) -> ValueDecl * { 14141 if (!D->isInvalidDecl() && 14142 SemaRef.Context.hasSameType(D->getType(), Ty)) 14143 return D; 14144 return nullptr; 14145 })) 14146 return SemaRef.BuildDeclRefExpr(VD, VD->getType().getNonReferenceType(), 14147 VK_LValue, Loc); 14148 if (SemaRef.getLangOpts().CPlusPlus) { 14149 if (auto *VD = filterLookupForUDReductionAndMapper<ValueDecl *>( 14150 Lookups, [&SemaRef, Ty, Loc](ValueDecl *D) -> ValueDecl * { 14151 if (!D->isInvalidDecl() && 14152 SemaRef.IsDerivedFrom(Loc, Ty, D->getType()) && 14153 !Ty.isMoreQualifiedThan(D->getType())) 14154 return D; 14155 return nullptr; 14156 })) { 14157 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true, 14158 /*DetectVirtual=*/false); 14159 if (SemaRef.IsDerivedFrom(Loc, Ty, VD->getType(), Paths)) { 14160 if (!Paths.isAmbiguous(SemaRef.Context.getCanonicalType( 14161 VD->getType().getUnqualifiedType()))) { 14162 if (SemaRef.CheckBaseClassAccess( 14163 Loc, VD->getType(), Ty, Paths.front(), 14164 /*DiagID=*/0) != Sema::AR_inaccessible) { 14165 SemaRef.BuildBasePathArray(Paths, BasePath); 14166 return SemaRef.BuildDeclRefExpr( 14167 VD, VD->getType().getNonReferenceType(), VK_LValue, Loc); 14168 } 14169 } 14170 } 14171 } 14172 } 14173 if (ReductionIdScopeSpec.isSet()) { 14174 SemaRef.Diag(Loc, diag::err_omp_not_resolved_reduction_identifier) 14175 << Ty << Range; 14176 return ExprError(); 14177 } 14178 return ExprEmpty(); 14179 } 14180 14181 namespace { 14182 /// Data for the reduction-based clauses. 14183 struct ReductionData { 14184 /// List of original reduction items. 14185 SmallVector<Expr *, 8> Vars; 14186 /// List of private copies of the reduction items. 14187 SmallVector<Expr *, 8> Privates; 14188 /// LHS expressions for the reduction_op expressions. 14189 SmallVector<Expr *, 8> LHSs; 14190 /// RHS expressions for the reduction_op expressions. 14191 SmallVector<Expr *, 8> RHSs; 14192 /// Reduction operation expression. 14193 SmallVector<Expr *, 8> ReductionOps; 14194 /// Taskgroup descriptors for the corresponding reduction items in 14195 /// in_reduction clauses. 14196 SmallVector<Expr *, 8> TaskgroupDescriptors; 14197 /// List of captures for clause. 14198 SmallVector<Decl *, 4> ExprCaptures; 14199 /// List of postupdate expressions. 14200 SmallVector<Expr *, 4> ExprPostUpdates; 14201 /// Reduction modifier. 14202 unsigned RedModifier = 0; 14203 ReductionData() = delete; 14204 /// Reserves required memory for the reduction data. 14205 ReductionData(unsigned Size, unsigned Modifier = 0) : RedModifier(Modifier) { 14206 Vars.reserve(Size); 14207 Privates.reserve(Size); 14208 LHSs.reserve(Size); 14209 RHSs.reserve(Size); 14210 ReductionOps.reserve(Size); 14211 TaskgroupDescriptors.reserve(Size); 14212 ExprCaptures.reserve(Size); 14213 ExprPostUpdates.reserve(Size); 14214 } 14215 /// Stores reduction item and reduction operation only (required for dependent 14216 /// reduction item). 14217 void push(Expr *Item, Expr *ReductionOp) { 14218 Vars.emplace_back(Item); 14219 Privates.emplace_back(nullptr); 14220 LHSs.emplace_back(nullptr); 14221 RHSs.emplace_back(nullptr); 14222 ReductionOps.emplace_back(ReductionOp); 14223 TaskgroupDescriptors.emplace_back(nullptr); 14224 } 14225 /// Stores reduction data. 14226 void push(Expr *Item, Expr *Private, Expr *LHS, Expr *RHS, Expr *ReductionOp, 14227 Expr *TaskgroupDescriptor) { 14228 Vars.emplace_back(Item); 14229 Privates.emplace_back(Private); 14230 LHSs.emplace_back(LHS); 14231 RHSs.emplace_back(RHS); 14232 ReductionOps.emplace_back(ReductionOp); 14233 TaskgroupDescriptors.emplace_back(TaskgroupDescriptor); 14234 } 14235 }; 14236 } // namespace 14237 14238 static bool checkOMPArraySectionConstantForReduction( 14239 ASTContext &Context, const OMPArraySectionExpr *OASE, bool &SingleElement, 14240 SmallVectorImpl<llvm::APSInt> &ArraySizes) { 14241 const Expr *Length = OASE->getLength(); 14242 if (Length == nullptr) { 14243 // For array sections of the form [1:] or [:], we would need to analyze 14244 // the lower bound... 14245 if (OASE->getColonLoc().isValid()) 14246 return false; 14247 14248 // This is an array subscript which has implicit length 1! 14249 SingleElement = true; 14250 ArraySizes.push_back(llvm::APSInt::get(1)); 14251 } else { 14252 Expr::EvalResult Result; 14253 if (!Length->EvaluateAsInt(Result, Context)) 14254 return false; 14255 14256 llvm::APSInt ConstantLengthValue = Result.Val.getInt(); 14257 SingleElement = (ConstantLengthValue.getSExtValue() == 1); 14258 ArraySizes.push_back(ConstantLengthValue); 14259 } 14260 14261 // Get the base of this array section and walk up from there. 14262 const Expr *Base = OASE->getBase()->IgnoreParenImpCasts(); 14263 14264 // We require length = 1 for all array sections except the right-most to 14265 // guarantee that the memory region is contiguous and has no holes in it. 14266 while (const auto *TempOASE = dyn_cast<OMPArraySectionExpr>(Base)) { 14267 Length = TempOASE->getLength(); 14268 if (Length == nullptr) { 14269 // For array sections of the form [1:] or [:], we would need to analyze 14270 // the lower bound... 14271 if (OASE->getColonLoc().isValid()) 14272 return false; 14273 14274 // This is an array subscript which has implicit length 1! 14275 ArraySizes.push_back(llvm::APSInt::get(1)); 14276 } else { 14277 Expr::EvalResult Result; 14278 if (!Length->EvaluateAsInt(Result, Context)) 14279 return false; 14280 14281 llvm::APSInt ConstantLengthValue = Result.Val.getInt(); 14282 if (ConstantLengthValue.getSExtValue() != 1) 14283 return false; 14284 14285 ArraySizes.push_back(ConstantLengthValue); 14286 } 14287 Base = TempOASE->getBase()->IgnoreParenImpCasts(); 14288 } 14289 14290 // If we have a single element, we don't need to add the implicit lengths. 14291 if (!SingleElement) { 14292 while (const auto *TempASE = dyn_cast<ArraySubscriptExpr>(Base)) { 14293 // Has implicit length 1! 14294 ArraySizes.push_back(llvm::APSInt::get(1)); 14295 Base = TempASE->getBase()->IgnoreParenImpCasts(); 14296 } 14297 } 14298 14299 // This array section can be privatized as a single value or as a constant 14300 // sized array. 14301 return true; 14302 } 14303 14304 static bool actOnOMPReductionKindClause( 14305 Sema &S, DSAStackTy *Stack, OpenMPClauseKind ClauseKind, 14306 ArrayRef<Expr *> VarList, SourceLocation StartLoc, SourceLocation LParenLoc, 14307 SourceLocation ColonLoc, SourceLocation EndLoc, 14308 CXXScopeSpec &ReductionIdScopeSpec, const DeclarationNameInfo &ReductionId, 14309 ArrayRef<Expr *> UnresolvedReductions, ReductionData &RD) { 14310 DeclarationName DN = ReductionId.getName(); 14311 OverloadedOperatorKind OOK = DN.getCXXOverloadedOperator(); 14312 BinaryOperatorKind BOK = BO_Comma; 14313 14314 ASTContext &Context = S.Context; 14315 // OpenMP [2.14.3.6, reduction clause] 14316 // C 14317 // reduction-identifier is either an identifier or one of the following 14318 // operators: +, -, *, &, |, ^, && and || 14319 // C++ 14320 // reduction-identifier is either an id-expression or one of the following 14321 // operators: +, -, *, &, |, ^, && and || 14322 switch (OOK) { 14323 case OO_Plus: 14324 case OO_Minus: 14325 BOK = BO_Add; 14326 break; 14327 case OO_Star: 14328 BOK = BO_Mul; 14329 break; 14330 case OO_Amp: 14331 BOK = BO_And; 14332 break; 14333 case OO_Pipe: 14334 BOK = BO_Or; 14335 break; 14336 case OO_Caret: 14337 BOK = BO_Xor; 14338 break; 14339 case OO_AmpAmp: 14340 BOK = BO_LAnd; 14341 break; 14342 case OO_PipePipe: 14343 BOK = BO_LOr; 14344 break; 14345 case OO_New: 14346 case OO_Delete: 14347 case OO_Array_New: 14348 case OO_Array_Delete: 14349 case OO_Slash: 14350 case OO_Percent: 14351 case OO_Tilde: 14352 case OO_Exclaim: 14353 case OO_Equal: 14354 case OO_Less: 14355 case OO_Greater: 14356 case OO_LessEqual: 14357 case OO_GreaterEqual: 14358 case OO_PlusEqual: 14359 case OO_MinusEqual: 14360 case OO_StarEqual: 14361 case OO_SlashEqual: 14362 case OO_PercentEqual: 14363 case OO_CaretEqual: 14364 case OO_AmpEqual: 14365 case OO_PipeEqual: 14366 case OO_LessLess: 14367 case OO_GreaterGreater: 14368 case OO_LessLessEqual: 14369 case OO_GreaterGreaterEqual: 14370 case OO_EqualEqual: 14371 case OO_ExclaimEqual: 14372 case OO_Spaceship: 14373 case OO_PlusPlus: 14374 case OO_MinusMinus: 14375 case OO_Comma: 14376 case OO_ArrowStar: 14377 case OO_Arrow: 14378 case OO_Call: 14379 case OO_Subscript: 14380 case OO_Conditional: 14381 case OO_Coawait: 14382 case NUM_OVERLOADED_OPERATORS: 14383 llvm_unreachable("Unexpected reduction identifier"); 14384 case OO_None: 14385 if (IdentifierInfo *II = DN.getAsIdentifierInfo()) { 14386 if (II->isStr("max")) 14387 BOK = BO_GT; 14388 else if (II->isStr("min")) 14389 BOK = BO_LT; 14390 } 14391 break; 14392 } 14393 SourceRange ReductionIdRange; 14394 if (ReductionIdScopeSpec.isValid()) 14395 ReductionIdRange.setBegin(ReductionIdScopeSpec.getBeginLoc()); 14396 else 14397 ReductionIdRange.setBegin(ReductionId.getBeginLoc()); 14398 ReductionIdRange.setEnd(ReductionId.getEndLoc()); 14399 14400 auto IR = UnresolvedReductions.begin(), ER = UnresolvedReductions.end(); 14401 bool FirstIter = true; 14402 for (Expr *RefExpr : VarList) { 14403 assert(RefExpr && "nullptr expr in OpenMP reduction clause."); 14404 // OpenMP [2.1, C/C++] 14405 // A list item is a variable or array section, subject to the restrictions 14406 // specified in Section 2.4 on page 42 and in each of the sections 14407 // describing clauses and directives for which a list appears. 14408 // OpenMP [2.14.3.3, Restrictions, p.1] 14409 // A variable that is part of another variable (as an array or 14410 // structure element) cannot appear in a private clause. 14411 if (!FirstIter && IR != ER) 14412 ++IR; 14413 FirstIter = false; 14414 SourceLocation ELoc; 14415 SourceRange ERange; 14416 Expr *SimpleRefExpr = RefExpr; 14417 auto Res = getPrivateItem(S, SimpleRefExpr, ELoc, ERange, 14418 /*AllowArraySection=*/true); 14419 if (Res.second) { 14420 // Try to find 'declare reduction' corresponding construct before using 14421 // builtin/overloaded operators. 14422 QualType Type = Context.DependentTy; 14423 CXXCastPath BasePath; 14424 ExprResult DeclareReductionRef = buildDeclareReductionRef( 14425 S, ELoc, ERange, Stack->getCurScope(), ReductionIdScopeSpec, 14426 ReductionId, Type, BasePath, IR == ER ? nullptr : *IR); 14427 Expr *ReductionOp = nullptr; 14428 if (S.CurContext->isDependentContext() && 14429 (DeclareReductionRef.isUnset() || 14430 isa<UnresolvedLookupExpr>(DeclareReductionRef.get()))) 14431 ReductionOp = DeclareReductionRef.get(); 14432 // It will be analyzed later. 14433 RD.push(RefExpr, ReductionOp); 14434 } 14435 ValueDecl *D = Res.first; 14436 if (!D) 14437 continue; 14438 14439 Expr *TaskgroupDescriptor = nullptr; 14440 QualType Type; 14441 auto *ASE = dyn_cast<ArraySubscriptExpr>(RefExpr->IgnoreParens()); 14442 auto *OASE = dyn_cast<OMPArraySectionExpr>(RefExpr->IgnoreParens()); 14443 if (ASE) { 14444 Type = ASE->getType().getNonReferenceType(); 14445 } else if (OASE) { 14446 QualType BaseType = 14447 OMPArraySectionExpr::getBaseOriginalType(OASE->getBase()); 14448 if (const auto *ATy = BaseType->getAsArrayTypeUnsafe()) 14449 Type = ATy->getElementType(); 14450 else 14451 Type = BaseType->getPointeeType(); 14452 Type = Type.getNonReferenceType(); 14453 } else { 14454 Type = Context.getBaseElementType(D->getType().getNonReferenceType()); 14455 } 14456 auto *VD = dyn_cast<VarDecl>(D); 14457 14458 // OpenMP [2.9.3.3, Restrictions, C/C++, p.3] 14459 // A variable that appears in a private clause must not have an incomplete 14460 // type or a reference type. 14461 if (S.RequireCompleteType(ELoc, D->getType(), 14462 diag::err_omp_reduction_incomplete_type)) 14463 continue; 14464 // OpenMP [2.14.3.6, reduction clause, Restrictions] 14465 // A list item that appears in a reduction clause must not be 14466 // const-qualified. 14467 if (rejectConstNotMutableType(S, D, Type, ClauseKind, ELoc, 14468 /*AcceptIfMutable*/ false, ASE || OASE)) 14469 continue; 14470 14471 OpenMPDirectiveKind CurrDir = Stack->getCurrentDirective(); 14472 // OpenMP [2.9.3.6, Restrictions, C/C++, p.4] 14473 // If a list-item is a reference type then it must bind to the same object 14474 // for all threads of the team. 14475 if (!ASE && !OASE) { 14476 if (VD) { 14477 VarDecl *VDDef = VD->getDefinition(); 14478 if (VD->getType()->isReferenceType() && VDDef && VDDef->hasInit()) { 14479 DSARefChecker Check(Stack); 14480 if (Check.Visit(VDDef->getInit())) { 14481 S.Diag(ELoc, diag::err_omp_reduction_ref_type_arg) 14482 << getOpenMPClauseName(ClauseKind) << ERange; 14483 S.Diag(VDDef->getLocation(), diag::note_defined_here) << VDDef; 14484 continue; 14485 } 14486 } 14487 } 14488 14489 // OpenMP [2.14.1.1, Data-sharing Attribute Rules for Variables Referenced 14490 // in a Construct] 14491 // Variables with the predetermined data-sharing attributes may not be 14492 // listed in data-sharing attributes clauses, except for the cases 14493 // listed below. For these exceptions only, listing a predetermined 14494 // variable in a data-sharing attribute clause is allowed and overrides 14495 // the variable's predetermined data-sharing attributes. 14496 // OpenMP [2.14.3.6, Restrictions, p.3] 14497 // Any number of reduction clauses can be specified on the directive, 14498 // but a list item can appear only once in the reduction clauses for that 14499 // directive. 14500 DSAStackTy::DSAVarData DVar = Stack->getTopDSA(D, /*FromParent=*/false); 14501 if (DVar.CKind == OMPC_reduction) { 14502 S.Diag(ELoc, diag::err_omp_once_referenced) 14503 << getOpenMPClauseName(ClauseKind); 14504 if (DVar.RefExpr) 14505 S.Diag(DVar.RefExpr->getExprLoc(), diag::note_omp_referenced); 14506 continue; 14507 } 14508 if (DVar.CKind != OMPC_unknown) { 14509 S.Diag(ELoc, diag::err_omp_wrong_dsa) 14510 << getOpenMPClauseName(DVar.CKind) 14511 << getOpenMPClauseName(OMPC_reduction); 14512 reportOriginalDsa(S, Stack, D, DVar); 14513 continue; 14514 } 14515 14516 // OpenMP [2.14.3.6, Restrictions, p.1] 14517 // A list item that appears in a reduction clause of a worksharing 14518 // construct must be shared in the parallel regions to which any of the 14519 // worksharing regions arising from the worksharing construct bind. 14520 if (isOpenMPWorksharingDirective(CurrDir) && 14521 !isOpenMPParallelDirective(CurrDir) && 14522 !isOpenMPTeamsDirective(CurrDir)) { 14523 DVar = Stack->getImplicitDSA(D, true); 14524 if (DVar.CKind != OMPC_shared) { 14525 S.Diag(ELoc, diag::err_omp_required_access) 14526 << getOpenMPClauseName(OMPC_reduction) 14527 << getOpenMPClauseName(OMPC_shared); 14528 reportOriginalDsa(S, Stack, D, DVar); 14529 continue; 14530 } 14531 } 14532 } 14533 14534 // Try to find 'declare reduction' corresponding construct before using 14535 // builtin/overloaded operators. 14536 CXXCastPath BasePath; 14537 ExprResult DeclareReductionRef = buildDeclareReductionRef( 14538 S, ELoc, ERange, Stack->getCurScope(), ReductionIdScopeSpec, 14539 ReductionId, Type, BasePath, IR == ER ? nullptr : *IR); 14540 if (DeclareReductionRef.isInvalid()) 14541 continue; 14542 if (S.CurContext->isDependentContext() && 14543 (DeclareReductionRef.isUnset() || 14544 isa<UnresolvedLookupExpr>(DeclareReductionRef.get()))) { 14545 RD.push(RefExpr, DeclareReductionRef.get()); 14546 continue; 14547 } 14548 if (BOK == BO_Comma && DeclareReductionRef.isUnset()) { 14549 // Not allowed reduction identifier is found. 14550 S.Diag(ReductionId.getBeginLoc(), 14551 diag::err_omp_unknown_reduction_identifier) 14552 << Type << ReductionIdRange; 14553 continue; 14554 } 14555 14556 // OpenMP [2.14.3.6, reduction clause, Restrictions] 14557 // The type of a list item that appears in a reduction clause must be valid 14558 // for the reduction-identifier. For a max or min reduction in C, the type 14559 // of the list item must be an allowed arithmetic data type: char, int, 14560 // float, double, or _Bool, possibly modified with long, short, signed, or 14561 // unsigned. For a max or min reduction in C++, the type of the list item 14562 // must be an allowed arithmetic data type: char, wchar_t, int, float, 14563 // double, or bool, possibly modified with long, short, signed, or unsigned. 14564 if (DeclareReductionRef.isUnset()) { 14565 if ((BOK == BO_GT || BOK == BO_LT) && 14566 !(Type->isScalarType() || 14567 (S.getLangOpts().CPlusPlus && Type->isArithmeticType()))) { 14568 S.Diag(ELoc, diag::err_omp_clause_not_arithmetic_type_arg) 14569 << getOpenMPClauseName(ClauseKind) << S.getLangOpts().CPlusPlus; 14570 if (!ASE && !OASE) { 14571 bool IsDecl = !VD || VD->isThisDeclarationADefinition(Context) == 14572 VarDecl::DeclarationOnly; 14573 S.Diag(D->getLocation(), 14574 IsDecl ? diag::note_previous_decl : diag::note_defined_here) 14575 << D; 14576 } 14577 continue; 14578 } 14579 if ((BOK == BO_OrAssign || BOK == BO_AndAssign || BOK == BO_XorAssign) && 14580 !S.getLangOpts().CPlusPlus && Type->isFloatingType()) { 14581 S.Diag(ELoc, diag::err_omp_clause_floating_type_arg) 14582 << getOpenMPClauseName(ClauseKind); 14583 if (!ASE && !OASE) { 14584 bool IsDecl = !VD || VD->isThisDeclarationADefinition(Context) == 14585 VarDecl::DeclarationOnly; 14586 S.Diag(D->getLocation(), 14587 IsDecl ? diag::note_previous_decl : diag::note_defined_here) 14588 << D; 14589 } 14590 continue; 14591 } 14592 } 14593 14594 Type = Type.getNonLValueExprType(Context).getUnqualifiedType(); 14595 VarDecl *LHSVD = buildVarDecl(S, ELoc, Type, ".reduction.lhs", 14596 D->hasAttrs() ? &D->getAttrs() : nullptr); 14597 VarDecl *RHSVD = buildVarDecl(S, ELoc, Type, D->getName(), 14598 D->hasAttrs() ? &D->getAttrs() : nullptr); 14599 QualType PrivateTy = Type; 14600 14601 // Try if we can determine constant lengths for all array sections and avoid 14602 // the VLA. 14603 bool ConstantLengthOASE = false; 14604 if (OASE) { 14605 bool SingleElement; 14606 llvm::SmallVector<llvm::APSInt, 4> ArraySizes; 14607 ConstantLengthOASE = checkOMPArraySectionConstantForReduction( 14608 Context, OASE, SingleElement, ArraySizes); 14609 14610 // If we don't have a single element, we must emit a constant array type. 14611 if (ConstantLengthOASE && !SingleElement) { 14612 for (llvm::APSInt &Size : ArraySizes) 14613 PrivateTy = Context.getConstantArrayType(PrivateTy, Size, nullptr, 14614 ArrayType::Normal, 14615 /*IndexTypeQuals=*/0); 14616 } 14617 } 14618 14619 if ((OASE && !ConstantLengthOASE) || 14620 (!OASE && !ASE && 14621 D->getType().getNonReferenceType()->isVariablyModifiedType())) { 14622 if (!Context.getTargetInfo().isVLASupported()) { 14623 if (isOpenMPTargetExecutionDirective(Stack->getCurrentDirective())) { 14624 S.Diag(ELoc, diag::err_omp_reduction_vla_unsupported) << !!OASE; 14625 S.Diag(ELoc, diag::note_vla_unsupported); 14626 } else { 14627 S.targetDiag(ELoc, diag::err_omp_reduction_vla_unsupported) << !!OASE; 14628 S.targetDiag(ELoc, diag::note_vla_unsupported); 14629 } 14630 continue; 14631 } 14632 // For arrays/array sections only: 14633 // Create pseudo array type for private copy. The size for this array will 14634 // be generated during codegen. 14635 // For array subscripts or single variables Private Ty is the same as Type 14636 // (type of the variable or single array element). 14637 PrivateTy = Context.getVariableArrayType( 14638 Type, 14639 new (Context) OpaqueValueExpr(ELoc, Context.getSizeType(), VK_RValue), 14640 ArrayType::Normal, /*IndexTypeQuals=*/0, SourceRange()); 14641 } else if (!ASE && !OASE && 14642 Context.getAsArrayType(D->getType().getNonReferenceType())) { 14643 PrivateTy = D->getType().getNonReferenceType(); 14644 } 14645 // Private copy. 14646 VarDecl *PrivateVD = 14647 buildVarDecl(S, ELoc, PrivateTy, D->getName(), 14648 D->hasAttrs() ? &D->getAttrs() : nullptr, 14649 VD ? cast<DeclRefExpr>(SimpleRefExpr) : nullptr); 14650 // Add initializer for private variable. 14651 Expr *Init = nullptr; 14652 DeclRefExpr *LHSDRE = buildDeclRefExpr(S, LHSVD, Type, ELoc); 14653 DeclRefExpr *RHSDRE = buildDeclRefExpr(S, RHSVD, Type, ELoc); 14654 if (DeclareReductionRef.isUsable()) { 14655 auto *DRDRef = DeclareReductionRef.getAs<DeclRefExpr>(); 14656 auto *DRD = cast<OMPDeclareReductionDecl>(DRDRef->getDecl()); 14657 if (DRD->getInitializer()) { 14658 Init = DRDRef; 14659 RHSVD->setInit(DRDRef); 14660 RHSVD->setInitStyle(VarDecl::CallInit); 14661 } 14662 } else { 14663 switch (BOK) { 14664 case BO_Add: 14665 case BO_Xor: 14666 case BO_Or: 14667 case BO_LOr: 14668 // '+', '-', '^', '|', '||' reduction ops - initializer is '0'. 14669 if (Type->isScalarType() || Type->isAnyComplexType()) 14670 Init = S.ActOnIntegerConstant(ELoc, /*Val=*/0).get(); 14671 break; 14672 case BO_Mul: 14673 case BO_LAnd: 14674 if (Type->isScalarType() || Type->isAnyComplexType()) { 14675 // '*' and '&&' reduction ops - initializer is '1'. 14676 Init = S.ActOnIntegerConstant(ELoc, /*Val=*/1).get(); 14677 } 14678 break; 14679 case BO_And: { 14680 // '&' reduction op - initializer is '~0'. 14681 QualType OrigType = Type; 14682 if (auto *ComplexTy = OrigType->getAs<ComplexType>()) 14683 Type = ComplexTy->getElementType(); 14684 if (Type->isRealFloatingType()) { 14685 llvm::APFloat InitValue = 14686 llvm::APFloat::getAllOnesValue(Context.getTypeSize(Type), 14687 /*isIEEE=*/true); 14688 Init = FloatingLiteral::Create(Context, InitValue, /*isexact=*/true, 14689 Type, ELoc); 14690 } else if (Type->isScalarType()) { 14691 uint64_t Size = Context.getTypeSize(Type); 14692 QualType IntTy = Context.getIntTypeForBitwidth(Size, /*Signed=*/0); 14693 llvm::APInt InitValue = llvm::APInt::getAllOnesValue(Size); 14694 Init = IntegerLiteral::Create(Context, InitValue, IntTy, ELoc); 14695 } 14696 if (Init && OrigType->isAnyComplexType()) { 14697 // Init = 0xFFFF + 0xFFFFi; 14698 auto *Im = new (Context) ImaginaryLiteral(Init, OrigType); 14699 Init = S.CreateBuiltinBinOp(ELoc, BO_Add, Init, Im).get(); 14700 } 14701 Type = OrigType; 14702 break; 14703 } 14704 case BO_LT: 14705 case BO_GT: { 14706 // 'min' reduction op - initializer is 'Largest representable number in 14707 // the reduction list item type'. 14708 // 'max' reduction op - initializer is 'Least representable number in 14709 // the reduction list item type'. 14710 if (Type->isIntegerType() || Type->isPointerType()) { 14711 bool IsSigned = Type->hasSignedIntegerRepresentation(); 14712 uint64_t Size = Context.getTypeSize(Type); 14713 QualType IntTy = 14714 Context.getIntTypeForBitwidth(Size, /*Signed=*/IsSigned); 14715 llvm::APInt InitValue = 14716 (BOK != BO_LT) ? IsSigned ? llvm::APInt::getSignedMinValue(Size) 14717 : llvm::APInt::getMinValue(Size) 14718 : IsSigned ? llvm::APInt::getSignedMaxValue(Size) 14719 : llvm::APInt::getMaxValue(Size); 14720 Init = IntegerLiteral::Create(Context, InitValue, IntTy, ELoc); 14721 if (Type->isPointerType()) { 14722 // Cast to pointer type. 14723 ExprResult CastExpr = S.BuildCStyleCastExpr( 14724 ELoc, Context.getTrivialTypeSourceInfo(Type, ELoc), ELoc, Init); 14725 if (CastExpr.isInvalid()) 14726 continue; 14727 Init = CastExpr.get(); 14728 } 14729 } else if (Type->isRealFloatingType()) { 14730 llvm::APFloat InitValue = llvm::APFloat::getLargest( 14731 Context.getFloatTypeSemantics(Type), BOK != BO_LT); 14732 Init = FloatingLiteral::Create(Context, InitValue, /*isexact=*/true, 14733 Type, ELoc); 14734 } 14735 break; 14736 } 14737 case BO_PtrMemD: 14738 case BO_PtrMemI: 14739 case BO_MulAssign: 14740 case BO_Div: 14741 case BO_Rem: 14742 case BO_Sub: 14743 case BO_Shl: 14744 case BO_Shr: 14745 case BO_LE: 14746 case BO_GE: 14747 case BO_EQ: 14748 case BO_NE: 14749 case BO_Cmp: 14750 case BO_AndAssign: 14751 case BO_XorAssign: 14752 case BO_OrAssign: 14753 case BO_Assign: 14754 case BO_AddAssign: 14755 case BO_SubAssign: 14756 case BO_DivAssign: 14757 case BO_RemAssign: 14758 case BO_ShlAssign: 14759 case BO_ShrAssign: 14760 case BO_Comma: 14761 llvm_unreachable("Unexpected reduction operation"); 14762 } 14763 } 14764 if (Init && DeclareReductionRef.isUnset()) 14765 S.AddInitializerToDecl(RHSVD, Init, /*DirectInit=*/false); 14766 else if (!Init) 14767 S.ActOnUninitializedDecl(RHSVD); 14768 if (RHSVD->isInvalidDecl()) 14769 continue; 14770 if (!RHSVD->hasInit() && 14771 (DeclareReductionRef.isUnset() || !S.LangOpts.CPlusPlus)) { 14772 S.Diag(ELoc, diag::err_omp_reduction_id_not_compatible) 14773 << Type << ReductionIdRange; 14774 bool IsDecl = !VD || VD->isThisDeclarationADefinition(Context) == 14775 VarDecl::DeclarationOnly; 14776 S.Diag(D->getLocation(), 14777 IsDecl ? diag::note_previous_decl : diag::note_defined_here) 14778 << D; 14779 continue; 14780 } 14781 // Store initializer for single element in private copy. Will be used during 14782 // codegen. 14783 PrivateVD->setInit(RHSVD->getInit()); 14784 PrivateVD->setInitStyle(RHSVD->getInitStyle()); 14785 DeclRefExpr *PrivateDRE = buildDeclRefExpr(S, PrivateVD, PrivateTy, ELoc); 14786 ExprResult ReductionOp; 14787 if (DeclareReductionRef.isUsable()) { 14788 QualType RedTy = DeclareReductionRef.get()->getType(); 14789 QualType PtrRedTy = Context.getPointerType(RedTy); 14790 ExprResult LHS = S.CreateBuiltinUnaryOp(ELoc, UO_AddrOf, LHSDRE); 14791 ExprResult RHS = S.CreateBuiltinUnaryOp(ELoc, UO_AddrOf, RHSDRE); 14792 if (!BasePath.empty()) { 14793 LHS = S.DefaultLvalueConversion(LHS.get()); 14794 RHS = S.DefaultLvalueConversion(RHS.get()); 14795 LHS = ImplicitCastExpr::Create(Context, PtrRedTy, 14796 CK_UncheckedDerivedToBase, LHS.get(), 14797 &BasePath, LHS.get()->getValueKind()); 14798 RHS = ImplicitCastExpr::Create(Context, PtrRedTy, 14799 CK_UncheckedDerivedToBase, RHS.get(), 14800 &BasePath, RHS.get()->getValueKind()); 14801 } 14802 FunctionProtoType::ExtProtoInfo EPI; 14803 QualType Params[] = {PtrRedTy, PtrRedTy}; 14804 QualType FnTy = Context.getFunctionType(Context.VoidTy, Params, EPI); 14805 auto *OVE = new (Context) OpaqueValueExpr( 14806 ELoc, Context.getPointerType(FnTy), VK_RValue, OK_Ordinary, 14807 S.DefaultLvalueConversion(DeclareReductionRef.get()).get()); 14808 Expr *Args[] = {LHS.get(), RHS.get()}; 14809 ReductionOp = 14810 CallExpr::Create(Context, OVE, Args, Context.VoidTy, VK_RValue, ELoc); 14811 } else { 14812 ReductionOp = S.BuildBinOp( 14813 Stack->getCurScope(), ReductionId.getBeginLoc(), BOK, LHSDRE, RHSDRE); 14814 if (ReductionOp.isUsable()) { 14815 if (BOK != BO_LT && BOK != BO_GT) { 14816 ReductionOp = 14817 S.BuildBinOp(Stack->getCurScope(), ReductionId.getBeginLoc(), 14818 BO_Assign, LHSDRE, ReductionOp.get()); 14819 } else { 14820 auto *ConditionalOp = new (Context) 14821 ConditionalOperator(ReductionOp.get(), ELoc, LHSDRE, ELoc, RHSDRE, 14822 Type, VK_LValue, OK_Ordinary); 14823 ReductionOp = 14824 S.BuildBinOp(Stack->getCurScope(), ReductionId.getBeginLoc(), 14825 BO_Assign, LHSDRE, ConditionalOp); 14826 } 14827 if (ReductionOp.isUsable()) 14828 ReductionOp = S.ActOnFinishFullExpr(ReductionOp.get(), 14829 /*DiscardedValue*/ false); 14830 } 14831 if (!ReductionOp.isUsable()) 14832 continue; 14833 } 14834 14835 // OpenMP [2.15.4.6, Restrictions, p.2] 14836 // A list item that appears in an in_reduction clause of a task construct 14837 // must appear in a task_reduction clause of a construct associated with a 14838 // taskgroup region that includes the participating task in its taskgroup 14839 // set. The construct associated with the innermost region that meets this 14840 // condition must specify the same reduction-identifier as the in_reduction 14841 // clause. 14842 if (ClauseKind == OMPC_in_reduction) { 14843 SourceRange ParentSR; 14844 BinaryOperatorKind ParentBOK; 14845 const Expr *ParentReductionOp = nullptr; 14846 Expr *ParentBOKTD = nullptr, *ParentReductionOpTD = nullptr; 14847 DSAStackTy::DSAVarData ParentBOKDSA = 14848 Stack->getTopMostTaskgroupReductionData(D, ParentSR, ParentBOK, 14849 ParentBOKTD); 14850 DSAStackTy::DSAVarData ParentReductionOpDSA = 14851 Stack->getTopMostTaskgroupReductionData( 14852 D, ParentSR, ParentReductionOp, ParentReductionOpTD); 14853 bool IsParentBOK = ParentBOKDSA.DKind != OMPD_unknown; 14854 bool IsParentReductionOp = ParentReductionOpDSA.DKind != OMPD_unknown; 14855 if ((DeclareReductionRef.isUnset() && IsParentReductionOp) || 14856 (DeclareReductionRef.isUsable() && IsParentBOK) || 14857 (IsParentBOK && BOK != ParentBOK) || IsParentReductionOp) { 14858 bool EmitError = true; 14859 if (IsParentReductionOp && DeclareReductionRef.isUsable()) { 14860 llvm::FoldingSetNodeID RedId, ParentRedId; 14861 ParentReductionOp->Profile(ParentRedId, Context, /*Canonical=*/true); 14862 DeclareReductionRef.get()->Profile(RedId, Context, 14863 /*Canonical=*/true); 14864 EmitError = RedId != ParentRedId; 14865 } 14866 if (EmitError) { 14867 S.Diag(ReductionId.getBeginLoc(), 14868 diag::err_omp_reduction_identifier_mismatch) 14869 << ReductionIdRange << RefExpr->getSourceRange(); 14870 S.Diag(ParentSR.getBegin(), 14871 diag::note_omp_previous_reduction_identifier) 14872 << ParentSR 14873 << (IsParentBOK ? ParentBOKDSA.RefExpr 14874 : ParentReductionOpDSA.RefExpr) 14875 ->getSourceRange(); 14876 continue; 14877 } 14878 } 14879 TaskgroupDescriptor = IsParentBOK ? ParentBOKTD : ParentReductionOpTD; 14880 } 14881 14882 DeclRefExpr *Ref = nullptr; 14883 Expr *VarsExpr = RefExpr->IgnoreParens(); 14884 if (!VD && !S.CurContext->isDependentContext()) { 14885 if (ASE || OASE) { 14886 TransformExprToCaptures RebuildToCapture(S, D); 14887 VarsExpr = 14888 RebuildToCapture.TransformExpr(RefExpr->IgnoreParens()).get(); 14889 Ref = RebuildToCapture.getCapturedExpr(); 14890 } else { 14891 VarsExpr = Ref = buildCapture(S, D, SimpleRefExpr, /*WithInit=*/false); 14892 } 14893 if (!S.isOpenMPCapturedDecl(D)) { 14894 RD.ExprCaptures.emplace_back(Ref->getDecl()); 14895 if (Ref->getDecl()->hasAttr<OMPCaptureNoInitAttr>()) { 14896 ExprResult RefRes = S.DefaultLvalueConversion(Ref); 14897 if (!RefRes.isUsable()) 14898 continue; 14899 ExprResult PostUpdateRes = 14900 S.BuildBinOp(Stack->getCurScope(), ELoc, BO_Assign, SimpleRefExpr, 14901 RefRes.get()); 14902 if (!PostUpdateRes.isUsable()) 14903 continue; 14904 if (isOpenMPTaskingDirective(Stack->getCurrentDirective()) || 14905 Stack->getCurrentDirective() == OMPD_taskgroup) { 14906 S.Diag(RefExpr->getExprLoc(), 14907 diag::err_omp_reduction_non_addressable_expression) 14908 << RefExpr->getSourceRange(); 14909 continue; 14910 } 14911 RD.ExprPostUpdates.emplace_back( 14912 S.IgnoredValueConversions(PostUpdateRes.get()).get()); 14913 } 14914 } 14915 } 14916 // All reduction items are still marked as reduction (to do not increase 14917 // code base size). 14918 Stack->addDSA(D, RefExpr->IgnoreParens(), OMPC_reduction, Ref, 14919 RD.RedModifier); 14920 if (CurrDir == OMPD_taskgroup) { 14921 if (DeclareReductionRef.isUsable()) 14922 Stack->addTaskgroupReductionData(D, ReductionIdRange, 14923 DeclareReductionRef.get()); 14924 else 14925 Stack->addTaskgroupReductionData(D, ReductionIdRange, BOK); 14926 } 14927 RD.push(VarsExpr, PrivateDRE, LHSDRE, RHSDRE, ReductionOp.get(), 14928 TaskgroupDescriptor); 14929 } 14930 return RD.Vars.empty(); 14931 } 14932 14933 OMPClause *Sema::ActOnOpenMPReductionClause( 14934 ArrayRef<Expr *> VarList, OpenMPReductionClauseModifier Modifier, 14935 SourceLocation StartLoc, SourceLocation LParenLoc, 14936 SourceLocation ModifierLoc, SourceLocation ColonLoc, SourceLocation EndLoc, 14937 CXXScopeSpec &ReductionIdScopeSpec, const DeclarationNameInfo &ReductionId, 14938 ArrayRef<Expr *> UnresolvedReductions) { 14939 if (ModifierLoc.isValid() && Modifier == OMPC_REDUCTION_unknown) { 14940 Diag(LParenLoc, diag::err_omp_unexpected_clause_value) 14941 << getListOfPossibleValues(OMPC_reduction, /*First=*/0, 14942 /*Last=*/OMPC_REDUCTION_unknown) 14943 << getOpenMPClauseName(OMPC_reduction); 14944 return nullptr; 14945 } 14946 // OpenMP 5.0, 2.19.5.4 reduction Clause, Restrictions 14947 // A reduction clause with the inscan reduction-modifier may only appear on a 14948 // worksharing-loop construct, a worksharing-loop SIMD construct, a simd 14949 // construct, a parallel worksharing-loop construct or a parallel 14950 // worksharing-loop SIMD construct. 14951 if (Modifier == OMPC_REDUCTION_inscan && 14952 (DSAStack->getCurrentDirective() != OMPD_for && 14953 DSAStack->getCurrentDirective() != OMPD_for_simd && 14954 DSAStack->getCurrentDirective() != OMPD_simd && 14955 DSAStack->getCurrentDirective() != OMPD_parallel_for && 14956 DSAStack->getCurrentDirective() != OMPD_parallel_for_simd)) { 14957 Diag(ModifierLoc, diag::err_omp_wrong_inscan_reduction); 14958 return nullptr; 14959 } 14960 14961 ReductionData RD(VarList.size(), Modifier); 14962 if (actOnOMPReductionKindClause(*this, DSAStack, OMPC_reduction, VarList, 14963 StartLoc, LParenLoc, ColonLoc, EndLoc, 14964 ReductionIdScopeSpec, ReductionId, 14965 UnresolvedReductions, RD)) 14966 return nullptr; 14967 14968 return OMPReductionClause::Create( 14969 Context, StartLoc, LParenLoc, ModifierLoc, ColonLoc, EndLoc, Modifier, 14970 RD.Vars, ReductionIdScopeSpec.getWithLocInContext(Context), ReductionId, 14971 RD.Privates, RD.LHSs, RD.RHSs, RD.ReductionOps, 14972 buildPreInits(Context, RD.ExprCaptures), 14973 buildPostUpdate(*this, RD.ExprPostUpdates)); 14974 } 14975 14976 OMPClause *Sema::ActOnOpenMPTaskReductionClause( 14977 ArrayRef<Expr *> VarList, SourceLocation StartLoc, SourceLocation LParenLoc, 14978 SourceLocation ColonLoc, SourceLocation EndLoc, 14979 CXXScopeSpec &ReductionIdScopeSpec, const DeclarationNameInfo &ReductionId, 14980 ArrayRef<Expr *> UnresolvedReductions) { 14981 ReductionData RD(VarList.size()); 14982 if (actOnOMPReductionKindClause(*this, DSAStack, OMPC_task_reduction, VarList, 14983 StartLoc, LParenLoc, ColonLoc, EndLoc, 14984 ReductionIdScopeSpec, ReductionId, 14985 UnresolvedReductions, RD)) 14986 return nullptr; 14987 14988 return OMPTaskReductionClause::Create( 14989 Context, StartLoc, LParenLoc, ColonLoc, EndLoc, RD.Vars, 14990 ReductionIdScopeSpec.getWithLocInContext(Context), ReductionId, 14991 RD.Privates, RD.LHSs, RD.RHSs, RD.ReductionOps, 14992 buildPreInits(Context, RD.ExprCaptures), 14993 buildPostUpdate(*this, RD.ExprPostUpdates)); 14994 } 14995 14996 OMPClause *Sema::ActOnOpenMPInReductionClause( 14997 ArrayRef<Expr *> VarList, SourceLocation StartLoc, SourceLocation LParenLoc, 14998 SourceLocation ColonLoc, SourceLocation EndLoc, 14999 CXXScopeSpec &ReductionIdScopeSpec, const DeclarationNameInfo &ReductionId, 15000 ArrayRef<Expr *> UnresolvedReductions) { 15001 ReductionData RD(VarList.size()); 15002 if (actOnOMPReductionKindClause(*this, DSAStack, OMPC_in_reduction, VarList, 15003 StartLoc, LParenLoc, ColonLoc, EndLoc, 15004 ReductionIdScopeSpec, ReductionId, 15005 UnresolvedReductions, RD)) 15006 return nullptr; 15007 15008 return OMPInReductionClause::Create( 15009 Context, StartLoc, LParenLoc, ColonLoc, EndLoc, RD.Vars, 15010 ReductionIdScopeSpec.getWithLocInContext(Context), ReductionId, 15011 RD.Privates, RD.LHSs, RD.RHSs, RD.ReductionOps, RD.TaskgroupDescriptors, 15012 buildPreInits(Context, RD.ExprCaptures), 15013 buildPostUpdate(*this, RD.ExprPostUpdates)); 15014 } 15015 15016 bool Sema::CheckOpenMPLinearModifier(OpenMPLinearClauseKind LinKind, 15017 SourceLocation LinLoc) { 15018 if ((!LangOpts.CPlusPlus && LinKind != OMPC_LINEAR_val) || 15019 LinKind == OMPC_LINEAR_unknown) { 15020 Diag(LinLoc, diag::err_omp_wrong_linear_modifier) << LangOpts.CPlusPlus; 15021 return true; 15022 } 15023 return false; 15024 } 15025 15026 bool Sema::CheckOpenMPLinearDecl(const ValueDecl *D, SourceLocation ELoc, 15027 OpenMPLinearClauseKind LinKind, QualType Type, 15028 bool IsDeclareSimd) { 15029 const auto *VD = dyn_cast_or_null<VarDecl>(D); 15030 // A variable must not have an incomplete type or a reference type. 15031 if (RequireCompleteType(ELoc, Type, diag::err_omp_linear_incomplete_type)) 15032 return true; 15033 if ((LinKind == OMPC_LINEAR_uval || LinKind == OMPC_LINEAR_ref) && 15034 !Type->isReferenceType()) { 15035 Diag(ELoc, diag::err_omp_wrong_linear_modifier_non_reference) 15036 << Type << getOpenMPSimpleClauseTypeName(OMPC_linear, LinKind); 15037 return true; 15038 } 15039 Type = Type.getNonReferenceType(); 15040 15041 // OpenMP 5.0 [2.19.3, List Item Privatization, Restrictions] 15042 // A variable that is privatized must not have a const-qualified type 15043 // unless it is of class type with a mutable member. This restriction does 15044 // not apply to the firstprivate clause, nor to the linear clause on 15045 // declarative directives (like declare simd). 15046 if (!IsDeclareSimd && 15047 rejectConstNotMutableType(*this, D, Type, OMPC_linear, ELoc)) 15048 return true; 15049 15050 // A list item must be of integral or pointer type. 15051 Type = Type.getUnqualifiedType().getCanonicalType(); 15052 const auto *Ty = Type.getTypePtrOrNull(); 15053 if (!Ty || (LinKind != OMPC_LINEAR_ref && !Ty->isDependentType() && 15054 !Ty->isIntegralType(Context) && !Ty->isPointerType())) { 15055 Diag(ELoc, diag::err_omp_linear_expected_int_or_ptr) << Type; 15056 if (D) { 15057 bool IsDecl = 15058 !VD || 15059 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly; 15060 Diag(D->getLocation(), 15061 IsDecl ? diag::note_previous_decl : diag::note_defined_here) 15062 << D; 15063 } 15064 return true; 15065 } 15066 return false; 15067 } 15068 15069 OMPClause *Sema::ActOnOpenMPLinearClause( 15070 ArrayRef<Expr *> VarList, Expr *Step, SourceLocation StartLoc, 15071 SourceLocation LParenLoc, OpenMPLinearClauseKind LinKind, 15072 SourceLocation LinLoc, SourceLocation ColonLoc, SourceLocation EndLoc) { 15073 SmallVector<Expr *, 8> Vars; 15074 SmallVector<Expr *, 8> Privates; 15075 SmallVector<Expr *, 8> Inits; 15076 SmallVector<Decl *, 4> ExprCaptures; 15077 SmallVector<Expr *, 4> ExprPostUpdates; 15078 if (CheckOpenMPLinearModifier(LinKind, LinLoc)) 15079 LinKind = OMPC_LINEAR_val; 15080 for (Expr *RefExpr : VarList) { 15081 assert(RefExpr && "NULL expr in OpenMP linear clause."); 15082 SourceLocation ELoc; 15083 SourceRange ERange; 15084 Expr *SimpleRefExpr = RefExpr; 15085 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange); 15086 if (Res.second) { 15087 // It will be analyzed later. 15088 Vars.push_back(RefExpr); 15089 Privates.push_back(nullptr); 15090 Inits.push_back(nullptr); 15091 } 15092 ValueDecl *D = Res.first; 15093 if (!D) 15094 continue; 15095 15096 QualType Type = D->getType(); 15097 auto *VD = dyn_cast<VarDecl>(D); 15098 15099 // OpenMP [2.14.3.7, linear clause] 15100 // A list-item cannot appear in more than one linear clause. 15101 // A list-item that appears in a linear clause cannot appear in any 15102 // other data-sharing attribute clause. 15103 DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, /*FromParent=*/false); 15104 if (DVar.RefExpr) { 15105 Diag(ELoc, diag::err_omp_wrong_dsa) << getOpenMPClauseName(DVar.CKind) 15106 << getOpenMPClauseName(OMPC_linear); 15107 reportOriginalDsa(*this, DSAStack, D, DVar); 15108 continue; 15109 } 15110 15111 if (CheckOpenMPLinearDecl(D, ELoc, LinKind, Type)) 15112 continue; 15113 Type = Type.getNonReferenceType().getUnqualifiedType().getCanonicalType(); 15114 15115 // Build private copy of original var. 15116 VarDecl *Private = 15117 buildVarDecl(*this, ELoc, Type, D->getName(), 15118 D->hasAttrs() ? &D->getAttrs() : nullptr, 15119 VD ? cast<DeclRefExpr>(SimpleRefExpr) : nullptr); 15120 DeclRefExpr *PrivateRef = buildDeclRefExpr(*this, Private, Type, ELoc); 15121 // Build var to save initial value. 15122 VarDecl *Init = buildVarDecl(*this, ELoc, Type, ".linear.start"); 15123 Expr *InitExpr; 15124 DeclRefExpr *Ref = nullptr; 15125 if (!VD && !CurContext->isDependentContext()) { 15126 Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/false); 15127 if (!isOpenMPCapturedDecl(D)) { 15128 ExprCaptures.push_back(Ref->getDecl()); 15129 if (Ref->getDecl()->hasAttr<OMPCaptureNoInitAttr>()) { 15130 ExprResult RefRes = DefaultLvalueConversion(Ref); 15131 if (!RefRes.isUsable()) 15132 continue; 15133 ExprResult PostUpdateRes = 15134 BuildBinOp(DSAStack->getCurScope(), ELoc, BO_Assign, 15135 SimpleRefExpr, RefRes.get()); 15136 if (!PostUpdateRes.isUsable()) 15137 continue; 15138 ExprPostUpdates.push_back( 15139 IgnoredValueConversions(PostUpdateRes.get()).get()); 15140 } 15141 } 15142 } 15143 if (LinKind == OMPC_LINEAR_uval) 15144 InitExpr = VD ? VD->getInit() : SimpleRefExpr; 15145 else 15146 InitExpr = VD ? SimpleRefExpr : Ref; 15147 AddInitializerToDecl(Init, DefaultLvalueConversion(InitExpr).get(), 15148 /*DirectInit=*/false); 15149 DeclRefExpr *InitRef = buildDeclRefExpr(*this, Init, Type, ELoc); 15150 15151 DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_linear, Ref); 15152 Vars.push_back((VD || CurContext->isDependentContext()) 15153 ? RefExpr->IgnoreParens() 15154 : Ref); 15155 Privates.push_back(PrivateRef); 15156 Inits.push_back(InitRef); 15157 } 15158 15159 if (Vars.empty()) 15160 return nullptr; 15161 15162 Expr *StepExpr = Step; 15163 Expr *CalcStepExpr = nullptr; 15164 if (Step && !Step->isValueDependent() && !Step->isTypeDependent() && 15165 !Step->isInstantiationDependent() && 15166 !Step->containsUnexpandedParameterPack()) { 15167 SourceLocation StepLoc = Step->getBeginLoc(); 15168 ExprResult Val = PerformOpenMPImplicitIntegerConversion(StepLoc, Step); 15169 if (Val.isInvalid()) 15170 return nullptr; 15171 StepExpr = Val.get(); 15172 15173 // Build var to save the step value. 15174 VarDecl *SaveVar = 15175 buildVarDecl(*this, StepLoc, StepExpr->getType(), ".linear.step"); 15176 ExprResult SaveRef = 15177 buildDeclRefExpr(*this, SaveVar, StepExpr->getType(), StepLoc); 15178 ExprResult CalcStep = 15179 BuildBinOp(CurScope, StepLoc, BO_Assign, SaveRef.get(), StepExpr); 15180 CalcStep = ActOnFinishFullExpr(CalcStep.get(), /*DiscardedValue*/ false); 15181 15182 // Warn about zero linear step (it would be probably better specified as 15183 // making corresponding variables 'const'). 15184 llvm::APSInt Result; 15185 bool IsConstant = StepExpr->isIntegerConstantExpr(Result, Context); 15186 if (IsConstant && !Result.isNegative() && !Result.isStrictlyPositive()) 15187 Diag(StepLoc, diag::warn_omp_linear_step_zero) << Vars[0] 15188 << (Vars.size() > 1); 15189 if (!IsConstant && CalcStep.isUsable()) { 15190 // Calculate the step beforehand instead of doing this on each iteration. 15191 // (This is not used if the number of iterations may be kfold-ed). 15192 CalcStepExpr = CalcStep.get(); 15193 } 15194 } 15195 15196 return OMPLinearClause::Create(Context, StartLoc, LParenLoc, LinKind, LinLoc, 15197 ColonLoc, EndLoc, Vars, Privates, Inits, 15198 StepExpr, CalcStepExpr, 15199 buildPreInits(Context, ExprCaptures), 15200 buildPostUpdate(*this, ExprPostUpdates)); 15201 } 15202 15203 static bool FinishOpenMPLinearClause(OMPLinearClause &Clause, DeclRefExpr *IV, 15204 Expr *NumIterations, Sema &SemaRef, 15205 Scope *S, DSAStackTy *Stack) { 15206 // Walk the vars and build update/final expressions for the CodeGen. 15207 SmallVector<Expr *, 8> Updates; 15208 SmallVector<Expr *, 8> Finals; 15209 SmallVector<Expr *, 8> UsedExprs; 15210 Expr *Step = Clause.getStep(); 15211 Expr *CalcStep = Clause.getCalcStep(); 15212 // OpenMP [2.14.3.7, linear clause] 15213 // If linear-step is not specified it is assumed to be 1. 15214 if (!Step) 15215 Step = SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get(); 15216 else if (CalcStep) 15217 Step = cast<BinaryOperator>(CalcStep)->getLHS(); 15218 bool HasErrors = false; 15219 auto CurInit = Clause.inits().begin(); 15220 auto CurPrivate = Clause.privates().begin(); 15221 OpenMPLinearClauseKind LinKind = Clause.getModifier(); 15222 for (Expr *RefExpr : Clause.varlists()) { 15223 SourceLocation ELoc; 15224 SourceRange ERange; 15225 Expr *SimpleRefExpr = RefExpr; 15226 auto Res = getPrivateItem(SemaRef, SimpleRefExpr, ELoc, ERange); 15227 ValueDecl *D = Res.first; 15228 if (Res.second || !D) { 15229 Updates.push_back(nullptr); 15230 Finals.push_back(nullptr); 15231 HasErrors = true; 15232 continue; 15233 } 15234 auto &&Info = Stack->isLoopControlVariable(D); 15235 // OpenMP [2.15.11, distribute simd Construct] 15236 // A list item may not appear in a linear clause, unless it is the loop 15237 // iteration variable. 15238 if (isOpenMPDistributeDirective(Stack->getCurrentDirective()) && 15239 isOpenMPSimdDirective(Stack->getCurrentDirective()) && !Info.first) { 15240 SemaRef.Diag(ELoc, 15241 diag::err_omp_linear_distribute_var_non_loop_iteration); 15242 Updates.push_back(nullptr); 15243 Finals.push_back(nullptr); 15244 HasErrors = true; 15245 continue; 15246 } 15247 Expr *InitExpr = *CurInit; 15248 15249 // Build privatized reference to the current linear var. 15250 auto *DE = cast<DeclRefExpr>(SimpleRefExpr); 15251 Expr *CapturedRef; 15252 if (LinKind == OMPC_LINEAR_uval) 15253 CapturedRef = cast<VarDecl>(DE->getDecl())->getInit(); 15254 else 15255 CapturedRef = 15256 buildDeclRefExpr(SemaRef, cast<VarDecl>(DE->getDecl()), 15257 DE->getType().getUnqualifiedType(), DE->getExprLoc(), 15258 /*RefersToCapture=*/true); 15259 15260 // Build update: Var = InitExpr + IV * Step 15261 ExprResult Update; 15262 if (!Info.first) 15263 Update = buildCounterUpdate( 15264 SemaRef, S, RefExpr->getExprLoc(), *CurPrivate, InitExpr, IV, Step, 15265 /*Subtract=*/false, /*IsNonRectangularLB=*/false); 15266 else 15267 Update = *CurPrivate; 15268 Update = SemaRef.ActOnFinishFullExpr(Update.get(), DE->getBeginLoc(), 15269 /*DiscardedValue*/ false); 15270 15271 // Build final: Var = InitExpr + NumIterations * Step 15272 ExprResult Final; 15273 if (!Info.first) 15274 Final = 15275 buildCounterUpdate(SemaRef, S, RefExpr->getExprLoc(), CapturedRef, 15276 InitExpr, NumIterations, Step, /*Subtract=*/false, 15277 /*IsNonRectangularLB=*/false); 15278 else 15279 Final = *CurPrivate; 15280 Final = SemaRef.ActOnFinishFullExpr(Final.get(), DE->getBeginLoc(), 15281 /*DiscardedValue*/ false); 15282 15283 if (!Update.isUsable() || !Final.isUsable()) { 15284 Updates.push_back(nullptr); 15285 Finals.push_back(nullptr); 15286 UsedExprs.push_back(nullptr); 15287 HasErrors = true; 15288 } else { 15289 Updates.push_back(Update.get()); 15290 Finals.push_back(Final.get()); 15291 if (!Info.first) 15292 UsedExprs.push_back(SimpleRefExpr); 15293 } 15294 ++CurInit; 15295 ++CurPrivate; 15296 } 15297 if (Expr *S = Clause.getStep()) 15298 UsedExprs.push_back(S); 15299 // Fill the remaining part with the nullptr. 15300 UsedExprs.append(Clause.varlist_size() + 1 - UsedExprs.size(), nullptr); 15301 Clause.setUpdates(Updates); 15302 Clause.setFinals(Finals); 15303 Clause.setUsedExprs(UsedExprs); 15304 return HasErrors; 15305 } 15306 15307 OMPClause *Sema::ActOnOpenMPAlignedClause( 15308 ArrayRef<Expr *> VarList, Expr *Alignment, SourceLocation StartLoc, 15309 SourceLocation LParenLoc, SourceLocation ColonLoc, SourceLocation EndLoc) { 15310 SmallVector<Expr *, 8> Vars; 15311 for (Expr *RefExpr : VarList) { 15312 assert(RefExpr && "NULL expr in OpenMP linear clause."); 15313 SourceLocation ELoc; 15314 SourceRange ERange; 15315 Expr *SimpleRefExpr = RefExpr; 15316 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange); 15317 if (Res.second) { 15318 // It will be analyzed later. 15319 Vars.push_back(RefExpr); 15320 } 15321 ValueDecl *D = Res.first; 15322 if (!D) 15323 continue; 15324 15325 QualType QType = D->getType(); 15326 auto *VD = dyn_cast<VarDecl>(D); 15327 15328 // OpenMP [2.8.1, simd construct, Restrictions] 15329 // The type of list items appearing in the aligned clause must be 15330 // array, pointer, reference to array, or reference to pointer. 15331 QType = QType.getNonReferenceType().getUnqualifiedType().getCanonicalType(); 15332 const Type *Ty = QType.getTypePtrOrNull(); 15333 if (!Ty || (!Ty->isArrayType() && !Ty->isPointerType())) { 15334 Diag(ELoc, diag::err_omp_aligned_expected_array_or_ptr) 15335 << QType << getLangOpts().CPlusPlus << ERange; 15336 bool IsDecl = 15337 !VD || 15338 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly; 15339 Diag(D->getLocation(), 15340 IsDecl ? diag::note_previous_decl : diag::note_defined_here) 15341 << D; 15342 continue; 15343 } 15344 15345 // OpenMP [2.8.1, simd construct, Restrictions] 15346 // A list-item cannot appear in more than one aligned clause. 15347 if (const Expr *PrevRef = DSAStack->addUniqueAligned(D, SimpleRefExpr)) { 15348 Diag(ELoc, diag::err_omp_used_in_clause_twice) 15349 << 0 << getOpenMPClauseName(OMPC_aligned) << ERange; 15350 Diag(PrevRef->getExprLoc(), diag::note_omp_explicit_dsa) 15351 << getOpenMPClauseName(OMPC_aligned); 15352 continue; 15353 } 15354 15355 DeclRefExpr *Ref = nullptr; 15356 if (!VD && isOpenMPCapturedDecl(D)) 15357 Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/true); 15358 Vars.push_back(DefaultFunctionArrayConversion( 15359 (VD || !Ref) ? RefExpr->IgnoreParens() : Ref) 15360 .get()); 15361 } 15362 15363 // OpenMP [2.8.1, simd construct, Description] 15364 // The parameter of the aligned clause, alignment, must be a constant 15365 // positive integer expression. 15366 // If no optional parameter is specified, implementation-defined default 15367 // alignments for SIMD instructions on the target platforms are assumed. 15368 if (Alignment != nullptr) { 15369 ExprResult AlignResult = 15370 VerifyPositiveIntegerConstantInClause(Alignment, OMPC_aligned); 15371 if (AlignResult.isInvalid()) 15372 return nullptr; 15373 Alignment = AlignResult.get(); 15374 } 15375 if (Vars.empty()) 15376 return nullptr; 15377 15378 return OMPAlignedClause::Create(Context, StartLoc, LParenLoc, ColonLoc, 15379 EndLoc, Vars, Alignment); 15380 } 15381 15382 OMPClause *Sema::ActOnOpenMPCopyinClause(ArrayRef<Expr *> VarList, 15383 SourceLocation StartLoc, 15384 SourceLocation LParenLoc, 15385 SourceLocation EndLoc) { 15386 SmallVector<Expr *, 8> Vars; 15387 SmallVector<Expr *, 8> SrcExprs; 15388 SmallVector<Expr *, 8> DstExprs; 15389 SmallVector<Expr *, 8> AssignmentOps; 15390 for (Expr *RefExpr : VarList) { 15391 assert(RefExpr && "NULL expr in OpenMP copyin clause."); 15392 if (isa<DependentScopeDeclRefExpr>(RefExpr)) { 15393 // It will be analyzed later. 15394 Vars.push_back(RefExpr); 15395 SrcExprs.push_back(nullptr); 15396 DstExprs.push_back(nullptr); 15397 AssignmentOps.push_back(nullptr); 15398 continue; 15399 } 15400 15401 SourceLocation ELoc = RefExpr->getExprLoc(); 15402 // OpenMP [2.1, C/C++] 15403 // A list item is a variable name. 15404 // OpenMP [2.14.4.1, Restrictions, p.1] 15405 // A list item that appears in a copyin clause must be threadprivate. 15406 auto *DE = dyn_cast<DeclRefExpr>(RefExpr); 15407 if (!DE || !isa<VarDecl>(DE->getDecl())) { 15408 Diag(ELoc, diag::err_omp_expected_var_name_member_expr) 15409 << 0 << RefExpr->getSourceRange(); 15410 continue; 15411 } 15412 15413 Decl *D = DE->getDecl(); 15414 auto *VD = cast<VarDecl>(D); 15415 15416 QualType Type = VD->getType(); 15417 if (Type->isDependentType() || Type->isInstantiationDependentType()) { 15418 // It will be analyzed later. 15419 Vars.push_back(DE); 15420 SrcExprs.push_back(nullptr); 15421 DstExprs.push_back(nullptr); 15422 AssignmentOps.push_back(nullptr); 15423 continue; 15424 } 15425 15426 // OpenMP [2.14.4.1, Restrictions, C/C++, p.1] 15427 // A list item that appears in a copyin clause must be threadprivate. 15428 if (!DSAStack->isThreadPrivate(VD)) { 15429 Diag(ELoc, diag::err_omp_required_access) 15430 << getOpenMPClauseName(OMPC_copyin) 15431 << getOpenMPDirectiveName(OMPD_threadprivate); 15432 continue; 15433 } 15434 15435 // OpenMP [2.14.4.1, Restrictions, C/C++, p.2] 15436 // A variable of class type (or array thereof) that appears in a 15437 // copyin clause requires an accessible, unambiguous copy assignment 15438 // operator for the class type. 15439 QualType ElemType = Context.getBaseElementType(Type).getNonReferenceType(); 15440 VarDecl *SrcVD = 15441 buildVarDecl(*this, DE->getBeginLoc(), ElemType.getUnqualifiedType(), 15442 ".copyin.src", VD->hasAttrs() ? &VD->getAttrs() : nullptr); 15443 DeclRefExpr *PseudoSrcExpr = buildDeclRefExpr( 15444 *this, SrcVD, ElemType.getUnqualifiedType(), DE->getExprLoc()); 15445 VarDecl *DstVD = 15446 buildVarDecl(*this, DE->getBeginLoc(), ElemType, ".copyin.dst", 15447 VD->hasAttrs() ? &VD->getAttrs() : nullptr); 15448 DeclRefExpr *PseudoDstExpr = 15449 buildDeclRefExpr(*this, DstVD, ElemType, DE->getExprLoc()); 15450 // For arrays generate assignment operation for single element and replace 15451 // it by the original array element in CodeGen. 15452 ExprResult AssignmentOp = 15453 BuildBinOp(/*S=*/nullptr, DE->getExprLoc(), BO_Assign, PseudoDstExpr, 15454 PseudoSrcExpr); 15455 if (AssignmentOp.isInvalid()) 15456 continue; 15457 AssignmentOp = ActOnFinishFullExpr(AssignmentOp.get(), DE->getExprLoc(), 15458 /*DiscardedValue*/ false); 15459 if (AssignmentOp.isInvalid()) 15460 continue; 15461 15462 DSAStack->addDSA(VD, DE, OMPC_copyin); 15463 Vars.push_back(DE); 15464 SrcExprs.push_back(PseudoSrcExpr); 15465 DstExprs.push_back(PseudoDstExpr); 15466 AssignmentOps.push_back(AssignmentOp.get()); 15467 } 15468 15469 if (Vars.empty()) 15470 return nullptr; 15471 15472 return OMPCopyinClause::Create(Context, StartLoc, LParenLoc, EndLoc, Vars, 15473 SrcExprs, DstExprs, AssignmentOps); 15474 } 15475 15476 OMPClause *Sema::ActOnOpenMPCopyprivateClause(ArrayRef<Expr *> VarList, 15477 SourceLocation StartLoc, 15478 SourceLocation LParenLoc, 15479 SourceLocation EndLoc) { 15480 SmallVector<Expr *, 8> Vars; 15481 SmallVector<Expr *, 8> SrcExprs; 15482 SmallVector<Expr *, 8> DstExprs; 15483 SmallVector<Expr *, 8> AssignmentOps; 15484 for (Expr *RefExpr : VarList) { 15485 assert(RefExpr && "NULL expr in OpenMP linear clause."); 15486 SourceLocation ELoc; 15487 SourceRange ERange; 15488 Expr *SimpleRefExpr = RefExpr; 15489 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange); 15490 if (Res.second) { 15491 // It will be analyzed later. 15492 Vars.push_back(RefExpr); 15493 SrcExprs.push_back(nullptr); 15494 DstExprs.push_back(nullptr); 15495 AssignmentOps.push_back(nullptr); 15496 } 15497 ValueDecl *D = Res.first; 15498 if (!D) 15499 continue; 15500 15501 QualType Type = D->getType(); 15502 auto *VD = dyn_cast<VarDecl>(D); 15503 15504 // OpenMP [2.14.4.2, Restrictions, p.2] 15505 // A list item that appears in a copyprivate clause may not appear in a 15506 // private or firstprivate clause on the single construct. 15507 if (!VD || !DSAStack->isThreadPrivate(VD)) { 15508 DSAStackTy::DSAVarData DVar = 15509 DSAStack->getTopDSA(D, /*FromParent=*/false); 15510 if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_copyprivate && 15511 DVar.RefExpr) { 15512 Diag(ELoc, diag::err_omp_wrong_dsa) 15513 << getOpenMPClauseName(DVar.CKind) 15514 << getOpenMPClauseName(OMPC_copyprivate); 15515 reportOriginalDsa(*this, DSAStack, D, DVar); 15516 continue; 15517 } 15518 15519 // OpenMP [2.11.4.2, Restrictions, p.1] 15520 // All list items that appear in a copyprivate clause must be either 15521 // threadprivate or private in the enclosing context. 15522 if (DVar.CKind == OMPC_unknown) { 15523 DVar = DSAStack->getImplicitDSA(D, false); 15524 if (DVar.CKind == OMPC_shared) { 15525 Diag(ELoc, diag::err_omp_required_access) 15526 << getOpenMPClauseName(OMPC_copyprivate) 15527 << "threadprivate or private in the enclosing context"; 15528 reportOriginalDsa(*this, DSAStack, D, DVar); 15529 continue; 15530 } 15531 } 15532 } 15533 15534 // Variably modified types are not supported. 15535 if (!Type->isAnyPointerType() && Type->isVariablyModifiedType()) { 15536 Diag(ELoc, diag::err_omp_variably_modified_type_not_supported) 15537 << getOpenMPClauseName(OMPC_copyprivate) << Type 15538 << getOpenMPDirectiveName(DSAStack->getCurrentDirective()); 15539 bool IsDecl = 15540 !VD || 15541 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly; 15542 Diag(D->getLocation(), 15543 IsDecl ? diag::note_previous_decl : diag::note_defined_here) 15544 << D; 15545 continue; 15546 } 15547 15548 // OpenMP [2.14.4.1, Restrictions, C/C++, p.2] 15549 // A variable of class type (or array thereof) that appears in a 15550 // copyin clause requires an accessible, unambiguous copy assignment 15551 // operator for the class type. 15552 Type = Context.getBaseElementType(Type.getNonReferenceType()) 15553 .getUnqualifiedType(); 15554 VarDecl *SrcVD = 15555 buildVarDecl(*this, RefExpr->getBeginLoc(), Type, ".copyprivate.src", 15556 D->hasAttrs() ? &D->getAttrs() : nullptr); 15557 DeclRefExpr *PseudoSrcExpr = buildDeclRefExpr(*this, SrcVD, Type, ELoc); 15558 VarDecl *DstVD = 15559 buildVarDecl(*this, RefExpr->getBeginLoc(), Type, ".copyprivate.dst", 15560 D->hasAttrs() ? &D->getAttrs() : nullptr); 15561 DeclRefExpr *PseudoDstExpr = buildDeclRefExpr(*this, DstVD, Type, ELoc); 15562 ExprResult AssignmentOp = BuildBinOp( 15563 DSAStack->getCurScope(), ELoc, BO_Assign, PseudoDstExpr, PseudoSrcExpr); 15564 if (AssignmentOp.isInvalid()) 15565 continue; 15566 AssignmentOp = 15567 ActOnFinishFullExpr(AssignmentOp.get(), ELoc, /*DiscardedValue*/ false); 15568 if (AssignmentOp.isInvalid()) 15569 continue; 15570 15571 // No need to mark vars as copyprivate, they are already threadprivate or 15572 // implicitly private. 15573 assert(VD || isOpenMPCapturedDecl(D)); 15574 Vars.push_back( 15575 VD ? RefExpr->IgnoreParens() 15576 : buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/false)); 15577 SrcExprs.push_back(PseudoSrcExpr); 15578 DstExprs.push_back(PseudoDstExpr); 15579 AssignmentOps.push_back(AssignmentOp.get()); 15580 } 15581 15582 if (Vars.empty()) 15583 return nullptr; 15584 15585 return OMPCopyprivateClause::Create(Context, StartLoc, LParenLoc, EndLoc, 15586 Vars, SrcExprs, DstExprs, AssignmentOps); 15587 } 15588 15589 OMPClause *Sema::ActOnOpenMPFlushClause(ArrayRef<Expr *> VarList, 15590 SourceLocation StartLoc, 15591 SourceLocation LParenLoc, 15592 SourceLocation EndLoc) { 15593 if (VarList.empty()) 15594 return nullptr; 15595 15596 return OMPFlushClause::Create(Context, StartLoc, LParenLoc, EndLoc, VarList); 15597 } 15598 15599 /// Tries to find omp_depend_t. type. 15600 static bool findOMPDependT(Sema &S, SourceLocation Loc, DSAStackTy *Stack, 15601 bool Diagnose = true) { 15602 QualType OMPDependT = Stack->getOMPDependT(); 15603 if (!OMPDependT.isNull()) 15604 return true; 15605 IdentifierInfo *II = &S.PP.getIdentifierTable().get("omp_depend_t"); 15606 ParsedType PT = S.getTypeName(*II, Loc, S.getCurScope()); 15607 if (!PT.getAsOpaquePtr() || PT.get().isNull()) { 15608 if (Diagnose) 15609 S.Diag(Loc, diag::err_omp_implied_type_not_found) << "omp_depend_t"; 15610 return false; 15611 } 15612 Stack->setOMPDependT(PT.get()); 15613 return true; 15614 } 15615 15616 OMPClause *Sema::ActOnOpenMPDepobjClause(Expr *Depobj, SourceLocation StartLoc, 15617 SourceLocation LParenLoc, 15618 SourceLocation EndLoc) { 15619 if (!Depobj) 15620 return nullptr; 15621 15622 bool OMPDependTFound = findOMPDependT(*this, StartLoc, DSAStack); 15623 15624 // OpenMP 5.0, 2.17.10.1 depobj Construct 15625 // depobj is an lvalue expression of type omp_depend_t. 15626 if (!Depobj->isTypeDependent() && !Depobj->isValueDependent() && 15627 !Depobj->isInstantiationDependent() && 15628 !Depobj->containsUnexpandedParameterPack() && 15629 (OMPDependTFound && 15630 !Context.typesAreCompatible(DSAStack->getOMPDependT(), Depobj->getType(), 15631 /*CompareUnqualified=*/true))) { 15632 Diag(Depobj->getExprLoc(), diag::err_omp_expected_omp_depend_t_lvalue) 15633 << 0 << Depobj->getType() << Depobj->getSourceRange(); 15634 } 15635 15636 if (!Depobj->isLValue()) { 15637 Diag(Depobj->getExprLoc(), diag::err_omp_expected_omp_depend_t_lvalue) 15638 << 1 << Depobj->getSourceRange(); 15639 } 15640 15641 return OMPDepobjClause::Create(Context, StartLoc, LParenLoc, EndLoc, Depobj); 15642 } 15643 15644 OMPClause * 15645 Sema::ActOnOpenMPDependClause(OpenMPDependClauseKind DepKind, 15646 SourceLocation DepLoc, SourceLocation ColonLoc, 15647 ArrayRef<Expr *> VarList, SourceLocation StartLoc, 15648 SourceLocation LParenLoc, SourceLocation EndLoc) { 15649 if (DSAStack->getCurrentDirective() == OMPD_ordered && 15650 DepKind != OMPC_DEPEND_source && DepKind != OMPC_DEPEND_sink) { 15651 Diag(DepLoc, diag::err_omp_unexpected_clause_value) 15652 << "'source' or 'sink'" << getOpenMPClauseName(OMPC_depend); 15653 return nullptr; 15654 } 15655 if ((DSAStack->getCurrentDirective() != OMPD_ordered || 15656 DSAStack->getCurrentDirective() == OMPD_depobj) && 15657 (DepKind == OMPC_DEPEND_unknown || DepKind == OMPC_DEPEND_source || 15658 DepKind == OMPC_DEPEND_sink || 15659 ((LangOpts.OpenMP < 50 || 15660 DSAStack->getCurrentDirective() == OMPD_depobj) && 15661 DepKind == OMPC_DEPEND_depobj))) { 15662 SmallVector<unsigned, 3> Except; 15663 Except.push_back(OMPC_DEPEND_source); 15664 Except.push_back(OMPC_DEPEND_sink); 15665 if (LangOpts.OpenMP < 50 || DSAStack->getCurrentDirective() == OMPD_depobj) 15666 Except.push_back(OMPC_DEPEND_depobj); 15667 Diag(DepLoc, diag::err_omp_unexpected_clause_value) 15668 << getListOfPossibleValues(OMPC_depend, /*First=*/0, 15669 /*Last=*/OMPC_DEPEND_unknown, Except) 15670 << getOpenMPClauseName(OMPC_depend); 15671 return nullptr; 15672 } 15673 SmallVector<Expr *, 8> Vars; 15674 DSAStackTy::OperatorOffsetTy OpsOffs; 15675 llvm::APSInt DepCounter(/*BitWidth=*/32); 15676 llvm::APSInt TotalDepCount(/*BitWidth=*/32); 15677 if (DepKind == OMPC_DEPEND_sink || DepKind == OMPC_DEPEND_source) { 15678 if (const Expr *OrderedCountExpr = 15679 DSAStack->getParentOrderedRegionParam().first) { 15680 TotalDepCount = OrderedCountExpr->EvaluateKnownConstInt(Context); 15681 TotalDepCount.setIsUnsigned(/*Val=*/true); 15682 } 15683 } 15684 for (Expr *RefExpr : VarList) { 15685 assert(RefExpr && "NULL expr in OpenMP shared clause."); 15686 if (isa<DependentScopeDeclRefExpr>(RefExpr)) { 15687 // It will be analyzed later. 15688 Vars.push_back(RefExpr); 15689 continue; 15690 } 15691 15692 SourceLocation ELoc = RefExpr->getExprLoc(); 15693 Expr *SimpleExpr = RefExpr->IgnoreParenCasts(); 15694 if (DepKind == OMPC_DEPEND_sink) { 15695 if (DSAStack->getParentOrderedRegionParam().first && 15696 DepCounter >= TotalDepCount) { 15697 Diag(ELoc, diag::err_omp_depend_sink_unexpected_expr); 15698 continue; 15699 } 15700 ++DepCounter; 15701 // OpenMP [2.13.9, Summary] 15702 // depend(dependence-type : vec), where dependence-type is: 15703 // 'sink' and where vec is the iteration vector, which has the form: 15704 // x1 [+- d1], x2 [+- d2 ], . . . , xn [+- dn] 15705 // where n is the value specified by the ordered clause in the loop 15706 // directive, xi denotes the loop iteration variable of the i-th nested 15707 // loop associated with the loop directive, and di is a constant 15708 // non-negative integer. 15709 if (CurContext->isDependentContext()) { 15710 // It will be analyzed later. 15711 Vars.push_back(RefExpr); 15712 continue; 15713 } 15714 SimpleExpr = SimpleExpr->IgnoreImplicit(); 15715 OverloadedOperatorKind OOK = OO_None; 15716 SourceLocation OOLoc; 15717 Expr *LHS = SimpleExpr; 15718 Expr *RHS = nullptr; 15719 if (auto *BO = dyn_cast<BinaryOperator>(SimpleExpr)) { 15720 OOK = BinaryOperator::getOverloadedOperator(BO->getOpcode()); 15721 OOLoc = BO->getOperatorLoc(); 15722 LHS = BO->getLHS()->IgnoreParenImpCasts(); 15723 RHS = BO->getRHS()->IgnoreParenImpCasts(); 15724 } else if (auto *OCE = dyn_cast<CXXOperatorCallExpr>(SimpleExpr)) { 15725 OOK = OCE->getOperator(); 15726 OOLoc = OCE->getOperatorLoc(); 15727 LHS = OCE->getArg(/*Arg=*/0)->IgnoreParenImpCasts(); 15728 RHS = OCE->getArg(/*Arg=*/1)->IgnoreParenImpCasts(); 15729 } else if (auto *MCE = dyn_cast<CXXMemberCallExpr>(SimpleExpr)) { 15730 OOK = MCE->getMethodDecl() 15731 ->getNameInfo() 15732 .getName() 15733 .getCXXOverloadedOperator(); 15734 OOLoc = MCE->getCallee()->getExprLoc(); 15735 LHS = MCE->getImplicitObjectArgument()->IgnoreParenImpCasts(); 15736 RHS = MCE->getArg(/*Arg=*/0)->IgnoreParenImpCasts(); 15737 } 15738 SourceLocation ELoc; 15739 SourceRange ERange; 15740 auto Res = getPrivateItem(*this, LHS, ELoc, ERange); 15741 if (Res.second) { 15742 // It will be analyzed later. 15743 Vars.push_back(RefExpr); 15744 } 15745 ValueDecl *D = Res.first; 15746 if (!D) 15747 continue; 15748 15749 if (OOK != OO_Plus && OOK != OO_Minus && (RHS || OOK != OO_None)) { 15750 Diag(OOLoc, diag::err_omp_depend_sink_expected_plus_minus); 15751 continue; 15752 } 15753 if (RHS) { 15754 ExprResult RHSRes = VerifyPositiveIntegerConstantInClause( 15755 RHS, OMPC_depend, /*StrictlyPositive=*/false); 15756 if (RHSRes.isInvalid()) 15757 continue; 15758 } 15759 if (!CurContext->isDependentContext() && 15760 DSAStack->getParentOrderedRegionParam().first && 15761 DepCounter != DSAStack->isParentLoopControlVariable(D).first) { 15762 const ValueDecl *VD = 15763 DSAStack->getParentLoopControlVariable(DepCounter.getZExtValue()); 15764 if (VD) 15765 Diag(ELoc, diag::err_omp_depend_sink_expected_loop_iteration) 15766 << 1 << VD; 15767 else 15768 Diag(ELoc, diag::err_omp_depend_sink_expected_loop_iteration) << 0; 15769 continue; 15770 } 15771 OpsOffs.emplace_back(RHS, OOK); 15772 } else { 15773 bool OMPDependTFound = LangOpts.OpenMP >= 50; 15774 if (OMPDependTFound) 15775 OMPDependTFound = findOMPDependT(*this, StartLoc, DSAStack, 15776 DepKind == OMPC_DEPEND_depobj); 15777 if (DepKind == OMPC_DEPEND_depobj) { 15778 // OpenMP 5.0, 2.17.11 depend Clause, Restrictions, C/C++ 15779 // List items used in depend clauses with the depobj dependence type 15780 // must be expressions of the omp_depend_t type. 15781 if (!RefExpr->isValueDependent() && !RefExpr->isTypeDependent() && 15782 !RefExpr->isInstantiationDependent() && 15783 !RefExpr->containsUnexpandedParameterPack() && 15784 (OMPDependTFound && 15785 !Context.hasSameUnqualifiedType(DSAStack->getOMPDependT(), 15786 RefExpr->getType()))) { 15787 Diag(ELoc, diag::err_omp_expected_omp_depend_t_lvalue) 15788 << 0 << RefExpr->getType() << RefExpr->getSourceRange(); 15789 continue; 15790 } 15791 if (!RefExpr->isLValue()) { 15792 Diag(ELoc, diag::err_omp_expected_omp_depend_t_lvalue) 15793 << 1 << RefExpr->getType() << RefExpr->getSourceRange(); 15794 continue; 15795 } 15796 } else { 15797 // OpenMP 5.0 [2.17.11, Restrictions] 15798 // List items used in depend clauses cannot be zero-length array 15799 // sections. 15800 QualType ExprTy = RefExpr->getType().getNonReferenceType(); 15801 const auto *OASE = dyn_cast<OMPArraySectionExpr>(SimpleExpr); 15802 if (OASE) { 15803 QualType BaseType = 15804 OMPArraySectionExpr::getBaseOriginalType(OASE->getBase()); 15805 if (const auto *ATy = BaseType->getAsArrayTypeUnsafe()) 15806 ExprTy = ATy->getElementType(); 15807 else 15808 ExprTy = BaseType->getPointeeType(); 15809 ExprTy = ExprTy.getNonReferenceType(); 15810 const Expr *Length = OASE->getLength(); 15811 Expr::EvalResult Result; 15812 if (Length && !Length->isValueDependent() && 15813 Length->EvaluateAsInt(Result, Context) && 15814 Result.Val.getInt().isNullValue()) { 15815 Diag(ELoc, 15816 diag::err_omp_depend_zero_length_array_section_not_allowed) 15817 << SimpleExpr->getSourceRange(); 15818 continue; 15819 } 15820 } 15821 15822 // OpenMP 5.0, 2.17.11 depend Clause, Restrictions, C/C++ 15823 // List items used in depend clauses with the in, out, inout or 15824 // mutexinoutset dependence types cannot be expressions of the 15825 // omp_depend_t type. 15826 if (!RefExpr->isValueDependent() && !RefExpr->isTypeDependent() && 15827 !RefExpr->isInstantiationDependent() && 15828 !RefExpr->containsUnexpandedParameterPack() && 15829 (OMPDependTFound && 15830 DSAStack->getOMPDependT().getTypePtr() == ExprTy.getTypePtr())) { 15831 Diag(ELoc, diag::err_omp_expected_addressable_lvalue_or_array_item) 15832 << (LangOpts.OpenMP >= 50 ? 1 : 0) << 1 15833 << RefExpr->getSourceRange(); 15834 continue; 15835 } 15836 15837 auto *ASE = dyn_cast<ArraySubscriptExpr>(SimpleExpr); 15838 if (!RefExpr->IgnoreParenImpCasts()->isLValue() || 15839 (ASE && 15840 !ASE->getBase() 15841 ->getType() 15842 .getNonReferenceType() 15843 ->isPointerType() && 15844 !ASE->getBase()->getType().getNonReferenceType()->isArrayType())) { 15845 Diag(ELoc, diag::err_omp_expected_addressable_lvalue_or_array_item) 15846 << (LangOpts.OpenMP >= 50 ? 1 : 0) 15847 << (LangOpts.OpenMP >= 50 ? 1 : 0) << RefExpr->getSourceRange(); 15848 continue; 15849 } 15850 15851 ExprResult Res; 15852 { 15853 Sema::TentativeAnalysisScope Trap(*this); 15854 Res = CreateBuiltinUnaryOp(ELoc, UO_AddrOf, 15855 RefExpr->IgnoreParenImpCasts()); 15856 } 15857 if (!Res.isUsable() && !isa<OMPArraySectionExpr>(SimpleExpr) && 15858 !isa<OMPArrayShapingExpr>(SimpleExpr)) { 15859 Diag(ELoc, diag::err_omp_expected_addressable_lvalue_or_array_item) 15860 << (LangOpts.OpenMP >= 50 ? 1 : 0) 15861 << (LangOpts.OpenMP >= 50 ? 1 : 0) << RefExpr->getSourceRange(); 15862 continue; 15863 } 15864 } 15865 } 15866 Vars.push_back(RefExpr->IgnoreParenImpCasts()); 15867 } 15868 15869 if (!CurContext->isDependentContext() && DepKind == OMPC_DEPEND_sink && 15870 TotalDepCount > VarList.size() && 15871 DSAStack->getParentOrderedRegionParam().first && 15872 DSAStack->getParentLoopControlVariable(VarList.size() + 1)) { 15873 Diag(EndLoc, diag::err_omp_depend_sink_expected_loop_iteration) 15874 << 1 << DSAStack->getParentLoopControlVariable(VarList.size() + 1); 15875 } 15876 if (DepKind != OMPC_DEPEND_source && DepKind != OMPC_DEPEND_sink && 15877 Vars.empty()) 15878 return nullptr; 15879 15880 auto *C = OMPDependClause::Create(Context, StartLoc, LParenLoc, EndLoc, 15881 DepKind, DepLoc, ColonLoc, Vars, 15882 TotalDepCount.getZExtValue()); 15883 if ((DepKind == OMPC_DEPEND_sink || DepKind == OMPC_DEPEND_source) && 15884 DSAStack->isParentOrderedRegion()) 15885 DSAStack->addDoacrossDependClause(C, OpsOffs); 15886 return C; 15887 } 15888 15889 OMPClause *Sema::ActOnOpenMPDeviceClause(OpenMPDeviceClauseModifier Modifier, 15890 Expr *Device, SourceLocation StartLoc, 15891 SourceLocation LParenLoc, 15892 SourceLocation ModifierLoc, 15893 SourceLocation EndLoc) { 15894 assert((ModifierLoc.isInvalid() || LangOpts.OpenMP >= 50) && 15895 "Unexpected device modifier in OpenMP < 50."); 15896 15897 bool ErrorFound = false; 15898 if (ModifierLoc.isValid() && Modifier == OMPC_DEVICE_unknown) { 15899 std::string Values = 15900 getListOfPossibleValues(OMPC_device, /*First=*/0, OMPC_DEVICE_unknown); 15901 Diag(ModifierLoc, diag::err_omp_unexpected_clause_value) 15902 << Values << getOpenMPClauseName(OMPC_device); 15903 ErrorFound = true; 15904 } 15905 15906 Expr *ValExpr = Device; 15907 Stmt *HelperValStmt = nullptr; 15908 15909 // OpenMP [2.9.1, Restrictions] 15910 // The device expression must evaluate to a non-negative integer value. 15911 ErrorFound = !isNonNegativeIntegerValue(ValExpr, *this, OMPC_device, 15912 /*StrictlyPositive=*/false) || 15913 ErrorFound; 15914 if (ErrorFound) 15915 return nullptr; 15916 15917 OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective(); 15918 OpenMPDirectiveKind CaptureRegion = 15919 getOpenMPCaptureRegionForClause(DKind, OMPC_device, LangOpts.OpenMP); 15920 if (CaptureRegion != OMPD_unknown && !CurContext->isDependentContext()) { 15921 ValExpr = MakeFullExpr(ValExpr).get(); 15922 llvm::MapVector<const Expr *, DeclRefExpr *> Captures; 15923 ValExpr = tryBuildCapture(*this, ValExpr, Captures).get(); 15924 HelperValStmt = buildPreInits(Context, Captures); 15925 } 15926 15927 return new (Context) 15928 OMPDeviceClause(Modifier, ValExpr, HelperValStmt, CaptureRegion, StartLoc, 15929 LParenLoc, ModifierLoc, EndLoc); 15930 } 15931 15932 static bool checkTypeMappable(SourceLocation SL, SourceRange SR, Sema &SemaRef, 15933 DSAStackTy *Stack, QualType QTy, 15934 bool FullCheck = true) { 15935 NamedDecl *ND; 15936 if (QTy->isIncompleteType(&ND)) { 15937 SemaRef.Diag(SL, diag::err_incomplete_type) << QTy << SR; 15938 return false; 15939 } 15940 if (FullCheck && !SemaRef.CurContext->isDependentContext() && 15941 !QTy.isTriviallyCopyableType(SemaRef.Context)) 15942 SemaRef.Diag(SL, diag::warn_omp_non_trivial_type_mapped) << QTy << SR; 15943 return true; 15944 } 15945 15946 /// Return true if it can be proven that the provided array expression 15947 /// (array section or array subscript) does NOT specify the whole size of the 15948 /// array whose base type is \a BaseQTy. 15949 static bool checkArrayExpressionDoesNotReferToWholeSize(Sema &SemaRef, 15950 const Expr *E, 15951 QualType BaseQTy) { 15952 const auto *OASE = dyn_cast<OMPArraySectionExpr>(E); 15953 15954 // If this is an array subscript, it refers to the whole size if the size of 15955 // the dimension is constant and equals 1. Also, an array section assumes the 15956 // format of an array subscript if no colon is used. 15957 if (isa<ArraySubscriptExpr>(E) || (OASE && OASE->getColonLoc().isInvalid())) { 15958 if (const auto *ATy = dyn_cast<ConstantArrayType>(BaseQTy.getTypePtr())) 15959 return ATy->getSize().getSExtValue() != 1; 15960 // Size can't be evaluated statically. 15961 return false; 15962 } 15963 15964 assert(OASE && "Expecting array section if not an array subscript."); 15965 const Expr *LowerBound = OASE->getLowerBound(); 15966 const Expr *Length = OASE->getLength(); 15967 15968 // If there is a lower bound that does not evaluates to zero, we are not 15969 // covering the whole dimension. 15970 if (LowerBound) { 15971 Expr::EvalResult Result; 15972 if (!LowerBound->EvaluateAsInt(Result, SemaRef.getASTContext())) 15973 return false; // Can't get the integer value as a constant. 15974 15975 llvm::APSInt ConstLowerBound = Result.Val.getInt(); 15976 if (ConstLowerBound.getSExtValue()) 15977 return true; 15978 } 15979 15980 // If we don't have a length we covering the whole dimension. 15981 if (!Length) 15982 return false; 15983 15984 // If the base is a pointer, we don't have a way to get the size of the 15985 // pointee. 15986 if (BaseQTy->isPointerType()) 15987 return false; 15988 15989 // We can only check if the length is the same as the size of the dimension 15990 // if we have a constant array. 15991 const auto *CATy = dyn_cast<ConstantArrayType>(BaseQTy.getTypePtr()); 15992 if (!CATy) 15993 return false; 15994 15995 Expr::EvalResult Result; 15996 if (!Length->EvaluateAsInt(Result, SemaRef.getASTContext())) 15997 return false; // Can't get the integer value as a constant. 15998 15999 llvm::APSInt ConstLength = Result.Val.getInt(); 16000 return CATy->getSize().getSExtValue() != ConstLength.getSExtValue(); 16001 } 16002 16003 // Return true if it can be proven that the provided array expression (array 16004 // section or array subscript) does NOT specify a single element of the array 16005 // whose base type is \a BaseQTy. 16006 static bool checkArrayExpressionDoesNotReferToUnitySize(Sema &SemaRef, 16007 const Expr *E, 16008 QualType BaseQTy) { 16009 const auto *OASE = dyn_cast<OMPArraySectionExpr>(E); 16010 16011 // An array subscript always refer to a single element. Also, an array section 16012 // assumes the format of an array subscript if no colon is used. 16013 if (isa<ArraySubscriptExpr>(E) || (OASE && OASE->getColonLoc().isInvalid())) 16014 return false; 16015 16016 assert(OASE && "Expecting array section if not an array subscript."); 16017 const Expr *Length = OASE->getLength(); 16018 16019 // If we don't have a length we have to check if the array has unitary size 16020 // for this dimension. Also, we should always expect a length if the base type 16021 // is pointer. 16022 if (!Length) { 16023 if (const auto *ATy = dyn_cast<ConstantArrayType>(BaseQTy.getTypePtr())) 16024 return ATy->getSize().getSExtValue() != 1; 16025 // We cannot assume anything. 16026 return false; 16027 } 16028 16029 // Check if the length evaluates to 1. 16030 Expr::EvalResult Result; 16031 if (!Length->EvaluateAsInt(Result, SemaRef.getASTContext())) 16032 return false; // Can't get the integer value as a constant. 16033 16034 llvm::APSInt ConstLength = Result.Val.getInt(); 16035 return ConstLength.getSExtValue() != 1; 16036 } 16037 16038 // The base of elements of list in a map clause have to be either: 16039 // - a reference to variable or field. 16040 // - a member expression. 16041 // - an array expression. 16042 // 16043 // E.g. if we have the expression 'r.S.Arr[:12]', we want to retrieve the 16044 // reference to 'r'. 16045 // 16046 // If we have: 16047 // 16048 // struct SS { 16049 // Bla S; 16050 // foo() { 16051 // #pragma omp target map (S.Arr[:12]); 16052 // } 16053 // } 16054 // 16055 // We want to retrieve the member expression 'this->S'; 16056 16057 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.2] 16058 // If a list item is an array section, it must specify contiguous storage. 16059 // 16060 // For this restriction it is sufficient that we make sure only references 16061 // to variables or fields and array expressions, and that no array sections 16062 // exist except in the rightmost expression (unless they cover the whole 16063 // dimension of the array). E.g. these would be invalid: 16064 // 16065 // r.ArrS[3:5].Arr[6:7] 16066 // 16067 // r.ArrS[3:5].x 16068 // 16069 // but these would be valid: 16070 // r.ArrS[3].Arr[6:7] 16071 // 16072 // r.ArrS[3].x 16073 namespace { 16074 class MapBaseChecker final : public StmtVisitor<MapBaseChecker, bool> { 16075 Sema &SemaRef; 16076 OpenMPClauseKind CKind = OMPC_unknown; 16077 OMPClauseMappableExprCommon::MappableExprComponentList &Components; 16078 bool NoDiagnose = false; 16079 const Expr *RelevantExpr = nullptr; 16080 bool AllowUnitySizeArraySection = true; 16081 bool AllowWholeSizeArraySection = true; 16082 SourceLocation ELoc; 16083 SourceRange ERange; 16084 16085 void emitErrorMsg() { 16086 // If nothing else worked, this is not a valid map clause expression. 16087 if (SemaRef.getLangOpts().OpenMP < 50) { 16088 SemaRef.Diag(ELoc, 16089 diag::err_omp_expected_named_var_member_or_array_expression) 16090 << ERange; 16091 } else { 16092 SemaRef.Diag(ELoc, diag::err_omp_non_lvalue_in_map_or_motion_clauses) 16093 << getOpenMPClauseName(CKind) << ERange; 16094 } 16095 } 16096 16097 public: 16098 bool VisitDeclRefExpr(DeclRefExpr *DRE) { 16099 if (!isa<VarDecl>(DRE->getDecl())) { 16100 emitErrorMsg(); 16101 return false; 16102 } 16103 assert(!RelevantExpr && "RelevantExpr is expected to be nullptr"); 16104 RelevantExpr = DRE; 16105 // Record the component. 16106 Components.emplace_back(DRE, DRE->getDecl()); 16107 return true; 16108 } 16109 16110 bool VisitMemberExpr(MemberExpr *ME) { 16111 Expr *E = ME; 16112 Expr *BaseE = ME->getBase()->IgnoreParenCasts(); 16113 16114 if (isa<CXXThisExpr>(BaseE)) { 16115 assert(!RelevantExpr && "RelevantExpr is expected to be nullptr"); 16116 // We found a base expression: this->Val. 16117 RelevantExpr = ME; 16118 } else { 16119 E = BaseE; 16120 } 16121 16122 if (!isa<FieldDecl>(ME->getMemberDecl())) { 16123 if (!NoDiagnose) { 16124 SemaRef.Diag(ELoc, diag::err_omp_expected_access_to_data_field) 16125 << ME->getSourceRange(); 16126 return false; 16127 } 16128 if (RelevantExpr) 16129 return false; 16130 return Visit(E); 16131 } 16132 16133 auto *FD = cast<FieldDecl>(ME->getMemberDecl()); 16134 16135 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C/C++, p.3] 16136 // A bit-field cannot appear in a map clause. 16137 // 16138 if (FD->isBitField()) { 16139 if (!NoDiagnose) { 16140 SemaRef.Diag(ELoc, diag::err_omp_bit_fields_forbidden_in_clause) 16141 << ME->getSourceRange() << getOpenMPClauseName(CKind); 16142 return false; 16143 } 16144 if (RelevantExpr) 16145 return false; 16146 return Visit(E); 16147 } 16148 16149 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C++, p.1] 16150 // If the type of a list item is a reference to a type T then the type 16151 // will be considered to be T for all purposes of this clause. 16152 QualType CurType = BaseE->getType().getNonReferenceType(); 16153 16154 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C/C++, p.2] 16155 // A list item cannot be a variable that is a member of a structure with 16156 // a union type. 16157 // 16158 if (CurType->isUnionType()) { 16159 if (!NoDiagnose) { 16160 SemaRef.Diag(ELoc, diag::err_omp_union_type_not_allowed) 16161 << ME->getSourceRange(); 16162 return false; 16163 } 16164 return RelevantExpr || Visit(E); 16165 } 16166 16167 // If we got a member expression, we should not expect any array section 16168 // before that: 16169 // 16170 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.7] 16171 // If a list item is an element of a structure, only the rightmost symbol 16172 // of the variable reference can be an array section. 16173 // 16174 AllowUnitySizeArraySection = false; 16175 AllowWholeSizeArraySection = false; 16176 16177 // Record the component. 16178 Components.emplace_back(ME, FD); 16179 return RelevantExpr || Visit(E); 16180 } 16181 16182 bool VisitArraySubscriptExpr(ArraySubscriptExpr *AE) { 16183 Expr *E = AE->getBase()->IgnoreParenImpCasts(); 16184 16185 if (!E->getType()->isAnyPointerType() && !E->getType()->isArrayType()) { 16186 if (!NoDiagnose) { 16187 SemaRef.Diag(ELoc, diag::err_omp_expected_base_var_name) 16188 << 0 << AE->getSourceRange(); 16189 return false; 16190 } 16191 return RelevantExpr || Visit(E); 16192 } 16193 16194 // If we got an array subscript that express the whole dimension we 16195 // can have any array expressions before. If it only expressing part of 16196 // the dimension, we can only have unitary-size array expressions. 16197 if (checkArrayExpressionDoesNotReferToWholeSize(SemaRef, AE, 16198 E->getType())) 16199 AllowWholeSizeArraySection = false; 16200 16201 if (const auto *TE = dyn_cast<CXXThisExpr>(E->IgnoreParenCasts())) { 16202 Expr::EvalResult Result; 16203 if (!AE->getIdx()->isValueDependent() && 16204 AE->getIdx()->EvaluateAsInt(Result, SemaRef.getASTContext()) && 16205 !Result.Val.getInt().isNullValue()) { 16206 SemaRef.Diag(AE->getIdx()->getExprLoc(), 16207 diag::err_omp_invalid_map_this_expr); 16208 SemaRef.Diag(AE->getIdx()->getExprLoc(), 16209 diag::note_omp_invalid_subscript_on_this_ptr_map); 16210 } 16211 assert(!RelevantExpr && "RelevantExpr is expected to be nullptr"); 16212 RelevantExpr = TE; 16213 } 16214 16215 // Record the component - we don't have any declaration associated. 16216 Components.emplace_back(AE, nullptr); 16217 16218 return RelevantExpr || Visit(E); 16219 } 16220 16221 bool VisitOMPArraySectionExpr(OMPArraySectionExpr *OASE) { 16222 assert(!NoDiagnose && "Array sections cannot be implicitly mapped."); 16223 Expr *E = OASE->getBase()->IgnoreParenImpCasts(); 16224 QualType CurType = 16225 OMPArraySectionExpr::getBaseOriginalType(E).getCanonicalType(); 16226 16227 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C++, p.1] 16228 // If the type of a list item is a reference to a type T then the type 16229 // will be considered to be T for all purposes of this clause. 16230 if (CurType->isReferenceType()) 16231 CurType = CurType->getPointeeType(); 16232 16233 bool IsPointer = CurType->isAnyPointerType(); 16234 16235 if (!IsPointer && !CurType->isArrayType()) { 16236 SemaRef.Diag(ELoc, diag::err_omp_expected_base_var_name) 16237 << 0 << OASE->getSourceRange(); 16238 return false; 16239 } 16240 16241 bool NotWhole = 16242 checkArrayExpressionDoesNotReferToWholeSize(SemaRef, OASE, CurType); 16243 bool NotUnity = 16244 checkArrayExpressionDoesNotReferToUnitySize(SemaRef, OASE, CurType); 16245 16246 if (AllowWholeSizeArraySection) { 16247 // Any array section is currently allowed. Allowing a whole size array 16248 // section implies allowing a unity array section as well. 16249 // 16250 // If this array section refers to the whole dimension we can still 16251 // accept other array sections before this one, except if the base is a 16252 // pointer. Otherwise, only unitary sections are accepted. 16253 if (NotWhole || IsPointer) 16254 AllowWholeSizeArraySection = false; 16255 } else if (AllowUnitySizeArraySection && NotUnity) { 16256 // A unity or whole array section is not allowed and that is not 16257 // compatible with the properties of the current array section. 16258 SemaRef.Diag( 16259 ELoc, diag::err_array_section_does_not_specify_contiguous_storage) 16260 << OASE->getSourceRange(); 16261 return false; 16262 } 16263 16264 if (const auto *TE = dyn_cast<CXXThisExpr>(E)) { 16265 Expr::EvalResult ResultR; 16266 Expr::EvalResult ResultL; 16267 if (!OASE->getLength()->isValueDependent() && 16268 OASE->getLength()->EvaluateAsInt(ResultR, SemaRef.getASTContext()) && 16269 !ResultR.Val.getInt().isOneValue()) { 16270 SemaRef.Diag(OASE->getLength()->getExprLoc(), 16271 diag::err_omp_invalid_map_this_expr); 16272 SemaRef.Diag(OASE->getLength()->getExprLoc(), 16273 diag::note_omp_invalid_length_on_this_ptr_mapping); 16274 } 16275 if (OASE->getLowerBound() && !OASE->getLowerBound()->isValueDependent() && 16276 OASE->getLowerBound()->EvaluateAsInt(ResultL, 16277 SemaRef.getASTContext()) && 16278 !ResultL.Val.getInt().isNullValue()) { 16279 SemaRef.Diag(OASE->getLowerBound()->getExprLoc(), 16280 diag::err_omp_invalid_map_this_expr); 16281 SemaRef.Diag(OASE->getLowerBound()->getExprLoc(), 16282 diag::note_omp_invalid_lower_bound_on_this_ptr_mapping); 16283 } 16284 assert(!RelevantExpr && "RelevantExpr is expected to be nullptr"); 16285 RelevantExpr = TE; 16286 } 16287 16288 // Record the component - we don't have any declaration associated. 16289 Components.emplace_back(OASE, nullptr); 16290 return RelevantExpr || Visit(E); 16291 } 16292 bool VisitOMPArrayShapingExpr(OMPArrayShapingExpr *E) { 16293 Expr *Base = E->getBase(); 16294 16295 // Record the component - we don't have any declaration associated. 16296 Components.emplace_back(E, nullptr); 16297 16298 return Visit(Base->IgnoreParenImpCasts()); 16299 } 16300 16301 bool VisitUnaryOperator(UnaryOperator *UO) { 16302 if (SemaRef.getLangOpts().OpenMP < 50 || !UO->isLValue() || 16303 UO->getOpcode() != UO_Deref) { 16304 emitErrorMsg(); 16305 return false; 16306 } 16307 if (!RelevantExpr) { 16308 // Record the component if haven't found base decl. 16309 Components.emplace_back(UO, nullptr); 16310 } 16311 return RelevantExpr || Visit(UO->getSubExpr()->IgnoreParenImpCasts()); 16312 } 16313 bool VisitBinaryOperator(BinaryOperator *BO) { 16314 if (SemaRef.getLangOpts().OpenMP < 50 || !BO->getType()->isPointerType()) { 16315 emitErrorMsg(); 16316 return false; 16317 } 16318 16319 // Pointer arithmetic is the only thing we expect to happen here so after we 16320 // make sure the binary operator is a pointer type, the we only thing need 16321 // to to is to visit the subtree that has the same type as root (so that we 16322 // know the other subtree is just an offset) 16323 Expr *LE = BO->getLHS()->IgnoreParenImpCasts(); 16324 Expr *RE = BO->getRHS()->IgnoreParenImpCasts(); 16325 Components.emplace_back(BO, nullptr); 16326 assert((LE->getType().getTypePtr() == BO->getType().getTypePtr() || 16327 RE->getType().getTypePtr() == BO->getType().getTypePtr()) && 16328 "Either LHS or RHS have base decl inside"); 16329 if (BO->getType().getTypePtr() == LE->getType().getTypePtr()) 16330 return RelevantExpr || Visit(LE); 16331 return RelevantExpr || Visit(RE); 16332 } 16333 bool VisitCXXThisExpr(CXXThisExpr *CTE) { 16334 assert(!RelevantExpr && "RelevantExpr is expected to be nullptr"); 16335 RelevantExpr = CTE; 16336 Components.emplace_back(CTE, nullptr); 16337 return true; 16338 } 16339 bool VisitStmt(Stmt *) { 16340 emitErrorMsg(); 16341 return false; 16342 } 16343 const Expr *getFoundBase() const { 16344 return RelevantExpr; 16345 } 16346 explicit MapBaseChecker( 16347 Sema &SemaRef, OpenMPClauseKind CKind, 16348 OMPClauseMappableExprCommon::MappableExprComponentList &Components, 16349 bool NoDiagnose, SourceLocation &ELoc, SourceRange &ERange) 16350 : SemaRef(SemaRef), CKind(CKind), Components(Components), 16351 NoDiagnose(NoDiagnose), ELoc(ELoc), ERange(ERange) {} 16352 }; 16353 } // namespace 16354 16355 /// Return the expression of the base of the mappable expression or null if it 16356 /// cannot be determined and do all the necessary checks to see if the expression 16357 /// is valid as a standalone mappable expression. In the process, record all the 16358 /// components of the expression. 16359 static const Expr *checkMapClauseExpressionBase( 16360 Sema &SemaRef, Expr *E, 16361 OMPClauseMappableExprCommon::MappableExprComponentList &CurComponents, 16362 OpenMPClauseKind CKind, bool NoDiagnose) { 16363 SourceLocation ELoc = E->getExprLoc(); 16364 SourceRange ERange = E->getSourceRange(); 16365 MapBaseChecker Checker(SemaRef, CKind, CurComponents, NoDiagnose, ELoc, 16366 ERange); 16367 if (Checker.Visit(E->IgnoreParens())) 16368 return Checker.getFoundBase(); 16369 return nullptr; 16370 } 16371 16372 // Return true if expression E associated with value VD has conflicts with other 16373 // map information. 16374 static bool checkMapConflicts( 16375 Sema &SemaRef, DSAStackTy *DSAS, const ValueDecl *VD, const Expr *E, 16376 bool CurrentRegionOnly, 16377 OMPClauseMappableExprCommon::MappableExprComponentListRef CurComponents, 16378 OpenMPClauseKind CKind) { 16379 assert(VD && E); 16380 SourceLocation ELoc = E->getExprLoc(); 16381 SourceRange ERange = E->getSourceRange(); 16382 16383 // In order to easily check the conflicts we need to match each component of 16384 // the expression under test with the components of the expressions that are 16385 // already in the stack. 16386 16387 assert(!CurComponents.empty() && "Map clause expression with no components!"); 16388 assert(CurComponents.back().getAssociatedDeclaration() == VD && 16389 "Map clause expression with unexpected base!"); 16390 16391 // Variables to help detecting enclosing problems in data environment nests. 16392 bool IsEnclosedByDataEnvironmentExpr = false; 16393 const Expr *EnclosingExpr = nullptr; 16394 16395 bool FoundError = DSAS->checkMappableExprComponentListsForDecl( 16396 VD, CurrentRegionOnly, 16397 [&IsEnclosedByDataEnvironmentExpr, &SemaRef, VD, CurrentRegionOnly, ELoc, 16398 ERange, CKind, &EnclosingExpr, 16399 CurComponents](OMPClauseMappableExprCommon::MappableExprComponentListRef 16400 StackComponents, 16401 OpenMPClauseKind) { 16402 assert(!StackComponents.empty() && 16403 "Map clause expression with no components!"); 16404 assert(StackComponents.back().getAssociatedDeclaration() == VD && 16405 "Map clause expression with unexpected base!"); 16406 (void)VD; 16407 16408 // The whole expression in the stack. 16409 const Expr *RE = StackComponents.front().getAssociatedExpression(); 16410 16411 // Expressions must start from the same base. Here we detect at which 16412 // point both expressions diverge from each other and see if we can 16413 // detect if the memory referred to both expressions is contiguous and 16414 // do not overlap. 16415 auto CI = CurComponents.rbegin(); 16416 auto CE = CurComponents.rend(); 16417 auto SI = StackComponents.rbegin(); 16418 auto SE = StackComponents.rend(); 16419 for (; CI != CE && SI != SE; ++CI, ++SI) { 16420 16421 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.3] 16422 // At most one list item can be an array item derived from a given 16423 // variable in map clauses of the same construct. 16424 if (CurrentRegionOnly && 16425 (isa<ArraySubscriptExpr>(CI->getAssociatedExpression()) || 16426 isa<OMPArraySectionExpr>(CI->getAssociatedExpression()) || 16427 isa<OMPArrayShapingExpr>(CI->getAssociatedExpression())) && 16428 (isa<ArraySubscriptExpr>(SI->getAssociatedExpression()) || 16429 isa<OMPArraySectionExpr>(SI->getAssociatedExpression()) || 16430 isa<OMPArrayShapingExpr>(SI->getAssociatedExpression()))) { 16431 SemaRef.Diag(CI->getAssociatedExpression()->getExprLoc(), 16432 diag::err_omp_multiple_array_items_in_map_clause) 16433 << CI->getAssociatedExpression()->getSourceRange(); 16434 SemaRef.Diag(SI->getAssociatedExpression()->getExprLoc(), 16435 diag::note_used_here) 16436 << SI->getAssociatedExpression()->getSourceRange(); 16437 return true; 16438 } 16439 16440 // Do both expressions have the same kind? 16441 if (CI->getAssociatedExpression()->getStmtClass() != 16442 SI->getAssociatedExpression()->getStmtClass()) 16443 break; 16444 16445 // Are we dealing with different variables/fields? 16446 if (CI->getAssociatedDeclaration() != SI->getAssociatedDeclaration()) 16447 break; 16448 } 16449 // Check if the extra components of the expressions in the enclosing 16450 // data environment are redundant for the current base declaration. 16451 // If they are, the maps completely overlap, which is legal. 16452 for (; SI != SE; ++SI) { 16453 QualType Type; 16454 if (const auto *ASE = 16455 dyn_cast<ArraySubscriptExpr>(SI->getAssociatedExpression())) { 16456 Type = ASE->getBase()->IgnoreParenImpCasts()->getType(); 16457 } else if (const auto *OASE = dyn_cast<OMPArraySectionExpr>( 16458 SI->getAssociatedExpression())) { 16459 const Expr *E = OASE->getBase()->IgnoreParenImpCasts(); 16460 Type = 16461 OMPArraySectionExpr::getBaseOriginalType(E).getCanonicalType(); 16462 } else if (const auto *OASE = dyn_cast<OMPArrayShapingExpr>( 16463 SI->getAssociatedExpression())) { 16464 Type = OASE->getBase()->getType()->getPointeeType(); 16465 } 16466 if (Type.isNull() || Type->isAnyPointerType() || 16467 checkArrayExpressionDoesNotReferToWholeSize( 16468 SemaRef, SI->getAssociatedExpression(), Type)) 16469 break; 16470 } 16471 16472 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.4] 16473 // List items of map clauses in the same construct must not share 16474 // original storage. 16475 // 16476 // If the expressions are exactly the same or one is a subset of the 16477 // other, it means they are sharing storage. 16478 if (CI == CE && SI == SE) { 16479 if (CurrentRegionOnly) { 16480 if (CKind == OMPC_map) { 16481 SemaRef.Diag(ELoc, diag::err_omp_map_shared_storage) << ERange; 16482 } else { 16483 assert(CKind == OMPC_to || CKind == OMPC_from); 16484 SemaRef.Diag(ELoc, diag::err_omp_once_referenced_in_target_update) 16485 << ERange; 16486 } 16487 SemaRef.Diag(RE->getExprLoc(), diag::note_used_here) 16488 << RE->getSourceRange(); 16489 return true; 16490 } 16491 // If we find the same expression in the enclosing data environment, 16492 // that is legal. 16493 IsEnclosedByDataEnvironmentExpr = true; 16494 return false; 16495 } 16496 16497 QualType DerivedType = 16498 std::prev(CI)->getAssociatedDeclaration()->getType(); 16499 SourceLocation DerivedLoc = 16500 std::prev(CI)->getAssociatedExpression()->getExprLoc(); 16501 16502 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C++, p.1] 16503 // If the type of a list item is a reference to a type T then the type 16504 // will be considered to be T for all purposes of this clause. 16505 DerivedType = DerivedType.getNonReferenceType(); 16506 16507 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C/C++, p.1] 16508 // A variable for which the type is pointer and an array section 16509 // derived from that variable must not appear as list items of map 16510 // clauses of the same construct. 16511 // 16512 // Also, cover one of the cases in: 16513 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.5] 16514 // If any part of the original storage of a list item has corresponding 16515 // storage in the device data environment, all of the original storage 16516 // must have corresponding storage in the device data environment. 16517 // 16518 if (DerivedType->isAnyPointerType()) { 16519 if (CI == CE || SI == SE) { 16520 SemaRef.Diag( 16521 DerivedLoc, 16522 diag::err_omp_pointer_mapped_along_with_derived_section) 16523 << DerivedLoc; 16524 SemaRef.Diag(RE->getExprLoc(), diag::note_used_here) 16525 << RE->getSourceRange(); 16526 return true; 16527 } 16528 if (CI->getAssociatedExpression()->getStmtClass() != 16529 SI->getAssociatedExpression()->getStmtClass() || 16530 CI->getAssociatedDeclaration()->getCanonicalDecl() == 16531 SI->getAssociatedDeclaration()->getCanonicalDecl()) { 16532 assert(CI != CE && SI != SE); 16533 SemaRef.Diag(DerivedLoc, diag::err_omp_same_pointer_dereferenced) 16534 << DerivedLoc; 16535 SemaRef.Diag(RE->getExprLoc(), diag::note_used_here) 16536 << RE->getSourceRange(); 16537 return true; 16538 } 16539 } 16540 16541 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.4] 16542 // List items of map clauses in the same construct must not share 16543 // original storage. 16544 // 16545 // An expression is a subset of the other. 16546 if (CurrentRegionOnly && (CI == CE || SI == SE)) { 16547 if (CKind == OMPC_map) { 16548 if (CI != CE || SI != SE) { 16549 // Allow constructs like this: map(s, s.ptr[0:1]), where s.ptr is 16550 // a pointer. 16551 auto Begin = 16552 CI != CE ? CurComponents.begin() : StackComponents.begin(); 16553 auto End = CI != CE ? CurComponents.end() : StackComponents.end(); 16554 auto It = Begin; 16555 while (It != End && !It->getAssociatedDeclaration()) 16556 std::advance(It, 1); 16557 assert(It != End && 16558 "Expected at least one component with the declaration."); 16559 if (It != Begin && It->getAssociatedDeclaration() 16560 ->getType() 16561 .getCanonicalType() 16562 ->isAnyPointerType()) { 16563 IsEnclosedByDataEnvironmentExpr = false; 16564 EnclosingExpr = nullptr; 16565 return false; 16566 } 16567 } 16568 SemaRef.Diag(ELoc, diag::err_omp_map_shared_storage) << ERange; 16569 } else { 16570 assert(CKind == OMPC_to || CKind == OMPC_from); 16571 SemaRef.Diag(ELoc, diag::err_omp_once_referenced_in_target_update) 16572 << ERange; 16573 } 16574 SemaRef.Diag(RE->getExprLoc(), diag::note_used_here) 16575 << RE->getSourceRange(); 16576 return true; 16577 } 16578 16579 // The current expression uses the same base as other expression in the 16580 // data environment but does not contain it completely. 16581 if (!CurrentRegionOnly && SI != SE) 16582 EnclosingExpr = RE; 16583 16584 // The current expression is a subset of the expression in the data 16585 // environment. 16586 IsEnclosedByDataEnvironmentExpr |= 16587 (!CurrentRegionOnly && CI != CE && SI == SE); 16588 16589 return false; 16590 }); 16591 16592 if (CurrentRegionOnly) 16593 return FoundError; 16594 16595 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.5] 16596 // If any part of the original storage of a list item has corresponding 16597 // storage in the device data environment, all of the original storage must 16598 // have corresponding storage in the device data environment. 16599 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.6] 16600 // If a list item is an element of a structure, and a different element of 16601 // the structure has a corresponding list item in the device data environment 16602 // prior to a task encountering the construct associated with the map clause, 16603 // then the list item must also have a corresponding list item in the device 16604 // data environment prior to the task encountering the construct. 16605 // 16606 if (EnclosingExpr && !IsEnclosedByDataEnvironmentExpr) { 16607 SemaRef.Diag(ELoc, 16608 diag::err_omp_original_storage_is_shared_and_does_not_contain) 16609 << ERange; 16610 SemaRef.Diag(EnclosingExpr->getExprLoc(), diag::note_used_here) 16611 << EnclosingExpr->getSourceRange(); 16612 return true; 16613 } 16614 16615 return FoundError; 16616 } 16617 16618 // Look up the user-defined mapper given the mapper name and mapped type, and 16619 // build a reference to it. 16620 static ExprResult buildUserDefinedMapperRef(Sema &SemaRef, Scope *S, 16621 CXXScopeSpec &MapperIdScopeSpec, 16622 const DeclarationNameInfo &MapperId, 16623 QualType Type, 16624 Expr *UnresolvedMapper) { 16625 if (MapperIdScopeSpec.isInvalid()) 16626 return ExprError(); 16627 // Get the actual type for the array type. 16628 if (Type->isArrayType()) { 16629 assert(Type->getAsArrayTypeUnsafe() && "Expect to get a valid array type"); 16630 Type = Type->getAsArrayTypeUnsafe()->getElementType().getCanonicalType(); 16631 } 16632 // Find all user-defined mappers with the given MapperId. 16633 SmallVector<UnresolvedSet<8>, 4> Lookups; 16634 LookupResult Lookup(SemaRef, MapperId, Sema::LookupOMPMapperName); 16635 Lookup.suppressDiagnostics(); 16636 if (S) { 16637 while (S && SemaRef.LookupParsedName(Lookup, S, &MapperIdScopeSpec)) { 16638 NamedDecl *D = Lookup.getRepresentativeDecl(); 16639 while (S && !S->isDeclScope(D)) 16640 S = S->getParent(); 16641 if (S) 16642 S = S->getParent(); 16643 Lookups.emplace_back(); 16644 Lookups.back().append(Lookup.begin(), Lookup.end()); 16645 Lookup.clear(); 16646 } 16647 } else if (auto *ULE = cast_or_null<UnresolvedLookupExpr>(UnresolvedMapper)) { 16648 // Extract the user-defined mappers with the given MapperId. 16649 Lookups.push_back(UnresolvedSet<8>()); 16650 for (NamedDecl *D : ULE->decls()) { 16651 auto *DMD = cast<OMPDeclareMapperDecl>(D); 16652 assert(DMD && "Expect valid OMPDeclareMapperDecl during instantiation."); 16653 Lookups.back().addDecl(DMD); 16654 } 16655 } 16656 // Defer the lookup for dependent types. The results will be passed through 16657 // UnresolvedMapper on instantiation. 16658 if (SemaRef.CurContext->isDependentContext() || Type->isDependentType() || 16659 Type->isInstantiationDependentType() || 16660 Type->containsUnexpandedParameterPack() || 16661 filterLookupForUDReductionAndMapper<bool>(Lookups, [](ValueDecl *D) { 16662 return !D->isInvalidDecl() && 16663 (D->getType()->isDependentType() || 16664 D->getType()->isInstantiationDependentType() || 16665 D->getType()->containsUnexpandedParameterPack()); 16666 })) { 16667 UnresolvedSet<8> URS; 16668 for (const UnresolvedSet<8> &Set : Lookups) { 16669 if (Set.empty()) 16670 continue; 16671 URS.append(Set.begin(), Set.end()); 16672 } 16673 return UnresolvedLookupExpr::Create( 16674 SemaRef.Context, /*NamingClass=*/nullptr, 16675 MapperIdScopeSpec.getWithLocInContext(SemaRef.Context), MapperId, 16676 /*ADL=*/false, /*Overloaded=*/true, URS.begin(), URS.end()); 16677 } 16678 SourceLocation Loc = MapperId.getLoc(); 16679 // [OpenMP 5.0], 2.19.7.3 declare mapper Directive, Restrictions 16680 // The type must be of struct, union or class type in C and C++ 16681 if (!Type->isStructureOrClassType() && !Type->isUnionType() && 16682 (MapperIdScopeSpec.isSet() || MapperId.getAsString() != "default")) { 16683 SemaRef.Diag(Loc, diag::err_omp_mapper_wrong_type); 16684 return ExprError(); 16685 } 16686 // Perform argument dependent lookup. 16687 if (SemaRef.getLangOpts().CPlusPlus && !MapperIdScopeSpec.isSet()) 16688 argumentDependentLookup(SemaRef, MapperId, Loc, Type, Lookups); 16689 // Return the first user-defined mapper with the desired type. 16690 if (auto *VD = filterLookupForUDReductionAndMapper<ValueDecl *>( 16691 Lookups, [&SemaRef, Type](ValueDecl *D) -> ValueDecl * { 16692 if (!D->isInvalidDecl() && 16693 SemaRef.Context.hasSameType(D->getType(), Type)) 16694 return D; 16695 return nullptr; 16696 })) 16697 return SemaRef.BuildDeclRefExpr(VD, Type, VK_LValue, Loc); 16698 // Find the first user-defined mapper with a type derived from the desired 16699 // type. 16700 if (auto *VD = filterLookupForUDReductionAndMapper<ValueDecl *>( 16701 Lookups, [&SemaRef, Type, Loc](ValueDecl *D) -> ValueDecl * { 16702 if (!D->isInvalidDecl() && 16703 SemaRef.IsDerivedFrom(Loc, Type, D->getType()) && 16704 !Type.isMoreQualifiedThan(D->getType())) 16705 return D; 16706 return nullptr; 16707 })) { 16708 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true, 16709 /*DetectVirtual=*/false); 16710 if (SemaRef.IsDerivedFrom(Loc, Type, VD->getType(), Paths)) { 16711 if (!Paths.isAmbiguous(SemaRef.Context.getCanonicalType( 16712 VD->getType().getUnqualifiedType()))) { 16713 if (SemaRef.CheckBaseClassAccess( 16714 Loc, VD->getType(), Type, Paths.front(), 16715 /*DiagID=*/0) != Sema::AR_inaccessible) { 16716 return SemaRef.BuildDeclRefExpr(VD, Type, VK_LValue, Loc); 16717 } 16718 } 16719 } 16720 } 16721 // Report error if a mapper is specified, but cannot be found. 16722 if (MapperIdScopeSpec.isSet() || MapperId.getAsString() != "default") { 16723 SemaRef.Diag(Loc, diag::err_omp_invalid_mapper) 16724 << Type << MapperId.getName(); 16725 return ExprError(); 16726 } 16727 return ExprEmpty(); 16728 } 16729 16730 namespace { 16731 // Utility struct that gathers all the related lists associated with a mappable 16732 // expression. 16733 struct MappableVarListInfo { 16734 // The list of expressions. 16735 ArrayRef<Expr *> VarList; 16736 // The list of processed expressions. 16737 SmallVector<Expr *, 16> ProcessedVarList; 16738 // The mappble components for each expression. 16739 OMPClauseMappableExprCommon::MappableExprComponentLists VarComponents; 16740 // The base declaration of the variable. 16741 SmallVector<ValueDecl *, 16> VarBaseDeclarations; 16742 // The reference to the user-defined mapper associated with every expression. 16743 SmallVector<Expr *, 16> UDMapperList; 16744 16745 MappableVarListInfo(ArrayRef<Expr *> VarList) : VarList(VarList) { 16746 // We have a list of components and base declarations for each entry in the 16747 // variable list. 16748 VarComponents.reserve(VarList.size()); 16749 VarBaseDeclarations.reserve(VarList.size()); 16750 } 16751 }; 16752 } 16753 16754 // Check the validity of the provided variable list for the provided clause kind 16755 // \a CKind. In the check process the valid expressions, mappable expression 16756 // components, variables, and user-defined mappers are extracted and used to 16757 // fill \a ProcessedVarList, \a VarComponents, \a VarBaseDeclarations, and \a 16758 // UDMapperList in MVLI. \a MapType, \a IsMapTypeImplicit, \a MapperIdScopeSpec, 16759 // and \a MapperId are expected to be valid if the clause kind is 'map'. 16760 static void checkMappableExpressionList( 16761 Sema &SemaRef, DSAStackTy *DSAS, OpenMPClauseKind CKind, 16762 MappableVarListInfo &MVLI, SourceLocation StartLoc, 16763 CXXScopeSpec &MapperIdScopeSpec, DeclarationNameInfo MapperId, 16764 ArrayRef<Expr *> UnresolvedMappers, 16765 OpenMPMapClauseKind MapType = OMPC_MAP_unknown, 16766 bool IsMapTypeImplicit = false) { 16767 // We only expect mappable expressions in 'to', 'from', and 'map' clauses. 16768 assert((CKind == OMPC_map || CKind == OMPC_to || CKind == OMPC_from) && 16769 "Unexpected clause kind with mappable expressions!"); 16770 16771 // If the identifier of user-defined mapper is not specified, it is "default". 16772 // We do not change the actual name in this clause to distinguish whether a 16773 // mapper is specified explicitly, i.e., it is not explicitly specified when 16774 // MapperId.getName() is empty. 16775 if (!MapperId.getName() || MapperId.getName().isEmpty()) { 16776 auto &DeclNames = SemaRef.getASTContext().DeclarationNames; 16777 MapperId.setName(DeclNames.getIdentifier( 16778 &SemaRef.getASTContext().Idents.get("default"))); 16779 } 16780 16781 // Iterators to find the current unresolved mapper expression. 16782 auto UMIt = UnresolvedMappers.begin(), UMEnd = UnresolvedMappers.end(); 16783 bool UpdateUMIt = false; 16784 Expr *UnresolvedMapper = nullptr; 16785 16786 // Keep track of the mappable components and base declarations in this clause. 16787 // Each entry in the list is going to have a list of components associated. We 16788 // record each set of the components so that we can build the clause later on. 16789 // In the end we should have the same amount of declarations and component 16790 // lists. 16791 16792 for (Expr *RE : MVLI.VarList) { 16793 assert(RE && "Null expr in omp to/from/map clause"); 16794 SourceLocation ELoc = RE->getExprLoc(); 16795 16796 // Find the current unresolved mapper expression. 16797 if (UpdateUMIt && UMIt != UMEnd) { 16798 UMIt++; 16799 assert( 16800 UMIt != UMEnd && 16801 "Expect the size of UnresolvedMappers to match with that of VarList"); 16802 } 16803 UpdateUMIt = true; 16804 if (UMIt != UMEnd) 16805 UnresolvedMapper = *UMIt; 16806 16807 const Expr *VE = RE->IgnoreParenLValueCasts(); 16808 16809 if (VE->isValueDependent() || VE->isTypeDependent() || 16810 VE->isInstantiationDependent() || 16811 VE->containsUnexpandedParameterPack()) { 16812 // Try to find the associated user-defined mapper. 16813 ExprResult ER = buildUserDefinedMapperRef( 16814 SemaRef, DSAS->getCurScope(), MapperIdScopeSpec, MapperId, 16815 VE->getType().getCanonicalType(), UnresolvedMapper); 16816 if (ER.isInvalid()) 16817 continue; 16818 MVLI.UDMapperList.push_back(ER.get()); 16819 // We can only analyze this information once the missing information is 16820 // resolved. 16821 MVLI.ProcessedVarList.push_back(RE); 16822 continue; 16823 } 16824 16825 Expr *SimpleExpr = RE->IgnoreParenCasts(); 16826 16827 if (!RE->isLValue()) { 16828 if (SemaRef.getLangOpts().OpenMP < 50) { 16829 SemaRef.Diag( 16830 ELoc, diag::err_omp_expected_named_var_member_or_array_expression) 16831 << RE->getSourceRange(); 16832 } else { 16833 SemaRef.Diag(ELoc, diag::err_omp_non_lvalue_in_map_or_motion_clauses) 16834 << getOpenMPClauseName(CKind) << RE->getSourceRange(); 16835 } 16836 continue; 16837 } 16838 16839 OMPClauseMappableExprCommon::MappableExprComponentList CurComponents; 16840 ValueDecl *CurDeclaration = nullptr; 16841 16842 // Obtain the array or member expression bases if required. Also, fill the 16843 // components array with all the components identified in the process. 16844 const Expr *BE = checkMapClauseExpressionBase( 16845 SemaRef, SimpleExpr, CurComponents, CKind, /*NoDiagnose=*/false); 16846 if (!BE) 16847 continue; 16848 16849 assert(!CurComponents.empty() && 16850 "Invalid mappable expression information."); 16851 16852 if (const auto *TE = dyn_cast<CXXThisExpr>(BE)) { 16853 // Add store "this" pointer to class in DSAStackTy for future checking 16854 DSAS->addMappedClassesQualTypes(TE->getType()); 16855 // Try to find the associated user-defined mapper. 16856 ExprResult ER = buildUserDefinedMapperRef( 16857 SemaRef, DSAS->getCurScope(), MapperIdScopeSpec, MapperId, 16858 VE->getType().getCanonicalType(), UnresolvedMapper); 16859 if (ER.isInvalid()) 16860 continue; 16861 MVLI.UDMapperList.push_back(ER.get()); 16862 // Skip restriction checking for variable or field declarations 16863 MVLI.ProcessedVarList.push_back(RE); 16864 MVLI.VarComponents.resize(MVLI.VarComponents.size() + 1); 16865 MVLI.VarComponents.back().append(CurComponents.begin(), 16866 CurComponents.end()); 16867 MVLI.VarBaseDeclarations.push_back(nullptr); 16868 continue; 16869 } 16870 16871 // For the following checks, we rely on the base declaration which is 16872 // expected to be associated with the last component. The declaration is 16873 // expected to be a variable or a field (if 'this' is being mapped). 16874 CurDeclaration = CurComponents.back().getAssociatedDeclaration(); 16875 assert(CurDeclaration && "Null decl on map clause."); 16876 assert( 16877 CurDeclaration->isCanonicalDecl() && 16878 "Expecting components to have associated only canonical declarations."); 16879 16880 auto *VD = dyn_cast<VarDecl>(CurDeclaration); 16881 const auto *FD = dyn_cast<FieldDecl>(CurDeclaration); 16882 16883 assert((VD || FD) && "Only variables or fields are expected here!"); 16884 (void)FD; 16885 16886 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.10] 16887 // threadprivate variables cannot appear in a map clause. 16888 // OpenMP 4.5 [2.10.5, target update Construct] 16889 // threadprivate variables cannot appear in a from clause. 16890 if (VD && DSAS->isThreadPrivate(VD)) { 16891 DSAStackTy::DSAVarData DVar = DSAS->getTopDSA(VD, /*FromParent=*/false); 16892 SemaRef.Diag(ELoc, diag::err_omp_threadprivate_in_clause) 16893 << getOpenMPClauseName(CKind); 16894 reportOriginalDsa(SemaRef, DSAS, VD, DVar); 16895 continue; 16896 } 16897 16898 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.9] 16899 // A list item cannot appear in both a map clause and a data-sharing 16900 // attribute clause on the same construct. 16901 16902 // Check conflicts with other map clause expressions. We check the conflicts 16903 // with the current construct separately from the enclosing data 16904 // environment, because the restrictions are different. We only have to 16905 // check conflicts across regions for the map clauses. 16906 if (checkMapConflicts(SemaRef, DSAS, CurDeclaration, SimpleExpr, 16907 /*CurrentRegionOnly=*/true, CurComponents, CKind)) 16908 break; 16909 if (CKind == OMPC_map && 16910 checkMapConflicts(SemaRef, DSAS, CurDeclaration, SimpleExpr, 16911 /*CurrentRegionOnly=*/false, CurComponents, CKind)) 16912 break; 16913 16914 // OpenMP 4.5 [2.10.5, target update Construct] 16915 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C++, p.1] 16916 // If the type of a list item is a reference to a type T then the type will 16917 // be considered to be T for all purposes of this clause. 16918 auto I = llvm::find_if( 16919 CurComponents, 16920 [](const OMPClauseMappableExprCommon::MappableComponent &MC) { 16921 return MC.getAssociatedDeclaration(); 16922 }); 16923 assert(I != CurComponents.end() && "Null decl on map clause."); 16924 QualType Type; 16925 auto *ASE = dyn_cast<ArraySubscriptExpr>(VE->IgnoreParens()); 16926 auto *OASE = dyn_cast<OMPArraySectionExpr>(VE->IgnoreParens()); 16927 auto *OAShE = dyn_cast<OMPArrayShapingExpr>(VE->IgnoreParens()); 16928 if (ASE) { 16929 Type = ASE->getType().getNonReferenceType(); 16930 } else if (OASE) { 16931 QualType BaseType = 16932 OMPArraySectionExpr::getBaseOriginalType(OASE->getBase()); 16933 if (const auto *ATy = BaseType->getAsArrayTypeUnsafe()) 16934 Type = ATy->getElementType(); 16935 else 16936 Type = BaseType->getPointeeType(); 16937 Type = Type.getNonReferenceType(); 16938 } else if (OAShE) { 16939 Type = OAShE->getBase()->getType()->getPointeeType(); 16940 } else { 16941 Type = VE->getType(); 16942 } 16943 16944 // OpenMP 4.5 [2.10.5, target update Construct, Restrictions, p.4] 16945 // A list item in a to or from clause must have a mappable type. 16946 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.9] 16947 // A list item must have a mappable type. 16948 if (!checkTypeMappable(VE->getExprLoc(), VE->getSourceRange(), SemaRef, 16949 DSAS, Type)) 16950 continue; 16951 16952 Type = I->getAssociatedDeclaration()->getType().getNonReferenceType(); 16953 16954 if (CKind == OMPC_map) { 16955 // target enter data 16956 // OpenMP [2.10.2, Restrictions, p. 99] 16957 // A map-type must be specified in all map clauses and must be either 16958 // to or alloc. 16959 OpenMPDirectiveKind DKind = DSAS->getCurrentDirective(); 16960 if (DKind == OMPD_target_enter_data && 16961 !(MapType == OMPC_MAP_to || MapType == OMPC_MAP_alloc)) { 16962 SemaRef.Diag(StartLoc, diag::err_omp_invalid_map_type_for_directive) 16963 << (IsMapTypeImplicit ? 1 : 0) 16964 << getOpenMPSimpleClauseTypeName(OMPC_map, MapType) 16965 << getOpenMPDirectiveName(DKind); 16966 continue; 16967 } 16968 16969 // target exit_data 16970 // OpenMP [2.10.3, Restrictions, p. 102] 16971 // A map-type must be specified in all map clauses and must be either 16972 // from, release, or delete. 16973 if (DKind == OMPD_target_exit_data && 16974 !(MapType == OMPC_MAP_from || MapType == OMPC_MAP_release || 16975 MapType == OMPC_MAP_delete)) { 16976 SemaRef.Diag(StartLoc, diag::err_omp_invalid_map_type_for_directive) 16977 << (IsMapTypeImplicit ? 1 : 0) 16978 << getOpenMPSimpleClauseTypeName(OMPC_map, MapType) 16979 << getOpenMPDirectiveName(DKind); 16980 continue; 16981 } 16982 16983 // OpenMP 4.5 [2.15.5.1, Restrictions, p.3] 16984 // A list item cannot appear in both a map clause and a data-sharing 16985 // attribute clause on the same construct 16986 // 16987 // OpenMP 5.0 [2.19.7.1, Restrictions, p.7] 16988 // A list item cannot appear in both a map clause and a data-sharing 16989 // attribute clause on the same construct unless the construct is a 16990 // combined construct. 16991 if (VD && ((SemaRef.LangOpts.OpenMP <= 45 && 16992 isOpenMPTargetExecutionDirective(DKind)) || 16993 DKind == OMPD_target)) { 16994 DSAStackTy::DSAVarData DVar = DSAS->getTopDSA(VD, /*FromParent=*/false); 16995 if (isOpenMPPrivate(DVar.CKind)) { 16996 SemaRef.Diag(ELoc, diag::err_omp_variable_in_given_clause_and_dsa) 16997 << getOpenMPClauseName(DVar.CKind) 16998 << getOpenMPClauseName(OMPC_map) 16999 << getOpenMPDirectiveName(DSAS->getCurrentDirective()); 17000 reportOriginalDsa(SemaRef, DSAS, CurDeclaration, DVar); 17001 continue; 17002 } 17003 } 17004 } 17005 17006 // Try to find the associated user-defined mapper. 17007 ExprResult ER = buildUserDefinedMapperRef( 17008 SemaRef, DSAS->getCurScope(), MapperIdScopeSpec, MapperId, 17009 Type.getCanonicalType(), UnresolvedMapper); 17010 if (ER.isInvalid()) 17011 continue; 17012 MVLI.UDMapperList.push_back(ER.get()); 17013 17014 // Save the current expression. 17015 MVLI.ProcessedVarList.push_back(RE); 17016 17017 // Store the components in the stack so that they can be used to check 17018 // against other clauses later on. 17019 DSAS->addMappableExpressionComponents(CurDeclaration, CurComponents, 17020 /*WhereFoundClauseKind=*/OMPC_map); 17021 17022 // Save the components and declaration to create the clause. For purposes of 17023 // the clause creation, any component list that has has base 'this' uses 17024 // null as base declaration. 17025 MVLI.VarComponents.resize(MVLI.VarComponents.size() + 1); 17026 MVLI.VarComponents.back().append(CurComponents.begin(), 17027 CurComponents.end()); 17028 MVLI.VarBaseDeclarations.push_back(isa<MemberExpr>(BE) ? nullptr 17029 : CurDeclaration); 17030 } 17031 } 17032 17033 OMPClause *Sema::ActOnOpenMPMapClause( 17034 ArrayRef<OpenMPMapModifierKind> MapTypeModifiers, 17035 ArrayRef<SourceLocation> MapTypeModifiersLoc, 17036 CXXScopeSpec &MapperIdScopeSpec, DeclarationNameInfo &MapperId, 17037 OpenMPMapClauseKind MapType, bool IsMapTypeImplicit, SourceLocation MapLoc, 17038 SourceLocation ColonLoc, ArrayRef<Expr *> VarList, 17039 const OMPVarListLocTy &Locs, ArrayRef<Expr *> UnresolvedMappers) { 17040 OpenMPMapModifierKind Modifiers[] = {OMPC_MAP_MODIFIER_unknown, 17041 OMPC_MAP_MODIFIER_unknown, 17042 OMPC_MAP_MODIFIER_unknown}; 17043 SourceLocation ModifiersLoc[OMPMapClause::NumberOfModifiers]; 17044 17045 // Process map-type-modifiers, flag errors for duplicate modifiers. 17046 unsigned Count = 0; 17047 for (unsigned I = 0, E = MapTypeModifiers.size(); I < E; ++I) { 17048 if (MapTypeModifiers[I] != OMPC_MAP_MODIFIER_unknown && 17049 llvm::find(Modifiers, MapTypeModifiers[I]) != std::end(Modifiers)) { 17050 Diag(MapTypeModifiersLoc[I], diag::err_omp_duplicate_map_type_modifier); 17051 continue; 17052 } 17053 assert(Count < OMPMapClause::NumberOfModifiers && 17054 "Modifiers exceed the allowed number of map type modifiers"); 17055 Modifiers[Count] = MapTypeModifiers[I]; 17056 ModifiersLoc[Count] = MapTypeModifiersLoc[I]; 17057 ++Count; 17058 } 17059 17060 MappableVarListInfo MVLI(VarList); 17061 checkMappableExpressionList(*this, DSAStack, OMPC_map, MVLI, Locs.StartLoc, 17062 MapperIdScopeSpec, MapperId, UnresolvedMappers, 17063 MapType, IsMapTypeImplicit); 17064 17065 // We need to produce a map clause even if we don't have variables so that 17066 // other diagnostics related with non-existing map clauses are accurate. 17067 return OMPMapClause::Create(Context, Locs, MVLI.ProcessedVarList, 17068 MVLI.VarBaseDeclarations, MVLI.VarComponents, 17069 MVLI.UDMapperList, Modifiers, ModifiersLoc, 17070 MapperIdScopeSpec.getWithLocInContext(Context), 17071 MapperId, MapType, IsMapTypeImplicit, MapLoc); 17072 } 17073 17074 QualType Sema::ActOnOpenMPDeclareReductionType(SourceLocation TyLoc, 17075 TypeResult ParsedType) { 17076 assert(ParsedType.isUsable()); 17077 17078 QualType ReductionType = GetTypeFromParser(ParsedType.get()); 17079 if (ReductionType.isNull()) 17080 return QualType(); 17081 17082 // [OpenMP 4.0], 2.15 declare reduction Directive, Restrictions, C\C++ 17083 // A type name in a declare reduction directive cannot be a function type, an 17084 // array type, a reference type, or a type qualified with const, volatile or 17085 // restrict. 17086 if (ReductionType.hasQualifiers()) { 17087 Diag(TyLoc, diag::err_omp_reduction_wrong_type) << 0; 17088 return QualType(); 17089 } 17090 17091 if (ReductionType->isFunctionType()) { 17092 Diag(TyLoc, diag::err_omp_reduction_wrong_type) << 1; 17093 return QualType(); 17094 } 17095 if (ReductionType->isReferenceType()) { 17096 Diag(TyLoc, diag::err_omp_reduction_wrong_type) << 2; 17097 return QualType(); 17098 } 17099 if (ReductionType->isArrayType()) { 17100 Diag(TyLoc, diag::err_omp_reduction_wrong_type) << 3; 17101 return QualType(); 17102 } 17103 return ReductionType; 17104 } 17105 17106 Sema::DeclGroupPtrTy Sema::ActOnOpenMPDeclareReductionDirectiveStart( 17107 Scope *S, DeclContext *DC, DeclarationName Name, 17108 ArrayRef<std::pair<QualType, SourceLocation>> ReductionTypes, 17109 AccessSpecifier AS, Decl *PrevDeclInScope) { 17110 SmallVector<Decl *, 8> Decls; 17111 Decls.reserve(ReductionTypes.size()); 17112 17113 LookupResult Lookup(*this, Name, SourceLocation(), LookupOMPReductionName, 17114 forRedeclarationInCurContext()); 17115 // [OpenMP 4.0], 2.15 declare reduction Directive, Restrictions 17116 // A reduction-identifier may not be re-declared in the current scope for the 17117 // same type or for a type that is compatible according to the base language 17118 // rules. 17119 llvm::DenseMap<QualType, SourceLocation> PreviousRedeclTypes; 17120 OMPDeclareReductionDecl *PrevDRD = nullptr; 17121 bool InCompoundScope = true; 17122 if (S != nullptr) { 17123 // Find previous declaration with the same name not referenced in other 17124 // declarations. 17125 FunctionScopeInfo *ParentFn = getEnclosingFunction(); 17126 InCompoundScope = 17127 (ParentFn != nullptr) && !ParentFn->CompoundScopes.empty(); 17128 LookupName(Lookup, S); 17129 FilterLookupForScope(Lookup, DC, S, /*ConsiderLinkage=*/false, 17130 /*AllowInlineNamespace=*/false); 17131 llvm::DenseMap<OMPDeclareReductionDecl *, bool> UsedAsPrevious; 17132 LookupResult::Filter Filter = Lookup.makeFilter(); 17133 while (Filter.hasNext()) { 17134 auto *PrevDecl = cast<OMPDeclareReductionDecl>(Filter.next()); 17135 if (InCompoundScope) { 17136 auto I = UsedAsPrevious.find(PrevDecl); 17137 if (I == UsedAsPrevious.end()) 17138 UsedAsPrevious[PrevDecl] = false; 17139 if (OMPDeclareReductionDecl *D = PrevDecl->getPrevDeclInScope()) 17140 UsedAsPrevious[D] = true; 17141 } 17142 PreviousRedeclTypes[PrevDecl->getType().getCanonicalType()] = 17143 PrevDecl->getLocation(); 17144 } 17145 Filter.done(); 17146 if (InCompoundScope) { 17147 for (const auto &PrevData : UsedAsPrevious) { 17148 if (!PrevData.second) { 17149 PrevDRD = PrevData.first; 17150 break; 17151 } 17152 } 17153 } 17154 } else if (PrevDeclInScope != nullptr) { 17155 auto *PrevDRDInScope = PrevDRD = 17156 cast<OMPDeclareReductionDecl>(PrevDeclInScope); 17157 do { 17158 PreviousRedeclTypes[PrevDRDInScope->getType().getCanonicalType()] = 17159 PrevDRDInScope->getLocation(); 17160 PrevDRDInScope = PrevDRDInScope->getPrevDeclInScope(); 17161 } while (PrevDRDInScope != nullptr); 17162 } 17163 for (const auto &TyData : ReductionTypes) { 17164 const auto I = PreviousRedeclTypes.find(TyData.first.getCanonicalType()); 17165 bool Invalid = false; 17166 if (I != PreviousRedeclTypes.end()) { 17167 Diag(TyData.second, diag::err_omp_declare_reduction_redefinition) 17168 << TyData.first; 17169 Diag(I->second, diag::note_previous_definition); 17170 Invalid = true; 17171 } 17172 PreviousRedeclTypes[TyData.first.getCanonicalType()] = TyData.second; 17173 auto *DRD = OMPDeclareReductionDecl::Create(Context, DC, TyData.second, 17174 Name, TyData.first, PrevDRD); 17175 DC->addDecl(DRD); 17176 DRD->setAccess(AS); 17177 Decls.push_back(DRD); 17178 if (Invalid) 17179 DRD->setInvalidDecl(); 17180 else 17181 PrevDRD = DRD; 17182 } 17183 17184 return DeclGroupPtrTy::make( 17185 DeclGroupRef::Create(Context, Decls.begin(), Decls.size())); 17186 } 17187 17188 void Sema::ActOnOpenMPDeclareReductionCombinerStart(Scope *S, Decl *D) { 17189 auto *DRD = cast<OMPDeclareReductionDecl>(D); 17190 17191 // Enter new function scope. 17192 PushFunctionScope(); 17193 setFunctionHasBranchProtectedScope(); 17194 getCurFunction()->setHasOMPDeclareReductionCombiner(); 17195 17196 if (S != nullptr) 17197 PushDeclContext(S, DRD); 17198 else 17199 CurContext = DRD; 17200 17201 PushExpressionEvaluationContext( 17202 ExpressionEvaluationContext::PotentiallyEvaluated); 17203 17204 QualType ReductionType = DRD->getType(); 17205 // Create 'T* omp_parm;T omp_in;'. All references to 'omp_in' will 17206 // be replaced by '*omp_parm' during codegen. This required because 'omp_in' 17207 // uses semantics of argument handles by value, but it should be passed by 17208 // reference. C lang does not support references, so pass all parameters as 17209 // pointers. 17210 // Create 'T omp_in;' variable. 17211 VarDecl *OmpInParm = 17212 buildVarDecl(*this, D->getLocation(), ReductionType, "omp_in"); 17213 // Create 'T* omp_parm;T omp_out;'. All references to 'omp_out' will 17214 // be replaced by '*omp_parm' during codegen. This required because 'omp_out' 17215 // uses semantics of argument handles by value, but it should be passed by 17216 // reference. C lang does not support references, so pass all parameters as 17217 // pointers. 17218 // Create 'T omp_out;' variable. 17219 VarDecl *OmpOutParm = 17220 buildVarDecl(*this, D->getLocation(), ReductionType, "omp_out"); 17221 if (S != nullptr) { 17222 PushOnScopeChains(OmpInParm, S); 17223 PushOnScopeChains(OmpOutParm, S); 17224 } else { 17225 DRD->addDecl(OmpInParm); 17226 DRD->addDecl(OmpOutParm); 17227 } 17228 Expr *InE = 17229 ::buildDeclRefExpr(*this, OmpInParm, ReductionType, D->getLocation()); 17230 Expr *OutE = 17231 ::buildDeclRefExpr(*this, OmpOutParm, ReductionType, D->getLocation()); 17232 DRD->setCombinerData(InE, OutE); 17233 } 17234 17235 void Sema::ActOnOpenMPDeclareReductionCombinerEnd(Decl *D, Expr *Combiner) { 17236 auto *DRD = cast<OMPDeclareReductionDecl>(D); 17237 DiscardCleanupsInEvaluationContext(); 17238 PopExpressionEvaluationContext(); 17239 17240 PopDeclContext(); 17241 PopFunctionScopeInfo(); 17242 17243 if (Combiner != nullptr) 17244 DRD->setCombiner(Combiner); 17245 else 17246 DRD->setInvalidDecl(); 17247 } 17248 17249 VarDecl *Sema::ActOnOpenMPDeclareReductionInitializerStart(Scope *S, Decl *D) { 17250 auto *DRD = cast<OMPDeclareReductionDecl>(D); 17251 17252 // Enter new function scope. 17253 PushFunctionScope(); 17254 setFunctionHasBranchProtectedScope(); 17255 17256 if (S != nullptr) 17257 PushDeclContext(S, DRD); 17258 else 17259 CurContext = DRD; 17260 17261 PushExpressionEvaluationContext( 17262 ExpressionEvaluationContext::PotentiallyEvaluated); 17263 17264 QualType ReductionType = DRD->getType(); 17265 // Create 'T* omp_parm;T omp_priv;'. All references to 'omp_priv' will 17266 // be replaced by '*omp_parm' during codegen. This required because 'omp_priv' 17267 // uses semantics of argument handles by value, but it should be passed by 17268 // reference. C lang does not support references, so pass all parameters as 17269 // pointers. 17270 // Create 'T omp_priv;' variable. 17271 VarDecl *OmpPrivParm = 17272 buildVarDecl(*this, D->getLocation(), ReductionType, "omp_priv"); 17273 // Create 'T* omp_parm;T omp_orig;'. All references to 'omp_orig' will 17274 // be replaced by '*omp_parm' during codegen. This required because 'omp_orig' 17275 // uses semantics of argument handles by value, but it should be passed by 17276 // reference. C lang does not support references, so pass all parameters as 17277 // pointers. 17278 // Create 'T omp_orig;' variable. 17279 VarDecl *OmpOrigParm = 17280 buildVarDecl(*this, D->getLocation(), ReductionType, "omp_orig"); 17281 if (S != nullptr) { 17282 PushOnScopeChains(OmpPrivParm, S); 17283 PushOnScopeChains(OmpOrigParm, S); 17284 } else { 17285 DRD->addDecl(OmpPrivParm); 17286 DRD->addDecl(OmpOrigParm); 17287 } 17288 Expr *OrigE = 17289 ::buildDeclRefExpr(*this, OmpOrigParm, ReductionType, D->getLocation()); 17290 Expr *PrivE = 17291 ::buildDeclRefExpr(*this, OmpPrivParm, ReductionType, D->getLocation()); 17292 DRD->setInitializerData(OrigE, PrivE); 17293 return OmpPrivParm; 17294 } 17295 17296 void Sema::ActOnOpenMPDeclareReductionInitializerEnd(Decl *D, Expr *Initializer, 17297 VarDecl *OmpPrivParm) { 17298 auto *DRD = cast<OMPDeclareReductionDecl>(D); 17299 DiscardCleanupsInEvaluationContext(); 17300 PopExpressionEvaluationContext(); 17301 17302 PopDeclContext(); 17303 PopFunctionScopeInfo(); 17304 17305 if (Initializer != nullptr) { 17306 DRD->setInitializer(Initializer, OMPDeclareReductionDecl::CallInit); 17307 } else if (OmpPrivParm->hasInit()) { 17308 DRD->setInitializer(OmpPrivParm->getInit(), 17309 OmpPrivParm->isDirectInit() 17310 ? OMPDeclareReductionDecl::DirectInit 17311 : OMPDeclareReductionDecl::CopyInit); 17312 } else { 17313 DRD->setInvalidDecl(); 17314 } 17315 } 17316 17317 Sema::DeclGroupPtrTy Sema::ActOnOpenMPDeclareReductionDirectiveEnd( 17318 Scope *S, DeclGroupPtrTy DeclReductions, bool IsValid) { 17319 for (Decl *D : DeclReductions.get()) { 17320 if (IsValid) { 17321 if (S) 17322 PushOnScopeChains(cast<OMPDeclareReductionDecl>(D), S, 17323 /*AddToContext=*/false); 17324 } else { 17325 D->setInvalidDecl(); 17326 } 17327 } 17328 return DeclReductions; 17329 } 17330 17331 TypeResult Sema::ActOnOpenMPDeclareMapperVarDecl(Scope *S, Declarator &D) { 17332 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); 17333 QualType T = TInfo->getType(); 17334 if (D.isInvalidType()) 17335 return true; 17336 17337 if (getLangOpts().CPlusPlus) { 17338 // Check that there are no default arguments (C++ only). 17339 CheckExtraCXXDefaultArguments(D); 17340 } 17341 17342 return CreateParsedType(T, TInfo); 17343 } 17344 17345 QualType Sema::ActOnOpenMPDeclareMapperType(SourceLocation TyLoc, 17346 TypeResult ParsedType) { 17347 assert(ParsedType.isUsable() && "Expect usable parsed mapper type"); 17348 17349 QualType MapperType = GetTypeFromParser(ParsedType.get()); 17350 assert(!MapperType.isNull() && "Expect valid mapper type"); 17351 17352 // [OpenMP 5.0], 2.19.7.3 declare mapper Directive, Restrictions 17353 // The type must be of struct, union or class type in C and C++ 17354 if (!MapperType->isStructureOrClassType() && !MapperType->isUnionType()) { 17355 Diag(TyLoc, diag::err_omp_mapper_wrong_type); 17356 return QualType(); 17357 } 17358 return MapperType; 17359 } 17360 17361 OMPDeclareMapperDecl *Sema::ActOnOpenMPDeclareMapperDirectiveStart( 17362 Scope *S, DeclContext *DC, DeclarationName Name, QualType MapperType, 17363 SourceLocation StartLoc, DeclarationName VN, AccessSpecifier AS, 17364 Decl *PrevDeclInScope) { 17365 LookupResult Lookup(*this, Name, SourceLocation(), LookupOMPMapperName, 17366 forRedeclarationInCurContext()); 17367 // [OpenMP 5.0], 2.19.7.3 declare mapper Directive, Restrictions 17368 // A mapper-identifier may not be redeclared in the current scope for the 17369 // same type or for a type that is compatible according to the base language 17370 // rules. 17371 llvm::DenseMap<QualType, SourceLocation> PreviousRedeclTypes; 17372 OMPDeclareMapperDecl *PrevDMD = nullptr; 17373 bool InCompoundScope = true; 17374 if (S != nullptr) { 17375 // Find previous declaration with the same name not referenced in other 17376 // declarations. 17377 FunctionScopeInfo *ParentFn = getEnclosingFunction(); 17378 InCompoundScope = 17379 (ParentFn != nullptr) && !ParentFn->CompoundScopes.empty(); 17380 LookupName(Lookup, S); 17381 FilterLookupForScope(Lookup, DC, S, /*ConsiderLinkage=*/false, 17382 /*AllowInlineNamespace=*/false); 17383 llvm::DenseMap<OMPDeclareMapperDecl *, bool> UsedAsPrevious; 17384 LookupResult::Filter Filter = Lookup.makeFilter(); 17385 while (Filter.hasNext()) { 17386 auto *PrevDecl = cast<OMPDeclareMapperDecl>(Filter.next()); 17387 if (InCompoundScope) { 17388 auto I = UsedAsPrevious.find(PrevDecl); 17389 if (I == UsedAsPrevious.end()) 17390 UsedAsPrevious[PrevDecl] = false; 17391 if (OMPDeclareMapperDecl *D = PrevDecl->getPrevDeclInScope()) 17392 UsedAsPrevious[D] = true; 17393 } 17394 PreviousRedeclTypes[PrevDecl->getType().getCanonicalType()] = 17395 PrevDecl->getLocation(); 17396 } 17397 Filter.done(); 17398 if (InCompoundScope) { 17399 for (const auto &PrevData : UsedAsPrevious) { 17400 if (!PrevData.second) { 17401 PrevDMD = PrevData.first; 17402 break; 17403 } 17404 } 17405 } 17406 } else if (PrevDeclInScope) { 17407 auto *PrevDMDInScope = PrevDMD = 17408 cast<OMPDeclareMapperDecl>(PrevDeclInScope); 17409 do { 17410 PreviousRedeclTypes[PrevDMDInScope->getType().getCanonicalType()] = 17411 PrevDMDInScope->getLocation(); 17412 PrevDMDInScope = PrevDMDInScope->getPrevDeclInScope(); 17413 } while (PrevDMDInScope != nullptr); 17414 } 17415 const auto I = PreviousRedeclTypes.find(MapperType.getCanonicalType()); 17416 bool Invalid = false; 17417 if (I != PreviousRedeclTypes.end()) { 17418 Diag(StartLoc, diag::err_omp_declare_mapper_redefinition) 17419 << MapperType << Name; 17420 Diag(I->second, diag::note_previous_definition); 17421 Invalid = true; 17422 } 17423 auto *DMD = OMPDeclareMapperDecl::Create(Context, DC, StartLoc, Name, 17424 MapperType, VN, PrevDMD); 17425 DC->addDecl(DMD); 17426 DMD->setAccess(AS); 17427 if (Invalid) 17428 DMD->setInvalidDecl(); 17429 17430 // Enter new function scope. 17431 PushFunctionScope(); 17432 setFunctionHasBranchProtectedScope(); 17433 17434 CurContext = DMD; 17435 17436 return DMD; 17437 } 17438 17439 void Sema::ActOnOpenMPDeclareMapperDirectiveVarDecl(OMPDeclareMapperDecl *DMD, 17440 Scope *S, 17441 QualType MapperType, 17442 SourceLocation StartLoc, 17443 DeclarationName VN) { 17444 VarDecl *VD = buildVarDecl(*this, StartLoc, MapperType, VN.getAsString()); 17445 if (S) 17446 PushOnScopeChains(VD, S); 17447 else 17448 DMD->addDecl(VD); 17449 Expr *MapperVarRefExpr = buildDeclRefExpr(*this, VD, MapperType, StartLoc); 17450 DMD->setMapperVarRef(MapperVarRefExpr); 17451 } 17452 17453 Sema::DeclGroupPtrTy 17454 Sema::ActOnOpenMPDeclareMapperDirectiveEnd(OMPDeclareMapperDecl *D, Scope *S, 17455 ArrayRef<OMPClause *> ClauseList) { 17456 PopDeclContext(); 17457 PopFunctionScopeInfo(); 17458 17459 if (D) { 17460 if (S) 17461 PushOnScopeChains(D, S, /*AddToContext=*/false); 17462 D->CreateClauses(Context, ClauseList); 17463 } 17464 17465 return DeclGroupPtrTy::make(DeclGroupRef(D)); 17466 } 17467 17468 OMPClause *Sema::ActOnOpenMPNumTeamsClause(Expr *NumTeams, 17469 SourceLocation StartLoc, 17470 SourceLocation LParenLoc, 17471 SourceLocation EndLoc) { 17472 Expr *ValExpr = NumTeams; 17473 Stmt *HelperValStmt = nullptr; 17474 17475 // OpenMP [teams Constrcut, Restrictions] 17476 // The num_teams expression must evaluate to a positive integer value. 17477 if (!isNonNegativeIntegerValue(ValExpr, *this, OMPC_num_teams, 17478 /*StrictlyPositive=*/true)) 17479 return nullptr; 17480 17481 OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective(); 17482 OpenMPDirectiveKind CaptureRegion = 17483 getOpenMPCaptureRegionForClause(DKind, OMPC_num_teams, LangOpts.OpenMP); 17484 if (CaptureRegion != OMPD_unknown && !CurContext->isDependentContext()) { 17485 ValExpr = MakeFullExpr(ValExpr).get(); 17486 llvm::MapVector<const Expr *, DeclRefExpr *> Captures; 17487 ValExpr = tryBuildCapture(*this, ValExpr, Captures).get(); 17488 HelperValStmt = buildPreInits(Context, Captures); 17489 } 17490 17491 return new (Context) OMPNumTeamsClause(ValExpr, HelperValStmt, CaptureRegion, 17492 StartLoc, LParenLoc, EndLoc); 17493 } 17494 17495 OMPClause *Sema::ActOnOpenMPThreadLimitClause(Expr *ThreadLimit, 17496 SourceLocation StartLoc, 17497 SourceLocation LParenLoc, 17498 SourceLocation EndLoc) { 17499 Expr *ValExpr = ThreadLimit; 17500 Stmt *HelperValStmt = nullptr; 17501 17502 // OpenMP [teams Constrcut, Restrictions] 17503 // The thread_limit expression must evaluate to a positive integer value. 17504 if (!isNonNegativeIntegerValue(ValExpr, *this, OMPC_thread_limit, 17505 /*StrictlyPositive=*/true)) 17506 return nullptr; 17507 17508 OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective(); 17509 OpenMPDirectiveKind CaptureRegion = getOpenMPCaptureRegionForClause( 17510 DKind, OMPC_thread_limit, LangOpts.OpenMP); 17511 if (CaptureRegion != OMPD_unknown && !CurContext->isDependentContext()) { 17512 ValExpr = MakeFullExpr(ValExpr).get(); 17513 llvm::MapVector<const Expr *, DeclRefExpr *> Captures; 17514 ValExpr = tryBuildCapture(*this, ValExpr, Captures).get(); 17515 HelperValStmt = buildPreInits(Context, Captures); 17516 } 17517 17518 return new (Context) OMPThreadLimitClause( 17519 ValExpr, HelperValStmt, CaptureRegion, StartLoc, LParenLoc, EndLoc); 17520 } 17521 17522 OMPClause *Sema::ActOnOpenMPPriorityClause(Expr *Priority, 17523 SourceLocation StartLoc, 17524 SourceLocation LParenLoc, 17525 SourceLocation EndLoc) { 17526 Expr *ValExpr = Priority; 17527 Stmt *HelperValStmt = nullptr; 17528 OpenMPDirectiveKind CaptureRegion = OMPD_unknown; 17529 17530 // OpenMP [2.9.1, task Constrcut] 17531 // The priority-value is a non-negative numerical scalar expression. 17532 if (!isNonNegativeIntegerValue( 17533 ValExpr, *this, OMPC_priority, 17534 /*StrictlyPositive=*/false, /*BuildCapture=*/true, 17535 DSAStack->getCurrentDirective(), &CaptureRegion, &HelperValStmt)) 17536 return nullptr; 17537 17538 return new (Context) OMPPriorityClause(ValExpr, HelperValStmt, CaptureRegion, 17539 StartLoc, LParenLoc, EndLoc); 17540 } 17541 17542 OMPClause *Sema::ActOnOpenMPGrainsizeClause(Expr *Grainsize, 17543 SourceLocation StartLoc, 17544 SourceLocation LParenLoc, 17545 SourceLocation EndLoc) { 17546 Expr *ValExpr = Grainsize; 17547 Stmt *HelperValStmt = nullptr; 17548 OpenMPDirectiveKind CaptureRegion = OMPD_unknown; 17549 17550 // OpenMP [2.9.2, taskloop Constrcut] 17551 // The parameter of the grainsize clause must be a positive integer 17552 // expression. 17553 if (!isNonNegativeIntegerValue( 17554 ValExpr, *this, OMPC_grainsize, 17555 /*StrictlyPositive=*/true, /*BuildCapture=*/true, 17556 DSAStack->getCurrentDirective(), &CaptureRegion, &HelperValStmt)) 17557 return nullptr; 17558 17559 return new (Context) OMPGrainsizeClause(ValExpr, HelperValStmt, CaptureRegion, 17560 StartLoc, LParenLoc, EndLoc); 17561 } 17562 17563 OMPClause *Sema::ActOnOpenMPNumTasksClause(Expr *NumTasks, 17564 SourceLocation StartLoc, 17565 SourceLocation LParenLoc, 17566 SourceLocation EndLoc) { 17567 Expr *ValExpr = NumTasks; 17568 Stmt *HelperValStmt = nullptr; 17569 OpenMPDirectiveKind CaptureRegion = OMPD_unknown; 17570 17571 // OpenMP [2.9.2, taskloop Constrcut] 17572 // The parameter of the num_tasks clause must be a positive integer 17573 // expression. 17574 if (!isNonNegativeIntegerValue( 17575 ValExpr, *this, OMPC_num_tasks, 17576 /*StrictlyPositive=*/true, /*BuildCapture=*/true, 17577 DSAStack->getCurrentDirective(), &CaptureRegion, &HelperValStmt)) 17578 return nullptr; 17579 17580 return new (Context) OMPNumTasksClause(ValExpr, HelperValStmt, CaptureRegion, 17581 StartLoc, LParenLoc, EndLoc); 17582 } 17583 17584 OMPClause *Sema::ActOnOpenMPHintClause(Expr *Hint, SourceLocation StartLoc, 17585 SourceLocation LParenLoc, 17586 SourceLocation EndLoc) { 17587 // OpenMP [2.13.2, critical construct, Description] 17588 // ... where hint-expression is an integer constant expression that evaluates 17589 // to a valid lock hint. 17590 ExprResult HintExpr = VerifyPositiveIntegerConstantInClause(Hint, OMPC_hint); 17591 if (HintExpr.isInvalid()) 17592 return nullptr; 17593 return new (Context) 17594 OMPHintClause(HintExpr.get(), StartLoc, LParenLoc, EndLoc); 17595 } 17596 17597 /// Tries to find omp_event_handle_t type. 17598 static bool findOMPEventHandleT(Sema &S, SourceLocation Loc, 17599 DSAStackTy *Stack) { 17600 QualType OMPEventHandleT = Stack->getOMPEventHandleT(); 17601 if (!OMPEventHandleT.isNull()) 17602 return true; 17603 IdentifierInfo *II = &S.PP.getIdentifierTable().get("omp_event_handle_t"); 17604 ParsedType PT = S.getTypeName(*II, Loc, S.getCurScope()); 17605 if (!PT.getAsOpaquePtr() || PT.get().isNull()) { 17606 S.Diag(Loc, diag::err_omp_implied_type_not_found) << "omp_event_handle_t"; 17607 return false; 17608 } 17609 Stack->setOMPEventHandleT(PT.get()); 17610 return true; 17611 } 17612 17613 OMPClause *Sema::ActOnOpenMPDetachClause(Expr *Evt, SourceLocation StartLoc, 17614 SourceLocation LParenLoc, 17615 SourceLocation EndLoc) { 17616 if (!Evt->isValueDependent() && !Evt->isTypeDependent() && 17617 !Evt->isInstantiationDependent() && 17618 !Evt->containsUnexpandedParameterPack()) { 17619 if (!findOMPEventHandleT(*this, Evt->getExprLoc(), DSAStack)) 17620 return nullptr; 17621 // OpenMP 5.0, 2.10.1 task Construct. 17622 // event-handle is a variable of the omp_event_handle_t type. 17623 auto *Ref = dyn_cast<DeclRefExpr>(Evt->IgnoreParenImpCasts()); 17624 if (!Ref) { 17625 Diag(Evt->getExprLoc(), diag::err_omp_event_var_expected) 17626 << 0 << Evt->getSourceRange(); 17627 return nullptr; 17628 } 17629 auto *VD = dyn_cast_or_null<VarDecl>(Ref->getDecl()); 17630 if (!VD) { 17631 Diag(Evt->getExprLoc(), diag::err_omp_event_var_expected) 17632 << 0 << Evt->getSourceRange(); 17633 return nullptr; 17634 } 17635 if (!Context.hasSameUnqualifiedType(DSAStack->getOMPEventHandleT(), 17636 VD->getType()) || 17637 VD->getType().isConstant(Context)) { 17638 Diag(Evt->getExprLoc(), diag::err_omp_event_var_expected) 17639 << 1 << VD->getType() << Evt->getSourceRange(); 17640 return nullptr; 17641 } 17642 // OpenMP 5.0, 2.10.1 task Construct 17643 // [detach clause]... The event-handle will be considered as if it was 17644 // specified on a firstprivate clause. 17645 DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(VD, /*FromParent=*/false); 17646 if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_firstprivate && 17647 DVar.RefExpr) { 17648 Diag(Evt->getExprLoc(), diag::err_omp_wrong_dsa) 17649 << getOpenMPClauseName(DVar.CKind) 17650 << getOpenMPClauseName(OMPC_firstprivate); 17651 reportOriginalDsa(*this, DSAStack, VD, DVar); 17652 return nullptr; 17653 } 17654 } 17655 17656 return new (Context) OMPDetachClause(Evt, StartLoc, LParenLoc, EndLoc); 17657 } 17658 17659 OMPClause *Sema::ActOnOpenMPDistScheduleClause( 17660 OpenMPDistScheduleClauseKind Kind, Expr *ChunkSize, SourceLocation StartLoc, 17661 SourceLocation LParenLoc, SourceLocation KindLoc, SourceLocation CommaLoc, 17662 SourceLocation EndLoc) { 17663 if (Kind == OMPC_DIST_SCHEDULE_unknown) { 17664 std::string Values; 17665 Values += "'"; 17666 Values += getOpenMPSimpleClauseTypeName(OMPC_dist_schedule, 0); 17667 Values += "'"; 17668 Diag(KindLoc, diag::err_omp_unexpected_clause_value) 17669 << Values << getOpenMPClauseName(OMPC_dist_schedule); 17670 return nullptr; 17671 } 17672 Expr *ValExpr = ChunkSize; 17673 Stmt *HelperValStmt = nullptr; 17674 if (ChunkSize) { 17675 if (!ChunkSize->isValueDependent() && !ChunkSize->isTypeDependent() && 17676 !ChunkSize->isInstantiationDependent() && 17677 !ChunkSize->containsUnexpandedParameterPack()) { 17678 SourceLocation ChunkSizeLoc = ChunkSize->getBeginLoc(); 17679 ExprResult Val = 17680 PerformOpenMPImplicitIntegerConversion(ChunkSizeLoc, ChunkSize); 17681 if (Val.isInvalid()) 17682 return nullptr; 17683 17684 ValExpr = Val.get(); 17685 17686 // OpenMP [2.7.1, Restrictions] 17687 // chunk_size must be a loop invariant integer expression with a positive 17688 // value. 17689 llvm::APSInt Result; 17690 if (ValExpr->isIntegerConstantExpr(Result, Context)) { 17691 if (Result.isSigned() && !Result.isStrictlyPositive()) { 17692 Diag(ChunkSizeLoc, diag::err_omp_negative_expression_in_clause) 17693 << "dist_schedule" << ChunkSize->getSourceRange(); 17694 return nullptr; 17695 } 17696 } else if (getOpenMPCaptureRegionForClause( 17697 DSAStack->getCurrentDirective(), OMPC_dist_schedule, 17698 LangOpts.OpenMP) != OMPD_unknown && 17699 !CurContext->isDependentContext()) { 17700 ValExpr = MakeFullExpr(ValExpr).get(); 17701 llvm::MapVector<const Expr *, DeclRefExpr *> Captures; 17702 ValExpr = tryBuildCapture(*this, ValExpr, Captures).get(); 17703 HelperValStmt = buildPreInits(Context, Captures); 17704 } 17705 } 17706 } 17707 17708 return new (Context) 17709 OMPDistScheduleClause(StartLoc, LParenLoc, KindLoc, CommaLoc, EndLoc, 17710 Kind, ValExpr, HelperValStmt); 17711 } 17712 17713 OMPClause *Sema::ActOnOpenMPDefaultmapClause( 17714 OpenMPDefaultmapClauseModifier M, OpenMPDefaultmapClauseKind Kind, 17715 SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation MLoc, 17716 SourceLocation KindLoc, SourceLocation EndLoc) { 17717 if (getLangOpts().OpenMP < 50) { 17718 if (M != OMPC_DEFAULTMAP_MODIFIER_tofrom || 17719 Kind != OMPC_DEFAULTMAP_scalar) { 17720 std::string Value; 17721 SourceLocation Loc; 17722 Value += "'"; 17723 if (M != OMPC_DEFAULTMAP_MODIFIER_tofrom) { 17724 Value += getOpenMPSimpleClauseTypeName(OMPC_defaultmap, 17725 OMPC_DEFAULTMAP_MODIFIER_tofrom); 17726 Loc = MLoc; 17727 } else { 17728 Value += getOpenMPSimpleClauseTypeName(OMPC_defaultmap, 17729 OMPC_DEFAULTMAP_scalar); 17730 Loc = KindLoc; 17731 } 17732 Value += "'"; 17733 Diag(Loc, diag::err_omp_unexpected_clause_value) 17734 << Value << getOpenMPClauseName(OMPC_defaultmap); 17735 return nullptr; 17736 } 17737 } else { 17738 bool isDefaultmapModifier = (M != OMPC_DEFAULTMAP_MODIFIER_unknown); 17739 bool isDefaultmapKind = (Kind != OMPC_DEFAULTMAP_unknown); 17740 if (!isDefaultmapKind || !isDefaultmapModifier) { 17741 std::string ModifierValue = "'alloc', 'from', 'to', 'tofrom', " 17742 "'firstprivate', 'none', 'default'"; 17743 std::string KindValue = "'scalar', 'aggregate', 'pointer'"; 17744 if (!isDefaultmapKind && isDefaultmapModifier) { 17745 Diag(KindLoc, diag::err_omp_unexpected_clause_value) 17746 << KindValue << getOpenMPClauseName(OMPC_defaultmap); 17747 } else if (isDefaultmapKind && !isDefaultmapModifier) { 17748 Diag(MLoc, diag::err_omp_unexpected_clause_value) 17749 << ModifierValue << getOpenMPClauseName(OMPC_defaultmap); 17750 } else { 17751 Diag(MLoc, diag::err_omp_unexpected_clause_value) 17752 << ModifierValue << getOpenMPClauseName(OMPC_defaultmap); 17753 Diag(KindLoc, diag::err_omp_unexpected_clause_value) 17754 << KindValue << getOpenMPClauseName(OMPC_defaultmap); 17755 } 17756 return nullptr; 17757 } 17758 17759 // OpenMP [5.0, 2.12.5, Restrictions, p. 174] 17760 // At most one defaultmap clause for each category can appear on the 17761 // directive. 17762 if (DSAStack->checkDefaultmapCategory(Kind)) { 17763 Diag(StartLoc, diag::err_omp_one_defaultmap_each_category); 17764 return nullptr; 17765 } 17766 } 17767 DSAStack->setDefaultDMAAttr(M, Kind, StartLoc); 17768 17769 return new (Context) 17770 OMPDefaultmapClause(StartLoc, LParenLoc, MLoc, KindLoc, EndLoc, Kind, M); 17771 } 17772 17773 bool Sema::ActOnStartOpenMPDeclareTargetDirective(SourceLocation Loc) { 17774 DeclContext *CurLexicalContext = getCurLexicalContext(); 17775 if (!CurLexicalContext->isFileContext() && 17776 !CurLexicalContext->isExternCContext() && 17777 !CurLexicalContext->isExternCXXContext() && 17778 !isa<CXXRecordDecl>(CurLexicalContext) && 17779 !isa<ClassTemplateDecl>(CurLexicalContext) && 17780 !isa<ClassTemplatePartialSpecializationDecl>(CurLexicalContext) && 17781 !isa<ClassTemplateSpecializationDecl>(CurLexicalContext)) { 17782 Diag(Loc, diag::err_omp_region_not_file_context); 17783 return false; 17784 } 17785 ++DeclareTargetNestingLevel; 17786 return true; 17787 } 17788 17789 void Sema::ActOnFinishOpenMPDeclareTargetDirective() { 17790 assert(DeclareTargetNestingLevel > 0 && 17791 "Unexpected ActOnFinishOpenMPDeclareTargetDirective"); 17792 --DeclareTargetNestingLevel; 17793 } 17794 17795 NamedDecl * 17796 Sema::lookupOpenMPDeclareTargetName(Scope *CurScope, CXXScopeSpec &ScopeSpec, 17797 const DeclarationNameInfo &Id, 17798 NamedDeclSetType &SameDirectiveDecls) { 17799 LookupResult Lookup(*this, Id, LookupOrdinaryName); 17800 LookupParsedName(Lookup, CurScope, &ScopeSpec, true); 17801 17802 if (Lookup.isAmbiguous()) 17803 return nullptr; 17804 Lookup.suppressDiagnostics(); 17805 17806 if (!Lookup.isSingleResult()) { 17807 VarOrFuncDeclFilterCCC CCC(*this); 17808 if (TypoCorrection Corrected = 17809 CorrectTypo(Id, LookupOrdinaryName, CurScope, nullptr, CCC, 17810 CTK_ErrorRecovery)) { 17811 diagnoseTypo(Corrected, PDiag(diag::err_undeclared_var_use_suggest) 17812 << Id.getName()); 17813 checkDeclIsAllowedInOpenMPTarget(nullptr, Corrected.getCorrectionDecl()); 17814 return nullptr; 17815 } 17816 17817 Diag(Id.getLoc(), diag::err_undeclared_var_use) << Id.getName(); 17818 return nullptr; 17819 } 17820 17821 NamedDecl *ND = Lookup.getAsSingle<NamedDecl>(); 17822 if (!isa<VarDecl>(ND) && !isa<FunctionDecl>(ND) && 17823 !isa<FunctionTemplateDecl>(ND)) { 17824 Diag(Id.getLoc(), diag::err_omp_invalid_target_decl) << Id.getName(); 17825 return nullptr; 17826 } 17827 if (!SameDirectiveDecls.insert(cast<NamedDecl>(ND->getCanonicalDecl()))) 17828 Diag(Id.getLoc(), diag::err_omp_declare_target_multiple) << Id.getName(); 17829 return ND; 17830 } 17831 17832 void Sema::ActOnOpenMPDeclareTargetName( 17833 NamedDecl *ND, SourceLocation Loc, OMPDeclareTargetDeclAttr::MapTypeTy MT, 17834 OMPDeclareTargetDeclAttr::DevTypeTy DT) { 17835 assert((isa<VarDecl>(ND) || isa<FunctionDecl>(ND) || 17836 isa<FunctionTemplateDecl>(ND)) && 17837 "Expected variable, function or function template."); 17838 17839 // Diagnose marking after use as it may lead to incorrect diagnosis and 17840 // codegen. 17841 if (LangOpts.OpenMP >= 50 && 17842 (ND->isUsed(/*CheckUsedAttr=*/false) || ND->isReferenced())) 17843 Diag(Loc, diag::warn_omp_declare_target_after_first_use); 17844 17845 Optional<OMPDeclareTargetDeclAttr::DevTypeTy> DevTy = 17846 OMPDeclareTargetDeclAttr::getDeviceType(cast<ValueDecl>(ND)); 17847 if (DevTy.hasValue() && *DevTy != DT) { 17848 Diag(Loc, diag::err_omp_device_type_mismatch) 17849 << OMPDeclareTargetDeclAttr::ConvertDevTypeTyToStr(DT) 17850 << OMPDeclareTargetDeclAttr::ConvertDevTypeTyToStr(*DevTy); 17851 return; 17852 } 17853 Optional<OMPDeclareTargetDeclAttr::MapTypeTy> Res = 17854 OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(cast<ValueDecl>(ND)); 17855 if (!Res) { 17856 auto *A = OMPDeclareTargetDeclAttr::CreateImplicit(Context, MT, DT, 17857 SourceRange(Loc, Loc)); 17858 ND->addAttr(A); 17859 if (ASTMutationListener *ML = Context.getASTMutationListener()) 17860 ML->DeclarationMarkedOpenMPDeclareTarget(ND, A); 17861 checkDeclIsAllowedInOpenMPTarget(nullptr, ND, Loc); 17862 } else if (*Res != MT) { 17863 Diag(Loc, diag::err_omp_declare_target_to_and_link) << ND; 17864 } 17865 } 17866 17867 static void checkDeclInTargetContext(SourceLocation SL, SourceRange SR, 17868 Sema &SemaRef, Decl *D) { 17869 if (!D || !isa<VarDecl>(D)) 17870 return; 17871 auto *VD = cast<VarDecl>(D); 17872 Optional<OMPDeclareTargetDeclAttr::MapTypeTy> MapTy = 17873 OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD); 17874 if (SemaRef.LangOpts.OpenMP >= 50 && 17875 (SemaRef.getCurLambda(/*IgnoreNonLambdaCapturingScope=*/true) || 17876 SemaRef.getCurBlock() || SemaRef.getCurCapturedRegion()) && 17877 VD->hasGlobalStorage()) { 17878 llvm::Optional<OMPDeclareTargetDeclAttr::MapTypeTy> MapTy = 17879 OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD); 17880 if (!MapTy || *MapTy != OMPDeclareTargetDeclAttr::MT_To) { 17881 // OpenMP 5.0, 2.12.7 declare target Directive, Restrictions 17882 // If a lambda declaration and definition appears between a 17883 // declare target directive and the matching end declare target 17884 // directive, all variables that are captured by the lambda 17885 // expression must also appear in a to clause. 17886 SemaRef.Diag(VD->getLocation(), 17887 diag::err_omp_lambda_capture_in_declare_target_not_to); 17888 SemaRef.Diag(SL, diag::note_var_explicitly_captured_here) 17889 << VD << 0 << SR; 17890 return; 17891 } 17892 } 17893 if (MapTy.hasValue()) 17894 return; 17895 SemaRef.Diag(VD->getLocation(), diag::warn_omp_not_in_target_context); 17896 SemaRef.Diag(SL, diag::note_used_here) << SR; 17897 } 17898 17899 static bool checkValueDeclInTarget(SourceLocation SL, SourceRange SR, 17900 Sema &SemaRef, DSAStackTy *Stack, 17901 ValueDecl *VD) { 17902 return OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD) || 17903 checkTypeMappable(SL, SR, SemaRef, Stack, VD->getType(), 17904 /*FullCheck=*/false); 17905 } 17906 17907 void Sema::checkDeclIsAllowedInOpenMPTarget(Expr *E, Decl *D, 17908 SourceLocation IdLoc) { 17909 if (!D || D->isInvalidDecl()) 17910 return; 17911 SourceRange SR = E ? E->getSourceRange() : D->getSourceRange(); 17912 SourceLocation SL = E ? E->getBeginLoc() : D->getLocation(); 17913 if (auto *VD = dyn_cast<VarDecl>(D)) { 17914 // Only global variables can be marked as declare target. 17915 if (!VD->isFileVarDecl() && !VD->isStaticLocal() && 17916 !VD->isStaticDataMember()) 17917 return; 17918 // 2.10.6: threadprivate variable cannot appear in a declare target 17919 // directive. 17920 if (DSAStack->isThreadPrivate(VD)) { 17921 Diag(SL, diag::err_omp_threadprivate_in_target); 17922 reportOriginalDsa(*this, DSAStack, VD, DSAStack->getTopDSA(VD, false)); 17923 return; 17924 } 17925 } 17926 if (const auto *FTD = dyn_cast<FunctionTemplateDecl>(D)) 17927 D = FTD->getTemplatedDecl(); 17928 if (auto *FD = dyn_cast<FunctionDecl>(D)) { 17929 llvm::Optional<OMPDeclareTargetDeclAttr::MapTypeTy> Res = 17930 OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(FD); 17931 if (IdLoc.isValid() && Res && *Res == OMPDeclareTargetDeclAttr::MT_Link) { 17932 Diag(IdLoc, diag::err_omp_function_in_link_clause); 17933 Diag(FD->getLocation(), diag::note_defined_here) << FD; 17934 return; 17935 } 17936 } 17937 if (auto *VD = dyn_cast<ValueDecl>(D)) { 17938 // Problem if any with var declared with incomplete type will be reported 17939 // as normal, so no need to check it here. 17940 if ((E || !VD->getType()->isIncompleteType()) && 17941 !checkValueDeclInTarget(SL, SR, *this, DSAStack, VD)) 17942 return; 17943 if (!E && !OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD)) { 17944 // Checking declaration inside declare target region. 17945 if (isa<VarDecl>(D) || isa<FunctionDecl>(D) || 17946 isa<FunctionTemplateDecl>(D)) { 17947 auto *A = OMPDeclareTargetDeclAttr::CreateImplicit( 17948 Context, OMPDeclareTargetDeclAttr::MT_To, 17949 OMPDeclareTargetDeclAttr::DT_Any, SourceRange(IdLoc, IdLoc)); 17950 D->addAttr(A); 17951 if (ASTMutationListener *ML = Context.getASTMutationListener()) 17952 ML->DeclarationMarkedOpenMPDeclareTarget(D, A); 17953 } 17954 return; 17955 } 17956 } 17957 if (!E) 17958 return; 17959 checkDeclInTargetContext(E->getExprLoc(), E->getSourceRange(), *this, D); 17960 } 17961 17962 OMPClause *Sema::ActOnOpenMPToClause(ArrayRef<Expr *> VarList, 17963 CXXScopeSpec &MapperIdScopeSpec, 17964 DeclarationNameInfo &MapperId, 17965 const OMPVarListLocTy &Locs, 17966 ArrayRef<Expr *> UnresolvedMappers) { 17967 MappableVarListInfo MVLI(VarList); 17968 checkMappableExpressionList(*this, DSAStack, OMPC_to, MVLI, Locs.StartLoc, 17969 MapperIdScopeSpec, MapperId, UnresolvedMappers); 17970 if (MVLI.ProcessedVarList.empty()) 17971 return nullptr; 17972 17973 return OMPToClause::Create( 17974 Context, Locs, MVLI.ProcessedVarList, MVLI.VarBaseDeclarations, 17975 MVLI.VarComponents, MVLI.UDMapperList, 17976 MapperIdScopeSpec.getWithLocInContext(Context), MapperId); 17977 } 17978 17979 OMPClause *Sema::ActOnOpenMPFromClause(ArrayRef<Expr *> VarList, 17980 CXXScopeSpec &MapperIdScopeSpec, 17981 DeclarationNameInfo &MapperId, 17982 const OMPVarListLocTy &Locs, 17983 ArrayRef<Expr *> UnresolvedMappers) { 17984 MappableVarListInfo MVLI(VarList); 17985 checkMappableExpressionList(*this, DSAStack, OMPC_from, MVLI, Locs.StartLoc, 17986 MapperIdScopeSpec, MapperId, UnresolvedMappers); 17987 if (MVLI.ProcessedVarList.empty()) 17988 return nullptr; 17989 17990 return OMPFromClause::Create( 17991 Context, Locs, MVLI.ProcessedVarList, MVLI.VarBaseDeclarations, 17992 MVLI.VarComponents, MVLI.UDMapperList, 17993 MapperIdScopeSpec.getWithLocInContext(Context), MapperId); 17994 } 17995 17996 OMPClause *Sema::ActOnOpenMPUseDevicePtrClause(ArrayRef<Expr *> VarList, 17997 const OMPVarListLocTy &Locs) { 17998 MappableVarListInfo MVLI(VarList); 17999 SmallVector<Expr *, 8> PrivateCopies; 18000 SmallVector<Expr *, 8> Inits; 18001 18002 for (Expr *RefExpr : VarList) { 18003 assert(RefExpr && "NULL expr in OpenMP use_device_ptr clause."); 18004 SourceLocation ELoc; 18005 SourceRange ERange; 18006 Expr *SimpleRefExpr = RefExpr; 18007 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange); 18008 if (Res.second) { 18009 // It will be analyzed later. 18010 MVLI.ProcessedVarList.push_back(RefExpr); 18011 PrivateCopies.push_back(nullptr); 18012 Inits.push_back(nullptr); 18013 } 18014 ValueDecl *D = Res.first; 18015 if (!D) 18016 continue; 18017 18018 QualType Type = D->getType(); 18019 Type = Type.getNonReferenceType().getUnqualifiedType(); 18020 18021 auto *VD = dyn_cast<VarDecl>(D); 18022 18023 // Item should be a pointer or reference to pointer. 18024 if (!Type->isPointerType()) { 18025 Diag(ELoc, diag::err_omp_usedeviceptr_not_a_pointer) 18026 << 0 << RefExpr->getSourceRange(); 18027 continue; 18028 } 18029 18030 // Build the private variable and the expression that refers to it. 18031 auto VDPrivate = 18032 buildVarDecl(*this, ELoc, Type, D->getName(), 18033 D->hasAttrs() ? &D->getAttrs() : nullptr, 18034 VD ? cast<DeclRefExpr>(SimpleRefExpr) : nullptr); 18035 if (VDPrivate->isInvalidDecl()) 18036 continue; 18037 18038 CurContext->addDecl(VDPrivate); 18039 DeclRefExpr *VDPrivateRefExpr = buildDeclRefExpr( 18040 *this, VDPrivate, RefExpr->getType().getUnqualifiedType(), ELoc); 18041 18042 // Add temporary variable to initialize the private copy of the pointer. 18043 VarDecl *VDInit = 18044 buildVarDecl(*this, RefExpr->getExprLoc(), Type, ".devptr.temp"); 18045 DeclRefExpr *VDInitRefExpr = buildDeclRefExpr( 18046 *this, VDInit, RefExpr->getType(), RefExpr->getExprLoc()); 18047 AddInitializerToDecl(VDPrivate, 18048 DefaultLvalueConversion(VDInitRefExpr).get(), 18049 /*DirectInit=*/false); 18050 18051 // If required, build a capture to implement the privatization initialized 18052 // with the current list item value. 18053 DeclRefExpr *Ref = nullptr; 18054 if (!VD) 18055 Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/true); 18056 MVLI.ProcessedVarList.push_back(VD ? RefExpr->IgnoreParens() : Ref); 18057 PrivateCopies.push_back(VDPrivateRefExpr); 18058 Inits.push_back(VDInitRefExpr); 18059 18060 // We need to add a data sharing attribute for this variable to make sure it 18061 // is correctly captured. A variable that shows up in a use_device_ptr has 18062 // similar properties of a first private variable. 18063 DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_firstprivate, Ref); 18064 18065 // Create a mappable component for the list item. List items in this clause 18066 // only need a component. 18067 MVLI.VarBaseDeclarations.push_back(D); 18068 MVLI.VarComponents.resize(MVLI.VarComponents.size() + 1); 18069 MVLI.VarComponents.back().push_back( 18070 OMPClauseMappableExprCommon::MappableComponent(SimpleRefExpr, D)); 18071 } 18072 18073 if (MVLI.ProcessedVarList.empty()) 18074 return nullptr; 18075 18076 return OMPUseDevicePtrClause::Create( 18077 Context, Locs, MVLI.ProcessedVarList, PrivateCopies, Inits, 18078 MVLI.VarBaseDeclarations, MVLI.VarComponents); 18079 } 18080 18081 OMPClause *Sema::ActOnOpenMPIsDevicePtrClause(ArrayRef<Expr *> VarList, 18082 const OMPVarListLocTy &Locs) { 18083 MappableVarListInfo MVLI(VarList); 18084 for (Expr *RefExpr : VarList) { 18085 assert(RefExpr && "NULL expr in OpenMP is_device_ptr clause."); 18086 SourceLocation ELoc; 18087 SourceRange ERange; 18088 Expr *SimpleRefExpr = RefExpr; 18089 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange); 18090 if (Res.second) { 18091 // It will be analyzed later. 18092 MVLI.ProcessedVarList.push_back(RefExpr); 18093 } 18094 ValueDecl *D = Res.first; 18095 if (!D) 18096 continue; 18097 18098 QualType Type = D->getType(); 18099 // item should be a pointer or array or reference to pointer or array 18100 if (!Type.getNonReferenceType()->isPointerType() && 18101 !Type.getNonReferenceType()->isArrayType()) { 18102 Diag(ELoc, diag::err_omp_argument_type_isdeviceptr) 18103 << 0 << RefExpr->getSourceRange(); 18104 continue; 18105 } 18106 18107 // Check if the declaration in the clause does not show up in any data 18108 // sharing attribute. 18109 DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, /*FromParent=*/false); 18110 if (isOpenMPPrivate(DVar.CKind)) { 18111 Diag(ELoc, diag::err_omp_variable_in_given_clause_and_dsa) 18112 << getOpenMPClauseName(DVar.CKind) 18113 << getOpenMPClauseName(OMPC_is_device_ptr) 18114 << getOpenMPDirectiveName(DSAStack->getCurrentDirective()); 18115 reportOriginalDsa(*this, DSAStack, D, DVar); 18116 continue; 18117 } 18118 18119 const Expr *ConflictExpr; 18120 if (DSAStack->checkMappableExprComponentListsForDecl( 18121 D, /*CurrentRegionOnly=*/true, 18122 [&ConflictExpr]( 18123 OMPClauseMappableExprCommon::MappableExprComponentListRef R, 18124 OpenMPClauseKind) -> bool { 18125 ConflictExpr = R.front().getAssociatedExpression(); 18126 return true; 18127 })) { 18128 Diag(ELoc, diag::err_omp_map_shared_storage) << RefExpr->getSourceRange(); 18129 Diag(ConflictExpr->getExprLoc(), diag::note_used_here) 18130 << ConflictExpr->getSourceRange(); 18131 continue; 18132 } 18133 18134 // Store the components in the stack so that they can be used to check 18135 // against other clauses later on. 18136 OMPClauseMappableExprCommon::MappableComponent MC(SimpleRefExpr, D); 18137 DSAStack->addMappableExpressionComponents( 18138 D, MC, /*WhereFoundClauseKind=*/OMPC_is_device_ptr); 18139 18140 // Record the expression we've just processed. 18141 MVLI.ProcessedVarList.push_back(SimpleRefExpr); 18142 18143 // Create a mappable component for the list item. List items in this clause 18144 // only need a component. We use a null declaration to signal fields in 18145 // 'this'. 18146 assert((isa<DeclRefExpr>(SimpleRefExpr) || 18147 isa<CXXThisExpr>(cast<MemberExpr>(SimpleRefExpr)->getBase())) && 18148 "Unexpected device pointer expression!"); 18149 MVLI.VarBaseDeclarations.push_back( 18150 isa<DeclRefExpr>(SimpleRefExpr) ? D : nullptr); 18151 MVLI.VarComponents.resize(MVLI.VarComponents.size() + 1); 18152 MVLI.VarComponents.back().push_back(MC); 18153 } 18154 18155 if (MVLI.ProcessedVarList.empty()) 18156 return nullptr; 18157 18158 return OMPIsDevicePtrClause::Create(Context, Locs, MVLI.ProcessedVarList, 18159 MVLI.VarBaseDeclarations, 18160 MVLI.VarComponents); 18161 } 18162 18163 OMPClause *Sema::ActOnOpenMPAllocateClause( 18164 Expr *Allocator, ArrayRef<Expr *> VarList, SourceLocation StartLoc, 18165 SourceLocation ColonLoc, SourceLocation LParenLoc, SourceLocation EndLoc) { 18166 if (Allocator) { 18167 // OpenMP [2.11.4 allocate Clause, Description] 18168 // allocator is an expression of omp_allocator_handle_t type. 18169 if (!findOMPAllocatorHandleT(*this, Allocator->getExprLoc(), DSAStack)) 18170 return nullptr; 18171 18172 ExprResult AllocatorRes = DefaultLvalueConversion(Allocator); 18173 if (AllocatorRes.isInvalid()) 18174 return nullptr; 18175 AllocatorRes = PerformImplicitConversion(AllocatorRes.get(), 18176 DSAStack->getOMPAllocatorHandleT(), 18177 Sema::AA_Initializing, 18178 /*AllowExplicit=*/true); 18179 if (AllocatorRes.isInvalid()) 18180 return nullptr; 18181 Allocator = AllocatorRes.get(); 18182 } else { 18183 // OpenMP 5.0, 2.11.4 allocate Clause, Restrictions. 18184 // allocate clauses that appear on a target construct or on constructs in a 18185 // target region must specify an allocator expression unless a requires 18186 // directive with the dynamic_allocators clause is present in the same 18187 // compilation unit. 18188 if (LangOpts.OpenMPIsDevice && 18189 !DSAStack->hasRequiresDeclWithClause<OMPDynamicAllocatorsClause>()) 18190 targetDiag(StartLoc, diag::err_expected_allocator_expression); 18191 } 18192 // Analyze and build list of variables. 18193 SmallVector<Expr *, 8> Vars; 18194 for (Expr *RefExpr : VarList) { 18195 assert(RefExpr && "NULL expr in OpenMP private clause."); 18196 SourceLocation ELoc; 18197 SourceRange ERange; 18198 Expr *SimpleRefExpr = RefExpr; 18199 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange); 18200 if (Res.second) { 18201 // It will be analyzed later. 18202 Vars.push_back(RefExpr); 18203 } 18204 ValueDecl *D = Res.first; 18205 if (!D) 18206 continue; 18207 18208 auto *VD = dyn_cast<VarDecl>(D); 18209 DeclRefExpr *Ref = nullptr; 18210 if (!VD && !CurContext->isDependentContext()) 18211 Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/false); 18212 Vars.push_back((VD || CurContext->isDependentContext()) 18213 ? RefExpr->IgnoreParens() 18214 : Ref); 18215 } 18216 18217 if (Vars.empty()) 18218 return nullptr; 18219 18220 if (Allocator) 18221 DSAStack->addInnerAllocatorExpr(Allocator); 18222 return OMPAllocateClause::Create(Context, StartLoc, LParenLoc, Allocator, 18223 ColonLoc, EndLoc, Vars); 18224 } 18225 18226 OMPClause *Sema::ActOnOpenMPNontemporalClause(ArrayRef<Expr *> VarList, 18227 SourceLocation StartLoc, 18228 SourceLocation LParenLoc, 18229 SourceLocation EndLoc) { 18230 SmallVector<Expr *, 8> Vars; 18231 for (Expr *RefExpr : VarList) { 18232 assert(RefExpr && "NULL expr in OpenMP nontemporal clause."); 18233 SourceLocation ELoc; 18234 SourceRange ERange; 18235 Expr *SimpleRefExpr = RefExpr; 18236 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange); 18237 if (Res.second) 18238 // It will be analyzed later. 18239 Vars.push_back(RefExpr); 18240 ValueDecl *D = Res.first; 18241 if (!D) 18242 continue; 18243 18244 // OpenMP 5.0, 2.9.3.1 simd Construct, Restrictions. 18245 // A list-item cannot appear in more than one nontemporal clause. 18246 if (const Expr *PrevRef = 18247 DSAStack->addUniqueNontemporal(D, SimpleRefExpr)) { 18248 Diag(ELoc, diag::err_omp_used_in_clause_twice) 18249 << 0 << getOpenMPClauseName(OMPC_nontemporal) << ERange; 18250 Diag(PrevRef->getExprLoc(), diag::note_omp_explicit_dsa) 18251 << getOpenMPClauseName(OMPC_nontemporal); 18252 continue; 18253 } 18254 18255 Vars.push_back(RefExpr); 18256 } 18257 18258 if (Vars.empty()) 18259 return nullptr; 18260 18261 return OMPNontemporalClause::Create(Context, StartLoc, LParenLoc, EndLoc, 18262 Vars); 18263 } 18264 18265 OMPClause *Sema::ActOnOpenMPInclusiveClause(ArrayRef<Expr *> VarList, 18266 SourceLocation StartLoc, 18267 SourceLocation LParenLoc, 18268 SourceLocation EndLoc) { 18269 SmallVector<Expr *, 8> Vars; 18270 for (Expr *RefExpr : VarList) { 18271 assert(RefExpr && "NULL expr in OpenMP nontemporal clause."); 18272 SourceLocation ELoc; 18273 SourceRange ERange; 18274 Expr *SimpleRefExpr = RefExpr; 18275 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange, 18276 /*AllowArraySection=*/true); 18277 if (Res.second) 18278 // It will be analyzed later. 18279 Vars.push_back(RefExpr); 18280 ValueDecl *D = Res.first; 18281 if (!D) 18282 continue; 18283 18284 const DSAStackTy::DSAVarData DVar = 18285 DSAStack->getTopDSA(D, /*FromParent=*/true); 18286 // OpenMP 5.0, 2.9.6, scan Directive, Restrictions. 18287 // A list item that appears in the inclusive or exclusive clause must appear 18288 // in a reduction clause with the inscan modifier on the enclosing 18289 // worksharing-loop, worksharing-loop SIMD, or simd construct. 18290 if (DVar.CKind != OMPC_reduction || 18291 DVar.Modifier != OMPC_REDUCTION_inscan) 18292 Diag(ELoc, diag::err_omp_inclusive_exclusive_not_reduction) 18293 << RefExpr->getSourceRange(); 18294 18295 if (DSAStack->getParentDirective() != OMPD_unknown) 18296 DSAStack->markDeclAsUsedInScanDirective(D); 18297 Vars.push_back(RefExpr); 18298 } 18299 18300 if (Vars.empty()) 18301 return nullptr; 18302 18303 return OMPInclusiveClause::Create(Context, StartLoc, LParenLoc, EndLoc, Vars); 18304 } 18305 18306 OMPClause *Sema::ActOnOpenMPExclusiveClause(ArrayRef<Expr *> VarList, 18307 SourceLocation StartLoc, 18308 SourceLocation LParenLoc, 18309 SourceLocation EndLoc) { 18310 SmallVector<Expr *, 8> Vars; 18311 for (Expr *RefExpr : VarList) { 18312 assert(RefExpr && "NULL expr in OpenMP nontemporal clause."); 18313 SourceLocation ELoc; 18314 SourceRange ERange; 18315 Expr *SimpleRefExpr = RefExpr; 18316 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange, 18317 /*AllowArraySection=*/true); 18318 if (Res.second) 18319 // It will be analyzed later. 18320 Vars.push_back(RefExpr); 18321 ValueDecl *D = Res.first; 18322 if (!D) 18323 continue; 18324 18325 OpenMPDirectiveKind ParentDirective = DSAStack->getParentDirective(); 18326 DSAStackTy::DSAVarData DVar; 18327 if (ParentDirective != OMPD_unknown) 18328 DVar = DSAStack->getTopDSA(D, /*FromParent=*/true); 18329 // OpenMP 5.0, 2.9.6, scan Directive, Restrictions. 18330 // A list item that appears in the inclusive or exclusive clause must appear 18331 // in a reduction clause with the inscan modifier on the enclosing 18332 // worksharing-loop, worksharing-loop SIMD, or simd construct. 18333 if (ParentDirective == OMPD_unknown || DVar.CKind != OMPC_reduction || 18334 DVar.Modifier != OMPC_REDUCTION_inscan) { 18335 Diag(ELoc, diag::err_omp_inclusive_exclusive_not_reduction) 18336 << RefExpr->getSourceRange(); 18337 } else { 18338 DSAStack->markDeclAsUsedInScanDirective(D); 18339 } 18340 Vars.push_back(RefExpr); 18341 } 18342 18343 if (Vars.empty()) 18344 return nullptr; 18345 18346 return OMPExclusiveClause::Create(Context, StartLoc, LParenLoc, EndLoc, Vars); 18347 } 18348